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(live-links): unlock a Control link with its password, host-side throttles and lock

review2a1139e12199
diff --git a/src/core/watch-link/chat-cast.guard.test.ts b/src/core/watch-link/chat-cast.guard.test.ts
index 2a0069e6f..6c15610be 100644
--- a/src/core/watch-link/chat-cast.guard.test.ts
+++ b/src/core/watch-link/chat-cast.guard.test.ts
@@ -1,6 +1,6 @@
// 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 link only (watcher-policy.ts). Nothing registers `watch:chat` on
+// 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.
@@ -20,7 +20,7 @@ const MENTIONS = /WATCH_CHAT_CAST|WATCH_EVENT\s*\.\s*chat\b|WATCH_EVENT\s*\[\s*[
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 link only',
+ '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"
}
diff --git a/src/core/watch-link/link-host.test.ts b/src/core/watch-link/link-host.test.ts
index f047a8ada..d4cf1bfc4 100644
--- a/src/core/watch-link/link-host.test.ts
+++ b/src/core/watch-link/link-host.test.ts
@@ -4,7 +4,7 @@
//
// 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 } from 'vitest'
+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'
@@ -14,7 +14,15 @@ 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 { WATCH_EVENT, type WatchKeyframe } from '../../shared/watch-link/protocol'
+import {
+ WATCH_EVENT,
+ WATCH_INPUT_CAST,
+ WATCH_UNLOCK_CAST,
+ type WatchControlEvent,
+ type WatchKeyframe,
+ type WatchLinkRole,
+ type WatchMeta
+} from '../../shared/watch-link/protocol'
import {
createLinkHost,
CONFIRM_DEADLINE_MS,
@@ -23,14 +31,18 @@ import {
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 type { WatchLinkRecord } from './store'
+import { hashControlPassword, verifyControlPassword, type ControlPasswordHash } from './password'
+import type { WatchLinkControlRecord, WatchLinkRecord } from './store'
import type { UiSink } from '../ui-sink-registry'
const ESC = '\x1b'
@@ -81,7 +93,12 @@ function manualClock() {
type ManualClock = ReturnType<typeof manualClock>
interface SetupOpts {
- role?: 'viewer' | 'commenter'
+ 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>
join?: (clientId: number, nodeId: string, viewerId: string) => Promise<WatchJoin | null> | WatchJoin | null
capture?: (sid: string) => Promise<VisibleCapture> | VisibleCapture
alive?: (sid: string) => boolean
@@ -96,7 +113,7 @@ 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
+ createdAt: 0, expiresAt: Date.now() + 3600_000, secret, ...(o.control ? { control: o.control } : {})
}
const peers: RelayTransport[] = []
const sinks = new Map<number, UiSink>()
@@ -108,6 +125,9 @@ function setup(o: SetupOpts = {}) {
const joinTimes: number[] = []
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 = {
@@ -165,7 +185,20 @@ function setup(o: SetupOpts = {}) {
},
onChat: (m) => chats.push(m),
onViewerJoined: (n) => joined.push(n),
- onGone: (r) => gone.push(r)
+ 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: () => {
+ locks++
+ if (record.control) record.control.locked = true
+ }
})
hosts.push(host)
return {
@@ -174,6 +207,10 @@ function setup(o: SetupOpts = {}) {
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]
}
@@ -965,3 +1002,525 @@ describe('createLinkHost — ending', () => {
expect(t.left).toHaveLength(MAX_VIEWERS_PER_LINK)
})
})
+
+/** 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 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, ...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' })
+ })
+
+ // --- 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, '‮', 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‮ 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'])
+ })
+
+ 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' })
+ })
+
+ // --- 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 is accepted, and reaches no pty yet', 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' })
+ const calls = t.calls.length
+ expect(a.c.sendInput('ls\r')).toBe(true)
+ await settleReal()
+ expect(a.log.closed).toBe(0)
+ expect(t.host.viewers()).toHaveLength(1)
+ expect(t.calls.slice(calls)).toEqual([])
+ // Released: the same input is now a breach.
+ expect(await ask(a, () => a.c.release())).toEqual({ state: 'available' })
+ expect(a.c.sendInput('ls\r')).toBe(true)
+ await vi.waitFor(() => expect(a.log.closed).toBe(1))
+ expect(t.host.viewers()).toEqual([])
+ })
+
+ it('on a Commenter link, unlock and input 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' }])
+ 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)
+ })
+})
diff --git a/src/core/watch-link/link-host.ts b/src/core/watch-link/link-host.ts
index 9c1a02d2c..424cc319d 100644
--- a/src/core/watch-link/link-host.ts
+++ b/src/core/watch-link/link-host.ts
@@ -5,12 +5,28 @@
// 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).
//
-// READ-ONLY IS ENFORCED HERE, on the host. The relay-host `access` hook refuses every request and
-// every cast but a Commenter's chat (watcherAccess), and this module's own `PeerAttach` is the second
-// layer: it forwards nothing to any platform, and a request or a non-chat cast that reaches it anyway
-// means the access policy failed, so the session is CLOSED (fail closed, as relay-host does for a
-// throwing wrapSink). No viewer byte, size or resize reaches a pty: the join, the size sync and the
-// capture take only ids the host chose. No `interceptReq` is ever supplied (it would bypass `access`).
+// 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. No viewer size or resize reaches a pty, and no viewer byte does yet (accepted input is not
+// delivered): the join, the size sync and the capture 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
+// lives in memory and only `allowControl` resets it. 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.
//
// 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).
@@ -79,12 +95,17 @@ import type { RpcErr } from '../../shared/rpc'
import { bytesToB64, bytesToHex } from '../../shared/watch-link/bytes'
import { deriveWatchLinkKeys } from '../../shared/watch-link/keys'
import {
+ PASSWORD_MAX,
WATCH_CHAT_CAST,
WATCH_EVENT,
+ WATCH_INPUT_CAST,
WATCH_PROTOCOL_VERSION,
+ WATCH_RELEASE_CAST,
+ WATCH_UNLOCK_CAST,
sanitizeChatName,
sanitizeChatText,
type WatchChatMessage,
+ type WatchControlEvent,
type WatchKeyframe,
type WatchLinkEndReason,
type WatchMeta
@@ -123,6 +144,11 @@ export const WATCHER_SIZE_SYNC_MS = 10_000
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 = 10
const RATE = 256 * 1024
const BURST = 1024 * 1024
@@ -176,6 +202,14 @@ export interface LinkHostDeps {
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`
+ * before it returns (the host reads the record live and never writes it). */
+ onControlLocked(): void
}
export type LinkRuntimeStatus = 'live' | 'reconnecting' | 'refused'
export interface LinkViewer {
@@ -187,6 +221,10 @@ export interface LinkViewer {
* 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
+ /** Typed in the last few seconds. False until input is delivered. */
+ typing: boolean
}
export interface LinkHost {
start(): void
@@ -196,6 +234,13 @@ export interface LinkHost {
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. */
+ passwordChanged(): void
+ /** The owner cleared the lock: the link-wide wrong count starts over, then as `controlChanged`. */
+ allowControl(): void
}
interface Conn {
@@ -213,6 +258,12 @@ interface Conn {
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
// The watched session (null while waiting).
sessionId: string | null
altScreen: boolean
@@ -268,6 +319,18 @@ function normalizeJoin(r: unknown): WatchJoin | null {
return { sessionId, cols: o.cols as number, rows: o.rows as number, altScreen: o.altScreen === true }
}
+/** 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 }
+}
+
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()
@@ -289,6 +352,13 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Lin
let syncTimer: unknown = null
let stopped = false
const warnedHost = new Set<string>()
+ /** Wrong unlock attempts across the link (in memory: only the lock is persisted, by the service). */
+ let linkWrong = 0
+ /** 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
const clearTimer = (h: unknown): void => {
if (h !== null) deps.clearTimeout(h)
@@ -366,6 +436,7 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Lin
const sid = c.sessionId
c.sessionId = null
c.streaming = false
+ c.controlling = false
if (sid !== null) leave(c.clientId, sid, c.viewerId, c)
safe('the scheduler', () => c.ev.onClose())
updateSyncTimer()
@@ -591,6 +662,8 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Lin
cols: res.cols,
rows: res.rows
}
+ // A Control link's state for THIS viewer rides every (re)join; absent on every other role.
+ if (record.role === 'controller') meta.control = controlStateFor(c)
if (!send(c, WATCH_EVENT.meta, meta)) return
clearTimer(c.settleTimer)
c.settleTimer = deps.setTimeout(() => {
@@ -656,11 +729,29 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Lin
safe('onChange', deps.onChange)
}
function onViewerCast(c: Conn, method: string, args: unknown[]): void {
- // relay-host's access hook admits a Commenter's chat cast and nothing else.
- if (method !== WATCH_CHAT_CAST || record.role !== 'commenter') {
- policyBreach(c, `cast ${method}`)
+ // relay-host's access hook admits exactly these (watcherAccess); anything else got past it.
+ 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)
+ 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
@@ -674,6 +765,122 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Lin
publish({ id: bytesToHex(nacl.randomBytes(8)), name, text, at: now, from: 'viewer' })
}
+ // --- 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
+ if (c.controlling && ctl && ctl.enabled && !ctl.locked) return { state: 'controlling' }
+ if (ctl?.locked) return { state: 'locked' }
+ if (!ctl || !ctl.enabled) return { state: 'off' }
+ return { state: 'available' }
+ }
+ 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: state.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 = readUnlock(args[0])
+ // A malformed attempt is still an attempt.
+ if (!attempt) {
+ wrongAttempt(c)
+ 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)
+ return
+ }
+ c.controlling = true
+ c.wrong = 0
+ c.name = attempt.name
+ sendControl(c, { state: 'controlling' })
+ 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).state
+ if (state === 'locked' || state === 'off') sendControl(c, { state, reason: state })
+ else sendControl(c, { state, reason: 'too-soon' })
+ }
+ function wrongAttempt(c: Conn): void {
+ c.wrong++
+ linkWrong++
+ sendControl(c, { state: controlStateFor(c).state, reason: 'wrong' })
+ if (linkWrong >= WRONG_PER_LINK) lockLink()
+ 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. */
+ function lockLink(): void {
+ controlEpoch++
+ safe('onControlLocked', () => deps.onControlLocked())
+ for (const c of joinedConns()) {
+ c.controlling = false
+ sendControl(c, { state: 'locked', reason: '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) c.controlling = false
+ sendControl(c, controlStateFor(c))
+ }
+ safe('onChange', deps.onChange)
+ }
+ function onRelease(c: Conn): void {
+ if (c.ended || c.joinedAt === null || !c.controlling) return
+ c.controlling = false
+ sendControl(c, controlStateFor(c))
+ safe('onChange', deps.onChange)
+ }
+ function onInput(c: Conn): void {
+ if (c.ended) return
+ if (controlStateFor(c).state !== 'controlling') {
+ policyBreach(c, `cast ${WATCH_INPUT_CAST}`)
+ return
+ }
+ // Accepted from a controller, and not delivered yet: no viewer byte reaches the pane.
+ }
+
// --- listeners and viewer sessions ----------------------------------------------------------------
const bridged = (c: Conn): void => {
@@ -696,6 +903,9 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Lin
joinedAt: null,
name: null,
lastChatAt: -Infinity,
+ controlling: false,
+ wrong: 0,
+ lastUnlockAt: -Infinity,
sessionId: null,
altScreen: false,
joining: false,
@@ -824,7 +1034,14 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Lin
const out: LinkViewer[] = []
for (const c of conns) {
if (c.joinedAt === null || c.ended) continue
- out.push({ viewerId: c.viewerId, name: c.name, joinedAt: c.joinedAt, waiting: c.joinRefused && c.sessionId === null })
+ out.push({
+ viewerId: c.viewerId,
+ name: c.name,
+ joinedAt: c.joinedAt,
+ waiting: c.joinRefused && c.sessionId === null,
+ controlling: c.controlling,
+ typing: false
+ })
}
return out
}
@@ -916,7 +1133,7 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Lin
},
postSharerChat(text) {
const clean = sanitizeChatText(text)
- if (!clean || record.role !== 'commenter' || stopped) return null
+ 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
@@ -928,6 +1145,25 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Lin
if (sched.idle > 0 || sched.bridged >= MAX_VIEWERS_PER_LINK) return 'live'
return sched.lastError ? 'reconnecting' : 'live'
},
- viewers
+ viewers,
+ controlChanged() {
+ if (stopped || record.role !== 'controller') return
+ broadcastControl()
+ },
+ passwordChanged() {
+ if (stopped || record.role !== 'controller') return
+ controlEpoch++
+ for (const c of joinedConns()) {
+ if (!c.controlling) continue
+ c.controlling = false
+ 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/service.test.ts b/src/core/watch-link/service.test.ts
index 0cc4aa0c8..9dec131a7 100644
--- a/src/core/watch-link/service.test.ts
+++ b/src/core/watch-link/service.test.ts
@@ -80,7 +80,10 @@ function fakeHosts() {
postSharerChat: (text) => ({ id: 'm1', name: record.label, text, at: 1, from: 'sharer' }),
chatHistory: () => h.chat,
status: () => h.status,
- viewers: () => h.viewers
+ viewers: () => h.viewers,
+ controlChanged: () => {},
+ passwordChanged: () => {},
+ allowControl: () => {}
}
}
return { made, createHost }
@@ -790,7 +793,7 @@ describe('createWatchLinkService — the host seams', () => {
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 }]
+ 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 }])
})
@@ -800,8 +803,8 @@ describe('createWatchLinkService — the host seams', () => {
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 },
- { viewerId: 'v-2', name: null, joinedAt: 6, waiting: false }
+ { 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])
})
@@ -810,7 +813,7 @@ describe('createWatchLinkService — the host seams', () => {
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 }]
+ 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' })
diff --git a/src/core/watch-link/service.ts b/src/core/watch-link/service.ts
index 69509b016..3cfcfb742 100644
--- a/src/core/watch-link/service.ts
+++ b/src/core/watch-link/service.ts
@@ -431,7 +431,14 @@ export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkSer
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 })
+ onGone: (reason) => end(r.linkId, reason, { serverRevoke: false, notify: true }),
+ // A Control link is not wired to the owner's controls yet: no password opens it, and a lock
+ // holds in memory only (the host reads `record.control` and never writes it).
+ verifyPassword: async () => false,
+ onControlTaken: () => {},
+ onControlLocked: () => {
+ if (r.control) r.control.locked = true
+ }
})
} catch (err) {
warn(`a link could not be hosted: ${errorText(err)}`)
diff --git a/src/core/watch-link/service.workspace.test.ts b/src/core/watch-link/service.workspace.test.ts
index aa132858b..0b3aba56c 100644
--- a/src/core/watch-link/service.workspace.test.ts
+++ b/src/core/watch-link/service.workspace.test.ts
@@ -70,7 +70,8 @@ function linksOver(store: WorkspaceStore) {
emit: () => {},
createHost: (): LinkHost => ({
start: () => {}, stop: (r) => { stopped.push(r) }, kick: () => false, postSharerChat: () => null,
- chatHistory: () => [], status: () => 'live', viewers: () => []
+ chatHistory: () => [], status: () => 'live', viewers: () => [],
+ controlChanged: () => {}, passwordChanged: () => {}, allowControl: () => {}
})
})
services.push(s)
diff --git a/src/core/watch-link/watcher-policy.test.ts b/src/core/watch-link/watcher-policy.test.ts
index a8b737573..fd7530797 100644
--- a/src/core/watch-link/watcher-policy.test.ts
+++ b/src/core/watch-link/watcher-policy.test.ts
@@ -1,8 +1,15 @@
import { describe, it, expect } from 'vitest'
import { IPC } from '../../shared/ipc'
import { encodePtyData, decodePtyData } from '../../shared/rpc'
-import { WATCH_CHAT_CAST, WATCH_EVENT } from '../../shared/watch-link/protocol'
-import { watcherAccess, watcherEventAllowed, wrapWatcherSink, WATCHER_BUFFER_LIMIT } from './watcher-policy'
+import {
+ WATCH_CHAT_CAST,
+ WATCH_EVENT,
+ 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'
@@ -13,10 +20,12 @@ const channelValues = (): string[] =>
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 both roles', () => {
+ it('refuses every IPC channel as a request and as a cast, for every role', () => {
for (const ch of channelValues()) {
- for (const role of ['viewer', 'commenter'] as const) {
+ for (const role of ROLES) {
expect(watcherAccess('req', ch, role).allow).toBe(false)
expect(watcherAccess('cast', ch, role).allow).toBe(false)
}
@@ -27,6 +36,35 @@ describe('watcherAccess', () => {
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: chat for commenter and controller, unlock / input / release for controller, all as casts', () => {
+ const admitted = new Set([
+ `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_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', () => {
diff --git a/src/core/watch-link/watcher-policy.ts b/src/core/watch-link/watcher-policy.ts
index 0707cd9e9..c457893ca 100644
--- a/src/core/watch-link/watcher-policy.ts
+++ b/src/core/watch-link/watcher-policy.ts
@@ -1,7 +1,10 @@
// 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 a Commenter link's chat cast.
+// - Inbound: every request and cast is refused, except the chat cast on a Commenter or Control
+// link, and the unlock / input / release casts on a Control link. 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()).
@@ -15,7 +18,14 @@
// 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, type WatchLinkRole } from '../../shared/watch-link/protocol'
+import {
+ WATCH_CHAT_CAST,
+ WATCH_EVENT_PREFIX,
+ 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'
@@ -25,8 +35,14 @@ 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: 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' && method === WATCH_CHAT_CAST && role === 'commenter') return { allow: true }
+ if (kind !== 'cast') return { allow: false, message: WATCHER_REFUSAL }
+ 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 }
}