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.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(relay): refuse low-order keys, require canonical base64, SAS v2
review1a9c2e768aa8
diff --git a/src/core/relay/approved-devices-core.ts b/src/core/relay/approved-devices-core.tsindex e1b8a009e..635b7f559 100644--- a/src/core/relay/approved-devices-core.ts+++ b/src/core/relay/approved-devices-core.ts@@ -6,6 +6,7 @@//// Kept pure (no I/O) so it can be unit-tested; the disk read/write wrapper lives in// `approved-devices.ts`.+import { isLowOrderPublicKey } from './e2ee'/** The persisted shape of every relay pin store (<userData>/remote-approved-{phones,guests,hosts}.json). */export interface ApprovedDevices {@@ -34,14 +35,27 @@ export function parseApprovedDevices(raw: unknown): ApprovedDevices {return { pubkeys: out }}-/** True when `pubkeyB64` has been pinned before. Empty input is never pinned. */+/**+ * A low-order X25519 key in ANY base64 spelling Node would decode (deliberately lenient here: the+ * question is "could this string name such a key", not "is it well formed"). No device holds a+ * secret for one — its shared secret is a public constant — so it is never pinned and never counts+ * as pinned, even if an older build (or a hand edit) put one in the file. The relay handshake+ * refuses it first (e2ee.ts deriveSharedKey); this is the store's own belt.+ */+function isLowOrderKeyB64(pubkeyB64: string): boolean {+ const bytes = Buffer.from(pubkeyB64, 'base64')+ return bytes.length === 32 && isLowOrderPublicKey(Uint8Array.from(bytes))+}++/** True when `pubkeyB64` has been pinned before. Empty input and a low-order key are never pinned. */export function isPinned(store: ApprovedDevices, pubkeyB64: string): boolean {- return pubkeyB64.length > 0 && store.pubkeys.includes(pubkeyB64)+ return pubkeyB64.length > 0 && store.pubkeys.includes(pubkeyB64) && !isLowOrderKeyB64(pubkeyB64)}-/** Return a store with `pubkeyB64` pinned. Idempotent; returns the same object when already present. */+/** Return a store with `pubkeyB64` pinned. Idempotent; returns the same object when already present+ * — or when the key is empty or low-order (refused: see isLowOrderKeyB64). */export function pinDevice(store: ApprovedDevices, pubkeyB64: string): ApprovedDevices {- if (pubkeyB64.length === 0 || store.pubkeys.includes(pubkeyB64)) return store+ if (pubkeyB64.length === 0 || store.pubkeys.includes(pubkeyB64) || isLowOrderKeyB64(pubkeyB64)) return storereturn { pubkeys: [...store.pubkeys, pubkeyB64] }}diff --git a/src/core/relay/e2ee.test.ts b/src/core/relay/e2ee.test.tsnew file mode 100644index 000000000..ece390c3b--- /dev/null+++ b/src/core/relay/e2ee.test.ts@@ -0,0 +1,168 @@+// The relay's key-intake and SAS rules (src/core/relay/e2ee.ts). Three properties, each a security+// finding fixed in one place:+// - a LOW-ORDER X25519 peer key is refused: with one the shared secret is a public constant, so+// both humans would read the same fixed SAS and anyone on the wire derives the session key;+// - a key or nonce is accepted only in CANONICAL base64: Node's decoder skips junk characters, so+// a visibly different string would otherwise decode to the same key;+// - the SAS is v2 (6 + 4 digits), whose first seven characters are the v1 code, so an older peer+// showing six digits can still be compared.+import { describe, expect, it } from 'vitest'+import nacl from 'tweetnacl'+import {+ WeakPeerKeyError,+ deriveSharedKey,+ genKeyPair,+ isLowOrderPublicKey,+ peerPublicKeyFromB64,+ publicKeyFromB64,+ publicKeyToB64,+ sasFromSharedKey+} from './e2ee'+import { lowOrderKeys } from './low-order-keys.test-support'++const b64 = (k: Uint8Array): string => Buffer.from(k).toString('base64')++/** The v1 SAS formula, kept here only to prove v2 extends it. */+function sasV1(shared: Uint8Array): string {+ const h = nacl.hash(shared)+ const n = ((h[0] << 24) | (h[1] << 16) | (h[2] << 8) | h[3]) >>> 0+ const code = (n % 1_000_000).toString().padStart(6, '0')+ return `${code.slice(0, 3)} ${code.slice(3)}`+}++describe('low-order peer keys', () => {+ it('deriveSharedKey refuses every low-order encoding, for any of our secrets', () => {+ const ours = genKeyPair()+ for (const k of lowOrderKeys()) {+ expect(() => deriveSharedKey(b64(k), ours.secretKey), Buffer.from(k).toString('hex')).toThrow(WeakPeerKeyError)+ }+ })++ it('isLowOrderPublicKey names exactly the low-order points, needing no secret', () => {+ for (const k of lowOrderKeys()) expect(isLowOrderPublicKey(k)).toBe(true)+ for (let i = 0; i < 64; i++) expect(isLowOrderPublicKey(genKeyPair().publicKey)).toBe(false)+ })++ it('peerPublicKeyFromB64 refuses a low-order key and accepts a real one', () => {+ for (const k of lowOrderKeys()) expect(() => peerPublicKeyFromB64(b64(k))).toThrow(WeakPeerKeyError)+ const real = genKeyPair().publicKey+ expect(peerPublicKeyFromB64(b64(real))).toEqual(real)+ })++ it('the refusal carries a stable code and says why', () => {+ try {+ deriveSharedKey(b64(new Uint8Array(32)), genKeyPair().secretKey)+ throw new Error('not refused')+ } catch (e) {+ expect(e).toBeInstanceOf(WeakPeerKeyError)+ expect((e as WeakPeerKeyError).code).toBe('E_WEAK_PEER_KEY')+ expect((e as Error).message).toMatch(/low-order/)+ }+ })++ it('two real keys still agree on the shared key, and it is exactly nacl.box.before', () => {+ for (let i = 0; i < 20; i++) {+ const a = genKeyPair()+ const b = genKeyPair()+ const ab = deriveSharedKey(b64(b.publicKey), a.secretKey)+ expect(ab).toEqual(deriveSharedKey(b64(a.publicKey), b.secretKey))+ expect(ab).toEqual(nacl.box.before(b.publicKey, a.secretKey))+ }+ })+})++describe('canonical base64', () => {+ const key = genKeyPair().publicKey+ const canonical = b64(key)++ it('accepts the canonical, padded form', () => {+ expect(publicKeyFromB64(canonical)).toEqual(key)+ })++ it('refuses a string that only decodes to the key (junk, whitespace, wrong alphabet, no padding)', () => {+ const variants = [+ '!!!@@@' + canonical,+ canonical + '====junk',+ 'а' + canonical, // a Cyrillic letter+ ' ' + canonical,+ canonical + '\n',+ canonical.slice(0, 22) + ' ' + canonical.slice(22),+ canonical.replace(/=$/, ''), // missing padding+ canonical.replace(/\+/g, '-').replace(/\//g, '_'), // base64url alphabet+ 'A'.repeat(1_000_000) + canonical+ ].filter((v) => v !== canonical)+ for (const v of variants) {+ // Node's own decoder hands back the real key for most of these: that is the finding.+ expect(() => publicKeyFromB64(v), JSON.stringify(v.slice(0, 60))).toThrow()+ }+ })++ it('refuses non-zero padding bits (a second spelling of the same 32 bytes)', () => {+ // 32 bytes = 256 bits = 42 full sextets + 4 bits; the 43rd character carries 2 padding bits.+ const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'+ const last = alphabet.indexOf(canonical[42])+ const twin = canonical.slice(0, 42) + alphabet[last | 1] + '='+ expect(Buffer.from(twin, 'base64')).toEqual(Buffer.from(key))+ expect(twin).not.toBe(canonical)+ expect(() => publicKeyFromB64(twin)).toThrow()+ })++ it('refuses a non-string', () => {+ expect(() => publicKeyFromB64(undefined as unknown as string)).toThrow()+ expect(() => publicKeyFromB64(42 as unknown as string)).toThrow()+ })+})++describe('SAS v2', () => {+ // The vectors the iOS and Android apps must reproduce byte for byte (docs/ios-protocol-migration.md+ // §3.1). Computed independently (Python hashlib.sha512) from the contract:+ // h = SHA-512(shared); a = BE_u32(h[0..4]) mod 1e6; b = BE_u32(h[4..8]) mod 1e4;+ // SAS = pad6(a)[0..3] + " " + pad6(a)[3..6] + " " + pad4(b)+ const vectors: Array<[string, Uint8Array, string]> = [+ ['32 x 0x00', new Uint8Array(32), '809 281 4822'],+ // The vector the iOS app pins too (eneskirca/nodeterm-ios#75): SHA-512 begins 5ce86efb 75fa4e2c.+ ['32 x 0x01', new Uint8Array(32).fill(0x01), '736 635 8284'],+ ['0x00..0x1f', Uint8Array.from({ length: 32 }, (_, i) => i), '170 596 5663'],+ ['32 x 0xff', new Uint8Array(32).fill(0xff), '773 237 5799'],+ ['00 17 then 30 x 00 (six-digit half needs its leading zero)', Uint8Array.from([0x00, 0x17, ...new Array(30).fill(0)]), '071 120 4361'],+ ['00 0b then 30 x 00 (four-digit half needs its leading zero)', Uint8Array.from([0x00, 0x0b, ...new Array(30).fill(0)]), '243 975 0790']+ ]+ for (const [name, shared, want] of vectors) {+ it(`vector: ${name}`, () => {+ expect(sasFromSharedKey(shared)).toBe(want)+ })+ }++ it('end-to-end vector: fixed secret keys → box.before → SAS (both sides)', () => {+ const a = nacl.box.keyPair.fromSecretKey(new Uint8Array(32).fill(0x01))+ const b = nacl.box.keyPair.fromSecretKey(new Uint8Array(32).fill(0x02))+ const ab = deriveSharedKey(b64(b.publicKey), a.secretKey)+ const ba = deriveSharedKey(b64(a.publicKey), b.secretKey)+ expect(b64(a.publicKey)).toBe(E2E_VECTOR.pubA)+ expect(b64(b.publicKey)).toBe(E2E_VECTOR.pubB)+ expect(Buffer.from(nacl.scalarMult(a.secretKey, b.publicKey)).toString('hex')).toBe(E2E_VECTOR.rawX25519Hex)+ expect(Buffer.from(ab).toString('hex')).toBe(E2E_VECTOR.sharedHex)+ expect(sasFromSharedKey(ab)).toBe(E2E_VECTOR.sas)+ expect(sasFromSharedKey(ba)).toBe(E2E_VECTOR.sas)+ })++ it('the first seven characters are the v1 code, for any key', () => {+ for (let i = 0; i < 200; i++) {+ const shared = nacl.randomBytes(32)+ const v2 = sasFromSharedKey(shared)+ expect(v2).toMatch(/^\d{3} \d{3} \d{4}$/)+ expect(v2.slice(0, 7)).toBe(sasV1(shared))+ }+ })+})++/** Fixed-key end-to-end vector: secret A = 32 x 0x01, secret B = 32 x 0x02. */+const E2E_VECTOR = {+ pubA: 'pOCSkrZRwni5dyxWn1+puxPZBrRqtoyd+dwrRAn4ogk=',+ pubB: 'zo060cy2M+x7cMF4FKXHbs0CloUFDTRHRboFhw5YfVk=',+ /** Raw X25519(secretA, pubB), before NaCl's HSalsa20 (checked against pyca/cryptography). */+ rawX25519Hex: '2ed76ab549b1e73c031eb49c9448f0798aea81b698279a0c3dc3e49fbfc4b953',+ /** nacl.box.before = HSalsa20(raw): the "shared key" the SAS is computed from. */+ sharedHex: '18a99320f3488fa18a04239715d8ee738065e65c3d4b2898522d6c3d4ead588c',+ sas: '561 048 8895'+}diff --git a/src/core/relay/e2ee.ts b/src/core/relay/e2ee.tsindex 11e986d86..0708306bf 100644--- a/src/core/relay/e2ee.ts+++ b/src/core/relay/e2ee.ts@@ -19,14 +19,91 @@ export function publicKeyToB64(key: Uint8Array): string {return Buffer.from(key).toString('base64')}+/**+ * Decode base64 that must be in CANONICAL form: standard alphabet, padded, nothing else. Node's+ * `Buffer.from(x, 'base64')` skips every character outside the alphabet and ignores trailing junk,+ * so `"!!!" + key`, `key + "====junk"` or a key with a Cyrillic letter in front all decode to the+ * real key — a visibly different string standing for the same identity. And the relay compares keys+ * as STRINGS (pin stores, team.json, autoApprove), so a second spelling of one key is also a key+ * that matches none of its own pins. One key, one spelling: the decoded bytes must re-encode to the+ * exact input.+ *+ * Padding is REQUIRED (an unpadded key is refused): every producer pads — the desktop and server+ * (`Buffer#toString('base64')`), iOS (`base64EncodedString()`), Android (`java.util.Base64`) and+ * the web viewer (`bytesToB64`) — so accepting the unpadded form would only add a second spelling.+ * The length is checked before decoding, so a megabyte of junk is refused without being decoded.+ */+export function canonicalB64ToBytes(b64: unknown, bytes: number, what: string): Uint8Array {+ if (typeof b64 !== 'string') throw new Error(`Invalid ${what}: not a string`)+ if (b64.length !== 4 * Math.ceil(bytes / 3)) {+ throw new Error(`Invalid ${what}: expected ${bytes} bytes of canonical base64`)+ }+ const out = Buffer.from(b64, 'base64')+ if (out.length !== bytes) {+ throw new Error(`Invalid ${what}: expected ${bytes} bytes, got ${out.length}`)+ }+ if (out.toString('base64') !== b64) throw new Error(`Invalid ${what}: not canonical base64`)+ return Uint8Array.from(out)+}+export function publicKeyFromB64(b64: string): Uint8Array {- const key = Uint8Array.from(Buffer.from(b64, 'base64'))- if (key.length !== nacl.box.publicKeyLength) {- throw new Error(`Invalid public key: expected ${nacl.box.publicKeyLength} bytes, got ${key.length}`)+ return canonicalB64ToBytes(b64, nacl.box.publicKeyLength, 'public key')+}++/**+ * A PEER's public key is refused when it is a low-order X25519 point. With one, the X25519 output+ * is all zero whatever our secret is, so `box.before` = HSalsa20(0) is a PUBLIC CONSTANT: both+ * humans then read the same fixed SAS ("357 836" under v1), a secret-less peer completes the+ * handshake, and anyone on the wire derives the session key from the two plaintext nonces. RFC 7748+ * §6.1; relay-pop.ts refuses the same degenerate secret for the PoP. Thrown with a stable `code`.+ */+export class WeakPeerKeyError extends Error {+ readonly code = 'E_WEAK_PEER_KEY'+ constructor() {+ super(+ 'Refused a low-order X25519 public key: with it the shared secret would be a public constant, ' ++ 'so the connection could be read by anyone. The code or key is corrupt or was tampered with.'+ )+ this.name = 'WeakPeerKeyError'}+}++/** True when every byte is zero. Reads every byte (no early exit). */+function allZero(b: Uint8Array): boolean {+ let acc = 0+ for (let i = 0; i < b.length; i++) acc |= b[i]+ return acc === 0+}++// X25519 clamps every scalar to a multiple of 8 below the prime-order subgroup's order, so ANY+// scalar sends a point of order dividing 8 (and only such a point) to zero. A fixed probe therefore+// answers "is this key low-order?" with no secret — for the intakes that have none at hand (a join+// code, a pairing offer, a pin store).+const LOW_ORDER_PROBE = new Uint8Array(32).fill(0x5a)++/** Is this 32-byte X25519 public key a low-order point (any of its encodings)? */+export function isLowOrderPublicKey(pub: Uint8Array): boolean {+ if (pub.length !== nacl.box.publicKeyLength) return false+ return allZero(nacl.scalarMult(LOW_ORDER_PROBE, pub))+}++/** A peer's public key from canonical base64, refusing a low-order point (`WeakPeerKeyError`). */+export function peerPublicKeyFromB64(b64: string): Uint8Array {+ const key = publicKeyFromB64(b64)+ if (isLowOrderPublicKey(key)) throw new WeakPeerKeyError()return key}+/** True for a string that is a usable PEER key: canonical base64 of 32 bytes, not low-order. */+export function isUsablePeerKeyB64(b64: unknown): boolean {+ try {+ peerPublicKeyFromB64(b64 as string)+ return true+ } catch {+ return false+ }+}+// Same strictness for a secret key: `Buffer.from(x, 'base64')` silently drops non-alphabet// characters and truncates, so a corrupt/short blob would otherwise decode to a short-but-accepted// key that only blows up ("bad secret key size") deep inside a later nacl.box call.@@ -42,11 +119,30 @@ export function secretKeyFromB64(b64: string): Uint8Array {// and our secret key. Both sides arrive at the same value. This is the STABLE// per-device-pair key (both endpoints use static keys for pin-once), so it must// NOT be used directly to encrypt traffic — see deriveSessionKey.+//+// REFUSES a low-order peer key (`WeakPeerKeyError`), checked on the RAW X25519 output — the input+// to HSalsa20, which is where a low-order key shows up as all zero; `box.before`'s own output never+// is. Every relay handshake (both roles) and the /pair envelope derive through here, so this is the+// one choke point the intakes upstream (join code, pairing offer, pins) are belts to.export function deriveSharedKey(theirPubB64: string, ourSecret: Uint8Array): Uint8Array {const theirPub = publicKeyFromB64(theirPubB64)- return nacl.box.before(theirPub, ourSecret)+ const raw = nacl.scalarMult(ourSecret, theirPub)+ if (allZero(raw)) throw new WeakPeerKeyError()+ // `box.before` is exactly scalarMult then HSalsa20(key = raw, input = 16 zero bytes, sigma); doing+ // the second half here spares a second X25519 (~ms in tweetnacl's pure JS). e2ee.test.ts pins the+ // output against `nacl.box.before` and a fixed end-to-end vector.+ const out = new Uint8Array(32)+ lowlevel.crypto_core_hsalsa20(out, HSALSA_ZERO, raw, SIGMA)+ return out}+// tweetnacl's d.ts does not declare `lowlevel`; it is the library's documented low-level export.+const lowlevel = (nacl as unknown as {+ lowlevel: { crypto_core_hsalsa20(out: Uint8Array, inp: Uint8Array, k: Uint8Array, c: Uint8Array): number }+}).lowlevel+const HSALSA_ZERO = new Uint8Array(16)+const SIGMA = new TextEncoder().encode('expand 32-byte k')+// A fresh 16-byte session nonce, exchanged in the handshake.export function randomSessionNonce(): Uint8Array {return nacl.randomBytes(16)@@ -83,15 +179,27 @@ export function encrypt(plain: Uint8Array, shared: Uint8Array): Uint8Array {return box}-// Short Authentication String: a 6-digit code derived from the ECDH shared key. Both peers-// compute the SAME value (same shared key), so the two humans can compare it out-of-band to-// confirm they're on the same channel before the host approves a connection. Formatted "NNN NNN".+// Short Authentication String (v2): a 10-digit code derived from the ECDH shared key. Both peers+// compute the SAME value (same shared key), so the two humans can compare it out of band to confirm+// they are on the same channel before anything opens. Formatted "NNN NNN NNNN":+//+// h = SHA-512(shared)+// a = BE_u32(h[0..4]) mod 1_000_000 // the v1 code+// b = BE_u32(h[4..8]) mod 10_000 // four more digits+// SAS = pad6(a)[0..3] + " " + pad6(a)[3..6] + " " + pad4(b)+//+// v1 was the first six digits alone: ~20 bits, which an attacker who substitutes a pinned key (a+// tampered offer, join code or QR) can grind to a match on both legs in seconds. v2 is ~33 bits.+// The first seven characters ARE the v1 code, so a peer still on v1 (six digits) is compared on the+// first six — the copy under every SAS says so (SAS_COMPARE_HINT). The iOS and Android apps compute+// the same bytes; the vectors are in e2ee.test.ts and docs/ios-protocol-migration.md §3.1.export function sasFromSharedKey(shared: Uint8Array): string {const h = nacl.hash(shared) // SHA-512- // Fold the first 4 bytes into a 32-bit int, then take 6 decimal digits.- const n = ((h[0] << 24) | (h[1] << 16) | (h[2] << 8) | h[3]) >>> 0- const code = (n % 1_000_000).toString().padStart(6, '0')- return `${code.slice(0, 3)} ${code.slice(3)}`+ const a = (((h[0] << 24) | (h[1] << 16) | (h[2] << 8) | h[3]) >>> 0) % 1_000_000+ const b = (((h[4] << 24) | (h[5] << 16) | (h[6] << 8) | h[7]) >>> 0) % 10_000+ const six = a.toString().padStart(6, '0')+ const four = b.toString().padStart(4, '0')+ return `${six.slice(0, 3)} ${six.slice(3)} ${four}`}// Decrypt a `nonce ‖ ciphertext ‖ mac` box. Returns null on malformed input ordiff --git a/src/core/relay/join-code.test.ts b/src/core/relay/join-code.test.tsindex e715ada8b..0733c6924 100644--- a/src/core/relay/join-code.test.ts+++ b/src/core/relay/join-code.test.ts@@ -3,6 +3,7 @@ import { describe, it, expect } from 'vitest'import { encodeJoinCode, decodeJoinCode, isJoinCode, allowedEndpoint } from './join-code'import { genKeyPair, publicKeyToB64 } from './e2ee'import { hostIdFromPublicKeyB64 } from './relay-id'+import { lowOrderKeysB64 } from './low-order-keys.test-support'const pub = publicKeyToB64(genKeyPair().publicKey)const good = { v: 1 as const, relayEndpoint: 'wss://relay.nodeterm.dev', hostId: hostIdFromPublicKeyB64(pub), hostPublicKeyB64: pub, hostDeviceId: 'd', label: 'box' }@@ -30,4 +31,24 @@ describe('join code', () => {for (const ok of ['wss://relay.nodeterm.dev', 'wss://1.2.3.4:443/x', 'ws://127.0.0.1:8080', 'ws://localhost', 'ws://[::1]:9']) expect(allowedEndpoint(ok), ok).toBe(true)for (const bad of ['ws://evil.example', 'ws://10.0.0.5', 'http://relay.nodeterm.dev', 'https://relay.nodeterm.dev', 'junk', '']) expect(allowedEndpoint(bad), bad).toBe(false)})+ it('refuses a low-order host key even when the hostId matches it (a key with a public-constant secret)', () => {+ for (const weak of lowOrderKeysB64()) {+ const code = encodeJoinCode({ ...good, hostPublicKeyB64: weak, hostId: hostIdFromPublicKeyB64(weak) })+ expect(decodeJoinCode(code), weak).toBeNull()+ }+ })+ it('refuses a host key that only decodes to the real one (non-canonical base64)', () => {+ for (const twin of ['!!!@@@' + pub, pub + '====junk', pub.replace(/=$/, '')]) {+ // Node decodes every one of these to the same 32 bytes, so the hostId still matches.+ expect(hostIdFromPublicKeyB64(twin)).toBe(good.hostId)+ expect(decodeJoinCode(encodeJoinCode({ ...good, hostPublicKeyB64: twin })), twin).toBeNull()+ }+ })+ it('refuses junk mixed into the code itself, but tolerates a code wrapped across lines', () => {+ const s = encodeJoinCode(good)+ const body = s.slice('nodeterm://join?code='.length)+ expect(decodeJoinCode('nodeterm://join?code=' + body.slice(0, 20) + '!!' + body.slice(20))).toBeNull()+ expect(decodeJoinCode('nodeterm://join?code=' + body + '==')).toBeNull()+ expect(decodeJoinCode('nodeterm://join?code=' + body.slice(0, 40) + '\n' + body.slice(40, 90) + ' \r\n' + body.slice(90))).toEqual(good)+ })})diff --git a/src/core/relay/join-code.ts b/src/core/relay/join-code.tsindex 34a032979..b5452a1d2 100644--- a/src/core/relay/join-code.ts+++ b/src/core/relay/join-code.ts@@ -3,6 +3,7 @@// The host key inside is what authenticates the host to the joiner, and the hostId must derive// from it, so a code cannot point a teammate at a different room than the key it carries.import { hostIdFromPublicKeyB64 } from './relay-id'+import { isUsablePeerKeyB64 } from './e2ee'// The prefix is shared with the renderer (which cannot import this file); one definition.import { JOIN_CODE_PREFIX as PREFIX, isJoinCode } from '../../shared/relay-join-code'@@ -25,16 +26,33 @@ export function encodeJoinCode(c: JoinCode): string {return PREFIX + Buffer.from(JSON.stringify(c), 'utf-8').toString('base64url')}+/** The code body's bytes, or null. Canonical base64url only: Node's decoder skips characters+ * outside the alphabet, so junk inside a code (or after it) would otherwise decode to the same+ * code. ASCII whitespace is removed first — a code that travelled through a chat or a mail client+ * arrives wrapped across lines, and a line break is visible, not a disguise. */+function codeBytes(body: string): Buffer | null {+ const b = body.replace(/[\t\n\r ]+/g, '')+ if (!b || !/^[A-Za-z0-9_-]+$/.test(b)) return null+ const bytes = Buffer.from(b, 'base64url')+ return bytes.toString('base64url') === b ? bytes : null+}+export function decodeJoinCode(s: string): JoinCode | null {const t = s.trim()if (!t.startsWith(PREFIX)) return nulltry {- const o = JSON.parse(Buffer.from(t.slice(PREFIX.length), 'base64url').toString('utf-8')) as Record<string, unknown>+ const bytes = codeBytes(t.slice(PREFIX.length))+ if (!bytes) return null+ const o = JSON.parse(bytes.toString('utf-8')) as Record<string, unknown>const str = (k: string, max: number) => typeof o[k] === 'string' && (o[k] as string).length > 0 && (o[k] as string).length <= maxif (o.v !== 1 || !str('relayEndpoint', 512) || !str('hostId', 64) || !str('hostPublicKeyB64', 64) || !str('hostDeviceId', 128)) return nullif (typeof o.label !== 'string' || o.label.length > 60) return nullif (!allowedEndpoint(o.relayEndpoint as string)) return null- // May throw on a malformed key; inside the try, so junk decodes to null.+ // The joiner PINS this key, so it is held to the handshake's rules: canonical base64 (one+ // spelling per key) and not a low-order point (a public-constant shared secret — the SAS would+ // be a fixed value both humans "match"). A chosen low-order key satisfies the hostId check+ // below, so that check alone never covered it.+ if (!isUsablePeerKeyB64(o.hostPublicKeyB64)) return nullif (hostIdFromPublicKeyB64(o.hostPublicKeyB64 as string) !== o.hostId) return nullreturn { v: 1, relayEndpoint: o.relayEndpoint as string, hostId: o.hostId as string, hostPublicKeyB64: o.hostPublicKeyB64 as string, hostDeviceId: o.hostDeviceId as string, label: o.label }} catch {diff --git a/src/core/relay/low-order-keys.test-support.ts b/src/core/relay/low-order-keys.test-support.tsnew file mode 100644index 000000000..36461ae29--- /dev/null+++ b/src/core/relay/low-order-keys.test-support.ts@@ -0,0 +1,26 @@+// Test support (not a test file): every encoding of an X25519 point of order dividing 8 — libsodium's+// blocklist — each also with the top bit set (X25519 ignores that bit, so it is the same point). Used+// by e2ee.test.ts and the relay regression tests to prove each intake refuses ALL of them, not just 0.+export const LOW_ORDER_POINTS_HEX = [+ '0000000000000000000000000000000000000000000000000000000000000000', // 0+ '0100000000000000000000000000000000000000000000000000000000000000', // 1+ 'e0eb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b800', // order 8+ '5f9c95bca3508c24b1d0b1559c83ef5b04445cc4581c8e86d8224eddd09f1157', // order 8+ 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f', // p - 1+ 'edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f', // p (non-canonical 0)+ 'eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f' // p + 1 (non-canonical 1)+]++export function lowOrderKeys(): Uint8Array[] {+ return LOW_ORDER_POINTS_HEX.flatMap((h) => {+ const plain = Uint8Array.from(Buffer.from(h, 'hex'))+ const high = Uint8Array.from(plain)+ high[31] |= 0x80+ return [plain, high]+ })+}++/** The same keys as canonical standard base64 (what a peer would put on the wire). */+export function lowOrderKeysB64(): string[] {+ return lowOrderKeys().map((k) => Buffer.from(k).toString('base64'))+}diff --git a/src/core/relay/mutual-approval-core.ts b/src/core/relay/mutual-approval-core.tsindex ece719178..b21ee190a 100644--- a/src/core/relay/mutual-approval-core.ts+++ b/src/core/relay/mutual-approval-core.ts@@ -1,4 +1,4 @@-// Pure state for SYMMETRIC pairing approval: both ends verify the same 6-digit SAS out of band and+// Pure state for SYMMETRIC pairing approval: both ends verify the same SAS out of band and// both pin the other's key. Today approval is one-way (only the host pins the client). This adds the// second confirmation direction + the pin-both-ends bookkeeping as pure logic — no sockets, no// Electron — so it unit-tests directly and 4c can wire it into either end's handshake.@@ -80,7 +80,7 @@ export function isMutuallyApproved(s: MutualApproval): boolean {return s.localConfirmed && s.remoteConfirmed}-/** The 6-digit code ("NNN NNN") BOTH ends compute + confirm. Thin alias so 4c reads clearly. */+/** The 10-digit code ("NNN NNN NNNN", SAS v2) BOTH ends compute + confirm. Thin alias so 4c reads clearly. */export function mutualSas(shared: Uint8Array): string {return sasFromSharedKey(shared)}diff --git a/src/core/relay/relay-client.ts b/src/core/relay/relay-client.tsindex 4c6d71142..420bdcee6 100644--- a/src/core/relay/relay-client.ts+++ b/src/core/relay/relay-client.ts@@ -38,7 +38,7 @@ import { decodePtyData } from '../../shared/rpc'import { createRelayPtyGate } from '../../shared/relay-pty-channel'export interface RelayClientSession {- /** The 6-digit SAS both humans compare, or null before the key is derived. */+ /** The 10-digit SAS (v2, "NNN NNN NNNN") both humans compare, or null before the key is derived. */sas(): string | null/** The host's stable box public key (base64) this session is bound to, or null before ready. */peerKeyB64(): string | nulldiff --git a/src/core/relay/relay-host.ts b/src/core/relay/relay-host.tsindex 05910ecb3..9d9eee80f 100644--- a/src/core/relay/relay-host.ts+++ b/src/core/relay/relay-host.ts@@ -114,7 +114,7 @@ export interface RelayHostHooks {export interface RelayHostSession {/** The peer's presence/platform ClientId once it is open, else null. */clientId(): number | null- /** The 6-digit SAS both humans compare, or null before the key is derived. */+ /** The 10-digit SAS (v2, "NNN NNN NNNN") both humans compare, or null before the key is derived. */sas(): string | null/** The peer's stable box public key (base64), or null before the handshake learned it. */peerKeyB64(): string | nulldiff --git a/src/core/relay/relay-low-order.test.ts b/src/core/relay/relay-low-order.test.tsnew file mode 100644index 000000000..5c121f5ac--- /dev/null+++ b/src/core/relay/relay-low-order.test.ts@@ -0,0 +1,335 @@+// Regression: a LOW-ORDER X25519 key (here 0^32 and every other small-order encoding) used to be+// accepted by the relay handshake. `nacl.box.before(lowOrder, anySecret)` = HSalsa20(0), a constant+// with no secret in it, so:+// - a secret-less client completed the handshake with a real host and was shown a CONSTANT SAS;+// - an attacker who substituted the host key in an offer / join code / QR with 0^32 and rewrote the+// victim's hello key to 0^32 sat transparently in the middle: both humans saw the SAME digits,+// both confirmed, the host PINNED 0^32, and the attacker read and injected every byte;+// - once 0^32 was a pinned member (hosted autoApprove), ANYONE opened a session with no secret.+// Each `it` below is one of those attacks run against the REAL relay host and client (ported from the+// security audit's working repro); every one must now fail closed.+import { describe, expect, it, vi } from 'vitest'+import nacl from 'tweetnacl'+import { connectRelayHost } from './relay-host'+import { connectRelayClient } from './relay-client'+import type { RelayTransport } from './relay-socket'+import type { PeerAttach } from './relay-host'+import type { RpcRequest } from '../../shared/rpc'+import {+ WeakPeerKeyError,+ deriveSessionKey,+ encrypt,+ genKeyPair,+ publicKeyToB64,+ randomSessionNonce+} from './e2ee'+import { lowOrderKeysB64 } from './low-order-keys.test-support'++const TAG_RPC = 0x01+const TAG_TUNNEL_TEXT = 0x03+const ZERO_KEY_B64 = Buffer.from(new Uint8Array(32)).toString('base64')+const enc = (s: string): Uint8Array => new TextEncoder().encode(s)++/** A transport pair with a man in the middle: each frame passes through `c2h` / `h2c`, which may+ * rewrite it (return the new value), pass it, or drop it (return null). */+function mitmPipe(hooks: { c2h?: (d: unknown) => unknown; h2c?: (d: unknown) => unknown } = {}) {+ let hostOnMsg: ((d: unknown) => void) | null = null+ let clientOnMsg: ((d: unknown) => void) | null = null+ let hostOnClose: (() => void) | null = null+ let clientOnClose: (() => void) | null = null+ let closed = 0+ const hostT: RelayTransport = {+ bufferedAmount: 0,+ send: (d) => {+ const x = hooks.h2c ? hooks.h2c(d) : d+ if (x !== null) clientOnMsg?.(x)+ },+ close: () => {+ closed+++ clientOnClose?.()+ hostOnClose?.()+ },+ onMessage: (cb) => {+ hostOnMsg = cb+ },+ onClose: (cb) => {+ hostOnClose = cb+ }+ }+ const clientT: RelayTransport = {+ bufferedAmount: 0,+ send: (d) => {+ const x = hooks.c2h ? hooks.c2h(d) : d+ if (x !== null) hostOnMsg?.(x)+ },+ close: () => {+ closed+++ hostOnClose?.()+ clientOnClose?.()+ },+ onMessage: (cb) => {+ clientOnMsg = cb+ },+ onClose: (cb) => {+ clientOnClose = cb+ }+ }+ return { hostT, clientT, closes: () => closed }+}++/** Seal [role][seq:8][tag][body] exactly as relay-socket.ts does. */+function seal(sessionKey: Uint8Array, role: number, seq: number, tag: number, body: Uint8Array): Uint8Array {+ const out = new Uint8Array(1 + 8 + 1 + body.length)+ out[0] = role+ const v = new DataView(out.buffer)+ v.setUint32(1, Math.floor(seq / 0x100000000), true)+ v.setUint32(5, seq >>> 0, true)+ out[9] = tag+ out.set(body, 10)+ return encrypt(out, sessionKey)+}++function fakeAttach() {+ const dispatched: RpcRequest[] = []+ const casts: Array<{ method: string; args: unknown[] }> = []+ let next = 1+ const attach: PeerAttach = {+ attach: () => next++,+ detach: () => {},+ dispatch: async (_id, req) => {+ dispatched.push(req)+ return { t: 'res', id: req.id, ok: true, result: null }+ },+ cast: (_id, method, args) => {+ casts.push({ method, args })+ }+ }+ return { attach, dispatched, casts }+}++const silence = (): void => {+ vi.spyOn(console, 'warn').mockImplementation(() => {})+}++describe('relay handshake refuses low-order keys', () => {+ it('a secret-less client presenting a low-order key gets no e2ee_ready, no SAS and a closed socket', async () => {+ silence()+ for (const weak of lowOrderKeysB64()) {+ const hostKeys = genKeyPair()+ const fa = fakeAttach()+ const pipe = mitmPipe()+ const pending = vi.fn()+ const closed = vi.fn()+ connectRelayHost({+ url: 'ws://127.0.0.1/x',+ token: 't',+ ourKeys: hostKeys,+ attach: fa.attach,+ transport: pipe.hostT,+ onPeerPending: pending,+ onOpen: () => {},+ onClose: closed+ })+ const fromHost: unknown[] = []+ pipe.clientT.onMessage((d) => fromHost.push(d))+ const nonceB64 = Buffer.from(randomSessionNonce()).toString('base64')+ pipe.clientT.send(JSON.stringify({ type: 'e2ee_hello', publicKeyB64: weak, nonceB64 }))+ // The host never answered: no e2ee_ready, so there is no session key to derive.+ expect(fromHost, weak).toEqual([])+ expect(pipe.closes(), weak).toBeGreaterThan(0)+ expect(closed, weak).toHaveBeenCalled()+ // The attacker's next step (the encrypted auth marker under the constant key) reaches nothing.+ const base = nacl.box.before(new Uint8Array(32), nacl.randomBytes(32))+ const sk = deriveSessionKey(base, nacl.randomBytes(16), Buffer.from(nonceB64, 'base64'))+ pipe.clientT.send(seal(sk, 2, 0, TAG_RPC, enc(JSON.stringify({ type: 'e2ee_auth' }))))+ await Promise.resolve()+ expect(pending, weak).not.toHaveBeenCalled()+ expect(fa.dispatched).toEqual([])+ }+ })++ it('a non-canonical spelling of a real key is refused too (Node would decode it to the same key)', () => {+ silence()+ const hostKeys = genKeyPair()+ const client = genKeyPair()+ const pipe = mitmPipe()+ const pending = vi.fn()+ connectRelayHost({+ url: 'ws://127.0.0.1/x',+ token: 't',+ ourKeys: hostKeys,+ attach: fakeAttach().attach,+ transport: pipe.hostT,+ onPeerPending: pending,+ onOpen: () => {},+ onClose: () => {}+ })+ const fromHost: unknown[] = []+ pipe.clientT.onMessage((d) => fromHost.push(d))+ const nonceB64 = Buffer.from(randomSessionNonce()).toString('base64')+ const junk = '!!!@@@' + publicKeyToB64(client.publicKey)+ expect(Buffer.from(junk, 'base64')).toEqual(Buffer.from(client.publicKey)) // the finding+ pipe.clientT.send(JSON.stringify({ type: 'e2ee_hello', publicKeyB64: junk, nonceB64 }))+ expect(fromHost).toEqual([])+ expect(pipe.closes()).toBeGreaterThan(0)+ })++ it('a client handed a low-order host key (substituted offer / join code / QR) refuses before dialing', () => {+ for (const weak of lowOrderKeysB64()) {+ const pipe = mitmPipe()+ const sent: unknown[] = []+ pipe.hostT.onMessage((d) => sent.push(d))+ expect(() =>+ connectRelayClient({+ url: 'ws://127.0.0.1/x',+ token: 't',+ hostKeyB64: weak,+ ourKeys: genKeyPair(),+ transport: pipe.clientT,+ onSas: () => {},+ onApproved: () => {},+ onFrame: () => {},+ onPtyData: () => {},+ onClose: () => {}+ })+ ).toThrow(WeakPeerKeyError)+ // Not even a hello went out.+ expect(sent, weak).toEqual([])+ }+ })++ it('the transparent MITM (victim pins 0^32, its hello is rewritten to 0^32) dies at the host: no SAS, no pin, nothing read', async () => {+ silence()+ const hostKeys = genKeyPair()+ const victim = genKeyPair()+ const fa = fakeAttach()+ const pinned: string[] = []+ let hostSas: string | null = null+ const opened: string[] = []+ // The attacker relays every byte; its only edit is the victim's hello key → 0^32.+ const fromHostPlain: string[] = []+ const pipe = mitmPipe({+ c2h: (d) => {+ if (typeof d === 'string') {+ const m = JSON.parse(d) as { type?: string }+ if (m.type === 'e2ee_hello') return JSON.stringify({ ...m, publicKeyB64: ZERO_KEY_B64 })+ }+ return d+ },+ h2c: (d) => {+ if (typeof d === 'string') fromHostPlain.push(d)+ return d+ }+ })+ connectRelayHost({+ url: 'ws://127.0.0.1/x',+ token: 't',+ ourKeys: hostKeys,+ attach: fa.attach,+ transport: pipe.hostT,+ pins: {+ record: async (s) => {+ pinned.push(s.peerKeyB64)+ }+ },+ onPeerPending: (s) => {+ hostSas = s.sas()+ },+ onOpen: () => opened.push('host'),+ onClose: () => {}+ })+ // The victim's offer pins the REAL host key here (the 0^32 offer half is refused before dialing,+ // above); the host still has to refuse the rewritten hello on its own.+ connectRelayClient({+ url: 'ws://127.0.0.1/x',+ token: 't',+ hostKeyB64: publicKeyToB64(hostKeys.publicKey),+ ourKeys: victim,+ transport: pipe.clientT,+ onSas: () => {},+ onApproved: () => opened.push('client'),+ onFrame: () => {},+ onPtyData: () => {},+ onClose: () => {}+ })+ await Promise.resolve()+ await Promise.resolve()+ // The host never answered the rewritten hello, so the attacker has no host nonce to key with.+ expect(fromHostPlain).toEqual([])+ expect(pipe.closes()).toBeGreaterThan(0)+ expect(hostSas).toBeNull()+ expect(pinned).toEqual([])+ expect(opened).toEqual([])+ expect(fa.dispatched).toEqual([])+ })++ it('a host that pins a low-order key (hosted autoApprove) is never asked: the handshake stops first', async () => {+ silence()+ const hostKeys = genKeyPair()+ const fa = fakeAttach()+ const pipe = mitmPipe()+ const asked = vi.fn((k: string) => k === ZERO_KEY_B64)+ let opened = false+ connectRelayHost({+ url: 'ws://127.0.0.1/x',+ token: 't',+ ourKeys: hostKeys,+ attach: fa.attach,+ transport: pipe.hostT,+ autoApprove: asked,+ onPeerPending: () => {},+ onOpen: () => {+ opened = true+ },+ onClose: () => {}+ })+ const fromHost: unknown[] = []+ pipe.clientT.onMessage((d) => fromHost.push(d))+ const nonceB64 = Buffer.from(randomSessionNonce()).toString('base64')+ pipe.clientT.send(JSON.stringify({ type: 'e2ee_hello', publicKeyB64: ZERO_KEY_B64, nonceB64 }))+ // Even had the attacker the session key, every tunnel frame below would land on a closed socket.+ const base = nacl.box.before(new Uint8Array(32), nacl.randomBytes(32))+ const sk = deriveSessionKey(base, nacl.randomBytes(16), Buffer.from(nonceB64, 'base64'))+ pipe.clientT.send(seal(sk, 2, 0, TAG_RPC, enc(JSON.stringify({ type: 'e2ee_auth' }))))+ pipe.clientT.send(seal(sk, 2, 1, TAG_TUNNEL_TEXT, enc(JSON.stringify({ t: 'cast', method: 'trust:confirm', args: [] }))))+ pipe.clientT.send(seal(sk, 2, 2, TAG_TUNNEL_TEXT, enc(JSON.stringify({ t: 'req', id: 9, method: 'fs:read', args: ['/etc/passwd'] }))))+ await new Promise((r) => setTimeout(r, 10))+ expect(fromHost).toEqual([])+ expect(asked).not.toHaveBeenCalled()+ expect(opened).toBe(false)+ expect(fa.dispatched).toEqual([])+ })++ it('a real client still connects and both ends show the same 10-digit SAS', async () => {+ const hostKeys = genKeyPair()+ const pipe = mitmPipe()+ let hostSas: string | null = null+ connectRelayHost({+ url: 'ws://127.0.0.1/x',+ token: 't',+ ourKeys: hostKeys,+ attach: fakeAttach().attach,+ transport: pipe.hostT,+ onPeerPending: (s) => {+ hostSas = s.sas()+ },+ onOpen: () => {},+ onClose: () => {}+ })+ const client = connectRelayClient({+ url: 'ws://127.0.0.1/x',+ token: 't',+ hostKeyB64: publicKeyToB64(hostKeys.publicKey),+ ourKeys: genKeyPair(),+ transport: pipe.clientT,+ onSas: () => {},+ onApproved: () => {},+ onFrame: () => {},+ onPtyData: () => {},+ onClose: () => {}+ })+ await vi.waitFor(() => expect(hostSas).not.toBeNull())+ expect(hostSas).toMatch(/^\d{3} \d{3} \d{4}$/)+ expect(client.sas()).toBe(hostSas)+ })+})diff --git a/src/core/relay/relay-socket.ts b/src/core/relay/relay-socket.tsindex 227be28f4..ee3a4fe29 100644--- a/src/core/relay/relay-socket.ts+++ b/src/core/relay/relay-socket.ts@@ -31,6 +31,7 @@// production passes a `ws` WebSocket wrapped via `wrapWebSocket`.import {+ canonicalB64ToBytes,decrypt,deriveSessionKey,deriveSharedKey,@@ -148,10 +149,13 @@ type HandshakeControl =function nonceToB64(n: Uint8Array): string {return Buffer.from(n).toString('base64')}+// Canonical base64 only (e2ee.ts canonicalB64ToBytes): a nonce with junk around it is not a nonce.function nonceFromB64(b64: unknown): Uint8Array | null {- if (typeof b64 !== 'string') return null- const n = Uint8Array.from(Buffer.from(b64, 'base64'))- return n.length === 16 ? n : null+ try {+ return canonicalB64ToBytes(b64, 16, 'session nonce')+ } catch {+ return null+ }}type State = 'connecting' | 'handshaking' | 'ready' | 'closed'@@ -163,6 +167,11 @@ export function connectRelay(opts: ConnectRelayOptions): RelaySocket {if (opts.role === 'client' && !opts.theirPubB64) {throw new Error('connectRelay: client role requires theirPubB64 (the host public key)')}+ // A client derives its identity key from the PINNED host key before anything is opened: a key+ // that is not canonical base64, or is a low-order point (WeakPeerKeyError — a public-constant+ // shared secret), throws HERE, so no socket is dialed for a session that could never be private.+ const clientBaseKey =+ opts.role === 'client' ? deriveSharedKey(opts.theirPubB64!, opts.ourKeys.secretKey) : nulllet transport: RelayTransport | null = null// baseKey = the stable ECDH precompute (for the SAS, which represents the pinned identity).@@ -233,7 +242,7 @@ export function connectRelay(opts: ConnectRelayOptions): RelaySocket {if (opts.role === 'client') {// Client knows the host pubkey: derive the base (identity) key now and greet with our// session nonce. The traffic key is derived once the host's nonce arrives in e2ee_ready.- baseKey = deriveSharedKey(opts.theirPubB64!, opts.ourKeys.secretKey)+ baseKey = clientBaseKeysendControl({type: 'e2ee_hello',publicKeyB64: publicKeyToB64(opts.ourKeys.publicKey),@@ -376,8 +385,23 @@ export function connectRelay(opts: ConnectRelayOptions): RelaySocket {if (typeof control.publicKeyB64 !== 'string' || !clientNonce || !ourNonce) {return}+ // Refuse a key that is not canonical base64 or is a LOW-ORDER point (WeakPeerKeyError): with+ // the latter the shared secret is a public constant — a secret-less peer would complete the+ // handshake, both humans would read the same fixed SAS, and anyone on the wire could derive+ // the session key. FAIL CLOSED: no key is learned or bound (peerPubB64 is set only after a+ // successful derive, so nothing can pin or auto-approve the refused key), no `e2ee_ready` is+ // sent, and the transport is closed so the caller's onClose runs its usual teardown. Never a+ // throw here: this runs inside the WebSocket's synchronous message emit.+ let derived: Uint8Array+ try {+ derived = deriveSharedKey(control.publicKeyB64, opts.ourKeys.secretKey)+ } catch (err) {+ console.warn(`[relay] refused a peer handshake key: ${err instanceof Error ? err.message : String(err)}`)+ transport?.close()+ return+ }peerPubB64 = control.publicKeyB64- baseKey = deriveSharedKey(control.publicKeyB64, opts.ourKeys.secretKey)+ baseKey = derived// salt = hostNonce ‖ clientNonce (host's nonce first, both roles agree on the order).sessionKey = deriveSessionKey(baseKey, ourNonce, clientNonce)sendControl({ type: 'e2ee_ready', nonceB64: nonceToB64(ourNonce) })diff --git a/src/core/relay/relay-trust.ts b/src/core/relay/relay-trust.tsindex af93b85c1..3ee083ade 100644--- a/src/core/relay/relay-trust.ts+++ b/src/core/relay/relay-trust.ts@@ -2,7 +2,7 @@//// Stage 4 makes two desktops equal peers, which means a pairing GRANTS THE PEER SHELL ACCESS on this// machine. The only thing standing between a relay man-in-the-middle and that shell is mutual-// approval: BOTH humans compare the same 6-digit SAS out of band and BOTH press Confirm. The pure+// approval: BOTH humans compare the same SAS out of band and BOTH press Confirm. The pure// latch is `mutual-approval-core.ts`; this file is the wiring it says it cannot enforce, and the// wiring is where the property can be silently destroyed.//@@ -70,7 +70,7 @@ export interface PinStore {}export interface TrustGate {- /** SAS both humans compare ("NNN NNN"), or null before the key is derived. */+ /** SAS both humans compare ("NNN NNN NNNN", v2), or null before the key is derived. */sas(): string | null/** This human pressed Confirm. Latches localConfirmed and tells the peer over the tunnel. */confirmHere(): voiddiff --git a/src/core/relay/team-admin.test.ts b/src/core/relay/team-admin.test.tsindex 18cd685dc..5a672b2b0 100644--- a/src/core/relay/team-admin.test.ts+++ b/src/core/relay/team-admin.test.ts@@ -23,6 +23,7 @@ import {} from './team-admin'import { createHostKey } from './host-key'import { genKeyPair, publicKeyToB64 } from './e2ee'+import { lowOrderKeysB64 } from './low-order-keys.test-support'import type { HostedService, HostedStatus } from './hosted-service'// A unix socket path is limited to ~107 bytes, and a long mkdtemp path (macOS's /var/folders/…)@@ -148,6 +149,12 @@ describe('validation helpers (platform-neutral)', () => {expect(ownerKeyProblem(k.replace(/=$/, ''))).toMatch(/canonical/)expect(ownerKeyProblem(` ${k}`)).toMatch(/canonical/)expect(ownerKeyProblem(k.replace(/\+/g, '-').replace(/\//g, '_').replace(/=$/, ''))).not.toBeNull()+ // Junk Node's decoder would skip still decodes to the key, but is not its spelling.+ expect(ownerKeyProblem('!!!' + k)).not.toBeNull()+ })++ it('refuses a low-order key (the relay handshake refuses it: no device holds its secret)', () => {+ for (const weak of lowOrderKeysB64()) expect(ownerKeyProblem(weak), weak).toMatch(/low-order/)})it('labels are at most 60 characters and control-free', () => {diff --git a/src/core/relay/team-admin.ts b/src/core/relay/team-admin.tsindex 8078797a7..71ed445ea 100644--- a/src/core/relay/team-admin.ts+++ b/src/core/relay/team-admin.ts@@ -19,7 +19,7 @@ import { chmodSync, lstatSync, rmSync } from 'node:fs'import { ensurePrivateDir } from './private-dir'import { TeamStore, TEAM_LABEL_MAX, TEAM_PROJECT_ID_MAX } from './team-store'import { loadHostKey } from './host-key'-import { publicKeyFromB64, publicKeyToB64 } from './e2ee'+import { isLowOrderPublicKey, publicKeyToB64 } from './e2ee'import { ADMIN_ERROR_CODE_RE, adminErrorCode } from './admin-error'import { runBootstrap } from './team-bootstrap'import { parseResumeSessions, type ResumeEntry, type ResumeResult } from '../../shared/share-team'@@ -149,14 +149,11 @@ export function socketPathProblem(sock: string, platform: NodeJS.Platform = proc* (missing padding, stray whitespace — Node's base64 decoder skips both) would be written to the* team and never match anyone. */export function ownerKeyProblem(key: string): string | null {- let bytes: Uint8Array- try {- bytes = publicKeyFromB64(key)- } catch {- const got = Buffer.from(key, 'base64').length+ const bytes = Buffer.from(key, 'base64')+ if (bytes.length !== 32) {return (`That is not a device key: a device key is 32 bytes of base64 (44 characters ending in "="), ` +- `and this decodes to ${got} bytes. Check that the whole key was copied.`+ `and this decodes to ${bytes.length} bytes. Check that the whole key was copied.`)}if (publicKeyToB64(bytes) !== key) {@@ -165,6 +162,12 @@ export function ownerKeyProblem(key: string): string | null {'spaces, or "-"/"_" in place of "+"/"/".')}+ // A low-order X25519 point: no device holds a secret for it, and the relay handshake refuses it+ // (its shared secret is a public constant). Writing it to team.json would name a member nobody+ // could ever be — or, before that refusal existed, everybody.+ if (isLowOrderPublicKey(Uint8Array.from(bytes))) {+ return 'That is not a usable device key: it is a low-order X25519 point, which the relay refuses.'+ }return null}diff --git a/src/main/remote/approved-devices-core.test.ts b/src/main/remote/approved-devices-core.test.tsindex 1deec9f27..e2a4e9277 100644--- a/src/main/remote/approved-devices-core.test.ts+++ b/src/main/remote/approved-devices-core.test.ts@@ -6,6 +6,7 @@ import {pinDevice,unpinDevice} from './approved-devices-core'+import { lowOrderKeysB64 } from '../../core/relay/low-order-keys.test-support'describe('approved-devices-core', () => {describe('parseApprovedDevices', () => {@@ -58,4 +59,15 @@ describe('approved-devices-core', () => {expect(unpinDevice(store, 'zzz')).toBe(store)})})++ describe('low-order keys (a public-constant shared secret: no device holds one)', () => {+ it('are never pinned, and never count as pinned even when the file holds one', () => {+ for (const weak of lowOrderKeysB64()) {+ expect(pinDevice(emptyApprovedDevices(), weak), weak).toEqual({ pubkeys: [] })+ expect(isPinned({ pubkeys: [weak] }, weak), weak).toBe(false)+ // Another spelling Node decodes to the same key is refused too.+ expect(isPinned({ pubkeys: ['!' + weak] }, '!' + weak)).toBe(false)+ }+ })+ })})diff --git a/src/main/remote/hosted-join.test.ts b/src/main/remote/hosted-join.test.tsindex cef89fb95..3360bf289 100644--- a/src/main/remote/hosted-join.test.ts+++ b/src/main/remote/hosted-join.test.ts@@ -176,9 +176,10 @@ describe('joinHostedTeam', () => {expect((await s.store.list())[0].approvedAt).toBe('2026-09-01T00:00:00Z')})- it('a known hostId whose code now carries a different key string never auto-approves, and its token is not reused', async () => {- // A non-canonical base64 spelling of the same 32 bytes: same hostId, different key string. The- // rule compares the key the code carries with the key the bookmark was approved for, exactly.+ it('a known hostId whose code carries a second spelling of the key is refused outright: nothing minted, nothing touched', async () => {+ // A non-canonical base64 spelling of the same 32 bytes: same hostId, different key string. It+ // used to reach the join (no auto-approve, a fresh token); the decoder now accepts one spelling+ // per key, so the code is invalid before any token is minted or any bookmark is touched.// 32 bytes encode as 43 characters + '=', and the last of those carries 2 unused low bits.const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'const k = code.hostPublicKeyB64@@ -186,10 +187,12 @@ describe('joinHostedTeam', () => {expect(hostIdFromPublicKeyB64(alt)).toBe(code.hostId)expect(alt).not.toBe(k)const s = setup({ bookmarks: [bookmark({ approvedAt: '2026-09-01T00:00:00Z' })] })- await joinHostedTeam(encodeJoinCode({ ...code, hostPublicKeyB64: alt }), s.deps, events().ev)- expect(s.c.last().autoApprove).toBe(false)- expect(s.api.count('device')).toBe(1)- expect((await s.store.list())[0]).toMatchObject({ deviceToken: 'DT', approvedAt: null })+ await expect(joinHostedTeam(encodeJoinCode({ ...code, hostPublicKeyB64: alt }), s.deps, events().ev)).rejects.toThrow(+ /E_JOIN_BAD_CODE/+ )+ expect(s.c.sessions).toHaveLength(0)+ expect(s.api.calls).toEqual([])+ expect((await s.store.list())[0]).toMatchObject({ approvedAt: '2026-09-01T00:00:00Z' })})it('a bookmark whose stored code no longer decodes is not trusted either', async () => {diff --git a/src/main/remote/mutual-approval-core.test.ts b/src/main/remote/mutual-approval-core.test.tsindex 07ffc18b6..2b389488f 100644--- a/src/main/remote/mutual-approval-core.test.ts+++ b/src/main/remote/mutual-approval-core.test.ts@@ -11,7 +11,7 @@ import { genKeyPair, deriveSharedKey, publicKeyToB64 } from './e2ee'import { isPinned } from './approved-devices-core'describe('mutual SAS agreement', () => {- it('both ends derive the SAME 6-digit code from their shared key', () => {+ it('both ends derive the SAME 10-digit code from their shared key', () => {const host = genKeyPair()const client = genKeyPair()const hostShared = deriveSharedKey(publicKeyToB64(client.publicKey), host.secretKey)@@ -19,7 +19,7 @@ describe('mutual SAS agreement', () => {const a = mutualSas(hostShared)const b = mutualSas(clientShared)expect(a).toBe(b)- expect(a).toMatch(/^\d{3} \d{3}$/)+ expect(a).toMatch(/^\d{3} \d{3} \d{4}$/)})it('a man-in-the-middle (different shared key) shows a DIFFERENT code', () => {diff --git a/src/main/remote/pairing.test.ts b/src/main/remote/pairing.test.tsnew file mode 100644index 000000000..d1267d8ee--- /dev/null+++ b/src/main/remote/pairing.test.ts@@ -0,0 +1,32 @@+// The `nodeterm://pair` offer is what a Team Access client PINS as the host's key: decodeOffer is an+// intake for that key, so it must refuse what the handshake would refuse — a low-order point (a+// public-constant shared secret) and a string that only decodes to a key (non-canonical base64).+import { describe, expect, it } from 'vitest'+import { decodeOffer, encodeOffer } from './pairing'+import { genKeyPair, publicKeyToB64 } from './e2ee'+import { lowOrderKeysB64 } from '../../core/relay/low-order-keys.test-support'++const hostKey = publicKeyToB64(genKeyPair().publicKey)+const good = { relayEndpoint: 'wss://relay.nodeterm.dev', pairingToken: 'tok', hostPublicKeyB64: hostKey }++describe('decodeOffer', () => {+ it('round-trips a real offer', () => {+ expect(decodeOffer(encodeOffer(good))).toEqual(good)+ })++ it('refuses a low-order host key', () => {+ for (const weak of lowOrderKeysB64()) {+ expect(decodeOffer(encodeOffer({ ...good, hostPublicKeyB64: weak })), weak).toBeNull()+ }+ })++ it('refuses a host key in non-canonical base64', () => {+ for (const twin of ['!!!@@@' + hostKey, hostKey + '====junk', hostKey.replace(/=$/, ''), ' ' + hostKey]) {+ expect(decodeOffer(encodeOffer({ ...good, hostPublicKeyB64: twin })), twin).toBeNull()+ }+ })++ it('still refuses a plaintext relay to another machine', () => {+ expect(decodeOffer(encodeOffer({ ...good, relayEndpoint: 'ws://evil.example' }))).toBeNull()+ })+})diff --git a/src/main/remote/pairing.ts b/src/main/remote/pairing.tsindex cfa561254..9c44b3458 100644--- a/src/main/remote/pairing.ts+++ b/src/main/remote/pairing.ts@@ -4,6 +4,8 @@// Electron, and no zod — validation is hand-rolled so decode never throws// (returns null instead).+import { isUsablePeerKeyB64 } from '../../core/relay/e2ee'+export type PairingOffer = {// The relay WebSocket endpoint the client connects to.relayEndpoint: string@@ -95,6 +97,8 @@ function isPairingOffer(value: unknown): value is PairingOffer {typeof o.pairingToken === 'string' &&o.pairingToken.length > 0 &&typeof o.hostPublicKeyB64 === 'string' &&- o.hostPublicKeyB64.length > 0+ // The client PINS this key: canonical base64 only, and never a low-order point (its shared+ // secret is a public constant, so the SAS would be a fixed value both humans "match").+ isUsablePeerKeyB64(o.hostPublicKeyB64))}diff --git a/src/main/remote/relay-client.test.ts b/src/main/remote/relay-client.test.tsindex 907d10581..6669bc5a0 100644--- a/src/main/remote/relay-client.test.ts+++ b/src/main/remote/relay-client.test.ts@@ -217,9 +217,9 @@ afterEach(() => {})describe('relay client — SAS + mutual approval', () => {- it('both ends derive the SAME 6-digit SAS from this session', () => {+ it('both ends derive the SAME 10-digit SAS from this session', () => {const p = pairHostAndClient()- expect(p.clientSas()).toMatch(/^\d{3} \d{3}$/)+ expect(p.clientSas()).toMatch(/^\d{3} \d{3} \d{4}$/)expect(p.clientSas()).toBe(p.host.sas())})diff --git a/src/main/remote/relay-host-service.test.ts b/src/main/remote/relay-host-service.test.tsindex a863b5334..b7fa1d970 100644--- a/src/main/remote/relay-host-service.test.ts+++ b/src/main/remote/relay-host-service.test.ts@@ -310,7 +310,7 @@ describe('initRelayHost — nothing is served before mutual approval', () => {const pending = pendingSent()expect(pending).toBeTruthy()- expect(pending!.sas).toMatch(/^\d{3} \d{3}$/)+ expect(pending!.sas).toMatch(/^\d{3} \d{3} \d{4}$/)expect(pending!.peerKeyB64).toBe(host.peerKeyB64)// No client, no presence, no open before the human confirms.expect(peerRegistry().ids()).toEqual([])diff --git a/src/main/remote/relay-host.test.ts b/src/main/remote/relay-host.test.tsindex bbb7338f4..03f4cb407 100644--- a/src/main/remote/relay-host.test.ts+++ b/src/main/remote/relay-host.test.ts@@ -577,7 +577,7 @@ describe('relay host — nothing is served before mutual approval', () => {})const s = openHostAgainstFakeRelay() // E2EE is up, approval is NOT givenexpect(s.pending).toHaveLength(1) // the SAS is known: ask the human- expect(s.session.sas()).toMatch(/^\d{3} \d{3}$/)+ expect(s.session.sas()).toMatch(/^\d{3} \d{3} \d{4}$/)s.peerSendsTunnelText(JSON.stringify({ t: 'req', id: 1, method: 'pty:create', args: [{ cols: 80, rows: 24 }] })diff --git a/src/main/remote/relay-socket.test.ts b/src/main/remote/relay-socket.test.tsindex 29cd56a8a..1650b9c32 100644--- a/src/main/remote/relay-socket.test.ts+++ b/src/main/remote/relay-socket.test.ts@@ -136,7 +136,7 @@ describe('relay-socket: a handshake control frame after the session is READY isconst sasBefore = host.sas()const peerBefore = host.peerPublicKeyB64()expect(peerBefore).toBe(publicKeyToB64(clientKeys.publicKey)) // the REAL peer- expect(sasBefore).toMatch(/^\d{3} \d{3}$/)+ expect(sasBefore).toMatch(/^\d{3} \d{3} \d{4}$/)// The MITM injects a fresh, well-formed e2ee_hello carrying the ATTACKER's keypair. On the// vulnerable code this re-derives baseKey/sessionKey and overwrites peerPubB64.@@ -169,7 +169,7 @@ describe('relay-socket: a handshake control frame after the session is READY isit('the genuine single handshake is unaffected (both ends reach ready and agree on the SAS)', () => {const { host, client } = readyPair()- expect(host.sas()).toMatch(/^\d{3} \d{3}$/)+ expect(host.sas()).toMatch(/^\d{3} \d{3} \d{4}$/)expect(host.sas()).toBe(client.sas())})})diff --git a/src/main/remote/relay-trust.test.ts b/src/main/remote/relay-trust.test.tsindex 772e3cdd3..3104b6658 100644--- a/src/main/remote/relay-trust.test.ts+++ b/src/main/remote/relay-trust.test.ts@@ -215,7 +215,7 @@ describe('obligation (a): only the encrypted tunnel can confirm the peer', () =>it('both ends see the same SAS (the digits the humans compare)', () => {const { hostGate, peerGate } = bridgedPair()- expect(hostGate.sas()).toMatch(/^\d{3} \d{3}$/)+ expect(hostGate.sas()).toMatch(/^\d{3} \d{3} \d{4}$/)expect(hostGate.sas()).toBe(peerGate.sas())})diff --git a/src/main/remote/remote-security.test.ts b/src/main/remote/remote-security.test.tsindex 623a1a0de..bc37f3021 100644--- a/src/main/remote/remote-security.test.ts+++ b/src/main/remote/remote-security.test.ts@@ -136,7 +136,7 @@ describe('projects.list serves the host projects blob', () => {// --- R2: SAS determinism -----------------------------------------------------describe('R2: channel SAS', () => {- it('is identical for both peers and stable, formatted NNN NNN', () => {+ it('is identical for both peers and stable, formatted NNN NNN NNNN', () => {const host = genKeyPair()const client = genKeyPair()const hostShared = deriveSharedKey(publicKeyToB64(client.publicKey), host.secretKey)@@ -144,7 +144,7 @@ describe('R2: channel SAS', () => {const a = sasFromSharedKey(hostShared)const b = sasFromSharedKey(clientShared)expect(a).toBe(b)- expect(a).toMatch(/^\d{3} \d{3}$/)+ expect(a).toMatch(/^\d{3} \d{3} \d{4}$/)expect(sasFromSharedKey(hostShared)).toBe(a) // deterministic})})diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex e52601d1b..395c6e188 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -283,6 +283,8 @@ import { SetupConsentDialog } from '../components/SetupConsentDialog'import { ConsentNotice } from '../remote/ConsentNotice'import { approvePhoneWithFeedback } from '../lib/phone-approval'import { peerApprovalView } from '@shared/remote/approval'+import { admitPendingPeer } from '../lib/pendingPeerAdmission'+import { SAS_COMPARE_HINT } from '@shared/remote/sas'import { promptDialog } from '../components/promptDialog'import { UpgradeDialog } from '../components/UpgradeDialog'import { LiveLinkDialog } from '../components/LiveLinkDialog'@@ -1163,6 +1165,8 @@ interface PendingPeerState {/** The peer's stable box key (phone source): survives the phone's reconnect churn where the* per-attach id does not, so a mid-retry Approve still lands. */pub?: string | null+ /** The peer's stable box key (relay source). With `pub`, what `admitPendingPeer` compares. */+ peerKeyB64?: string}/**@@ -2283,10 +2287,33 @@ export function Canvas() {confirmFlags.current.merge = !!vsetMergeTargetState(v)}, [])+ // The dialog's current request, read synchronously by `offerPendingPeer` (a state value would be+ // a render behind when two handshakes land in one tick). Written ONLY by setPendingPeer.+ const pendingPeerRef = useRef<PendingPeerState | null>(null)const setPendingPeer = useCallback((v: PendingPeerState | null) => {+ pendingPeerRef.current = vconfirmFlags.current.peer = !!vsetPendingPeerState(v)}, [])+ /**+ * A device finished its handshake and asks for the SAS dialog. The dialog has ONE slot, and a+ * different device must never swap its digits under the human comparing them (a click meant for+ * one device would approve another): `admitPendingPeer` refuses it, fail closed. A refused phone+ * is rejected explicitly (it retries, and is asked once this dialog is answered); a relay peer has+ * no reject, so it is simply never confirmed. The same device re-raising replaces in place.+ */+ const offerPendingPeer = useCallback(+ (next: PendingPeerState) => {+ const verdict = admitPendingPeer(pendingPeerRef.current, next)+ if (verdict === 'refuse') {+ console.warn(`[remote] a second device asked for approval while one is open; refused (${next.source})`)+ if (next.source === 'phone') window.nodeTerminal.remoteHost.reject(next.id, next.pub ?? undefined)+ return+ }+ setPendingPeer(next)+ },+ [setPendingPeer]+ )const setCloseTarget = useCallback((v: { id: string; name: string; count: number; end: boolean } | null) => {confirmFlags.current.closeProject = !!vsetCloseTargetState(v)@@ -4298,9 +4325,9 @@ export function Canvas() {// migration is complete. Standing phone consent has a request/reply persistence outcome.useEffect(() => {return window.nodeTerminal.relayHost.onPeerPending((info) =>- setPendingPeer({ ...info, source: 'relay' })+ offerPendingPeer({ ...info, source: 'relay' }))- }, [setPendingPeer])+ }, [offerPendingPeer])// The LEGACY phone host feeds the SAME dialog (issue #372): when the SAS prompt migrated to// the relayHost tunnel, the phone — still on the legacy dialect — lost its prompt entirely:@@ -4311,20 +4338,17 @@ export function Canvas() {// host-side expiry drops the dialog rather than leaving Approve aimed at a dead id.useEffect(() => {const unPending = window.nodeTerminal.remoteHost.onPeerPending((info) =>- setPendingPeer({ ...info, source: 'phone', label: 'Your phone' })+ offerPendingPeer({ ...info, source: 'phone', label: 'Your phone' }))const unCleared = window.nodeTerminal.remoteHost.onPeerPendingCleared((info) => {- setPendingPeerState((cur) => {- const next = cur && cur.source === 'phone' && cur.id === info.id ? null : cur- confirmFlags.current.peer = !!next- return next- })+ const cur = pendingPeerRef.current+ if (cur && cur.source === 'phone' && cur.id === info.id) setPendingPeer(null)})return () => {unPending()unCleared()}- }, [setPendingPeer])+ }, [offerPendingPeer, setPendingPeer])// Team Access seat table (docs/…/team-access, Task 3): a SEPARATE relay-host subscription set from// the SAS-approval effect above — one feeds the dialog, this one feeds the live/pending seats store.@@ -5763,8 +5787,8 @@ export function Canvas() {// A hosted team's owner is not at a host screen: they read the same code in their approval// dialog, so the joiner reads it to them (a call, a chat).const question = hosted- ? `Read this code to an owner of ${label || 'the team'} (call or chat) — they see the same code before approving this device:\n\n${sas}`- : `Verify this code matches the one shown on the host:\n\n${sas}`+ ? `Read this code to an owner of ${label || 'the team'} (call or chat) — they see the same code before approving this device:\n\n${sas}\n\n${SAS_COMPARE_HINT}`+ : `Verify this code matches the one shown on the host:\n\n${sas}\n\n${SAS_COMPARE_HINT}`if (sas && window.confirm(question)) {window.nodeTerminal.relayClient.confirm(connectionId)// Nothing left for this user to do: the owner's wait starts now (the joiner says so).diff --git a/src/renderer/canvas/sas-approval.source.test.ts b/src/renderer/canvas/sas-approval.source.test.tsnew file mode 100644index 000000000..690b46ed3--- /dev/null+++ b/src/renderer/canvas/sas-approval.source.test.ts@@ -0,0 +1,46 @@+import { describe, expect, it } from 'vitest'+import { readFileSync } from 'node:fs'++/**+ * STRUCTURAL pins for the SAS approval glue in Canvas.tsx (no render harness for a 20,000-line+ * component). The behaviour is proven elsewhere: the admission rule in+ * `lib/pendingPeerAdmission.test.ts`, the dialog copy in `shared/remote/approval.test.ts`. What only+ * a source read can pin is that Canvas USES them:+ * - both sources of a host approval (the relay tunnel and the legacy phone host) go through+ * `offerPendingPeer`, so a second device can never swap the digits under the human comparing+ * the first device's code;+ * - the joiner's own prompt carries SAS_COMPARE_HINT under the code, on both branches.+ */+const src = readFileSync(new URL('./Canvas.tsx', import.meta.url), 'utf8').replace(/\r\n/g, '\n')++function between(start: string, end: string): string {+ const a = src.indexOf(start)+ expect(a, start).toBeGreaterThan(-1)+ const b = src.indexOf(end, a + start.length)+ expect(b, end).toBeGreaterThan(a)+ return src.slice(a, b)+}++describe('SAS approval glue in Canvas', () => {+ it('every pending-peer subscription offers through the admission rule, never straight into the slot', () => {+ for (const sub of ['relayHost.onPeerPending((info) =>', 'remoteHost.onPeerPending((info) =>']) {+ const body = between(sub, ')\n')+ expect(body, sub).toContain('offerPendingPeer(')+ expect(body, sub).not.toContain('setPendingPeer(')+ }+ const offer = between('const offerPendingPeer = useCallback(', '[setPendingPeer]')+ expect(offer).toContain('admitPendingPeer(pendingPeerRef.current, next)')+ expect(offer).toMatch(/verdict === 'refuse'[\s\S]*remoteHost\.reject\(next\.id/)+ })++ it('the ref the rule reads is written by the one setter', () => {+ const setter = between('const setPendingPeer = useCallback(', '}, [])')+ expect(setter).toContain('pendingPeerRef.current = v')+ expect(src.match(/pendingPeerRef\.current = /g)).toHaveLength(1)+ })++ it('the joiner prompt shows the comparison rule under the code on both branches', () => {+ const body = between('const question = hosted', 'if (sas && window.confirm(question))')+ expect(body.match(/\$\{sas\}\\n\\n\$\{SAS_COMPARE_HINT\}/g)).toHaveLength(2)+ })+})diff --git a/src/renderer/components/HostedApprovalDialog.test.tsx b/src/renderer/components/HostedApprovalDialog.test.tsxindex f7ec492ba..964b87b35 100644--- a/src/renderer/components/HostedApprovalDialog.test.tsx+++ b/src/renderer/components/HostedApprovalDialog.test.tsx@@ -11,6 +11,7 @@ import { createRoot, type Root } from 'react-dom/client'import { HostedApprovalDialog } from './HostedApprovalDialog'import { CONFIRM_ARM_MS } from './confirm-key'import { openDialogCount, pushDialog, popDialog, resetDialogStack } from './dialog-stack'+import { SAS_COMPARE_HINT } from '@shared/remote/sas';(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true@@ -30,7 +31,7 @@ afterEach(() => {const pending = (over: Partial<{ pendingId: string; sas: string; peerKeyB64: string; since: number }> = {}) => ({pendingId: 'p',- sas: '123 456',+ sas: '123 456 7890',peerKeyB64: 'AAAABBBBCCCC',since: 0,...over@@ -58,7 +59,10 @@ const key = (target: EventTarget, init: KeyboardEventInit) => {describe('HostedApprovalDialog', () => {it('defaults to Viewer, shows SAS + fingerprint, and approves with the chosen role', () => {const { onApprove } = mount()- expect(byText('123 456')).toBeTruthy()+ expect(byText('123 456 7890')).toBeTruthy()+ // The ten-digit code carries the comparison rule under it (an older joiner shows six digits).+ expect(text()).toContain(SAS_COMPARE_HINT)+ expect(text().indexOf('123 456 7890')).toBeLessThan(text().indexOf(SAS_COMPARE_HINT))expect(text()).toMatch(/AAAA·BBBB/)expect(roleSelect().value).toBe('viewer')act(() => {diff --git a/src/renderer/components/HostedApprovalDialog.tsx b/src/renderer/components/HostedApprovalDialog.tsxindex 9808769c9..123a0af9a 100644--- a/src/renderer/components/HostedApprovalDialog.tsx+++ b/src/renderer/components/HostedApprovalDialog.tsx@@ -16,6 +16,7 @@ import type { HostedPending, HostedRole } from '@shared/types'import { keyFingerprint } from '../lib/hostedTeam'import { CONFIRM_ARM_MS } from './confirm-key'import { useDialogStack } from './dialog-stack'+import { SAS_COMPARE_HINT } from '@shared/remote/sas'// What each role can reach, stated at its fullest: an owner decides from this line alone. A Viewer// reads every file in the shared folder (the access policy jails reads to the folder, not to what@@ -74,6 +75,8 @@ export function HostedApprovalDialog(props: {<strong>A device wants to join {team}</strong>{'\n\n'}Compare this code with the person joining (call or chat) before allowing:{'\n\n'}<strong>{pending.sas}</strong>+ {'\n'}+ {SAS_COMPARE_HINT}{'\n\n'}Device key {keyFingerprint(pending.peerKeyB64)}{more > 0 ? `\n\n${more} more ${more === 1 ? 'request is' : 'requests are'} waiting.` : ''}{'\n\n'}Role:diff --git a/src/renderer/lib/pendingPeerAdmission.test.ts b/src/renderer/lib/pendingPeerAdmission.test.tsnew file mode 100644index 000000000..0e5d08e7b--- /dev/null+++ b/src/renderer/lib/pendingPeerAdmission.test.ts@@ -0,0 +1,33 @@+import { describe, expect, it } from 'vitest'+import { admitPendingPeer } from './pendingPeerAdmission'++describe('admitPendingPeer — one SAS dialog, never swapped under the human', () => {+ it('shows a request when no dialog is open', () => {+ expect(admitPendingPeer(null, { source: 'phone', id: 'a', pub: 'K1' })).toBe('show')+ expect(admitPendingPeer(null, { source: 'relay', id: 'seat-1', peerKeyB64: 'K1' })).toBe('show')+ })++ it("replaces in place when the SAME phone re-raises with a fresh id (issue #372's retry churn)", () => {+ expect(admitPendingPeer({ source: 'phone', id: 'a', pub: 'K1' }, { source: 'phone', id: 'b', pub: 'K1' })).toBe('replace')+ })++ it('refuses a DIFFERENT phone while one is being compared', () => {+ expect(admitPendingPeer({ source: 'phone', id: 'a', pub: 'K1' }, { source: 'phone', id: 'b', pub: 'K2' })).toBe('refuse')+ })++ it('refuses a relay peer while a phone is being compared, and the other way round', () => {+ expect(admitPendingPeer({ source: 'phone', id: 'a', pub: 'K1' }, { source: 'relay', id: 'a', peerKeyB64: 'K1' })).toBe('refuse')+ expect(admitPendingPeer({ source: 'relay', id: 's', peerKeyB64: 'K1' }, { source: 'phone', id: 's', pub: 'K1' })).toBe('refuse')+ })++ it('keys a relay peer by its peerKeyB64 (a seat re-raise keeps the dialog; another seat is refused)', () => {+ expect(admitPendingPeer({ source: 'relay', id: 's1', peerKeyB64: 'K1' }, { source: 'relay', id: 's1', peerKeyB64: 'K1' })).toBe('replace')+ expect(admitPendingPeer({ source: 'relay', id: 's1', peerKeyB64: 'K1' }, { source: 'relay', id: 's2', peerKeyB64: 'K2' })).toBe('refuse')+ })++ it('without a key on either side, only the exact pending id is the same device', () => {+ expect(admitPendingPeer({ source: 'phone', id: 'a', pub: null }, { source: 'phone', id: 'a', pub: 'K1' })).toBe('replace')+ expect(admitPendingPeer({ source: 'phone', id: 'a', pub: null }, { source: 'phone', id: 'b', pub: null })).toBe('refuse')+ expect(admitPendingPeer({ source: 'relay', id: 's1', peerKeyB64: '' }, { source: 'relay', id: 's2', peerKeyB64: '' })).toBe('refuse')+ })+})diff --git a/src/renderer/lib/pendingPeerAdmission.ts b/src/renderer/lib/pendingPeerAdmission.tsnew file mode 100644index 000000000..9c8f71e64--- /dev/null+++ b/src/renderer/lib/pendingPeerAdmission.ts@@ -0,0 +1,43 @@+// The host's SAS approval dialog has ONE slot (Canvas `pendingPeer`), fed by two sources: the relay+// tunnel (Team Access seats) and the legacy phone host (standing + interactive). A second device+// that finished its handshake while the human was comparing the first device's code used to+// REPLACE the dialog's content — the digits could change under the human between reading them and+// pressing Allow, so a click meant for device A approved device B.+//+// The rule (pure, so it is tested without a Canvas harness):+// - nothing open → 'show';+// - the SAME device re-raised → 'replace' in place. The phone's retry churn re-raises with a+// fresh id but the same key (issue #372), and the dialog must+// follow it or Allow lands on a dead id;+// - a DIFFERENT device → 'refuse'. Fail closed: the open dialog stays exactly as the+// human is reading it. The caller rejects a phone explicitly+// (it retries and is asked once this dialog is answered); a+// relay peer has no reject — it is simply never confirmed.+// "Same device" = same source and same stable key (phone: `pub`; relay: `peerKeyB64`). When either+// side has no key, only the exact pending id counts as the same device.++export interface PendingPeerIdentity {+ source: 'relay' | 'phone'+ id: string+ pub?: string | null+ peerKeyB64?: string | null+}++export type PendingPeerAdmission = 'show' | 'replace' | 'refuse'++function keyOf(p: PendingPeerIdentity): string | null {+ const k = p.source === 'phone' ? p.pub : p.peerKeyB64+ return typeof k === 'string' && k.length > 0 ? k : null+}++export function admitPendingPeer(+ current: PendingPeerIdentity | null,+ incoming: PendingPeerIdentity+): PendingPeerAdmission {+ if (!current) return 'show'+ if (current.source !== incoming.source) return 'refuse'+ const a = keyOf(current)+ const b = keyOf(incoming)+ if (a !== null && b !== null) return a === b ? 'replace' : 'refuse'+ return current.id === incoming.id ? 'replace' : 'refuse'+}diff --git a/src/server/team-cli.test.ts b/src/server/team-cli.test.tsindex 6c863d97e..5ecca5cc3 100644--- a/src/server/team-cli.test.ts+++ b/src/server/team-cli.test.ts@@ -7,6 +7,7 @@ import { startTeamAdmin, adminSocketPath, type AdminStatusResult, type TeamAdminimport { genKeyPair, publicKeyToB64 } from '../core/relay/e2ee'import type { HostedService, HostedStatus } from '../core/relay/hosted-service'import { POP_REFUSED_MESSAGE } from '../core/relay/relay-pop'+import { SAS_COMPARE_HINT } from '../shared/remote/sas'import { BOOTSTRAP_MARKER } from '../core/remote-ssh/share-team-remote'const KEY = publicKeyToB64(genKeyPair().publicKey)@@ -182,9 +183,10 @@ describe('describeStatus', () => {})it('pending join requests are listed by their SAS', () => {- const text = describeStatus(idleStatus({}, { pending: [{ pendingId: 'x', sas: '123 456', peerKeyB64: 'k', since: 0 }] })).join('\n')+ const text = describeStatus(idleStatus({}, { pending: [{ pendingId: 'x', sas: '123 456 7890', peerKeyB64: 'k', since: 0 }] })).join('\n')expect(text).toMatch(/1 join request/)- expect(text).toMatch(/123 456/)+ expect(text).toMatch(/123 456 7890/)+ expect(text).toContain(SAS_COMPARE_HINT)})it('tolerates a reply shape it does not know (an older or newer server)', () => {diff --git a/src/server/team-cli.ts b/src/server/team-cli.tsindex e6d5c6ac6..48668aaf3 100644--- a/src/server/team-cli.ts+++ b/src/server/team-cli.ts@@ -20,6 +20,7 @@ import {} from '../core/relay/team-admin'import { POP_REFUSED_MESSAGE } from '../core/relay/relay-pop'import { parseResumeSessions } from '../shared/share-team'+import { SAS_COMPARE_HINT } from '../shared/remote/sas'// One rule for what never reaches the admin's terminal: the same characters a label may not// contain (C0/C1 controls, DEL, and the text-direction controls). Server-supplied strings can carry@@ -294,6 +295,7 @@ export function describeStatus(result: AdminStatusResult): string[] {if (pending.length > 0) {lines.push(`${plural(pending.length, 'join request')} waiting for an owner (approve from an owner's desktop):`)for (const p of pending) lines.push(` code ${str(p.sas, '?')}`)+ lines.push(` ${SAS_COMPARE_HINT}`)}return lines}diff --git a/src/shared/remote/approval.test.ts b/src/shared/remote/approval.test.tsindex a0aa9549b..a47fa7e36 100644--- a/src/shared/remote/approval.test.ts+++ b/src/shared/remote/approval.test.ts@@ -1,6 +1,7 @@import { describe, it, expect } from 'vitest'import { peerApprovalView } from './approval'import { describeGrant } from './consent'+import { SAS_COMPARE_HINT } from './sas'describe('peerApprovalView', () => {it('names the peer for the consent notice and echoes the SAS + confirm target', () => {@@ -21,4 +22,15 @@ describe('peerApprovalView', () => {expect(view.message).toContain('— — —')expect(view.confirmId).toBe('peer-2')})++ it('says to compare all ten digits, and what six digits on the other device mean', () => {+ const view = peerApprovalView({ id: 'peer-3', sas: '123 456 7890' })+ expect(view.message).toContain('123 456 7890')+ expect(view.message).toContain(SAS_COMPARE_HINT)+ expect(SAS_COMPARE_HINT).toBe(+ 'Compare all ten digits. If the other device shows only six, it runs an older version: compare the first six.'+ )+ // The hint sits under the code, before the deny instruction.+ expect(view.message.indexOf('123 456 7890')).toBeLessThan(view.message.indexOf(SAS_COMPARE_HINT))+ })})diff --git a/src/shared/remote/approval.ts b/src/shared/remote/approval.tsindex 73a9b0906..ea97d07d3 100644--- a/src/shared/remote/approval.ts+++ b/src/shared/remote/approval.ts@@ -4,6 +4,8 @@// (`relayHost.confirm(id)`). Pure + shared so it is unit-testable without a jsdom harness — Canvas// has none — and so the SAS copy lives in one place.+import { SAS_COMPARE_HINT } from './sas'+/** The pending-peer fields this view needs (a superset-friendly shape of `RelayPeerPending`). */export interface PeerApprovalInput {id: string@@ -29,6 +31,7 @@ export function peerApprovalView(peer: PeerApprovalInput): PeerApprovalView {`A device wants to access this machine.\n\n` +`Approve ONLY if you started this connection. The other device shows the same code:\n\n` +` ${peer.sas ?? '— — —'}\n\n` ++ `${SAS_COMPARE_HINT}\n\n` +`If the codes don't match, deny it.`}}diff --git a/src/shared/remote/sas.ts b/src/shared/remote/sas.tsnew file mode 100644index 000000000..d4d3e9942--- /dev/null+++ b/src/shared/remote/sas.ts@@ -0,0 +1,8 @@+// The copy every SAS the desktop shows carries under it. One definition, so no surface can drift.+//+// The SAS is v2 (src/core/relay/e2ee.ts sasFromSharedKey): ten digits, "NNN NNN NNNN". The first six+// ARE the v1 code, so a peer still running an older desktop or phone build (which shows only six)+// is compared on those six. That comparison is weaker (~20 bits instead of ~33): the copy says+// why the other device shows fewer digits, so the human can tell "older version" from "mismatch".+export const SAS_COMPARE_HINT =+ 'Compare all ten digits. If the other device shows only six, it runs an older version: compare the first six.'