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(watch-link): derive a live link's keys from its secret, and its URL format

review51002acebdf2
diff --git a/src/shared/watch-link/bytes.ts b/src/shared/watch-link/bytes.ts
new file mode 100644
index 000000000..541e3eaf0
--- /dev/null
+++ b/src/shared/watch-link/bytes.ts
@@ -0,0 +1,62 @@
+// Byte helpers for the live-link protocol. ISOMORPHIC: this directory is vendored byte-for-byte by
+// nodeterm-web (the viewer page), so nothing here may touch `Buffer`, `node:*` or the DOM beyond
+// `btoa`/`atob`/`TextEncoder`, which Node ≥ 16 and every browser provide.
+
+const B64 = /^[A-Za-z0-9+/]*={0,2}$/
+const B64URL = /^[A-Za-z0-9_-]*$/
+
+export function bytesToB64(b: Uint8Array): string {
+ let s = ''
+ for (let i = 0; i < b.length; i++) s += String.fromCharCode(b[i])
+ return btoa(s)
+}
+
+/** Strict: a string with characters outside the alphabet is `null`, never a silently shorter key. */
+export function b64ToBytes(s: string): Uint8Array | null {
+ if (typeof s !== 'string' || s.length % 4 !== 0 || !B64.test(s)) return null
+ try {
+ const bin = atob(s)
+ const out = new Uint8Array(bin.length)
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i)
+ return out
+ } catch {
+ return null
+ }
+}
+
+export function bytesToB64url(b: Uint8Array): string {
+ return bytesToB64(b).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
+}
+
+export function b64urlToBytes(s: string): Uint8Array | null {
+ if (typeof s !== 'string' || !B64URL.test(s)) return null
+ const std = s.replace(/-/g, '+').replace(/_/g, '/')
+ return b64ToBytes(std + '='.repeat((4 - (std.length % 4)) % 4))
+}
+
+export function bytesToHex(b: Uint8Array): string {
+ let s = ''
+ for (let i = 0; i < b.length; i++) s += b[i].toString(16).padStart(2, '0')
+ return s
+}
+
+export function utf8(s: string): Uint8Array {
+ return new TextEncoder().encode(s)
+}
+
+/** WebCrypto takes only ArrayBuffer-backed views: TypeScript types a bare `Uint8Array` as possibly
+ * SharedArrayBuffer-backed, and browsers refuse those at runtime. A copy is exact and costs nothing
+ * at key sizes, so every `crypto.subtle` argument goes through here instead of a cast. */
+export function webCryptoBytes(b: Uint8Array): Uint8Array<ArrayBuffer> {
+ return new Uint8Array(b)
+}
+
+export function concatBytes(...parts: Uint8Array[]): Uint8Array {
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0))
+ let o = 0
+ for (const p of parts) {
+ out.set(p, o)
+ o += p.length
+ }
+ return out
+}
diff --git a/src/shared/watch-link/keys.test.ts b/src/shared/watch-link/keys.test.ts
new file mode 100644
index 000000000..51f9d7c15
--- /dev/null
+++ b/src/shared/watch-link/keys.test.ts
@@ -0,0 +1,64 @@
+import { describe, it, expect } from 'vitest'
+import { createHash } from 'node:crypto'
+import nacl from 'tweetnacl'
+import { bytesToB64, b64ToBytes, bytesToB64url, b64urlToBytes, bytesToHex, utf8, concatBytes } from './bytes'
+import { deriveWatchLinkKeys, newWatchLinkSecret, sha256Hex, WATCH_LINK_KDF_PREFIX } from './keys'
+import { formatWatchLink, parseWatchLinkLocation, LINK_ID_RE } from './link'
+
+const secret = Uint8Array.from({ length: 32 }, (_, i) => i)
+
+describe('bytes', () => {
+ it('round-trips base64 and base64url like Buffer does', () => {
+ const b = nacl.randomBytes(57)
+ expect(bytesToB64(b)).toBe(Buffer.from(b).toString('base64'))
+ expect(bytesToB64url(b)).toBe(Buffer.from(b).toString('base64url'))
+ expect(b64ToBytes(bytesToB64(b))).toEqual(b)
+ expect(b64urlToBytes(bytesToB64url(b))).toEqual(b)
+ expect(bytesToHex(Uint8Array.of(0, 255, 16))).toBe('00ff10')
+ expect(concatBytes(utf8('a'), utf8('bc'))).toEqual(utf8('abc'))
+ })
+ it('refuses malformed base64 instead of silently truncating', () => {
+ expect(b64ToBytes('not base64!!')).toBeNull()
+ expect(b64urlToBytes('+/+/')).toBeNull()
+ })
+})
+
+describe('deriveWatchLinkKeys', () => {
+ it('derives each key from a domain-separated SHA-512 of the secret', () => {
+ const k = deriveWatchLinkKeys(secret)
+ const sub = (label: string) =>
+ new Uint8Array(createHash('sha512').update(Buffer.concat([Buffer.from(WATCH_LINK_KDF_PREFIX + label), Buffer.from(secret)])).digest()).slice(0, 32)
+ expect(k.host.secretKey).toEqual(sub('host'))
+ expect(k.host.publicKey).toEqual(nacl.box.keyPair.fromSecretKey(sub('host')).publicKey)
+ expect(k.viewer.secretKey).toEqual(sub('viewer'))
+ expect(k.joinKey).toEqual(sub('join'))
+ expect(k.host.publicKey).not.toEqual(k.viewer.publicKey)
+ })
+ it('makes a fresh 32-byte secret each time', () => {
+ const a = newWatchLinkSecret()
+ expect(a).toHaveLength(32)
+ expect(a).not.toEqual(newWatchLinkSecret())
+ })
+ it('hashes the join key as lowercase hex sha256', async () => {
+ const k = deriveWatchLinkKeys(secret)
+ expect(await sha256Hex(k.joinKey)).toBe(createHash('sha256').update(k.joinKey).digest('hex'))
+ })
+})
+
+describe('link format', () => {
+ const id = 'AbCdEfGhIjKlMnOpQrStUv'
+ it('formats and parses the viewer URL', () => {
+ const url = formatWatchLink(id, secret)
+ expect(url).toBe(`https://nodeterm.dev/s/${id}#1.${Buffer.from(secret).toString('base64url')}`)
+ const u = new URL(url)
+ expect(parseWatchLinkLocation(u.pathname, u.hash)).toEqual({ linkId: id, secret })
+ })
+ it('refuses a wrong version, id or secret length', () => {
+ const s = Buffer.from(secret).toString('base64url')
+ expect(parseWatchLinkLocation(`/s/${id}`, `#2.${s}`)).toBeNull()
+ expect(parseWatchLinkLocation('/s/short', `#1.${s}`)).toBeNull()
+ expect(parseWatchLinkLocation(`/s/${id}`, `#1.${s.slice(1)}`)).toBeNull()
+ expect(parseWatchLinkLocation(`/s/${id}/x`, `#1.${s}`)).toBeNull()
+ expect(LINK_ID_RE.test(id)).toBe(true)
+ })
+})
diff --git a/src/shared/watch-link/keys.ts b/src/shared/watch-link/keys.ts
new file mode 100644
index 000000000..ca5f611a1
--- /dev/null
+++ b/src/shared/watch-link/keys.ts
@@ -0,0 +1,41 @@
+// Everything a live link needs is derived from ONE 32-byte secret S that lives only in the URL
+// fragment. The host key pair lets the viewer pin the host; the viewer key pair is what the host
+// accepts in the handshake (so the relay handshake itself is unchanged); the join key is shown to
+// the API, which stores only its SHA-256 and so can gate a join without learning S. The three are
+// domain-separated, so learning the join key (the API does) reveals nothing about the other two.
+import nacl from 'tweetnacl'
+import { bytesToHex, concatBytes, utf8, webCryptoBytes } from './bytes'
+
+export const WATCH_LINK_KDF_PREFIX = 'nodeterm-watch-link-v1/'
+export const WATCH_LINK_SECRET_BYTES = 32
+
+export interface KeyPairBytes {
+ publicKey: Uint8Array
+ secretKey: Uint8Array
+}
+export interface WatchLinkKeys {
+ host: KeyPairBytes
+ viewer: KeyPairBytes
+ joinKey: Uint8Array
+}
+
+function sub(secret: Uint8Array, label: string): Uint8Array {
+ return nacl.hash(concatBytes(utf8(WATCH_LINK_KDF_PREFIX + label), secret)).slice(0, 32)
+}
+
+export function deriveWatchLinkKeys(secret: Uint8Array): WatchLinkKeys {
+ if (secret.length !== WATCH_LINK_SECRET_BYTES) throw new Error('A live link secret is 32 bytes.')
+ return {
+ host: nacl.box.keyPair.fromSecretKey(sub(secret, 'host')),
+ viewer: nacl.box.keyPair.fromSecretKey(sub(secret, 'viewer')),
+ joinKey: sub(secret, 'join')
+ }
+}
+
+export function newWatchLinkSecret(): Uint8Array {
+ return nacl.randomBytes(WATCH_LINK_SECRET_BYTES)
+}
+
+export async function sha256Hex(b: Uint8Array): Promise<string> {
+ return bytesToHex(new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', webCryptoBytes(b))))
+}
diff --git a/src/shared/watch-link/link.ts b/src/shared/watch-link/link.ts
new file mode 100644
index 000000000..c841392e7
--- /dev/null
+++ b/src/shared/watch-link/link.ts
@@ -0,0 +1,23 @@
+// The viewer URL: https://nodeterm.dev/s/<linkId>#1.<S>. The id names a link and unlocks nothing;
+// S is in the FRAGMENT so it never reaches an HTTP request, a server log or a referrer.
+import { b64urlToBytes, bytesToB64url } from './bytes'
+import { WATCH_LINK_SECRET_BYTES } from './keys'
+
+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}$/
+
+export function formatWatchLink(linkId: string, secret: Uint8Array, origin: string = WATCH_LINK_ORIGIN): string {
+ return `${origin}/s/${linkId}#${WATCH_LINK_FRAGMENT_VERSION}.${bytesToB64url(secret)}`
+}
+
+export function parseWatchLinkLocation(pathname: string, hash: string): { linkId: string; secret: Uint8Array } | null {
+ const m = /^\/s\/([^/]+)\/?$/.exec(pathname)
+ if (!m || !LINK_ID_RE.test(m[1])) return null
+ const frag = hash.startsWith('#') ? hash.slice(1) : hash
+ const dot = frag.indexOf('.')
+ if (dot < 0 || frag.slice(0, dot) !== WATCH_LINK_FRAGMENT_VERSION) return null
+ const secret = b64urlToBytes(frag.slice(dot + 1))
+ if (!secret || secret.length !== WATCH_LINK_SECRET_BYTES) return null
+ return { linkId: m[1], secret }
+}