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(watch-link): harden the vendored protocol (chat bidi + code-point caps, sealBox, link format)

revieweac2d29010c4
diff --git a/src/core/watch-link/api.test.ts b/src/core/watch-link/api.test.ts
index 78a833b5e..7877ee531 100644
--- a/src/core/watch-link/api.test.ts
+++ b/src/core/watch-link/api.test.ts
@@ -68,13 +68,25 @@ function trackTimers(delay: number) {
}
}
+/** 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: 'L', expiresAt: serverNow / 1000 + 3600 }, { date: new Date(serverNow).toUTCString() }), 5_000)
+ 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: 'L', expiresAt: 5_000 + 3_600_000 })
+ 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' })
+ }
})
it('maps create errors', async () => {
@@ -241,8 +253,8 @@ describe('createWatchLinkApi', () => {
// 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: 'L', expiresAt: serverExp }, headers), 5_000).a.create('e', 'h', 3600)
- expect(r).toEqual({ ok: true, linkId: 'L', expiresAt: serverExp * 1000 })
+ 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 })
}
})
diff --git a/src/core/watch-link/api.ts b/src/core/watch-link/api.ts
index ba061e87e..d28777e5e 100644
--- a/src/core/watch-link/api.ts
+++ b/src/core/watch-link/api.ts
@@ -1,6 +1,7 @@
// 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'
export type CreateError = 'not-entitled' | 'limit-active' | 'limit-daily' | 'rate-limited' | 'license-check' | 'bad-request' | 'network'
export type HostTokenResult = MintResult | { ok: false; kind: 'gone'; reason: 'revoked' | 'expired' }
@@ -81,12 +82,15 @@ export function createWatchLinkApi(o: { apiBase: string; fetch?: typeof fetch; n
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).
- if (r.status === 200 && typeof r.json?.linkId === 'string' && typeof exp === 'number' && Number.isFinite(exp) && exp > 0) {
+ // 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) && 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).
const t = now()
- return { ok: true, linkId: r.json.linkId, expiresAt: t + tokenTtlMs(exp, r.date, t) }
+ 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) {
diff --git a/src/core/watch-link/service.ts b/src/core/watch-link/service.ts
index 7d6c797d6..b1ff906b7 100644
--- a/src/core/watch-link/service.ts
+++ b/src/core/watch-link/service.ts
@@ -305,7 +305,14 @@ export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkSer
statePending = true
queueMicrotask(() => {
statePending = false
- safeEmit(IPC.watchLinkState, list())
+ // `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
diff --git a/src/core/watch-link/wire.test.ts b/src/core/watch-link/wire.test.ts
index 493284ee4..26a9fa8a6 100644
--- a/src/core/watch-link/wire.test.ts
+++ b/src/core/watch-link/wire.test.ts
@@ -7,8 +7,19 @@ 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, WATCH_CHAT_CAST, WATCH_EVENT_PREFIX } from '../../shared/watch-link/protocol'
+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 () => {
@@ -60,6 +71,35 @@ describe('the wire rules match the relay they were copied from', () => {
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', () => {
@@ -67,6 +107,15 @@ describe('protocol', () => {
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)
@@ -77,4 +126,47 @@ describe('protocol', () => {
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("the chat bidi set is exactly @shared/presence's (restated: this directory imports nothing outside)", () => {
+ // Over the whole BMP, outside the controls and the whitespace the sanitizer handles anyway: a
+ // character is stripped from chat if and only if presence calls it a bidi control.
+ 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 stripped = sanitizeChatText(`a${ch}b`) === 'ab'
+ if (stripped !== bidi) expect.fail(`U+${cp.toString(16)}: presence bidi=${bidi}, stripped from chat=${stripped}`)
+ checked++
+ }
+ expect(checked).toBeGreaterThan(60_000)
+ })
+ 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/shared/watch-link/isomorphism.guard.test.ts b/src/shared/watch-link/isomorphism.guard.test.ts
new file mode 100644
index 000000000..e1928074e
--- /dev/null
+++ b/src/shared/watch-link/isomorphism.guard.test.ts
@@ -0,0 +1,138 @@
+// 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', '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
index 51f9d7c15..88b2ac190 100644
--- a/src/shared/watch-link/keys.test.ts
+++ b/src/shared/watch-link/keys.test.ts
@@ -17,6 +17,12 @@ describe('bytes', () => {
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()
@@ -34,6 +40,9 @@ describe('deriveWatchLinkKeys', () => {
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)
@@ -61,4 +70,13 @@ describe('link format', () => {
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/link.ts b/src/shared/watch-link/link.ts
index c841392e7..7c70db6d8 100644
--- a/src/shared/watch-link/link.ts
+++ b/src/shared/watch-link/link.ts
@@ -7,7 +7,19 @@ 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)}`
}
diff --git a/src/shared/watch-link/protocol.ts b/src/shared/watch-link/protocol.ts
index 7f4b6cf50..1875b659a 100644
--- a/src/shared/watch-link/protocol.ts
+++ b/src/shared/watch-link/protocol.ts
@@ -53,15 +53,47 @@ export interface WatchChatMessage {
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
+/** 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): string | null {
if (typeof raw !== 'string') return null
- const s = raw.replace(/[\r\n\t]+/g, ' ').replace(CONTROLS, '').replace(/\s+/g, ' ').trim().slice(0, max).trim()
+ // 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(/\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)
diff --git a/src/shared/watch-link/wire.ts b/src/shared/watch-link/wire.ts
index 95aaa4ebf..97aabcabf 100644
--- a/src/shared/watch-link/wire.ts
+++ b/src/shared/watch-link/wire.ts
@@ -21,11 +21,17 @@ 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
-export function sealBox(plain: Uint8Array, key: Uint8Array, nonce: Uint8Array = nacl.randomBytes(nacl.box.nonceLength)): Uint8Array {
+/** 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))
}