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.

fix(presence): cap the focus/project ids and rate-limit every client cast

enesa9e6f9ba63d6
diff --git a/src/core/presence/hub.test.ts b/src/core/presence/hub.test.ts
index 7b7ce9cb7..e0b1d9505 100644
--- a/src/core/presence/hub.test.ts
+++ b/src/core/presence/hub.test.ts
@@ -1,9 +1,14 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { initPlatform, resetPlatformForTests } from '../platform'
import { fakePlatform, type FakePlatform } from '../platform-fake'
-import { PresenceHub, allocateRelayClientId, TYPING_THROTTLE_MS } from './hub'
+import {
+ PresenceHub,
+ allocateRelayClientId,
+ PRESENCE_RATE_BUDGETS,
+ TYPING_THROTTLE_MS
+} from './hub'
import { IPC } from '../../shared/ipc'
-import { PRESENCE_COLORS, type PeerDiff, type PeerState } from '../../shared/presence'
+import { PRESENCE_COLORS, REF_MAX_LEN, type PeerDiff, type PeerState } from '../../shared/presence'
let fake: FakePlatform
@@ -350,6 +355,160 @@ describe('PresenceHub noteTyping (Stage 2 caller; wired here)', () => {
})
})
+describe('caps on client-supplied ids (focus / project)', () => {
+ // Focus and project ids come straight off the wire and are stored verbatim in the peer table and
+ // reflected to EVERY peer. Uncapped, a 10 MB `presence:focus` becomes 10 MB x N peers of egress
+ // down the very sink pty output rides — terminals would stall behind a hostile string.
+ it('caps focus and project at REF_MAX_LEN code points, in the table AND in the broadcast diff', () => {
+ const hub = new PresenceHub()
+ hub.join(1, 'browser')
+
+ hub.setFocus(1, 'n'.repeat(REF_MAX_LEN + 5_000))
+ expect(hub.peers()[0].focus).toBe('n'.repeat(REF_MAX_LEN))
+ expect(diffs().at(-1)).toEqual({
+ op: 'update',
+ clientId: 1,
+ patch: { focus: 'n'.repeat(REF_MAX_LEN) }
+ })
+
+ hub.setProject(1, 'p'.repeat(REF_MAX_LEN + 5_000))
+ expect(hub.peers()[0].projectId).toBe('p'.repeat(REF_MAX_LEN))
+ expect(diffs().at(-1)).toMatchObject({
+ op: 'update',
+ clientId: 1,
+ patch: { projectId: 'p'.repeat(REF_MAX_LEN) }
+ })
+ })
+
+ it('caps by code point (the shared truncation rule), never splitting an emoji', () => {
+ const hub = new PresenceHub()
+ hub.join(1, 'browser')
+ hub.setFocus(1, '🙂'.repeat(REF_MAX_LEN + 100))
+ const focus = hub.peers()[0].focus as string
+ expect([...focus]).toHaveLength(REF_MAX_LEN)
+ expect(focus).not.toMatch(/[\uD800-\uDFFF]/u)
+ })
+
+ // Real ids are short (`term-ab12`, `web-3f9c`), so the cap can never truncate a legitimate one.
+ it('leaves a real node/project id untouched', () => {
+ const hub = new PresenceHub()
+ hub.join(1, 'browser')
+ hub.setFocus(1, 'term-ab12cd')
+ hub.setProject(1, 'proj-9f3a-2')
+ expect(hub.peers()[0]).toMatchObject({ focus: 'term-ab12cd', projectId: 'proj-9f3a-2' })
+ })
+})
+
+describe('rate limiting (a hostile tab must not degrade the room)', () => {
+ beforeEach(() => {
+ vi.useFakeTimers()
+ vi.setSystemTime(0)
+ })
+
+ /** Fire `n` cursor casts through the CAST entry point (where the limiter lives), each with a
+ * distinct position so the unchanged-value no-op can never be mistaken for a rate-limit drop. */
+ function floodCursor(clientId: number, n: number, from = 0): void {
+ for (let i = 0; i < n; i++) {
+ fake.senderListeners[IPC.presenceCursor](clientId, { x: from + i, y: 0 })
+ }
+ }
+
+ it('drops cursor casts past the burst budget, and refills at the sustained rate', () => {
+ const hub = new PresenceHub()
+ hub.registerIpc()
+ hub.join(1, 'browser')
+ const budget = PRESENCE_RATE_BUDGETS[IPC.presenceCursor]
+
+ const before = diffs().length
+ floodCursor(1, 1000) // a tight loop, all in the same millisecond
+ const passed = diffs().length - before
+ expect(passed).toBe(budget.burst) // the bucket, and not one cast more
+
+ // No time passed → still nothing gets through.
+ floodCursor(1, 100, 10_000)
+ expect(diffs().length - before).toBe(budget.burst)
+
+ // One second later the bucket has refilled by exactly the sustained rate.
+ vi.setSystemTime(1000)
+ floodCursor(1, 1000, 20_000)
+ expect(diffs().length - before).toBe(budget.burst + budget.perSec)
+ })
+
+ it('never drops an honest client: the renderer 20 Hz cursor stream passes in full', () => {
+ const hub = new PresenceHub()
+ hub.registerIpc()
+ hub.join(1, 'browser')
+
+ const before = diffs().length
+ // 10 s of the renderer's own throttle (CURSOR_MIN_INTERVAL_MS = 50 → 20 Hz). The cursor budget
+ // is matched to it, so a well-behaved tab must never lose a sample.
+ for (let i = 0; i < 200; i++) {
+ vi.setSystemTime(i * 50)
+ fake.senderListeners[IPC.presenceCursor](1, { x: i, y: i })
+ }
+ expect(diffs().length - before).toBe(200)
+ })
+
+ it('the limit is per (client, channel): a flooding tab starves neither its peers nor its own other channels', () => {
+ const hub = new PresenceHub()
+ hub.registerIpc()
+ hub.join(1, 'browser')
+ hub.join(2, 'browser')
+
+ floodCursor(1, 1000) // client 1 exhausts its cursor bucket
+ const after = diffs().length
+
+ // Client 2's cursor is untouched…
+ fake.senderListeners[IPC.presenceCursor](2, { x: 1, y: 1 })
+ expect(diffs().at(-1)).toEqual({ op: 'update', clientId: 2, patch: { cursor: { x: 1, y: 1 } } })
+ // …and so is client 1's focus (a separate channel keeps a separate bucket).
+ fake.senderListeners[IPC.presenceFocus](1, 'node-a')
+ expect(diffs().at(-1)).toEqual({ op: 'update', clientId: 1, patch: { focus: 'node-a' } })
+ expect(diffs().length).toBe(after + 2)
+ })
+
+ it('throttles the chat, focus and project channels too', () => {
+ const hub = new PresenceHub()
+ hub.registerIpc()
+ hub.join(1, 'browser')
+
+ for (const [channel, cast] of [
+ [IPC.presenceChat, (i: number) => fake.senderListeners[IPC.presenceChat](1, `msg ${i}`)],
+ [IPC.presenceFocus, (i: number) => fake.senderListeners[IPC.presenceFocus](1, `node-${i}`)],
+ [IPC.presenceProject, (i: number) => fake.senderListeners[IPC.presenceProject](1, `p-${i}`)]
+ ] as Array<[string, (i: number) => void]>) {
+ const before = diffs().length
+ for (let i = 0; i < 500; i++) cast(i)
+ expect(diffs().length - before).toBe(PRESENCE_RATE_BUDGETS[channel].burst)
+ }
+ })
+
+ it('a dropped cast changes nothing — the peer keeps the last state that got through', () => {
+ const hub = new PresenceHub()
+ hub.registerIpc()
+ hub.join(1, 'browser')
+ const budget = PRESENCE_RATE_BUDGETS[IPC.presenceCursor]
+
+ floodCursor(1, budget.burst + 50)
+ // The dropped casts must not be applied to the table either (silently ignored, not queued).
+ expect(hub.peers()[0].cursor).toEqual({ x: budget.burst - 1, y: 0 })
+ })
+
+ it('leaving frees the client\'s buckets, so a reconnecting id starts fresh', () => {
+ const hub = new PresenceHub()
+ hub.registerIpc()
+ hub.join(1, 'browser')
+ const budget = PRESENCE_RATE_BUDGETS[IPC.presenceCursor]
+ floodCursor(1, 1000)
+
+ hub.leave(1)
+ hub.join(1, 'browser')
+ const before = diffs().length
+ floodCursor(1, 1000, 50_000)
+ expect(diffs().length - before).toBe(budget.burst)
+ })
+})
+
describe('registerIpc', () => {
it('registers hello as a sender-aware request and the three signals as sender-aware casts', () => {
const hub = new PresenceHub()
diff --git a/src/core/presence/hub.ts b/src/core/presence/hub.ts
index 211134a7e..65e833be9 100644
--- a/src/core/presence/hub.ts
+++ b/src/core/presence/hub.ts
@@ -12,6 +12,7 @@ import { IPC } from '../../shared/ipc'
import { platform } from '../platform'
import {
CHAT_MAX_LEN,
+ REF_MAX_LEN,
capCodePoints,
defaultNameFor,
nextFreeColor,
@@ -25,6 +26,32 @@ import {
/** A typing badge re-broadcasts at most this often per (client, node) — see noteTyping. */
export const TYPING_THROTTLE_MS = 500
+/**
+ * Per-(client, channel) token buckets: `perSec` is the sustained rate, `burst` the bucket size
+ * (how far a client may run ahead of it). Everything the hub takes from a client fans out to every
+ * peer, so an unlimited ingest is an unlimited N-way amplifier: the ~20 Hz cursor throttle lives in
+ * the HONEST renderer only, and a tab that simply doesn't run it — or a scripted client on the
+ * shared Server Edition password — would otherwise be free to broadcast at loop speed and fill
+ * every peer's WS send buffer (the same sink pty output rides, so terminals stall behind it).
+ *
+ * The budgets are sized to the app's own behaviour, so a well-behaved client can never hit one:
+ * - cursor: 20/s, exactly the renderer's CURSOR_MIN_INTERVAL_MS (50 ms) throttle, with 2 s of
+ * burst for scheduling jitter,
+ * - chat: one cast per keystroke — faster than any human types,
+ * - focus / project: one per node hover / tab switch — orders of magnitude of headroom,
+ * - hello: sent at connect (and once more when the user names themselves).
+ * Excess casts are DROPPED silently. Never disconnect: an honest client that hits a burst edge
+ * (a wedged event loop suddenly flushing) would lose a frame, not its session — and the next
+ * cursor sample carries the current position anyway, so a dropped one is invisible.
+ */
+export const PRESENCE_RATE_BUDGETS: Record<string, { perSec: number; burst: number }> = {
+ [IPC.presenceCursor]: { perSec: 20, burst: 40 },
+ [IPC.presenceChat]: { perSec: 25, burst: 50 },
+ [IPC.presenceFocus]: { perSec: 10, burst: 20 },
+ [IPC.presenceProject]: { perSec: 5, burst: 10 },
+ [IPC.presenceHello]: { perSec: 2, burst: 5 }
+}
+
// Relay peers (phones) have no webContents id and no ServerPlatform uiId, so their ClientIds are
// minted here from a high range that can never collide with either (both start small and count up).
let nextRelayId = 1_000_000
@@ -49,6 +76,8 @@ export class PresenceHub {
private table = new Map<ClientId, PeerState>()
/** `${clientId}:${nodeId}` → last typing broadcast (throttle window). */
private lastTyping = new Map<string, number>()
+ /** `${clientId}:${channel}` → its token bucket (see PRESENCE_RATE_BUDGETS / allow). */
+ private buckets = new Map<string, { tokens: number; at: number }>()
private ipcRegistered = false
/** A UI connected. Colors are assigned next-free; the name is a placeholder until hello. */
@@ -84,9 +113,43 @@ export class PresenceHub {
for (const key of [...this.lastTyping.keys()]) {
if (key.startsWith(`${clientId}:`)) this.lastTyping.delete(key)
}
+ // Drop the rate-limit state too, or the maps would grow for the life of the process (a
+ // long-lived server sees every reconnect as a new ClientId).
+ for (const key of [...this.buckets.keys()]) {
+ if (key.startsWith(`${clientId}:`)) this.buckets.delete(key)
+ }
this.emit({ op: 'leave', clientId })
}
+ /**
+ * Take one token from this client's bucket for `channel`, or report that it is empty.
+ *
+ * WHERE THIS LIVES, AND WHY: at the CAST/REQUEST entry point (registerIpc) — not inside the
+ * setters. The hub is a dumb reflector whose setters are also the API the shells and Stage 2's
+ * internal callers use (noteTyping from the pty:write path, a relay bridge patching a phone's
+ * peer); rate-limiting those would throttle the app's own trusted plumbing. The entry point is
+ * the exact seam where an untrusted client's message becomes hub state, which is what needs a
+ * budget — and it is the one place ALL shells funnel through, so no shell can forget it.
+ */
+ private allow(clientId: ClientId, channel: string): boolean {
+ const budget = PRESENCE_RATE_BUDGETS[channel]
+ if (!budget) return true
+ const key = `${clientId}:${channel}`
+ const now = Date.now()
+ const prev = this.buckets.get(key)
+ // A fresh client starts with a full bucket; an existing one refills at `perSec`, capped at
+ // `burst` (so an idle minute does not bank a minute's worth of casts).
+ const tokens = prev
+ ? Math.min(budget.burst, prev.tokens + ((now - prev.at) / 1000) * budget.perSec)
+ : budget.burst
+ if (tokens < 1) {
+ this.buckets.set(key, { tokens, at: now })
+ return false
+ }
+ this.buckets.set(key, { tokens: tokens - 1, at: now })
+ return true
+ }
+
/** The client claims an identity. Returns its own clientId (so it never draws its own cursor)
* plus the current table. Names are unverified by design — see docs/team-presence.md. */
hello(clientId: ClientId, id: PeerIdentity): { clientId: ClientId; peers: PeerState[] } {
@@ -124,10 +187,12 @@ export class PresenceHub {
this.emit({ op: 'update', clientId, patch: { cursor: next } })
}
+ /** The node this client is working in. The id is client-supplied and reflected to every peer, so
+ * it goes through the shared truncation rule (REF_MAX_LEN) exactly like chat — see presence.ts. */
setFocus(clientId: ClientId, nodeId: string | null): void {
const peer = this.table.get(clientId)
if (!peer) return
- const next = typeof nodeId === 'string' && nodeId ? nodeId : null
+ const next = typeof nodeId === 'string' && nodeId ? capCodePoints(nodeId, REF_MAX_LEN) : null
if (peer.focus === next) return
peer.focus = next
this.emit({ op: 'update', clientId, patch: { focus: next } })
@@ -150,11 +215,14 @@ export class PresenceHub {
/** Which project (canvas) this client is on. Everyone else uses it to decide whether this
* peer's cursor/focus belongs on THEIR screen (peersOnProject) — a project is a separate
- * canvas with its own nodes and its own flow coordinates. null = no project open. */
+ * canvas with its own nodes and its own flow coordinates. null = no project open.
+ * Client-supplied, so capped with the shared truncation rule (REF_MAX_LEN) like every other
+ * string off the wire. */
setProject(clientId: ClientId, projectId: string | null): void {
const peer = this.table.get(clientId)
if (!peer) return
- const next = typeof projectId === 'string' && projectId ? projectId : null
+ const next =
+ typeof projectId === 'string' && projectId ? capCodePoints(projectId, REF_MAX_LEN) : null
if (peer.projectId === next) return
peer.projectId = next
this.emit({ op: 'update', clientId, patch: { projectId: next } })
@@ -193,22 +261,33 @@ export class PresenceHub {
if (this.ipcRegistered) return
this.ipcRegistered = true
const p = platform()
- p.handleWithSender(IPC.presenceHello, (senderId: number, id: PeerIdentity) =>
- this.hello(senderId, id)
- )
+ // Every entry point is rate-limited here (see allow): this is the seam where an untrusted
+ // client's message becomes hub state — and every shell funnels through it.
+ p.handleWithSender(IPC.presenceHello, (senderId: number, id: PeerIdentity) => {
+ // A dropped hello still ANSWERS (the response is how a client learns its own ClientId, and
+ // silence would hang its promise); it just doesn't apply the identity or broadcast.
+ if (!this.allow(senderId, IPC.presenceHello)) return { clientId: senderId, peers: this.peers() }
+ return this.hello(senderId, id)
+ })
p.onWithSender(
IPC.presenceCursor,
- (senderId: number, cursor: { x: number; y: number } | null) => this.setCursor(senderId, cursor)
+ (senderId: number, cursor: { x: number; y: number } | null) => {
+ if (!this.allow(senderId, IPC.presenceCursor)) return
+ this.setCursor(senderId, cursor)
+ }
)
- p.onWithSender(IPC.presenceFocus, (senderId: number, nodeId: string | null) =>
+ p.onWithSender(IPC.presenceFocus, (senderId: number, nodeId: string | null) => {
+ if (!this.allow(senderId, IPC.presenceFocus)) return
this.setFocus(senderId, nodeId)
- )
- p.onWithSender(IPC.presenceChat, (senderId: number, text: string | null) =>
+ })
+ p.onWithSender(IPC.presenceChat, (senderId: number, text: string | null) => {
+ if (!this.allow(senderId, IPC.presenceChat)) return
this.setChat(senderId, text)
- )
- p.onWithSender(IPC.presenceProject, (senderId: number, projectId: string | null) =>
+ })
+ p.onWithSender(IPC.presenceProject, (senderId: number, projectId: string | null) => {
+ if (!this.allow(senderId, IPC.presenceProject)) return
this.setProject(senderId, projectId)
- )
+ })
}
private emit(diff: PeerDiff): void {
diff --git a/src/shared/presence.ts b/src/shared/presence.ts
index b5fedf664..43350903d 100644
--- a/src/shared/presence.ts
+++ b/src/shared/presence.ts
@@ -60,6 +60,12 @@ export const TYPING_DECAY_MS = 2000
/** Caps: a peer cannot flood the wire with a giant name or chat line. */
export const NAME_MAX_LEN = 32
export const CHAT_MAX_LEN = 200
+/** Cap for the ids a client reports (focus node, active project). Real ones are short and
+ * generated (`term-ab12`, `web-3f9c`), so this can never truncate a legitimate id — it exists
+ * because these strings are taken verbatim off the wire and reflected to EVERY peer, down the
+ * same sink pty output rides: an uncapped 10 MB `presence:focus` at cursor rate would fill every
+ * peer's send buffer and stall their terminals behind it. */
+export const REF_MAX_LEN = 128
/** First palette color not already in use; wraps by count once every color is taken.
* `taken` is `readonly` so callers stay unconstrained (a mutable `string[]` is accepted). */
@@ -89,7 +95,8 @@ export function peersOnProject(peers: PeerState[], projectId: string | null): Pe
/** Cap a string at `max` *code points*, not UTF-16 code units: `slice` would cut a surrogate
* pair (emoji, CJK extensions) in half and leave a lone surrogate, which renders as "�" in
* every peer's facepile / chat bubble. The single truncation rule for the whole feature — the
- * hub caps chat with it (CHAT_MAX_LEN) and capName caps names with it.
+ * hub caps chat (CHAT_MAX_LEN) and the focus/project ids (REF_MAX_LEN) with it, and capName caps
+ * names with it.
*
* COST IS O(max), NOT O(text) — deliberately. This is a door for UNTRUSTED input (any client can
* cast a `presence:chat` / `presence:focus` of whatever size the socket accepts), and the obvious