Add end-to-end encryption for mobile WebSocket transport
Replace the disabled TLS cert pinning approach with application-layer E2EE using tweetnacl (Curve25519 ECDH + XSalsa20-Poly1305). The WebSocket stays plain ws:// but all RPC traffic is encrypted after a one-round-trip handshake. Desktop: generate persistent Curve25519 keypair, E2EE channel module handles handshake state machine and transparent encrypt/decrypt. Mobile: ephemeral keypair per connection for forward secrecy, expo-crypto PRNG polyfill for Hermes compatibility. Pairing schema updated from v1 (certFingerprint) to v2 (publicKeyB64). Mock server updated with E2EE support. 24 tests covering crypto, channel handshake, and integration. Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
@@ -42,16 +42,16 @@ export function registerMobileHandlers(rpcServer: OrcaRuntimeRpcServer): void {
|
||||
|
||||
const device = registry.addDevice(`Mobile ${new Date().toLocaleDateString()}`)
|
||||
|
||||
// Why: certFingerprint is 'sha256:pending' when TLS is disabled (Phase 1
|
||||
// will add cert pinning on mobile). The mobile app stores it but doesn't
|
||||
// enforce it until TLS is re-enabled.
|
||||
const fingerprint = rpcServer.getTlsFingerprint() ?? 'sha256:pending'
|
||||
const publicKeyB64 = rpcServer.getE2EEPublicKey()
|
||||
if (!publicKeyB64) {
|
||||
return { available: false as const }
|
||||
}
|
||||
|
||||
const url = encodePairingOffer({
|
||||
v: PAIRING_OFFER_VERSION,
|
||||
endpoint,
|
||||
deviceToken: device.token,
|
||||
certFingerprint: fingerprint
|
||||
publicKeyB64
|
||||
})
|
||||
|
||||
const qrDataUrl = await QRCode.toDataURL(url, {
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
// Why: the E2EE keypair enables application-layer encryption between mobile
|
||||
// and desktop over plain ws://. The public key is embedded in the QR pairing
|
||||
// offer so the mobile client can derive a shared secret via ECDH.
|
||||
import { existsSync, readFileSync, writeFileSync, chmodSync } from 'fs'
|
||||
import { join } from 'path'
|
||||
import nacl from 'tweetnacl'
|
||||
|
||||
const KEYPAIR_FILENAME = 'orca-e2ee-keypair.json'
|
||||
const KEYPAIR_VERSION = 1
|
||||
|
||||
type KeypairFile = {
|
||||
v: number
|
||||
publicKeyB64: string
|
||||
secretKeyB64: string
|
||||
}
|
||||
|
||||
export type E2EEKeypair = {
|
||||
publicKey: Uint8Array
|
||||
secretKey: Uint8Array
|
||||
publicKeyB64: string
|
||||
}
|
||||
|
||||
export function loadOrCreateE2EEKeypair(userDataPath: string): E2EEKeypair {
|
||||
const filePath = join(userDataPath, KEYPAIR_FILENAME)
|
||||
|
||||
if (existsSync(filePath)) {
|
||||
try {
|
||||
const raw: KeypairFile = JSON.parse(readFileSync(filePath, 'utf-8'))
|
||||
if (raw.v === KEYPAIR_VERSION && raw.publicKeyB64 && raw.secretKeyB64) {
|
||||
const publicKey = Uint8Array.from(Buffer.from(raw.publicKeyB64, 'base64'))
|
||||
const secretKey = Uint8Array.from(Buffer.from(raw.secretKeyB64, 'base64'))
|
||||
if (publicKey.length === 32 && secretKey.length === 32) {
|
||||
return { publicKey, secretKey, publicKeyB64: raw.publicKeyB64 }
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Malformed file — regenerate below.
|
||||
}
|
||||
}
|
||||
|
||||
const keypair = nacl.box.keyPair()
|
||||
const publicKeyB64 = Buffer.from(keypair.publicKey).toString('base64')
|
||||
const secretKeyB64 = Buffer.from(keypair.secretKey).toString('base64')
|
||||
|
||||
const data: KeypairFile = { v: KEYPAIR_VERSION, publicKeyB64, secretKeyB64 }
|
||||
writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf-8')
|
||||
chmodSync(filePath, 0o600)
|
||||
|
||||
return { publicKey: keypair.publicKey, secretKey: keypair.secretKey, publicKeyB64 }
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import type { WebSocket } from 'ws'
|
||||
import { E2EEChannel, type E2EEChannelOptions } from './e2ee-channel'
|
||||
import { generateKeyPair, deriveSharedKey, encrypt, decrypt } from './e2ee-crypto'
|
||||
|
||||
function publicKeyToBase64(key: Uint8Array): string {
|
||||
return Buffer.from(key).toString('base64')
|
||||
}
|
||||
|
||||
function createMockWs() {
|
||||
const sent: string[] = []
|
||||
return {
|
||||
OPEN: 1 as const,
|
||||
readyState: 1,
|
||||
send: vi.fn((data: string) => sent.push(data)),
|
||||
close: vi.fn(),
|
||||
sent
|
||||
}
|
||||
}
|
||||
|
||||
function setup(overrides?: Partial<E2EEChannelOptions>) {
|
||||
const serverKeys = generateKeyPair()
|
||||
const clientKeys = generateKeyPair()
|
||||
const ws = createMockWs()
|
||||
const onReady = vi.fn()
|
||||
const onError = vi.fn()
|
||||
|
||||
const channel = new E2EEChannel(ws as unknown as WebSocket, {
|
||||
serverSecretKey: serverKeys.secretKey,
|
||||
validateToken: (token) => token === 'valid-token',
|
||||
onReady,
|
||||
onError,
|
||||
...overrides
|
||||
})
|
||||
|
||||
return { channel, ws, serverKeys, clientKeys, onReady, onError }
|
||||
}
|
||||
|
||||
function doHandshake(ctx: ReturnType<typeof setup>) {
|
||||
const hello = JSON.stringify({
|
||||
type: 'e2ee_hello',
|
||||
publicKeyB64: publicKeyToBase64(ctx.clientKeys.publicKey),
|
||||
deviceToken: 'valid-token'
|
||||
})
|
||||
ctx.channel.handleRawMessage(hello)
|
||||
return deriveSharedKey(ctx.clientKeys.secretKey, ctx.serverKeys.publicKey)
|
||||
}
|
||||
|
||||
describe('E2EEChannel', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
describe('handshake', () => {
|
||||
it('completes handshake with valid hello', () => {
|
||||
const ctx = setup()
|
||||
doHandshake(ctx)
|
||||
|
||||
expect(ctx.onReady).toHaveBeenCalledWith(ctx.channel)
|
||||
expect(ctx.onError).not.toHaveBeenCalled()
|
||||
expect(ctx.channel.deviceToken).toBe('valid-token')
|
||||
|
||||
const readyMsg = JSON.parse(ctx.ws.sent[0]!)
|
||||
expect(readyMsg).toEqual({ type: 'e2ee_ready' })
|
||||
})
|
||||
|
||||
it('rejects invalid token', () => {
|
||||
const ctx = setup()
|
||||
ctx.channel.handleRawMessage(
|
||||
JSON.stringify({
|
||||
type: 'e2ee_hello',
|
||||
publicKeyB64: publicKeyToBase64(ctx.clientKeys.publicKey),
|
||||
deviceToken: 'bad-token'
|
||||
})
|
||||
)
|
||||
|
||||
expect(ctx.onError).toHaveBeenCalledWith(4001, 'Unauthorized')
|
||||
expect(ctx.onReady).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects malformed JSON', () => {
|
||||
const ctx = setup()
|
||||
ctx.channel.handleRawMessage('not json')
|
||||
|
||||
expect(ctx.onError).toHaveBeenCalledWith(4001, 'Invalid handshake message')
|
||||
})
|
||||
|
||||
it('rejects missing fields', () => {
|
||||
const ctx = setup()
|
||||
ctx.channel.handleRawMessage(JSON.stringify({ type: 'e2ee_hello' }))
|
||||
|
||||
expect(ctx.onError).toHaveBeenCalledWith(4001, 'Invalid e2ee_hello')
|
||||
})
|
||||
|
||||
it('rejects invalid public key length', () => {
|
||||
const ctx = setup()
|
||||
ctx.channel.handleRawMessage(
|
||||
JSON.stringify({
|
||||
type: 'e2ee_hello',
|
||||
publicKeyB64: Buffer.from('short').toString('base64'),
|
||||
deviceToken: 'valid-token'
|
||||
})
|
||||
)
|
||||
|
||||
expect(ctx.onError).toHaveBeenCalledWith(4001, 'Invalid public key')
|
||||
})
|
||||
|
||||
it('times out if no hello received', () => {
|
||||
const ctx = setup()
|
||||
|
||||
vi.advanceTimersByTime(10_001)
|
||||
|
||||
expect(ctx.onError).toHaveBeenCalledWith(4002, 'E2EE handshake timeout')
|
||||
})
|
||||
|
||||
it('clears timeout after successful handshake', () => {
|
||||
const ctx = setup()
|
||||
doHandshake(ctx)
|
||||
|
||||
vi.advanceTimersByTime(10_001)
|
||||
|
||||
expect(ctx.onError).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('post-handshake messaging', () => {
|
||||
it('decrypts and forwards messages', () => {
|
||||
const ctx = setup()
|
||||
const sharedKey = doHandshake(ctx)
|
||||
const received: string[] = []
|
||||
|
||||
ctx.channel.onMessage((plaintext) => {
|
||||
received.push(plaintext)
|
||||
})
|
||||
|
||||
const request = '{"id":"rpc-1","method":"status.get"}'
|
||||
ctx.channel.handleRawMessage(encrypt(request, sharedKey))
|
||||
|
||||
expect(received).toEqual([request])
|
||||
})
|
||||
|
||||
it('provides encrypted reply function', () => {
|
||||
const ctx = setup()
|
||||
const sharedKey = doHandshake(ctx)
|
||||
|
||||
ctx.channel.onMessage((_plaintext, encryptedReply) => {
|
||||
encryptedReply('{"id":"rpc-1","ok":true}')
|
||||
})
|
||||
|
||||
ctx.channel.handleRawMessage(encrypt('{"id":"rpc-1","method":"status.get"}', sharedKey))
|
||||
|
||||
// The reply (ws.sent[1], after e2ee_ready) should be encrypted
|
||||
const replyEncrypted = ctx.ws.sent[1]!
|
||||
const replyPlain = decrypt(replyEncrypted, sharedKey)
|
||||
expect(replyPlain).toBe('{"id":"rpc-1","ok":true}')
|
||||
})
|
||||
|
||||
it('silently drops messages with wrong key', () => {
|
||||
const ctx = setup()
|
||||
doHandshake(ctx)
|
||||
const received: string[] = []
|
||||
|
||||
ctx.channel.onMessage((plaintext) => {
|
||||
received.push(plaintext)
|
||||
})
|
||||
|
||||
const attackerKey = deriveSharedKey(generateKeyPair().secretKey, generateKeyPair().publicKey)
|
||||
ctx.channel.handleRawMessage(encrypt('attack', attackerKey))
|
||||
|
||||
expect(received).toEqual([])
|
||||
})
|
||||
|
||||
it('closes after too many consecutive decrypt failures', () => {
|
||||
const ctx = setup()
|
||||
doHandshake(ctx)
|
||||
ctx.channel.onMessage(() => {})
|
||||
|
||||
const badKey = deriveSharedKey(generateKeyPair().secretKey, generateKeyPair().publicKey)
|
||||
|
||||
for (let i = 0; i < 4; i++) {
|
||||
ctx.channel.handleRawMessage(encrypt('bad', badKey))
|
||||
}
|
||||
expect(ctx.onError).not.toHaveBeenCalled()
|
||||
|
||||
ctx.channel.handleRawMessage(encrypt('bad', badKey))
|
||||
expect(ctx.onError).toHaveBeenCalledWith(4003, 'Too many decryption failures')
|
||||
})
|
||||
|
||||
it('resets failure count on successful decrypt', () => {
|
||||
const ctx = setup()
|
||||
const sharedKey = doHandshake(ctx)
|
||||
ctx.channel.onMessage(() => {})
|
||||
|
||||
const badKey = deriveSharedKey(generateKeyPair().secretKey, generateKeyPair().publicKey)
|
||||
|
||||
for (let i = 0; i < 4; i++) {
|
||||
ctx.channel.handleRawMessage(encrypt('bad', badKey))
|
||||
}
|
||||
|
||||
// Successful decrypt resets the counter
|
||||
ctx.channel.handleRawMessage(encrypt('good', sharedKey))
|
||||
|
||||
for (let i = 0; i < 4; i++) {
|
||||
ctx.channel.handleRawMessage(encrypt('bad', badKey))
|
||||
}
|
||||
expect(ctx.onError).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('cross-compatibility', () => {
|
||||
it('desktop encrypt is decryptable by desktop decrypt (sanity)', () => {
|
||||
const a = generateKeyPair()
|
||||
const b = generateKeyPair()
|
||||
const sharedA = deriveSharedKey(a.secretKey, b.publicKey)
|
||||
const sharedB = deriveSharedKey(b.secretKey, a.publicKey)
|
||||
|
||||
const msg = '{"method":"terminal.subscribe","params":{"terminal":"t1"}}'
|
||||
const enc = encrypt(msg, sharedA)
|
||||
expect(decrypt(enc, sharedB)).toBe(msg)
|
||||
})
|
||||
})
|
||||
|
||||
describe('destroy', () => {
|
||||
it('clears state and stops forwarding', () => {
|
||||
const ctx = setup()
|
||||
const sharedKey = doHandshake(ctx)
|
||||
const received: string[] = []
|
||||
|
||||
ctx.channel.onMessage((plaintext) => {
|
||||
received.push(plaintext)
|
||||
})
|
||||
|
||||
ctx.channel.destroy()
|
||||
ctx.channel.handleRawMessage(encrypt('after destroy', sharedKey))
|
||||
|
||||
expect(received).toEqual([])
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,145 @@
|
||||
// Why: the E2EE channel sits between the WebSocket transport and the RPC handler.
|
||||
// It owns the handshake state machine and transparent encrypt/decrypt so the RPC
|
||||
// handler only sees plaintext JSON, identical to the Unix socket path.
|
||||
import type { WebSocket } from 'ws'
|
||||
import { deriveSharedKey, encrypt, decrypt } from './e2ee-crypto'
|
||||
|
||||
type ChannelState = 'awaiting_hello' | 'ready'
|
||||
|
||||
const HANDSHAKE_TIMEOUT_MS = 10_000
|
||||
const MAX_CONSECUTIVE_DECRYPT_FAILURES = 5
|
||||
|
||||
type E2EEHello = {
|
||||
type: 'e2ee_hello'
|
||||
publicKeyB64: string
|
||||
deviceToken: string
|
||||
}
|
||||
|
||||
export type E2EEChannelOptions = {
|
||||
serverSecretKey: Uint8Array
|
||||
validateToken: (token: string) => boolean
|
||||
onReady: (channel: E2EEChannel) => void
|
||||
onError: (code: number, reason: string) => void
|
||||
}
|
||||
|
||||
export class E2EEChannel {
|
||||
private state: ChannelState = 'awaiting_hello'
|
||||
private sharedKey: Uint8Array | null = null
|
||||
private consecutiveFailures = 0
|
||||
private handshakeTimer: ReturnType<typeof setTimeout> | null = null
|
||||
private readonly ws: WebSocket
|
||||
private readonly serverSecretKey: Uint8Array
|
||||
private readonly validateToken: (token: string) => boolean
|
||||
private readonly onReady: (channel: E2EEChannel) => void
|
||||
private readonly onError: (code: number, reason: string) => void
|
||||
// Why: the RPC handler is set after the channel is ready, so the channel
|
||||
// can forward decrypted messages. Kept as a callback rather than constructor
|
||||
// param because the handler needs the encrypt function for replies.
|
||||
private messageHandler:
|
||||
| ((plaintext: string, encryptedReply: (response: string) => void) => void)
|
||||
| null = null
|
||||
|
||||
deviceToken: string | null = null
|
||||
|
||||
constructor(ws: WebSocket, options: E2EEChannelOptions) {
|
||||
this.ws = ws
|
||||
this.serverSecretKey = options.serverSecretKey
|
||||
this.validateToken = options.validateToken
|
||||
this.onReady = options.onReady
|
||||
this.onError = options.onError
|
||||
|
||||
this.handshakeTimer = setTimeout(() => {
|
||||
this.onError(4002, 'E2EE handshake timeout')
|
||||
}, HANDSHAKE_TIMEOUT_MS)
|
||||
}
|
||||
|
||||
onMessage(
|
||||
handler: (plaintext: string, encryptedReply: (response: string) => void) => void
|
||||
): void {
|
||||
this.messageHandler = handler
|
||||
}
|
||||
|
||||
handleRawMessage(raw: string): void {
|
||||
if (this.state === 'awaiting_hello') {
|
||||
this.handleHello(raw)
|
||||
return
|
||||
}
|
||||
|
||||
if (!this.sharedKey) {
|
||||
return
|
||||
}
|
||||
|
||||
const plaintext = decrypt(raw, this.sharedKey)
|
||||
if (plaintext === null) {
|
||||
this.consecutiveFailures++
|
||||
if (this.consecutiveFailures >= MAX_CONSECUTIVE_DECRYPT_FAILURES) {
|
||||
this.onError(4003, 'Too many decryption failures')
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
this.consecutiveFailures = 0
|
||||
const encryptedReply = (response: string) => {
|
||||
if (this.ws.readyState === this.ws.OPEN) {
|
||||
this.ws.send(encrypt(response, this.sharedKey!))
|
||||
}
|
||||
}
|
||||
this.messageHandler?.(plaintext, encryptedReply)
|
||||
}
|
||||
|
||||
private handleHello(raw: string): void {
|
||||
let hello: E2EEHello
|
||||
try {
|
||||
hello = JSON.parse(raw) as E2EEHello
|
||||
} catch {
|
||||
this.onError(4001, 'Invalid handshake message')
|
||||
return
|
||||
}
|
||||
|
||||
if (hello.type !== 'e2ee_hello' || !hello.publicKeyB64 || !hello.deviceToken) {
|
||||
this.onError(4001, 'Invalid e2ee_hello')
|
||||
return
|
||||
}
|
||||
|
||||
if (!this.validateToken(hello.deviceToken)) {
|
||||
this.onError(4001, 'Unauthorized')
|
||||
return
|
||||
}
|
||||
|
||||
this.deviceToken = hello.deviceToken
|
||||
|
||||
// Why: derive the shared key from our secret + client's public key.
|
||||
// Both sides compute the same shared secret via ECDH.
|
||||
const clientPublicKey = Uint8Array.from(Buffer.from(hello.publicKeyB64, 'base64'))
|
||||
if (clientPublicKey.length !== 32) {
|
||||
this.onError(4001, 'Invalid public key')
|
||||
return
|
||||
}
|
||||
|
||||
this.sharedKey = deriveSharedKey(this.serverSecretKey, clientPublicKey)
|
||||
this.state = 'ready'
|
||||
|
||||
if (this.handshakeTimer) {
|
||||
clearTimeout(this.handshakeTimer)
|
||||
this.handshakeTimer = null
|
||||
}
|
||||
|
||||
// Why: send e2ee_ready as plaintext — the client needs it to know the
|
||||
// handshake succeeded before it starts encrypting. The first actual
|
||||
// encrypted message from the server will implicitly prove key possession.
|
||||
if (this.ws.readyState === this.ws.OPEN) {
|
||||
this.ws.send(JSON.stringify({ type: 'e2ee_ready' }))
|
||||
}
|
||||
|
||||
this.onReady(this)
|
||||
}
|
||||
|
||||
destroy(): void {
|
||||
if (this.handshakeTimer) {
|
||||
clearTimeout(this.handshakeTimer)
|
||||
this.handshakeTimer = null
|
||||
}
|
||||
this.sharedKey = null
|
||||
this.messageHandler = null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { generateKeyPair, deriveSharedKey, encrypt, decrypt } from './e2ee-crypto'
|
||||
|
||||
describe('e2ee-crypto', () => {
|
||||
it('encrypt/decrypt round-trips with shared key', () => {
|
||||
const server = generateKeyPair()
|
||||
const client = generateKeyPair()
|
||||
|
||||
const serverShared = deriveSharedKey(server.secretKey, client.publicKey)
|
||||
const clientShared = deriveSharedKey(client.secretKey, server.publicKey)
|
||||
|
||||
const message = '{"id":"rpc-1","method":"status.get"}'
|
||||
const encrypted = encrypt(message, clientShared)
|
||||
const decrypted = decrypt(encrypted, serverShared)
|
||||
|
||||
expect(decrypted).toBe(message)
|
||||
})
|
||||
|
||||
it('decrypt returns null with wrong key', () => {
|
||||
const server = generateKeyPair()
|
||||
const client = generateKeyPair()
|
||||
const attacker = generateKeyPair()
|
||||
|
||||
const clientShared = deriveSharedKey(client.secretKey, server.publicKey)
|
||||
const attackerShared = deriveSharedKey(attacker.secretKey, server.publicKey)
|
||||
|
||||
const encrypted = encrypt('secret data', clientShared)
|
||||
expect(decrypt(encrypted, attackerShared)).toBeNull()
|
||||
})
|
||||
|
||||
it('each encryption produces unique ciphertext (random nonce)', () => {
|
||||
const server = generateKeyPair()
|
||||
const client = generateKeyPair()
|
||||
const shared = deriveSharedKey(client.secretKey, server.publicKey)
|
||||
|
||||
const message = 'same message'
|
||||
const a = encrypt(message, shared)
|
||||
const b = encrypt(message, shared)
|
||||
|
||||
expect(a).not.toBe(b)
|
||||
})
|
||||
|
||||
it('handles empty string', () => {
|
||||
const server = generateKeyPair()
|
||||
const client = generateKeyPair()
|
||||
const shared = deriveSharedKey(client.secretKey, server.publicKey)
|
||||
|
||||
const encrypted = encrypt('', shared)
|
||||
expect(decrypt(encrypted, shared)).toBe('')
|
||||
})
|
||||
|
||||
it('handles unicode content', () => {
|
||||
const server = generateKeyPair()
|
||||
const client = generateKeyPair()
|
||||
const shared = deriveSharedKey(client.secretKey, server.publicKey)
|
||||
|
||||
const message = '日本語テスト 🎉 émojis'
|
||||
const encrypted = encrypt(message, shared)
|
||||
expect(decrypt(encrypted, shared)).toBe(message)
|
||||
})
|
||||
|
||||
it('decrypt returns null for truncated data', () => {
|
||||
const shared = deriveSharedKey(generateKeyPair().secretKey, generateKeyPair().publicKey)
|
||||
expect(decrypt('dG9vc2hvcnQ=', shared)).toBeNull()
|
||||
})
|
||||
|
||||
it('decrypt returns null for tampered data', () => {
|
||||
const server = generateKeyPair()
|
||||
const client = generateKeyPair()
|
||||
const shared = deriveSharedKey(client.secretKey, server.publicKey)
|
||||
|
||||
const encrypted = encrypt('hello', shared)
|
||||
const bytes = Buffer.from(encrypted, 'base64')
|
||||
bytes[bytes.length - 1] ^= 0xff
|
||||
const tampered = bytes.toString('base64')
|
||||
|
||||
expect(decrypt(tampered, shared)).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,41 @@
|
||||
// Why: shared E2EE primitives for the desktop side. Wraps tweetnacl to provide
|
||||
// encrypt/decrypt with the NaCl box format: [24-byte nonce][ciphertext], encoded
|
||||
// as base64 for transmission over WebSocket text frames.
|
||||
import nacl from 'tweetnacl'
|
||||
|
||||
export function generateKeyPair(): nacl.BoxKeyPair {
|
||||
return nacl.box.keyPair()
|
||||
}
|
||||
|
||||
export function deriveSharedKey(ourSecretKey: Uint8Array, peerPublicKey: Uint8Array): Uint8Array {
|
||||
return nacl.box.before(peerPublicKey, ourSecretKey)
|
||||
}
|
||||
|
||||
export function encrypt(plaintext: string, sharedKey: Uint8Array): string {
|
||||
const nonce = nacl.randomBytes(nacl.box.nonceLength)
|
||||
const messageBytes = new TextEncoder().encode(plaintext)
|
||||
const ciphertext = nacl.box.after(messageBytes, nonce, sharedKey)
|
||||
|
||||
const bundle = new Uint8Array(nonce.length + ciphertext.length)
|
||||
bundle.set(nonce)
|
||||
bundle.set(ciphertext, nonce.length)
|
||||
|
||||
return Buffer.from(bundle).toString('base64')
|
||||
}
|
||||
|
||||
export function decrypt(encrypted: string, sharedKey: Uint8Array): string | null {
|
||||
const bundle = Uint8Array.from(Buffer.from(encrypted, 'base64'))
|
||||
if (bundle.length < nacl.box.nonceLength + nacl.box.overheadLength) {
|
||||
return null
|
||||
}
|
||||
|
||||
const nonce = bundle.slice(0, nacl.box.nonceLength)
|
||||
const ciphertext = bundle.slice(nacl.box.nonceLength)
|
||||
const plaintext = nacl.box.open.after(ciphertext, nonce, sharedKey)
|
||||
|
||||
if (!plaintext) {
|
||||
return null
|
||||
}
|
||||
|
||||
return new TextDecoder().decode(plaintext)
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import type { WebSocket } from 'ws'
|
||||
import { E2EEChannel } from './e2ee-channel'
|
||||
import { generateKeyPair, deriveSharedKey, encrypt, decrypt } from './e2ee-crypto'
|
||||
|
||||
// Why: this test simulates the full mobile → desktop E2EE flow without a real
|
||||
// WebSocket. The "mobile" side generates an ephemeral keypair, sends e2ee_hello,
|
||||
// the E2EEChannel (desktop) derives the shared key, and then both sides can
|
||||
// exchange encrypted RPC messages. This validates that the handshake protocol
|
||||
// and crypto are end-to-end compatible.
|
||||
|
||||
function publicKeyToBase64(key: Uint8Array): string {
|
||||
return Buffer.from(key).toString('base64')
|
||||
}
|
||||
|
||||
describe('E2EE integration (simulated mobile ↔ desktop)', () => {
|
||||
let serverKeys: ReturnType<typeof generateKeyPair>
|
||||
let mobileEphemeralKeys: ReturnType<typeof generateKeyPair>
|
||||
let wsSent: string[]
|
||||
let mockWs: {
|
||||
OPEN: 1
|
||||
readyState: number
|
||||
send: ReturnType<typeof vi.fn>
|
||||
close: ReturnType<typeof vi.fn>
|
||||
}
|
||||
let channel: E2EEChannel
|
||||
let onReady: ReturnType<typeof vi.fn>
|
||||
let onError: ReturnType<typeof vi.fn>
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
|
||||
serverKeys = generateKeyPair()
|
||||
mobileEphemeralKeys = generateKeyPair()
|
||||
wsSent = []
|
||||
mockWs = {
|
||||
OPEN: 1,
|
||||
readyState: 1,
|
||||
send: vi.fn((data: string) => wsSent.push(data)),
|
||||
close: vi.fn()
|
||||
}
|
||||
onReady = vi.fn()
|
||||
onError = vi.fn()
|
||||
|
||||
channel = new E2EEChannel(mockWs as unknown as WebSocket, {
|
||||
serverSecretKey: serverKeys.secretKey,
|
||||
validateToken: (token) => token === 'device-abc',
|
||||
onReady,
|
||||
onError
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
channel.destroy()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('full handshake → encrypted RPC round-trip', () => {
|
||||
// Mobile sends e2ee_hello (plaintext)
|
||||
const hello = JSON.stringify({
|
||||
type: 'e2ee_hello',
|
||||
publicKeyB64: publicKeyToBase64(mobileEphemeralKeys.publicKey),
|
||||
deviceToken: 'device-abc'
|
||||
})
|
||||
channel.handleRawMessage(hello)
|
||||
|
||||
// Desktop should respond with e2ee_ready
|
||||
expect(onReady).toHaveBeenCalled()
|
||||
expect(wsSent).toHaveLength(1)
|
||||
expect(JSON.parse(wsSent[0]!)).toEqual({ type: 'e2ee_ready' })
|
||||
|
||||
// Both sides derive the same shared key
|
||||
const mobileShared = deriveSharedKey(mobileEphemeralKeys.secretKey, serverKeys.publicKey)
|
||||
|
||||
// Set up the desktop message handler
|
||||
const desktopReceived: string[] = []
|
||||
channel.onMessage((plaintext, encryptedReply) => {
|
||||
desktopReceived.push(plaintext)
|
||||
encryptedReply(JSON.stringify({ id: 'rpc-1', ok: true, result: { status: 'ready' } }))
|
||||
})
|
||||
|
||||
// Mobile sends encrypted RPC request
|
||||
const request = JSON.stringify({ id: 'rpc-1', method: 'status.get' })
|
||||
channel.handleRawMessage(encrypt(request, mobileShared))
|
||||
|
||||
// Desktop received the plaintext
|
||||
expect(desktopReceived).toEqual([request])
|
||||
|
||||
// Desktop's encrypted reply (wsSent[1]) is decryptable by mobile
|
||||
expect(wsSent).toHaveLength(2)
|
||||
const replyPlain = decrypt(wsSent[1]!, mobileShared)
|
||||
expect(JSON.parse(replyPlain!)).toEqual({
|
||||
id: 'rpc-1',
|
||||
ok: true,
|
||||
result: { status: 'ready' }
|
||||
})
|
||||
})
|
||||
|
||||
it('mobile reconnects with fresh ephemeral key', () => {
|
||||
// First connection
|
||||
channel.handleRawMessage(
|
||||
JSON.stringify({
|
||||
type: 'e2ee_hello',
|
||||
publicKeyB64: publicKeyToBase64(mobileEphemeralKeys.publicKey),
|
||||
deviceToken: 'device-abc'
|
||||
})
|
||||
)
|
||||
expect(onReady).toHaveBeenCalledTimes(1)
|
||||
|
||||
const firstShared = deriveSharedKey(mobileEphemeralKeys.secretKey, serverKeys.publicKey)
|
||||
|
||||
// Simulate disconnect + reconnect with new ephemeral key
|
||||
channel.destroy()
|
||||
wsSent.length = 0
|
||||
|
||||
const newMobileKeys = generateKeyPair()
|
||||
const newChannel = new E2EEChannel(mockWs as unknown as WebSocket, {
|
||||
serverSecretKey: serverKeys.secretKey,
|
||||
validateToken: (token) => token === 'device-abc',
|
||||
onReady,
|
||||
onError
|
||||
})
|
||||
|
||||
newChannel.handleRawMessage(
|
||||
JSON.stringify({
|
||||
type: 'e2ee_hello',
|
||||
publicKeyB64: publicKeyToBase64(newMobileKeys.publicKey),
|
||||
deviceToken: 'device-abc'
|
||||
})
|
||||
)
|
||||
|
||||
expect(onReady).toHaveBeenCalledTimes(2)
|
||||
|
||||
const secondShared = deriveSharedKey(newMobileKeys.secretKey, serverKeys.publicKey)
|
||||
|
||||
// Keys from different sessions must not be interchangeable
|
||||
expect(Buffer.from(firstShared).toString('hex')).not.toBe(
|
||||
Buffer.from(secondShared).toString('hex')
|
||||
)
|
||||
|
||||
// Verify new session works
|
||||
const received: string[] = []
|
||||
newChannel.onMessage((plaintext) => received.push(plaintext))
|
||||
newChannel.handleRawMessage(encrypt('{"id":"2","method":"test"}', secondShared))
|
||||
expect(received).toEqual(['{"id":"2","method":"test"}'])
|
||||
|
||||
newChannel.destroy()
|
||||
})
|
||||
|
||||
it('streaming messages work through E2EE', () => {
|
||||
channel.handleRawMessage(
|
||||
JSON.stringify({
|
||||
type: 'e2ee_hello',
|
||||
publicKeyB64: publicKeyToBase64(mobileEphemeralKeys.publicKey),
|
||||
deviceToken: 'device-abc'
|
||||
})
|
||||
)
|
||||
|
||||
const mobileShared = deriveSharedKey(mobileEphemeralKeys.secretKey, serverKeys.publicKey)
|
||||
const received: string[] = []
|
||||
|
||||
channel.onMessage((plaintext, encryptedReply) => {
|
||||
received.push(plaintext)
|
||||
// Simulate streaming: send multiple encrypted responses
|
||||
for (let i = 0; i < 3; i++) {
|
||||
encryptedReply(
|
||||
JSON.stringify({
|
||||
id: 'stream-1',
|
||||
ok: true,
|
||||
streaming: true,
|
||||
result: { type: 'data', chunk: `line ${i}\n` }
|
||||
})
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
channel.handleRawMessage(
|
||||
encrypt(JSON.stringify({ id: 'stream-1', method: 'terminal.subscribe' }), mobileShared)
|
||||
)
|
||||
|
||||
// 1 e2ee_ready + 3 streaming responses
|
||||
expect(wsSent).toHaveLength(4)
|
||||
|
||||
for (let i = 1; i < 4; i++) {
|
||||
const plain = decrypt(wsSent[i]!, mobileShared)
|
||||
const parsed = JSON.parse(plain!)
|
||||
expect(parsed.streaming).toBe(true)
|
||||
expect(parsed.result.chunk).toBe(`line ${i - 1}\n`)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -16,6 +16,8 @@ import { UnixSocketTransport } from './rpc/unix-socket-transport'
|
||||
import { WebSocketTransport } from './rpc/ws-transport'
|
||||
import type { WebSocket } from 'ws'
|
||||
import { DeviceRegistry } from './device-registry'
|
||||
import { loadOrCreateE2EEKeypair, type E2EEKeypair } from './e2ee-keypair'
|
||||
import { E2EEChannel } from './rpc/e2ee-channel'
|
||||
|
||||
const DEFAULT_WS_PORT = 6768
|
||||
|
||||
@@ -38,9 +40,13 @@ export class OrcaRuntimeRpcServer {
|
||||
private readonly wsPort: number
|
||||
private readonly authToken = randomBytes(24).toString('hex')
|
||||
private deviceRegistry: DeviceRegistry | null = null
|
||||
private e2eeKeypair: E2EEKeypair | null = null
|
||||
private tlsFingerprint: string | null = null
|
||||
private activeTransports: RpcTransport[] = []
|
||||
private transports: RuntimeTransportMetadata[] = []
|
||||
// Why: each WebSocket connection has its own E2EE channel that manages the
|
||||
// handshake and encrypt/decrypt lifecycle. Keyed by WebSocket instance.
|
||||
private e2eeChannels = new Map<WebSocket, E2EEChannel>()
|
||||
|
||||
constructor({
|
||||
runtime,
|
||||
@@ -67,6 +73,14 @@ export class OrcaRuntimeRpcServer {
|
||||
return this.tlsFingerprint
|
||||
}
|
||||
|
||||
getE2EEPublicKey(): string | null {
|
||||
return this.e2eeKeypair?.publicKeyB64 ?? null
|
||||
}
|
||||
|
||||
getE2EEKeypair(): E2EEKeypair | null {
|
||||
return this.e2eeKeypair
|
||||
}
|
||||
|
||||
getWebSocketEndpoint(): string | null {
|
||||
const ws = this.transports.find((t) => t.kind === 'websocket')
|
||||
return ws?.endpoint ?? null
|
||||
@@ -104,32 +118,57 @@ export class OrcaRuntimeRpcServer {
|
||||
const transportsMeta: RuntimeTransportMetadata[] = [transportMeta]
|
||||
|
||||
// Why: WebSocket transport is opt-in and starts alongside the Unix socket.
|
||||
// It uses TLS with a self-signed cert and per-device tokens from the
|
||||
// device registry, not the shared runtime auth token.
|
||||
// It uses per-device tokens and E2EE (application-layer encryption via
|
||||
// tweetnacl) rather than TLS, since React Native can't pin self-signed certs.
|
||||
if (this.enableWebSocket) {
|
||||
try {
|
||||
this.deviceRegistry = new DeviceRegistry(this.userDataPath)
|
||||
this.e2eeKeypair = loadOrCreateE2EEKeypair(this.userDataPath)
|
||||
|
||||
// Why: React Native's built-in WebSocket cannot disable TLS verification
|
||||
// for self-signed certificates. Use plain ws:// for now — per-device
|
||||
// tokens still provide auth. TLS will be re-enabled once the mobile app
|
||||
// implements certificate pinning via the fingerprint from QR pairing.
|
||||
const wsTransport = new WebSocketTransport({
|
||||
host: '0.0.0.0',
|
||||
port: this.wsPort
|
||||
})
|
||||
|
||||
// Why: WebSocket transport uses dispatchStreaming which can emit
|
||||
// multiple responses for subscription methods. Auth validation
|
||||
// happens before dispatch.
|
||||
wsTransport.onMessage((msg, reply, ws) => {
|
||||
void this.handleWebSocketMessage(msg, reply, wsTransport, ws)
|
||||
// Why: each WebSocket connection gets an E2EE channel that handles the
|
||||
// handshake before any RPC messages are processed. The channel decrypts
|
||||
// inbound messages and encrypts outbound replies transparently.
|
||||
wsTransport.onMessage((msg, _reply, ws) => {
|
||||
let channel = this.e2eeChannels.get(ws)
|
||||
if (!channel) {
|
||||
channel = new E2EEChannel(ws, {
|
||||
serverSecretKey: this.e2eeKeypair!.secretKey,
|
||||
validateToken: (token) => this.deviceRegistry?.validateToken(token) != null,
|
||||
onReady: (ch) => {
|
||||
if (ch.deviceToken) {
|
||||
wsTransport.setClientId(ws, ch.deviceToken)
|
||||
}
|
||||
},
|
||||
onError: (code, reason) => {
|
||||
this.e2eeChannels.get(ws)?.destroy()
|
||||
this.e2eeChannels.delete(ws)
|
||||
ws.close(code, reason)
|
||||
}
|
||||
})
|
||||
channel.onMessage((plaintext, encryptedReply) => {
|
||||
void this.handleWebSocketMessage(plaintext, encryptedReply, wsTransport, ws)
|
||||
})
|
||||
this.e2eeChannels.set(ws, channel)
|
||||
}
|
||||
channel.handleRawMessage(msg)
|
||||
})
|
||||
|
||||
// Why: when a mobile client disconnects, the runtime must clean up
|
||||
// connection-scoped state like mobile-fit overrides to prevent
|
||||
// orphaned phone-fit state on the desktop terminal.
|
||||
// connection-scoped state like mobile-fit overrides and the E2EE
|
||||
// channel to prevent orphaned state.
|
||||
wsTransport.onConnectionClose((clientId) => {
|
||||
for (const [ws, channel] of this.e2eeChannels) {
|
||||
if (channel.deviceToken === clientId) {
|
||||
channel.destroy()
|
||||
this.e2eeChannels.delete(ws)
|
||||
break
|
||||
}
|
||||
}
|
||||
this.runtime.onClientDisconnected(clientId)
|
||||
})
|
||||
|
||||
|
||||
@@ -3,10 +3,10 @@ import { encodePairingOffer, decodePairingOffer, type PairingOffer } from './pai
|
||||
|
||||
describe('pairing offer', () => {
|
||||
const offer: PairingOffer = {
|
||||
v: 1,
|
||||
endpoint: 'wss://192.168.1.10:6768',
|
||||
v: 2,
|
||||
endpoint: 'ws://192.168.1.10:6768',
|
||||
deviceToken: 'abcdef1234567890abcdef1234567890abcdef1234567890',
|
||||
certFingerprint: 'sha256:deadbeef'
|
||||
publicKeyB64: 'dGVzdC1wdWJsaWMta2V5LWJhc2U2NC1lbmNvZGVk'
|
||||
}
|
||||
|
||||
it('encode then decode round-trips correctly', () => {
|
||||
@@ -32,19 +32,19 @@ describe('pairing offer', () => {
|
||||
})
|
||||
|
||||
it('rejects payloads with missing fields', () => {
|
||||
const partial = { v: 1, endpoint: 'wss://host:1234' }
|
||||
const partial = { v: 2, endpoint: 'ws://host:1234' }
|
||||
const base64 = Buffer.from(JSON.stringify(partial)).toString('base64')
|
||||
expect(() => decodePairingOffer(`orca://pair#${base64}`)).toThrow()
|
||||
})
|
||||
|
||||
it('rejects payloads with wrong version', () => {
|
||||
const wrong = { ...offer, v: 2 }
|
||||
const wrong = { ...offer, v: 1 }
|
||||
const base64 = Buffer.from(JSON.stringify(wrong)).toString('base64')
|
||||
expect(() => decodePairingOffer(`orca://pair#${base64}`)).toThrow()
|
||||
})
|
||||
|
||||
it('rejects payloads with invalid fingerprint prefix', () => {
|
||||
const wrong = { ...offer, certFingerprint: 'md5:abc' }
|
||||
it('rejects payloads with missing publicKeyB64', () => {
|
||||
const wrong = { v: 2, endpoint: 'ws://host:1234', deviceToken: 'tok' }
|
||||
const base64 = Buffer.from(JSON.stringify(wrong)).toString('base64')
|
||||
expect(() => decodePairingOffer(`orca://pair#${base64}`)).toThrow()
|
||||
})
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
export const PAIRING_OFFER_VERSION = 1
|
||||
export const PAIRING_OFFER_VERSION = 2
|
||||
|
||||
export const PairingOfferV1 = z.object({
|
||||
export const PairingOfferSchema = z.object({
|
||||
v: z.literal(PAIRING_OFFER_VERSION),
|
||||
endpoint: z.string().min(1),
|
||||
deviceToken: z.string().min(1),
|
||||
certFingerprint: z.string().startsWith('sha256:')
|
||||
// Why: the desktop's Curve25519 public key, base64-encoded. The mobile client
|
||||
// uses this to derive a shared secret via ECDH for end-to-end encryption.
|
||||
publicKeyB64: z.string().min(1)
|
||||
})
|
||||
|
||||
export type PairingOffer = z.infer<typeof PairingOfferV1>
|
||||
export type PairingOffer = z.infer<typeof PairingOfferSchema>
|
||||
|
||||
export function encodePairingOffer(offer: PairingOffer): string {
|
||||
const json = JSON.stringify(offer)
|
||||
@@ -29,5 +31,5 @@ export function decodePairingOffer(url: string): PairingOffer {
|
||||
const base64url = url.slice(hashIndex + 1)
|
||||
const base64 = base64url.replace(/-/g, '+').replace(/_/g, '/')
|
||||
const json = Buffer.from(base64, 'base64').toString('utf-8')
|
||||
return PairingOfferV1.parse(JSON.parse(json))
|
||||
return PairingOfferSchema.parse(JSON.parse(json))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user