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): seal a Control password to the connection; no invisible characters in names

review431e991d4e85
diff --git a/src/core/watch-link/client.test.ts b/src/core/watch-link/client.test.ts
index 40129499b..2f7711fd1 100644
--- a/src/core/watch-link/client.test.ts
+++ b/src/core/watch-link/client.test.ts
@@ -14,6 +14,8 @@ import { encodePtyData } from '../../shared/rpc'
import { connectWatchClient, TRUST_CONFIRM_JSON, type WatchSocket } from '../../shared/watch-link/client'
import { deriveWatchLinkKeys, type WatchLinkKeys } from '../../shared/watch-link/keys'
import { INPUT_MAX } from '../../shared/watch-link/protocol'
+import { openUnlock } from '../../shared/watch-link/unlock-seal'
+import { bytesToB64 } from '../../shared/watch-link/bytes'
function hostWith(opts: { keys?: WatchLinkKeys; autoApprove?: boolean } = {}) {
const keys = opts.keys ?? deriveWatchLinkKeys(nacl.randomBytes(32))
@@ -192,6 +194,32 @@ describe('connectWatchClient against the real relay socket', () => {
expect(h.tunnel).toHaveLength(before.tunnel + 1)
})
+ // Finding L3: once a meta on this connection offered an unlock key, the password is sealed to it and
+ // never sent in the clear on this connection again.
+ it('seals an unlock to the key the connection offered, and from then on never sends one in the clear', async () => {
+ const h = hostWith()
+ const c = connectWatchClient({ socket: h.peerT, keys: h.keys, events: events().ev })
+ await vi.waitFor(() => expect(h.tunnel).toContain(TRUST_CONFIRM_JSON))
+ h.confirm()
+ // A key that is not one is ignored: still in the clear (what a host from before sealing gets).
+ h.host.sendTunnelText(JSON.stringify({ t: 'ev', channel: 'watch:meta', args: [{ v: 1, unlockKey: 'AAAA' }] }))
+ expect(c.unlock('Mert', 'correct-horse-77')).toBe(true)
+ expect(h.tunnel.at(-1)).toBe('{"t":"cast","method":"watch:unlock","args":[{"name":"Mert","password":"correct-horse-77"}]}')
+ const conn = nacl.box.keyPair()
+ h.host.sendTunnelText(JSON.stringify({ t: 'ev', channel: 'watch:meta', args: [{ v: 1, unlockKey: bytesToB64(conn.publicKey) }] }))
+ expect(c.unlock('Mert', 'correct-horse-77')).toBe(true)
+ const sealed = h.tunnel.at(-1)!
+ expect(sealed).not.toContain('correct-horse-77')
+ const arg = (JSON.parse(sealed) as { method: string; args: unknown[] })
+ expect(arg.method).toBe('watch:unlock')
+ expect(openUnlock(arg.args[0], conn.secretKey)).toEqual({ name: 'Mert', password: 'correct-horse-77' })
+ // A later meta without one (a rejoin's) does not bring the clear text back.
+ h.host.sendTunnelText(JSON.stringify({ t: 'ev', channel: 'watch:meta', args: [{ v: 1 }] }))
+ expect(c.unlock('Mert', 'correct-horse-77')).toBe(true)
+ expect(h.tunnel.at(-1)).not.toContain('correct-horse-77')
+ expect(openUnlock(JSON.parse(h.tunnel.at(-1)!).args[0], conn.secretKey)).toEqual({ name: 'Mert', password: 'correct-horse-77' })
+ })
+
it('keeps both directions flowing past seq 255', async () => {
// A strictly increasing counter stays increasing under most encodings, so a short exchange
// cannot tell the relay's little-endian seq from a byte-swapped copy. Past one byte it can:
diff --git a/src/core/watch-link/wire.test.ts b/src/core/watch-link/wire.test.ts
index 26a9fa8a6..5ea8297b6 100644
--- a/src/core/watch-link/wire.test.ts
+++ b/src/core/watch-link/wire.test.ts
@@ -134,9 +134,11 @@ describe('protocol', () => {
// 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)", () => {
+ it("chat strips every @shared/presence bidi control (restated: this directory imports nothing outside), and from text exactly the invisible format characters but the two joiners", () => {
// Over the whole BMP, outside the controls and the whitespace the sanitizer handles anyway: a
- // character is stripped from chat if and only if presence calls it a bidi control.
+ // character is stripped from chat TEXT if and only if it is a format character (Cf) other than
+ // ZWNJ / ZWJ — and every one presence calls a bidi control is among them.
+ const cf = /^\p{Cf}$/u
let checked = 0
for (let cp = 0; cp <= 0xffff; cp++) {
if (cp >= 0xd800 && cp <= 0xdfff) continue
@@ -145,12 +147,37 @@ describe('protocol', () => {
if (/\s/.test(ch)) continue
BIDI_CONTROL_CHARS.lastIndex = 0
const bidi = BIDI_CONTROL_CHARS.test(ch)
+ const invisible = cf.test(ch) && cp !== 0x200c && cp !== 0x200d
const stripped = sanitizeChatText(`a${ch}b`) === 'ab'
- if (stripped !== bidi) expect.fail(`U+${cp.toString(16)}: presence bidi=${bidi}, stripped from chat=${stripped}`)
+ if (bidi && !stripped) expect.fail(`U+${cp.toString(16)}: a presence bidi control kept in chat`)
+ if (stripped !== invisible) expect.fail(`U+${cp.toString(16)}: invisible=${invisible}, stripped from chat=${stripped}`)
+ if (bidi && sanitizeChatName(`a${ch}b`) !== 'ab') expect.fail(`U+${cp.toString(16)}: a presence bidi control kept in a name`)
checked++
}
expect(checked).toBeGreaterThan(60_000)
})
+ it('a NAME keeps no invisible character: every format character, and the blank letters, go', () => {
+ // Finding L4: "Sharer" and "Sharer" + an invisible character were two names drawn alike.
+ for (const ch of ['\u200b', '\u200c', '\u200d', '\u2060', '\u00ad', '\ufeff', '\u034f', '\u115f', '\u1160', '\u2800', '\u3164', '\uffa0', '\u{e0041}', '\u{e007f}']) {
+ expect(sanitizeChatName(`Sha${ch}rer${ch}`)).toBe('Sharer')
+ }
+ // Over the whole BMP: a name loses every format character.
+ for (let cp = 0; cp <= 0xffff; cp++) {
+ if (cp >= 0xd800 && cp <= 0xdfff) continue
+ const ch = String.fromCharCode(cp)
+ if (/^\p{Cf}$/u.test(ch) && sanitizeChatName(`a${ch}b`) !== 'ab') expect.fail(`U+${cp.toString(16)} kept in a name`)
+ }
+ // A name made only of them is no name.
+ expect(sanitizeChatName('\u200b\u3164\u2800')).toBeNull()
+ // Visible letters and emoji stay (an emoji sequence loses its joiner in a NAME: a name is a claim).
+ expect(sanitizeChatName('Ayşe')).toBe('Ayşe')
+ expect(sanitizeChatName('Ada \u{1F469}\u200D\u{1F4BB}')).toBe('Ada \u{1F469}\u{1F4BB}')
+ })
+ it('chat TEXT keeps the zero-width joiner (emoji sequences) and the non-joiner (Persian, the Indic scripts), and loses the other invisibles', () => {
+ expect(sanitizeChatText('hi \u{1F469}\u200D\u{1F4BB}')).toBe('hi \u{1F469}\u200D\u{1F4BB}')
+ expect(sanitizeChatText('\u0645\u06cc\u200c\u062e\u0648\u0627\u0645')).toBe('\u0645\u06cc\u200c\u062e\u0648\u0627\u0645')
+ expect(sanitizeChatText('pass\u200bword\u00ad \u2060here\u{e0041}')).toBe('password here')
+ })
it('caps by code point, never leaving half a surrogate pair', () => {
// 499 units, then an astral character (2 units): it does not fit in 500, so it is left out WHOLE.
const text = sanitizeChatText('x'.repeat(CHAT_TEXT_MAX - 1) + '\u{1F600}tail')!
diff --git a/src/shared/watch-link/client.ts b/src/shared/watch-link/client.ts
index 6091bc117..360c6bcfe 100644
--- a/src/shared/watch-link/client.ts
+++ b/src/shared/watch-link/client.ts
@@ -2,14 +2,16 @@
// sealed frames, keepalive) plus the trust gate's client obligation (send our own trust:confirm,
// open only once the host's arrives). After the handshake it sends only its own trust:confirm,
// keepalives, and the viewer's casts: read-back (`requestHistory`), chat (`sendChat`) and, on a
-// Control link, unlock / input / release. Whether a cast is accepted is the link host's decision, and an obligation on it: chat only
+// Control link, unlock (sealed to the connection's unlock key when its host offers one,
+// ./unlock-seal.ts) / input / release. Whether a cast is accepted is the link host's decision, and an obligation on it: chat only
// on a Commenter or Control link, input only from a viewer that unlocked with the link's password.
// Nothing on this side enforces that; `sendInput`'s size cap only keeps an oversized cast off the wire.
import nacl from 'tweetnacl'
import { b64ToBytes, bytesToB64, concatBytes, utf8 } from './bytes'
import { hkdfSha256 } from './hkdf'
import type { WatchLinkKeys } from './keys'
-import { INPUT_MAX, WATCH_CHAT_CAST, WATCH_HISTORY_CAST, WATCH_INPUT_CAST, WATCH_RELEASE_CAST, WATCH_UNLOCK_CAST, readHistoryRequest } from './protocol'
+import { INPUT_MAX, WATCH_CHAT_CAST, WATCH_EVENT, WATCH_HISTORY_CAST, WATCH_INPUT_CAST, WATCH_RELEASE_CAST, WATCH_UNLOCK_CAST, readHistoryRequest } from './protocol'
+import { readUnlockKey, sealUnlock } from './unlock-seal'
import {
NONCE_BYTES, RELAY_SESSION_INFO, ROLE_CLIENT, ROLE_HOST, TAG_RPC, TAG_TUNNEL_BIN, TAG_TUNNEL_TEXT,
decodePtyFrame, openBox, parseTunnelJson, readHeader, sealBox, withHeader
@@ -49,7 +51,10 @@ export interface WatchClient {
* would refuse is refused here (false, nothing sent). */
requestHistory(before?: number): boolean
sendChat(name: string, text: string): boolean
- /** Ask to type, with the link's password. The answer is a `watch:control` event, not a return value. */
+ /** Ask to type, with the link's password. The answer is a `watch:control` event, not a return value.
+ * Sealed to this connection's unlock key once a meta on it offered one (`WatchMeta.unlockKey`), and
+ * from then on never sent in the clear on this connection; in the clear only to a host that offered
+ * none (one from before sealing). */
unlock(name: string, password: string): boolean
/** Typed bytes, sent as given. Refused here (false, nothing sent) when empty, not a string, or longer
* than `INPUT_MAX` UTF-16 units. */
@@ -108,6 +113,9 @@ export function connectWatchClient(opts: {
let opened = false
let warnedUnknown = false
let keepalive: unknown = null
+ /** The key this connection's host offered to seal an unlock to: the latest one a meta carried. Once
+ * set it is never cleared, so an unlock on this connection is never sent in the clear again. */
+ let unlockKey: Uint8Array | null = null
function sendSealed(tag: number, body: Uint8Array): boolean {
if (!sessionKey || state === 'closed') return false
@@ -198,6 +206,10 @@ export function connectWatchClient(opts: {
} else if (m.t === 'cast' && m.method === 'trust:denied') {
events.onDenied(typeof m.args[0] === 'string' ? m.args[0] : 'denied')
} else if (m.t === 'ev' && opened) {
+ if (m.channel === WATCH_EVENT.meta) {
+ const key = readUnlockKey((m.args[0] as { unlockKey?: unknown } | null | undefined)?.unlockKey)
+ if (key) unlockKey = key
+ }
events.onEvent(m.channel, m.args)
}
return
@@ -226,7 +238,18 @@ export function connectWatchClient(opts: {
return cast(WATCH_HISTORY_CAST, [arg])
},
sendChat: (name, text) => cast(WATCH_CHAT_CAST, [{ name, text }]),
- unlock: (name, password) => cast(WATCH_UNLOCK_CAST, [{ name, password }]),
+ unlock(name, password) {
+ if (!unlockKey) return cast(WATCH_UNLOCK_CAST, [{ name, password }])
+ let arg: ReturnType<typeof sealUnlock>
+ try {
+ arg = sealUnlock(name, password, unlockKey)
+ } catch {
+ // JSON.stringify cannot fail on two strings, and the key is 32 bytes; nothing goes out in the
+ // clear if it somehow does.
+ return false
+ }
+ return cast(WATCH_UNLOCK_CAST, [arg])
+ },
sendInput(data) {
if (typeof data !== 'string' || data.length === 0 || data.length > INPUT_MAX) return false
return cast(WATCH_INPUT_CAST, [{ data }])
diff --git a/src/shared/watch-link/isomorphism.guard.test.ts b/src/shared/watch-link/isomorphism.guard.test.ts
index e1928074e..1bd612c84 100644
--- a/src/shared/watch-link/isomorphism.guard.test.ts
+++ b/src/shared/watch-link/isomorphism.guard.test.ts
@@ -101,7 +101,7 @@ function violations(sources: Record<string, string>): string[] {
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'])
+ expect(vendored()).toEqual(['bytes.ts', 'client.ts', 'hkdf.ts', 'keys.ts', 'link.ts', 'protocol.ts', 'unlock-seal.ts', 'wire.ts'])
})
it('no source imports outside the directory, and every type-only import says `type`', () => {
diff --git a/src/shared/watch-link/protocol.control.test.ts b/src/shared/watch-link/protocol.control.test.ts
index 59aabfacc..75a73d69c 100644
--- a/src/shared/watch-link/protocol.control.test.ts
+++ b/src/shared/watch-link/protocol.control.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
-import { readControlEvent, readTypingNames, isWatchEndReason, TYPING_NAMES_MAX } from './protocol'
+import { CONTROL_LOCK_MAX_MS, readControlEvent, readTypingNames, isWatchEndReason, TYPING_NAMES_MAX } from './protocol'
describe('control protocol readers', () => {
it('accepts only known states and reasons', () => {
@@ -15,6 +15,17 @@ describe('control protocol readers', () => {
expect(readTypingNames({ names: ['a\u202eb', 'a\u202eb', 7, ' '] })).toEqual(['ab'])
expect(readTypingNames('x')).toEqual([])
})
+ it('keeps how long a lock lasts only beside `locked`, and only a duration a host can mean', () => {
+ expect(readControlEvent({ state: 'locked', reason: 'locked', lockedForMs: 900_000 })).toEqual({ state: 'locked', reason: 'locked', lockedForMs: 900_000 })
+ expect(readControlEvent({ state: 'locked', lockedForMs: 0 })).toEqual({ state: 'locked', lockedForMs: 0 })
+ expect(readControlEvent({ state: 'locked', lockedForMs: CONTROL_LOCK_MAX_MS })).toEqual({ state: 'locked', lockedForMs: CONTROL_LOCK_MAX_MS })
+ // Past the cap, negative, fractional, not a number: "until the sharer lifts it" — never a promise.
+ for (const lockedForMs of [CONTROL_LOCK_MAX_MS + 1, -1, 1.5, '900000', Number.NaN, Infinity, null]) {
+ expect(readControlEvent({ state: 'locked', lockedForMs })).toEqual({ state: 'locked' })
+ }
+ // Beside any other state it means nothing.
+ expect(readControlEvent({ state: 'available', lockedForMs: 1000 })).toEqual({ state: 'available' })
+ })
it('knows the new end reason', () => {
expect(isWatchEndReason('attempts')).toBe(true)
})
diff --git a/src/shared/watch-link/protocol.ts b/src/shared/watch-link/protocol.ts
index 9b3597b01..869b8d464 100644
--- a/src/shared/watch-link/protocol.ts
+++ b/src/shared/watch-link/protocol.ts
@@ -20,7 +20,17 @@ export const WATCH_EVENT = {
} as const
/** A viewer's chat line (Commenter and Control links). */
export const WATCH_CHAT_CAST = 'watch:chat'
-/** Control links only: `{ name, password }`. Answered to that viewer alone with `watch:control`. */
+/**
+ * Control links only. Answered to that viewer alone with `watch:control`. Two forms:
+ * - SEALED, `{ sealed: { key, nonce, box } }` (./unlock-seal.ts): `{ name, password }` in a
+ * `nacl.box` from a fresh key pair of the page's to the key THIS connection's meta offered
+ * (`WatchMeta.unlockKey`). Every holder of a link can derive the tunnel's keys (both are derived
+ * from the link's secret), so a recording of the relay traffic plus the link would otherwise read a
+ * password a controller typed; the per-connection key pair is not derived from anything.
+ * - PLAIN, `{ name, password }`: what a page from before sealing sends, and what a page sends to a host
+ * that offered no key (a host from before sealing). A host refuses it (as a malformed attempt) on a
+ * connection that has already sent a sealed one.
+ */
export const WATCH_UNLOCK_CAST = 'watch:unlock'
/**
* Control links only, from a controlling viewer: `{ data }`, at most `INPUT_MAX` UTF-16 units.
@@ -90,6 +100,9 @@ export interface WatchMeta {
/** Present (true) when the watched node is an agent whose conversation `watch:history` can read
* back. Absent: a plain terminal, or a host older than read-back. */
history?: true
+ /** A Control link only: the base64 X25519 public key THIS connection seals its unlock to
+ * (`WATCH_UNLOCK_CAST`). The same for the connection's life; absent from a host older than sealing. */
+ unlockKey?: string
}
/** `controlling`: this viewer may type. `available`: a Control link this viewer may unlock.
@@ -105,7 +118,13 @@ const CONTROL_REASONS: readonly WatchControlReason[] = ['wrong', 'locked', 'off'
export interface WatchControlEvent {
state: WatchControlState
reason?: WatchControlReason
+ /** With `locked` only: how long until the lock lifts by itself, in ms from when the host sent it.
+ * Absent: it does not (a lock from a host older than timed locks); only the sharer can lift it. The
+ * sharer can always lift it sooner. */
+ lockedForMs?: number
}
+/** The longest a wrong-password lock lasts by itself (the host doubles it from 15 minutes per lock). */
+export const CONTROL_LOCK_MAX_MS = 24 * 60 * 60_000
export interface WatchTypingEvent {
/** Self-chosen names: claims, shown as such. */
names: string[]
@@ -122,10 +141,18 @@ export const TYPING_NAMES_MAX = 10
* is dropped, never the state with it. */
export function readControlEvent(x: unknown): WatchControlEvent | null {
if (!x || typeof x !== 'object') return null
- const { state, reason } = x as Record<string, unknown>
+ const { state, reason, lockedForMs } = x as Record<string, unknown>
if (!(CONTROL_STATES as readonly unknown[]).includes(state)) return null
const out: WatchControlEvent = { state: state as WatchControlState }
if ((CONTROL_REASONS as readonly unknown[]).includes(reason)) out.reason = reason as WatchControlReason
+ // Only beside `locked`, and only a duration a host can mean: anything else reads as "until the
+ // sharer lifts it", never as a time the page would promise.
+ if (
+ state === 'locked' && typeof lockedForMs === 'number' && Number.isInteger(lockedForMs) &&
+ lockedForMs >= 0 && lockedForMs <= CONTROL_LOCK_MAX_MS
+ ) {
+ out.lockedForMs = lockedForMs
+ }
return out
}
/** A `watch:typing` payload's names: each one a clean chat name, deduplicated in order, at most
@@ -176,6 +203,17 @@ const CONTROLS = /[\u0000-\u001f\u007f-\u009f]/g
// directory imports nothing from outside itself (it is vendored byte for byte into nodeterm-web), so
// the class is restated here and src/core/watch-link/wire.test.ts pins the two equal.
const BIDI_CONTROLS = /[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g
+// Every other format character (Unicode category Cf) is invisible too: the zero-width space and
+// joiners, the word joiner, the soft hyphen, the tag characters. In a NAME any of them makes a second
+// name that looks exactly like the first — "Sharer" and "Sharer" + U+200B — in the chat, in "X is
+// typing…" and in the owner's "someone using the name …" notice. So a name keeps none of them, nor the
+// letters that draw as blank space (the Hangul fillers, the Braille blank, the combining grapheme
+// joiner, which is invisible but a mark rather than Cf).
+const NAME_INVISIBLES = /[\p{Cf}\u034f\u115f\u1160\u2800\u3164\uffa0]/gu
+// In chat TEXT the same characters go, but for the two joiners real writing needs: the zero-width
+// joiner (U+200D) holds emoji sequences together, and the zero-width non-joiner (U+200C) is how
+// Persian and the Indic scripts are spelled. Text is not an identity claim; a name is.
+const TEXT_INVISIBLES = /(?![\u200c\u200d])\p{Cf}/gu
/** How much of a raw value the cleaning chain may look at, as a multiple of the cap: a cast is
* attacker-sized, and the regex chain must not run over megabytes to keep 500 units of it. Generous
* enough that whitespace and controls collapsing away never empty an honest message. */
@@ -193,7 +231,7 @@ function capUnits(s: string, max: number): string {
return out
}
-function clean(raw: unknown, max: number): string | null {
+function clean(raw: unknown, max: number, invisibles: RegExp = TEXT_INVISIBLES): string | null {
if (typeof raw !== 'string') return null
// Bound the input BEFORE the regex chain (by code point), then cap the cleaned text the same way.
const bounded = capUnits(raw, max * RAW_FACTOR)
@@ -201,13 +239,16 @@ function clean(raw: unknown, max: number): string | null {
.replace(/[\r\n\t]+/g, ' ')
.replace(CONTROLS, '')
.replace(BIDI_CONTROLS, '')
+ .replace(invisibles, '')
.replace(/\s+/g, ' ')
.trim()
const s = capUnits(cleaned, max).trim()
return s ? s : null
}
export const sanitizeChatText = (raw: unknown): string | null => clean(raw, CHAT_TEXT_MAX)
-export const sanitizeChatName = (raw: unknown): string | null => clean(raw, CHAT_NAME_MAX)
+/** A self-chosen name (chat, the typing line, an unlock): no invisible character at all, so two names
+ * that look alike ARE alike. */
+export const sanitizeChatName = (raw: unknown): string | null => clean(raw, CHAT_NAME_MAX, NAME_INVISIBLES)
// --- read-back (`watch:history`) --------------------------------------------------------------------
diff --git a/src/shared/watch-link/unlock-seal.test.ts b/src/shared/watch-link/unlock-seal.test.ts
new file mode 100644
index 000000000..7ab241e44
--- /dev/null
+++ b/src/shared/watch-link/unlock-seal.test.ts
@@ -0,0 +1,80 @@
+import { describe, expect, it } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+import nacl from 'tweetnacl'
+import { b64ToBytes, bytesToB64 } from './bytes'
+import { isSealedUnlock, openUnlock, readUnlockKey, sealUnlock, SEALED_BOX_B64_MAX } from './unlock-seal'
+
+const vectors = JSON.parse(readFileSync(join(__dirname, 'vectors.json'), 'utf8').replace(/\r\n/g, '\n'))
+const hex = (h: string): Uint8Array => Uint8Array.from(Buffer.from(h, 'hex'))
+
+describe('the sealed unlock', () => {
+ it('opens with the connection key it was sealed to, and with no other', () => {
+ const host = nacl.box.keyPair()
+ const arg = sealUnlock('Ada', 'hunter2hunter2', host.publicKey)
+ expect(isSealedUnlock(arg)).toBe(true)
+ expect(openUnlock(arg, host.secretKey)).toEqual({ name: 'Ada', password: 'hunter2hunter2' })
+ // Another connection's key (a link holder replaying a recording knows neither secret).
+ expect(openUnlock(arg, nacl.box.keyPair().secretKey)).toBeNull()
+ // Nothing of the password is in what crosses the wire.
+ expect(JSON.stringify(arg)).not.toContain('hunter2')
+ })
+
+ it('draws a fresh key pair and nonce every time: the same password never seals to the same bytes', () => {
+ const host = nacl.box.keyPair()
+ const a = sealUnlock('Ada', 'pw-pw-pw-pw', host.publicKey).sealed
+ const b = sealUnlock('Ada', 'pw-pw-pw-pw', host.publicKey).sealed
+ expect(a.key).not.toBe(b.key)
+ expect(a.nonce).not.toBe(b.nonce)
+ expect(a.box).not.toBe(b.box)
+ })
+
+ it('opens the vector nodeterm-web is tested against', () => {
+ expect(vectors.unlockSeals.length).toBeGreaterThan(0)
+ for (const v of vectors.unlockSeals) {
+ const secret = hex(v.hostSecretHex)
+ expect(bytesToB64(nacl.box.keyPair.fromSecretKey(secret).publicKey)).toBe(v.hostPublicB64)
+ expect(openUnlock({ sealed: v.sealed }, secret)).toEqual({ name: v.name, password: v.password })
+ }
+ })
+
+ it('refuses anything that is not a sealed unlock this key opens', () => {
+ const host = nacl.box.keyPair()
+ const { sealed } = sealUnlock('Ada', 'pw-pw-pw-pw', host.publicKey)
+ const bad: unknown[] = [
+ undefined, null, 'x', { name: 'Ada', password: 'pw' }, { sealed: null }, { sealed: 'x' },
+ { sealed: { ...sealed, key: 'AAAA' } },
+ { sealed: { ...sealed, nonce: bytesToB64(new Uint8Array(23)) } },
+ { sealed: { ...sealed, box: 'not base64!' } },
+ { sealed: { ...sealed, box: 7 } },
+ // One flipped bit of the box: the MAC fails.
+ { sealed: { ...sealed, box: bytesToB64(b64ToBytes(sealed.box)!.map((x, i) => (i === 0 ? x ^ 1 : x))) } },
+ { sealed: { ...sealed, box: 'A'.repeat(SEALED_BOX_B64_MAX + 4) } }
+ ]
+ for (const arg of bad) expect(openUnlock(arg, host.secretKey)).toBeNull()
+ })
+
+ it('refuses a box whose content is not a JSON object', () => {
+ const host = nacl.box.keyPair()
+ const page = nacl.box.keyPair()
+ const nonce = nacl.randomBytes(24)
+ for (const body of ['[1,2]', '"x"', 'not json', 'ÿþ']) {
+ const bytes = body === 'ÿþ' ? Uint8Array.of(0xff, 0xfe) : new TextEncoder().encode(body)
+ const box = nacl.box(bytes, nonce, host.publicKey, page.secretKey)
+ const arg = { sealed: { key: bytesToB64(page.publicKey), nonce: bytesToB64(nonce), box: bytesToB64(box) } }
+ expect(openUnlock(arg, host.secretKey)).toBeNull()
+ }
+ })
+
+ it('reads an offered key only as 32 bytes of strict base64', () => {
+ const k = nacl.box.keyPair().publicKey
+ expect(readUnlockKey(bytesToB64(k))).toEqual(k)
+ for (const x of [undefined, 7, '', bytesToB64(new Uint8Array(31)), bytesToB64(new Uint8Array(33)), `${bytesToB64(k)} `, 'A'.repeat(200)]) {
+ expect(readUnlockKey(x)).toBeNull()
+ }
+ })
+
+ it('throws (sends nothing) for a key that is not one', () => {
+ expect(() => sealUnlock('Ada', 'pw', new Uint8Array(31))).toThrow()
+ })
+})
diff --git a/src/shared/watch-link/unlock-seal.ts b/src/shared/watch-link/unlock-seal.ts
new file mode 100644
index 000000000..a2f741aa6
--- /dev/null
+++ b/src/shared/watch-link/unlock-seal.ts
@@ -0,0 +1,91 @@
+// A Control link's password, sealed to ONE connection (`WATCH_UNLOCK_CAST`'s sealed form).
+//
+// Why: the tunnel's keys are not secret from a link holder. Both the host's and the viewer's key pairs
+// are derived from the link's secret (./keys.ts), and the session key from those plus two nonces sent
+// in the clear, so anyone who holds the link AND a recording of the relay traffic can read every
+// connection of it — a password a controller typed included. Sealing the unlock to a key pair that is
+// derived from nothing closes that for the password: the host makes a fresh X25519 key pair for each
+// viewer connection and offers its public key in that connection's meta (`WatchMeta.unlockKey`), the
+// page seals `{ name, password }` with `nacl.box` from a fresh key pair of its own and sends that
+// pair's public key beside the box. Neither secret key ever leaves its end, so a recording opens
+// nothing.
+//
+// What it does not do: an ACTIVE attacker holding the link who sits on the relay can still answer the
+// page as the host (the host's key pair is derived from the link too) and offer its own key. And what a
+// controller TYPES after unlocking rides the tunnel as before: readable to a link holder with a
+// recording. docs/live-links.md, "Threat notes".
+//
+// ISOMORPHIC like the rest of this directory (vendored byte for byte into nodeterm-web).
+import nacl from 'tweetnacl'
+import { b64ToBytes, bytesToB64, utf8 } from './bytes'
+
+/** An X25519 public key, and the box's nonce (`nacl.box`). */
+export const UNLOCK_KEY_BYTES = 32
+export const UNLOCK_NONCE_BYTES = 24
+/** The longest box the host opens, in base64 characters: a name (32 units) and a password (128 code
+ * points) as JSON, with every character escaped, fit in well under half of it. */
+export const SEALED_BOX_B64_MAX = 4096
+
+export interface SealedUnlock {
+ /** The page's own one-time public key (base64). */
+ key: string
+ nonce: string
+ /** `nacl.box(JSON { name, password }, nonce, hostKey, pageSecret)`, base64. */
+ box: string
+}
+
+const exactly = (x: unknown, n: number): Uint8Array | null => {
+ if (typeof x !== 'string' || x.length > 64) return null
+ const b = b64ToBytes(x)
+ return b && b.length === n ? b : null
+}
+
+/** A meta's `unlockKey`: 32 bytes of strict base64, or null. */
+export function readUnlockKey(x: unknown): Uint8Array | null {
+ return exactly(x, UNLOCK_KEY_BYTES)
+}
+
+/** The sealed cast argument for `name` and `password`, to `hostKey`. A fresh key pair and nonce each
+ * time: the caller cannot supply either. */
+export function sealUnlock(name: string, password: string, hostKey: Uint8Array): { sealed: SealedUnlock } {
+ if (!(hostKey instanceof Uint8Array) || hostKey.length !== UNLOCK_KEY_BYTES) throw new Error('An unlock key is 32 bytes.')
+ const page = nacl.box.keyPair()
+ const nonce = nacl.randomBytes(UNLOCK_NONCE_BYTES)
+ const box = nacl.box(utf8(JSON.stringify({ name, password })), nonce, hostKey, page.secretKey)
+ page.secretKey.fill(0)
+ return { sealed: { key: bytesToB64(page.publicKey), nonce: bytesToB64(nonce), box: bytesToB64(box) } }
+}
+
+/**
+ * The host's side: `{ name, password }` as the page sent them (not yet sanitized or bounded — the
+ * caller's unlock reader does that), or null for anything that is not a sealed unlock this connection's
+ * key opens: a missing or malformed field, a box over `SEALED_BOX_B64_MAX`, one that fails to open,
+ * JSON that is not an object.
+ */
+export function openUnlock(arg: unknown, hostSecret: Uint8Array): { name: unknown; password: unknown } | null {
+ if (!arg || typeof arg !== 'object') return null
+ const sealed = (arg as { sealed?: unknown }).sealed
+ if (!sealed || typeof sealed !== 'object') return null
+ const s = sealed as Record<string, unknown>
+ const key = exactly(s.key, UNLOCK_KEY_BYTES)
+ const nonce = exactly(s.nonce, UNLOCK_NONCE_BYTES)
+ if (!key || !nonce || typeof s.box !== 'string' || s.box.length > SEALED_BOX_B64_MAX) return null
+ const box = b64ToBytes(s.box)
+ if (!box) return null
+ const plain = nacl.box.open(box, nonce, key, hostSecret)
+ if (!plain) return null
+ let body: unknown
+ try {
+ body = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(plain))
+ } catch {
+ return null
+ }
+ if (!body || typeof body !== 'object' || Array.isArray(body)) return null
+ const { name, password } = body as Record<string, unknown>
+ return { name, password }
+}
+
+/** Whether a cast argument is the sealed form (whether or not it opens). */
+export function isSealedUnlock(arg: unknown): boolean {
+ return !!arg && typeof arg === 'object' && 'sealed' in arg
+}
diff --git a/src/shared/watch-link/vectors.json b/src/shared/watch-link/vectors.json
index f1f8ff69d..e83fde395 100644
--- a/src/shared/watch-link/vectors.json
+++ b/src/shared/watch-link/vectors.json
@@ -36,7 +36,7 @@
"hex": "010002733168656c6c6f"
},
{
- "sessionId": "sess-é",
+ "sessionId": "sess-\u00e9",
"data": "a\u001b[31mb",
"hex": "010007736573732dc3a9611b5b33316d62"
}
@@ -56,5 +56,18 @@
"info": "nodeterm-relay-session-v2",
"sessionKeyHex": "b981020481a96beea9f8d84ad0821080833f37f1b8dd46bbbad8eb9350ac2543"
}
+ ],
+ "unlockSeals": [
+ {
+ "hostSecretHex": "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20",
+ "hostPublicB64": "B6N8vBQgk8i3VdwbEOhstCY3StFqqFPtC9/AsrhtHHw=",
+ "sealed": {
+ "key": "Pry2khSTRNxU5YFgz5C+2e6h3RToHI6R3lV699ev2RU=",
+ "nonce": "AAcOFRwjKjE4P0ZNVFtiaXB3foWMk5qh",
+ "box": "hjkePn1uutxgyUjg/Z9NkwrtBYrnFHizAtqhlZFy7p/89pgiQC5HOWorQLFSz+QCRzgeRYPz5U7yyp8gbd9H2/4hggDN097+2YfGiWQ="
+ },
+ "name": "Ay\u015fe \ud83d\udc69\u200d\ud83d\udcbb",
+ "password": "tr0ub4dor & \u201c3\u201d"
+ }
]
}
diff --git a/src/shared/watch-link/vectors.test.ts b/src/shared/watch-link/vectors.test.ts
index b9ceaf5b5..3693e7313 100644
--- a/src/shared/watch-link/vectors.test.ts
+++ b/src/shared/watch-link/vectors.test.ts
@@ -6,6 +6,7 @@ import { bytesToHex, concatBytes, utf8 } from './bytes'
import { hkdfSha256 } from './hkdf'
import { formatWatchLink } from './link'
import { encodePtyFrame, RELAY_SESSION_INFO } from './wire'
+import { openUnlock } from './unlock-seal'
// vectors.json is what nodeterm-web's copy is tested against. It is the fixture; this test proves
// the code still produces it. Regenerate ONLY for a deliberate protocol change (bump the version).
@@ -24,6 +25,11 @@ describe('watch-link vectors', () => {
expect(formatWatchLink(v.linkId, secret)).toBe(v.url)
}
for (const f of vectors.ptyFrames) expect(bytesToHex(encodePtyFrame(f.sessionId, f.data))).toBe(f.hex)
+ // A Control link's sealed unlock: what a page sealed (nodeterm-web opens the same vector).
+ expect(vectors.unlockSeals.length).toBeGreaterThan(0)
+ for (const v of vectors.unlockSeals) {
+ expect(openUnlock({ sealed: v.sealed }, hex(v.hostSecretHex))).toEqual({ name: v.name, password: v.password })
+ }
})
it('derives every session key: HKDF-SHA256(base, hostNonce ‖ clientNonce, info)', async () => {