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>
42 lines
1.4 KiB
TypeScript
42 lines
1.4 KiB
TypeScript
// 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)
|
|
}
|