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): the viewer client closes on a failed key derivation, and pins its trust frames

reviewcb6103aa9e11
diff --git a/src/core/watch-link/client.test.ts b/src/core/watch-link/client.test.ts
index be2248434..fc4f160d7 100644
--- a/src/core/watch-link/client.test.ts
+++ b/src/core/watch-link/client.test.ts
@@ -1,30 +1,74 @@
-// The viewer client runs against the REAL host-role relay socket, not a fake. That is what pins the
-// wire constants src/shared/watch-link/wire.ts restates (the seq header, TAG_*, ROLE_*, NONCE_BYTES):
-// they are module-private in relay-socket.ts, so a drift there shows up here as a handshake that
-// never completes or a frame the host never sees. It lives in core because it imports core modules
-// the web tsconfig project that vendors src/shared/watch-link cannot see.
+// The viewer client runs against the REAL host-role relay socket and the REAL trust gate, not fakes.
+// That is what pins the wire constants src/shared/watch-link/wire.ts restates (the seq header, TAG_*,
+// ROLE_*, NONCE_BYTES) and the trust frames client.ts builds: they are module-private in
+// relay-socket.ts / owned by relay-trust.ts, so a drift there shows up here as a handshake that never
+// completes, a frame the host never sees, or a gate that never opens. It lives in core because it
+// imports core modules the web tsconfig project that vendors src/shared/watch-link cannot see.
import { describe, it, expect, vi } from 'vitest'
import nacl from 'tweetnacl'
import { connectRelay } from '../relay/relay-socket'
import { transportPair } from '../relay/transport-pair'
import { publicKeyToB64 } from '../relay/e2ee'
+import { createTrustGate, deniedFrame, type TrustGate } from '../relay/relay-trust'
import { encodePtyData } from '../../shared/rpc'
-import { connectWatchClient, TRUST_CONFIRM_JSON } from '../../shared/watch-link/client'
-import { deriveWatchLinkKeys } from '../../shared/watch-link/keys'
+import { connectWatchClient, TRUST_CONFIRM_JSON, type WatchSocket } from '../../shared/watch-link/client'
+import { deriveWatchLinkKeys, type WatchLinkKeys } from '../../shared/watch-link/keys'
-function hostWith(keys = deriveWatchLinkKeys(nacl.randomBytes(32))) {
+function hostWith(opts: { keys?: WatchLinkKeys; autoApprove?: boolean } = {}) {
+ const keys = opts.keys ?? deriveWatchLinkKeys(nacl.randomBytes(32))
const { hostT, peerT } = transportPair()
const tunnel: string[] = []
let ready = false
+ let closed = 0
+ let gateOpened = false
+ let gate: TrustGate | null = null
const host = connectRelay({
url: 'wss://x', token: 't', role: 'host',
ourKeys: { publicKey: keys.host.publicKey, secretKey: keys.host.secretKey },
transport: hostT,
- onReady: () => { ready = true },
- onRpc: () => {}, onFrame: () => {}, onClose: () => {},
- onTunnel: (kind, payload) => { if (kind === 'text') tunnel.push(new TextDecoder().decode(payload)) }
+ onReady: () => {
+ ready = true
+ // The host's own gate, wired the way the relay hosts wire it: confirms travel only over the
+ // encrypted tunnel, in both directions.
+ gate = createTrustGate({
+ peerKeyB64: host.peerPublicKeyB64() ?? '',
+ sessionId: 'watch-test',
+ sas: () => host.sas(),
+ sendConfirm: (json) => { host.sendTunnelText(json) },
+ onOpen: () => { gateOpened = true },
+ autoApprove: opts.autoApprove
+ })
+ },
+ onRpc: () => {}, onFrame: () => {},
+ onClose: () => { closed++ },
+ onTunnel: (kind, payload) => {
+ if (kind !== 'text') return
+ const json = new TextDecoder().decode(payload)
+ tunnel.push(json)
+ gate?.onTunnelText(json)
+ }
})
- return { keys, host, hostT, peerT, tunnel, isReady: () => ready }
+ return {
+ keys, host, hostT, peerT, tunnel,
+ isReady: () => ready,
+ hostClosed: () => closed,
+ gateOpen: () => gateOpened,
+ /** The host's human (or its pin) confirms, through the real gate. */
+ confirm: () => {
+ if (!gate) throw new Error('the host is not ready, so it has no gate yet')
+ gate.confirmHere()
+ }
+ }
+}
+
+/** The client's socket with a count of the binary (sealed) frames it sent. */
+function counting(socket: WatchSocket) {
+ const sent = { text: 0, binary: 0 }
+ const wrapped: WatchSocket = {
+ ...socket,
+ send: (d) => { if (typeof d === 'string') sent.text++; else sent.binary++; socket.send(d) }
+ }
+ return { socket: wrapped, sent }
}
function events() {
@@ -50,9 +94,11 @@ describe('connectWatchClient against the real relay socket', () => {
await vi.waitFor(() => expect(h.tunnel).toContain(TRUST_CONFIRM_JSON))
expect(h.host.peerPublicKeyB64()).toBe(publicKeyToB64(h.keys.viewer.publicKey))
expect(c.isOpen()).toBe(false)
- h.host.sendTunnelText(TRUST_CONFIRM_JSON)
+ h.confirm()
expect(log.open).toBe(1)
expect(c.isOpen()).toBe(true)
+ // The client's confirm is one the host's real gate accepts: both halves in, the gate opens.
+ await vi.waitFor(() => expect(h.gateOpen()).toBe(true))
})
it('delivers ev frames and pty data only after it is open', async () => {
@@ -64,7 +110,7 @@ describe('connectWatchClient against the real relay socket', () => {
h.host.sendTunnelBinary(encodePtyData('s1', 'early'))
expect(log.events).toEqual([])
expect(log.pty).toEqual([])
- h.host.sendTunnelText(TRUST_CONFIRM_JSON)
+ h.confirm()
h.host.sendTunnelText(JSON.stringify({ t: 'ev', channel: 'watch:meta', args: [{ v: 1 }] }))
h.host.sendTunnelBinary(encodePtyData('s1', 'late'))
expect(log.events).toEqual([['watch:meta', [{ v: 1 }]]])
@@ -76,17 +122,20 @@ describe('connectWatchClient against the real relay socket', () => {
const { log, ev } = events()
connectWatchClient({ socket: h.peerT, keys: h.keys, events: ev })
await vi.waitFor(() => expect(h.tunnel).toContain(TRUST_CONFIRM_JSON))
- h.host.sendTunnelText(JSON.stringify({ t: 'cast', method: 'trust:denied', args: ['denied'] }))
- expect(log.denied).toEqual(['denied'])
+ h.host.sendTunnelText(deniedFrame('removed'))
+ expect(log.denied).toEqual(['removed'])
expect(log.open).toBe(0)
})
it('cannot talk to a host whose key is not the link one', async () => {
const real = deriveWatchLinkKeys(nacl.randomBytes(32))
- const impostor = hostWith(deriveWatchLinkKeys(nacl.randomBytes(32)))
- connectWatchClient({ socket: impostor.peerT, keys: real, events: events().ev })
- await new Promise((r) => setTimeout(r, 20))
+ const impostor = hostWith({ keys: deriveWatchLinkKeys(nacl.randomBytes(32)) })
+ const { socket, sent } = counting(impostor.peerT)
+ const c = connectWatchClient({ socket, keys: real, events: events().ev })
+ // The first sealed frame is the e2ee_auth box; the host has already judged it when send returns.
+ await vi.waitFor(() => expect(sent.binary).toBe(1))
expect(impostor.isReady()).toBe(false)
+ expect(c.isOpen()).toBe(false)
})
it('sends a chat cast only while open', async () => {
@@ -94,7 +143,7 @@ describe('connectWatchClient against the real relay socket', () => {
const c = connectWatchClient({ socket: h.peerT, keys: h.keys, events: events().ev })
expect(c.sendChat('Ada', 'hi')).toBe(false)
await vi.waitFor(() => expect(h.tunnel).toContain(TRUST_CONFIRM_JSON))
- h.host.sendTunnelText(TRUST_CONFIRM_JSON)
+ h.confirm()
expect(c.sendChat('Ada', 'hi')).toBe(true)
expect(h.tunnel.at(-1)).toBe(JSON.stringify({ t: 'cast', method: 'watch:chat', args: [{ name: 'Ada', text: 'hi' }] }))
})
@@ -107,7 +156,7 @@ describe('connectWatchClient against the real relay socket', () => {
const { log, ev } = events()
const c = connectWatchClient({ socket: h.peerT, keys: h.keys, events: ev })
await vi.waitFor(() => expect(h.tunnel).toContain(TRUST_CONFIRM_JSON))
- h.host.sendTunnelText(TRUST_CONFIRM_JSON)
+ h.confirm()
for (let i = 0; i < 300; i++) h.host.sendTunnelBinary(encodePtyData('s1', String(i)))
expect(log.pty).toHaveLength(300)
expect(log.pty.at(-1)).toEqual(['s1', '299'])
@@ -121,21 +170,21 @@ describe('connectWatchClient against the real relay socket', () => {
const { log, ev } = events()
const timer: { tick?: () => void; ms?: number } = {}
const stopped: unknown[] = []
- let sent = 0
+ const { socket, sent } = counting(h.peerT)
const c = connectWatchClient({
- socket: { ...h.peerT, send: (d) => { sent++; h.peerT.send(d) } }, keys: h.keys, events: ev,
+ socket, keys: h.keys, events: ev,
setInterval: (fn, ms) => { timer.tick = fn; timer.ms = ms; return 'handle' },
clearInterval: (handle) => { stopped.push(handle) }
})
await vi.waitFor(() => expect(h.tunnel).toContain(TRUST_CONFIRM_JSON))
- h.host.sendTunnelText(TRUST_CONFIRM_JSON)
+ h.confirm()
expect(timer.ms).toBe(25_000)
// A keepalive is a real sealed frame and spends a seq number; the host must still accept what
// follows it.
- const before = sent
+ const before = sent.binary
timer.tick?.()
timer.tick?.()
- expect(sent - before).toBe(2)
+ expect(sent.binary - before).toBe(2)
expect(c.sendChat('Ada', 'after keepalives')).toBe(true)
expect(h.tunnel.at(-1)).toBe(JSON.stringify({ t: 'cast', method: 'watch:chat', args: [{ name: 'Ada', text: 'after keepalives' }] }))
// The far side hangs up: the client reports it once, stops its keepalive, and stops sending.
@@ -156,10 +205,67 @@ describe('connectWatchClient against the real relay socket', () => {
clearInterval: (handle) => { stopped.push(handle) }
})
await vi.waitFor(() => expect(h.tunnel).toContain(TRUST_CONFIRM_JSON))
- h.host.sendTunnelText(TRUST_CONFIRM_JSON)
+ h.confirm()
c.close()
+ expect(h.hostClosed()).toBe(1)
expect(log.closed).toBe(0)
expect(stopped).toEqual(['handle'])
expect(c.isOpen()).toBe(false)
})
+
+ it('closes, and says so once, when the session key cannot be derived', async () => {
+ // WebCrypto refusing (a page served without a secure context has no crypto.subtle at all) used
+ // to be an unhandled rejection that left the client in 'deriving' forever, with no event.
+ const spy = vi.spyOn(globalThis.crypto.subtle, 'importKey').mockRejectedValueOnce(new Error('no HKDF here'))
+ try {
+ const h = hostWith()
+ const { log, ev } = events()
+ const c = connectWatchClient({ socket: h.peerT, keys: h.keys, events: ev })
+ await vi.waitFor(() => expect(log.closed).toBe(1))
+ expect(h.hostClosed()).toBe(1)
+ expect(h.isReady()).toBe(false)
+ expect(c.isOpen()).toBe(false)
+ await new Promise((r) => setTimeout(r, 0))
+ expect(log.closed).toBe(1)
+ } finally {
+ spy.mockRestore()
+ }
+ })
+
+ it('opens only after its own confirm went out, even when the host confirms inside onReady', async () => {
+ // A pinned host confirms synchronously the moment it is ready, before the client's own confirm
+ // (deferred past the host's send) has left. Opening then would open a session whose host gate
+ // has not seen the viewer's half.
+ const h = hostWith({ autoApprove: true })
+ let confirmOutAtOpen: boolean | null = null
+ const { ev } = events()
+ connectWatchClient({
+ socket: h.peerT, keys: h.keys,
+ events: { ...ev, onOpen: () => { confirmOutAtOpen = h.tunnel.includes(TRUST_CONFIRM_JSON) } }
+ })
+ await vi.waitFor(() => expect(confirmOutAtOpen).not.toBeNull())
+ expect(confirmOutAtOpen).toBe(true)
+ await vi.waitFor(() => expect(h.gateOpen()).toBe(true))
+ })
+
+ it('warns once, and drops, a socket message that is neither text nor bytes', async () => {
+ // A browser WebSocket left at its default binaryType delivers Blobs; the adapter owes bytes.
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ try {
+ const h = hostWith()
+ const { log, ev } = events()
+ const c = connectWatchClient({ socket: h.peerT, keys: h.keys, events: ev })
+ await vi.waitFor(() => expect(h.tunnel).toContain(TRUST_CONFIRM_JSON))
+ h.confirm()
+ const deliver = h.hostT.send as (d: unknown) => void
+ deliver(new Blob(['x']))
+ deliver({ not: 'bytes' })
+ expect(warn).toHaveBeenCalledTimes(1)
+ expect(String(warn.mock.calls[0][0])).toContain('arraybuffer')
+ expect(c.isOpen()).toBe(true)
+ expect(log.closed).toBe(0)
+ } finally {
+ warn.mockRestore()
+ }
+ })
})
diff --git a/src/core/watch-link/wire.test.ts b/src/core/watch-link/wire.test.ts
index 6d7c89a7b..493284ee4 100644
--- a/src/core/watch-link/wire.test.ts
+++ b/src/core/watch-link/wire.test.ts
@@ -1,5 +1,7 @@
import { describe, it, expect } from 'vitest'
import { hkdfSync } from 'node:crypto'
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
import nacl from 'tweetnacl'
import { encodePtyData, encodeArgs, parseRpcMessage } from '../../shared/rpc'
import { decrypt, deriveSessionKey, encrypt, randomSessionNonce } from '../relay/e2ee'
@@ -20,6 +22,15 @@ describe('the wire rules match the relay they were copied from', () => {
const base = nacl.randomBytes(32), hn = randomSessionNonce(), cn = randomSessionNonce()
expect(await hkdfSha256(base, concatBytes(hn, cn), utf8(RELAY_SESSION_INFO), 32)).toEqual(deriveSessionKey(base, hn, cn))
})
+ it("the session-key vectors nodeterm-web tests against are the relay's deriveSessionKey", () => {
+ const vectors = JSON.parse(readFileSync(join(__dirname, '../../shared/watch-link/vectors.json'), 'utf8').replace(/\r\n/g, '\n'))
+ const hex = (h: string): Uint8Array => Uint8Array.from(Buffer.from(h, 'hex'))
+ expect(vectors.sessionKeys.length).toBeGreaterThan(0)
+ for (const v of vectors.sessionKeys) {
+ const key = deriveSessionKey(hex(v.baseKeyHex), hex(v.hostNonceHex), hex(v.clientNonceHex))
+ expect(Buffer.from(key).toString('hex')).toBe(v.sessionKeyHex)
+ }
+ })
it("the session nonce is as long as e2ee's randomSessionNonce", () => {
expect(randomSessionNonce()).toHaveLength(NONCE_BYTES)
})
diff --git a/src/shared/watch-link/client.ts b/src/shared/watch-link/client.ts
index 8133bf30b..fe4c57771 100644
--- a/src/shared/watch-link/client.ts
+++ b/src/shared/watch-link/client.ts
@@ -1,7 +1,9 @@
// The browser half of a live link: the CLIENT role of src/core/relay/relay-socket.ts (handshake,
// sealed frames, keepalive) plus the trust gate's client obligation (send our own trust:confirm,
-// open only once the host's arrives). Nothing here can write to the terminal: the only message it
-// can send after the handshake is a chat cast, which the host accepts for Commenter links only.
+// open only once the host's arrives). Nothing here writes to the terminal: after the handshake it
+// sends only its own trust:confirm, keepalives, and the viewer's chat casts (`sendChat`). Whether a
+// chat cast is accepted is the link host's decision, and an obligation on it: the link host (Task 11)
+// accepts one only on a Commenter link. Nothing on this side enforces that.
import nacl from 'tweetnacl'
import { b64ToBytes, bytesToB64, concatBytes, utf8 } from './bytes'
import { hkdfSha256 } from './hkdf'
@@ -12,6 +14,16 @@ import {
decodePtyFrame, openBox, parseTunnelJson, readHeader, sealBox, withHeader
} from './wire'
+/**
+ * What a transport adapter owes the client (a core `RelayTransport` already satisfies it):
+ * - Text frames arrive as strings, binary frames as `Uint8Array` or `ArrayBuffer`. A browser
+ * WebSocket must be given `binaryType = 'arraybuffer'`: its default delivers Blobs, which are
+ * not accepted (the client warns once and drops anything that is neither text nor bytes).
+ * - `send` is callable immediately: the client sends `e2ee_hello` synchronously from
+ * `connectWatchClient`. A browser WebSocket still CONNECTING throws on send, so the adapter
+ * queues until open, as core's `openWebSocketTransport` does.
+ * - `onClose` fires exactly once, on a close OR an error.
+ */
export interface WatchSocket {
send(data: string | Uint8Array): void
close(): void
@@ -25,6 +37,11 @@ export interface WatchClientEvents {
onDenied(reason: string): void
onClose(): void
}
+/**
+ * The CALLER owns the handshake deadline. A host that is offline never sends `e2ee_ready`, and a
+ * host that does not hold the link's key never authenticates, so without a timeout of the caller's
+ * own the client never reaches a terminal event: no `onOpen`, `onDenied` or `onClose`.
+ */
export interface WatchClient {
sendChat(name: string, text: string): boolean
close(): void
@@ -49,6 +66,7 @@ function json(raw: string): Record<string, unknown> | null {
}
}
+/** See `WatchSocket` for what the socket owes, and `WatchClient` for the handshake deadline. */
export function connectWatchClient(opts: {
socket: WatchSocket
keys: WatchLinkKeys
@@ -57,7 +75,15 @@ export function connectWatchClient(opts: {
clearInterval?: (h: unknown) => void
}): WatchClient {
const { socket, keys, events } = opts
- const every = opts.setInterval ?? ((fn: () => void, ms: number) => setInterval(fn, ms))
+ const every =
+ opts.setInterval ??
+ ((fn: () => void, ms: number) => {
+ const h: unknown = setInterval(fn, ms)
+ // Node only: a keepalive must not hold the process open. A browser's handle is a number.
+ const timer = h as { unref?: () => void } | null
+ timer?.unref?.()
+ return h
+ })
const stopEvery = opts.clearInterval ?? ((h: unknown) => clearInterval(h as ReturnType<typeof setInterval>))
const ourNonce = nacl.randomBytes(NONCE_BYTES)
const baseKey = nacl.box.before(keys.host.publicKey, keys.viewer.secretKey)
@@ -66,7 +92,9 @@ export function connectWatchClient(opts: {
let sendSeq = 0
let recvSeq = -1
let hostConfirmed = false
+ let confirmSent = false
let opened = false
+ let warnedUnknown = false
let keepalive: unknown = null
function sendSealed(tag: number, body: Uint8Array): boolean {
@@ -75,7 +103,7 @@ export function connectWatchClient(opts: {
return true
}
function maybeOpen(): void {
- if (opened || !hostConfirmed || state !== 'ready') return
+ if (opened || !hostConfirmed || !confirmSent || state !== 'ready') return
opened = true
events.onOpen()
}
@@ -92,7 +120,19 @@ export function connectWatchClient(opts: {
const hostNonce = b64ToBytes(m.nonceB64)
if (!hostNonce || hostNonce.length !== NONCE_BYTES) return
state = 'deriving'
- const key = await hkdfSha256(baseKey, concatBytes(hostNonce, ourNonce), utf8(RELAY_SESSION_INFO), 32)
+ let key: Uint8Array
+ try {
+ key = await hkdfSha256(baseKey, concatBytes(hostNonce, ourNonce), utf8(RELAY_SESSION_INFO), 32)
+ } catch {
+ // No WebCrypto HKDF (a page without a secure context has no crypto.subtle). Without this the
+ // rejection went unhandled and the client sat in 'deriving' with no event, forever.
+ if (state !== 'deriving') return
+ shutdown()
+ socket.close()
+ // Explicit: shutdown() already marked us closed, so the socket's own close callback is silent.
+ events.onClose()
+ return
+ }
if (state !== 'deriving') return
sessionKey = key
state = 'auth'
@@ -106,7 +146,16 @@ export function connectWatchClient(opts: {
return
}
const bytes = toBytes(data)
- if (!bytes || !sessionKey) return
+ if (!bytes) {
+ if (!warnedUnknown) {
+ warnedUnknown = true
+ console.warn(
+ "nodeterm live link: dropped a socket message that is neither text nor bytes; the WebSocket needs binaryType = 'arraybuffer'."
+ )
+ }
+ return
+ }
+ if (!sessionKey) return
const plain = openBox(bytes, sessionKey)
const h = plain && readHeader(plain)
if (!h || h.role !== ROLE_HOST || h.seq <= recvSeq || h.body.length < 1) return
@@ -119,8 +168,10 @@ export function connectWatchClient(opts: {
keepalive = every(() => void sendSealed(TAG_RPC, utf8(KEEPALIVE_JSON)), KEEPALIVE_MS)
// After this handler returns: over an in-process transport the host is still inside its own
// send and has not created its trust gate yet, and a confirm it cannot see is lost for good.
+ // A host that confirms inside its onReady (a pinned one) is heard before this runs, which is
+ // why maybeOpen also waits for `confirmSent`.
queueMicrotask(() => {
- sendSealed(TAG_TUNNEL_TEXT, utf8(TRUST_CONFIRM_JSON))
+ confirmSent = sendSealed(TAG_TUNNEL_TEXT, utf8(TRUST_CONFIRM_JSON))
maybeOpen()
})
return
@@ -145,9 +196,9 @@ export function connectWatchClient(opts: {
}
})
socket.onClose(() => {
- const wasOpen = state !== 'closed'
+ const alreadyClosed = state === 'closed'
shutdown()
- if (wasOpen) events.onClose()
+ if (!alreadyClosed) events.onClose()
})
socket.send(JSON.stringify({ type: 'e2ee_hello', publicKeyB64: bytesToB64(keys.viewer.publicKey), nonceB64: bytesToB64(ourNonce) }))
diff --git a/src/shared/watch-link/vectors.json b/src/shared/watch-link/vectors.json
index 2ed65f557..f1f8ff69d 100644
--- a/src/shared/watch-link/vectors.json
+++ b/src/shared/watch-link/vectors.json
@@ -40,5 +40,21 @@
"data": "a\u001b[31mb",
"hex": "010007736573732dc3a9611b5b33316d62"
}
+ ],
+ "sessionKeys": [
+ {
+ "baseKeyHex": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",
+ "hostNonceHex": "202122232425262728292a2b2c2d2e2f",
+ "clientNonceHex": "303132333435363738393a3b3c3d3e3f",
+ "info": "nodeterm-relay-session-v2",
+ "sessionKeyHex": "84cad65c51ad66339182b498586645dbe43473d759450a1eabcc883463f076e2"
+ },
+ {
+ "baseKeyHex": "a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5",
+ "hostNonceHex": "ffffffffffffffffffffffffffffffff",
+ "clientNonceHex": "00000000000000000000000000000000",
+ "info": "nodeterm-relay-session-v2",
+ "sessionKeyHex": "b981020481a96beea9f8d84ad0821080833f37f1b8dd46bbbad8eb9350ac2543"
+ }
]
}
diff --git a/src/shared/watch-link/vectors.test.ts b/src/shared/watch-link/vectors.test.ts
index 3e5296cae..b9ceaf5b5 100644
--- a/src/shared/watch-link/vectors.test.ts
+++ b/src/shared/watch-link/vectors.test.ts
@@ -2,18 +2,20 @@ import { describe, it, expect } from 'vitest'
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import { deriveWatchLinkKeys, sha256Hex } from './keys'
-import { bytesToHex } from './bytes'
+import { bytesToHex, concatBytes, utf8 } from './bytes'
+import { hkdfSha256 } from './hkdf'
import { formatWatchLink } from './link'
-import { encodePtyFrame } from './wire'
+import { encodePtyFrame, RELAY_SESSION_INFO } from './wire'
// vectors.json is what nodeterm-web's copy is tested against. It is the fixture; this test proves
// the code still produces it. Regenerate ONLY for a deliberate protocol change (bump the version).
const vectors = JSON.parse(readFileSync(join(__dirname, 'vectors.json'), 'utf8').replace(/\r\n/g, '\n'))
+const hex = (h: string): Uint8Array => Uint8Array.from(Buffer.from(h, 'hex'))
describe('watch-link vectors', () => {
it('the code reproduces every vector', async () => {
for (const v of vectors.keys) {
- const secret = Uint8Array.from(Buffer.from(v.secretHex, 'hex'))
+ const secret = hex(v.secretHex)
const k = deriveWatchLinkKeys(secret)
expect(bytesToHex(k.host.publicKey)).toBe(v.hostPublicHex)
expect(bytesToHex(k.viewer.publicKey)).toBe(v.viewerPublicHex)
@@ -23,4 +25,15 @@ describe('watch-link vectors', () => {
}
for (const f of vectors.ptyFrames) expect(bytesToHex(encodePtyFrame(f.sessionId, f.data))).toBe(f.hex)
})
+
+ it('derives every session key: HKDF-SHA256(base, hostNonce ‖ clientNonce, info)', async () => {
+ // The web copy cannot run against the real relay, so this is how it checks its WebCrypto HKDF
+ // path. src/core/watch-link/wire.test.ts pins the same vectors to the relay's deriveSessionKey.
+ expect(vectors.sessionKeys.length).toBeGreaterThan(0)
+ for (const v of vectors.sessionKeys) {
+ expect(v.info).toBe(RELAY_SESSION_INFO)
+ const key = await hkdfSha256(hex(v.baseKeyHex), concatBytes(hex(v.hostNonceHex), hex(v.clientNonceHex)), utf8(v.info), 32)
+ expect(bytesToHex(key)).toBe(v.sessionKeyHex)
+ }
+ })
})