Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(core): delete the live links engine; keep watch-attach, joinOnly and the visible capture

review6ff9ba1ba5b1
diff --git a/docs/session-backends.md b/docs/session-backends.md
index e02f61e47..a770ff6c6 100644
--- a/docs/session-backends.md
+++ b/docs/session-backends.md
@@ -103,7 +103,6 @@ foreground-process question and would be the model for that leg.
- The session-memory panel counts Zellij sessions but does not measure them; the idle-session reaper does not see them.
- Pasted text reaches Zellij as a command-line argument (readable by other local users while the call runs); pastes over 120 KB are refused.
- The stale-folder banner and the live pane folder for file links are unavailable.
-- A live link to a Zellij node gets no screen snapshot (viewers start from the live stream), and can be watched only while its terminal is attached in this app.
- SSH projects and Windows keep tmux / the session host.
- nodeterm mobile’s direct SSH attach only finds tmux sessions.
diff --git a/src/core/__fixtures__/no-session-host.ts b/src/core/__fixtures__/no-session-host.ts
index 83524a32f..4ae3358b8 100644
--- a/src/core/__fixtures__/no-session-host.ts
+++ b/src/core/__fixtures__/no-session-host.ts
@@ -52,7 +52,6 @@ export function noSessionHost(): Record<string, unknown> {
sessionHostCaptureVisible: async () => null,
sessionHostPaneCwd: async () => null,
sessionHostSupportsWatch: async () => false,
- sessionHostWatchKnown: () => undefined,
sessionHostListSessionsDetailed: async () => null,
sessionHostMessageOwner: async () => null,
sessionHostMessagePasteReady: async () => false,
diff --git a/src/core/capture-route.realtmux.test.ts b/src/core/capture-route.realtmux.test.ts
index d36be03b2..63fb4b8e7 100644
--- a/src/core/capture-route.realtmux.test.ts
+++ b/src/core/capture-route.realtmux.test.ts
@@ -1,11 +1,11 @@
-// A LIVE LINK'S KEYFRAME, CAPTURED FROM A REAL TMUX (R10 + R17, amended by R18: no alt-screen flag).
+// THE VISIBLE-SCREEN CAPTURE, FROM A REAL TMUX (no alt-screen flag).
//
// What is measured here is a property of tmux, not of our code, so it cannot be unit-tested:
// - the one invocation `capture-pane … ; display-message …` really does print the visible screen
// and THEN the cursor line, and only the visible rows (never the history above them);
// - the target spelling is EXACT. Node ids end in a counter, so `nt-x-1` is a prefix of `nt-x-12`,
// and tmux falls back to prefix matching on a miss: a bare target would capture ANOTHER node's
-// screen and send it to this link's viewers. `=name:` is the spelling that is exact AND resolves
+// screen and paint it on this node's client. `=name:` is the spelling that is exact AND resolves
// for a target-pane (measured on tmux 3.4: `=name` alone is "can't find pane").
//
// Private socket in a private TMUX_TMPDIR (`makeTmuxTmpdir`), never `node-terminal`/`nodeterm-rmt`;
diff --git a/src/core/capture-route.ts b/src/core/capture-route.ts
index c0ff10135..7ffd544c3 100644
--- a/src/core/capture-route.ts
+++ b/src/core/capture-route.ts
@@ -1,4 +1,5 @@
-// A live link's KEYFRAME: the visible screen of a node's session, never the history above it.
+// The VISIBLE screen of a node's session, never the history above it: what the phone's resume
+// repaint and the relay attach snapshot paint (main/remote/host-service.ts).
//
// Pure: no tmux, no ssh, no PtyManager. `PtyManager.captureVisible` runs the argv built here (locally,
// or over the ControlMaster through `remoteCaptureVisibleArgs`) and parses the reply here.
@@ -6,7 +7,7 @@
// Which backend gets one (`visibleCaptureRoute`): the session host answers its own negotiated
// `captureVisible` from its headless emulator (route `sessionHost`; an older host without the feature
// answers nothing, never its ~200-line scrollback `capture`). A direct Windows pane has no visible-only
-// read, so it gets NO keyframe (the viewer starts from the live stream) rather than history. A plain
+// read, so it gets NO capture (the client starts from the live stream) rather than history. A plain
// shell has no tmux to ask, and neither has a Zellij session (the optional local backend,
// zellij-backend.ts).
//
@@ -16,7 +17,7 @@
//
// The target is EXACT (`capturePaneTarget`). Node ids end in a counter, so `nt-x-1` is a prefix of
// `nt-x-12`, and tmux resolves a bare target by fnmatch then PREFIX on a miss: a bare target would
-// capture ANOTHER node's screen and send it to this link's viewers. Measured on tmux 3.4, with only
+// capture ANOTHER node's screen and paint it on this node's client. Measured on tmux 3.4, with only
// `nt-x-12` alive:
// capture-pane -t nt-x-1 → 12's screen, exit 0 (the trap)
// capture-pane -t =nt-x-1 → "can't find pane", exit 1 (also for =nt-x-12: `=name` alone never
@@ -30,13 +31,10 @@
/**
* What a visible-only capture returns: the screen and the cursor, read at one instant.
*
- * No alternate-screen flag on the tmux and SSH routes (controller ruling R18). A keyframe's `altScreen`
- * is decided by the CALLER from the join (a tmux-backed client ⇒ `true`), not from the capture: a watcher
- * co-attaches to the tmux CLIENT's output, and tmux paints its client on the alternate screen
- * whatever the pane's application does, so every `tmux`/`ssh`-route join means `altScreen: true`.
- * The pane's own `#{alternate_on}` (vim, a TUI) describes a different screen — a shell pane reads 0
- * while the stream is on the alternate screen — and mapping it into the keyframe would scroll every
- * tmux redraw into the viewer's history.
+ * No alternate-screen flag on the tmux and SSH routes. A client of a tmux-backed session reads the
+ * tmux CLIENT's output, and tmux paints its client on the alternate screen whatever the pane's
+ * application does. The pane's own `#{alternate_on}` (vim, a TUI) describes a different screen — a
+ * shell pane reads 0 while the stream is on the alternate screen.
*
* The SESSION-HOST route is the exception and sets `altScreen` itself: there is no tmux client between
* the pane and the stream, so the emulator's active buffer is exactly the stream's.
@@ -49,13 +47,12 @@ export interface VisibleCapture {
cursor: { x: number; y: number } | null
/**
* There is NO capture: the backend has no visible-only one, or the capture failed. Set only by
- * `unavailableCapture()`; a real capture of an empty pane never carries it. The difference matters
- * (controller ruling R36): a viewer paints a keyframe as reset + clear, so an empty keyframe sent for
- * "no capture" would erase everything the stream had drawn. The link host sends no keyframe for it.
+ * `unavailableCapture()`; a real capture of an empty pane never carries it. The difference matters:
+ * a client paints a capture as reset + clear, so an empty one sent for "no capture" would erase
+ * everything the stream had drawn.
*/
unavailable?: true
- /** Set ONLY by the `sessionHost` route (see above); the link host then uses it instead of the
- * join's. Absent on every tmux/SSH capture. */
+ /** Set ONLY by the `sessionHost` route (see above). Absent on every tmux/SSH capture. */
altScreen?: boolean
}
@@ -70,7 +67,7 @@ export function visibleCaptureRoute(
): 'none' | 'ssh' | 'tmux' | 'sessionHost' {
// A Zellij session is `tmuxBacked` too (that field means "releasing a client destroys nothing"),
// but there is no tmux session to capture: never aim the tmux socket at it (pty-manager's rule
- // for every path that would talk to tmux). No keyframe — the viewer starts from the live stream.
+ // for every path that would talk to tmux). No capture — the client starts from the live stream.
if (s.nativeWindowsPane || s.zellij) return 'none'
if (s.sessionHost) return 'sessionHost'
if (s.sshRemote) return 'ssh'
diff --git a/src/core/pane-input.realtmux.test.ts b/src/core/pane-input.realtmux.test.ts
index ea53febf9..4d0b5e1bb 100644
--- a/src/core/pane-input.realtmux.test.ts
+++ b/src/core/pane-input.realtmux.test.ts
@@ -1,7 +1,7 @@
-// LIVE LINK CONTROL INPUT, PROVEN AGAINST A REAL TMUX DRIVING A REAL PANE.
+// PANE INPUT, PROVEN AGAINST A REAL TMUX DRIVING A REAL PANE.
//
// The subject is `controlInputPlan` / `remoteControlInputPlan` run through the production
-// `runPasteDelivery`, i.e. exactly what `PtyManager.controlInput` runs: keys as `source-file -` with
+// `runPasteDelivery`, i.e. exactly what `PtyManager.sendPaneKeys` runs: keys as `source-file -` with
// `send-keys -H` lines behind a mode cancel, pastes as `load-buffer -` + `paste-buffer -d -p -r`.
// What judges is not a parser of ours: the pane runs a program that puts its tty in RAW mode and
// appends every byte it receives to a file, so a byte either reached the application or it did not.
diff --git a/src/core/pane-input.test.ts b/src/core/pane-input.test.ts
index 6bc0498e2..0c562df4f 100644
--- a/src/core/pane-input.test.ts
+++ b/src/core/pane-input.test.ts
@@ -1,4 +1,4 @@
-// The pure builders behind a live link controller's input. What they MEAN on a real tmux (bytes
+// The pure builders behind pane input (`PtyManager.sendPaneKeys`). What they MEAN on a real tmux (bytes
// exact, the prefix inert, a mode cancelled first, the exact session only) is proven in
// `pane-input.realtmux.test.ts`; this file pins their shape and their refusals.
import { describe, expect, it } from 'vitest'
diff --git a/src/core/pane-input.ts b/src/core/pane-input.ts
index 61953e14d..05eaae2ad 100644
--- a/src/core/pane-input.ts
+++ b/src/core/pane-input.ts
@@ -1,10 +1,11 @@
-// LIVE LINK CONTROL: a controller's typed bytes reach the node's PANE, never a tmux CLIENT.
+// PANE INPUT: typed bytes reach a node's PANE, never a tmux CLIENT. `PtyManager.sendPaneKeys` uses
+// these plans (bulk pause, Esc in the ⌘M chat view, the chat clear). They were written for live-link
+// Control, retired in 2026-11; the measurements below are about tmux and still hold.
//
-// Why a pane and not a client. Writing into a tmux client's pty — the owner's painter, or the
-// watcher's own `attach-session` client — makes tmux read the bytes as that client's KEYBOARD:
-// they go through its key tables, so `C-b s` opens the session chooser and every other session on
-// the server is one keystroke away (`C-b s`, `j`, Enter). A watcher's own client is also read-only
-// and would drop every byte. So keys are injected into the pane with `send-keys -H`, which tmux
+// Why a pane and not a client. Writing into a tmux client's pty (the owner's painter) makes tmux
+// read the bytes as that client's KEYBOARD: they go through its key tables, so `C-b s` opens the
+// session chooser and every other session on the server is one keystroke away (`C-b s`, `j`,
+// Enter). So keys are injected into the pane with `send-keys -H`, which tmux
// hands to the pane as `KEYC_LITERAL` bytes (`cmd-send-keys.c` → `window_pane_key` →
// `input_key`: "Literal keys go as themselves"), with no client and no key table involved — the
// same command the background-write path already types with (`encodeSendKeysHex`).
@@ -85,32 +86,10 @@ import {
} from './tmux-naming'
import { RMT_TMUX_SOCKET, childArgs, remoteDeleteBufferArgs, tmuxCmd } from './remote-ssh/control-master'
-/** One unit of a controller's input. `keys` are typed byte for byte; `paste` is text tmux frames
- * per the pane's own bracketed-paste state. */
+/** One unit of pane input. `keys` are typed byte for byte; `paste` is text tmux frames per the
+ * pane's own bracketed-paste state. */
export type ControlInputChunk = { kind: 'keys'; data: string } | { kind: 'paste'; text: string }
-/**
- * How a controller's input reaches a session's pane (`PtyManager.watcherInputRoute`):
- * - `tmux` — the local tmux, by the plans in this file;
- * - `ssh` — the same plans on the host, over the project's ControlMaster;
- * - `write` — PtyManager's ordinary write path (the Windows session host, a direct Windows pane,
- * the plain-shell fallback: there is no tmux client in between to reach a key table);
- * - `none` — refused (Zellij: its key bindings are session-wide; an unknown session).
- */
-export type WatcherInputRoute = 'tmux' | 'ssh' | 'write' | 'none'
-/** Every route, for a reader that must check one it did not produce (link-host.ts `normalizeJoin`). */
-export const WATCHER_INPUT_ROUTES = ['tmux', 'ssh', 'write', 'none'] as const satisfies readonly WatcherInputRoute[]
-
-/**
- * How long one chunk of a controller's input may take, from the moment it is HANDED OVER: the link
- * host gives up on it then (INPUT_DELIVERY_TIMEOUT_MS is this value) and tells its controller it was
- * dropped, and `PtyManager.controlInput` answers false at the same instant — a chunk that waited
- * behind a slow one gets only what is left — and moves the session's chain on. So a delivery that
- * never answers cannot hold every later chunk behind it, and a chunk with nothing left when its turn
- * comes is never delivered at all.
- */
-export const PANE_INPUT_DEADLINE_MS = 20_000
-
/** Bytes per `send-keys -H` line: 3 characters each on the line, so ~3 KiB a line. */
export const KEYS_PER_COMMAND = 1024
diff --git a/src/core/pty-join-only.test.ts b/src/core/pty-join-only.test.ts
index dfc9dfe98..04e7ffc66 100644
--- a/src/core/pty-join-only.test.ts
+++ b/src/core/pty-join-only.test.ts
@@ -222,6 +222,14 @@ describe('joinOnly: a viewer may watch a terminal but never start one', () => {
expect(spawned).toHaveLength(1) // a tmux CLIENT onto the existing session, not a new session
})
+ it('a hosted Viewer (joinOnly, sizeVote:false) keeps its new-session -A mirror, never attach-session', async () => {
+ await tmuxManager('present')
+ await create(VIEWER, { joinOnly: true, sizeVote: false })
+ expect(spawned[0].args).toContain('new-session')
+ expect(spawned[0].args).toContain('-A')
+ expect(spawned[0].args).not.toContain('attach-session')
+ })
+
it('a refusal leaves nothing behind: the owner still opens the node normally afterwards', async () => {
await manager()
expect(await create(VIEWER, { joinOnly: true })).toEqual(REFUSED)
diff --git a/src/core/pty-manager.capture-visible.test.ts b/src/core/pty-manager.capture-visible.test.ts
index 18eecde5b..4d9ac575a 100644
--- a/src/core/pty-manager.capture-visible.test.ts
+++ b/src/core/pty-manager.capture-visible.test.ts
@@ -1,4 +1,4 @@
-// `PtyManager.captureVisible` — a live link's keyframe: WHICH binary is asked with WHICH argv, and
+// `PtyManager.captureVisible` — the visible-screen capture: WHICH binary is asked with WHICH argv, and
// the failure contract. The argv's meaning (exact target, visible rows only, the cursor line from the
// same invocation) is proven against a real tmux in `capture-route.realtmux.test.ts` and
// through a real /bin/sh in `remote-ssh/capture-visible.realsh.test.ts`; this file pins dispatch.
@@ -205,57 +205,3 @@ describe('captureVisible — SSH project', () => {
expect(await m.captureVisible('sess-1')).toEqual(unavailableCapture())
})
})
-
-describe('readWindowSize — the size a watcher client is spawned at', () => {
- async function bare(tmux: string | null = '/usr/bin/tmux') {
- const { PtyManager } = await import('./pty-manager')
- const mgr = new PtyManager() as unknown as {
- tmuxPath: string | null
- readWindowSize(k: string, ssh?: unknown): Promise<unknown>
- }
- mgr.tmuxPath = tmux
- return mgr
- }
-
- it('asks the local tmux for exactly this session and parses the reply', async () => {
- script.answer = () => ({ stdout: '120 39 off\n' })
- const m = await bare()
- expect(await m.readWindowSize(NODE)).toEqual({ cols: 120, rows: 39 })
- expect(calls).toEqual([
- {
- file: '/usr/bin/tmux',
- args: ['-L', TMUX_SOCKET, 'display-message', '-p', '-t', TARGET, '#{window_width} #{window_height} #{status}']
- }
- ])
- })
-
- it('asks the REMOTE tmux over the ControlMaster for an SSH node', async () => {
- script.answer = () => ({ stdout: '100 30 off\n' })
- const m = await bare(null)
- expect(await m.readWindowSize(NODE, SSH_REMOTE)).toEqual({ cols: 100, rows: 30 })
- expect(calls).toHaveLength(1)
- expect(calls[0].file).toBe('/usr/bin/ssh')
- expect(calls[0].args.at(-1)).toContain(
- `tmux -L ${RMT_TMUX_SOCKET} display-message -p -t '${TARGET}' '#{window_width} #{window_height} #{status}'`
- )
- })
-
- it('an exact-target miss (every format empty), a failure or no tmux is undefined', async () => {
- script.answer = () => ({ stdout: ' \n' })
- expect(await (await bare()).readWindowSize(NODE)).toBeUndefined()
- script.answer = () => {
- throw Object.assign(new Error('no server running'), { code: 1 })
- }
- expect(await (await bare()).readWindowSize(NODE)).toBeUndefined()
- calls.length = 0
- expect(await (await bare(null)).readWindowSize(NODE)).toBeUndefined()
- expect(calls).toEqual([])
- })
-
- it('a remote node with no ssh binary is undefined — never read from the local tmux', async () => {
- ssh.path = null
- const m = await bare()
- expect(await m.readWindowSize(NODE, SSH_REMOTE)).toBeUndefined()
- expect(calls).toEqual([])
- })
-})
diff --git a/src/core/pty-manager.control-input.test.ts b/src/core/pty-manager.control-input.test.ts
deleted file mode 100644
index 89cc2b0a3..000000000
--- a/src/core/pty-manager.control-input.test.ts
+++ /dev/null
@@ -1,562 +0,0 @@
-// `PtyManager.watcherInputRoute` / `controlInput` / `nodeControlSupport` — a live link controller's
-// input: WHICH route a session gets, WHICH binary is asked with WHICH argv and WHICH stdin, the
-// per-session order, and the never-rejects contract. What the plans MEAN on a real tmux (bytes
-// exact, the prefix inert, a mode cancelled first, the exact session only) is
-// `pane-input.realtmux.test.ts`; this file pins dispatch, in the style of
-// `pty-manager.capture-visible.test.ts`. It is its own file because the runner here must carry
-// STDIN (`runWithStdin` reads the child off execFile's promise, as Node's own promisified execFile
-// provides it), which the capture-visible harness has no reason to fake.
-import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
-import { initPlatform, resetPlatformForTests } from './platform'
-import { fakePlatform } from './platform-fake'
-import { TMUX_SOCKET, sessionName } from './tmux-naming'
-import { PANE_INPUT_DEADLINE_MS, keysCommandText, remoteKeysArgs } from './pane-input'
-import { INPUT_DELIVERY_TIMEOUT_MS } from './watch-link/link-host'
-import { DEFAULT_SETTINGS } from '../shared/types'
-import { DaReplyGate } from './da-reply-gate'
-
-type Call = { file: string; args: string[]; input: string | undefined }
-const calls = vi.hoisted(() => [] as Array<{ file: string; args: string[]; input: string | undefined }>)
-/** What each `execFile` resolves to. A promise lets a test HOLD a call; a throw rejects it. */
-const script = vi.hoisted(() => ({
- answer: (() => ({ stdout: '' })) as (file: string, args: string[]) => { stdout: string } | Promise<{ stdout: string }>
-}))
-
-vi.mock('child_process', async () => {
- const { promisify } = await import('util')
- type Cb = (err: Error | null, res?: { stdout: string; stderr: string }) => void
- const execFile = (file: string, args: string[], a?: unknown, b?: unknown): unknown => {
- const cb = (typeof a === 'function' ? a : b) as Cb | undefined
- calls.push({ file, args, input: undefined })
- Promise.resolve()
- .then(() => script.answer(file, args))
- .then(
- (r) => cb?.(null, { stdout: r.stdout, stderr: '' }),
- (e) => cb?.(e as Error)
- )
- return {}
- }
- // `runWithStdin` reads the ChildProcess off the promise (`.child`) and ends its stdin with the
- // payload, exactly as Node's real promisified execFile carries it.
- ;(execFile as unknown as Record<symbol, unknown>)[promisify.custom] = (file: string, args: string[]) => {
- const call = { file, args, input: undefined as string | undefined }
- calls.push(call)
- // Answered at CALL time, so a test can hold exactly the n-th call.
- let answer: { stdout: string } | Promise<{ stdout: string }>
- try {
- answer = script.answer(file, args)
- } catch (e) {
- answer = Promise.reject(e)
- }
- const p = Promise.resolve(answer).then((r) => ({ stdout: r.stdout, stderr: '' }))
- const child = { stdin: { on: () => undefined, end: (input: string) => void (call.input = input) } }
- return Object.assign(p, { child })
- }
- return { execFile, execFileSync: (): string => '' }
-})
-
-const ssh = vi.hoisted(() => ({ path: '/usr/bin/ssh' as string | null }))
-vi.mock('./exec-path', async (importOriginal) => ({
- ...(await importOriginal<typeof import('./exec-path')>()),
- findExecutableSync: (bin: string) => (bin === 'ssh' ? ssh.path : null),
- shellPathNow: () => '/usr/bin:/bin',
- resolveShellPath: async () => '/usr/bin:/bin'
-}))
-
-vi.mock('node-pty', () => ({ spawn: () => ({}) }))
-
-const hostSendKeys = vi.hoisted(() => vi.fn(async (): Promise<boolean | 'pasted-not-submitted'> => true))
-vi.mock('./session-host-backend', async (original) => ({
- ...(await original<typeof import('./session-host-backend')>()),
- sessionHostSendKeys: hostSendKeys
-}))
-
-const NODE = 'node-1'
-const NAME = sessionName(NODE)
-const SSH_REMOTE = { conn: { host: 'h', user: 'u' }, controlPath: '/tmp/cm-abc', remoteCwd: '/srv' }
-
-type Mgr = {
- tmuxPath: string | null
- sessions: Map<string, Record<string, unknown>>
- byPersistKey: Map<string, string>
- zellijKeys: Set<string>
- released: Map<string, unknown>
- getSettings: () => typeof DEFAULT_SETTINGS
- watcherInputRoute(id: string): string
- controlInput(id: string, chunk: unknown, isCurrent?: () => boolean): Promise<boolean>
- nodeControlSupport(persistKey: string): string
-}
-
-/** A manager with one registered session, built without `create` — these methods read only the
- * session's backend fields and its pty, so a spawn harness would be noise. */
-async function manager(session: Record<string, unknown> | null, tmux: string | null = '/usr/bin/tmux') {
- const { PtyManager } = await import('./pty-manager')
- const mgr = new PtyManager() as unknown as Mgr
- mgr.tmuxPath = tmux
- const write = vi.fn()
- if (session) {
- mgr.sessions.set('sess-1', { persistKey: NODE, indexKey: NODE, nodeId: NODE, tmuxBacked: true, daReplies: new DaReplyGate(4_000), proc: { write }, ...session })
- mgr.byPersistKey.set(NODE, 'sess-1')
- }
- return { mgr, write }
-}
-
-const flush = () => new Promise((r) => setTimeout(r, 0))
-
-beforeEach(() => {
- calls.length = 0
- ssh.path = '/usr/bin/ssh'
- hostSendKeys.mockReset()
- hostSendKeys.mockImplementation(async () => true)
- script.answer = () => ({ stdout: '' })
- // `findSsh` memoizes per module; a fresh module per test lets one test say "no ssh here".
- vi.resetModules()
- initPlatform(fakePlatform())
-})
-afterEach(() => {
- vi.useRealTimers()
- resetPlatformForTests()
-})
-
-describe('watcherInputRoute', () => {
- it('routes each backend to the pane, or refuses', async () => {
- const cases: Array<[Record<string, unknown> | null, string | null, string]> = [
- [{ zellij: true }, '/usr/bin/tmux', 'none'], // session-wide key bindings: refused
- [{ sshRemote: SSH_REMOTE }, '/usr/bin/tmux', 'ssh'],
- [{ sshRemote: SSH_REMOTE }, null, 'ssh'], // the HOST's tmux, never the local one
- [{ sshRemote: SSH_REMOTE, tmuxBacked: false }, '/usr/bin/tmux', 'none'],
- [{ sessionHost: true }, null, 'write'],
- [{ nativeWindowsPane: {}, tmuxBacked: false }, null, 'write'],
- [{}, '/usr/bin/tmux', 'tmux'],
- [{}, null, 'none'], // tmux-backed but no tmux to ask
- [{ tmuxBacked: false, persistKey: undefined }, '/usr/bin/tmux', 'write'], // plain shell: the pty IS the shell
- [{ watcherClient: true }, '/usr/bin/tmux', 'tmux'], // a watcher's read-only client: the PANE, never the client
- [null, '/usr/bin/tmux', 'none']
- ]
- for (const [session, tmux, route] of cases) {
- const { mgr } = await manager(session, tmux)
- expect(mgr.watcherInputRoute('sess-1'), JSON.stringify(session)).toBe(route)
- }
- })
-
- it('a watcher client that is somehow not tmux-backed is never written into (it is read-only)', async () => {
- const { mgr } = await manager({ watcherClient: true, tmuxBacked: false, persistKey: undefined })
- expect(mgr.watcherInputRoute('sess-1')).toBe('none')
- })
-})
-
-describe('controlInput — local tmux', () => {
- it('keys: one `source-file -`, the command text on stdin, the name from the Session', async () => {
- const { mgr, write } = await manager({})
- expect(await mgr.controlInput('sess-1', { kind: 'keys', data: '\x02s' })).toBe(true)
- expect(calls).toEqual([
- { file: '/usr/bin/tmux', args: ['-L', TMUX_SOCKET, 'source-file', '-'], input: keysCommandText(NAME, '\x02s') }
- ])
- expect(write).not.toHaveBeenCalled() // never into the client's pty
- })
-
- it('paste: load-buffer from stdin, framed by tmux (-p), sanitized, no Enter', async () => {
- const { mgr } = await manager({})
- expect(await mgr.controlInput('sess-1', { kind: 'paste', text: 'a\x1b[201~b\nc' })).toBe(true)
- expect(calls).toHaveLength(1)
- const [c] = calls as Call[]
- expect(c.file).toBe('/usr/bin/tmux')
- expect(c.input).toBe('a[201~b\nc')
- expect(c.args.slice(0, 7)).toEqual(['-L', TMUX_SOCKET, 'load-buffer', '-b', c.args[4], '-', ';'])
- expect(c.args).toContain('-p')
- expect(c.args).toContain(`=${NAME}:`)
- expect(c.args).not.toContain('Enter')
- })
-
- it('a failed paste answers false and sweeps its own buffer', async () => {
- script.answer = (_f, args) => {
- if (args.includes('load-buffer')) throw Object.assign(new Error("can't find pane"), { code: 1 })
- return { stdout: '' }
- }
- const { mgr } = await manager({})
- expect(await mgr.controlInput('sess-1', { kind: 'paste', text: 'x' })).toBe(false)
- await flush()
- const buffer = calls[0].args[4]
- expect(calls[1].args).toEqual(['-L', TMUX_SOCKET, 'delete-buffer', '-b', buffer])
- })
-
- it('a failed keys delivery answers false, never rejects', async () => {
- script.answer = () => {
- throw Object.assign(new Error("can't find session"), { code: 1 })
- }
- const { mgr } = await manager({})
- await expect(mgr.controlInput('sess-1', { kind: 'keys', data: 'x' })).resolves.toBe(false)
- })
-
- it('an empty key chunk is refused without running anything; an empty paste has nothing to do', async () => {
- const { mgr } = await manager({})
- expect(await mgr.controlInput('sess-1', { kind: 'keys', data: '' })).toBe(false)
- expect(await mgr.controlInput('sess-1', { kind: 'paste', text: '\x1b' })).toBe(true)
- expect(calls).toEqual([])
- })
-
- it('a malformed chunk is refused without running anything', async () => {
- const { mgr } = await manager({})
- for (const bad of [null, {}, { kind: 'keys' }, { kind: 'keys', data: 5 }, { kind: 'paste', text: {} }, { kind: 'type', data: 'x' }]) {
- expect(await mgr.controlInput('sess-1', bad)).toBe(false)
- }
- expect(calls).toEqual([])
- })
-})
-
-describe('controlInput — ssh', () => {
- it('keys: run on the HOST over the ControlMaster, the command text on stdin', async () => {
- const { mgr } = await manager({ sshRemote: SSH_REMOTE })
- expect(await mgr.controlInput('sess-1', { kind: 'keys', data: 'ls\r' })).toBe(true)
- expect(calls).toEqual([
- {
- file: '/usr/bin/ssh',
- args: remoteKeysArgs(SSH_REMOTE.conn, SSH_REMOTE.controlPath),
- input: keysCommandText(NAME, 'ls\r')
- }
- ])
- })
-
- it('paste: the remote plan, sanitized text on stdin, no Enter', async () => {
- const { mgr } = await manager({ sshRemote: SSH_REMOTE })
- expect(await mgr.controlInput('sess-1', { kind: 'paste', text: 'p\x1bq' })).toBe(true)
- expect(calls[0].file).toBe('/usr/bin/ssh')
- expect(calls[0].input).toBe('pq')
- expect(calls[0].args.at(-1)).toContain('paste-buffer -d -p -r')
- expect(calls[0].args.at(-1)).not.toContain('Enter')
- })
-
- it('no ssh binary: false, nothing run — never the local tmux', async () => {
- ssh.path = null
- const { mgr } = await manager({ sshRemote: SSH_REMOTE })
- expect(await mgr.controlInput('sess-1', { kind: 'keys', data: 'x' })).toBe(false)
- expect(calls).toEqual([])
- })
-})
-
-describe('controlInput — never through a tmux CLIENT', () => {
- // The routing half of the security boundary. pane-input.realtmux.test.ts proves what the plans
- // MEAN on a real tmux (the prefix reaches the app, never tmux), but it runs the plans directly and
- // cannot see which route PtyManager picks. This pins the pick: a tmux-backed session's client pty
- // — the owner's painter, or a watcher's own read-only client — is never written into; the bytes
- // travel as `send-keys -H` text on `source-file -`'s stdin (a paste as `load-buffer -`).
- it("the owner's painter, a watcher's own client and an SSH session: keys and a paste reach the pane through tmux, never the client's pty", async () => {
- const cases: Array<[Record<string, unknown>, string]> = [
- [{}, '/usr/bin/tmux'],
- [{ watcherClient: true }, '/usr/bin/tmux'],
- [{ sshRemote: SSH_REMOTE }, '/usr/bin/ssh']
- ]
- for (const [session, file] of cases) {
- calls.length = 0
- const { mgr, write } = await manager(session)
- expect(await mgr.controlInput('sess-1', { kind: 'keys', data: '\x02s' }), JSON.stringify(session)).toBe(true)
- expect(await mgr.controlInput('sess-1', { kind: 'paste', text: 'echo hi\n' }), JSON.stringify(session)).toBe(true)
- expect(write, JSON.stringify(session)).not.toHaveBeenCalled()
- expect(calls.map((c) => c.file), JSON.stringify(session)).toEqual([file, file])
- expect(calls[0].input).toBe(keysCommandText(NAME, '\x02s'))
- expect(calls[0].input).toContain('-H 02 73')
- expect(calls[1].input).toBe('echo hi\n')
- // Never a payload on a command line, local or remote: argv is readable by every user (`ps`).
- const argv = calls.flatMap((c) => c.args).join(' ')
- expect(argv, JSON.stringify(session)).not.toContain('02 73')
- expect(argv, JSON.stringify(session)).not.toContain('\x02')
- expect(argv, JSON.stringify(session)).not.toContain('echo hi')
- }
- })
-})
-
-describe('controlInput — the ordinary write path', () => {
- it('plain shell: keys are written to the pty as they are', async () => {
- const { mgr, write } = await manager({ tmuxBacked: false, persistKey: undefined })
- expect(await mgr.controlInput('sess-1', { kind: 'keys', data: '\x1b[A' })).toBe(true)
- expect(write).toHaveBeenCalledWith('\x1b[A')
- expect(calls).toEqual([])
- })
-
- it('plain shell: a paste is written sanitized and unframed', async () => {
- const { mgr, write } = await manager({ tmuxBacked: false, persistKey: undefined })
- expect(await mgr.controlInput('sess-1', { kind: 'paste', text: 'a\x1b[201~b' })).toBe(true)
- expect(write).toHaveBeenCalledWith('a[201~b')
- })
-
- it('a pty that throws on write is a failed delivery, not an exception', async () => {
- const { mgr, write } = await manager({ tmuxBacked: false, persistKey: undefined })
- write.mockImplementation(() => {
- throw new Error('EIO')
- })
- await expect(mgr.controlInput('sess-1', { kind: 'keys', data: 'x' })).resolves.toBe(false)
- })
-
- it('session host: keys ride the pty; a paste goes through its no-Enter sendKeys, true only for true', async () => {
- const { mgr, write } = await manager({ sessionHost: true })
- expect(await mgr.controlInput('sess-1', { kind: 'keys', data: 'x' })).toBe(true)
- expect(write).toHaveBeenCalledWith('x')
- expect(await mgr.controlInput('sess-1', { kind: 'paste', text: 'a\nb' })).toBe(true)
- expect(hostSendKeys).toHaveBeenCalledWith(NAME, 'a\nb', false)
- hostSendKeys.mockImplementation(async () => 'pasted-not-submitted')
- expect(await mgr.controlInput('sess-1', { kind: 'paste', text: 'c' })).toBe(false)
- hostSendKeys.mockImplementation(async () => false)
- expect(await mgr.controlInput('sess-1', { kind: 'paste', text: 'c' })).toBe(false)
- expect(calls).toEqual([])
- })
-
- it('a direct Windows pane: a paste goes through the pane (framed only if its app asked), no Enter', async () => {
- const sendText = vi.fn(async () => true)
- const { mgr, write } = await manager({ nativeWindowsPane: { sendText }, tmuxBacked: false, persistKey: undefined })
- expect(await mgr.controlInput('sess-1', { kind: 'paste', text: 'a\nb' })).toBe(true)
- expect(sendText).toHaveBeenCalledWith('a\nb', false)
- expect(await mgr.controlInput('sess-1', { kind: 'keys', data: '\x03' })).toBe(true)
- expect(write).toHaveBeenCalledWith('\x03')
- })
-})
-
-describe('controlInput — refusals and order', () => {
- it("'none' resolves false without spawning anything", async () => {
- for (const session of [{ zellij: true }, null]) {
- const { mgr, write } = await manager(session)
- expect(await mgr.controlInput('sess-1', { kind: 'keys', data: 'x' })).toBe(false)
- expect(await mgr.controlInput('sess-1', { kind: 'paste', text: 'x' })).toBe(false)
- // A refused route never reports "delivered", not even for a paste with nothing in it.
- expect(await mgr.controlInput('sess-1', { kind: 'paste', text: '' })).toBe(false)
- expect(write).not.toHaveBeenCalled()
- }
- expect(calls).toEqual([])
- expect(hostSendKeys).not.toHaveBeenCalled()
- })
-
- it('two chunks on one session run strictly in order: the second starts only after the first settles', async () => {
- let release!: () => void
- const held = new Promise<{ stdout: string }>((r) => (release = () => r({ stdout: '' })))
- let n = 0
- script.answer = () => (++n === 1 ? held : { stdout: '' })
- const { mgr } = await manager({})
- const first = mgr.controlInput('sess-1', { kind: 'keys', data: 'a' })
- const second = mgr.controlInput('sess-1', { kind: 'keys', data: 'b' })
- for (let i = 0; i < 5; i++) await flush()
- expect(calls).toHaveLength(1)
- expect(calls[0].input).toBe(keysCommandText(NAME, 'a'))
- release()
- expect(await first).toBe(true)
- expect(await second).toBe(true)
- expect(calls.map((c) => c.input)).toEqual([keysCommandText(NAME, 'a'), keysCommandText(NAME, 'b')])
- })
-
- it('a failed chunk does not stall the chain', async () => {
- let n = 0
- script.answer = () => {
- if (++n === 1) throw Object.assign(new Error('boom'), { code: 1 })
- return { stdout: '' }
- }
- const { mgr } = await manager({})
- const a = mgr.controlInput('sess-1', { kind: 'keys', data: 'a' })
- const b = mgr.controlInput('sess-1', { kind: 'keys', data: 'b' })
- expect(await a).toBe(false)
- expect(await b).toBe(true)
- })
-
- it('the session is re-read inside the step: gone by then → false, nothing run', async () => {
- let release!: () => void
- const held = new Promise<{ stdout: string }>((r) => (release = () => r({ stdout: '' })))
- script.answer = () => held
- const { mgr } = await manager({})
- const a = mgr.controlInput('sess-1', { kind: 'keys', data: 'a' })
- const b = mgr.controlInput('sess-1', { kind: 'keys', data: 'b' })
- await flush()
- mgr.sessions.delete('sess-1')
- release()
- expect(await a).toBe(true)
- expect(await b).toBe(false)
- expect(calls).toHaveLength(1)
- })
-
- it('different sessions do not wait for each other', async () => {
- const held = new Promise<{ stdout: string }>(() => undefined)
- let n = 0
- script.answer = () => (++n === 1 ? held : { stdout: '' })
- const { mgr } = await manager({})
- mgr.sessions.set('sess-2', { persistKey: 'node-2', tmuxBacked: true, proc: { write: vi.fn() } })
- void mgr.controlInput('sess-1', { kind: 'keys', data: 'a' })
- expect(await mgr.controlInput('sess-2', { kind: 'keys', data: 'b' })).toBe(true)
- })
-})
-
-// Final review, Minor 3: a chunk already handed over waits in the session's chain (behind a slow step
-// of another link, say). Its sender may lose control meanwhile — a stop, a demotion — and the link host
-// can no longer recall it. `isCurrent`, asked right before the step spawns (or writes), drops it there.
-describe('controlInput — isCurrent, asked right before the step runs', () => {
- it('a chunk whose sender stopped controlling while it waited behind a slow step never runs; the chain moves on', async () => {
- let release!: () => void
- const held = new Promise<{ stdout: string }>((r) => (release = () => r({ stdout: '' })))
- let n = 0
- script.answer = () => (++n === 1 ? held : { stdout: '' })
- const { mgr } = await manager({})
- let current = true
- let asked = 0
- const first = mgr.controlInput('sess-1', { kind: 'keys', data: 'a' })
- const keys = mgr.controlInput('sess-1', { kind: 'keys', data: 'b' }, () => (asked++, current))
- const paste = mgr.controlInput('sess-1', { kind: 'paste', text: 'p' }, () => (asked++, current))
- const later = mgr.controlInput('sess-1', { kind: 'keys', data: 'c' }, () => true)
- for (let i = 0; i < 5; i++) await flush()
- expect(calls).toHaveLength(1)
- expect(asked).toBe(0) // not asked at hand-over: only when its turn comes
- current = false // the owner turned typing off, or the link stopped, while they waited
- release()
- expect(await first).toBe(true)
- expect(await keys).toBe(false)
- expect(await paste).toBe(false)
- expect(await later).toBe(true)
- expect(asked).toBe(2)
- expect(calls.map((c) => c.input)).toEqual([keysCommandText(NAME, 'a'), keysCommandText(NAME, 'c')])
- })
-
- it('a predicate that throws reads as not current (fail closed)', async () => {
- const { mgr } = await manager({})
- expect(
- await mgr.controlInput('sess-1', { kind: 'keys', data: 'a' }, () => {
- throw new Error('boom')
- })
- ).toBe(false)
- expect(calls).toEqual([])
- })
-
- it('every route honours it: ssh, the plain-shell write, the session host and a direct Windows pane', async () => {
- const sendText = vi.fn(async () => true)
- for (const session of [
- { sshRemote: SSH_REMOTE },
- { tmuxBacked: false },
- { sessionHost: true },
- { nativeWindowsPane: { sendText }, tmuxBacked: false, persistKey: undefined }
- ]) {
- const { mgr, write } = await manager(session)
- expect(await mgr.controlInput('sess-1', { kind: 'keys', data: 'a' }, () => false), JSON.stringify(session)).toBe(false)
- expect(await mgr.controlInput('sess-1', { kind: 'paste', text: 'p' }, () => false)).toBe(false)
- expect(write).not.toHaveBeenCalled()
- }
- expect(calls).toEqual([])
- expect(hostSendKeys).not.toHaveBeenCalled()
- expect(sendText).not.toHaveBeenCalled()
- })
-
- it('a current chunk runs as before', async () => {
- const { mgr } = await manager({})
- expect(await mgr.controlInput('sess-1', { kind: 'keys', data: 'a' }, () => true)).toBe(true)
- expect(calls.map((c) => c.input)).toEqual([keysCommandText(NAME, 'a')])
- })
-})
-
-describe('nodeControlSupport', () => {
- it('Zellij is unsupported, whether known from a record or from a live session', async () => {
- const a = await manager(null)
- a.mgr.zellijKeys.add(NODE)
- expect(a.mgr.nodeControlSupport(NODE)).toBe('unsupported')
- const b = await manager({ zellij: true })
- expect(b.mgr.nodeControlSupport(NODE)).toBe('unsupported')
- })
-
- it('a live session, a released one, or a new tmux node is ok', async () => {
- expect((await manager({})).mgr.nodeControlSupport(NODE)).toBe('ok')
- const r = await manager(null, null)
- r.mgr.released.set(NODE, { sessionId: 'old', remote: false })
- expect(r.mgr.nodeControlSupport(NODE)).toBe('ok')
- expect((await manager(null)).mgr.nodeControlSupport('node-new')).toBe('ok')
- })
-
- // A node with no session anywhere would be CREATED in the selected backend, and a Zellij session
- // refuses control. A live (or released) session still answers for itself: the backend follows the
- // session that exists.
- it('no session or record on a machine whose new sessions are Zellij: unsupported', async () => {
- const zellij = { ...DEFAULT_SETTINGS, tmuxEnabled: true, sessionBackend: 'zellij' as const }
- const fresh = await manager(null)
- fresh.mgr.getSettings = () => zellij
- expect(fresh.mgr.nodeControlSupport('node-new')).toBe('unsupported')
- const noTmux = await manager(null, null)
- noTmux.mgr.getSettings = () => zellij
- expect(noTmux.mgr.nodeControlSupport('node-new')).toBe('unsupported')
- const live = await manager({})
- live.mgr.getSettings = () => zellij
- expect(live.mgr.nodeControlSupport(NODE)).toBe('ok')
- const released = await manager(null)
- released.mgr.getSettings = () => zellij
- released.mgr.released.set(NODE, { sessionId: 'old', remote: false })
- expect(released.mgr.nodeControlSupport(NODE)).toBe('ok')
- })
-
- it('no session, no record, no tmux to make one: unknown', async () => {
- expect((await manager(null, null)).mgr.nodeControlSupport('node-new')).toBe('unknown')
- const off = await manager(null)
- off.mgr.getSettings = () => ({ ...DEFAULT_SETTINGS, tmuxEnabled: false })
- expect(off.mgr.nodeControlSupport('node-new')).toBe('unknown')
- })
-})
-
-// Every step of a session's input chain settles in bounded time, whatever the route: a delivery that
-// never answers would otherwise hold the chain — and every later chunk would wait behind it, to land
-// long after the link host (which gives up at INPUT_DELIVERY_TIMEOUT_MS) told its controller it was
-// dropped.
-describe('controlInput — bounded on every route', () => {
- it('the deadline is the link host\'s own', () => {
- expect(PANE_INPUT_DEADLINE_MS).toBe(INPUT_DELIVERY_TIMEOUT_MS)
- })
-
- for (const [route, session] of [
- ['a direct Windows pane', 'pane'],
- ['the session host', 'host']
- ] as const) {
- it(`${route}: a paste that never answers is false at the deadline, and the chain moves on`, async () => {
- const sendText = vi.fn((): Promise<boolean> => new Promise(() => {}))
- if (session === 'host') hostSendKeys.mockImplementation(() => new Promise(() => {}))
- const { mgr } = await manager(
- session === 'pane' ? { nativeWindowsPane: { sendText }, tmuxBacked: false, persistKey: undefined } : { sessionHost: true }
- )
- vi.useFakeTimers()
- let answer: boolean | null = null
- void mgr.controlInput('sess-1', { kind: 'paste', text: 'a' }).then((v) => (answer = v))
- await vi.advanceTimersByTimeAsync(PANE_INPUT_DEADLINE_MS - 1)
- expect(answer).toBeNull()
- await vi.advanceTimersByTimeAsync(1)
- expect(answer).toBe(false)
- sendText.mockImplementation(async () => true)
- hostSendKeys.mockImplementation(async () => true)
- expect(await mgr.controlInput('sess-1', { kind: 'paste', text: 'b' })).toBe(true)
- })
- }
-
- // The deadline runs from the HAND-OVER: a chunk that waited 15 s behind a slow step has 5 s left,
- // not a fresh 20 — its caller gives up 20 s after handing it over, whatever the chain did meanwhile.
- it('a chunk queued behind a slow step for 15 s gets at most 5 s more', async () => {
- let releaseFirst!: (v: boolean) => void
- let n = 0
- const sendText = vi.fn(
- (): Promise<boolean> => (++n === 1 ? new Promise<boolean>((r) => (releaseFirst = r)) : new Promise<boolean>(() => {}))
- )
- const { mgr } = await manager({ nativeWindowsPane: { sendText }, tmuxBacked: false, persistKey: undefined })
- vi.useFakeTimers()
- const first = mgr.controlInput('sess-1', { kind: 'paste', text: 'a' })
- let second: boolean | null = null
- void mgr.controlInput('sess-1', { kind: 'paste', text: 'b' }).then((v) => (second = v))
- await vi.advanceTimersByTimeAsync(15_000)
- releaseFirst(true)
- expect(await first).toBe(true)
- await vi.advanceTimersByTimeAsync(0)
- expect(sendText).toHaveBeenCalledTimes(2) // 'b' started, with 5 s left
- await vi.advanceTimersByTimeAsync(PANE_INPUT_DEADLINE_MS - 15_000 - 1)
- expect(second).toBeNull()
- await vi.advanceTimersByTimeAsync(1)
- expect(second).toBe(false)
- })
-
- it('a chunk that could not START before the deadline is dropped undelivered: its caller gave up on it', async () => {
- const sendText = vi.fn((): Promise<boolean> => new Promise(() => {}))
- const { mgr } = await manager({ nativeWindowsPane: { sendText }, tmuxBacked: false, persistKey: undefined })
- vi.useFakeTimers()
- const first = mgr.controlInput('sess-1', { kind: 'paste', text: 'a' })
- const second = mgr.controlInput('sess-1', { kind: 'paste', text: 'b' }) // queued behind the hung one
- await vi.advanceTimersByTimeAsync(PANE_INPUT_DEADLINE_MS)
- expect(await first).toBe(false)
- expect(await second).toBe(false)
- expect(sendText).toHaveBeenCalledTimes(1) // 'b' never reached the pane
- sendText.mockImplementation(async () => true)
- expect(await mgr.controlInput('sess-1', { kind: 'paste', text: 'c' })).toBe(true)
- expect(sendText).toHaveBeenLastCalledWith('c', false)
- })
-})
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index 80ed350e8..a8380a9be 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -59,8 +59,6 @@ import {
remoteTmuxEnterArgs,
remoteCapturePaneArgs,
remoteCaptureVisibleArgs,
- remoteTmuxWatcherArgs,
- remoteWindowSizeArgs,
remotePaneCommandArgs,
remoteSendKeyArgs,
remotePaneCwdArgs,
@@ -100,22 +98,8 @@ import {
visibleCaptureRoute,
type VisibleCapture
} from './capture-route'
-import {
- PANE_INPUT_DEADLINE_MS,
- controlInputPlan,
- remoteControlInputPlan,
- type ControlInputChunk,
- type WatcherInputRoute
-} from './pane-input'
-import type { ControlSupport } from '../shared/watch-link-types'
+import { controlInputPlan, remoteControlInputPlan } from './pane-input'
import { sanitizePasteText } from './paste-injection'
-import {
- localWatcherAttachArgs,
- localWindowSizeArgs,
- parseTmuxVersion,
- parseWindowSize,
- supportsWatcherClient
-} from './watch-link/watcher-client'
import {
recordFreshSpawnOwner,
forgetPaneOwner,
@@ -828,21 +812,11 @@ function releaseSpawnSlotOnOutput(session: Session | undefined, release: SpawnSl
}
}
-/**
- * Marks a create as a live link WATCHER's (`joinAsWatcher`), and nothing else sets it. A symbol, not a
- * `PtyCreateOptions` field: that type is the `pty:create` wire payload, and a symbol cannot arrive over
- * IPC, the WS bridge or the relay — so no renderer, browser tab or peer can ask for a watcher client
- * (or opt out of one). Object spread copies it, so it survives spawnNew's option rewrites.
- */
-const WATCHER_CLIENT: unique symbol = Symbol('nodeterm.watcherClient')
-type WatcherCreateOptions = PtyCreateOptions & { readonly [WATCHER_CLIENT]?: true }
-function isWatcherCreate(options: PtyCreateOptions): boolean {
- return (options as WatcherCreateOptions)[WATCHER_CLIENT] === true
-}
/**
* Marks a join-only create that `spawnNew` PROVED has a live session-host generation to watch (the
- * host advertised `watch-attach` and answered `hasSession` strictly). Same symbol discipline as
- * `WATCHER_CLIENT`: set only inside this process, never from a wire payload. `spawnSession` turns it
+ * host advertised `watch-attach` and answered `hasSession` strictly). A symbol, not a
+ * `PtyCreateOptions` field: that type is the `pty:create` wire payload, and a symbol cannot arrive
+ * over IPC, the WS bridge or the relay, so it is set only inside this process. `spawnSession` turns it
* into a read-only `watchExistingSessionHostPty` — no spawn plan, no size claim, no pause ticket.
*/
const SESSION_HOST_WATCH: unique symbol = Symbol('nodeterm.sessionHostWatch')
@@ -993,10 +967,10 @@ interface Session {
launchAgentId?: string
launchPath?: string
/**
- * A live link watcher's OWN tmux client (`attach-session -E -f ignore-size,read-only`, spawned by
- * `joinAsWatcher` when no Session was held). Never indexed, and invisible to the persistKey lookups
- * (`sessionByPersistKey`, `liveSessionForNode`): it is read-only, so an owner joining it, or a
- * background write going through it, would lose every keystroke. Only watchers ever reach it.
+ * A read-only session-host `watch-attach` client (a joinOnly create `spawnNew` proved has a live
+ * generation to watch, `SESSION_HOST_WATCH`). Never indexed, and invisible to the persistKey
+ * lookups (`sessionByPersistKey`, `liveSessionForNode`): it cannot type, so an owner joining it, or
+ * a background write going through it, would lose every keystroke.
*/
watcherClient?: boolean
}
@@ -1564,8 +1538,8 @@ export class PtyManager {
// enforced (so the pane is not left to reflow), and whether this node's tmux was REMOTE (so it
// is never shadowed against our local socket). The `Session` holding both goes with `forget`
// below; this is the record that survives it.
- // Not for a watcher's own client: its size is whatever it was spawned at, never the size an owner
- // enforced, and a later shadow would push that size into the pane (`shadowAttach`).
+ // Not for a read-only watch client: it never enforced a size, and a later shadow would push
+ // whatever it reported into the pane (`shadowAttach`).
if (session.persistKey && !session.watcherClient)
this.released.set(session.persistKey, {
sessionId,
@@ -2794,15 +2768,8 @@ export class PtyManager {
options: PtyCreateOptions,
persistKey: string
): Promise<PtyCreateResult> | undefined {
- let existingId = this.byPersistKey.get(persistKey)
- let existing = existingId ? this.sessions.get(existingId) : undefined
- // A second live link viewer of a node no owner Session is held for shares the first viewer's own
- // tmux client (unindexed, see `watcherClient`) rather than opening another — each one is a tmux
- // client, and over SSH an ssh channel against the host's MaxSessions. Only a watcher may join it.
- if ((!existingId || !existing) && isWatcherCreate(options)) {
- existingId = this.watcherClientSessionId(persistKey)
- existing = existingId ? this.sessions.get(existingId) : undefined
- }
+ const existingId = this.byPersistKey.get(persistKey)
+ const existing = existingId ? this.sessions.get(existingId) : undefined
if (!existingId || !existing) return undefined
// A node that lives on a remote host never joins a session that is not on THAT host. The match
// above is by node id alone, and a LOCAL session can carry a remote node's id (a hosted team
@@ -2887,10 +2854,6 @@ export class PtyManager {
}
: { sessionId: existingId, fresh: false, coAttachMouse, coAttachAltScreen, tmuxClient, persistent }
if (resized) return Promise.resolve(base) // tmux is redrawing this client — do not paint twice
- // A live link's watcher never paints from this screen (its keyframe is a VISIBLE-only capture —
- // this one is history on SSH and the session host), so it is not captured for one (R64/M4): on SSH
- // that was a `-S -200` capture over the master on every viewer join and rejoin, thrown away.
- if (isWatcherCreate(options)) return Promise.resolve(base)
// An empty capture (plain shell — no tmux to capture; a tmux/ssh blip) is OMITTED, never sent
// as '': the renderer must not reset a terminal for nothing. A plain-shell joiner therefore
// still lands on a blank-but-live screen — there is no source of truth for its past output,
@@ -3095,40 +3058,6 @@ export class PtyManager {
(await sessionHostHasSession(sessionName(options.persistKey)).catch(() => true)))
if (newRefused) return { sessionId: '', fresh: false, unavailable: 'new-only' }
}
- // A watcher's own client is a read-only TMUX client (`attach-session -E -f ignore-size,read-only`),
- // and a Zellij session has no such client to spawn: refused, never a Zellij attach (which would be
- // a full, typing client). A watcher still co-attaches to a Zellij session this process holds (the
- // `join` above); it just gets no keyframe (`visibleCaptureRoute`).
- if (isWatcherCreate(options) && zellijChoice?.use)
- return { sessionId: '', fresh: false, unavailable: 'join-only' }
- // A session-host watch needs neither of the tmux watcher gates below: there is no tmux client to
- // flag, and the attachment takes the pty's size from the host's own answer (`geometry`) rather
- // than spawning at a read one. `create` (and its in-flight barrier) still runs as for tmux.
- // A watcher's own LOCAL client needs client flags (tmux >= 3.2). Without them it would either fail
- // to attach or — worse, spelled without the flags — resize the owner's window. Refused the same
- // way as a session that cannot be confirmed. Over SSH the host's version is unknown here: the
- // flags are passed and an old remote tmux rejects them (see `remoteTmuxWatcherArgs`).
- if (
- isWatcherCreate(options) &&
- !sessionHostWatch &&
- !options.sshRemote &&
- !(await this.localTmuxSupportsWatcherClient())
- )
- return { sessionId: '', fresh: false, unavailable: 'join-only' }
- // A watcher's own client is spawned at the window's CURRENT size, read here, just before the spawn
- // — never at a guessed one (the caller's, a remembered size, a default). `ignore-size` only holds
- // while an unflagged client is attached somewhere on the server; if the watcher is ever the only
- // one, tmux sizes the window to it, so a wrong spawn size is a wrong window size. Unknown ⇒ refused
- // ("not now": the link host backs off and asks again).
- // The read runs INSIDE the node's in-flight barrier (`create`), on purpose: a second viewer's join
- // waits for this client and then shares it, instead of spawning another. The cost, accepted: an
- // owner opening the same node in that instant waits for the read too — bounded by the probe and
- // process timeouts (`runAsync`) — and then spawns its own client as usual.
- if (isWatcherCreate(options) && !sessionHostWatch) {
- const windowSize = await this.readWindowSize(options.persistKey as string, options.sshRemote)
- if (!windowSize) return { sessionId: '', fresh: false, unavailable: 'join-only' }
- options = { ...options, cols: windowSize.cols, rows: windowSize.rows }
- }
// Ensure the login-shell PATH is resolved (prewarmed in init(); usually already settled)
// so the session env below picks it up — awaiting keeps the event loop free either way.
await resolveShellPath()
@@ -3437,13 +3366,6 @@ export class PtyManager {
}
})
- /** A live link watcher's own tmux client for this node, if one is running (see `watcherClient`). */
- private watcherClientSessionId(persistKey: string): string | undefined {
- for (const [id, session] of this.sessions) {
- if (session.watcherClient && session.persistKey === persistKey) return id
- }
- return undefined
- }
/** Find the live session registered under a node id (persistKey), if any. */
private sessionByPersistKey(persistKey: string): Session | undefined {
@@ -4446,9 +4368,7 @@ export class PtyManager {
// pre-flight above is the one thing that CAN, which is exactly why it runs before this.)
// The shared background-write client goes too, for the same reason, when it is this node's
// session it happens to be attached to.
- // A watcher's own client is not a painter: read-only, it never types, and it is kept at the
- // window's own size (`syncWatcherClientSize`), so a background-write client may stay beside it.
- if (options.persistKey && !isWatcherCreate(options)) {
+ if (options.persistKey) {
// The other half of the swap log (see `shadowAttach`), and only when there is really
// something to retire: a painter arriving at a session no control client held swapped
// nothing, and a line per terminal anyone opens is noise in the report it exists for.
@@ -4788,19 +4708,7 @@ export class PtyManager {
// holds the ssh client. Only when BOTH sshRemote and persistKey are set and ssh resolves —
// otherwise this falls through to the unchanged local-tmux / plain-shell branches below.
const remoteSsh = options.sshRemote && options.persistKey ? findSsh() : null
- if (isWatcherCreate(options) && options.sshRemote && options.persistKey && remoteSsh) {
- // A live link watcher's own client on the host: attach-only, read-only, ignore-size, no env
- // (see `remoteTmuxWatcherArgs`). Nothing the owner's branch below does — tokens, hook/account
- // env, the session-env file, `markPresent` — belongs to a client that creates nothing.
- file = remoteSsh
- if (process.env.NODETERM_APP_AGENT_SOCK) env.SSH_AUTH_SOCK = process.env.NODETERM_APP_AGENT_SOCK
- nativeSshArgv = remoteTmuxWatcherArgs(
- options.sshRemote.conn,
- options.sshRemote.controlPath,
- sessionName(options.persistKey)
- )
- args = nativeSshArgv
- } else if (options.sshRemote && options.persistKey && remoteSsh) {
+ if (options.sshRemote && options.persistKey && remoteSsh) {
file = remoteSsh
// The remote twin of the local `ensureNodeToken` above: materialise THIS node's token on the
// host before the attach. The connect path writes one for every node the canvas had AT
@@ -4989,10 +4897,6 @@ export class PtyManager {
// one its name prefixes (`exactSessionTarget`).
exactSessionTarget(sessionName(options.persistKey))
]
- } else if (isWatcherCreate(options)) {
- // A live link watcher's own client: attach-only, `-E`, `ignore-size,read-only`, exact target
- // (see `watch-link/watcher-client.ts`). No `-f <conf>`: attach never starts a server.
- args = localWatcherAttachArgs(TMUX_SOCKET, sessionName(options.persistKey))
} else {
// The hook-server env (port/token/node id/agent id) is passed explicitly via `-e`
// (one `-e KEY=VALUE` per key) since the shared tmux server can't rely on inherited env.
@@ -5211,7 +5115,7 @@ export class PtyManager {
// A read-only session-host attachment is never the node's session either: an owner opening the
// node must spawn its own (typing, size-voting) attachment rather than join this one.
indexKey:
- options.persistKey && !sinks && !isWatcherCreate(options) && !watchHost
+ options.persistKey && !sinks && !watchHost
? options.persistKey
: undefined,
onData: sinks?.onData,
@@ -5243,7 +5147,7 @@ export class PtyManager {
sessionHost: useSessionHost,
...(useSessionHost && options.agentId ? { launchAgentId: options.agentId } : {}),
...(useSessionHost && env[envPathKey(env)] ? { launchPath: env[envPathKey(env)] } : {}),
- ...(isWatcherCreate(options) || watchHost ? { watcherClient: true } : {}),
+ ...(watchHost ? { watcherClient: true } : {}),
...(useLocalZellij ? { zellij: true } : {})
}
// Both shared timers are armed by the first session that needs them: the scrollback snapshots
@@ -5970,15 +5874,6 @@ export class PtyManager {
return this.sessions.get(sessionId)?.nodeId
}
- /**
- * Is this session known to the manager — created and not yet ended? Read-only. A live link's host
- * asks it after a join and after every keyframe capture (controller rulings R30/R38): the session's
- * exit can race either, and its `pty:exit` was delivered before the viewer knew the session id.
- */
- hasSession(sessionId: string): boolean {
- return this.sessions.has(sessionId)
- }
-
/**
* The CURRENT screen of a live session, by sessionId — the redraw sent to a client that fell so
* far behind that its socket backlog was discarded (see ServerPlatform's WS_DROP_WATER). Reuses
@@ -6002,8 +5897,8 @@ export class PtyManager {
}
/**
- * A live link's keyframe: the VISIBLE screen of a session, with the cursor read in the same tmux
- * invocation — never history. The keyframe's `altScreen` is the caller's, from the join (a
+ * The VISIBLE screen of a session, with the cursor read in the same tmux invocation — never
+ * history (the phone's resume repaint). On tmux and SSH `altScreen` is the caller's (a
* tmux-backed client paints on the alternate screen; see `VisibleCapture`). Which backends get
* one, the exact target and the parse are `capture-route.ts`. The session host
* (scrollback only), a direct Windows pane and a plain shell get `unavailableCapture()`, as does
@@ -6048,395 +5943,6 @@ export class PtyManager {
return unavailableCapture()
}
- /**
- * How a live-link controller's input reaches this session's PANE (pane-input.ts).
- *
- * Never through a tmux CLIENT: a byte written into a client's pty is that client's KEYBOARD, so
- * the prefix would reach tmux (`C-b s` opens the session chooser) — and a watcher's own client is
- * read-only besides. A tmux-backed session (local, or on the SSH host) is typed into with
- * `send-keys -H` on the pane. The Windows session host, a direct Windows pane and the plain-shell
- * fallback take PtyManager's ordinary write: there is no tmux client in between, so no key table.
- * Zellij is refused: its key bindings are session-wide (zellij-backend.ts).
- */
- watcherInputRoute(sessionId: string): WatcherInputRoute {
- const s = this.sessions.get(sessionId)
- if (!s) return 'none'
- if (s.zellij) return 'none' // session-wide key bindings: refused
- if (s.sshRemote) return s.tmuxBacked ? 'ssh' : 'none'
- // A read-only session-host attachment (`watch-attach`, the node not held here) has no typing
- // path: the host refuses writes from it, and its keys must not be retyped as a framed paste.
- // Control typing reaches a session-host node only for a viewer that joined while the node was
- // open in this app (the route is read once, at join: this viewer is not upgraded later).
- if (s.sessionHost && s.watcherClient) return 'none'
- if (s.sessionHost || s.nativeWindowsPane) return 'write'
- if (s.tmuxBacked) return this.tmuxPath ? 'tmux' : 'none'
- // A watcher's own client is read-only and always tmux-backed; were one ever not, writing into it
- // would drop every byte, so it is refused rather than reported delivered.
- if (s.watcherClient) return 'none'
- return 'write' // the plain-shell fallback: the pty IS the shell
- }
-
- /**
- * Deliver one chunk of a controller's input to the session's pane. Resolves whether it was
- * delivered; never rejects. Serialized per session id: a second chunk starts only after the first
- * settled, so keys and pastes reach the pane in the order they were typed. The Session is re-read
- * inside each step (it can be gone by then → false), and the tmux name is resolved from it, never
- * from the caller. A false is never retried here (a timed-out delivery may well have run).
- *
- * BOUNDED on every route, by a deadline PANE_INPUT_DEADLINE_MS after the chunk was HANDED OVER —
- * the link host's own deadline, which runs from the same moment. The tmux and SSH routes are bounded
- * already (`runWithStdin`: PROC_TIMEOUT_MS), the session host's request by its own timeout once
- * connected — but its reconnect can wait on a host that is still starting, and a step that never
- * settled would hold every later chunk behind it, to land long after the link host told its
- * controller it was dropped. So a step gets only what is LEFT of its chunk's deadline (a chunk that
- * waited 15 s behind a slow one has 5 s), answers false when it runs out (a late delivery may still
- * land, as with any timed-out one), and a chunk with nothing left when its turn comes is dropped
- * undelivered: whoever handed it over has given up on it.
- *
- * `isCurrent` (the link host's: its sender still controls, in the period it typed in) is asked right
- * before the step runs — after any wait behind a slow step, immediately before the spawn or the
- * write, nothing awaited in between: false (or a throw) and the chunk is never delivered (false).
- * A chunk handed over while its sender controlled must not land after a stop or a demotion.
- */
- controlInput(sessionId: string, chunk: ControlInputChunk, isCurrent?: () => boolean): Promise<boolean> {
- const handedAt = Date.now()
- const prev = this.controlInputChains.get(sessionId) ?? Promise.resolve(true)
- const step = prev
- .then(() => {
- const left = PANE_INPUT_DEADLINE_MS - (Date.now() - handedAt)
- return left <= 0 ? false : settleWithin(this.deliverControlInput(sessionId, chunk, isCurrent), left)
- })
- .catch(() => false)
- this.controlInputChains.set(sessionId, step)
- void step.then(() => {
- if (this.controlInputChains.get(sessionId) === step) this.controlInputChains.delete(sessionId)
- })
- return step
- }
-
- /** The tail of each session's `controlInput` chain; deleted when the tail settles. */
- private readonly controlInputChains = new Map<string, Promise<boolean>>()
-
- private async deliverControlInput(
- sessionId: string,
- chunk: ControlInputChunk,
- isCurrent?: () => boolean
- ): Promise<boolean> {
- // The chunk arrives from a viewer over the network: its shape is checked, not assumed.
- const c = chunk as { kind?: unknown; data?: unknown; text?: unknown } | null
- const keys = c?.kind === 'keys' && typeof c.data === 'string'
- const paste = c?.kind === 'paste' && typeof c.text === 'string'
- if (!keys && !paste) return false
- const s = this.sessions.get(sessionId)
- const route = this.watcherInputRoute(sessionId)
- if (!s || route === 'none') return false
- // An empty key chunk is refused on every route (the tmux builder would have no bytes to type);
- // a paste that sanitizes to nothing has nothing to do.
- if (keys && (c.data as string).length === 0) return false
- if (paste && sanitizePasteText(c.text as string).length === 0) return true
- // Right before the spawn or the write (synchronous from here to it, on every route): a sender that
- // stopped controlling while this chunk waited never gets it delivered. A throw reads as not current.
- if (isCurrent) {
- let current = false
- try {
- current = isCurrent() === true
- } catch {
- current = false
- }
- if (!current) return false
- }
- try {
- switch (route) {
- case 'tmux': {
- const tmuxPath = this.tmuxPath
- if (!tmuxPath || !s.persistKey) return false
- const plan = controlInputPlan(TMUX_SOCKET, sessionName(s.persistKey), chunk)
- if (!plan) return true
- return await runPasteDelivery(plan, (args, input) => runWithStdin(tmuxPath, args, input))
- }
- case 'ssh': {
- const ssh = findSsh()
- if (!ssh || !s.sshRemote || !s.persistKey) return false
- const { conn, controlPath } = s.sshRemote
- const plan = remoteControlInputPlan(conn, controlPath, sessionName(s.persistKey), chunk)
- if (!plan) return true
- return await runPasteDelivery(plan, (args, input) => runWithStdin(ssh, args, input))
- }
- case 'write': {
- if (chunk.kind === 'keys') {
- this.write(null, sessionId, chunk.data)
- return true
- }
- // A paste: framed only when the pane's app asked for bracketed paste, never with an Enter.
- // The session host's and a direct Windows pane's no-Enter text path (core/settled-text.ts)
- // writes at once — the screen-settle wait runs only before an Enter — and frames by the
- // emulator's own `?2004h` state, which is `paste-buffer -p`'s contract.
- if (s.nativeWindowsPane) return (await s.nativeWindowsPane.sendText(chunk.text, false)) === true
- const name = s.persistKey ?? s.indexKey
- if (s.sessionHost && name) return (await sessionHostSendKeys(sessionName(name), chunk.text, false)) === true
- // A plain shell: no emulator here knows what the app asked for, so unframed (markers at an
- // app that never asked would arrive as literal `[200~`).
- this.write(null, sessionId, sanitizePasteText(chunk.text))
- return true
- }
- }
- } catch {
- // A builder refusing a name it did not generate, or a pty that threw on write (it exited).
- return false
- }
- }
-
- /**
- * Can a live link offer Control on this node? `unsupported` for a Zellij node (session-wide key
- * bindings), or a node with no session on a machine whose new sessions are Zellij; `ok` when a
- * session for it is live or released (its pane can be reached), or when a new node would be
- * tmux-backed here; `unknown` otherwise (nothing to tell from yet).
- */
- nodeControlSupport(persistKey: string): ControlSupport {
- const live = this.liveSessionForPersistKey(persistKey)
- if (this.zellijKeys.has(persistKey) || live?.zellij) return 'unsupported'
- if (live || this.released.has(persistKey)) return 'ok'
- // No session here: a new one would be created in the SELECTED backend, and a Zellij one refuses
- // control. (A node whose tmux session is warm but not held by this process reads the same way
- // until it is mounted; the live branch above answers it then.)
- if (this.zellijSelected()) return 'unsupported'
- if (this.tmuxPath && this.getSettings().tmuxEnabled) return 'ok'
- return 'unknown'
- }
-
- /**
- * Join a node's RUNNING session as a live link's viewer. It never starts one (`joinOnly`: a session
- * that cannot be confirmed is refused `unavailable: 'join-only'`), and it never votes on its size:
- * - joining a Session held in this process casts no size vote (`sizeVote: false`) — the pty stays
- * at its owners' size;
- * - when no Session is held it spawns its OWN tmux client (shared by later viewers of the node):
- * `attach-session -E -f ignore-size,read-only` on the exact target (`watch-link/watcher-client.ts`)
- * — never creating, never stripping the session env, unable to type.
- * `ignore-size` is NOT unconditional (measured, tmux 3.4): tmux honours it only while at least one
- * client WITHOUT the flag is attached to some session on the same server. When the watcher's client
- * is the only one, tmux's `window-size latest` sizes the window to it. So the client is spawned at
- * the window's CURRENT size, read immediately before the spawn and REFUSED when it cannot be read
- * (`spawnNew`), and `syncWatcherClientSize` keeps it there while the link host has viewers. Residual:
- * when the watcher becomes the only client, the window stays at the last-synced size until another
- * client sizes it, and a read can race an owner resizing or leaving (the window then keeps the size
- * read a moment before).
- * A local tmux older than 3.2 has no client flags: refused. Only the named fields are forwarded, and
- * the watcher rules are set after them. A remote node is never watched through the local tmux
- * (`requireRemote` whenever `sshRemote` is given).
- */
- async joinAsWatcher(
- clientId: ClientId,
- opts: {
- persistKey: string
- viewerId: string
- cols?: number
- rows?: number
- sshRemote?: PtyCreateOptions['sshRemote']
- requireRemote?: boolean
- }
- ): Promise<PtyCreateResult> {
- const { persistKey, viewerId, sshRemote } = opts
- // The Session a watcher create would JOIN (`join` reads the index).
- const indexedId = this.byPersistKey.get(persistKey)
- const held = indexedId ? this.sessions.get(indexedId) : undefined
- const given =
- Number.isInteger(opts.cols) && Number.isInteger(opts.rows) && opts.cols! > 0 && opts.rows! > 0
- ? { cols: opts.cols!, rows: opts.rows! }
- : undefined
- // The size this view starts at when it JOINS a client that already exists (it is told the
- // authoritative size right after). It is never a spawn size: a watcher's own client is spawned only
- // at the window size `spawnNew` reads itself, or not at all. For a HELD session that is the
- // session's own size — no tmux read (R64/M4): the read took the CALLER's `sshRemote`, which is
- // absent for a remote node whose master is down, and so asked the LOCAL tmux about a remote node.
- const size =
- given ??
- (held && indexedId ? this.sessionSize(indexedId) : null) ??
- this.watchSizeFor(persistKey) ?? { cols: 80, rows: 24 }
- const options: WatcherCreateOptions = {
- persistKey,
- viewerId,
- cols: size.cols,
- rows: size.rows,
- ...(sshRemote ? { sshRemote } : {}),
- ...(opts.requireRemote || sshRemote ? { requireRemote: true } : {}),
- joinOnly: true,
- sizeVote: false,
- [WATCHER_CLIENT]: true
- }
- return this.create(clientId, options)
- }
-
- /**
- * Keep a watcher's OWN tmux client at the window's current size, so that if it becomes the only
- * client on the server (when tmux stops honouring `ignore-size`) the window keeps its latest size
- * instead of snapping to the size the client was spawned at. The link host calls it on every
- * keyframe and on a timer while the node has viewers.
- *
- * Reads the window size by exact target (locally, or over the ControlMaster) and resizes THIS
- * client's pty to exactly that — not a size vote (`sizes` is untouched), never a viewer-supplied
- * size — then tells the viewers the size they render, as `applySize` does. A no-op answering false
- * for anything that is not a watcher's own client, an unreadable size, or a session that went away
- * during the read. With the production conf (`status off`) the window IS the client size, so a
- * client of the window's size leaves the window where it is.
- *
- * SERIALIZED per session (controller ruling R24): the link host calls it before every keyframe and
- * on a timer, and two links can watch one node, so calls overlap — and two reads racing each other
- * could be applied out of order, leaving the client at the OLDER size. So one read is in flight per
- * session, and every caller that arrives meanwhile shares ONE queued rerun that reads after it: the
- * latest read is the one applied last. Never rejects.
- */
- syncWatcherClientSize(sessionId: string): Promise<boolean> {
- const slot = this.watcherSizeSyncs.get(sessionId)
- if (!slot) return this.startWatcherSizeSync(sessionId)
- // Starts only once the read in flight settled, so its answer can never land after this one.
- slot.rerun ??= slot.current.then(() => this.startWatcherSizeSync(sessionId))
- return slot.rerun
- }
-
- /** One `syncWatcherClientSize` read per session at a time; `rerun` is the one queued behind it. */
- private readonly watcherSizeSyncs = new Map<string, { current: Promise<boolean>; rerun: Promise<boolean> | null }>()
-
- private startWatcherSizeSync(sessionId: string): Promise<boolean> {
- const current = this.syncWatcherClientSizeOnce(sessionId)
- const slot = { current, rerun: null as Promise<boolean> | null }
- this.watcherSizeSyncs.set(sessionId, slot)
- // Registered BEFORE any rerun's `.then`, so it runs first: with a rerun queued the slot stays until
- // the rerun replaces it; with none, the session has no sync in flight any more.
- void current.finally(() => {
- if (this.watcherSizeSyncs.get(sessionId) === slot && !slot.rerun) this.watcherSizeSyncs.delete(sessionId)
- })
- return current
- }
-
- private async syncWatcherClientSizeOnce(sessionId: string): Promise<boolean> {
- try {
- const session = this.sessions.get(sessionId)
- if (!session?.watcherClient || !session.persistKey) return false
- // A session-host watch attachment has no window to read: the host pushes the pty's size
- // itself (`geometry`), and `applyBackendSize` already forwards it to the viewers.
- if (session.sessionHost) return true
- const size = await this.readWindowSize(session.persistKey, session.sshRemote)
- if (!size || this.sessions.get(sessionId) !== session) return false
- if (session.appliedSize?.cols !== size.cols || session.appliedSize?.rows !== size.rows) {
- try {
- session.proc.resize(size.cols, size.rows)
- } catch {
- return false // the client already exited
- }
- session.appliedSize = size
- }
- // The same per-subscriber `pty:size` applySize sends (a live link's viewer renders exactly this).
- const channel = IPC.ptySize(sessionId)
- for (const sub of session.subscribers) {
- const shown = session.shown.get(sub)
- if (shown && shown.cols === size.cols && shown.rows === size.rows) continue
- session.shown.set(sub, size)
- this.send(subClient(sub), channel, size)
- }
- return true
- } catch {
- return false
- }
- }
-
- /**
- * The size a session runs at NOW: the backend's authoritative size (the session host's answer),
- * else the size pushed into its pty. What a live link's `watch:meta` reports for the session a viewer
- * just joined (controller ruling R25): for a co-attached watcher that is the owner's pty size; for a
- * watcher's OWN client it is the window size the client was spawned at and `syncWatcherClientSize`
- * keeps it at — a client `watchSizeFor` cannot see (it is hidden from every persistKey lookup). A
- * copy; null for a session this manager does not know, or one that has no size yet.
- */
- sessionSize(sessionId: string): { cols: number; rows: number } | null {
- const session = this.sessions.get(sessionId)
- const size = session?.backendSize ?? session?.appliedSize
- return size ? { cols: size.cols, rows: size.rows } : null
- }
-
- /**
- * The CURRENT size a client of a node's tmux window has, read from tmux rather than from memory:
- * with no Session held there is nothing to remember it from. One `display-message` by exact target
- * reads `#{window_width} #{window_height} #{status}`, and the status lines are ADDED to the height
- * (`parseWindowSize`): a client is window + status rows tall, so a client spawned at the bare window
- * height would make tmux shrink the window. With the production conf (`status off`) the two agree.
- * Local, or over the ControlMaster for an SSH node (never the local tmux for a remote node: the
- * caller passes the node's `sshRemote`, and a remote node with no master is not read at all).
- * undefined on any failure, an exact-target miss (tmux answers exit 0 with empty formats) or a
- * status value it does not know.
- */
- async readWindowSize(
- persistKey: string,
- sshRemote?: PtyCreateOptions['sshRemote']
- ): Promise<{ cols: number; rows: number } | undefined> {
- const target = sessionName(persistKey)
- try {
- if (sshRemote) {
- const ssh = findSsh()
- if (!ssh) return undefined
- const { stdout } = await runAsync(ssh, remoteWindowSizeArgs(sshRemote.conn, sshRemote.controlPath, target), {
- encoding: 'utf-8'
- })
- return parseWindowSize(stdout)
- }
- if (!this.tmuxPath) return undefined
- const { stdout } = await runAsync(this.tmuxPath, localWindowSizeArgs(TMUX_SOCKET, target), {
- encoding: 'utf-8',
- timeout: PROBE_TIMEOUT_MS
- })
- return parseWindowSize(stdout)
- } catch {
- return undefined
- }
- }
-
- /** `tmux -V` for the LOCAL binary, per binary path (a watcher client needs >= 3.2). Only a DEFINITE
- * answer — tmux printed a version, supported or not — is kept; a probe that failed (spawn error,
- * timeout) is dropped, so the next watcher join asks again. Concurrent joins share one probe. */
- private watcherTmuxProbe: { path: string; ok: Promise<boolean> } | null = null
- /** The refusal is logged once per app run, not once per viewer. */
- private watcherTmuxRefusalLogged = false
-
- private localTmuxSupportsWatcherClient(): Promise<boolean> {
- const tmuxPath = this.tmuxPath
- if (!tmuxPath) return Promise.resolve(false)
- if (this.watcherTmuxProbe?.path === tmuxPath) return this.watcherTmuxProbe.ok
- const probe: { path: string; ok: Promise<boolean> } = {
- path: tmuxPath,
- ok: this.confirmedProcessRun(tmuxPath, ['-V'], { timeout: PROBE_TIMEOUT_MS, encoding: 'utf-8' }).then(
- (res) => {
- const stdout = String((res as { stdout?: unknown })?.stdout ?? '')
- const supported = supportsWatcherClient(parseTmuxVersion(stdout))
- if (!supported && !this.watcherTmuxRefusalLogged) {
- this.watcherTmuxRefusalLogged = true
- const seen = stdout.trim().slice(0, 40) || 'unknown'
- console.warn(
- `[pty] live link watchers refused: the local tmux (${seen}) has no client flags; tmux 3.2 or newer is needed`
- )
- }
- return supported
- },
- () => {
- // Not an answer: forget this probe (unless a newer one replaced it) and refuse this join.
- if (this.watcherTmuxProbe === probe) this.watcherTmuxProbe = null
- return false
- }
- )
- }
- this.watcherTmuxProbe = probe
- return probe.ok
- }
-
- /**
- * The size a live link should report for a node: what its pty runs at now (the session host's
- * authoritative size first, else the size pushed into the pty), or what it ran at when its last
- * client was released. A copy; undefined when this process never ran the node.
- */
- watchSizeFor(persistKey: string): { cols: number; rows: number } | undefined {
- const live = this.liveSessionForPersistKey(persistKey)
- const size = live?.backendSize ?? live?.appliedSize ?? this.released.get(persistKey)?.size
- return size ? { cols: size.cols, rows: size.rows } : undefined
- }
-
/**
* Where the pane's cursor is, for a client about to PAINT a captured screen.
*
@@ -6862,7 +6368,7 @@ export class PtyManager {
/**
* Type raw keys into a node's tmux pane by node id — no mounted terminal needed. Same stdin-only
- * `source-file -` plan a live-link controller uses (bytes never ride argv; exact target
+ * `source-file -` plan of pane-input.ts (bytes never ride argv; exact target
* `=nt-<id>:`), local or over the owning project's ControlMaster. Never rejects.
*/
async sendPaneKeys(persistKey: string, data: string): Promise<PaneKeysResult> {
diff --git a/src/core/pty-persistence-status.test.ts b/src/core/pty-persistence-status.test.ts
index 61c06ce1a..2b17f4b3e 100644
--- a/src/core/pty-persistence-status.test.ts
+++ b/src/core/pty-persistence-status.test.ts
@@ -4,12 +4,10 @@ import { fakePlatform } from './platform-fake'
import { PtyManager } from './pty-manager'
const host = vi.hoisted(() => ({
- supported: vi.fn(() => false),
- watchKnown: vi.fn((): boolean | undefined => undefined)
+ supported: vi.fn(() => false)
}))
vi.mock('./session-host-backend', () => ({
- sessionHostSupported: host.supported,
- sessionHostWatchKnown: host.watchKnown
+ sessionHostSupported: host.supported
}))
vi.mock('node-pty', () => ({ spawn: vi.fn() }))
@@ -17,7 +15,6 @@ describe('local persistence discovery (#575)', () => {
beforeEach(() => {
initPlatform(fakePlatform())
host.supported.mockReturnValue(false)
- host.watchKnown.mockReset().mockReturnValue(undefined)
})
afterEach(() => { vi.restoreAllMocks(); resetPlatformForTests() })
@@ -43,9 +40,8 @@ describe('local persistence discovery (#575)', () => {
it('never treats a Windows tmux path as protection', () => {
expect(manager('win32', true).tmuxStatus().persistence?.backend).toBeNull()
})
- it('reports no live-link join flag, whatever the connected host speaks', () => {
+ it('reports the session-host backend and nothing else', () => {
host.supported.mockReturnValue(true)
- host.watchKnown.mockReturnValue(true)
expect(manager('win32', false).tmuxStatus().persistence).toEqual({ enabled: true, backend: 'session-host' })
})
it('keeps the user setting distinct from backend discovery', () => {
diff --git a/src/core/pty-require-remote-join.test.ts b/src/core/pty-require-remote-join.test.ts
index 21861c11f..c262ebcfe 100644
--- a/src/core/pty-require-remote-join.test.ts
+++ b/src/core/pty-require-remote-join.test.ts
@@ -166,8 +166,8 @@ describe('requireRemote create vs a live session of the same node id', () => {
})
it('warns once for the held session, however often the refused join is retried', async () => {
- // A live-link watcher retries its join every 2/4/8/15 s for as long as the link lives, and each
- // retry is refused the same way: one warning for the held session, not one per retry.
+ // A caller may retry a refused join on a backoff, and each retry is refused the same way: one
+ // warning for the held session, not one per retry.
const local = await localHeld()
const retry = () => create(MODAL_OR_SECOND_VIEW, { agentId: 'claude', requireRemote: true })
const results = [await retry(), await retry(), await retry()]
diff --git a/src/core/pty-session-host-watch-zellij.test.ts b/src/core/pty-session-host-watch-zellij.test.ts
index 9f857e896..538e1c9c6 100644
--- a/src/core/pty-session-host-watch-zellij.test.ts
+++ b/src/core/pty-session-host-watch-zellij.test.ts
@@ -1,7 +1,7 @@
// A POSIX machine with NO tmux: the session host is eligible, but a node may live in Zellij instead.
// A join-only create (hosted-relay viewer) whose session the host does NOT have must fall through to
// the existing join decision — which reaches a LIVE Zellij session — rather than being refused by the
-// session-host watch probe before Zellij is ever asked (review of the win-10-live-links package).
+// session-host watch probe before Zellij is ever asked.
import fs from 'fs'
import path from 'path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
diff --git a/src/core/pty-session-host-watch.test.ts b/src/core/pty-session-host-watch.test.ts
index ee4c834b6..ebd73fabf 100644
--- a/src/core/pty-session-host-watch.test.ts
+++ b/src/core/pty-session-host-watch.test.ts
@@ -1,6 +1,6 @@
-// Live links on a SESSION-HOST node (Windows, or no tmux): a join-only create — a live link watcher or
-// a hosted-relay viewer — joins a generation the host CONFIRMED through a read-only `watch-attach`
-// attachment, and is refused for every other answer; the keyframe and the pane cwd come from the
+// A SESSION-HOST node (Windows, or no tmux): a join-only create — a hosted-relay viewer — joins a
+// generation the host CONFIRMED through a read-only `watch-attach`
+// attachment, and is refused for every other answer; the visible screen and the pane cwd come from the
// host's own negotiated reads. Harness mirrors pty-session-host.test.ts: no local tmux, so the
// session host is the selected backend, and every backend export this file reaches is mocked.
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
@@ -39,7 +39,6 @@ vi.mock('./session-host-backend', async (importOriginal) => ({
watchExistingSessionHostPty: backend.watch,
sessionHostHasSession: backend.hasSession,
sessionHostSupportsWatch: backend.supportsWatch,
- sessionHostWatchKnown: () => undefined,
sessionHostCaptureVisible: backend.captureVisible,
sessionHostPaneCwd: backend.paneCwd,
sessionHostCapture: backend.capture,
@@ -154,16 +153,6 @@ describe('PtyManager: join-only creates on the session host', () => {
expect(backend.attachExisting).not.toHaveBeenCalled()
})
- it('a live link watcher (joinAsWatcher) takes the same route and has no typing path', async () => {
- const m = await makeManager()
- const res = await m.joinAsWatcher(VIEWER, { persistKey: NODE, viewerId: 'link-a' })
- expect(res.unavailable).toBeUndefined()
- expect(backend.watch).toHaveBeenCalledTimes(1)
- expect(m.watcherInputRoute(res.sessionId)).toBe('none')
- // A session-host watch has no tmux window to read; the host pushes its size itself.
- await expect(m.syncWatcherClientSize(res.sessionId)).resolves.toBe(true)
- })
-
it('an owner opening the node afterwards gets its OWN attachment, never the viewer one', async () => {
await makeManager()
const viewer = await viewerCreate()
diff --git a/src/core/pty-spawn-refusal-ssh.test.ts b/src/core/pty-spawn-refusal-ssh.test.ts
new file mode 100644
index 000000000..8ea3d92e8
--- /dev/null
+++ b/src/core/pty-spawn-refusal-ssh.test.ts
@@ -0,0 +1,61 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import { fakePlatform } from './platform-fake'
+import type { PtyCreateOptions } from '../shared/types'
+
+/**
+ * A remote node needs an ssh to run over. On Windows without the OpenSSH Client feature there is no
+ * ssh binary: `spawnRefusal` refuses such a node as `ssh` where ssh is a process, and serves it where
+ * the native transport (src/core/remote-ssh/native) carries it without one.
+ */
+
+vi.mock('./session-host-backend', async () =>
+ (await import('./__fixtures__/no-session-host')).noSessionHost()
+)
+
+// `ssh` is found or not per test (`findSsh` memoizes per module, hence `vi.resetModules` below).
+const ssh = vi.hoisted(() => ({ path: '/usr/bin/ssh' as string | null }))
+vi.mock('./exec-path', async (importOriginal) => {
+ const real = await importOriginal<typeof import('./exec-path')>()
+ return {
+ ...real,
+ findExecutableSync: (bin: string, fallbacks?: string[]) =>
+ bin === 'ssh' ? ssh.path : real.findExecutableSync(bin, fallbacks)
+ }
+})
+
+let platformModule: typeof import('./platform')
+
+beforeEach(async () => {
+ ssh.path = '/usr/bin/ssh'
+ // A fresh module graph per test (`findSsh` memoizes per module), so the platform the manager
+ // reads is the one initialised here — imported AFTER the reset, never the static copy.
+ vi.resetModules()
+ platformModule = await import('./platform')
+ platformModule.initPlatform(fakePlatform())
+})
+afterEach(() => {
+ platformModule.resetPlatformForTests()
+})
+
+async function manager() {
+ const { PtyManager } = await import('./pty-manager')
+ return new PtyManager()
+}
+
+describe('spawnRefusal with no ssh binary (Windows without the OpenSSH Client feature)', () => {
+ const SSH_REMOTE = { controlPath: '/tmp/nt-test-cm', conn: { host: 'h', user: 'u' }, remoteCwd: '/srv/app' }
+ const opts = { cols: 80, rows: 24, persistKey: 'n-native', sshRemote: SSH_REMOTE, requireRemote: true } as PtyCreateOptions
+ afterEach(() => vi.unstubAllEnvs())
+
+ it('refused as ssh where ssh is a process; served where the native transport carries it', async () => {
+ ssh.path = null
+ const m = await manager()
+ const refusal = (o: PtyCreateOptions): string | undefined =>
+ (m as unknown as { spawnRefusal(o: PtyCreateOptions): string | undefined }).spawnRefusal(o)
+ vi.stubEnv('NODETERM_NATIVE_SSH', '0')
+ expect(refusal(opts)).toBe('ssh')
+ // The `ssh` sentinel every runner routes to NativeMux: nothing is spawned from it.
+ vi.stubEnv('NODETERM_NATIVE_SSH', '1')
+ expect(refusal(opts)).toBeUndefined()
+ })
+})
diff --git a/src/core/pty-watch-join.test.ts b/src/core/pty-watch-join.test.ts
deleted file mode 100644
index b16199640..000000000
--- a/src/core/pty-watch-join.test.ts
+++ /dev/null
@@ -1,743 +0,0 @@
-import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
-import { fakePlatform, type FakePlatform } from './platform-fake'
-import { IPC } from '../shared/ipc'
-import type { PtyCreateOptions, PtyCreateResult } from '../shared/types'
-
-/**
- * A live link's viewer joins a node's RUNNING session: `joinAsWatcher` must never spawn one and never
- * vote on its size, whatever the caller hands it, and `watchSizeFor` names the size the link reports.
- * Harness copied from pty-join-only.test.ts (a mocked `node-pty` that records each spawn and each
- * resize, so "spawned nothing" is `spawned.length === 0` and "kept its size" is "no resize pushed").
- */
-
-interface FakePty {
- file: string
- args: string[]
- cols: number
- rows: number
- writes: string[]
- onDataCb?: (d: string) => void
- onExitCb?: (e: { exitCode: number }) => void
- resizes: Array<{ cols: number; rows: number }>
- killed: boolean
-}
-const spawned: FakePty[] = []
-
-vi.mock('./session-host-backend', async () =>
- (await import('./__fixtures__/no-session-host')).noSessionHost()
-)
-
-vi.mock('node-pty', () => ({
- spawn: (file: string, args: string[], opts: { cols: number; rows: number }) => {
- const p: FakePty = {
- file,
- args: [...(args ?? [])],
- cols: opts.cols,
- rows: opts.rows,
- writes: [],
- resizes: [],
- killed: false
- }
- spawned.push(p)
- return {
- onData: (cb: (d: string) => void) => {
- p.onDataCb = cb
- },
- onExit: (cb: (e: { exitCode: number }) => void) => {
- p.onExitCb = cb
- },
- write: (d: string) => p.writes.push(d),
- resize: (cols: number, rows: number) => p.resizes.push({ cols, rows }),
- pause: () => {},
- resume: () => {},
- kill: () => {
- p.killed = true
- },
- pid: 1234
- }
- }
-}))
-
-vi.mock('./pty-devices', async (importOriginal) => ({
- ...(await importOriginal<typeof import('./pty-devices')>()),
- readPtyDevices: () => ({ ceiling: 511, inUse: 8 })
-}))
-
-// `ssh` is found or not per test (`findSsh` memoizes per module, hence `vi.resetModules` below).
-const ssh = vi.hoisted(() => ({ path: '/usr/bin/ssh' as string | null }))
-vi.mock('./exec-path', async (importOriginal) => {
- const real = await importOriginal<typeof import('./exec-path')>()
- return {
- ...real,
- findExecutableSync: (bin: string, fallbacks?: string[]) =>
- bin === 'ssh' ? ssh.path : real.findExecutableSync(bin, fallbacks)
- }
-})
-vi.mock('./remote-ssh/agent-probe', async (importOriginal) => ({
- ...(await importOriginal<typeof import('./remote-ssh/agent-probe')>()),
- probeAgentSockToPin: async () => undefined
-}))
-
-const OWNER = 1
-const WATCHER = 7
-const VIEWER = 2
-const REFUSED: PtyCreateResult = { sessionId: '', fresh: false, unavailable: 'join-only' }
-
-let fake: FakePlatform
-
-let platformModule: typeof import('./platform')
-
-beforeEach(async () => {
- spawned.length = 0
- ssh.path = '/usr/bin/ssh'
- // A fresh module graph per test (`findSsh` memoizes per module), so the platform the manager
- // reads is the one initialised here — imported AFTER the reset, never the static copy.
- vi.resetModules()
- platformModule = await import('./platform')
- fake = fakePlatform()
- platformModule.initPlatform(fake)
- vi.useFakeTimers()
-})
-afterEach(() => {
- vi.useRealTimers()
- platformModule.resetPlatformForTests()
-})
-
-type ConfirmedProcessRun = (file: string, args: readonly string[], opts?: object) => Promise<unknown>
-
-async function manager(deps: { confirmedProcessRun?: ConfirmedProcessRun } = {}) {
- const { PtyManager } = await import('./pty-manager')
- const m = new PtyManager(deps)
- m.registerIpc()
- return m
-}
-
-/** `has-session` as tmux 3.4 resolves it: `=name` is exact, a bare name prefix-matches a miss. */
-function hasSession(live: string[], args: readonly string[]): boolean {
- const target = args[args.indexOf('-t') + 1] ?? ''
- if (target.startsWith('=')) return live.includes(target.slice(1))
- return live.some((s) => s === target || s.startsWith(target))
-}
-
-/** Every `tmux -V` the manager asked (the watcher client's version probe). */
-const versionAsks: string[] = []
-
-/** A `tmux -V` that could not run at all (spawn error, timeout) — not an answer. */
-const PROBE_FAILS = 'PROBE_FAILS'
-
-/** A tmux-backed manager whose probes answer from `live` without touching a tmux socket. `version`
- * is what `tmux -V` answers (a list is consumed in order, the last answer repeating); `window` what
- * the window-size read answers, `null` = unreadable. */
-async function tmuxManager(
- live: string[],
- {
- version = 'tmux 3.4\n',
- window = { cols: 120, rows: 39 }
- }: { version?: string | string[]; window?: { cols: number; rows: number } | null } = {}
-) {
- versionAsks.length = 0
- const answers = Array.isArray(version) ? [...version] : [version]
- const confirmedProcessRun: ConfirmedProcessRun = async (_file, args) => {
- if (args[0] === '-V') {
- const answer = answers.length > 1 ? answers.shift()! : answers[0]
- versionAsks.push(answer)
- if (answer === PROBE_FAILS) throw Object.assign(new Error('spawn tmux ETIMEDOUT'), { code: 'ETIMEDOUT' })
- return { stdout: answer, stderr: '' }
- }
- if (hasSession(live, args)) return { stdout: '', stderr: '' }
- throw Object.assign(new Error("can't find session"), { code: 1 })
- }
- const m = await manager({ confirmedProcessRun })
- vi.spyOn(
- m as unknown as { readWindowSize: (k: string) => Promise<unknown> },
- 'readWindowSize'
- ).mockResolvedValue(window ?? undefined)
- ;(m as unknown as { tmuxPath: string }).tmuxPath = '/usr/bin/tmux'
- vi.spyOn(
- m as unknown as { tmuxSessionExists: (k: string) => Promise<boolean> },
- 'tmuxSessionExists'
- ).mockImplementation(async (k: string) => hasSession(live, ['-t', `nt-${k}`]))
- vi.spyOn(
- m as unknown as { paneCwdStale: (k: string) => Promise<boolean> },
- 'paneCwdStale'
- ).mockResolvedValue(false)
- return m
-}
-
-const create = (clientId: number, options: Partial<PtyCreateOptions>) =>
- fake.handlers[IPC.ptyCreate](clientId, {
- cols: 80,
- rows: 24,
- persistKey: 'n1',
- ...options
- }) as Promise<PtyCreateResult>
-const kill = (clientId: number, sessionId: string) =>
- fake.senderListeners[IPC.ptyKill](clientId, sessionId)
-const WATCH = { persistKey: 'n1', viewerId: 'watch-s1', cols: 40, rows: 10 }
-
-describe('joinAsWatcher', () => {
- it('never starts a session: no live session is a join-only refusal, and nothing spawns', async () => {
- const m = await manager()
- expect(await m.joinAsWatcher(WATCHER, WATCH)).toEqual(REFUSED)
- expect(spawned).toHaveLength(0)
- })
-
- it('refuses when only a session whose name EXTENDS this node id is alive', async () => {
- const m = await tmuxManager(['nt-n12'])
- expect(await m.joinAsWatcher(WATCHER, WATCH)).toEqual(REFUSED)
- expect(spawned).toHaveLength(0)
- })
-
- it("joins the owner's live session and never shrinks it", async () => {
- const m = await manager()
- const a = await create(OWNER, { cols: 120, rows: 40 })
- const w = await m.joinAsWatcher(WATCHER, WATCH)
- expect(w.sessionId).toBe(a.sessionId)
- expect(w.fresh).toBe(false)
- expect(w.unavailable).toBeUndefined()
- expect(spawned).toHaveLength(1)
- expect(spawned[0].resizes).toEqual([])
- // Still a subscriber: told the authoritative size to render.
- const sizes = fake.sent.filter((s) => s.channel === IPC.ptySize(a.sessionId))
- expect(sizes.map((s) => s.to)).toEqual([WATCHER])
- expect(sizes[0].args[0]).toEqual({ cols: 120, rows: 40 })
- })
-
- it('with no Session held, spawns its OWN client: attach-session -E -f ignore-size,read-only, exact target', async () => {
- const m = await tmuxManager(['nt-n1'])
- const w = await m.joinAsWatcher(WATCHER, WATCH)
- expect(w.unavailable).toBeUndefined()
- expect(w.fresh).toBe(false)
- expect(spawned).toHaveLength(1)
- expect(spawned[0].file).toBe('/usr/bin/tmux')
- expect(spawned[0].args).toEqual([
- '-L',
- 'node-terminal',
- 'attach-session',
- '-E',
- '-f',
- 'ignore-size,read-only',
- '-t',
- '=nt-n1:'
- ])
- })
-
- it('control: a hosted Viewer (joinOnly, not a watcher) keeps its new-session -A mirror, byte-identical', async () => {
- await tmuxManager(['nt-n1'])
- await create(VIEWER, { joinOnly: true, sizeVote: false })
- expect(spawned[0].args).toContain('new-session')
- expect(spawned[0].args).toContain('-A')
- expect(spawned[0].args).not.toContain('attach-session')
- expect(versionAsks).toEqual([]) // no version probe on that path either
- })
-
- it('spawns its client at the window CURRENT size, not the caller-reported one', async () => {
- const m = await tmuxManager(['nt-n1'], { window: { cols: 132, rows: 43 } })
- await m.joinAsWatcher(WATCHER, WATCH)
- expect([spawned[0].cols, spawned[0].rows]).toEqual([132, 43])
- })
-
- it('an unreadable window size REFUSES the spawn — never a guessed size (caller, remembered, default)', async () => {
- const m = await tmuxManager(['nt-n1'], { window: null })
- // The caller's size is not used...
- expect(await m.joinAsWatcher(WATCHER, WATCH)).toEqual(REFUSED)
- // ...nor the default...
- expect(await m.joinAsWatcher(WATCHER, { persistKey: 'n1', viewerId: 'watch-s1' })).toEqual(REFUSED)
- expect(spawned).toHaveLength(0)
- // ...nor a remembered (released) size.
- const own = await create(OWNER, { cols: 132, rows: 43 })
- kill(OWNER, own.sessionId)
- expect(m.watchSizeFor('n1')).toEqual({ cols: 132, rows: 43 })
- expect(await m.joinAsWatcher(WATCHER, WATCH)).toEqual(REFUSED)
- expect(spawned).toHaveLength(1) // the owner's own client, nothing for the watcher
- })
-
- it('the refusal is "not now": once the window can be read, the next join spawns', async () => {
- const m = await tmuxManager(['nt-n1'], { window: null })
- expect(await m.joinAsWatcher(WATCHER, WATCH)).toEqual(REFUSED)
- ;(m as unknown as { readWindowSize: ReturnType<typeof vi.fn> }).readWindowSize.mockResolvedValue({
- cols: 150,
- rows: 45
- })
- const w = await m.joinAsWatcher(WATCHER, WATCH)
- expect(w.unavailable).toBeUndefined()
- expect([spawned[0].cols, spawned[0].rows]).toEqual([150, 45])
- })
-
- // R64/M4: joining a HELD session reads nothing from tmux — the session's own size is the answer.
- // The read used to take the CALLER's sshRemote, which is absent for a remote node whose master is
- // down, and so asked the LOCAL tmux about a remote node's name.
- it('reads the window size only to SPAWN a client — never to join a held session', async () => {
- const m = await tmuxManager(['nt-n1'], { window: { cols: 132, rows: 43 } })
- const read = (m as unknown as { readWindowSize: ReturnType<typeof vi.fn> }).readWindowSize
- // The held session is a REMOTE node's (an SSH project's), the case R64/M4 is about: a
- // `requireRemote` watcher may join it, where a held LOCAL session would be refused
- // (`held-elsewhere`) and the size rule below would never run. No host is asked anything: the
- // freshness read answers "absent" so the owner's (mocked) ssh client spawns.
- const internals = m as unknown as {
- remoteSessionVerdict: () => Promise<string>
- captureForResync: (s: string) => Promise<string>
- paneCursor: (s: string) => Promise<unknown>
- }
- vi.spyOn(internals, 'remoteSessionVerdict').mockResolvedValue('absent')
- vi.spyOn(internals, 'captureForResync').mockResolvedValue('')
- vi.spyOn(internals, 'paneCursor').mockResolvedValue(undefined)
- const sshRemote = { controlPath: '/tmp/nt-test-cm-watch-size', conn: { host: 'h', user: 'u' }, remoteCwd: '/srv/app' }
- const a = await create(OWNER, { cols: 120, rows: 40, requireRemote: true, sshRemote })
- expect(a.unavailable).toBeUndefined()
- expect(spawned[0].file).toBe('/usr/bin/ssh')
- await m.joinAsWatcher(WATCHER, WATCH) // a live Session is held and the caller gave a size
- // No size, and no master (it is down): joins the held remote session.
- const w = await m.joinAsWatcher(WATCHER + 1, { persistKey: 'n1', viewerId: 'watch-s2', requireRemote: true })
- expect(w.unavailable).toBeUndefined()
- expect(w.sessionId).toBe(a.sessionId)
- expect(spawned).toHaveLength(1)
- expect(read).not.toHaveBeenCalled()
- // The view is shown the held session's own size (nothing to correct, so nothing more is sent).
- expect(fake.sent.filter((x) => x.channel === IPC.ptySize(a.sessionId) && x.to === WATCHER + 1)).toEqual([])
- // With nothing held, the spawn reads it — once, by the node's exact target.
- const m2 = await tmuxManager(['nt-n2'], { window: { cols: 132, rows: 43 } })
- const read2 = (m2 as unknown as { readWindowSize: ReturnType<typeof vi.fn> }).readWindowSize
- await m2.joinAsWatcher(WATCHER, { persistKey: 'n2', viewerId: 'watch-s3' })
- expect(read2).toHaveBeenCalledTimes(1)
- expect(read2.mock.calls[0][0]).toBe('n2')
- })
-
- // R64/M4: a watcher never paints from the co-attach screen (its keyframe is a visible-only capture),
- // so a join captures nothing for it. On SSH that was a `-S -200` history capture per viewer join.
- it("a watcher's join takes no co-attach capture; a second owner view still does (control)", async () => {
- const m = await tmuxManager(['nt-n1'])
- const spies = m as unknown as { captureForResync: (s: string) => Promise<string>; paneCursor: (s: string) => Promise<unknown> }
- const capture = vi.spyOn(spies, 'captureForResync').mockResolvedValue('SCREEN')
- const cursor = vi.spyOn(spies, 'paneCursor').mockResolvedValue(undefined)
- await create(OWNER, { cols: 120, rows: 40 })
- const w = await m.joinAsWatcher(WATCHER, WATCH)
- expect(w.unavailable).toBeUndefined()
- expect(w.screen).toBeUndefined()
- expect(capture).not.toHaveBeenCalled()
- expect(cursor).not.toHaveBeenCalled()
- const second = await create(VIEWER, { cols: 120, rows: 40 })
- expect(second.screen).toBe('SCREEN')
- expect(capture).toHaveBeenCalledTimes(1)
- })
-
- it('local tmux < 3.2 has no client flags: FAIL CLOSED, nothing spawned, logged once', async () => {
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
- const m = await tmuxManager(['nt-n1'], { version: 'tmux 3.1c\n' })
- expect(await m.joinAsWatcher(WATCHER, WATCH)).toEqual(REFUSED)
- expect(await m.joinAsWatcher(WATCHER, WATCH)).toEqual(REFUSED)
- expect(spawned).toHaveLength(0)
- expect(versionAsks).toHaveLength(1) // memoized
- const lines = warn.mock.calls.filter((c) => String(c[0]).includes('live link'))
- expect(lines).toHaveLength(1)
- expect(String(lines[0][0])).toContain('3.2')
- warn.mockRestore()
- })
-
- it('an unreadable local tmux version fails closed too', async () => {
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
- const m = await tmuxManager(['nt-n1'], { version: 'tmux master\n' })
- expect(await m.joinAsWatcher(WATCHER, WATCH)).toEqual(REFUSED)
- expect(spawned).toHaveLength(0)
- warn.mockRestore()
- })
-
- it('a FAILED version probe is not an answer: not memoized, the next join asks again', async () => {
- const m = await tmuxManager(['nt-n1'], { version: [PROBE_FAILS, 'tmux 3.4\n'] })
- expect(await m.joinAsWatcher(WATCHER, WATCH)).toEqual(REFUSED)
- expect(spawned).toHaveLength(0)
- const w = await m.joinAsWatcher(WATCHER, WATCH)
- expect(w.unavailable).toBeUndefined()
- expect(spawned).toHaveLength(1)
- expect(versionAsks).toEqual([PROBE_FAILS, 'tmux 3.4\n'])
- // A definite answer IS kept.
- await m.joinAsWatcher(WATCHER + 1, { ...WATCH, persistKey: 'n1', viewerId: 'watch-s2' })
- expect(versionAsks).toHaveLength(2)
- })
-
- it('a definite OLD answer is kept (no re-probe per viewer)', async () => {
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
- const m = await tmuxManager(['nt-n1'], { version: ['tmux 3.1c\n', 'tmux 3.4\n'] })
- expect(await m.joinAsWatcher(WATCHER, WATCH)).toEqual(REFUSED)
- expect(await m.joinAsWatcher(WATCHER, WATCH)).toEqual(REFUSED)
- expect(versionAsks).toEqual(['tmux 3.1c\n'])
- warn.mockRestore()
- })
-
- it('the version is probed once, however many watchers spawn', async () => {
- const m = await tmuxManager(['nt-n1', 'nt-n2'])
- await m.joinAsWatcher(WATCHER, WATCH)
- await m.joinAsWatcher(WATCHER + 1, { ...WATCH, persistKey: 'n2', viewerId: 'watch-s2' })
- expect(spawned).toHaveLength(2)
- expect(versionAsks).toHaveLength(1)
- })
-
- it("a second viewer of the same node shares the first viewer's client instead of opening another", async () => {
- const m = await tmuxManager(['nt-n1'])
- const a = await m.joinAsWatcher(WATCHER, WATCH)
- const b = await m.joinAsWatcher(WATCHER + 1, { ...WATCH, viewerId: 'watch-s2' })
- expect(b.sessionId).toBe(a.sessionId)
- expect(spawned).toHaveLength(1)
- })
-
- it("a watcher client's release never overwrites the owner's released size (a shadow would push it)", async () => {
- const m = await tmuxManager(['nt-n1'])
- const own = await create(OWNER, { cols: 132, rows: 43 })
- kill(OWNER, own.sessionId)
- expect(m.watchSizeFor('n1')).toEqual({ cols: 132, rows: 43 })
- const w = await m.joinAsWatcher(WATCHER, WATCH) // no Session held → its own client, at the window (120x39)
- expect([spawned.at(-1)!.cols, spawned.at(-1)!.rows]).toEqual([120, 39])
- m.kill(WATCHER, w.sessionId, 'watch-s1') // the watcher's own view: its client is released
- expect(spawned.at(-1)!.killed).toBe(true)
- expect(m.watchSizeFor('n1')).toEqual({ cols: 132, rows: 43 })
- })
-
- it("the watcher's client is never the node's Session for anyone else: the owner spawns its own", async () => {
- const m = await tmuxManager(['nt-n1'])
- const w = await m.joinAsWatcher(WATCHER, WATCH)
- const a = await create(OWNER, { cols: 120, rows: 40 })
- expect(a.sessionId).not.toBe(w.sessionId)
- expect(spawned).toHaveLength(2)
- expect(spawned[1].args).toContain('new-session')
- expect(spawned[1].args).toContain('-D')
- })
-
- it("a watcher's client is not a painter: it does not retire the node's background-write clients", async () => {
- const m = await tmuxManager(['nt-n1'])
- const shadow = vi.spyOn(m as unknown as { shadowDispose: (k: string) => void }, 'shadowDispose')
- const shared = vi.spyOn(m as unknown as { sharedDisposeOn: (k: string) => void }, 'sharedDisposeOn')
- await m.joinAsWatcher(WATCHER, WATCH)
- expect(shadow).not.toHaveBeenCalled()
- expect(shared).not.toHaveBeenCalled()
- // Control: an owner's painter does retire them.
- await create(OWNER, { cols: 120, rows: 40 })
- expect(shadow).toHaveBeenCalledWith('n1')
- })
-
- it("a background write never goes into the watcher's read-only client", async () => {
- const m = await tmuxManager(['nt-n1'])
- await m.joinAsWatcher(WATCHER, WATCH)
- await m.backgroundWrite('n1', 'echo hi\r')
- expect(spawned[0].writes).toEqual([])
- })
-
- it('forwards only the named fields — nothing else a caller passes reaches create()', async () => {
- const m = await tmuxManager(['nt-n1'])
- const spy = vi.spyOn(m as unknown as { create: (...a: unknown[]) => Promise<unknown> }, 'create')
- await m.joinAsWatcher(WATCHER, { ...WATCH, shell: 'sh', agentId: 'claude', accountId: 'a1' } as never)
- const passed = spy.mock.calls[0][1] as Record<string, unknown>
- expect(Object.keys(passed).sort()).toEqual(['cols', 'joinOnly', 'persistKey', 'rows', 'sizeVote', 'viewerId'])
- expect(passed.joinOnly).toBe(true)
- expect(passed.sizeVote).toBe(false)
- })
-})
-
-describe('joinAsWatcher over SSH', () => {
- const SSH_REMOTE = { controlPath: '/tmp/nt-test-cm', conn: { host: 'h', user: 'u' }, remoteCwd: '/srv/app' }
-
- async function sshManager(verdict: 'present' | 'absent' | 'unknown') {
- const m = await tmuxManager([])
- vi.spyOn(
- m as unknown as { remoteSessionVerdict: () => Promise<string> },
- 'remoteSessionVerdict'
- ).mockResolvedValue(verdict)
- return m
- }
-
- it('spawns a tty-allocating ssh child that ATTACHES with the watcher flags, no local version probe', async () => {
- const m = await sshManager('present')
- const w = await m.joinAsWatcher(WATCHER, { ...WATCH, sshRemote: SSH_REMOTE })
- expect(w.unavailable).toBeUndefined()
- expect(spawned).toHaveLength(1)
- expect(spawned[0].file).toBe('/usr/bin/ssh')
- expect(spawned[0].args[0]).toBe('-t')
- const remote = spawned[0].args.at(-1)!
- expect(remote).toContain("attach-session -E -f 'ignore-size,read-only' -t '=nt-n1:'")
- expect(remote).not.toContain('new-session')
- expect(versionAsks).toEqual([])
- })
-
- it('a remote window size that cannot be read: refused, nothing spawned', async () => {
- const m = await sshManager('present')
- ;(m as unknown as { readWindowSize: ReturnType<typeof vi.fn> }).readWindowSize.mockResolvedValue(undefined)
- expect(await m.joinAsWatcher(WATCHER, { ...WATCH, sshRemote: SSH_REMOTE })).toEqual(REFUSED)
- expect(spawned).toHaveLength(0)
- })
-
- it('a remote session the host says is gone: refused, nothing spawned', async () => {
- const m = await sshManager('absent')
- expect(await m.joinAsWatcher(WATCHER, { ...WATCH, sshRemote: SSH_REMOTE })).toEqual(REFUSED)
- expect(spawned).toHaveLength(0)
- })
-
- it('a remote node with no ssh binary is NEVER watched through the local tmux', async () => {
- ssh.path = null
- const m = await sshManager('present')
- const w = await m.joinAsWatcher(WATCHER, { ...WATCH, sshRemote: SSH_REMOTE })
- expect(w.sessionId).toBe('')
- expect(w.unavailable).toBe('ssh')
- expect(spawned).toHaveLength(0)
- })
-})
-
-describe('spawnRefusal with no ssh binary (Windows without the OpenSSH Client feature)', () => {
- const SSH_REMOTE = { controlPath: '/tmp/nt-test-cm', conn: { host: 'h', user: 'u' }, remoteCwd: '/srv/app' }
- const opts = { cols: 80, rows: 24, persistKey: 'n-native', sshRemote: SSH_REMOTE, requireRemote: true } as PtyCreateOptions
- afterEach(() => vi.unstubAllEnvs())
-
- it('refused as ssh where ssh is a process; served where the native transport carries it', async () => {
- ssh.path = null
- const m = await manager()
- const refusal = (o: PtyCreateOptions): string | undefined =>
- (m as unknown as { spawnRefusal(o: PtyCreateOptions): string | undefined }).spawnRefusal(o)
- vi.stubEnv('NODETERM_NATIVE_SSH', '0')
- expect(refusal(opts)).toBe('ssh')
- // The `ssh` sentinel every runner routes to NativeMux: nothing is spawned from it.
- vi.stubEnv('NODETERM_NATIVE_SSH', '1')
- expect(refusal(opts)).toBeUndefined()
- })
-})
-
-describe('joinAsWatcher (continued)', () => {
- it('the join-only, non-voting rules are FORCED — a caller cannot turn them off', async () => {
- const m = await manager()
- const smuggled = { ...WATCH, joinOnly: false, sizeVote: true } as never
- expect(await m.joinAsWatcher(WATCHER, smuggled)).toEqual(REFUSED)
- expect(spawned).toHaveLength(0)
-
- await create(OWNER, { cols: 120, rows: 40 })
- await m.joinAsWatcher(WATCHER, smuggled)
- expect(spawned[0].resizes).toEqual([])
- })
-})
-
-describe('syncWatcherClientSize', () => {
- type Read = ReturnType<typeof vi.fn>
- const readOf = (m: object): Read => (m as unknown as { readWindowSize: Read }).readWindowSize
- const sessionOf = (m: object, id: string) =>
- (m as unknown as { sessions: Map<string, { sizes: Map<unknown, unknown>; appliedSize?: unknown }> }).sessions.get(id)!
-
- it("resizes the watcher's OWN client to exactly the window size read now, and tells its viewers", async () => {
- const m = await tmuxManager(['nt-n1'])
- const w = await m.joinAsWatcher(WATCHER, WATCH) // spawned at the window, 120x39
- readOf(m).mockResolvedValue({ cols: 200, rows: 50 }) // the owner (elsewhere) resized the window
- fake.sent.length = 0
- expect(await m.syncWatcherClientSize(w.sessionId)).toBe(true)
- expect(spawned[0].resizes).toEqual([{ cols: 200, rows: 50 }])
- const sizes = fake.sent.filter((x) => x.channel === IPC.ptySize(w.sessionId))
- expect(sizes.map((x) => x.to)).toEqual([WATCHER])
- expect(sizes[0].args[0]).toEqual({ cols: 200, rows: 50 })
- })
-
- it('is never a size vote, and never a viewer-supplied size', async () => {
- const m = await tmuxManager(['nt-n1'])
- const w = await m.joinAsWatcher(WATCHER, WATCH)
- await m.joinAsWatcher(WATCHER + 1, { persistKey: 'n1', viewerId: 'watch-s2', cols: 33, rows: 7 })
- readOf(m).mockResolvedValue({ cols: 200, rows: 50 })
- await m.syncWatcherClientSize(w.sessionId)
- expect(spawned[0].resizes).toEqual([{ cols: 200, rows: 50 }])
- expect(sessionOf(m, w.sessionId).sizes.size).toBe(0)
- })
-
- it('an unchanged window resizes nothing (a full redraw is not free)', async () => {
- const m = await tmuxManager(['nt-n1'])
- const w = await m.joinAsWatcher(WATCHER, WATCH)
- expect(await m.syncWatcherClientSize(w.sessionId)).toBe(true)
- expect(spawned[0].resizes).toEqual([])
- })
-
- it('an unreadable size changes nothing', async () => {
- const m = await tmuxManager(['nt-n1'])
- const w = await m.joinAsWatcher(WATCHER, WATCH)
- readOf(m).mockResolvedValue(undefined)
- expect(await m.syncWatcherClientSize(w.sessionId)).toBe(false)
- expect(spawned[0].resizes).toEqual([])
- })
-
- it("never touches a session that is not a watcher's own client (the owner's pty is never resized)", async () => {
- const m = await tmuxManager(['nt-n1'])
- const own = await create(OWNER, { cols: 120, rows: 40 })
- await m.joinAsWatcher(WATCHER, WATCH) // co-attaches to the owner's Session
- readOf(m).mockClear()
- readOf(m).mockResolvedValue({ cols: 200, rows: 50 })
- expect(await m.syncWatcherClientSize(own.sessionId)).toBe(false)
- expect(readOf(m)).not.toHaveBeenCalled()
- expect(spawned[0].resizes).toEqual([])
- expect(await m.syncWatcherClientSize('no-such-session')).toBe(false)
- })
-
- it('a client that went away during the read is left alone', async () => {
- const m = await tmuxManager(['nt-n1'])
- const w = await m.joinAsWatcher(WATCHER, WATCH)
- let answer: (v: unknown) => void = () => {}
- readOf(m).mockImplementation(() => new Promise((r) => (answer = r)))
- const pending = m.syncWatcherClientSize(w.sessionId)
- m.kill(WATCHER, w.sessionId, 'watch-s1')
- answer({ cols: 200, rows: 50 })
- expect(await pending).toBe(false)
- expect(spawned[0].resizes).toEqual([])
- })
-
- // Controller ruling R24: the link host syncs on every keyframe AND on a 10 s timer, and two links can
- // watch one node, so calls overlap. Two reads racing each other could land out of order and leave the
- // client at the OLDER size. So one read is in flight per session, and callers that arrive meanwhile
- // share ONE queued rerun, which reads after it (the latest read is applied last).
- it('serializes per session: one read in flight, callers meanwhile share ONE rerun, the later read applied last', async () => {
- const m = await tmuxManager(['nt-n1'])
- const w = await m.joinAsWatcher(WATCHER, WATCH) // spawned at the window, 120x39
- const answers: Array<(v: unknown) => void> = []
- readOf(m).mockClear()
- readOf(m).mockImplementation(() => new Promise((r) => answers.push(r)))
- const first = m.syncWatcherClientSize(w.sessionId)
- const second = m.syncWatcherClientSize(w.sessionId)
- const third = m.syncWatcherClientSize(w.sessionId)
- expect(second).toBe(third) // one queued rerun, shared
- await vi.advanceTimersByTimeAsync(0)
- expect(readOf(m)).toHaveBeenCalledTimes(1) // nothing reads beside the one in flight
- answers[0]({ cols: 100, rows: 30 })
- expect(await first).toBe(true)
- await vi.advanceTimersByTimeAsync(0)
- expect(readOf(m)).toHaveBeenCalledTimes(2) // the rerun reads only once the first settled
- answers[1]({ cols: 200, rows: 50 })
- expect(await second).toBe(true)
- expect(spawned[0].resizes).toEqual([{ cols: 100, rows: 30 }, { cols: 200, rows: 50 }])
- // Settled: the next call starts a fresh read at once.
- readOf(m).mockResolvedValue({ cols: 200, rows: 50 })
- expect(await m.syncWatcherClientSize(w.sessionId)).toBe(true)
- expect(readOf(m)).toHaveBeenCalledTimes(3)
- })
-
- it('serialization is per session: another session reads at the same time', async () => {
- const m = await tmuxManager(['nt-n1', 'nt-n2'])
- const a = await m.joinAsWatcher(WATCHER, WATCH)
- const b = await m.joinAsWatcher(WATCHER, { persistKey: 'n2', viewerId: 'watch-s2' })
- readOf(m).mockClear()
- readOf(m).mockImplementation(() => new Promise(() => {}))
- void m.syncWatcherClientSize(a.sessionId)
- void m.syncWatcherClientSize(b.sessionId)
- await vi.advanceTimersByTimeAsync(0)
- expect(readOf(m).mock.calls.map((c) => c[0])).toEqual(['n1', 'n2'])
- })
-
- it('a read that throws settles the slot: the next call reads again', async () => {
- const m = await tmuxManager(['nt-n1'])
- const w = await m.joinAsWatcher(WATCHER, WATCH)
- readOf(m).mockRejectedValueOnce(new Error('boom'))
- expect(await m.syncWatcherClientSize(w.sessionId)).toBe(false)
- readOf(m).mockResolvedValue({ cols: 130, rows: 40 })
- expect(await m.syncWatcherClientSize(w.sessionId)).toBe(true)
- expect(spawned[0].resizes).toEqual([{ cols: 130, rows: 40 }])
- })
-
- it('an SSH watcher client is synced from the HOST read', async () => {
- const m = await tmuxManager([])
- vi.spyOn(
- m as unknown as { remoteSessionVerdict: () => Promise<string> },
- 'remoteSessionVerdict'
- ).mockResolvedValue('present')
- const SSH_REMOTE = { controlPath: '/tmp/nt-test-cm', conn: { host: 'h', user: 'u' }, remoteCwd: '/srv/app' }
- const w = await m.joinAsWatcher(WATCHER, { ...WATCH, sshRemote: SSH_REMOTE })
- readOf(m).mockClear()
- readOf(m).mockResolvedValue({ cols: 210, rows: 55 })
- expect(await m.syncWatcherClientSize(w.sessionId)).toBe(true)
- expect(readOf(m)).toHaveBeenCalledWith('n1', expect.objectContaining({ controlPath: '/tmp/nt-test-cm' }))
- expect(spawned[0].resizes).toEqual([{ cols: 210, rows: 55 }])
- })
-})
-
-// Controller ruling R25: the size a live link's `watch:meta` reports is the JOINED session's current
-// size. For a watcher's own client that is the size it runs at (the window's, read at spawn and kept by
-// the sync) — `watchSizeFor` cannot see that client (it is invisible to every persistKey lookup) and
-// would answer a stale released size or nothing.
-describe('sessionSize', () => {
- it("is the owner's pty size for a co-attached watcher, and follows the owner's resize", async () => {
- const m = await manager()
- const own = await create(OWNER, { cols: 120, rows: 40 })
- const w = await m.joinAsWatcher(WATCHER, WATCH)
- expect(w.sessionId).toBe(own.sessionId)
- expect(m.sessionSize(w.sessionId)).toEqual({ cols: 120, rows: 40 })
- fake.senderListeners[IPC.ptyResize](OWNER, own.sessionId, 100, 30)
- expect(m.sessionSize(w.sessionId)).toEqual({ cols: 100, rows: 30 })
- })
-
- it("is a watcher's OWN client's size — the window's, read at spawn and kept by the sync", async () => {
- const m = await tmuxManager(['nt-n1'])
- const w = await m.joinAsWatcher(WATCHER, WATCH) // caller said 40x10; spawned at the window, 120x39
- expect(m.sessionSize(w.sessionId)).toEqual({ cols: 120, rows: 39 })
- expect(m.watchSizeFor('n1')).toBeUndefined() // what the old wiring would have reported: nothing
- ;(m as unknown as { readWindowSize: ReturnType<typeof vi.fn> }).readWindowSize.mockResolvedValue({ cols: 200, rows: 50 })
- await m.syncWatcherClientSize(w.sessionId)
- expect(m.sessionSize(w.sessionId)).toEqual({ cols: 200, rows: 50 })
- })
-
- it('is null for a session this manager does not know', async () => {
- const m = await manager()
- expect(m.sessionSize('no-such-session')).toBeNull()
- })
-
- it('hands back a copy, not the live size record', async () => {
- const m = await manager()
- const own = await create(OWNER, { cols: 120, rows: 40 })
- const size = m.sessionSize(own.sessionId)!
- size.cols = 1
- expect(m.sessionSize(own.sessionId)).toEqual({ cols: 120, rows: 40 })
- })
-})
-
-// Controller ruling R38: a live link asks "is the session I joined still there?" after the join and
-// after every capture (an exit can race either — R30). An explicit accessor, not `nodeOfSession(sid)
-// !== undefined`, which would lean on every watched session having been created with a persistKey.
-describe('hasSession', () => {
- it('is true for a live session, owner or watcher, and false once it ended', async () => {
- const m = await manager()
- const own = await create(OWNER, { cols: 120, rows: 40 })
- const w = await m.joinAsWatcher(WATCHER, WATCH)
- expect(m.hasSession(own.sessionId)).toBe(true)
- expect(m.hasSession(w.sessionId)).toBe(true)
- spawned[spawned.length - 1].onExitCb!({ exitCode: 0 })
- expect(m.hasSession(own.sessionId)).toBe(false)
- })
-
- it('is false for a session this manager never created', async () => {
- const m = await manager()
- expect(m.hasSession('no-such-session')).toBe(false)
- expect(m.hasSession('')).toBe(false)
- })
-})
-
-describe('watchSizeFor', () => {
- it('is the size the live pty runs at, whatever the watcher reported', async () => {
- const m = await manager()
- await create(OWNER, { cols: 120, rows: 40 })
- await m.joinAsWatcher(WATCHER, WATCH)
- expect(m.watchSizeFor('n1')).toEqual({ cols: 120, rows: 40 })
- })
-
- it('follows the pty when the owner resizes it', async () => {
- const m = await manager()
- const { sessionId } = await create(OWNER, { cols: 120, rows: 40 })
- fake.senderListeners[IPC.ptyResize](OWNER, sessionId, 100, 30)
- expect(m.watchSizeFor('n1')).toEqual({ cols: 100, rows: 30 })
- })
-
- it('is the size the pty had when its last client was released', async () => {
- const m = await tmuxManager(['nt-n1'])
- const { sessionId } = await create(OWNER, { cols: 132, rows: 43 })
- kill(OWNER, sessionId)
- expect(spawned[0].killed).toBe(true)
- expect(m.watchSizeFor('n1')).toEqual({ cols: 132, rows: 43 })
- })
-
- it('is undefined for a node this process never ran', async () => {
- const m = await manager()
- expect(m.watchSizeFor('n1')).toBeUndefined()
- })
-
- it('hands back a copy, not the live size record', async () => {
- const m = await manager()
- await create(OWNER, { cols: 120, rows: 40 })
- const size = m.watchSizeFor('n1')!
- size.cols = 1
- expect(m.watchSizeFor('n1')).toEqual({ cols: 120, rows: 40 })
- })
-})
diff --git a/src/core/pty-zellij-fold.test.ts b/src/core/pty-zellij-fold.test.ts
index 4d45617e0..7fbe61016 100644
--- a/src/core/pty-zellij-fold.test.ts
+++ b/src/core/pty-zellij-fold.test.ts
@@ -129,27 +129,3 @@ describe('a socket path Zellij would refuse falls back to tmux', () => {
expect(m.tmuxStatus().zellij).toMatchObject({ selected: true, socketTooLong: true })
})
})
-
-describe('a live link watcher never spawns into a Zellij session', () => {
- it('a live Zellij node with no held session: the watcher is refused before any tmux probe', async () => {
- // A watcher's own client is a read-only TMUX client; for a Zellij node the only honest answer
- // is "not now" — never a Zellij attach, which would be a full, typing client.
- const file = path.join(dir, 'zellij-live')
- fs.writeFileSync(
- file,
- `#!/bin/sh\necho "$@" >> '${log}'\n` +
- 'case "$1" in list-sessions) echo "nt-w1 [Created 1s ago]"; exit 0;; esac\n' +
- 'case "$*" in *list-panes*) echo \'[{"id":0,"is_plugin":false,"is_focused":true}]\'; exit 0;; esac\n' +
- 'exit 0\n',
- { mode: 0o755 }
- )
- const m = await manager(file, { sessionBackend: 'zellij' })
- vi.spyOn(m as unknown as { strictTmuxVerdict: () => Promise<string> }, 'strictTmuxVerdict').mockResolvedValue('absent')
- const readWindowSize = vi.spyOn(m, 'readWindowSize')
- const r = await m.joinAsWatcher(1 as never, { persistKey: 'w1', viewerId: 'v1', cols: 80, rows: 24 })
- expect(r).toMatchObject({ sessionId: '', unavailable: 'join-only' })
- expect(readWindowSize).not.toHaveBeenCalled()
- expect(h.spawns).toHaveLength(0)
- expect(calls()).not.toMatch(/attach/)
- })
-})
diff --git a/src/core/relay/relay-trust.ts b/src/core/relay/relay-trust.ts
index 3ee083ade..3ba4e12e4 100644
--- a/src/core/relay/relay-trust.ts
+++ b/src/core/relay/relay-trust.ts
@@ -26,17 +26,15 @@
// its own `onTunnel` — so a confirm arriving on session A's tunnel is physically unable to reach
// session B's state, and `recordApproval` can only ever pin the key bound into the state it is given.
//
-// LOCAL confirms have exactly six call sites, four on the HOST side and two on the CLIENT side.
+// LOCAL confirms have exactly five call sites, three on the HOST side and two on the CLIENT side.
// Host side: `confirmHere()` from the desktop's Team Access dialog (`relay:host:confirm`), the host's
-// `autoApprove` for a key its pin store holds (the hosted team's `team.json`), a hosted owner's
-// `relay:hosted:approve`, and a live link's `autoApprove` for the ONE viewer key derived from that
-// link's own secret, read from the host's own link record (src/core/watch-link/link-host.ts; any
-// other key is denied at once, never asked). Client side: the joining human's
+// `autoApprove` for a key its pin store holds (the hosted team's `team.json`), and a hosted owner's
+// `relay:hosted:approve`. Client side: the joining human's
// `relay:client:confirm`, and the client's `autoApprove` for a hosted team's approved bookmark
// (src/main/remote/hosted-join.ts). That auto-confirm reads the bookmark's `approvedAt` alone
// (`source` is a label). Share with team's `seedBookmark` sets it without a SAS comparison; that is
// not a new confirm site, because the code it is given came back from `team bootstrap` over an
-// authenticated ssh channel. A seventh is a design change.
+// authenticated ssh channel. A sixth is a design change.
import {
confirmLocal,
confirmRemote,
diff --git a/src/core/relay/scoped-guest-policy.test.ts b/src/core/relay/scoped-guest-policy.test.ts
index 802a4fff6..5b3333511 100644
--- a/src/core/relay/scoped-guest-policy.test.ts
+++ b/src/core/relay/scoped-guest-policy.test.ts
@@ -488,31 +488,6 @@ describe('relay host — host-only channels refused to every peer', () => {
await vi.waitFor(() => expect(t.dispatched.map((r) => r.method)).toEqual([IPC.workspaceLoad]))
expect(t.casts).toEqual([])
})
- // Live links: an editor (or an unscoped Team Access seat) passes every access check, so the host-only
- // prefix is the one thing between a peer and publishing a host terminal with the host's Pro — and the
- // list answer carries every link's secret. Refused BEFORE any policy runs, whatever the hooks say.
- for (const [label, hooks] of [['no policy hooks (full access)', undefined], ['policy hooks', 'scoped']] as const) {
- it(`refuses every watchLink channel, request and cast, with ${label}`, async () => {
- const t = openHost(hooks === 'scoped' ? scopedGuestHooks('alpha', deps()) : undefined)
- await vi.waitFor(() => expect(t.opened.length).toBe(2))
- const methods = (Object.values(IPC) as unknown[]).filter(
- (v): v is string => typeof v === 'string' && v.startsWith('watchLink:')
- )
- expect(methods).toHaveLength(14)
- // The Control link's owner verbs are among them, by name: a peer must never set a link's
- // password, turn its typing on, clear its lock, or probe a terminal for it.
- for (const ch of [IPC.watchLinkSetControl, IPC.watchLinkSetPassword, IPC.watchLinkAllowControl, IPC.watchLinkControlSupport]) {
- expect(methods, ch).toContain(ch)
- }
- methods.forEach((method, i) =>
- t.client.send(JSON.stringify({ t: 'req', id: 200 + i, method, args: [{ nodeId: 'a1', role: 'viewer', ttlSeconds: 3600, label: 'x' }] }))
- )
- for (const method of methods) t.client.send(JSON.stringify({ t: 'cast', method, args: [] }))
- await vi.waitFor(() => expect(t.frames.filter((f) => f.includes('E_FORBIDDEN')).length).toBe(methods.length))
- expect(t.dispatched).toEqual([])
- expect(t.casts).toEqual([])
- })
- }
it('still lets a hosted team\'s own verbs through to their interceptor', async () => {
const t = openHost()
await vi.waitFor(() => expect(t.opened.length).toBe(2))
diff --git a/src/core/remote-ssh/control-master.test.ts b/src/core/remote-ssh/control-master.test.ts
index 898f86efb..ff51fd66c 100644
--- a/src/core/remote-ssh/control-master.test.ts
+++ b/src/core/remote-ssh/control-master.test.ts
@@ -9,8 +9,6 @@ import {
probeSaysAbsent,
remoteCapturePaneArgs,
remoteCaptureVisibleArgs,
- remoteTmuxWatcherArgs,
- remoteWindowSizeArgs,
remotePaneCommandArgs,
remotePaneCwdArgs,
remotePaneProcessArgs,
@@ -290,34 +288,6 @@ describe('remoteCaptureVisibleArgs', () => {
})
})
-describe('remoteTmuxWatcherArgs', () => {
- it('a tty-allocating child that ATTACHES read-only and ignore-size, never creates', () => {
- const args = remoteTmuxWatcherArgs(conn, '/s.sock', 'nt-x')
- expect(args[0]).toBe('-t')
- expect(args.slice(1, 1 + childPrefix.length)).toEqual(childPrefix)
- expect(args[args.length - 1]).toBe(
- `${TP}tmux -L ${RMT_TMUX_SOCKET} attach-session -E -f 'ignore-size,read-only' -t '=nt-x:'`
- )
- })
-
- it('has no create path and no plain-shell fallback — a watcher never gets a shell', () => {
- const cmd = remoteTmuxWatcherArgs(conn, '/s.sock', 'nt-x').at(-1)!
- expect(cmd).not.toContain('new-session')
- expect(cmd).not.toContain('SHELL')
- expect(cmd).not.toContain('exec')
- })
-})
-
-describe('remoteWindowSizeArgs', () => {
- it('reads the window size of exactly this session on the host', () => {
- const args = remoteWindowSizeArgs(conn, '/s.sock', 'nt-x')
- expect(args.slice(0, childPrefix.length)).toEqual(childPrefix)
- expect(args[args.length - 1]).toBe(
- `${TP}tmux -L ${RMT_TMUX_SOCKET} display-message -p -t '=nt-x:' '#{window_width} #{window_height} #{status}'`
- )
- })
-})
-
describe('remotePaneCommandArgs', () => {
it('asks the remote tmux for the pane_current_command of the session', () => {
const args = remotePaneCommandArgs(conn, '/s.sock', 'nt-x')
diff --git a/src/core/remote-ssh/control-master.ts b/src/core/remote-ssh/control-master.ts
index f02224035..f1ac0ab1e 100644
--- a/src/core/remote-ssh/control-master.ts
+++ b/src/core/remote-ssh/control-master.ts
@@ -23,7 +23,6 @@ import { typedInputScript } from '../typed-input'
import { canControlCanvas } from '../../shared/agents/config'
import { COMBINED_PANE_MARKER, PANE_OWNER_FMT, PS_FOREGROUND_FLAGS } from '../agents/pane-owner'
import { VISIBLE_CAPTURE_FORMAT, capturePaneTarget } from '../capture-route'
-import { WATCHER_CLIENT_FLAGS, WINDOW_SIZE_FORMAT } from '../watch-link/watcher-client'
// Dependency-free (no node-pty): safe to import from these pure builders.
/**
@@ -58,8 +57,8 @@ export const LEGACY_RMT_TMUX_SOCKET = 'nodeterm-rmt'
* `command not found` on any host whose ssh exec-channel PATH misses the install dir — most
* visibly macOS with Homebrew's tmux in `/opt/homebrew/bin`. The prologue is one assignment, so
* the command's own exit code (what `probeSaysAbsent` and every caller reads) is unchanged.
- * Exported for the live link's pane-input builders (`pane-input.ts`), which build their
- * remote commands beside their local twins rather than here.
+ * Exported for the pane-input builders (`pane-input.ts`), which build their remote commands beside
+ * their local twins rather than here.
*/
export function tmuxCmd(body: string): string {
return `${remoteTmuxPathPrologue()}${body}`
@@ -578,8 +577,8 @@ export function remoteCapturePaneArgs(conn: SshConnection, controlPath: string,
)
}
/**
- * The VISIBLE screen of a remote session, with SGR, and nothing above it — a live link's keyframe
- * must never carry history, and `remoteCapturePaneArgs` always adds `-S`. The cursor line rides the
+ * The VISIBLE screen of a remote session, with SGR, and nothing above it — the phone's resume
+ * repaint must never carry history, and `remoteCapturePaneArgs` always adds `-S`. The cursor line rides the
* SAME tmux invocation (see `capture-route.ts` for why, and for the measured exact-target
* spelling). Every piece that the REMOTE shell would otherwise read is single-quoted: tmux's `;`
* separator (bare, it would end the tmux command and run `display-message` as a shell command), the
@@ -596,42 +595,6 @@ export function remoteCaptureVisibleArgs(conn: SshConnection, controlPath: strin
)
)
}
-/**
- * A live link watcher's OWN client on the host, for a node no Session is held for: a tty-allocating
- * ssh child (`-t`, like `remoteTmuxPtyArgs`) running `attach-session -E -f ignore-size,read-only` on
- * the exact target — never creating, never touching the session env, and out of the window's sizing
- * while an unflagged client is attached anywhere on the server (tmux honours `ignore-size` only then;
- * the caller spawns it at the window's current size and keeps it synced — `watch-link/watcher-client.ts`). Deliberately NOT wrapped like the owner's
- * interactive command: a host without tmux gets a failed command, never a plain login shell — a
- * watcher must not get a shell. An old remote tmux (< 3.2) rejects `-f` with a usage error: the
- * command fails and nothing attaches. Proven under a real /bin/sh in watcher-attach.realsh.test.ts
- * and on a real tty in watcher-client.realtty.test.ts.
- */
-export function remoteTmuxWatcherArgs(conn: SshConnection, controlPath: string, sessionId: string): string[] {
- return [
- '-t',
- ...childArgs(
- conn,
- controlPath,
- tmuxCmd(
- `tmux -L ${RMT_TMUX_SOCKET} attach-session -E -f ${posixQuote(WATCHER_CLIENT_FLAGS)} ` +
- `-t ${posixQuote(capturePaneTarget(sessionId))}`
- )
- )
- ]
-}
-
-/** The REMOTE window size of exactly this session, so a watcher's client is spawned at it. */
-export function remoteWindowSizeArgs(conn: SshConnection, controlPath: string, sessionId: string): string[] {
- return childArgs(
- conn,
- controlPath,
- tmuxCmd(
- `tmux -L ${RMT_TMUX_SOCKET} display-message -p -t ${posixQuote(capturePaneTarget(sessionId))} ` +
- posixQuote(WINDOW_SIZE_FORMAT)
- )
- )
-}
/**
* Ask the REMOTE tmux when a node's session was created, AND what the host's clock says now — in
* one round trip, because the caller wants an AGE and the two clocks are not the same clock.
diff --git a/src/core/remote-ssh/native/native-pty-argv.guard.test.ts b/src/core/remote-ssh/native/native-pty-argv.guard.test.ts
index cf97ac8f8..538c63f0e 100644
--- a/src/core/remote-ssh/native/native-pty-argv.guard.test.ts
+++ b/src/core/remote-ssh/native/native-pty-argv.guard.test.ts
@@ -21,6 +21,6 @@ describe('pty-manager: the native ssh pty argv', () => {
it('assigns nativeSshArgv only from the remote-tmux builders', () => {
const writes = [...src.matchAll(/\bnativeSshArgv\s*=(?!=)\s*([A-Za-z_][\w]*)/g)].map((m) => m[1])
expect(writes.length).toBeGreaterThan(0)
- for (const w of writes) expect(['null', 'remoteTmuxWatcherArgs', 'remoteTmuxPtyArgs']).toContain(w)
+ for (const w of writes) expect(['null', 'remoteTmuxPtyArgs']).toContain(w)
})
})
diff --git a/src/core/remote-ssh/watcher-attach.realsh.test.ts b/src/core/remote-ssh/watcher-attach.realsh.test.ts
deleted file mode 100644
index 3423e877d..000000000
--- a/src/core/remote-ssh/watcher-attach.realsh.test.ts
+++ /dev/null
@@ -1,155 +0,0 @@
-// A live link watcher's REMOTE tmux client, and the remote window-size read, executed by a real
-// /bin/sh — the remote shell is what reads these lines.
-//
-// What only execution can prove:
-// - the client flags (`-f ignore-size,read-only`) and the exact target reach tmux as their own argv
-// elements;
-// - an OLD remote tmux that rejects the flags (< 3.2) ends the command with a failure and nothing
-// else: no retry with other flags, no create, and above all NO plain-shell fallback (the owner's
-// interactive command execs a login shell when tmux is missing; a watcher must never get one);
-// - the window-size read answers through a real tmux, and an exact-target miss answers nothing.
-// Private socket in a private TMUX_TMPDIR; the delegating stub re-points `-L nodeterm-rmt` at it.
-import { describe, expect, it, beforeAll, afterAll } from 'vitest'
-import { execFileSync } from 'child_process'
-import fs from 'fs'
-import path from 'path'
-import { remoteTmuxWatcherArgs, remoteWindowSizeArgs, RMT_TMUX_SOCKET } from './control-master'
-import { WINDOW_SIZE_FORMAT, parseWindowSize } from '../watch-link/watcher-client'
-import { testTmpDir } from '../test-tmp'
-import { makeTmuxTmpdir } from '../tmux-test-socket'
-
-const conn = { host: 'h.example.com', user: 'deploy', port: 2222, identityFile: '/k/id' }
-const SOCKET = `nt-wlwa-${process.pid}`
-const REAL_TMUX = (() => {
- if (process.platform === 'win32') return null
- try {
- return execFileSync('/bin/sh', ['-c', 'command -v tmux'], { encoding: 'utf8' }).trim() || null
- } catch {
- return null
- }
-})()
-
-let root: string
-let recordDir: string
-let oldDir: string
-let emptyDir: string
-let delegateDir: string
-let markerDir: string
-let tmuxTmp = ''
-
-const watcherLine = (id: string): string => remoteTmuxWatcherArgs(conn, '/cm/p1', id).at(-1)!
-const sizeLine = (id: string): string => remoteWindowSizeArgs(conn, '/cm/p1', id).at(-1)!
-
-function runUnder(binDir: string, line: string): { status: number; stdout: string; stderr: string } {
- try {
- const stdout = execFileSync('/bin/sh', ['-c', line], {
- env: {
- PATH: binDir,
- HOME: '/home/u',
- // A watcher that fell back to a shell would exec $SHELL: make that a canary.
- SHELL: path.join(root, 'shell-canary'),
- ...(tmuxTmp ? { TMUX_TMPDIR: tmuxTmp } : {})
- },
- encoding: 'utf8',
- stdio: ['ignore', 'pipe', 'pipe']
- })
- return { status: 0, stdout, stderr: '' }
- } catch (e) {
- const err = e as { status?: number; stdout?: string; stderr?: string }
- return { status: err.status ?? -1, stdout: String(err.stdout ?? ''), stderr: String(err.stderr ?? '') }
- }
-}
-
-const markers = (): string[] => fs.readdirSync(markerDir).sort()
-
-beforeAll(() => {
- root = testTmpDir('ntwas-')
- recordDir = path.join(root, 'record')
- oldDir = path.join(root, 'old')
- emptyDir = path.join(root, 'empty')
- delegateDir = path.join(root, 'delegate')
- markerDir = path.join(root, 'markers')
- for (const d of [recordDir, oldDir, emptyDir, delegateDir, markerDir]) fs.mkdirSync(d)
- fs.writeFileSync(path.join(root, 'shell-canary'), `#!/bin/sh\n: > '${markerDir}/shell'\n`, { mode: 0o755 })
- fs.writeFileSync(path.join(recordDir, 'tmux'), `#!/bin/sh\nfor a in "$@"; do printf '%s\\0' "$a"; done\n`, {
- mode: 0o755
- })
- // tmux 3.1c's own answer to `attach-session -f …`: a usage line and exit 1. Every call is counted.
- fs.writeFileSync(
- path.join(oldDir, 'tmux'),
- `#!/bin/sh\n: > "${markerDir}/old-tmux-$$"\necho 'usage: attach-session [-dErx] [-c working-directory] [-t target-session]' >&2\nexit 1\n`,
- { mode: 0o755 }
- )
- if (!REAL_TMUX) return
- tmuxTmp = makeTmuxTmpdir('ntwa-', SOCKET)
- fs.writeFileSync(
- path.join(delegateDir, 'tmux'),
- `#!/bin/sh\n[ "$1" = "-L" ] && [ "$2" = "${RMT_TMUX_SOCKET}" ] || exit 99\nshift 2\nexec '${REAL_TMUX}' -L '${SOCKET}' "$@"\n`,
- { mode: 0o755 }
- )
- execFileSync(REAL_TMUX, ['-L', SOCKET, '-f', '/dev/null', 'new-session', '-d', '-s', 'nt-w-12', '-x', '100', '-y', '30', 'sleep 60'], {
- env: { ...process.env, TMUX_TMPDIR: tmuxTmp },
- stdio: 'ignore'
- })
-})
-
-afterAll(() => {
- if (!REAL_TMUX || !tmuxTmp) return
- try {
- execFileSync(REAL_TMUX, ['-L', SOCKET, 'kill-session', '-t', '=nt-w-12'], {
- env: { ...process.env, TMUX_TMPDIR: tmuxTmp },
- stdio: 'ignore'
- })
- } catch {
- /* already gone */
- }
- fs.rmSync(tmuxTmp, { recursive: true, force: true })
-})
-
-describe('remoteTmuxWatcherArgs (real /bin/sh)', () => {
- it('the client flags and the exact target reach the remote tmux as their own argv elements', () => {
- const { status, stdout } = runUnder(recordDir, watcherLine('nt-abc'))
- expect(status).toBe(0)
- const argv = stdout.split('\0')
- expect(argv.pop()).toBe('')
- expect(argv).toEqual(['-L', RMT_TMUX_SOCKET, 'attach-session', '-E', '-f', 'ignore-size,read-only', '-t', '=nt-abc:'])
- })
-
- it('an OLD remote tmux (< 3.2) rejects the flags: the command fails, once, and no shell runs', () => {
- fs.readdirSync(markerDir).forEach((f) => fs.unlinkSync(path.join(markerDir, f)))
- const { status, stderr } = runUnder(oldDir, watcherLine('nt-abc'))
- expect(status).not.toBe(0)
- expect(stderr).toContain('usage: attach-session')
- const calls = markers().filter((m) => m.startsWith('old-tmux-'))
- expect(calls).toHaveLength(1)
- expect(markers()).not.toContain('shell')
- })
-
- it('a host with no tmux at all: the command fails and no shell runs', () => {
- fs.readdirSync(markerDir).forEach((f) => fs.unlinkSync(path.join(markerDir, f)))
- const { status } = runUnder(emptyDir, watcherLine('nt-abc'))
- expect(status).not.toBe(0)
- expect(markers()).toEqual([])
- })
-})
-
-describe('remoteWindowSizeArgs (real /bin/sh)', () => {
- it('the target and the format reach the remote tmux intact', () => {
- const { status, stdout } = runUnder(recordDir, sizeLine('nt-abc'))
- expect(status).toBe(0)
- const argv = stdout.split('\0')
- expect(argv.pop()).toBe('')
- expect(argv).toEqual(['-L', RMT_TMUX_SOCKET, 'display-message', '-p', '-t', '=nt-abc:', WINDOW_SIZE_FORMAT])
- })
-
- it.skipIf(!REAL_TMUX)('end to end through a real tmux: the window size of exactly this session', () => {
- // Skipped without a tmux binary: the proof is tmux's own reply.
- const hit = runUnder(delegateDir, sizeLine('nt-w-12'))
- expect(hit.status).toBe(0)
- // `-f /dev/null` = tmux defaults, status on: the client size for a 100x30 window is 100x31.
- expect(parseWindowSize(hit.stdout)).toEqual({ cols: 100, rows: 31 })
- // A prefix of a live session's name: exit 0 with every format empty — no size, never 12's.
- const miss = runUnder(delegateDir, sizeLine('nt-w-1'))
- expect(parseWindowSize(miss.stdout)).toBeUndefined()
- })
-})
diff --git a/src/core/session-host-backend.ts b/src/core/session-host-backend.ts
index 8cadd130f..11b5cfa27 100644
--- a/src/core/session-host-backend.ts
+++ b/src/core/session-host-backend.ts
@@ -148,7 +148,7 @@ export function attachExistingSessionHostPty(name: string): SessionHostPty {
return new SessionHostPty(getClient(), name, null, 0)
}
-/** A live link / relay viewer's READ-ONLY attachment to an already-running session: never spawns,
+/** A relay viewer's READ-ONLY attachment to an already-running session: never spawns,
* casts no size claim, takes no pause ticket, cannot type. `ready` rejects with
* `SessionHostWatchUnsupportedError` when the running host predates the `watch-attach` feature. */
export function watchExistingSessionHostPty(name: string): SessionHostPty {
@@ -161,13 +161,7 @@ export async function sessionHostSupportsWatch(): Promise<boolean> {
return getClient().supportsFeature('watch-attach')
}
-/** The same answer WITHOUT connecting — undefined while this process has no connection (nothing
- * session-host-backed has been opened yet). Synchronous, for `tmuxStatus`. */
-export function sessionHostWatchKnown(): boolean | undefined {
- return client?.connectedFeature('watch-attach')
-}
-
-/** A live link's keyframe: the visible screen, cursor and active buffer. Null = no capture (an
+/** The visible screen, cursor and active buffer. Null = no capture (an
* older host, a gone session, any failure) — never history in its place. */
export async function sessionHostCaptureVisible(name: string): Promise<CaptureVisibleResult | null> {
return getClient().captureVisible(name)
diff --git a/src/core/session-host-client-live-links.test.ts b/src/core/session-host-client-watch-attach.test.ts
similarity index 99%
rename from src/core/session-host-client-live-links.test.ts
rename to src/core/session-host-client-watch-attach.test.ts
index 27a0f1385..c3ff4ff56 100644
--- a/src/core/session-host-client-live-links.test.ts
+++ b/src/core/session-host-client-watch-attach.test.ts
@@ -1,4 +1,4 @@
-// Live links on the session host, client side: a watcher's attachment (`watch-attach`) carries no
+// The session host's watch-attach, client side: a viewer's attachment (`watch-attach`) carries no
// size claim, no pause ticket and no input; the client up/downgrades its one connection's attachment
// as voting subscribers come and go; and the two negotiated reads (`captureVisible`, `paneCwd`) are
// never sent to a host that did not advertise them. Real client, fake host, real socket.
diff --git a/src/core/session-host-client.ts b/src/core/session-host-client.ts
index ccfb1ee76..30749dd29 100644
--- a/src/core/session-host-client.ts
+++ b/src/core/session-host-client.ts
@@ -208,7 +208,7 @@ type SubscriberEntry = {
spawn?: SessionHostSpawnOptions
scrollback: number
phase: 'attaching' | 'attached'
- /** A `watch-attach` viewer (live link / relay viewer): it never holds a size claim or a pause
+ /** A `watch-attach` viewer (a relay viewer): it never holds a size claim or a pause
* ticket, and its writes are dropped here — the host refuses them too. */
watch?: boolean
}
@@ -1463,7 +1463,7 @@ export class SessionHostClient {
}
/**
- * A live link / relay viewer's READ-ONLY attach (`watch-attach`): never spawns, never claims a size,
+ * A relay viewer's READ-ONLY attach (`watch-attach`): never spawns, never claims a size,
* never pauses, never types. Rejects with `SessionHostWatchUnsupportedError` — before anything is
* registered — when the connected host did not advertise the feature (a long-lived host from an
* older build), so the caller can refuse the viewer instead of casting a size vote for it.
@@ -1925,8 +1925,8 @@ export class SessionHostClient {
return result.text
}
- /** A live link's keyframe (`captureVisible` feature). Null when the host did not advertise the
- * feature (never sent then), the session is gone, or anything failed — a keyframe is an
+ /** The visible screen (`captureVisible` feature). Null when the host did not advertise the
+ * feature (never sent then), the session is gone, or anything failed — a capture is an
* optimisation, and "no capture" must stay distinguishable from an empty screen. */
async captureVisible(name: string): Promise<CaptureVisibleResult | null> {
try {
diff --git a/src/core/watch-link/__fixtures__/xterm-vt500.ts b/src/core/watch-link/__fixtures__/xterm-vt500.ts
deleted file mode 100644
index 1c2d117e7..000000000
--- a/src/core/watch-link/__fixtures__/xterm-vt500.ts
+++ /dev/null
@@ -1,292 +0,0 @@
-// xterm.js 5.5.0's VT500 parser table, for the stream filter's differential test (test-only).
-//
-// The six blocks between the BEGIN/END markers are copied VERBATIM from the installed package:
-// node_modules/@xterm/xterm/src/common/parser/Constants.ts ParserState, ParserAction
-// node_modules/@xterm/xterm/src/common/parser/EscapeSequenceParser.ts TableAccess, TransitionTable,
-// NON_ASCII_PRINTABLE,
-// VT500_TRANSITION_TABLE
-// `stream-filter.xterm.test.ts` compares each block with that source, so an xterm upgrade that
-// changes the table fails there instead of silently testing the filter against an old model.
-// Only the code after the END marker is ours; the lines of `parse()` it models are pinned there too.
-//
-// The copied blocks are xterm.js's, under its MIT license. Its notice, verbatim from the installed
-// package's LICENSE (`stream-filter.xterm.test.ts` checks it against that file):
-//
-// Copyright (c) 2017-2019, The xterm.js authors (https://github.com/xtermjs/xterm.js)
-// Copyright (c) 2014-2016, SourceLair Private Company (https://www.sourcelair.com)
-// Copyright (c) 2012-2013, Christopher Jeffrey (https://github.com/chjj/)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-// ---- BEGIN verbatim xterm 5.5.0 ----
-export const enum ParserState {
- GROUND = 0,
- ESCAPE = 1,
- ESCAPE_INTERMEDIATE = 2,
- CSI_ENTRY = 3,
- CSI_PARAM = 4,
- CSI_INTERMEDIATE = 5,
- CSI_IGNORE = 6,
- SOS_PM_APC_STRING = 7,
- OSC_STRING = 8,
- DCS_ENTRY = 9,
- DCS_PARAM = 10,
- DCS_IGNORE = 11,
- DCS_INTERMEDIATE = 12,
- DCS_PASSTHROUGH = 13
-}
-
-export const enum ParserAction {
- IGNORE = 0,
- ERROR = 1,
- PRINT = 2,
- EXECUTE = 3,
- OSC_START = 4,
- OSC_PUT = 5,
- OSC_END = 6,
- CSI_DISPATCH = 7,
- PARAM = 8,
- COLLECT = 9,
- ESC_DISPATCH = 10,
- CLEAR = 11,
- DCS_HOOK = 12,
- DCS_PUT = 13,
- DCS_UNHOOK = 14
-}
-
-const enum TableAccess {
- TRANSITION_ACTION_SHIFT = 4,
- TRANSITION_STATE_MASK = 15,
- INDEX_STATE_SHIFT = 8
-}
-
-export class TransitionTable {
- public table: Uint8Array;
-
- constructor(length: number) {
- this.table = new Uint8Array(length);
- }
-
- /**
- * Set default transition.
- * @param action default action
- * @param next default next state
- */
- public setDefault(action: ParserAction, next: ParserState): void {
- this.table.fill(action << TableAccess.TRANSITION_ACTION_SHIFT | next);
- }
-
- /**
- * Add a transition to the transition table.
- * @param code input character code
- * @param state current parser state
- * @param action parser action to be done
- * @param next next parser state
- */
- public add(code: number, state: ParserState, action: ParserAction, next: ParserState): void {
- this.table[state << TableAccess.INDEX_STATE_SHIFT | code] = action << TableAccess.TRANSITION_ACTION_SHIFT | next;
- }
-
- /**
- * Add transitions for multiple input character codes.
- * @param codes input character code array
- * @param state current parser state
- * @param action parser action to be done
- * @param next next parser state
- */
- public addMany(codes: number[], state: ParserState, action: ParserAction, next: ParserState): void {
- for (let i = 0; i < codes.length; i++) {
- this.table[state << TableAccess.INDEX_STATE_SHIFT | codes[i]] = action << TableAccess.TRANSITION_ACTION_SHIFT | next;
- }
- }
-}
-
-const NON_ASCII_PRINTABLE = 0xA0;
-
-export const VT500_TRANSITION_TABLE = (function (): TransitionTable {
- const table: TransitionTable = new TransitionTable(4095);
-
- // range macro for byte
- const BYTE_VALUES = 256;
- const blueprint = Array.apply(null, Array(BYTE_VALUES)).map((unused: any, i: number) => i);
- const r = (start: number, end: number): number[] => blueprint.slice(start, end);
-
- // Default definitions.
- const PRINTABLES = r(0x20, 0x7f); // 0x20 (SP) included, 0x7F (DEL) excluded
- const EXECUTABLES = r(0x00, 0x18);
- EXECUTABLES.push(0x19);
- EXECUTABLES.push.apply(EXECUTABLES, r(0x1c, 0x20));
-
- const states: number[] = r(ParserState.GROUND, ParserState.DCS_PASSTHROUGH + 1);
- let state: any;
-
- // set default transition
- table.setDefault(ParserAction.ERROR, ParserState.GROUND);
- // printables
- table.addMany(PRINTABLES, ParserState.GROUND, ParserAction.PRINT, ParserState.GROUND);
- // global anywhere rules
- for (state in states) {
- table.addMany([0x18, 0x1a, 0x99, 0x9a], state, ParserAction.EXECUTE, ParserState.GROUND);
- table.addMany(r(0x80, 0x90), state, ParserAction.EXECUTE, ParserState.GROUND);
- table.addMany(r(0x90, 0x98), state, ParserAction.EXECUTE, ParserState.GROUND);
- table.add(0x9c, state, ParserAction.IGNORE, ParserState.GROUND); // ST as terminator
- table.add(0x1b, state, ParserAction.CLEAR, ParserState.ESCAPE); // ESC
- table.add(0x9d, state, ParserAction.OSC_START, ParserState.OSC_STRING); // OSC
- table.addMany([0x98, 0x9e, 0x9f], state, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING);
- table.add(0x9b, state, ParserAction.CLEAR, ParserState.CSI_ENTRY); // CSI
- table.add(0x90, state, ParserAction.CLEAR, ParserState.DCS_ENTRY); // DCS
- }
- // rules for executables and 7f
- table.addMany(EXECUTABLES, ParserState.GROUND, ParserAction.EXECUTE, ParserState.GROUND);
- table.addMany(EXECUTABLES, ParserState.ESCAPE, ParserAction.EXECUTE, ParserState.ESCAPE);
- table.add(0x7f, ParserState.ESCAPE, ParserAction.IGNORE, ParserState.ESCAPE);
- table.addMany(EXECUTABLES, ParserState.OSC_STRING, ParserAction.IGNORE, ParserState.OSC_STRING);
- table.addMany(EXECUTABLES, ParserState.CSI_ENTRY, ParserAction.EXECUTE, ParserState.CSI_ENTRY);
- table.add(0x7f, ParserState.CSI_ENTRY, ParserAction.IGNORE, ParserState.CSI_ENTRY);
- table.addMany(EXECUTABLES, ParserState.CSI_PARAM, ParserAction.EXECUTE, ParserState.CSI_PARAM);
- table.add(0x7f, ParserState.CSI_PARAM, ParserAction.IGNORE, ParserState.CSI_PARAM);
- table.addMany(EXECUTABLES, ParserState.CSI_IGNORE, ParserAction.EXECUTE, ParserState.CSI_IGNORE);
- table.addMany(EXECUTABLES, ParserState.CSI_INTERMEDIATE, ParserAction.EXECUTE, ParserState.CSI_INTERMEDIATE);
- table.add(0x7f, ParserState.CSI_INTERMEDIATE, ParserAction.IGNORE, ParserState.CSI_INTERMEDIATE);
- table.addMany(EXECUTABLES, ParserState.ESCAPE_INTERMEDIATE, ParserAction.EXECUTE, ParserState.ESCAPE_INTERMEDIATE);
- table.add(0x7f, ParserState.ESCAPE_INTERMEDIATE, ParserAction.IGNORE, ParserState.ESCAPE_INTERMEDIATE);
- // osc
- table.add(0x5d, ParserState.ESCAPE, ParserAction.OSC_START, ParserState.OSC_STRING);
- table.addMany(PRINTABLES, ParserState.OSC_STRING, ParserAction.OSC_PUT, ParserState.OSC_STRING);
- table.add(0x7f, ParserState.OSC_STRING, ParserAction.OSC_PUT, ParserState.OSC_STRING);
- table.addMany([0x9c, 0x1b, 0x18, 0x1a, 0x07], ParserState.OSC_STRING, ParserAction.OSC_END, ParserState.GROUND);
- table.addMany(r(0x1c, 0x20), ParserState.OSC_STRING, ParserAction.IGNORE, ParserState.OSC_STRING);
- // sos/pm/apc does nothing
- table.addMany([0x58, 0x5e, 0x5f], ParserState.ESCAPE, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING);
- table.addMany(PRINTABLES, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING);
- table.addMany(EXECUTABLES, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING);
- table.add(0x9c, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.GROUND);
- table.add(0x7f, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING);
- // csi entries
- table.add(0x5b, ParserState.ESCAPE, ParserAction.CLEAR, ParserState.CSI_ENTRY);
- table.addMany(r(0x40, 0x7f), ParserState.CSI_ENTRY, ParserAction.CSI_DISPATCH, ParserState.GROUND);
- table.addMany(r(0x30, 0x3c), ParserState.CSI_ENTRY, ParserAction.PARAM, ParserState.CSI_PARAM);
- table.addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.CSI_ENTRY, ParserAction.COLLECT, ParserState.CSI_PARAM);
- table.addMany(r(0x30, 0x3c), ParserState.CSI_PARAM, ParserAction.PARAM, ParserState.CSI_PARAM);
- table.addMany(r(0x40, 0x7f), ParserState.CSI_PARAM, ParserAction.CSI_DISPATCH, ParserState.GROUND);
- table.addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.CSI_PARAM, ParserAction.IGNORE, ParserState.CSI_IGNORE);
- table.addMany(r(0x20, 0x40), ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.CSI_IGNORE);
- table.add(0x7f, ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.CSI_IGNORE);
- table.addMany(r(0x40, 0x7f), ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.GROUND);
- table.addMany(r(0x20, 0x30), ParserState.CSI_ENTRY, ParserAction.COLLECT, ParserState.CSI_INTERMEDIATE);
- table.addMany(r(0x20, 0x30), ParserState.CSI_INTERMEDIATE, ParserAction.COLLECT, ParserState.CSI_INTERMEDIATE);
- table.addMany(r(0x30, 0x40), ParserState.CSI_INTERMEDIATE, ParserAction.IGNORE, ParserState.CSI_IGNORE);
- table.addMany(r(0x40, 0x7f), ParserState.CSI_INTERMEDIATE, ParserAction.CSI_DISPATCH, ParserState.GROUND);
- table.addMany(r(0x20, 0x30), ParserState.CSI_PARAM, ParserAction.COLLECT, ParserState.CSI_INTERMEDIATE);
- // esc_intermediate
- table.addMany(r(0x20, 0x30), ParserState.ESCAPE, ParserAction.COLLECT, ParserState.ESCAPE_INTERMEDIATE);
- table.addMany(r(0x20, 0x30), ParserState.ESCAPE_INTERMEDIATE, ParserAction.COLLECT, ParserState.ESCAPE_INTERMEDIATE);
- table.addMany(r(0x30, 0x7f), ParserState.ESCAPE_INTERMEDIATE, ParserAction.ESC_DISPATCH, ParserState.GROUND);
- table.addMany(r(0x30, 0x50), ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND);
- table.addMany(r(0x51, 0x58), ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND);
- table.addMany([0x59, 0x5a, 0x5c], ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND);
- table.addMany(r(0x60, 0x7f), ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND);
- // dcs entry
- table.add(0x50, ParserState.ESCAPE, ParserAction.CLEAR, ParserState.DCS_ENTRY);
- table.addMany(EXECUTABLES, ParserState.DCS_ENTRY, ParserAction.IGNORE, ParserState.DCS_ENTRY);
- table.add(0x7f, ParserState.DCS_ENTRY, ParserAction.IGNORE, ParserState.DCS_ENTRY);
- table.addMany(r(0x1c, 0x20), ParserState.DCS_ENTRY, ParserAction.IGNORE, ParserState.DCS_ENTRY);
- table.addMany(r(0x20, 0x30), ParserState.DCS_ENTRY, ParserAction.COLLECT, ParserState.DCS_INTERMEDIATE);
- table.addMany(r(0x30, 0x3c), ParserState.DCS_ENTRY, ParserAction.PARAM, ParserState.DCS_PARAM);
- table.addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.DCS_ENTRY, ParserAction.COLLECT, ParserState.DCS_PARAM);
- table.addMany(EXECUTABLES, ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE);
- table.addMany(r(0x20, 0x80), ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE);
- table.addMany(r(0x1c, 0x20), ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE);
- table.addMany(EXECUTABLES, ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_PARAM);
- table.add(0x7f, ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_PARAM);
- table.addMany(r(0x1c, 0x20), ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_PARAM);
- table.addMany(r(0x30, 0x3c), ParserState.DCS_PARAM, ParserAction.PARAM, ParserState.DCS_PARAM);
- table.addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_IGNORE);
- table.addMany(r(0x20, 0x30), ParserState.DCS_PARAM, ParserAction.COLLECT, ParserState.DCS_INTERMEDIATE);
- table.addMany(EXECUTABLES, ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_INTERMEDIATE);
- table.add(0x7f, ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_INTERMEDIATE);
- table.addMany(r(0x1c, 0x20), ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_INTERMEDIATE);
- table.addMany(r(0x20, 0x30), ParserState.DCS_INTERMEDIATE, ParserAction.COLLECT, ParserState.DCS_INTERMEDIATE);
- table.addMany(r(0x30, 0x40), ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_IGNORE);
- table.addMany(r(0x40, 0x7f), ParserState.DCS_INTERMEDIATE, ParserAction.DCS_HOOK, ParserState.DCS_PASSTHROUGH);
- table.addMany(r(0x40, 0x7f), ParserState.DCS_PARAM, ParserAction.DCS_HOOK, ParserState.DCS_PASSTHROUGH);
- table.addMany(r(0x40, 0x7f), ParserState.DCS_ENTRY, ParserAction.DCS_HOOK, ParserState.DCS_PASSTHROUGH);
- table.addMany(EXECUTABLES, ParserState.DCS_PASSTHROUGH, ParserAction.DCS_PUT, ParserState.DCS_PASSTHROUGH);
- table.addMany(PRINTABLES, ParserState.DCS_PASSTHROUGH, ParserAction.DCS_PUT, ParserState.DCS_PASSTHROUGH);
- table.add(0x7f, ParserState.DCS_PASSTHROUGH, ParserAction.IGNORE, ParserState.DCS_PASSTHROUGH);
- table.addMany([0x1b, 0x9c, 0x18, 0x1a], ParserState.DCS_PASSTHROUGH, ParserAction.DCS_UNHOOK, ParserState.GROUND);
- // special handling of unicode chars
- table.add(NON_ASCII_PRINTABLE, ParserState.GROUND, ParserAction.PRINT, ParserState.GROUND);
- table.add(NON_ASCII_PRINTABLE, ParserState.OSC_STRING, ParserAction.OSC_PUT, ParserState.OSC_STRING);
- table.add(NON_ASCII_PRINTABLE, ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.CSI_IGNORE);
- table.add(NON_ASCII_PRINTABLE, ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE);
- table.add(NON_ASCII_PRINTABLE, ParserState.DCS_PASSTHROUGH, ParserAction.DCS_PUT, ParserState.DCS_PASSTHROUGH);
- return table;
-})();
-// ---- END verbatim xterm 5.5.0 ----
-
-const STRING_STATES = new Set<number>([
- ParserState.SOS_PM_APC_STRING,
- ParserState.OSC_STRING,
- ParserState.DCS_ENTRY,
- ParserState.DCS_PARAM,
- ParserState.DCS_IGNORE,
- ParserState.DCS_INTERMEDIATE,
- ParserState.DCS_PASSTHROUGH
-])
-
-// One code through `EscapeSequenceParser.parse()`'s state walk, without its handlers. Two facts
-// about `parse()` make a one-code-at-a-time walk of the table exact: its read-ahead loops (PRINT,
-// PARAM, OSC_PUT, DCS_PUT) only take codes whose table entry keeps the state they are in, and an
-// OSC or DCS ended by ESC goes to ESCAPE although the table says GROUND
-// (`transition |= ParserState.ESCAPE`). An ERROR (a non-ASCII code in SOS/PM/APC or a DCS header)
-// goes to GROUND with the default error handler, as the table says. The lines of parse() this
-// stands for are pinned in `stream-filter.xterm.test.ts`.
-function step(state: number, code: number): number {
- let transition = VT500_TRANSITION_TABLE.table[state << TableAccess.INDEX_STATE_SHIFT | (code < 0xa0 ? code : NON_ASCII_PRINTABLE)]
- const action = transition >> TableAccess.TRANSITION_ACTION_SHIFT
- if ((action === ParserAction.OSC_END || action === ParserAction.DCS_UNHOOK) && code === 0x1b) {
- transition |= ParserState.ESCAPE
- }
- return transition & TableAccess.TRANSITION_STATE_MASK
-}
-
-/**
- * For each code point of a stream read from GROUND, whether xterm consumes it INSIDE a string
- * sequence (OSC, DCS, SOS, PM, APC): in a string state before it and still in one after it.
- */
-export function xtermStringPayload(codePoints: readonly number[]): boolean[] {
- let state: number = ParserState.GROUND
- return codePoints.map((code) => {
- const next = step(state, code)
- const inside = STRING_STATES.has(state) && STRING_STATES.has(next)
- state = next
- return inside
- })
-}
-
-/** Whether xterm, reading these code points from GROUND, ever enters a string sequence. */
-export function xtermEntersString(codePoints: readonly number[]): boolean {
- let state: number = ParserState.GROUND
- for (const code of codePoints) {
- state = step(state, code)
- if (STRING_STATES.has(state)) return true
- }
- return false
-}
diff --git a/src/core/watch-link/api.test.ts b/src/core/watch-link/api.test.ts
deleted file mode 100644
index c9a592553..000000000
--- a/src/core/watch-link/api.test.ts
+++ /dev/null
@@ -1,368 +0,0 @@
-import { describe, it, expect, vi } from 'vitest'
-import { createWatchLinkApi } from './api'
-
-const res = (status: number, body: unknown, headers: Record<string, string> = {}) =>
- new Response(body === null ? null : JSON.stringify(body), { status, headers: { 'content-type': 'application/json', ...headers } })
-function api(reply: (url: string, init: RequestInit) => Response | Promise<Response>, now = 1_000_000) {
- const calls: { url: string; body: unknown }[] = []
- const a = createWatchLinkApi({
- apiBase: 'https://api.test/',
- now: () => now,
- fetch: (async (url: string, init: RequestInit) => { calls.push({ url, body: JSON.parse(String(init.body)) }); return reply(url, init) }) as typeof fetch
- })
- return { a, calls }
-}
-
-/** A fetch that never answers on its own: it settles only when the caller's AbortSignal fires. */
-function hungFetch() {
- const signals: AbortSignal[] = []
- const f = ((_url: string, init: RequestInit) =>
- new Promise<Response>((_resolve, reject) => {
- const signal = init.signal as AbortSignal
- signals.push(signal)
- signal.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError')))
- })) as unknown as typeof fetch
- return { f, signals }
-}
-
-/** A 200 whose body sends part of a chunk and then dies the way undici reports a reset (`terminated`). */
-function resetMidBody() {
- let pulls = 0
- const body = new ReadableStream<Uint8Array>({
- pull(c) {
- if (pulls++ === 0) c.enqueue(new TextEncoder().encode('{"pairingToken":"P'))
- else c.error(new TypeError('terminated'))
- }
- })
- return new Response(body, { status: 200, headers: { 'content-type': 'application/json' } })
-}
-
-/**
- * Tracks the abort timers `createWatchLinkApi` arms. Only timers armed with `delay` are counted, so a
- * timer some other layer arms (undici, vitest) cannot make the count lie either way.
- */
-function trackTimers(delay: number) {
- const realSet = globalThis.setTimeout
- const realClear = globalThis.clearTimeout
- const live = new Set<unknown>()
- let armed = 0
- const setSpy = vi.spyOn(globalThis, 'setTimeout').mockImplementation(((fn: () => void, ms?: number, ...args: unknown[]) => {
- const h = realSet(fn, ms, ...args)
- if (ms === delay) {
- armed++
- live.add(h)
- }
- return h
- }) as unknown as typeof setTimeout)
- const clearSpy = vi.spyOn(globalThis, 'clearTimeout').mockImplementation(((h?: Parameters<typeof clearTimeout>[0]) => {
- live.delete(h)
- return realClear(h)
- }) as typeof clearTimeout)
- return {
- live,
- armed: () => armed,
- restore: () => {
- setSpy.mockRestore()
- clearSpy.mockRestore()
- }
- }
-}
-
-/** A link id as the server mints it: 16 random bytes, base64url, 22 characters. */
-const LID = 'AbCdEfGhIjKlMnOpQrStUv'
-
-describe('createWatchLinkApi', () => {
- it('create posts the hash and corrects expiry to the local clock', async () => {
- const serverNow = Date.parse('Tue, 29 Sep 2026 10:00:00 GMT')
- const { a, calls } = api(() => res(200, { linkId: LID, expiresAt: serverNow / 1000 + 3600 }, { date: new Date(serverNow).toUTCString() }), 5_000)
- const r = await a.create('ent', 'ab'.repeat(32), 3600)
- expect(calls[0]).toEqual({ url: 'https://api.test/v1/watch-links', body: { entitlement: 'ent', joinKeyHash: 'ab'.repeat(32), ttlSeconds: 3600 } })
- expect(r).toEqual({ ok: true, linkId: LID, expiresAt: 5_000 + 3_600_000 })
- })
-
- // A link id the URL cannot carry: formatWatchLink refuses it, and the store would drop the record
- // at the next boot. A malformed reply, like a missing expiry — never a link.
- it('create refuses a link id that is not 22 base64url characters', async () => {
- const exp = Date.now() / 1000 + 3600
- for (const linkId of ['L', `${LID}x`, 'AbCdEfGhIjKlMnOpQrSt/v', 'AbCdEfGhIjKlMnOpQrSt%v', 42]) {
- expect(await api(() => res(200, { linkId, expiresAt: exp })).a.create('e', 'h', 3600)).toEqual({ ok: false, error: 'network' })
- }
- })
-
- // Unlimited (`ttlSeconds: 0`): the server answers `expiresAt: null` — accepted for that request and
- // for no other. A null to a finite request, or no expiry at all, is a malformed reply.
- it('create with ttlSeconds 0 accepts a null expiry, and only for that request', async () => {
- const { a, calls } = api(() => res(200, { linkId: LID, expiresAt: null }))
- expect(await a.create('ent', 'h', 0)).toEqual({ ok: true, linkId: LID, expiresAt: null })
- expect(calls[0].body).toEqual({ entitlement: 'ent', joinKeyHash: 'h', ttlSeconds: 0 })
- for (const ttl of [900, 3600, 86400]) {
- expect(await api(() => res(200, { linkId: LID, expiresAt: null })).a.create('e', 'h', ttl)).toEqual({ ok: false, error: 'network' })
- }
- expect(await api(() => res(200, { linkId: LID })).a.create('e', 'h', 0)).toEqual({ ok: false, error: 'network' })
- expect(await api(() => res(200, { linkId: LID, expiresAt: 'never' })).a.create('e', 'h', 0)).toEqual({ ok: false, error: 'network' })
- })
-
- it('create with ttlSeconds 0 answered with an end time (a capped server) re-anchors it like any other', async () => {
- const serverNow = Date.parse('Tue, 29 Sep 2026 10:00:00 GMT')
- const { a } = api(() => res(200, { linkId: LID, expiresAt: serverNow / 1000 + 86400 }, { date: new Date(serverNow).toUTCString() }), 5_000)
- expect(await a.create('ent', 'h', 0)).toEqual({ ok: true, linkId: LID, expiresAt: 5_000 + 86_400_000 })
- })
-
- it('a 400 bad_ttl to an Unlimited request is ttl-unsupported (an older server); any other 400 stays bad-request', async () => {
- expect(await api(() => res(400, { error: 'bad_ttl' })).a.create('e', 'h', 0)).toEqual({ ok: false, error: 'ttl-unsupported' })
- expect(await api(() => res(400, { error: 'bad_ttl' })).a.create('e', 'h', 3600)).toEqual({ ok: false, error: 'bad-request' })
- expect(await api(() => res(400, { error: 'bad_request' })).a.create('e', 'h', 0)).toEqual({ ok: false, error: 'bad-request' })
- expect(await api(() => res(400, null)).a.create('e', 'h', 0)).toEqual({ ok: false, error: 'bad-request' })
- })
-
- it('maps create errors', async () => {
- const cases: [Response, string][] = [
- [res(402, { error: 'not_entitled' }), 'not-entitled'],
- [res(403, { error: 'companion_device' }), 'not-entitled'],
- [res(429, { error: 'rate_limited', scope: 'active_links' }), 'limit-active'],
- [res(429, { error: 'rate_limited', scope: 'license' }), 'limit-daily'],
- [res(429, { error: 'rate_limited', scope: 'ip' }), 'rate-limited'],
- [res(503, { error: 'license_check_unavailable' }), 'license-check'],
- [res(400, { error: 'bad_ttl' }), 'bad-request'],
- [res(500, null), 'network']
- ]
- for (const [r, want] of cases) expect(await api(() => r.clone()).a.create('e', 'h', 3600)).toEqual({ ok: false, error: want })
- expect(await api(() => { throw new Error('offline') }).a.create('e', 'h', 3600)).toEqual({ ok: false, error: 'network' })
- })
-
- it('hostToken maps 410 to gone and other refusals to the scheduler kinds', async () => {
- expect(await api(() => res(410, { error: 'gone', reason: 'revoked' })).a.hostToken('L', 'e')).toEqual({ ok: false, kind: 'gone', reason: 'revoked' })
- expect(await api(() => res(404, { error: 'not_found' })).a.hostToken('L', 'e')).toMatchObject({ ok: false, kind: 'refused' })
- expect(await api(() => res(429, {}, { 'retry-after': '60' })).a.hostToken('L', 'e')).toEqual({ ok: false, kind: 'rate-limited', status: 429, retryAfterMs: 60_000 })
- const ok = await api(() => res(200, { pairingToken: 'P', exp: 1_000 + 120 }, { date: new Date(1_000_000).toUTCString() })).a.hostToken('L', 'e')
- expect(ok).toMatchObject({ ok: true, pairingToken: 'P' })
- })
-
- it('hostToken maps a 410 expired, and the owner-check refusals 402/403', async () => {
- expect(await api(() => res(410, { error: 'gone', reason: 'expired' })).a.hostToken('L', 'e')).toEqual({ ok: false, kind: 'gone', reason: 'expired' })
- expect(await api(() => res(402, { error: 'not_entitled' })).a.hostToken('L', 'e')).toEqual({ ok: false, kind: 'refused', status: 402 })
- expect(await api(() => res(403, { error: 'companion_device' })).a.hostToken('L', 'e')).toEqual({ ok: false, kind: 'refused', status: 403 })
- })
-
- it('hostToken takes the token lifetime from the Date header, not the local clock', async () => {
- // The server says it is 10:00:00 and the token ends at 10:02:00. This machine's clock reads
- // something else entirely; the lifetime must still be two minutes.
- const serverNow = Date.parse('Tue, 29 Sep 2026 10:00:00 GMT')
- const reply = () => res(200, { pairingToken: 'P', exp: serverNow / 1000 + 120 }, { date: new Date(serverNow).toUTCString() })
- expect(await api(reply, 5_000).a.hostToken('L', 'e')).toEqual({ ok: true, pairingToken: 'P', hostId: '', ttlMs: 120_000 })
- })
-
- it('hostToken: a 200 without a usable pairingToken is a bad response, not a network failure', async () => {
- for (const body of [{ exp: 1_120 }, { pairingToken: 42, exp: 1_120 }, { pairingToken: '', exp: 1_120 }, null]) {
- expect(await api(() => res(200, body)).a.hostToken('L', 'e')).toEqual({ ok: false, kind: 'bad-response', status: 200 })
- }
- // A body that is not JSON at all is the server's fault too.
- expect(await api(() => new Response('<html>', { status: 200 })).a.hostToken('L', 'e')).toEqual({ ok: false, kind: 'bad-response', status: 200 })
- })
-
- it('hostToken: a body that stalls until the timeout is a network failure, not a bad response', async () => {
- const a = createWatchLinkApi({
- apiBase: 'https://api.test',
- timeoutMs: 20,
- fetch: (async (_url: string, init: RequestInit) => {
- const signal = init.signal as AbortSignal
- const body = new ReadableStream<Uint8Array>({
- start(c) {
- signal.addEventListener('abort', () => c.error(new DOMException('aborted', 'AbortError')))
- }
- })
- return new Response(body, { status: 200, headers: { 'content-type': 'application/json' } })
- }) as typeof fetch
- })
- expect(await a.hostToken('L', 'e')).toEqual({ ok: false, kind: 'network' })
- })
-
- it('status, revoke and revokeAll', async () => {
- expect(await api(() => res(200, { state: 'revoked' })).a.status('L', 'e')).toBe('revoked')
- expect(await api(() => res(500, null)).a.status('L', 'e')).toBe('unknown')
- const r = api(() => res(204, null))
- expect(await r.a.revoke('L', 'e')).toBe(true)
- expect(r.calls[0].url).toBe('https://api.test/v1/watch-links/L/revoke')
- expect(await api(() => res(204, null)).a.revokeAll('e')).toBe(true)
- })
-
- it('status reads only the three known states; revoke answers false on anything but 204', async () => {
- expect(await api(() => res(200, { state: 'live' })).a.status('L', 'e')).toBe('live')
- expect(await api(() => res(200, { state: 'expired' })).a.status('L', 'e')).toBe('expired')
- expect(await api(() => res(200, { state: 'paused' })).a.status('L', 'e')).toBe('unknown')
- expect(await api(() => res(404, { error: 'not_found' })).a.status('L', 'e')).toBe('unknown')
- expect(await api(() => res(404, { error: 'not_found' })).a.revoke('L', 'e')).toBe(false)
- expect(await api(() => res(200, {})).a.revokeAll('e')).toBe(false)
- const all = api(() => res(204, null))
- await all.a.revokeAll('e')
- expect(all.calls[0]).toEqual({ url: 'https://api.test/v1/watch-links/revoke-all', body: { entitlement: 'e' } })
- })
-
- it('the timeout ends a fetch that never answers', async () => {
- const timeoutMs = 20
- const { f, signals } = hungFetch()
- const a = createWatchLinkApi({ apiBase: 'https://api.test', fetch: f, timeoutMs })
- const started = Date.now()
- const [created, token, state, revoked, revokedAll] = await Promise.all([
- a.create('e', 'h', 3600),
- a.hostToken('L', 'e'),
- a.status('L', 'e'),
- a.revoke('L', 'e'),
- a.revokeAll('e')
- ])
- expect(created).toEqual({ ok: false, error: 'network' })
- expect(token).toEqual({ ok: false, kind: 'network' })
- expect(state).toBe('unknown')
- expect(revoked).toBe(false)
- expect(revokedAll).toBe(false)
- expect(signals).toHaveLength(5)
- expect(signals.every((s) => s.aborted)).toBe(true)
- // Generous bound: the point is that it ended on the timeout, not on vitest's own 5 s limit.
- expect(Date.now() - started).toBeLessThan(2_000)
- })
-
- it('the entitlement rides only the JSON body, never the URL or a header', async () => {
- const ENT = 'ENT-SECRET-7f3a'
- const seen: { url: string; init: RequestInit }[] = []
- const a = createWatchLinkApi({
- apiBase: 'https://api.test',
- fetch: (async (url: string, init: RequestInit) => {
- seen.push({ url, init })
- return res(204, null)
- }) as typeof fetch
- })
- await a.create(ENT, 'h', 3600)
- await a.hostToken('L', ENT)
- await a.status('L', ENT)
- await a.revoke('L', ENT)
- await a.revokeAll(ENT)
- expect(seen).toHaveLength(5)
- for (const { url, init } of seen) {
- expect(url).not.toContain(ENT)
- expect(JSON.stringify(Object.entries(new Headers(init.headers)))).not.toContain(ENT)
- expect(init.method).toBe('POST')
- expect(JSON.parse(String(init.body)).entitlement).toBe(ENT)
- }
- })
-
- it('url-encodes the link id in the path', async () => {
- const id = 'a/b?c#d %'
- const enc = 'a%2Fb%3Fc%23d%20%25'
- const r = api(() => res(204, null))
- await r.a.hostToken(id, 'e')
- await r.a.status(id, 'e')
- await r.a.revoke(id, 'e')
- expect(r.calls.map((c) => c.url)).toEqual([
- `https://api.test/v1/watch-links/${enc}/host-token`,
- `https://api.test/v1/watch-links/${enc}/status`,
- `https://api.test/v1/watch-links/${enc}/revoke`
- ])
- })
-
- it('create accepts a 200 only when expiresAt is a finite number above zero', async () => {
- const bodies = [
- '{"linkId":"L","expiresAt":0}',
- '{"linkId":"L","expiresAt":-5}',
- // NaN cannot cross JSON (it serializes to null); a string and a non-finite number can.
- '{"linkId":"L","expiresAt":null}',
- '{"linkId":"L","expiresAt":"1790679600"}',
- '{"linkId":"L","expiresAt":1e999}',
- '{"linkId":"L"}'
- ]
- for (const text of bodies) {
- expect(await api(() => new Response(text, { status: 200 })).a.create('e', 'h', 3600)).toEqual({ ok: false, error: 'network' })
- }
- })
-
- it('create falls back to the local clock when the Date header is missing or unparseable', async () => {
- // Without a server clock to subtract, the instant is taken as-is: expiresAt = the server's
- // instant in ms (local now + (instant - local now)).
- const serverExp = Date.parse('Tue, 29 Sep 2026 11:00:00 GMT') / 1000
- for (const headers of [{}, { date: 'yesterday' }] as Record<string, string>[]) {
- const r = await api(() => res(200, { linkId: LID, expiresAt: serverExp }, headers), 5_000).a.create('e', 'h', 3600)
- expect(r).toEqual({ ok: true, linkId: LID, expiresAt: serverExp * 1000 })
- }
- })
-
- it('hostToken: our own malformed request (400) is refused, never retried as a network failure', async () => {
- expect(await api(() => res(400, { error: 'bad_request' })).a.hostToken('L', 'e')).toEqual({ ok: false, kind: 'refused', status: 400 })
- })
-
- it('hostToken: a 5xx is a network failure that keeps its status', async () => {
- for (const status of [500, 502, 503]) {
- expect(await api(() => res(status, null)).a.hostToken('L', 'e')).toEqual({ ok: false, kind: 'network', status })
- }
- })
-
- it('Retry-After counts only as whole seconds, clamped to an hour', async () => {
- const after = async (value: string) => api(() => res(429, {}, { 'retry-after': value })).a.hostToken('L', 'e')
- // Delay-seconds (RFC 9110) only; everything else leaves the wait to the scheduler's own floor.
- for (const value of ['Wed, 21 Oct 2026 07:28:00 GMT', '1e9', 'Infinity', '0x10', '', '0.5', '-5', '0']) {
- expect(await after(value)).toEqual({ ok: false, kind: 'rate-limited', status: 429 })
- }
- expect(await api(() => res(429, {})).a.hostToken('L', 'e')).toEqual({ ok: false, kind: 'rate-limited', status: 429 })
- expect(await after('60')).toEqual({ ok: false, kind: 'rate-limited', status: 429, retryAfterMs: 60_000 })
- expect(await after('3600')).toEqual({ ok: false, kind: 'rate-limited', status: 429, retryAfterMs: 3_600_000 })
- for (const value of ['3601', '86400', '99999999999999999999']) {
- expect(await after(value)).toEqual({ ok: false, kind: 'rate-limited', status: 429, retryAfterMs: 3_600_000 })
- }
- })
-
- it('a transport error while the body streams is no answer, never a bad response', async () => {
- expect(await api(() => resetMidBody()).a.hostToken('L', 'e')).toEqual({ ok: false, kind: 'network' })
- expect(await api(() => resetMidBody()).a.create('e', 'h', 3600)).toEqual({ ok: false, error: 'network' })
- expect(await api(() => resetMidBody()).a.status('L', 'e')).toBe('unknown')
- })
-
- it('a completed body that does not parse is the server\'s fault', async () => {
- for (const text of ['{"pairingToken":"P"', '', 'not json']) {
- expect(await api(() => new Response(text, { status: 200 })).a.hostToken('L', 'e')).toEqual({ ok: false, kind: 'bad-response', status: 200 })
- }
- })
-
- it('every request refuses to follow a redirect', async () => {
- const inits: RequestInit[] = []
- const a = createWatchLinkApi({
- apiBase: 'https://api.test',
- fetch: (async (_url: string, init: RequestInit) => {
- inits.push(init)
- return res(204, null)
- }) as typeof fetch
- })
- await a.create('e', 'h', 3600)
- await a.hostToken('L', 'e')
- await a.status('L', 'e')
- await a.revoke('L', 'e')
- await a.revokeAll('e')
- expect(inits.map((i) => i.redirect)).toEqual(['error', 'error', 'error', 'error', 'error'])
- })
-
- it('the abort timer is cleared after every outcome', async () => {
- const T = 4_321
- const t = trackTimers(T)
- try {
- const run = (reply: (init: RequestInit) => Promise<Response>) =>
- createWatchLinkApi({ apiBase: 'https://api.test', timeoutMs: T, fetch: ((_u: string, init: RequestInit) => reply(init)) as typeof fetch })
- // success, error status, thrown fetch, and a body that dies mid-stream
- await run(async () => res(200, { pairingToken: 'P', exp: 1_120 })).hostToken('L', 'e')
- await run(async () => res(500, null)).hostToken('L', 'e')
- await run(async () => { throw new Error('offline') }).hostToken('L', 'e')
- await run(async () => resetMidBody()).hostToken('L', 'e')
- expect(t.armed()).toBe(4)
- expect(t.live.size).toBe(0)
- } finally {
- t.restore()
- }
- // and the timeout itself: the timer that fired is cleared too, and nothing else is left armed
- const T2 = 17
- const t2 = trackTimers(T2)
- try {
- const { f } = hungFetch()
- expect(await createWatchLinkApi({ apiBase: 'https://api.test', timeoutMs: T2, fetch: f }).revoke('L', 'e')).toBe(false)
- expect(t2.armed()).toBe(1)
- expect(t2.live.size).toBe(0)
- } finally {
- t2.restore()
- }
- })
-})
diff --git a/src/core/watch-link/api.ts b/src/core/watch-link/api.ts
deleted file mode 100644
index e564d695c..000000000
--- a/src/core/watch-link/api.ts
+++ /dev/null
@@ -1,158 +0,0 @@
-// HTTP client for the live-link routes (nodeterm-server, Plan 1). Credentials ride the JSON body
-// over TLS, never argv. Every call is bounded by a timeout that also covers the body read.
-import { tokenTtlMs, type MintResult } from '../relay/host-token'
-import { LINK_ID_RE } from '../../shared/watch-link/link'
-
-/** `ttl-unsupported`: a `400 {"error":"bad_ttl"}` answered to an Unlimited request (`ttlSeconds` 0) —
- * a server older than unlimited links. The same 400 to a finite request stays `bad-request`. */
-export type CreateError =
- | 'not-entitled'
- | 'limit-active'
- | 'limit-daily'
- | 'rate-limited'
- | 'license-check'
- | 'bad-request'
- | 'ttl-unsupported'
- | 'network'
-export type HostTokenResult = MintResult | { ok: false; kind: 'gone'; reason: 'revoked' | 'expired' }
-export interface WatchLinkApi {
- /** `ttlSeconds` 0 asks for an Unlimited link; only then may the answer's `expiresAt` be null. */
- create(
- entitlement: string,
- joinKeyHash: string,
- ttlSeconds: number
- ): Promise<{ ok: true; linkId: string; expiresAt: number | null } | { ok: false; error: CreateError }>
- hostToken(linkId: string, entitlement: string): Promise<HostTokenResult>
- status(linkId: string, entitlement: string): Promise<'live' | 'revoked' | 'expired' | 'unknown'>
- revoke(linkId: string, entitlement: string): Promise<boolean>
- revokeAll(entitlement: string): Promise<boolean>
-}
-
-interface Reply {
- status: number
- /** The parsed body when it is a JSON object; null for 204, an empty or non-JSON body, or any other JSON value. */
- json: Record<string, unknown> | null
- date: string | null
- retryAfter: string | null
-}
-
-/** The longest wait a Retry-After may impose. Our limiters do not count a refused request, so asking
- * again early is cheap, while an unbounded header (a proxy's `86400`) would park a link's host for
- * longer than the link lives. */
-const RETRY_AFTER_MAX_S = 3600
-
-/** Retry-After as RFC 9110 delay-seconds only, clamped. Anything else (an HTTP-date, `1e9`,
- * `Infinity`, `0x10`, `0.5`, empty, 0) is no answer: the scheduler's own floor applies. */
-function retryAfterMs(header: string | null): number | undefined {
- if (header === null || !/^\d+$/.test(header)) return undefined
- const s = Number(header)
- return s > 0 ? Math.min(s, RETRY_AFTER_MAX_S) * 1000 : undefined
-}
-
-export function createWatchLinkApi(o: { apiBase: string; fetch?: typeof fetch; now?: () => number; timeoutMs?: number }): WatchLinkApi {
- const base = o.apiBase.replace(/\/+$/, '')
- const now = o.now ?? Date.now
- const f = o.fetch ?? fetch
-
- /** One POST. null = no answer (the request failed, or the body did not arrive whole, timeout included). */
- async function post(path: string, body: unknown): Promise<Reply | null> {
- const ctrl = new AbortController()
- const timer = setTimeout(() => ctrl.abort(), o.timeoutMs ?? 8000)
- try {
- const r = await f(`${base}${path}`, {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify(body),
- signal: ctrl.signal,
- // A 307/308 would re-send this body, entitlement included, to wherever Location points. None
- // of these routes redirects, so a redirect is an error rather than a hop.
- redirect: 'error'
- })
- let json: Record<string, unknown> | null = null
- if (r.status !== 204) {
- // Reading and parsing are two different failures. A read that throws (a reset mid-body, the
- // timeout's abort) is the network's: the outer catch turns it into "no answer". A body that
- // arrived whole but is not a JSON object is the server's: json stays null.
- const text = await r.text()
- try {
- const v: unknown = JSON.parse(text)
- json = v !== null && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : null
- } catch {
- json = null
- }
- }
- return { status: r.status, json, date: r.headers.get('date'), retryAfter: r.headers.get('retry-after') }
- } catch {
- return null
- } finally {
- clearTimeout(timer)
- }
- }
- const path = (id: string, verb: string) => `/v1/watch-links/${encodeURIComponent(id)}/${verb}`
-
- return {
- async create(entitlement, joinKeyHash, ttlSeconds) {
- const r = await post('/v1/watch-links', { entitlement, joinKeyHash, ttlSeconds })
- if (!r) return { ok: false, error: 'network' }
- const exp = r.json?.expiresAt
- // A link always ends in the future; 0, a negative or a non-finite instant is a malformed reply,
- // and tokenTtlMs would turn it into its two-minute HOST-TOKEN default (a link that "expires" in
- // 2 minutes while its server row stays live and counts against the active-link cap). A link id
- // the URL could not carry (`formatWatchLink` refuses it, and the store would drop the record at
- // the next boot) is malformed too.
- const linkId = r.json?.linkId
- if (r.status === 200 && typeof linkId === 'string' && LINK_ID_RE.test(linkId)) {
- // No end time — an Unlimited link — only when one was asked for. A null to a finite request is
- // a malformed reply: taken as given it would be a link nobody asked to outlive its choice.
- if (exp === null && ttlSeconds === 0) return { ok: true, linkId, expiresAt: null }
- if (typeof exp === 'number' && Number.isFinite(exp) && exp > 0) {
- // `expiresAt` is an instant on the SERVER's clock; the Date header turns it into time left,
- // which is then anchored on this machine's clock (see tokenTtlMs). A capped server answers an
- // Unlimited request with an end time too: re-anchored the same way.
- const t = now()
- return { ok: true, linkId, expiresAt: t + tokenTtlMs(exp, r.date, t) }
- }
- }
- if (r.status === 402 || r.status === 403) return { ok: false, error: 'not-entitled' }
- if (r.status === 429) {
- const scope = r.json?.scope
- return { ok: false, error: scope === 'active_links' ? 'limit-active' : scope === 'license' ? 'limit-daily' : 'rate-limited' }
- }
- if (r.status === 503) return { ok: false, error: 'license-check' }
- if (r.status === 400) {
- return { ok: false, error: ttlSeconds === 0 && r.json?.error === 'bad_ttl' ? 'ttl-unsupported' : 'bad-request' }
- }
- return { ok: false, error: 'network' }
- },
- async hostToken(linkId, entitlement) {
- const r = await post(path(linkId, 'host-token'), { entitlement })
- if (!r) return { ok: false, kind: 'network' }
- if (r.status === 200) {
- // A 200 without a token is the server's fault, not the network's (same rule as mintHostToken).
- if (typeof r.json?.pairingToken !== 'string' || !r.json.pairingToken) return { ok: false, kind: 'bad-response', status: 200 }
- const exp = typeof r.json.exp === 'number' ? r.json.exp : 0
- return { ok: true, pairingToken: r.json.pairingToken, hostId: '', ttlMs: tokenTtlMs(exp, r.date, now()) }
- }
- if (r.status === 410) return { ok: false, kind: 'gone', reason: r.json?.reason === 'expired' ? 'expired' : 'revoked' }
- if (r.status === 429) {
- const ra = retryAfterMs(r.retryAfter)
- return { ok: false, kind: 'rate-limited', status: 429, ...(ra !== undefined ? { retryAfterMs: ra } : {}) }
- }
- // 400 is our own malformed request (the owner check's body validation): it can never succeed,
- // so it stops minting like the other refusals instead of being retried as a network failure.
- if (r.status === 400 || r.status === 402 || r.status === 403 || r.status === 404) return { ok: false, kind: 'refused', status: r.status }
- return { ok: false, kind: 'network', status: r.status }
- },
- async status(linkId, entitlement) {
- const r = await post(path(linkId, 'status'), { entitlement })
- const s = r?.status === 200 ? r.json?.state : null
- return s === 'live' || s === 'revoked' || s === 'expired' ? s : 'unknown'
- },
- async revoke(linkId, entitlement) {
- return (await post(path(linkId, 'revoke'), { entitlement }))?.status === 204
- },
- async revokeAll(entitlement) {
- return (await post('/v1/watch-links/revoke-all', { entitlement }))?.status === 204
- }
- }
-}
diff --git a/src/core/watch-link/chat-cast.guard.test.ts b/src/core/watch-link/chat-cast.guard.test.ts
deleted file mode 100644
index 6c15610be..000000000
--- a/src/core/watch-link/chat-cast.guard.test.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-// A viewer's chat reaches the owner ONLY through a live link's own relay session: the cast arrives on
-// that session's `PeerAttach.cast`, which the link host answers (link-host.ts), after the watcher
-// policy admitted it for a Commenter or Control link only (watcher-policy.ts). Nothing registers `watch:chat` on
-// a platform. If something did, a hosted Editor or a Server Edition browser tab — clients of the same
-// core, whose casts go to the platform — could post "viewer" chat into the owner's popover, and a
-// Viewer link's refusal would no longer be the only door.
-//
-// So this names every file allowed to mention the cast, and fails on any other, with its reason. The
-// event of the same name (`WATCH_EVENT.chat`, host → viewer) is the same string, so a handler
-// registered under it would be the same door: it is matched too, and only the link host writes it.
-import { describe, expect, it } from 'vitest'
-import { readFileSync, readdirSync, statSync } from 'node:fs'
-import { join, relative } from 'node:path'
-
-const SRC = join(__dirname, '..', '..')
-
-/** The cast, the event of the same string, or the string itself. */
-const MENTIONS = /WATCH_CHAT_CAST|WATCH_EVENT\s*\.\s*chat\b|WATCH_EVENT\s*\[\s*['"`]chat['"`]\s*\]|['"`]watch:chat['"`]/
-
-const ALLOWED: Record<string, string> = {
- 'shared/watch-link/protocol.ts': 'defines the cast and the event',
- 'shared/watch-link/client.ts': "the viewer's browser client sends the cast",
- 'core/watch-link/watcher-policy.ts': 'admits the cast for a Commenter or Control link only',
- 'core/watch-link/link-host.ts': "answers the cast on the link's own relay session, and sends the event"
-}
-
-function sources(dir: string, out: string[] = []): string[] {
- for (const entry of readdirSync(dir)) {
- const p = join(dir, entry)
- if (statSync(p).isDirectory()) {
- if (entry !== 'node_modules') sources(p, out)
- } else if (/\.tsx?$/.test(entry) && !/\.test\.tsx?$/.test(entry)) out.push(p)
- }
- return out
-}
-
-describe('the watch:chat cast', () => {
- it('is mentioned by no source file outside the live-link path', () => {
- const offenders: string[] = []
- for (const file of sources(SRC)) {
- const rel = relative(SRC, file).replace(/\\/g, '/')
- const text = readFileSync(file, 'utf8').replace(/\r\n/g, '\n')
- if (MENTIONS.test(text) && !(rel in ALLOWED)) offenders.push(rel)
- }
- expect(offenders).toEqual([])
- })
-
- it('matches every spelling of it', () => {
- for (const text of [
- 'WATCH_CHAT_CAST',
- 'WATCH_EVENT.chat',
- 'WATCH_EVENT .chat',
- "WATCH_EVENT['chat']",
- "'watch:chat'",
- '"watch:chat"',
- '`watch:chat`'
- ]) {
- expect(MENTIONS.test(text), text).toBe(true)
- }
- for (const text of ["'watchLink:chat'", 'WATCH_EVENT.chatty', "'watch:chat-history'"]) expect(MENTIONS.test(text), text).toBe(false)
- })
-
- it('every allowlisted file still exists and still mentions it (a stale entry is a hole)', () => {
- for (const rel of Object.keys(ALLOWED)) {
- const text = readFileSync(join(SRC, rel), 'utf8')
- expect(MENTIONS.test(text), rel).toBe(true)
- }
- })
-})
diff --git a/src/core/watch-link/client.test.ts b/src/core/watch-link/client.test.ts
deleted file mode 100644
index 2f7711fd1..000000000
--- a/src/core/watch-link/client.test.ts
+++ /dev/null
@@ -1,343 +0,0 @@
-// The viewer client runs against the REAL host-role relay socket and the REAL trust gate, not fakes.
-// That is what pins the wire constants src/shared/watch-link/wire.ts restates (the seq header, TAG_*,
-// ROLE_*, NONCE_BYTES) and the trust frames client.ts builds: they are module-private in
-// relay-socket.ts / owned by relay-trust.ts, so a drift there shows up here as a handshake that never
-// completes, a frame the host never sees, or a gate that never opens. It lives in core because it
-// imports core modules the web tsconfig project that vendors src/shared/watch-link cannot see.
-import { describe, it, expect, vi } from 'vitest'
-import nacl from 'tweetnacl'
-import { connectRelay } from '../relay/relay-socket'
-import { transportPair } from '../relay/transport-pair'
-import { publicKeyToB64 } from '../relay/e2ee'
-import { createTrustGate, deniedFrame, type TrustGate } from '../relay/relay-trust'
-import { encodePtyData } from '../../shared/rpc'
-import { connectWatchClient, TRUST_CONFIRM_JSON, type WatchSocket } from '../../shared/watch-link/client'
-import { deriveWatchLinkKeys, type WatchLinkKeys } from '../../shared/watch-link/keys'
-import { INPUT_MAX } from '../../shared/watch-link/protocol'
-import { openUnlock } from '../../shared/watch-link/unlock-seal'
-import { bytesToB64 } from '../../shared/watch-link/bytes'
-
-function hostWith(opts: { keys?: WatchLinkKeys; autoApprove?: boolean } = {}) {
- const keys = opts.keys ?? deriveWatchLinkKeys(nacl.randomBytes(32))
- const { hostT, peerT } = transportPair()
- const tunnel: string[] = []
- let ready = false
- let closed = 0
- let gateOpened = false
- let gate: TrustGate | null = null
- const host = connectRelay({
- url: 'wss://x', token: 't', role: 'host',
- ourKeys: { publicKey: keys.host.publicKey, secretKey: keys.host.secretKey },
- transport: hostT,
- onReady: () => {
- ready = true
- // The host's own gate, wired the way the relay hosts wire it: confirms travel only over the
- // encrypted tunnel, in both directions.
- gate = createTrustGate({
- peerKeyB64: host.peerPublicKeyB64() ?? '',
- sessionId: 'watch-test',
- sas: () => host.sas(),
- sendConfirm: (json) => { host.sendTunnelText(json) },
- onOpen: () => { gateOpened = true },
- autoApprove: opts.autoApprove
- })
- },
- onRpc: () => {}, onFrame: () => {},
- onClose: () => { closed++ },
- onTunnel: (kind, payload) => {
- if (kind !== 'text') return
- const json = new TextDecoder().decode(payload)
- tunnel.push(json)
- gate?.onTunnelText(json)
- }
- })
- return {
- keys, host, hostT, peerT, tunnel,
- isReady: () => ready,
- hostClosed: () => closed,
- gateOpen: () => gateOpened,
- /** The host's human (or its pin) confirms, through the real gate. */
- confirm: () => {
- if (!gate) throw new Error('the host is not ready, so it has no gate yet')
- gate.confirmHere()
- }
- }
-}
-
-/** The client's socket with a count of the binary (sealed) frames it sent. */
-function counting(socket: WatchSocket) {
- const sent = { text: 0, binary: 0 }
- const wrapped: WatchSocket = {
- ...socket,
- send: (d) => { if (typeof d === 'string') sent.text++; else sent.binary++; socket.send(d) }
- }
- return { socket: wrapped, sent }
-}
-
-function events() {
- const log = { open: 0, events: [] as [string, unknown[]][], pty: [] as [string, string][], denied: [] as string[], closed: 0 }
- return {
- log,
- ev: {
- onOpen: () => { log.open++ },
- onEvent: (c: string, a: unknown[]) => { log.events.push([c, a]) },
- onPtyData: (s: string, d: string) => { log.pty.push([s, d]) },
- onDenied: (r: string) => { log.denied.push(r) },
- onClose: () => { log.closed++ }
- }
- }
-}
-
-describe('connectWatchClient against the real relay socket', () => {
- it('completes the handshake, confirms trust, and opens once the host confirms', async () => {
- const h = hostWith()
- const { log, ev } = events()
- const c = connectWatchClient({ socket: h.peerT, keys: h.keys, events: ev })
- await vi.waitFor(() => expect(h.isReady()).toBe(true))
- await vi.waitFor(() => expect(h.tunnel).toContain(TRUST_CONFIRM_JSON))
- expect(h.host.peerPublicKeyB64()).toBe(publicKeyToB64(h.keys.viewer.publicKey))
- expect(c.isOpen()).toBe(false)
- h.confirm()
- expect(log.open).toBe(1)
- expect(c.isOpen()).toBe(true)
- // The client's confirm is one the host's real gate accepts: both halves in, the gate opens.
- await vi.waitFor(() => expect(h.gateOpen()).toBe(true))
- })
-
- it('delivers ev frames and pty data only after it is open', async () => {
- const h = hostWith()
- const { log, ev } = events()
- connectWatchClient({ socket: h.peerT, keys: h.keys, events: ev })
- await vi.waitFor(() => expect(h.tunnel).toContain(TRUST_CONFIRM_JSON))
- h.host.sendTunnelText(JSON.stringify({ t: 'ev', channel: 'watch:meta', args: [{ v: 1 }] }))
- h.host.sendTunnelBinary(encodePtyData('s1', 'early'))
- expect(log.events).toEqual([])
- expect(log.pty).toEqual([])
- h.confirm()
- h.host.sendTunnelText(JSON.stringify({ t: 'ev', channel: 'watch:meta', args: [{ v: 1 }] }))
- h.host.sendTunnelBinary(encodePtyData('s1', 'late'))
- expect(log.events).toEqual([['watch:meta', [{ v: 1 }]]])
- expect(log.pty).toEqual([['s1', 'late']])
- })
-
- it('reports a denial and never opens', async () => {
- const h = hostWith()
- const { log, ev } = events()
- connectWatchClient({ socket: h.peerT, keys: h.keys, events: ev })
- await vi.waitFor(() => expect(h.tunnel).toContain(TRUST_CONFIRM_JSON))
- h.host.sendTunnelText(deniedFrame('removed'))
- expect(log.denied).toEqual(['removed'])
- expect(log.open).toBe(0)
- })
-
- it('cannot talk to a host whose key is not the link one', async () => {
- const real = deriveWatchLinkKeys(nacl.randomBytes(32))
- const impostor = hostWith({ keys: deriveWatchLinkKeys(nacl.randomBytes(32)) })
- const { socket, sent } = counting(impostor.peerT)
- const c = connectWatchClient({ socket, keys: real, events: events().ev })
- // The first sealed frame is the e2ee_auth box; the host has already judged it when send returns.
- await vi.waitFor(() => expect(sent.binary).toBe(1))
- expect(impostor.isReady()).toBe(false)
- expect(c.isOpen()).toBe(false)
- })
-
- it('sends a chat cast only while open', async () => {
- const h = hostWith()
- const c = connectWatchClient({ socket: h.peerT, keys: h.keys, events: events().ev })
- expect(c.sendChat('Ada', 'hi')).toBe(false)
- await vi.waitFor(() => expect(h.tunnel).toContain(TRUST_CONFIRM_JSON))
- h.confirm()
- expect(c.sendChat('Ada', 'hi')).toBe(true)
- expect(h.tunnel.at(-1)).toBe(JSON.stringify({ t: 'cast', method: 'watch:chat', args: [{ name: 'Ada', text: 'hi' }] }))
- })
-
- it('asks for read-back only while open, with the cursor only when one is given', async () => {
- const h = hostWith()
- const c = connectWatchClient({ socket: h.peerT, keys: h.keys, events: events().ev })
- expect(c.requestHistory()).toBe(false)
- await vi.waitFor(() => expect(h.tunnel).toContain(TRUST_CONFIRM_JSON))
- h.confirm()
- expect(c.requestHistory()).toBe(true)
- expect(h.tunnel.at(-1)).toBe('{"t":"cast","method":"watch:history","args":[{}]}')
- expect(c.requestHistory(4096)).toBe(true)
- expect(h.tunnel.at(-1)).toBe('{"t":"cast","method":"watch:history","args":[{"before":4096}]}')
- // A cursor the host would refuse never leaves the client.
- const n = h.tunnel.length
- expect(c.requestHistory(-1)).toBe(false)
- expect(c.requestHistory(1.5)).toBe(false)
- expect(h.tunnel).toHaveLength(n)
- })
-
- it('sends the control casts only while open, exactly as the host reads them', async () => {
- const h = hostWith()
- const { socket, sent } = counting(h.peerT)
- const c = connectWatchClient({ socket, keys: h.keys, events: events().ev })
- expect(c.unlock('Mert', 'pw')).toBe(false)
- expect(c.sendInput('ab')).toBe(false)
- expect(c.release()).toBe(false)
- await vi.waitFor(() => expect(h.tunnel).toContain(TRUST_CONFIRM_JSON))
- h.confirm()
- // Every one of them is a TAG_TUNNEL_TEXT frame: the host's onTunnel hands only those over as 'text'.
- expect(c.unlock('Mert', 'pw')).toBe(true)
- expect(h.tunnel.at(-1)).toBe('{"t":"cast","method":"watch:unlock","args":[{"name":"Mert","password":"pw"}]}')
- expect(c.sendInput('ab')).toBe(true)
- expect(h.tunnel.at(-1)).toBe('{"t":"cast","method":"watch:input","args":[{"data":"ab"}]}')
- expect(c.release()).toBe(true)
- expect(h.tunnel.at(-1)).toBe('{"t":"cast","method":"watch:release","args":[]}')
- // Over the cap (or empty, or not a string): refused here, and nothing leaves the client.
- const before = { tunnel: h.tunnel.length, binary: sent.binary }
- expect(c.sendInput('x'.repeat(INPUT_MAX + 1))).toBe(false)
- expect(c.sendInput('')).toBe(false)
- expect(c.sendInput(7 as never)).toBe(false)
- expect({ tunnel: h.tunnel.length, binary: sent.binary }).toEqual(before)
- expect(c.sendInput('x'.repeat(INPUT_MAX))).toBe(true)
- expect(h.tunnel).toHaveLength(before.tunnel + 1)
- })
-
- // Finding L3: once a meta on this connection offered an unlock key, the password is sealed to it and
- // never sent in the clear on this connection again.
- it('seals an unlock to the key the connection offered, and from then on never sends one in the clear', async () => {
- const h = hostWith()
- const c = connectWatchClient({ socket: h.peerT, keys: h.keys, events: events().ev })
- await vi.waitFor(() => expect(h.tunnel).toContain(TRUST_CONFIRM_JSON))
- h.confirm()
- // A key that is not one is ignored: still in the clear (what a host from before sealing gets).
- h.host.sendTunnelText(JSON.stringify({ t: 'ev', channel: 'watch:meta', args: [{ v: 1, unlockKey: 'AAAA' }] }))
- expect(c.unlock('Mert', 'correct-horse-77')).toBe(true)
- expect(h.tunnel.at(-1)).toBe('{"t":"cast","method":"watch:unlock","args":[{"name":"Mert","password":"correct-horse-77"}]}')
- const conn = nacl.box.keyPair()
- h.host.sendTunnelText(JSON.stringify({ t: 'ev', channel: 'watch:meta', args: [{ v: 1, unlockKey: bytesToB64(conn.publicKey) }] }))
- expect(c.unlock('Mert', 'correct-horse-77')).toBe(true)
- const sealed = h.tunnel.at(-1)!
- expect(sealed).not.toContain('correct-horse-77')
- const arg = (JSON.parse(sealed) as { method: string; args: unknown[] })
- expect(arg.method).toBe('watch:unlock')
- expect(openUnlock(arg.args[0], conn.secretKey)).toEqual({ name: 'Mert', password: 'correct-horse-77' })
- // A later meta without one (a rejoin's) does not bring the clear text back.
- h.host.sendTunnelText(JSON.stringify({ t: 'ev', channel: 'watch:meta', args: [{ v: 1 }] }))
- expect(c.unlock('Mert', 'correct-horse-77')).toBe(true)
- expect(h.tunnel.at(-1)).not.toContain('correct-horse-77')
- expect(openUnlock(JSON.parse(h.tunnel.at(-1)!).args[0], conn.secretKey)).toEqual({ name: 'Mert', password: 'correct-horse-77' })
- })
-
- it('keeps both directions flowing past seq 255', async () => {
- // A strictly increasing counter stays increasing under most encodings, so a short exchange
- // cannot tell the relay's little-endian seq from a byte-swapped copy. Past one byte it can:
- // a swapped 256 decodes below a swapped 255 and the receiver drops it as a replay.
- const h = hostWith()
- const { log, ev } = events()
- const c = connectWatchClient({ socket: h.peerT, keys: h.keys, events: ev })
- await vi.waitFor(() => expect(h.tunnel).toContain(TRUST_CONFIRM_JSON))
- h.confirm()
- for (let i = 0; i < 300; i++) h.host.sendTunnelBinary(encodePtyData('s1', String(i)))
- expect(log.pty).toHaveLength(300)
- expect(log.pty.at(-1)).toEqual(['s1', '299'])
- for (let i = 0; i < 300; i++) expect(c.sendChat('Ada', String(i))).toBe(true)
- expect(h.tunnel.at(-1)).toBe(JSON.stringify({ t: 'cast', method: 'watch:chat', args: [{ name: 'Ada', text: '299' }] }))
- expect(h.tunnel.filter((m) => m.includes('watch:chat'))).toHaveLength(300)
- })
-
- it('keeps the sealed stream in order across keepalives, and stops them when the socket closes', async () => {
- const h = hostWith()
- const { log, ev } = events()
- const timer: { tick?: () => void; ms?: number } = {}
- const stopped: unknown[] = []
- const { socket, sent } = counting(h.peerT)
- const c = connectWatchClient({
- socket, keys: h.keys, events: ev,
- setInterval: (fn, ms) => { timer.tick = fn; timer.ms = ms; return 'handle' },
- clearInterval: (handle) => { stopped.push(handle) }
- })
- await vi.waitFor(() => expect(h.tunnel).toContain(TRUST_CONFIRM_JSON))
- h.confirm()
- expect(timer.ms).toBe(25_000)
- // A keepalive is a real sealed frame and spends a seq number; the host must still accept what
- // follows it.
- const before = sent.binary
- timer.tick?.()
- timer.tick?.()
- expect(sent.binary - before).toBe(2)
- expect(c.sendChat('Ada', 'after keepalives')).toBe(true)
- expect(h.tunnel.at(-1)).toBe(JSON.stringify({ t: 'cast', method: 'watch:chat', args: [{ name: 'Ada', text: 'after keepalives' }] }))
- // The far side hangs up: the client reports it once, stops its keepalive, and stops sending.
- h.hostT.close()
- expect(log.closed).toBe(1)
- expect(stopped).toEqual(['handle'])
- expect(c.isOpen()).toBe(false)
- expect(c.sendChat('Ada', 'too late')).toBe(false)
- })
-
- it('does not report a close the caller asked for, and still stops its keepalive', async () => {
- const h = hostWith()
- const { log, ev } = events()
- const stopped: unknown[] = []
- const c = connectWatchClient({
- socket: h.peerT, keys: h.keys, events: ev,
- setInterval: () => 'handle',
- clearInterval: (handle) => { stopped.push(handle) }
- })
- await vi.waitFor(() => expect(h.tunnel).toContain(TRUST_CONFIRM_JSON))
- h.confirm()
- c.close()
- expect(h.hostClosed()).toBe(1)
- expect(log.closed).toBe(0)
- expect(stopped).toEqual(['handle'])
- expect(c.isOpen()).toBe(false)
- })
-
- it('closes, and says so once, when the session key cannot be derived', async () => {
- // WebCrypto refusing (a page served without a secure context has no crypto.subtle at all) used
- // to be an unhandled rejection that left the client in 'deriving' forever, with no event.
- const spy = vi.spyOn(globalThis.crypto.subtle, 'importKey').mockRejectedValueOnce(new Error('no HKDF here'))
- try {
- const h = hostWith()
- const { log, ev } = events()
- const c = connectWatchClient({ socket: h.peerT, keys: h.keys, events: ev })
- await vi.waitFor(() => expect(log.closed).toBe(1))
- expect(h.hostClosed()).toBe(1)
- expect(h.isReady()).toBe(false)
- expect(c.isOpen()).toBe(false)
- await new Promise((r) => setTimeout(r, 0))
- expect(log.closed).toBe(1)
- } finally {
- spy.mockRestore()
- }
- })
-
- it('opens only after its own confirm went out, even when the host confirms inside onReady', async () => {
- // A pinned host confirms synchronously the moment it is ready, before the client's own confirm
- // (deferred past the host's send) has left. Opening then would open a session whose host gate
- // has not seen the viewer's half.
- const h = hostWith({ autoApprove: true })
- let confirmOutAtOpen: boolean | null = null
- const { ev } = events()
- connectWatchClient({
- socket: h.peerT, keys: h.keys,
- events: { ...ev, onOpen: () => { confirmOutAtOpen = h.tunnel.includes(TRUST_CONFIRM_JSON) } }
- })
- await vi.waitFor(() => expect(confirmOutAtOpen).not.toBeNull())
- expect(confirmOutAtOpen).toBe(true)
- await vi.waitFor(() => expect(h.gateOpen()).toBe(true))
- })
-
- it('warns once, and drops, a socket message that is neither text nor bytes', async () => {
- // A browser WebSocket left at its default binaryType delivers Blobs; the adapter owes bytes.
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
- try {
- const h = hostWith()
- const { log, ev } = events()
- const c = connectWatchClient({ socket: h.peerT, keys: h.keys, events: ev })
- await vi.waitFor(() => expect(h.tunnel).toContain(TRUST_CONFIRM_JSON))
- h.confirm()
- const deliver = h.hostT.send as (d: unknown) => void
- deliver(new Blob(['x']))
- deliver({ not: 'bytes' })
- expect(warn).toHaveBeenCalledTimes(1)
- expect(String(warn.mock.calls[0][0])).toContain('arraybuffer')
- expect(c.isOpen()).toBe(true)
- expect(log.closed).toBe(0)
- } finally {
- warn.mockRestore()
- }
- })
-})
diff --git a/src/core/watch-link/control-input.test.ts b/src/core/watch-link/control-input.test.ts
deleted file mode 100644
index e9d655087..000000000
--- a/src/core/watch-link/control-input.test.ts
+++ /dev/null
@@ -1,274 +0,0 @@
-import { describe, it, expect } from 'vitest'
-import type { ControlInputChunk } from '../pane-input'
-import {
- PASTE_END,
- PASTE_MAX,
- PASTE_START,
- TYPING_WINDOW_MS,
- createInputSplitter,
- createTypingTracker,
- type InputSplitter
-} from './control-input'
-
-const keys = (data: string): ControlInputChunk => ({ kind: 'keys', data })
-const paste = (text: string): ControlInputChunk => ({ kind: 'paste', text })
-const ESC = '\x1b'
-
-/** Adjacent keys chunks joined: two pushes of plain keys are two chunks, one push is one, and what
- * reaches the pane is the same bytes either way. Only a paste boundary separates keys. */
-function merged(chunks: ControlInputChunk[]): ControlInputChunk[] {
- const out: ControlInputChunk[] = []
- for (const c of chunks) {
- const last = out.at(-1)
- if (c.kind === 'keys' && last?.kind === 'keys') out[out.length - 1] = keys(last.data + c.data)
- else out.push(c)
- }
- return out
-}
-/** Push every part, then drain what is still held (the host's flush). */
-function run(s: InputSplitter, ...parts: string[]): ControlInputChunk[] {
- const out: ControlInputChunk[] = []
- for (const p of parts) out.push(...s.push(p))
- out.push(...s.drain())
- return out
-}
-
-describe('createInputSplitter', () => {
- it('plain typing is one keys chunk per push, byte for byte (control bytes and escapes included)', () => {
- const s = createInputSplitter()
- expect(s.push('ls -la\r')).toEqual([keys('ls -la\r')])
- expect(s.push('\x03')).toEqual([keys('\x03')])
- expect(s.push(`${ESC}[A${ESC}OB\x7f`)).toEqual([keys(`${ESC}[A${ESC}OB\x7f`)])
- expect(s.push('çé漢🙂')).toEqual([keys('çé漢🙂')])
- })
-
- it('a paste in one push is one paste chunk; keys around it stay keys, in order', () => {
- const s = createInputSplitter()
- expect(s.push(`${PASTE_START}echo hi\nls${PASTE_END}`)).toEqual([paste('echo hi\nls')])
- expect(s.push(`ab${PASTE_START}x${ESC}[Ay${PASTE_END}\r`)).toEqual([keys('ab'), paste(`x${ESC}[Ay`), keys('\r')])
- // Two pastes back to back stay two pastes.
- expect(s.push(`${PASTE_START}1${PASTE_END}${PASTE_START}2${PASTE_END}`)).toEqual([paste('1'), paste('2')])
- })
-
- it('an empty paste yields nothing (there is nothing to deliver)', () => {
- const s = createInputSplitter()
- expect(s.push(`${PASTE_START}${PASTE_END}`)).toEqual([])
- expect(s.push('a')).toEqual([keys('a')])
- })
-
- it('markers split at EVERY boundary across two pushes give the same chunks as one push', () => {
- const input = `ab${PASTE_START}one\ntwo${PASTE_END}cd${PASTE_START}x${PASTE_END}`
- const want = [keys('ab'), paste('one\ntwo'), keys('cd'), paste('x')]
- expect(run(createInputSplitter(), input)).toEqual(want)
- for (let i = 1; i < input.length; i++) {
- const got = run(createInputSplitter(), input.slice(0, i), input.slice(i))
- expect(merged(got), `split at ${i}`).toEqual(want)
- }
- })
-
- it('a marker split over three pushes is still a marker', () => {
- const s = createInputSplitter()
- expect(s.push(`${ESC}[2`)).toEqual([])
- expect(s.push('00')).toEqual([])
- expect(s.push(`~hi${ESC}`)).toEqual([])
- expect(s.push('[201~')).toEqual([paste('hi')])
- })
-
- it('a held marker prefix that turns out not to be a marker comes out as keys', () => {
- const s = createInputSplitter()
- expect(s.push(`a${ESC}[20`)).toEqual([keys('a')])
- expect(s.push('x')).toEqual([keys(`${ESC}[20x`)])
- // F9 and Insert start like the marker and are not it.
- expect(s.push(`${ESC}[20~`)).toEqual([keys(`${ESC}[20~`)])
- expect(s.push(`${ESC}[2~`)).toEqual([keys(`${ESC}[2~`)])
- })
-
- it('a lone Esc (a prefix of the paste marker) is held, and drain() hands it over as keys', () => {
- const s = createInputSplitter()
- expect(s.push(ESC)).toEqual([])
- expect(s.drain()).toEqual([keys(ESC)])
- expect(s.drain()).toEqual([])
- // Drained, it is gone: the next push does not repeat it.
- expect(s.push('[A')).toEqual([keys('[A')])
- })
-
- it('drain() hands over only what a key press can end on (Esc, Alt+[); a longer marker prefix waits for the next input', () => {
- const s = createInputSplitter()
- expect(s.push(`${ESC}[`)).toEqual([])
- expect(s.drain()).toEqual([keys(`${ESC}[`)])
- for (const prefix of [`${ESC}[2`, `${ESC}[20`, `${ESC}[200`]) {
- expect(s.push(`a${prefix}`)).toEqual([keys('a')])
- expect(s.drain()).toEqual([])
- // The rest of the marker, a whole batch later: still a paste.
- expect(s.push(`${PASTE_START.slice(prefix.length)}hi${PASTE_END}`)).toEqual([paste('hi')])
- }
- // A held prefix that the next input does not complete comes out then, as keys.
- expect(s.push(`${ESC}[20`)).toEqual([])
- expect(s.drain()).toEqual([])
- expect(s.push('x')).toEqual([keys(`${ESC}[20x`)])
- })
-
- it('drain() never hands over a held high surrogate (no key press ends on half a character)', () => {
- const s = createInputSplitter()
- expect(s.push('a\ud83d')).toEqual([keys('a')])
- expect(s.drain()).toEqual([])
- expect(s.push('\ude42')).toEqual([keys('\ud83d\ude42')])
- })
-
- it('pasteOpen() tells whether a paste is waiting for its end', () => {
- const s = createInputSplitter()
- expect(s.pasteOpen()).toBe(false)
- s.push(`${PASTE_START}x`)
- expect(s.pasteOpen()).toBe(true)
- s.push(PASTE_END)
- expect(s.pasteOpen()).toBe(false)
- s.push(`${PASTE_START}x`)
- s.reset()
- expect(s.pasteOpen()).toBe(false)
- })
-
- it('drain() inside a paste hands over nothing: an open paste waits for its end', () => {
- const s = createInputSplitter()
- expect(s.push(`${PASTE_START}abc${ESC}[20`)).toEqual([])
- expect(s.drain()).toEqual([])
- // The held part completes the end marker.
- expect(s.push('1~z')).toEqual([paste('abc'), keys('z')])
- // A held part that does not end it is paste text.
- expect(s.push(`${PASTE_START}d${ESC}[20`)).toEqual([])
- expect(s.drain()).toEqual([])
- expect(s.push(`9${PASTE_END}`)).toEqual([paste(`d${ESC}[209`)])
- })
-
- it('a PASTE_END outside a paste is keys, passed through as typed', () => {
- const s = createInputSplitter()
- expect(s.push(`a${PASTE_END}b`)).toEqual([keys(`a${PASTE_END}b`)])
- })
-
- it('a PASTE_START inside a paste is paste text', () => {
- const s = createInputSplitter()
- expect(s.push(`${PASTE_START}a${PASTE_START}b${PASTE_END}`)).toEqual([paste(`a${PASTE_START}b`)])
- })
-
- it('a high surrogate at the end of a push waits for its pair (an emoji split across two casts)', () => {
- const s = createInputSplitter()
- const emoji = '🙂'
- expect(s.push(`a${emoji[0]}`)).toEqual([keys('a')])
- expect(s.push(`${emoji[1]}b`)).toEqual([keys(`${emoji}b`)])
- })
-
- it('a paste over PASTE_MAX is cut to PASTE_MAX; the rest up to its end is discarded, and typing goes on', () => {
- const s = createInputSplitter()
- const half = 'x'.repeat(PASTE_MAX / 2 + 10)
- expect(s.push(PASTE_START + half)).toEqual([])
- expect(s.push(half)).toEqual([])
- expect(s.push('y'.repeat(1000))).toEqual([])
- const out = s.push(`${PASTE_END}ls\r`)
- expect(out).toHaveLength(2)
- expect(out[0].kind).toBe('paste')
- expect((out[0] as { text: string }).text).toBe('x'.repeat(PASTE_MAX))
- expect(out[1]).toEqual(keys('ls\r'))
- })
-
- it('a paste cut at PASTE_MAX never ends on half a surrogate pair', () => {
- const s = createInputSplitter()
- const text = 'a'.repeat(PASTE_MAX - 1) + '🙂🙂'
- const out = s.push(`${PASTE_START}${text}${PASTE_END}`)
- expect(out).toEqual([paste('a'.repeat(PASTE_MAX - 1))])
- })
-
- it('reset() drops an open paste and a held prefix', () => {
- const s = createInputSplitter()
- expect(s.push(`${PASTE_START}secret`)).toEqual([])
- s.reset()
- expect(s.push(`more${PASTE_END}`)).toEqual([keys(`more${PASTE_END}`)])
- expect(s.push(ESC)).toEqual([])
- s.reset()
- expect(s.drain()).toEqual([])
- })
-
- it('discard() keeps the framing: a paste any dropped part of which was dropped is discarded whole, and the next keys come through', () => {
- const s = createInputSplitter()
- expect(s.push(`${PASTE_START}head`)).toEqual([])
- s.discard('middle') // over budget: dropped
- expect(s.push(`tail${PASTE_END}ls\r`)).toEqual([keys('ls\r')])
- // A paste whose END was dropped: closed by the discard, nothing left open.
- expect(s.push(`${PASTE_START}a`)).toEqual([])
- s.discard(`b${PASTE_END}`)
- expect(s.push('x')).toEqual([keys('x')])
- // A paste whose START was dropped: the rest is not typed as keys either.
- s.discard(`${PASTE_START}evil\n`)
- expect(s.push(`rm -rf /\n${PASTE_END}y`)).toEqual([keys('y')])
- })
-
- it('discard() keeps a start-marker prefix it ends on: completed by the next input, that paste is discarded whole', () => {
- const s = createInputSplitter()
- for (const prefix of [ESC, `${ESC}[`, `${ESC}[2`, `${ESC}[20`, `${ESC}[200`]) {
- s.discard(`dropped${prefix}`)
- expect(s.drain()).toEqual([]) // a dropped byte is never handed over
- expect(s.push(`${PASTE_START.slice(prefix.length)}rm -rf ~\n${PASTE_END}ok`)).toEqual([keys('ok')])
- }
- // Not completed: the dropped prefix is dropped, the rest is keys.
- s.discard(`dropped${ESC}[2`)
- expect(s.push('x')).toEqual([keys('x')])
- // Extended a character at a time by tiny casts: still the dropped paste's start.
- s.discard(`dropped${ESC}`)
- expect(s.push('[')).toEqual([])
- expect(s.drain()).toEqual([])
- expect(s.push('2')).toEqual([])
- expect(s.push(`00~evil${PASTE_END}ok`)).toEqual([keys('ok')])
- })
-
- it('discard() drops keys, and a held prefix with them', () => {
- const s = createInputSplitter()
- expect(s.push(`a${ESC}`)).toEqual([keys('a')])
- s.discard('dropped')
- expect(s.drain()).toEqual([])
- expect(s.push('b')).toEqual([keys('b')])
- // A dropped cast that ENDS in a prefix holds nothing either.
- s.discard(`dropped${ESC}`)
- expect(s.drain()).toEqual([])
- expect(s.push('[A')).toEqual([keys('[A')])
- })
-})
-
-describe('createTypingTracker', () => {
- it('names who typed in the window, most recent first, one entry per viewer', () => {
- const t = createTypingTracker()
- t.note('v1', 'Ada', 1000)
- t.note('v2', 'Bob', 1500)
- t.note('v1', 'Ada', 2000)
- expect(t.names(2100)).toEqual(['Ada', 'Bob'])
- t.note('v2', 'Bob', 2200)
- expect(t.names(2300)).toEqual(['Bob', 'Ada'])
- expect(t.typing('v1', 2300)).toBe(true)
- expect(t.typing('v3', 2300)).toBe(false)
- })
-
- it('two viewers under one name are named once', () => {
- const t = createTypingTracker()
- t.note('v1', 'Ada', 1000)
- t.note('v2', 'Ada', 1100)
- expect(t.names(1200)).toEqual(['Ada'])
- })
-
- it('a name outside the window disappears', () => {
- const t = createTypingTracker()
- t.note('v1', 'Ada', 1000)
- t.note('v2', 'Bob', 3000)
- expect(t.names(1000 + TYPING_WINDOW_MS - 1)).toEqual(['Bob', 'Ada'])
- expect(t.names(1000 + TYPING_WINDOW_MS)).toEqual(['Bob'])
- expect(t.typing('v1', 1000 + TYPING_WINDOW_MS)).toBe(false)
- expect(t.names(3000 + TYPING_WINDOW_MS)).toEqual([])
- })
-
- it('drop removes a viewer at once', () => {
- const t = createTypingTracker()
- t.note('v1', 'Ada', 1000)
- t.note('v2', 'Bob', 1000)
- t.drop('v1')
- expect(t.names(1001)).toEqual(['Bob'])
- expect(t.typing('v1', 1001)).toBe(false)
- t.drop('nobody')
- expect(t.names(1001)).toEqual(['Bob'])
- })
-})
diff --git a/src/core/watch-link/control-input.ts b/src/core/watch-link/control-input.ts
deleted file mode 100644
index 3ef813910..000000000
--- a/src/core/watch-link/control-input.ts
+++ /dev/null
@@ -1,238 +0,0 @@
-// A live link controller's input before it reaches the pane: which bytes are KEYS (typed byte for
-// byte, pane-input.ts's keys plan) and which are a PASTE (text tmux frames per the pane's own
-// bracketed-paste state, `paste-buffer -p`), and who typed in the last few seconds. Pure: no timers,
-// no I/O — the link host owns both (link-host.ts).
-//
-// THE SPLITTER. While controlling, the viewer page holds its xterm in bracketed-paste mode, so every
-// paste arrives framed `ESC[200~ … ESC[201~` and the host can tell a paste from typing. Everything
-// outside a frame is keys, which is also where every control byte belongs: tmux 3.7 passes paste
-// buffer content through vis(3), so a Ctrl-C inside a paste would arrive as the text `^C`
-// (pane-input.ts, measured). The splitter keeps state across pushes because the page splits a long
-// input into casts of at most INPUT_MAX units, so a marker (or a surrogate pair) can straddle two.
-//
-// Four rules beyond "find the markers":
-// - A trailing PREFIX of the marker being looked for is held until the next push. A lone Esc is such
-// a prefix, and so is Alt+[ (`ESC [`) — the only two a single key press can end on — so `drain()`
-// hands exactly those over as keys, and the host calls it when it flushes a batch: an Esc reaches
-// the pane within one batch instead of waiting for the next key (an agent CLI's "Esc to interrupt"
-// must not need a second key). A longer prefix (`ESC [ 2`, `ESC [ 2 0`, `ESC [ 2 0 0`) is no key: it
-// stays held for the next input, so a start marker split across two casts with a batch flush in
-// between is still a paste. Residual: one split right after `ESC` or `ESC [` that waits longer than
-// a batch interval for its second cast is typed as keys (the same bytes, unframed by tmux).
-// - A trailing high surrogate outside a paste is held the same way (and never drained: no key ends on
-// half a character), so an emoji split across two casts is not typed as two replacement characters.
-// - A paste is cut at PASTE_MAX units (never between the halves of a surrogate pair); the rest up to
-// its end is discarded, and the splitter keeps looking for the end, so typing after it is keys.
-// - Input the host DROPPED (over budget, no session to type into) is fed to `discard()`, which keeps
-// the framing and delivers nothing: a paste that any dropped part belonged to is discarded WHOLE.
-// Without it a paste whose end marker was dropped would stay open for good and swallow every key
-// typed after it, and a paste whose start was dropped would have its text typed as KEYS — each
-// newline a command run in the shell. A dropped input that ENDS in a start-marker prefix keeps that
-// prefix, marked dropped: completed by the next input it opens a paste that is discarded whole;
-// not completed, it is dropped (never typed, never drained).
-import type { ControlInputChunk } from '../pane-input'
-
-export const PASTE_START = '\x1b[200~'
-export const PASTE_END = '\x1b[201~'
-/** The longest paste delivered, in UTF-16 units; the rest of a longer one is discarded. */
-export const PASTE_MAX = 256 * 1024
-/** A name is in the typing set for this long after that viewer's last accepted input. */
-export const TYPING_WINDOW_MS = 4000
-
-export interface InputSplitter {
- /** Accepted input: the chunks it completes, in order. Consecutive keys in one push are one chunk. */
- push(data: string): ControlInputChunk[]
- /** Input that was dropped: tracked for framing, never delivered (see the header). */
- discard(data: string): void
- /** A held Esc or Alt+[ (`ESC [`) as keys — what a key press can end on. A longer marker prefix, a
- * held surrogate, a prefix kept from dropped input and an open paste all keep waiting. */
- drain(): ControlInputChunk[]
- /** A paste is open, waiting for its end. */
- pasteOpen(): boolean
- /** Control lost or the connection ended: forget an open paste and anything held. */
- reset(): void
-}
-
-/** The held prefixes `drain()` hands over: a key press can end on these, never on a longer one. */
-const DRAINABLE = new Set(['\x1b', '\x1b['])
-
-const isHighSurrogate = (code: number): boolean => code >= 0xd800 && code <= 0xdbff
-
-/** The length of the longest proper prefix of `marker` that `s` ends with. */
-function heldMarkerPrefix(s: string, marker: string): number {
- for (let k = Math.min(marker.length - 1, s.length); k > 0; k--) {
- if (s.endsWith(marker.slice(0, k))) return k
- }
- return 0
-}
-
-export function createInputSplitter(): InputSplitter {
- let inPaste = false
- /** The tail of the last push that may combine with the next one. */
- let held = ''
- /** `held` came from dropped input (a start-marker prefix `discard` kept): never keys. */
- let heldDropped = false
- let parts: string[] = []
- let pasteLen = 0
- /** The open paste reached PASTE_MAX: nothing more is appended. */
- let full = false
- /** Part of the open paste was dropped: it is discarded at its end. */
- let poisoned = false
-
- function openPaste(): void {
- inPaste = true
- parts = []
- pasteLen = 0
- full = false
- poisoned = false
- }
- function appendPaste(s: string): void {
- if (full || poisoned || s.length === 0) return
- const room = PASTE_MAX - pasteLen
- if (s.length <= room) {
- parts.push(s)
- pasteLen += s.length
- return
- }
- parts.push(s.slice(0, room))
- pasteLen = PASTE_MAX
- full = true
- }
- /** The paste just closed: its text, or null when there is nothing to deliver. */
- function closePaste(): string | null {
- inPaste = false
- let text = poisoned ? '' : parts.join('')
- parts = []
- pasteLen = 0
- // A cut that fell between the halves of a pair leaves a lone high surrogate: drop it.
- if (full && text.length > 0 && isHighSurrogate(text.charCodeAt(text.length - 1))) text = text.slice(0, -1)
- return text.length > 0 ? text : null
- }
-
- /** One scan over `held + data`. `deliver` false: track the framing, deliver nothing. */
- function scan(data: string, deliver: boolean): ControlInputChunk[] {
- let s = held + data
- // How many leading characters of `s` were dropped input (a prefix `discard` kept, outside a paste).
- let droppedHead = heldDropped ? held.length : 0
- held = ''
- heldDropped = false
- const out: ControlInputChunk[] = []
- let keys = ''
- const flushKeys = (): void => {
- if (keys.length > 0 && deliver) out.push({ kind: 'keys', data: keys })
- keys = ''
- }
- if (!deliver && inPaste) poisoned = true
- while (s.length > 0) {
- if (!inPaste) {
- const i = s.indexOf(PASTE_START)
- if (droppedHead > 0) {
- const head = droppedHead
- droppedHead = 0
- if (i >= 0 && i < head) {
- // A start marker that began in dropped input: the paste it opens is discarded whole.
- openPaste()
- poisoned = true
- s = s.slice(i + PASTE_START.length)
- continue
- }
- const h = heldMarkerPrefix(s, PASTE_START)
- if (i < 0 && s.length - h < head) {
- // The dropped prefix grew and is still only a prefix: held, still dropped.
- held = s.slice(s.length - h)
- heldDropped = true
- break
- }
- s = s.slice(head) // dropped bytes are never keys
- continue
- }
- if (i < 0) {
- let h = heldMarkerPrefix(s, PASTE_START)
- // A surrogate is held for accepted input only: dropped input keeps only a marker prefix.
- if (deliver && h === 0 && isHighSurrogate(s.charCodeAt(s.length - 1))) h = 1
- keys += s.slice(0, s.length - h)
- held = s.slice(s.length - h)
- heldDropped = !deliver && h > 0
- break
- }
- keys += s.slice(0, i)
- flushKeys()
- openPaste()
- if (!deliver) poisoned = true
- s = s.slice(i + PASTE_START.length)
- } else {
- const i = s.indexOf(PASTE_END)
- if (i < 0) {
- const h = heldMarkerPrefix(s, PASTE_END)
- appendPaste(s.slice(0, s.length - h))
- // Inside a paste the held part is paste text or the end marker: keep it either way.
- held = s.slice(s.length - h)
- break
- }
- appendPaste(s.slice(0, i))
- const text = closePaste()
- if (text !== null && deliver) out.push({ kind: 'paste', text })
- s = s.slice(i + PASTE_END.length)
- }
- }
- flushKeys()
- return out
- }
-
- return {
- push: (data) => scan(data, true),
- discard(data) {
- scan(data, false)
- },
- drain() {
- if (inPaste || heldDropped || !DRAINABLE.has(held)) return []
- const data = held
- held = ''
- return [{ kind: 'keys', data }]
- },
- pasteOpen: () => inPaste,
- reset() {
- inPaste = false
- held = ''
- heldDropped = false
- parts = []
- pasteLen = 0
- full = false
- poisoned = false
- }
- }
-}
-
-export interface TypingTracker {
- /** `viewerId` (named `name`) gave accepted input at `at`. */
- note(viewerId: string, name: string, at: number): void
- /** The viewer stopped controlling or left: out of the set at once. */
- drop(viewerId: string): void
- /** Names with input in the TYPING_WINDOW_MS before `at`, most recent first, each name once. */
- names(at: number): string[]
- typing(viewerId: string, at: number): boolean
-}
-
-export function createTypingTracker(): TypingTracker {
- // Insertion order is recency: `note` re-inserts, so the last entry is the most recent typist.
- const last = new Map<string, { name: string; at: number }>()
- const recent = (e: { at: number }, at: number): boolean => at - e.at < TYPING_WINDOW_MS
- return {
- note(viewerId, name, at) {
- last.delete(viewerId)
- last.set(viewerId, { name, at })
- },
- drop(viewerId) {
- last.delete(viewerId)
- },
- names(at) {
- const out: string[] = []
- for (const e of [...last.values()].reverse()) if (recent(e, at) && !out.includes(e.name)) out.push(e.name)
- return out
- },
- typing(viewerId, at) {
- const e = last.get(viewerId)
- return !!e && recent(e, at)
- }
- }
-}
diff --git a/src/core/watch-link/history.test.ts b/src/core/watch-link/history.test.ts
deleted file mode 100644
index aee8d5d72..000000000
--- a/src/core/watch-link/history.test.ts
+++ /dev/null
@@ -1,94 +0,0 @@
-import { describe, expect, it } from 'vitest'
-import type { ChatMessage, ChatTranscriptResult } from '../../shared/types'
-import { HISTORY_MESSAGES_MAX } from '../../shared/watch-link/protocol'
-import { historyPageFrom } from './history'
-
-const SINCE = 10_000
-const text = (role: 'user' | 'assistant', at: number | undefined, t: string, key?: number): ChatMessage => ({
- role,
- parts: [{ kind: 'text', text: t }],
- ...(at === undefined ? {} : { at }),
- ...(key === undefined ? {} : { key })
-})
-const read = (messages: ChatMessage[], olderCursor: number | null = null, found = true): { kind: 'page'; result: ChatTranscriptResult } => ({
- kind: 'page',
- result: { messages, found, olderCursor, unmatchedResults: [] }
-})
-
-describe('historyPageFrom', () => {
- it('keeps only what was written at or after the link was created', () => {
- const p = historyPageFrom(read([text('user', 9_999, 'before'), text('user', 10_000, 'at'), text('assistant', 12_000, 'after')], 400), SINCE, null)
- expect(p.status).toBe('ok')
- expect(p.messages.map((m) => (m.parts[0] as { text: string }).text)).toEqual(['at', 'after'])
- // The window reached the link's creation: no paging past it, whatever the transcript says.
- expect(p.olderCursor).toBeNull()
- expect(p.start).toBe('shared')
- })
-
- it('pages on while the window is entirely after the link', () => {
- const p = historyPageFrom(read([text('user', 11_000, 'a'), text('assistant', 12_000, 'b')], 4096), SINCE, null)
- expect(p.olderCursor).toBe(4096)
- expect(p.start).toBeNull()
- })
-
- it('says the conversation started when the transcript has nothing older', () => {
- const p = historyPageFrom(read([text('user', 11_000, 'a')], null), SINCE, 9000)
- expect(p).toMatchObject({ before: 9000, olderCursor: null, start: 'conversation' })
- })
-
- it('never sends a message with no time, and calls a wholly untimed conversation untimed', () => {
- expect(historyPageFrom(read([text('user', undefined, 'x'), text('assistant', 11_000, 'y')]), SINCE, null).messages).toHaveLength(1)
- const p = historyPageFrom(read([text('user', undefined, 'x'), text('assistant', undefined, 'y')]), SINCE, null)
- expect(p.status).toBe('untimed')
- expect(p.messages).toEqual([])
- })
-
- it('sends tool names and arguments, a plan body, but never a result or thinking', () => {
- const m: ChatMessage = {
- role: 'assistant',
- at: 11_000,
- parts: [
- { kind: 'thinking', text: 'secret reasoning' },
- { kind: 'tool', name: 'Bash', arg: 'cat .env', result: 'TOKEN=abc' },
- { kind: 'tool', name: 'ExitPlanMode', arg: '', body: '## Plan\n1. do it' }
- ]
- }
- const p = historyPageFrom(read([m]), SINCE, null)
- expect(p.messages[0].parts).toEqual([
- { kind: 'tool', name: 'Bash', arg: 'cat .env' },
- { kind: 'tool', name: 'ExitPlanMode', arg: '' },
- { kind: 'text', text: '## Plan\n1. do it' }
- ])
- expect(JSON.stringify(p)).not.toContain('TOKEN=abc')
- expect(JSON.stringify(p)).not.toContain('secret reasoning')
- })
-
- it('a newest page with no transcript is an empty conversation; an older one is a failed read', () => {
- expect(historyPageFrom(read([], null, false), SINCE, null)).toMatchObject({ status: 'ok', messages: [], start: 'conversation' })
- expect(historyPageFrom(read([], null, false), SINCE, 500).status).toBe('error')
- })
-
- it('reports a failed read and a node with no conversation', () => {
- expect(historyPageFrom(null, SINCE, null).status).toBe('error')
- expect(historyPageFrom({ kind: 'unsupported' }, SINCE, null).status).toBe('unsupported')
- })
-
- it('past the message cap, pages on from the oldest message kept', () => {
- const many = Array.from({ length: HISTORY_MESSAGES_MAX + 3 }, (_, i) => text('assistant', 11_000 + i, `m${i}`, 1000 + i * 10))
- const p = historyPageFrom(read(many, 900), SINCE, null)
- expect(p.messages).toHaveLength(HISTORY_MESSAGES_MAX)
- expect((p.messages[0].parts[0] as { text: string }).text).toBe('m3')
- expect(p.olderCursor).toBe(1030)
- })
-
- it('past the message cap on a reader that does not page, says it was cut', () => {
- const many = Array.from({ length: HISTORY_MESSAGES_MAX + 1 }, (_, i) => text('assistant', 11_000 + i, `m${i}`))
- const p = historyPageFrom(read(many, null), SINCE, null)
- expect(p).toMatchObject({ olderCursor: null, start: 'cut' })
- })
-
- it('cleans what it sends: no escape sequence reaches the page', () => {
- const p = historyPageFrom(read([text('assistant', 11_000, 'ok\x1b]52;c;Zm9v\x07 done')]), SINCE, null)
- expect((p.messages[0].parts[0] as { text: string }).text).toBe('ok]52;c;Zm9v done')
- })
-})
diff --git a/src/core/watch-link/history.ts b/src/core/watch-link/history.ts
deleted file mode 100644
index 89e73a431..000000000
--- a/src/core/watch-link/history.ts
+++ /dev/null
@@ -1,91 +0,0 @@
-// A live link's read-back (`watch:history`, src/shared/watch-link/protocol.ts): one page of the
-// watched agent's conversation, cut to what was written after the link was created.
-//
-// Why a conversation and not the terminal's history: the viewer's stream is a tmux CLIENT, which paints
-// on the alternate screen, so the viewer's emulator never has lines to scroll; a keyframe is the
-// visible screen and never history (docs/live-links.md → Keyframes). And on an agent node the terminal's
-// history would not help anyway: Claude's fullscreen TUI keeps its conversation on the pane's alternate
-// screen, where tmux records no history at all.
-//
-// The read itself is the ⌘M panel's (`readChatTranscript` behind the phone's `chat.page`, wired by the
-// desktop shell); this module only turns its answer into a page, and holds the cutoff:
-// - a message older than the link, or with no time, never reaches a page (nothing proves it came
-// after the link);
-// - only text and tool names/arguments travel: tool results and thinking never do;
-// - paging stops at the link's creation even when the transcript goes further back.
-import type { ChatMessage, ChatTranscriptResult } from '../../shared/types'
-import {
- HISTORY_MESSAGES_MAX,
- readHistoryPage,
- type WatchHistoryMessage,
- type WatchHistoryPage,
- type WatchHistoryPart,
- type WatchHistoryStart,
- type WatchHistoryStatus
-} from '../../shared/watch-link/protocol'
-
-/** How large a transcript window one page reads (the ⌘M panel's older-page size). */
-export const HISTORY_READ_BYTES = 512 * 1024
-
-/** What the shell's reader answered: a transcript page, or a node with no conversation to read. A
- * failed read is a rejection, never an empty page. */
-export type HistoryRead = { kind: 'page'; result: ChatTranscriptResult } | { kind: 'unsupported' }
-
-function partsOf(m: ChatMessage): WatchHistoryPart[] {
- const out: WatchHistoryPart[] = []
- for (const p of m.parts) {
- if (p.kind === 'text') out.push({ kind: 'text', text: p.text })
- else if (p.kind === 'tool') {
- out.push({ kind: 'tool', name: p.name, arg: p.arg })
- // A plan or a question is read in full on the screen (it is what the card shows); its result is not.
- if (p.body) out.push({ kind: 'text', text: p.body })
- }
- // thinking: never
- }
- return out
-}
-
-const empty = (before: number | null, since: number, status: WatchHistoryStatus): WatchHistoryPage => ({
- before,
- status,
- since,
- messages: [],
- olderCursor: null,
- start: status === 'ok' ? 'conversation' : null
-})
-
-/** The page for one read. `since` is the link's `createdAt`; `before` the cursor the viewer asked for.
- * A null `read` is a failed read. */
-export function historyPageFrom(read: HistoryRead | null, since: number, before: number | null): WatchHistoryPage {
- if (read === null) return empty(before, since, 'error')
- if (read.kind === 'unsupported') return empty(before, since, 'unsupported')
- const { result } = read
- if (!result.found) {
- // The NEWEST page found nothing: no conversation was written yet. An OLDER page that finds nothing
- // is a failed read (the transcript reader's own contract), never "the start".
- return before === null ? empty(before, since, 'ok') : empty(before, since, 'error')
- }
- const all = result.messages
- const timed = all.filter((m) => typeof m.at === 'number' && Number.isFinite(m.at))
- if (all.length > 0 && timed.length === 0) return empty(before, since, 'untimed')
- const reachedShare = timed.some((m) => (m.at as number) < since)
- let kept: ChatMessage[] = timed.filter((m) => (m.at as number) >= since)
- let olderCursor: number | null = reachedShare ? null : typeof result.olderCursor === 'number' ? result.olderCursor : null
- let start: WatchHistoryStart | null = olderCursor !== null ? null : reachedShare ? 'shared' : 'conversation'
- if (kept.length > HISTORY_MESSAGES_MAX) {
- kept = kept.slice(-HISTORY_MESSAGES_MAX)
- // Page on from the oldest message kept when its line's offset is known; a reader that does not
- // page cannot go back further.
- const key = kept[0].key
- if (typeof key === 'number' && Number.isInteger(key) && key >= 0) {
- olderCursor = key
- start = null
- } else {
- olderCursor = null
- start = 'cut'
- }
- }
- const messages: WatchHistoryMessage[] = kept.map((m) => ({ role: m.role, at: m.at as number, parts: partsOf(m) }))
- // Through the protocol's own reader: the same cleaning and bounds the viewer applies.
- return readHistoryPage({ before, status: 'ok', since, messages, olderCursor, start }) ?? empty(before, since, 'error')
-}
diff --git a/src/core/watch-link/link-host.test.ts b/src/core/watch-link/link-host.test.ts
deleted file mode 100644
index ffbd13e70..000000000
--- a/src/core/watch-link/link-host.test.ts
+++ /dev/null
@@ -1,2819 +0,0 @@
-// The link host against the REAL relay host, the REAL hosted scheduler and the REAL browser client
-// (src/shared/watch-link/client.ts) over an in-process transport. Only the pty and the clients registry
-// are fakes, and they record every call, so "nothing a viewer sent reached the pty" is checkable.
-//
-// Timing-sensitive cases run on a MANUAL clock injected as the link host's (and so the scheduler's)
-// setTimeout/now; the handshake itself is real async crypto, awaited with vi.waitFor on real time.
-import { describe, it, expect, vi, afterEach, beforeAll } from 'vitest'
-import nacl from 'tweetnacl'
-import { transportPair } from '../relay/transport-pair'
-import { connectRelay, type RelayTransport } from '../relay/relay-socket'
-import { publicKeyToB64 } from '../relay/e2ee'
-import { encodePtyData, parseRpcMessage } from '../../shared/rpc'
-import { IPC } from '../../shared/ipc'
-import { isHostOnlyChannel } from '../../shared/host-control'
-import { connectWatchClient } from '../../shared/watch-link/client'
-import { deriveWatchLinkKeys } from '../../shared/watch-link/keys'
-import { readUnlockKey, sealUnlock } from '../../shared/watch-link/unlock-seal'
-import { bytesToB64 } from '../../shared/watch-link/bytes'
-import {
- INPUT_MAX,
- TYPING_NAMES_MAX,
- WATCH_CHAT_CAST,
- WATCH_EVENT,
- WATCH_HISTORY_CAST,
- WATCH_INPUT_CAST,
- WATCH_RELEASE_CAST,
- WATCH_UNLOCK_CAST,
- type WatchControlEvent,
- type WatchKeyframe,
- type WatchLinkRole,
- type WatchMeta
-} from '../../shared/watch-link/protocol'
-import {
- createLinkHost,
- CONFIRM_DEADLINE_MS,
- DROPPED_NOTICE_MIN_MS,
- INPUT_BATCH_MS,
- INPUT_BURST,
- INPUT_CHUNKS_MAX,
- INPUT_DELIVERY_TIMEOUT_MS,
- INPUT_GRACE_MS,
- INPUT_RATE,
- TYPING_EVENT_MIN_MS,
- FULL_STATUS_POLL_MS,
- MAX_VIEWERS_PER_LINK,
- REJOIN_BACKOFF_MS,
- REJOIN_STABLE_MS,
- SETTLE_BOUND_MS,
- UNLOCK_MIN_INTERVAL_MS,
- WATCHER_SIZE_SYNC_MS,
- WRONG_PER_CONN,
- WRONG_PER_LINK,
- type LinkHost,
- type WatchJoin,
- type WatchPty
-} from './link-host'
-import type { HostTokenResult } from './api'
-import { unavailableCapture, type VisibleCapture } from '../capture-route'
-import { hashControlPassword, verifyControlPassword, type ControlPasswordHash } from './password'
-import type { WatchLinkControlRecord, WatchLinkRecord } from './store'
-import type { UiSink } from '../ui-sink-registry'
-import type { ControlInputChunk, WatcherInputRoute } from '../pane-input'
-import { PASTE_END, PASTE_START, TYPING_WINDOW_MS } from './control-input'
-import type { HistoryRead } from './history'
-import type { ChatMessage } from '../../shared/types'
-import type { WatchHistoryPage } from '../../shared/watch-link/protocol'
-
-const ESC = '\x1b'
-const TRUST_CONFIRM = '{"t":"cast","method":"trust:confirm","args":[]}'
-
-const hosts: LinkHost[] = []
-afterEach(() => {
- for (const h of hosts.splice(0)) h.stop('revoked')
- vi.restoreAllMocks()
-})
-
-/** A clock and timer queue owned by the test. Firing a timer lets the event loop turn once, so the
- * async work it starts (a join, a capture) settles before the next one fires. */
-function manualClock() {
- let t = 1_000_000
- let nextId = 1
- const timers = new Map<number, { at: number; fn: () => void }>()
- const flush = (): Promise<void> => new Promise((r) => setImmediate(r))
- return {
- now: () => t,
- setTimeout: (fn: () => void, ms: number): unknown => {
- const id = nextId++
- timers.set(id, { at: t + Math.max(0, ms), fn })
- return id
- },
- clearTimeout: (h: unknown) => {
- timers.delete(h as number)
- },
- /** How many timers are armed and not yet fired or cleared. */
- pending: (): number => timers.size,
- async advance(ms: number): Promise<void> {
- const end = t + ms
- for (;;) {
- let best: [number, { at: number; fn: () => void }] | null = null
- for (const e of timers) if (e[1].at <= end && (!best || e[1].at < best[1].at)) best = e
- if (!best) break
- timers.delete(best[0])
- t = best[1].at
- best[1].fn()
- await flush()
- await flush()
- }
- t = end
- await flush()
- await flush()
- },
- flush
- }
-}
-type ManualClock = ReturnType<typeof manualClock>
-
-/** A join answer as a custom `join` writes it: the input route may be left to `SetupOpts.route`. */
-type JoinAnswer = Omit<WatchJoin, 'input'> & { input?: WatchJoin['input'] }
-
-interface SetupOpts {
- role?: WatchLinkRole
- /** A Control link's record state (the test mutates it the way the service does). */
- control?: WatchLinkControlRecord
- /** Default: the real `verifyControlPassword` against `record.control`, read at call time (as the
- * service does). */
- verifyPassword?: (pw: string) => Promise<boolean>
- /** Replaces the service's lock (which sets `record.control.locked`); still counted in `locks()`. */
- onControlLocked?: (by?: string | null) => void
- /** Replaces the service's record of the link-wide wrong count; still recorded in `wrongs`. */
- onWrongAttempt?: (count: number) => void
- join?: (clientId: number, nodeId: string, viewerId: string) => Promise<JoinAnswer | null> | JoinAnswer | null
- capture?: (sid: string) => Promise<VisibleCapture> | VisibleCapture
- alive?: (sid: string) => boolean
- /** The host side's socket backlog, per listener (in the order listeners were opened). */
- buffered?: (listener: number) => number
- clock?: ManualClock
- /** The pane delivery (`WatchPty.input`). Default: resolves true. Every call is recorded first. */
- input?: (sid: string, chunk: ControlInputChunk) => Promise<boolean> | boolean
- /** The input route the default join answers, and the one added to a custom join's answer that has
- * none. 'missing': leave the field out (the host must read that as 'none'). Default 'tmux'. */
- route?: WatcherInputRoute | 'missing'
- mint?: () => Promise<HostTokenResult>
- status?: () => Promise<'live' | 'revoked' | 'expired' | 'unknown'>
- /** The read-back seam (`LinkHostDeps.history`); absent = no read-back. Every call is recorded. */
- history?: (before: number | null) => Promise<HistoryRead>
- historySupported?: () => boolean
-}
-
-function setup(o: SetupOpts = {}) {
- const secret = nacl.randomBytes(32)
- const record: WatchLinkRecord = {
- linkId: 'AbCdEfGhIjKlMnOpQrStUv', nodeId: 'node-1', role: o.role ?? 'viewer', label: 'Ada', title: 'build',
- createdAt: 0, expiresAt: Date.now() + 3600_000, secret, ...(o.control ? { control: o.control } : {})
- }
- const peers: RelayTransport[] = []
- const sinks = new Map<number, UiSink>()
- let nextId = 1_000_000
- const left: string[] = []
- /** Every pty call, in order: 'join', 'sync:<sid>', 'capture:<sid>'. */
- const calls: string[] = []
- const joinArgs: [number, string, string][] = []
- const joinTimes: number[] = []
- /** Every `pty.input` call, in order: [sessionId, chunk]. */
- const inputs: [string, ControlInputChunk][] = []
- /** Every `pty.input` call's `isCurrent` predicate, in the same order. */
- const currents: ((() => boolean) | undefined)[] = []
- /** Every link-wide wrong count the host reported (`onWrongAttempt`), in order. */
- const wrongs: number[] = []
- /** Who tipped each lock, as the host named it (`onControlLocked`). */
- const lockedBy: (string | null)[] = []
- let mints = 0
- let changes = 0
- let verifies = 0
- let locks = 0
- const taken: string[] = []
- const clock = o.clock
- const now = clock ? clock.now : () => Date.now()
- const pty: WatchPty = {
- join: async (clientId, nodeId, viewerId) => {
- calls.push('join')
- joinArgs.push([clientId, nodeId, viewerId])
- joinTimes.push(now())
- const route = o.route ?? 'tmux'
- const r = o.join ? await o.join(clientId, nodeId, viewerId) : { sessionId: 's1', cols: 100, rows: 30, altScreen: true }
- // 'missing' hands the host an answer with no route, as a wiring slip would.
- if (!r || 'input' in r || route === 'missing') return r as WatchJoin | null
- return { ...r, input: route }
- },
- leave: (_c, sid, vid) => {
- left.push(`${sid}/${vid}`)
- },
- captureVisible: async (sid) => {
- calls.push(`capture:${sid}`)
- return o.capture ? o.capture(sid) : { screen: 'SCREEN', cursor: null }
- },
- syncSize: async (sid) => {
- calls.push(`sync:${sid}`)
- return true
- },
- alive: (sid) => (o.alive ? o.alive(sid) : true),
- input: async (sid, chunk, isCurrent) => {
- inputs.push([sid, chunk])
- currents.push(isCurrent)
- return o.input ? o.input(sid, chunk) : true
- }
- }
- const chats: unknown[] = []
- const joined: number[] = []
- const gone: string[] = []
- /** Every read-back read, by the cursor it was asked for. */
- const reads: (number | null)[] = []
- const host = createLinkHost(record, {
- ...(o.history
- ? {
- history: (before: number | null) => {
- reads.push(before)
- return o.history!(before)
- }
- }
- : {}),
- ...(o.historySupported ? { historySupported: o.historySupported } : {}),
- relayUrl: 'wss://relay.test',
- mint: async () => {
- mints++
- return o.mint ? o.mint() : { ok: true, pairingToken: 'tok', hostId: '', ttlMs: 120_000 }
- },
- status: o.status ?? (async () => 'live'),
- clients: {
- attach: (s) => {
- const id = nextId++
- sinks.set(id, s)
- return id
- },
- detach: (id) => {
- sinks.delete(id)
- }
- },
- pty,
- transport: () => {
- const i = peers.length
- const { hostT, peerT } = transportPair({ hostBuffered: () => o.buffered?.(i) ?? 0 })
- peers.push(peerT)
- return hostT
- },
- now,
- setTimeout: clock ? clock.setTimeout : (fn, ms) => setTimeout(fn, ms),
- clearTimeout: clock ? clock.clearTimeout : (h) => clearTimeout(h as ReturnType<typeof setTimeout>),
- onChange: () => {
- changes++
- },
- onChat: (m) => chats.push(m),
- onViewerJoined: (n) => joined.push(n),
- onGone: (r) => gone.push(r),
- verifyPassword: (pw) => {
- verifies++
- if (o.verifyPassword) return o.verifyPassword(pw)
- return record.control ? verifyControlPassword(pw, record.control) : Promise.resolve(false)
- },
- onControlTaken: (name) => {
- taken.push(name)
- },
- // What the service does, synchronously, before returning (the host reads the record live).
- onControlLocked: (by) => {
- locks++
- lockedBy.push(by ?? null)
- if (o.onControlLocked) o.onControlLocked(by)
- else if (record.control) record.control.locked = true
- },
- // What the service does: the count goes on the record (and to disk).
- onWrongAttempt: (count) => {
- wrongs.push(count)
- if (o.onWrongAttempt) o.onWrongAttempt(count)
- else if (record.control) record.control.wrong = count
- }
- })
- hosts.push(host)
- return {
- record, host, peers, sinks, left, calls, joinArgs, joinTimes, inputs, currents, wrongs, lockedBy, chats, joined, gone, reads,
- keys: deriveWatchLinkKeys(secret),
- mints: () => mints,
- /** How many times the host reported a change to the registry (`onChange`). */
- changes: () => changes,
- /** How many times the host asked to verify a password, and the names that took control. */
- verifies: () => verifies,
- taken,
- locks: () => locks,
- /** The n-th attached viewer's sink (attach order). */
- sink: (n = 0) => [...sinks.values()][n]
- }
-}
-type Setup = ReturnType<typeof setup>
-
-function viewer(peer: RelayTransport, keys: ReturnType<typeof deriveWatchLinkKeys>) {
- const log = { open: 0, events: [] as [string, unknown[]][], pty: [] as string[], denied: [] as string[], closed: 0 }
- const c = connectWatchClient({
- socket: peer,
- keys,
- events: {
- onOpen: () => { log.open++ },
- onEvent: (ch, a) => { log.events.push([ch, a]) },
- onPtyData: (_s, d) => { log.pty.push(d) },
- onDenied: (r) => { log.denied.push(r) },
- onClose: () => { log.closed++ }
- }
- })
- const named = (ch: string) => log.events.filter((e) => e[0] === ch).map((e) => e[1][0])
- return { c, log, named, keyframes: () => named(WATCH_EVENT.keyframe) as WatchKeyframe[] }
-}
-type Viewer = ReturnType<typeof viewer>
-
-/** Open the n-th listener's viewer and wait for its first keyframe. */
-async function openViewer(t: Setup, n = 0): Promise<Viewer> {
- await vi.waitFor(() => expect(t.peers.length).toBeGreaterThan(n))
- const v = viewer(t.peers[n], t.keys)
- await vi.waitFor(() => expect(v.keyframes().length).toBeGreaterThanOrEqual(1))
- return v
-}
-/** Open the n-th listener's viewer and wait for its meta (a no-capture backend sends no keyframe). */
-async function openViewerMeta(t: Setup, n = 0): Promise<Viewer> {
- await vi.waitFor(() => expect(t.peers.length).toBeGreaterThan(n))
- const v = viewer(t.peers[n], t.keys)
- await vi.waitFor(() => expect(v.named(WATCH_EVENT.meta).length).toBeGreaterThanOrEqual(1))
- return v
-}
-const pty = (sink: UiSink, sid: string, data: string): void => sink.sendBinary(encodePtyData(sid, data))
-const ptyEvent = (sink: UiSink, channel: string, ...args: unknown[]): void =>
- sink.sendText(JSON.stringify({ t: 'ev', channel, args }))
-
-describe('createLinkHost — a viewer session', () => {
- it('opens a viewer, sends meta then the visible keyframe, then the filtered stream', async () => {
- const t = setup()
- t.host.start()
- await vi.waitFor(() => expect(t.peers).toHaveLength(1))
- const v = viewer(t.peers[0], t.keys)
- await vi.waitFor(() => expect(v.log.events.map((e) => e[0])).toEqual([WATCH_EVENT.meta, WATCH_EVENT.keyframe]))
- expect(v.log.events[0][1][0]).toMatchObject({ v: 1, role: 'viewer', label: 'Ada', title: 'build', cols: 100, rows: 30 })
- // No cursor was read, so the keyframe carries none (not `cursor: null`).
- expect(v.log.events[1][1][0]).toEqual({ sessionId: 's1', screen: 'SCREEN', altScreen: true })
- const [id, sink] = [...t.sinks.entries()][0]
- expect(id).toBeGreaterThanOrEqual(1_000_000)
- // The join is MID-STREAM (R12): nothing is shown until the first escape, then OSC 52 is removed.
- pty(sink, 's1', 'lost')
- pty(sink, 's1', `${ESC}[Ha${ESC}]52;c;c2VjcmV0\x07b`)
- expect(v.log.pty).toEqual([`${ESC}[Hab`])
- expect(t.joined).toEqual([1])
- expect(t.host.viewers()).toHaveLength(1)
- // The host built every join argument itself: its client id, the record's node, a fresh viewer id.
- expect(t.joinArgs).toEqual([[id, 'node-1', t.host.viewers()[0].viewerId]])
- expect(t.host.viewers()[0].viewerId).toMatch(/^v-[0-9a-f]{8}$/)
- // A replacement listener opened for the next viewer.
- await vi.waitFor(() => expect(t.peers).toHaveLength(2))
- })
-
- it("a keyframe carries the host's cursor, and its screen passes a FRESH filter (R9, R10)", async () => {
- const screen =
- `${ESC}[1mhi${ESC}[m ${ESC}]8;;https://evil.test/${ESC}\\link${ESC}]8;;${ESC}\\ ` +
- `${ESC}]52;c;c2VjcmV0\x07end${ESC}P1$r0m${ESC}\\\n`
- const t = setup({ capture: () => ({ screen, cursor: { x: 3, y: 1 } }) })
- t.host.start()
- const v = await openViewer(t)
- expect(v.keyframes()[0]).toEqual({
- sessionId: 's1',
- screen: `${ESC}[1mhi${ESC}[m link end\n`,
- altScreen: true,
- cursor: { x: 3, y: 1 }
- })
- })
-
- it("a REAL capture of an empty screen still sends a keyframe with screen '' (R36), and altScreen follows the join", async () => {
- const t = setup({
- join: () => ({ sessionId: 's1', cols: 80, rows: 24, altScreen: false }),
- capture: () => ({ screen: '', cursor: null })
- })
- t.host.start()
- const v = await openViewer(t)
- expect(v.keyframes()[0]).toEqual({ sessionId: 's1', screen: '', altScreen: false })
- })
-
- it("a session-host capture states its own altScreen, which wins over the join's (no tmux client between)", async () => {
- const t = setup({
- join: () => ({ sessionId: 's1', cols: 80, rows: 24, altScreen: false }),
- capture: () => ({ screen: 'vim\n', cursor: { x: 0, y: 0 }, altScreen: true })
- })
- t.host.start()
- const v = await openViewer(t)
- expect(v.keyframes()[0]).toEqual({ sessionId: 's1', screen: 'vim\n', altScreen: true, cursor: { x: 0, y: 0 } })
- })
-
- it("denies a peer whose key is not the link's viewer key, and reopens a listener", async () => {
- const t = setup()
- t.host.start()
- await vi.waitFor(() => expect(t.peers).toHaveLength(1))
- const stranger = deriveWatchLinkKeys(nacl.randomBytes(32))
- const v = viewer(t.peers[0], { ...t.keys, viewer: stranger.viewer })
- await vi.waitFor(() => expect(v.log.denied).toEqual(['denied']))
- expect(v.log.open).toBe(0)
- expect(t.sinks.size).toBe(0)
- expect(t.calls).toEqual([])
- await vi.waitFor(() => expect(t.peers.length).toBeGreaterThanOrEqual(2))
- })
-})
-
-describe('createLinkHost — read-only, both directions', () => {
- it('sends a raw peer nothing but the trust confirm before its own confirm; then refuses every request and drops every cast', async () => {
- const t = setup()
- t.host.start()
- await vi.waitFor(() => expect(t.peers).toHaveLength(1))
- const replies = new Map<number, { ok: boolean; error?: { code: string } }>()
- const frames: { kind: 'text' | 'binary'; json: string | null; beforeOurConfirm: boolean }[] = []
- let confirmed = false
- let rawClosed = 0
- const raw = connectRelay({
- url: 'x', token: 'x', role: 'client', theirPubB64: publicKeyToB64(t.keys.host.publicKey),
- ourKeys: { publicKey: t.keys.viewer.publicKey, secretKey: t.keys.viewer.secretKey },
- transport: t.peers[0], onReady: () => {}, onRpc: () => {}, onFrame: () => {},
- onClose: () => { rawClosed++ },
- onTunnel: (kind, p) => {
- const json = kind === 'text' ? new TextDecoder().decode(p) : null
- frames.push({ kind, json, beforeOurConfirm: !confirmed })
- const m = json ? parseRpcMessage(json) : null
- if (m?.t === 'res') replies.set(m.id, m as { ok: boolean; error?: { code: string } })
- }
- })
- // The host confirms its own half at once (the key is the link's), and then must send NOTHING more:
- // no meta, no keyframe, no pty frame, while the fake pty would happily serve a session (F20).
- await vi.waitFor(() => expect(frames.some((f) => f.json?.includes('trust:confirm'))).toBe(true))
- await new Promise((r) => setTimeout(r, 30))
- expect(t.sinks.size).toBe(0)
- expect(t.calls).toEqual([])
- for (const f of frames) {
- expect(f.kind).toBe('text')
- expect(parseRpcMessage(f.json!)).toEqual({ t: 'cast', method: 'trust:confirm', args: [] })
- }
- confirmed = true
- raw.sendTunnelText(TRUST_CONFIRM)
- await vi.waitFor(() => expect(t.sinks.size).toBe(1))
- await vi.waitFor(() => expect(frames.some((f) => f.json?.includes(WATCH_EVENT.keyframe))).toBe(true))
-
- // One request for every channel IPC names (and every per-session channel), and the same as a cast.
- const methods = [
- ...(Object.values(IPC) as unknown[]).filter((v): v is string => typeof v === 'string'),
- ...(Object.values(IPC) as unknown[])
- .filter((v): v is (id: string) => string => typeof v === 'function')
- .map((f) => f('s1'))
- ]
- methods.forEach((method, i) => {
- raw.sendTunnelText(JSON.stringify({ t: 'req', id: i + 1, method, args: ['s1', 'rm -rf ~\r', 1, 1] }))
- raw.sendTunnelText(JSON.stringify({ t: 'cast', method, args: ['s1', 'rm -rf ~\r', 1, 1] }))
- })
- await vi.waitFor(() => expect(replies.size).toBe(methods.length))
- methods.forEach((method, i) => {
- const r = replies.get(i + 1)!
- expect(r.ok, method).toBe(false)
- // Host-only channels are refused by relay-host before any policy; everything else by the watcher's.
- expect(r.error?.code, method).toBe(isHostOnlyChannel(method) ? 'E_FORBIDDEN' : 'E_ROLE')
- })
- // Refused by the ACCESS policy: a request or cast that reached the link host's own PeerAttach would
- // have closed this viewer (fail closed). It is still here, and the pty saw only the host's calls.
- expect(t.host.viewers()).toHaveLength(1)
- expect(rawClosed).toBe(0)
- expect(new Set(t.calls)).toEqual(new Set(['join', 'sync:s1', 'capture:s1']))
- expect(t.joinArgs).toHaveLength(1)
- expect(t.chats).toEqual([])
- })
-
- it('a viewer link drops chat casts; the viewer stays connected', async () => {
- const t = setup({ role: 'viewer' })
- t.host.start()
- const v = await openViewer(t)
- expect(v.c.sendChat('Ada', 'hello')).toBe(true)
- await new Promise((r) => setTimeout(r, 20))
- expect(t.chats).toEqual([])
- expect(t.host.chatHistory()).toEqual([])
- expect(t.host.viewers()).toHaveLength(1)
- })
-
- it('a pty event for the watched session is consumed (never forwarded), and another session is invisible', async () => {
- const t = setup()
- t.host.start()
- const v = await openViewer(t)
- const sink = t.sink()
- pty(sink, 's1', `${ESC}[H`)
- pty(sink, 's2', `${ESC}[Hother`)
- ptyEvent(sink, IPC.ptyResync('s1'), 'history')
- ptyEvent(sink, IPC.ptySize('s1'), { cols: 90, rows: 20 })
- ptyEvent(sink, IPC.ptySize('s2'), { cols: 1, rows: 1 })
- await new Promise((r) => setTimeout(r, 10))
- expect(v.log.pty).toEqual([`${ESC}[H`])
- expect(v.log.events.map((e) => e[0])).toEqual([WATCH_EVENT.meta, WATCH_EVENT.keyframe, IPC.ptySize('s1')])
- })
-})
-
-describe('createLinkHost — joining, waiting, rejoining', () => {
- it('waits (once), then streams when the session appears', async () => {
- const clock = manualClock()
- let running = false
- const t = setup({ clock, join: () => (running ? { sessionId: 's9', cols: 80, rows: 24, altScreen: false } : null) })
- t.host.start()
- await vi.waitFor(() => expect(t.peers).toHaveLength(1))
- const v = viewer(t.peers[0], t.keys)
- await vi.waitFor(() => expect(v.log.events.map((e) => e[0])).toEqual([WATCH_EVENT.waiting]))
- await clock.advance(REJOIN_BACKOFF_MS[0])
- expect(t.joinArgs).toHaveLength(2)
- expect(v.log.events.map((e) => e[0])).toEqual([WATCH_EVENT.waiting]) // not repeated per retry
- running = true
- await clock.advance(REJOIN_BACKOFF_MS[1])
- await vi.waitFor(() => expect(v.log.events.map((e) => e[0])).toEqual([WATCH_EVENT.waiting, WATCH_EVENT.meta, WATCH_EVENT.keyframe]))
- expect(v.named(WATCH_EVENT.meta)[0]).toMatchObject({ cols: 80, rows: 24 })
- })
-
- // R63: the OWNER is told a viewer has no session to watch — on a backend with no watcher client of
- // its own (Windows' session host, no local tmux, Zellij) only a terminal open in the app can be
- // watched. Reported by a REFUSED join, once per episode, and cleared by a join that lands.
- it("a refused join marks the viewer waiting in the owner's view, once; a join that lands clears it", async () => {
- const clock = manualClock()
- let running = false
- const t = setup({ clock, join: () => (running ? { sessionId: 's9', cols: 80, rows: 24, altScreen: false } : null) })
- t.host.start()
- await vi.waitFor(() => expect(t.peers).toHaveLength(1))
- const v = viewer(t.peers[0], t.keys)
- await vi.waitFor(() => expect(t.host.viewers().map((x) => x.waiting)).toEqual([true]))
- const changesAfterFirst = t.changes()
- await clock.advance(REJOIN_BACKOFF_MS[0])
- await clock.advance(REJOIN_BACKOFF_MS[1])
- expect(t.joinArgs.length).toBeGreaterThanOrEqual(3)
- expect(t.changes()).toBe(changesAfterFirst) // a failing rejoin loop reports nothing new
- running = true
- await clock.advance(REJOIN_BACKOFF_MS[2])
- await vi.waitFor(() => expect(v.named(WATCH_EVENT.meta)).toHaveLength(1))
- expect(t.host.viewers().map((x) => x.waiting)).toEqual([false])
- expect(t.changes()).toBeGreaterThan(changesAfterFirst)
- })
-
- it('a session that ENDS is not "waiting" for the owner until a rejoin is refused (a quick rejoin is no news)', async () => {
- const clock = manualClock()
- let n = 0
- let up = true
- const t = setup({ clock, join: () => (up ? { sessionId: `s${++n}`, cols: 80, rows: 24, altScreen: true } : null) })
- t.host.start()
- const v = await openViewer(t)
- ptyEvent(t.sink(), IPC.ptyExit('s1'), 0)
- await clock.flush()
- expect(v.named(WATCH_EVENT.waiting)).toHaveLength(1) // the VIEWER is told at once
- expect(t.host.viewers().map((x) => x.waiting)).toEqual([false]) // the owner is not, yet
- up = false
- await clock.advance(REJOIN_BACKOFF_MS[0])
- expect(t.host.viewers().map((x) => x.waiting)).toEqual([true]) // the rejoin was refused
- })
-
- it('every join starts the filter mid-stream: the first join AND a rejoin after the session ended', async () => {
- const clock = manualClock()
- let n = 0
- const t = setup({ clock, join: () => ({ sessionId: `s${++n}`, cols: 80, rows: 24, altScreen: true }) })
- t.host.start()
- const v = await openViewer(t)
- const sink = t.sink()
- pty(sink, 's1', 'x')
- pty(sink, 's1', `${ESC}[Hy`)
- expect(v.log.pty).toEqual([`${ESC}[Hy`])
- ptyEvent(sink, IPC.ptyExit('s1'), 0)
- await clock.flush()
- expect(v.named(WATCH_EVENT.waiting)).toHaveLength(1)
- expect(t.left).toEqual([`s1/${t.host.viewers()[0].viewerId}`])
- await clock.advance(REJOIN_BACKOFF_MS[0])
- await vi.waitFor(() => expect(v.keyframes().map((k) => k.sessionId)).toContain('s2'))
- // A second meta (R14), and the rejoined session's filter is mid-stream again.
- expect(v.named(WATCH_EVENT.meta)).toHaveLength(2)
- pty(sink, 's2', 'z')
- pty(sink, 's1', `${ESC}[Hdead`)
- pty(sink, 's2', `${ESC}[Hw`)
- expect(v.log.pty).toEqual([`${ESC}[Hy`, `${ESC}[Hw`])
- // The lifecycle event itself never reached the viewer.
- expect(v.log.events.map((e) => e[0]).filter((c) => c.startsWith('pty:'))).toEqual([])
- })
-
- it('the rejoin backoff grows for sessions that exit at once, and resets only after one stayed up 30 s (R26)', async () => {
- const clock = manualClock()
- let n = 0
- const t = setup({ clock, join: () => ({ sessionId: `s${++n}`, cols: 80, rows: 24, altScreen: true }) })
- t.host.start()
- const v = await openViewer(t)
- const sink = t.sink()
- const exitCurrent = async (): Promise<void> => {
- await vi.waitFor(() => expect(v.keyframes().map((k) => k.sessionId)).toContain(`s${n}`))
- ptyEvent(sink, IPC.ptyExit(`s${n}`), 0)
- await clock.flush()
- }
- await exitCurrent()
- const expected = [2_000, 4_000, 8_000, 15_000, 15_000, 15_000]
- for (const d of expected) {
- await clock.advance(d)
- await exitCurrent()
- }
- const deltas = t.joinTimes.slice(1).map((x, i) => x - t.joinTimes[i])
- expect(deltas).toEqual(expected)
- // This one stays up for REJOIN_STABLE_MS from its join keyframe: the backoff resets.
- await clock.advance(15_000)
- await vi.waitFor(() => expect(v.keyframes().map((k) => k.sessionId)).toContain(`s${n}`))
- await clock.advance(REJOIN_STABLE_MS)
- ptyEvent(sink, IPC.ptyExit(`s${n}`), 0)
- await clock.flush()
- const before = t.joinTimes.length
- await clock.advance(REJOIN_BACKOFF_MS[0])
- expect(t.joinTimes).toHaveLength(before + 1)
- })
-
- it('a join that throws is "waiting" and backs off; a capture that throws sends NO keyframe and the viewer streams (R36)', async () => {
- const clock = manualClock()
- let fail = true
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
- const t = setup({
- clock,
- join: () => {
- if (fail) throw new Error('spawn failed')
- return { sessionId: 's1', cols: 80, rows: 24, altScreen: true }
- },
- capture: () => {
- throw new Error('capture failed')
- }
- })
- t.host.start()
- await vi.waitFor(() => expect(t.peers).toHaveLength(1))
- const v = viewer(t.peers[0], t.keys)
- await vi.waitFor(() => expect(v.named(WATCH_EVENT.waiting)).toHaveLength(1))
- fail = false
- await clock.advance(REJOIN_BACKOFF_MS[0])
- await vi.waitFor(() => expect(v.named(WATCH_EVENT.meta)).toHaveLength(1))
- await clock.flush()
- expect(v.keyframes()).toEqual([])
- pty(t.sink(), 's1', `${ESC}[Hstreams`)
- expect(v.log.pty).toEqual([`${ESC}[Hstreams`])
- expect(warn).toHaveBeenCalled()
- })
-
- it('a join answering no valid size is REFUSED — left, waiting, retried — never given a guessed size', async () => {
- const clock = manualClock()
- let size = { cols: 0, rows: 24 }
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
- const t = setup({ clock, join: () => ({ sessionId: 's1', ...size, altScreen: true }) })
- t.host.start()
- await vi.waitFor(() => expect(t.peers).toHaveLength(1))
- const v = viewer(t.peers[0], t.keys)
- await vi.waitFor(() => expect(v.named(WATCH_EVENT.waiting)).toHaveLength(1))
- expect(v.named(WATCH_EVENT.meta)).toEqual([])
- expect(t.left).toEqual([`s1/${t.host.viewers()[0].viewerId}`])
- expect(t.calls).not.toContain('capture:s1')
- for (const bad of [{ cols: 80, rows: Number.NaN }, { cols: 80.5, rows: 24 }, { cols: -1, rows: 24 }]) {
- size = bad
- await clock.advance(60_000)
- }
- expect(v.named(WATCH_EVENT.meta)).toEqual([])
- size = { cols: 132, rows: 40 }
- await clock.advance(60_000)
- await vi.waitFor(() => expect(v.named(WATCH_EVENT.meta)).toHaveLength(1))
- expect(v.named(WATCH_EVENT.meta)[0]).toMatchObject({ cols: 132, rows: 40 })
- expect(warn).toHaveBeenCalled()
- })
-
- it('an exit that raced the join (the session is already gone) is waiting + rejoin, not a dead stream (R30)', async () => {
- const clock = manualClock()
- const dead = new Set(['s1'])
- let n = 0
- const t = setup({ clock, join: () => ({ sessionId: `s${++n}`, cols: 80, rows: 24, altScreen: true }), alive: (s) => !dead.has(s) })
- t.host.start()
- await vi.waitFor(() => expect(t.peers).toHaveLength(1))
- const v = viewer(t.peers[0], t.keys)
- await vi.waitFor(() => expect(v.named(WATCH_EVENT.waiting)).toHaveLength(1))
- expect(v.keyframes()).toEqual([])
- expect(t.left).toEqual([`s1/${t.host.viewers()[0].viewerId}`])
- expect(t.calls).not.toContain('capture:s1')
- await clock.advance(REJOIN_BACKOFF_MS[0])
- await vi.waitFor(() => expect(v.keyframes().map((k) => k.sessionId)).toEqual(['s2']))
- })
-
- it('a session gone by the time its capture returns gets no keyframe: waiting + rejoin (R30)', async () => {
- const clock = manualClock()
- const dead = new Set<string>()
- let n = 0
- const t = setup({
- clock,
- join: () => ({ sessionId: `s${++n}`, cols: 80, rows: 24, altScreen: true }),
- capture: (sid) => {
- if (sid === 's1') dead.add('s1') // exits while being captured
- return { screen: 'SCREEN', cursor: null }
- },
- alive: (s) => !dead.has(s)
- })
- t.host.start()
- await vi.waitFor(() => expect(t.peers).toHaveLength(1))
- const v = viewer(t.peers[0], t.keys)
- await vi.waitFor(() => expect(v.named(WATCH_EVENT.waiting)).toHaveLength(1))
- expect(v.keyframes()).toEqual([])
- await clock.advance(REJOIN_BACKOFF_MS[0])
- await vi.waitFor(() => expect(v.keyframes().map((k) => k.sessionId)).toEqual(['s2']))
- })
-})
-
-describe('createLinkHost — keyframes and the stream', () => {
- it('sync runs after a join (before its keyframe capture), before every keyframe capture, and every 10 s while watched', async () => {
- const clock = manualClock()
- const t = setup({ clock })
- t.host.start()
- const v = await openViewer(t)
- expect(t.calls).toEqual(['join', 'sync:s1', 'capture:s1'])
- pty(t.sink(), 's1', `${ESC}[H`) // settles the filter: one follow-up keyframe at the min interval
- await clock.advance(1_000)
- expect(t.calls.slice(3)).toEqual(['sync:s1', 'capture:s1'])
- expect(v.keyframes()).toHaveLength(2)
- await clock.advance(WATCHER_SIZE_SYNC_MS - 1_000)
- expect(t.calls.slice(5)).toEqual(['sync:s1'])
- await clock.advance(WATCHER_SIZE_SYNC_MS)
- expect(t.calls.slice(6)).toEqual(['sync:s1'])
- // No joined viewer: no more syncs.
- t.host.kick(t.host.viewers()[0].viewerId)
- await clock.advance(3 * WATCHER_SIZE_SYNC_MS)
- expect(t.calls.slice(7)).toEqual([])
- })
-
- it('onOverBudget stops the stream NOW even while a keyframe timer is armed (F10)', async () => {
- const clock = manualClock()
- let buffered = 0
- const t = setup({ clock, buffered: () => buffered })
- t.host.start()
- const v = await openViewer(t)
- const sink = t.sink()
- // Settling arms the follow-up keyframe timer while the stream keeps flowing.
- pty(sink, 's1', `${ESC}[H`)
- expect(v.log.pty).toEqual([`${ESC}[H`])
- buffered = 600 * 1024
- pty(sink, 's1', 'a') // dropped: over the buffer limit
- buffered = 0
- pty(sink, 's1', 'b') // must NOT follow the dropped frame without a repaint between
- expect(v.log.pty).toEqual([`${ESC}[H`])
- await clock.advance(1_000)
- expect(v.keyframes()).toHaveLength(2)
- pty(sink, 's1', 'c')
- expect(v.log.pty).toEqual([`${ESC}[H`, 'c'])
- })
-
- it('a stalled viewer is throttled to keyframes, painted only once its socket drained', async () => {
- const clock = manualClock()
- let buffered = 0
- const t = setup({ clock, buffered: () => buffered })
- t.host.start()
- const v = await openViewer(t)
- const sink = t.sink()
- pty(sink, 's1', `${ESC}[H`)
- await clock.advance(1_000) // the settle follow-up
- expect(v.keyframes()).toHaveLength(2)
- buffered = 1_000_000
- for (let i = 0; i < 50; i++) pty(sink, 's1', 'y\r\n')
- expect(v.log.pty).toEqual([`${ESC}[H`])
- await clock.advance(3_000) // still backed up: no keyframe on top of the backlog
- expect(v.keyframes()).toHaveLength(2)
- buffered = 0
- await clock.advance(1_000)
- expect(v.keyframes()).toHaveLength(3)
- pty(sink, 's1', 'after')
- expect(v.log.pty).toEqual([`${ESC}[H`, 'after'])
- })
-
- it('the token bucket throttles a flood to at most one keyframe a second', async () => {
- const clock = manualClock()
- const t = setup({ clock })
- t.host.start()
- const v = await openViewer(t)
- const sink = t.sink()
- pty(sink, 's1', `${ESC}[H`)
- await clock.advance(1_000)
- const chunk = 'x'.repeat(64 * 1024)
- for (let i = 0; i < 40; i++) pty(sink, 's1', chunk) // 2.5 MB at one instant: past the 1 MB burst
- const forwarded = v.log.pty.join('').length
- expect(forwarded).toBeLessThanOrEqual(1024 * 1024)
- await clock.advance(1_000)
- expect(v.keyframes()).toHaveLength(3)
- })
-
- it('a follow-up keyframe when the filter settles after the join keyframe; one at 2 s if it has not (R23)', async () => {
- const clock = manualClock()
- const t = setup({ clock })
- t.host.start()
- const v = await openViewer(t)
- const sink = t.sink()
- // Settles half a second in: the follow-up comes at the min interval, and the 2 s bound adds none.
- await clock.advance(500)
- pty(sink, 's1', `${ESC}[H`)
- await clock.advance(499)
- expect(v.keyframes()).toHaveLength(1)
- await clock.advance(1)
- expect(v.keyframes()).toHaveLength(2)
- await clock.advance(5_000)
- expect(v.keyframes()).toHaveLength(2)
- })
-
- it('an unsettled filter gets a keyframe at the 2 s bound, and one more when it settles later (R23)', async () => {
- const clock = manualClock()
- const t = setup({ clock })
- t.host.start()
- const v = await openViewer(t)
- await clock.advance(SETTLE_BOUND_MS - 1)
- expect(v.keyframes()).toHaveLength(1)
- await clock.advance(1)
- expect(v.keyframes()).toHaveLength(2)
- await clock.advance(3_000)
- expect(v.keyframes()).toHaveLength(2)
- pty(t.sink(), 's1', `${ESC}[H`)
- await clock.advance(0)
- expect(v.keyframes()).toHaveLength(3)
- await clock.advance(10_000)
- expect(v.keyframes()).toHaveLength(3)
- })
-
- it('a filter that settled before the join keyframe was painted takes no follow-up', async () => {
- const clock = manualClock()
- let release: (c: VisibleCapture) => void = () => {}
- const t = setup({ clock, capture: () => new Promise<VisibleCapture>((r) => (release = r)) })
- t.host.start()
- await vi.waitFor(() => expect(t.peers).toHaveLength(1))
- const v = viewer(t.peers[0], t.keys)
- await vi.waitFor(() => expect(t.calls).toContain('capture:s1'))
- pty(t.sink(), 's1', `${ESC}[Hx`) // not forwarded (no keyframe yet), but the filter settles
- release({ screen: 'SCREEN', cursor: null })
- await vi.waitFor(() => expect(v.keyframes()).toHaveLength(1))
- await clock.advance(10_000)
- expect(v.keyframes()).toHaveLength(1)
- expect(v.log.pty).toEqual([])
- })
-
- it('a backend with NO visible capture never gets a watch:keyframe — join, 2 s bound, settle follow-up, throttle — and keeps streaming (R36)', async () => {
- const clock = manualClock()
- let buffered = 0
- const t = setup({ clock, capture: () => unavailableCapture(), buffered: () => buffered })
- t.host.start()
- const v = await openViewerMeta(t)
- await clock.flush()
- const captures = () => t.calls.filter((c) => c === 'capture:s1').length
- expect(captures()).toBe(1)
- expect(v.keyframes()).toEqual([])
- const sink = t.sink()
- pty(sink, 's1', 'lost') // mid-stream: swallowed until the first escape
- await clock.advance(SETTLE_BOUND_MS) // the 2 s bound: a capture, nothing sent
- expect(captures()).toBe(2)
- expect(v.keyframes()).toEqual([])
- pty(sink, 's1', `${ESC}[Ha`) // settles; streaming, with no keyframe ever sent
- expect(v.log.pty).toEqual([`${ESC}[Ha`])
- await clock.advance(1_000) // the settle follow-up: a capture, nothing sent, still streaming
- expect(captures()).toBe(3)
- pty(sink, 's1', 'b')
- // Throttled: dropped while over budget, then streaming RESUMES without a keyframe.
- buffered = 600 * 1024
- pty(sink, 's1', 'dropped')
- buffered = 0
- pty(sink, 's1', 'still-dropped')
- await clock.advance(1_000)
- expect(captures()).toBe(4)
- pty(sink, 's1', 'resumed')
- expect(v.log.pty).toEqual([`${ESC}[Ha`, 'b', 'resumed'])
- expect(v.keyframes()).toEqual([])
- expect(v.log.events.map((e) => e[0]).filter((c) => c === WATCH_EVENT.keyframe)).toEqual([])
- })
-
- it('a FAILED capture on a capture-capable backend sends no keyframe, and the stream resumes (R36)', async () => {
- const clock = manualClock()
- let buffered = 0
- let fail = false
- vi.spyOn(console, 'warn').mockImplementation(() => {})
- const t = setup({
- clock,
- buffered: () => buffered,
- capture: () => {
- if (fail) throw new Error('ssh: master gone')
- return { screen: 'SCREEN', cursor: null }
- }
- })
- t.host.start()
- const v = await openViewer(t)
- const sink = t.sink()
- fail = true
- pty(sink, 's1', `${ESC}[H`) // settles: the follow-up capture fails
- await clock.advance(1_000)
- expect(v.keyframes()).toHaveLength(1)
- pty(sink, 's1', 'a')
- buffered = 600 * 1024
- pty(sink, 's1', 'dropped') // throttled; its repaint capture fails too
- buffered = 0
- await clock.advance(1_000)
- pty(sink, 's1', 'b')
- expect(v.keyframes()).toHaveLength(1)
- expect(v.log.pty).toEqual([`${ESC}[H`, 'a', 'b'])
- })
-
- it("one capture per session is shared by the link's viewers joining it together (R27)", async () => {
- const clock = manualClock()
- const releases: ((c: VisibleCapture) => void)[] = []
- const t = setup({ clock, capture: () => new Promise<VisibleCapture>((r) => releases.push(r)) })
- t.host.start()
- await vi.waitFor(() => expect(t.peers).toHaveLength(1))
- const a = viewer(t.peers[0], t.keys)
- await vi.waitFor(() => expect(t.calls).toContain('capture:s1'))
- await vi.waitFor(() => expect(t.peers).toHaveLength(2))
- const b = viewer(t.peers[1], t.keys)
- await vi.waitFor(() => expect(t.joinArgs).toHaveLength(2))
- await clock.flush()
- expect(t.calls.filter((c) => c === 'capture:s1')).toHaveLength(1)
- releases[0]({ screen: 'ONE', cursor: null })
- await vi.waitFor(() => expect(b.keyframes()).toHaveLength(1))
- expect(a.keyframes().map((k) => k.screen)).toEqual(['ONE'])
- expect(b.keyframes().map((k) => k.screen)).toEqual(['ONE'])
- })
-
- it('a keyframe asked for while a capture runs waits for a NEWER one; the stream resumes only on it', async () => {
- const clock = manualClock()
- const releases: ((c: VisibleCapture) => void)[] = []
- const t = setup({ clock, capture: () => new Promise<VisibleCapture>((r) => releases.push(r)) })
- t.host.start()
- await vi.waitFor(() => expect(t.peers).toHaveLength(1))
- const v = viewer(t.peers[0], t.keys)
- await vi.waitFor(() => expect(releases).toHaveLength(1))
- // The 2 s bound asks for a keyframe while the join keyframe's capture is still running.
- await clock.advance(SETTLE_BOUND_MS)
- expect(releases).toHaveLength(1) // one capture in flight per session: the second is queued
- releases[0]({ screen: 'OLD', cursor: null })
- await vi.waitFor(() => expect(releases).toHaveLength(2))
- expect(v.keyframes().map((k) => k.screen)).toEqual(['OLD'])
- pty(t.sink(), 's1', `${ESC}[Hbetween`) // after the OLD paint, before the newer one: not forwarded
- expect(v.log.pty).toEqual([])
- releases[1]({ screen: 'NEW', cursor: null })
- await vi.waitFor(() => expect(v.keyframes().map((k) => k.screen)).toEqual(['OLD', 'NEW']))
- pty(t.sink(), 's1', 'after')
- expect(v.log.pty).toEqual(['after'])
- })
-})
-
-describe('createLinkHost — chat', () => {
- it('relays commenter chat, rate-limited and sanitized, to viewers and the owner', async () => {
- const t = setup({ role: 'commenter' })
- t.host.start()
- const v = await openViewer(t)
- expect(v.c.sendChat('Ada', 'hello\u0007')).toBe(true)
- expect(v.c.sendChat('Ada', 'again')).toBe(true) // inside 2 s: dropped by the host
- await vi.waitFor(() => expect(t.chats).toHaveLength(1))
- expect(t.chats[0]).toMatchObject({ name: 'Ada', text: 'hello', from: 'viewer' })
- await vi.waitFor(() => expect(v.named(WATCH_EVENT.chat)).toHaveLength(1))
- expect(t.host.viewers()[0].name).toBe('Ada')
- expect(t.host.postSharerChat('hi back')).toMatchObject({ from: 'sharer', name: 'Ada', text: 'hi back' })
- await vi.waitFor(() => expect(v.named(WATCH_EVENT.chat)).toHaveLength(2))
- expect(t.host.chatHistory()).toHaveLength(2)
- })
-
- it('a sharer cannot chat on a viewer link', async () => {
- const t = setup({ role: 'viewer' })
- expect(t.host.postSharerChat('hi')).toBeNull()
- })
-
- it('skips chat for a viewer over 512 KB behind, and closes one over 8 MB behind — no end, not a revoke (R28)', async () => {
- const buffered = [0, 0]
- const t = setup({ role: 'commenter', buffered: (i) => buffered[i] ?? 0 })
- t.host.start()
- const a = await openViewer(t, 0)
- const b = await openViewer(t, 1)
- expect(t.host.viewers()).toHaveLength(2)
- const aId = t.host.viewers()[0].viewerId
- buffered[0] = 600 * 1024
- t.host.postSharerChat('one')
- await vi.waitFor(() => expect(b.named(WATCH_EVENT.chat)).toHaveLength(1))
- expect(a.named(WATCH_EVENT.chat)).toHaveLength(0)
- buffered[0] = 9 * 1024 * 1024
- t.host.postSharerChat('two')
- await vi.waitFor(() => expect(b.named(WATCH_EVENT.chat)).toHaveLength(2))
- await vi.waitFor(() => expect(a.log.closed).toBe(1))
- expect(a.named(WATCH_EVENT.end)).toEqual([])
- expect(t.host.viewers().map((x) => x.viewerId)).not.toContain(aId)
- expect(t.left).toContain(`s1/${aId}`)
- expect(t.gone).toEqual([])
- })
-})
-
-describe('createLinkHost — ending', () => {
- it('kick ends one viewer with a reason; stop ends everyone, leaves the pty and mints nothing (F1)', async () => {
- const t = setup()
- t.host.start()
- const a = await openViewer(t, 0)
- const b = await openViewer(t, 1)
- await vi.waitFor(() => expect(t.host.viewers()).toHaveLength(2))
- await vi.waitFor(() => expect(t.peers).toHaveLength(3))
- expect(t.host.kick(t.host.viewers()[0].viewerId)).toBe(true)
- expect(t.host.kick('v-nobody0')).toBe(false)
- await vi.waitFor(() => expect(a.named(WATCH_EVENT.end)).toEqual([{ reason: 'kicked' }]))
- await new Promise((r) => setTimeout(r, 10))
- const minted = t.mints()
- t.host.stop('revoked')
- await vi.waitFor(() => expect(b.named(WATCH_EVENT.end)).toEqual([{ reason: 'revoked' }]))
- await new Promise((r) => setTimeout(r, 20))
- expect(t.mints()).toBe(minted)
- expect(t.left).toHaveLength(2)
- expect(t.sinks.size).toBe(0)
- expect(t.host.viewers()).toEqual([])
- })
-
- it('start after stop is a no-op (F26)', async () => {
- const t = setup()
- t.host.stop('revoked')
- t.host.start()
- await new Promise((r) => setTimeout(r, 10))
- expect(t.mints()).toBe(0)
- expect(t.peers).toHaveLength(0)
- })
-
- it('a 410 from the host-token route ends the link as gone', async () => {
- const t = setup({ mint: async () => ({ ok: false, kind: 'gone', reason: 'expired' }) })
- t.host.start()
- await vi.waitFor(() => expect(t.gone).toEqual(['expired']))
- })
-
- it('a peer that never confirms is closed at the confirm deadline, freeing its slot (R31)', async () => {
- const clock = manualClock()
- const t = setup({ clock })
- t.host.start()
- await vi.waitFor(() => expect(t.peers).toHaveLength(1))
- let closed = 0
- connectRelay({
- url: 'x', token: 'x', role: 'client', theirPubB64: publicKeyToB64(t.keys.host.publicKey),
- ourKeys: { publicKey: t.keys.viewer.publicKey, secretKey: t.keys.viewer.secretKey },
- transport: t.peers[0], onReady: () => {}, onRpc: () => {}, onFrame: () => {},
- onClose: () => { closed++ }
- })
- await vi.waitFor(() => expect(t.peers).toHaveLength(2)) // bridged: a replacement opened
- await clock.advance(CONFIRM_DEADLINE_MS - 1)
- expect(closed).toBe(0)
- await clock.advance(1)
- expect(closed).toBe(1)
- expect(t.sinks.size).toBe(0)
- // A confirming viewer on the replacement is not affected by that deadline.
- const v = viewer(t.peers[1], t.keys)
- await vi.waitFor(() => expect(v.keyframes()).toHaveLength(1))
- await clock.advance(CONFIRM_DEADLINE_MS)
- expect(t.host.viewers()).toHaveLength(1)
- })
-
- it('a full link opens no 11th listener and polls status; a server-side revoke ends it', async () => {
- const clock = manualClock()
- let state: 'live' | 'revoked' = 'live'
- const status = vi.fn(async () => state)
- const t = setup({ clock, status })
- t.host.start()
- const vs: Viewer[] = []
- for (let i = 0; i < MAX_VIEWERS_PER_LINK; i++) vs.push(await openViewer(t, i))
- await clock.flush()
- expect(t.peers).toHaveLength(MAX_VIEWERS_PER_LINK) // no idle listener while full
- // Finding L6: a revoke made elsewhere reaches a full link's viewers within a minute (it was five).
- expect(FULL_STATUS_POLL_MS).toBe(60_000)
- await clock.advance(FULL_STATUS_POLL_MS - 1)
- expect(status).not.toHaveBeenCalled()
- await clock.advance(1)
- expect(status).toHaveBeenCalledTimes(1)
- expect(t.gone).toEqual([])
- state = 'revoked'
- // On a FULL link any viewer ending while the scheduler still runs would re-mint a listener: the
- // revoke's stop must end them only after the scheduler stopped (F1, R37).
- const minted = t.mints()
- await clock.advance(FULL_STATUS_POLL_MS)
- expect(status).toHaveBeenCalledTimes(2)
- expect(t.gone).toEqual(['revoked'])
- for (const v of vs) expect(v.named(WATCH_EVENT.end)).toEqual([{ reason: 'revoked' }])
- await clock.advance(60_000)
- expect(t.mints()).toBe(minted)
- expect(t.peers).toHaveLength(MAX_VIEWERS_PER_LINK)
- })
-
- it('stop on a full link with a viewer over 8 MiB behind mints nothing; that viewer is closed without an end (R37)', async () => {
- const clock = manualClock()
- const buffered: number[] = []
- const t = setup({ clock, buffered: (i) => buffered[i] ?? 0 })
- t.host.start()
- const vs: Viewer[] = []
- for (let i = 0; i < MAX_VIEWERS_PER_LINK; i++) vs.push(await openViewer(t, i))
- await clock.flush()
- const minted = t.mints()
- buffered[3] = 9 * 1024 * 1024
- t.host.stop('revoked')
- await clock.advance(60_000)
- expect(t.mints()).toBe(minted)
- expect(vs[3].named(WATCH_EVENT.end)).toEqual([])
- await vi.waitFor(() => expect(vs[3].log.closed).toBe(1))
- vs.forEach((v, i) => {
- if (i !== 3) expect(v.named(WATCH_EVENT.end)).toEqual([{ reason: 'revoked' }])
- })
- expect(t.sinks.size).toBe(0)
- expect(t.left).toHaveLength(MAX_VIEWERS_PER_LINK)
- })
-})
-
-describe('createLinkHost — read-back (watch:history)', () => {
- const say = (role: 'user' | 'assistant', at: number, text: string): ChatMessage => ({ role, at, parts: [{ kind: 'text', text }] })
- const page = (messages: ChatMessage[], olderCursor: number | null = null): HistoryRead => ({
- kind: 'page',
- result: { messages, found: true, olderCursor, unmatchedResults: [] }
- })
- const pages = (v: Viewer) => v.named(WATCH_EVENT.history) as WatchHistoryPage[]
-
- it('tells the viewer in its meta whether read-back is there, on every link', async () => {
- const on = setup({ role: 'viewer', historySupported: () => true })
- on.host.start()
- const a = await openViewer(on)
- expect((a.named(WATCH_EVENT.meta)[0] as WatchMeta).history).toBe(true)
- const off = setup({ role: 'viewer' })
- off.host.start()
- const b = await openViewer(off)
- expect((b.named(WATCH_EVENT.meta)[0] as WatchMeta).history).toBeUndefined()
- const throws = setup({ role: 'viewer', historySupported: () => { throw new Error('boom') } })
- throws.host.start()
- const c = await openViewer(throws)
- expect((c.named(WATCH_EVENT.meta)[0] as WatchMeta).history).toBeUndefined()
- })
-
- it('answers a Viewer link with what was written after the link was created, and nothing before', async () => {
- const t = setup({ role: 'viewer', history: async () => page([say('user', 9_000, 'before the link'), say('assistant', 12_000, 'after the link')], 64) })
- t.record.createdAt = 10_000
- t.host.start()
- const v = await openViewer(t)
- expect(v.c.requestHistory()).toBe(true)
- await vi.waitFor(() => expect(pages(v)).toHaveLength(1))
- expect(t.reads).toEqual([null])
- expect(pages(v)[0]).toMatchObject({ before: null, status: 'ok', since: 10_000, olderCursor: null, start: 'shared' })
- expect(JSON.stringify(pages(v)[0])).not.toContain('before the link')
- expect(pages(v)[0].messages.map((m) => (m.parts[0] as { text: string }).text)).toEqual(['after the link'])
- // Only the asker hears the answer: it is not a broadcast.
- expect(t.host.viewers()).toHaveLength(1)
- })
-
- it('passes the cursor through, and answers it with the page it asked for', async () => {
- const t = setup({ role: 'commenter', history: async (before) => page([say('user', 5_000, `b${before}`)], 0) })
- t.host.start()
- const v = await openViewer(t)
- v.c.requestHistory(4096)
- await vi.waitFor(() => expect(pages(v)).toHaveLength(1))
- expect(t.reads).toEqual([4096])
- expect(pages(v)[0]).toMatchObject({ before: 4096, olderCursor: 0, start: null })
- })
-
- it('says unsupported with no reader, and error on a failed read; the viewer stays connected', async () => {
- const none = setup({ role: 'viewer' })
- none.host.start()
- const a = await openViewer(none)
- a.c.requestHistory()
- await vi.waitFor(() => expect(pages(a)).toHaveLength(1))
- expect(pages(a)[0].status).toBe('unsupported')
- const failing = setup({ role: 'viewer', history: async () => { throw new Error('ssh: master is gone') } })
- failing.host.start()
- const b = await openViewer(failing)
- b.c.requestHistory()
- await vi.waitFor(() => expect(pages(b)).toHaveLength(1))
- expect(pages(b)[0]).toMatchObject({ status: 'error', messages: [] })
- expect(b.log.closed).toBe(0)
- expect(failing.host.viewers()).toHaveLength(1)
- })
-
- it('reads one page at a time per viewer, and runs only the latest request that waited', async () => {
- let release!: () => void
- const held = new Promise<void>((r) => (release = r))
- let first = true
- const t = setup({
- role: 'viewer',
- history: async (before) => {
- if (first) {
- first = false
- await held
- }
- return page([say('user', 5_000, `b${before}`)], null)
- }
- })
- t.host.start()
- const v = await openViewer(t)
- v.c.requestHistory()
- await vi.waitFor(() => expect(t.reads).toEqual([null]))
- v.c.requestHistory(10)
- v.c.requestHistory(20)
- await settleReal()
- expect(t.reads).toEqual([null])
- release()
- await vi.waitFor(() => expect(pages(v)).toHaveLength(2), { timeout: 3000 })
- expect(t.reads).toEqual([null, 20])
- expect(pages(v).map((p) => p.before)).toEqual([null, 20])
- })
-
- it('ignores a malformed request: no read, no answer, no disconnect', async () => {
- const t = setup({ role: 'viewer', history: async () => page([]) })
- t.host.start()
- const p = await openRaw(t)
- p.cast(WATCH_HISTORY_CAST, [{ before: -5 }])
- p.cast(WATCH_HISTORY_CAST, ['nope'])
- await settleReal()
- expect(t.reads).toEqual([])
- expect(p.named(WATCH_EVENT.history)).toHaveLength(0)
- expect(p.closed()).toBe(0)
- })
-})
-
-/** A raw relay client with the link's viewer key: it sends whatever casts the test chooses (the real
- * client cannot send a malformed one), and records every event the host sends it. */
-function rawPeer(t: Setup, n = 0) {
- const events: [string, unknown[]][] = []
- let hostConfirmed = false
- let closed = 0
- const raw = connectRelay({
- url: 'x', token: 'x', role: 'client', theirPubB64: publicKeyToB64(t.keys.host.publicKey),
- ourKeys: { publicKey: t.keys.viewer.publicKey, secretKey: t.keys.viewer.secretKey },
- transport: t.peers[n], onReady: () => {}, onRpc: () => {}, onFrame: () => {},
- onClose: () => { closed++ },
- onTunnel: (kind, p) => {
- if (kind !== 'text') return
- const m = parseRpcMessage(new TextDecoder().decode(p))
- if (m?.t === 'cast' && m.method === 'trust:confirm') hostConfirmed = true
- if (m?.t === 'ev') events.push([m.channel, m.args])
- }
- })
- return {
- hostConfirmed: () => hostConfirmed,
- closed: () => closed,
- confirm: () => raw.sendTunnelText(TRUST_CONFIRM),
- cast: (method: string, args: unknown[]) => raw.sendTunnelText(JSON.stringify({ t: 'cast', method, args })),
- named: (ch: string) => events.filter((e) => e[0] === ch).map((e) => e[1][0])
- }
-}
-type RawPeer = ReturnType<typeof rawPeer>
-/** Open the n-th listener with a raw peer, confirm, and wait for its first keyframe. */
-async function openRaw(t: Setup, n = 0): Promise<RawPeer> {
- await vi.waitFor(() => expect(t.peers.length).toBeGreaterThan(n))
- const p = rawPeer(t, n)
- await vi.waitFor(() => expect(p.hostConfirmed()).toBe(true))
- p.confirm()
- await vi.waitFor(() => expect(p.named(WATCH_EVENT.keyframe).length).toBeGreaterThanOrEqual(1))
- return p
-}
-function deferred<T>() {
- let resolve!: (v: T) => void
- const promise = new Promise<T>((r) => (resolve = r))
- return { promise, resolve }
-}
-const settleReal = (ms = 40): Promise<void> => new Promise((r) => setTimeout(r, ms))
-/** A pane delivery whose FIRST call waits for `release()` (true); every later call answers true. */
-function holdFirst() {
- const held = deferred<boolean>()
- let first = true
- return {
- input: (): Promise<boolean> | boolean => {
- if (!first) return true
- first = false
- return held.promise
- },
- release: () => held.resolve(true)
- }
-}
-
-// A Control link: unlocking with the link's password, the host-side throttles and the lock. The
-// password check is the real scrypt one (`verifyControlPassword` against `record.control`, read at
-// call time, as the service does), so a wait for an answer is a wait on real time.
-const PW = 'hunter2hunter2'
-const WRONG = 'not-the-password'
-
-describe('createLinkHost — control', () => {
- let HASH: ControlPasswordHash
- beforeAll(async () => {
- HASH = await hashControlPassword(PW)
- })
- const ctl = (over: Partial<WatchLinkControlRecord> = {}): WatchLinkControlRecord => ({ enabled: true, locked: false, wrong: 0, ...HASH, ...over })
- const controlOf = (v: Viewer | RawPeer): WatchControlEvent[] => v.named(WATCH_EVENT.control) as WatchControlEvent[]
- const metaOf = (v: Viewer, n = 0): WatchMeta => v.named(WATCH_EVENT.meta)[n] as WatchMeta
- /** Send one cast and wait for the `watch:control` that answers it. */
- async function ask(v: Viewer | RawPeer, send: () => unknown): Promise<WatchControlEvent> {
- const before = controlOf(v).length
- const sent = send()
- if (typeof sent === 'boolean') expect(sent).toBe(true)
- await vi.waitFor(() => expect(controlOf(v).length).toBeGreaterThan(before), { timeout: 5_000 })
- return controlOf(v)[before]
- }
- const unlock = (v: Viewer, name: string, pw: unknown): Promise<WatchControlEvent> =>
- ask(v, () => v.c.unlock(name, pw as string))
- const rawUnlock = (p: RawPeer, args: unknown[]): Promise<WatchControlEvent> => ask(p, () => p.cast(WATCH_UNLOCK_CAST, args))
- const controller = (o: SetupOpts = {}): Setup => setup({ role: 'controller', control: ctl(), ...o })
-
- // --- meta -------------------------------------------------------------------------------------------
-
- it('meta.control is available on a Control link with typing on, and absent on viewer and commenter links', async () => {
- const t = controller()
- t.host.start()
- const v = await openViewer(t)
- expect(metaOf(v)).toMatchObject({ role: 'controller' })
- expect(metaOf(v).control).toEqual({ state: 'available' })
- for (const role of ['viewer', 'commenter'] as const) {
- const o = setup({ role })
- o.host.start()
- const w = await openViewer(o)
- expect(metaOf(w)).toMatchObject({ role })
- expect('control' in metaOf(w)).toBe(false)
- }
- })
-
- it('meta.control is off when typing is off and locked when the link is locked; locked wins over off', async () => {
- const cases: { control: WatchLinkControlRecord; want: WatchControlEvent }[] = [
- { control: ctl({ enabled: false }), want: { state: 'off' } },
- { control: ctl({ locked: true }), want: { state: 'locked' } },
- { control: ctl({ enabled: false, locked: true }), want: { state: 'locked' } }
- ]
- for (const c of cases) {
- const t = controller({ control: c.control })
- t.host.start()
- const v = await openViewer(t)
- expect(metaOf(v).control).toEqual(c.want)
- }
- })
-
- it('meta.control says controlling on a rejoin while this viewer controls: control is per connection, not per session', async () => {
- const clock = manualClock()
- let n = 0
- const t = controller({ clock, join: () => ({ sessionId: `s${++n}`, cols: 80, rows: 24, altScreen: true }) })
- t.host.start()
- const v = await openViewer(t)
- expect(await unlock(v, 'Ada', PW)).toEqual({ state: 'controlling' })
- ptyEvent(t.sink(), IPC.ptyExit('s1'), 0)
- await clock.flush()
- await clock.advance(REJOIN_BACKOFF_MS[0])
- await vi.waitFor(() => expect(v.named(WATCH_EVENT.meta)).toHaveLength(2))
- expect(metaOf(v, 1).control).toEqual({ state: 'controlling' })
- // A viewer that never unlocked joins the same link as `available`.
- const w = await openViewer(t, 1)
- expect(metaOf(w).control).toEqual({ state: 'available' })
- })
-
- // --- finding L3: the unlock is sealed to a key pair of THIS connection's ---------------------------
-
- it('a Control link offers each connection its own unlock key, the same on every rejoin; other roles none', async () => {
- const clock = manualClock()
- let n = 0
- const t = controller({ clock, join: () => ({ sessionId: `s${++n}`, cols: 80, rows: 24, altScreen: true }) })
- t.host.start()
- const a = await openViewer(t, 0)
- const b = await openViewer(t, 1)
- const ka = metaOf(a).unlockKey
- expect(readUnlockKey(ka)).not.toBeNull()
- expect(readUnlockKey(metaOf(b).unlockKey)).not.toBeNull()
- expect(metaOf(b).unlockKey).not.toBe(ka)
- // Not derived from the link: nothing a link holder can compute.
- expect([bytesToB64(t.keys.host.publicKey), bytesToB64(t.keys.viewer.publicKey)]).not.toContain(ka)
- ptyEvent(t.sink(0), IPC.ptyExit('s1'), 0)
- await clock.flush()
- await clock.advance(REJOIN_BACKOFF_MS[0])
- await vi.waitFor(() => expect(a.named(WATCH_EVENT.meta)).toHaveLength(2))
- expect(metaOf(a, 1).unlockKey).toBe(ka)
- for (const role of ['viewer', 'commenter'] as const) {
- const o = setup({ role })
- o.host.start()
- const w = await openViewer(o)
- expect('unlockKey' in metaOf(w)).toBe(false)
- }
- })
-
- it('a sealed unlock opens with the connection key: the right password controls, and the real client seals', async () => {
- const t = controller()
- t.host.start()
- // The real client (it seals on its own once the meta offered a key).
- const v = await openViewer(t, 0)
- expect(await unlock(v, 'Ada', PW)).toEqual({ state: 'controlling' })
- // A raw peer sealing it by hand to the key its own meta offered.
- const p = await openRaw(t, 1)
- const key = readUnlockKey((p.named(WATCH_EVENT.meta)[0] as WatchMeta).unlockKey)!
- expect(await rawUnlock(p, [sealUnlock('Bob', PW, key)])).toEqual({ state: 'controlling' })
- expect(t.taken).toEqual(['Ada', 'Bob'])
- })
-
- it('an unlock sealed to another key (another connection\'s, a replay) is wrong and counted, never verified', async () => {
- const clock = manualClock()
- const t = controller({ clock })
- t.host.start()
- const other = await openRaw(t, 0)
- const p = await openRaw(t, 1)
- const otherKey = readUnlockKey((other.named(WATCH_EVENT.meta)[0] as WatchMeta).unlockKey)!
- await clock.advance(UNLOCK_MIN_INTERVAL_MS)
- expect(await rawUnlock(p, [sealUnlock('Eve', PW, otherKey)])).toEqual({ state: 'available', reason: 'wrong' })
- await clock.advance(UNLOCK_MIN_INTERVAL_MS)
- expect(await rawUnlock(p, [{ sealed: { key: 'x', nonce: 'y', box: 'z' } }])).toEqual({ state: 'available', reason: 'wrong' })
- expect(t.verifies()).toBe(0)
- expect(t.wrongs).toEqual([1, 2])
- })
-
- it('a plain unlock (a page from before sealing) still works — but not after the same connection sent a sealed one', async () => {
- const clock = manualClock()
- const t = controller({ clock })
- t.host.start()
- const old = await openRaw(t, 0)
- expect(await rawUnlock(old, [{ name: 'Ada', password: PW }])).toEqual({ state: 'controlling' })
- const p = await openRaw(t, 1)
- const key = readUnlockKey((p.named(WATCH_EVENT.meta)[0] as WatchMeta).unlockKey)!
- await clock.advance(UNLOCK_MIN_INTERVAL_MS)
- expect(await rawUnlock(p, [sealUnlock('Bob', WRONG, key)])).toEqual({ state: 'available', reason: 'wrong' })
- const verified = t.verifies()
- await clock.advance(UNLOCK_MIN_INTERVAL_MS)
- // The right password, in the clear, on a connection that seals: refused unverified, counted.
- expect(await rawUnlock(p, [{ name: 'Bob', password: PW }])).toEqual({ state: 'available', reason: 'wrong' })
- expect(t.verifies()).toBe(verified)
- expect(t.taken).toEqual(['Ada'])
- })
-
- // --- watch:unlock -----------------------------------------------------------------------------------
-
- it('an unlock sent before the viewer joined is ignored, even with the right password: no answer, no verification', async () => {
- const t = controller()
- t.host.start()
- await vi.waitFor(() => expect(t.peers).toHaveLength(1))
- const p = rawPeer(t, 0)
- await vi.waitFor(() => expect(p.hostConfirmed()).toBe(true))
- p.cast(WATCH_UNLOCK_CAST, [{ name: 'Ada', password: PW }]) // before our own confirm: not joined
- p.confirm()
- await vi.waitFor(() => expect(p.named(WATCH_EVENT.keyframe)).toHaveLength(1))
- await settleReal()
- expect(controlOf(p)).toEqual([])
- expect(t.verifies()).toBe(0)
- expect(t.host.viewers().map((x) => x.controlling)).toEqual([false])
- })
-
- it('a malformed unlock is answered wrong and COUNTED, with no verification — a 129-code-point password included', async () => {
- const clock = manualClock()
- const t = controller({ clock })
- t.host.start()
- // Through the real client: a name that does not survive sanitizing, a password that is not a
- // string, a password one code point too long. Three of them end the connection.
- const v = await openViewer(t, 0)
- expect(await unlock(v, '\u202e', PW)).toEqual({ state: 'available', reason: 'wrong' })
- await clock.advance(UNLOCK_MIN_INTERVAL_MS)
- expect(await unlock(v, 'Ada', 12345678)).toEqual({ state: 'available', reason: 'wrong' })
- await clock.advance(UNLOCK_MIN_INTERVAL_MS)
- expect(await unlock(v, 'Ada', 'a'.repeat(129))).toEqual({ state: 'available', reason: 'wrong' })
- await vi.waitFor(() => expect(v.named(WATCH_EVENT.end)).toEqual([{ reason: 'attempts' }]))
- expect(t.verifies()).toBe(0)
- // Through a raw peer: no payload object at all, and 129 code points spelled as surrogate pairs.
- const p = await openRaw(t, 1)
- expect(await rawUnlock(p, [5])).toEqual({ state: 'available', reason: 'wrong' })
- await clock.advance(UNLOCK_MIN_INTERVAL_MS)
- expect(await rawUnlock(p, [{ name: 'Ada', password: '\u{1F600}'.repeat(129) }])).toEqual({ state: 'available', reason: 'wrong' })
- expect(t.verifies()).toBe(0)
- // 128 code points is a password (256 UTF-16 units): it is verified, and is wrong.
- await clock.advance(UNLOCK_MIN_INTERVAL_MS)
- expect(await rawUnlock(p, [{ name: 'Ada', password: '\u{1F600}'.repeat(128) }])).toEqual({ state: 'available', reason: 'wrong' })
- expect(t.verifies()).toBe(1)
- await vi.waitFor(() => expect(p.named(WATCH_EVENT.end)).toEqual([{ reason: 'attempts' }]))
- expect(t.taken).toEqual([])
- })
-
- it("an attempt within 2 s of this viewer's previous one is too-soon and NOT counted", async () => {
- const clock = manualClock()
- const t = controller({ clock })
- t.host.start()
- const v = await openViewer(t)
- expect(await unlock(v, 'Ada', WRONG)).toEqual({ state: 'available', reason: 'wrong' })
- await clock.advance(UNLOCK_MIN_INTERVAL_MS - 1)
- expect(await unlock(v, 'Ada', PW)).toEqual({ state: 'available', reason: 'too-soon' })
- expect(t.verifies()).toBe(1)
- await clock.advance(1)
- expect(await unlock(v, 'Ada', WRONG)).toEqual({ state: 'available', reason: 'wrong' })
- // Two counted wrong attempts: still connected (the too-soon one did not count).
- await settleReal()
- expect(t.host.viewers()).toHaveLength(1)
- expect(v.named(WATCH_EVENT.end)).toEqual([])
- await clock.advance(UNLOCK_MIN_INTERVAL_MS)
- expect(await unlock(v, 'Ada', WRONG)).toEqual({ state: 'available', reason: 'wrong' })
- await vi.waitFor(() => expect(v.named(WATCH_EVENT.end)).toEqual([{ reason: 'attempts' }]))
- })
-
- it("an attempt while another verification for this link is in flight is too-soon, and not verified", async () => {
- const held = deferred<boolean>()
- let calls = 0
- const t = controller({
- verifyPassword: (pw) => (++calls === 1 ? held.promise : verifyControlPassword(pw, HASH))
- })
- t.host.start()
- const a = await openViewer(t, 0)
- const b = await openViewer(t, 1)
- expect(a.c.unlock('Ada', PW)).toBe(true)
- await vi.waitFor(() => expect(t.verifies()).toBe(1))
- expect(await unlock(b, 'Bob', PW)).toEqual({ state: 'available', reason: 'too-soon' })
- expect(t.verifies()).toBe(1)
- held.resolve(false)
- await vi.waitFor(() => expect(controlOf(a)).toEqual([{ state: 'available', reason: 'wrong' }]))
- // The flight is over: Bob's next attempt (his previous was not stamped) is verified.
- expect(await unlock(b, 'Bob', PW)).toEqual({ state: 'controlling' })
- expect(t.verifies()).toBe(2)
- })
-
- it('a locked link answers locked and an off link answers off, without verifying or counting', async () => {
- const clock = manualClock()
- for (const c of [{ control: ctl({ locked: true }), want: { state: 'locked', reason: 'locked' } }, { control: ctl({ enabled: false }), want: { state: 'off', reason: 'off' } }]) {
- const t = controller({ clock, control: c.control })
- t.host.start()
- const v = await openViewer(t)
- for (let i = 0; i < WRONG_PER_CONN + 1; i++) {
- expect(await unlock(v, 'Ada', i % 2 ? PW : WRONG)).toEqual(c.want)
- await clock.advance(UNLOCK_MIN_INTERVAL_MS)
- }
- expect(t.verifies()).toBe(0)
- expect(v.named(WATCH_EVENT.end)).toEqual([])
- expect(t.host.viewers()).toHaveLength(1)
- t.host.stop('revoked')
- }
- })
-
- it('an unlock from a viewer already controlling answers controlling and does nothing else', async () => {
- const clock = manualClock()
- const t = controller({ clock })
- t.host.start()
- const v = await openViewer(t)
- expect(await unlock(v, 'Ada', PW)).toEqual({ state: 'controlling' })
- const changes = t.changes()
- await clock.advance(UNLOCK_MIN_INTERVAL_MS)
- expect(await unlock(v, 'Eve', WRONG)).toEqual({ state: 'controlling' })
- expect(t.verifies()).toBe(1)
- expect(t.taken).toEqual(['Ada'])
- expect(t.changes()).toBe(changes)
- expect(t.host.viewers()[0]).toMatchObject({ name: 'Ada', controlling: true })
- })
-
- it('a wrong password answers available/wrong; the third on one connection ends it with `attempts`', async () => {
- const clock = manualClock()
- const t = controller({ clock })
- t.host.start()
- const v = await openViewer(t)
- for (let i = 0; i < WRONG_PER_CONN; i++) {
- if (i > 0) await clock.advance(UNLOCK_MIN_INTERVAL_MS)
- expect(await unlock(v, 'Ada', WRONG)).toEqual({ state: 'available', reason: 'wrong' })
- }
- await vi.waitFor(() => expect(v.named(WATCH_EVENT.end)).toEqual([{ reason: 'attempts' }]))
- await vi.waitFor(() => expect(v.log.closed).toBe(1))
- expect(t.host.viewers()).toEqual([])
- expect(t.verifies()).toBe(WRONG_PER_CONN)
- expect(t.taken).toEqual([])
- expect(t.locks()).toBe(0)
- })
-
- it('the right password makes this viewer controlling under its sanitized name, tells the owner, and resets its own wrong count', async () => {
- const clock = manualClock()
- const t = controller({ clock })
- t.host.start()
- const v = await openViewer(t)
- expect(await unlock(v, 'Ada', WRONG)).toEqual({ state: 'available', reason: 'wrong' })
- await clock.advance(UNLOCK_MIN_INTERVAL_MS)
- expect(await unlock(v, 'Ada', WRONG)).toEqual({ state: 'available', reason: 'wrong' })
- await clock.advance(UNLOCK_MIN_INTERVAL_MS)
- const changes = t.changes()
- expect(await unlock(v, ' Ada\u202e Lovelace\t', PW)).toEqual({ state: 'controlling' })
- expect(t.taken).toEqual(['Ada Lovelace'])
- expect(t.changes()).toBeGreaterThan(changes)
- expect(t.host.viewers()).toEqual([
- expect.objectContaining({ name: 'Ada Lovelace', controlling: true, typing: false })
- ])
- // Two wrong before the success; after it (and a release) two more do not end the connection.
- expect(await ask(v, () => v.c.release())).toEqual({ state: 'available' })
- await clock.advance(UNLOCK_MIN_INTERVAL_MS)
- expect(await unlock(v, 'Ada', WRONG)).toEqual({ state: 'available', reason: 'wrong' })
- await clock.advance(UNLOCK_MIN_INTERVAL_MS)
- expect(await unlock(v, 'Ada', WRONG)).toEqual({ state: 'available', reason: 'wrong' })
- await settleReal()
- expect(v.named(WATCH_EVENT.end)).toEqual([])
- expect(t.host.viewers()).toHaveLength(1)
- })
-
- it('a verification is re-checked after its await: control turned off meanwhile is no success', async () => {
- const held = deferred<boolean>()
- const t = controller({ verifyPassword: () => held.promise })
- t.host.start()
- const v = await openViewer(t)
- expect(v.c.unlock('Ada', PW)).toBe(true)
- await vi.waitFor(() => expect(t.verifies()).toBe(1))
- t.record.control!.enabled = false
- t.host.controlChanged()
- await vi.waitFor(() => expect(controlOf(v)).toEqual([{ state: 'off' }]))
- held.resolve(true)
- await vi.waitFor(() => expect(controlOf(v)).toEqual([{ state: 'off' }, { state: 'off', reason: 'off' }]))
- expect(t.taken).toEqual([])
- expect(t.host.viewers()[0].controlling).toBe(false)
- })
-
- it('a verification is re-checked after its await: a password change, a kicked viewer or a stopped host meanwhile is no success', async () => {
- // The password changed while the old one was being checked: the old one must not open it.
- {
- const held = deferred<boolean>()
- const t = controller({ verifyPassword: () => held.promise })
- t.host.start()
- const v = await openViewer(t)
- expect(v.c.unlock('Ada', PW)).toBe(true)
- await vi.waitFor(() => expect(t.verifies()).toBe(1))
- t.host.passwordChanged()
- held.resolve(true)
- // A verification that raced a change is void, not wrong: not counted, and the viewer may retry.
- await vi.waitFor(() => expect(controlOf(v)).toEqual([{ state: 'available', reason: 'too-soon' }]))
- expect(t.taken).toEqual([])
- expect(t.host.viewers()[0].controlling).toBe(false)
- }
- for (const end of ['kick', 'stop'] as const) {
- const held = deferred<boolean>()
- const t = controller({ verifyPassword: () => held.promise })
- t.host.start()
- const v = await openViewer(t)
- expect(v.c.unlock('Ada', PW)).toBe(true)
- await vi.waitFor(() => expect(t.verifies()).toBe(1))
- if (end === 'kick') t.host.kick(t.host.viewers()[0].viewerId)
- else t.host.stop('revoked')
- held.resolve(true)
- await settleReal()
- expect(t.taken).toEqual([])
- expect(controlOf(v)).toEqual([])
- }
- })
-
- // --- the link-wide lock -----------------------------------------------------------------------------
-
- it('the 10th wrong attempt across the link locks it once: every viewer is told, controllers are demoted, the 11th is not verified', async () => {
- const clock = manualClock()
- const t = controller({ clock })
- t.host.start()
- const ada = await openViewer(t, 0)
- let n = 1
- /** A fresh viewer for each three wrong attempts (three end a connection). */
- const attacker = async (attempts: number): Promise<Viewer> => {
- const v = await openViewer(t, n++)
- for (let i = 0; i < attempts; i++) {
- await clock.advance(UNLOCK_MIN_INTERVAL_MS)
- expect(await unlock(v, 'Eve', `${WRONG}-${i}`)).toEqual({ state: 'available', reason: 'wrong' })
- }
- return v
- }
- await attacker(3)
- // Ada unlocks after three wrong attempts: a success does not reset the LINK's count.
- expect(await unlock(ada, 'Ada', PW)).toEqual({ state: 'controlling' })
- await attacker(3)
- await attacker(3)
- expect(t.locks()).toBe(0)
- const eve = await openViewer(t, n++)
- await clock.advance(UNLOCK_MIN_INTERVAL_MS)
- const before = controlOf(eve).length
- expect(eve.c.unlock('Eve', WRONG)).toBe(true)
- await vi.waitFor(() => expect(controlOf(eve).slice(before)).toEqual([
- { state: 'available', reason: 'wrong' },
- { state: 'locked', reason: 'locked' }
- ]))
- expect(t.locks()).toBe(1)
- expect(t.record.control!.locked).toBe(true)
- await vi.waitFor(() => expect(controlOf(ada).at(-1)).toEqual({ state: 'locked', reason: 'locked' }))
- expect(t.host.viewers().find((x) => x.name === 'Ada')!.controlling).toBe(false)
- // The 11th attempt — the right password, even — is answered locked and never verified.
- const verified = t.verifies()
- await clock.advance(UNLOCK_MIN_INTERVAL_MS)
- expect(await unlock(eve, 'Eve', PW)).toEqual({ state: 'locked', reason: 'locked' })
- expect(t.verifies()).toBe(verified)
- expect(t.locks()).toBe(1)
- expect(t.taken).toEqual(['Ada'])
- }, 20_000) // eleven real scrypt checks
-
- // Finding L2: the service gives a lock a lift time; every viewer is told how long it lasts, and the
- // owner is told who tipped it.
- it('a timed lock tells each viewer how long it lasts: in the lock, in a refused unlock, in a later meta', async () => {
- const clock = manualClock()
- let n = 0
- const t: Setup = controller({
- clock,
- join: () => ({ sessionId: `s${++n}`, cols: 80, rows: 24, altScreen: true }),
- control: ctl({ wrong: WRONG_PER_LINK - 1 }),
- verifyPassword: async (pw) => pw === PW,
- onControlLocked: () => {
- t.record.control!.locked = true
- t.record.control!.lockedUntil = clock.now() + 15 * 60_000
- }
- })
- t.host.start()
- const v = await openViewer(t, 0)
- const w = await openViewer(t, 1)
- await clock.advance(UNLOCK_MIN_INTERVAL_MS)
- const before = controlOf(v).length
- expect(v.c.unlock('Eve', WRONG)).toBe(true)
- await vi.waitFor(() => expect(controlOf(v).slice(before)).toEqual([
- { state: 'available', reason: 'wrong' },
- { state: 'locked', reason: 'locked', lockedForMs: 15 * 60_000 }
- ]))
- await vi.waitFor(() => expect(controlOf(w).at(-1)).toEqual({ state: 'locked', reason: 'locked', lockedForMs: 15 * 60_000 }))
- expect(t.lockedBy).toEqual(['Eve'])
- await clock.advance(5 * 60_000)
- expect(await unlock(v, 'Eve', PW)).toEqual({ state: 'locked', reason: 'locked', lockedForMs: 10 * 60_000 })
- // A rejoin's meta says what is left.
- const metas = w.named(WATCH_EVENT.meta).length
- ptyEvent(t.sink(1), IPC.ptyExit('s2'), 0)
- await clock.flush()
- await clock.advance(REJOIN_BACKOFF_MS[0])
- await vi.waitFor(() => expect(w.named(WATCH_EVENT.meta)).toHaveLength(metas + 1))
- expect(metaOf(w, metas).control).toEqual({ state: 'locked', lockedForMs: 10 * 60_000 - REJOIN_BACKOFF_MS[0] })
- // The lock lifts (the service clears it and tells the host): every viewer may unlock again.
- t.record.control!.locked = false
- t.record.control!.lockedUntil = null
- t.host.allowControl()
- await vi.waitFor(() => expect(controlOf(w).at(-1)).toEqual({ state: 'available' }))
- await clock.advance(UNLOCK_MIN_INTERVAL_MS)
- expect(await unlock(w, 'Ada', PW)).toEqual({ state: 'controlling' })
- })
-
- it('the lock names who tipped it: the attempt\'s own name, else the chat name of the connection that sent it, else nobody', async () => {
- for (const c of [{ chat: 'Mallory', want: 'Mallory' }, { chat: null, want: null }]) {
- const clock = manualClock()
- const t = controller({ clock, control: ctl({ wrong: WRONG_PER_LINK - 1 }) })
- t.host.start()
- const p = await openRaw(t, 0)
- if (c.chat) {
- p.cast(WATCH_CHAT_CAST, [{ name: c.chat, text: 'hi' }])
- await vi.waitFor(() => expect(t.chats).toHaveLength(1))
- }
- await clock.advance(UNLOCK_MIN_INTERVAL_MS)
- // A malformed attempt (no name left once cleaned) tips it.
- await rawUnlock(p, [{ name: '\u200b', password: 'x' }])
- await vi.waitFor(() => expect(t.locks()).toBe(1))
- expect(t.lockedBy).toEqual([c.want])
- }
- })
-
- it('allowControl resets the link count and tells every viewer it is available again', async () => {
- const clock = manualClock()
- const t = controller({ clock, verifyPassword: async (pw) => pw === PW })
- t.host.start()
- const watcher = await openViewer(t, 0)
- let n = 1
- for (let wrong = 0; wrong < WRONG_PER_LINK; ) {
- const v = await openViewer(t, n++)
- for (let i = 0; i < WRONG_PER_CONN && wrong < WRONG_PER_LINK; i++, wrong++) {
- await clock.advance(UNLOCK_MIN_INTERVAL_MS)
- await unlock(v, 'Eve', WRONG)
- }
- }
- expect(t.locks()).toBe(1)
- await vi.waitFor(() => expect(controlOf(watcher).at(-1)).toEqual({ state: 'locked', reason: 'locked' }))
- // The service clears the lock, then tells the host.
- t.record.control!.locked = false
- const changes = t.changes()
- t.host.allowControl()
- await vi.waitFor(() => expect(controlOf(watcher).at(-1)).toEqual({ state: 'available' }))
- expect(t.changes()).toBeGreaterThan(changes)
- // The count was reset: one more wrong attempt does not lock again.
- await clock.advance(UNLOCK_MIN_INTERVAL_MS)
- expect(await unlock(watcher, 'Eve', WRONG)).toEqual({ state: 'available', reason: 'wrong' })
- expect(t.locks()).toBe(1)
- await clock.advance(UNLOCK_MIN_INTERVAL_MS)
- expect(await unlock(watcher, 'Ada', PW)).toEqual({ state: 'controlling' })
- })
-
- // Final review, Minor 2: the link-wide wrong count is the service's to keep (persisted beside
- // `locked`), so an app restart no longer hands out nine fresh guesses. The host starts from the
- // record's count and reports every new one.
- it('the link-wide count starts from the record: a host built from a record at 9 (a restart) locks on its next wrong attempt', async () => {
- const clock = manualClock()
- const t = controller({ clock, control: ctl({ wrong: WRONG_PER_LINK - 1 }), verifyPassword: async (pw) => pw === PW })
- t.host.start()
- const v = await openViewer(t, 0)
- await clock.advance(UNLOCK_MIN_INTERVAL_MS)
- const before = controlOf(v).length
- expect(v.c.unlock('Eve', WRONG)).toBe(true)
- await vi.waitFor(() => expect(controlOf(v).slice(before)).toEqual([
- { state: 'available', reason: 'wrong' },
- { state: 'locked', reason: 'locked' }
- ]))
- expect(t.locks()).toBe(1)
- expect(t.wrongs).toEqual([WRONG_PER_LINK])
- })
-
- it('every wrong attempt reports the new link-wide count, from the one the record holds', async () => {
- const clock = manualClock()
- const t = controller({ clock, control: ctl({ wrong: 4 }), verifyPassword: async (pw) => pw === PW })
- t.host.start()
- const v = await openViewer(t, 0)
- for (let i = 0; i < 2; i++) {
- await clock.advance(UNLOCK_MIN_INTERVAL_MS)
- expect(await unlock(v, 'Eve', WRONG)).toEqual({ state: 'available', reason: 'wrong' })
- }
- // A malformed attempt counts too.
- await clock.advance(UNLOCK_MIN_INTERVAL_MS)
- expect(await unlock(v, 'Eve', '')).toEqual({ state: 'available', reason: 'wrong' })
- expect(t.wrongs).toEqual([5, 6, 7])
- expect(t.record.control!.wrong).toBe(7)
- expect(t.locks()).toBe(0)
- })
-
- it('a password change resets the link-wide count: a host at 9 does not lock on the next wrong attempt', async () => {
- const clock = manualClock()
- const t = controller({ clock, control: ctl({ wrong: WRONG_PER_LINK - 1 }), verifyPassword: async (pw) => pw === PW })
- t.host.start()
- const v = await openViewer(t, 0)
- t.record.control!.wrong = 0 // what the service does with the new hash
- t.host.passwordChanged()
- await clock.advance(UNLOCK_MIN_INTERVAL_MS)
- expect(await unlock(v, 'Eve', WRONG)).toEqual({ state: 'available', reason: 'wrong' })
- expect(t.locks()).toBe(0)
- expect(t.wrongs).toEqual([1])
- })
-
- it('a record count outside 0..10 (a hand edit) is read as the nearest bound, never as more guesses', async () => {
- for (const [wrong, next] of [[-5, 1], [Number.NaN, 1], [1.5, 2], [99, WRONG_PER_LINK]] as const) {
- const clock = manualClock()
- const t = controller({ clock, control: ctl({ wrong }), verifyPassword: async (pw) => pw === PW })
- t.host.start()
- const v = await openViewer(t, 0)
- await clock.advance(UNLOCK_MIN_INTERVAL_MS)
- await unlock(v, 'Eve', WRONG)
- expect(t.wrongs, String(wrong)).toEqual([next])
- t.host.stop('revoked')
- }
- })
-
- // --- release and the owner's changes ----------------------------------------------------------------
-
- it('release drops a controller back to available; from anyone else it is ignored', async () => {
- const clock = manualClock()
- const t = controller({ clock })
- t.host.start()
- const a = await openViewer(t, 0)
- const b = await openViewer(t, 1)
- expect(await unlock(a, 'Ada', PW)).toEqual({ state: 'controlling' })
- const changes = t.changes()
- expect(await ask(a, () => a.c.release())).toEqual({ state: 'available' })
- expect(t.changes()).toBeGreaterThan(changes)
- expect(t.host.viewers().map((x) => x.controlling)).toEqual([false, false])
- const after = t.changes()
- expect(b.c.release()).toBe(true)
- expect(a.c.release()).toBe(true) // released already
- await settleReal()
- expect(controlOf(b)).toEqual([])
- expect(controlOf(a)).toHaveLength(2)
- expect(t.changes()).toBe(after)
- expect(t.host.viewers()).toHaveLength(2)
- })
-
- it('controlChanged: turned off demotes every controller and tells every viewer off; turned on, available', async () => {
- const clock = manualClock()
- const t = controller({ clock })
- t.host.start()
- const a = await openViewer(t, 0)
- const b = await openViewer(t, 1)
- expect(await unlock(a, 'Ada', PW)).toEqual({ state: 'controlling' })
- let changes = t.changes()
- t.record.control!.enabled = false
- t.host.controlChanged()
- await vi.waitFor(() => expect(controlOf(b)).toEqual([{ state: 'off' }]))
- expect(controlOf(a).at(-1)).toEqual({ state: 'off' })
- expect(t.host.viewers().map((x) => x.controlling)).toEqual([false, false])
- expect(t.changes()).toBeGreaterThan(changes)
- await clock.advance(UNLOCK_MIN_INTERVAL_MS)
- expect(await unlock(a, 'Ada', PW)).toEqual({ state: 'off', reason: 'off' })
- changes = t.changes()
- t.record.control!.enabled = true
- t.host.controlChanged()
- await vi.waitFor(() => expect(controlOf(b)).toEqual([{ state: 'off' }, { state: 'available' }]))
- expect(controlOf(a).at(-1)).toEqual({ state: 'available' })
- expect(t.changes()).toBeGreaterThan(changes)
- })
-
- it('passwordChanged demotes every controller and tells each one available; the old password no longer opens it', async () => {
- const clock = manualClock()
- const t = controller({ clock })
- t.host.start()
- const a = await openViewer(t, 0)
- const b = await openViewer(t, 1)
- expect(await unlock(a, 'Ada', PW)).toEqual({ state: 'controlling' })
- // What the service does: swap the hash, then tell the host.
- Object.assign(t.record.control!, await hashControlPassword('a-new-password'))
- const changes = t.changes()
- t.host.passwordChanged()
- await vi.waitFor(() => expect(controlOf(a).at(-1)).toEqual({ state: 'available' }))
- expect(t.host.viewers().map((x) => x.controlling)).toEqual([false, false])
- expect(t.changes()).toBeGreaterThan(changes)
- await settleReal()
- expect(controlOf(b)).toEqual([]) // never controlling: nothing to tell it
- await clock.advance(UNLOCK_MIN_INTERVAL_MS)
- expect(await unlock(a, 'Ada', PW)).toEqual({ state: 'available', reason: 'wrong' })
- await clock.advance(UNLOCK_MIN_INTERVAL_MS)
- expect(await unlock(a, 'Ada', 'a-new-password')).toEqual({ state: 'controlling' })
- })
-
- // --- chat and input ----------------------------------------------------------------------------------
-
- it('chat works on a Control link as on a Commenter link, both ways', async () => {
- const t = controller()
- t.host.start()
- const v = await openViewer(t)
- expect(v.c.sendChat('Ada', 'hello')).toBe(true)
- await vi.waitFor(() => expect(t.chats).toHaveLength(1))
- expect(t.chats[0]).toMatchObject({ name: 'Ada', text: 'hello', from: 'viewer' })
- expect(t.host.postSharerChat('hi back')).toMatchObject({ from: 'sharer', text: 'hi back' })
- await vi.waitFor(() => expect(v.named(WATCH_EVENT.chat)).toHaveLength(2))
- expect(t.host.viewers()).toHaveLength(1)
- })
-
- it('input from a viewer that is not controlling closes it; from a controller it reaches the pane; after a release it is dropped for 5 s, then a breach', async () => {
- const clock = manualClock()
- vi.spyOn(console, 'warn').mockImplementation(() => {})
- const t = controller({ clock })
- t.host.start()
- const a = await openViewer(t, 0)
- const b = await openViewer(t, 1)
- expect(b.c.sendInput('ls\r')).toBe(true)
- await vi.waitFor(() => expect(b.log.closed).toBe(1))
- expect(t.host.viewers()).toHaveLength(1)
- expect(await unlock(a, 'Ada', PW)).toEqual({ state: 'controlling' })
- expect(a.c.sendInput('ls\r')).toBe(true)
- await clock.advance(INPUT_BATCH_MS)
- await vi.waitFor(() => expect(t.inputs).toEqual([['s1', { kind: 'keys', data: 'ls\r' }]]))
- expect(a.log.closed).toBe(0)
- // Released: a keystroke still in flight is dropped, and the connection stays.
- expect(await ask(a, () => a.c.release())).toEqual({ state: 'available' })
- expect(a.c.sendInput('x')).toBe(true)
- await clock.advance(INPUT_GRACE_MS)
- expect(a.log.closed).toBe(0)
- expect(t.inputs).toHaveLength(1)
- // Past the grace it is a breach.
- await clock.advance(100)
- expect(a.c.sendInput('x')).toBe(true)
- await vi.waitFor(() => expect(a.log.closed).toBe(1))
- expect(t.host.viewers()).toEqual([])
- expect(t.inputs).toHaveLength(1)
- })
-
- it('on a Commenter link, unlock, input and release casts from a raw peer are refused before the host: nothing comes back, nothing is verified', async () => {
- const t = setup({ role: 'commenter' })
- t.host.start()
- const p = await openRaw(t, 0)
- p.cast(WATCH_UNLOCK_CAST, [{ name: 'Ada', password: PW }])
- p.cast(WATCH_INPUT_CAST, [{ data: 'ls\r' }])
- p.cast(WATCH_RELEASE_CAST, [])
- await settleReal(60)
- expect(controlOf(p)).toEqual([])
- expect(t.verifies()).toBe(0)
- // An input that reached the link host would have closed this viewer (a policy breach).
- expect(p.closed()).toBe(0)
- expect(t.host.viewers()).toHaveLength(1)
- })
-
- // --- hardening -----------------------------------------------------------------------------------
-
- it('a connection that ends on the success answer (backlog over 8 MiB) did not take control: no onControlTaken', async () => {
- const clock = manualClock()
- const held = deferred<boolean>()
- let buffered = 0
- const t = controller({ clock, verifyPassword: () => held.promise, buffered: () => buffered })
- t.host.start()
- const v = await openViewer(t)
- expect(v.c.unlock('Ada', PW)).toBe(true)
- await vi.waitFor(() => expect(t.verifies()).toBe(1))
- buffered = 9 * 1024 * 1024
- held.resolve(true)
- await vi.waitFor(() => expect(v.log.closed).toBe(1))
- expect(t.taken).toEqual([])
- expect(t.host.viewers()).toEqual([])
- })
-
- it('a lock the service failed to record is logged loudly once, and every viewer is still told and demoted', async () => {
- const clock = manualClock()
- const error = vi.spyOn(console, 'error').mockImplementation(() => {})
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
- const t = controller({
- clock,
- verifyPassword: async (pw) => pw === PW,
- onControlLocked: () => {
- throw new Error('disk on fire')
- }
- })
- t.host.start()
- const ada = await openViewer(t, 0)
- expect(await unlock(ada, 'Ada', PW)).toEqual({ state: 'controlling' })
- let n = 1
- for (let wrong = 0; wrong < WRONG_PER_LINK; ) {
- const v = await openViewer(t, n++)
- for (let i = 0; i < WRONG_PER_CONN && wrong < WRONG_PER_LINK; i++, wrong++) {
- await clock.advance(UNLOCK_MIN_INTERVAL_MS)
- await unlock(v, 'Eve', WRONG)
- }
- }
- expect(t.locks()).toBe(1)
- expect(t.record.control!.locked).toBe(false)
- expect(error).toHaveBeenCalledTimes(1)
- expect(String(error.mock.calls[0][0])).toMatch(/onControlLocked did not lock the link/)
- // Nothing the viewers chose is in it: no name, no password.
- for (const arg of error.mock.calls[0]) {
- expect(String(arg)).not.toContain('Eve')
- expect(String(arg)).not.toContain(WRONG)
- }
- await vi.waitFor(() => expect(controlOf(ada).at(-1)).toEqual({ state: 'locked', reason: 'locked' }))
- expect(t.host.viewers().find((x) => x.name === 'Ada')!.controlling).toBe(false)
- expect(warn).toHaveBeenCalled() // the throw itself, through safe()
- })
-
- it('a password check that rejects is void: too-soon, not counted, and the next attempt after 2 s is verified', async () => {
- const clock = manualClock()
- vi.spyOn(console, 'warn').mockImplementation(() => {})
- let calls = 0
- const t = controller({
- clock,
- verifyPassword: (pw) => (++calls === 1 ? Promise.reject(new Error('pool gone')) : verifyControlPassword(pw, HASH))
- })
- t.host.start()
- const v = await openViewer(t)
- expect(await unlock(v, 'Ada', PW)).toEqual({ state: 'available', reason: 'too-soon' })
- expect(t.verifies()).toBe(1)
- // Two counted wrong attempts after it: still connected, so the rejected one was not counted.
- await clock.advance(UNLOCK_MIN_INTERVAL_MS)
- expect(await unlock(v, 'Ada', WRONG)).toEqual({ state: 'available', reason: 'wrong' })
- await clock.advance(UNLOCK_MIN_INTERVAL_MS)
- expect(await unlock(v, 'Ada', WRONG)).toEqual({ state: 'available', reason: 'wrong' })
- await settleReal()
- expect(v.named(WATCH_EVENT.end)).toEqual([])
- // The flight was released: the next attempt is verified, and opens it.
- await clock.advance(UNLOCK_MIN_INTERVAL_MS)
- expect(await unlock(v, 'Ada', PW)).toEqual({ state: 'controlling' })
- expect(t.verifies()).toBe(4)
- })
-
- it('viewers() reports the effective state: a controller of a link whose control went off is not controlling', async () => {
- const t = controller()
- t.host.start()
- const v = await openViewer(t)
- expect(await unlock(v, 'Ada', PW)).toEqual({ state: 'controlling' })
- expect(t.host.viewers()[0].controlling).toBe(true)
- // The record changed, and the host has not been told yet.
- t.record.control!.enabled = false
- expect(t.host.viewers()[0].controlling).toBe(false)
- t.record.control!.enabled = true
- expect(t.host.viewers()[0].controlling).toBe(true)
- })
-
- // --- typing: the input path and the typing set ------------------------------------------------------
-
- describe('control typing', () => {
- /** A Control link whose password check is instant (the scrypt one is tested above). */
- const typist = (o: SetupOpts = {}): Setup => controller({ clock: manualClock(), verifyPassword: async (pw) => pw === PW, ...o })
- const dropped = (v: Viewer): WatchControlEvent[] => controlOf(v).filter((e) => e.reason === 'dropped')
- const typingOf = (v: Viewer): string[][] => (v.named(WATCH_EVENT.typing) as { names: string[] }[]).map((e) => e.names)
- /** Cast one input and let the host take it (the in-process transport delivers synchronously). */
- async function type(v: Viewer, data: string, clock: ManualClock): Promise<void> {
- expect(v.c.sendInput(data)).toBe(true)
- await clock.flush()
- }
- /** A typist link with one or more controllers, already unlocked. */
- async function controllers(names: string[], o: SetupOpts = {}) {
- const clock = o.clock ?? manualClock()
- const t = typist({ ...o, clock })
- t.host.start()
- const vs: Viewer[] = []
- for (let i = 0; i < names.length; i++) {
- const v = await openViewer(t, i)
- expect(await unlock(v, names[i], PW)).toEqual({ state: 'controlling' })
- vs.push(v)
- }
- return { t, clock, vs }
- }
- const delivered = (t: Setup): string[] =>
- t.inputs.map(([sid, c]) => `${sid}:${c.kind}:${c.kind === 'keys' ? c.data : c.text}`)
-
- it('a controller types `ls\\r`: one keys chunk to the joined session, after INPUT_BATCH_MS', async () => {
- const { t, clock, vs } = await controllers(['Ada'])
- await type(vs[0], 'l', clock)
- await type(vs[0], 's', clock)
- await type(vs[0], '\r', clock)
- await clock.advance(INPUT_BATCH_MS - 1)
- expect(t.inputs).toEqual([])
- await clock.advance(1)
- await vi.waitFor(() => expect(t.inputs).toEqual([['s1', { kind: 'keys', data: 'ls\r' }]]))
- expect(t.host.viewers()[0]).toMatchObject({ controlling: true, typing: true })
- expect(dropped(vs[0])).toEqual([])
- })
-
- it('a paste arrives as one paste chunk between the keys around it', async () => {
- const { t, clock, vs } = await controllers(['Ada'])
- await type(vs[0], `a${PASTE_START}echo 1\necho 2${PASTE_END}b`, clock)
- await clock.advance(INPUT_BATCH_MS)
- await vi.waitFor(() => expect(delivered(t)).toEqual(['s1:keys:a', 's1:paste:echo 1\necho 2', 's1:keys:b']))
- })
-
- it('a lone Esc reaches the pane within one batch (it is held as a marker prefix, then drained)', async () => {
- const { t, clock, vs } = await controllers(['Ada'])
- await type(vs[0], ESC, clock)
- await clock.advance(INPUT_BATCH_MS)
- await vi.waitFor(() => expect(delivered(t)).toEqual([`s1:keys:${ESC}`]))
- })
-
- it("a non-controlling viewer's input closes it and delivers nothing", async () => {
- const { t, clock, vs } = await controllers(['Ada'])
- vi.spyOn(console, 'warn').mockImplementation(() => {})
- const b = await openViewer(t, 1)
- await type(b, 'rm -rf ~\r', clock)
- await vi.waitFor(() => expect(b.log.closed).toBe(1))
- await clock.advance(INPUT_BATCH_MS)
- expect(t.inputs).toEqual([])
- expect(vs[0].log.closed).toBe(0)
- })
-
- it('malformed input from a controller is a breach: not a string, empty, or over INPUT_MAX', async () => {
- vi.spyOn(console, 'warn').mockImplementation(() => {})
- for (const args of [[{ data: 5 }], [{ data: '' }], [{ data: 'x'.repeat(INPUT_MAX + 1) }], [null], []]) {
- const clock = manualClock()
- const t = typist({ clock })
- t.host.start()
- const p = await openRaw(t, 0)
- p.cast(WATCH_UNLOCK_CAST, [{ name: 'Ada', password: PW }])
- await vi.waitFor(() => expect(controlOf(p)).toEqual([{ state: 'controlling' }]))
- p.cast(WATCH_INPUT_CAST, args)
- await vi.waitFor(() => expect(p.closed()).toBe(1))
- await clock.advance(INPUT_BATCH_MS)
- expect(t.inputs).toEqual([])
- t.host.stop('revoked')
- }
- })
-
- it("a terminal's own answer (DA) is dropped, never counted against the budget, and is not typing", async () => {
- const { t, clock, vs } = await controllers(['Ada'])
- await type(vs[0], `${ESC}[?1;2c`, clock)
- await clock.advance(INPUT_BATCH_MS)
- expect(t.inputs).toEqual([])
- expect(t.host.viewers()[0].typing).toBe(false)
- // Well past the burst in answers, and a keystroke still goes through.
- const answers = `${ESC}[?1;2c`.repeat(INPUT_MAX / 8)
- for (let i = 0; i < 20; i++) await type(vs[0], answers, clock)
- await type(vs[0], 'x', clock)
- await clock.advance(INPUT_BATCH_MS)
- await vi.waitFor(() => expect(delivered(t)).toEqual(['s1:keys:x']))
- expect(dropped(vs[0])).toEqual([])
- })
-
- it('bucket: 300 KiB in one burst delivers INPUT_BURST, and sends ONE dropped notice', async () => {
- const { t, clock, vs } = await controllers(['Ada'])
- const total = 300 * 1024
- for (let sent = 0; sent < total; sent += INPUT_MAX) await type(vs[0], 'a'.repeat(Math.min(INPUT_MAX, total - sent)), clock)
- await clock.advance(INPUT_BATCH_MS)
- await vi.waitFor(() => expect(t.inputs.reduce((n, [, c]) => n + (c.kind === 'keys' ? c.data.length : 0), 0)).toBe(INPUT_BURST))
- expect(dropped(vs[0])).toEqual([{ state: 'controlling', reason: 'dropped' }])
- expect(vs[0].log.closed).toBe(0)
- // The bucket refills at INPUT_RATE: a second's worth goes through again.
- await clock.advance(1000)
- await type(vs[0], 'b'.repeat(INPUT_RATE / 4), clock)
- await clock.advance(INPUT_BATCH_MS)
- await vi.waitFor(() => expect(delivered(t).some((d) => d.startsWith('s1:keys:b'))).toBe(true))
- })
-
- it('a 1 MB paste over the budget is discarded whole (never typed as keys), and typing after it works', async () => {
- const { t, clock, vs } = await controllers(['Ada'])
- const body = `${PASTE_START}${'echo pwned\n'.repeat(96 * 1024)}${PASTE_END}`
- for (let i = 0; i < body.length; i += INPUT_MAX) await type(vs[0], body.slice(i, i + INPUT_MAX), clock)
- await clock.advance(INPUT_BATCH_MS)
- await clock.advance(1000)
- await type(vs[0], 'x', clock)
- await clock.advance(INPUT_BATCH_MS)
- await vi.waitFor(() => expect(delivered(t)).toEqual(['s1:keys:x']))
- expect(dropped(vs[0])).toHaveLength(1)
- })
-
- it("two controllers' batches arrive whole and in flush order", async () => {
- const held = holdFirst()
- const { t, clock, vs } = await controllers(['Ada', 'Bob'], {
- input: held.input
- })
- await type(vs[0], `a${PASTE_START}P${PASTE_END}b`, clock)
- await clock.advance(INPUT_BATCH_MS)
- await vi.waitFor(() => expect(t.inputs).toHaveLength(1))
- await type(vs[1], 'z', clock)
- await clock.advance(INPUT_BATCH_MS)
- // Bob's batch waits behind Ada's, whose first chunk is still in the pane.
- expect(delivered(t)).toEqual(['s1:keys:a'])
- held.release()
- await vi.waitFor(() => expect(delivered(t)).toEqual(['s1:keys:a', 's1:paste:P', 's1:keys:b', 's1:keys:z']))
- })
-
- it('one controller types on while its previous batch is still in the pane: its input waits, then goes as one batch', async () => {
- const held = holdFirst()
- const { t, clock, vs } = await controllers(['Ada'], {
- input: held.input
- })
- await type(vs[0], 'a', clock)
- await clock.advance(INPUT_BATCH_MS)
- await vi.waitFor(() => expect(t.inputs).toHaveLength(1))
- for (const k of ['b', 'c', 'd']) {
- await type(vs[0], k, clock)
- await clock.advance(INPUT_BATCH_MS)
- }
- expect(delivered(t)).toEqual(['s1:keys:a'])
- held.release()
- await vi.waitFor(() => expect(delivered(t)).toEqual(['s1:keys:a', 's1:keys:bcd']))
- })
-
- it('control turned off while a batch is pending: nothing delivered; a keystroke in flight is dropped and the viewer stays', async () => {
- const { t, clock, vs } = await controllers(['Ada'])
- await type(vs[0], 'x', clock)
- t.record.control!.enabled = false
- t.host.controlChanged()
- await type(vs[0], 'y', clock) // in flight when control went off
- await clock.advance(INPUT_BATCH_MS)
- await clock.advance(1000)
- expect(t.inputs).toEqual([])
- expect(vs[0].log.closed).toBe(0)
- expect(t.host.viewers()[0]).toMatchObject({ controlling: false, typing: false })
- expect(dropped(vs[0])).toEqual([])
- })
-
- it('a batch already queued behind another is not delivered once its sender lost control', async () => {
- const held = holdFirst()
- const { t, clock, vs } = await controllers(['Ada', 'Bob'], {
- input: held.input
- })
- await type(vs[0], 'a', clock)
- await clock.advance(INPUT_BATCH_MS)
- await vi.waitFor(() => expect(t.inputs).toHaveLength(1))
- await type(vs[1], 'z', clock)
- await clock.advance(INPUT_BATCH_MS)
- expect(await ask(vs[1], () => vs[1].c.release())).toEqual({ state: 'available' })
- held.release()
- await clock.flush()
- await settleReal()
- expect(delivered(t)).toEqual(['s1:keys:a'])
- })
-
- it('every chunk re-reads the record: typing turned off in the record mid-batch stops the rest, even before the host is told', async () => {
- // The control period (`controlGen`) does not move until the host is told; the record is read
- // live. A chunk must not go out on the strength of the period alone.
- const held = holdFirst()
- const { t, clock, vs } = await controllers(['Ada'], { input: held.input })
- await type(vs[0], `a${PASTE_START}P${PASTE_END}b`, clock)
- await clock.advance(INPUT_BATCH_MS)
- await vi.waitFor(() => expect(t.inputs).toHaveLength(1))
- t.record.control!.enabled = false // no controlChanged(): the host has not been told yet
- held.release()
- await clock.flush()
- await settleReal()
- expect(delivered(t)).toEqual(['s1:keys:a'])
- })
-
- it('the bucket holds across batches: after a whole burst was delivered, more input in the same second is dropped until it refills', async () => {
- // The pending-batch cap alone bounds ONE batch; only the bucket bounds the rate across batches.
- const { t, clock, vs } = await controllers(['Ada'])
- for (let sent = 0; sent < INPUT_BURST; sent += INPUT_MAX) await type(vs[0], 'a'.repeat(INPUT_MAX), clock)
- await clock.advance(INPUT_BATCH_MS)
- await vi.waitFor(() => expect(t.inputs.reduce((n, [, c]) => n + (c.kind === 'keys' ? c.data.length : 0), 0)).toBe(INPUT_BURST))
- expect(dropped(vs[0])).toEqual([])
- // INPUT_BATCH_MS later the bucket holds ~1.3 KiB: 16 KiB more is over budget.
- await type(vs[0], 'b'.repeat(INPUT_MAX), clock)
- await clock.advance(INPUT_BATCH_MS)
- await settleReal()
- expect(delivered(t).some((d) => d.startsWith('s1:keys:b'))).toBe(false)
- expect(dropped(vs[0])).toEqual([{ state: 'controlling', reason: 'dropped' }])
- expect(vs[0].log.closed).toBe(0)
- })
-
- it('a batch queued from before a release is not delivered after the same viewer unlocks again', async () => {
- const held = holdFirst()
- const { t, clock, vs } = await controllers(['Ada', 'Bob'], {
- input: held.input
- })
- await type(vs[0], 'a', clock)
- await clock.advance(INPUT_BATCH_MS)
- await vi.waitFor(() => expect(t.inputs).toHaveLength(1))
- await type(vs[1], 'old', clock)
- await clock.advance(INPUT_BATCH_MS)
- expect(await ask(vs[1], () => vs[1].c.release())).toEqual({ state: 'available' })
- await clock.advance(UNLOCK_MIN_INTERVAL_MS)
- expect(await unlock(vs[1], 'Bob', PW)).toEqual({ state: 'controlling' })
- held.release()
- await type(vs[1], 'new', clock)
- await clock.advance(INPUT_BATCH_MS)
- await vi.waitFor(() => expect(delivered(t)).toEqual(['s1:keys:a', 's1:keys:new']))
- // Voided by the release it was told about: no "dropped" on top.
- expect(dropped(vs[1])).toEqual([])
- })
-
- it('a batch already in the chain whose session ended is not typed into the next session', async () => {
- const held = holdFirst()
- let n = 0
- const { t, clock, vs } = await controllers(['Ada'], {
- join: () => ({ sessionId: `s${++n}`, cols: 80, rows: 24, altScreen: true }),
- input: held.input
- })
- await type(vs[0], `a${PASTE_START}P${PASTE_END}b`, clock)
- await clock.advance(INPUT_BATCH_MS)
- await vi.waitFor(() => expect(t.inputs).toHaveLength(1))
- ptyEvent(t.sink(), IPC.ptyExit('s1'), 0)
- await clock.flush()
- await clock.advance(REJOIN_BACKOFF_MS[0])
- await vi.waitFor(() => expect(vs[0].named(WATCH_EVENT.meta)).toHaveLength(2))
- held.release()
- await vi.waitFor(() => expect(dropped(vs[0])).toHaveLength(1))
- expect(delivered(t)).toEqual(['s1:keys:a'])
- })
-
- it('a paste open when its session ended is discarded whole, even when its end arrives at the next session', async () => {
- let n = 0
- const { t, clock, vs } = await controllers(['Ada'], { join: () => ({ sessionId: `s${++n}`, cols: 80, rows: 24, altScreen: true }) })
- await type(vs[0], `${PASTE_START}first half `, clock)
- ptyEvent(t.sink(), IPC.ptyExit('s1'), 0)
- await clock.flush()
- await clock.advance(REJOIN_BACKOFF_MS[0])
- await vi.waitFor(() => expect(vs[0].named(WATCH_EVENT.meta)).toHaveLength(2))
- await type(vs[0], `second half${PASTE_END}ok`, clock)
- await clock.advance(INPUT_BATCH_MS)
- await vi.waitFor(() => expect(delivered(t)).toEqual(['s2:keys:ok']))
- // The pending batch was empty (the paste had not ended), and the paste was still lost: told.
- expect(dropped(vs[0])).toHaveLength(1)
- })
-
- it('in-flight input after a release is dropped silently; 5.1 s later it is a breach', async () => {
- vi.spyOn(console, 'warn').mockImplementation(() => {})
- const { t, clock, vs } = await controllers(['Ada'])
- expect(await ask(vs[0], () => vs[0].c.release())).toEqual({ state: 'available' })
- await type(vs[0], 'x', clock)
- await clock.advance(INPUT_BATCH_MS)
- expect(vs[0].log.closed).toBe(0)
- expect(t.inputs).toEqual([])
- expect(dropped(vs[0])).toEqual([])
- await clock.advance(INPUT_GRACE_MS + 100)
- await type(vs[0], 'x', clock)
- await vi.waitFor(() => expect(vs[0].log.closed).toBe(1))
- expect(t.inputs).toEqual([])
- })
-
- it('the session changes (exit, then a rejoin to s2): the next input goes to s2', async () => {
- let n = 0
- const { t, clock, vs } = await controllers(['Ada'], { join: () => ({ sessionId: `s${++n}`, cols: 80, rows: 24, altScreen: true }) })
- ptyEvent(t.sink(), IPC.ptyExit('s1'), 0)
- await clock.flush()
- await clock.advance(REJOIN_BACKOFF_MS[0])
- await vi.waitFor(() => expect(vs[0].named(WATCH_EVENT.meta)).toHaveLength(2))
- expect(metaOf(vs[0], 1).control).toEqual({ state: 'controlling' })
- await type(vs[0], 'pwd\r', clock)
- await clock.advance(INPUT_BATCH_MS)
- await vi.waitFor(() => expect(delivered(t)).toEqual(['s2:keys:pwd\r']))
- })
-
- it('no session (waiting): dropped with a notice, and nothing is delivered after a later join', async () => {
- let n = 0
- let refuse = false
- const { t, clock, vs } = await controllers(['Ada'], {
- join: () => (refuse ? null : { sessionId: `s${++n}`, cols: 80, rows: 24, altScreen: true })
- })
- refuse = true
- ptyEvent(t.sink(), IPC.ptyExit('s1'), 0)
- await clock.flush()
- await vi.waitFor(() => expect(vs[0].named(WATCH_EVENT.waiting)).toHaveLength(1))
- await type(vs[0], 'held?\r', clock)
- await vi.waitFor(() => expect(dropped(vs[0])).toHaveLength(1))
- refuse = false
- await clock.advance(REJOIN_BACKOFF_MS[0])
- await vi.waitFor(() => expect(vs[0].named(WATCH_EVENT.meta)).toHaveLength(2))
- await clock.advance(INPUT_BATCH_MS * 10)
- expect(t.inputs).toEqual([])
- })
-
- it('a pending batch for a session that ended is dropped with a notice, never typed into the next one', async () => {
- let n = 0
- const { t, clock, vs } = await controllers(['Ada'], { join: () => ({ sessionId: `s${++n}`, cols: 80, rows: 24, altScreen: true }) })
- await type(vs[0], 'x', clock)
- ptyEvent(t.sink(), IPC.ptyExit('s1'), 0)
- await clock.flush()
- await clock.advance(INPUT_BATCH_MS)
- await vi.waitFor(() => expect(dropped(vs[0])).toHaveLength(1))
- await clock.advance(REJOIN_BACKOFF_MS[0])
- await vi.waitFor(() => expect(vs[0].named(WATCH_EVENT.meta)).toHaveLength(2))
- await clock.advance(INPUT_BATCH_MS)
- expect(t.inputs).toEqual([])
- })
-
- it('a pane delivery answering false stops the batch and sends a dropped notice, at most one per DROPPED_NOTICE_MIN_MS', async () => {
- const { t, clock, vs } = await controllers(['Ada'], { input: () => false })
- await type(vs[0], `a${PASTE_START}P${PASTE_END}b`, clock)
- await clock.advance(INPUT_BATCH_MS)
- await vi.waitFor(() => expect(dropped(vs[0])).toHaveLength(1))
- expect(delivered(t)).toEqual(['s1:keys:a'])
- await type(vs[0], 'c', clock)
- await clock.advance(INPUT_BATCH_MS)
- await vi.waitFor(() => expect(t.inputs).toHaveLength(2))
- expect(dropped(vs[0])).toHaveLength(1)
- await clock.advance(DROPPED_NOTICE_MIN_MS)
- await type(vs[0], 'd', clock)
- await clock.advance(INPUT_BATCH_MS)
- await vi.waitFor(() => expect(dropped(vs[0])).toHaveLength(2))
- expect(vs[0].log.closed).toBe(0)
- })
-
- it('a pane delivery that rejects counts as false, and nothing typed is logged', async () => {
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
- const error = vi.spyOn(console, 'error').mockImplementation(() => {})
- const { t, clock, vs } = await controllers(['Ada'], {
- input: () => Promise.reject(new Error('pane gone while typing hunter2-secret'))
- })
- await type(vs[0], 'hunter2-secret\r', clock)
- await clock.advance(INPUT_BATCH_MS)
- await vi.waitFor(() => expect(dropped(vs[0])).toHaveLength(1))
- expect(t.inputs).toHaveLength(1)
- for (const call of [...warn.mock.calls, ...error.mock.calls]) {
- for (const arg of call) expect(String(arg)).not.toContain('hunter2')
- }
- })
-
- it('typing: two controllers type, every viewer gets watch:typing names, at most once a second; after 4 s of silence, names []', async () => {
- const { t, clock, vs } = await controllers(['Ada', 'Bob'])
- const watcher = await openViewer(t, 2)
- const changes = t.changes()
- await type(vs[0], 'a', clock)
- await vi.waitFor(() => expect(typingOf(watcher)).toEqual([['Ada']]))
- expect(t.changes()).toBeGreaterThan(changes)
- // A burst inside one second is one event.
- for (let i = 0; i < 5; i++) {
- await clock.advance(100)
- await type(vs[1], 'b', clock)
- await type(vs[0], 'a', clock)
- }
- expect(typingOf(watcher)).toEqual([['Ada']])
- await clock.advance(TYPING_EVENT_MIN_MS)
- await vi.waitFor(() => expect(typingOf(watcher)).toHaveLength(2))
- expect([...typingOf(watcher)[1]].sort()).toEqual(['Ada', 'Bob'])
- for (const v of [...vs, watcher]) expect(typingOf(v).at(-1)!.sort()).toEqual(['Ada', 'Bob'])
- expect(t.host.viewers().map((x) => x.typing)).toEqual([true, true, false])
- // Silence: cleared within the window plus one tick, then no more timer work for typing.
- await clock.advance(TYPING_WINDOW_MS + TYPING_EVENT_MIN_MS)
- expect(typingOf(watcher).at(-1)).toEqual([])
- expect(t.host.viewers().map((x) => x.typing)).toEqual([false, false, false])
- const n = typingOf(watcher).length
- await clock.advance(10 * TYPING_EVENT_MIN_MS)
- expect(typingOf(watcher)).toHaveLength(n)
- })
-
- it('a controller that releases leaves the typing set at the next tick', async () => {
- const { t, clock, vs } = await controllers(['Ada'])
- const watcher = await openViewer(t, 1)
- await type(vs[0], 'a', clock)
- await vi.waitFor(() => expect(typingOf(watcher)).toEqual([['Ada']]))
- expect(await ask(vs[0], () => vs[0].c.release())).toEqual({ state: 'available' })
- expect(t.host.viewers()[0].typing).toBe(false)
- await clock.advance(TYPING_EVENT_MIN_MS)
- expect(typingOf(watcher)).toEqual([['Ada'], []])
- })
-
- it('a viewer that joins (or rejoins) while someone types gets the typing set right after its meta', async () => {
- let n = 0
- const { t, clock, vs } = await controllers(['Ada'], { join: () => ({ sessionId: `s${++n}`, cols: 80, rows: 24, altScreen: true }) })
- await type(vs[0], 'a', clock)
- await vi.waitFor(() => expect(typingOf(vs[0])).toEqual([['Ada']]))
- const late = await openViewer(t, 1)
- const names = late.log.events.map((e) => e[0])
- const meta = names.indexOf(WATCH_EVENT.meta)
- expect(names[meta + 1]).toBe(WATCH_EVENT.typing)
- expect(typingOf(late)).toEqual([['Ada']])
- // A rejoin of the typist itself: the set rides its new meta too.
- ptyEvent(t.sink(0), IPC.ptyExit('s1'), 0)
- await clock.flush()
- await clock.advance(REJOIN_BACKOFF_MS[0])
- await vi.waitFor(() => expect(vs[0].named(WATCH_EVENT.meta)).toHaveLength(2))
- const ev = vs[0].log.events.map((e) => e[0])
- expect(ev[ev.lastIndexOf(WATCH_EVENT.meta) + 1]).toBe(WATCH_EVENT.typing)
- // Nobody typing: no typing event after a meta.
- const quiet = typist()
- quiet.host.start()
- const q = await openViewer(quiet)
- expect(q.named(WATCH_EVENT.typing)).toEqual([])
- })
-
- it('ten typists at once (the most a link holds) are all named, within TYPING_NAMES_MAX', async () => {
- const names = Array.from({ length: TYPING_NAMES_MAX }, (_, i) => `N${i}`)
- const { clock, vs } = await controllers(names)
- for (const v of vs) await type(v, 'a', clock)
- await clock.advance(TYPING_EVENT_MIN_MS)
- expect(typingOf(vs[0]).at(-1)).toHaveLength(TYPING_NAMES_MAX)
- })
-
- it("an input route of 'none' (or none, or an unknown one, answered): meta says off/unsupported, and an unlock is refused with it, never counted", async () => {
- const cases: SetupOpts[] = [
- { route: 'none' },
- { route: 'missing' },
- { join: () => ({ sessionId: 's1', cols: 80, rows: 24, altScreen: true, input: 'zellij' as never }) }
- ]
- for (const o of cases) {
- const t = typist(o)
- t.host.start()
- const v = await openViewer(t)
- expect(metaOf(v).control).toEqual({ state: 'off', reason: 'unsupported' })
- // Answered as it stands: no throttle, no count, no verification.
- for (let i = 0; i < WRONG_PER_CONN + 1; i++) {
- expect(await unlock(v, 'Ada', PW)).toEqual({ state: 'off', reason: 'unsupported' })
- }
- expect(t.verifies()).toBe(0)
- expect(v.log.closed).toBe(0)
- expect(t.host.viewers()[0].controlling).toBe(false)
- }
- })
-
- it("a controller whose rejoin answers 'none' is demoted: its meta says unsupported, and input in flight is dropped", async () => {
- let n = 0
- const { t, clock, vs } = await controllers(['Ada'], {
- join: () => ({ sessionId: `s${++n}`, cols: 80, rows: 24, altScreen: true, input: n === 1 ? 'tmux' : 'none' })
- })
- ptyEvent(t.sink(), IPC.ptyExit('s1'), 0)
- await clock.flush()
- await clock.advance(REJOIN_BACKOFF_MS[0])
- await vi.waitFor(() => expect(vs[0].named(WATCH_EVENT.meta)).toHaveLength(2))
- expect(metaOf(vs[0], 1).control).toEqual({ state: 'off', reason: 'unsupported' })
- expect(t.host.viewers()[0].controlling).toBe(false)
- vi.spyOn(console, 'warn').mockImplementation(() => {})
- await type(vs[0], 'x', clock)
- await clock.advance(INPUT_BATCH_MS)
- expect(vs[0].log.closed).toBe(0)
- expect(t.inputs).toEqual([])
- // It stopped controlling at that join: past the grace, input is the breach it is from anyone.
- await clock.advance(INPUT_GRACE_MS + 100)
- await type(vs[0], 'x', clock)
- await vi.waitFor(() => expect(vs[0].log.closed).toBe(1))
- expect(t.inputs).toEqual([])
- })
-
- it('while the panes have not taken its last batch, a controller collects at most INPUT_BURST more; past it, dropped', async () => {
- const held = holdFirst()
- const { t, clock, vs } = await controllers(['Ada'], {
- input: held.input
- })
- await type(vs[0], 'a', clock)
- await clock.advance(INPUT_BATCH_MS)
- await vi.waitFor(() => expect(t.inputs).toHaveLength(1))
- // Inside the bucket (1 byte spent): 15 full casts.
- for (let i = 0; i < 15; i++) await type(vs[0], 'b'.repeat(INPUT_MAX), clock)
- expect(dropped(vs[0])).toEqual([])
- // A second later the bucket has room again, but the batch waiting for the pane is full.
- await clock.advance(1000)
- await type(vs[0], 'c'.repeat(INPUT_MAX), clock) // fills the batch to INPUT_BURST exactly
- await type(vs[0], 'd'.repeat(INPUT_MAX), clock) // over: dropped
- await vi.waitFor(() => expect(dropped(vs[0])).toHaveLength(1))
- held.release()
- await clock.advance(INPUT_BATCH_MS) // the batch's own timer, armed by the last accepted cast
- const size = (): number => t.inputs.reduce((n, [, c]) => n + (c.kind === 'keys' ? c.data.length : 0), 0)
- await vi.waitFor(() => expect(size()).toBe(1 + INPUT_BURST))
- await settleReal()
- expect(size()).toBe(1 + INPUT_BURST)
- expect(delivered(t).some((d) => d.includes('d'))).toBe(false)
- })
-
- // --- losing control: a password change and the lock take the same path as every other --------------
-
- it('a password change: the pending batch is not delivered, a keystroke in flight is dropped, the viewer stays and leaves the typing set; 5 s later input is a breach', async () => {
- vi.spyOn(console, 'warn').mockImplementation(() => {})
- const { t, clock, vs } = await controllers(['Ada'])
- const watcher = await openViewer(t, 1)
- await type(vs[0], 'a', clock)
- await vi.waitFor(() => expect(typingOf(watcher)).toEqual([['Ada']]))
- t.host.passwordChanged()
- await vi.waitFor(() => expect(controlOf(vs[0]).at(-1)).toEqual({ state: 'available' }))
- expect(t.host.viewers()[0]).toMatchObject({ controlling: false, typing: false })
- await type(vs[0], 'b', clock) // in flight when the password changed
- await clock.advance(INPUT_BATCH_MS)
- expect(t.inputs).toEqual([])
- expect(vs[0].log.closed).toBe(0)
- await clock.advance(TYPING_EVENT_MIN_MS)
- expect(typingOf(watcher).at(-1)).toEqual([])
- await clock.advance(INPUT_GRACE_MS)
- await type(vs[0], 'c', clock)
- await vi.waitFor(() => expect(vs[0].log.closed).toBe(1))
- expect(t.inputs).toEqual([])
- })
-
- it('a password change voids a batch queued in the chain, even after its sender unlocks with the new password', async () => {
- const held = holdFirst()
- let password = PW
- const { t, clock, vs } = await controllers(['Ada', 'Bob'], { input: held.input, verifyPassword: async (pw) => pw === password })
- await type(vs[0], 'a', clock)
- await clock.advance(INPUT_BATCH_MS)
- await vi.waitFor(() => expect(t.inputs).toHaveLength(1))
- await type(vs[1], 'old', clock)
- await clock.advance(INPUT_BATCH_MS)
- password = 'a-new-password'
- t.host.passwordChanged()
- await clock.advance(UNLOCK_MIN_INTERVAL_MS)
- expect(await unlock(vs[1], 'Bob', 'a-new-password')).toEqual({ state: 'controlling' })
- held.release()
- await type(vs[1], 'new', clock)
- await clock.advance(INPUT_BATCH_MS)
- await vi.waitFor(() => expect(delivered(t)).toEqual(['s1:keys:a', 's1:keys:new']))
- await settleReal()
- expect(delivered(t)).toEqual(['s1:keys:a', 's1:keys:new'])
- })
-
- it('the lock: a keystroke in flight is dropped and the controller stays; 5 s later input is a breach', async () => {
- vi.spyOn(console, 'warn').mockImplementation(() => {})
- const { t, clock, vs } = await controllers(['Ada'])
- await type(vs[0], 'a', clock)
- let n = 1
- for (let wrong = 0; wrong < WRONG_PER_LINK; ) {
- const v = await openViewer(t, n++)
- for (let i = 0; i < WRONG_PER_CONN && wrong < WRONG_PER_LINK; i++, wrong++) {
- await clock.advance(UNLOCK_MIN_INTERVAL_MS)
- await unlock(v, 'Eve', WRONG)
- }
- }
- expect(t.locks()).toBe(1)
- await vi.waitFor(() => expect(controlOf(vs[0]).at(-1)).toEqual({ state: 'locked', reason: 'locked' }))
- await type(vs[0], 'b', clock)
- await clock.advance(INPUT_BATCH_MS)
- expect(vs[0].log.closed).toBe(0)
- await clock.advance(INPUT_GRACE_MS + 100)
- await type(vs[0], 'c', clock)
- await vi.waitFor(() => expect(vs[0].log.closed).toBe(1))
- // 'a' flushed (still controlling) during the first throttle wait; nothing after the lock did.
- expect(delivered(t)).toEqual(['s1:keys:a'])
- })
-
- it('malformed input inside the grace window is a silent drop too, not a breach', async () => {
- const clock = manualClock()
- const t = typist({ clock })
- t.host.start()
- const p = await openRaw(t, 0)
- p.cast(WATCH_UNLOCK_CAST, [{ name: 'Ada', password: PW }])
- await vi.waitFor(() => expect(controlOf(p)).toEqual([{ state: 'controlling' }]))
- p.cast(WATCH_RELEASE_CAST, [])
- await vi.waitFor(() => expect(controlOf(p)).toHaveLength(2))
- p.cast(WATCH_INPUT_CAST, [{ data: 5 }])
- p.cast(WATCH_INPUT_CAST, [{ data: 'x'.repeat(INPUT_MAX + 1) }])
- await clock.advance(INPUT_BATCH_MS)
- await settleReal()
- expect(p.closed()).toBe(0)
- expect(t.inputs).toEqual([])
- })
-
- // --- the splitter across batches and drops ---------------------------------------------------------
-
- it('a start marker split across two casts with a batch in between is still a paste', async () => {
- const { t, clock, vs } = await controllers(['Ada'])
- await type(vs[0], `a${ESC}[20`, clock)
- await clock.advance(INPUT_BATCH_MS)
- await vi.waitFor(() => expect(delivered(t)).toEqual(['s1:keys:a']))
- await type(vs[0], `0~line 1\nline 2${PASTE_END}`, clock)
- await clock.advance(INPUT_BATCH_MS)
- await vi.waitFor(() => expect(delivered(t)).toEqual(['s1:keys:a', 's1:paste:line 1\nline 2']))
- })
-
- it('a dropped cast that ends in a start-marker prefix: the paste it begins is discarded, never typed as keys', async () => {
- const { t, clock, vs } = await controllers(['Ada'])
- for (let i = 0; i < INPUT_BURST / INPUT_MAX; i++) await type(vs[0], 'a'.repeat(INPUT_MAX), clock)
- await type(vs[0], `b${ESC}[20`, clock) // over budget: dropped
- await vi.waitFor(() => expect(dropped(vs[0])).toHaveLength(1))
- await clock.advance(INPUT_BATCH_MS)
- await clock.advance(1000)
- await type(vs[0], `0~rm -rf ~\n${PASTE_END}ok`, clock)
- await clock.advance(INPUT_BATCH_MS)
- await vi.waitFor(() => expect(delivered(t).at(-1)).toBe('s1:keys:ok'))
- expect(delivered(t).filter((d) => !d.startsWith('s1:keys:a'))).toEqual(['s1:keys:ok'])
- })
-
- // --- a pane that never answers --------------------------------------------------------------------
-
- it('a pane delivery that never settles times out after INPUT_DELIVERY_TIMEOUT_MS: dropped notice, the chain moves on, a late answer is ignored', async () => {
- vi.spyOn(console, 'warn').mockImplementation(() => {})
- const late = deferred<boolean>()
- let calls = 0
- const { t, clock, vs } = await controllers(['Ada', 'Bob'], { input: () => (++calls === 1 ? late.promise : true) })
- await type(vs[0], `a${PASTE_START}P${PASTE_END}`, clock)
- await clock.advance(INPUT_BATCH_MS)
- await vi.waitFor(() => expect(t.inputs).toHaveLength(1))
- await type(vs[1], 'z', clock)
- await clock.advance(INPUT_BATCH_MS)
- // Ada's chunk went to the pane one batch interval ago: its deadline is that far closer.
- await clock.advance(INPUT_DELIVERY_TIMEOUT_MS - INPUT_BATCH_MS - 1)
- expect(delivered(t)).toEqual(['s1:keys:a'])
- await clock.advance(1)
- await vi.waitFor(() => expect(delivered(t)).toEqual(['s1:keys:a', 's1:keys:z']))
- expect(dropped(vs[0])).toHaveLength(1)
- expect(dropped(vs[1])).toEqual([])
- // The answer arrives after all: nothing more is delivered, nobody is told twice.
- late.resolve(true)
- await settleReal()
- expect(delivered(t)).toEqual(['s1:keys:a', 's1:keys:z'])
- expect(dropped(vs[0])).toHaveLength(1)
- })
-
- it('a connection that ends while its delivery hangs releases the chain at once; stop() leaves no delivery timer', async () => {
- const { t, clock, vs } = await controllers(['Ada', 'Bob'], { input: (_s, c) => (c.kind === 'keys' && c.data === 'a' ? new Promise<boolean>(() => {}) : true) })
- await type(vs[0], 'a', clock)
- await clock.advance(INPUT_BATCH_MS)
- await vi.waitFor(() => expect(t.inputs).toHaveLength(1))
- await type(vs[1], 'z', clock)
- await clock.advance(INPUT_BATCH_MS)
- expect(t.host.kick(t.host.viewers()[0].viewerId)).toBe(true)
- await vi.waitFor(() => expect(delivered(t)).toEqual(['s1:keys:a', 's1:keys:z']))
- // A hung delivery when the link stops: its timer goes with it.
- await type(vs[1], 'a', clock)
- await clock.advance(INPUT_BATCH_MS)
- await vi.waitFor(() => expect(t.inputs).toHaveLength(3))
- t.host.stop('revoked')
- await clock.flush()
- expect(clock.pending()).toBe(0)
- })
-
- // --- the typing name -------------------------------------------------------------------------------
-
- it('the typing set names the name control was taken under, not a later chat name', async () => {
- const { t, clock, vs } = await controllers(['Ada'])
- const watcher = await openViewer(t, 1)
- expect(vs[0].c.sendChat('Bob', 'hi')).toBe(true)
- await vi.waitFor(() => expect(t.chats).toHaveLength(1))
- await type(vs[0], 'a', clock)
- await vi.waitFor(() => expect(typingOf(watcher)).toEqual([['Ada']]))
- })
-
- // The owner must never read "Bob · typing" beside an "Ada took control" notice: while a viewer
- // controls, the owner's list names it as the typing set does. Once it stops, its chat name again.
- it("the owner's viewer list names a controller by its unlock name, and by its chat name once it stops", async () => {
- const { t, clock, vs } = await controllers(['Ada'])
- expect(vs[0].c.sendChat('Bob', 'hi')).toBe(true)
- await vi.waitFor(() => expect(t.chats).toHaveLength(1))
- await type(vs[0], 'a', clock)
- expect(t.host.viewers()[0]).toMatchObject({ name: 'Ada', controlling: true, typing: true })
- expect(await ask(vs[0], () => vs[0].c.release())).toEqual({ state: 'available' })
- expect(t.host.viewers()[0]).toMatchObject({ name: 'Bob', controlling: false })
- })
-
- it('stop() with a pending batch and a live typing set leaves no timer behind', async () => {
- const { t, clock, vs } = await controllers(['Ada', 'Bob'])
- await type(vs[0], 'a', clock)
- await type(vs[1], 'b', clock)
- expect(clock.pending()).toBeGreaterThan(0)
- t.host.stop('revoked')
- await clock.flush()
- expect(clock.pending()).toBe(0)
- await clock.advance(60_000)
- expect(t.inputs).toEqual([])
- })
-
- it('a viewer that ends with a pending batch: its timer is cleared and nothing is delivered', async () => {
- const { t, clock, vs } = await controllers(['Ada'])
- await type(vs[0], 'a', clock)
- const before = clock.pending()
- expect(t.host.kick(t.host.viewers()[0].viewerId)).toBe(true)
- expect(clock.pending()).toBeLessThan(before)
- await clock.advance(INPUT_BATCH_MS * 10)
- expect(t.inputs).toEqual([])
- })
-
- // Final review, Minor 3: a chunk already handed to PtyManager waits in its per-session chain (a
- // slow step of another link, say). The host gives it a predicate PtyManager asks right before it
- // spawns: false from the moment its sender stops controlling, so it never lands after control ended.
- it('every chunk handed to the pane carries a predicate that turns false the moment control ends', async () => {
- for (const end of ['record-off', 'off', 'release', 'password', 'lock', 'kick', 'stop'] as const) {
- const held = holdFirst()
- const { t, clock, vs } = await controllers(['Ada'], { input: held.input })
- await type(vs[0], 'a', clock)
- await clock.advance(INPUT_BATCH_MS)
- await vi.waitFor(() => expect(t.currents).toHaveLength(1))
- const isCurrent = t.currents[0]
- expect(typeof isCurrent, end).toBe('function')
- expect(isCurrent!(), end).toBe(true)
- if (end === 'record-off') t.record.control!.enabled = false // read live, before the host is told
- else if (end === 'off') {
- t.record.control!.enabled = false
- t.host.controlChanged()
- } else if (end === 'release') expect(await ask(vs[0], () => vs[0].c.release())).toEqual({ state: 'available' })
- else if (end === 'password') t.host.passwordChanged()
- else if (end === 'lock') {
- t.record.control!.locked = true
- t.host.controlChanged()
- } else if (end === 'kick') expect(t.host.kick(t.host.viewers()[0].viewerId)).toBe(true)
- else t.host.stop('revoked')
- expect(isCurrent!(), end).toBe(false)
- held.release()
- t.host.stop('revoked')
- }
- })
-
- it('a predicate never answers true for a sender that unlocked AGAIN: the period it was typed in is over', async () => {
- const held = holdFirst()
- const { t, clock, vs } = await controllers(['Ada'], { input: held.input })
- await type(vs[0], 'a', clock)
- await clock.advance(INPUT_BATCH_MS)
- await vi.waitFor(() => expect(t.currents).toHaveLength(1))
- const isCurrent = t.currents[0]!
- expect(await ask(vs[0], () => vs[0].c.release())).toEqual({ state: 'available' })
- await clock.advance(UNLOCK_MIN_INTERVAL_MS)
- expect(await unlock(vs[0], 'Ada', PW)).toEqual({ state: 'controlling' })
- expect(isCurrent()).toBe(false)
- held.release()
- })
-
- // Final review, Minor 8: a paste/keys alternation costs one pane delivery (one tmux spawn) per
- // chunk. A batch holds at most INPUT_CHUNKS_MAX; the rest of THAT batch is dropped in whole chunks
- // (a paste is never cut), with the rate-limited dropped notice, and the next batch works.
- it(`a batch holds at most INPUT_CHUNKS_MAX (${INPUT_CHUNKS_MAX}) chunks: the rest of it is dropped whole, with one notice`, async () => {
- const { t, clock, vs } = await controllers(['Ada'])
- const pair = (i: number): string => `k${i}${PASTE_START}p${i}${PASTE_END}`
- const flood = Array.from({ length: INPUT_CHUNKS_MAX }, (_, i) => pair(i)).join('')
- expect(flood.length).toBeLessThanOrEqual(INPUT_MAX)
- await type(vs[0], flood, clock) // 2 × INPUT_CHUNKS_MAX chunks in one cast
- // More of the same batch, before it flushes: a paste opened here and closed in the next cast…
- await type(vs[0], `late${PASTE_START}half`, clock)
- await type(vs[0], `-of-a-paste${PASTE_END}tail`, clock)
- await clock.advance(INPUT_BATCH_MS)
- await vi.waitFor(() => expect(t.inputs).toHaveLength(INPUT_CHUNKS_MAX))
- await clock.flush()
- await settleReal()
- const want = Array.from({ length: INPUT_CHUNKS_MAX / 2 }, (_, i) => [`s1:keys:k${i}`, `s1:paste:p${i}`]).flat()
- expect(delivered(t)).toEqual(want)
- // …is dropped whole: no part of the late paste, nothing typed after it in that batch.
- expect(delivered(t).some((d) => /late|half|tail/.test(d))).toBe(false)
- expect(dropped(vs[0])).toEqual([{ state: 'controlling', reason: 'dropped' }])
- expect(vs[0].log.closed).toBe(0)
- // The next batch is a new one.
- await type(vs[0], 'x', clock)
- await clock.advance(INPUT_BATCH_MS)
- await vi.waitFor(() => expect(delivered(t).at(-1)).toBe('s1:keys:x'))
- })
-
- it('a batch of exactly INPUT_CHUNKS_MAX chunks is delivered whole, with no notice', async () => {
- const { t, clock, vs } = await controllers(['Ada'])
- const flood = Array.from({ length: INPUT_CHUNKS_MAX / 2 }, (_, i) => `k${i}${PASTE_START}p${i}${PASTE_END}`).join('')
- await type(vs[0], flood, clock)
- await clock.advance(INPUT_BATCH_MS)
- await vi.waitFor(() => expect(t.inputs).toHaveLength(INPUT_CHUNKS_MAX))
- await settleReal()
- expect(dropped(vs[0])).toEqual([])
- })
- })
-})
diff --git a/src/core/watch-link/link-host.ts b/src/core/watch-link/link-host.ts
deleted file mode 100644
index ea7c641c4..000000000
--- a/src/core/watch-link/link-host.ts
+++ /dev/null
@@ -1,1709 +0,0 @@
-// One live link at runtime: its standing relay listeners (one hosted-scheduler, capped at
-// MAX_VIEWERS_PER_LINK bridged), and for every connected viewer a relay-host session whose peer key
-// must be the one derived from the link secret. The viewer is attached as a QUIET, SELF-PACED core
-// client; the host joins the node's RUNNING session on its behalf (join-only, never a size vote,
-// every argument built from the host's own records — nothing comes from the viewer), sends meta and a
-// visible-screen keyframe, then streams through the watcher sink (watcher-policy.ts).
-//
-// THE VIEWER'S INBOUND SURFACE IS ENFORCED HERE, on the host. The relay-host `access` hook
-// (watcherAccess) refuses every request and every cast but chat (Commenter and Control links) and
-// unlock / input / release (Control links), and this module's own `PeerAttach` is the second layer:
-// it forwards nothing to any platform, and a request, or a cast the link's role does not admit, that
-// reaches it anyway means the access policy failed, so the session is CLOSED (fail closed, as
-// relay-host does for a throwing wrapSink). Input from a viewer that is not controlling is the same
-// breach (but for the GRACE below). No viewer size or resize reaches a pty; the only viewer bytes that
-// reach anything are a controller's input, into the pane of the session the host joined (TYPING
-// below). The join, the size sync, the capture and the input take only ids the host chose. No
-// `interceptReq` is ever supplied (it would bypass `access`).
-//
-// CONTROL (a Control link, role 'controller') is per CONNECTION: a viewer that unlocks with the link's
-// password (`watch:unlock`) is `controlling` until it releases, disconnects or is kicked, or until the
-// owner turns control off or changes the password, or the link locks; a reconnect unlocks again. The
-// record is the service's: the host READS `record.control` live and never writes it (the service sets
-// `locked` inside `onControlLocked`, before it returns). An unlock is answered to that viewer alone
-// (`watch:control`), and every throttle is here: one attempt per UNLOCK_MIN_INTERVAL_MS per viewer and
-// one verification in flight per link (both `too-soon`, not counted); a malformed attempt counts as
-// wrong and is never verified, so an over-long password never reaches scrypt; WRONG_PER_CONN wrong
-// attempts end that connection (`attempts`), WRONG_PER_LINK across the link lock it. The link count is
-// the record's: the host starts from `record.control.wrong` and reports every new count to the service
-// (`onWrongAttempt`), which writes it — an app restart does not reset it. `allowControl` and a password
-// change reset it. A lock lifts by itself (finding L2): the service sets `record.control.lockedUntil`
-// with it and calls `allowControl` when it passes; every `locked` this host sends carries how long is
-// left (`lockedForMs`), and the lock's notice names who tipped it (`onControlLocked(by)`). The unlock
-// itself is SEALED to a key pair of the connection's own (finding L3, unlock-seal.ts): made with the
-// first meta, offered in every meta (`unlockKey`), zeroed at the end; a plain unlock (an older page) is
-// still read, except on a connection that already sent a sealed one. A verification is re-checked after its await: an
-// ended viewer, a stopped host, or any change to control meanwhile (off, locked, a new password — the
-// control epoch) voids it, uncounted. A join whose input route is `none` (Zellij, an unknown session;
-// also what a missing or unknown route reads as) makes that viewer's state `off`/`unsupported`: its
-// meta says so, an unlock is answered so (uncounted), and a controller is demoted.
-//
-// TYPING (`watch:input` from a controller). A cast whose data is not a string of 1..INPUT_MAX units is a
-// breach. A terminal's own answer to the pane's query (`isTerminalReport`: DA, CPR, a colour — every
-// controller's emulator answers every query) is dropped, uncounted. Then the connection's own token
-// bucket (INPUT_RATE / INPUT_BURST, UTF-8 bytes), a session to type into, and a batch the panes have
-// not taken yet holding at most INPUT_BURST decide; dropped input still goes through the splitter's
-// `discard` (a paste any part of which was dropped is discarded whole), and the viewer is told
-// `{controlling, dropped}` at most once per DROPPED_NOTICE_MIN_MS. A batch holds at most
-// INPUT_CHUNKS_MAX chunks (each chunk is one pane delivery — a tmux spawn — and a paste/keys alternation
-// would otherwise cost one per chunk): past it, the rest of THAT batch is dropped in whole chunks, the
-// same way and with the same notice. Accepted data goes through the
-// connection's SPLITTER (control-input.ts: keys vs a bracketed paste) into its BATCH; the batch flushes
-// INPUT_BATCH_MS after its first input into ONE flush CHAIN per link host, through `pty.input`
-// (PtyManager's pane delivery, never a tmux client's key table). A connection has at most one batch in
-// the chain: while it waits there, new input keeps collecting, so a slow pane coalesces input instead
-// of piling up deliveries. ORDER: a connection's input reaches the pane in the order it was typed, and
-// every batch arrives whole (no other controller's chunk inside it); ACROSS controllers it is roughly
-// flush order — a connection whose previous batch is still in the chain re-enters only when that batch
-// finishes, behind whatever other controllers flushed meanwhile. Each chunk is re-checked before it
-// goes — same control period (`controlGen`, bumped by every loss of control), still controlling,
-// still the session it was typed at. The same check rides the chunk as a predicate (`isCurrent`), which
-// PtyManager asks right before the step spawns: a chunk handed over and still waiting in its per-session
-// chain (behind a slow step) never lands after its sender stopped controlling. A false, a rejection, or
-// no answer within
-// INPUT_DELIVERY_TIMEOUT_MS stops the batch with the `dropped` notice (an SSH host without tmux answers
-// false on every chunk: never silence) and the chain moves on. Input is never held for a later
-// session: a session that ends drops the pending batch and discards an open paste (told either way).
-// The typing set names a controller by the name it unlocked under, not a later chat name. Nothing
-// typed is ever logged.
-//
-// GRACE. Keystrokes are in flight when control ends (a release, the owner turning typing off, a new
-// password, the lock, a join whose terminal cannot take input — every one of them goes through
-// `loseControl`): input from a connection that stopped
-// controlling within INPUT_GRACE_MS is dropped silently — not delivered, not counted, not a breach.
-// From a connection that never controlled, or later than that, it is a breach as before.
-//
-// THE TYPING SET: the names with accepted input in the last TYPING_WINDOW_MS. It is recomputed at
-// most once per TYPING_EVENT_MIN_MS while anyone is in it (which is also what clears it), sent as
-// `watch:typing` to every joined viewer when the SET changes (a new order alone is no news), and to a
-// viewer right after its meta on every (re)join while it is not empty — otherwise a viewer that
-// reconnects mid-typing would never learn it. A connection that loses control or ends leaves it at
-// once (the event follows within a tick).
-//
-// relay-host never tells us about ends it caused itself (`deny`, `close`): every such path goes
-// through `ended()`, which reports to the scheduler exactly once (the hosted-service pattern).
-//
-// THE STREAM. The watcher's filter (stream-filter.ts) starts MID-STREAM on every join: a viewer
-// co-attaches to a running session and its first byte may fall inside an OSC 52. Frames that arrive
-// before `c.sessionId` is known never reach the filter at all (the wrapper needs the session id), so
-// a join can never start in text mode. A mid-stream filter swallows text until the first escape; the
-// join keyframe is sent at once, and if the filter had not settled by then ONE follow-up keyframe is
-// taken when it does (`onSettled`), plus one at SETTLE_BOUND_MS after the join if it still has not
-// (controller ruling R23). The filter is never reset to text mode to "unstick" it: inside a string
-// that would print the string's payload.
-//
-// KEYFRAMES are a visible-only capture (never history) passed through a FRESH text-mode filter (a
-// capture starts in ground state, and `capture-pane -e` emits OSC 8 verbatim — R9), with the host's
-// cursor when it was read (R10) and `altScreen` from the join (a tmux client paints on the alternate
-// screen — R18). One capture per session is in flight at a time, shared by this link's viewers of
-// that session (R27): a JOIN keyframe may share a capture already running (that viewer has forwarded
-// nothing of this session, so an earlier screen cannot paint over newer output it showed), any other
-// keyframe needs a capture STARTED after it asked. A per-viewer sequence makes sure an older result
-// is never painted after a newer one, and streaming resumes only on the newest.
-//
-// NO CAPTURE IS NOT AN EMPTY SCREEN (R36). A backend with no visible-only capture (a session host from
-// a build before `captureVisible`, a direct Windows pty, a plain shell) and a capture that failed answer
-// `unavailable`, and then NO keyframe is sent: the viewer paints a keyframe as reset + clear, so an empty one would erase what
-// the stream had drawn. The viewer follows the stream instead (at the join it still gets meta), and a
-// throttled viewer resumes streaming without a repaint. Residual: on such a backend a throttled
-// viewer shows gaps until the application repaints them.
-//
-// SIZE. A viewer never sizes anything. Its meta carries the joined session's CURRENT size (R25). A
-// watcher's OWN tmux client (spawned when no owner Session is held) attaches with `ignore-size`, but
-// tmux honours that only while some client WITHOUT the flag is attached to the server (measured,
-// tmux 3.4): when the watcher is the only client, tmux's `window-size latest` sizes the window to it.
-// So `syncSize` (PtyManager.syncWatcherClientSize, serialized per session there — R24) keeps that
-// client at the window's size: before every keyframe capture (the screen then matches the size) and
-// every WATCHER_SIZE_SYNC_MS while this link has a joined viewer. Residual: when the watcher becomes the
-// only client, the window stays at the last-synced size until another client sizes it (an owner resize
-// in the last interval before leaving is not caught).
-//
-// SPLIT PANES: a keyframe captures the session's ACTIVE pane only (`=nt-<id>:`); the stream, which is
-// the tmux client's own output, repairs the rest as tmux redraws it.
-//
-// BACKLOG. A watcher is self-paced (the registry never pauses or drops for it), so it bounds its own
-// backlog: pty frames stop at WATCHER_BUFFER_LIMIT (watcher-policy), chat is skipped for a viewer that
-// far behind, and past VIEWER_BACKLOG_CLOSE the viewer's session is closed (R28): a socket that never
-// drains must not grow the host's memory. meta, keyframe, waiting and end are small and rare.
-//
-// REJOIN. A session that ends (exit, closed, recycled, or found gone after a join or a capture — R30)
-// sends the viewer `watch:waiting` and rejoins on a backoff. A join that is REFUSED (no session it may
-// join) also marks the viewer `waiting` for the OWNER (`LinkViewer.waiting`, R63): on a backend with no
-// watcher client of its own (Windows' session host, no local tmux, Zellij) only a terminal this app has
-// open can be watched, and the owner is the one who can open it — a LIVE chip alone would say nothing. The backoff is reset only once a joined
-// session stayed up for REJOIN_STABLE_MS from its join keyframe (R26), never on a join or a lifecycle
-// event: an old remote tmux that rejects the client flags, or an owner's repeated `-D`, attaches then
-// exits at once, and resetting on success turned that into a spawn + read + capture every 2 s forever.
-//
-// Nothing here throws out of a callback or a void promise: relay-host calls into this module from a
-// socket's message emit and from the trust gate's async settle, where a throw is lost or unhandled.
-import nacl from 'tweetnacl'
-import { connectRelayHost, type PeerAttach, type RelayHostSession } from '../relay/relay-host'
-import type { RelayTransport } from '../relay/relay-socket'
-import { createHostedScheduler, type Listener, type SchedulerStatus } from '../relay/hosted-scheduler'
-import type { MintResult } from '../relay/host-token'
-import type { UiSink } from '../ui-sink-registry'
-import type { RpcErr } from '../../shared/rpc'
-import { bytesToB64, bytesToHex } from '../../shared/watch-link/bytes'
-import { deriveWatchLinkKeys } from '../../shared/watch-link/keys'
-import {
- CONTROL_LOCK_MAX_MS,
- INPUT_MAX,
- PASSWORD_MAX,
- TYPING_NAMES_MAX,
- WATCH_CHAT_CAST,
- WATCH_EVENT,
- WATCH_HISTORY_CAST,
- WATCH_INPUT_CAST,
- WATCH_PROTOCOL_VERSION,
- WATCH_RELEASE_CAST,
- WATCH_UNLOCK_CAST,
- readHistoryRequest,
- sanitizeChatName,
- sanitizeChatText,
- type WatchChatMessage,
- type WatchControlEvent,
- type WatchKeyframe,
- type WatchLinkEndReason,
- type WatchMeta
-} from '../../shared/watch-link/protocol'
-import type { HostTokenResult } from './api'
-import { unavailableCapture, type VisibleCapture } from '../capture-route'
-import { createInputSplitter, createTypingTracker, type InputSplitter } from './control-input'
-import { PANE_INPUT_DEADLINE_MS, WATCHER_INPUT_ROUTES, type ControlInputChunk, type WatcherInputRoute } from '../pane-input'
-import { isTerminalReport } from '../terminal-reports'
-import { createStreamFilter, type StreamFilter } from './stream-filter'
-import { historyPageFrom, type HistoryRead } from './history'
-import { createTokenBucket, type TokenBucket } from './token-bucket'
-import { isSealedUnlock, openUnlock } from '../../shared/watch-link/unlock-seal'
-import {
- WATCHER_BUFFER_LIMIT,
- WATCHER_REFUSAL,
- WATCHER_RESUME_BELOW,
- watcherAccess,
- wrapWatcherSink
-} from './watcher-policy'
-import { CONTROL_WRONG_MAX, type WatchLinkRecord } from './store'
-import { errorText } from '../../shared/error-text'
-
-export const MAX_VIEWERS_PER_LINK = 10
-/** While the link is full (no idle listener, so no mint), how often the API is asked whether the link
- * was revoked or expired server-side: a Stop all from another machine reaches the viewers of a full
- * link within this (finding L6; it was 5 minutes). Only while full: otherwise the next mint learns it. */
-export const FULL_STATUS_POLL_MS = 60_000
-export const CHAT_MIN_INTERVAL_MS = 2_000
-export const CHAT_HISTORY_MAX = 200
-export const KEYFRAME_MIN_INTERVAL_MS = 1_000
-/** Rejoin delays, by attempt. The last repeats: an instant-exit loop climbs to 15 s (R26, R35), and a
- * viewer waiting for a terminal to start sees it within 15 s. */
-export const REJOIN_BACKOFF_MS = [2_000, 4_000, 8_000, 15_000]
-/** A joined session that stayed up this long (from its join keyframe) resets the rejoin backoff. */
-export const REJOIN_STABLE_MS = 30_000
-/** An unsettled mid-stream filter gets one more keyframe this long after the join (R23). */
-export const SETTLE_BOUND_MS = 2_000
-/** How often a watcher's own tmux client is re-synced to the window size while the link has viewers. */
-export const WATCHER_SIZE_SYNC_MS = 10_000
-/** A peer that completed the handshake with the right key but has not confirmed by now is closed: it
- * would hold one of the link's viewer slots until its socket drops (R31). */
-export const CONFIRM_DEADLINE_MS = 30_000
-/** A viewer whose socket backlog passes this is closed (viewer gone, not a revoke) — R28. */
-export const VIEWER_BACKLOG_CLOSE = 8 * 1024 * 1024
-/** A Control link's unlock throttles: one attempt per viewer per 2 s; 3 wrong end that connection;
- * 10 wrong across the link lock control until the owner allows it again. */
-export const UNLOCK_MIN_INTERVAL_MS = 2_000
-export const WRONG_PER_CONN = 3
-export const WRONG_PER_LINK = CONTROL_WRONG_MAX
-/** A controller's input budget (UTF-8 bytes): its own token bucket, separate from the stream's. */
-export const INPUT_RATE = 64 * 1024
-export const INPUT_BURST = 256 * 1024
-/** Input is collected this long per connection, then delivered as one batch. */
-export const INPUT_BATCH_MS = 20
-/** At most this many chunks in one batch: each is a pane delivery (a tmux spawn). Past it, the rest of
- * that batch is dropped (whole chunks: a paste is never cut) with the `dropped` notice. */
-export const INPUT_CHUNKS_MAX = 64
-/** The typing set is recomputed (and sent, when it changed) at most this often. */
-export const TYPING_EVENT_MIN_MS = 1000
-/** A viewer is told its input was dropped at most this often. */
-export const DROPPED_NOTICE_MIN_MS = 10_000
-/** Read-back reads start at most this often per viewer; one runs at a time, and a request that arrives
- * meanwhile waits (the newest one wins). Each read is a transcript read on the host (an ssh round trip
- * for an SSH node), so a viewer that asks in a loop must not turn into a read loop. */
-export const HISTORY_MIN_INTERVAL_MS = 500
-/** Input from a connection that stopped controlling this recently is dropped silently: keystrokes in
- * flight when control ended are not a breach. Later than this, they are. */
-export const INPUT_GRACE_MS = 5000
-/** A pane delivery that has not answered by now counts as failed: the batch stops (`dropped`) and the
- * link's chain moves on. A late answer is ignored. */
-export const INPUT_DELIVERY_TIMEOUT_MS = PANE_INPUT_DEADLINE_MS
-const RATE = 256 * 1024
-const BURST = 1024 * 1024
-
-/** What `WatchPty.join` answers for a session the viewer now watches. */
-export interface WatchJoin {
- sessionId: string
- /** The joined session's CURRENT size (`PtyManager.sessionSize`), never a viewer's (R25). */
- cols: number
- rows: number
- /** The stream is a tmux client's output (`PtyCreateResult.tmuxClient`), which tmux paints on the
- * alternate screen whatever the pane's application does (R18). */
- altScreen: boolean
- /** How a controller's input reaches this session's pane (`PtyManager.watcherInputRoute`). `none`
- * (Zellij, an unknown session; also what a missing or unknown answer reads as) refuses control. */
- input: WatcherInputRoute
-}
-
-/**
- * The pty seam (wired to PtyManager by the shells). Every argument is the HOST's: a node id from the
- * link record, a viewer id this module minted, a session id `join` answered. Nothing from a viewer.
- */
-export interface WatchPty {
- /**
- * Join the node's RUNNING session for this viewer (`joinAsWatcher`: join-only, no size vote, remote
- * fields from the host's own records). null for every refusal — no running session, any
- * `unavailable` (`join-only`, `ssh`, `codex-account`), a spawn refused because the window size could
- * not be read — and the caller may also throw; both mean "waiting, try again later".
- */
- join(clientId: number, nodeId: string, viewerId: string): Promise<WatchJoin | null>
- leave(clientId: number, sessionId: string, viewerId: string): void
- /** The visible screen and cursor, never history (`PtyManager.captureVisible`). */
- captureVisible(sessionId: string): Promise<VisibleCapture>
- /** Keep a watcher's OWN tmux client at the window's size (`PtyManager.syncWatcherClientSize`, which
- * serializes per session). Takes no size: nothing a viewer says can size anything. */
- syncSize(sessionId: string): Promise<boolean>
- /** The session is still known to the pty layer (an exit can race the join or a capture — R30). */
- alive(sessionId: string): boolean
- /** Deliver one chunk of a controller's input to the session's PANE (`PtyManager.controlInput`, never
- * a tmux client's key table). Whether it was delivered; a rejection counts as false. `isCurrent` is
- * asked right before the delivery runs (the chunk may wait behind a slow one): false — its sender no
- * longer controls, in the period it typed in — and it is never delivered. */
- input(sessionId: string, chunk: ControlInputChunk, isCurrent?: () => boolean): Promise<boolean>
-}
-export interface QuietClients {
- attach(sink: UiSink): number
- detach(id: number): void
-}
-export interface LinkHostDeps {
- relayUrl: string
- mint(): Promise<HostTokenResult>
- status(): Promise<'live' | 'revoked' | 'expired' | 'unknown'>
- clients: QuietClients
- pty: WatchPty
- transport?: () => RelayTransport
- now(): number
- setTimeout(fn: () => void, ms: number): unknown
- clearTimeout(h: unknown): void
- onChange(): void
- onChat(msg: WatchChatMessage): void
- onViewerJoined(count: number): void
- onGone(reason: 'revoked' | 'expired'): void
- /** A Control link's password check, against `record.control` as it is when called. Never asked
- * about a malformed or over-long password, and at most one check is in flight per link. */
- verifyPassword(pw: string): Promise<boolean>
- /** A viewer unlocked control, under this sanitized, self-chosen name. */
- onControlTaken(name: string): void
- /** WRONG_PER_LINK wrong attempts across the link. The service sets `record.control.locked = true`
- * (and when it lifts, `lockedUntil`) before it returns (the host reads the record live and never
- * writes it). `by`: the name the attempt that tipped it gave, else the chat name of the connection
- * that sent it, else null — a self-chosen claim, for the owner's notice. */
- onControlLocked(by?: string | null): void
- /** A wrong unlock attempt: the link-wide count is now `count` (1..WRONG_PER_LINK). The service puts it
- * on `record.control.wrong` and writes it (the 10th rides the lock's own write), so a restart does
- * not reset it. Called before `onControlLocked`. */
- onWrongAttempt(count: number): void
- /** Read-back (`watch:history`, ./history.ts): one transcript page of the link's node ending at
- * `before` (null: the newest). Rejects on a failed read. Absent: every request is answered
- * `unsupported`. The cutoff at the link's creation is applied HERE, not by the reader. */
- history?(before: number | null): Promise<HistoryRead>
- /** Whether the node is an agent with a readable conversation; asked for every (re)join's meta. */
- historySupported?(): boolean
-}
-export type LinkRuntimeStatus = 'live' | 'reconnecting' | 'refused'
-export interface LinkViewer {
- viewerId: string
- /** While controlling, the name it unlocked under; otherwise its chat name (null before it chats). */
- name: string | null
- joinedAt: number
- /** Connected, but its last join found no session to watch (R63): what the owner must be told,
- * because only the owner can fix it — on a backend with no watcher client (Windows' session host,
- * no local tmux, Zellij) a viewer can co-attach only to a terminal this app has OPEN. Set by a
- * REFUSED join, never by a session merely ending: that rejoins in seconds, usually successfully. */
- waiting: boolean
- /** Unlocked this Control link with its password and has not lost control since. */
- controlling: boolean
- /** Gave accepted input in the last TYPING_WINDOW_MS, while controlling. */
- typing: boolean
-}
-export interface LinkHost {
- start(): void
- stop(reason: WatchLinkEndReason): void
- kick(viewerId: string): boolean
- postSharerChat(text: string): WatchChatMessage | null
- chatHistory(): WatchChatMessage[]
- status(): LinkRuntimeStatus
- viewers(): LinkViewer[]
- /** The service changed `record.control.enabled` (or cleared `locked`): off or locked demotes every
- * controller, and every joined viewer is told its state. */
- controlChanged(): void
- /** The password was replaced: every controller is demoted and must unlock with the new one, and the
- * link-wide wrong count starts over (the service resets the record's). */
- passwordChanged(): void
- /** The lock was cleared — the owner's Allow control again, or its time ran out (the service's timer,
- * finding L2): the link-wide wrong count starts over, then as `controlChanged`. */
- allowControl(): void
-}
-
-interface Conn {
- viewerId: string
- ev: { onBridged(): void; onClose(): void }
- session: RelayHostSession | null
- clientId: number | null
- /** The WRAPPED watcher sink relay-host attached (every event we send passes its outbound filter). */
- sink: UiSink | null
- attachFailed: boolean
- bridged: boolean
- ended: boolean
- confirmTimer: unknown
- /** When both ends confirmed and the viewer became a client; null before. */
- joinedAt: number | null
- name: string | null
- lastChatAt: number
- /** Unlocked this Control link (per connection: a reconnect unlocks again). */
- controlling: boolean
- /** Wrong unlock attempts on this connection since its last success. */
- wrong: number
- /** When this viewer's last unlock attempt was taken (a too-soon one is not). */
- lastUnlockAt: number
- /** When this connection last stopped controlling (INPUT_GRACE_MS); null while it never did. */
- controlStoppedAt: number | null
- /** Bumped every time this connection loses control: a batch from before is never delivered. */
- controlGen: number
- /** The last landed join's input route; null before the first one. */
- input: WatcherInputRoute | null
- splitter: InputSplitter
- inputBucket: TokenBucket
- /** Input collected since the last flush: its chunks, the session it was typed at, its UTF-8 bytes. */
- batch: ControlInputChunk[]
- /** The batch reached INPUT_CHUNKS_MAX: the rest of it is dropped until it is flushed. */
- batchFull: boolean
- batchSession: string | null
- batchBytes: number
- batchTimer: unknown
- /** A batch of this connection is in the host-wide flush chain and has not finished. */
- inChain: boolean
- /** The chunk being delivered now: its deadline timer, and how to settle it early (end, stop). */
- delivery: { timer: unknown; settle(ok: boolean): void } | null
- lastDroppedAt: number
- /** The name control was taken under (the unlock's); a later chat name does not change who typed. */
- controlName: string | null
- /** A Control link: the key pair THIS connection's unlock is sealed to (finding L3), made with the
- * first meta and kept for the connection's life (its public half rides every meta); zeroed at the end. */
- unlockKeys: nacl.BoxKeyPair | null
- /** This connection sent a sealed unlock: a later one in the clear is refused (counted as malformed). */
- sealedOnly: boolean
- // The watched session (null while waiting).
- sessionId: string | null
- altScreen: boolean
- joining: boolean
- waiting: boolean
- /** The last join answered no session (LinkViewer.waiting). Cleared by a join that lands. */
- joinRefused: boolean
- streaming: boolean
- filter: StreamFilter
- bucket: TokenBucket
- /** The current session's mid-stream filter has left its unknown start state. */
- settled: boolean
- /** Take one more keyframe when it does (it had not when the join keyframe was delivered). */
- followUpOnSettle: boolean
- /** The current session's first keyframe step is done: painted, or skipped because there was no
- * capture (R36). From here the viewer streams. */
- joinKeyframeDone: boolean
- kfSeq: number
- kfDelivered: number
- /** When the last keyframe step was done (painted or skipped): keyframes and resumes are ≤ 1/s. */
- lastKeyframeAt: number
- keyframeTimer: unknown
- settleTimer: unknown
- stableTimer: unknown
- rejoinAttempt: number
- rejoinTimer: unknown
- /** Read-back: a read is running; the request that arrived meanwhile (the newest wins); when the last
- * read started; the timer holding the next one to HISTORY_MIN_INTERVAL_MS. */
- historyBusy: boolean
- historyNext: { before: number | null } | null
- historyLastAt: number
- historyTimer: unknown
- warned: Set<string>
-}
-
-/** One connection's batch in the flush chain: its chunks, the session typed at, the control period. */
-interface Batch {
- chunks: ControlInputChunk[]
- session: string
- gen: number
-}
-
-interface CaptureSlot {
- current: { epoch: number; result: Promise<VisibleCapture> } | null
- /** The one rerun queued behind `current`, shared by every keyframe that needs a newer capture. */
- next: { result: Promise<VisibleCapture>; start(): void } | null
-}
-
-/** The same members, in any order (the typing set is a set: a new order alone is no news). */
-function sameMembers(a: string[], b: string[]): boolean {
- if (a.length !== b.length) return false
- const set = new Set(b)
- return a.every((x) => set.has(x))
-}
-
-/** The session a join attached to, if it answered one (a refused join may still have attached). */
-function joinedSessionId(r: unknown): string | null {
- const sid = r && typeof r === 'object' ? (r as { sessionId?: unknown }).sessionId : undefined
- return typeof sid === 'string' && sid ? sid : null
-}
-
-/** A usable join, or null. A join without a valid size is REFUSED, never given a guessed one (R20, R37):
- * a wiring slip then shows as "waiting", loudly, instead of a viewer laid out at a wrong size for the
- * rest of the session (its join-time `pty:size` was already recorded as shown and is not resent). */
-function normalizeJoin(r: unknown): WatchJoin | null {
- const sessionId = joinedSessionId(r)
- if (sessionId === null) return null
- const o = r as Partial<WatchJoin>
- const dim = (n: unknown): boolean => Number.isInteger(n) && (n as number) > 0
- if (!dim(o.cols) || !dim(o.rows)) return null
- // A missing or unknown route refuses control: typing must never be guessed onto a backend.
- const input = (WATCHER_INPUT_ROUTES as readonly unknown[]).includes(o.input) ? (o.input as WatcherInputRoute) : 'none'
- return { sessionId, cols: o.cols as number, rows: o.rows as number, altScreen: o.altScreen === true, input }
-}
-
-/** A well-formed unlock payload, or null. The password is bounded before anything else reads it: over
- * PASSWORD_MAX code points is malformed, and the cheap UTF-16 test first means a huge string is never
- * split into an array. An empty one cannot match any stored password and is not worth a scrypt. */
-function readUnlock(p: unknown): { name: string; password: string } | null {
- if (!p || typeof p !== 'object') return null
- const name = sanitizeChatName((p as { name?: unknown }).name)
- const password = (p as { password?: unknown }).password
- if (!name || typeof password !== 'string' || password.length === 0) return null
- if (password.length > PASSWORD_MAX * 2 || Array.from(password).length > PASSWORD_MAX) return null
- return { name, password }
-}
-
-/** The link-wide wrong count a record holds, as an integer 0..WRONG_PER_LINK: a hand edit cannot buy
- * guesses (the store refuses anything else on load; this is the host's own belt). */
-function storedWrong(r: WatchLinkRecord): number {
- const n = r.control?.wrong
- if (typeof n !== 'number' || Number.isNaN(n)) return 0
- return Math.min(WRONG_PER_LINK, Math.max(0, Math.floor(n)))
-}
-
-function normalizeCapture(c: unknown): VisibleCapture {
- if (!c || typeof c !== 'object' || typeof (c as VisibleCapture).screen !== 'string') return unavailableCapture()
- if ((c as VisibleCapture).unavailable === true) return unavailableCapture()
- const cur = (c as VisibleCapture).cursor
- const ok = !!cur && Number.isInteger(cur.x) && Number.isInteger(cur.y) && cur.x >= 0 && cur.y >= 0
- const alt = (c as VisibleCapture).altScreen
- return {
- screen: (c as VisibleCapture).screen,
- cursor: ok ? { x: cur!.x, y: cur!.y } : null,
- ...(typeof alt === 'boolean' ? { altScreen: alt } : {})
- }
-}
-
-export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): LinkHost {
- const keys = deriveWatchLinkKeys(record.secret)
- const hostKeys = { publicKey: keys.host.publicKey, secretKey: keys.host.secretKey }
- const expectedViewerKey = bytesToB64(keys.viewer.publicKey)
- const conns = new Set<Conn>()
- const chat: WatchChatMessage[] = []
- const captures = new Map<string, CaptureSlot>()
- let captureEpoch = 0
- let sched: SchedulerStatus | null = null
- let pollTimer: unknown = null
- let syncTimer: unknown = null
- let stopped = false
- const warnedHost = new Set<string>()
- /** Wrong unlock attempts across the link, starting from the record's (the service persists every new
- * count, so an app restart does not reset it). */
- let linkWrong = storedWrong(record)
- /** A password check is in flight: one per link. */
- let verifying = false
- /** Bumped by every change to control (off/on, a new password, the lock, allowControl): a check that
- * started under an older epoch is void when it returns. */
- let controlEpoch = 0
- /** One delivery at a time across the link: every controller's batch reaches the pane whole, in
- * flush order. Never rejects (each link is caught), so a failure cannot stall the chain. */
- let inputChain: Promise<void> = Promise.resolve()
- const tracker = createTypingTracker()
- /** The typing set as last sent (names) and the viewers in it (for the owner's view). */
- let typingNames: string[] = []
- let typingIds: string[] = []
- let typingTimer: unknown = null
- let lastTypingAt = -Infinity
-
- const clearTimer = (h: unknown): void => {
- if (h !== null) deps.clearTimeout(h)
- }
- /** One line per kind per viewer (or per link): a failure that repeats every rejoin must not flood. */
- const warn = (c: Conn | null, kind: string, detail: string): void => {
- const seen = c ? c.warned : warnedHost
- if (seen.has(kind)) return
- seen.add(kind)
- console.warn(`[watch-link] ${kind}: ${detail}`)
- }
- /** A callback the registry owns must not throw into relay-host's emit or the trust gate's settle. */
- const safe = (label: string, fn: () => void): void => {
- try {
- fn()
- } catch (err) {
- console.warn(`[watch-link] ${label} threw: ${errorText(err)}`)
- }
- }
- const bufferedOf = (c: Conn): number => {
- try {
- return c.sink?.bufferedAmount?.() ?? 0
- } catch {
- return 0
- }
- }
-
- /** Send one `watch:*` event through the viewer's own (filtered) sink. False when not sent. */
- function send(c: Conn, channel: string, payload: unknown, opts: { chat?: boolean } = {}): boolean {
- if (c.ended || !c.sink) return false
- const buffered = bufferedOf(c)
- if (buffered > VIEWER_BACKLOG_CLOSE) {
- dropStalled(c)
- return false
- }
- if (opts.chat && buffered > WATCHER_BUFFER_LIMIT) return false
- try {
- c.sink.sendText(JSON.stringify({ t: 'ev', channel, args: [payload] }))
- } catch {
- // A dead socket: relay-host's own close tears the session down.
- }
- return true
- }
- function dropStalled(c: Conn): void {
- // While stopping, the scheduler may still be running (the end notices go out first): closing now
- // would re-mint a listener on a full link. `stop` closes every viewer a moment later anyway (R37).
- if (stopped) return
- warn(null, 'a viewer stopped draining its socket; closed it', `backlog over ${VIEWER_BACKLOG_CLOSE} bytes`)
- c.session?.close()
- ended(c)
- }
- function leave(clientId: number | null, sessionId: string, viewerId: string, c: Conn | null): void {
- if (clientId === null || clientId < 0) return
- try {
- deps.pty.leave(clientId, sessionId, viewerId)
- } catch (err) {
- warn(c, 'leaving a watched session failed', errorText(err))
- }
- }
- const aliveOf = (c: Conn, sessionId: string): boolean => {
- try {
- return deps.pty.alive(sessionId) === true
- } catch (err) {
- warn(c, 'the session liveness check failed', errorText(err))
- return false
- }
- }
-
- function ended(c: Conn): void {
- if (c.ended) return
- c.ended = true
- conns.delete(c)
- for (const h of [c.confirmTimer, c.rejoinTimer, c.keyframeTimer, c.settleTimer, c.stableTimer, c.historyTimer]) clearTimer(h)
- c.confirmTimer = c.rejoinTimer = c.keyframeTimer = c.settleTimer = c.stableTimer = c.historyTimer = null
- c.historyNext = null
- const sid = c.sessionId
- c.sessionId = null
- c.streaming = false
- c.controlling = false
- clearInput(c)
- c.splitter.reset()
- // A delivery still waiting for the pane must not hold every other controller's batch.
- c.delivery?.settle(false)
- forgetTyping(c)
- c.unlockKeys?.secretKey.fill(0)
- c.unlockKeys = null
- if (sid !== null) leave(c.clientId, sid, c.viewerId, c)
- safe('the scheduler', () => c.ev.onClose())
- updateSyncTimer()
- if (c.joinedAt !== null && !stopped) safe('onChange', deps.onChange)
- }
- function endConn(c: Conn, reason: WatchLinkEndReason): void {
- send(c, WATCH_EVENT.end, { reason })
- c.session?.close()
- ended(c)
- }
- /** The access policy let something through: fail closed. */
- function policyBreach(c: Conn, what: string): void {
- // `what` names a peer-chosen method: quoted and capped, so it cannot forge a log line.
- console.warn(`[watch-link] a viewer's ${JSON.stringify(what.slice(0, 80))} got past the watcher policy; closing that viewer`)
- c.session?.close()
- ended(c)
- }
-
- // --- captures: one in flight per session, shared by this link's viewers (R27) ---------------------
-
- async function runCapture(sessionId: string): Promise<VisibleCapture> {
- // Size first, so the screen is captured at the size the viewer is about to be told.
- try {
- await deps.pty.syncSize(sessionId)
- } catch (err) {
- warn(null, 'the watcher size sync failed', errorText(err))
- }
- try {
- return normalizeCapture(await deps.pty.captureVisible(sessionId))
- } catch (err) {
- warn(null, 'a keyframe capture failed', errorText(err))
- return unavailableCapture()
- }
- }
- function startCapture(sessionId: string, slot: CaptureSlot): Promise<VisibleCapture> {
- const result = runCapture(sessionId)
- slot.current = { epoch: ++captureEpoch, result }
- void result.then(() => {
- slot.current = null
- const next = slot.next
- slot.next = null
- if (next) next.start()
- else if (captures.get(sessionId) === slot) captures.delete(sessionId)
- })
- return result
- }
- /** A capture of `sessionId` that started after epoch `needAfter` (-1: any, even one running now). */
- function captureFor(sessionId: string, needAfter: number): Promise<VisibleCapture> {
- let slot = captures.get(sessionId)
- if (!slot) {
- slot = { current: null, next: null }
- captures.set(sessionId, slot)
- }
- if (!slot.current) return startCapture(sessionId, slot)
- if (slot.current.epoch > needAfter) return slot.current.result
- if (slot.next) return slot.next.result
- const s = slot
- let resolve: (v: VisibleCapture | Promise<VisibleCapture>) => void = () => {}
- const result = new Promise<VisibleCapture>((r) => (resolve = r))
- s.next = { result, start: () => resolve(stopped ? unavailableCapture() : startCapture(sessionId, s)) }
- return result
- }
-
- // --- keyframes ------------------------------------------------------------------------------------
-
- function requestKeyframe(c: Conn, join: boolean): void {
- const sid = c.sessionId
- if (sid === null || c.ended || stopped) return
- // Nothing is forwarded from here until the newest keyframe is painted: a frame sent now could be
- // painted over by an older screen.
- c.streaming = false
- const seq = ++c.kfSeq
- void captureFor(sid, join ? -1 : captureEpoch).then((cap) => {
- try {
- deliverKeyframe(c, sid, seq, cap)
- } catch (err) {
- warn(c, 'painting a keyframe failed', errorText(err))
- }
- })
- }
- function deliverKeyframe(c: Conn, sid: string, seq: number, cap: VisibleCapture): void {
- if (c.ended || stopped || c.sessionId !== sid || seq <= c.kfDelivered) return
- if (!aliveOf(c, sid)) {
- sessionOver(c)
- return
- }
- // No capture (R36): nothing is painted — an empty keyframe would erase what the stream drew — but
- // the step still counts as done, so the viewer streams (it must not wait for a keyframe that never
- // comes) and the next request waits out the minimum interval like a painted one.
- if (!cap.unavailable) {
- const kf: WatchKeyframe = {
- sessionId: sid,
- // A FRESH filter: the capture starts in ground state, and carries OSC 8 links verbatim (R9).
- screen: createStreamFilter().push(cap.screen),
- // The join's answer (R18), unless the capture knows the stream's buffer itself (session host).
- altScreen: cap.altScreen ?? c.altScreen,
- ...(cap.cursor ? { cursor: { x: cap.cursor.x, y: cap.cursor.y } } : {})
- }
- if (!send(c, WATCH_EVENT.keyframe, kf)) return
- }
- c.kfDelivered = seq
- c.lastKeyframeAt = deps.now()
- if (seq === c.kfSeq) c.streaming = true
- if (!c.joinKeyframeDone) {
- c.joinKeyframeDone = true
- c.followUpOnSettle = !c.settled
- clearTimer(c.stableTimer)
- c.stableTimer = deps.setTimeout(() => {
- c.stableTimer = null
- c.rejoinAttempt = 0
- }, REJOIN_STABLE_MS)
- }
- }
- /** A keyframe at most KEYFRAME_MIN_INTERVAL_MS after the last one, once the socket has drained. */
- function scheduleKeyframe(c: Conn): void {
- if (c.ended || stopped || c.sessionId === null || c.keyframeTimer !== null) return
- const tick = (): void => {
- c.keyframeTimer = null
- if (c.ended || stopped || c.sessionId === null) return
- const buffered = bufferedOf(c)
- if (buffered > VIEWER_BACKLOG_CLOSE) {
- dropStalled(c)
- return
- }
- // Wait for the socket to drain before painting over it.
- if (buffered > WATCHER_RESUME_BELOW) {
- c.keyframeTimer = deps.setTimeout(tick, KEYFRAME_MIN_INTERVAL_MS)
- return
- }
- requestKeyframe(c, false)
- }
- c.keyframeTimer = deps.setTimeout(tick, Math.max(0, KEYFRAME_MIN_INTERVAL_MS - (deps.now() - c.lastKeyframeAt)))
- }
- /** WatcherSinkDeps.onOverBudget: stop forwarding NOW, whatever is armed (F10), then repaint. */
- function throttle(c: Conn): void {
- c.streaming = false
- scheduleKeyframe(c)
- }
- function onSettled(c: Conn, sid: string): void {
- if (c.ended || c.sessionId !== sid) return
- c.settled = true
- clearTimer(c.settleTimer)
- c.settleTimer = null
- if (c.followUpOnSettle) {
- c.followUpOnSettle = false
- scheduleKeyframe(c)
- }
- }
-
- // --- joining the node's session -------------------------------------------------------------------
-
- function enterWaiting(c: Conn): void {
- if (c.waiting) return
- c.waiting = true
- send(c, WATCH_EVENT.waiting, {})
- }
- /** The owner's view of a viewer with nothing to watch (LinkViewer.waiting): reported on a change only,
- * so a rejoin loop that keeps failing costs one push, not one per attempt. */
- function setJoinRefused(c: Conn, refused: boolean): void {
- if (c.joinRefused === refused) return
- c.joinRefused = refused
- if (c.joinedAt !== null && !c.ended) safe('onChange', deps.onChange)
- }
- function scheduleRejoin(c: Conn): void {
- if (c.ended || stopped || c.rejoinTimer !== null) return
- const delay = REJOIN_BACKOFF_MS[Math.min(c.rejoinAttempt, REJOIN_BACKOFF_MS.length - 1)]
- c.rejoinAttempt++
- c.rejoinTimer = deps.setTimeout(() => {
- c.rejoinTimer = null
- runJoin(c)
- }, delay)
- }
- const runJoin = (c: Conn): void => {
- join(c).catch((err) => warn(c, 'a join failed', errorText(err)))
- }
- async function join(c: Conn): Promise<void> {
- if (c.ended || stopped || c.clientId === null || c.clientId < 0 || c.joining || c.sessionId !== null) return
- c.joining = true
- const clientId = c.clientId
- let res: WatchJoin | null = null
- let attached: string | null = null
- try {
- const raw = await deps.pty.join(clientId, record.nodeId, c.viewerId)
- attached = joinedSessionId(raw)
- res = normalizeJoin(raw)
- if (!res && attached !== null) warn(c, 'a join answered no valid size; refused', `session ${attached}`)
- } catch (err) {
- warn(c, 'joining the node session failed', errorText(err))
- } finally {
- c.joining = false
- }
- // Refused, or this viewer went away meanwhile: never stay subscribed to what the join attached.
- if (attached !== null && (!res || c.ended || stopped)) leave(clientId, attached, c.viewerId, c)
- if (c.ended || stopped) return
- // An exit that raced the join was delivered before this viewer knew its session id, and dropped.
- if (res && !aliveOf(c, res.sessionId)) {
- leave(clientId, res.sessionId, c.viewerId, c)
- res = null
- }
- if (!res) {
- enterWaiting(c)
- setJoinRefused(c, true)
- scheduleRejoin(c)
- return
- }
- setJoinRefused(c, false)
- const sid = res.sessionId
- // EVERY join restarts the filter mid-stream (R12): this is a running session.
- c.filter.reset({ midStream: true, onSettled: () => onSettled(c, sid) })
- c.sessionId = sid
- c.altScreen = res.altScreen
- c.streaming = false
- c.joinKeyframeDone = false
- c.settled = false
- c.followUpOnSettle = false
- c.waiting = false
- c.input = res.input
- // A terminal that cannot take input: whoever controls it stops (its keystrokes in flight get the
- // grace), and the meta below says `unsupported`.
- const demoted = res.input === 'none' && c.controlling
- if (demoted) loseControl(c)
- // Meta after EVERY (re)attach: the viewer leaves `waiting` on it (R14).
- const meta: WatchMeta = {
- v: WATCH_PROTOCOL_VERSION,
- role: record.role,
- label: record.label,
- title: record.title,
- expiresAt: record.expiresAt,
- cols: res.cols,
- rows: res.rows
- }
- // A Control link's state for THIS viewer rides every (re)join, with the key its unlock is sealed to
- // (one per connection, the same on every rejoin); absent on every other role.
- if (record.role === 'controller') {
- meta.control = controlStateFor(c)
- c.unlockKeys ??= nacl.box.keyPair()
- meta.unlockKey = bytesToB64(c.unlockKeys.publicKey)
- }
- if (historySupported()) meta.history = true
- if (!send(c, WATCH_EVENT.meta, meta)) return
- // The typing set is otherwise sent only when it changes: a viewer (re)joining mid-typing would
- // never learn it.
- if (typingNames.length > 0) send(c, WATCH_EVENT.typing, { names: typingNames })
- if (demoted) safe('onChange', deps.onChange)
- clearTimer(c.settleTimer)
- c.settleTimer = deps.setTimeout(() => {
- c.settleTimer = null
- if (c.sessionId === sid && !c.settled) scheduleKeyframe(c)
- }, SETTLE_BOUND_MS)
- requestKeyframe(c, true)
- updateSyncTimer()
- }
- /** The watched session is over: leave it, say so, look for the next one. */
- function sessionOver(c: Conn): void {
- const sid = c.sessionId
- if (sid === null || c.ended) return
- c.sessionId = null
- c.streaming = false
- c.followUpOnSettle = false
- for (const h of [c.keyframeTimer, c.settleTimer, c.stableTimer]) clearTimer(h)
- c.keyframeTimer = c.settleTimer = c.stableTimer = null
- const clientId = c.clientId
- // Deferred: a lifecycle event arrives from inside PtyManager's own delivery loop for that session.
- queueMicrotask(() => leave(clientId, sid, c.viewerId, c))
- // Input typed at this session's screen never reaches the next session.
- abandonInput(c)
- enterWaiting(c)
- scheduleRejoin(c)
- updateSyncTimer()
- }
-
- // --- size sync ------------------------------------------------------------------------------------
-
- function activeSessions(): Set<string> {
- const out = new Set<string>()
- for (const c of conns) if (!c.ended && c.sessionId !== null) out.add(c.sessionId)
- return out
- }
- function syncSize(sessionId: string): void {
- try {
- void deps.pty.syncSize(sessionId).catch((err) => warn(null, 'the watcher size sync failed', errorText(err)))
- } catch (err) {
- warn(null, 'the watcher size sync failed', errorText(err))
- }
- }
- function updateSyncTimer(): void {
- if (stopped || activeSessions().size === 0) {
- clearTimer(syncTimer)
- syncTimer = null
- return
- }
- if (syncTimer !== null) return
- syncTimer = deps.setTimeout(() => {
- syncTimer = null
- if (stopped) return
- for (const sid of activeSessions()) syncSize(sid)
- updateSyncTimer()
- }, WATCHER_SIZE_SYNC_MS)
- }
-
- // --- chat -----------------------------------------------------------------------------------------
-
- function publish(msg: WatchChatMessage): void {
- chat.push(msg)
- if (chat.length > CHAT_HISTORY_MAX) chat.splice(0, chat.length - CHAT_HISTORY_MAX)
- for (const c of [...conns]) if (c.joinedAt !== null && !c.ended) send(c, WATCH_EVENT.chat, msg, { chat: true })
- safe('onChat', () => deps.onChat(msg))
- safe('onChange', deps.onChange)
- }
- function onViewerCast(c: Conn, method: string, args: unknown[]): void {
- // relay-host's access hook admits exactly these (watcherAccess); anything else got past it.
- if (method === WATCH_HISTORY_CAST) {
- onHistory(c, args)
- return
- }
- if (method === WATCH_CHAT_CAST && (record.role === 'commenter' || record.role === 'controller')) {
- onChat(c, args)
- return
- }
- if (record.role === 'controller') {
- if (method === WATCH_UNLOCK_CAST) {
- // Never the error's text: nothing that might carry the password is logged.
- onUnlock(c, args).catch((err) => warn(c, 'an unlock failed', err instanceof Error ? err.name : 'not an Error'))
- return
- }
- if (method === WATCH_INPUT_CAST) {
- onInput(c, args)
- return
- }
- if (method === WATCH_RELEASE_CAST) {
- onRelease(c)
- return
- }
- }
- policyBreach(c, `cast ${method}`)
- }
- function onChat(c: Conn, args: unknown[]): void {
- if (c.ended || c.joinedAt === null) return
- const now = deps.now()
- if (now - c.lastChatAt < CHAT_MIN_INTERVAL_MS) return
- const p = args[0]
- if (!p || typeof p !== 'object') return
- const name = sanitizeChatName((p as { name?: unknown }).name)
- const text = sanitizeChatText((p as { text?: unknown }).text)
- if (!name || !text) return
- c.lastChatAt = now
- c.name = name
- publish({ id: bytesToHex(nacl.randomBytes(8)), name, text, at: now, from: 'viewer' })
- }
-
- // --- read-back (./history.ts) ---------------------------------------------------------------------
-
- function historySupported(): boolean {
- try {
- return deps.historySupported?.() === true
- } catch (err) {
- warn(null, 'asking whether read-back is there failed', errorText(err))
- return false
- }
- }
- function onHistory(c: Conn, args: unknown[]): void {
- if (c.ended || c.joinedAt === null || stopped) return
- // A malformed request is ignored, like a malformed chat line: the cast itself is admitted.
- const req = readHistoryRequest(args[0])
- if (!req) return
- c.historyNext = req
- pumpHistory(c)
- }
- function pumpHistory(c: Conn): void {
- if (c.ended || stopped || c.historyBusy || c.historyTimer !== null || c.historyNext === null) return
- const wait = HISTORY_MIN_INTERVAL_MS - (deps.now() - c.historyLastAt)
- if (wait > 0) {
- c.historyTimer = deps.setTimeout(() => {
- c.historyTimer = null
- pumpHistory(c)
- }, wait)
- return
- }
- const { before } = c.historyNext
- c.historyNext = null
- c.historyBusy = true
- c.historyLastAt = deps.now()
- const read = async (): Promise<HistoryRead | null> => {
- if (!deps.history) return { kind: 'unsupported' }
- try {
- return await deps.history(before)
- } catch (err) {
- warn(c, 'a read-back failed', errorText(err))
- return null
- }
- }
- void read().then((r) => {
- c.historyBusy = false
- if (c.ended || stopped) return
- // The record is read now: the cutoff is the link's creation, whatever the reader returned.
- send(c, WATCH_EVENT.history, historyPageFrom(r, record.createdAt, before))
- pumpHistory(c)
- })
- }
-
- // --- control (a Control link) -----------------------------------------------------------------------
-
- /** This viewer's control state, as meta and every unprompted `watch:control` carry it. */
- function controlStateFor(c: Conn): WatchControlEvent {
- const ctl = record.control
- // The watched terminal cannot take input (Zellij, an unknown session): no password changes that.
- if (c.input === 'none') return { state: 'off', reason: 'unsupported' }
- if (c.controlling && ctl && ctl.enabled && !ctl.locked) return { state: 'controlling' }
- if (ctl?.locked) return lockedState()
- if (!ctl || !ctl.enabled) return { state: 'off' }
- return { state: 'available' }
- }
- /** `locked`, with how long until it lifts by itself when it does (finding L2): from the record's
- * `lockedUntil`, which the service sets with the lock and clears when it lifts. */
- function lockedState(reason?: 'locked'): WatchControlEvent {
- const until = record.control?.lockedUntil
- const ev: WatchControlEvent = reason ? { state: 'locked', reason } : { state: 'locked' }
- if (typeof until === 'number' && Number.isFinite(until)) {
- ev.lockedForMs = Math.min(CONTROL_LOCK_MAX_MS, Math.max(0, Math.round(until - deps.now())))
- }
- return ev
- }
- /**
- * An unlock cast's `{ name, password }`, sealed or plain, or null when it is malformed (counted). A
- * sealed one must open with THIS connection's key (finding L3) and latches the connection: a plain
- * one after it is malformed — a page that seals never sends one, so it can only be a replay or a
- * downgrade. A plain one is what a page from before sealing sends, and is read as before.
- */
- function unlockOf(c: Conn, arg: unknown): { name: string; password: string } | null {
- if (!isSealedUnlock(arg)) return c.sealedOnly ? null : readUnlock(arg)
- c.sealedOnly = true
- const opened = c.unlockKeys ? openUnlock(arg, c.unlockKeys.secretKey) : null
- return opened ? readUnlock(opened) : null
- }
- function sendControl(c: Conn, ev: WatchControlEvent): void {
- send(c, WATCH_EVENT.control, ev)
- }
- const joinedConns = (): Conn[] => [...conns].filter((c) => c.joinedAt !== null && !c.ended)
-
- async function onUnlock(c: Conn, args: unknown[]): Promise<void> {
- if (c.ended || c.joinedAt === null || stopped) return
- const state = controlStateFor(c)
- // Already controlling, locked or off: answered as it stands, never counted, never throttled.
- if (state.state === 'controlling') {
- sendControl(c, state)
- return
- }
- if (state.state === 'locked' || state.state === 'off') {
- sendControl(c, { ...state, reason: state.reason ?? state.state })
- return
- }
- const now = deps.now()
- if (verifying || now - c.lastUnlockAt < UNLOCK_MIN_INTERVAL_MS) {
- sendControl(c, { state: state.state, reason: 'too-soon' })
- return
- }
- c.lastUnlockAt = now
- const attempt = unlockOf(c, args[0])
- // A malformed attempt is still an attempt.
- if (!attempt) {
- wrongAttempt(c, null)
- return
- }
- verifying = true
- const epoch = controlEpoch
- let right: boolean | null = null
- try {
- right = (await deps.verifyPassword(attempt.password)) === true
- } catch (err) {
- warn(c, 'a control password check failed', err instanceof Error ? err.name : 'not an Error')
- } finally {
- verifying = false
- }
- if (c.ended || stopped) return
- if (right === null || epoch !== controlEpoch || controlStateFor(c).state !== 'available') {
- refuseVoid(c)
- return
- }
- if (!right) {
- wrongAttempt(c, attempt.name)
- return
- }
- c.controlling = true
- c.wrong = 0
- c.name = attempt.name
- c.controlName = attempt.name
- sendControl(c, { state: 'controlling' })
- // That send can end the connection (a backlog past VIEWER_BACKLOG_CLOSE): then nobody took control.
- if (c.ended) return
- safe('onControlTaken', () => deps.onControlTaken(attempt.name))
- safe('onChange', deps.onChange)
- }
- /** A check whose answer no longer applies (control changed under it, or it failed): void, not
- * wrong. Nothing is counted, and the viewer may try again. */
- function refuseVoid(c: Conn): void {
- const state = controlStateFor(c)
- if (state.state === 'locked' || state.state === 'off') sendControl(c, { ...state, reason: state.reason ?? state.state })
- else sendControl(c, { state: state.state, reason: 'too-soon' })
- }
- /** `name`: the name this attempt gave, when it was well formed; the lock's notice names it. */
- function wrongAttempt(c: Conn, name: string | null): void {
- c.wrong++
- linkWrong++
- // The service records (and writes) the link-wide count before any lock below.
- const count = Math.min(linkWrong, WRONG_PER_LINK)
- safe('onWrongAttempt', () => deps.onWrongAttempt(count))
- sendControl(c, { state: controlStateFor(c).state, reason: 'wrong' })
- if (linkWrong >= WRONG_PER_LINK) lockLink(name ?? c.name)
- if (c.wrong >= WRONG_PER_CONN) endConn(c, 'attempts')
- }
- /** Locked: the service records it (synchronously, in `onControlLocked`), every viewer is told, and
- * every controller drops back to watching. `by`: who tipped it, as it named itself (or null). */
- function lockLink(by: string | null): void {
- controlEpoch++
- safe('onControlLocked', () => deps.onControlLocked(by))
- // The lock rests on the service recording it before it returns. If it did not (it threw, or a
- // wiring slip), the next attempt would be verified again: say so loudly, and still demote and tell.
- if (record.control?.locked !== true) console.error('[watch-link] onControlLocked did not lock the link')
- for (const c of joinedConns()) {
- loseControl(c)
- sendControl(c, lockedState('locked'))
- }
- safe('onChange', deps.onChange)
- }
- /** Control changed under every viewer: off or locked demotes the controllers; each is told. */
- function broadcastControl(): void {
- controlEpoch++
- const ctl = record.control
- const usable = !!ctl && ctl.enabled && !ctl.locked
- for (const c of joinedConns()) {
- if (!usable) loseControl(c)
- sendControl(c, controlStateFor(c))
- }
- safe('onChange', deps.onChange)
- }
- function onRelease(c: Conn): void {
- if (c.ended || c.joinedAt === null || !c.controlling) return
- loseControl(c)
- sendControl(c, controlStateFor(c))
- safe('onChange', deps.onChange)
- }
-
- // --- typing: the input path ---------------------------------------------------------------------------
-
- /** This connection stops controlling: its pending input is discarded, an open paste forgotten, it
- * leaves the typing set, and its keystrokes still in flight get INPUT_GRACE_MS of silence. */
- function loseControl(c: Conn): void {
- if (!c.controlling) return
- c.controlling = false
- c.controlStoppedAt = deps.now()
- c.controlGen++
- clearInput(c)
- c.splitter.reset()
- forgetTyping(c)
- }
- function clearInput(c: Conn): void {
- clearTimer(c.batchTimer)
- c.batchTimer = null
- c.batch = []
- c.batchFull = false
- c.batchBytes = 0
- c.batchSession = null
- }
- /** The watched session ended: pending input is dropped (and the controller told), and an open paste
- * is discarded whole when its end arrives. */
- function abandonInput(c: Conn): void {
- const had = c.batch.length > 0 || c.splitter.pasteOpen()
- clearInput(c)
- c.splitter.discard('')
- if (had) noteDropped(c)
- }
- /** "Some of your input did not reach the terminal", at most once per DROPPED_NOTICE_MIN_MS, and only
- * to a connection that is still controlling (one that lost control was told its new state). */
- function noteDropped(c: Conn): void {
- if (c.ended || controlStateFor(c).state !== 'controlling') return
- const now = deps.now()
- if (now - c.lastDroppedAt < DROPPED_NOTICE_MIN_MS) return
- c.lastDroppedAt = now
- sendControl(c, { state: 'controlling', reason: 'dropped' })
- }
- const withinGrace = (c: Conn): boolean => c.controlStoppedAt !== null && deps.now() - c.controlStoppedAt <= INPUT_GRACE_MS
-
- function onInput(c: Conn, args: unknown[]): void {
- if (c.ended) return
- if (controlStateFor(c).state !== 'controlling') {
- // Keystrokes in flight when control ended (released, demoted, or the record changed and the
- // host has not been told yet) are dropped silently. From anyone else, or later, a breach.
- if (c.controlling || withinGrace(c)) return
- policyBreach(c, `cast ${WATCH_INPUT_CAST}`)
- return
- }
- const p = args[0]
- const data = p && typeof p === 'object' ? (p as { data?: unknown }).data : undefined
- if (typeof data !== 'string' || data.length === 0 || data.length > INPUT_MAX) {
- policyBreach(c, `malformed ${WATCH_INPUT_CAST}`)
- return
- }
- // The viewer's emulator answering the pane's own queries (DA, CPR, a colour) is not typing: every
- // controller would answer every query again into the pane. Not counted against the budget.
- if (isTerminalReport(data)) return
- const bytes = Buffer.byteLength(data, 'utf8')
- const sid = c.sessionId
- // No session to type into (waiting), or over budget — a batch already holding INPUT_CHUNKS_MAX
- // chunks, the bucket, or a batch the panes have not taken yet already holding a burst: dropped, and
- // the viewer told. Input is never held for a later session. The splitter still sees it, so a paste
- // it belonged to is discarded whole.
- if (sid === null || c.batchFull || c.batchBytes + bytes > INPUT_BURST || !c.inputBucket.take(bytes)) {
- c.splitter.discard(data)
- noteDropped(c)
- return
- }
- if (c.batchSession !== null && c.batchSession !== sid) abandonInput(c)
- c.batchSession = sid
- c.batchBytes += bytes
- appendChunks(c, c.splitter.push(data))
- if (c.controlName) tracker.note(c.viewerId, c.controlName, deps.now())
- scheduleTyping()
- if (c.batchTimer === null) {
- c.batchTimer = deps.setTimeout(() => {
- c.batchTimer = null
- flushBatch(c)
- }, INPUT_BATCH_MS)
- }
- }
- /** Adjacent keys merge (up to INPUT_MAX units): one pane delivery per run of typing, not per cast. A
- * batch holds at most INPUT_CHUNKS_MAX chunks: the first chunk past it ends the batch's intake. */
- function appendChunks(c: Conn, chunks: ControlInputChunk[]): void {
- for (const ch of chunks) {
- if (c.batchFull) return
- const last = c.batch[c.batch.length - 1]
- if (ch.kind === 'keys' && last?.kind === 'keys' && last.data.length + ch.data.length <= INPUT_MAX) {
- c.batch[c.batch.length - 1] = { kind: 'keys', data: last.data + ch.data }
- } else if (c.batch.length >= INPUT_CHUNKS_MAX) {
- batchFilled(c)
- return
- } else c.batch.push(ch)
- }
- }
- /** The batch is full: this chunk and the rest of the batch are dropped, in whole chunks — what the
- * splitter still holds belongs to that rest (an open paste is discarded whole, a held prefix is never
- * keys), and later input is dropped until the batch is flushed. The viewer is told. */
- function batchFilled(c: Conn): void {
- c.batchFull = true
- c.splitter.discard('')
- noteDropped(c)
- }
- /** Hand the connection's batch to the host-wide chain. While its previous batch is still there, this
- * one waits (and keeps collecting) and follows it the moment it finishes: one batch per connection
- * in the chain at most, so a slow pane cannot pile up deliveries. */
- function flushBatch(c: Conn): void {
- if (c.ended || stopped || c.inChain) return
- // A held Esc or Alt+[ is a key press by now; a longer marker prefix keeps waiting (control-input.ts).
- appendChunks(c, c.splitter.drain())
- const chunks = c.batch
- const session = c.batchSession
- c.batch = []
- c.batchFull = false
- c.batchBytes = 0
- c.batchSession = null
- if (chunks.length === 0 || session === null) return
- const batch = { chunks, session, gen: c.controlGen }
- c.inChain = true
- // A rejection here would skip every later batch of every controller: caught, by name only.
- inputChain = inputChain
- .then(() => deliverBatch(c, batch))
- .catch((err) => warn(null, 'the input chain failed', err instanceof Error ? err.name : 'not an Error'))
- }
- /** The batch's sender still controls, in the control period it typed in. */
- const stillControls = (c: Conn, b: Batch): boolean =>
- !stopped && !c.ended && c.controlGen === b.gen && controlStateFor(c).state === 'controlling'
- /** Deliver one batch whole, chunk by chunk, re-checking before each that its sender still controls,
- * under the same control period, the session it typed at. A false (or a rejection) stops it. */
- async function deliverBatch(c: Conn, b: Batch): Promise<void> {
- try {
- for (const chunk of b.chunks) {
- // Control ended since it was typed (and the viewer was told its new state): void, silently.
- if (!stillControls(c, b)) return
- // The session it was typed at is gone: what is left did not reach the terminal.
- if (c.sessionId !== b.session) {
- noteDropped(c)
- return
- }
- const ok = await deliverChunk(c, b, chunk)
- if (!ok) {
- noteDropped(c)
- return
- }
- }
- } finally {
- c.inChain = false
- // What it collected meanwhile, when its own timer has already fired.
- if (c.batchTimer === null) safe('an input flush', () => flushBatch(c))
- }
- }
-
- /** One chunk to the pane, answered within INPUT_DELIVERY_TIMEOUT_MS. A rejection, a throw, or no
- * answer in time is false; an answer after that is ignored. `ended` settles it at once (false), so a
- * pane that never answers cannot hold the link's chain beyond its deadline. */
- function deliverChunk(c: Conn, b: Batch, chunk: ControlInputChunk): Promise<boolean> {
- return new Promise<boolean>((resolve) => {
- let settled = false
- const slot: { timer: unknown; settle(ok: boolean): void } = {
- timer: null,
- settle(ok) {
- if (settled) return
- settled = true
- clearTimer(slot.timer)
- slot.timer = null
- if (c.delivery === slot) c.delivery = null
- resolve(ok)
- }
- }
- c.delivery = slot
- slot.timer = deps.setTimeout(() => {
- slot.timer = null
- warn(c, 'a pane delivery timed out', `no answer in ${INPUT_DELIVERY_TIMEOUT_MS} ms`)
- slot.settle(false)
- }, INPUT_DELIVERY_TIMEOUT_MS)
- const failed = (err: unknown): void => {
- // Never the error's text: what failed to type may be in it.
- warn(c, 'delivering input failed', err instanceof Error ? err.name : 'not an Error')
- slot.settle(false)
- }
- // The same check as before this chunk, asked again by PtyManager right before it runs: a chunk
- // still waiting in its per-session chain when its sender stops controlling never lands.
- const isCurrent = (): boolean => stillControls(c, b) && c.sessionId === b.session
- try {
- void Promise.resolve(deps.pty.input(b.session, chunk, isCurrent)).then((ok) => slot.settle(ok === true), failed)
- } catch (err) {
- failed(err)
- }
- })
- }
-
- // --- typing: who is typing --------------------------------------------------------------------------
-
- function forgetTyping(c: Conn): void {
- tracker.drop(c.viewerId)
- scheduleTyping()
- }
- /** Recompute the typing set now, or at most TYPING_EVENT_MIN_MS after the last time. */
- function scheduleTyping(): void {
- if (stopped || typingTimer !== null) return
- const wait = TYPING_EVENT_MIN_MS - (deps.now() - lastTypingAt)
- if (wait <= 0) evaluateTyping()
- else typingTimer = deps.setTimeout(evaluateTyping, wait)
- }
- function evaluateTyping(): void {
- typingTimer = null
- if (stopped) return
- const now = deps.now()
- lastTypingAt = now
- const names = tracker.names(now).slice(0, TYPING_NAMES_MAX)
- const ids = joinedConns()
- .filter((c) => tracker.typing(c.viewerId, now))
- .map((c) => c.viewerId)
- const namesChanged = !sameMembers(names, typingNames)
- const idsChanged = !sameMembers(ids, typingIds)
- typingNames = names
- typingIds = ids
- if (namesChanged) for (const c of joinedConns()) send(c, WATCH_EVENT.typing, { names })
- if (namesChanged || idsChanged) safe('onChange', deps.onChange)
- // While anyone is in the set, look again in a second (that is also what clears it).
- if (names.length > 0 && typingTimer === null && !stopped) typingTimer = deps.setTimeout(evaluateTyping, TYPING_EVENT_MIN_MS)
- }
-
- // --- listeners and viewer sessions ----------------------------------------------------------------
-
- const bridged = (c: Conn): void => {
- if (c.bridged) return
- c.bridged = true
- safe('the scheduler', () => c.ev.onBridged())
- }
-
- function openListener(token: string, ev: { onBridged(): void; onClose(): void }): Listener {
- const c: Conn = {
- viewerId: `v-${bytesToHex(nacl.randomBytes(4))}`,
- ev,
- session: null,
- clientId: null,
- sink: null,
- attachFailed: false,
- bridged: false,
- ended: false,
- confirmTimer: null,
- joinedAt: null,
- name: null,
- lastChatAt: -Infinity,
- controlling: false,
- wrong: 0,
- lastUnlockAt: -Infinity,
- controlStoppedAt: null,
- controlGen: 0,
- input: null,
- splitter: createInputSplitter(),
- inputBucket: createTokenBucket({ ratePerSec: INPUT_RATE, burst: INPUT_BURST, now: deps.now }),
- batch: [],
- batchFull: false,
- batchSession: null,
- batchBytes: 0,
- batchTimer: null,
- inChain: false,
- delivery: null,
- lastDroppedAt: -Infinity,
- controlName: null,
- unlockKeys: null,
- sealedOnly: false,
- sessionId: null,
- altScreen: false,
- joining: false,
- waiting: false,
- joinRefused: false,
- streaming: false,
- filter: createStreamFilter({ midStream: true }),
- bucket: createTokenBucket({ ratePerSec: RATE, burst: BURST, now: deps.now }),
- settled: false,
- followUpOnSettle: false,
- joinKeyframeDone: false,
- kfSeq: 0,
- kfDelivered: 0,
- lastKeyframeAt: -Infinity,
- keyframeTimer: null,
- settleTimer: null,
- stableTimer: null,
- rejoinAttempt: 0,
- rejoinTimer: null,
- historyBusy: false,
- historyNext: null,
- historyLastAt: -Infinity,
- historyTimer: null,
- warned: new Set()
- }
- conns.add(c)
- const attach: PeerAttach = {
- attach: (sink) => {
- c.sink = sink
- try {
- c.clientId = deps.clients.attach(sink)
- } catch (err) {
- // Answered with an id nothing owns; onOpen then closes the session.
- warn(c, 'registering a viewer failed', errorText(err))
- c.attachFailed = true
- c.clientId = -1
- }
- return c.clientId
- },
- detach: (id) => {
- if (id < 0) return
- try {
- deps.clients.detach(id)
- } catch (err) {
- warn(c, 'unregistering a viewer failed', errorText(err))
- }
- },
- // Never reached: the access hook refuses every request first. If one arrives, the policy failed.
- dispatch: async (_id, req): Promise<RpcErr> => {
- policyBreach(c, `request ${req.method}`)
- return { t: 'res', id: req.id, ok: false, error: { code: 'E_ROLE', message: WATCHER_REFUSAL } }
- },
- cast: (_id, method, args) => {
- try {
- onViewerCast(c, method, args)
- } catch (err) {
- warn(c, 'a viewer cast failed', errorText(err))
- }
- }
- }
- try {
- c.session = connectRelayHost({
- url: deps.relayUrl,
- token,
- ourKeys: hostKeys,
- attach,
- transport: deps.transport?.(),
- // Answered from our OWN record, never from anything the peer sent: the handshake key must be
- // the one only a holder of the link secret can derive.
- autoApprove: (peerKeyB64) => {
- bridged(c) // a completed handshake proves the relay leg; the scheduler opens a replacement
- if (peerKeyB64 !== expectedViewerKey) return false
- clearTimer(c.confirmTimer)
- c.confirmTimer = deps.setTimeout(() => {
- c.confirmTimer = null
- if (c.ended || c.joinedAt !== null) return
- c.session?.close()
- ended(c)
- }, CONFIRM_DEADLINE_MS)
- return true
- },
- hooks: {
- access: (_s, kind, method) => watcherAccess(kind, method, record.role),
- wrapSink: (_s, base) =>
- wrapWatcherSink(base, {
- sessionId: () => c.sessionId,
- streaming: () => c.streaming,
- filter: c.filter,
- bucket: c.bucket,
- onOverBudget: () => throttle(c),
- onLifecycle: () => sessionOver(c)
- })
- },
- // A peer with any other key: refused at once, never an approval dialog.
- onPeerPending: (s) => {
- c.session ??= s
- s.deny('denied')
- ended(c)
- },
- onOpen: (s) => {
- c.session ??= s
- clearTimer(c.confirmTimer)
- c.confirmTimer = null
- if (c.ended || stopped || c.attachFailed) {
- s.close()
- ended(c)
- return
- }
- c.joinedAt = deps.now()
- safe('onViewerJoined', () => deps.onViewerJoined(viewers().length))
- safe('onChange', deps.onChange)
- runJoin(c)
- },
- onClose: () => ended(c)
- })
- } catch (err) {
- conns.delete(c)
- throw err
- }
- return {
- bridged: false,
- close: () => {
- c.session?.close()
- ended(c)
- }
- }
- }
-
- function viewers(): LinkViewer[] {
- const out: LinkViewer[] = []
- const now = deps.now()
- for (const c of conns) {
- if (c.joinedAt === null || c.ended) continue
- // The effective state: a flag the host has not yet been told to clear never reads as control.
- const controlling = controlStateFor(c).state === 'controlling'
- out.push({
- viewerId: c.viewerId,
- // While it controls, the name it unlocked under — the one the typing set and the owner's
- // "took control" notice use — never a later chat name beside them.
- name: controlling ? (c.controlName ?? c.name) : c.name,
- joinedAt: c.joinedAt,
- waiting: c.joinRefused && c.sessionId === null,
- controlling,
- typing: tracker.typing(c.viewerId, now)
- })
- }
- return out
- }
- function gone(reason: 'revoked' | 'expired'): void {
- if (stopped) return
- stop(reason)
- safe('onGone', () => deps.onGone(reason))
- }
- function armFullPoll(s: SchedulerStatus): void {
- const full = s.state === 'running' && s.idle === 0 && s.bridged >= MAX_VIEWERS_PER_LINK
- if (!full || stopped) {
- clearTimer(pollTimer)
- pollTimer = null
- return
- }
- if (pollTimer !== null) return
- pollTimer = deps.setTimeout(() => {
- pollTimer = null
- void (async () => {
- let st: 'live' | 'revoked' | 'expired' | 'unknown' = 'unknown'
- try {
- st = await deps.status()
- } catch (err) {
- warn(null, 'the link status poll failed', errorText(err))
- }
- if (stopped) return
- if (st === 'revoked' || st === 'expired') gone(st)
- else if (sched) armFullPoll(sched)
- })()
- }, FULL_STATUS_POLL_MS)
- }
-
- const scheduler = createHostedScheduler(
- {
- mint: async (): Promise<MintResult> => {
- const r = await deps.mint()
- if (!r.ok && r.kind === 'gone') {
- const reason = r.reason
- queueMicrotask(() => gone(reason))
- return { ok: false, kind: 'refused', status: 410 }
- }
- return r
- },
- open: openListener,
- setTimeout: deps.setTimeout,
- clearTimeout: deps.clearTimeout,
- onStatus: (s) => {
- sched = s
- armFullPoll(s)
- safe('onChange', deps.onChange)
- },
- maxBridged: MAX_VIEWERS_PER_LINK
- },
- deps.now
- )
-
- function stop(reason: WatchLinkEndReason): void {
- if (stopped) return
- stopped = true
- // Tell every viewer first: the scheduler's stop closes every listener, bridged ones included, and
- // a closed session can no longer be told anything (F1).
- for (const c of [...conns]) if (c.joinedAt !== null && !c.ended) send(c, WATCH_EVENT.end, { reason })
- // `stopped` before the listeners close, so no ended() re-mints a listener.
- scheduler.stop()
- clearTimer(pollTimer)
- pollTimer = null
- clearTimer(syncTimer)
- syncTimer = null
- for (const c of [...conns]) {
- c.session?.close()
- ended(c)
- }
- clearTimer(typingTimer)
- typingTimer = null
- typingNames = []
- typingIds = []
- safe('onChange', deps.onChange)
- }
-
- return {
- start: () => {
- if (!stopped) scheduler.start()
- },
- stop,
- kick(viewerId) {
- for (const c of conns) {
- if (c.viewerId === viewerId && c.joinedAt !== null && !c.ended) {
- endConn(c, 'kicked')
- return true
- }
- }
- return false
- },
- postSharerChat(text) {
- const clean = sanitizeChatText(text)
- if (!clean || (record.role !== 'commenter' && record.role !== 'controller') || stopped) return null
- const msg: WatchChatMessage = { id: bytesToHex(nacl.randomBytes(8)), name: record.label, text: clean, at: deps.now(), from: 'sharer' }
- publish(msg)
- return msg
- },
- chatHistory: () => [...chat],
- status() {
- if (!sched) return 'reconnecting'
- if (sched.state === 'backend-refused') return 'refused'
- if (sched.idle > 0 || sched.bridged >= MAX_VIEWERS_PER_LINK) return 'live'
- return sched.lastError ? 'reconnecting' : 'live'
- },
- viewers,
- controlChanged() {
- if (stopped || record.role !== 'controller') return
- broadcastControl()
- },
- passwordChanged() {
- if (stopped || record.role !== 'controller') return
- // A new password starts the link-wide count over (the service resets the record's too).
- linkWrong = 0
- controlEpoch++
- for (const c of joinedConns()) {
- if (!c.controlling) continue
- loseControl(c)
- sendControl(c, controlStateFor(c))
- }
- safe('onChange', deps.onChange)
- },
- allowControl() {
- if (stopped || record.role !== 'controller') return
- linkWrong = 0
- broadcastControl()
- }
- }
-}
diff --git a/src/core/watch-link/password.constant-time.test.ts b/src/core/watch-link/password.constant-time.test.ts
deleted file mode 100644
index 90028f721..000000000
--- a/src/core/watch-link/password.constant-time.test.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-// The Control password check compares the derived key with the stored one in CONSTANT TIME. No
-// behavioural test can tell `timingSafeEqual` from `Buffer.equals` (both answer the same), so this
-// file watches the call itself: every check that gets as far as a derived key goes through
-// `timingSafeEqual`, with the derived key and the stored hash, and answers exactly what it answered.
-// Its own file because `vi.mock` is per file and every other test here wants the real module.
-import { describe, expect, it, vi } from 'vitest'
-
-const seen = vi.hoisted(() => ({ calls: [] as Array<{ a: Buffer; b: Buffer; answer: boolean }> }))
-
-vi.mock('node:crypto', async (importOriginal) => {
- const actual = await importOriginal<typeof import('node:crypto')>()
- return {
- ...actual,
- timingSafeEqual: (a: NodeJS.ArrayBufferView, b: NodeJS.ArrayBufferView): boolean => {
- const answer = actual.timingSafeEqual(a, b)
- seen.calls.push({ a: Buffer.from(a as Uint8Array), b: Buffer.from(b as Uint8Array), answer })
- return answer
- }
- }
-})
-
-import { SCRYPT, hashControlPassword, verifyControlPassword } from './password'
-
-describe('control password check: constant time', () => {
- it('compares the derived key with the stored hash through timingSafeEqual, right and wrong alike', async () => {
- const h = await hashControlPassword('correct horse')
- const stored = Buffer.from(h.hash, 'base64')
- for (const [pw, want] of [['correct horse', true], ['correct hors', false]] as const) {
- seen.calls.length = 0
- expect(await verifyControlPassword(pw, h)).toBe(want)
- expect(seen.calls).toHaveLength(1)
- const [c] = seen.calls
- expect(c.a).toHaveLength(SCRYPT.keylen)
- expect(c.b.equals(stored)).toBe(true)
- expect(c.answer).toBe(want)
- }
- })
-
- it('a malformed stored hash is refused before any key is derived or compared', async () => {
- seen.calls.length = 0
- expect(await verifyControlPassword('x'.repeat(8), { salt: '!!', hash: 'short' })).toBe(false)
- expect(seen.calls).toHaveLength(0)
- })
-})
diff --git a/src/core/watch-link/password.test.ts b/src/core/watch-link/password.test.ts
deleted file mode 100644
index cf3b58569..000000000
--- a/src/core/watch-link/password.test.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import { describe, expect, it } from 'vitest'
-import { hashControlPassword, verifyControlPassword, SCRYPT } from './password'
-
-describe('control password hash', () => {
- it('verifies the right password and refuses a wrong one', async () => {
- const h = await hashControlPassword('correct horse')
- expect(Buffer.from(h.salt, 'base64')).toHaveLength(SCRYPT.saltBytes)
- expect(Buffer.from(h.hash, 'base64')).toHaveLength(SCRYPT.keylen)
- expect(await verifyControlPassword('correct horse', h)).toBe(true)
- expect(await verifyControlPassword('correct hors', h)).toBe(false)
- })
- it('salts: the same password hashes differently twice', async () => {
- const [a, b] = await Promise.all([hashControlPassword('x'.repeat(8)), hashControlPassword('x'.repeat(8))])
- expect(a.salt).not.toBe(b.salt)
- expect(a.hash).not.toBe(b.hash)
- })
- it('answers false, never throws, for a malformed stored hash or a non-string', async () => {
- expect(await verifyControlPassword('x'.repeat(8), { salt: '!!', hash: 'short' })).toBe(false)
- expect(await verifyControlPassword(7 as never, await hashControlPassword('x'.repeat(8)))).toBe(false)
- expect(await verifyControlPassword('x'.repeat(8), null as never)).toBe(false)
- expect(await verifyControlPassword('x'.repeat(8), { salt: 7, hash: [] } as never)).toBe(false)
- })
- it('compares the NFC form: a composed and a decomposed spelling of one password are the same password', async () => {
- const composed = 'caf\u00e9-p\u00e4ss' // é and ä as single code points
- const decomposed = 'cafe\u0301-pa\u0308ss' // the same letters as base + combining mark
- expect(composed).not.toBe(decomposed)
- expect(await verifyControlPassword(decomposed, await hashControlPassword(composed))).toBe(true)
- })
-})
diff --git a/src/core/watch-link/password.ts b/src/core/watch-link/password.ts
deleted file mode 100644
index cb92a9baa..000000000
--- a/src/core/watch-link/password.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-// The Control link password: scrypt (N = 2^15, r = 8, p = 1, a 16-byte random salt, a 32-byte key),
-// stored as {salt, hash} only. The plaintext is never kept, logged or echoed: it lives only for the
-// call that hashes or checks it, which is why there is no "show again" (Change password sets a new one).
-//
-// The password is compared in its NFC form: two input paths can produce different Unicode forms of
-// the same letters (composed é, or e plus a combining accent), and both must unlock.
-//
-// `verifyControlPassword` answers false, never throws: a malformed stored hash (a hand-edited file) or
-// a non-string password (a viewer's cast is untrusted input) is a refused unlock, not an error. The
-// comparison of the derived keys is constant-time.
-import { randomBytes, scrypt, timingSafeEqual } from 'node:crypto'
-
-export interface ControlPasswordHash {
- /** base64 */
- salt: string
- /** base64 */
- hash: string
-}
-// maxmem: scrypt needs 128 * N * r bytes = 32 MiB here, which is exactly Node's default ceiling and
-// over it once its own bookkeeping is counted, so the ceiling is raised.
-export const SCRYPT = { N: 32768, r: 8, p: 1, keylen: 32, saltBytes: 16, maxmem: 64 * 1024 * 1024 } as const
-
-function derive(pw: string, salt: Buffer): Promise<Buffer> {
- return new Promise((resolve, reject) =>
- scrypt(
- pw.normalize('NFC'),
- salt,
- SCRYPT.keylen,
- { N: SCRYPT.N, r: SCRYPT.r, p: SCRYPT.p, maxmem: SCRYPT.maxmem },
- (err, key) => (err ? reject(err) : resolve(key))
- )
- )
-}
-
-export async function hashControlPassword(pw: string): Promise<ControlPasswordHash> {
- const salt = randomBytes(SCRYPT.saltBytes)
- return { salt: salt.toString('base64'), hash: (await derive(pw, salt)).toString('base64') }
-}
-
-export async function verifyControlPassword(pw: string, h: ControlPasswordHash): Promise<boolean> {
- try {
- if (typeof pw !== 'string') return false
- const salt = Buffer.from(h.salt, 'base64')
- const want = Buffer.from(h.hash, 'base64')
- if (salt.length !== SCRYPT.saltBytes || want.length !== SCRYPT.keylen) return false
- return timingSafeEqual(await derive(pw, salt), want)
- } catch {
- return false
- }
-}
diff --git a/src/core/watch-link/pty-seam.test.ts b/src/core/watch-link/pty-seam.test.ts
deleted file mode 100644
index fa8deacc2..000000000
--- a/src/core/watch-link/pty-seam.test.ts
+++ /dev/null
@@ -1,242 +0,0 @@
-import { describe, it, expect, vi } from 'vitest'
-import { createWatchPty, watchRemoteFor, watchRemoteRecords, type WatchPtyManager, type WatchRemoteRecords } from './pty-seam'
-import { sshAttachmentId } from '../../shared/ssh'
-import type { PtyCreateResult } from '../../shared/types'
-
-function fakeManager(over: Partial<Record<keyof WatchPtyManager, unknown>> = {}) {
- const m = {
- joinAsWatcher: vi.fn(async (_c: number, _o: object): Promise<PtyCreateResult> => ({ sessionId: 's1', tmuxClient: true }) as PtyCreateResult),
- sessionSize: vi.fn((_s: string): { cols: number; rows: number } | null => ({ cols: 120, rows: 40 })),
- kill: vi.fn(),
- captureVisible: vi.fn(async () => ({ screen: 'x', cursor: { x: 1, y: 2 } })),
- syncWatcherClientSize: vi.fn(async () => true),
- hasSession: vi.fn(() => true),
- watcherInputRoute: vi.fn((_s: string): string => 'tmux'),
- controlInput: vi.fn(async (_s: string, _c: unknown) => true)
- }
- return Object.assign(m, over) as typeof m
-}
-
-describe('createWatchPty — the WatchPty seam both shells wire (R39)', () => {
- it('joins with the host ids only (never a size), and reports the JOINED session size and tmux-ness', async () => {
- const m = fakeManager()
- const pty = createWatchPty(m as unknown as WatchPtyManager)
- expect(await pty.join(7, 'n1', 'v-1')).toEqual({ sessionId: 's1', cols: 120, rows: 40, altScreen: true, input: 'tmux' })
- expect(m.joinAsWatcher).toHaveBeenCalledWith(7, { persistKey: 'n1', viewerId: 'v-1' })
- expect(m.sessionSize).toHaveBeenCalledWith('s1')
- expect(m.kill).not.toHaveBeenCalled()
- })
-
- it('altScreen is true only for a tmux client', async () => {
- const m = fakeManager({ joinAsWatcher: vi.fn(async () => ({ sessionId: 's1' })) })
- expect(await createWatchPty(m as unknown as WatchPtyManager).join(7, 'n1', 'v-1')).toMatchObject({ altScreen: false })
- })
-
- it('no session: null, nothing to leave', async () => {
- const m = fakeManager({ joinAsWatcher: vi.fn(async () => ({ sessionId: '', unavailable: 'join-only' })) })
- expect(await createWatchPty(m as unknown as WatchPtyManager).join(7, 'n1', 'v-1')).toBeNull()
- expect(m.kill).not.toHaveBeenCalled()
- })
-
- it('a joined session whose size is unknown is REFUSED — never an 80x24 guess — and left, not leaked', async () => {
- const m = fakeManager({ sessionSize: vi.fn(() => null) })
- expect(await createWatchPty(m as unknown as WatchPtyManager).join(7, 'n1', 'v-1')).toBeNull()
- expect(m.kill).toHaveBeenCalledWith(7, 's1', 'v-1')
- })
-
- it('an unavailable answer that still names a session is refused and left', async () => {
- const m = fakeManager({ joinAsWatcher: vi.fn(async () => ({ sessionId: 's1', unavailable: 'ssh' })) })
- expect(await createWatchPty(m as unknown as WatchPtyManager).join(7, 'n1', 'v-1')).toBeNull()
- expect(m.kill).toHaveBeenCalledWith(7, 's1', 'v-1')
- expect(m.sessionSize).not.toHaveBeenCalled()
- })
-
- it("a remote node's fields come from the shell's own records, requireRemote included", async () => {
- const m = fakeManager()
- const sshRemote = { conn: { host: 'h' } as never, controlPath: '/cp', remoteCwd: '~' }
- const pty = createWatchPty(m as unknown as WatchPtyManager, (nodeId) =>
- nodeId === 'r1' ? { requireRemote: true, sshRemote } : nodeId === 'r2' ? { requireRemote: true } : {}
- )
- await pty.join(7, 'r1', 'v-1')
- await pty.join(7, 'r2', 'v-2')
- expect(m.joinAsWatcher.mock.calls).toEqual([
- [7, { persistKey: 'r1', viewerId: 'v-1', sshRemote, requireRemote: true }],
- [7, { persistKey: 'r2', viewerId: 'v-2', requireRemote: true }]
- ])
- })
-
- it('leave, capture, size sync and liveness go to the matching PtyManager member', async () => {
- const m = fakeManager()
- const pty = createWatchPty(m as unknown as WatchPtyManager)
- pty.leave(7, 's1', 'v-1')
- expect(m.kill).toHaveBeenCalledWith(7, 's1', 'v-1')
- expect(await pty.captureVisible('s1')).toEqual({ screen: 'x', cursor: { x: 1, y: 2 } })
- expect(await pty.syncSize('s1')).toBe(true)
- expect(m.syncWatcherClientSize).toHaveBeenCalledWith('s1')
- expect(pty.alive('s1')).toBe(true)
- m.hasSession.mockReturnValue(false)
- expect(pty.alive('s1')).toBe(false)
- })
-
- // Control: the join reports how a controller's input reaches the JOINED session's pane (the route
- // PtyManager decides — Zellij and an unknown session answer `none`), and input goes to the pane.
- it("a join carries the joined session's input route, read from PtyManager", async () => {
- for (const route of ['tmux', 'ssh', 'write', 'none']) {
- const m = fakeManager({ watcherInputRoute: vi.fn(() => route) })
- expect(await createWatchPty(m as unknown as WatchPtyManager).join(7, 'n1', 'v-1')).toMatchObject({ input: route })
- expect(m.watcherInputRoute).toHaveBeenCalledWith('s1')
- }
- // A refused join never asks.
- const none = fakeManager({ sessionSize: vi.fn(() => null) })
- await createWatchPty(none as unknown as WatchPtyManager).join(7, 'n1', 'v-1')
- expect(none.watcherInputRoute).not.toHaveBeenCalled()
- })
-
- it("input goes to PtyManager.controlInput for that session, and its answer comes back as it is", async () => {
- const m = fakeManager()
- const pty = createWatchPty(m as unknown as WatchPtyManager)
- expect(await pty.input('s1', { kind: 'keys', data: 'ls\r' })).toBe(true)
- expect(m.controlInput.mock.calls[0].slice(0, 2)).toEqual(['s1', { kind: 'keys', data: 'ls\r' }])
- m.controlInput.mockResolvedValueOnce(false)
- expect(await pty.input('s1', { kind: 'paste', text: 'x' })).toBe(false)
- expect(m.controlInput.mock.calls[1].slice(0, 2)).toEqual(['s1', { kind: 'paste', text: 'x' }])
- })
-
- it("the link host's isCurrent predicate reaches controlInput unchanged (asked right before the step runs)", async () => {
- const m = fakeManager()
- const pty = createWatchPty(m as unknown as WatchPtyManager)
- const isCurrent = (): boolean => false
- await pty.input('s1', { kind: 'keys', data: 'a' }, isCurrent)
- expect(m.controlInput).toHaveBeenCalledWith('s1', { kind: 'keys', data: 'a' }, isCurrent)
- })
-})
-
-// Final review, Minor 4: a watcher join must never reach the LOCAL socket for a node whose session
-// lives in a HOST's tmux — an SSH project's node, and also a remote-tmux node in a LOCAL project
-// (`ssh` + `sshRemoteTmux` on the node), whose master is the project's host attachment.
-describe('watchRemoteFor — where a watcher join goes, from the shell\'s own records', () => {
- const server = { host: 'box', user: 'alice' }
- const other = { host: 'other', user: 'bob', port: 2222 }
- const ref = (conn: object, controlPath: string, remoteCwd?: string) => ({ conn: conn as never, controlPath, remoteCwd })
- function records(o: {
- sshProject?: string
- copies?: { projectId: string; projectServer?: unknown; ssh?: unknown; sshRemoteTmux?: unknown }[]
- refs?: Record<string, ReturnType<typeof ref>>
- }): WatchRemoteRecords & { asked: string[] } {
- const asked: string[] = []
- return {
- asked,
- sshProjectIdForNode: () => o.sshProject,
- nodeCopies: () => o.copies ?? [],
- refFor: (id) => {
- asked.push(id)
- return o.refs?.[id]
- }
- }
- }
-
- it('an SSH project\'s node: requireRemote, over that project\'s master when it is up', () => {
- expect(watchRemoteFor('n1', records({ sshProject: 'p-ssh', refs: { 'p-ssh': ref(server, '/cm/1', '/srv') } }))).toEqual({
- requireRemote: true,
- sshRemote: { conn: server, controlPath: '/cm/1', remoteCwd: '/srv' }
- })
- expect(watchRemoteFor('n1', records({ sshProject: 'p-ssh' }))).toEqual({ requireRemote: true })
- })
-
- it('a remote-tmux node in a LOCAL project: requireRemote, over its host attachment (`sshAttachmentId`)', () => {
- const attachment = sshAttachmentId('p-local', other as never)
- const r = records({
- copies: [{ projectId: 'p-local', ssh: other, sshRemoteTmux: true }],
- refs: { [attachment]: ref(other, '/cm/2') }
- })
- expect(watchRemoteFor('n1', r)).toEqual({
- requireRemote: true,
- sshRemote: { conn: other, controlPath: '/cm/2', remoteCwd: '~' }
- })
- expect(r.asked).toEqual([attachment])
- })
-
- it('an unheld remote-tmux node whose master is down still never joins the LOCAL socket', () => {
- expect(watchRemoteFor('n1', records({ copies: [{ projectId: 'p-local', ssh: other, sshRemoteTmux: true }] }))).toEqual({
- requireRemote: true
- })
- // `sshRemoteTmux` alone (a binding that lost its host) is remote all the same — the renderer's rule.
- expect(watchRemoteFor('n1', records({ copies: [{ projectId: 'p-local', ssh: { user: 'x' }, sshRemoteTmux: true }] }))).toEqual({
- requireRemote: true
- })
- })
-
- it("a remote-tmux node on its own project's host goes over the PROJECT's master (`sshConnectionIdForProject`)", () => {
- const r = records({
- copies: [{ projectId: 'p-x', projectServer: server, ssh: { host: 'box', user: 'someone-else' }, sshRemoteTmux: true }],
- refs: { 'p-x': ref(server, '/cm/3', '/home/alice') }
- })
- expect(watchRemoteFor('n1', r)).toEqual({
- requireRemote: true,
- sshRemote: { conn: server, controlPath: '/cm/3', remoteCwd: '/home/alice' }
- })
- })
-
- it('a local node, and a standalone ssh terminal node (its ssh runs in LOCAL tmux), are local', () => {
- expect(watchRemoteFor('n1', records({}))).toEqual({})
- expect(watchRemoteFor('n1', records({ copies: [{ projectId: 'p-local' }] }))).toEqual({})
- expect(watchRemoteFor('n1', records({ copies: [{ projectId: 'p-local', ssh: other }] }))).toEqual({})
- expect(watchRemoteFor('n1', records({ copies: [{ projectId: 'p-local', ssh: other, sshRemoteTmux: 'true' }] }))).toEqual({})
- })
-
- it('any copy that says remote-tmux makes the join remote (fail closed), and the first copy with a live master serves it', () => {
- const attachment = sshAttachmentId('p-b', other as never)
- const r = records({
- copies: [
- { projectId: 'p-a' },
- { projectId: 'p-b', ssh: other, sshRemoteTmux: true }
- ],
- refs: { [attachment]: ref(other, '/cm/4') }
- })
- expect(watchRemoteFor('n1', r)).toMatchObject({ requireRemote: true, sshRemote: { controlPath: '/cm/4' } })
- })
-
- it("both shells read the records the same way: the workspace store's own copies, each with its project's server", () => {
- const canvases = [
- { id: 'p-a', nodes: [{ id: 'n1' }] },
- { id: 'p-b', nodes: [{ id: 'n2' }, { id: 'n1', ssh: other, sshRemoteTmux: true }] }
- ]
- let scans = 0
- const store = {
- sshProjectIdForNode: (id: string) => (id === 'n-ssh' ? 'p-ssh' : undefined),
- projectIdsForNode: (id: string) => (id === 'n1' ? ['p-a', 'p-b'] : []),
- persistedCanvases: () => {
- scans++
- return canvases as never
- },
- projectTargetInfo: (id: string) => (id === 'p-b' ? { ssh: { server, remoteCwd: '~' }, name: 'B' } : { name: id })
- }
- const asked: string[] = []
- const recs = watchRemoteRecords(store, (id) => {
- asked.push(id)
- return undefined
- })
- expect(recs.sshProjectIdForNode('n-ssh')).toBe('p-ssh')
- expect(recs.nodeCopies('n1')).toEqual([
- { projectId: 'p-a', projectServer: undefined, ssh: undefined, sshRemoteTmux: undefined },
- { projectId: 'p-b', projectServer: server, ssh: other, sshRemoteTmux: true }
- ])
- // A node no project holds costs no scan of every project file.
- scans = 0
- expect(recs.nodeCopies('nowhere')).toEqual([])
- expect(scans).toBe(0)
- expect(watchRemoteFor('n1', recs)).toEqual({ requireRemote: true })
- expect(asked).toEqual([sshAttachmentId('p-b', other as never)])
- })
-
- it('records that throw read as remote-unknown: requireRemote, never the local socket', () => {
- const bad: WatchRemoteRecords = {
- sshProjectIdForNode: () => {
- throw new Error('index not loaded')
- },
- nodeCopies: () => [],
- refFor: () => undefined
- }
- expect(watchRemoteFor('n1', bad)).toEqual({ requireRemote: true })
- })
-})
diff --git a/src/core/watch-link/pty-seam.ts b/src/core/watch-link/pty-seam.ts
deleted file mode 100644
index be298b86a..000000000
--- a/src/core/watch-link/pty-seam.ts
+++ /dev/null
@@ -1,155 +0,0 @@
-// The live link's pty seam (link-host.ts `WatchPty`) over PtyManager — ONE definition both shells
-// wire, because the join's rules are easy to get subtly wrong and a second copy is how one shell
-// ends up a rule behind the other:
-// - the join passes only ids the host chose: the node id, the viewer id the link host minted, and
-// remote fields from the shell's own records (`remoteFor`) — never a size (R39): a watcher's own
-// tmux client is spawned at the window size PtyManager reads itself, or not at all (R19/R20);
-// - the size the viewer is told is the JOINED session's current size (`sessionSize`, R25), and a
-// session whose size is unknown is REFUSED rather than given a guessed 80x24 (R37/R39);
-// - a refusal that had already attached leaves what it attached (the link host only knows a session
-// id this seam answered, so it could not leave it);
-// - `alive` is PtyManager's explicit `hasSession` (R38), `syncSize` its per-session serialized sync (R24);
-// - a join reports how a controller's input reaches the JOINED session's PANE
-// (`watcherInputRoute`: `none` for Zellij or a session it no longer holds, which refuses control),
-// and `input` is `controlInput` — the pane, never a tmux client's key table — with the link host's
-// `isCurrent` predicate, asked right before the step runs.
-//
-// WHERE a node's session lives is `watchRemoteFor`, also ONE definition: an SSH project's node and a
-// remote-tmux node in a LOCAL project (`ssh` + `sshRemoteTmux` on the node, served by the project's host
-// attachment) are both watched on their HOST, over the master this machine already holds for them, or
-// not at all (`requireRemote`): an unheld one must never join a same-named session on the LOCAL socket.
-import type { PtyCreateOptions } from '../../shared/types'
-import { sshConnectionIdForProject, type SshConnection } from '../../shared/ssh'
-import type { PtyManager } from '../pty-manager'
-import type { WorkspaceStore } from '../workspace-store'
-import type { WatchPty } from './link-host'
-
-export type WatchPtyManager = Pick<
- PtyManager,
- | 'joinAsWatcher'
- | 'sessionSize'
- | 'kill'
- | 'captureVisible'
- | 'syncWatcherClientSize'
- | 'hasSession'
- | 'controlInput'
- | 'watcherInputRoute'
->
-
-/** Where a node's session lives, from the SHELL's own records. `requireRemote` for every node of an
- * SSH project (a downed master must never let the local tmux attach a same-named local orphan). */
-export interface WatchRemote {
- sshRemote?: PtyCreateOptions['sshRemote']
- requireRemote?: boolean
-}
-
-/** The shell's own records `watchRemoteFor` reads. Nothing here comes from a viewer. */
-export interface WatchRemoteRecords {
- /** The SSH project that holds the node (`WorkspaceStore.sshProjectIdForNode`). */
- sshProjectIdForNode(nodeId: string): string | undefined
- /** Every persisted copy of the node: the machine-local id of the project holding it, that project's
- * own SSH server (absent for a local project), and the node's binding fields as stored. */
- nodeCopies(nodeId: string): readonly { projectId: string; projectServer?: unknown; ssh?: unknown; sshRemoteTmux?: unknown }[]
- /** The live master of a connection id (`SshProjectManager.refForProject`); undefined when it is down. */
- refFor(connectionId: string): { conn: SshConnection; controlPath: string; remoteCwd?: string } | undefined
-}
-
-/**
- * The records over the workspace store — the same in both shells; only the masters differ (the desktop's
- * SSH-project manager; the Server Edition has none). The copies come from every project holding the
- * node (`projectIdsForNode`, memoized, answers "none" without a scan of every project file), each with
- * that project's own SSH server.
- */
-export function watchRemoteRecords(
- store: Pick<WorkspaceStore, 'sshProjectIdForNode' | 'projectIdsForNode' | 'persistedCanvases' | 'projectTargetInfo'>,
- refFor: WatchRemoteRecords['refFor']
-): WatchRemoteRecords {
- return {
- sshProjectIdForNode: (id) => store.sshProjectIdForNode(id),
- nodeCopies: (id) => {
- if (store.projectIdsForNode(id).length === 0) return []
- return store.persistedCanvases().flatMap((c) => {
- const n = c.nodes.find((x) => x.id === id)
- if (!n) return []
- return [{ projectId: c.id, projectServer: store.projectTargetInfo(c.id)?.ssh?.server, ssh: n.ssh, sshRemoteTmux: n.sshRemoteTmux }]
- })
- },
- refFor
- }
-}
-
-/** A binding read from hand-editable, git-shared data: an object with a non-empty string host. */
-function sshConnOf(v: unknown): SshConnection | null {
- if (typeof v !== 'object' || v === null) return null
- const host = (v as { host?: unknown }).host
- return typeof host === 'string' && host ? (v as SshConnection) : null
-}
-
-/**
- * Where a watcher join for `nodeId` goes, from the shell's own records:
- * - a node of an SSH project: that project's master (`requireRemote` always);
- * - a node with `sshRemoteTmux` in any persisted copy — a remote-tmux node in a LOCAL project — its
- * connection's master, chosen the way the canvas chooses it (`sshConnectionIdForProject`: the
- * project's own when the hosts match, else the project × endpoint attachment), `requireRemote`
- * whether or not that master is up (the renderer's own rule for the node's spawn);
- * - anything else (a local node, a standalone ssh terminal whose `ssh` runs in LOCAL tmux): local.
- * Records that throw answer `requireRemote` with no master: a join that cannot be placed never reaches
- * the local socket. It joins only a REMOTE session this process already holds; a held LOCAL one is
- * refused (`held-elsewhere`, see PtyManager `join`), and otherwise it waits.
- */
-export function watchRemoteFor(nodeId: string, r: WatchRemoteRecords): WatchRemote {
- try {
- const sshProject = r.sshProjectIdForNode(nodeId)
- if (sshProject) return remoteOver(r.refFor(sshProject))
- let remote = false
- for (const copy of r.nodeCopies(nodeId)) {
- if (copy.sshRemoteTmux !== true) continue
- remote = true
- const conn = sshConnOf(copy.ssh)
- if (!conn) continue
- const ref = r.refFor(sshConnectionIdForProject(copy.projectId, conn, sshConnOf(copy.projectServer) ?? undefined))
- if (ref) return remoteOver(ref)
- }
- return remote ? { requireRemote: true } : {}
- } catch {
- return { requireRemote: true }
- }
-}
-function remoteOver(ref: ReturnType<WatchRemoteRecords['refFor']>): WatchRemote {
- return {
- requireRemote: true,
- ...(ref ? { sshRemote: { conn: ref.conn, controlPath: ref.controlPath, remoteCwd: ref.remoteCwd ?? '~' } } : {})
- }
-}
-
-export function createWatchPty(pty: WatchPtyManager, remoteFor: (nodeId: string) => WatchRemote = () => ({})): WatchPty {
- return {
- async join(clientId, nodeId, viewerId) {
- const remote = remoteFor(nodeId)
- const res = await pty.joinAsWatcher(clientId, {
- persistKey: nodeId,
- viewerId,
- ...(remote.sshRemote ? { sshRemote: remote.sshRemote } : {}),
- ...(remote.requireRemote ? { requireRemote: true } : {})
- })
- if (!res.sessionId) return null
- const size = res.unavailable ? null : pty.sessionSize(res.sessionId)
- if (!size) {
- pty.kill(clientId, res.sessionId, viewerId)
- return null
- }
- return {
- sessionId: res.sessionId,
- cols: size.cols,
- rows: size.rows,
- altScreen: res.tmuxClient === true,
- input: pty.watcherInputRoute(res.sessionId)
- }
- },
- leave: (clientId, sessionId, viewerId) => pty.kill(clientId, sessionId, viewerId),
- captureVisible: (sessionId) => pty.captureVisible(sessionId),
- syncSize: (sessionId) => pty.syncWatcherClientSize(sessionId),
- alive: (sessionId) => pty.hasSession(sessionId),
- input: (sessionId, chunk, isCurrent) => pty.controlInput(sessionId, chunk, isCurrent)
- }
-}
diff --git a/src/core/watch-link/service.test.ts b/src/core/watch-link/service.test.ts
deleted file mode 100644
index 0cff9787d..000000000
--- a/src/core/watch-link/service.test.ts
+++ /dev/null
@@ -1,1864 +0,0 @@
-import { describe, it, expect, vi, afterEach } from 'vitest'
-import { join } from 'node:path'
-import { readFileSync } from 'node:fs'
-import { testTmpDir } from '../test-tmp'
-import {
- createFifoGate,
- createWatchLinkService,
- registerWatchLinkIpc,
- sendToOwners,
- shutdownWithin,
- workspaceNodeState,
- type WatchLinkNodeState,
- type WatchLinkService,
- type WatchLinkServiceDeps
-} from './service'
-import { WatchLinkStore, WatchLinkStoreUnreadable, type WatchLinkRecord, type SaveOutcome } from './store'
-import type { WatchLinkApi as ApiClient } from './api'
-import { WRONG_PER_LINK, type LinkHost, type LinkHostDeps, type LinkRuntimeStatus, type LinkViewer, type WatchPty } from './link-host'
-import type { WatchChatMessage } from '../../shared/watch-link/protocol'
-import type { ControlSupport, WatchLinkNotice, WatchLinkView } from '../../shared/watch-link-types'
-import { hashControlPassword, verifyControlPassword, type ControlPasswordHash } from './password'
-import { IPC } from '../../shared/ipc'
-import { fakePlatform } from '../platform-fake'
-
-const services: WatchLinkService[] = []
-afterEach(async () => {
- for (const s of services.splice(0)) await s.shutdown()
- vi.useRealTimers()
-})
-
-const HOUR = 3600_000
-
-function fakeApi(over: Partial<ApiClient> = {}) {
- const calls: string[] = []
- const ttls: number[] = []
- let n = 0
- const api: ApiClient = {
- create: async (_ent, _hash, ttl) => {
- calls.push('create')
- ttls.push(ttl)
- n++
- // Like the server: Unlimited (0) answers no end time.
- return { ok: true, linkId: `Link${String(n).padStart(18, '0')}`, expiresAt: ttl === 0 ? null : Date.now() + HOUR }
- },
- hostToken: async (id) => {
- calls.push(`hostToken ${id}`)
- return { ok: true, pairingToken: 't', hostId: '', ttlMs: 120_000 }
- },
- status: async () => 'live',
- revoke: async (id) => {
- calls.push(`revoke ${id}`)
- return true
- },
- revokeAll: async () => {
- calls.push('revokeAll')
- return true
- },
- ...over
- }
- return { api, calls, ttls }
-}
-
-interface FakeHost {
- record: WatchLinkRecord
- deps: LinkHostDeps
- stopped: string[]
- /** controlChanged / passwordChanged / allowControl, in call order. */
- hooks: string[]
- starts: number
- status: LinkRuntimeStatus
- viewers: LinkViewer[]
- chat: WatchChatMessage[]
-}
-function fakeHosts() {
- const made: FakeHost[] = []
- const createHost = (record: WatchLinkRecord, deps: LinkHostDeps): LinkHost => {
- const h: FakeHost = { record, deps, stopped: [], hooks: [], starts: 0, status: 'live', viewers: [], chat: [] }
- made.push(h)
- return {
- start: () => {
- h.starts++
- },
- stop: (r) => {
- h.stopped.push(r)
- },
- kick: (id) => h.viewers.some((v) => v.viewerId === id),
- postSharerChat: (text) => ({ id: 'm1', name: record.label, text, at: 1, from: 'sharer' }),
- chatHistory: () => h.chat,
- status: () => h.status,
- viewers: () => h.viewers,
- controlChanged: () => {
- h.hooks.push('controlChanged')
- },
- passwordChanged: () => {
- h.hooks.push('passwordChanged')
- },
- allowControl: () => {
- h.hooks.push('allowControl')
- }
- }
- }
- return { made, createHost }
-}
-
-const fakePty = (over: Partial<WatchPty> = {}): WatchPty => ({
- join: async () => ({ sessionId: 's1', cols: 80, rows: 24, altScreen: true, input: 'tmux' }),
- leave: () => {},
- captureVisible: async () => ({ screen: '', cursor: null }),
- syncSize: async () => true,
- alive: () => true,
- input: async () => true,
- ...over
-})
-
-type Store = WatchLinkServiceDeps['store']
-
-interface Opts {
- api?: Partial<ApiClient>
- nodes?: Map<string, WatchLinkNodeState>
- entitlement?: string | null
- relayAllowed?: boolean
- store?: Store
- pty?: WatchPty
- workspaceReady?: () => Promise<unknown>
- unsupported?: boolean
- persistTimeoutMs?: number
- workspaceWaitMs?: number
- now?: () => number
- controlSupport?: (nodeId: string) => ControlSupport
- hashPassword?: (pw: string) => Promise<ControlPasswordHash>
- verifyPassword?: (pw: string, h: ControlPasswordHash) => Promise<boolean>
- /** The REAL link host (and a relay transport no test reaches) instead of the fake. */
- realHost?: boolean
- history?: WatchLinkServiceDeps['history']
- historySupported?: WatchLinkServiceDeps['historySupported']
-}
-function service(o: Opts = {}) {
- const file = join(testTmpDir('wls-'), 'watch-links.json')
- const { api, calls, ttls } = fakeApi(o.api)
- const hosts = fakeHosts()
- const nodes = o.nodes ?? new Map<string, WatchLinkNodeState>([['n1', 'present'], ['n2', 'present']])
- const emitted: [string, unknown[]][] = []
- const store = o.store ?? new WatchLinkStore({ file })
- const ent = { value: o.entitlement === undefined ? 'ent' : o.entitlement }
- const s = createWatchLinkService({
- api,
- relayUrl: 'wss://r',
- store,
- entitlement: () => ent.value,
- relayAllowed: () => o.relayAllowed ?? true,
- nodeState: (id) => nodes.get(id) ?? 'absent',
- ...(o.workspaceReady ? { workspaceReady: o.workspaceReady } : {}),
- clients: { attach: () => 1, detach: () => {} },
- pty: o.pty ?? fakePty(),
- emit: (ch, ...a) => emitted.push([ch, a]),
- ...(o.realHost
- ? {
- transport: () => {
- throw new Error('no relay in this test')
- }
- }
- : { createHost: hosts.createHost }),
- ...(o.controlSupport ? { controlSupport: o.controlSupport } : {}),
- ...(o.hashPassword ? { hashPassword: o.hashPassword } : {}),
- ...(o.verifyPassword ? { verifyPassword: o.verifyPassword } : {}),
- ...(o.unsupported ? { unsupported: true } : {}),
- ...(o.history ? { history: o.history } : {}),
- ...(o.historySupported ? { historySupported: o.historySupported } : {}),
- ...(o.persistTimeoutMs ? { persistTimeoutMs: o.persistTimeoutMs } : {}),
- ...(o.workspaceWaitMs ? { workspaceWaitMs: o.workspaceWaitMs } : {}),
- ...(o.now ? { now: o.now } : {})
- })
- services.push(s)
- const notices = () => emitted.filter(([ch]) => ch === IPC.watchLinkNotice).map(([, a]) => a[0] as WatchLinkNotice)
- const states = () => emitted.filter(([ch]) => ch === IPC.watchLinkState).map(([, a]) => a[0] as WatchLinkView[])
- return { s, calls, ttls, api, hosts, nodes, emitted, notices, states, store, file, ent }
-}
-const req = (over: Record<string, unknown> = {}) => ({ nodeId: 'n1', role: 'viewer', ttlSeconds: 3600, label: 'Ada', title: 'build', ...over })
-const record = (over: Partial<WatchLinkRecord> = {}): WatchLinkRecord => ({
- linkId: 'Good000000000000000000', nodeId: 'n1', role: 'viewer', label: 'A', title: 't', createdAt: 0,
- expiresAt: Date.now() + 60_000, secret: new Uint8Array(32).fill(3), ...over
-})
-const deferred = <T>() => {
- let resolve!: (v: T) => void
- let reject!: (e: unknown) => void
- const promise = new Promise<T>((res, rej) => {
- resolve = res
- reject = rej
- })
- return { promise, resolve, reject }
-}
-const flush = async (n = 20) => {
- for (let i = 0; i < n; i++) await Promise.resolve()
-}
-/** A store that records every save and answers the outcomes a test chose. */
-function fakeStore(o: { load?: () => Promise<WatchLinkRecord[]>; save?: (r: readonly WatchLinkRecord[]) => Promise<SaveOutcome>; opaque?: number } = {}) {
- const saves: WatchLinkRecord[][] = []
- let discarded = 0
- const store: Store = {
- load: o.load ?? (async () => []),
- save: (r) => {
- saves.push([...r])
- return o.save ? o.save(r) : Promise.resolve('saved')
- },
- discardOpaque: () => {
- discarded++
- },
- opaqueCount: () => o.opaque ?? 0
- }
- return { store, saves, discarded: () => discarded }
-}
-
-describe('createWatchLinkService — create', () => {
- it('creates a link, persists it, starts a host and answers the URL', async () => {
- const t = service()
- const r = await t.s.create(req())
- expect(r.ok).toBe(true)
- if (!r.ok) return
- expect(r.link.url).toMatch(/^https:\/\/nodeterm\.dev\/s\/Link0+1#1\.[A-Za-z0-9_-]{43}$/)
- expect(r.link).toMatchObject({ nodeId: 'n1', role: 'viewer', label: 'Ada', title: 'build', status: 'live', viewers: [] })
- expect(t.hosts.made).toHaveLength(1)
- expect(t.hosts.made[0].starts).toBe(1)
- expect(await t.store.load()).toHaveLength(1)
- expect(t.states().at(-1)?.map((l) => l.linkId)).toEqual([r.link.linkId])
- expect(t.notices()).toEqual([]) // persisted: no not-persistent notice
- })
-
- it('refuses bad input, a node no project holds, no relay, no entitlement and a sixth link — before any request', async () => {
- const t = service({ nodes: new Map([['n1', 'present'], ['maybe', 'unknown'], ['gone', 'absent']]) })
- const bad = { ok: false, error: 'bad-request' }
- expect(await t.s.create(req({ ttlSeconds: 7200 }))).toEqual(bad)
- expect(await t.s.create(req({ ttlSeconds: '3600' }))).toEqual(bad)
- expect(await t.s.create(req({ role: 'editor' }))).toEqual(bad)
- expect(await t.s.create(req({ nodeId: '../x' }))).toEqual(bad)
- expect(await t.s.create(req({ nodeId: 12 }))).toEqual(bad)
- expect(await t.s.create(req({ label: '' }))).toEqual(bad)
- expect(await t.s.create(req({ label: '\u0007\u202e ' }))).toEqual(bad)
- expect(await t.s.create(req({ label: 5 }))).toEqual(bad)
- expect(await t.s.create(null)).toEqual(bad)
- expect(await t.s.create('x')).toEqual(bad)
- // Create requires PRESENT: "unknown" is not "there" (R40).
- expect(await t.s.create(req({ nodeId: 'gone' }))).toEqual({ ok: false, error: 'node-missing' })
- expect(await t.s.create(req({ nodeId: 'maybe' }))).toEqual({ ok: false, error: 'node-missing' })
- expect(await service({ relayAllowed: false }).s.create(req())).toEqual({ ok: false, error: 'relay-unavailable' })
- expect(await service({ entitlement: null }).s.create(req())).toEqual({ ok: false, error: 'not-entitled' })
- for (let i = 0; i < 5; i++) expect((await t.s.create(req())).ok).toBe(true)
- expect(await t.s.create(req())).toEqual({ ok: false, error: 'limit-machine' })
- expect(t.calls.filter((c) => c === 'create')).toHaveLength(5)
- })
-
- it('cleans the label and title: controls and bidi overrides stripped, capped in UTF-16 units without splitting a pair', async () => {
- const t = service()
- const r = await t.s.create(req({ label: ' A\u202eda\u0000\u200f ', title: `x\u2066${'😀'.repeat(50)}` }))
- if (!r.ok) throw new Error(r.error)
- expect(r.link.label).toBe('Ada')
- expect(r.link.title).toBe(`x${'😀'.repeat(39)}`) // 1 + 78 units; one more pair would be 81 > 80
- expect(r.link.title.length).toBeLessThanOrEqual(80)
- const blank = await t.s.create(req({ title: '\u0001' }))
- expect(blank.ok && blank.link.title).toBe('Terminal')
- // What was written reloads (the store refuses a label over 40 / a title over 80 units).
- expect(await t.store.load()).toHaveLength(2)
- })
-
- it('passes API refusals through without starting or persisting anything', async () => {
- const t = service({ api: { create: async () => ({ ok: false, error: 'limit-daily' }) } })
- expect(await t.s.create(req())).toEqual({ ok: false, error: 'limit-daily' })
- expect(t.hosts.made).toHaveLength(0)
- expect(t.s.list()).toEqual([])
- })
-
- it('a failed local write revokes the server row and leaves nothing behind (spec: no half-created link)', async () => {
- const f = fakeStore({ save: async () => 'failed' })
- const t = service({ store: f.store })
- expect(await t.s.create(req())).toEqual({ ok: false, error: 'persist-failed' })
- expect(t.calls).toContain('revoke Link000000000000000001')
- expect(t.hosts.made).toHaveLength(0)
- expect(t.s.list()).toEqual([])
- })
-
- it('a local write that HANGS is bounded: persist-failed, the row revoked, and the corrected list queued behind it', async () => {
- const held = deferred<SaveOutcome>()
- const f = fakeStore({ save: () => held.promise })
- const t = service({ store: f.store, persistTimeoutMs: 20 })
- expect(await t.s.create(req())).toEqual({ ok: false, error: 'persist-failed' })
- expect(t.calls).toContain('revoke Link000000000000000001')
- expect(t.hosts.made).toHaveLength(0)
- // The write that hangs carries the link; the one queued after it does not, so when the disk
- // recovers the file ends without it.
- expect(f.saves.map((s) => s.length)).toEqual([1, 0])
- held.resolve('saved')
- })
-
- it('two concurrent creates at four links: one is created, the other answers limit-machine (G17)', async () => {
- const gate = deferred<void>()
- let n = 0
- const t = service({
- api: {
- create: async () => {
- n++
- const id = `Race${String(n).padStart(18, '0')}`
- if (n === 5) await gate.promise // the fifth create is in flight while the sixth asks
- return { ok: true, linkId: id, expiresAt: Date.now() + HOUR }
- }
- }
- })
- for (let i = 0; i < 4; i++) expect((await t.s.create(req())).ok).toBe(true)
- const fifth = t.s.create(req())
- await flush()
- const sixth = await t.s.create(req())
- expect(sixth).toEqual({ ok: false, error: 'limit-machine' })
- gate.resolve()
- expect((await fifth).ok).toBe(true)
- expect(n).toBe(5)
- expect(t.s.list()).toHaveLength(5)
- })
-
- it('a create whose write is pending counts ONCE against the cap', async () => {
- const held = deferred<SaveOutcome>()
- let saves = 0
- const f = fakeStore({ save: () => (++saves === 4 ? held.promise : Promise.resolve('saved')) })
- const t = service({ store: f.store })
- for (let i = 0; i < 3; i++) expect((await t.s.create(req())).ok).toBe(true)
- const fourth = t.s.create(req()) // its write is held: created server-side, not yet answered
- await vi.waitFor(() => expect(saves).toBe(4))
- expect((await t.s.create(req())).ok).toBe(true) // the fifth: 4 links + this one = 5
- held.resolve('saved')
- expect((await fourth).ok).toBe(true)
- expect(await t.s.create(req())).toEqual({ ok: false, error: 'limit-machine' })
- })
-
- it('a link being written is no link yet: not listed, and no stop can end it half-way; a concurrent write keeps it on disk', async () => {
- const held = deferred<SaveOutcome>()
- let saves = 0
- const f = fakeStore({ save: () => (++saves === 2 ? held.promise : Promise.resolve('saved')) })
- const t = service({ store: f.store })
- expect((await t.s.create(req({ nodeId: 'n2' }))).ok).toBe(true)
- const creating = t.s.create(req())
- await vi.waitFor(() => expect(saves).toBe(2))
- expect(t.s.list().map((l) => l.nodeId)).toEqual(['n2'])
- await t.s.revoke('Link000000000000000001') // the other link ends meanwhile…
- expect(f.saves.at(-1)?.map((r) => r.linkId)).toEqual(['Link000000000000000002']) // …and its write keeps this one
- held.resolve('saved')
- const r = await creating
- expect(r.ok).toBe(true)
- expect(t.s.list().map((l) => l.linkId)).toEqual(['Link000000000000000002'])
- expect(t.hosts.made.map((h) => h.record.linkId)).toEqual(['Link000000000000000001', 'Link000000000000000002'])
- })
-
- it('links the keychain could not unseal this run count against the cap (R46/M3)', async () => {
- const f = fakeStore({ opaque: 3 })
- const t = service({ store: f.store })
- expect((await t.s.create(req())).ok).toBe(true)
- expect((await t.s.create(req())).ok).toBe(true)
- expect(await t.s.create(req())).toEqual({ ok: false, error: 'limit-machine' }) // 2 + 3 opaque = 5
- expect(t.calls.filter((c) => c === 'create')).toHaveLength(2)
- })
-
- it('a node that leaves every project while the record is being written: node-missing, revoked, off disk (R46/M4)', async () => {
- const held = deferred<SaveOutcome>()
- let saves = 0
- const f = fakeStore({ save: () => (++saves === 1 ? held.promise : Promise.resolve('saved')) })
- const t = service({ store: f.store })
- const creating = t.s.create(req())
- await vi.waitFor(() => expect(saves).toBe(1))
- t.nodes.set('n1', 'absent') // deleted during the write; no workspace change could see this record
- held.resolve('saved')
- expect(await creating).toEqual({ ok: false, error: 'node-missing' })
- expect(t.calls).toContain('revoke Link000000000000000001')
- expect(t.hosts.made).toEqual([])
- expect(t.s.list()).toEqual([])
- expect(f.saves.at(-1)).toEqual([]) // the list without it, queued behind the write that carried it
- })
-
- it('a create is not blocked by a workspace load that never finishes: init decides after its own bound (R46/M5)', async () => {
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
- const f = fakeStore({ load: async () => [record({ nodeId: 'n2' })] })
- const t = service({
- store: f.store,
- workspaceReady: () => new Promise(() => {}),
- workspaceWaitMs: 20,
- nodes: new Map([['n1', 'present'], ['n2', 'unknown']])
- })
- expect((await t.s.create(req())).ok).toBe(true)
- expect(t.s.list().map((l) => l.nodeId).sort()).toEqual(['n1', 'n2']) // the resumed link is kept (unknown)
- expect(t.calls.filter((c) => c.startsWith('revoke '))).toEqual([])
- expect(warn.mock.calls.filter(([l]) => /did not finish loading/.test(String(l)))).toHaveLength(1)
- warn.mockRestore()
- })
-
- it('waits for init: a create during the boot load counts the resumed links and never hosts one twice (G11)', async () => {
- const loading = deferred<WatchLinkRecord[]>()
- const f = fakeStore({ load: () => loading.promise })
- const t = service({ store: f.store })
- void t.s.init()
- const loaded = Array.from({ length: 5 }, (_, i) => record({ linkId: `Boot${String(i).padStart(18, '0')}` }))
- const creating = t.s.create(req())
- await flush()
- expect(t.calls).not.toContain('create') // nothing asked before the load settled
- loading.resolve(loaded)
- expect(await creating).toEqual({ ok: false, error: 'limit-machine' })
- expect(t.hosts.made.map((h) => h.record.linkId)).toEqual(loaded.map((r) => r.linkId))
- await t.s.init() // idempotent: the same promise, no second start
- expect(t.hosts.made).toHaveLength(5)
- })
-
- it('a create waiting on an init that never settles is bounded too', async () => {
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
- const f = fakeStore({ load: () => new Promise(() => {}) })
- const t = service({ store: f.store, persistTimeoutMs: 20, workspaceWaitMs: 20 })
- expect(await t.s.create(req())).toEqual({ ok: false, error: 'persist-failed' })
- expect(await t.s.create(req())).toEqual({ ok: false, error: 'persist-failed' })
- expect(t.calls).not.toContain('create')
- // Diagnosable, once: it is the links file that did not load, not a failed write.
- expect(warn.mock.calls.filter(([l]) => /links file did not load/.test(String(l)))).toHaveLength(1)
- warn.mockRestore()
- })
-
- it('the Server Edition (unsupported): create answers unsupported, list is empty, nothing is loaded or hosted (R43)', async () => {
- const load = vi.fn(async () => [record()])
- const f = fakeStore({ load })
- const t = service({ store: f.store, unsupported: true })
- await t.s.init()
- expect(await t.s.create(req())).toEqual({ ok: false, error: 'unsupported' })
- expect(t.s.list()).toEqual([])
- expect(await t.s.revokeAll()).toBe('unsupported')
- t.s.onWorkspaceChanged()
- await flush()
- expect(load).not.toHaveBeenCalled()
- expect(f.saves).toEqual([])
- expect(t.hosts.made).toEqual([])
- expect(t.calls).toEqual([])
- })
-})
-
-describe('createWatchLinkService — ending a link', () => {
- it('revoke stops the host, forgets the record and revokes server-side, with no notice (the owner did it)', async () => {
- const t = service()
- const r = await t.s.create(req())
- if (!r.ok) throw new Error('create failed')
- await t.s.revoke(r.link.linkId)
- expect(t.hosts.made[0].stopped).toEqual(['revoked'])
- expect(t.s.list()).toEqual([])
- expect(await t.store.load()).toEqual([])
- expect(t.calls).toContain(`revoke ${r.link.linkId}`)
- expect(t.notices()).toEqual([])
- expect(t.states().at(-1)).toEqual([])
- })
-
- it('revoke is complete locally and reaches the server even when the write HANGS (Task 9 note B)', async () => {
- const f = fakeStore()
- const t = service({ store: f.store })
- const r = await t.s.create(req())
- if (!r.ok) throw new Error('create failed')
- const held = deferred<SaveOutcome>()
- f.store.save = (recs) => {
- f.saves.push([...recs])
- return held.promise
- }
- await t.s.revoke(r.link.linkId) // resolves although the write never lands
- expect(t.calls).toContain(`revoke ${r.link.linkId}`)
- expect(t.hosts.made[0].stopped).toEqual(['revoked'])
- expect(t.states().at(-1)).toEqual([])
- expect(f.saves.at(-1)).toEqual([]) // the write was ISSUED before the sessions ended (spec order)
- held.resolve('saved')
- })
-
- it('revokeAll ends every link without a notice, discards opaque entries and calls the server ONCE (G14)', async () => {
- const f = fakeStore()
- const t = service({ store: f.store })
- await t.s.create(req())
- await t.s.create(req({ nodeId: 'n2' }))
- await t.s.revokeAll()
- expect(t.s.list()).toEqual([])
- expect(t.hosts.made.map((h) => h.stopped)).toEqual([['revoked'], ['revoked']])
- expect(t.calls.filter((c) => c === 'revokeAll')).toHaveLength(1)
- expect(t.calls.filter((c) => c.startsWith('revoke '))).toEqual([])
- expect(t.notices()).toEqual([])
- expect(f.discarded()).toBe(1)
- expect(f.saves.at(-1)).toEqual([])
- })
-
- // R62: Stop all is the only control that reaches links on OTHER machines, so its server call is
- // awaited and its answer reported — a failed call must not look like a stop.
- it('revokeAll AWAITS the server and answers what it reached; this machine stops first, whatever the answer', async () => {
- const answer = deferred<boolean>()
- const t = service({ api: { revokeAll: () => answer.promise } })
- await t.s.create(req())
- let settled: string | null = null
- const p = t.s.revokeAll().then((o) => (settled = o))
- await flush()
- // Local first: stopped and listed as gone before the server answered.
- expect(t.hosts.made[0].stopped).toEqual(['revoked'])
- expect(t.s.list()).toEqual([])
- expect(settled).toBeNull()
- answer.resolve(true)
- await p
- expect(settled).toBe('stopped')
- })
-
- it("revokeAll: a refused or failed server call is 'failed', never 'stopped'", async () => {
- const refused = service({ api: { revokeAll: async () => false } })
- await refused.s.create(req())
- expect(await refused.s.revokeAll()).toBe('failed')
- expect(refused.s.list()).toEqual([]) // this machine's links are stopped all the same
- const thrown = service({
- api: {
- revokeAll: async () => {
- throw new Error('offline')
- }
- }
- })
- expect(await thrown.s.revokeAll()).toBe('failed')
- })
-
- it("revokeAll with no entitlement stops this machine and answers 'no-entitlement' — no request", async () => {
- const t = service({ entitlement: null })
- t.ent.value = 'ent'
- await t.s.create(req())
- t.ent.value = null
- expect(await t.s.revokeAll()).toBe('no-entitlement')
- expect(t.s.list()).toEqual([])
- expect(t.calls.filter((c) => c === 'revokeAll')).toEqual([])
- })
-
- it('Stop all reaches the server even when the boot load hangs (a stop never waits on the disk)', async () => {
- const f = fakeStore({ load: () => new Promise(() => {}) })
- const t = service({ store: f.store, persistTimeoutMs: 20, workspaceWaitMs: 20 })
- await t.s.revokeAll()
- await t.s.revoke('Link000000000000000001')
- expect(t.calls).toEqual(['revokeAll'])
- })
-
- it('a node that is ABSENT ends every link of the node, revokes each, and tells the owner', async () => {
- const t = service()
- await t.s.create(req())
- await t.s.create(req({ role: 'commenter' }))
- await t.s.create(req({ nodeId: 'n2' }))
- t.nodes.set('n1', 'absent')
- t.s.onWorkspaceChanged()
- await vi.waitFor(() => expect(t.s.list().map((l) => l.nodeId)).toEqual(['n2']))
- expect(t.hosts.made.filter((h) => h.stopped.includes('node-gone'))).toHaveLength(2)
- expect(t.calls.filter((c) => c.startsWith('revoke '))).toHaveLength(2)
- expect(t.notices().filter((n) => n.kind === 'ended' && n.reason === 'node-gone')).toHaveLength(2)
- })
-
- it('a node whose state is UNKNOWN is never ended or revoked (an unread project is not evidence)', async () => {
- const t = service()
- await t.s.create(req())
- t.nodes.set('n1', 'unknown')
- t.s.onWorkspaceChanged()
- await flush()
- expect(t.s.list()).toHaveLength(1)
- expect(t.hosts.made[0].stopped).toEqual([])
- expect(t.calls.filter((c) => c.startsWith('revoke '))).toEqual([])
- })
-
- it('a node-state check that throws reads as unknown', async () => {
- const t = service()
- await t.s.create(req())
- t.nodes.get = () => {
- throw new Error('boom')
- }
- t.s.onWorkspaceChanged()
- await flush()
- expect(t.s.list()).toHaveLength(1)
- })
-
- it('binds read-back to the link\'s own node: a viewer names only a cursor', async () => {
- const reads: [string, number | null][] = []
- const t = service({
- history: async (nodeId, before) => {
- reads.push([nodeId, before])
- return { kind: 'unsupported' }
- },
- historySupported: (nodeId) => nodeId === 'n2'
- })
- expect((await t.s.create(req({ nodeId: 'n2' }))).ok).toBe(true)
- const deps = t.hosts.made[0].deps
- expect(deps.historySupported?.()).toBe(true)
- await deps.history?.(77)
- expect(reads).toEqual([['n2', 77]])
- // Without the shell's reader there is no read-back at all.
- const bare = service()
- expect((await bare.s.create(req())).ok).toBe(true)
- expect(bare.hosts.made[0].deps.history).toBeUndefined()
- expect(bare.hosts.made[0].deps.historySupported).toBeUndefined()
- })
-
- it('a server-side end (onGone) ends the link locally, tells the owner, and does not revoke again', async () => {
- const t = service()
- const r = await t.s.create(req())
- if (!r.ok) throw new Error('create failed')
- t.hosts.made[0].deps.onGone('revoked')
- expect(t.s.list()).toEqual([])
- expect(t.notices()).toEqual([{ kind: 'ended', linkId: r.link.linkId, nodeId: 'n1', title: 'build', reason: 'revoked' }])
- expect(t.calls.filter((c) => c.startsWith('revoke '))).toEqual([])
- })
-
- it('expiry ends the link with an expired notice and no server revoke', async () => {
- vi.useFakeTimers()
- const t = service({ api: { create: async () => ({ ok: true, linkId: 'Exp0000000000000000000', expiresAt: Date.now() + 1000 }) } })
- expect((await t.s.create(req())).ok).toBe(true)
- await vi.advanceTimersByTimeAsync(999)
- expect(t.s.list()).toHaveLength(1)
- await vi.advanceTimersByTimeAsync(1)
- expect(t.s.list()).toEqual([])
- expect(t.hosts.made[0].stopped).toEqual(['expired'])
- expect(t.notices()).toEqual([{ kind: 'ended', linkId: 'Exp0000000000000000000', nodeId: 'n1', title: 'build', reason: 'expired' }])
- expect(t.calls.filter((c) => c.startsWith('revoke '))).toEqual([])
- })
-
- it('a host change after the link expired ends it even if its timer slept past (G24: monotonic timers across a lid-close)', async () => {
- let clock = 1_000_000
- const t = service({
- now: () => clock,
- api: { create: async () => ({ ok: true, linkId: 'Lid0000000000000000000', expiresAt: clock + HOUR }) }
- })
- expect((await t.s.create(req())).ok).toBe(true)
- clock += HOUR // the wall clock moved on; the expiry timer (monotonic) has not fired
- t.hosts.made[0].deps.onChange()
- await vi.waitFor(() => expect(t.s.list()).toEqual([]))
- expect(t.notices().at(-1)).toMatchObject({ kind: 'ended', reason: 'expired' })
- })
-
- it('shutdown stops hosts as host-stopping, keeps the records, and nothing ends a link after it', async () => {
- const t = service()
- await t.s.create(req())
- await t.s.shutdown()
- expect(t.hosts.made[0].stopped).toEqual(['host-stopping'])
- expect(await t.store.load()).toHaveLength(1)
- t.nodes.set('n1', 'absent')
- t.s.onWorkspaceChanged()
- await flush()
- expect(t.calls.filter((c) => c.startsWith('revoke '))).toEqual([])
- expect(await t.s.create(req())).toEqual({ ok: false, error: 'unsupported' })
- })
-})
-
-// An Unlimited link's record has `expiresAt: null`: no expiry timer, never swept or ended for time.
-// (Creating one is Task 6's; these resume it from the store, which is where a null first appears.)
-describe('createWatchLinkService — a link with no expiry (expiresAt: null)', () => {
- const ended = (t: ReturnType<typeof service>) => t.notices().filter((n) => n.kind === 'ended')
-
- it('is resumed at launch and never pruned for time, however late the clock reads', async () => {
- const f = fakeStore({ load: async () => [record({ expiresAt: null })] })
- const t = service({ store: f.store, now: () => Number.MAX_SAFE_INTEGER })
- await t.s.init()
- expect(t.s.list().map((l) => [l.linkId, l.expiresAt])).toEqual([['Good000000000000000000', null]])
- expect(t.hosts.made.map((h) => h.record.linkId)).toEqual(['Good000000000000000000'])
- expect(f.saves).toEqual([]) // nothing was pruned, so nothing is written
- })
-
- it('arms no expiry timer: still listed and hosted after any amount of time', async () => {
- vi.useFakeTimers()
- const f = fakeStore({ load: async () => [record({ expiresAt: null })] })
- const t = service({ store: f.store })
- await t.s.init()
- expect(vi.getTimerCount()).toBe(0)
- await vi.advanceTimersByTimeAsync(400 * 24 * HOUR)
- expect(t.s.list()).toHaveLength(1)
- expect(t.hosts.made[0].stopped).toEqual([])
- expect(ended(t)).toEqual([])
- })
-
- it('a host change never ends it as expired (the G24 check has no end time to compare)', async () => {
- let clock = 1_000_000
- const f = fakeStore({ load: async () => [record({ expiresAt: null })] })
- const t = service({ store: f.store, now: () => clock })
- await t.s.init()
- clock = Number.MAX_SAFE_INTEGER
- t.hosts.made[0].deps.onChange()
- await flush()
- expect(t.s.list()).toHaveLength(1)
- expect(t.hosts.made[0].stopped).toEqual([])
- expect(ended(t)).toEqual([])
- })
-
- it('still ends for every other reason (a revoke)', async () => {
- const f = fakeStore({ load: async () => [record({ expiresAt: null })] })
- const t = service({ store: f.store })
- await t.s.init()
- await t.s.revoke('Good000000000000000000')
- expect(t.s.list()).toEqual([])
- expect(t.hosts.made[0].stopped).toEqual(['revoked'])
- })
-})
-
-describe('createWatchLinkService — init (resume at launch)', () => {
- it('resumes live and UNKNOWN records, drops expired ones, and revokes only an ABSENT one', async () => {
- const t = service({ nodes: new Map([['n1', 'present'], ['maybe', 'unknown']]) })
- const good = record()
- await t.store.save([
- good,
- record({ linkId: 'Maybe00000000000000000', nodeId: 'maybe' }),
- record({ linkId: 'Old0000000000000000000', expiresAt: Date.now() - 1 }),
- record({ linkId: 'Orph000000000000000000', nodeId: 'gone' })
- ])
- await t.s.init()
- expect(t.s.list().map((l) => l.linkId)).toEqual(['Good000000000000000000', 'Maybe00000000000000000'])
- expect(t.hosts.made.map((h) => h.record.linkId)).toEqual(['Good000000000000000000', 'Maybe00000000000000000'])
- expect(t.calls.filter((c) => c.startsWith('revoke '))).toEqual(['revoke Orph000000000000000000'])
- expect((await t.store.load()).map((r) => r.linkId)).toEqual(['Good000000000000000000', 'Maybe00000000000000000'])
- })
-
- it('the launch-time empty workspace revokes NOTHING: every node reads unknown until the index is read', async () => {
- // What `workspaceNodeState` answers before the workspace store has loaded its index.
- const t = service({ nodes: new Map([['n1', 'unknown'], ['n2', 'unknown']]) })
- await t.store.save([record(), record({ linkId: 'Two0000000000000000000', nodeId: 'n2' })])
- await t.s.init()
- expect(t.s.list()).toHaveLength(2)
- expect(t.calls.filter((c) => c.startsWith('revoke '))).toEqual([])
- })
-
- it('decides nothing before the workspace load it is handed has settled (R40)', async () => {
- const ready = deferred<void>()
- const nodes = new Map<string, WatchLinkNodeState>([['n1', 'unknown']])
- const f = fakeStore({ load: async () => [record()] })
- const t = service({ store: f.store, nodes, workspaceReady: () => ready.promise })
- const init = t.s.init()
- await flush()
- expect(t.hosts.made).toEqual([])
- nodes.set('n1', 'absent') // the load completed and the node is really gone
- ready.resolve()
- await init
- expect(t.s.list()).toEqual([])
- expect(t.calls).toEqual(['revoke Good000000000000000000'])
- })
-
- it('a workspace load that fails still lets init run (every answer is then unknown)', async () => {
- const f = fakeStore({ load: async () => [record()] })
- const t = service({ store: f.store, nodes: new Map([['n1', 'unknown']]), workspaceReady: () => Promise.reject(new Error('x')) })
- await t.s.init()
- expect(t.s.list()).toHaveLength(1)
- })
-
- it('writes the file only when it pruned something (R42a)', async () => {
- const f = fakeStore({ load: async () => [record()] })
- const t = service({ store: f.store })
- await t.s.init()
- expect(f.saves).toEqual([])
- const g = fakeStore({ load: async () => [record(), record({ linkId: 'Old0000000000000000000', expiresAt: 1 })] })
- const u = service({ store: g.store })
- await u.s.init()
- expect(g.saves.map((s) => s.map((r) => r.linkId))).toEqual([['Good000000000000000000']])
- })
-
- it('an unreadable links file: init resolves, runs memory-only, never writes, and says so on every create (R22/R42c)', async () => {
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
- const f = fakeStore({ load: async () => Promise.reject(new WatchLinkStoreUnreadable('unknown-version', 'watch-links.json has version 2, expected 1')) })
- const t = service({ store: f.store })
- await expect(t.s.init()).resolves.toBeUndefined()
- expect(warn).toHaveBeenCalledTimes(1)
- expect(String(warn.mock.calls[0][0])).toMatch(/unknown-version/)
- expect((await t.s.create(req())).ok).toBe(true)
- expect((await t.s.create(req())).ok).toBe(true)
- await t.s.revoke('Link000000000000000001')
- expect(f.saves).toEqual([])
- expect(t.notices().filter((n) => n.kind === 'not-persistent')).toHaveLength(3) // boot + each create
- warn.mockRestore()
- })
-
- it('a keychain that refuses to seal: created links work, and every create says they are not persisted (R42c)', async () => {
- const f = fakeStore({ save: async () => 'memory-only' })
- const t = service({ store: f.store })
- expect((await t.s.create(req())).ok).toBe(true)
- expect((await t.s.create(req())).ok).toBe(true)
- expect(t.notices().filter((n) => n.kind === 'not-persistent')).toHaveLength(2)
- expect(t.hosts.made).toHaveLength(2)
- })
-
- it('in a build that may not relay, resumed links are kept and listed refused, and nothing is hosted (G21)', async () => {
- const f = fakeStore({ load: async () => [record()] })
- const t = service({ store: f.store, relayAllowed: false })
- await t.s.init()
- expect(t.hosts.made).toEqual([])
- expect(t.s.list().map((l) => l.status)).toEqual(['refused'])
- })
-
- it('keeps at most five resumed links; the rest are pruned and revoked', async () => {
- const recs = Array.from({ length: 7 }, (_, i) => record({ linkId: `Many${String(i).padStart(18, '0')}` }))
- const f = fakeStore({ load: async () => recs })
- const t = service({ store: f.store })
- await t.s.init()
- expect(t.s.list()).toHaveLength(5)
- expect(t.calls.filter((c) => c.startsWith('revoke '))).toHaveLength(2)
- })
-})
-
-describe('createWatchLinkService — the host seams', () => {
- it('never mints with an empty entitlement: a local refusal, no request (R41b)', async () => {
- const t = service()
- await t.s.create(req())
- t.ent.value = null
- expect(await t.hosts.made[0].deps.mint()).toEqual({ ok: false, kind: 'refused', status: 402 })
- expect(t.calls.filter((c) => c.startsWith('hostToken'))).toEqual([])
- expect(await t.hosts.made[0].deps.status()).toBe('unknown')
- t.ent.value = 'ent2'
- expect((await t.hosts.made[0].deps.mint()).ok).toBe(true)
- })
-
- it('an entitlement change re-arms ONLY the refused hosts (R41a)', async () => {
- const t = service()
- await t.s.create(req())
- await t.s.create(req({ nodeId: 'n2' }))
- t.hosts.made[0].status = 'refused'
- t.s.onEntitlementChanged()
- expect(t.hosts.made.map((h) => h.starts)).toEqual([2, 1])
- })
-
- it('checks the node before every join: absent ends the link (node-gone + revoke), unknown joins (R29/G8)', async () => {
- const join = vi.fn(async () => ({ sessionId: 's1', cols: 80, rows: 24, altScreen: true, input: 'tmux' as const }))
- const t = service({ pty: fakePty({ join }) })
- const r = await t.s.create(req())
- if (!r.ok) throw new Error('create failed')
- const pty = t.hosts.made[0].deps.pty
- t.nodes.set('n1', 'unknown')
- expect(await pty.join(1, 'n1', 'v-1')).toMatchObject({ sessionId: 's1' })
- t.nodes.set('n1', 'absent')
- expect(await pty.join(1, 'n1', 'v-2')).toBeNull()
- expect(join).toHaveBeenCalledTimes(1)
- expect(t.s.list()).toEqual([])
- expect(t.hosts.made[0].stopped).toEqual(['node-gone'])
- expect(t.calls).toContain(`revoke ${r.link.linkId}`)
- // The other members pass straight through.
- expect(pty.alive('s1')).toBe(true)
- expect(await pty.syncSize('s1')).toBe(true)
- expect(await pty.captureVisible('s1')).toEqual({ screen: '', cursor: null })
- })
-
- it('tells the owner when someone starts watching', async () => {
- const t = service()
- const r = await t.s.create(req())
- if (!r.ok) throw new Error('create failed')
- t.hosts.made[0].deps.onViewerJoined(2)
- expect(t.notices()).toEqual([{ kind: 'joined', linkId: r.link.linkId, nodeId: 'n1', title: 'build', viewers: 2 }])
- })
-
- it('strips bidi controls from everything a viewer wrote before the owner sees it', async () => {
- const t = service()
- const r = await t.s.create(req({ role: 'commenter' }))
- if (!r.ok) throw new Error('create failed')
- const h = t.hosts.made[0]
- h.deps.onChat({ id: 'x', name: 'E\u202eve\u061c', text: 'hi\u2066 there \u{1F468}\u200d\u{1F469}', at: 1, from: 'viewer' })
- const chat = t.emitted.find(([ch]) => ch === IPC.watchLinkChat)
- // Bidi (ALM included) gone; the ZWJ joining an emoji sequence stays.
- expect(chat?.[1]).toEqual([r.link.linkId, { id: 'x', name: 'Eve', text: 'hi there \u{1F468}\u200d\u{1F469}', at: 1, from: 'viewer' }])
- h.chat = [{ id: 'y', name: '\u200fMal', text: 'a\u202ab', at: 2, from: 'viewer' }]
- expect(t.s.chatHistory(r.link.linkId)).toEqual([{ id: 'y', name: 'Mal', text: 'ab', at: 2, from: 'viewer' }])
- h.viewers = [{ viewerId: 'v-1', name: 'E\u202eve', joinedAt: 5, waiting: false, controlling: false, typing: false }]
- expect(t.s.list()[0].viewers).toEqual([{ viewerId: 'v-1', name: 'Eve', joinedAt: 5, waiting: false, controlling: false, typing: false }])
- })
-
- // R63: a viewer the host could not join to a session reaches the owner's view as `waiting`.
- it("a viewer's waiting state reaches the owner's view", async () => {
- const t = service()
- const r = await t.s.create(req())
- if (!r.ok) throw new Error('create failed')
- t.hosts.made[0].viewers = [
- { viewerId: 'v-1', name: null, joinedAt: 5, waiting: true, controlling: false, typing: false },
- { viewerId: 'v-2', name: null, joinedAt: 6, waiting: false, controlling: false, typing: false }
- ]
- expect(t.s.list()[0].viewers.map((v) => v.waiting)).toEqual([true, false])
- })
-
- it('kick, owner chat and history go to the link host; an unknown link answers nothing', async () => {
- const t = service()
- const r = await t.s.create(req({ role: 'commenter' }))
- if (!r.ok) throw new Error('create failed')
- t.hosts.made[0].viewers = [{ viewerId: 'v-1', name: null, joinedAt: 1, waiting: false, controlling: false, typing: false }]
- expect(t.s.kick(r.link.linkId, 'v-1')).toBe(true)
- expect(t.s.kick(r.link.linkId, 'v-9')).toBe(false)
- expect(t.s.sendChat(r.link.linkId, 'hello')).toMatchObject({ text: 'hello', from: 'sharer' })
- expect(t.s.kick('Nope000000000000000000', 'v-1')).toBe(false)
- expect(t.s.sendChat('Nope000000000000000000', 'x')).toBeNull()
- expect(t.s.chatHistory('Nope000000000000000000')).toEqual([])
- })
-})
-
-describe('state pushes are coalesced (R46/M7)', () => {
- it('one push per end, although the stopped host also reports a change; one push for a whole shutdown', async () => {
- const t = service()
- for (const nodeId of ['n1', 'n2', 'n1']) expect((await t.s.create(req({ nodeId }))).ok).toBe(true)
- // Like the real link host: `stop` reports a change.
- for (const h of t.hosts.made) {
- const deps = h.deps
- h.stopped = new Proxy(h.stopped, {
- get: (arr, k) => (k === 'push' ? (...a: string[]) => (deps.onChange(), arr.push(...a)) : Reflect.get(arr, k))
- })
- }
- const before = t.states().length
- await t.s.revoke(t.s.list()[0].linkId)
- await flush()
- expect(t.states().length - before).toBe(1)
- expect(t.states().at(-1)).toHaveLength(2)
- await t.s.shutdown()
- await flush()
- expect(t.states().length - before).toBe(2)
- })
-})
-
-describe('shutdownWithin (R46/M6)', () => {
- it('answers at the bound when the last write hangs, at once when it lands, and nothing for no service', async () => {
- const hung = { shutdown: () => new Promise<void>(() => {}) } as unknown as WatchLinkService
- const t0 = Date.now()
- await shutdownWithin(hung, 30)
- expect(Date.now() - t0).toBeGreaterThanOrEqual(25)
- const quick = { shutdown: vi.fn(async () => {}) } as unknown as WatchLinkService
- await shutdownWithin(quick, 60_000) // would time the test out if it waited for the bound
- expect((quick as unknown as { shutdown: ReturnType<typeof vi.fn> }).shutdown).toHaveBeenCalledTimes(1)
- await shutdownWithin(null, 60_000)
- })
-})
-
-describe('registerWatchLinkIpc / sendToOwners', () => {
- it('the IPC answers owners only', async () => {
- const t = service()
- const p = fakePlatform({ isOwnerClient: (id) => id === 1 })
- registerWatchLinkIpc(p, t.s)
- expect(await p.handlers[IPC.watchLinkCreate](2, req())).toEqual({ ok: false, error: 'unsupported' })
- expect(await p.handlers[IPC.watchLinkList](2)).toEqual([])
- expect(await p.handlers[IPC.watchLinkKick](2, 'x', 'y')).toBe(false)
- expect(await p.handlers[IPC.watchLinkChatSend](2, 'x', 'y')).toBeNull()
- expect(await p.handlers[IPC.watchLinkChatHistory](2, 'x')).toEqual([])
- const made = (await p.handlers[IPC.watchLinkCreate](1, req())) as { ok: boolean; link: WatchLinkView }
- expect(made.ok).toBe(true)
- expect(await p.handlers[IPC.watchLinkRevoke](2, made.link.linkId)).toBeUndefined()
- expect(await p.handlers[IPC.watchLinkRevokeAll](2)).toBe('unsupported')
- expect((await p.handlers[IPC.watchLinkList](1)) as WatchLinkView[]).toHaveLength(1) // a non-owner stopped nothing
- await p.handlers[IPC.watchLinkRevoke](1, made.link.linkId)
- expect(await p.handlers[IPC.watchLinkList](1)).toEqual([])
- })
-
- it('a platform with no owner notion answers nobody', async () => {
- const t = service()
- const p = fakePlatform()
- delete (p as { isOwnerClient?: unknown }).isOwnerClient
- registerWatchLinkIpc(p, t.s)
- expect(await p.handlers[IPC.watchLinkCreate](1, req())).toEqual({ ok: false, error: 'unsupported' })
- })
-
- it('registers exactly the eleven request channels', () => {
- const p = fakePlatform({ isOwnerClient: () => true })
- registerWatchLinkIpc(p, service().s)
- expect(Object.keys(p.handlers).sort()).toEqual(
- [
- IPC.watchLinkCreate, IPC.watchLinkList, IPC.watchLinkRevoke, IPC.watchLinkRevokeAll, IPC.watchLinkKick,
- IPC.watchLinkChatSend, IPC.watchLinkChatHistory, IPC.watchLinkSetControl, IPC.watchLinkSetPassword,
- IPC.watchLinkAllowControl, IPC.watchLinkControlSupport
- ].sort()
- )
- })
-
- it('the Control channels answer owners only, and refuse arguments of the wrong type', async () => {
- const t = service({ controlSupport: () => 'ok', hashPassword: fastHash })
- const p = fakePlatform({ isOwnerClient: (id) => id === 1 })
- registerWatchLinkIpc(p, t.s)
- const made = (await p.handlers[IPC.watchLinkCreate](1, ctlReq())) as { ok: true; link: WatchLinkView }
- const id = made.link.linkId
- const h = t.hosts.made[0]
- // A client that is not the machine's owner reaches nothing.
- expect(await p.handlers[IPC.watchLinkSetControl](2, id, false)).toBe(false)
- expect(await p.handlers[IPC.watchLinkSetPassword](2, id, 'another password')).toBe(false)
- expect(await p.handlers[IPC.watchLinkAllowControl](2, id)).toBe(false)
- expect(await p.handlers[IPC.watchLinkControlSupport](2, 'n1')).toBe('unknown')
- // Wrong types.
- expect(await p.handlers[IPC.watchLinkSetControl](1, id, 'false')).toBe(false)
- expect(await p.handlers[IPC.watchLinkSetControl](1, 7, false)).toBe(false)
- expect(await p.handlers[IPC.watchLinkSetPassword](1, id, 12345678)).toBe(false)
- expect(await p.handlers[IPC.watchLinkAllowControl](1, null)).toBe(false)
- expect(await p.handlers[IPC.watchLinkControlSupport](1, 5)).toBe('unknown')
- expect(h.hooks).toEqual([])
- // The owner.
- expect(await p.handlers[IPC.watchLinkControlSupport](1, 'n1')).toBe('ok')
- expect(await p.handlers[IPC.watchLinkSetControl](1, id, false)).toBe(true)
- expect(await p.handlers[IPC.watchLinkSetPassword](1, id, 'another password')).toBe(true)
- h.deps.onControlLocked()
- expect(await p.handlers[IPC.watchLinkAllowControl](1, id)).toBe(true)
- expect(h.hooks).toEqual(['controlChanged', 'passwordChanged', 'allowControl'])
- })
-
- it('sendToOwners reaches owner clients only (the link URL carries its secret)', () => {
- const p = fakePlatform({ isOwnerClient: (id) => id === 3 })
- p.clients.push(2, 3, 4)
- sendToOwners(p, IPC.watchLinkState, [])
- expect(p.sent).toEqual([{ to: 3, channel: IPC.watchLinkState, args: [[]] }])
- })
-})
-
-describe('workspaceNodeState', () => {
- const store = (held: Record<string, string[]>, known: Set<string> | undefined) => ({
- projectIdsForNode: (id: string) => held[id] ?? [],
- knownNodeIdsStrict: () => known
- })
- it('present when a project holds it', () => {
- expect(workspaceNodeState(store({ n1: ['p1'] }, undefined), 'n1')).toBe('present')
- })
- it('absent only on a complete read that lacks it', () => {
- expect(workspaceNodeState(store({}, new Set(['n2'])), 'n1')).toBe('absent')
- expect(workspaceNodeState(store({}, new Set()), 'n1')).toBe('absent')
- })
- it('unknown when the read is incomplete (index not loaded, an unread project)', () => {
- expect(workspaceNodeState(store({}, undefined), 'n1')).toBe('unknown')
- })
- it('present when the complete read has it even if the project scan does not', () => {
- expect(workspaceNodeState(store({}, new Set(['n1'])), 'n1')).toBe('present')
- })
-})
-
-// A store round trip with the real file: the brief's end-to-end persistence claim.
-describe('createWatchLinkService — real store', () => {
- it('a created link is on disk, and a revoked one is gone from it', async () => {
- const t = service()
- const r = await t.s.create(req())
- if (!r.ok) throw new Error('create failed')
- expect(JSON.parse(readFileSync(t.file, 'utf8')).links).toHaveLength(1)
- await t.s.revoke(r.link.linkId)
- await t.store.load() // queued behind the revoke's write
- expect(JSON.parse(readFileSync(t.file, 'utf8')).links).toEqual([])
- })
-})
-
-// --- Control links and Unlimited links ------------------------------------------------------------------
-
-const PW = 'correct horse battery'
-const NEW_PW = 'staple gun ninety'
-const ctlReq = (over: Record<string, unknown> = {}) => req({ role: 'controller', password: PW, ...over })
-/** A hash shaped like scrypt's (16-byte salt, 32-byte key) without its ~80 ms: for the tests that
- * are about the plumbing, not the password. Different every call, like a fresh salt. */
-let fastN = 0
-const fastHash = async (): Promise<ControlPasswordHash> => {
- fastN++
- return {
- salt: Buffer.alloc(16, fastN % 256).toString('base64'),
- hash: Buffer.alloc(32, (fastN * 7) % 256).toString('base64')
- }
-}
-const allLogged = (spies: ReturnType<typeof vi.spyOn>[]) => spies.flatMap((sp) => sp.mock.calls.flat().map(String)).join('\n')
-
-describe('createWatchLinkService — creating a Control link', () => {
- it('hashes the password, keeps only {salt, hash} in the record, and the host checks against it', async () => {
- const t = service()
- const r = await t.s.create(ctlReq())
- if (!r.ok) throw new Error(r.error)
- expect(r.link).toMatchObject({ role: 'controller', control: { enabled: true, locked: false } })
- const text = readFileSync(t.file, 'utf8')
- expect(text).not.toContain(PW)
- expect(text).not.toContain(Buffer.from(PW).toString('base64'))
- expect(text).not.toContain(Buffer.from(PW).toString('hex'))
- const [loaded] = await t.store.load()
- expect(Object.keys(loaded.control ?? {}).sort()).toEqual(['enabled', 'hash', 'lockStep', 'locked', 'lockedUntil', 'salt', 'wrong'])
- expect(loaded.control).toMatchObject({ enabled: true, locked: false })
- expect(await verifyControlPassword(PW, loaded.control!)).toBe(true)
- const h = t.hosts.made[0]
- expect(await h.deps.verifyPassword(PW)).toBe(true)
- expect(await h.deps.verifyPassword('not the password')).toBe(false)
- })
-
- it('a viewer or commenter link ignores a password field: no control, nothing of it on disk', async () => {
- const t = service()
- for (const role of ['viewer', 'commenter']) {
- const r = await t.s.create(req({ role, password: PW }))
- if (!r.ok) throw new Error(r.error)
- expect(r.link.control).toBeNull()
- }
- expect(readFileSync(t.file, 'utf8')).not.toContain(PW)
- expect((await t.store.load()).map((l) => l.control)).toEqual([undefined, undefined])
- expect(await t.hosts.made[0].deps.verifyPassword(PW)).toBe(false)
- })
-
- it('a Control link without an acceptable password is bad-password, and nothing is asked of the server', async () => {
- const t = service()
- for (const password of [undefined, '', 'short', 12345678, 'abcdefg\n', 'x'.repeat(129), null, {}]) {
- expect(await t.s.create(ctlReq({ password })), JSON.stringify(password)).toEqual({ ok: false, error: 'bad-password' })
- }
- // A request that is malformed otherwise is bad-request, whatever its password.
- expect(await t.s.create(ctlReq({ password: 'short', ttlSeconds: 7 }))).toEqual({ ok: false, error: 'bad-request' })
- expect(t.calls).toEqual([])
- expect(t.hosts.made).toEqual([])
- })
-
- it('a Control link on a terminal that cannot take input (Zellij) is control-unsupported, before any request', async () => {
- const answers = new Map<string, ControlSupport>([['n1', 'unsupported'], ['n2', 'unknown']])
- const t = service({ controlSupport: (id) => answers.get(id) ?? 'ok' })
- expect(await t.s.create(ctlReq())).toEqual({ ok: false, error: 'control-unsupported' })
- expect(t.calls).toEqual([])
- // Only a Control link is asked about; unknown leaves the create to decide.
- expect((await t.s.create(req({ role: 'commenter' }))).ok).toBe(true)
- expect((await t.s.create(ctlReq({ nodeId: 'n2' }))).ok).toBe(true)
- // A check that throws reads as unknown.
- const u = service({
- controlSupport: () => {
- throw new Error('boom')
- }
- })
- expect((await u.s.create(ctlReq())).ok).toBe(true)
- // A shell that wires no check: unknown.
- expect((await service().s.create(ctlReq())).ok).toBe(true)
- })
-
- it('the password is hashed BEFORE the server create: a hash that fails creates no server row, and logs nothing of it', async () => {
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
- const t = service({
- hashPassword: async (pw) => {
- throw new Error(`scrypt said no about ${pw}`)
- }
- })
- // `unsupported`: the one kind whose desktop copy names no cause ("can't be created here right now");
- // `network` would say nodeterm's service could not be reached, which is not what happened.
- expect(await t.s.create(ctlReq())).toEqual({ ok: false, error: 'unsupported' })
- expect(t.calls).toEqual([])
- expect(t.hosts.made).toEqual([])
- expect(allLogged([warn])).not.toContain(PW)
- warn.mockRestore()
- })
-})
-
-describe('createWatchLinkService — creating an Unlimited link', () => {
- it('asks for ttlSeconds 0 and records expiresAt: null, with no expiry timer: still live after any time', async () => {
- vi.useFakeTimers()
- const t = service()
- const r = await t.s.create(req({ ttlSeconds: 0 }))
- if (!r.ok) throw new Error(r.error)
- expect(t.ttls).toEqual([0])
- expect(r.link.expiresAt).toBeNull()
- expect((await t.store.load())[0].expiresAt).toBeNull()
- expect(vi.getTimerCount()).toBe(0)
- await vi.advanceTimersByTimeAsync(400 * 24 * HOUR)
- expect(t.s.list().map((l) => l.expiresAt)).toEqual([null])
- expect(t.hosts.made[0].stopped).toEqual([])
- })
-
- it('an older server (ttl-unsupported) creates nothing here', async () => {
- const t = service({ api: { create: async () => ({ ok: false, error: 'ttl-unsupported' }) } })
- expect(await t.s.create(req({ ttlSeconds: 0 }))).toEqual({ ok: false, error: 'ttl-unsupported' })
- expect(t.hosts.made).toEqual([])
- expect(t.s.list()).toEqual([])
- expect(await t.store.load()).toEqual([])
- })
-
- // The backend checks an Unlimited link's license daily at its host-token mint and answers 402 once
- // the owner's Pro lapsed. That is the same refusal as any other: the REAL host stops minting (no
- // retry loop) and the owner's view reads `status: 'refused'`.
- it("a 402 at the mint (Pro lapsed) stops minting for good and the view reads status 'refused'", async () => {
- const quiet = [vi.spyOn(console, 'warn').mockImplementation(() => {}), vi.spyOn(console, 'error').mockImplementation(() => {})]
- vi.useFakeTimers()
- let mints = 0
- const t = service({
- realHost: true,
- api: {
- hostToken: async () => {
- mints++
- return { ok: false, kind: 'refused', status: 402 }
- }
- }
- })
- const r = await t.s.create(req({ ttlSeconds: 0 }))
- if (!r.ok) throw new Error(r.error)
- await vi.waitFor(() => expect(mints).toBe(1))
- await vi.advanceTimersByTimeAsync(48 * HOUR)
- expect(mints).toBe(1)
- expect(t.s.list()[0]).toMatchObject({ status: 'refused', expiresAt: null })
- expect(t.states().at(-1)?.[0].status).toBe('refused')
- for (const q of quiet) q.mockRestore()
- })
-})
-
-describe('createWatchLinkService — the Control host seams', () => {
- it('a lock is set on the record SYNCHRONOUSLY, then written, and the owner is told', async () => {
- const t = service()
- const r = await t.s.create(ctlReq())
- if (!r.ok) throw new Error(r.error)
- const h = t.hosts.made[0]
- h.deps.onControlLocked()
- expect(h.record.control?.locked).toBe(true) // before any await: the host's lock rests on it
- const until = h.record.control?.lockedUntil
- expect(until).toEqual(expect.any(Number))
- expect(t.notices().at(-1)).toEqual({ kind: 'control-locked', linkId: r.link.linkId, nodeId: 'n1', title: 'build', by: null, until })
- expect((await t.store.load())[0].control?.locked).toBe(true)
- await flush()
- expect(t.states().at(-1)?.[0].control).toEqual({ enabled: true, locked: true, lockedUntil: until })
- })
-
- it('a lock whose write fails still holds in memory, and the failure is logged', async () => {
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
- let outcome: SaveOutcome = 'saved'
- const f = fakeStore({ save: async () => outcome })
- const t = service({ store: f.store })
- const r = await t.s.create(ctlReq())
- if (!r.ok) throw new Error(r.error)
- outcome = 'failed'
- t.hosts.made[0].deps.onControlLocked()
- await vi.waitFor(() => expect(warn.mock.calls.some(([l]) => /lock/.test(String(l)))).toBe(true))
- expect(t.s.list()[0].control).toMatchObject({ enabled: true, locked: true })
- const c = t.hosts.made[0].record.control!
- for (const secret of [PW, c.salt, c.hash]) expect(allLogged([warn])).not.toContain(secret)
- warn.mockRestore()
- })
-
- // Final review, Minor 2: the link-wide wrong count is persisted beside `locked`, so an app restart
- // no longer resets it toward the lock (with Unlimited links that was 9 fresh guesses per restart).
- it('each wrong attempt puts the link-wide count on the record and writes it — at most 10 writes, the 10th rides the lock', async () => {
- const written: (WatchLinkRecord['control'] | undefined)[] = []
- const f = fakeStore({
- save: async (recs) => {
- written.push(recs[0]?.control ? { ...recs[0].control } : undefined)
- return 'saved'
- }
- })
- const t = service({ store: f.store, hashPassword: fastHash })
- const r = await t.s.create(ctlReq())
- if (!r.ok) throw new Error(r.error)
- const h = t.hosts.made[0]
- expect(h.record.control?.wrong).toBe(0)
- const saves = f.saves.length
- for (let n = 1; n <= WRONG_PER_LINK; n++) {
- h.deps.onWrongAttempt(n)
- expect(h.record.control?.wrong).toBe(n) // synchronously: the record is the count's home
- if (n === WRONG_PER_LINK) h.deps.onControlLocked() // what the host does at the 10th
- }
- await flush()
- expect(f.saves.length - saves).toBe(WRONG_PER_LINK)
- expect(written.slice(saves).map((c) => c?.wrong)).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
- expect(written.at(-1)).toMatchObject({ wrong: WRONG_PER_LINK, locked: true })
- })
-
- it('a count outside 0..10 is clamped onto the record (the store would refuse to write it)', async () => {
- const t = service({ hashPassword: fastHash })
- const r = await t.s.create(ctlReq())
- if (!r.ok) throw new Error(r.error)
- const h = t.hosts.made[0]
- h.deps.onWrongAttempt(99)
- expect(h.record.control?.wrong).toBe(WRONG_PER_LINK)
- h.deps.onWrongAttempt(-3)
- expect(h.record.control?.wrong).toBe(0)
- h.deps.onWrongAttempt(Number.NaN)
- expect(h.record.control?.wrong).toBe(0)
- await flush()
- expect((await t.store.load())[0].control?.wrong).toBe(0)
- })
-
- it('the count survives a restart: a host resumed from the saved record starts from it', async () => {
- const t = service({ hashPassword: fastHash })
- const r = await t.s.create(ctlReq())
- if (!r.ok) throw new Error(r.error)
- for (let n = 1; n <= 9; n++) t.hosts.made[0].deps.onWrongAttempt(n)
- await flush()
- expect((await t.store.load())[0].control?.wrong).toBe(9)
- await t.s.shutdown()
- const again = service({ store: new WatchLinkStore({ file: t.file }) })
- await again.s.init()
- expect(again.hosts.made[0].record.control?.wrong).toBe(9)
- })
-
- // Finding L2: a lock lifts by itself — 15 minutes for the first since the owner last allowed control,
- // doubling each time, 24 h at most — so a link holder cannot lock control for everyone for good.
- describe('a timed lock (finding L2)', () => {
- const MIN = 60_000
- async function locked(o: Opts = {}) {
- vi.useFakeTimers()
- const t = service({ hashPassword: fastHash, ...o })
- // Unlimited: a lock can outlast a finite link, which would end it first.
- const r = await t.s.create(ctlReq({ ttlSeconds: 0 }))
- if (!r.ok) throw new Error(r.error)
- const h = t.hosts.made[0]
- return { t, h, id: r.link.linkId }
- }
- const lockNow = (h: FakeHost, by: string | null = null): void => {
- for (let n = 1; n <= WRONG_PER_LINK; n++) h.deps.onWrongAttempt(n)
- h.deps.onControlLocked(by)
- }
-
- it('lasts 15 minutes, names who tipped it, then lifts by itself: unlocking allowed again, the count over, the host told, saved', async () => {
- const { t, h } = await locked()
- const t0 = Date.now()
- lockNow(h, 'Mert')
- expect(h.record.control).toMatchObject({ locked: true, lockedUntil: t0 + 15 * MIN, lockStep: 1, wrong: WRONG_PER_LINK })
- expect(t.notices().at(-1)).toMatchObject({ kind: 'control-locked', by: 'Mert', until: t0 + 15 * MIN })
- expect(t.s.list()[0].control).toEqual({ enabled: true, locked: true, lockedUntil: t0 + 15 * MIN })
- await vi.advanceTimersByTimeAsync(15 * MIN - 1)
- expect(h.record.control?.locked).toBe(true)
- expect(h.hooks).toEqual([])
- await vi.advanceTimersByTimeAsync(1)
- expect(h.record.control).toMatchObject({ locked: false, lockedUntil: null, wrong: 0, lockStep: 1 })
- expect(h.hooks).toEqual(['allowControl'])
- expect(t.s.list()[0].control).toEqual({ enabled: true, locked: false, lockedUntil: null })
- await flush()
- expect((await t.store.load())[0].control).toMatchObject({ locked: false, lockedUntil: null, wrong: 0, lockStep: 1 })
- })
-
- it('each later lock lasts twice as long, never past 24 h; Allow control again lifts it at once and starts the backoff over', async () => {
- const { t, h, id } = await locked()
- const lasted: number[] = []
- for (let i = 0; i < 9; i++) {
- lockNow(h)
- lasted.push((h.record.control!.lockedUntil as number) - Date.now())
- await vi.advanceTimersByTimeAsync(lasted.at(-1)!)
- expect(h.record.control?.locked).toBe(false)
- }
- expect(lasted.map((ms) => ms / MIN)).toEqual([15, 30, 60, 120, 240, 480, 960, 1440, 1440])
- lockNow(h)
- expect(await t.s.allowControl(id)).toBe(true)
- expect(h.record.control).toMatchObject({ locked: false, lockedUntil: null, wrong: 0, lockStep: 0 })
- // The pending lift finds nothing to do when its time comes.
- const hooks = h.hooks.length
- await vi.advanceTimersByTimeAsync(25 * HOUR)
- expect(h.hooks.length).toBe(hooks)
- lockNow(h)
- expect((h.record.control!.lockedUntil as number) - Date.now()).toBe(15 * MIN)
- })
-
- it('a restart neither lifts a lock early nor makes it permanent', async () => {
- const { t, h } = await locked()
- const t0 = Date.now()
- lockNow(h, 'Mert')
- await flush()
- await t.s.shutdown()
- await vi.advanceTimersByTimeAsync(5 * MIN)
- const again = service({ store: new WatchLinkStore({ file: t.file }) })
- await again.s.init()
- const h2 = again.hosts.made[0]
- expect(h2.record.control).toMatchObject({ locked: true, lockedUntil: t0 + 15 * MIN, wrong: WRONG_PER_LINK, lockStep: 1 })
- await vi.advanceTimersByTimeAsync(10 * MIN)
- expect(h2.record.control).toMatchObject({ locked: false, lockedUntil: null, wrong: 0, lockStep: 1 })
- expect(h2.hooks).toEqual(['allowControl'])
- })
-
- it('a restart after the lock should have lifted lifts it BEFORE the host is built (it starts from a count of 0), and saves that', async () => {
- const { t, h } = await locked()
- lockNow(h)
- await flush()
- await t.s.shutdown()
- await vi.advanceTimersByTimeAsync(2 * HOUR)
- const again = service({ store: new WatchLinkStore({ file: t.file }) })
- await again.s.init()
- const h2 = again.hosts.made[0]
- // The host was handed a record already lifted: nothing to tell it.
- expect(h2.record.control).toMatchObject({ locked: false, lockedUntil: null, wrong: 0, lockStep: 1 })
- expect(h2.hooks).toEqual([])
- await flush()
- expect((await again.store.load())[0].control).toMatchObject({ locked: false, wrong: 0, lockStep: 1 })
- })
-
- it('a lock written before timed locks (no lift time) keeps its meaning: it waits for the owner', async () => {
- vi.useFakeTimers()
- const t = service({ hashPassword: fastHash })
- const r = await t.s.create(ctlReq({ ttlSeconds: 0 }))
- if (!r.ok) throw new Error(r.error)
- const old = t.hosts.made[0].record
- await t.s.shutdown()
- const legacy = { ...old, control: { enabled: true, salt: old.control!.salt, hash: old.control!.hash, locked: true, wrong: WRONG_PER_LINK } }
- await new WatchLinkStore({ file: t.file }).save([legacy])
- const again = service({ store: new WatchLinkStore({ file: t.file }) })
- await again.s.init()
- const h = again.hosts.made[0]
- expect(h.record.control).toMatchObject({ locked: true, lockedUntil: null })
- expect(again.s.list()[0].control).toEqual({ enabled: true, locked: true, lockedUntil: null })
- await vi.advanceTimersByTimeAsync(400 * HOUR)
- expect(h.record.control?.locked).toBe(true)
- expect(h.hooks).toEqual([])
- expect(await again.s.allowControl(r.link.linkId)).toBe(true)
- expect(h.record.control).toMatchObject({ locked: false, lockStep: 0 })
- })
-
- it('a lift time further off than 24 h (the clock went back, a hand edit) is brought in to 24 h from now', async () => {
- const { t, h } = await locked()
- lockNow(h)
- await flush()
- await t.s.shutdown()
- const saved = (await new WatchLinkStore({ file: t.file }).load())[0]
- await new WatchLinkStore({ file: t.file }).save([{ ...saved, control: { ...saved.control!, lockedUntil: Date.now() + 400 * HOUR } }])
- const again = service({ store: new WatchLinkStore({ file: t.file }) })
- await again.s.init()
- const h2 = again.hosts.made[0]
- expect(h2.record.control?.lockedUntil).toBe(Date.now() + 24 * HOUR)
- await vi.advanceTimersByTimeAsync(24 * HOUR)
- expect(h2.record.control?.locked).toBe(false)
- })
- })
-
- it('a new password and Allow control again reset the count, on the record and on disk', async () => {
- const t = service({ hashPassword: fastHash })
- const r = await t.s.create(ctlReq())
- if (!r.ok) throw new Error(r.error)
- const h = t.hosts.made[0]
- for (let n = 1; n <= 5; n++) h.deps.onWrongAttempt(n)
- expect(await t.s.setPassword(r.link.linkId, NEW_PW)).toBe(true)
- expect(h.record.control?.wrong).toBe(0)
- expect((await t.store.load())[0].control?.wrong).toBe(0)
- for (let n = 1; n <= WRONG_PER_LINK; n++) h.deps.onWrongAttempt(n)
- h.deps.onControlLocked()
- expect(await t.s.allowControl(r.link.linkId)).toBe(true)
- expect(h.record.control).toMatchObject({ locked: false, wrong: 0 })
- expect((await t.store.load())[0].control).toMatchObject({ locked: false, wrong: 0 })
- })
-
- it('a viewer taking control tells the owner, under the name it gave (bidi stripped)', async () => {
- const t = service()
- const r = await t.s.create(ctlReq())
- if (!r.ok) throw new Error(r.error)
- t.hosts.made[0].deps.onControlTaken('E\u202eve')
- expect(t.notices().at(-1)).toEqual({ kind: 'control-taken', linkId: r.link.linkId, nodeId: 'n1', title: 'build', name: 'Eve' })
- await flush()
- expect(t.states().length).toBeGreaterThan(0)
- })
-
- it("the owner's view carries each viewer's controlling and typing from the host, and the link's control state", async () => {
- const t = service()
- const r = await t.s.create(ctlReq())
- if (!r.ok) throw new Error(r.error)
- t.hosts.made[0].viewers = [
- { viewerId: 'v-1', name: 'Ada', joinedAt: 5, waiting: false, controlling: true, typing: true },
- { viewerId: 'v-2', name: null, joinedAt: 6, waiting: false, controlling: false, typing: false }
- ]
- expect(t.s.list()[0].viewers.map((v) => [v.controlling, v.typing])).toEqual([[true, true], [false, false]])
- expect(t.s.list()[0].control).toEqual({ enabled: true, locked: false, lockedUntil: null })
- })
-})
-
-describe('createWatchLinkService — the owner controls a Control link', () => {
- it('setControl writes enabled, persists it and tells the host; refused for anything but a live Control link', async () => {
- const t = service()
- const r = await t.s.create(ctlReq())
- const v = await t.s.create(req({ role: 'commenter', nodeId: 'n2' }))
- if (!r.ok || !v.ok) throw new Error('create failed')
- const h = t.hosts.made[0]
- expect(await t.s.setControl(r.link.linkId, false)).toBe(true)
- expect(h.hooks).toEqual(['controlChanged'])
- expect((await t.store.load()).find((l) => l.linkId === r.link.linkId)?.control?.enabled).toBe(false)
- await flush()
- expect(t.states().at(-1)?.find((l) => l.linkId === r.link.linkId)?.control).toEqual({ enabled: false, locked: false, lockedUntil: null })
- expect(await t.s.setControl(r.link.linkId, true)).toBe(true)
- expect(h.hooks).toEqual(['controlChanged', 'controlChanged'])
- // Not a Control link, an unknown link, an ended one.
- expect(await t.s.setControl(v.link.linkId, false)).toBe(false)
- expect(await t.s.setControl('Nope000000000000000000', false)).toBe(false)
- await t.s.revoke(r.link.linkId)
- expect(await t.s.setControl(r.link.linkId, false)).toBe(false)
- expect(t.hosts.made[1].hooks).toEqual([])
- })
-
- it('setPassword checks the new password, swaps the hash, persists, and demotes every controller; the old one stops working', async () => {
- const t = service()
- const r = await t.s.create(ctlReq())
- if (!r.ok) throw new Error(r.error)
- const h = t.hosts.made[0]
- const before = { ...(await t.store.load())[0].control! }
- for (const bad of ['short', 'abcdefg\n', 'x'.repeat(129), 12345678]) {
- expect(await t.s.setPassword(r.link.linkId, bad as string)).toBe(false)
- }
- expect(h.hooks).toEqual([])
- expect(await t.s.setPassword(r.link.linkId, NEW_PW)).toBe(true)
- expect(h.hooks).toEqual(['passwordChanged'])
- const after = (await t.store.load())[0].control!
- expect(after.salt).not.toBe(before.salt)
- expect(after.hash).not.toBe(before.hash)
- expect(readFileSync(t.file, 'utf8')).not.toContain(NEW_PW)
- // The host checks against the CURRENT hash.
- expect(await h.deps.verifyPassword(NEW_PW)).toBe(true)
- expect(await h.deps.verifyPassword(PW)).toBe(false)
- const v = await t.s.create(req({ role: 'viewer', nodeId: 'n2' }))
- if (!v.ok) throw new Error(v.error)
- expect(await t.s.setPassword(v.link.linkId, NEW_PW)).toBe(false)
- })
-
- it('allowControl clears the lock, persists it and tells the host', async () => {
- const t = service({ hashPassword: fastHash })
- const r = await t.s.create(ctlReq())
- if (!r.ok) throw new Error(r.error)
- const h = t.hosts.made[0]
- h.deps.onControlLocked()
- expect(await t.s.allowControl(r.link.linkId)).toBe(true)
- expect(h.hooks).toEqual(['allowControl'])
- expect((await t.store.load())[0].control?.locked).toBe(false)
- expect(t.s.list()[0].control).toEqual({ enabled: true, locked: false, lockedUntil: null })
- expect(await t.s.allowControl('Nope000000000000000000')).toBe(false)
- })
-
- // THE BRAKE HOLDS (final review, Important 1): a change that NARROWS access is the owner's emergency
- // brake. It stays in force whatever the disk does, and the owner is told 'unsaved' (applied now, gone
- // at a restart); the next write that lands carries it. A widening still changes nothing on a failure.
- function snapStore(o: { save: () => Promise<SaveOutcome> }) {
- /** What each write carried for the first record, copied AT CALL TIME (the store snapshots then). */
- const written: (WatchLinkRecord['control'] | undefined)[] = []
- const f = fakeStore({
- save: (recs) => {
- written.push(recs[0]?.control ? { ...recs[0].control } : undefined)
- return o.save()
- }
- })
- return { ...f, written }
- }
-
- it("typing OFF whose write fails stays off at the host and in memory, answers 'unsaved', and the next write that lands carries it", async () => {
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
- let outcome: SaveOutcome = 'saved'
- const f = snapStore({ save: async () => outcome })
- const t = service({ store: f.store, hashPassword: fastHash })
- const r = await t.s.create(ctlReq())
- if (!r.ok) throw new Error(r.error)
- const id = r.link.linkId
- const h = t.hosts.made[0]
- outcome = 'failed'
- const saves = f.saves.length
- expect(await t.s.setControl(id, false)).toBe('unsaved')
- // Never undone: the record the host reads, the owner's view, and the host told once.
- expect(h.record.control?.enabled).toBe(false)
- expect(t.s.list()[0].control).toEqual({ enabled: false, locked: false, lockedUntil: null })
- expect(h.hooks).toEqual(['controlChanged'])
- expect(f.saves.length).toBe(saves + 1) // no "corrected" list queued behind it
- expect(f.written.at(-1)?.enabled).toBe(false)
- // The next write that lands (any change: here a second link) carries the narrowed state.
- outcome = 'saved'
- const other = await t.s.create(req({ nodeId: 'n2' }))
- expect(other.ok).toBe(true)
- expect(f.written.at(-1)?.enabled).toBe(false)
- expect(t.s.list().find((l) => l.linkId === id)?.control).toEqual({ enabled: false, locked: false, lockedUntil: null })
- expect(allLogged([warn])).not.toContain(PW)
- warn.mockRestore()
- })
-
- it("a new password whose write fails is in force — the old one refused, the new one opens — answers 'unsaved', and the next write that lands carries its hash", async () => {
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
- let outcome: SaveOutcome = 'saved'
- const f = snapStore({ save: async () => outcome })
- const t = service({ store: f.store })
- const r = await t.s.create(ctlReq())
- if (!r.ok) throw new Error(r.error)
- const id = r.link.linkId
- const h = t.hosts.made[0]
- const before = { ...h.record.control! }
- outcome = 'failed'
- expect(await t.s.setPassword(id, NEW_PW)).toBe('unsaved')
- expect(h.hooks).toEqual(['passwordChanged']) // every controller demoted, never re-told
- expect(await h.deps.verifyPassword(PW)).toBe(false)
- expect(await h.deps.verifyPassword(NEW_PW)).toBe(true)
- const now = h.record.control!
- expect(now.hash).not.toBe(before.hash)
- outcome = 'saved'
- h.deps.onControlLocked() // any later write: this one is the lock's
- await flush()
- expect(f.written.at(-1)).toMatchObject({ salt: now.salt, hash: now.hash, locked: true })
- for (const secret of [PW, NEW_PW, now.salt, now.hash]) expect(allLogged([warn])).not.toContain(secret)
- warn.mockRestore()
- })
-
- it("a narrowing whose write HANGS is bounded: 'unsaved' at the bound, still in force, and the next write that lands carries it", async () => {
- vi.spyOn(console, 'warn').mockImplementation(() => {})
- let held: ReturnType<typeof deferred<SaveOutcome>> | null = null
- const f = snapStore({ save: () => (held ? held.promise : Promise.resolve('saved')) })
- const t = service({ store: f.store, persistTimeoutMs: 20, hashPassword: fastHash })
- const r = await t.s.create(ctlReq())
- if (!r.ok) throw new Error(r.error)
- const id = r.link.linkId
- const h = t.hosts.made[0]
- held = deferred<SaveOutcome>()
- expect(await t.s.setControl(id, false)).toBe('unsaved')
- expect(h.record.control?.enabled).toBe(false)
- expect(h.hooks).toEqual(['controlChanged'])
- expect(await t.s.setPassword(id, NEW_PW)).toBe('unsaved')
- expect(h.hooks).toEqual(['controlChanged', 'passwordChanged'])
- const after = { ...h.record.control! }
- expect(t.s.list()[0].control).toEqual({ enabled: false, locked: false, lockedUntil: null })
- // The disk answers again: the hung writes land, and the next write carries both changes.
- const d = held
- held = null
- d.resolve('failed')
- await flush()
- const other = await t.s.create(req({ nodeId: 'n2' }))
- expect(other.ok).toBe(true)
- expect(f.written.at(-1)).toMatchObject({ enabled: false, salt: after.salt, hash: after.hash })
- expect(h.record.control).toMatchObject({ enabled: false, salt: after.salt, hash: after.hash })
- })
-
- it('a widening whose write fails changes nothing and answers false; a lock is never undone', async () => {
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
- let outcome: SaveOutcome = 'saved'
- const f = fakeStore({ save: async () => outcome })
- const t = service({ store: f.store, hashPassword: fastHash })
- const r = await t.s.create(ctlReq())
- if (!r.ok) throw new Error(r.error)
- const id = r.link.linkId
- const h = t.hosts.made[0]
- outcome = 'failed'
- h.deps.onControlLocked() // its own write fails too: the lock holds
- expect(await t.s.allowControl(id)).toBe(false)
- expect(h.hooks).toEqual([]) // a widening the write refused never reached the host
- expect(t.s.list()[0].control).toMatchObject({ enabled: true, locked: true })
- warn.mockRestore()
- })
-})
-
-// A change that NARROWS access (typing off, a new password) reaches the host at once, before the write.
-// One that WIDENS it (typing on, allow again) reaches it only once the write landed: a viewer must never
-// unlock and type during a write the owner is then told failed.
-describe('createWatchLinkService — owner changes, by direction', () => {
- async function heldWrites(o: { hashPassword?: Opts['hashPassword'] } = {}) {
- let held: ReturnType<typeof deferred<SaveOutcome>> | null = null
- // What each write carried, copied AT CALL TIME (the store snapshots then; the record objects in
- // `f.saves` are the live ones and would show later changes).
- const written: (WatchLinkRecord['control'] | undefined)[] = []
- const f = fakeStore({
- save: (recs) => {
- written.push(recs[0]?.control ? { ...recs[0].control } : undefined)
- return held ? held.promise : Promise.resolve('saved')
- }
- })
- const t = service({ store: f.store, hashPassword: o.hashPassword ?? fastHash })
- const r = await t.s.create(ctlReq())
- if (!r.ok) throw new Error(r.error)
- const h = t.hosts.made[0]
- return {
- t, f, h, written, id: r.link.linkId,
- hold: () => (held = deferred<SaveOutcome>()),
- release: (o: SaveOutcome) => {
- const d = held!
- held = null
- d.resolve(o)
- }
- }
- }
-
- it('typing OFF reaches the host before the write lands', async () => {
- const x = await heldWrites()
- x.hold()
- const off = x.t.s.setControl(x.id, false)
- await flush()
- expect(x.h.record.control?.enabled).toBe(false)
- expect(x.h.hooks).toEqual(['controlChanged'])
- x.release('saved')
- expect(await off).toBe(true)
- })
-
- it('typing ON waits for the write: the record the host reads stays off throughout, and a failed write never turns it on', async () => {
- const x = await heldWrites()
- expect(await x.t.s.setControl(x.id, false)).toBe(true)
- x.h.hooks.length = 0
- x.hold()
- const on = x.t.s.setControl(x.id, true)
- await flush()
- // What an unlock checks (the host reads the record live): still off while the write is in flight.
- expect(x.h.record.control?.enabled).toBe(false)
- expect(x.h.hooks).toEqual([])
- expect(x.t.s.list()[0].control).toEqual({ enabled: false, locked: false, lockedUntil: null })
- // …and yet the write carries the change.
- expect(x.written.at(-1)?.enabled).toBe(true)
- x.release('failed')
- expect(await on).toBe(false)
- expect(x.h.record.control?.enabled).toBe(false)
- expect(x.h.hooks).toEqual([])
- expect(x.written.at(-1)?.enabled).toBe(false) // the list as it is, queued behind
- })
-
- it('typing ON that lands: applied, then the host is told', async () => {
- const x = await heldWrites()
- expect(await x.t.s.setControl(x.id, false)).toBe(true)
- x.h.hooks.length = 0
- x.hold()
- const on = x.t.s.setControl(x.id, true)
- await flush()
- expect(x.h.hooks).toEqual([])
- x.release('saved')
- expect(await on).toBe(true)
- expect(x.h.record.control?.enabled).toBe(true)
- expect(x.h.hooks).toEqual(['controlChanged'])
- expect(x.t.s.list()[0].control).toEqual({ enabled: true, locked: false, lockedUntil: null })
- })
-
- it('allowControl waits for the write too: still locked throughout, and a failed write never unlocks it', async () => {
- const x = await heldWrites()
- x.h.deps.onControlLocked()
- await flush()
- x.hold()
- const allow = x.t.s.allowControl(x.id)
- await flush()
- expect(x.h.record.control?.locked).toBe(true)
- expect(x.h.hooks).toEqual([])
- x.release('failed')
- expect(await allow).toBe(false)
- expect(x.h.record.control?.locked).toBe(true)
- expect(x.h.hooks).toEqual([])
- x.hold()
- const again = x.t.s.allowControl(x.id)
- await flush()
- expect(x.h.record.control?.locked).toBe(true)
- x.release('saved')
- expect(await again).toBe(true)
- expect(x.h.record.control?.locked).toBe(false)
- expect(x.h.hooks).toEqual(['allowControl'])
- })
-
- it('typing ON then OFF while the ON is still being written: OFF wins, and the disk ends off', async () => {
- const x = await heldWrites()
- expect(await x.t.s.setControl(x.id, false)).toBe(true)
- x.h.hooks.length = 0
- x.hold()
- const on = x.t.s.setControl(x.id, true)
- await flush()
- expect(await x.t.s.setControl(x.id, false)).toBe(true) // the later click
- x.release('saved')
- expect(await on).toBe(true) // written, then replaced by the later change
- expect(x.h.record.control?.enabled).toBe(false)
- expect(x.h.hooks).toEqual([])
- await vi.waitFor(() => expect(x.written.at(-1)?.enabled).toBe(false))
- })
-
- it('a write issued while a widening is in flight cannot leave the disk behind memory', async () => {
- const x = await heldWrites()
- expect(await x.t.s.setControl(x.id, false)).toBe(true)
- x.hold()
- const on = x.t.s.setControl(x.id, true)
- await flush()
- const n = x.written.length
- // A lock writes the LIVE record (still off) behind the write that carries ON — and touches
- // another field, so the ON keeps its turn and is applied once its write lands.
- x.h.deps.onControlLocked()
- expect(x.written.length).toBe(n + 1)
- expect(x.written.at(-1)).toMatchObject({ enabled: false, locked: true })
- x.release('saved')
- expect(await on).toBe(true)
- expect(x.h.record.control).toMatchObject({ enabled: true, locked: true })
- // The last write is the record as memory holds it, not the lock's older snapshot.
- await vi.waitFor(() => expect(x.written.at(-1)).toEqual({ ...x.h.record.control }))
- })
-})
-
-describe('createWatchLinkService — one bound on scrypt', () => {
- it('a FIFO gate: a third task waits for a slot, slots go in arrival order, a failure frees its slot', async () => {
- const gate = createFifoGate(2)
- const started: string[] = []
- const held = new Map<string, ReturnType<typeof deferred<string>>>()
- const run = (k: string) =>
- gate(() => {
- started.push(k)
- const d = deferred<string>()
- held.set(k, d)
- return d.promise
- })
- const out = ['a', 'b', 'c', 'd', 'e'].map((k) => run(k).catch((e: Error) => `x${e.message}`))
- await flush()
- expect(started).toEqual(['a', 'b'])
- held.get('b')!.reject(new Error('b'))
- await flush()
- expect(started).toEqual(['a', 'b', 'c'])
- held.get('a')!.resolve('a')
- await flush()
- expect(started).toEqual(['a', 'b', 'c', 'd'])
- held.get('c')!.resolve('c')
- held.get('d')!.resolve('d')
- await flush()
- held.get('e')!.resolve('e')
- expect(await Promise.all(out)).toEqual(['a', 'xb', 'c', 'd', 'e'])
- // A task that throws synchronously frees its slot too.
- const t2 = createFifoGate(1)
- await expect(
- t2(() => {
- throw new Error('sync')
- })
- ).rejects.toThrow('sync')
- expect(await t2(async () => 'next')).toBe('next')
- })
-
- it("every link host's password check goes through ONE 2-slot gate, in order; a new password's hash waits its turn too", async () => {
- const started: string[] = []
- const held = new Map<string, ReturnType<typeof deferred<boolean>>>()
- const t = service({
- hashPassword: async (pw) => {
- started.push(`hash:${pw}`)
- return fastHash()
- },
- verifyPassword: (pw) => {
- started.push(pw)
- const d = deferred<boolean>()
- held.set(pw, d)
- return d.promise
- }
- })
- for (const nodeId of ['n1', 'n2', 'n1']) expect((await t.s.create(ctlReq({ nodeId }))).ok).toBe(true)
- started.length = 0
- const [a, b, c] = t.hosts.made
- const results = [a.deps.verifyPassword('pa'), b.deps.verifyPassword('pb'), c.deps.verifyPassword('pc')]
- const changed = t.s.setPassword(a.record.linkId, NEW_PW)
- await flush()
- expect(started).toEqual(['pa', 'pb'])
- held.get('pb')!.resolve(false)
- await flush()
- expect(started).toEqual(['pa', 'pb', 'pc'])
- held.get('pa')!.resolve(true)
- await flush()
- expect(started).toEqual(['pa', 'pb', 'pc', `hash:${NEW_PW}`])
- held.get('pc')!.resolve(true)
- expect(await Promise.all(results)).toEqual([true, false, true])
- expect(await changed).toBe(true)
- })
-})
-
-describe('createWatchLinkService — a password check queued behind a new password', () => {
- it('reads the NEW hash when it runs: the old password fails, the new one opens', async () => {
- const holds = new Map<string, ReturnType<typeof deferred<boolean>>>()
- const seen: { pw: string; hash: string }[] = []
- const t = service({
- verifyPassword: (pw, h) => {
- seen.push({ pw, hash: h.hash })
- if (pw.startsWith('hold-')) {
- const d = deferred<boolean>()
- holds.set(pw, d)
- return d.promise
- }
- return verifyControlPassword(pw, h)
- }
- })
- for (const nodeId of ['n1', 'n2', 'n1']) expect((await t.s.create(ctlReq({ nodeId }))).ok).toBe(true)
- const [a, b, c] = t.hosts.made
- const oldHash = a.record.control!.hash
- // Both slots busy; then the new password's hash, then two checks on link A, queue in that order.
- const busy = [b.deps.verifyPassword('hold-b'), c.deps.verifyPassword('hold-c')]
- await flush()
- const changed = t.s.setPassword(a.record.linkId, NEW_PW)
- const oldTry = a.deps.verifyPassword(PW)
- const newTry = a.deps.verifyPassword(NEW_PW)
- await flush()
- expect(seen.map((x) => x.pw)).toEqual(['hold-b', 'hold-c'])
- // One slot frees: the hash runs in it while the other stays busy, so both checks are still queued
- // when the new password lands; the first takes the hash's slot after it.
- holds.get('hold-b')!.resolve(false)
- expect(await changed).toBe(true)
- expect(await oldTry).toBe(false)
- holds.get('hold-c')!.resolve(false)
- expect(await newTry).toBe(true)
- const newHash = a.record.control!.hash
- expect(newHash).not.toBe(oldHash)
- expect(seen.filter((x) => x.pw === PW || x.pw === NEW_PW).map((x) => x.hash)).toEqual([newHash, newHash])
- await Promise.all(busy)
- })
-})
-
-describe('createWatchLinkService — controlSupport', () => {
- it("answers the shell's check; anything else, a throw, an unsafe id or no check at all is unknown", () => {
- const answers: Record<string, unknown> = { n1: 'ok', n2: 'unsupported', n3: 'maybe' }
- const t = service({ controlSupport: (id) => answers[id] as ControlSupport })
- expect(t.s.controlSupport('n1')).toBe('ok')
- expect(t.s.controlSupport('n2')).toBe('unsupported')
- expect(t.s.controlSupport('n3')).toBe('unknown')
- expect(t.s.controlSupport('../x')).toBe('unknown')
- expect(t.s.controlSupport(7 as unknown as string)).toBe('unknown')
- const boom = service({
- controlSupport: () => {
- throw new Error('x')
- }
- })
- expect(boom.s.controlSupport('n1')).toBe('unknown')
- expect(service().s.controlSupport('n1')).toBe('unknown')
- })
-})
-
-// A sanitizer whose character class renders as `[-]` cannot be reviewed by reading it (R46/M1): the
-// owner-side files spell every bidi and zero-width character as an escape.
-describe('no literal bidi or zero-width characters in the live-link owner sources', () => {
- const LITERAL = new RegExp('[\\u061c\\u200b-\\u200f\\u202a-\\u202e\\u2066-\\u2069\\ufeff]')
- for (const f of ['service.ts', 'service.test.ts', 'pty-seam.ts', '../../shared/watch-link-types.ts', '../../shared/presence.ts']) {
- it(f, () => {
- expect(LITERAL.test(readFileSync(join(__dirname, f), 'utf8'))).toBe(false)
- })
- }
-})
diff --git a/src/core/watch-link/service.ts b/src/core/watch-link/service.ts
deleted file mode 100644
index 92d8a1a1f..000000000
--- a/src/core/watch-link/service.ts
+++ /dev/null
@@ -1,1222 +0,0 @@
-// The live-link registry (docs/live-links.md): the owner's side of every link this machine hosts —
-// at most MAX_LINKS_PER_MACHINE, each with its link host (link-host.ts). Records are persisted
-// (spec D8) and resumed at launch. Owner state goes to OWNER clients only (`sendToOwners`): every
-// view carries the link's URL, and the URL carries the secret.
-//
-// A LINK ENDS on: the owner's Stop (`revoke`, no notice — the owner did it), Stop all (`revokeAll`,
-// one server call, awaited and reported — it is what reaches other machines' links), its expiry (a timer, plus a re-check on every host change because timers are
-// monotonic and a closed lid pauses them — G24), the node leaving every project, or the server saying
-// it is gone (a mint or status answering 410 — `onGone`, which does raise a notice).
-//
-// NODE GONE IS TRI-STATE (controller ruling R40). `nodeState` answers present / absent / unknown, and
-// only ABSENT ends a link and revokes it server-side: an empty answer during the launch-time workspace
-// load, or for a node in a project whose file was not read this run, is not evidence the node is gone,
-// and a revoke cannot be undone. `init()` first waits for the workspace load it is handed, then keeps
-// (and hosts) a link whose node is unknown — its join is join-only, so a node that never comes back
-// costs a waiting viewer, never a spawned session. Create requires PRESENT. The same check runs before
-// every join (R29): the link host is registry-free, so the registry wraps its `pty.join`.
-//
-// PERSISTENCE never blocks the owner (Task 9 note B, spec revoke order). Ending a link removes the
-// record and ISSUES the write (the store snapshots at call time) before the sessions end, and never
-// waits for it before the server revoke: a disk that hangs must not keep a revoked link's viewers
-// connected or its server row alive. A create does wait for its write (a link that cannot be
-// written must not exist: the server row is revoked), but no longer than PERSIST_TIMEOUT_MS.
-// A links file that could not be read (WatchLinkStoreUnreadable) turns this run MEMORY-ONLY: the
-// store is latched and never written, links still work and end at quit, and the owner is told on
-// every create (R22, R42c). A keychain that refuses to SEAL is narrower (R45): the store still writes
-// every link it holds a sealed form of — read at boot or sealed earlier this run — so only a link that
-// was never sealed (the one just created) is not saved; it answers memory-only, and the owner is told.
-// `init()` writes only when it actually pruned something (R42a), so a boot never rewrites the file.
-//
-// ENTITLEMENT. A host never mints with an empty entitlement (the API would answer 400, which stops
-// minting for good): it answers itself a local refusal, and `onEntitlementChanged` re-arms every host
-// the API refused once the license layer reports a change — a 7-day token expiring under a running
-// link is the ordinary case (R41).
-//
-// CONTROL LINKS (role 'controller'). The password is checked by `controlPasswordProblem` and hashed
-// (scrypt, ./password.ts) BEFORE the server row is created, so a hash that fails creates nothing; only
-// {salt, hash} is kept, never the plaintext, and nothing logged carries the password, the hash or the
-// salt. Every scrypt run of this process — the hosts' unlock checks and the owner's new passwords — goes
-// through ONE FIFO gate of SCRYPT_SLOTS (each run is ~32 MiB and ~80 ms on libuv's 4-thread pool, and
-// unlock attempts arrive from strangers): a run waits for a slot, it is never refused. The lock the
-// link host asks for (`onControlLocked`) is set on the record synchronously — the host reads the record
-// live — and is never undone by a failed write. So is the link-wide count of wrong attempts the host
-// reports (`onWrongAttempt`): it goes on the record and is written, at most WRONG_PER_LINK writes per
-// link (the last rides the lock's), so an app restart does not reset it; a new password and Allow
-// control again reset it. The owner's changes go by DIRECTION. One that NARROWS access (typing off, a
-// new password) is the owner's brake: it reaches the record and the host at once — a leaked password or
-// an unwanted typist must not wait on the disk — and is NEVER undone: a write that fails or does not
-// answer within PERSIST_TIMEOUT_MS answers 'unsaved' (in force now, undone by a restart unless a later
-// write lands — every write carries the whole list from memory, so the next one that lands saves it;
-// Stop ends it for good). One that WIDENS it (typing on, allow again) is written first, from a copy of
-// the record, and reaches the record and the host only once that write landed: nobody can unlock and
-// type during a write the owner is then told failed, which answers false. The owner is never told a
-// change was kept that the next launch would not have. A later change to the same field supersedes an
-// earlier one still being written (its late apply is skipped).
-//
-// AN UNLIMITED LINK (`ttlSeconds` 0) has `expiresAt: null`: no expiry timer, no expiry check on a host
-// change, never pruned for time at launch. It ends like any link otherwise, and when its owner's Pro
-// lapses the server refuses its host-token mint (402) — the host stops minting and the view says
-// `refused`, the same state as any refused mint.
-//
-// THE SERVER EDITION registers this same service with `unsupported: true` until it has a license layer
-// (R43): create answers `unsupported`, list answers [], nothing is loaded, hosted or revoked. The same
-// mode is what a Server Edition that does not own its data dir would need (G15).
-//
-// Nothing here throws out of a callback or a void promise; every timer is cleared by `end`/`shutdown`.
-import type { CorePlatform } from '../platform'
-import type { WorkspaceStore } from '../workspace-store'
-import { IPC } from '../../shared/ipc'
-import { isSafeNodeId } from '../../shared/safe-id'
-import { formatWatchLink } from '../../shared/watch-link/link'
-import { deriveWatchLinkKeys, newWatchLinkSecret, sha256Hex } from '../../shared/watch-link/keys'
-import type { WatchChatMessage, WatchLinkEndReason } from '../../shared/watch-link/protocol'
-import {
- LABEL_MAX,
- MAX_LINKS_PER_MACHINE,
- TITLE_MAX,
- WATCH_LINK_TTLS,
- stripBidiControls,
- type ControlSupport,
- type ControlChangeResult,
- type CreateWatchLinkError,
- type CreateWatchLinkRequest,
- type CreateWatchLinkResult,
- type RevokeAllOutcome,
- type WatchLinkNotice,
- type WatchLinkView,
- type WatchLinkViewerView
-} from '../../shared/watch-link-types'
-import { controlPasswordProblem } from '../../shared/watch-link-password'
-import type { HostTokenResult, WatchLinkApi as WatchLinkApiClient } from './api'
-import { WRONG_PER_LINK, createLinkHost, type LinkHost, type QuietClients, type WatchPty } from './link-host'
-import type { HistoryRead } from './history'
-import { hashControlPassword, verifyControlPassword, type ControlPasswordHash } from './password'
-import {
- CONTROL_LOCK_STEP_MAX,
- WatchLinkStoreUnreadable,
- controlLockMs,
- type WatchLinkControlRecord,
- type WatchLinkRecord,
- type WatchLinkStore
-} from './store'
-import type { RelayTransport } from '../relay/relay-socket'
-import { errorText } from '../../shared/error-text'
-import { CONTROL_LOCK_MAX_MS } from '../../shared/watch-link/protocol'
-
-/** setTimeout's own ceiling (a longer delay fires at once). A link lives ≤ 24 h, far below it. */
-const MAX_DELAY_MS = 2_147_483_647
-/** The longest a create waits for its local write (or for the links file's boot load). */
-export const PERSIST_TIMEOUT_MS = 10_000
-/** The longest `init()` waits for the boot workspace load before deciding with the nodes it cannot
- * place yet read as unknown (which keeps their links: the safe side). */
-export const WORKSPACE_READY_TIMEOUT_MS = 10_000
-/** Concurrent scrypt runs (unlock checks and new passwords) this process allows. */
-export const SCRYPT_SLOTS = 2
-
-export type WatchLinkNodeState = 'present' | 'absent' | 'unknown'
-
-export interface WatchLinkServiceDeps {
- api: WatchLinkApiClient
- relayUrl: string
- store: Pick<WatchLinkStore, 'load' | 'save' | 'discardOpaque' | 'opaqueCount'>
- /** The stored Pro entitlement token, or null. Travels only in the API client's JSON body. */
- entitlement(): string | null
- /** False in a build that may not relay (an unpackaged dev build): no create, and resumed links
- * are kept but not hosted (G21) — a dev run must not host the installed app's links. */
- relayAllowed(): boolean
- /** Is the node in some project (present), provably in none (absent), or cannot be told (unknown)?
- * The shells answer with `workspaceNodeState`. */
- nodeState(nodeId: string): WatchLinkNodeState
- /** Resolves once the workspace index has been read: `init()` decides nothing before it (R40). */
- workspaceReady?(): Promise<unknown>
- clients: QuietClients
- pty: WatchPty
- /** Owner clients only (`sendToOwners`). */
- emit(channel: string, ...args: unknown[]): void
- /** Can this node's terminal take a Control link's input (`PtyManager.nodeControlSupport`)? Absent,
- * throwing or anything else answers `unknown`, which leaves the create to decide. */
- controlSupport?(nodeId: string): ControlSupport
- /** Read-back (`watch:history`): one transcript page of `nodeId`'s conversation ending at `before`
- * (null: the newest), through the SAME reader as the ⌘M panel and the phone's `chat.page`. Rejects
- * on a failed read. The link host cuts every page at the link's creation (./history.ts); the reader
- * knows nothing of links. Absent: viewers are told read-back is not available. */
- history?(nodeId: string, before: number | null): Promise<HistoryRead>
- /** Is `nodeId` an agent whose conversation `history` can read? Rides every join's meta. */
- historySupported?(nodeId: string): boolean
- /** This shell cannot host links (the Server Edition until it has a license layer — R43). */
- unsupported?: boolean
- now?(): number
- setTimeout?(fn: () => void, ms: number): unknown
- clearTimeout?(h: unknown): void
- /** TEST ONLY. */
- persistTimeoutMs?: number
- /** TEST ONLY. */
- workspaceWaitMs?: number
- /** TEST ONLY. */
- createHost?: typeof createLinkHost
- /** TEST ONLY: the relay transport the link hosts dial. */
- transport?: () => RelayTransport
- /** TEST ONLY: scrypt's hash (./password.ts). */
- hashPassword?: (pw: string) => Promise<ControlPasswordHash>
- /** TEST ONLY: scrypt's check (./password.ts). */
- verifyPassword?: (pw: string, h: ControlPasswordHash) => Promise<boolean>
-}
-
-export interface WatchLinkService {
- /** Load and resume the persisted links. Idempotent (one promise); never rejects. */
- init(): Promise<void>
- create(req: unknown): Promise<CreateWatchLinkResult>
- list(): WatchLinkView[]
- revoke(linkId: string): Promise<void>
- /** Stop this machine's links at once, then ask the server to revoke every link of the license and
- * answer what that reached (`RevokeAllOutcome`). Never rejects. */
- revokeAll(): Promise<RevokeAllOutcome>
- kick(linkId: string, viewerId: string): boolean
- sendChat(linkId: string, text: string): WatchChatMessage | null
- chatHistory(linkId: string): WatchChatMessage[]
- /** After every workspace load/save: a node that is now ABSENT ends its links. */
- onWorkspaceChanged(): void
- /** After the license layer reports a change: re-arm every host the API refused. */
- onEntitlementChanged(): void
- /** A live Control link: turn typing on or off (`ControlChangeResult`). False for any other link, or
- * typing ON that could not be saved (then nothing changed); 'unsaved' for typing OFF that could not
- * be saved (it holds all the same). */
- setControl(linkId: string, enabled: boolean): Promise<ControlChangeResult>
- /** A live Control link: replace its password (every controller drops back to watching, the link-wide
- * wrong count starts over). False for a password `controlPasswordProblem` refuses, any other link,
- * or a hash that failed; 'unsaved' for a new password in force that could not be saved. */
- setPassword(linkId: string, pw: string): Promise<ControlChangeResult>
- /** A live Control link locked by wrong passwords: allow unlocking again. False as setControl. */
- allowControl(linkId: string): Promise<boolean>
- /** Whether this node's terminal can take a Control link's input (the create dialog asks). */
- controlSupport(nodeId: string): ControlSupport
- /** Stop every host (`host-stopping`), keep the records for the next launch. Resolves once the
- * last write this service issued has settled (the caller bounds it). */
- shutdown(): Promise<void>
-}
-
-/**
- * The node-gone rule over the workspace store, shared by both shells: present when some project
- * holds the node; absent only when the store has a COMPLETE read of every project
- * (`knownNodeIdsStrict`) and the node is not in it; unknown otherwise (the index not loaded yet, a
- * project file not read this run, an SSH project with no cache, an index rebuilt from nothing this
- * run). The STRICT accessor, never the mirror's `knownNodeIds`: absent here revokes a link for good.
- */
-export function workspaceNodeState(
- store: Pick<WorkspaceStore, 'projectIdsForNode' | 'knownNodeIdsStrict'>,
- nodeId: string
-): WatchLinkNodeState {
- if (store.projectIdsForNode(nodeId).length > 0) return 'present'
- const known = store.knownNodeIdsStrict()
- if (!known) return 'unknown'
- return known.has(nodeId) ? 'present' : 'absent'
-}
-
-// C0/C1 controls and DEL; the bidi controls are `stripBidiControls`'s.
-const CONTROLS = /[\u0000-\u001f\u007f-\u009f]/g
-
-/** A label or title as the owner typed it (or as a git-shared node title says): controls and bidi
- * overrides gone, trimmed, capped at `max` UTF-16 units — the unit the store checks on load —
- * without splitting a surrogate pair. null when nothing is left. */
-function cleanText(raw: unknown, max: number): string | null {
- if (typeof raw !== 'string') return null
- const s = stripBidiControls(raw.replace(CONTROLS, '')).trim()
- let out = ''
- for (const ch of s) {
- if (out.length + ch.length > max) break
- out += ch
- }
- out = out.trim()
- return out || null
-}
-
-/** A create request as the owner sent it: everything checked, the password apart from the request
- * (only a Control link carries one; another role's `password` field is ignored). */
-type ParsedRequest = { req: Omit<CreateWatchLinkRequest, 'password'>; password: string | null }
-
-function parseRequest(raw: unknown): ParsedRequest | 'bad-request' | 'bad-password' {
- if (!raw || typeof raw !== 'object') return 'bad-request'
- const r = raw as Record<string, unknown>
- // `isSafeNodeId` coerces: `12` passes its regex. The type check comes first.
- if (typeof r.nodeId !== 'string' || !isSafeNodeId(r.nodeId)) return 'bad-request'
- if (r.role !== 'viewer' && r.role !== 'commenter' && r.role !== 'controller') return 'bad-request'
- // 0 is Unlimited: no end time.
- if (!(WATCH_LINK_TTLS as readonly unknown[]).includes(r.ttlSeconds)) return 'bad-request'
- const label = cleanText(r.label, LABEL_MAX)
- if (!label) return 'bad-request'
- const title = cleanText(r.title, TITLE_MAX) ?? 'Terminal'
- const req: ParsedRequest['req'] = { nodeId: r.nodeId, role: r.role, ttlSeconds: r.ttlSeconds as CreateWatchLinkRequest['ttlSeconds'], label, title }
- if (r.role !== 'controller') return { req, password: null }
- if (controlPasswordProblem(r.password) !== null) return 'bad-password'
- return { req, password: r.password as string }
-}
-
-/**
- * At most `slots` tasks run at once; the rest wait, and get a slot in the order they asked (FIFO). A
- * task's failure (a rejection, or a throw) frees its slot like a success. Nothing is ever refused.
- */
-export function createFifoGate(slots: number): <T>(task: () => Promise<T>) => Promise<T> {
- let active = 0
- const waiting: (() => void)[] = []
- const release = (): void => {
- const next = waiting.shift()
- if (next) next() // the slot passes straight to the next in line
- else active--
- }
- return <T>(task: () => Promise<T>): Promise<T> =>
- new Promise<T>((resolve, reject) => {
- const run = (): void => {
- let p: Promise<T>
- try {
- p = Promise.resolve(task())
- } catch (err) {
- p = Promise.reject(err)
- }
- p.then(resolve, reject).finally(release)
- }
- if (active < slots) {
- active++
- run()
- } else waiting.push(run)
- })
-}
-
-/** A live Control link's record, with its control state. */
-type ControlRecord = WatchLinkRecord & { control: WatchLinkControlRecord }
-
-/** A chat message as the OWNER is shown it: whatever a viewer wrote, without bidi overrides. */
-function ownerChat(msg: WatchChatMessage): WatchChatMessage {
- return { ...msg, name: stripBidiControls(msg.name), text: stripBidiControls(msg.text) }
-}
-
-/** Send to the machine's OWNER clients only — never a relay peer, never a live link's viewer. */
-export function sendToOwners(
- p: Pick<CorePlatform, 'clientIds' | 'isOwnerClient' | 'sendTo'>,
- channel: string,
- ...args: unknown[]
-): void {
- for (const id of p.clientIds()) if (p.isOwnerClient?.(id) === true) p.sendTo(id, channel, ...args)
-}
-
-/** An error's NAME only: what failed around a password (its hash, its check) may be in the message. */
-const errorName = (err: unknown): string => (err instanceof Error ? err.name : 'not an Error')
-const TIMEOUT = Symbol('timeout')
-
-export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkService {
- const now = deps.now ?? Date.now
- const setT = deps.setTimeout ?? ((fn: () => void, ms: number) => setTimeout(fn, ms))
- const clearT = deps.clearTimeout ?? ((h: unknown) => clearTimeout(h as ReturnType<typeof setTimeout>))
- const createHost = deps.createHost ?? createLinkHost
- const persistTimeoutMs = deps.persistTimeoutMs ?? PERSIST_TIMEOUT_MS
- const workspaceWaitMs = deps.workspaceWaitMs ?? WORKSPACE_READY_TIMEOUT_MS
- const hashPassword = deps.hashPassword ?? hashControlPassword
- const verifyPassword = deps.verifyPassword ?? verifyControlPassword
- // ONE gate for every scrypt run of this service — the process has one — whichever link asks.
- const scrypt = createFifoGate(SCRYPT_SLOTS)
- // A wait on init covers init's own (bounded) workspace wait plus the links file's load: init's
- // bound always fires first, so a slow workspace never reads as a failed write.
- const initWaitMs = workspaceWaitMs + persistTimeoutMs
- const unsupported = deps.unsupported === true
-
- const records = new Map<string, WatchLinkRecord>()
- /** Created server-side, being written: in every write's snapshot (a concurrent write must not drop
- * it from disk), but not yet a link — not listed, not hosted, and no stop path can end it half-way. */
- const writing = new Map<string, WatchLinkRecord>()
- const hosts = new Map<string, LinkHost>()
- const expiry = new Map<string, unknown>()
- /** A timed wrong-password lock's timer, per link (finding L2). */
- const lockTimers = new Map<string, unknown>()
- let initPromise: Promise<void> | null = null
- /** Creates between their cap check and their answer (G17): they count against the cap. A create's
- * record joins `records` only as it answers, so it is never counted twice. */
- let creating = 0
- let stopped = false
- /** The links file could not be read: never write it this run (R22). */
- let storeLatched = false
- /** The last write could not seal (the keychain refused): links live in memory only. */
- let sealRefused = false
- let lastWrite: Promise<unknown> = Promise.resolve()
-
- const fail = (error: CreateWatchLinkError): CreateWatchLinkResult => ({ ok: false, error })
- const warn = (line: string): void => console.warn(`[watch-link] ${line}`)
- const warned = new Set<string>()
- const warnOnce = (kind: string, line: string): void => {
- if (warned.has(kind)) return
- warned.add(kind)
- warn(line)
- }
- const persistentNow = (): boolean => !storeLatched && !sealRefused
-
- function safeEmit(channel: string, ...args: unknown[]): void {
- try {
- deps.emit(channel, ...args)
- } catch (err) {
- warn(`telling the owner failed: ${errorText(err)}`)
- }
- }
- const notice = (n: WatchLinkNotice): void => safeEmit(IPC.watchLinkNotice, n)
-
- function nodeStateOf(nodeId: string): WatchLinkNodeState {
- try {
- const s = deps.nodeState(nodeId)
- return s === 'present' || s === 'absent' ? s : 'unknown'
- } catch {
- return 'unknown' // a check that cannot answer is never evidence of absence
- }
- }
-
- /** `p`'s answer, or TIMEOUT after `ms` (the timer is cleared as soon as `p` settles). A rejection
- * reads as a timeout: either way the caller got no answer. */
- function within<T>(p: Promise<T>, ms: number): Promise<T | typeof TIMEOUT> {
- return new Promise((resolve) => {
- const h = setT(() => resolve(TIMEOUT), ms)
- p.then(
- (v) => {
- clearT(h)
- resolve(v)
- },
- () => {
- clearT(h)
- resolve(TIMEOUT)
- }
- )
- })
- }
-
- function viewOf(r: WatchLinkRecord): WatchLinkView {
- const h = hosts.get(r.linkId)
- // No host: a build that may not relay (G21), or a host that could not be built — nobody can
- // watch it, which is what `refused` says.
- let status: WatchLinkView['status'] = 'refused'
- let viewers: WatchLinkViewerView[] = []
- if (h) {
- try {
- status = h.status()
- viewers = h.viewers().map((v) => ({
- viewerId: v.viewerId,
- name: v.name === null ? null : stripBidiControls(v.name),
- joinedAt: v.joinedAt,
- waiting: v.waiting === true,
- controlling: v.controlling === true,
- typing: v.typing === true
- }))
- } catch (err) {
- warn(`reading a link's state failed: ${errorText(err)}`)
- }
- }
- return {
- linkId: r.linkId,
- nodeId: r.nodeId,
- role: r.role,
- label: stripBidiControls(r.label),
- title: stripBidiControls(r.title),
- createdAt: r.createdAt,
- expiresAt: r.expiresAt,
- url: formatWatchLink(r.linkId, r.secret),
- status,
- viewers,
- control:
- r.role === 'controller' && r.control
- ? {
- enabled: r.control.enabled,
- locked: r.control.locked,
- lockedUntil: r.control.locked && typeof r.control.lockedUntil === 'number' ? r.control.lockedUntil : null
- }
- : null
- }
- }
- const list = (): WatchLinkView[] => (unsupported ? [] : [...records.values()].map(viewOf))
- // Coalesced (R46/M7): ending a link stops its host, whose `stop` reports a change, and then the end
- // reports its own; a shutdown stops every host. One push per synchronous burst — each push carries
- // every link's URL, and the list is read when the push goes out, so it is never stale.
- let statePending = false
- const emitState = (): void => {
- if (statePending) return
- statePending = true
- queueMicrotask(() => {
- statePending = false
- // `formatWatchLink` throws on a record it could not make a URL of. Every record passed its
- // checks (the API client's link-id rule, the store's load rules), but a throw here would be
- // uncaught inside a microtask, so it is caught and reported instead.
- try {
- safeEmit(IPC.watchLinkState, list())
- } catch (err) {
- warn(`listing live links failed: ${errorText(err)}`)
- }
- })
- }
- /** Links this machine holds but cannot host this run (sealed, keychain locked) — they count against
- * the cap like any link (R46/M3). */
- const opaqueHeld = (): number => {
- try {
- return deps.store.opaqueCount()
- } catch {
- return 0
- }
- }
-
- /** Write the current records. Called, not awaited, wherever the owner must not wait on the disk;
- * the store snapshots at call time and serializes its writes, so disk order is call order.
- * `instead` is written in place of the record with its id (a change not yet applied in memory). */
- function persist(instead?: WatchLinkRecord): Promise<boolean> {
- if (storeLatched) return Promise.resolve(true) // memory-only this run: nothing is written
- const list = [...records.values(), ...writing.values()].map((x) => (instead && x.linkId === instead.linkId ? instead : x))
- const p = deps.store.save(list).then(
- (outcome) => {
- sealRefused = outcome === 'memory-only'
- return outcome !== 'failed'
- },
- () => false
- )
- lastWrite = p
- return p
- }
-
- function controlSupportOf(nodeId: string): ControlSupport {
- try {
- const s = deps.controlSupport?.(nodeId)
- return s === 'ok' || s === 'unsupported' ? s : 'unknown'
- } catch {
- return 'unknown' // a check that cannot answer leaves the create to decide
- }
- }
-
- /** The scrypt check of a Control link, through the gate. The record's {salt, hash} is read when the
- * check RUNS — a password change swaps them in place, and a check queued for a slot meanwhile must
- * be made against the new one. Never rejects (a failed check is a wrong password). */
- function checkPassword(r: WatchLinkRecord, pw: string): Promise<boolean> {
- if (r.role !== 'controller' || !r.control) return Promise.resolve(false)
- return scrypt(() => {
- const c = r.control
- return c ? verifyPassword(pw, { salt: c.salt, hash: c.hash }) : Promise.resolve(false)
- }).then(
- (ok) => ok === true,
- (err) => {
- warn(`checking a control password failed (${errorName(err)})`)
- return false
- }
- )
- }
-
- function revokeServer(linkId: string): void {
- const ent = deps.entitlement()
- if (!ent) return
- void deps.api.revoke(linkId, ent).catch(() => false) // best effort (the client never rejects)
- }
-
- function armExpiry(r: WatchLinkRecord): void {
- const t = expiry.get(r.linkId)
- if (t !== undefined) clearT(t)
- expiry.delete(r.linkId)
- const at = r.expiresAt
- if (at === null) return // an Unlimited link: no end time, no timer
- const delay = Math.min(MAX_DELAY_MS, Math.max(0, at - now()))
- expiry.set(
- r.linkId,
- setT(() => {
- expiry.delete(r.linkId)
- if (records.get(r.linkId) !== r) return
- if (now() < at) armExpiry(r) // a clamped delay: not yet
- else end(r.linkId, 'expired', { serverRevoke: false, notify: true })
- }, delay)
- )
- }
-
- /**
- * A Control link's wrong-password lock lifts by itself at `lockedUntil` (finding L2): arm that, or
- * lift it now when its time has passed (an app restart past it, a lid-close). A lock with no
- * `lockedUntil` (one written before timed locks) has nothing to arm: it waits for the owner, as it
- * always did. A `lockedUntil` further away than the longest lock (the clock went back, a hand edit)
- * is brought in to that: no lock outlasts `CONTROL_LOCK_MAX_MS` from now.
- */
- function armLock(r: WatchLinkRecord): void {
- const t = lockTimers.get(r.linkId)
- if (t !== undefined) clearT(t)
- lockTimers.delete(r.linkId)
- const c = r.control
- if (!c || !c.locked || typeof c.lockedUntil !== 'number') return
- if (c.lockedUntil - now() > CONTROL_LOCK_MAX_MS) c.lockedUntil = now() + CONTROL_LOCK_MAX_MS
- const until = c.lockedUntil
- const delay = until - now()
- if (delay <= 0) {
- liftLock(r, until)
- return
- }
- lockTimers.set(
- r.linkId,
- setT(() => {
- lockTimers.delete(r.linkId)
- liftLock(r, until)
- }, Math.min(MAX_DELAY_MS, delay))
- )
- }
- /** The lock armed for `until` lifts: unlocking is allowed again and the link-wide count starts over;
- * `lockStep` stays, so the next lock lasts twice as long. Nothing if the link ended, or the lock
- * changed meanwhile (lifted by the owner, or a new lock). The record changes first and is then
- * written; a write that fails changes nothing that matters — a `lockedUntil` in the past reads as
- * lifted at the next launch too. */
- function liftLock(r: WatchLinkRecord, until: number): void {
- const c = r.control
- if (stopped || !c || !c.locked || c.lockedUntil !== until) return
- if (now() < until) {
- armLock(r) // a clamped delay: not yet
- return
- }
- c.locked = false
- c.lockedUntil = null
- c.wrong = 0
- // The link may still be loading (`init` lifts a lapsed lock before any host exists).
- if (records.get(r.linkId) !== r) return
- tellHost(r.linkId, (h) => h.allowControl())
- emitState()
- void persist().then((saved) => {
- if (!saved) warn("a Control link's lifted lock could not be saved; it reads as lifted at the next launch anyway")
- })
- }
-
- /** The host's pty seam, with the node-gone check before every join (R29, G8). */
- function guardedPty(r: WatchLinkRecord): WatchPty {
- return {
- join: async (clientId, nodeId, viewerId) => {
- // Off the link host's own call stack: ending the link stops that host.
- await Promise.resolve()
- if (nodeStateOf(nodeId) === 'absent') {
- end(r.linkId, 'node-gone', { serverRevoke: true, notify: true })
- return null
- }
- return deps.pty.join(clientId, nodeId, viewerId)
- },
- leave: (clientId, sessionId, viewerId) => deps.pty.leave(clientId, sessionId, viewerId),
- captureVisible: (sessionId) => deps.pty.captureVisible(sessionId),
- syncSize: (sessionId) => deps.pty.syncSize(sessionId),
- alive: (sessionId) => deps.pty.alive(sessionId),
- input: (sessionId, chunk, isCurrent) => deps.pty.input(sessionId, chunk, isCurrent)
- }
- }
-
- function onHostChange(linkId: string): void {
- const r = records.get(linkId)
- if (r && r.expiresAt !== null && now() >= r.expiresAt) {
- // A reconnect after a lid-close: the expiry timer may not have fired yet (G24). Deferred: this
- // runs inside the link host's own status callback, and ending the link stops that host.
- queueMicrotask(() => end(linkId, 'expired', { serverRevoke: false, notify: true }))
- return
- }
- emitState()
- }
-
- function start(r: WatchLinkRecord): void {
- if (stopped || hosts.has(r.linkId)) return
- armExpiry(r)
- // Before the host exists: a lock whose time passed while nodeterm was closed is lifted first, so the
- // host starts from a wrong count of 0.
- armLock(r)
- if (!deps.relayAllowed()) return // kept and listed `refused`, never hosted (G21)
- let host: LinkHost
- try {
- host = createHost(r, {
- relayUrl: deps.relayUrl,
- mint: async (): Promise<HostTokenResult> => {
- const ent = deps.entitlement()
- // Never a request with an empty entitlement: the API answers 400, and a 400 stops minting
- // for good. The same end state, reached locally; `onEntitlementChanged` re-arms it (R41).
- if (!ent) return { ok: false, kind: 'refused', status: 402 }
- return deps.api.hostToken(r.linkId, ent)
- },
- status: async () => {
- const ent = deps.entitlement()
- return ent ? deps.api.status(r.linkId, ent) : 'unknown'
- },
- clients: deps.clients,
- pty: guardedPty(r),
- transport: deps.transport,
- now,
- setTimeout: setT,
- clearTimeout: clearT,
- onChange: () => onHostChange(r.linkId),
- onChat: (msg) => safeEmit(IPC.watchLinkChat, r.linkId, ownerChat(msg)),
- onViewerJoined: (count) =>
- notice({ kind: 'joined', linkId: r.linkId, nodeId: r.nodeId, title: stripBidiControls(r.title), viewers: count }),
- onGone: (reason) => end(r.linkId, reason, { serverRevoke: false, notify: true }),
- verifyPassword: (pw) => checkPassword(r, pw),
- // Bound to THIS link's node: a viewer names no node, only a cursor.
- ...(deps.history ? { history: (before: number | null) => deps.history!(r.nodeId, before) } : {}),
- ...(deps.historySupported ? { historySupported: () => deps.historySupported!(r.nodeId) } : {}),
- onControlTaken: (name) => {
- notice({
- kind: 'control-taken',
- linkId: r.linkId,
- nodeId: r.nodeId,
- title: stripBidiControls(r.title),
- // A name the viewer gave itself (sanitized by the host); no bidi override reaches the owner.
- name: stripBidiControls(String(name))
- })
- emitState()
- },
- onControlLocked: (by) => {
- // SYNCHRONOUSLY, before any I/O: the host's lock rests on this flag (it reads the record live
- // and never writes it). Never undone by a failed write: a lock whose write fails still holds,
- // and still lifts at its time (finding L2: it lifts by itself — 15 minutes for the first since
- // the owner last allowed control, doubling each time, 24 h at most).
- const c = r.control
- let until: number | null = null
- if (c) {
- const step = Number.isInteger(c.lockStep) ? (c.lockStep as number) : 0
- until = now() + controlLockMs(step)
- c.locked = true
- c.lockedUntil = until
- c.lockStep = Math.min(CONTROL_LOCK_STEP_MAX, step + 1)
- }
- takeTurn(r, 'locked') // an "allow again" still being written must not land over it
- if (records.get(r.linkId) === r) {
- armLock(r)
- void persist().then((saved) => {
- if (!saved) warn("a Control link's lock could not be saved; a restart would lift it early")
- })
- }
- notice({
- kind: 'control-locked',
- linkId: r.linkId,
- nodeId: r.nodeId,
- title: stripBidiControls(r.title),
- // A name the attempt gave itself (sanitized by the host): a claim, shown as one.
- by: typeof by === 'string' && by ? stripBidiControls(by) : null,
- until
- })
- emitState()
- },
- onWrongAttempt: (count) => {
- // On the record SYNCHRONOUSLY (a later write snapshots it), as an integer 0..WRONG_PER_LINK:
- // the store refuses to write anything else.
- if (!r.control || typeof count !== 'number' || Number.isNaN(count)) return
- r.control.wrong = Math.min(WRONG_PER_LINK, Math.max(0, Math.floor(count)))
- // The count that locks rides the lock's own write (`onControlLocked`, which follows): at most
- // WRONG_PER_LINK writes per link between resets.
- if (r.control.wrong >= WRONG_PER_LINK || records.get(r.linkId) !== r) return
- void persist().then((saved) => {
- if (!saved) warn("a Control link's wrong-attempt count could not be saved; an app restart would reset it")
- })
- }
- })
- } catch (err) {
- warn(`a link could not be hosted: ${errorText(err)}`)
- return
- }
- hosts.set(r.linkId, host)
- try {
- host.start()
- } catch (err) {
- warn(`a link host did not start: ${errorText(err)}`)
- }
- }
-
- /** Forget the record and its timer; the host is returned for the caller to stop AFTER the write
- * was issued (spec: delete and write the record first, then end the sessions). */
- function drop(linkId: string): { record: WatchLinkRecord; host: LinkHost | undefined } | null {
- const record = records.get(linkId)
- if (!record) return null
- records.delete(linkId)
- const t = expiry.get(linkId)
- if (t !== undefined) clearT(t)
- expiry.delete(linkId)
- const lt = lockTimers.get(linkId)
- if (lt !== undefined) clearT(lt)
- lockTimers.delete(linkId)
- const host = hosts.get(linkId)
- hosts.delete(linkId)
- return { record, host }
- }
- function stopHost(host: LinkHost | undefined, reason: WatchLinkEndReason): void {
- try {
- host?.stop(reason)
- } catch (err) {
- warn(`stopping a link host failed: ${errorText(err)}`)
- }
- }
-
- function end(
- linkId: string,
- reason: 'expired' | 'revoked' | 'node-gone',
- o: { serverRevoke: boolean; notify: boolean }
- ): void {
- const gone = drop(linkId)
- if (!gone) return
- void persist()
- stopHost(gone.host, reason)
- emitState()
- if (o.notify) {
- notice({ kind: 'ended', linkId, nodeId: gone.record.nodeId, title: stripBidiControls(gone.record.title), reason })
- }
- if (o.serverRevoke) revokeServer(linkId)
- }
-
- async function runInit(): Promise<void> {
- if (unsupported) return
- if (deps.workspaceReady) {
- // A failed load leaves nodes unknown, which keeps every link: the safe side. A load that does
- // not finish (a stalled mount) is waited for no longer than WORKSPACE_READY_TIMEOUT_MS (R46/M5).
- const ready = await within(
- Promise.resolve().then(() => deps.workspaceReady!()).then(() => 'ready', () => 'failed'),
- workspaceWaitMs
- )
- if (ready === TIMEOUT) {
- warn(`the workspace did not finish loading within ${workspaceWaitMs} ms; resuming links whose node cannot be placed yet`)
- }
- }
- let loaded: WatchLinkRecord[] = []
- try {
- loaded = await deps.store.load()
- } catch (err) {
- // The store refuses to write over a file it could not read (and latched itself); any other
- // failure is treated the same way, because writing over it is the one unrecoverable mistake.
- storeLatched = true
- const why = err instanceof WatchLinkStoreUnreadable ? `${err.reason}: ${err.message}` : errorText(err)
- warn(`live links will not be saved this run — the links file could not be read (${why})`)
- }
- if (stopped) return
- const t = now()
- let pruned = false
- for (const r of loaded) {
- if (records.has(r.linkId)) continue
- if (r.expiresAt !== null && r.expiresAt <= t) {
- pruned = true
- continue
- }
- if (nodeStateOf(r.nodeId) === 'absent') {
- pruned = true
- revokeServer(r.linkId)
- continue
- }
- if (records.size >= MAX_LINKS_PER_MACHINE) {
- // A hand-edited file: this machine hosts five links at most.
- pruned = true
- revokeServer(r.linkId)
- continue
- }
- records.set(r.linkId, r)
- }
- if (pruned) void persist()
- for (const r of [...records.values()]) start(r)
- emitState()
- if (!persistentNow()) notice({ kind: 'not-persistent' })
- }
-
- const init = (): Promise<void> =>
- (initPromise ??= runInit().catch((err) => warn(`resuming live links failed: ${errorText(err)}`)))
-
- /** The record of a LIVE Control link (listed, a controller, with its control state), or null. */
- function liveControl(linkId: unknown): ControlRecord | null {
- if (unsupported || stopped || typeof linkId !== 'string') return null
- const r = records.get(linkId)
- return r && r.role === 'controller' && r.control ? (r as ControlRecord) : null
- }
- function tellHost(linkId: string, fn: (h: LinkHost) => void): void {
- const h = hosts.get(linkId)
- if (!h) return
- try {
- fn(h)
- } catch (err) {
- warn(`telling a link host about a control change failed: ${errorText(err)}`)
- }
- }
-
- /** Each owner change (and a lock) takes a TURN on the field it touches; an earlier WIDENING of the
- * same field still being written sees it lost its turn and does not apply (a narrowing applies at
- * once and is never undone, so it has nothing to skip). */
- type ControlField = 'enabled' | 'locked' | 'password'
- const turns = new WeakMap<WatchLinkRecord, Record<ControlField, number>>()
- function takeTurn(r: WatchLinkRecord, f: ControlField): number {
- const t = turns.get(r) ?? { enabled: 0, locked: 0, password: 0 }
- turns.set(r, t)
- return ++t[f]
- }
- const hasTurn = (r: WatchLinkRecord, f: ControlField, n: number): boolean => turns.get(r)?.[f] === n
-
- /**
- * An owner's change that NARROWS access (typing off, a new password): the owner's BRAKE. Applied in
- * memory and told to the host AT ONCE, then written — and NEVER undone. A write that fails, or does
- * not answer within PERSIST_TIMEOUT_MS, answers 'unsaved': the change holds until nodeterm quits, and
- * the next write that lands (every write carries the whole list as memory holds it) saves it. Undoing
- * it instead would hand typing back, or re-open a possibly leaked password, because a disk hiccuped.
- */
- async function narrowControl(
- r: ControlRecord,
- field: ControlField,
- o: { apply(): void; host(h: LinkHost): void }
- ): Promise<true | 'unsaved'> {
- takeTurn(r, field) // a widening of this field still being written must not land over it
- o.apply()
- tellHost(r.linkId, o.host)
- emitState()
- const written = await within(persist(), persistTimeoutMs)
- if (written === true) return true
- warn("an owner's change to a Control link could not be saved; it holds until nodeterm quits")
- return 'unsaved'
- }
-
- /**
- * An owner's change that WIDENS access (typing on, allow again): written FIRST, from a copy of the
- * record — the record the host reads is untouched, so nobody can unlock during the write — and
- * applied to the record and told to the host only once that write landed. A write that fails or does
- * not answer changes nothing in memory (the list as it is is queued behind it) and answers false. A
- * later change to the same field wins: this one is then not applied, and the list as memory holds it
- * is written again over this write's copy.
- */
- async function widenControl(
- r: ControlRecord,
- field: ControlField,
- o: { change(c: WatchLinkControlRecord): void; host(h: LinkHost): void }
- ): Promise<boolean> {
- const turn = takeTurn(r, field)
- const next = { ...r.control }
- o.change(next)
- const write = persist({ ...r, control: next })
- const written = await within(write, persistTimeoutMs)
- const live = liveControl(r.linkId) === r
- if (written !== true) {
- if (live) void persist()
- warn("an owner's change to a Control link could not be saved; nothing changed")
- return false
- }
- if (!live) return false
- if (!hasTurn(r, field, turn)) {
- void persist() // this write's copy is on disk; memory says what the later change made of it
- return true
- }
- o.change(r.control)
- // A write issued meanwhile snapshotted the record before this change, and lands after this one.
- if (lastWrite !== write) void persist()
- tellHost(r.linkId, o.host)
- emitState()
- return true
- }
-
- return {
- init,
-
- async create(raw) {
- if (unsupported || stopped) return fail('unsupported')
- const parsed = parseRequest(raw)
- if (parsed === 'bad-request' || parsed === 'bad-password') return fail(parsed)
- const req = parsed.req
- if (!deps.relayAllowed()) return fail('relay-unavailable')
- // The resumed links count against the cap, and init must never start a host for a link a
- // create already started (G11). Bounded: a hung disk answers, it does not hang the dialog.
- if ((await within(init(), initWaitMs)) === TIMEOUT) {
- warnOnce('init-timeout', `the live-links file did not load within ${initWaitMs} ms`)
- return fail('persist-failed')
- }
- if (stopped) return fail('unsupported')
- if (nodeStateOf(req.nodeId) !== 'present') return fail('node-missing')
- // Before any request: a terminal whose key bindings are session-wide (Zellij) is never typed into.
- if (req.role === 'controller' && controlSupportOf(req.nodeId) === 'unsupported') return fail('control-unsupported')
- if (records.size + creating + opaqueHeld() >= MAX_LINKS_PER_MACHINE) return fail('limit-machine')
- const ent = deps.entitlement()
- if (!ent) return fail('not-entitled')
- creating++
- try {
- // Hashed BEFORE the server row exists: a hash that fails creates nothing anywhere. Only the
- // {salt, hash} goes on; the plaintext is not referenced past this.
- let control: WatchLinkControlRecord | undefined
- if (req.role === 'controller' && parsed.password !== null) {
- let h: ControlPasswordHash
- try {
- h = await scrypt(() => hashPassword(parsed.password as string))
- } catch (err) {
- // `unsupported` ("can't be created here right now"): the one error that names no cause —
- // `network` would say nodeterm's service could not be reached, which is not what happened.
- warn(`hashing a control password failed (${errorName(err)}); nothing was created`)
- return fail('unsupported')
- }
- parsed.password = null
- control = { enabled: true, locked: false, wrong: 0, lockedUntil: null, lockStep: 0, salt: h.salt, hash: h.hash }
- }
- const secret = newWatchLinkSecret()
- const joinKeyHash = await sha256Hex(deriveWatchLinkKeys(secret).joinKey)
- const created = await deps.api.create(ent, joinKeyHash, req.ttlSeconds)
- if (!created.ok) return fail(created.error)
- if (stopped) {
- revokeServer(created.linkId)
- return fail('unsupported')
- }
- const record: WatchLinkRecord = {
- linkId: created.linkId,
- nodeId: req.nodeId,
- role: req.role,
- label: req.label,
- title: req.title,
- createdAt: now(),
- // null for an Unlimited link (the API accepts a null only for a `ttlSeconds` 0 request).
- expiresAt: created.expiresAt,
- secret,
- ...(control ? { control } : {})
- }
- writing.set(record.linkId, record)
- let written: boolean | typeof TIMEOUT
- try {
- written = await within(persist(), persistTimeoutMs)
- } finally {
- writing.delete(record.linkId)
- }
- if (written !== true || stopped) {
- // No half-created link: queue the list without it behind whatever is stuck (so a write
- // that lands late is overwritten), and revoke the server row. (Quitting meanwhile is the
- // same: the owner was never shown this link.)
- void persist()
- revokeServer(record.linkId)
- return fail(stopped ? 'unsupported' : 'persist-failed')
- }
- // The node may have left every project while the record was being written — a workspace
- // change could not see this record then (it is not a link yet). Absent now: undo it (R46/M4).
- if (nodeStateOf(record.nodeId) === 'absent') {
- void persist()
- revokeServer(record.linkId)
- return fail('node-missing')
- }
- records.set(record.linkId, record)
- start(record)
- emitState()
- if (!persistentNow()) notice({ kind: 'not-persistent' })
- return { ok: true, link: viewOf(record) }
- } catch (err) {
- warn(`creating a live link failed: ${errorText(err)}`)
- return fail('network')
- } finally {
- creating--
- }
- },
-
- list,
-
- async revoke(linkId) {
- if (unsupported || typeof linkId !== 'string') return
- await within(init(), initWaitMs) // no link exists before init; a hung load must not hang the stop
- end(linkId, 'revoked', { serverRevoke: true, notify: false })
- },
-
- async revokeAll() {
- if (unsupported) return 'unsupported'
- // Bounded like revoke: on a disk that hangs, "Stop all" still reaches the server below.
- await within(init(), initWaitMs)
- const gone = [...records.keys()].map(drop)
- // "Stop all" revokes every link of the license server-side, the ones this run cannot unseal too.
- try {
- deps.store.discardOpaque()
- } catch (err) {
- warn(`forgetting unreadable links failed: ${errorText(err)}`)
- }
- void persist()
- for (const g of gone) stopHost(g?.host, 'revoked')
- emitState()
- // This machine's links are stopped. The server call is the only thing that reaches the links of
- // OTHER machines on the license, so it is AWAITED and its answer reported (R62): a stop that did
- // not reach the server must not look like one that did.
- let ent: string | null
- try {
- ent = deps.entitlement()
- } catch {
- ent = null
- }
- if (!ent) return 'no-entitlement'
- try {
- return (await deps.api.revokeAll(ent)) ? 'stopped' : 'failed'
- } catch {
- return 'failed'
- }
- },
-
- kick(linkId, viewerId) {
- try {
- return hosts.get(linkId)?.kick(viewerId) ?? false
- } catch (err) {
- warn(`kicking a viewer failed: ${errorText(err)}`)
- return false
- }
- },
-
- sendChat(linkId, text) {
- try {
- const msg = hosts.get(linkId)?.postSharerChat(text) ?? null
- return msg ? ownerChat(msg) : null
- } catch (err) {
- warn(`sending a chat message failed: ${errorText(err)}`)
- return null
- }
- },
-
- chatHistory(linkId) {
- try {
- return (hosts.get(linkId)?.chatHistory() ?? []).map(ownerChat)
- } catch {
- return []
- }
- },
-
- onWorkspaceChanged() {
- if (unsupported || stopped) return
- void init().then(() => {
- if (stopped) return
- for (const r of [...records.values()]) {
- if (nodeStateOf(r.nodeId) === 'absent') end(r.linkId, 'node-gone', { serverRevoke: true, notify: true })
- }
- })
- },
-
- onEntitlementChanged() {
- if (stopped) return
- for (const h of hosts.values()) {
- try {
- if (h.status() === 'refused') h.start()
- } catch (err) {
- warn(`re-arming a link host failed: ${errorText(err)}`)
- }
- }
- },
-
- async setControl(linkId, enabled) {
- const r = liveControl(linkId)
- if (!r || typeof enabled !== 'boolean') return false
- const c = r.control
- if (c.enabled === enabled) {
- // Nothing to change here — but it is still the owner's latest word on this field: an earlier
- // change still being written must not land over it.
- takeTurn(r, 'enabled')
- return true
- }
- if (enabled) {
- return widenControl(r, 'enabled', {
- change: (x) => {
- x.enabled = true
- },
- host: (h) => h.controlChanged()
- })
- }
- return narrowControl(r, 'enabled', {
- apply: () => {
- c.enabled = false
- },
- host: (h) => h.controlChanged()
- })
- },
-
- async setPassword(linkId, pw) {
- if (!liveControl(linkId) || controlPasswordProblem(pw) !== null) return false
- let h: ControlPasswordHash
- try {
- h = await scrypt(() => hashPassword(pw))
- } catch (err) {
- warn(`hashing a new control password failed (${errorName(err)}); nothing changed`)
- return false
- }
- // The link may have ended (or this run stopped) while the hash ran.
- const r = liveControl(linkId)
- if (!r) return false
- const c = r.control
- return narrowControl(r, 'password', {
- apply: () => {
- c.salt = h.salt
- c.hash = h.hash
- // A new password starts the link-wide wrong count over (the host resets its own).
- c.wrong = 0
- },
- // Every controller drops back to watching and must unlock with the new password.
- host: (x) => x.passwordChanged()
- })
- },
-
- async allowControl(linkId) {
- const r = liveControl(linkId)
- if (!r) return false
- if (!r.control.locked) {
- takeTurn(r, 'locked')
- return true
- }
- return widenControl(r, 'locked', {
- change: (x) => {
- x.locked = false
- x.lockedUntil = null
- x.wrong = 0 // the count starts over with the lock (the host resets its own)
- x.lockStep = 0 // and so does the backoff: the next lock lasts 15 minutes again
- },
- host: (h) => {
- armLock(r) // nothing left to lift
- h.allowControl()
- }
- })
- },
-
- controlSupport(nodeId) {
- if (typeof nodeId !== 'string' || !isSafeNodeId(nodeId)) return 'unknown'
- return controlSupportOf(nodeId)
- },
-
- shutdown() {
- if (!stopped) {
- stopped = true
- for (const t of expiry.values()) clearT(t)
- expiry.clear()
- for (const t of lockTimers.values()) clearT(t)
- lockTimers.clear()
- const all = [...hosts.values()]
- hosts.clear()
- for (const h of all) stopHost(h, 'host-stopping')
- }
- return lastWrite.then(
- () => undefined,
- () => undefined
- )
- }
- }
-}
-
-/**
- * `shutdown()` bounded: the service's last write may hang on a stalled disk, and a shell's close must
- * not (R46/M6). The Server Edition awaits this in both close paths; the desktop races its own 1.5 s
- * flush instead. The timer is cleared (and never holds the process) either way.
- */
-export async function shutdownWithin(s: WatchLinkService | null, ms: number): Promise<void> {
- if (!s) return
- let timer: ReturnType<typeof setTimeout> | undefined
- const bound = new Promise<void>((resolve) => {
- timer = setTimeout(resolve, ms)
- timer.unref?.()
- })
- try {
- await Promise.race([s.shutdown(), bound])
- } finally {
- clearTimeout(timer)
- }
-}
-
-/** The owner IPC. Relay peers never reach these handlers (the `watchLink:` prefix is host-only and
- * refused before any policy runs); the owner check is the belt behind that, for any other client. */
-export function registerWatchLinkIpc(
- p: Pick<CorePlatform, 'handleWithSender' | 'isOwnerClient'>,
- s: WatchLinkService
-): void {
- const owner = (id: number): boolean => p.isOwnerClient?.(id) === true
- const str = (v: unknown): v is string => typeof v === 'string'
- p.handleWithSender(IPC.watchLinkCreate, (sender: number, req: unknown) =>
- owner(sender) ? s.create(req) : ({ ok: false, error: 'unsupported' } satisfies CreateWatchLinkResult))
- p.handleWithSender(IPC.watchLinkList, (sender: number) => (owner(sender) ? s.list() : []))
- p.handleWithSender(IPC.watchLinkRevoke, (sender: number, id: unknown) =>
- owner(sender) && str(id) ? s.revoke(id) : undefined)
- p.handleWithSender(IPC.watchLinkRevokeAll, (sender: number) =>
- owner(sender) ? s.revokeAll() : ('unsupported' satisfies RevokeAllOutcome))
- p.handleWithSender(IPC.watchLinkKick, (sender: number, id: unknown, viewer: unknown) =>
- owner(sender) && str(id) && str(viewer) ? s.kick(id, viewer) : false)
- p.handleWithSender(IPC.watchLinkChatSend, (sender: number, id: unknown, text: unknown) =>
- owner(sender) && str(id) && str(text) ? s.sendChat(id, text) : null)
- p.handleWithSender(IPC.watchLinkChatHistory, (sender: number, id: unknown) =>
- owner(sender) && str(id) ? s.chatHistory(id) : [])
- p.handleWithSender(IPC.watchLinkSetControl, (sender: number, id: unknown, enabled: unknown) =>
- owner(sender) && str(id) && typeof enabled === 'boolean' ? s.setControl(id, enabled) : false)
- // The password is handed straight to the service, which keeps only its hash; never logged here.
- p.handleWithSender(IPC.watchLinkSetPassword, (sender: number, id: unknown, pw: unknown) =>
- owner(sender) && str(id) && str(pw) ? s.setPassword(id, pw) : false)
- p.handleWithSender(IPC.watchLinkAllowControl, (sender: number, id: unknown) =>
- owner(sender) && str(id) ? s.allowControl(id) : false)
- p.handleWithSender(IPC.watchLinkControlSupport, (sender: number, nodeId: unknown) =>
- owner(sender) && str(nodeId) ? s.controlSupport(nodeId) : ('unknown' satisfies ControlSupport))
-}
diff --git a/src/core/watch-link/service.workspace.test.ts b/src/core/watch-link/service.workspace.test.ts
deleted file mode 100644
index 4459145b6..000000000
--- a/src/core/watch-link/service.workspace.test.ts
+++ /dev/null
@@ -1,193 +0,0 @@
-// The node-gone rule against the REAL workspace store (ruling R44). A lost or corrupt workspace.json
-// is rebuilt from nothing during the run: the renderer's load sets the corrupt file aside and its
-// unconditional boot save writes an EMPTY index. That index must not read as a complete read of every
-// project — every node would be "absent" and every live link revoked a second after launch, while
-// each project's own `.nodeterm/project.json` still holds its nodes.
-import { describe, it, expect, afterEach } from 'vitest'
-import { promises as fs } from 'node:fs'
-import path from 'node:path'
-import { testTmpDir } from '../test-tmp'
-import { initPlatform, resetPlatformForTests } from '../platform'
-import { fakePlatform } from '../platform-fake'
-import { WorkspaceStore } from '../workspace-store'
-import { createWatchLinkService, workspaceNodeState, type WatchLinkService } from './service'
-import type { WatchLinkRecord } from './store'
-import type { WatchLinkApi as ApiClient } from './api'
-import type { LinkHost } from './link-host'
-import type { Project, Workspace } from '../../shared/types'
-
-const services: WatchLinkService[] = []
-afterEach(async () => {
- for (const s of services.splice(0)) await s.shutdown()
- resetPlatformForTests()
-})
-
-const project = (cwd: string): Project => ({
- id: 'p1', name: 'foo', color: '#7aa2f7', viewport: { x: 0, y: 0, zoom: 1 }, cwd,
- nodes: [{ id: 'term-1', kind: 'terminal', position: { x: 0, y: 0 }, size: { width: 1, height: 1 }, title: 't', color: '#fff', group: null }]
-})
-const ws = (projects: Project[]): Workspace => ({ version: 2, activeProjectId: projects[0]?.id ?? '', projects })
-
-/** A machine with one folder project holding node `term-1`, its index written by a previous run. */
-async function machine() {
- const userData = testTmpDir('nt-wl-ws-')
- const projRoot = testTmpDir('nt-wl-proj-')
- initPlatform(fakePlatform({ userDataDir: userData }))
- await new WorkspaceStore().save(ws([project(projRoot)]))
- return { userData, projRoot, index: path.join(userData, 'workspace.json') }
-}
-
-/** The live-link service over this store, resuming one link to `term-1`. */
-function linksOver(store: WorkspaceStore) {
- const calls: string[] = []
- const stopped: string[] = []
- const api: ApiClient = {
- create: async () => ({ ok: false, error: 'network' }),
- hostToken: async () => ({ ok: false, kind: 'network' }),
- status: async () => 'live',
- revoke: async (id) => {
- calls.push(`revoke ${id}`)
- return true
- },
- revokeAll: async () => true
- }
- const record: WatchLinkRecord = {
- linkId: 'Keep000000000000000000', nodeId: 'term-1', role: 'viewer', label: 'A', title: 't',
- createdAt: 0, expiresAt: Date.now() + 3_600_000, secret: new Uint8Array(32).fill(1)
- }
- const s = createWatchLinkService({
- api,
- relayUrl: 'wss://r',
- store: { load: async () => [record], save: async () => 'saved', discardOpaque: () => {}, opaqueCount: () => 0 },
- entitlement: () => 'ent',
- relayAllowed: () => true,
- nodeState: (id) => workspaceNodeState(store, id),
- clients: { attach: () => 1, detach: () => {} },
- pty: {
- join: async () => null, leave: () => {}, captureVisible: async () => ({ screen: '', cursor: null }),
- syncSize: async () => true, alive: () => true, input: async () => false
- },
- emit: () => {},
- createHost: (): LinkHost => ({
- start: () => {}, stop: (r) => { stopped.push(r) }, kick: () => false, postSharerChat: () => null,
- chatHistory: () => [], status: () => 'live', viewers: () => [],
- controlChanged: () => {}, passwordChanged: () => {}, allowControl: () => {}
- })
- })
- services.push(s)
- store.onPersist = () => s.onWorkspaceChanged()
- return { s, calls, stopped }
-}
-const settle = async () => {
- for (let i = 0; i < 20; i++) await Promise.resolve()
-}
-
-describe('an index rebuilt from nothing is never a complete read (R44)', () => {
- it('control: with a readable index, a node that leaves every project IS absent and its link ends', async () => {
- await machine()
- const store = new WorkspaceStore()
- await store.load({ sideline: false })
- const links = linksOver(store)
- await links.s.init()
- expect(workspaceNodeState(store, 'term-1')).toBe('present')
- await store.save(ws([])) // the user removed the project
- expect(workspaceNodeState(store, 'term-1')).toBe('absent')
- await settle()
- expect(links.calls).toEqual(['revoke Keep000000000000000000'])
- expect(links.stopped).toEqual(['node-gone'])
- })
-
- it('a CORRUPT index: boot read, the renderer sets it aside, its empty boot save — the node stays unknown, no link is revoked', async () => {
- const m = await machine()
- await fs.writeFile(m.index, '{nope')
- const store = new WorkspaceStore()
- await store.load({ sideline: false }) // the desktop's boot read (bootWorkspaceLoad)
- const links = linksOver(store)
- await links.s.init()
- expect(links.s.list()).toHaveLength(1)
- await store.load() // the renderer's load: sets the corrupt file aside
- expect((await fs.readdir(m.userData)).some((n) => n.startsWith('workspace.json.corrupt-'))).toBe(true)
- await store.save(ws([])) // the renderer's unconditional boot save: an EMPTY index
- expect(JSON.parse(await fs.readFile(m.index, 'utf8')).entries).toEqual([])
- expect(workspaceNodeState(store, 'term-1')).toBe('unknown')
- expect(store.knownNodeIdsStrict()).toBeUndefined()
- await settle()
- expect(links.calls).toEqual([])
- expect(links.stopped).toEqual([])
- expect(links.s.list()).toHaveLength(1)
- // The project file still holds the node: reopening the folder brings it back with the same id.
- expect(await fs.readFile(path.join(m.projRoot, '.nodeterm/project.json'), 'utf8')).toContain('term-1')
- })
-
- it('a DELETED index is the same (for the rest of the run, even once projects are added back)', async () => {
- const m = await machine()
- await fs.rm(m.index)
- const store = new WorkspaceStore()
- await store.load({ sideline: false })
- const links = linksOver(store)
- await links.s.init()
- await store.load()
- await store.save(ws([]))
- expect(workspaceNodeState(store, 'term-1')).toBe('unknown')
- const other = testTmpDir('nt-wl-other-')
- await store.save(ws([{ ...project(other), id: 'p2', nodes: [] }])) // a project added back, not the node's
- expect(workspaceNodeState(store, 'term-1')).toBe('unknown')
- await settle()
- expect(links.calls).toEqual([])
- })
-
- it('an index that could not be READ (EIO, EACCES) is the same: a failed read is never evidence', async () => {
- const m = await machine()
- await fs.rm(m.index)
- await fs.mkdir(m.index) // readFile answers EISDIR: the store falls back to an empty workspace
- const store = new WorkspaceStore()
- await store.load({ sideline: false })
- expect(store.knownNodeIdsStrict()).toBeUndefined()
- await fs.rmdir(m.index)
- await store.save(ws([]))
- expect(workspaceNodeState(store, 'term-1')).toBe('unknown')
- })
-
- // NEW-1: a file that PARSES but is no index this build recognises falls through to an empty
- // workspace just like an unparsable one — and its empty boot save must not read as complete either.
- for (const [label, body] of [
- ['{}', '{}'],
- ['[]', '[]'],
- ['null', 'null'],
- ['a v2 without its projects list', '{"version":2}'],
- ['a v3 without entries', '{"version":3}'],
- ['a v3 whose entries are not objects', '{"version":3,"entries":[5]}'],
- ['a newer build\'s index', '{"version":4,"entries":[]}']
- ] as const) {
- it(`a PARSABLE but unrecognised index (${label}) is the same: unknown after the empty boot save, and load() answers`, async () => {
- const m = await machine()
- await fs.writeFile(m.index, body)
- const store = new WorkspaceStore()
- await expect(store.load({ sideline: false })).resolves.toMatchObject({ projects: [] })
- const links = linksOver(store)
- await links.s.init()
- await store.load()
- await store.save(ws([]))
- expect(workspaceNodeState(store, 'term-1')).toBe('unknown')
- await settle()
- expect(links.calls).toEqual([])
- expect(links.s.list()).toHaveLength(1)
- })
- }
-
- // …while an index that says, readably, that there is nothing IS a complete read.
- for (const [label, body] of [
- ['v3', '{"version":3,"entries":[]}'],
- ['v2', '{"version":2,"activeProjectId":"","projects":[]}']
- ] as const) {
- it(`a genuinely empty ${label} index stays a complete read: the node is absent`, async () => {
- const m = await machine()
- await fs.writeFile(m.index, body)
- const store = new WorkspaceStore()
- await store.load()
- await store.save(ws([]))
- expect(store.knownNodeIdsStrict()).toEqual(new Set())
- expect(workspaceNodeState(store, 'term-1')).toBe('absent')
- })
- }
-})
diff --git a/src/core/watch-link/store.test.ts b/src/core/watch-link/store.test.ts
deleted file mode 100644
index 077823c7a..000000000
--- a/src/core/watch-link/store.test.ts
+++ /dev/null
@@ -1,758 +0,0 @@
-import { describe, it, expect, vi } from 'vitest'
-import { promises as fsp, existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
-import { dirname, join } from 'node:path'
-import { createHash } from 'node:crypto'
-import { testTmpDir } from '../test-tmp'
-import { renameAtomic, writeFileAtomic } from '../fs-atomic'
-import { WatchLinkStore, WatchLinkStoreUnreadable, type WatchLinkRecord } from './store'
-import { hashControlPassword } from './password'
-
-// Pass-through spies, so a test can hold one write open (ordering), fail one (chain recovery,
-// set-aside failure) or count them (a latched store must not write at all).
-vi.mock('../fs-atomic', async (importOriginal) => {
- const actual = await importOriginal<typeof import('../fs-atomic')>()
- return { ...actual, writeFileAtomic: vi.fn(actual.writeFileAtomic), renameAtomic: vi.fn(actual.renameAtomic) }
-})
-
-const file = () => join(testTmpDir('wl-'), 'watch-links.json')
-// Computed once: two `rec()` calls a millisecond apart must still compare equal.
-const EXPIRES_AT = Date.now() + 3600_000
-const rec = (over: Partial<WatchLinkRecord> = {}): WatchLinkRecord => ({
- linkId: 'AbCdEfGhIjKlMnOpQrStUv', nodeId: 'n1', role: 'viewer', label: 'Ada', title: 'build',
- createdAt: 1, expiresAt: EXPIRES_AT, secret: new Uint8Array(32).fill(7), ...over
-})
-const seal = (b: Buffer) => Buffer.from(b.toString('hex'))
-const unseal = (b: Buffer) => Buffer.from(b.toString(), 'hex')
-
-// The shape of the real desktop seam (src/main/platform-electron.ts): safeStorage encrypts the
-// buffer's UTF-8 TEXT and decrypts back to text. Reversing the code points stands in for the cipher;
-// what matters is the two UTF-8 conversions, which mangle any byte sequence that is not valid UTF-8.
-const reverseText = (s: string) => [...s].reverse().join('')
-const electronSeal = (b: Buffer) => Buffer.from(reverseText(b.toString('utf8')), 'utf8')
-const electronUnseal = (b: Buffer) => Buffer.from(reverseText(b.toString('utf8')), 'utf8')
-// 0x80..0x9f: every byte a lone UTF-8 continuation byte, so `toString('utf8')` replaces each one.
-const HIGH_BYTES = Uint8Array.from({ length: 32 }, (_, i) => 0x80 + i)
-
-const b64 = (b: Uint8Array) => Buffer.from(b).toString('base64')
-const rawEntry = (over: Record<string, unknown> = {}) => ({
- linkId: 'AbCdEfGhIjKlMnOpQrStUv', nodeId: 'n1', role: 'viewer', label: 'Ada', title: 'build',
- createdAt: 1, expiresAt: EXPIRES_AT, secret: b64(new Uint8Array(32).fill(7)), sealed: false, ...over
-})
-const writeLinks = (f: string, links: unknown[], v: unknown = 1) => writeFileSync(f, JSON.stringify({ v, links }))
-
-describe('WatchLinkStore', () => {
- it('round-trips sealed records and writes 0600', async () => {
- const f = file()
- const s = new WatchLinkStore({ file: f, seal, unseal })
- expect(await s.save([rec()])).toBe('saved')
- expect(await s.load()).toEqual([rec()])
- expect(readFileSync(f, 'utf8')).not.toContain(Buffer.from(new Uint8Array(32).fill(7)).toString('base64'))
- if (process.platform !== 'win32') expect(statSync(f).mode & 0o777).toBe(0o600)
- })
-
- it('round-trips a high-byte secret through an Electron-shaped (UTF-8 text) seam', async () => {
- const f = file()
- const s = new WatchLinkStore({ file: f, seal: electronSeal, unseal: electronUnseal })
- const r = rec({ secret: HIGH_BYTES })
- expect(await s.save([r])).toBe('saved')
- expect(await new WatchLinkStore({ file: f, seal: electronSeal, unseal: electronUnseal }).load()).toEqual([r])
- })
-
- it('stores raw secrets where the platform has no seal (Server Edition)', async () => {
- const f = file()
- const s = new WatchLinkStore({ file: f })
- expect(await s.save([rec()])).toBe('saved')
- expect(await s.load()).toEqual([rec()])
- expect(await s.save([rec({ secret: HIGH_BYTES })])).toBe('saved')
- expect(await s.load()).toEqual([rec({ secret: HIGH_BYTES })])
- })
-
- it('writes an empty file and reports memory-only when sealing throws', async () => {
- const f = file()
- const s = new WatchLinkStore({ file: f, seal: () => { throw new Error('locked') }, unseal })
- expect(await s.save([rec()])).toBe('memory-only')
- expect(JSON.parse(readFileSync(f, 'utf8'))).toEqual({ v: 1, links: [] })
- })
-
- it('reports a non-seal error while building the file as failed, and leaves the old file intact', async () => {
- const f = file()
- const s = new WatchLinkStore({ file: f, seal, unseal })
- expect(await s.save([rec()])).toBe('saved')
- const before = readFileSync(f, 'utf8')
- const broken = { ...rec({ linkId: 'BbCdEfGhIjKlMnOpQrStUv' }), secret: undefined } as unknown as WatchLinkRecord
- expect(await s.save([rec(), broken])).toBe('failed')
- expect(readFileSync(f, 'utf8')).toBe(before)
- })
-
- it('an unsealable secret is skipped, and a desktop never accepts a raw one', async () => {
- const f = file()
- await new WatchLinkStore({ file: f }).save([rec()]) // raw on disk
- const desktop = new WatchLinkStore({ file: f, seal, unseal: () => { throw new Error('keychain reset') } })
- expect(await desktop.load()).toEqual([])
- const f2 = file()
- await new WatchLinkStore({ file: f2, seal, unseal }).save([rec()])
- expect(await new WatchLinkStore({ file: f2, seal, unseal: () => { throw new Error('reset') } }).load()).toEqual([])
- })
-
- it('tolerates a missing or corrupt file and drops malformed entries', async () => {
- const f = file()
- expect(await new WatchLinkStore({ file: f }).load()).toEqual([])
- writeFileSync(f, '{nope')
- expect(await new WatchLinkStore({ file: f }).load()).toEqual([])
- writeFileSync(f, JSON.stringify({ v: 1, links: [{ linkId: 'bad', nodeId: 'n', role: 'viewer', secret: 'AA==', sealed: false }] }))
- expect(await new WatchLinkStore({ file: f }).load()).toEqual([])
- })
-
- it('drops an entry whose node id is not a safe node id', async () => {
- const f = file()
- writeLinks(f, [
- rawEntry({ nodeId: '../x', linkId: 'A1CdEfGhIjKlMnOpQrStUv' }),
- rawEntry({ nodeId: 'a b', linkId: 'A2CdEfGhIjKlMnOpQrStUv' }),
- rawEntry({ nodeId: 'x'.repeat(129), linkId: 'A3CdEfGhIjKlMnOpQrStUv' }),
- rawEntry({ nodeId: 12, linkId: 'A4CdEfGhIjKlMnOpQrStUv' }),
- rawEntry({ nodeId: ['n1'], linkId: 'A5CdEfGhIjKlMnOpQrStUv' }),
- rawEntry()
- ])
- expect(await new WatchLinkStore({ file: f }).load()).toEqual([rec()])
- })
-
- it('drops a secret of the wrong length, sealed and unsealed', async () => {
- // Each bad entry is otherwise valid, so nothing but the length check can reject it.
- const f = file()
- writeLinks(f, [rawEntry({ linkId: 'ShortRawGhIjKlMnOpQrSt', secret: b64(new Uint8Array(1).fill(7)) }), rawEntry()])
- expect(await new WatchLinkStore({ file: f }).load()).toEqual([rec()])
-
- const f2 = file()
- const sealB64 = (bytes: Uint8Array) => seal(Buffer.from(b64(bytes), 'utf8')).toString('base64')
- writeLinks(f2, [
- rawEntry({ linkId: 'ShortSealIjKlMnOpQrStUv'.slice(0, 22), secret: sealB64(new Uint8Array(31).fill(7)), sealed: true }),
- rawEntry({ linkId: 'LongSealhIjKlMnOpQrStUv'.slice(0, 22), secret: sealB64(new Uint8Array(33).fill(7)), sealed: true }),
- rawEntry({ secret: sealB64(new Uint8Array(32).fill(7)), sealed: true })
- ])
- expect(await new WatchLinkStore({ file: f2, seal, unseal }).load()).toEqual([rec()])
- })
-
- it('returns at most 200 entries', async () => {
- const f = file()
- const id = (i: number) => `L${String(i).padStart(21, '0')}`
- writeLinks(f, Array.from({ length: 250 }, (_, i) => rawEntry({ linkId: id(i) })))
- const loaded = await new WatchLinkStore({ file: f }).load()
- expect(loaded).toHaveLength(200)
- expect(loaded[199].linkId).toBe(id(199))
- })
-
- it('sets an unparseable file aside and stays writable', async () => {
- const f = file()
- writeFileSync(f, '{nope')
- const s = new WatchLinkStore({ file: f })
- expect(await s.load()).toEqual([])
- expect(existsSync(f)).toBe(false)
- const aside = readdirSync(dirname(f)).filter((n) => n.startsWith('watch-links.json.corrupt-'))
- expect(aside).toHaveLength(1)
- expect(readFileSync(join(dirname(f), aside[0]), 'utf8')).toBe('{nope')
- expect(await s.save([rec()])).toBe('saved')
- expect(await s.load()).toEqual([rec()])
- })
-
- it('sets aside JSON that is not an object ([] or null) and stays writable', async () => {
- for (const body of ['[]', 'null']) {
- const f = file()
- writeFileSync(f, body)
- const s = new WatchLinkStore({ file: f })
- expect(await s.load()).toEqual([])
- expect(existsSync(f)).toBe(false)
- const aside = readdirSync(dirname(f)).filter((n) => n.startsWith('watch-links.json.corrupt-'))
- expect(aside).toHaveLength(1)
- expect(readFileSync(join(dirname(f), aside[0]), 'utf8')).toBe(body)
- expect(await s.save([rec()])).toBe('saved')
- expect(await s.load()).toEqual([rec()])
- }
- })
-
- describe('never writes over a file it could not read', () => {
- const expectLatched = async (s: WatchLinkStore, f: string, before: string) => {
- const writes = vi.mocked(writeFileAtomic).mock.calls.length
- expect(await s.save([])).toBe('failed')
- expect(await s.save([rec()])).toBe('failed')
- expect(vi.mocked(writeFileAtomic).mock.calls.length).toBe(writes)
- expect(readFileSync(f, 'utf8')).toBe(before)
- }
-
- it('a read error other than ENOENT rejects and latches the store', async () => {
- const f = file()
- expect(await new WatchLinkStore({ file: f }).save([rec()])).toBe('saved')
- const before = readFileSync(f, 'utf8')
- const eio = Object.assign(new Error('EIO: i/o error, open'), { code: 'EIO' })
- const open = vi.spyOn(fsp, 'open').mockRejectedValueOnce(eio)
- const s = new WatchLinkStore({ file: f })
- await expect(s.load()).rejects.toBeInstanceOf(WatchLinkStoreUnreadable)
- open.mockRestore()
- await expectLatched(s, f, before)
- })
-
- it('a path that cannot be read as a file (a directory) rejects', async () => {
- const f = file()
- mkdirSync(f)
- const s = new WatchLinkStore({ file: f })
- await expect(s.load()).rejects.toBeInstanceOf(WatchLinkStoreUnreadable)
- expect(await s.save([rec()])).toBe('failed')
- expect(statSync(f).isDirectory()).toBe(true)
- })
-
- it('a file larger than 1 MiB rejects and latches the store', async () => {
- const f = file()
- writeLinks(f, [rawEntry({ pad: 'x'.repeat(1024 * 1024) })])
- const before = readFileSync(f, 'utf8')
- const s = new WatchLinkStore({ file: f })
- await expect(s.load()).rejects.toBeInstanceOf(WatchLinkStoreUnreadable)
- await expectLatched(s, f, before)
- })
-
- it('a version other than 1 rejects and latches the store', async () => {
- const f = file()
- writeLinks(f, [rawEntry()], 2)
- const before = readFileSync(f, 'utf8')
- const s = new WatchLinkStore({ file: f })
- await expect(s.load()).rejects.toBeInstanceOf(WatchLinkStoreUnreadable)
- await expectLatched(s, f, before)
- })
-
- it('a save issued while load() is pending waits for it (real {"v":2} file)', async () => {
- const f = file()
- writeLinks(f, [rawEntry()], 2)
- const before = readFileSync(f, 'utf8')
- const s = new WatchLinkStore({ file: f })
- const loading = s.load()
- const saving = s.save([])
- await expect(loading).rejects.toBeInstanceOf(WatchLinkStoreUnreadable)
- expect(await saving).toBe('failed')
- expect(readFileSync(f, 'utf8')).toBe(before)
- })
-
- it('a save issued while a slow read is held waits for its verdict', async () => {
- const f = file()
- expect(await new WatchLinkStore({ file: f }).save([rec()])).toBe('saved')
- const before = readFileSync(f, 'utf8')
- let release!: () => void
- const gate = new Promise<void>((r) => { release = r })
- const eacces = Object.assign(new Error('EACCES: permission denied, open'), { code: 'EACCES' })
- const open = vi.spyOn(fsp, 'open').mockImplementationOnce(async () => {
- await gate // the read is still in flight when the save arrives
- throw eacces
- })
- const writes = vi.mocked(writeFileAtomic).mock.calls.length
- const s = new WatchLinkStore({ file: f })
- const loading = s.load()
- const saving = s.save([])
- for (let i = 0; i < 10; i++) await Promise.resolve() // microtasks only, no timers
- expect(vi.mocked(writeFileAtomic).mock.calls.length).toBe(writes) // nothing written yet
- release()
- await expect(loading).rejects.toBeInstanceOf(WatchLinkStoreUnreadable)
- open.mockRestore()
- expect(await saving).toBe('failed')
- expect(vi.mocked(writeFileAtomic).mock.calls.length).toBe(writes)
- expect(readFileSync(f, 'utf8')).toBe(before)
- })
-
- it('an unparseable file that cannot be set aside rejects and latches the store', async () => {
- const f = file()
- writeFileSync(f, '{nope')
- vi.mocked(renameAtomic).mockRejectedValueOnce(Object.assign(new Error('EPERM'), { code: 'EPERM' }))
- const s = new WatchLinkStore({ file: f })
- await expect(s.load()).rejects.toBeInstanceOf(WatchLinkStoreUnreadable)
- await expectLatched(s, f, '{nope')
- })
- })
-
- it('serializes saves: an older snapshot never lands after a newer one', async () => {
- // A revoke is a save of the smaller list. If two writes overlap and finish out of order, the
- // OLDER snapshot is what stays on disk — and the revoked link comes back at the next boot.
- const f = file()
- const s = new WatchLinkStore({ file: f })
- const { writeFileAtomic: realWrite } = await vi.importActual<typeof import('../fs-atomic')>('../fs-atomic')
- const events: string[] = []
- let release!: () => void
- const gate = new Promise<void>((r) => { release = r })
- let bLanded!: () => void
- const bDone = new Promise<void>((r) => { bLanded = r })
- vi.mocked(writeFileAtomic)
- .mockImplementationOnce(async (...args) => {
- events.push('a:start')
- await gate // the FIRST write is held until the test releases it
- await realWrite(...args)
- events.push('a:end')
- })
- .mockImplementationOnce(async (...args) => {
- events.push('b:start')
- await realWrite(...args)
- events.push('b:end')
- bLanded()
- })
- const a = s.save([rec()])
- const b = s.save([])
- // Let already-scheduled work run (microtasks only, no timers). Serialized, the second write has
- // still not been called: it waits on the held first one. If it has (the bug), let it land
- // before releasing the first, so the out-of-order finish is certain rather than a race.
- for (let i = 0; i < 10; i++) await Promise.resolve()
- if (events.includes('b:start')) await bDone
- release()
- expect(await a).toBe('saved')
- expect(await b).toBe('saved')
- expect(events).toEqual(['a:start', 'a:end', 'b:start', 'b:end'])
- expect(JSON.parse(readFileSync(f, 'utf8'))).toEqual({ v: 1, links: [] })
- expect(await s.load()).toEqual([])
- })
-
- it('a failed save does not break the chain for the next one', async () => {
- const f = file()
- const s = new WatchLinkStore({ file: f })
- vi.mocked(writeFileAtomic).mockRejectedValueOnce(new Error('EPERM'))
- const a = s.save([rec()])
- const b = s.save([rec({ label: 'Bob' })])
- expect(await a).toBe('failed')
- expect(await b).toBe('saved')
- expect(await s.load()).toEqual([rec({ label: 'Bob' })])
- })
-})
-
-// Ruling R42(b): an entry whose SEALED secret cannot be unsealed this run (the keychain is locked at
-// login, or was reset) is not evidence that the link is gone. The store keeps it verbatim — never
-// returned by load(), never erased by a save — until its own expiresAt passes. Only then is it dropped.
-describe('opaque entries (a sealed secret this run cannot unseal)', () => {
- const locked = () => {
- throw new Error('keychain locked')
- }
- const other = rec({ linkId: 'OtherLinkIjKlMnOpQrStU', label: 'Bob' })
-
- it('survives a save verbatim and comes back once the keychain answers again', async () => {
- const f = file()
- expect(await new WatchLinkStore({ file: f, seal, unseal }).save([rec()])).toBe('saved')
- const sealedEntry = JSON.parse(readFileSync(f, 'utf8')).links[0]
-
- // This run: the keychain refuses. The link is not returned (it cannot be hosted without its secret).
- const s = new WatchLinkStore({ file: f, seal, unseal: locked })
- expect(await s.load()).toEqual([])
- // A save of this run's own links (a new one) must not erase it.
- expect(await s.save([other])).toBe('saved')
- const onDisk = JSON.parse(readFileSync(f, 'utf8')).links as Record<string, unknown>[]
- expect(onDisk).toHaveLength(2)
- expect(onDisk.find((e) => e.linkId === rec().linkId)).toEqual(sealedEntry)
- // An empty save (every live link revoked) keeps it too.
- expect(await s.save([])).toBe('saved')
- expect(JSON.parse(readFileSync(f, 'utf8')).links).toEqual([sealedEntry])
-
- // Next run the keychain answers: the link is back, secret intact.
- expect(await new WatchLinkStore({ file: f, seal, unseal }).load()).toEqual([rec()])
- })
-
- it('is dropped by the first save after its own expiresAt', async () => {
- const f = file()
- expect(await new WatchLinkStore({ file: f, seal, unseal }).save([rec()])).toBe('saved')
- let t = EXPIRES_AT - 1
- const s = new WatchLinkStore({ file: f, seal, unseal: locked, now: () => t })
- expect(await s.load()).toEqual([])
- expect(await s.save([])).toBe('saved')
- expect(JSON.parse(readFileSync(f, 'utf8')).links).toHaveLength(1)
- t = EXPIRES_AT
- expect(await s.save([])).toBe('saved')
- expect(JSON.parse(readFileSync(f, 'utf8')).links).toEqual([])
- // Gone for good: time going back does not bring it back.
- t = EXPIRES_AT - 1
- expect(await s.save([])).toBe('saved')
- expect(JSON.parse(readFileSync(f, 'utf8')).links).toEqual([])
- })
-
- it('a live record with the same id wins over the opaque copy (never two entries for one link)', async () => {
- const f = file()
- expect(await new WatchLinkStore({ file: f, seal, unseal }).save([rec()])).toBe('saved')
- const s = new WatchLinkStore({ file: f, seal, unseal: locked })
- expect(await s.load()).toEqual([])
- expect(await s.save([rec({ label: 'Live' })])).toBe('saved')
- const links = JSON.parse(readFileSync(f, 'utf8')).links as Record<string, unknown>[]
- expect(links).toHaveLength(1)
- expect(links[0].label).toBe('Live')
- })
-
- it('is kept when sealing fails too (memory-only writes no live link, but never erases one it could not read)', async () => {
- const f = file()
- expect(await new WatchLinkStore({ file: f, seal, unseal }).save([rec()])).toBe('saved')
- const sealedEntry = JSON.parse(readFileSync(f, 'utf8')).links[0]
- const s = new WatchLinkStore({ file: f, seal: locked, unseal: locked })
- expect(await s.load()).toEqual([])
- expect(await s.save([other])).toBe('memory-only')
- expect(JSON.parse(readFileSync(f, 'utf8')).links).toEqual([sealedEntry])
- })
-
- it('opaqueCount() counts the ones still carried: not past their expiry, not discarded', async () => {
- const f = file()
- expect(await new WatchLinkStore({ file: f, seal, unseal }).save([rec(), other])).toBe('saved')
- let t = EXPIRES_AT - 1
- const s = new WatchLinkStore({ file: f, seal, unseal: locked, now: () => t })
- expect(s.opaqueCount()).toBe(0)
- await s.load()
- expect(s.opaqueCount()).toBe(2)
- t = EXPIRES_AT
- expect(s.opaqueCount()).toBe(0)
- t = EXPIRES_AT - 1
- s.discardOpaque()
- expect(s.opaqueCount()).toBe(0)
- })
-
- it('discardOpaque() drops them from the next save ("Stop all": the server revoked them)', async () => {
- const f = file()
- expect(await new WatchLinkStore({ file: f, seal, unseal }).save([rec()])).toBe('saved')
- const s = new WatchLinkStore({ file: f, seal, unseal: locked })
- expect(await s.load()).toEqual([])
- s.discardOpaque()
- expect(await s.save([])).toBe('saved')
- expect(JSON.parse(readFileSync(f, 'utf8')).links).toEqual([])
- })
-
- it('only a sealed entry the keychain REFUSED is opaque: a malformed or raw-on-desktop one is still dropped', async () => {
- const f = file()
- const sealB64 = (bytes: Uint8Array) => seal(Buffer.from(b64(bytes), 'utf8')).toString('base64')
- writeLinks(f, [
- // Unsealed fine, but the wrong length: malformed, not a keychain problem.
- rawEntry({ linkId: 'ShortSealIjKlMnOpQrStU', secret: sealB64(new Uint8Array(31).fill(7)), sealed: true }),
- // A raw secret on a desktop is never adopted.
- rawEntry({ linkId: 'RawOnDesktopKlMnOpQrSt' })
- ])
- const s = new WatchLinkStore({ file: f, seal, unseal })
- expect(await s.load()).toEqual([])
- expect(await s.save([])).toBe('saved')
- expect(JSON.parse(readFileSync(f, 'utf8')).links).toEqual([])
- })
-})
-
-// Ruling R45: when the keychain starts refusing to SEAL mid-run, the links this run already holds a
-// sealed form of — read at boot, or sealed by an earlier write — are written with that ciphertext; only
-// a link that was never sealed is left out ('memory-only'). Writing no live link at all lost every
-// link loaded fine at boot, and writing nothing would keep a link stopped offline on disk (hosted again
-// at the next launch). A link no longer in the list is still dropped.
-describe('a keychain that stops sealing mid-run (R45)', () => {
- const a = rec({ linkId: 'AaaaEfGhIjKlMnOpQrStUv', secret: new Uint8Array(32).fill(1) })
- const b = rec({ linkId: 'BbbbEfGhIjKlMnOpQrStUv', secret: new Uint8Array(32).fill(2) })
- const c = rec({ linkId: 'CcccEfGhIjKlMnOpQrStUv', secret: new Uint8Array(32).fill(3) })
- const switchable = () => {
- const state = { refuse: false }
- const flaky = (b: Buffer) => {
- if (state.refuse) throw new Error('keychain locked')
- return seal(b)
- }
- return { state, flaky }
- }
- const ids = (f: string) => (JSON.parse(readFileSync(f, 'utf8')).links as { linkId: string }[]).map((e) => e.linkId)
-
- it('boot-loaded links survive it with the ciphertext they were read with; a revoked one is gone; a new one is not written', async () => {
- const f = file()
- expect(await new WatchLinkStore({ file: f, seal, unseal }).save([a, b])).toBe('saved')
- const before = JSON.parse(readFileSync(f, 'utf8')).links
- const k = switchable()
- const s = new WatchLinkStore({ file: f, seal: k.flaky, unseal })
- expect(await s.load()).toEqual([a, b])
- k.state.refuse = true
- expect(await s.save([a, b])).toBe('saved') // everything it holds is on disk: nothing is memory-only
- expect(JSON.parse(readFileSync(f, 'utf8')).links).toEqual(before)
- expect(await s.save([a])).toBe('saved') // b stopped: gone from the file, not resurrected
- expect(ids(f)).toEqual([a.linkId])
- expect(await s.save([a, c])).toBe('memory-only') // c was never sealed: left out, a kept
- expect(ids(f)).toEqual([a.linkId])
- // Next launch, keychain back: a resumes; b (stopped) and c (never written) do not.
- expect(await new WatchLinkStore({ file: f, seal, unseal }).load()).toEqual([a])
- })
-
- it('a link sealed by an earlier write this run survives it too', async () => {
- const f = file()
- const k = switchable()
- const s = new WatchLinkStore({ file: f, seal: k.flaky, unseal })
- expect(await s.save([c])).toBe('saved')
- k.state.refuse = true
- expect(await s.save([c, b])).toBe('memory-only')
- expect(ids(f)).toEqual([c.linkId])
- expect(await new WatchLinkStore({ file: f, seal, unseal }).load()).toEqual([c])
- })
-
- it('a sealed form is reused only for the SAME secret', async () => {
- const f = file()
- const k = switchable()
- const s = new WatchLinkStore({ file: f, seal: k.flaky, unseal })
- expect(await s.save([a])).toBe('saved')
- k.state.refuse = true
- expect(await s.save([{ ...a, secret: new Uint8Array(32).fill(9) }])).toBe('memory-only')
- expect(ids(f)).toEqual([])
- })
-
- it('keeps a sealed form only for the links in the last saved list (a stopped link\'s form is dropped)', async () => {
- const f = file()
- const k = switchable()
- const s = new WatchLinkStore({ file: f, seal: k.flaky, unseal })
- expect(await s.save([a, b])).toBe('saved')
- expect(await s.save([a])).toBe('saved') // b stopped
- k.state.refuse = true
- // b again (same id, same secret): its form was dropped with it, so it needs sealing — refused.
- expect(await s.save([a, b])).toBe('memory-only')
- expect(ids(f)).toEqual([a.linkId])
- })
-
- it('holds a DIGEST of each secret, never its text or bytes', async () => {
- const f = file()
- const s = new WatchLinkStore({ file: f, seal, unseal })
- await s.save([a, c])
- await s.load()
- const held = JSON.stringify([...(s as unknown as { sealedForms: Map<string, unknown> }).sealedForms])
- for (const r of [a, c]) {
- expect(held).not.toContain(Buffer.from(r.secret).toString('base64'))
- expect(held).not.toContain(Buffer.from(r.secret).toString('hex'))
- }
- expect(held).toContain(createHash('sha256').update(a.secret).digest('hex'))
- })
-
- it('never re-seals a secret it already holds sealed (the file does not churn on every write)', async () => {
- const f = file()
- let seals = 0
- const counting = (b: Buffer) => {
- seals++
- return seal(b)
- }
- const s = new WatchLinkStore({ file: f, seal: counting, unseal })
- await s.save([a])
- await s.save([a, b])
- await s.save([a, b])
- expect(seals).toBe(2)
- })
-})
-
-// A Control link's record carries `control` (the password's scrypt hash and the lock), and an
-// Unlimited link's `expiresAt` is null. `control` is present IFF the role is 'controller': a
-// hand-edited file cannot give a viewer link a password, and a controller link without one is dropped.
-describe('controller records and unlimited expiry', () => {
- const SALT = b64(new Uint8Array(16).fill(1))
- const HASH = b64(new Uint8Array(32).fill(2))
- const control = { enabled: true, salt: SALT, hash: HASH, locked: false, wrong: 0, lockedUntil: null, lockStep: 0 }
- const ctl = (over: Partial<WatchLinkRecord> = {}) => rec({ role: 'controller', control, expiresAt: null, ...over })
-
- it('round-trips a controller record with no expiry through save and a fresh store', async () => {
- for (const opts of [{ seal, unseal }, {}]) {
- const f = file()
- expect(await new WatchLinkStore({ file: f, ...opts }).save([ctl()])).toBe('saved')
- expect(await new WatchLinkStore({ file: f, ...opts }).load()).toEqual([ctl()])
- }
- const f = file()
- const locked = ctl({ control: { enabled: false, salt: SALT, hash: HASH, locked: true, wrong: 10, lockedUntil: null, lockStep: 0 } })
- expect(await new WatchLinkStore({ file: f, seal, unseal }).save([locked])).toBe('saved')
- expect(await new WatchLinkStore({ file: f, seal, unseal }).load()).toEqual([locked])
- })
-
- it('drops a controller entry without control, and a viewer or commenter entry that carries one', async () => {
- const f = file()
- writeLinks(f, [
- rawEntry({ linkId: 'NoControlIjKlMnOpQrStU', role: 'controller' }),
- rawEntry({ linkId: 'NullControlKlMnOpQrStU', role: 'controller', control: null }),
- rawEntry({ linkId: 'ViewerPwdhIjKlMnOpQrSt', role: 'viewer', control }),
- rawEntry({ linkId: 'CommentPwdIjKlMnOpQrSt', role: 'commenter', control }),
- rawEntry({ linkId: 'ViewerNullIjKlMnOpQrSt', role: 'viewer', control: null }),
- rawEntry({ role: 'controller', control, expiresAt: null })
- ])
- expect(await new WatchLinkStore({ file: f }).load()).toEqual([ctl()])
- })
-
- it('drops a controller entry whose control is malformed', async () => {
- const id = (i: number) => `Bad${String(i).padStart(19, '0')}`
- const bad: unknown[] = [
- 'x',
- [],
- 7,
- { ...control, salt: b64(new Uint8Array(15).fill(1)) },
- { ...control, salt: b64(new Uint8Array(17).fill(1)) },
- { ...control, hash: b64(new Uint8Array(31).fill(2)) },
- { ...control, hash: b64(new Uint8Array(33).fill(2)) },
- // Node's base64 decoder skips characters it does not know: only canonical text is accepted.
- { ...control, salt: `!${SALT}` },
- { ...control, hash: `${HASH.slice(0, 20)}*${HASH.slice(20)}` },
- { ...control, salt: SALT.replace(/=+$/, '') },
- { ...control, salt: 7 },
- { ...control, hash: null },
- { enabled: true, salt: SALT, locked: false },
- { ...control, enabled: 'true' },
- { ...control, enabled: 1 },
- { ...control, locked: 'false' },
- { salt: SALT, hash: HASH, locked: false },
- { enabled: true, salt: SALT, hash: HASH },
- // The link-wide wrong count (final review, Minor 2): an integer 0..10 when present.
- { ...control, wrong: 11 },
- { ...control, wrong: -1 },
- { ...control, wrong: 1.5 },
- { ...control, wrong: '3' },
- { ...control, wrong: null },
- { ...control, wrong: Number.MAX_SAFE_INTEGER },
- // When a lock lifts (finding L2): null or a finite epoch ms ≥ 0; how many locks: 0..16.
- { ...control, locked: true, lockedUntil: -1 },
- { ...control, locked: true, lockedUntil: '1700000000000' },
- { ...control, locked: true, lockedUntil: {} },
- { ...control, lockStep: -1 },
- { ...control, lockStep: 17 },
- { ...control, lockStep: 1.5 },
- { ...control, lockStep: '2' },
- { ...control, lockStep: null }
- ]
- const f = file()
- writeLinks(f, [...bad.map((c, i) => rawEntry({ linkId: id(i), role: 'controller', control: c, expiresAt: null })), rawEntry()])
- expect(await new WatchLinkStore({ file: f }).load()).toEqual([rec()])
- })
-
- // Final review, Minor 2: the link-wide wrong-attempt count is persisted beside `locked`, so an app
- // restart no longer resets it. A file written before it existed has no `wrong`: it reads as 0.
- it('round-trips the link-wide wrong count, and reads a control written without one (an older file) as 0', async () => {
- for (const opts of [{ seal, unseal }, {}]) {
- const f = file()
- const seven = ctl({ control: { ...control, wrong: 7 } })
- expect(await new WatchLinkStore({ file: f, ...opts }).save([seven])).toBe('saved')
- expect(await new WatchLinkStore({ file: f, ...opts }).load()).toEqual([seven])
- }
- const f = file()
- const older = { enabled: true, salt: SALT, hash: HASH, locked: false }
- writeLinks(f, [rawEntry({ role: 'controller', expiresAt: null, control: older })])
- expect(await new WatchLinkStore({ file: f }).load()).toEqual([ctl()])
- })
-
- // Finding L2: a lock lifts by itself. When (`lockedUntil`) and how many locks there were since the
- // owner last allowed control (`lockStep`) are persisted, so a restart neither lifts a lock early nor
- // makes it permanent.
- it('round-trips when a lock lifts and how many locks there were', async () => {
- for (const opts of [{ seal, unseal }, {}]) {
- const f = file()
- const timed = ctl({ control: { ...control, locked: true, wrong: 10, lockedUntil: 1_700_000_900_000, lockStep: 3 } })
- expect(await new WatchLinkStore({ file: f, ...opts }).save([timed])).toBe('saved')
- expect(await new WatchLinkStore({ file: f, ...opts }).load()).toEqual([timed])
- }
- })
-
- it('an existing lock with no lift time (written before timed locks) keeps its meaning: locked until the owner acts', async () => {
- const f = file()
- const older = { enabled: true, salt: SALT, hash: HASH, locked: true, wrong: 10 }
- writeLinks(f, [rawEntry({ role: 'controller', expiresAt: null, control: older })])
- expect(await new WatchLinkStore({ file: f }).load()).toEqual([ctl({ control: { ...control, locked: true, wrong: 10, lockedUntil: null, lockStep: 0 } })])
- })
-
- it('carries a lift time only while locked: an unlocked record with one reads as none', async () => {
- const f = file()
- writeLinks(f, [rawEntry({ role: 'controller', expiresAt: null, control: { ...control, locked: false, lockedUntil: 1_700_000_900_000, lockStep: 2 } })])
- expect(await new WatchLinkStore({ file: f }).load()).toEqual([ctl({ control: { ...control, lockStep: 2 } })])
- })
-
- it('keeps only the seven control fields: an extra one is not loaded or carried', async () => {
- const f = file()
- writeLinks(f, [rawEntry({ role: 'controller', expiresAt: null, control: { ...control, password: 'hunter22' } })])
- const s = new WatchLinkStore({ file: f })
- expect(await s.load()).toEqual([ctl()])
- expect(await s.save(await s.load())).toBe('saved')
- expect(readFileSync(f, 'utf8')).not.toContain('hunter22')
- })
-
- it('writes only the seven control fields of a record', async () => {
- const f = file()
- const withExtra = ctl({ control: { ...control, password: 'hunter22' } as WatchLinkRecord['control'] })
- expect(await new WatchLinkStore({ file: f, seal, unseal }).save([withExtra])).toBe('saved')
- expect(readFileSync(f, 'utf8')).not.toContain('hunter22')
- expect(await new WatchLinkStore({ file: f, seal, unseal }).load()).toEqual([ctl()])
- })
-
- // `control` IFF the role is 'controller' at WRITE time too: a record the next load would drop is
- // never written. The whole save answers 'failed' and the file stays as it was (a bug, made loud).
- it("refuses to write a record that breaks control-iff-controller: 'failed', the file untouched", async () => {
- const f = file()
- const s = new WatchLinkStore({ file: f, seal, unseal })
- expect(await s.save([ctl()])).toBe('saved')
- const before = readFileSync(f, 'utf8')
- const broken: WatchLinkRecord[] = [
- rec({ role: 'viewer', control }),
- rec({ role: 'commenter', control }),
- rec({ role: 'controller' }),
- ctl({ control: { ...control, salt: b64(new Uint8Array(15).fill(1)) } }),
- ctl({ control: { ...control, hash: 'not base64!' } }),
- ctl({ control: { ...control, enabled: 'yes' } as unknown as WatchLinkRecord['control'] }),
- ctl({ control: { ...control, locked: undefined } as unknown as WatchLinkRecord['control'] }),
- ctl({ control: { ...control, wrong: 11 } }),
- ctl({ control: { ...control, wrong: -1 } }),
- ctl({ control: { ...control, wrong: 2.5 } }),
- ctl({ control: { ...control, locked: true, lockedUntil: Number.NaN } }),
- ctl({ control: { ...control, locked: true, lockedUntil: -5 } }),
- ctl({ control: { ...control, lockStep: 99 } })
- ]
- for (const r of broken) {
- expect(await s.save([rec({ linkId: 'OtherLinkIjKlMnOpQrStU' }), r]), JSON.stringify(r.control ?? r.role)).toBe('failed')
- expect(readFileSync(f, 'utf8')).toBe(before)
- }
- // A store that refused a bad list still writes the next good one.
- expect(await s.save([rec()])).toBe('saved')
- expect(await s.load()).toEqual([rec()])
- })
-
- it('never writes the plaintext password: the file holds only its salt and scrypt hash', async () => {
- const password = 'correct horse battery staple'
- const h = await hashControlPassword(password)
- const r = ctl({ control: { enabled: true, salt: h.salt, hash: h.hash, locked: false, wrong: 0, lockedUntil: null, lockStep: 0 } })
- for (const opts of [{ seal, unseal }, {}]) {
- const f = file()
- expect(await new WatchLinkStore({ file: f, ...opts }).save([r])).toBe('saved')
- const text = readFileSync(f, 'utf8')
- expect(text).not.toContain(password)
- expect(text).not.toContain(Buffer.from(password).toString('base64'))
- expect(text).not.toContain(Buffer.from(password).toString('hex'))
- expect(text).toContain(h.hash)
- expect(await new WatchLinkStore({ file: f, ...opts }).load()).toEqual([r])
- }
- })
-
- it('loads expiresAt: null and drops an entry whose expiresAt is neither null nor a finite number', async () => {
- const f = file()
- writeLinks(f, [
- rawEntry({ linkId: 'StrExpiryIjKlMnOpQrStU', expiresAt: 'x' }),
- rawEntry({ linkId: 'NoExpiryhIjKlMnOpQrStU', expiresAt: undefined }),
- rawEntry({ linkId: 'ObjExpiryIjKlMnOpQrStU', expiresAt: {} }),
- rawEntry({ expiresAt: null })
- ])
- expect(await new WatchLinkStore({ file: f }).load()).toEqual([rec({ expiresAt: null })])
- })
-
- describe('an opaque entry (keychain refused) with no expiry', () => {
- const locked = () => {
- throw new Error('keychain locked')
- }
- const timed = rec({ linkId: 'TimedLinkjKlMnOpQrStUv', label: 'Bob' })
-
- it('is carried on every write and counted, however late it gets; a timed one is still dropped past its expiry', async () => {
- const f = file()
- expect(await new WatchLinkStore({ file: f, seal, unseal }).save([ctl(), timed])).toBe('saved')
- const onDisk = JSON.parse(readFileSync(f, 'utf8')).links as Record<string, unknown>[]
- const unlimited = onDisk.find((e) => e.linkId === ctl().linkId)
- expect(unlimited).toMatchObject({ expiresAt: null, role: 'controller', control })
- let t = EXPIRES_AT - 1
- const s = new WatchLinkStore({ file: f, seal, unseal: locked, now: () => t })
- expect(await s.load()).toEqual([])
- expect(s.opaqueCount()).toBe(2)
- expect(await s.save([])).toBe('saved')
- expect(JSON.parse(readFileSync(f, 'utf8')).links).toEqual(onDisk)
- t = EXPIRES_AT + 10 * 365 * 24 * 3600_000 // years later: the timed one is gone, the unlimited one is not
- expect(s.opaqueCount()).toBe(1)
- expect(await s.save([])).toBe('saved')
- expect(JSON.parse(readFileSync(f, 'utf8')).links).toEqual([unlimited])
- expect(await s.save([])).toBe('saved')
- expect(JSON.parse(readFileSync(f, 'utf8')).links).toEqual([unlimited])
- // The keychain answers again: the link comes back whole, control included.
- expect(await new WatchLinkStore({ file: f, seal, unseal }).load()).toEqual([ctl()])
- })
-
- it('is still dropped by discardOpaque() ("Stop all")', async () => {
- const f = file()
- expect(await new WatchLinkStore({ file: f, seal, unseal }).save([ctl()])).toBe('saved')
- const s = new WatchLinkStore({ file: f, seal, unseal: locked })
- expect(await s.load()).toEqual([])
- expect(s.opaqueCount()).toBe(1)
- s.discardOpaque()
- expect(s.opaqueCount()).toBe(0)
- expect(await s.save([])).toBe('saved')
- expect(JSON.parse(readFileSync(f, 'utf8')).links).toEqual([])
- })
- })
-})
diff --git a/src/core/watch-link/store.ts b/src/core/watch-link/store.ts
deleted file mode 100644
index 05df5e388..000000000
--- a/src/core/watch-link/store.ts
+++ /dev/null
@@ -1,414 +0,0 @@
-// Active live links survive an app restart (spec D8). The secret is sealed through the platform's
-// secret seam: Electron safeStorage on the desktop, and ABSENT on the Server Edition by design
-// (headless, no keychain: raw bytes in a 0600 file, the same rule as its node secrets). On the
-// desktop there is no plaintext fallback: if sealing throws, a link that was never sealed is not
-// written (it lives in memory for this run; see R45 below for the ones that were); a raw secret found
-// on a desktop is refused, never adopted.
-//
-// What is sealed is the BASE64 TEXT of the secret, never its bytes. The desktop seam is a string
-// seam (`safeStorage.encryptString(b.toString('utf8'))` / `Buffer.from(decryptString(b), 'utf8')`),
-// so 32 random bytes — almost never valid UTF-8 — come back as different bytes of a different
-// length. Same convention as src/core/agents/node-auth-secret.ts. Unsealed entries (Server Edition)
-// are the base64 of the raw bytes.
-//
-// The store never writes over a file it could not read. Only ENOENT means "no links". Any other
-// read error, a file over 1 MiB, or a version other than 1 makes `load()` reject and LATCHES the
-// store: every later `save()` resolves 'failed' without touching disk, so the file survives for the
-// next boot or a newer build. JSON that does not parse is set aside as `<file>.corrupt-<ts>` and the
-// store starts empty; if the set-aside fails, the same latch applies.
-//
-// Loads and saves are SERIALIZED, in call order, on one chain: each waits for the previous one to
-// settle. Two overlapping atomic writes can still complete out of order, and the older snapshot would
-// then be what stays on disk — a revoked link resurrected at the next boot. And a save issued while a
-// load is still reading must not run before that load's verdict: it would write over a file the load
-// is about to refuse (a slow EACCES/EIO, a newer build's version), or land between reading a corrupt
-// file and setting it aside. The snapshot is taken (and sealed) when `save` is CALLED, so disk order
-// is call order; a failed load or write never breaks the chain for what follows.
-//
-// OPAQUE ENTRIES (controller ruling R42). A sealed secret the keychain REFUSES to unseal this run
-// (locked at login, or reset) says nothing about whether the link is gone: the next run may unseal it.
-// So such an entry is kept exactly as it was read — never returned by `load()` (nothing can host a
-// link without its secret), never erased by a `save()` — and carried back verbatim on every write
-// until its own `expiresAt` passes; the first write after that drops it. A sealed secret that unseals
-// but is malformed, and a raw secret found on a desktop, are not opaque: they are dropped as before.
-// `discardOpaque()` is for "Stop all", whose server revoke has ended every link of the license.
-//
-// A KEYCHAIN THAT STOPS SEALING MID-RUN (controller ruling R45). The store keeps the sealed form of
-// every secret it read or sealed this run and reuses it on every write (it never re-seals), so when
-// `seal` starts throwing only a link it NEVER sealed is left out (reported 'memory-only'); links read
-// at boot and links sealed earlier stay on disk, and a link no longer in the list is still dropped.
-//
-// A CONTROL LINK (role 'controller') carries `control`: whether typing is on, the password's scrypt
-// salt and hash (./password.ts — never the plaintext), whether wrong attempts locked it, the
-// link-wide count of wrong attempts toward that lock (`wrong`, 0..CONTROL_WRONG_MAX — persisted, so an
-// app restart does not hand an attacker who holds the link fresh guesses; a file written before the
-// count existed reads as 0), when the lock lifts by itself (`lockedUntil`, finding L2 — persisted, so a
-// restart neither lifts it early nor makes it permanent; a lock written before timed locks has none and
-// lasts until the owner allows control again, as it always did) and how many locks there have been
-// since the owner last did (`lockStep`, so each lock lasts twice as long as the last, up to 24 h). An
-// older build reads the file as before and ignores the two new fields: a timed lock is permanent there
-// (the safe direction for a downgrade). It is
-// written as it is, not sealed: the hash is scrypt'd, and anyone who can read this 0600 file under
-// userData is already this user. `control` is present IFF the role is 'controller', and a load drops
-// any entry that breaks that rule: a hand-edited file cannot give a viewer link a password, and a
-// controller link with no password is not a link this build can host. A save refuses ('failed', the
-// file untouched) a list holding such a record: it would be written only for the next load to drop it.
-//
-// AN UNLIMITED LINK has `expiresAt: null`: it lives until it is stopped. An opaque one is carried
-// until it is discarded, never dropped for time.
-import { promises as fs } from 'node:fs'
-import { createHash } from 'node:crypto'
-import { renameAtomic, writeFileAtomic } from '../fs-atomic'
-import { LINK_ID_RE } from '../../shared/watch-link/link'
-import { CONTROL_LOCK_MAX_MS, type WatchLinkRole } from '../../shared/watch-link/protocol'
-import { isSafeNodeId } from '../../shared/safe-id'
-
-/** Wrong unlock attempts across a Control link that lock it (link-host.ts `WRONG_PER_LINK`). */
-export const CONTROL_WRONG_MAX = 10
-/** How long a wrong-password lock lasts by itself: 15 minutes for the first lock since the owner last
- * allowed control, doubling with each later one, never past `CONTROL_LOCK_MAX_MS` (24 h). */
-export const CONTROL_LOCK_FIRST_MS = 15 * 60_000
-/** The most locks the record counts (`lockStep`): far past the step where the cap is reached. */
-export const CONTROL_LOCK_STEP_MAX = 16
-export function controlLockMs(step: number): number {
- const n = Number.isInteger(step) && step > 0 ? Math.min(step, CONTROL_LOCK_STEP_MAX) : 0
- return Math.min(CONTROL_LOCK_FIRST_MS * 2 ** n, CONTROL_LOCK_MAX_MS)
-}
-
-/** A Control link's typing state. The salt and hash are base64 (16 and 32 bytes). */
-export interface WatchLinkControlRecord {
- enabled: boolean
- salt: string
- hash: string
- locked: boolean
- /** Wrong unlock attempts across the link since the last reset (a new password, Allow control
- * again, a lock that lifted): an integer 0..CONTROL_WRONG_MAX. */
- wrong: number
- /** While `locked`: when the lock lifts by itself (epoch ms, this machine's clock); null (or absent)
- * for a lock that lifts only when the owner allows control again — every lock a build from before
- * timed locks wrote. Always null while not locked. */
- lockedUntil?: number | null
- /** How many locks since the owner last allowed control again (0..CONTROL_LOCK_STEP_MAX): the next
- * lock lasts `controlLockMs(lockStep)`. A lock that lifts by itself does not reset it. Absent: 0. */
- lockStep?: number
-}
-
-export interface WatchLinkRecord {
- linkId: string
- nodeId: string
- role: WatchLinkRole
- label: string
- title: string
- createdAt: number
- /** Epoch ms; `null` for an Unlimited link (no end time). */
- expiresAt: number | null
- secret: Uint8Array
- /** Present IFF `role === 'controller'`. */
- control?: WatchLinkControlRecord
-}
-export type SaveOutcome = 'saved' | 'memory-only' | 'failed'
-
-export type WatchLinkStoreUnreadableReason = 'read-error' | 'too-large' | 'unknown-version' | 'set-aside-failed'
-
-/** `load()` could not read the file and will not write over it: the store is now latched. */
-export class WatchLinkStoreUnreadable extends Error {
- constructor(
- readonly reason: WatchLinkStoreUnreadableReason,
- message: string,
- options?: { cause?: unknown }
- ) {
- super(message, options)
- this.name = 'WatchLinkStoreUnreadable'
- }
-}
-
-/** A DIGEST of a secret (never its text or bytes: the cache must not be a second plaintext copy)
- * and the sealed text the file holds for it. */
-interface SealedForm {
- digest: string
- sealed: string
-}
-const digestOf = (secret: Uint8Array): string => createHash('sha256').update(secret).digest('hex')
-
-interface FileEntry {
- linkId: string
- nodeId: string
- role: WatchLinkRole
- label: string
- title: string
- createdAt: number
- expiresAt: number | null
- control?: WatchLinkControlRecord
- secret: string
- sealed: boolean
-}
-
-/** A machine holds a handful of links; anything near this is a hand edit, not our file. */
-export const MAX_FILE_BYTES = 1024 * 1024
-/** Entries past this are dropped on read. */
-export const MAX_ENTRIES = 200
-const SECRET_BYTES = 32
-const CONTROL_SALT_BYTES = 16
-const CONTROL_HASH_BYTES = 32
-const noop = (): void => {}
-
-const str = (v: unknown, max: number): v is string => typeof v === 'string' && v.length <= max
-const num = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v)
-/** An expiry that has not passed at `t`: never one of an Unlimited link (`null`). */
-const live = (expiresAt: number | null, t: number): boolean => expiresAt === null || expiresAt > t
-const codeOf = (e: unknown): string =>
- typeof e === 'object' && e && 'code' in e ? String((e as { code: unknown }).code) : ''
-
-/** Base64 text → the 32-byte secret, or null. Canonical text only: Node's base64 decoder skips
- * characters it does not know, so a mangled string could otherwise decode to *some* bytes. */
-function decodeSecret(text: string): Uint8Array | null {
- const bytes = Buffer.from(text, 'base64')
- if (bytes.length !== SECRET_BYTES) return null
- if (bytes.toString('base64') !== text) return null
- return new Uint8Array(bytes)
-}
-
-/** Canonical base64 of exactly `bytes` bytes (the same rule as `decodeSecret`). */
-function isB64Of(v: unknown, bytes: number): v is string {
- if (typeof v !== 'string' || v.length > 64) return false
- const b = Buffer.from(v, 'base64')
- return b.length === bytes && b.toString('base64') === v
-}
-
-/** A Control link's `control`, rebuilt from its seven fields (nothing else is carried), or null. An
- * absent `wrong` is 0 (a file written before the count was persisted); a present one must be an
- * integer 0..CONTROL_WRONG_MAX. An absent `lockedUntil` is null — a lock written before timed locks
- * keeps its meaning, "until the owner allows control again" — and a present one must be null or a
- * finite epoch ms ≥ 0; it is carried only while `locked`. An absent `lockStep` is 0; a present one must
- * be an integer 0..CONTROL_LOCK_STEP_MAX. */
-function readControl(v: unknown): WatchLinkControlRecord | null {
- if (!v || typeof v !== 'object' || Array.isArray(v)) return null
- const { enabled, salt, hash, locked, wrong = 0, lockedUntil = null, lockStep = 0 } = v as Record<string, unknown>
- if (typeof enabled !== 'boolean' || typeof locked !== 'boolean') return null
- if (!isB64Of(salt, CONTROL_SALT_BYTES) || !isB64Of(hash, CONTROL_HASH_BYTES)) return null
- if (!Number.isInteger(wrong) || (wrong as number) < 0 || (wrong as number) > CONTROL_WRONG_MAX) return null
- if (lockedUntil !== null && (!num(lockedUntil) || lockedUntil < 0)) return null
- if (!Number.isInteger(lockStep) || (lockStep as number) < 0 || (lockStep as number) > CONTROL_LOCK_STEP_MAX) return null
- return {
- enabled, salt, hash, locked, wrong: wrong as number,
- lockedUntil: locked ? (lockedUntil as number | null) : null,
- lockStep: lockStep as number
- }
-}
-
-export class WatchLinkStore {
- /** The previous load or write, settled either way: the next one starts only after it. */
- private writing: Promise<void> = Promise.resolve()
- /** False once `load()` found a file it could not read: never write over it this run. */
- private writable = true
- /** Valid entries whose sealed secret this run could not unseal (R42), carried back on every write
- * until their own `expiresAt`. Set by each `load()`. */
- private opaque: FileEntry[] = []
- /** The sealed form of every secret this run read or sealed, by link id, with a digest of the secret
- * it seals (R45): reused on every write, so a keychain that starts refusing mid-run costs only a
- * link it never sealed. Replaced by each save's list, so a stopped link's form goes with it. */
- private sealedForms = new Map<string, SealedForm>()
-
- constructor(
- private readonly o: {
- file: string
- seal?: (b: Buffer) => Buffer
- unseal?: (b: Buffer) => Buffer
- /** Clock for dropping an opaque entry past its `expiresAt` (tests). */
- now?: () => number
- }
- ) {}
-
- /** Forget every opaque entry: the next write leaves them out ("Stop all" revoked them server-side). */
- discardOpaque(): void {
- this.opaque = []
- }
-
- /** How many opaque entries are still carried (not past their own expiry): links this machine holds
- * but cannot host this run. They count against the per-machine cap (R46), or a run with a locked
- * keychain could create five more and the next launch would find ten. */
- opaqueCount(): number {
- const t = (this.o.now ?? Date.now)()
- return this.opaque.filter((e) => live(e.expiresAt, t)).length
- }
-
- load(): Promise<WatchLinkRecord[]> {
- const loading = this.writing.then(() => this.read())
- this.writing = loading.then(noop, noop)
- return loading
- }
-
- private async read(): Promise<WatchLinkRecord[]> {
- let text: string
- try {
- const handle = await fs.open(this.o.file, 'r')
- try {
- const { size } = await handle.stat()
- if (size > MAX_FILE_BYTES) {
- throw this.latch('too-large', `${this.o.file} is ${size} bytes, over the ${MAX_FILE_BYTES}-byte limit`)
- }
- text = await handle.readFile('utf8')
- } finally {
- await handle.close().catch(() => {})
- }
- } catch (e) {
- if (e instanceof WatchLinkStoreUnreadable) throw e
- if (codeOf(e) === 'ENOENT') return []
- throw this.latch('read-error', `could not read ${this.o.file}: ${(e as Error)?.message ?? e}`, e)
- }
-
- let body: unknown
- try {
- body = JSON.parse(text.replace(/\r\n/g, '\n'))
- } catch {
- body = undefined
- }
- if (!body || typeof body !== 'object' || Array.isArray(body)) {
- // Not JSON, or JSON that cannot be any version of this envelope: keep a copy, start empty.
- await this.setAside()
- return []
- }
- const { v, links } = body as { v?: unknown; links?: unknown }
- if (v !== 1) throw this.latch('unknown-version', `${this.o.file} has version ${JSON.stringify(v)}, expected 1`)
-
- const out: WatchLinkRecord[] = []
- const opaque: FileEntry[] = []
- const sealedForms = new Map<string, SealedForm>()
- for (const e of Array.isArray(links) ? (links.slice(0, MAX_ENTRIES) as Partial<FileEntry>[]) : []) {
- if (!e || !str(e.linkId, 22) || !LINK_ID_RE.test(e.linkId)) continue
- // `isSafeNodeId` does not check the type: `12` and `["n1"]` pass its regex by coercion.
- if (typeof e.nodeId !== 'string' || !isSafeNodeId(e.nodeId)) continue
- if (e.role !== 'viewer' && e.role !== 'commenter' && e.role !== 'controller') continue
- // `control` exactly when the role is 'controller', and then well-formed.
- let control: WatchLinkControlRecord | null = null
- if (e.role === 'controller') {
- control = readControl(e.control)
- if (!control) continue
- } else if (e.control !== undefined) continue
- if (!str(e.label, 40) || !str(e.title, 80) || !num(e.createdAt) || typeof e.secret !== 'string') continue
- if (e.expiresAt !== null && !num(e.expiresAt)) continue
- const expiresAt: number | null = e.expiresAt
- const extra = control ? { control } : {}
- const sealed = e.sealed === true
- const secret = this.readSecret(e.secret, sealed)
- if (secret === 'refused') {
- opaque.push({
- linkId: e.linkId, nodeId: e.nodeId, role: e.role, label: e.label, title: e.title,
- createdAt: e.createdAt, expiresAt, ...extra, secret: e.secret, sealed: true
- })
- continue
- }
- if (!secret) continue
- if (sealed) sealedForms.set(e.linkId, { digest: digestOf(secret), sealed: e.secret })
- out.push({ linkId: e.linkId, nodeId: e.nodeId, role: e.role, label: e.label, title: e.title, createdAt: e.createdAt, expiresAt, secret, ...extra })
- }
- this.opaque = opaque
- this.sealedForms = sealedForms
- return out
- }
-
- private latch(reason: WatchLinkStoreUnreadableReason, message: string, cause?: unknown): WatchLinkStoreUnreadable {
- this.writable = false
- return new WatchLinkStoreUnreadable(reason, message, cause === undefined ? undefined : { cause })
- }
-
- private async setAside(): Promise<void> {
- const aside = `${this.o.file}.corrupt-${Date.now()}`
- try {
- await renameAtomic(this.o.file, aside)
- } catch (e) {
- throw this.latch('set-aside-failed', `${this.o.file} does not parse and could not be set aside as ${aside}`, e)
- }
- }
-
- /** The secret; null for a malformed one (dropped); 'refused' for a sealed one this run cannot
- * unseal — no keychain here, or it refused (kept as an opaque entry, R42). */
- private readSecret(stored: string, sealed: boolean): Uint8Array | null | 'refused' {
- if (sealed) {
- if (!this.o.unseal) return 'refused'
- let text: string
- try {
- text = this.o.unseal(Buffer.from(stored, 'base64')).toString('utf8')
- } catch {
- return 'refused'
- }
- return decodeSecret(text)
- }
- // A desktop (it can seal) never adopts a raw secret it finds on disk.
- return this.o.seal ? null : decodeSecret(stored)
- }
-
- /** The opaque entries this write carries: none past its own expiry (dropped for good; an Unlimited
- * one has none), none a live record replaces. */
- private carriedOpaque(written: readonly FileEntry[]): FileEntry[] {
- const t = (this.o.now ?? Date.now)()
- this.opaque = this.opaque.filter((e) => live(e.expiresAt, t))
- const ids = new Set(written.map((e) => e.linkId))
- return this.opaque.filter((e) => !ids.has(e.linkId))
- }
-
- async save(records: readonly WatchLinkRecord[]): Promise<SaveOutcome> {
- // `control` IFF the role is 'controller', and then well-formed — at WRITE time as on load: a record
- // the next load would drop is never written. The whole save fails and the file stays as it was:
- // such a record is a bug, and a link the next run silently loses is the worst way to find it.
- for (const r of records) {
- if (r.role === 'controller' ? !readControl(r.control) : r.control !== undefined) return 'failed'
- }
- const links: FileEntry[] = []
- let outcome: SaveOutcome = 'saved'
- // Only the records in THIS list keep a cached sealed form: a stopped link's goes with it.
- const sealedNext = new Map<string, SealedForm>()
- try {
- for (const r of records) {
- const text = Buffer.from(r.secret).toString('base64')
- let secret = text
- if (this.o.seal) {
- const known = this.sealedForms.get(r.linkId)
- const digest = digestOf(r.secret)
- if (known && known.digest === digest) {
- // Never re-sealed: the form read at boot or sealed earlier this run is still valid, and a
- // keychain that has started refusing must not cost a link it already holds sealed (R45).
- secret = known.sealed
- } else {
- try {
- secret = this.o.seal(Buffer.from(text, 'utf8')).toString('base64')
- } catch {
- // The keychain refused and this link was never sealed: no plaintext fallback. It is left
- // out of the file (it lives in memory this run); every other link is written.
- outcome = 'memory-only'
- continue
- }
- }
- sealedNext.set(r.linkId, { digest, sealed: secret })
- }
- // Only the seven control fields are written (as `readControl` read them above): nothing else that
- // rides on the object reaches disk.
- const c = r.control ? readControl(r.control) : null
- const control = c ? { control: c } : {}
- links.push({
- linkId: r.linkId, nodeId: r.nodeId, role: r.role, label: r.label, title: r.title,
- createdAt: r.createdAt, expiresAt: r.expiresAt, ...control, secret, sealed: !!this.o.seal
- })
- }
- } catch {
- // Not a seal failure (a malformed record): leave the old file exactly as it is.
- return 'failed'
- }
- if (this.o.seal) this.sealedForms = sealedNext
- // Everything above ran synchronously at call time, so the chain is extended in call order. The
- // opaque entries are joined at WRITE time: a save issued while a load was still reading carries
- // what that load found.
- const write = this.writing.then(() => {
- if (!this.writable) throw new Error('watch-link store is latched: it could not read its file')
- const data = JSON.stringify({ v: 1, links: [...links, ...this.carriedOpaque(links)] })
- return writeFileAtomic(this.o.file, data, { mode: 0o600 })
- })
- this.writing = write.catch(() => {})
- try {
- await write
- return outcome
- } catch {
- return 'failed'
- }
- }
-}
diff --git a/src/core/watch-link/stream-filter.test.ts b/src/core/watch-link/stream-filter.test.ts
deleted file mode 100644
index 6a0ea6a01..000000000
--- a/src/core/watch-link/stream-filter.test.ts
+++ /dev/null
@@ -1,406 +0,0 @@
-import { describe, it, expect, vi } from 'vitest'
-import { readFileSync } from 'node:fs'
-import { join } from 'node:path'
-import { createStreamFilter } from './stream-filter'
-
-const ESC = '\x1b'
-const BEL = '\x07'
-const run = (chunks: string[]): string => {
- const f = createStreamFilter()
- return chunks.map((c) => f.push(c)).join('')
-}
-// One string pushed in pieces of `size` chars, the way a pty delivers a large write.
-const pushInPieces = (text: string, size: number, midStream = false): string => {
- const f = createStreamFilter({ midStream })
- let out = ''
- for (let i = 0; i < text.length; i += size) out += f.push(text.slice(i, i + size))
- return out
-}
-// 2 MiB of base64, the shape of a large OSC 52.
-const BIG = 'QUJD'.repeat(512 * 1024)
-
-// The filter's rules, one UTF-16 unit at a time and without a fast path: the oracle the fuzz test
-// holds the production parser to.
-function oneCharAtATime(input: string, midStream: boolean): string {
- // midStream: as if an 8-bit DCS introducer had just been read.
- let mode: 'text' | 'esc' | 'string' | 'stringEsc' = midStream ? 'string' : 'text'
- let osc = false
- let out = ''
- const start = (ch: string): 'string' => {
- osc = ch === ']' || ch === '\x9d'
- return 'string'
- }
- for (let i = 0; i < input.length; i++) {
- const ch = input[i]
- const n = ch.charCodeAt(0)
- const intro8 = '\x90\x98\x9d\x9e\x9f'.includes(ch)
- if (mode === 'text') {
- if (ch === ESC) mode = 'esc'
- else if (intro8) mode = start(ch)
- else out += ch
- } else if (mode === 'string') {
- if (ch === '\x9c' || (ch === BEL && osc)) mode = 'text'
- else if (ch === ESC) mode = 'stringEsc'
- else if (intro8) mode = start(ch)
- } else if (']PX^_'.includes(ch) || intro8) mode = start(ch)
- else if (ch === ESC) mode = 'esc'
- else if (n <= 0x17 || n === 0x19 || (n >= 0x1c && n <= 0x1f)) out += ch
- else if (n === 0x7f) continue
- else if (ch === '\\' && mode === 'stringEsc') mode = 'text'
- else {
- out += ESC + ch
- mode = 'text'
- }
- }
- return out
-}
-
-describe('createStreamFilter', () => {
- it('passes text, CSI and SGR untouched', () => {
- const s = `plain ${ESC}[31mred${ESC}[0m ${ESC}[2J${ESC}[H\r\n${ESC}7${ESC}8 é🙂`
- expect(run([s])).toBe(s)
- })
-
- it('removes OSC 52 terminated by BEL and by ST, and every string-type sequence', () => {
- expect(run([`a${ESC}]52;c;c2VjcmV0\x07b`])).toBe('ab')
- expect(run([`a${ESC}]0;title${ESC}\\b`])).toBe('ab')
- expect(run([`a${ESC}Pq#0;2;0;0;0${ESC}\\b`])).toBe('ab')
- expect(run([`a${ESC}_Gf=100;AAAA${ESC}\\b`])).toBe('ab')
- expect(run([`a${ESC}^pm${ESC}\\b${ESC}Xsos${ESC}\\c`])).toBe('abc')
- expect(run([`a\x9d52;c;x\x9cb\x90dcs\x9cc`])).toBe('abc')
- })
-
- it('handles a split at every position of an OSC 52', () => {
- const s = `before${ESC}]52;c;c2VjcmV0${ESC}\\after${ESC}[1m!`
- for (let i = 0; i <= s.length; i++) {
- expect(run([s.slice(0, i), s.slice(i)])).toBe(`beforeafter${ESC}[1m!`)
- }
- })
-
- it('an ESC inside a string aborts it and starts a new sequence', () => {
- expect(run([`a${ESC}]52;c;xx${ESC}[31mred`])).toBe(`a${ESC}[31mred`)
- })
-
- // No length cap: xterm has none, so any cap would show a viewer bytes the owner's screen did not
- // (measured: a 900 KB tmux copy is one 1.2 MB OSC 52). The sizes and push sizes are a pty's.
- it('a 2 MiB OSC 52, BEL- or ST-terminated, is swallowed whole in 64 KiB or 4 KiB pushes', () => {
- for (const end of [BEL, `${ESC}\\`, '\x9c']) {
- for (const size of [65536, 4096]) {
- expect(pushInPieces(`a${ESC}]52;c;${BIG}${end}b${ESC}[mc`, size), `${JSON.stringify(end)} / ${size}`).toBe(
- `ab${ESC}[mc`
- )
- }
- }
- })
-
- it('a 2 MiB DCS is swallowed whole, a BEL in its data included', () => {
- const half = BIG.slice(0, BIG.length / 2)
- for (const size of [65536, 4096]) {
- expect(pushInPieces(`a${ESC}Pq${half}${BEL}${half}${ESC}\\b`, size)).toBe('ab')
- expect(pushInPieces(`a\x90q${half}${BEL}${half}\x9cb`, size)).toBe('ab')
- }
- })
-
- it("is swallowed whole even past xterm's own 10,000,000-char payload limit", () => {
- // xterm stops handing a string that long to its handler but stays in it until the terminator.
- const huge = 'QUJD'.repeat(4 * 1024 * 1024)
- expect(pushInPieces(`a${ESC}]52;c;${huge}${BEL}b`, 65536)).toBe('ab')
- })
-
- it('the string branch counts nothing, so no length can end a string (source)', () => {
- // The tests above catch a cap up to the longest string they push (16 MiB); a cap past that
- // would need a longer test to see. A cap needs a counter and a comparison, and the branch that
- // reads a string's payload has neither.
- const src = readFileSync(join(__dirname, 'stream-filter.ts'), 'utf8').replace(/\r\n/g, '\n')
- const start = src.indexOf("} else if (mode === 'string') {")
- const branch = src.slice(start, src.indexOf('} else {', start)).replace(/\/\/.*$/gm, '')
- expect(start).toBeGreaterThan(-1)
- expect(branch).toContain('.exec(chunk)')
- expect(branch).not.toMatch(/\+\+|--|\+=|-=|[<>]/)
- })
-
- it('reset forgets a half-read sequence', () => {
- const f = createStreamFilter()
- expect(f.push(`a${ESC}]52;c;`)).toBe('a')
- f.reset()
- expect(f.push('visible')).toBe('visible')
- })
-
- it('a keyframe screen (capture-pane -e) loses its OSC 8 links and keeps the link text', () => {
- // tmux 3.4 `capture-pane -p -e` emits hyperlinks verbatim (measured), ST-terminated; programs
- // may end them with BEL instead. A keyframe is one push of a whole screen through a FRESH filter.
- const screen = [
- `${ESC}[1m$ ${ESC}[0mls -l`,
- `see ${ESC}]8;id=1;https://example.com/a${ESC}\\the docs${ESC}]8;;${ESC}\\ for more`,
- `${ESC}]8;;file:///etc/passwd${ESC}\\passwd${ESC}]8;;${ESC}\\ and ${ESC}[4m${ESC}]8;;https://x.test/${BEL}x${ESC}]8;;${BEL}${ESC}[24m`,
- ''
- ].join('\n')
- const out = createStreamFilter().push(screen)
- expect(out).toBe(
- [`${ESC}[1m$ ${ESC}[0mls -l`, 'see the docs for more', `passwd and ${ESC}[4mx${ESC}[24m`, ''].join('\n')
- )
- expect(out).not.toContain(']8;')
- })
-
- // Each case below is a way the viewer could otherwise RECEIVE bytes the owner's terminal treats as
- // string payload. The reference is xterm.js 5.5's VT500 transition table
- // (node_modules/@xterm/xterm/src/common/parser/EscapeSequenceParser.ts): it renders the owner's
- // node, the session host's emulator and the viewer page alike.
-
- it('BEL ends only an OSC: a DCS, SOS, PM or APC keeps swallowing until ST', () => {
- // xterm.js treats BEL inside DCS as data and inside SOS/PM/APC as ignored, so the owner never
- // sees what follows it; ending the string there would show the viewer hidden bytes.
- expect(run([`a${ESC}Ptmux;x${BEL}hidden${ESC}\\b`])).toBe('ab')
- expect(run([`a${ESC}_Gq${BEL}hidden${ESC}\\b`])).toBe('ab')
- expect(run([`a${ESC}^pm${BEL}hidden${ESC}\\b${ESC}Xsos${BEL}hidden\x9cc`])).toBe('abc')
- expect(run([`a\x90dcs${BEL}hidden\x9cb`])).toBe('ab')
- expect(run([`a\x9eq${BEL}hidden\x9cb\x98s${BEL}h\x9cc\x9fa${BEL}h\x9cd`])).toBe('abcd')
- })
-
- it('an 8-bit introducer after ESC starts a string, as it does in xterm.js', () => {
- expect(run([`a${ESC}\x9d52;c;c2VjcmV0\x9cb`])).toBe('ab')
- expect(run([`a${ESC}]0;t${ESC}\x9d52;c;c2VjcmV0\x9cb`])).toBe('ab')
- expect(run([`a${ESC}`, `\x90q#0\x9cb`])).toBe('ab')
- })
-
- it('a C0 control or DEL between ESC and the introducer does not end the escape', () => {
- // xterm.js executes C0 and ignores DEL while in ESCAPE, so `ESC \n ]52;…` is still an OSC 52.
- expect(run([`a${ESC}\n]52;c;c2VjcmV0${BEL}b`])).toBe('a\nb')
- expect(run([`a${ESC}\x7f]52;c;c2VjcmV0${BEL}b`])).toBe('ab')
- expect(run([`a${ESC}]0;t${ESC}\r\x7f]52;c;c2VjcmV0${BEL}b`])).toBe('a\rb')
- // The C0 is still executed, and the ESC still applies to what follows it.
- expect(run([`a${ESC}\r[1mB`])).toBe(`a\r${ESC}[1mB`)
- })
-
- it('never emits a lone ESC that the text after a removed string would complete', () => {
- // `ESC ESC ]…` is ONE OSC in xterm.js (the second ESC restarts the escape); emitting the first
- // ESC would glue it to the text after the removed string, here into an OSC 0 of its own.
- expect(run([`${ESC}${ESC}]52;c;c2VjcmV0${BEL}]0;x${BEL}`])).toBe(`]0;x${BEL}`)
- expect(run([`a${ESC}`, `${ESC}`, `]52;c;x${BEL}]b`])).toBe('a]b')
- expect(run([`a${ESC}${ESC}[1mb`])).toBe(`a${ESC}[1mb`)
- })
-
- it('an 8-bit introducer inside a string starts a new string of its own kind', () => {
- // OSC → DCS: the BEL is now DCS data, not a terminator.
- expect(run([`a${ESC}]0;t\x90q${BEL}hidden\x9cb`])).toBe('ab')
- // DCS → OSC: and now it is one.
- expect(run([`a${ESC}Pq\x9d0;t${BEL}b`])).toBe('ab')
- })
-
- it('reset also forgets a pending ESC', () => {
- const f = createStreamFilter()
- expect(f.push(`a${ESC}`)).toBe('a')
- f.reset()
- expect(f.push(']visible')).toBe(']visible')
- })
-
- it('output never carries a string introducer, whatever the input, start and chunking', () => {
- // Why this is enough: in xterm.js a string state (OSC/DCS/SOS/PM/APC) is entered only from
- // ESCAPE on ] P X ^ _, or anywhere on an 8-bit introducer; ESCAPE is entered only by ESC and is
- // left by any char except C0 executables, DEL and ESC. So if no push emits an 8-bit introducer
- // or ends on ESC, and every ESC it emits is followed by a char that leaves ESCAPE without
- // entering a string, the viewer's parser can never enter one — even when the caller drops some
- // pushes (drop-and-redraw) or starts on a keyframe.
- const ALPHABET = [
- 'a', 'b', ' ', '\n', '\r', '\t', '\x00', ESC, ']', 'P', 'X', '^', '_', '[', '\\', 'm', '8', ';',
- BEL, '\x18', '\x1a', '\x7f', '\x9c', '\x9d', '\x90', '\x98', '\x9e', '\x9f', '\x9b', '\x85', 'é', '🙂'
- ]
- const INTRO_8 = /[\x90\x98\x9d\x9e\x9f]/
- const staysOrStringAfterEsc = (c: string): boolean => {
- const n = c.charCodeAt(0)
- const c0Executable = n <= 0x17 || n === 0x19 || (n >= 0x1c && n <= 0x1f)
- return c0Executable || n === 0x7f || c === ESC || ']PX^_'.includes(c) || INTRO_8.test(c)
- }
- // mulberry32, seeded: reproducible, and without an LCG's short low-bit cycles.
- let seed = 0x5eed
- const rand = (n: number): number => {
- seed = (seed + 0x6d2b79f5) >>> 0
- let z = seed
- z = Math.imul(z ^ (z >>> 15), z | 1)
- z ^= z + Math.imul(z ^ (z >>> 7), z | 61)
- return ((z ^ (z >>> 14)) >>> 0) % n
- }
- for (let iter = 0; iter < 4000; iter++) {
- let input = ''
- for (let i = rand(60); i > 0; i--) input += ALPHABET[rand(ALPHABET.length)]
- const midStream = rand(2) === 1
- // Cut anywhere, a surrogate pair included: nothing in the filter counts or splits on one.
- const cuts = [0, input.length]
- for (let k = rand(5); k > 0; k--) cuts.push(rand(input.length + 1))
- cuts.sort((x, y) => x - y)
- const chunks = cuts.slice(1).map((end, i) => input.slice(cuts[i], end))
-
- const f = createStreamFilter({ midStream })
- const outs = chunks.map((c) => f.push(c))
- for (const out of outs) {
- const ctx = JSON.stringify({ input, chunks, midStream, out })
- expect(INTRO_8.test(out), ctx).toBe(false)
- expect(out.endsWith(ESC), ctx).toBe(false)
- for (let i = out.indexOf(ESC); i !== -1; i = out.indexOf(ESC, i + 1)) {
- expect(staysOrStringAfterEsc(out[i + 1]), ctx).toBe(false)
- }
- }
- // However it is chunked, the result is the char-by-char statement of the same rules: the
- // parser's slicing and fast path neither drop, reorder nor add a char.
- expect(outs.join(''), JSON.stringify({ chunks, midStream })).toBe(oneCharAtATime(input, midStream))
- }
- })
-})
-
-describe('createStreamFilter, joined mid-stream', () => {
- // A watcher co-attaches to a RUNNING session, so its first byte can land anywhere: inside an OSC 52,
- // or right after an ESC that the previous read ended on. A filter that starts in text would print
- // the rest of that string, or read `]52;…` as text.
- const mid = (chunks: string[]): string => {
- const f = createStreamFilter({ midStream: true })
- return chunks.map((c) => f.push(c)).join('')
- }
-
- it('a join at any offset never prints a byte of a string, and resyncs at the next escape', () => {
- // Text is lowercase, spaces and `ESC [ m`; every string's payload is from a disjoint alphabet
- // (uppercase, digits, `=;]\`), so any payload byte in the output is visible as such.
- const STREAM = [
- 'pre ', `${ESC}[m`, 'one ',
- `${ESC}]52;C;U0VDUkVUQQ==${BEL}`, 'mid ',
- `${ESC}]52;C;U0VDUkVUQg==${ESC}\\`, 'two ',
- `${ESC}PQDATA${BEL}MORE${ESC}\\`, 'three ',
- `${ESC}_GAPC${BEL}HIDDEN${ESC}\\`, 'four ',
- `\x9d52;C;U0VDUkVUQw==\x9c`, 'five ',
- `\x90QDATA${BEL}MORE\x9c`,
- `${ESC}[m`, 'tail'
- ].join('')
- const resync = STREAM.lastIndexOf(ESC)
- for (let k = 0; k <= STREAM.length; k++) {
- const rest = STREAM.slice(k)
- for (const out of [mid([rest]), mid([rest.slice(0, 3), rest.slice(3)])]) {
- expect(out, `join at ${k}`).toMatch(/^[a-z \x1b[]*$/)
- if (k <= resync) expect(out.endsWith(`${ESC}[mtail`), `join at ${k}: ${JSON.stringify(out)}`).toBe(true)
- }
- }
- })
-
- it('a join right after a lone trailing ESC does not print the OSC 52 that ESC started', () => {
- const rest = `]52;c;c2VjcmV0${BEL}rest${ESC}[mtail`
- expect(mid([rest])).toBe(`${ESC}[mtail`)
- // What a filter starting in text would have sent: the whole clipboard.
- expect(run([rest])).toContain('c2VjcmV0')
- })
-
- it('a join into plain text loses only the text up to the first ESC', () => {
- expect(mid(['hello world', ` ${ESC}[1mbold${ESC}[m after`])).toBe(`${ESC}[1mbold${ESC}[m after`)
- })
-
- it('starts as an unknown string: ST, ESC-ST and 8-bit introducers end it, BEL does not', () => {
- expect(mid([`DATA${ESC}\\after`])).toBe('after')
- expect(mid([`DATA${ESC}`, `\\after`])).toBe('after')
- expect(mid(['DATA\x9cafter'])).toBe('after')
- // It may be a DCS or APC, where BEL is data.
- expect(mid([`DATA${BEL}more${ESC}[mafter`])).toBe(`${ESC}[mafter`)
- // An 8-bit introducer starts a string of ITS kind: this one is an OSC, which BEL ends.
- expect(mid([`DATA\x9d52;c;x${BEL}after`])).toBe('after')
- })
-
- it('a join into the tail of a 2 MiB OSC 52 swallows all of it', () => {
- const tail = BIG.slice(12345)
- for (const size of [65536, 4096]) {
- expect(pushInPieces(`${tail}${BEL}rest${ESC}[mafter`, size, true)).toBe(`${ESC}[mafter`)
- expect(pushInPieces(`${tail}${ESC}\\after`, size, true)).toBe('after')
- }
- })
-
- it('reset({ midStream }) inside an OSC forgets that it was one: BEL no longer ends it', () => {
- const g = createStreamFilter()
- expect(g.push(`a${ESC}]0;t`)).toBe('a')
- g.reset({ midStream: true })
- expect(g.push(`x${BEL}y${ESC}[mz`)).toBe(`${ESC}[mz`)
- })
-
- // Controller ruling R23: the link host takes a follow-up keyframe once a joined filter has left its
- // unknown start state (the text it swallowed until then is on the owner's screen, not the viewer's).
- describe('onSettled', () => {
- const settledBy = (input: string): number => {
- let n = 0
- createStreamFilter({ midStream: true, onSettled: () => n++ }).push(input)
- return n
- }
-
- it('fires once, when the unknown start state is first left: ESC, ST or an 8-bit introducer', () => {
- expect(settledBy(`x${ESC}[mtext`)).toBe(1)
- expect(settledBy(`x${ESC}\\text`)).toBe(1)
- expect(settledBy('x\x9ctext')).toBe(1)
- expect(settledBy(`x\x9d52;c;x${BEL}text`)).toBe(1)
- // BEL does not end the unknown string (it may be a DCS or APC), so it settles nothing.
- expect(settledBy(`x${BEL}more`)).toBe(0)
- expect(settledBy('plain text, no escape')).toBe(0)
- })
-
- it('fires once only, however many escapes follow, across pushes', () => {
- let n = 0
- const f = createStreamFilter({ midStream: true, onSettled: () => n++ })
- expect(f.push('swallowed ')).toBe('')
- expect(n).toBe(0)
- expect(f.push(`${ESC}[1mA${ESC}[m ${ESC}]0;t${BEL}B`)).toBe(`${ESC}[1mA${ESC}[m B`)
- expect(n).toBe(1)
- // Later strings end at later stop chars; none of them is the start state any more.
- expect(f.push(`${ESC}[2J${ESC}]0;x${BEL}${ESC}P1$r${ESC}\\${ESC}[H`)).toBe(`${ESC}[2J${ESC}[H`)
- expect(n).toBe(1)
- })
-
- it('fires after the chunk is parsed: the push still returns everything after the escape', () => {
- const seen: string[] = []
- const f = createStreamFilter({ midStream: true, onSettled: () => seen.push('settled') })
- expect(f.push(`lost${ESC}[Hkept`)).toBe(`${ESC}[Hkept`)
- expect(seen).toEqual(['settled'])
- })
-
- it('never fires for a filter that starts in text', () => {
- let n = 0
- const f = createStreamFilter({ onSettled: () => n++ })
- f.push(`a${ESC}]52;c;x${BEL}b${ESC}[m`)
- expect(n).toBe(0)
- })
-
- it('reset({ midStream, onSettled }) re-arms it; reset() and a midStream reset without it disarm it', () => {
- let a = 0
- let b = 0
- const f = createStreamFilter({ midStream: true, onSettled: () => a++ })
- f.push(`${ESC}[m`)
- f.reset({ midStream: true, onSettled: () => b++ })
- f.push(`${ESC}[m`)
- expect([a, b]).toEqual([1, 1])
- // Each disarmed filter then reads a whole OSC, whose BEL is a stop char a stale callback would fire on.
- f.reset({ midStream: true, onSettled: () => b++ })
- f.reset({ midStream: true })
- f.push(`${ESC}[m${ESC}]0;t${BEL}${ESC}[m`)
- f.reset({ midStream: true, onSettled: () => b++ })
- f.reset()
- f.push(`${ESC}]0;t${BEL}${ESC}[m`)
- expect([a, b]).toEqual([1, 1])
- })
-
- it('a throwing callback costs nothing: the chunk is returned whole and the state is right', () => {
- const f = createStreamFilter({
- midStream: true,
- onSettled: () => {
- throw new Error('boom')
- }
- })
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
- try {
- expect(f.push(`lost${ESC}[Hkept`)).toBe(`${ESC}[Hkept`)
- expect(f.push(`${ESC}]52;c;c2VjcmV0${BEL}after`)).toBe('after')
- } finally {
- warn.mockRestore()
- }
- })
- })
-
- it('reset({ midStream }) drops what was being read and starts as a join', () => {
- const f = createStreamFilter()
- expect(f.push('a')).toBe('a')
- f.reset({ midStream: true })
- expect(f.push(`b${ESC}[mc`)).toBe(`${ESC}[mc`)
- f.reset()
- expect(f.push('d')).toBe('d')
- })
-})
diff --git a/src/core/watch-link/stream-filter.ts b/src/core/watch-link/stream-filter.ts
deleted file mode 100644
index 45d9040dc..000000000
--- a/src/core/watch-link/stream-filter.ts
+++ /dev/null
@@ -1,195 +0,0 @@
-// Removes every STRING-type escape sequence (OSC, DCS, SOS, PM, APC; 7- and 8-bit introducers)
-// from a live link's pty stream. They carry what is not text on the screen: the clipboard (OSC 52,
-// which tmux emits on every copy with `set-clipboard on`), window titles, hyperlink targets, file
-// transfers, palette changes. Everything else (CSI, other ESC sequences, text) passes unchanged.
-//
-// Stateful across chunks, and it must see EVERY byte of the stream even while nothing is being
-// forwarded: a frame that skipped the parser would leave it mid-sequence and print the tail of an
-// OSC 52 (the clipboard) as text. That is also why it is reset only for a new pty session.
-// A string is swallowed until its terminator, however long. There is no length cap: xterm has none
-// (it stays in a string until ESC, ST, BEL for an OSC, CAN or SUB), so a cap could only ever show a
-// viewer bytes the owner's screen does not. Measured: past the 1 MiB cap an earlier version had, a
-// 900 KB tmux copy (one 1.2 MB OSC 52) put 151,428 chars of the clipboard's base64 on the viewer's
-// screen. And the filter keeps no buffer, so there is nothing for a cap to bound.
-//
-// Where a string starts and ends follows xterm.js 5.5's VT500 table (EscapeSequenceParser.ts), which
-// renders the owner's node, the session host's emulator and the viewer page. Every rule below that
-// goes past "ESC + ] P X ^ _" closes a way the viewer would receive bytes the owner's terminal
-// treats as string payload:
-// - BEL ends an OSC only. Inside DCS it is data, inside SOS/PM/APC it is ignored, so the owner never
-// sees what follows it.
-// - In ESCAPE, xterm executes C0 controls and ignores DEL without leaving it, restarts it on a second
-// ESC, and takes an 8-bit introducer as a string start: `ESC \n ]52;…` is still an OSC 52.
-// - An 8-bit introducer inside a string starts a new string of ITS kind (an OSC turned DCS no longer
-// ends at BEL).
-// Where xterm ENDS a string on something this parser does not (CAN, SUB, other C1 controls, and a
-// non-ASCII char, U+00A0 and up, inside SOS/PM/APC or a DCS before its final byte: ERROR → GROUND),
-// the viewer misses a little text until the next terminator; it never sees more than the owner.
-//
-// A viewer that joins a RUNNING session (`midStream`) cannot know where in the stream its first byte
-// falls: inside an OSC 52, or right after an ESC the previous read ended on (`]52;c;…` would then
-// read as text, the whole clipboard). So it starts as if an unknown string had just begun: nothing
-// is shown until the next ESC, ST or 8-bit introducer, where xterm's state is known again whatever
-// it was (ESCAPE, GROUND, a new string). The cost is the text between the join and the first
-// escape: the viewer misses it until those cells are painted again.
-//
-// The output guarantee the caller relies on: no push emits an 8-bit introducer or ends on ESC, and
-// every ESC it emits is followed by a char that leaves ESCAPE without starting a string. So the
-// viewer's parser can never be put into a string state, even by output that is dropped in part
-// (drop-and-redraw) or starts on a keyframe.
-//
-// It runs on the owner's process for every byte, once per viewer, so text is copied, and a string's
-// payload skipped, by searching for the next char that matters rather than char by char: about 3x
-// faster on a captured tmux stream of colored output (an ESC every ~8 bytes) on a loaded host,
-// 22-39 MB/s char by char, 64-130 MB/s by slice. Such a flood reaches a tmux 3.4 client at
-// ~2.7 MB/s. One tmux copy of a large clipboard is a single OSC 52 of over a megabyte, whose
-// payload is skipped at ~390 MB/s (~53 MB/s char by char).
-
-const ESC = '\x1b'
-// Fast path: a chunk with none of these, read in text mode, is returned as it is.
-const TEXT_SPECIAL = /[\x1b\x90\x98\x9d-\x9f]/
-const INTRO_8_ANY = /[\x90\x98\x9d-\x9f]/
-// What can end a string: ESC, ST, an 8-bit introducer, and BEL for an OSC only.
-const STRING_STOP = /[\x1b\x90\x98\x9c-\x9f]/g
-const OSC_STOP = /[\x07\x1b\x90\x98\x9c-\x9f]/g
-
-// OSC, DCS, SOS, PM, APC: `ESC ] P X ^ _` and their 8-bit forms.
-function isIntro7(c: number): boolean {
- return c === 0x5d || c === 0x50 || c === 0x58 || c === 0x5e || c === 0x5f
-}
-function isIntro8(c: number): boolean {
- return c === 0x9d || c === 0x90 || c === 0x98 || c === 0x9e || c === 0x9f
-}
-// The C0 controls xterm executes while staying in ESCAPE: all but CAN, SUB and ESC itself.
-function isC0Executable(c: number): boolean {
- return c <= 0x17 || c === 0x19 || (c >= 0x1c && c <= 0x1f)
-}
-
-export interface StreamFilterOptions {
- /**
- * The first byte may fall anywhere in the stream. Every viewer that co-attaches to a running
- * session must set it, and so must every `reset()` onto a session that is already running;
- * without it a join inside a string, or right after an ESC, sends the string's payload as text.
- * Starts exactly as if an 8-bit DCS introducer had just been read: nothing is shown until the
- * next ESC (an `ESC \` ST is dropped), ST or 8-bit introducer; BEL does not end it (the unknown
- * string may be a DCS or APC, where BEL is data). Like every string, it has no length limit.
- */
- midStream?: boolean
- /**
- * With `midStream`: called ONCE, when that unknown start state is first left (the first ESC, ST or
- * 8-bit introducer), after the chunk that left it has been parsed. From then on text flows again, so
- * the link host takes one more keyframe to repaint the text it swallowed before (controller ruling
- * R23). Ignored without `midStream`; replaced or dropped by every `reset`. A throw is logged, never
- * propagated: the parse it follows is complete, and the chunk's output must not be lost with it.
- */
- onSettled?: () => void
-}
-
-export interface StreamFilter {
- push(chunk: string): string
- /** Forget the current sequence, for a new pty session; `midStream` as for `createStreamFilter`. */
- reset(opts?: StreamFilterOptions): void
-}
-
-/**
- * A string sequence is swallowed until its terminator however long it is: xterm has no length
- * limit, so a cap would only show a viewer what the owner's screen does not, and nothing is
- * buffered, so there is no memory for one to bound.
- */
-export function createStreamFilter(opts?: StreamFilterOptions): StreamFilter {
- // 'esc' is ESCAPE after a plain ESC; 'stringEsc' is ESCAPE after the ESC that ended a string,
- // where `ESC \` is that string's ST and is dropped with it.
- let mode: 'text' | 'esc' | 'string' | 'stringEsc' = 'text'
- let osc = false
- // Armed while a midStream start has not been left: the start state is the only string state it is
- // set in, so the first stop char read while it is set is the one that leaves that state.
- let settle: (() => void) | null = null
- const enterString = (introducer: number): void => {
- mode = 'string'
- osc = introducer === 0x5d || introducer === 0x9d
- }
- const start = (o: StreamFilterOptions | undefined): void => {
- settle = null
- if (o?.midStream) {
- enterString(0x90)
- settle = o.onSettled ?? null
- } else {
- mode = 'text'
- osc = false
- }
- }
- const fire = (cb: () => void): void => {
- try {
- cb()
- } catch (err) {
- console.warn(`[watch-link] onSettled threw: ${err instanceof Error ? err.message : String(err)}`)
- }
- }
- start(opts)
- return {
- reset(o) {
- start(o)
- },
- push(chunk) {
- if (mode === 'text' && !TEXT_SPECIAL.test(chunk)) return chunk
- // An 8-bit introducer is rare (a decoded stream carries one only if a program wrote the
- // two-byte UTF-8 form), so in most chunks ESC is the only char text mode stops at.
- const has8 = INTRO_8_ANY.test(chunk)
- const n = chunk.length
- let out = ''
- let i = 0
- let settled: (() => void) | null = null
- while (i < n) {
- if (mode === 'text') {
- let j = chunk.indexOf(ESC, i)
- if (j === -1) j = n
- if (has8) {
- for (let k = i; k < j; k++) {
- if (isIntro8(chunk.charCodeAt(k))) {
- j = k
- break
- }
- }
- }
- out += chunk.slice(i, j)
- if (j === n) break
- const c = chunk.charCodeAt(j)
- if (c === 0x1b) mode = 'esc'
- else enterString(c)
- i = j + 1
- } else if (mode === 'string') {
- const stop = osc ? OSC_STOP : STRING_STOP
- stop.lastIndex = i
- const m = stop.exec(chunk)
- // No terminator in this chunk: all of the rest is payload.
- if (m === null) break
- const c = chunk.charCodeAt(m.index)
- i = m.index + 1
- if (settle) {
- settled = settle
- settle = null
- }
- if (c === 0x1b) mode = 'stringEsc'
- else if (c === 0x9c || c === 0x07) mode = 'text'
- else enterString(c)
- } else {
- // ESCAPE. The ESC is held until the char that decides what it starts arrives.
- const c = chunk.charCodeAt(i)
- if (isIntro7(c) || isIntro8(c)) enterString(c)
- else if (c === 0x1b) mode = 'esc'
- else if (isC0Executable(c)) out += chunk[i]
- else if (c === 0x7f) {
- // DEL: ignored in ESCAPE.
- } else if (c === 0x5c && mode === 'stringEsc') mode = 'text'
- else {
- out += ESC + chunk[i]
- mode = 'text'
- }
- i++
- }
- }
- if (settled) fire(settled)
- return out
- }
- }
-}
diff --git a/src/core/watch-link/stream-filter.xterm.test.ts b/src/core/watch-link/stream-filter.xterm.test.ts
deleted file mode 100644
index a409259b3..000000000
--- a/src/core/watch-link/stream-filter.xterm.test.ts
+++ /dev/null
@@ -1,186 +0,0 @@
-// The stream filter held to xterm.js itself, through xterm 5.5's own VT500 table (copied verbatim in
-// __fixtures__/xterm-vt500.ts). Two ways a viewer could get what is not on the owner's screen, one
-// check each, on random streams:
-// - payload: every letter xterm consumes INSIDE a string sequence is changed; if the filter's
-// output changes with it, a byte of string payload reached the viewer;
-// - synthesis: xterm reading the filter's OUTPUT must never enter a string sequence (a lone ESC
-// glued to the text after a removed string would be one, without any payload byte leaking).
-// This is what the hand-written cases cannot do: it asks xterm, not the filter's own reading of
-// xterm, where each string starts and ends.
-import { describe, it, expect } from 'vitest'
-import { readFileSync } from 'node:fs'
-import { join } from 'node:path'
-import { createStreamFilter } from './stream-filter'
-import { xtermEntersString, xtermStringPayload } from './__fixtures__/xterm-vt500'
-
-const ESC = '\x1b'
-const BEL = '\x07'
-const XTERM_PARSER = join(__dirname, '..', '..', '..', 'node_modules', '@xterm', 'xterm', 'src', 'common', 'parser')
-
-const read = (file: string): string => readFileSync(file, 'utf8').replace(/\r\n/g, '\n')
-function block(src: string, start: string, end: string): string {
- const i = src.indexOf(start)
- if (i === -1) return `<missing: ${start}>`
- return src.slice(i, src.indexOf(end, i) + end.length)
-}
-
-// mulberry32, seeded: reproducible.
-function rng(seed: number): (n: number) => number {
- return (n) => {
- seed = (seed + 0x6d2b79f5) >>> 0
- let z = seed
- z = Math.imul(z ^ (z >>> 15), z | 1)
- z ^= z + Math.imul(z ^ (z >>> 7), z | 61)
- return ((z ^ (z >>> 14)) >>> 0) % n
- }
-}
-
-const LETTERS = 'abcdefghijklmnopqrstuvwxyz'
-const IS_LETTER = new Set(LETTERS)
-// Changing one lowercase letter to another moves neither parser: both take them as the same class
-// in every state (printable, OSC/DCS data, an ESC or DCS final byte).
-const flipLetter = (c: string): string => LETTERS[(LETTERS.indexOf(c) + 1) % LETTERS.length]
-
-// Text, C0 (BEL, CAN, SUB and others), DEL, ESC, the 7-bit introducer letters, 8-bit introducers and
-// other C1, and non-ASCII (U+00A0 is where xterm's NON_ASCII_PRINTABLE starts).
-const SINGLES = [
- '\x00', '\t', '\n', '\r', BEL, '\x18', '\x1a', '\x19', '\x1c', '\x7f', ESC, ']', 'P', 'X', '^', '_', '[',
- '\\', ';', '0', '9', ' ', '(', 'é', '\u00a0', '🙂', '\x85', '\x99', '\x9b', '\x9c', '\x9d', '\x90', '\x98',
- '\x9e', '\x9f'
-]
-const SNIPPETS = [
- [ESC, ']'], [ESC, 'P'], [ESC, 'X'], [ESC, '^'], [ESC, '_'], [ESC, '\\'], [ESC, '['], [ESC, ESC], [ESC, '\n'],
- [ESC, '\x7f'], [ESC, '('], [ESC, '\x9d'], ['\x9d'], ['\x90'], ['\x9c'], [BEL],
- [ESC, ']', '5', '2', ';', 'c', ';'], [ESC, ']', '8', ';', ';'], [ESC, 'P', 'q'], [ESC, 'P', '1', ';', '2', '$', 'q'],
- ['\x90', 'q'], [ESC, '_', 'G']
-]
-
-/** A random stream as code points, so a join lands between code points like a decoded pty read. */
-function randomStream(rand: (n: number) => number): string[] {
- const cps: string[] = []
- for (let parts = 1 + rand(40); parts > 0; parts--) {
- const kind = rand(10)
- if (kind < 4) for (let i = 1 + rand(6); i > 0; i--) cps.push(LETTERS[rand(LETTERS.length)])
- else if (kind < 8) cps.push(...SNIPPETS[rand(SNIPPETS.length)])
- else cps.push(SINGLES[rand(SINGLES.length)])
- }
- return cps
-}
-
-function filterInChunks(text: string, cuts: number[], midStream: boolean): string[] {
- const f = createStreamFilter({ midStream })
- const outs: string[] = []
- let from = 0
- for (const to of [...cuts, text.length]) {
- outs.push(f.push(text.slice(from, to)))
- from = to
- }
- return outs
-}
-
-const codePoints = (s: string): number[] => Array.from(s, (c) => c.codePointAt(0) ?? 0)
-
-/**
- * Feeds the stream from code point `join` on (xterm itself read it from the start), once as it is
- * and once with every string-payload letter after the join changed, cut into the same random
- * chunks; the two outputs must be equal, and xterm must not enter a string reading the output, as a
- * whole or any one push of it (the caller may drop pushes). Returns how many letters were changed.
- */
-function checkNothingHiddenReachesOutput(cps: string[], join: number, midStream: boolean, rand: (n: number) => number): number {
- const payload = xtermStringPayload(cps.map((c) => c.codePointAt(0) ?? 0))
- let flips = 0
- const changed = cps.map((c, i) => {
- if (i < join || !payload[i] || !IS_LETTER.has(c)) return c
- flips++
- return flipLetter(c)
- })
- const text = cps.slice(join).join('')
- const cuts: number[] = []
- for (let k = rand(4); k > 0; k--) cuts.push(rand(text.length + 1))
- cuts.sort((a, b) => a - b)
- const outs = filterInChunks(text, cuts, midStream)
- const out = outs.join('')
- const ctx = JSON.stringify({ stream: cps.join(''), join, midStream, cuts, out })
- expect(filterInChunks(changed.slice(join).join(''), cuts, midStream).join(''), ctx).toBe(out)
- for (const piece of [out, ...outs]) expect(xtermEntersString(codePoints(piece)), ctx).toBe(false)
- return flips
-}
-
-describe('createStreamFilter against xterm 5.5', () => {
- // R66: the copied blocks carry xterm.js's MIT notice in full — every line of the installed package's
- // LICENSE, in order, in the fixture's header comment.
- it("the fixture carries xterm's MIT permission notice, verbatim from the installed LICENSE", () => {
- const fixture = read(join(__dirname, '__fixtures__', 'xterm-vt500.ts'))
- const header = fixture.slice(0, fixture.indexOf('// ---- BEGIN verbatim'))
- const comment = header
- .split('\n')
- .map((l) => l.replace(/^\/\/ ?/, ''))
- .join('\n')
- const license = read(join(XTERM_PARSER, '..', '..', '..', 'LICENSE')).trim()
- expect(license).toMatch(/^Copyright \(c\)/)
- expect(license).toContain('Permission is hereby granted')
- expect(comment).toContain(license)
- })
-
- it('the model is the installed xterm parser table, verbatim', () => {
- const fixture = read(join(__dirname, '__fixtures__', 'xterm-vt500.ts'))
- const constants = read(join(XTERM_PARSER, 'Constants.ts'))
- const parser = read(join(XTERM_PARSER, 'EscapeSequenceParser.ts'))
- const blocks: [string, string, string][] = [
- [constants, 'export const enum ParserState {', '\n}'],
- [constants, 'export const enum ParserAction {', '\n}'],
- [parser, 'const enum TableAccess {', '\n}'],
- [parser, 'export class TransitionTable {', '\n}'],
- [parser, 'const NON_ASCII_PRINTABLE = 0xA0;', ';'],
- [parser, 'export const VT500_TRANSITION_TABLE = (function (): TransitionTable {', '\n})();']
- ]
- for (const [src, start, end] of blocks) {
- expect(block(fixture, start, end), `re-copy ${start} from the installed xterm`).toBe(block(src, start, end))
- }
- })
-
- it("the model's walk is parse()'s: the lines of it that step() stands for are unchanged", () => {
- // step() is not a copy but a statement of these lines of EscapeSequenceParser.parse()'s sync
- // loop, so an upgrade that changes only parse() must reach this test too.
- const parser = read(join(XTERM_PARSER, 'EscapeSequenceParser.ts'))
- const loop = block(parser, '// continue with main sync loop', 'this.currentState = transition & TableAccess.TRANSITION_STATE_MASK;')
- const actionCase = (action: string): string => {
- const i = loop.indexOf(`case ParserAction.${action}:`)
- const j = loop.indexOf('case ParserAction.', i + 1)
- return i === -1 ? `<missing case ${action}>` : loop.slice(i, j === -1 ? loop.length : j)
- }
- const lines = (text: string, line: string): number => text.split('\n').filter((l) => l.trim() === line).length
- // The table lookup and the state it moves to.
- expect(lines(loop, 'transition = this._transitions.table[this.currentState << TableAccess.INDEX_STATE_SHIFT | (code < 0xa0 ? code : NON_ASCII_PRINTABLE)];')).toBe(1)
- expect(loop.endsWith('this.currentState = transition & TableAccess.TRANSITION_STATE_MASK;')).toBe(true)
- // An OSC or DCS ended by ESC goes to ESCAPE, not the table's GROUND; nothing else is patched.
- const escPatch = 'if (code === 0x1b) transition |= ParserState.ESCAPE;'
- expect(lines(actionCase('OSC_END'), escPatch)).toBe(1)
- expect(lines(actionCase('DCS_UNHOOK'), escPatch)).toBe(1)
- expect(lines(loop, escPatch)).toBe(2)
- // The read-ahead loops stop exactly where the table would leave the state they are in.
- expect(lines(actionCase('PRINT'), 'if (j >= length || (code = data[j]) < 0x20 || (code > 0x7e && code < NON_ASCII_PRINTABLE)) {')).toBe(1)
- expect(lines(actionCase('PRINT'), 'if (++j >= length || (code = data[j]) < 0x20 || (code > 0x7e && code < NON_ASCII_PRINTABLE)) {')).toBe(3)
- expect(lines(actionCase('PARAM'), '} while (++i < length && (code = data[i]) > 0x2f && code < 0x3c);')).toBe(1)
- expect(lines(actionCase('DCS_PUT'), 'if (j >= length || (code = data[j]) === 0x18 || code === 0x1a || code === 0x1b || (code > 0x7f && code < NON_ASCII_PRINTABLE)) {')).toBe(1)
- expect(lines(actionCase('OSC_PUT'), 'if (j >= length || (code = data[j]) < 0x20 || (code > 0x7f && code < NON_ASCII_PRINTABLE)) {')).toBe(1)
- })
-
- it('nothing xterm hides reaches the output, from the start of a stream', () => {
- const rand = rng(0xc0ffee)
- let flips = 0
- for (let n = 0; n < 3000; n++) flips += checkNothingHiddenReachesOutput(randomStream(rand), 0, false, rand)
- // Not vacuous: the seeded run changes ~51k payload letters here, ~28k in the midStream run.
- expect(flips).toBeGreaterThan(20_000)
- })
-
- it('nothing xterm hides reaches the output, joined at a random offset (midStream)', () => {
- const rand = rng(0x10ad)
- let flips = 0
- for (let n = 0; n < 3000; n++) {
- const cps = randomStream(rand)
- flips += checkNothingHiddenReachesOutput(cps, rand(cps.length + 1), true, rand)
- }
- expect(flips).toBeGreaterThan(10_000)
- })
-})
diff --git a/src/core/watch-link/token-bucket.test.ts b/src/core/watch-link/token-bucket.test.ts
deleted file mode 100644
index 1a50f3bb9..000000000
--- a/src/core/watch-link/token-bucket.test.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-import { describe, it, expect } from 'vitest'
-import { createTokenBucket } from './token-bucket'
-
-describe('createTokenBucket', () => {
- it('spends a burst, then refills at the rate, never above the burst', () => {
- let t = 0
- const b = createTokenBucket({ ratePerSec: 100, burst: 300, now: () => t })
- expect(b.take(300)).toBe(true)
- expect(b.take(1)).toBe(false)
- t = 500
- expect(b.take(50)).toBe(true)
- expect(b.take(1)).toBe(false)
- t = 100_000
- expect(b.take(301)).toBe(false)
- expect(b.take(300)).toBe(true)
- })
-
- it('a refused take spends nothing', () => {
- let t = 0
- const b = createTokenBucket({ ratePerSec: 100, burst: 300, now: () => t })
- expect(b.take(250)).toBe(true)
- expect(b.take(60)).toBe(false)
- expect(b.take(50)).toBe(true)
- t = 10
- expect(b.take(1)).toBe(true)
- expect(b.take(1)).toBe(false)
- })
-
- it('a wall clock stepping backwards neither drains nor refills the bucket', () => {
- // The caller passes Date.now, which NTP can step back; an hour back must not leave the viewer
- // on keyframes for an hour, and the refill resumes from the new reading.
- let t = 10_000_000
- const b = createTokenBucket({ ratePerSec: 100, burst: 300, now: () => t })
- expect(b.take(200)).toBe(true)
- t -= 3_600_000
- expect(b.take(100)).toBe(true)
- expect(b.take(1)).toBe(false)
- t += 1000
- expect(b.take(100)).toBe(true)
- expect(b.take(1)).toBe(false)
- })
-})
diff --git a/src/core/watch-link/token-bucket.ts b/src/core/watch-link/token-bucket.ts
deleted file mode 100644
index 9822f59cf..000000000
--- a/src/core/watch-link/token-bucket.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-// A per-viewer byte budget: a live link must not turn a flooding terminal into unbounded relay
-// traffic. Past it, the viewer gets at most one keyframe per second instead of the stream.
-export interface TokenBucket {
- take(n: number): boolean
-}
-
-export function createTokenBucket(o: { ratePerSec: number; burst: number; now: () => number }): TokenBucket {
- let tokens = o.burst
- let last = o.now()
- return {
- take(n) {
- const t = o.now()
- // `now` may be a wall clock (Date.now), which can step back: a negative interval would drain
- // the bucket for as long as the step, so it counts as none and the refill resumes from `t`.
- tokens = Math.min(o.burst, tokens + (Math.max(0, t - last) / 1000) * o.ratePerSec)
- last = t
- if (n > tokens) return false
- tokens -= n
- return true
- }
- }
-}
diff --git a/src/core/watch-link/watcher-client.realtty.test.ts b/src/core/watch-link/watcher-client.realtty.test.ts
deleted file mode 100644
index bf5baa714..000000000
--- a/src/core/watch-link/watcher-client.realtty.test.ts
+++ /dev/null
@@ -1,313 +0,0 @@
-// A LIVE LINK WATCHER'S OWN TMUX CLIENT, ON A REAL TTY (controller rulings R19, R20).
-//
-// When no Session is held for a node (an app restart, a closed project, a released node), a watcher
-// joins by spawning its OWN tmux client. Measured on tmux 3.4, the owner's `new-session -A` spelling
-// for that client shrank the owner's 120x39 window to 40x9 (tmux's default `window-size latest`
-// makes the newest client the size) — SIGWINCH to a running agent, because somebody opened a link.
-// The watcher's client is therefore `attach-session -E -f ignore-size,read-only -t =nt-<id>:`, and
-// each word is load-bearing; this file measures each one on a real pty:
-// - ignore-size: while the owner is attached, the owner's window and its own client keep their size.
-// NOT unconditional: tmux 3.4 honours it only while an unflagged client is attached
-// somewhere on the server; alone, the watcher sizes the window like any client — the
-// last describe measures that rule and the sync that keeps the window where it was;
-// - read-only: bytes typed into the watcher's client never reach the pane;
-// - -E: attaching does not run `update-environment`, which would STRIP every listed name the
-// watcher's own env lacks (the account scope, CLAUDE_CONFIG_DIR — CLAUDE.md #419);
-// - attach-session (never new-session -A): a session that is gone is not re-created bare;
-// - the exact target: a prefix of a live session's name attaches to nothing.
-// The SSH arm is proven the same way: the generated remote line runs under a real /bin/sh inside a
-// real pty, with a stub that re-points `-L nodeterm-rmt` at this file's private socket.
-//
-// Private socket in a private TMUX_TMPDIR; sessions killed by exact target. Skipped (with the reason)
-// where there is no tmux binary or node-pty cannot load.
-import { describe, it, expect, beforeAll, afterAll } from 'vitest'
-import { execFileSync } from 'child_process'
-import fs from 'fs'
-import path from 'path'
-import { localWatcherAttachArgs, localWindowSizeArgs, parseWindowSize } from './watcher-client'
-import { remoteTmuxWatcherArgs, RMT_TMUX_SOCKET } from '../remote-ssh/control-master'
-import { makeTmuxTmpdir } from '../tmux-test-socket'
-import { testTmpDir } from '../test-tmp'
-
-let pty: typeof import('node-pty') | null = null
-try {
- pty = await import('node-pty')
-} catch {
- pty = null
-}
-const REAL_TMUX = (() => {
- if (process.platform === 'win32') return null
- try {
- return execFileSync('/bin/sh', ['-c', 'command -v tmux'], { encoding: 'utf8' }).trim() || null
- } catch {
- return null
- }
-})()
-// Needs both: the measurement is of tmux, and only a real tty can be a sized tmux client.
-const itReal = it.skipIf(!REAL_TMUX || !pty)
-
-const SOCKET = `nt-wlrt-${process.pid}`
-/** A variable the conf lists in `update-environment`, like the account-scope names production lists. */
-const SCOPED = 'CLAUDE_CONFIG_DIR'
-let tmp = ''
-let delegateDir = ''
-const sessions: string[] = []
-const clients: Array<import('node-pty').IPty> = []
-
-function baseEnv(): Record<string, string> {
- const env = { ...process.env, TMUX_TMPDIR: tmp } as Record<string, string>
- delete env.TMUX
- delete env.TMUX_PANE
- delete env[SCOPED]
- return env
-}
-
-function tmux(args: string[], env = baseEnv()): string {
- return execFileSync(REAL_TMUX!, ['-L', SOCKET, ...args], { env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })
-}
-function tryTmux(args: string[]): { ok: boolean; out: string } {
- try {
- return { ok: true, out: tmux(args) }
- } catch (e) {
- return { ok: false, out: String((e as { stderr?: string }).stderr ?? '') }
- }
-}
-
-const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms))
-async function until(check: () => boolean, ms = 3000): Promise<void> {
- const start = Date.now()
- while (!check() && Date.now() - start < ms) await sleep(25)
-}
-
-interface Client {
- proc: import('node-pty').IPty
- exit: { exitCode: number } | null
- out: string
-}
-function spawnClient(file: string, args: string[], cols: number, rows: number, env: Record<string, string>): Client {
- const proc = pty!.spawn(file, args, { name: 'xterm-256color', cols, rows, env })
- clients.push(proc)
- const c: Client = { proc, exit: null, out: '' }
- proc.onData((d) => (c.out += d))
- proc.onExit((e) => (c.exit = e))
- return c
-}
-
-const windowSize = (name: string): string =>
- tmux(['display-message', '-p', '-t', `=${name}:`, '#{window_width}x#{window_height}']).trim()
-const clientsOf = (name: string): string[] =>
- tmux(['list-clients', '-t', `=${name}`, '-F', '#{client_width}x#{client_height} #{client_flags}'])
- .split('\n')
- .filter(Boolean)
-
-/** The owner: a normal attached client at 120x40 whose env carries the scoped variable. */
-async function ownerOf(name: string): Promise<Client> {
- const owner = spawnClient(REAL_TMUX!, ['-L', SOCKET, 'attach-session', '-t', `=${name}`], 120, 40, {
- ...baseEnv(),
- [SCOPED]: '/accounts/a1'
- })
- await until(() => windowSize(name) === '120x39')
- return owner
-}
-
-function newSession(name: string, script: string): void {
- tmux(['new-session', '-d', '-s', name, '-x', '120', '-y', '40', script], { ...baseEnv(), [SCOPED]: '/accounts/a1' })
- sessions.push(name)
-}
-
-beforeAll(() => {
- if (!REAL_TMUX || !pty) return
- tmp = makeTmuxTmpdir('ntwr-', SOCKET)
- // Boot the private server with a session that keeps it alive, then list the scoped name in
- // `update-environment` exactly as the production conf does for the account scope.
- tmux(['-f', '/dev/null', 'new-session', '-d', '-s', 'keepalive', 'sleep 120'])
- sessions.push('keepalive')
- tmux(['set', '-g', 'update-environment', SCOPED])
- delegateDir = path.join(testTmpDir('ntwrd-'), 'bin')
- fs.mkdirSync(delegateDir)
- fs.writeFileSync(
- path.join(delegateDir, 'tmux'),
- `#!/bin/sh\n[ "$1" = "-L" ] && [ "$2" = "${RMT_TMUX_SOCKET}" ] || exit 99\nshift 2\nexec '${REAL_TMUX}' -L '${SOCKET}' "$@"\n`,
- { mode: 0o755 }
- )
-})
-
-afterAll(() => {
- for (const c of clients) {
- try {
- c.kill()
- } catch {
- /* already gone */
- }
- }
- if (!REAL_TMUX || !pty) return
- // Every session on this file's PRIVATE socket, each by exact target — including one a regression
- // might have CREATED (a watcher spelled `new-session -A` makes a login shell that never exits and
- // would keep the server alive after the directory is gone).
- const listed = tryTmux(['list-sessions', '-F', '#{session_name}'])
- const names = new Set([...sessions, ...(listed.ok ? listed.out.split('\n').filter(Boolean) : [])])
- for (const name of names) tryTmux(['kill-session', '-t', `=${name}`])
- fs.rmSync(tmp, { recursive: true, force: true })
-})
-
-describe("a watcher's own tmux client (local)", () => {
- itReal('with the owner attached, the watcher does not resize the window: 120x39, owner view unchanged', async () => {
- newSession('nt-own', 'sleep 120')
- await ownerOf('nt-own')
- const before = clientsOf('nt-own')
- const watcher = spawnClient(REAL_TMUX!, localWatcherAttachArgs(SOCKET, 'nt-own'), 40, 10, baseEnv())
- await until(() => clientsOf('nt-own').length === 2)
- await sleep(200)
- expect(watcher.exit).toBeNull()
- expect(windowSize('nt-own')).toBe('120x39')
- const after = clientsOf('nt-own')
- expect(after).toContain(before[0]) // the owner's client: same size, same flags
- expect(after.some((c) => c.includes('ignore-size') && c.includes('read-only'))).toBe(true)
- watcher.proc.kill()
- })
-
- itReal('does not strip the session env the watcher lacks (-E: no update-environment)', async () => {
- newSession('nt-env', 'sleep 120')
- await ownerOf('nt-env')
- expect(tmux(['show-environment', '-t', '=nt-env', SCOPED]).trim()).toBe(`${SCOPED}=/accounts/a1`)
- const watcher = spawnClient(REAL_TMUX!, localWatcherAttachArgs(SOCKET, 'nt-env'), 40, 10, baseEnv())
- await until(() => clientsOf('nt-env').length === 2)
- await sleep(200)
- expect(watcher.exit).toBeNull()
- expect(tmux(['show-environment', '-t', '=nt-env', SCOPED]).trim()).toBe(`${SCOPED}=/accounts/a1`)
- watcher.proc.kill()
- })
-
- itReal('read-only: what reaches the watcher client never reaches the pane', async () => {
- newSession('nt-ro', 'cat')
- const owner = await ownerOf('nt-ro')
- const watcher = spawnClient(REAL_TMUX!, localWatcherAttachArgs(SOCKET, 'nt-ro'), 40, 10, baseEnv())
- await until(() => clientsOf('nt-ro').length === 2)
- watcher.proc.write('FROM-WATCHER\r')
- await sleep(300)
- expect(tmux(['capture-pane', '-p', '-t', '=nt-ro:'])).not.toContain('FROM-WATCHER')
- // Control: the owner's client does type.
- owner.proc.write('FROM-OWNER\r')
- await until(() => tmux(['capture-pane', '-p', '-t', '=nt-ro:']).includes('FROM-OWNER'))
- expect(tmux(['capture-pane', '-p', '-t', '=nt-ro:'])).toContain('FROM-OWNER')
- watcher.proc.kill()
- })
-
- itReal('a session that is gone is not created: the client exits and nothing appears', async () => {
- const watcher = spawnClient(REAL_TMUX!, localWatcherAttachArgs(SOCKET, 'nt-gone'), 40, 10, baseEnv())
- await until(() => watcher.exit !== null)
- expect(watcher.exit?.exitCode).not.toBe(0)
- expect(tryTmux(['has-session', '-t', '=nt-gone']).ok).toBe(false)
- })
-
- itReal('a prefix of a live session name attaches to nothing', async () => {
- newSession('nt-p-12', 'sleep 120')
- const watcher = spawnClient(REAL_TMUX!, localWatcherAttachArgs(SOCKET, 'nt-p-1'), 40, 10, baseEnv())
- await until(() => watcher.exit !== null)
- expect(watcher.exit?.exitCode).not.toBe(0)
- expect(clientsOf('nt-p-12')).toEqual([])
- expect(tryTmux(['has-session', '-t', '=nt-p-1']).ok).toBe(false)
- })
-
- itReal('the window-size read answers the live window, and nothing for a miss', async () => {
- newSession('nt-sz', 'sleep 120')
- await ownerOf('nt-sz')
- // The owner's 120x40 client with tmux's default status line: window 120x39, client size 120x40.
- expect(parseWindowSize(tmux(localWindowSizeArgs(SOCKET, 'nt-sz').slice(2)))).toEqual({ cols: 120, rows: 40 })
- expect(parseWindowSize(tmux(localWindowSizeArgs(SOCKET, 'nt-s').slice(2)))).toBeUndefined()
- })
-})
-
-describe("a watcher's own tmux client (SSH arm, the generated remote line under a real /bin/sh)", () => {
- itReal('attaches read-only and ignore-size: with the owner attached the window stays 120x39, env intact', async () => {
- newSession('nt-rw', 'sleep 120')
- await ownerOf('nt-rw')
- const line = remoteTmuxWatcherArgs({ host: 'h', user: 'u' }, '/cm/p1', 'nt-rw').at(-1)!
- const watcher = spawnClient('/bin/sh', ['-c', line], 40, 10, { ...baseEnv(), PATH: `${delegateDir}:/usr/bin:/bin` })
- await until(() => clientsOf('nt-rw').length === 2)
- await sleep(200)
- expect(watcher.exit).toBeNull()
- expect(windowSize('nt-rw')).toBe('120x39')
- expect(clientsOf('nt-rw').some((c) => c.includes('ignore-size') && c.includes('read-only'))).toBe(true)
- expect(tmux(['show-environment', '-t', '=nt-rw', SCOPED]).trim()).toBe(`${SCOPED}=/accounts/a1`)
- watcher.proc.kill()
- })
-
- itReal('a gone remote session is not created', async () => {
- const line = remoteTmuxWatcherArgs({ host: 'h', user: 'u' }, '/cm/p1', 'nt-rgone').at(-1)!
- const watcher = spawnClient('/bin/sh', ['-c', line], 40, 10, { ...baseEnv(), PATH: `${delegateDir}:/usr/bin:/bin` })
- await until(() => watcher.exit !== null)
- expect(watcher.exit?.exitCode).not.toBe(0)
- expect(tryTmux(['has-session', '-t', '=nt-rgone']).ok).toBe(false)
- })
-})
-
-// R20 — `ignore-size` is honoured only while an UNFLAGGED client is attached somewhere on the server.
-// Its own private server (not SOCKET above, where the owner clients of the tests before stay attached
-// until afterAll and would keep `ignore-size` honoured). Sessions carry the production conf's
-// `status off`, so the window IS the client size.
-describe("keeping a watcher's own client at the window size (sync)", () => {
- const SYNC_SOCKET = `nt-wlsy-${process.pid}`
- const syncSessions: string[] = []
- const tx = (args: string[]): string =>
- execFileSync(REAL_TMUX!, ['-L', SYNC_SOCKET, ...args], {
- env: baseEnv(),
- encoding: 'utf8',
- stdio: ['ignore', 'pipe', 'pipe']
- })
- const win = (name: string): string =>
- tx(['display-message', '-p', '-t', `=${name}:`, '#{window_width}x#{window_height}']).trim()
- /** Exactly what `readWindowSize` + the spawn/sync do: the production argv, parsed. */
- const readSize = (name: string): { cols: number; rows: number } =>
- parseWindowSize(tx(localWindowSizeArgs(SYNC_SOCKET, name).slice(2)))!
-
- afterAll(() => {
- if (!REAL_TMUX || !pty) return
- for (const name of syncSessions) {
- try {
- tx(['kill-session', '-t', `=${name}`])
- } catch {
- /* gone */
- }
- }
- })
-
- async function scenario(name: string, sync: boolean): Promise<string[]> {
- const seen: string[] = []
- // `-f /dev/null` on the first call boots this private server with tmux defaults.
- tx(['-f', '/dev/null', 'new-session', '-d', '-s', name, '-x', '120', '-y', '40', 'sleep 120', ';', 'set-option', 'status', 'off'])
- syncSessions.push(name)
- // The watcher's own client, spawned at the window size read just before (spawnNew).
- const size = readSize(name)
- seen.push(`${size.cols}x${size.rows}`)
- const watcher = spawnClient(REAL_TMUX!, localWatcherAttachArgs(SYNC_SOCKET, name), size.cols, size.rows, baseEnv())
- await until(() => tx(['list-clients', '-t', `=${name}`]).trim().split('\n').filter(Boolean).length === 1)
- // An owner-style (unflagged) client joins and sizes the window to 200x50.
- const owner = spawnClient(REAL_TMUX!, ['-L', SYNC_SOCKET, 'attach-session', '-t', `=${name}`], 200, 50, baseEnv())
- await until(() => win(name) === '200x50')
- seen.push(win(name))
- if (sync) {
- // syncWatcherClientSize's step, restated here: read the window, resize the watcher's OWN pty to
- // exactly that. This file measures the TMUX rule the step relies on; the production step itself
- // (one read, the client resized only when the size changed, never a vote, serialized per
- // session) is pinned in src/core/pty-watch-join.test.ts ("syncWatcherClientSize").
- const now = readSize(name)
- watcher.proc.resize(now.cols, now.rows)
- await sleep(200)
- }
- owner.proc.kill()
- await until(() => tx(['list-clients', '-t', `=${name}`]).trim().split('\n').filter(Boolean).length === 1)
- await sleep(300)
- seen.push(win(name))
- watcher.proc.kill()
- return seen
- }
-
- itReal('control, WITHOUT sync: once the unflagged client leaves, the window snaps to the watcher (120x40)', async () => {
- expect(await scenario('nt-nosync', false)).toEqual(['120x40', '200x50', '120x40'])
- })
-
- itReal('WITH sync: the window keeps its latest size (200x50) after the unflagged client leaves', async () => {
- expect(await scenario('nt-sync', true)).toEqual(['120x40', '200x50', '200x50'])
- })
-})
diff --git a/src/core/watch-link/watcher-client.test.ts b/src/core/watch-link/watcher-client.test.ts
deleted file mode 100644
index 062e3f330..000000000
--- a/src/core/watch-link/watcher-client.test.ts
+++ /dev/null
@@ -1,84 +0,0 @@
-import { describe, it, expect } from 'vitest'
-import {
- WATCHER_CLIENT_FLAGS,
- WINDOW_SIZE_FORMAT,
- localWatcherAttachArgs,
- localWindowSizeArgs,
- parseTmuxVersion,
- parseWindowSize,
- supportsWatcherClient
-} from './watcher-client'
-
-describe('localWatcherAttachArgs', () => {
- const args = localWatcherAttachArgs('sock', 'nt-abc')
-
- it('attaches (never creates), skips update-environment, ignore-size and read-only', () => {
- expect(args).toEqual(['-L', 'sock', 'attach-session', '-E', '-f', 'ignore-size,read-only', '-t', '=nt-abc:'])
- expect(WATCHER_CLIENT_FLAGS).toBe('ignore-size,read-only')
- })
-
- it('has no create or take-over flag', () => {
- expect(args).not.toContain('new-session')
- expect(args).not.toContain('-A')
- expect(args).not.toContain('-D')
- expect(args).not.toContain('-d')
- })
-
- it('targets the session EXACTLY', () => {
- expect(args.filter((a) => a.includes('nt-abc'))).toEqual(['=nt-abc:'])
- })
-})
-
-describe('localWindowSizeArgs / parseWindowSize', () => {
- it('reads the window size of exactly this session, with its status lines', () => {
- expect(WINDOW_SIZE_FORMAT).toBe('#{window_width} #{window_height} #{status}')
- expect(localWindowSizeArgs('sock', 'nt-abc')).toEqual([
- '-L',
- 'sock',
- 'display-message',
- '-p',
- '-t',
- '=nt-abc:',
- '#{window_width} #{window_height} #{status}'
- ])
- })
-
- it('answers the CLIENT size that leaves the window where it is: window + status lines', () => {
- // The production conf has `status off`: the client size IS the window size.
- expect(parseWindowSize('120 40 off\n')).toEqual({ cols: 120, rows: 40 })
- // tmux defaults (`status on`): a client one row taller than the window, or the window loses a row.
- expect(parseWindowSize('120 39 on\n')).toEqual({ cols: 120, rows: 40 })
- expect(parseWindowSize('120 37 3\n')).toEqual({ cols: 120, rows: 40 })
- expect(parseWindowSize('80 24 off\r\n')).toEqual({ cols: 80, rows: 24 })
- })
-
- it('an exact-target miss (exit 0, every format empty) is no size, never 0x0', () => {
- for (const out of ['', ' \n', '\n', '0 24 off\n', '80 0 off\n', 'a b off\n', '80 24\n', '80 24 7\n', '80 24 yes\n', ' 80 24 off\n']) {
- expect(parseWindowSize(out)).toBeUndefined()
- }
- })
-})
-
-describe('parseTmuxVersion / supportsWatcherClient', () => {
- it('reads the versions tmux actually prints', () => {
- expect(parseTmuxVersion('tmux 3.4\n')).toEqual({ major: 3, minor: 4 })
- expect(parseTmuxVersion('tmux 3.2a\n')).toEqual({ major: 3, minor: 2 })
- expect(parseTmuxVersion('tmux 3.1c')).toEqual({ major: 3, minor: 1 })
- expect(parseTmuxVersion('tmux next-3.6')).toEqual({ major: 3, minor: 6 })
- expect(parseTmuxVersion('tmux 2.9a')).toEqual({ major: 2, minor: 9 })
- expect(parseTmuxVersion('tmux 10.0')).toEqual({ major: 10, minor: 0 })
- })
-
- it('an unreadable version is null', () => {
- for (const out of ['', 'tmux master', 'not tmux', 'tmux 3']) expect(parseTmuxVersion(out)).toBeNull()
- })
-
- it('client flags (-f ignore-size,read-only) need tmux 3.2; unknown fails closed', () => {
- expect(supportsWatcherClient({ major: 3, minor: 2 })).toBe(true)
- expect(supportsWatcherClient({ major: 3, minor: 4 })).toBe(true)
- expect(supportsWatcherClient({ major: 4, minor: 0 })).toBe(true)
- expect(supportsWatcherClient({ major: 3, minor: 1 })).toBe(false)
- expect(supportsWatcherClient({ major: 2, minor: 9 })).toBe(false)
- expect(supportsWatcherClient(null)).toBe(false)
- })
-})
diff --git a/src/core/watch-link/watcher-client.ts b/src/core/watch-link/watcher-client.ts
deleted file mode 100644
index 0dadb6e64..000000000
--- a/src/core/watch-link/watcher-client.ts
+++ /dev/null
@@ -1,81 +0,0 @@
-// A live link watcher's OWN tmux client — the one it spawns when no Session is held for the node
-// (after an app restart, for a closed project, for a released node). Pure: argv builders and parsers.
-//
-// The owner's spelling for a client, `new-session -A`, is wrong here in three ways, each measured on
-// tmux 3.4 (watcher-client.realtty.test.ts):
-// - SIZE. Under tmux's default `window-size latest` the newest client sets the window size: a watcher
-// at 40x10 shrank the owner's 120x39 window to 40x9 — a SIGWINCH to the agent running there, because
-// somebody opened a link. With `-f ignore-size` the window stayed at 120x39 and the owner's client as
-// it was — BUT only because the owner was attached: tmux 3.4 honours `ignore-size` only while at least
-// one client WITHOUT the flag is attached to some session on the same server. A watcher that is the
-// only client sizes the window like any other (measured: spawned at 40x10 alone → window 40x10; spawned
-// at 120x40, an owner joins at 200x50 and leaves → the window snaps back to 120x40). So the client is
-// spawned at the window's CURRENT size, read just before the spawn, and refused when that read fails
-// (`PtyManager.spawnNew`); `PtyManager.syncWatcherClientSize` keeps it at the window's size while the
-// link has viewers. Residual: drift for up to one sync interval, and a read racing an owner's resize
-// or departure (the window then keeps the size read a moment before).
-// - ENVIRONMENT. Attaching runs `update-environment`, which copies every listed name from the attaching
-// client's env into the session and STRIPS the ones that client lacks — the account scope
-// (CLAUDE_CONFIG_DIR, …, CLAUDE.md #419) included. `-E` skips it; the session env is untouched.
-// - CREATION. `new-session -A` creates when the session is gone, so a session that died between the
-// strict existence verdict and the spawn would be re-created bare, by a viewer. `attach-session`
-// never creates: it exits 1 ("can't find session") and nothing appears.
-// `read-only` is a belt: nothing is ever written into a watcher's pty, and if something were, tmux
-// drops input from a read-only client.
-//
-// The target is exact, `=nt-<id>:` (a bare name prefix-matches another node's session; measured, see
-// capture-route.ts). For attach-session both `=name` and `=name:` are exact; `=name:` is kept so every
-// watch-link target is spelled one way.
-//
-// Client flags (`-f`) need tmux 3.2. Locally the version is probed (`supportsWatcherClient`) and an
-// older or unreadable one refuses the watcher; over SSH the remote tmux rejects the flags itself.
-import { capturePaneTarget } from '../capture-route'
-
-export const WATCHER_CLIENT_FLAGS = 'ignore-size,read-only'
-
-/** The local tmux argv (after the binary) for a watcher's own client. */
-export function localWatcherAttachArgs(socket: string, sessionName: string): string[] {
- return ['-L', socket, 'attach-session', '-E', '-f', WATCHER_CLIENT_FLAGS, '-t', capturePaneTarget(sessionName)]
-}
-
-/**
- * What a watcher's client must be sized to so it leaves the window exactly where it is: the window's
- * width and height, plus the status lines tmux draws under it on that session (`#{status}`: `off`,
- * `on` = 1, or `2`–`5`). With the production conf (`set -g status off`) that is the window size itself;
- * a host whose server runs tmux's defaults (status on — a remote conf that was never sourced) would
- * otherwise lose one row to the status line every time the watcher, as the only client, set the size.
- */
-export const WINDOW_SIZE_FORMAT = '#{window_width} #{window_height} #{status}'
-
-export function localWindowSizeArgs(socket: string, sessionName: string): string[] {
- return ['-L', socket, 'display-message', '-p', '-t', capturePaneTarget(sessionName), WINDOW_SIZE_FORMAT]
-}
-
-/** `"<width> <height> <status>"` → the client size for that window (see `WINDOW_SIZE_FORMAT`), both
- * positive. An exact-target miss answers exit 0 with every format EMPTY, so anything else is no size,
- * never 0x0; an unknown status value is no size too. */
-export function parseWindowSize(stdout: string): { cols: number; rows: number } | undefined {
- const m = /^(\d+) (\d+) (off|on|[0-5])$/.exec(stdout.replace(/\r?\n$/, ''))
- if (!m) return undefined
- const cols = Number(m[1])
- const height = Number(m[2])
- const statusLines = m[3] === 'off' ? 0 : m[3] === 'on' ? 1 : Number(m[3])
- return cols > 0 && height > 0 ? { cols, rows: height + statusLines } : undefined
-}
-
-export interface TmuxVersion {
- major: number
- minor: number
-}
-
-/** `tmux -V` → `{major, minor}`: `tmux 3.4`, `tmux 3.2a`, `tmux next-3.6`. null when unreadable
- * (`tmux master`, a failed probe). */
-export function parseTmuxVersion(stdout: string): TmuxVersion | null {
- const m = /(\d+)\.(\d+)/.exec(stdout)
- return m ? { major: Number(m[1]), minor: Number(m[2]) } : null
-}
-
-/** Client flags (`attach-session -f`) first shipped in tmux 3.2. An unknown version fails closed. */
-export function supportsWatcherClient(v: TmuxVersion | null): boolean {
- return !!v && (v.major > 3 || (v.major === 3 && v.minor >= 2))
-}
diff --git a/src/core/watch-link/watcher-policy.test.ts b/src/core/watch-link/watcher-policy.test.ts
deleted file mode 100644
index 0bd2dbe88..000000000
--- a/src/core/watch-link/watcher-policy.test.ts
+++ /dev/null
@@ -1,216 +0,0 @@
-import { describe, it, expect } from 'vitest'
-import { IPC } from '../../shared/ipc'
-import { encodePtyData, decodePtyData } from '../../shared/rpc'
-import {
- WATCH_CHAT_CAST,
- WATCH_EVENT,
- WATCH_HISTORY_CAST,
- WATCH_INPUT_CAST,
- WATCH_RELEASE_CAST,
- WATCH_UNLOCK_CAST,
- type WatchLinkRole
-} from '../../shared/watch-link/protocol'
-import { watcherAccess, watcherEventAllowed, wrapWatcherSink, WATCHER_BUFFER_LIMIT, WATCHER_REFUSAL } from './watcher-policy'
-import { createStreamFilter, type StreamFilter } from './stream-filter'
-import { createTokenBucket } from './token-bucket'
-import type { UiSink } from '../ui-sink-registry'
-
-const channelValues = (): string[] =>
- (Object.values(IPC) as unknown[]).filter((v): v is string => typeof v === 'string')
-/** Every per-id channel factory in IPC (`pty:data:<sid>`, `pty:size:<sid>`, …). */
-const channelFactories = (): Array<(id: string) => string> =>
- (Object.values(IPC) as unknown[]).filter((v): v is (id: string) => string => typeof v === 'function')
-
-const ROLES: readonly WatchLinkRole[] = ['viewer', 'commenter', 'controller']
-
-describe('watcherAccess', () => {
- it('refuses every IPC channel as a request and as a cast, for every role', () => {
- for (const ch of channelValues()) {
- for (const role of ROLES) {
- expect(watcherAccess('req', ch, role).allow).toBe(false)
- expect(watcherAccess('cast', ch, role).allow).toBe(false)
- }
- }
- })
- it('allows the chat cast only for a commenter link, and never as a request', () => {
- expect(watcherAccess('cast', WATCH_CHAT_CAST, 'commenter')).toEqual({ allow: true })
- expect(watcherAccess('cast', WATCH_CHAT_CAST, 'viewer').allow).toBe(false)
- expect(watcherAccess('req', WATCH_CHAT_CAST, 'commenter').allow).toBe(false)
- })
-
- // The whole inbound surface, three roles by every viewer method there is (plus one that is not),
- // as a request and as a cast. Exactly these are admitted; everything else is the same refusal.
- it('admits exactly: history for every role, chat for commenter and controller, unlock / input / release for controller, all as casts', () => {
- const admitted = new Set([
- `cast ${WATCH_HISTORY_CAST} viewer`,
- `cast ${WATCH_HISTORY_CAST} commenter`,
- `cast ${WATCH_HISTORY_CAST} controller`,
- `cast ${WATCH_CHAT_CAST} commenter`,
- `cast ${WATCH_CHAT_CAST} controller`,
- `cast ${WATCH_UNLOCK_CAST} controller`,
- `cast ${WATCH_INPUT_CAST} controller`,
- `cast ${WATCH_RELEASE_CAST} controller`
- ])
- const methods = [WATCH_CHAT_CAST, WATCH_HISTORY_CAST, WATCH_UNLOCK_CAST, WATCH_INPUT_CAST, WATCH_RELEASE_CAST, 'watch:anything']
- let allowed = 0
- for (const kind of ['req', 'cast'] as const) {
- for (const method of methods) {
- for (const role of ROLES) {
- const key = `${kind} ${method} ${role}`
- const d = watcherAccess(kind, method, role)
- if (admitted.has(key)) {
- expect(d, key).toEqual({ allow: true })
- allowed++
- } else {
- expect(d, key).toEqual({ allow: false, message: WATCHER_REFUSAL })
- }
- }
- }
- }
- expect(allowed).toBe(admitted.size)
- })
-})
-
-describe('watcherEventAllowed', () => {
- it('passes watch:* and this session\'s pty:size only', () => {
- expect(watcherEventAllowed(WATCH_EVENT.meta, null)).toBe(true)
- expect(watcherEventAllowed(IPC.ptySize('s1'), 's1')).toBe(true)
- expect(watcherEventAllowed(IPC.ptySize('s2'), 's1')).toBe(false)
- expect(watcherEventAllowed(IPC.ptySize('s11'), 's1')).toBe(false)
- expect(watcherEventAllowed(IPC.ptySize('s1'), null)).toBe(false)
- })
- it('refuses this session\'s lifecycle and resync events (consumed, or history)', () => {
- for (const ch of [IPC.ptyExit('s1'), IPC.ptyClosed('s1'), IPC.ptyRecycled('s1'), IPC.ptyResync('s1')]) {
- expect(watcherEventAllowed(ch, 's1')).toBe(false)
- }
- })
- it('refuses every broadcast channel in IPC', () => {
- for (const ch of channelValues()) expect(watcherEventAllowed(ch, 's1')).toBe(false)
- })
- it('passes exactly one per-session channel in IPC: pty:size of this session', () => {
- const factories = channelFactories()
- expect(factories.length).toBeGreaterThan(5)
- for (const f of factories) {
- expect(watcherEventAllowed(f('s1'), 's1')).toBe(f === IPC.ptySize)
- expect(watcherEventAllowed(f('s2'), 's1')).toBe(false)
- }
- })
-})
-
-function harness(
- o: { streaming?: boolean; buffered?: number; rate?: number; burst?: number; filter?: StreamFilter } = {}
-) {
- const text: string[] = []
- const bin: string[] = []
- const base: UiSink = {
- sendText: (j) => text.push(j),
- sendBinary: (b) => bin.push(decodePtyData(b)!.data),
- bufferedAmount: () => o.buffered ?? 0
- }
- const calls = { over: 0, life: [] as string[] }
- let streaming = o.streaming ?? true
- const sink = wrapWatcherSink(base, {
- sessionId: () => 's1',
- streaming: () => streaming,
- filter: o.filter ?? createStreamFilter(),
- bucket: createTokenBucket({ ratePerSec: o.rate ?? 1e9, burst: o.burst ?? o.rate ?? 1e9, now: () => 0 }),
- onOverBudget: () => { calls.over++ },
- onLifecycle: (k) => { calls.life.push(k) }
- })
- return { sink, text, bin, calls, setStreaming: (v: boolean) => { streaming = v } }
-}
-const ev = (channel: string, ...args: unknown[]) => JSON.stringify({ t: 'ev', channel, args })
-
-describe('wrapWatcherSink', () => {
- it('forwards watch:* events and this session\'s pty:size', () => {
- const h = harness()
- const meta = ev(WATCH_EVENT.meta, { v: 1 })
- const size = ev(IPC.ptySize('s1'), 80, 24)
- h.sink.sendText(meta)
- h.sink.sendText(size)
- expect(h.text).toEqual([meta, size])
- })
- it('drops broadcast events and another session\'s data', () => {
- const h = harness()
- h.sink.sendText(ev('canvas:mut', 'p1', {}))
- h.sink.sendText(ev('presence:sync', []))
- h.sink.sendBinary(encodePtyData('s2', 'other'))
- expect(h.text).toEqual([])
- expect(h.bin).toEqual([])
- })
- it('filters the stream and keeps the parser fed while not streaming', () => {
- const h = harness({ streaming: false })
- h.sink.sendBinary(encodePtyData('s1', 'x\x1b]52;c;c2Vj'))
- h.setStreaming(true)
- h.sink.sendBinary(encodePtyData('s1', 'cmV0\x07visible'))
- expect(h.bin).toEqual(['visible'])
- })
- it('never lets another session\'s bytes move this viewer\'s parser', () => {
- const h = harness()
- h.sink.sendBinary(encodePtyData('s2', '\x1b]52;c;'))
- h.sink.sendBinary(encodePtyData('s1', 'visible'))
- expect(h.bin).toEqual(['visible'])
- })
- it('reports its session\'s lifecycle events and forwards none of them', () => {
- const h = harness()
- h.sink.sendText(ev(IPC.ptyExit('s1'), 0))
- // `{by}` names another client: never for a viewer's eyes.
- h.sink.sendText(ev(IPC.ptyClosed('s1'), { by: 3 }))
- h.sink.sendText(ev(IPC.ptyRecycled('s1'), { ready: true }))
- expect(h.calls.life).toEqual(['exit', 'closed', 'recycled'])
- expect(h.text).toEqual([])
- })
- it('ignores another session\'s lifecycle events and refuses a resync', () => {
- const h = harness()
- h.sink.sendText(ev(IPC.ptyExit('s2'), 0))
- h.sink.sendText(ev(IPC.ptyClosed('s2'), { by: 3 }))
- h.sink.sendText(ev(IPC.ptyRecycled('s2'), { ready: true }))
- h.sink.sendText(ev(IPC.ptyResync('s1'), 'HISTORY \x1b]8;;https://x\x07link\x1b]8;;\x07'))
- expect(h.calls.life).toEqual([])
- expect(h.text).toEqual([])
- })
- it('goes over budget when the socket backs up or the bucket is empty', () => {
- const backed = harness({ buffered: WATCHER_BUFFER_LIMIT + 1 })
- backed.sink.sendBinary(encodePtyData('s1', 'a'))
- expect(backed.bin).toEqual([])
- expect(backed.calls.over).toBe(1)
- const poor = harness({ rate: 5 })
- poor.sink.sendBinary(encodePtyData('s1', 'this is more than five bytes'))
- expect(poor.bin).toEqual([])
- expect(poor.calls.over).toBe(1)
- })
- it('keeps bufferedAmount pointing at the base sink', () => {
- expect(harness({ buffered: 42 }).sink.bufferedAmount?.()).toBe(42)
- })
-
- // A viewer that co-attaches to a RUNNING session is handed a `midStream` filter by the link host.
- // Its first frame may start inside an OSC 52 (tmux emits one per copy): the clipboard's base64
- // must not reach the viewer as text, however it is split across frames.
- it('forwards no payload byte when joined mid-OSC-52 with a midStream filter', () => {
- const secret = ['c2VjcmV0', 'LXBhc3N3b3Jk', 'LWZvci10aGUtY2xpcGJvYXJk']
- const frames = [secret[0], secret[1], `${secret[2]}\x07`, '\x1b[0mvisible']
- const h = harness({ filter: createStreamFilter({ midStream: true }) })
- for (const f of frames) h.sink.sendBinary(encodePtyData('s1', f))
- expect(h.bin).toEqual(['\x1b[0mvisible'])
- for (const part of secret) expect(h.bin.join('')).not.toContain(part)
- // Control: the same join through a filter that assumes it saw the stream from the start is
- // exactly the leak `midStream` exists to close.
- const naive = harness()
- for (const f of frames) naive.sink.sendBinary(encodePtyData('s1', f))
- expect(naive.bin.join('')).toContain(secret[0])
- })
-
- // A pty frame is coalesced up to 256 K UTF-16 units plus one read chunk, so a frame can be larger
- // than the bucket's burst and can then NEVER be taken. It goes over budget (the link host repaints
- // with a keyframe) instead of throwing, and it drains nothing: the next frame still passes.
- it('sends a frame larger than the burst over budget, forwards nothing, and does not throw', () => {
- const burst = 1024 * 1024
- const h = harness({ rate: 256 * 1024, burst })
- const huge = 'a'.repeat(burst + 1)
- expect(() => h.sink.sendBinary(encodePtyData('s1', huge))).not.toThrow()
- expect(h.calls.over).toBe(1)
- expect(h.bin).toEqual([])
- h.sink.sendBinary(encodePtyData('s1', 'small'))
- expect(h.bin).toEqual(['small'])
- })
-})
diff --git a/src/core/watch-link/watcher-policy.ts b/src/core/watch-link/watcher-policy.ts
deleted file mode 100644
index 9ec32dbc5..000000000
--- a/src/core/watch-link/watcher-policy.ts
+++ /dev/null
@@ -1,142 +0,0 @@
-// The `watcher` relay role, as two RelayHostHooks pieces. It deliberately does NOT go through
-// access-policy.ts's `decideAccess`: that function evaluates any non-editor role against the whole
-// VIEW table (files, git, presence, board log), and a live link may reach none of it.
-// - Inbound: every request and cast is refused, except the read-back cast (`watch:history`) on
-// every link, the chat cast on a Commenter or Control link, and the unlock / input / release casts
-// on a Control link. The read-back is only ever the watched agent's conversation since the link
-// was created (./history.ts), which every role was shown live. The policy knows only the role:
-// whether THIS viewer may type (it unlocked with the link's password) is the link host's
-// per-connection state, and the link host refuses input from a viewer that is not controlling.
-// - Outbound, deny by default too: `watch:*` events, this viewer's own pty data frames (filtered,
-// paced) and its session's `pty:size`, nothing else. Every broadcast is dropped (a second layer:
-// the watcher is also a QUIET client, absent from broadcast() and clientIds()).
-// - `pty:exit` / `pty:closed` / `pty:recycled` are CONSUMED (`onLifecycle`, which answers with
-// `watch:waiting`) and never forwarded: `pty:closed` carries `{by: ClientId}`, which identifies
-// another client of this core.
-// - `pty:resync` is refused. Its payload is the registry's default capture, which is history on
-// the SSH and session-host paths and carries OSC 8 verbatim; a watcher repaints only through
-// `watch:keyframe` (a visible-only capture passed through a fresh filter). The registry never
-// resyncs a self-paced client anyway; this is the second layer.
-// The viewer page reads `pty:size` and nothing else among pty events.
-import { IPC } from '../../shared/ipc'
-import { decodePtyData, decodePtyDataSessionId, encodePtyData } from '../../shared/rpc'
-import {
- WATCH_CHAT_CAST,
- WATCH_EVENT_PREFIX,
- WATCH_HISTORY_CAST,
- WATCH_INPUT_CAST,
- WATCH_RELEASE_CAST,
- WATCH_UNLOCK_CAST,
- type WatchLinkRole
-} from '../../shared/watch-link/protocol'
-import type { AccessDecision } from '../relay/relay-host'
-import type { UiSink } from '../ui-sink-registry'
-import type { StreamFilter } from './stream-filter'
-import type { TokenBucket } from './token-bucket'
-
-export const WATCHER_REFUSAL = 'A live link can only watch this terminal.'
-export const WATCHER_BUFFER_LIMIT = 512 * 1024
-export const WATCHER_RESUME_BELOW = 256 * 1024
-
-const CONTROL_CASTS: ReadonlySet<string> = new Set([WATCH_UNLOCK_CAST, WATCH_INPUT_CAST, WATCH_RELEASE_CAST])
-
-/** The ONLY admits: the read-back for every link, chat for a Commenter or Control link, unlock /
- * input / release for a Control link, all as casts. Every request, and everything else, is refused. */
-export function watcherAccess(kind: 'req' | 'cast', method: string, role: WatchLinkRole): AccessDecision {
- if (kind !== 'cast') return { allow: false, message: WATCHER_REFUSAL }
- if (method === WATCH_HISTORY_CAST) return { allow: true }
- if (method === WATCH_CHAT_CAST && (role === 'commenter' || role === 'controller')) return { allow: true }
- if (CONTROL_CASTS.has(method) && role === 'controller') return { allow: true }
- return { allow: false, message: WATCHER_REFUSAL }
-}
-
-/** The events a viewer may receive: `watch:*`, and its own session's `pty:size`. Nothing else. */
-export function watcherEventAllowed(channel: string, sessionId: string | null): boolean {
- if (channel.startsWith(WATCH_EVENT_PREFIX)) return true
- return !!sessionId && channel === IPC.ptySize(sessionId)
-}
-
-export type PtyLifecycle = 'exit' | 'closed' | 'recycled'
-
-function lifecycleOf(channel: string, sessionId: string): PtyLifecycle | null {
- if (channel === IPC.ptyExit(sessionId)) return 'exit'
- if (channel === IPC.ptyClosed(sessionId)) return 'closed'
- if (channel === IPC.ptyRecycled(sessionId)) return 'recycled'
- return null
-}
-
-/**
- * What the link host supplies. A throw from `onLifecycle`, `onOverBudget` or `filter.push` is not
- * caught here: it propagates into `UiSinkRegistry.deliver` as a sink strike, and two in a row evict
- * the watcher (the session is torn down). That fails closed, which is the intent.
- */
-export interface WatcherSinkDeps {
- sessionId(): string | null
- /** False until the keyframe for the current session was sent, and while throttled. */
- streaming(): boolean
- /** Per viewer, created by the link host: `{ midStream: true }` for a join to a running session. */
- filter: StreamFilter
- /** Counts encoded BYTES (the frame as it goes on the wire), not characters. */
- bucket: TokenBucket
- /**
- * A frame was dropped (socket backed up, or the bucket refused it). MUST make `streaming()` false
- * before it returns, until a keyframe repaints: otherwise the next frame that fits the bucket is
- * forwarded after the dropped one with no keyframe between. The filter stays in step either way
- * (it saw the dropped bytes), but the viewer's screen is wrong until the next repaint.
- */
- onOverBudget(): void
- /** This session exited, was closed or recycled. The event itself is never forwarded. */
- onLifecycle(kind: PtyLifecycle): void
-}
-
-function channelOf(json: string): string | null {
- try {
- const m = JSON.parse(json) as { t?: unknown; channel?: unknown }
- return m && m.t === 'ev' && typeof m.channel === 'string' ? m.channel : null
- } catch {
- return null
- }
-}
-
-export function wrapWatcherSink(base: UiSink, d: WatcherSinkDeps): UiSink {
- return {
- sendText: (json) => {
- const channel = channelOf(json)
- if (channel === null) return
- const sid = d.sessionId()
- const life = sid ? lifecycleOf(channel, sid) : null
- if (life) {
- d.onLifecycle(life)
- return
- }
- if (!watcherEventAllowed(channel, sid)) return
- base.sendText(json)
- },
- sendBinary: (buf) => {
- const sid = d.sessionId()
- // The header alone decides: another session's payload is never decoded, and its bytes never
- // reach this viewer's parser.
- if (!sid || decodePtyDataSessionId(buf) !== sid) return
- const frame = decodePtyData(buf)
- if (!frame) return
- // Always parse, even when nothing is forwarded (see stream-filter.ts).
- const text = d.filter.push(frame.data)
- if (!d.streaming() || !text) return
- if ((base.bufferedAmount?.() ?? 0) > WATCHER_BUFFER_LIMIT) {
- d.onOverBudget()
- return
- }
- const out = encodePtyData(sid, text)
- // `out.length` is encoded BYTES. A pty frame is coalesced up to MAX_BUF_BYTES (256 K UTF-16
- // units, pty-manager.ts) plus one read chunk, so it can exceed the bucket's burst, and such a
- // take can never succeed: it goes over budget like any other refusal (the link host repaints
- // with a keyframe), and a refused take drains nothing.
- if (!d.bucket.take(out.length)) {
- d.onOverBudget()
- return
- }
- base.sendBinary(out)
- },
- bufferedAmount: () => base.bufferedAmount?.() ?? 0
- }
-}
diff --git a/src/core/watch-link/wire.test.ts b/src/core/watch-link/wire.test.ts
deleted file mode 100644
index 5ea8297b6..000000000
--- a/src/core/watch-link/wire.test.ts
+++ /dev/null
@@ -1,199 +0,0 @@
-import { describe, it, expect } from 'vitest'
-import { hkdfSync } from 'node:crypto'
-import { readFileSync } from 'node:fs'
-import { join } from 'node:path'
-import nacl from 'tweetnacl'
-import { encodePtyData, encodeArgs, parseRpcMessage } from '../../shared/rpc'
-import { decrypt, deriveSessionKey, encrypt, randomSessionNonce } from '../relay/e2ee'
-import { hkdfSha256 } from '../../shared/watch-link/hkdf'
-import { sealBox, openBox, withHeader, readHeader, encodePtyFrame, decodePtyFrame, parseTunnelJson, NONCE_BYTES, RELAY_SESSION_INFO } from '../../shared/watch-link/wire'
-import {
- sanitizeChatText,
- sanitizeChatName,
- isWatchEndReason,
- CHAT_NAME_MAX,
- CHAT_TEXT_MAX,
- WATCH_CHAT_CAST,
- WATCH_EVENT,
- WATCH_EVENT_PREFIX
-} from '../../shared/watch-link/protocol'
-import { concatBytes, utf8 } from '../../shared/watch-link/bytes'
-import { isHostOnlyChannel } from '../../shared/host-control'
-import { BIDI_CONTROL_CHARS } from '../../shared/presence'
-
-describe('the wire rules match the relay they were copied from', () => {
- it('HKDF equals node:crypto', async () => {
- const ikm = nacl.randomBytes(32), salt = nacl.randomBytes(32)
- const ours = await hkdfSha256(ikm, salt, utf8(RELAY_SESSION_INFO), 32)
- expect(ours).toEqual(new Uint8Array(hkdfSync('sha256', ikm, salt, utf8(RELAY_SESSION_INFO), 32)))
- })
- it("HKDF info and salt order equal the relay's deriveSessionKey", async () => {
- // The test above feeds OUR info string to both sides, so it cannot see the relay's change.
- // This one derives the relay's session key from its own code: salt = hostNonce ‖ clientNonce.
- const base = nacl.randomBytes(32), hn = randomSessionNonce(), cn = randomSessionNonce()
- expect(await hkdfSha256(base, concatBytes(hn, cn), utf8(RELAY_SESSION_INFO), 32)).toEqual(deriveSessionKey(base, hn, cn))
- })
- it("the session-key vectors nodeterm-web tests against are the relay's deriveSessionKey", () => {
- const vectors = JSON.parse(readFileSync(join(__dirname, '../../shared/watch-link/vectors.json'), 'utf8').replace(/\r\n/g, '\n'))
- const hex = (h: string): Uint8Array => Uint8Array.from(Buffer.from(h, 'hex'))
- expect(vectors.sessionKeys.length).toBeGreaterThan(0)
- for (const v of vectors.sessionKeys) {
- const key = deriveSessionKey(hex(v.baseKeyHex), hex(v.hostNonceHex), hex(v.clientNonceHex))
- expect(Buffer.from(key).toString('hex')).toBe(v.sessionKeyHex)
- }
- })
- it("the session nonce is as long as e2ee's randomSessionNonce", () => {
- expect(randomSessionNonce()).toHaveLength(NONCE_BYTES)
- })
- it('a box sealed here opens with e2ee.decrypt and vice versa', () => {
- const key = nacl.randomBytes(32), plain = utf8('hello')
- expect(decrypt(sealBox(plain, key), key)).toEqual(plain)
- expect(openBox(encrypt(plain, key), key)).toEqual(plain)
- expect(openBox(Uint8Array.of(1, 2, 3), key)).toBeNull()
- })
- it('the header is role, seq high word LE, seq low word LE', () => {
- const h = withHeader(2, 2 ** 32 + 7, utf8('x'))
- expect(Array.from(h.slice(0, 9))).toEqual([2, 1, 0, 0, 0, 7, 0, 0, 0])
- expect(readHeader(h)).toEqual({ role: 2, seq: 2 ** 32 + 7, body: utf8('x') })
- expect(readHeader(Uint8Array.of(1, 2))).toBeNull()
- })
- it('pty frames equal rpc.ts', () => {
- const sid = 'sess-é', data = 'a\u001b[31mbé'
- expect(encodePtyFrame(sid, data)).toEqual(encodePtyData(sid, data))
- expect(decodePtyFrame(encodePtyData(sid, data))).toEqual({ sessionId: sid, data })
- expect(decodePtyFrame(Uint8Array.of(9))).toBeNull()
- })
- it('tunnel JSON parses like parseRpcMessage, undefined slots included', () => {
- const ev = JSON.stringify({ t: 'ev', channel: 'watch:meta', ...encodeArgs([{ a: 1 }, undefined]) })
- expect(parseTunnelJson(ev)).toEqual(parseRpcMessage(ev))
- const cast = JSON.stringify({ t: 'cast', method: 'trust:confirm', args: [] })
- expect(parseTunnelJson(cast)).toEqual({ t: 'cast', method: 'trust:confirm', args: [] })
- expect(parseTunnelJson('{"t":"res","id":1,"ok":true,"result":1}')).toBeNull()
- expect(parseTunnelJson('nope')).toBeNull()
- })
- it('an `undef` list restores only valid slot indices; junk entries are ignored', () => {
- const m = parseTunnelJson(JSON.stringify({ t: 'ev', channel: 'c', args: ['a', 'b', 'c'], undef: [-1, 1.5, '0', 99, null, 2] }))
- expect(m).toEqual({ t: 'ev', channel: 'c', args: ['a', 'b', undefined] })
- // A non-list `undef` restores nothing.
- expect(parseTunnelJson(JSON.stringify({ t: 'ev', channel: 'c', args: ['a'], undef: 0 }))).toEqual({ t: 'ev', channel: 'c', args: ['a'] })
- })
- it('a pty frame whose session-id length runs past the frame is refused, not read short', () => {
- const f = encodePtyFrame('abc', 'data')
- expect(decodePtyFrame(f)).toEqual({ sessionId: 'abc', data: 'data' })
- const lying = f.slice()
- lying[1] = 0xff // sidLen = 0xff03, far past the frame
- expect(decodePtyFrame(lying)).toBeNull()
- expect(decodePtyFrame(Uint8Array.of(0x01, 0x00, 0x05, 0x61, 0x62))).toBeNull() // sidLen 5, 2 bytes
- })
- it('readHeader reads a view that starts inside a larger buffer (a nonzero byteOffset)', () => {
- const h = withHeader(2, 2 ** 32 + 7, utf8('xy'))
- const backing = new Uint8Array(h.length + 13)
- backing.fill(0xee)
- backing.set(h, 5)
- const view = backing.subarray(5, 5 + h.length)
- expect(view.byteOffset).toBe(5)
- expect(readHeader(view)).toEqual({ role: 2, seq: 2 ** 32 + 7, body: utf8('xy') })
- })
- it('every sealed frame draws a fresh box nonce (the caller cannot supply one)', () => {
- const key = nacl.randomBytes(32), plain = utf8('same')
- const a = sealBox(plain, key), b = sealBox(plain, key)
- expect(a.subarray(0, nacl.box.nonceLength)).not.toEqual(b.subarray(0, nacl.box.nonceLength))
- expect(sealBox.length).toBe(2)
- })
-})
-
-describe('protocol', () => {
- it('the viewer cast is not in the host-only owner namespace', () => {
- expect(WATCH_CHAT_CAST.startsWith('watchLink:')).toBe(false)
- expect(WATCH_EVENT_PREFIX).toBe('watch:')
- })
- // relay-host refuses a host-only channel from every peer BEFORE any policy runs: the viewer's one
- // cast, and every event the host sends a viewer, must not be one of them (asked of the real rule,
- // not of a prefix this test assumes).
- it('the viewer cast and every viewer event are not host-only channels', () => {
- expect(isHostOnlyChannel(WATCH_CHAT_CAST)).toBe(false)
- for (const ch of Object.values(WATCH_EVENT)) expect(isHostOnlyChannel(ch)).toBe(false)
- // …while the owner's namespace is.
- expect(isHostOnlyChannel('watchLink:create')).toBe(true)
- })
- it('sanitizes chat text and names', () => {
- expect(sanitizeChatText(' hi\u0007 there\nfriend \u009b ')).toBe('hi there friend')
- expect(sanitizeChatText('x'.repeat(600))).toHaveLength(500)
- expect(sanitizeChatText(' ')).toBeNull()
- expect(sanitizeChatText(42)).toBeNull()
- expect(sanitizeChatName('\u001b[31mAda')).toBe('[31mAda')
- expect(sanitizeChatName('n'.repeat(40))).toHaveLength(32)
- expect(isWatchEndReason('kicked')).toBe(true)
- expect(isWatchEndReason('nope')).toBe(false)
- })
- it('strips every bidi control, from text and from names', () => {
- // An RLO would reorder everything the owner's popover and every viewer draw after it.
- expect(sanitizeChatText('ok \u202Egnihsihp\u202C done')).toBe('ok gnihsihp done')
- expect(sanitizeChatName('Ada\u2066\u200F\u061C\u200E\u202A\u2069')).toBe('Ada')
- expect(sanitizeChatText('\u202E\u2067')).toBeNull()
- // A ZWJ is not a bidi control: an emoji sequence survives.
- expect(sanitizeChatText('hi \u{1F469}\u200D\u{1F4BB}')).toBe('hi \u{1F469}\u200D\u{1F4BB}')
- })
- it("chat strips every @shared/presence bidi control (restated: this directory imports nothing outside), and from text exactly the invisible format characters but the two joiners", () => {
- // Over the whole BMP, outside the controls and the whitespace the sanitizer handles anyway: a
- // character is stripped from chat TEXT if and only if it is a format character (Cf) other than
- // ZWNJ / ZWJ — and every one presence calls a bidi control is among them.
- const cf = /^\p{Cf}$/u
- let checked = 0
- for (let cp = 0; cp <= 0xffff; cp++) {
- if (cp >= 0xd800 && cp <= 0xdfff) continue
- if (cp <= 0x1f || (cp >= 0x7f && cp <= 0x9f)) continue
- const ch = String.fromCharCode(cp)
- if (/\s/.test(ch)) continue
- BIDI_CONTROL_CHARS.lastIndex = 0
- const bidi = BIDI_CONTROL_CHARS.test(ch)
- const invisible = cf.test(ch) && cp !== 0x200c && cp !== 0x200d
- const stripped = sanitizeChatText(`a${ch}b`) === 'ab'
- if (bidi && !stripped) expect.fail(`U+${cp.toString(16)}: a presence bidi control kept in chat`)
- if (stripped !== invisible) expect.fail(`U+${cp.toString(16)}: invisible=${invisible}, stripped from chat=${stripped}`)
- if (bidi && sanitizeChatName(`a${ch}b`) !== 'ab') expect.fail(`U+${cp.toString(16)}: a presence bidi control kept in a name`)
- checked++
- }
- expect(checked).toBeGreaterThan(60_000)
- })
- it('a NAME keeps no invisible character: every format character, and the blank letters, go', () => {
- // Finding L4: "Sharer" and "Sharer" + an invisible character were two names drawn alike.
- for (const ch of ['\u200b', '\u200c', '\u200d', '\u2060', '\u00ad', '\ufeff', '\u034f', '\u115f', '\u1160', '\u2800', '\u3164', '\uffa0', '\u{e0041}', '\u{e007f}']) {
- expect(sanitizeChatName(`Sha${ch}rer${ch}`)).toBe('Sharer')
- }
- // Over the whole BMP: a name loses every format character.
- for (let cp = 0; cp <= 0xffff; cp++) {
- if (cp >= 0xd800 && cp <= 0xdfff) continue
- const ch = String.fromCharCode(cp)
- if (/^\p{Cf}$/u.test(ch) && sanitizeChatName(`a${ch}b`) !== 'ab') expect.fail(`U+${cp.toString(16)} kept in a name`)
- }
- // A name made only of them is no name.
- expect(sanitizeChatName('\u200b\u3164\u2800')).toBeNull()
- // Visible letters and emoji stay (an emoji sequence loses its joiner in a NAME: a name is a claim).
- expect(sanitizeChatName('Ayşe')).toBe('Ayşe')
- expect(sanitizeChatName('Ada \u{1F469}\u200D\u{1F4BB}')).toBe('Ada \u{1F469}\u{1F4BB}')
- })
- it('chat TEXT keeps the zero-width joiner (emoji sequences) and the non-joiner (Persian, the Indic scripts), and loses the other invisibles', () => {
- expect(sanitizeChatText('hi \u{1F469}\u200D\u{1F4BB}')).toBe('hi \u{1F469}\u200D\u{1F4BB}')
- expect(sanitizeChatText('\u0645\u06cc\u200c\u062e\u0648\u0627\u0645')).toBe('\u0645\u06cc\u200c\u062e\u0648\u0627\u0645')
- expect(sanitizeChatText('pass\u200bword\u00ad \u2060here\u{e0041}')).toBe('password here')
- })
- it('caps by code point, never leaving half a surrogate pair', () => {
- // 499 units, then an astral character (2 units): it does not fit in 500, so it is left out WHOLE.
- const text = sanitizeChatText('x'.repeat(CHAT_TEXT_MAX - 1) + '\u{1F600}tail')!
- expect(text).toBe('x'.repeat(CHAT_TEXT_MAX - 1))
- expect(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])/.test(text)).toBe(false)
- const name = sanitizeChatName('\u{1F600}'.repeat(40))!
- expect(name).toBe('\u{1F600}'.repeat(CHAT_NAME_MAX / 2))
- expect(name.length).toBe(CHAT_NAME_MAX)
- })
- it('bounds the raw input before the cleaning chain: a huge cast costs the cap, not its size', () => {
- // 4x the cap is read; anything past it never reaches the regex chain (and cannot reach the text).
- const huge = 'y'.repeat(CHAT_TEXT_MAX * 4) + 'MARKER' + 'z'.repeat(5_000_000)
- expect(sanitizeChatText(huge)).toBe('y'.repeat(CHAT_TEXT_MAX))
- // Whitespace and controls that collapse away inside the bound do not empty an honest message.
- expect(sanitizeChatText('\u0007'.repeat(CHAT_TEXT_MAX * 2) + 'hello')).toBe('hello')
- // A leading run longer than the bound is cut with it: the cleaned text may be EMPTY.
- expect(sanitizeChatText(' '.repeat(CHAT_TEXT_MAX * 4) + 'late')).toBeNull()
- })
-})
diff --git a/src/core/workspace-store.test.ts b/src/core/workspace-store.test.ts
index 4594f316e..676da5b5d 100644
--- a/src/core/workspace-store.test.ts
+++ b/src/core/workspace-store.test.ts
@@ -2491,32 +2491,10 @@ describe('knownNodeIds — every node id in every project, or undefined when it
await fresh.load()
expect(fresh.knownNodeIds()).toBeUndefined()
})
- // R44: a lost workspace.json is rebuilt from nothing — the renderer's boot save writes an EMPTY
- // index while every project.json still holds its nodes. Read as complete, it said every node was
- // gone (a live link revoked a second after launch). The STRICT accessor (live links) answers unknown
- // for the rest of such a run…
- it('the strict accessor stays undefined for the rest of a run whose index was lost or corrupt, whatever is saved after', async () => {
- await new WorkspaceStore().save(ws([project({ id: 'p-local', cwd: projRoot })]))
- for (const lose of ['corrupt', 'deleted'] as const) {
- const index = path.join(userData, 'workspace.json')
- if (lose === 'corrupt') await fs.writeFile(index, '{nope')
- else await fs.rm(index, { force: true })
- const store = new WorkspaceStore()
- await store.load()
- await store.save(ws([]))
- expect(store.knownNodeIdsStrict()).toBeUndefined()
- await store.save(ws([project({ id: 'p-local', cwd: projRoot })]))
- expect(store.knownNodeIdsStrict()).toBeUndefined()
- // The next run reads a readable index again, and answers.
- const next = new WorkspaceStore()
- await next.load()
- expect([...(next.knownNodeIdsStrict() ?? [])]).toEqual(['term-1'])
- }
- })
- // …while the agent-status MIRROR's accessor keeps its behaviour from before live links (R64/M2):
- // pruning an identity against a rebuilt index costs one hook event, and the flag lasts the whole
- // process — a Server Edition started on a fresh data dir runs for weeks.
- it("the mirror's accessor answers in such a run, exactly as before (it never reads the rebuild flag)", async () => {
+ // A lost workspace.json is rebuilt from nothing — the renderer's boot save writes an EMPTY index
+ // while every project.json still holds its nodes. The agent-status mirror's accessor answers in
+ // such a run: pruning an identity against a rebuilt index costs one hook event to restore.
+ it("the mirror's accessor answers in a run whose index was lost or corrupt", async () => {
await new WorkspaceStore().save(ws([project({ id: 'p-local', cwd: projRoot })]))
for (const lose of ['corrupt', 'deleted'] as const) {
const index = path.join(userData, 'workspace.json')
@@ -2532,22 +2510,15 @@ describe('knownNodeIds — every node id in every project, or undefined when it
expect([...(store.knownNodeIds() ?? [])]).toEqual(['term-1'])
}
})
- // Re-review NEW-1: an index of the right version that cannot be BUILT (loadV3 throws: a `cwd` that
- // is not a string) keeps rejecting as before, and marks the run like any other unreadable index.
- it('a v3 index whose build throws still rejects the load, and marks the run (strict only)', async () => {
+ // An index of the right version that cannot be BUILT (loadV3 throws: a `cwd` that is not a
+ // string) keeps rejecting the load.
+ it('a v3 index whose build throws still rejects the load', async () => {
await fs.writeFile(path.join(userData, 'workspace.json'), JSON.stringify({ version: 3, entries: [{ id: 'p1', name: 'x', color: '#fff', cwd: 5 }] }))
const store = new WorkspaceStore()
await expect(store.load()).rejects.toThrow()
await store.save(ws([]))
- expect(store.knownNodeIdsStrict()).toBeUndefined()
expect(store.knownNodeIds()).toEqual(new Set())
})
- it('a readable index: the two accessors agree', async () => {
- const store = new WorkspaceStore()
- await store.save(ws([project({ id: 'p-local', cwd: projRoot })]))
- expect(store.knownNodeIdsStrict()).toEqual(store.knownNodeIds())
- expect(new WorkspaceStore().knownNodeIdsStrict()).toBeUndefined() // not loaded: unknown to both
- })
})
describe('openProjectCount — open projects in the loaded index (the project-limit report)', () => {
diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.ts
index a20614f8f..2a0d4a0ed 100644
--- a/src/core/workspace-store.ts
+++ b/src/core/workspace-store.ts
@@ -358,30 +358,12 @@ export class WorkspaceStore {
private index: WorkspaceIndexV3 | null = null
/** Optional hook fired after every load()/save() — the watcher re-syncs its watch set (Task 5). */
onPersist?: () => void
- /**
- * Some load in THIS run found no readable workspace.json — missing (deleted, a first run, a crash
- * between the corrupt-file set-aside and the next write), unreadable, unparsable, or parsable but no
- * index this build recognises (`{}`, a v3 without entries, a newer build's version) — so whatever
- * index this run holds afterwards may have been rebuilt from NOTHING: the renderer's unconditional
- * boot save writes an EMPTY index over the set-aside file while every project's own
- * `.nodeterm/project.json` still holds its nodes. `knownNodeIdsStrict` then answers undefined for
- * the rest of the run (controller ruling R44): a live link would otherwise read every node as gone
- * and be revoked server-side a second after launch — irreversibly. The cost: a live link's node-gone
- * waits for the next launch with a readable index (links still end at their expiry).
- *
- * Live links ONLY (R64/M2): `knownNodeIds`, which the agent-status mirror prunes identities with,
- * does not read this flag. A mirror entry pruned against an index rebuilt from nothing costs one
- * hook event to restore; the flag lasts for the whole PROCESS, and a Server Edition started on a
- * fresh data dir runs for weeks — R54's first version switched the mirror's pruning off for all of
- * them, so the phone kept listing deleted sessions for up to the 30-day identity TTL.
- */
- private indexRebuiltThisRun = false
/**
* What the most recent `loadInner` found at the index path: `read` (a shape this build builds a
* workspace from, empty or not), `absent` (no file — a first run), or `unreadable` (the file is
* there but could not be read, did not parse, or is a shape this build does not recognise, such
- * as a newer build's). Unlike `indexRebuiltThisRun` it describes the LAST load, not the run, so a
- * caller about to write a fresh index can ask whether doing so would replace one it never read
+ * as a newer build's). It describes the LAST load, so a caller about to write a fresh index can
+ * ask whether doing so would replace one it never read
* (`adoptFolder`, which loads without sidelining and so leaves no backup behind).
*/
private indexReadState: 'read' | 'absent' | 'unreadable' = 'absent'
@@ -486,7 +468,6 @@ export class WorkspaceStore {
raw = await fs.readFile(this.indexPath, 'utf-8')
} catch (err) {
this.indexReadState = (err as NodeJS.ErrnoException)?.code === 'ENOENT' ? 'absent' : 'unreadable'
- this.indexRebuiltThisRun = true // R44: see the field
// No index. Usually a first run — but it is also what a crash BETWEEN the sideline rename
// below and the next index write leaves behind, and that case owes the user the note. Only
// this branch pays for the readdir, and only for a load that may touch disk anyway.
@@ -498,7 +479,6 @@ export class WorkspaceStore {
parsed = JSON.parse(raw)
} catch {
this.indexReadState = 'unreadable'
- this.indexRebuiltThisRun = true // R44: see the field
// Same rule as a corrupt project.json: sideline the only copy so the boot flow's
// unconditional save cannot replace it with an empty index. Read-only callers must not
// mutate the disk (sideline: false).
@@ -522,16 +502,14 @@ export class WorkspaceStore {
return built
} catch (e) {
this.indexReadState = 'unreadable'
- this.indexRebuiltThisRun = true // R44: an index we could not build is not a read of it
throw e
}
}
// v1/v2: assemble in memory now; the first save() performs the actual migration.
const legacy = migrateLegacy(parsed)
// PARSED, but no index this build recognises (`{}`, `null`, `[]`, a v2 without its projects list,
- // a v3 without entries, a newer build's version): the run's index is rebuilt from nothing exactly
- // as for an unparsable file (R44 / re-review NEW-1). A readable EMPTY v2/v3 index is not this.
- if (legacy === EMPTY_WORKSPACE) this.indexRebuiltThisRun = true
+ // a v3 without entries, a newer build's version): read as unreadable. A readable EMPTY v2/v3
+ // index is not this.
this.indexReadState = legacy === EMPTY_WORKSPACE ? 'unreadable' : 'read'
if (legacy.projects.length) this.pendingV2Backup = raw
return legacy
@@ -2493,9 +2471,8 @@ export class WorkspaceStore {
* the entry by its identity TTL alone. Same three-entry-kind scan as `findNode`.
* Consequence: ONE permanently unavailable local ref or one never-cached SSH project turns
* existence pruning off for EVERY project, leaving only the 30-day identity TTL.
- * It does NOT read `indexRebuiltThisRun` (R64/M2): for the mirror an index rebuilt from nothing is
- * an answer, because a wrongly pruned identity costs one hook event to restore. Live links, whose
- * "gone" is an irreversible revoke, ask `knownNodeIdsStrict`.
+ * An index rebuilt from nothing is an answer here: a wrongly pruned identity costs one hook event
+ * to restore.
* Parses through `parsedLastWritten`, so a mirror flush re-parses no unchanged project.json.
*/
knownNodeIds(): Set<string> | undefined {
@@ -2518,17 +2495,6 @@ export class WorkspaceStore {
return ids
}
- /**
- * `knownNodeIds`, for a caller whose "not in any project" is IRREVERSIBLE — a live link, which a node
- * gone ends and revokes server-side (R40). Also undefined for the rest of a run whose index was
- * rebuilt from nothing (`indexRebuiltThisRun`, R44): an empty index written over a lost
- * workspace.json is not a read of the projects it lost.
- */
- knownNodeIdsStrict(): Set<string> | undefined {
- if (this.indexRebuiltThisRun) return undefined
- return this.knownNodeIds()
- }
-
/**
* Every persisted canvas as {id, nodes, bridges} — the raw material the Server Edition derives
* its context-link map from (src/server/context-link.ts). Same three-entry-kind scan as
diff --git a/src/preload/index.ts b/src/preload/index.ts
index 23f4191e6..61c26248c 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -82,7 +82,6 @@ const subscribeProjectSetupConsentDismiss = subscribe<[{ requestId: string }]>(
// payload carries the projectId, fanned out the same way — nobody broadcasts it yet (Task 2), but
// the renderer cache subscribes ahead of the emitter.
const subscribeProjectTrustChanged = subscribe<[{ projectId: string }]>(IPC.projectTrustChanged)
-// Live links: owner-only pushes from core (the node chip, the popover and Settings all listen).
const api: NodeTerminalApi = {
pty: {
diff --git a/src/session-host/host.ts b/src/session-host/host.ts
index a6203114d..d3e007309 100644
--- a/src/session-host/host.ts
+++ b/src/session-host/host.ts
@@ -966,7 +966,7 @@ async function main(): Promise<void> {
const s = sessions.get(req.name)
if (!s || s.exited) return { ok: false, error: 'no such session' }
if (!s.subscribers.has(socket)) return { ok: false, error: 'not attached to session' }
- // A watch attachment (live link / relay viewer) is read-only end to end.
+ // A watch attachment (a relay viewer) is read-only end to end.
if (s.isWatching(socket)) return { ok: false, error: 'watch attachment is read-only' }
s.proc.write(req.data)
return { ok: true }
diff --git a/src/session-host/protocol.ts b/src/session-host/protocol.ts
index 0c0700f78..ed960b5c8 100644
--- a/src/session-host/protocol.ts
+++ b/src/session-host/protocol.ts
@@ -114,8 +114,8 @@ export type SessionHostRequest =
* answers `unknown command`; the client then fails closed and never falls back to sendKeys. */
| { id: number; cmd: 'writeDetachedV1'; name: string; data: string }
| { id: number; cmd: 'capture'; name: string; full: boolean }
- /** `captureVisible` feature only: the VISIBLE rows (no history) plus cursor + active buffer — a
- * live link's keyframe. Never sent to a host that did not advertise it. */
+ /** `captureVisible` feature only: the VISIBLE rows (no history) plus cursor + active buffer.
+ * Never sent to a host that did not advertise it. */
| { id: number; cmd: 'captureVisible'; name: string }
/** `paneCwd` feature only: the last cwd the pane REPORTED (OSC 7 / 9;9 / 633), never the spawn
* cwd. */
diff --git a/src/session-host/session-watch.test.ts b/src/session-host/session-watch.test.ts
index 29da27add..eed47c64f 100644
--- a/src/session-host/session-watch.test.ts
+++ b/src/session-host/session-watch.test.ts
@@ -1,5 +1,5 @@
// HostSession's `watch-attach` transaction and its reported cwd, at unit level (the real-protocol
-// wiring is live-links-host.test.ts). A watch attachment must never contribute a geometry claim or
+// wiring is watch-attach-host.test.ts). A watch attachment must never contribute a geometry claim or
// a pause ticket, and must give up any claim its connection held.
import { describe, expect, it, vi } from 'vitest'
import type { Socket } from 'net'
diff --git a/src/session-host/session.ts b/src/session-host/session.ts
index 3cb9520e6..e70c32dab 100644
--- a/src/session-host/session.ts
+++ b/src/session-host/session.ts
@@ -153,7 +153,7 @@ export class HostSession {
* the minimum across live claims so every viewer fits; removing the smallest claim grows it. */
private readonly geometryClaims = new Map<Socket, Geometry>()
/** Subscribed connections attached in `watch` mode (`watch-attach` feature): they receive output
- * but hold NO geometry claim, so a live link / relay viewer can never size the pty. A claim-
+ * but hold NO geometry claim, so a relay viewer can never size the pty. A claim-
* carrying attach on the same connection takes it out of this set again. */
private readonly watchers = new Set<Socket>()
/** The cwd the pane last REPORTED in its output (OSC 7 / 9;9 / 633 — see cwd-report.ts). Null
diff --git a/src/session-host/terminal-emulator.test.ts b/src/session-host/terminal-emulator.test.ts
index c5ad3b80f..eeef55ef1 100644
--- a/src/session-host/terminal-emulator.test.ts
+++ b/src/session-host/terminal-emulator.test.ts
@@ -17,7 +17,7 @@ function text(screen: string): string {
return screen.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '')
}
-describe('TerminalEmulator.captureVisible (live link keyframe)', () => {
+describe('TerminalEmulator.captureVisible (the visible-screen capture)', () => {
it('returns exactly the visible rows — no history — with the cursor and SGR', async () => {
const e = emulator()
let data = ''
diff --git a/src/session-host/terminal-emulator.ts b/src/session-host/terminal-emulator.ts
index 995806bc7..c4828b0e4 100644
--- a/src/session-host/terminal-emulator.ts
+++ b/src/session-host/terminal-emulator.ts
@@ -88,7 +88,7 @@ export class TerminalEmulator {
}
/**
- * A live link's keyframe: the VISIBLE rows of the ACTIVE buffer only (never history), in the shape
+ * The visible-screen capture: the VISIBLE rows of the ACTIVE buffer only (never history), in the shape
* `capture-pane -p -e` prints — SGR, one `\n`-terminated line per row — plus the viewport-relative
* cursor and whether the alternate buffer is active.
*
diff --git a/src/session-host/live-links-host.test.ts b/src/session-host/watch-attach-host.test.ts
similarity index 97%
rename from src/session-host/live-links-host.test.ts
rename to src/session-host/watch-attach-host.test.ts
index 22141f200..aa73e5889 100644
--- a/src/session-host/live-links-host.test.ts
+++ b/src/session-host/watch-attach-host.test.ts
@@ -1,6 +1,6 @@
-// Live links on the session host: drives the REAL bundled host over its real socket protocol for the
+// The session host's watch-attach and visible capture: drives the REAL bundled host over its real socket protocol for the
// three negotiated additions — `watch-attach` (a viewer subscribes with NO geometry claim and cannot
-// type or resize), `captureVisible` (the keyframe: visible rows + cursor + active buffer) and `paneCwd`
+// type or resize), `captureVisible` (visible rows + cursor + active buffer) and `paneCwd`
// (the cwd the pane REPORTED, never the spawn cwd). The fake pty echoes every write back as output,
// so a test types escape sequences in and reads what the host's emulator made of them.
import { afterEach, describe, expect, it } from 'vitest'
@@ -23,7 +23,7 @@ import { sessionHostPaths, type SessionHostState } from './paths'
function fakePtyPlugin(): Plugin {
return {
- name: 'session-host-live-links-fake-pty',
+ name: 'session-host-watch-attach-fake-pty',
setup(bundle) {
bundle.onResolve({ filter: /^node-pty$/ }, () => ({ path: 'node-pty', namespace: 'geo' }))
bundle.onLoad({ filter: /^node-pty$/, namespace: 'geo' }, () => ({
@@ -145,7 +145,7 @@ function dataSeen(events: SessionHostEvent[], marker: string): boolean {
return events.some((event) => event.type === 'data' && event.data.includes(marker))
}
-describe('session-host live link features', () => {
+describe('session-host watch-attach features', () => {
it('watch-attach, captureVisible and paneCwd over the real protocol', async () => {
const fixtureDir = mkdtempSync(path.join(os.tmpdir(), 'nt-session-host-live-'))
cleanupPaths.push(fixtureDir)
diff --git a/src/shared/host-control.test.ts b/src/shared/host-control.test.ts
index 34869ddd5..a4cb066e2 100644
--- a/src/shared/host-control.test.ts
+++ b/src/shared/host-control.test.ts
@@ -1,7 +1,6 @@
import { describe, it, expect } from 'vitest'
import { IPC } from './ipc'
import { HOST_ONLY_REFUSAL, isHostOnlyChannel } from './host-control'
-import { WATCH_CHAT_CAST, WATCH_EVENT, WATCH_HISTORY_CAST, WATCH_INPUT_CAST, WATCH_RELEASE_CAST, WATCH_UNLOCK_CAST } from './watch-link/protocol'
/**
* The ONE list both shells consult. It exists so the desktop's relay admission and any future
@@ -82,37 +81,6 @@ describe('isHostOnlyChannel', () => {
expect(isHostOnlyChannel('notgithubControl:approve')).toBe(false)
})
- it('every owner live-link channel is host-only, and the viewer protocol is not in that namespace', () => {
- // A live link publishes a host terminal to anyone with its URL, paid for with the host's Pro, and
- // the list answer carries every link's secret. A hosted editor passes every access check, so this
- // prefix is the only thing between a teammate and a link.
- const owner = (Object.values(IPC) as unknown[]).filter(
- (v): v is string => typeof v === 'string' && v.startsWith('watchLink:')
- )
- expect(owner).toHaveLength(14)
- for (const ch of owner) expect(isHostOnlyChannel(ch), ch).toBe(true)
- // The Control link's owner verbs by name: typing on/off, a new password, allow-again and the
- // terminal check. A relay peer (a hosted editor included) that could reach them would type into the
- // host's terminal through any of its Control links, or set the password that opens one.
- for (const ch of [IPC.watchLinkSetControl, IPC.watchLinkSetPassword, IPC.watchLinkAllowControl, IPC.watchLinkControlSupport]) {
- expect(owner, ch).toContain(ch)
- expect(isHostOnlyChannel(ch), ch).toBe(true)
- }
- // A namespace, not a list: a verb added later is refused the day it is added.
- expect(isHostOnlyChannel('watchLink:something-new')).toBe(true)
- // The viewer's own tunnel messages are `watch:*` — never refused as host-only, or a Commenter
- // could not chat (relay-host refuses host-only methods before any policy runs).
- expect(isHostOnlyChannel('watch:chat')).toBe(false)
- expect(isHostOnlyChannel('watch:meta')).toBe(false)
- // Every viewer message, Control's included (unlock, input, release, the per-viewer control state
- // and the typing set).
- const viewer = [...Object.values(WATCH_EVENT), WATCH_CHAT_CAST, WATCH_HISTORY_CAST, WATCH_UNLOCK_CAST, WATCH_INPUT_CAST, WATCH_RELEASE_CAST]
- for (const ch of viewer) {
- expect(ch.startsWith('watch:'), ch).toBe(true)
- expect(isHostOnlyChannel(ch), ch).toBe(false)
- }
- })
-
it('carries the refusal wording the peer sees, so both shells answer identically', () => {
expect(HOST_ONLY_REFUSAL).toBe('host-control method is not available to relay peers')
})
diff --git a/src/shared/host-control.ts b/src/shared/host-control.ts
index 6a0093d48..43ac49d3e 100644
--- a/src/shared/host-control.ts
+++ b/src/shared/host-control.ts
@@ -31,9 +31,6 @@ import { IPC } from './ipc'
* about the host's panes it never measured.
* - `station-notice:list` — every project's failed-station ids and titles, unscoped. A relay tab
* never asks (it takes the inert stub), and a guest bound to ONE project must not read the rest.
- * - `watchLink:*` — live links (src/core/watch-link/service.ts): a link publishes one of the host's
- * terminals to anyone holding its URL and is paid for with the host's Pro. An editor passes every
- * access check, so only this list keeps a teammate from minting one.
*
* DELIBERATELY NOT LISTED: `project-setup:subscribe`/`unsubscribe` and the `project-setup:event:*`
* push. They neither start nor authorize anything, and a peer that can see the canvas can already
@@ -70,10 +67,6 @@ export const HOST_ONLY_CHANNEL_PREFIXES: readonly string[] = [
'remote:',
'relay:host:',
'relay:client:',
- // Live links: publishing a host terminal to anyone with a URL, with the host's Pro. No relay peer
- // may create, list (every link's URL carries its secret), stop, kick or chat as the owner. The
- // viewer's own protocol is `watch:*`, which this prefix deliberately does not match.
- 'watchLink:',
// Agent-integration consent status: paths in the host's home it kept or wrote. The consent itself
// is in settings (already host-only).
'integrations:',
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index 8ce07e5f2..cf7e910ba 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -286,38 +286,6 @@ export const IPC = {
stationHandoverList: 'station-handover:list',
/** core → every renderer: the FULL current list on each change, never a delta. */
stationHandoverChanged: 'station-handover:changed',
- /** Live links (docs/live-links.md, src/core/watch-link/service.ts). OWNER-ONLY: every `watchLink:`
- * channel is host-only (host-control.ts), so no relay peer — hosted owners and editors included —
- * can create a link, which would publish a host terminal with the host's Pro. The viewer's own
- * tunnel protocol is `watch:*` (src/shared/watch-link/protocol.ts), deliberately NOT this
- * namespace. invoke: `create(CreateWatchLinkRequest)` → CreateWatchLinkResult. */
- watchLinkCreate: 'watchLink:create',
- /** invoke: the current links (WatchLinkView[]), for a renderer that booted after a push. */
- watchLinkList: 'watchLink:list',
- /** invoke: `(linkId)` — stop one link now (local first, then a best-effort server revoke). */
- watchLinkRevoke: 'watchLink:revoke',
- /** invoke: stop every link on this machine, then one server revoke-all. */
- watchLinkRevokeAll: 'watchLink:revoke-all',
- /** invoke: `(linkId, viewerId)` → boolean — end ONE viewer's connection (the link stays). */
- watchLinkKick: 'watchLink:kick',
- /** invoke: `(linkId, text)` → WatchChatMessage | null — the owner's reply on a Commenter link. */
- watchLinkChatSend: 'watchLink:chat-send',
- /** invoke: `(linkId)` → WatchChatMessage[] — this run's last messages (memory only). */
- watchLinkChatHistory: 'watchLink:chat-history',
- /** invoke: `(linkId, enabled)` → boolean — a Control link: turn typing on or off. */
- watchLinkSetControl: 'watchLink:set-control',
- /** invoke: `(linkId, password)` → boolean — a Control link: replace its password. */
- watchLinkSetPassword: 'watchLink:set-password',
- /** invoke: `(linkId)` → boolean — a Control link locked by wrong passwords: allow unlocking again. */
- watchLinkAllowControl: 'watchLink:allow-control',
- /** invoke: `(nodeId)` → ControlSupport — whether the node's terminal can take a Control link's input. */
- watchLinkControlSupport: 'watchLink:control-support',
- /** core → owner clients only: the full list on every change, never a delta. */
- watchLinkState: 'watchLink:state',
- /** core → owner clients only: `(linkId, WatchChatMessage)`. */
- watchLinkChat: 'watchLink:chat',
- /** core → owner clients only: a `WatchLinkNotice`. */
- watchLinkNotice: 'watchLink:notice',
/** Canvas sync: a client casts its local node mutations here; the core reflector
* (src/core/canvas-sync.ts) stamps each with the total order (`seq`) and sends it back out on the
* SAME channel to EVERY attached client — the sender included, whose copy is its ack (see
diff --git a/src/shared/presence.ts b/src/shared/presence.ts
index 65e02af67..5eb015031 100644
--- a/src/shared/presence.ts
+++ b/src/shared/presence.ts
@@ -154,8 +154,7 @@ export function capCodePoints(text: string, max: number): string {
* The directional formatting characters, as a character-class BODY (escapes only — a bidi character
* written literally makes the pattern unreadable, and a file carrying one is flagged as bidi text):
* ALM (U+061C), LRM/RLM (U+200E/F), the embeddings and overrides (U+202A–E) and the isolates
- * (U+2066–9). ONE definition: `UNSAFE_DISPLAY_CHARS` below and the live-link owner side
- * (@shared/watch-link-types `stripBidiControls`) are built from it.
+ * (U+2066–9). ONE definition: `UNSAFE_DISPLAY_CHARS` below is built from it.
*/
const BIDI_CONTROL_CLASS = '\\u061c\\u200e\\u200f\\u202a-\\u202e\\u2066-\\u2069'
/** Only the directional formatting characters (see BIDI_CONTROL_CLASS) — for text where the other
diff --git a/src/shared/session-backend.ts b/src/shared/session-backend.ts
index 2044e791e..6cc78b03a 100644
--- a/src/shared/session-backend.ts
+++ b/src/shared/session-backend.ts
@@ -33,7 +33,6 @@ export const ZELLIJ_BACKEND_GAPS: readonly string[] = [
'The session-memory panel counts Zellij sessions but does not measure them; the idle-session reaper does not see them.',
'Pasted text reaches Zellij as a command-line argument (readable by other local users while the call runs); pastes over 120 KB are refused.',
'The stale-folder banner and the live pane folder for file links are unavailable.',
- 'A live link to a Zellij node gets no screen snapshot (viewers start from the live stream), and can be watched only while its terminal is attached in this app.',
'SSH projects and Windows keep tmux / the session host.',
'nodeterm mobile’s direct SSH attach only finds tmux sessions.'
]
diff --git a/src/shared/watch-link-password.test.ts b/src/shared/watch-link-password.test.ts
deleted file mode 100644
index a32e2ceb9..000000000
--- a/src/shared/watch-link-password.test.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { describe, expect, it } from 'vitest'
-import { generateControlPassword, controlPasswordProblem, CONTROL_PASSWORD_ALPHABET, CONTROL_PASSWORD_LENGTH } from './watch-link-password'
-
-describe('control password', () => {
- it('generates 16 symbols from the 32-symbol alphabet, uniformly (byte & 31)', () => {
- const pw = generateControlPassword((n) => Uint8Array.from({ length: n }, (_, i) => i * 37))
- expect(pw).toHaveLength(CONTROL_PASSWORD_LENGTH)
- expect([...pw].every((c) => CONTROL_PASSWORD_ALPHABET.includes(c))).toBe(true)
- expect(CONTROL_PASSWORD_ALPHABET).toHaveLength(32)
- expect(/[ilou]/.test(CONTROL_PASSWORD_ALPHABET)).toBe(false)
- })
- it('validates typed passwords', () => {
- expect(controlPasswordProblem('1234567')).toBe('short')
- expect(controlPasswordProblem('12345678')).toBeNull()
- expect(controlPasswordProblem('🙂'.repeat(8))).toBeNull() // code points, not UTF-16 units
- expect(controlPasswordProblem('x'.repeat(129))).toBe('long')
- expect(controlPasswordProblem('abcdefg\n')).toBe('control')
- expect(controlPasswordProblem(12345678)).toBe('type')
- })
-})
diff --git a/src/shared/watch-link-password.ts b/src/shared/watch-link-password.ts
deleted file mode 100644
index 60a6026f8..000000000
--- a/src/shared/watch-link-password.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-// A Control link's password, OWNER side: the generator and the validator the create dialog and the
-// core service share (docs/live-links.md). Not in src/shared/watch-link/ on purpose: the viewer page
-// never makes or judges a password, it only carries one inside the E2E tunnel (`PASSWORD_MAX`).
-// The plaintext is never stored; core keeps a scrypt hash only (src/core/watch-link/password.ts).
-import { PASSWORD_MAX } from './watch-link/protocol'
-
-/** The shortest password a person may type, in code points. The longest is the unlock cast's own cap,
- * `PASSWORD_MAX` (128), so a password the owner set can always be sent by a viewer. */
-export const CONTROL_PASSWORD_MIN = 8
-/** What Generate makes: 16 symbols of 5 bits each, 80 bits. */
-export const CONTROL_PASSWORD_LENGTH = 16
-/** Crockford's base32 in lower case: no i, l, o or u, so nothing reads as another symbol. */
-export const CONTROL_PASSWORD_ALPHABET = '0123456789abcdefghjkmnpqrstvwxyz'
-
-/** `randomBytes` is the caller's CSPRNG (`crypto.getRandomValues` in the renderer). 32 symbols divide
- * 256, so `byte & 31` picks every symbol with the same probability. */
-export function generateControlPassword(randomBytes: (n: number) => Uint8Array): string {
- const b = randomBytes(CONTROL_PASSWORD_LENGTH)
- let out = ''
- for (let i = 0; i < CONTROL_PASSWORD_LENGTH; i++) out += CONTROL_PASSWORD_ALPHABET[b[i] & 31]
- return out
-}
-
-export type ControlPasswordProblem = 'type' | 'short' | 'long' | 'control'
-/** Why a typed password is refused, or null when it is acceptable. Lengths count code points, so an
- * emoji is one character, as a person counts it. C0/C1 controls (a pasted line break) are refused:
- * the viewer types the password into a one-line field and could never send one back. */
-export function controlPasswordProblem(pw: unknown): ControlPasswordProblem | null {
- if (typeof pw !== 'string') return 'type'
- // A code point is at most two UTF-16 units: past this many units it is too long whatever it holds,
- // and an IPC caller's megabyte string is never split into an array of code points.
- if (pw.length > PASSWORD_MAX * 2) return 'long'
- const n = Array.from(pw).length
- if (n < CONTROL_PASSWORD_MIN) return 'short'
- if (n > PASSWORD_MAX) return 'long'
- if (/[\u0000-\u001f\u007f-\u009f]/.test(pw)) return 'control'
- return null
-}
diff --git a/src/shared/watch-link-types.ts b/src/shared/watch-link-types.ts
deleted file mode 100644
index c7439a07e..000000000
--- a/src/shared/watch-link-types.ts
+++ /dev/null
@@ -1,211 +0,0 @@
-// Live links, OWNER side (docs/live-links.md): what the renderer and the core registry
-// (src/core/watch-link/service.ts) say to each other over the host-only `watchLink:*` IPC. NOT the
-// viewer's protocol — that is src/shared/watch-link/ (vendored byte for byte into nodeterm-web), and
-// this file must stay out of that directory.
-import type { WatchChatMessage, WatchLinkRole } from './watch-link/protocol'
-import { BIDI_CONTROL_CHARS } from './presence'
-export type { WatchChatMessage, WatchLinkRole }
-
-/** The expiry choices, in seconds: 15 min, 1 h (the default), 8 h, 24 h, and Unlimited (`0`): no end
- * time, the link lives until it is stopped (`expiresAt: null`). No other value is accepted. */
-export const WATCH_LINK_TTLS = [900, 3600, 28800, 86400, 0] as const
-export type WatchLinkTtl = (typeof WATCH_LINK_TTLS)[number]
-/** The wire value of Unlimited. */
-export const UNLIMITED_TTL = 0
-export const DEFAULT_WATCH_LINK_TTL: WatchLinkTtl = 3600
-/** Active links per machine (spec D6). */
-export const MAX_LINKS_PER_MACHINE = 5
-/** "Shown to viewers as" — UTF-16 units, the same bound the store checks on load. */
-export const LABEL_MAX = 40
-/** The node title shown to viewers — UTF-16 units, the same bound the store checks on load. */
-export const TITLE_MAX = 80
-
-export interface CreateWatchLinkRequest {
- nodeId: string
- role: WatchLinkRole
- ttlSeconds: WatchLinkTtl
- label: string
- title: string
- /** A Control link's password, required for that role (`controlPasswordProblem` must pass) and
- * ignored for the others. Core keeps only its hash; the plaintext is never stored or logged. */
- password?: string
-}
-
-/**
- * Why a create failed. Which copy each one needs is the renderer's (Tasks 15–17):
- * - `not-entitled` — no Pro entitlement stored, or the API answered 402/403: "Live links need an
- * active Pro plan." + Upgrade.
- * - `limit-machine` — 5 links active on this machine (checked locally, before any request).
- * - `limit-active` / `limit-daily` / `rate-limited` — the API's 429, by scope.
- * - `network` — a timeout, a thrown fetch, a 5xx or a malformed reply. Never "you are offline":
- * "Couldn't reach nodeterm's service. Nothing was shared."
- * - `license-check` — the API could not check the license right now (503).
- * - `relay-unavailable` — relaying is disabled in this build (an unpackaged dev build).
- * - `node-missing` — no project holds the node (a node opened seconds ago may not be saved yet:
- * flush the canvas save before asking).
- * - `bad-request` — the request did not validate (here or at the API).
- * - `persist-failed` — the server row was created but could not be written locally; it was revoked.
- * - `unsupported` — this surface cannot create links: the Server Edition until it has a license
- * layer ("Live links need a Pro license on this server — not available in the Server Edition
- * yet", never an Upgrade button — R43), a relay tab ("Live links are created on the machine that
- * runs this terminal"), a client that is not the machine's owner, or an app that is quitting. Also
- * a Control link whose password this machine could not hash (scrypt failed; nothing was created
- * anywhere): the desktop copy names no cause, and every other kind names one that is not it.
- * - `ttl-unsupported` — the API refused an Unlimited link (an older server): pick an end time.
- * - `control-unsupported` — a Control link on a terminal that cannot take typed input safely (a
- * Zellij session, whose key bindings would reach every session).
- * - `bad-password` — a Control link without an acceptable password.
- */
-export type CreateWatchLinkError =
- | 'not-entitled'
- | 'limit-machine'
- | 'limit-active'
- | 'limit-daily'
- | 'rate-limited'
- | 'network'
- | 'license-check'
- | 'relay-unavailable'
- | 'node-missing'
- | 'bad-request'
- | 'persist-failed'
- | 'unsupported'
- | 'ttl-unsupported'
- | 'control-unsupported'
- | 'bad-password'
-export type CreateWatchLinkResult = { ok: true; link: WatchLinkView } | { ok: false; error: CreateWatchLinkError }
-
-export interface WatchLinkViewerView {
- viewerId: string
- /** The name the viewer chatted under, if it has chatted; null otherwise ("Viewer 1"…). */
- name: string | null
- joinedAt: number
- /** Connected, but there is no session it may join (R63): on a machine with no watcher client of its
- * own (Windows' session host, no local tmux, Zellij) the terminal must be OPEN in this app. The
- * owner is told ("Viewers are waiting — open this terminal in nodeterm to let them watch"). */
- waiting: boolean
- /** Unlocked a Control link with its password: may type until it disconnects, is kicked, or the
- * owner turns typing off. Always false on the other roles. */
- controlling: boolean
- /** Typed in the last few seconds (the chip's "1 typing"). */
- typing: boolean
-}
-
-/** A Control link's owner-side state. */
-export interface WatchLinkControlView {
- /** Typing is on: a viewer with the password may unlock. */
- enabled: boolean
- /** Too many wrong passwords across the link: nobody may unlock until it lifts by itself
- * (`lockedUntil`) or the owner allows it again. */
- locked: boolean
- /** While locked: when the lock lifts by itself (epoch ms, this machine's clock); null for a lock that
- * waits for the owner (one written before timed locks), and always null while not locked. Absent
- * from a core older than timed locks. */
- lockedUntil?: number | null
-}
-
-export interface WatchLinkView {
- linkId: string
- nodeId: string
- role: WatchLinkRole
- label: string
- title: string
- createdAt: number
- /** Epoch ms; null for an Unlimited link (no end time). */
- expiresAt: number | null
- /** The full link, secret included (in the fragment). Owner clients only; never logged. */
- url: string
- /** `live` = listening or full; `reconnecting` = the relay leg is down or not yet up (chip "offline");
- * `refused` = the API refuses to mint for this link (an expired/lapsed entitlement, or a build that
- * may not relay) — the chip "refused". */
- status: 'live' | 'reconnecting' | 'refused'
- viewers: WatchLinkViewerView[]
- /** Present exactly for a Control link. */
- control: WatchLinkControlView | null
-}
-
-export type WatchLinkNotice =
- /** Someone started watching: how an owner notices a leaked link. `viewers` counts the link's own. */
- | { kind: 'joined'; linkId: string; nodeId: string; title: string; viewers: number }
- /** A link ended on its own: `revoked` here is a SERVER-side revoke (an owner's own Stop raises none). */
- | { kind: 'ended'; linkId: string; nodeId: string; title: string; reason: 'expired' | 'revoked' | 'node-gone' }
- /** A link is not written to disk this run. Two causes: the links file could not be read (then NO
- * link is saved this run; they work and end at quit — sent at boot and after every create), or the
- * keychain refused to seal (then only the link just created is not saved; links read at boot or
- * sealed earlier stay saved — sent after that create). Copy: "only the link just created is not
- * saved" unless the renderer knows it is the first cause. */
- | { kind: 'not-persistent' }
- /** A viewer unlocked a Control link. `name` is the name it gave itself: a claim, shown as one. */
- | { kind: 'control-taken'; linkId: string; nodeId: string; title: string; name: string }
- /** Too many wrong passwords: control is locked on that link until `until` (epoch ms; null: until the
- * owner allows it again) or until the owner allows it sooner. `by`: the name the attempt that tipped
- * it gave itself (a claim), null when it gave none — so a kick and a new password are obvious. */
- | { kind: 'control-locked'; linkId: string; nodeId: string; title: string; by?: string | null; until?: number | null }
-
-/** Whether a node's terminal can take a Control link's input: `ok` (tmux, the Windows session host, a
- * plain shell), `unsupported` (Zellij — its key bindings are session-wide), or `unknown` (nothing
- * can tell right now; the dialog keeps Control offered and the create decides). */
-export type ControlSupport = 'ok' | 'unsupported' | 'unknown'
-
-/**
- * What "Stop all" reached. THIS machine's links always stop at once, before the answer; the answer
- * is about the license-wide server revoke, the only thing that ends links shared from other machines:
- * - `stopped` — the server accepted it: every other machine's links end at their next mint (≤ ~90 s)
- * or, while a link is full, at its status poll (≤ 1 min).
- * - `no-entitlement` — no Pro entitlement is stored here, so the server was not asked: links on
- * other machines keep running.
- * - `failed` — the server call failed (no answer, a refusal, an expired token): they keep running.
- * - `unsupported` — this surface stops nothing (the Server Edition until it has a license layer, a
- * relay tab, a client that is not the machine's owner).
- */
-export type RevokeAllOutcome = 'stopped' | 'no-entitlement' | 'failed' | 'unsupported'
-
-/**
- * What an owner's change to a Control link did:
- * - `true` — applied and saved;
- * - `false` — refused, nothing changed (not a live Control link, a password the rule refuses, a hash
- * that failed, or a WIDENING change — typing on, allow again — whose write failed);
- * - `'unsaved'` — a NARROWING change (typing off, a new password) that is in force now but could not
- * be saved: it is never undone on a failed write (the owner's brake must not fail open), so it holds
- * until nodeterm quits and would be undone by a restart unless a later write lands first. Stopping
- * the link ends it for good.
- */
-export type ControlChangeResult = boolean | 'unsaved'
-
-/** `window.nodeTerminal.watchLink`. Desktop: real (preload). Server Edition: real bridge, and create
- * answers `unsupported` until that edition has a license layer. Relay tab: an inert stub. */
-export interface WatchLinkApi {
- create(req: CreateWatchLinkRequest): Promise<CreateWatchLinkResult>
- list(): Promise<WatchLinkView[]>
- revoke(linkId: string): Promise<void>
- /** Stop every link of the license, other machines included. Resolves once the server answered. */
- revokeAll(): Promise<RevokeAllOutcome>
- kick(linkId: string, viewerId: string): Promise<boolean>
- /** A Commenter link's owner reply; null when the link is not a Commenter link or the text is empty. */
- sendChat(linkId: string, text: string): Promise<WatchChatMessage | null>
- chatHistory(linkId: string): Promise<WatchChatMessage[]>
- /** A Control link: turn typing on or off (`ControlChangeResult`: off is a narrowing change, on a
- * widening one). */
- setControl(linkId: string, enabled: boolean): Promise<ControlChangeResult>
- /** A Control link: replace its password (every current controller drops back to watching, and the
- * link-wide wrong count starts over). A narrowing change: `ControlChangeResult`. */
- setPassword(linkId: string, password: string): Promise<ControlChangeResult>
- /** A Control link locked by wrong passwords: allow unlocking again (and reset the count). */
- allowControl(linkId: string): Promise<boolean>
- /** Whether this node's terminal can take a Control link's input (the dialog asks once on open). */
- controlSupport(nodeId: string): Promise<ControlSupport>
- /** The full list on every change, never a delta. */
- onState(cb: (links: WatchLinkView[]) => void): () => void
- onChat(cb: (linkId: string, msg: WatchChatMessage) => void): () => void
- onNotice(cb: (n: WatchLinkNotice) => void): () => void
-}
-
-/**
- * Strip the directional formatting characters (ALM, LRM/RLM, the embeddings and overrides, the
- * isolates — @shared/presence's ONE definition) from a string the owner side shows that someone else
- * wrote: a viewer's chat name and text, and the link's label and title (a title can come from a
- * git-shared node title). The vendored chat sanitizer strips C0/C1 but not these, and an RLO reorders
- * whatever the owner's UI draws after it. Only bidi: a ZWJ that joins an emoji sequence survives.
- */
-export function stripBidiControls(s: string): string {
- return s.replace(BIDI_CONTROL_CHARS, '')
-}
diff --git a/src/shared/watch-link/bytes.ts b/src/shared/watch-link/bytes.ts
deleted file mode 100644
index 541e3eaf0..000000000
--- a/src/shared/watch-link/bytes.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-// Byte helpers for the live-link protocol. ISOMORPHIC: this directory is vendored byte-for-byte by
-// nodeterm-web (the viewer page), so nothing here may touch `Buffer`, `node:*` or the DOM beyond
-// `btoa`/`atob`/`TextEncoder`, which Node ≥ 16 and every browser provide.
-
-const B64 = /^[A-Za-z0-9+/]*={0,2}$/
-const B64URL = /^[A-Za-z0-9_-]*$/
-
-export function bytesToB64(b: Uint8Array): string {
- let s = ''
- for (let i = 0; i < b.length; i++) s += String.fromCharCode(b[i])
- return btoa(s)
-}
-
-/** Strict: a string with characters outside the alphabet is `null`, never a silently shorter key. */
-export function b64ToBytes(s: string): Uint8Array | null {
- if (typeof s !== 'string' || s.length % 4 !== 0 || !B64.test(s)) return null
- try {
- const bin = atob(s)
- const out = new Uint8Array(bin.length)
- for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i)
- return out
- } catch {
- return null
- }
-}
-
-export function bytesToB64url(b: Uint8Array): string {
- return bytesToB64(b).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
-}
-
-export function b64urlToBytes(s: string): Uint8Array | null {
- if (typeof s !== 'string' || !B64URL.test(s)) return null
- const std = s.replace(/-/g, '+').replace(/_/g, '/')
- return b64ToBytes(std + '='.repeat((4 - (std.length % 4)) % 4))
-}
-
-export function bytesToHex(b: Uint8Array): string {
- let s = ''
- for (let i = 0; i < b.length; i++) s += b[i].toString(16).padStart(2, '0')
- return s
-}
-
-export function utf8(s: string): Uint8Array {
- return new TextEncoder().encode(s)
-}
-
-/** WebCrypto takes only ArrayBuffer-backed views: TypeScript types a bare `Uint8Array` as possibly
- * SharedArrayBuffer-backed, and browsers refuse those at runtime. A copy is exact and costs nothing
- * at key sizes, so every `crypto.subtle` argument goes through here instead of a cast. */
-export function webCryptoBytes(b: Uint8Array): Uint8Array<ArrayBuffer> {
- return new Uint8Array(b)
-}
-
-export function concatBytes(...parts: Uint8Array[]): Uint8Array {
- const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0))
- let o = 0
- for (const p of parts) {
- out.set(p, o)
- o += p.length
- }
- return out
-}
diff --git a/src/shared/watch-link/client.ts b/src/shared/watch-link/client.ts
deleted file mode 100644
index 360c6bcfe..000000000
--- a/src/shared/watch-link/client.ts
+++ /dev/null
@@ -1,264 +0,0 @@
-// The browser half of a live link: the CLIENT role of src/core/relay/relay-socket.ts (handshake,
-// sealed frames, keepalive) plus the trust gate's client obligation (send our own trust:confirm,
-// open only once the host's arrives). After the handshake it sends only its own trust:confirm,
-// keepalives, and the viewer's casts: read-back (`requestHistory`), chat (`sendChat`) and, on a
-// Control link, unlock (sealed to the connection's unlock key when its host offers one,
-// ./unlock-seal.ts) / input / release. Whether a cast is accepted is the link host's decision, and an obligation on it: chat only
-// on a Commenter or Control link, input only from a viewer that unlocked with the link's password.
-// Nothing on this side enforces that; `sendInput`'s size cap only keeps an oversized cast off the wire.
-import nacl from 'tweetnacl'
-import { b64ToBytes, bytesToB64, concatBytes, utf8 } from './bytes'
-import { hkdfSha256 } from './hkdf'
-import type { WatchLinkKeys } from './keys'
-import { INPUT_MAX, WATCH_CHAT_CAST, WATCH_EVENT, WATCH_HISTORY_CAST, WATCH_INPUT_CAST, WATCH_RELEASE_CAST, WATCH_UNLOCK_CAST, readHistoryRequest } from './protocol'
-import { readUnlockKey, sealUnlock } from './unlock-seal'
-import {
- NONCE_BYTES, RELAY_SESSION_INFO, ROLE_CLIENT, ROLE_HOST, TAG_RPC, TAG_TUNNEL_BIN, TAG_TUNNEL_TEXT,
- decodePtyFrame, openBox, parseTunnelJson, readHeader, sealBox, withHeader
-} from './wire'
-
-/**
- * What a transport adapter owes the client (a core `RelayTransport` already satisfies it):
- * - Text frames arrive as strings, binary frames as `Uint8Array` or `ArrayBuffer`. A browser
- * WebSocket must be given `binaryType = 'arraybuffer'`: its default delivers Blobs, which are
- * not accepted (the client warns once and drops anything that is neither text nor bytes).
- * - `send` is callable immediately: the client sends `e2ee_hello` synchronously from
- * `connectWatchClient`. A browser WebSocket still CONNECTING throws on send, so the adapter
- * queues until open, as core's `openWebSocketTransport` does.
- * - `onClose` fires exactly once, on a close OR an error.
- */
-export interface WatchSocket {
- send(data: string | Uint8Array): void
- close(): void
- onMessage(cb: (data: unknown) => void): void
- onClose(cb: () => void): void
-}
-export interface WatchClientEvents {
- onOpen(): void
- onEvent(channel: string, args: unknown[]): void
- onPtyData(sessionId: string, data: string): void
- onDenied(reason: string): void
- onClose(): void
-}
-/**
- * The CALLER owns the handshake deadline. A host that is offline never sends `e2ee_ready`, and a
- * host that does not hold the link's key never authenticates, so without a timeout of the caller's
- * own the client never reaches a terminal event: no `onOpen`, `onDenied` or `onClose`.
- */
-export interface WatchClient {
- /** Ask for a page of the agent's conversation since the link was shared: the newest, or the one
- * before `before` (a page's `olderCursor`). The answer is a `watch:history` event. A cursor the host
- * would refuse is refused here (false, nothing sent). */
- requestHistory(before?: number): boolean
- sendChat(name: string, text: string): boolean
- /** Ask to type, with the link's password. The answer is a `watch:control` event, not a return value.
- * Sealed to this connection's unlock key once a meta on it offered one (`WatchMeta.unlockKey`), and
- * from then on never sent in the clear on this connection; in the clear only to a host that offered
- * none (one from before sealing). */
- unlock(name: string, password: string): boolean
- /** Typed bytes, sent as given. Refused here (false, nothing sent) when empty, not a string, or longer
- * than `INPUT_MAX` UTF-16 units. */
- sendInput(data: string): boolean
- /** Stop typing: back to watching. */
- release(): boolean
- close(): void
- isOpen(): boolean
-}
-
-export const TRUST_CONFIRM_JSON = '{"t":"cast","method":"trust:confirm","args":[]}'
-const KEEPALIVE_MS = 25_000
-const KEEPALIVE_JSON = '{"kind":"keepalive"}'
-
-function toBytes(data: unknown): Uint8Array | null {
- if (data instanceof Uint8Array) return data
- if (data instanceof ArrayBuffer) return new Uint8Array(data)
- return null
-}
-function json(raw: string): Record<string, unknown> | null {
- try {
- const v = JSON.parse(raw)
- return v && typeof v === 'object' ? (v as Record<string, unknown>) : null
- } catch {
- return null
- }
-}
-
-/** See `WatchSocket` for what the socket owes, and `WatchClient` for the handshake deadline. */
-export function connectWatchClient(opts: {
- socket: WatchSocket
- keys: WatchLinkKeys
- events: WatchClientEvents
- setInterval?: (fn: () => void, ms: number) => unknown
- clearInterval?: (h: unknown) => void
-}): WatchClient {
- const { socket, keys, events } = opts
- const every =
- opts.setInterval ??
- ((fn: () => void, ms: number) => {
- const h: unknown = setInterval(fn, ms)
- // Node only: a keepalive must not hold the process open. A browser's handle is a number.
- const timer = h as { unref?: () => void } | null
- timer?.unref?.()
- return h
- })
- const stopEvery = opts.clearInterval ?? ((h: unknown) => clearInterval(h as ReturnType<typeof setInterval>))
- const ourNonce = nacl.randomBytes(NONCE_BYTES)
- const baseKey = nacl.box.before(keys.host.publicKey, keys.viewer.secretKey)
- let state: 'hello' | 'deriving' | 'auth' | 'ready' | 'closed' = 'hello'
- let sessionKey: Uint8Array | null = null
- let sendSeq = 0
- let recvSeq = -1
- let hostConfirmed = false
- let confirmSent = false
- let opened = false
- let warnedUnknown = false
- let keepalive: unknown = null
- /** The key this connection's host offered to seal an unlock to: the latest one a meta carried. Once
- * set it is never cleared, so an unlock on this connection is never sent in the clear again. */
- let unlockKey: Uint8Array | null = null
-
- function sendSealed(tag: number, body: Uint8Array): boolean {
- if (!sessionKey || state === 'closed') return false
- socket.send(sealBox(withHeader(ROLE_CLIENT, sendSeq++, concatBytes(Uint8Array.of(tag), body)), sessionKey))
- return true
- }
- function maybeOpen(): void {
- if (opened || !hostConfirmed || !confirmSent || state !== 'ready') return
- opened = true
- events.onOpen()
- }
- function shutdown(): void {
- if (state === 'closed') return
- state = 'closed'
- if (keepalive !== null) stopEvery(keepalive)
- keepalive = null
- }
-
- async function onControl(raw: string): Promise<void> {
- const m = json(raw)
- if (state !== 'hello' || m?.type !== 'e2ee_ready' || typeof m.nonceB64 !== 'string') return
- const hostNonce = b64ToBytes(m.nonceB64)
- if (!hostNonce || hostNonce.length !== NONCE_BYTES) return
- state = 'deriving'
- let key: Uint8Array
- try {
- key = await hkdfSha256(baseKey, concatBytes(hostNonce, ourNonce), utf8(RELAY_SESSION_INFO), 32)
- } catch {
- // No WebCrypto HKDF (a page without a secure context has no crypto.subtle). Without this the
- // rejection went unhandled and the client sat in 'deriving' with no event, forever.
- if (state !== 'deriving') return
- shutdown()
- socket.close()
- // Explicit: shutdown() already marked us closed, so the socket's own close callback is silent.
- events.onClose()
- return
- }
- if (state !== 'deriving') return
- sessionKey = key
- state = 'auth'
- sendSealed(TAG_RPC, utf8('{"type":"e2ee_auth"}'))
- }
-
- socket.onMessage((data) => {
- if (state === 'closed') return
- if (typeof data === 'string') {
- void onControl(data)
- return
- }
- const bytes = toBytes(data)
- if (!bytes) {
- if (!warnedUnknown) {
- warnedUnknown = true
- console.warn(
- "nodeterm live link: dropped a socket message that is neither text nor bytes; the WebSocket needs binaryType = 'arraybuffer'."
- )
- }
- return
- }
- if (!sessionKey) return
- const plain = openBox(bytes, sessionKey)
- const h = plain && readHeader(plain)
- if (!h || h.role !== ROLE_HOST || h.seq <= recvSeq || h.body.length < 1) return
- recvSeq = h.seq
- const tag = h.body[0]
- const body = h.body.subarray(1)
- if (state === 'auth') {
- if (tag !== TAG_RPC || json(new TextDecoder().decode(body))?.type !== 'e2ee_authenticated') return
- state = 'ready'
- keepalive = every(() => void sendSealed(TAG_RPC, utf8(KEEPALIVE_JSON)), KEEPALIVE_MS)
- // After this handler returns: over an in-process transport the host is still inside its own
- // send and has not created its trust gate yet, and a confirm it cannot see is lost for good.
- // A host that confirms inside its onReady (a pinned one) is heard before this runs, which is
- // why maybeOpen also waits for `confirmSent`.
- queueMicrotask(() => {
- confirmSent = sendSealed(TAG_TUNNEL_TEXT, utf8(TRUST_CONFIRM_JSON))
- maybeOpen()
- })
- return
- }
- if (state !== 'ready') return
- if (tag === TAG_TUNNEL_TEXT) {
- const m = parseTunnelJson(new TextDecoder().decode(body))
- if (!m) return
- if (m.t === 'cast' && m.method === 'trust:confirm') {
- hostConfirmed = true
- maybeOpen()
- } else if (m.t === 'cast' && m.method === 'trust:denied') {
- events.onDenied(typeof m.args[0] === 'string' ? m.args[0] : 'denied')
- } else if (m.t === 'ev' && opened) {
- if (m.channel === WATCH_EVENT.meta) {
- const key = readUnlockKey((m.args[0] as { unlockKey?: unknown } | null | undefined)?.unlockKey)
- if (key) unlockKey = key
- }
- events.onEvent(m.channel, m.args)
- }
- return
- }
- if (tag === TAG_TUNNEL_BIN && opened) {
- const f = decodePtyFrame(body)
- if (f) events.onPtyData(f.sessionId, f.data)
- }
- })
- socket.onClose(() => {
- const alreadyClosed = state === 'closed'
- shutdown()
- if (!alreadyClosed) events.onClose()
- })
- socket.send(JSON.stringify({ type: 'e2ee_hello', publicKeyB64: bytesToB64(keys.viewer.publicKey), nonceB64: bytesToB64(ourNonce) }))
-
- function cast(method: string, args: unknown[]): boolean {
- if (!opened || state !== 'ready') return false
- return sendSealed(TAG_TUNNEL_TEXT, utf8(JSON.stringify({ t: 'cast', method, args })))
- }
-
- return {
- requestHistory(before) {
- const arg = before === undefined ? {} : { before }
- if (readHistoryRequest(arg) === null) return false
- return cast(WATCH_HISTORY_CAST, [arg])
- },
- sendChat: (name, text) => cast(WATCH_CHAT_CAST, [{ name, text }]),
- unlock(name, password) {
- if (!unlockKey) return cast(WATCH_UNLOCK_CAST, [{ name, password }])
- let arg: ReturnType<typeof sealUnlock>
- try {
- arg = sealUnlock(name, password, unlockKey)
- } catch {
- // JSON.stringify cannot fail on two strings, and the key is 32 bytes; nothing goes out in the
- // clear if it somehow does.
- return false
- }
- return cast(WATCH_UNLOCK_CAST, [arg])
- },
- sendInput(data) {
- if (typeof data !== 'string' || data.length === 0 || data.length > INPUT_MAX) return false
- return cast(WATCH_INPUT_CAST, [{ data }])
- },
- release: () => cast(WATCH_RELEASE_CAST, []),
- close() {
- shutdown()
- socket.close()
- },
- isOpen: () => opened && state === 'ready'
- }
-}
diff --git a/src/shared/watch-link/hkdf.ts b/src/shared/watch-link/hkdf.ts
deleted file mode 100644
index b287307a5..000000000
--- a/src/shared/watch-link/hkdf.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-// HKDF-SHA256 over WebCrypto, the browser's equivalent of the relay's `hkdfSync` (e2ee.ts).
-import { webCryptoBytes } from './bytes'
-
-export async function hkdfSha256(ikm: Uint8Array, salt: Uint8Array, info: Uint8Array, length: number): Promise<Uint8Array> {
- const subtle = globalThis.crypto.subtle
- const key = await subtle.importKey('raw', webCryptoBytes(ikm), 'HKDF', false, ['deriveBits'])
- return new Uint8Array(
- await subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt: webCryptoBytes(salt), info: webCryptoBytes(info) }, key, length * 8)
- )
-}
diff --git a/src/shared/watch-link/isomorphism.guard.test.ts b/src/shared/watch-link/isomorphism.guard.test.ts
deleted file mode 100644
index 1bd612c84..000000000
--- a/src/shared/watch-link/isomorphism.guard.test.ts
+++ /dev/null
@@ -1,138 +0,0 @@
-// GUARD: src/shared/watch-link/ is VENDORED byte for byte into nodeterm-web (the viewer page), every
-// `*.ts` here except the tests. Two rules make that copy work there, and nothing in this repo's own
-// build would notice a break of either:
-// 1. A source file imports nothing outside this directory but `tweetnacl`. An `../presence` or a
-// `node:*` import compiles and passes every test here, and the vendored copy then fails to build
-// (the file it names is not in the web repo) or ships Node into the browser bundle.
-// 2. A type-only import is spelled `import type` (or `type X` inline). nodeterm-web compiles with
-// `verbatimModuleSyntax`, which refuses a plain import of something that is only a type.
-// TypeScript 7 has no JS compiler API to ask, so this reads the sources: an import of a name from a
-// sibling must name something that sibling exports as a VALUE.
-import { describe, it, expect } from 'vitest'
-import { readdirSync, readFileSync } from 'node:fs'
-import { join } from 'node:path'
-
-const DIR = __dirname
-/** The one package a vendored file may import. */
-const ALLOWED_PACKAGES = new Set(['tweetnacl'])
-
-const read = (f: string): string => readFileSync(join(DIR, f), 'utf8').replace(/\r\n/g, '\n')
-const vendored = (): string[] => readdirSync(DIR).filter((f) => f.endsWith('.ts') && !f.endsWith('.test.ts')).sort()
-
-/** Comments out, string contents kept (a URL's `//` inside quotes is not a comment). */
-function stripComments(src: string): string {
- return src.replace(/\/\*[\s\S]*?\*\//g, '').replace(/(^|[\s;{}(),])\/\/.*$/gm, '$1')
-}
-
-interface ImportDecl {
- file: string
- text: string
- spec: string
- typeOnly: boolean
- /** Named bindings, `type`-prefixed ones marked. Empty for a default/namespace/side-effect import. */
- names: { name: string; type: boolean }[]
-}
-
-function importsOf(file: string, src: string): ImportDecl[] {
- const out: ImportDecl[] = []
- const code = stripComments(src)
- const re = /^\s*(import|export)\s+(type\s+)?([\s\S]*?)\s+from\s+['"]([^'"]+)['"]/gm
- for (const m of code.matchAll(re)) {
- const body = m[3]
- const braces = /\{([\s\S]*)\}/.exec(body)
- const names = braces
- ? braces[1]
- .split(',')
- .map((p) => p.trim())
- .filter(Boolean)
- .map((p) => {
- const type = p.startsWith('type ')
- const name = (type ? p.slice(5) : p).split(/\s+as\s+/)[0].trim()
- return { name, type }
- })
- : []
- out.push({ file, text: m[0].trim(), spec: m[4], typeOnly: !!m[2], names })
- }
- // Side-effect imports, dynamic imports and require: none is allowed at all.
- for (const m of code.matchAll(/^\s*import\s+['"]([^'"]+)['"]/gm)) out.push({ file, text: m[0].trim(), spec: m[1], typeOnly: false, names: [] })
- for (const m of code.matchAll(/\b(?:import|require)\s*\(\s*['"]([^'"]+)['"]/g)) out.push({ file, text: m[0], spec: `dynamic:${m[1]}`, typeOnly: false, names: [] })
- return out
-}
-
-/** The names a file exports as VALUES (what a non-type import of it may name). */
-function valueExports(src: string): Set<string> {
- const code = stripComments(src)
- const out = new Set<string>()
- for (const m of code.matchAll(/^export\s+(?:async\s+)?(?:const|let|var|function\*?|class|enum)\s+([A-Za-z_$][\w$]*)/gm)) out.add(m[1])
- return out
-}
-
-/** Every rule violation in a set of sources. Exported to the self-test below. */
-function violations(sources: Record<string, string>): string[] {
- const files = new Set(Object.keys(sources))
- const exportsOf = new Map(Object.entries(sources).map(([f, src]) => [f, valueExports(src)]))
- const bad: string[] = []
- for (const [file, src] of Object.entries(sources)) {
- for (const imp of importsOf(file, src)) {
- if (imp.spec.startsWith('dynamic:')) {
- bad.push(`${file}: a dynamic import or require (${imp.text})`)
- continue
- }
- if (imp.spec.startsWith('./')) {
- const target = `${imp.spec.slice(2)}.ts`
- if (imp.spec.slice(2).includes('/') || !files.has(target)) {
- bad.push(`${file}: imports ${imp.spec}, which is not a sibling in this directory`)
- continue
- }
- if (imp.typeOnly) continue
- const values = exportsOf.get(target)!
- for (const n of imp.names) {
- if (n.type) continue
- if (!values.has(n.name)) bad.push(`${file}: imports ${n.name} from ${imp.spec} without \`type\`, but it is not a value there`)
- }
- continue
- }
- if (!ALLOWED_PACKAGES.has(imp.spec)) bad.push(`${file}: imports ${imp.spec} (only ${[...ALLOWED_PACKAGES].join(', ')} and siblings)`)
- }
- }
- return bad
-}
-
-describe('src/shared/watch-link stays isomorphic (it is vendored into nodeterm-web)', () => {
- it('the vendored set is what this guard reads', () => {
- // Not vacuous: the files the web repo copies, all of them seen here.
- expect(vendored()).toEqual(['bytes.ts', 'client.ts', 'hkdf.ts', 'keys.ts', 'link.ts', 'protocol.ts', 'unlock-seal.ts', 'wire.ts'])
- })
-
- it('no source imports outside the directory, and every type-only import says `type`', () => {
- const sources = Object.fromEntries(vendored().map((f) => [f, read(f)]))
- expect(violations(sources)).toEqual([])
- // The guard saw the imports it must judge (a regex that matched nothing would pass anything).
- const all = Object.entries(sources).flatMap(([f, src]) => importsOf(f, src))
- expect(all.filter((i) => i.spec.startsWith('./')).length).toBeGreaterThanOrEqual(8)
- expect(all.some((i) => i.file === 'client.ts' && i.spec === './keys' && i.typeOnly)).toBe(true)
- })
-
- it('no source reaches for Node: `Buffer`, `process` or a `node:` specifier', () => {
- for (const f of vendored()) {
- const code = stripComments(read(f)).replace(/'[^'\n]*'|"[^"\n]*"|`[^`]*`/g, "''")
- expect(code, f).not.toMatch(/\bBuffer\b|\bprocess\.|\brequire\b|['"]node:/)
- }
- })
-
- // The guard's own teeth, on synthetic sources: each rule must fire.
- it('self-test: each kind of break is caught', () => {
- const keys = 'export interface WatchLinkKeys { a: 1 }\nexport const K = 1\n'
- expect(violations({ 'keys.ts': keys, 'a.ts': "import { WatchLinkKeys } from './keys'\n" })).toHaveLength(1)
- expect(violations({ 'keys.ts': keys, 'a.ts': "import type { WatchLinkKeys } from './keys'\n" })).toEqual([])
- expect(violations({ 'keys.ts': keys, 'a.ts': "import { type WatchLinkKeys, K } from './keys'\n" })).toEqual([])
- expect(violations({ 'a.ts': "import { BIDI_CONTROL_CHARS } from '../presence'\n" })).toHaveLength(1)
- expect(violations({ 'a.ts': "import { x } from './sub/b'\n" })).toHaveLength(1)
- expect(violations({ 'a.ts': "import { randomBytes } from 'node:crypto'\n" })).toHaveLength(1)
- expect(violations({ 'a.ts': "import nacl from 'tweetnacl'\n" })).toEqual([])
- expect(violations({ 'a.ts': "export { x } from '../types'\n" })).toHaveLength(1)
- expect(violations({ 'a.ts': "const m = await import('./b')\n" })).toHaveLength(1)
- // A comment that names a forbidden import is not one.
- expect(violations({ 'a.ts': "// import { x } from '../presence'\n" })).toEqual([])
- })
-})
diff --git a/src/shared/watch-link/keys.test.ts b/src/shared/watch-link/keys.test.ts
deleted file mode 100644
index 88b2ac190..000000000
--- a/src/shared/watch-link/keys.test.ts
+++ /dev/null
@@ -1,82 +0,0 @@
-import { describe, it, expect } from 'vitest'
-import { createHash } from 'node:crypto'
-import nacl from 'tweetnacl'
-import { bytesToB64, b64ToBytes, bytesToB64url, b64urlToBytes, bytesToHex, utf8, concatBytes } from './bytes'
-import { deriveWatchLinkKeys, newWatchLinkSecret, sha256Hex, WATCH_LINK_KDF_PREFIX } from './keys'
-import { formatWatchLink, parseWatchLinkLocation, LINK_ID_RE } from './link'
-
-const secret = Uint8Array.from({ length: 32 }, (_, i) => i)
-
-describe('bytes', () => {
- it('round-trips base64 and base64url like Buffer does', () => {
- const b = nacl.randomBytes(57)
- expect(bytesToB64(b)).toBe(Buffer.from(b).toString('base64'))
- expect(bytesToB64url(b)).toBe(Buffer.from(b).toString('base64url'))
- expect(b64ToBytes(bytesToB64(b))).toEqual(b)
- expect(b64urlToBytes(bytesToB64url(b))).toEqual(b)
- expect(bytesToHex(Uint8Array.of(0, 255, 16))).toBe('00ff10')
- expect(concatBytes(utf8('a'), utf8('bc'))).toEqual(utf8('abc'))
- })
- it("pins base64url's two URL-safe characters with a fixed vector (random bytes may never hit them)", () => {
- // 0xfb 0xff = 111110 111111 1111(00): 62 → '-', 63 → '_', 60 → '8'.
- expect(bytesToB64url(Uint8Array.of(0xfb, 0xff))).toBe('-_8')
- expect(b64urlToBytes('-_8')).toEqual(Uint8Array.of(0xfb, 0xff))
- expect(bytesToB64(Uint8Array.of(0xfb, 0xff))).toBe('+/8=')
- })
- it('refuses malformed base64 instead of silently truncating', () => {
- expect(b64ToBytes('not base64!!')).toBeNull()
- expect(b64urlToBytes('+/+/')).toBeNull()
- })
-})
-
-describe('deriveWatchLinkKeys', () => {
- it('derives each key from a domain-separated SHA-512 of the secret', () => {
- const k = deriveWatchLinkKeys(secret)
- const sub = (label: string) =>
- new Uint8Array(createHash('sha512').update(Buffer.concat([Buffer.from(WATCH_LINK_KDF_PREFIX + label), Buffer.from(secret)])).digest()).slice(0, 32)
- expect(k.host.secretKey).toEqual(sub('host'))
- expect(k.host.publicKey).toEqual(nacl.box.keyPair.fromSecretKey(sub('host')).publicKey)
- expect(k.viewer.secretKey).toEqual(sub('viewer'))
- expect(k.joinKey).toEqual(sub('join'))
- expect(k.host.publicKey).not.toEqual(k.viewer.publicKey)
- })
- it('refuses a secret of any other length rather than derive keys from it', () => {
- for (const n of [0, 16, 31, 33, 64]) expect(() => deriveWatchLinkKeys(new Uint8Array(n))).toThrow(/32 bytes/)
- })
- it('makes a fresh 32-byte secret each time', () => {
- const a = newWatchLinkSecret()
- expect(a).toHaveLength(32)
- expect(a).not.toEqual(newWatchLinkSecret())
- })
- it('hashes the join key as lowercase hex sha256', async () => {
- const k = deriveWatchLinkKeys(secret)
- expect(await sha256Hex(k.joinKey)).toBe(createHash('sha256').update(k.joinKey).digest('hex'))
- })
-})
-
-describe('link format', () => {
- const id = 'AbCdEfGhIjKlMnOpQrStUv'
- it('formats and parses the viewer URL', () => {
- const url = formatWatchLink(id, secret)
- expect(url).toBe(`https://nodeterm.dev/s/${id}#1.${Buffer.from(secret).toString('base64url')}`)
- const u = new URL(url)
- expect(parseWatchLinkLocation(u.pathname, u.hash)).toEqual({ linkId: id, secret })
- })
- it('refuses a wrong version, id or secret length', () => {
- const s = Buffer.from(secret).toString('base64url')
- expect(parseWatchLinkLocation(`/s/${id}`, `#2.${s}`)).toBeNull()
- expect(parseWatchLinkLocation('/s/short', `#1.${s}`)).toBeNull()
- expect(parseWatchLinkLocation(`/s/${id}`, `#1.${s.slice(1)}`)).toBeNull()
- expect(parseWatchLinkLocation(`/s/${id}/x`, `#1.${s}`)).toBeNull()
- expect(LINK_ID_RE.test(id)).toBe(true)
- })
- // A link nobody can open — or one whose secret ends up outside the fragment — is never formatted.
- it('formats only what it could parse back: a bad id, secret or origin throws', () => {
- for (const bad of ['short', `${id}x`, 'AbCdEfGhIjKlMnOpQrSt/v', 'AbCdEfGhIjKlMnOpQrSt#v', ''])
- expect(() => formatWatchLink(bad, secret)).toThrow(/link id/)
- for (const n of [0, 31, 33]) expect(() => formatWatchLink(id, new Uint8Array(n))).toThrow(/secret/)
- for (const origin of ['https://nodeterm.dev/', 'https://nodeterm.dev/x', 'https://a.dev?x=1', 'https://a.dev#f', 'javascript:alert(1)', 'nodeterm.dev', ''])
- expect(() => formatWatchLink(id, secret, origin)).toThrow(/origin/)
- expect(formatWatchLink(id, secret, 'http://localhost:4321')).toMatch(/^http:\/\/localhost:4321\/s\//)
- })
-})
diff --git a/src/shared/watch-link/keys.ts b/src/shared/watch-link/keys.ts
deleted file mode 100644
index ca5f611a1..000000000
--- a/src/shared/watch-link/keys.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-// Everything a live link needs is derived from ONE 32-byte secret S that lives only in the URL
-// fragment. The host key pair lets the viewer pin the host; the viewer key pair is what the host
-// accepts in the handshake (so the relay handshake itself is unchanged); the join key is shown to
-// the API, which stores only its SHA-256 and so can gate a join without learning S. The three are
-// domain-separated, so learning the join key (the API does) reveals nothing about the other two.
-import nacl from 'tweetnacl'
-import { bytesToHex, concatBytes, utf8, webCryptoBytes } from './bytes'
-
-export const WATCH_LINK_KDF_PREFIX = 'nodeterm-watch-link-v1/'
-export const WATCH_LINK_SECRET_BYTES = 32
-
-export interface KeyPairBytes {
- publicKey: Uint8Array
- secretKey: Uint8Array
-}
-export interface WatchLinkKeys {
- host: KeyPairBytes
- viewer: KeyPairBytes
- joinKey: Uint8Array
-}
-
-function sub(secret: Uint8Array, label: string): Uint8Array {
- return nacl.hash(concatBytes(utf8(WATCH_LINK_KDF_PREFIX + label), secret)).slice(0, 32)
-}
-
-export function deriveWatchLinkKeys(secret: Uint8Array): WatchLinkKeys {
- if (secret.length !== WATCH_LINK_SECRET_BYTES) throw new Error('A live link secret is 32 bytes.')
- return {
- host: nacl.box.keyPair.fromSecretKey(sub(secret, 'host')),
- viewer: nacl.box.keyPair.fromSecretKey(sub(secret, 'viewer')),
- joinKey: sub(secret, 'join')
- }
-}
-
-export function newWatchLinkSecret(): Uint8Array {
- return nacl.randomBytes(WATCH_LINK_SECRET_BYTES)
-}
-
-export async function sha256Hex(b: Uint8Array): Promise<string> {
- return bytesToHex(new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', webCryptoBytes(b))))
-}
diff --git a/src/shared/watch-link/link.ts b/src/shared/watch-link/link.ts
deleted file mode 100644
index 7c70db6d8..000000000
--- a/src/shared/watch-link/link.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-// The viewer URL: https://nodeterm.dev/s/<linkId>#1.<S>. The id names a link and unlocks nothing;
-// S is in the FRAGMENT so it never reaches an HTTP request, a server log or a referrer.
-import { b64urlToBytes, bytesToB64url } from './bytes'
-import { WATCH_LINK_SECRET_BYTES } from './keys'
-
-export const WATCH_LINK_ORIGIN = 'https://nodeterm.dev'
-export const WATCH_LINK_FRAGMENT_VERSION = '1'
-export const LINK_ID_RE = /^[A-Za-z0-9_-]{22}$/
-
-/** A scheme and a host (and a port), nothing else: a path, query or fragment here would change what
- * the URL names, or put the secret somewhere other than the fragment. */
-const ORIGIN_RE = /^https?:\/\/[A-Za-z0-9.-]+(?::\d{1,5})?$/
-
-/**
- * The viewer URL for a link. Throws on an input that would not make one — an id `parseWatchLinkLocation`
- * would refuse, a secret of the wrong length, an origin that is more than an origin — rather than
- * format a link nobody can open (or one whose secret leaves the fragment).
- */
-export function formatWatchLink(linkId: string, secret: Uint8Array, origin: string = WATCH_LINK_ORIGIN): string {
- if (typeof linkId !== 'string' || !LINK_ID_RE.test(linkId)) throw new Error('A live link id is 22 base64url characters.')
- if (!secret || secret.length !== WATCH_LINK_SECRET_BYTES) throw new Error('A live link secret is 32 bytes.')
- if (typeof origin !== 'string' || !ORIGIN_RE.test(origin)) throw new Error('A live link origin is a scheme and a host.')
- return `${origin}/s/${linkId}#${WATCH_LINK_FRAGMENT_VERSION}.${bytesToB64url(secret)}`
-}
-
-export function parseWatchLinkLocation(pathname: string, hash: string): { linkId: string; secret: Uint8Array } | null {
- const m = /^\/s\/([^/]+)\/?$/.exec(pathname)
- if (!m || !LINK_ID_RE.test(m[1])) return null
- const frag = hash.startsWith('#') ? hash.slice(1) : hash
- const dot = frag.indexOf('.')
- if (dot < 0 || frag.slice(0, dot) !== WATCH_LINK_FRAGMENT_VERSION) return null
- const secret = b64urlToBytes(frag.slice(dot + 1))
- if (!secret || secret.length !== WATCH_LINK_SECRET_BYTES) return null
- return { linkId: m[1], secret }
-}
diff --git a/src/shared/watch-link/protocol.control.test.ts b/src/shared/watch-link/protocol.control.test.ts
deleted file mode 100644
index 75a73d69c..000000000
--- a/src/shared/watch-link/protocol.control.test.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { describe, expect, it } from 'vitest'
-import { CONTROL_LOCK_MAX_MS, readControlEvent, readTypingNames, isWatchEndReason, TYPING_NAMES_MAX } from './protocol'
-
-describe('control protocol readers', () => {
- it('accepts only known states and reasons', () => {
- expect(readControlEvent({ state: 'controlling' })).toEqual({ state: 'controlling' })
- expect(readControlEvent({ state: 'available', reason: 'wrong' })).toEqual({ state: 'available', reason: 'wrong' })
- expect(readControlEvent({ state: 'god' })).toBeNull()
- expect(readControlEvent({ state: 'off', reason: 'nope' })).toEqual({ state: 'off' })
- expect(readControlEvent(null)).toBeNull()
- })
- it('sanitizes and bounds typing names', () => {
- const many = Array.from({ length: 30 }, (_, i) => `n${i}`)
- expect(readTypingNames({ names: many })).toHaveLength(TYPING_NAMES_MAX)
- expect(readTypingNames({ names: ['a\u202eb', 'a\u202eb', 7, ' '] })).toEqual(['ab'])
- expect(readTypingNames('x')).toEqual([])
- })
- it('keeps how long a lock lasts only beside `locked`, and only a duration a host can mean', () => {
- expect(readControlEvent({ state: 'locked', reason: 'locked', lockedForMs: 900_000 })).toEqual({ state: 'locked', reason: 'locked', lockedForMs: 900_000 })
- expect(readControlEvent({ state: 'locked', lockedForMs: 0 })).toEqual({ state: 'locked', lockedForMs: 0 })
- expect(readControlEvent({ state: 'locked', lockedForMs: CONTROL_LOCK_MAX_MS })).toEqual({ state: 'locked', lockedForMs: CONTROL_LOCK_MAX_MS })
- // Past the cap, negative, fractional, not a number: "until the sharer lifts it" — never a promise.
- for (const lockedForMs of [CONTROL_LOCK_MAX_MS + 1, -1, 1.5, '900000', Number.NaN, Infinity, null]) {
- expect(readControlEvent({ state: 'locked', lockedForMs })).toEqual({ state: 'locked' })
- }
- // Beside any other state it means nothing.
- expect(readControlEvent({ state: 'available', lockedForMs: 1000 })).toEqual({ state: 'available' })
- })
- it('knows the new end reason', () => {
- expect(isWatchEndReason('attempts')).toBe(true)
- })
-})
diff --git a/src/shared/watch-link/protocol.history.test.ts b/src/shared/watch-link/protocol.history.test.ts
deleted file mode 100644
index 5aac97657..000000000
--- a/src/shared/watch-link/protocol.history.test.ts
+++ /dev/null
@@ -1,115 +0,0 @@
-import { describe, expect, it } from 'vitest'
-import {
- HISTORY_MESSAGES_MAX,
- HISTORY_PARTS_MAX,
- HISTORY_TEXT_MAX,
- HISTORY_TOOL_ARG_MAX,
- WATCH_EVENT,
- WATCH_HISTORY_CAST,
- readHistoryPage,
- readHistoryRequest,
- sanitizeHistoryText
-} from './protocol'
-
-const msg = (role: 'user' | 'assistant', at: number, text: string) => ({ role, at, parts: [{ kind: 'text', text }] })
-const page = (over: Record<string, unknown> = {}) => ({
- before: null,
- status: 'ok',
- since: 1000,
- messages: [msg('user', 1500, 'hi')],
- olderCursor: null,
- start: 'shared',
- ...over
-})
-
-describe('watch:history names', () => {
- it('is a watch: cast and event, never the owner namespace', () => {
- expect(WATCH_HISTORY_CAST).toBe('watch:history')
- expect(WATCH_EVENT.history).toBe('watch:history')
- expect(WATCH_HISTORY_CAST.startsWith('watchLink:')).toBe(false)
- })
-})
-
-describe('sanitizeHistoryText', () => {
- it('keeps newlines and tabs, drops CR, other controls, ESC and bidi controls', () => {
- expect(sanitizeHistoryText('a\r\nb\tc\x1b[31md‮e\u0007', 100)).toBe('a\nb\tc[31mde')
- })
- it('caps by code point and marks the cut', () => {
- const out = sanitizeHistoryText('😀'.repeat(10), 7)
- expect(out).toBe('😀😀😀…')
- expect(out!.length).toBeLessThanOrEqual(7)
- })
- it('answers null for a non-string or an empty result', () => {
- expect(sanitizeHistoryText(5, 10)).toBeNull()
- expect(sanitizeHistoryText('\x00\x01', 10)).toBeNull()
- })
-})
-
-describe('readHistoryRequest', () => {
- it('reads an absent or a non-negative integer cursor', () => {
- expect(readHistoryRequest(undefined)).toEqual({ before: null })
- expect(readHistoryRequest({})).toEqual({ before: null })
- expect(readHistoryRequest({ before: 42 })).toEqual({ before: 42 })
- })
- it('refuses anything else', () => {
- for (const before of [-1, 1.5, '3', Number.NaN, Number.MAX_SAFE_INTEGER + 1, null]) {
- expect(readHistoryRequest({ before })).toBeNull()
- }
- expect(readHistoryRequest('x')).toBeNull()
- })
-})
-
-describe('readHistoryPage', () => {
- it('reads a well-formed page', () => {
- expect(readHistoryPage(page())).toEqual(page())
- })
- it('refuses an unknown status or start, or a bad cursor', () => {
- expect(readHistoryPage(page({ status: 'nope' }))).toBeNull()
- expect(readHistoryPage(page({ start: 'nope' }))).toBeNull()
- expect(readHistoryPage(page({ olderCursor: -3 }))).toBeNull()
- expect(readHistoryPage(page({ before: 'x' }))).toBeNull()
- expect(readHistoryPage(null)).toBeNull()
- })
- it('drops a message before the link was shared, or with no time', () => {
- const p = readHistoryPage(page({ messages: [msg('user', 999, 'old'), { role: 'user', parts: [] }, msg('assistant', 1000, 'new')] }))
- expect(p!.messages).toEqual([msg('assistant', 1000, 'new')])
- })
- it('drops a malformed part and a message left with none', () => {
- const p = readHistoryPage(
- page({
- messages: [
- { role: 'assistant', at: 1200, parts: [{ kind: 'html', text: '<b>' }, { kind: 'text', text: 'ok' }] },
- { role: 'assistant', at: 1300, parts: [{ kind: 'text', text: '\x00' }] },
- { role: 'system', at: 1400, parts: [{ kind: 'text', text: 'x' }] }
- ]
- })
- )
- expect(p!.messages).toEqual([{ role: 'assistant', at: 1200, parts: [{ kind: 'text', text: 'ok' }] }])
- })
- it('caps tool names and args, parts and messages', () => {
- const p = readHistoryPage(
- page({
- messages: Array.from({ length: HISTORY_MESSAGES_MAX + 5 }, (_, i) => ({
- role: 'assistant',
- at: 2000 + i,
- parts: Array.from({ length: HISTORY_PARTS_MAX + 3 }, () => ({ kind: 'tool', name: 'Bash', arg: 'x'.repeat(HISTORY_TOOL_ARG_MAX * 2) }))
- }))
- })
- )
- expect(p!.messages).toHaveLength(HISTORY_MESSAGES_MAX)
- // The NEWEST are kept: the oldest five go.
- expect(p!.messages[0].at).toBe(2005)
- expect(p!.messages[0].parts).toHaveLength(HISTORY_PARTS_MAX)
- const tool = p!.messages[0].parts[0] as { arg: string }
- expect(tool.arg.length).toBeLessThanOrEqual(HISTORY_TOOL_ARG_MAX)
- })
- it('caps a text part', () => {
- const p = readHistoryPage(page({ messages: [msg('assistant', 1500, 'y'.repeat(HISTORY_TEXT_MAX + 50))] }))
- const text = (p!.messages[0].parts[0] as { text: string }).text
- expect(text.length).toBeLessThanOrEqual(HISTORY_TEXT_MAX)
- expect(text.endsWith('…')).toBe(true)
- })
- it('a status other than ok carries no messages', () => {
- expect(readHistoryPage(page({ status: 'error' }))!.messages).toEqual([])
- })
-})
diff --git a/src/shared/watch-link/protocol.ts b/src/shared/watch-link/protocol.ts
deleted file mode 100644
index 869b8d464..000000000
--- a/src/shared/watch-link/protocol.ts
+++ /dev/null
@@ -1,401 +0,0 @@
-// What travels inside a live link's E2E tunnel, besides raw pty frames and pty:* events.
-// The viewer's namespace is `watch:` on purpose: the OWNER's IPC is `watchLink:`, which the relay
-// host refuses from every peer as host-only BEFORE any policy runs (src/shared/host-control.ts).
-
-export const WATCH_PROTOCOL_VERSION = 1
-export const WATCH_EVENT_PREFIX = 'watch:'
-export const WATCH_EVENT = {
- meta: 'watch:meta',
- keyframe: 'watch:keyframe',
- waiting: 'watch:waiting',
- chat: 'watch:chat',
- end: 'watch:end',
- /** To ONE viewer, never a broadcast: its control state, after an unlock or when control changes
- * under it (turned off, locked). The initial state rides `watch:meta`. */
- control: 'watch:control',
- /** To every joined viewer: who typed in the last few seconds (`WatchTypingEvent`). */
- typing: 'watch:typing',
- /** To ONE viewer, the answer to its `watch:history` cast (`WatchHistoryPage`). */
- history: 'watch:history'
-} as const
-/** A viewer's chat line (Commenter and Control links). */
-export const WATCH_CHAT_CAST = 'watch:chat'
-/**
- * Control links only. Answered to that viewer alone with `watch:control`. Two forms:
- * - SEALED, `{ sealed: { key, nonce, box } }` (./unlock-seal.ts): `{ name, password }` in a
- * `nacl.box` from a fresh key pair of the page's to the key THIS connection's meta offered
- * (`WatchMeta.unlockKey`). Every holder of a link can derive the tunnel's keys (both are derived
- * from the link's secret), so a recording of the relay traffic plus the link would otherwise read a
- * password a controller typed; the per-connection key pair is not derived from anything.
- * - PLAIN, `{ name, password }`: what a page from before sealing sends, and what a page sends to a host
- * that offered no key (a host from before sealing). A host refuses it (as a malformed attempt) on a
- * connection that has already sent a sealed one.
- */
-export const WATCH_UNLOCK_CAST = 'watch:unlock'
-/**
- * Control links only, from a controlling viewer: `{ data }`, at most `INPUT_MAX` UTF-16 units.
- *
- * THE PASTE-FRAMING CONTRACT. Both ends keep it; the host trusts nothing else.
- * - A controlling viewer forces bracketed paste ON in its OWN emulator (`?2004h`, put back after
- * any reset the stream applies) and frames EVERY paste it sends as `ESC[200~` … `ESC[201~`. It
- * never decides from the emulator's mode: what the viewer renders is a tmux CLIENT's output,
- * whose `?2004h` is constant, so that mode says nothing about the application in the pane.
- * - Before framing, the page removes both paste markers and every ESC from the paste's content: a
- * paste is text, and a marker inside it would end the frame early and turn the rest into typed
- * keys.
- * - The host splits keys from pastes on those frames alone. Everything outside a frame is KEYS,
- * typed byte for byte (tmux `send-keys -H`). The content of a frame is a PASTE, delivered with
- * tmux `paste-buffer -p`, so tmux frames it for the pane only when the pane's application asked
- * for bracketed paste. Where there is no tmux (the Windows session host, a direct Windows pane, a
- * plain shell) the backend's own path decides the same way, or sends it unframed.
- * - An emulator's answer to a query in the stream (DA, CPR, an OSC colour) travels ALONE, as its
- * own cast, never merged with typed input: the host drops a cast that is entirely a terminal
- * report, and only a whole one.
- * - Input from a connection that stopped controlling within the last 5 s (it released, or the
- * owner turned typing off or changed the password, or the link locked) is dropped silently:
- * keystrokes in flight when control ended are not a breach. After that, or from a connection that
- * never controlled, input is a policy breach and the host closes the connection.
- */
-export const WATCH_INPUT_CAST = 'watch:input'
-/** Control links only: drop the sender back to watching. No arguments. */
-export const WATCH_RELEASE_CAST = 'watch:release'
-/**
- * Every role: one page of the watched agent's CONVERSATION, never the terminal's history. The stream
- * is a tmux client painting on the alternate screen, so the viewer's emulator has nothing to scroll;
- * this is how a viewer reads back. `{ before?: number }` (`readHistoryRequest`): absent for the
- * newest page, else the `olderCursor` of the previous answer. Answered to that viewer alone with
- * `watch:history`.
- *
- * THE CUTOFF. A page holds only messages written at or after the moment the link was created
- * (`WatchHistoryPage.since`, the host's clock). A message with no time is never sent: nothing proves
- * it came after. What the link exposes is therefore what the terminal showed while it was shared, as
- * text, and nothing from before. Tool results are never sent (the screen shows a few lines of them
- * at most), and neither is the agent's thinking.
- */
-export const WATCH_HISTORY_CAST = 'watch:history'
-
-/** A Control link (`controller`) is a Commenter link plus typing for whoever unlocks it with the
- * link's password. Every addition to this protocol is additive, so `WATCH_PROTOCOL_VERSION` stays 1:
- * an older viewer page ignores the new events and simply cannot take control. */
-export type WatchLinkRole = 'viewer' | 'commenter' | 'controller'
-/** `attempts`: too many wrong passwords on this connection (it may reconnect through the link). */
-export const WATCH_END_REASONS = ['revoked', 'expired', 'node-gone', 'session-ended', 'host-stopping', 'kicked', 'attempts'] as const
-export type WatchLinkEndReason = (typeof WATCH_END_REASONS)[number]
-export function isWatchEndReason(x: unknown): x is WatchLinkEndReason {
- return typeof x === 'string' && (WATCH_END_REASONS as readonly string[]).includes(x)
-}
-
-export interface WatchMeta {
- v: number
- role: WatchLinkRole
- /** Sharer-supplied; render as text, marked as set by the sharer. */
- label: string
- title: string
- /** Epoch ms on the host's clock, corrected to the server's; `null` for a link with no end time. */
- expiresAt: number | null
- cols: number
- rows: number
- /** A Control link's state for THIS viewer at join; absent on every other role. */
- control?: WatchControlEvent
- /** Present (true) when the watched node is an agent whose conversation `watch:history` can read
- * back. Absent: a plain terminal, or a host older than read-back. */
- history?: true
- /** A Control link only: the base64 X25519 public key THIS connection seals its unlock to
- * (`WATCH_UNLOCK_CAST`). The same for the connection's life; absent from a host older than sealing. */
- unlockKey?: string
-}
-
-/** `controlling`: this viewer may type. `available`: a Control link this viewer may unlock.
- * `off`: the owner turned typing off. `locked`: too many wrong passwords across the link. */
-export type WatchControlState = 'controlling' | 'available' | 'off' | 'locked'
-/** Why an unlock was refused or control was taken away: `wrong` password, the link is `locked`,
- * typing is `off`, an attempt `too-soon` after the last, the terminal is `unsupported`, or some input
- * was `dropped` — over the rate limit, with no session to type into, or a delivery to the pane that
- * failed. The host does not say which, so a viewer must not name a cause. */
-export type WatchControlReason = 'wrong' | 'locked' | 'off' | 'too-soon' | 'unsupported' | 'dropped'
-const CONTROL_STATES: readonly WatchControlState[] = ['controlling', 'available', 'off', 'locked']
-const CONTROL_REASONS: readonly WatchControlReason[] = ['wrong', 'locked', 'off', 'too-soon', 'unsupported', 'dropped']
-export interface WatchControlEvent {
- state: WatchControlState
- reason?: WatchControlReason
- /** With `locked` only: how long until the lock lifts by itself, in ms from when the host sent it.
- * Absent: it does not (a lock from a host older than timed locks); only the sharer can lift it. The
- * sharer can always lift it sooner. */
- lockedForMs?: number
-}
-/** The longest a wrong-password lock lasts by itself (the host doubles it from 15 minutes per lock). */
-export const CONTROL_LOCK_MAX_MS = 24 * 60 * 60_000
-export interface WatchTypingEvent {
- /** Self-chosen names: claims, shown as such. */
- names: string[]
-}
-
-/** The largest `watch:input` cast, in UTF-16 units. */
-export const INPUT_MAX = 16384
-/** The longest password the unlock cast carries, in code points. */
-export const PASSWORD_MAX = 128
-/** The most names one `watch:typing` event carries. */
-export const TYPING_NAMES_MAX = 10
-
-/** A `watch:control` payload (or `WatchMeta.control`), or null when it is not one. An unknown reason
- * is dropped, never the state with it. */
-export function readControlEvent(x: unknown): WatchControlEvent | null {
- if (!x || typeof x !== 'object') return null
- const { state, reason, lockedForMs } = x as Record<string, unknown>
- if (!(CONTROL_STATES as readonly unknown[]).includes(state)) return null
- const out: WatchControlEvent = { state: state as WatchControlState }
- if ((CONTROL_REASONS as readonly unknown[]).includes(reason)) out.reason = reason as WatchControlReason
- // Only beside `locked`, and only a duration a host can mean: anything else reads as "until the
- // sharer lifts it", never as a time the page would promise.
- if (
- state === 'locked' && typeof lockedForMs === 'number' && Number.isInteger(lockedForMs) &&
- lockedForMs >= 0 && lockedForMs <= CONTROL_LOCK_MAX_MS
- ) {
- out.lockedForMs = lockedForMs
- }
- return out
-}
-/** A `watch:typing` payload's names: each one a clean chat name, deduplicated in order, at most
- * `TYPING_NAMES_MAX`. Anything else reads as nobody typing. */
-export function readTypingNames(x: unknown): string[] {
- if (!x || typeof x !== 'object') return []
- const names = (x as Record<string, unknown>).names
- if (!Array.isArray(names)) return []
- const out: string[] = []
- for (const raw of names) {
- if (out.length >= TYPING_NAMES_MAX) break
- const name = sanitizeChatName(raw)
- if (name !== null && !out.includes(name)) out.push(name)
- }
- return out
-}
-export interface WatchKeyframe {
- sessionId: string
- /** The visible screen with SGR, or '' when the backend has no visible-only capture. */
- screen: string
- /** tmux paints its client on the alternate screen; the viewer must switch to it BEFORE painting,
- * or every tmux redraw scrolls into the viewer's history (CLAUDE.md, co-attach seeding). */
- altScreen: boolean
- /** The host's cursor when the screen was captured, 0-based (tmux `cursor_x` / `cursor_y`). tmux's
- * following stream moves the cursor RELATIVE to where it believes the tty cursor is, and a capture
- * trims trailing blanks, so without this every keyframe offsets what is typed next. Absent when
- * the host could not read it; the viewer then leaves the cursor where the screen text ends. */
- cursor?: { x: number; y: number }
-}
-export interface WatchChatMessage {
- id: string
- name: string
- text: string
- at: number
- from: 'viewer' | 'sharer'
-}
-
-/** Chat caps, in UTF-16 units (what an input's `maxLength` counts), never cutting a code point. */
-export const CHAT_TEXT_MAX = 500
-export const CHAT_NAME_MAX = 32
-// C0 and C1 controls, DEL, and the ESC that starts every sequence. A newline becomes a space: chat
-// is one line, and a pasted multi-line block must not reflow the owner's popover.
-const CONTROLS = /[\u0000-\u001f\u007f-\u009f]/g
-// The directional formatting characters: ALM (U+061C), LRM/RLM (U+200E/F), the embeddings and
-// overrides (U+202A–E) and the isolates (U+2066–9). Chat is text one stranger wrote for the owner and
-// every other viewer to read; an RLO reorders everything drawn after it. Escaped, never literal (a
-// literal one is invisible in review). The same set as @shared/presence's BIDI_CONTROL_CHARS — this
-// directory imports nothing from outside itself (it is vendored byte for byte into nodeterm-web), so
-// the class is restated here and src/core/watch-link/wire.test.ts pins the two equal.
-const BIDI_CONTROLS = /[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g
-// Every other format character (Unicode category Cf) is invisible too: the zero-width space and
-// joiners, the word joiner, the soft hyphen, the tag characters. In a NAME any of them makes a second
-// name that looks exactly like the first — "Sharer" and "Sharer" + U+200B — in the chat, in "X is
-// typing…" and in the owner's "someone using the name …" notice. So a name keeps none of them, nor the
-// letters that draw as blank space (the Hangul fillers, the Braille blank, the combining grapheme
-// joiner, which is invisible but a mark rather than Cf).
-const NAME_INVISIBLES = /[\p{Cf}\u034f\u115f\u1160\u2800\u3164\uffa0]/gu
-// In chat TEXT the same characters go, but for the two joiners real writing needs: the zero-width
-// joiner (U+200D) holds emoji sequences together, and the zero-width non-joiner (U+200C) is how
-// Persian and the Indic scripts are spelled. Text is not an identity claim; a name is.
-const TEXT_INVISIBLES = /(?![\u200c\u200d])\p{Cf}/gu
-/** How much of a raw value the cleaning chain may look at, as a multiple of the cap: a cast is
- * attacker-sized, and the regex chain must not run over megabytes to keep 500 units of it. Generous
- * enough that whitespace and controls collapsing away never empty an honest message. */
-const RAW_FACTOR = 4
-
-/** At most `max` UTF-16 units, cut BETWEEN code points: a plain `slice` can split a surrogate pair
- * and leave a lone surrogate, which renders as a replacement glyph. Stops reading at the cap. */
-function capUnits(s: string, max: number): string {
- if (s.length <= max) return s
- let out = ''
- for (const ch of s) {
- if (out.length + ch.length > max) break
- out += ch
- }
- return out
-}
-
-function clean(raw: unknown, max: number, invisibles: RegExp = TEXT_INVISIBLES): string | null {
- if (typeof raw !== 'string') return null
- // Bound the input BEFORE the regex chain (by code point), then cap the cleaned text the same way.
- const bounded = capUnits(raw, max * RAW_FACTOR)
- const cleaned = bounded
- .replace(/[\r\n\t]+/g, ' ')
- .replace(CONTROLS, '')
- .replace(BIDI_CONTROLS, '')
- .replace(invisibles, '')
- .replace(/\s+/g, ' ')
- .trim()
- const s = capUnits(cleaned, max).trim()
- return s ? s : null
-}
-export const sanitizeChatText = (raw: unknown): string | null => clean(raw, CHAT_TEXT_MAX)
-/** A self-chosen name (chat, the typing line, an unlock): no invisible character at all, so two names
- * that look alike ARE alike. */
-export const sanitizeChatName = (raw: unknown): string | null => clean(raw, CHAT_NAME_MAX, NAME_INVISIBLES)
-
-// --- read-back (`watch:history`) --------------------------------------------------------------------
-
-/** Why a page holds no messages: `unsupported` — the node is not an agent with a readable
- * conversation; `untimed` — its conversation states no times, so nothing in it can be shown as
- * written after the link was shared; `error` — the host could not read it (try again). */
-export const HISTORY_STATUSES = ['ok', 'unsupported', 'untimed', 'error'] as const
-export type WatchHistoryStatus = (typeof HISTORY_STATUSES)[number]
-/** Why there is nothing older (only when `olderCursor` is null): `shared` — the page reached the
- * moment the link was created; `conversation` — it reached the start of the conversation;
- * `cut` — the host's reader for this agent cannot page further back. */
-export const HISTORY_STARTS = ['shared', 'conversation', 'cut'] as const
-export type WatchHistoryStart = (typeof HISTORY_STARTS)[number]
-export type WatchHistoryPart = { kind: 'text'; text: string } | { kind: 'tool'; name: string; arg: string }
-export interface WatchHistoryMessage {
- role: 'user' | 'assistant'
- /** When the line was written, epoch ms on the host's clock; never before `since`. */
- at: number
- parts: WatchHistoryPart[]
-}
-export interface WatchHistoryPage {
- /** The cursor this page answers (`null`: the newest page). */
- before: number | null
- status: WatchHistoryStatus
- /** When the link was created (the host's clock): nothing older is ever on a page. */
- since: number
- /** Oldest first. */
- messages: WatchHistoryMessage[]
- /** Ask for this as `before` to read older messages; null when there is nothing older to show. */
- olderCursor: number | null
- /** Why there is nothing older; null while `olderCursor` is set. */
- start: WatchHistoryStart | null
-}
-
-/** One text part, in UTF-16 units (the cut ends in `…`). */
-export const HISTORY_TEXT_MAX = 20_000
-export const HISTORY_TOOL_NAME_MAX = 64
-export const HISTORY_TOOL_ARG_MAX = 200
-export const HISTORY_PARTS_MAX = 64
-/** Messages on one page; the NEWEST are kept. */
-export const HISTORY_MESSAGES_MAX = 200
-/** All the text on one page. Past it, the OLDER messages' text is cut to `…` (they keep their place). */
-export const HISTORY_PAGE_TEXT_MAX = 400_000
-const HISTORY_CURSOR_MAX = Number.MAX_SAFE_INTEGER
-// Every C0 control but TAB and LF (CR is folded into LF first), DEL and the C1 controls. ESC goes with
-// them: the page renders text, never a terminal sequence.
-const HISTORY_CONTROLS = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g
-
-const isCursor = (x: unknown): x is number => typeof x === 'number' && Number.isInteger(x) && x >= 0 && x <= HISTORY_CURSOR_MAX
-
-/** Multi-line text a viewer may read: LF and TAB kept, CR folded into LF, every other control and
- * every bidi control removed, at most `max` UTF-16 units (a cut ends in `…`). Null when nothing is
- * left. */
-export function sanitizeHistoryText(raw: unknown, max: number): string | null {
- if (typeof raw !== 'string' || max < 2) return null
- const s = capUnits(raw, max * RAW_FACTOR)
- .replace(/\r\n?/g, '\n')
- .replace(HISTORY_CONTROLS, '')
- .replace(BIDI_CONTROLS, '')
- .replace(/^\n+/, '')
- .replace(/\s+$/, '')
- if (!s) return null
- return s.length <= max ? s : `${capUnits(s, max - 1)}…`
-}
-
-/** A `watch:history` cast's argument, or null when it is not one. */
-export function readHistoryRequest(x: unknown): { before: number | null } | null {
- if (x === undefined) return { before: null }
- if (!x || typeof x !== 'object') return null
- const before = (x as Record<string, unknown>).before
- if (before === undefined) return { before: null }
- return isCursor(before) ? { before } : null
-}
-
-function readHistoryPart(x: unknown): WatchHistoryPart | null {
- if (!x || typeof x !== 'object') return null
- const p = x as Record<string, unknown>
- if (p.kind === 'text') {
- const text = sanitizeHistoryText(p.text, HISTORY_TEXT_MAX)
- return text === null ? null : { kind: 'text', text }
- }
- if (p.kind === 'tool') {
- const name = clean(p.name, HISTORY_TOOL_NAME_MAX)
- if (name === null) return null
- return { kind: 'tool', name, arg: clean(p.arg, HISTORY_TOOL_ARG_MAX) ?? '' }
- }
- return null
-}
-
-function readHistoryMessage(x: unknown, since: number): WatchHistoryMessage | null {
- if (!x || typeof x !== 'object') return null
- const m = x as Record<string, unknown>
- if (m.role !== 'user' && m.role !== 'assistant') return null
- // The cutoff, enforced on BOTH ends: the host builds pages with it and the page re-reads them with it.
- if (typeof m.at !== 'number' || !Number.isFinite(m.at) || m.at < since) return null
- if (!Array.isArray(m.parts)) return null
- const parts: WatchHistoryPart[] = []
- for (const raw of m.parts) {
- if (parts.length >= HISTORY_PARTS_MAX) break
- const part = readHistoryPart(raw)
- if (part) parts.push(part)
- }
- return parts.length > 0 ? { role: m.role, at: m.at, parts } : null
-}
-
-/** A `watch:history` page, cleaned and bounded, or null when it is not one. The host builds every page
- * through this too, so both ends hold the same limits. */
-export function readHistoryPage(x: unknown): WatchHistoryPage | null {
- if (!x || typeof x !== 'object') return null
- const p = x as Record<string, unknown>
- if (!(HISTORY_STATUSES as readonly unknown[]).includes(p.status)) return null
- if (p.before !== null && !isCursor(p.before)) return null
- if (p.olderCursor !== null && !isCursor(p.olderCursor)) return null
- if (p.start !== null && !(HISTORY_STARTS as readonly unknown[]).includes(p.start)) return null
- if (typeof p.since !== 'number' || !Number.isFinite(p.since) || p.since < 0) return null
- const since = p.since
- const messages: WatchHistoryMessage[] = []
- if (p.status === 'ok' && Array.isArray(p.messages)) {
- for (const raw of p.messages) {
- const m = readHistoryMessage(raw, since)
- if (m) messages.push(m)
- }
- }
- const kept = messages.slice(-HISTORY_MESSAGES_MAX)
- // The page's text budget, spent newest first: an older message past it keeps its place, as `…`.
- let budget = HISTORY_PAGE_TEXT_MAX
- for (let i = kept.length - 1; i >= 0; i--) {
- kept[i] = {
- ...kept[i],
- parts: kept[i].parts.map((part) => {
- if (part.kind !== 'text') return part
- if (part.text.length <= budget) {
- budget -= part.text.length
- return part
- }
- const text = budget >= 2 ? `${capUnits(part.text, budget - 1)}…` : '…'
- budget = 0
- return { kind: 'text', text }
- })
- }
- }
- return {
- before: p.before as number | null,
- status: p.status as WatchHistoryStatus,
- since,
- messages: kept,
- olderCursor: p.olderCursor as number | null,
- start: p.start as WatchHistoryStart | null
- }
-}
diff --git a/src/shared/watch-link/unlock-seal.test.ts b/src/shared/watch-link/unlock-seal.test.ts
deleted file mode 100644
index 7ab241e44..000000000
--- a/src/shared/watch-link/unlock-seal.test.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-import { describe, expect, it } from 'vitest'
-import { readFileSync } from 'node:fs'
-import { join } from 'node:path'
-import nacl from 'tweetnacl'
-import { b64ToBytes, bytesToB64 } from './bytes'
-import { isSealedUnlock, openUnlock, readUnlockKey, sealUnlock, SEALED_BOX_B64_MAX } from './unlock-seal'
-
-const vectors = JSON.parse(readFileSync(join(__dirname, 'vectors.json'), 'utf8').replace(/\r\n/g, '\n'))
-const hex = (h: string): Uint8Array => Uint8Array.from(Buffer.from(h, 'hex'))
-
-describe('the sealed unlock', () => {
- it('opens with the connection key it was sealed to, and with no other', () => {
- const host = nacl.box.keyPair()
- const arg = sealUnlock('Ada', 'hunter2hunter2', host.publicKey)
- expect(isSealedUnlock(arg)).toBe(true)
- expect(openUnlock(arg, host.secretKey)).toEqual({ name: 'Ada', password: 'hunter2hunter2' })
- // Another connection's key (a link holder replaying a recording knows neither secret).
- expect(openUnlock(arg, nacl.box.keyPair().secretKey)).toBeNull()
- // Nothing of the password is in what crosses the wire.
- expect(JSON.stringify(arg)).not.toContain('hunter2')
- })
-
- it('draws a fresh key pair and nonce every time: the same password never seals to the same bytes', () => {
- const host = nacl.box.keyPair()
- const a = sealUnlock('Ada', 'pw-pw-pw-pw', host.publicKey).sealed
- const b = sealUnlock('Ada', 'pw-pw-pw-pw', host.publicKey).sealed
- expect(a.key).not.toBe(b.key)
- expect(a.nonce).not.toBe(b.nonce)
- expect(a.box).not.toBe(b.box)
- })
-
- it('opens the vector nodeterm-web is tested against', () => {
- expect(vectors.unlockSeals.length).toBeGreaterThan(0)
- for (const v of vectors.unlockSeals) {
- const secret = hex(v.hostSecretHex)
- expect(bytesToB64(nacl.box.keyPair.fromSecretKey(secret).publicKey)).toBe(v.hostPublicB64)
- expect(openUnlock({ sealed: v.sealed }, secret)).toEqual({ name: v.name, password: v.password })
- }
- })
-
- it('refuses anything that is not a sealed unlock this key opens', () => {
- const host = nacl.box.keyPair()
- const { sealed } = sealUnlock('Ada', 'pw-pw-pw-pw', host.publicKey)
- const bad: unknown[] = [
- undefined, null, 'x', { name: 'Ada', password: 'pw' }, { sealed: null }, { sealed: 'x' },
- { sealed: { ...sealed, key: 'AAAA' } },
- { sealed: { ...sealed, nonce: bytesToB64(new Uint8Array(23)) } },
- { sealed: { ...sealed, box: 'not base64!' } },
- { sealed: { ...sealed, box: 7 } },
- // One flipped bit of the box: the MAC fails.
- { sealed: { ...sealed, box: bytesToB64(b64ToBytes(sealed.box)!.map((x, i) => (i === 0 ? x ^ 1 : x))) } },
- { sealed: { ...sealed, box: 'A'.repeat(SEALED_BOX_B64_MAX + 4) } }
- ]
- for (const arg of bad) expect(openUnlock(arg, host.secretKey)).toBeNull()
- })
-
- it('refuses a box whose content is not a JSON object', () => {
- const host = nacl.box.keyPair()
- const page = nacl.box.keyPair()
- const nonce = nacl.randomBytes(24)
- for (const body of ['[1,2]', '"x"', 'not json', 'ÿþ']) {
- const bytes = body === 'ÿþ' ? Uint8Array.of(0xff, 0xfe) : new TextEncoder().encode(body)
- const box = nacl.box(bytes, nonce, host.publicKey, page.secretKey)
- const arg = { sealed: { key: bytesToB64(page.publicKey), nonce: bytesToB64(nonce), box: bytesToB64(box) } }
- expect(openUnlock(arg, host.secretKey)).toBeNull()
- }
- })
-
- it('reads an offered key only as 32 bytes of strict base64', () => {
- const k = nacl.box.keyPair().publicKey
- expect(readUnlockKey(bytesToB64(k))).toEqual(k)
- for (const x of [undefined, 7, '', bytesToB64(new Uint8Array(31)), bytesToB64(new Uint8Array(33)), `${bytesToB64(k)} `, 'A'.repeat(200)]) {
- expect(readUnlockKey(x)).toBeNull()
- }
- })
-
- it('throws (sends nothing) for a key that is not one', () => {
- expect(() => sealUnlock('Ada', 'pw', new Uint8Array(31))).toThrow()
- })
-})
diff --git a/src/shared/watch-link/unlock-seal.ts b/src/shared/watch-link/unlock-seal.ts
deleted file mode 100644
index a2f741aa6..000000000
--- a/src/shared/watch-link/unlock-seal.ts
+++ /dev/null
@@ -1,91 +0,0 @@
-// A Control link's password, sealed to ONE connection (`WATCH_UNLOCK_CAST`'s sealed form).
-//
-// Why: the tunnel's keys are not secret from a link holder. Both the host's and the viewer's key pairs
-// are derived from the link's secret (./keys.ts), and the session key from those plus two nonces sent
-// in the clear, so anyone who holds the link AND a recording of the relay traffic can read every
-// connection of it — a password a controller typed included. Sealing the unlock to a key pair that is
-// derived from nothing closes that for the password: the host makes a fresh X25519 key pair for each
-// viewer connection and offers its public key in that connection's meta (`WatchMeta.unlockKey`), the
-// page seals `{ name, password }` with `nacl.box` from a fresh key pair of its own and sends that
-// pair's public key beside the box. Neither secret key ever leaves its end, so a recording opens
-// nothing.
-//
-// What it does not do: an ACTIVE attacker holding the link who sits on the relay can still answer the
-// page as the host (the host's key pair is derived from the link too) and offer its own key. And what a
-// controller TYPES after unlocking rides the tunnel as before: readable to a link holder with a
-// recording. docs/live-links.md, "Threat notes".
-//
-// ISOMORPHIC like the rest of this directory (vendored byte for byte into nodeterm-web).
-import nacl from 'tweetnacl'
-import { b64ToBytes, bytesToB64, utf8 } from './bytes'
-
-/** An X25519 public key, and the box's nonce (`nacl.box`). */
-export const UNLOCK_KEY_BYTES = 32
-export const UNLOCK_NONCE_BYTES = 24
-/** The longest box the host opens, in base64 characters: a name (32 units) and a password (128 code
- * points) as JSON, with every character escaped, fit in well under half of it. */
-export const SEALED_BOX_B64_MAX = 4096
-
-export interface SealedUnlock {
- /** The page's own one-time public key (base64). */
- key: string
- nonce: string
- /** `nacl.box(JSON { name, password }, nonce, hostKey, pageSecret)`, base64. */
- box: string
-}
-
-const exactly = (x: unknown, n: number): Uint8Array | null => {
- if (typeof x !== 'string' || x.length > 64) return null
- const b = b64ToBytes(x)
- return b && b.length === n ? b : null
-}
-
-/** A meta's `unlockKey`: 32 bytes of strict base64, or null. */
-export function readUnlockKey(x: unknown): Uint8Array | null {
- return exactly(x, UNLOCK_KEY_BYTES)
-}
-
-/** The sealed cast argument for `name` and `password`, to `hostKey`. A fresh key pair and nonce each
- * time: the caller cannot supply either. */
-export function sealUnlock(name: string, password: string, hostKey: Uint8Array): { sealed: SealedUnlock } {
- if (!(hostKey instanceof Uint8Array) || hostKey.length !== UNLOCK_KEY_BYTES) throw new Error('An unlock key is 32 bytes.')
- const page = nacl.box.keyPair()
- const nonce = nacl.randomBytes(UNLOCK_NONCE_BYTES)
- const box = nacl.box(utf8(JSON.stringify({ name, password })), nonce, hostKey, page.secretKey)
- page.secretKey.fill(0)
- return { sealed: { key: bytesToB64(page.publicKey), nonce: bytesToB64(nonce), box: bytesToB64(box) } }
-}
-
-/**
- * The host's side: `{ name, password }` as the page sent them (not yet sanitized or bounded — the
- * caller's unlock reader does that), or null for anything that is not a sealed unlock this connection's
- * key opens: a missing or malformed field, a box over `SEALED_BOX_B64_MAX`, one that fails to open,
- * JSON that is not an object.
- */
-export function openUnlock(arg: unknown, hostSecret: Uint8Array): { name: unknown; password: unknown } | null {
- if (!arg || typeof arg !== 'object') return null
- const sealed = (arg as { sealed?: unknown }).sealed
- if (!sealed || typeof sealed !== 'object') return null
- const s = sealed as Record<string, unknown>
- const key = exactly(s.key, UNLOCK_KEY_BYTES)
- const nonce = exactly(s.nonce, UNLOCK_NONCE_BYTES)
- if (!key || !nonce || typeof s.box !== 'string' || s.box.length > SEALED_BOX_B64_MAX) return null
- const box = b64ToBytes(s.box)
- if (!box) return null
- const plain = nacl.box.open(box, nonce, key, hostSecret)
- if (!plain) return null
- let body: unknown
- try {
- body = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(plain))
- } catch {
- return null
- }
- if (!body || typeof body !== 'object' || Array.isArray(body)) return null
- const { name, password } = body as Record<string, unknown>
- return { name, password }
-}
-
-/** Whether a cast argument is the sealed form (whether or not it opens). */
-export function isSealedUnlock(arg: unknown): boolean {
- return !!arg && typeof arg === 'object' && 'sealed' in arg
-}
diff --git a/src/shared/watch-link/vectors.json b/src/shared/watch-link/vectors.json
deleted file mode 100644
index e83fde395..000000000
--- a/src/shared/watch-link/vectors.json
+++ /dev/null
@@ -1,73 +0,0 @@
-{
- "version": 1,
- "keys": [
- {
- "secretHex": "0000000000000000000000000000000000000000000000000000000000000000",
- "linkId": "AAAAAAAAAAAAAAAAAAAAAA",
- "hostPublicHex": "248c49740f0280865e9ca638c9cc1f32b015020a6ad0695b0b5c2d7d70ad9e61",
- "viewerPublicHex": "074dd1d6df9be25839ef8d69e5d9ed41b69523d9255dcc050ca3b409cf6d8961",
- "joinKeyHex": "257ba29f11037668071cafc88d291c8d63a088cbb2825db768f0b83c74dda201",
- "joinKeyHashHex": "719d067205a29f7687a7f4c44c49370530eacf2f908f4c8e724b9f88c036d12e",
- "url": "https://nodeterm.dev/s/AAAAAAAAAAAAAAAAAAAAAA#1.AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
- },
- {
- "secretHex": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",
- "linkId": "AbCdEfGhIjKlMnOpQrStUv",
- "hostPublicHex": "38d7d938cec47e82954388abcaf4c5f5bcf56a8d34f8c23b356db98539f6d408",
- "viewerPublicHex": "beda76d249bcd037d1511ea2438833aa0cdc57fdbe258c2976baefb049fbbc69",
- "joinKeyHex": "580abda58a4fda2821d7791d4d6abaaaa2946b7b56c6b09c40bff22d596e91fe",
- "joinKeyHashHex": "0e46259ff2ae7ae4fa121f053ad89ab71dd8eccd3e68763138c3eb5ddb3951ab",
- "url": "https://nodeterm.dev/s/AbCdEfGhIjKlMnOpQrStUv#1.AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8"
- },
- {
- "secretHex": "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
- "linkId": "-_-_-_-_-_-_-_-_-_-_-_",
- "hostPublicHex": "e7d5c5757e8b6956555f854561fc3858b1856fb9bbf6daf8ef61884bff81742b",
- "viewerPublicHex": "45df4e450d431b11c6be7dd91dbadfc680a24b10f4e392835d200950fa5a5129",
- "joinKeyHex": "06774dd6c06178807a798c85add0bdaeb60a03efefe6d48916b7d97cb188799c",
- "joinKeyHashHex": "7eb31e2557fbe97b6cdb072994bd032bcf9544f2df6251b9de282a657a1b25a4",
- "url": "https://nodeterm.dev/s/-_-_-_-_-_-_-_-_-_-_-_#1.__________________________________________8"
- }
- ],
- "ptyFrames": [
- {
- "sessionId": "s1",
- "data": "hello",
- "hex": "010002733168656c6c6f"
- },
- {
- "sessionId": "sess-\u00e9",
- "data": "a\u001b[31mb",
- "hex": "010007736573732dc3a9611b5b33316d62"
- }
- ],
- "sessionKeys": [
- {
- "baseKeyHex": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",
- "hostNonceHex": "202122232425262728292a2b2c2d2e2f",
- "clientNonceHex": "303132333435363738393a3b3c3d3e3f",
- "info": "nodeterm-relay-session-v2",
- "sessionKeyHex": "84cad65c51ad66339182b498586645dbe43473d759450a1eabcc883463f076e2"
- },
- {
- "baseKeyHex": "a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5",
- "hostNonceHex": "ffffffffffffffffffffffffffffffff",
- "clientNonceHex": "00000000000000000000000000000000",
- "info": "nodeterm-relay-session-v2",
- "sessionKeyHex": "b981020481a96beea9f8d84ad0821080833f37f1b8dd46bbbad8eb9350ac2543"
- }
- ],
- "unlockSeals": [
- {
- "hostSecretHex": "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20",
- "hostPublicB64": "B6N8vBQgk8i3VdwbEOhstCY3StFqqFPtC9/AsrhtHHw=",
- "sealed": {
- "key": "Pry2khSTRNxU5YFgz5C+2e6h3RToHI6R3lV699ev2RU=",
- "nonce": "AAcOFRwjKjE4P0ZNVFtiaXB3foWMk5qh",
- "box": "hjkePn1uutxgyUjg/Z9NkwrtBYrnFHizAtqhlZFy7p/89pgiQC5HOWorQLFSz+QCRzgeRYPz5U7yyp8gbd9H2/4hggDN097+2YfGiWQ="
- },
- "name": "Ay\u015fe \ud83d\udc69\u200d\ud83d\udcbb",
- "password": "tr0ub4dor & \u201c3\u201d"
- }
- ]
-}
diff --git a/src/shared/watch-link/vectors.test.ts b/src/shared/watch-link/vectors.test.ts
deleted file mode 100644
index 3693e7313..000000000
--- a/src/shared/watch-link/vectors.test.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-import { describe, it, expect } from 'vitest'
-import { readFileSync } from 'node:fs'
-import { join } from 'node:path'
-import { deriveWatchLinkKeys, sha256Hex } from './keys'
-import { bytesToHex, concatBytes, utf8 } from './bytes'
-import { hkdfSha256 } from './hkdf'
-import { formatWatchLink } from './link'
-import { encodePtyFrame, RELAY_SESSION_INFO } from './wire'
-import { openUnlock } from './unlock-seal'
-
-// vectors.json is what nodeterm-web's copy is tested against. It is the fixture; this test proves
-// the code still produces it. Regenerate ONLY for a deliberate protocol change (bump the version).
-const vectors = JSON.parse(readFileSync(join(__dirname, 'vectors.json'), 'utf8').replace(/\r\n/g, '\n'))
-const hex = (h: string): Uint8Array => Uint8Array.from(Buffer.from(h, 'hex'))
-
-describe('watch-link vectors', () => {
- it('the code reproduces every vector', async () => {
- for (const v of vectors.keys) {
- const secret = hex(v.secretHex)
- const k = deriveWatchLinkKeys(secret)
- expect(bytesToHex(k.host.publicKey)).toBe(v.hostPublicHex)
- expect(bytesToHex(k.viewer.publicKey)).toBe(v.viewerPublicHex)
- expect(bytesToHex(k.joinKey)).toBe(v.joinKeyHex)
- expect(await sha256Hex(k.joinKey)).toBe(v.joinKeyHashHex)
- expect(formatWatchLink(v.linkId, secret)).toBe(v.url)
- }
- for (const f of vectors.ptyFrames) expect(bytesToHex(encodePtyFrame(f.sessionId, f.data))).toBe(f.hex)
- // A Control link's sealed unlock: what a page sealed (nodeterm-web opens the same vector).
- expect(vectors.unlockSeals.length).toBeGreaterThan(0)
- for (const v of vectors.unlockSeals) {
- expect(openUnlock({ sealed: v.sealed }, hex(v.hostSecretHex))).toEqual({ name: v.name, password: v.password })
- }
- })
-
- it('derives every session key: HKDF-SHA256(base, hostNonce ‖ clientNonce, info)', async () => {
- // The web copy cannot run against the real relay, so this is how it checks its WebCrypto HKDF
- // path. src/core/watch-link/wire.test.ts pins the same vectors to the relay's deriveSessionKey.
- expect(vectors.sessionKeys.length).toBeGreaterThan(0)
- for (const v of vectors.sessionKeys) {
- expect(v.info).toBe(RELAY_SESSION_INFO)
- const key = await hkdfSha256(hex(v.baseKeyHex), concatBytes(hex(v.hostNonceHex), hex(v.clientNonceHex)), utf8(v.info), 32)
- expect(bytesToHex(key)).toBe(v.sessionKeyHex)
- }
- })
-})
diff --git a/src/shared/watch-link/wire.ts b/src/shared/watch-link/wire.ts
deleted file mode 100644
index 97aabcabf..000000000
--- a/src/shared/watch-link/wire.ts
+++ /dev/null
@@ -1,96 +0,0 @@
-// The relay's wire rules, restated without Node so the browser can speak them. The SOURCE of truth
-// is src/core/relay/relay-socket.ts + e2ee.ts + src/shared/rpc.ts, and two tests pin this copy to it:
-// - src/core/watch-link/wire.test.ts compares against the originals directly: the sealed box (both
-// directions), the pty frame, the tunnel JSON, the HKDF info string + salt order (against e2ee's
-// deriveSessionKey), and NONCE_BYTES against e2ee's randomSessionNonce. An edit to any of those in
-// the originals fails it.
-// - The seq header, TAG_*, ROLE_* and the nonce length the host accepts are module-private in
-// relay-socket.ts, so nothing compares them directly; src/core/watch-link/client.test.ts pins them
-// END TO END, by running the client that uses them against the real host-role relay socket. Its
-// past-seq-255 case is what catches a byte-swapped seq word. The one thing it cannot reach is the
-// order of the two seq words (only a seq past 2^32 would show it), and wire.test.ts pins that
-// layout to a literal copied from relay-socket.ts's private withHeader.
-// Both tests live in core because they import core modules the web tsconfig project cannot see.
-//
-// Sealed box: nonce(24) ‖ nacl.box.after(plain). Plain: [role:1][seqHi u32 LE][seqLo u32 LE][tag:1][body].
-import nacl from 'tweetnacl'
-import { concatBytes } from './bytes'
-
-export const TAG_RPC = 0x01
-export const TAG_TUNNEL_TEXT = 0x03
-export const TAG_TUNNEL_BIN = 0x04
-export const ROLE_HOST = 1
-export const ROLE_CLIENT = 2
-/** The HANDSHAKE nonce each side sends in `e2ee_hello` (the session key's HKDF salt is
- * hostNonce ‖ clientNonce). NOT the 24-byte box nonce: that one is `nacl.box.nonceLength`, drawn
- * fresh inside `sealBox` for every frame and carried in front of it. */
-export const NONCE_BYTES = 16
-export const RELAY_SESSION_INFO = 'nodeterm-relay-session-v2'
-const HEADER_BYTES = 9
-
-/** Seal one frame under the session key. The box nonce is drawn here, fresh per frame, and never
- * taken from a caller: a reused nonce under one key leaks the XOR of two plaintexts. */
-export function sealBox(plain: Uint8Array, key: Uint8Array): Uint8Array {
- const nonce = nacl.randomBytes(nacl.box.nonceLength)
- return concatBytes(nonce, nacl.box.after(plain, nonce, key))
-}
-
-export function openBox(box: Uint8Array, key: Uint8Array): Uint8Array | null {
- if (box.length < nacl.box.nonceLength + nacl.box.overheadLength) return null
- return nacl.box.open.after(box.subarray(nacl.box.nonceLength), box.subarray(0, nacl.box.nonceLength), key) ?? null
-}
-
-export function withHeader(role: number, seq: number, body: Uint8Array): Uint8Array {
- const out = new Uint8Array(HEADER_BYTES + body.length)
- const view = new DataView(out.buffer)
- out[0] = role
- view.setUint32(1, Math.floor(seq / 0x100000000), true)
- view.setUint32(5, seq >>> 0, true)
- out.set(body, HEADER_BYTES)
- return out
-}
-
-export function readHeader(plain: Uint8Array): { role: number; seq: number; body: Uint8Array } | null {
- if (plain.length < HEADER_BYTES) return null
- const view = new DataView(plain.buffer, plain.byteOffset, plain.byteLength)
- return { role: plain[0], seq: view.getUint32(1, true) * 0x100000000 + view.getUint32(5, true), body: plain.subarray(HEADER_BYTES) }
-}
-
-export function encodePtyFrame(sessionId: string, data: string): Uint8Array {
- const enc = new TextEncoder()
- const sid = enc.encode(sessionId)
- const out = new Uint8Array(3 + sid.length)
- out[0] = 0x01
- out[1] = (sid.length >> 8) & 0xff
- out[2] = sid.length & 0xff
- out.set(sid, 3)
- return concatBytes(out, enc.encode(data))
-}
-
-export function decodePtyFrame(buf: Uint8Array): { sessionId: string; data: string } | null {
- if (buf.length < 3 || buf[0] !== 0x01) return null
- const len = (buf[1] << 8) | buf[2]
- if (buf.length < 3 + len) return null
- const dec = new TextDecoder()
- return { sessionId: dec.decode(buf.subarray(3, 3 + len)), data: dec.decode(buf.subarray(3 + len)) }
-}
-
-export type TunnelMessage =
- | { t: 'ev'; channel: string; args: unknown[] }
- | { t: 'cast'; method: string; args: unknown[] }
-
-/** The two message kinds a viewer ever receives. `undef` restores `undefined` slots (rpc.ts). */
-export function parseTunnelJson(json: string): TunnelMessage | null {
- let m: { t?: unknown; channel?: unknown; method?: unknown; args?: unknown; undef?: unknown }
- try {
- m = JSON.parse(json)
- } catch {
- return null
- }
- if (!m || typeof m !== 'object' || !Array.isArray(m.args)) return null
- const args = [...m.args]
- if (Array.isArray(m.undef)) for (const i of m.undef) if (Number.isInteger(i) && i >= 0 && i < args.length) args[i] = undefined
- if (m.t === 'ev' && typeof m.channel === 'string') return { t: 'ev', channel: m.channel, args }
- if (m.t === 'cast' && typeof m.method === 'string') return { t: 'cast', method: m.method, args }
- return null
-}