// The relay end to end: the real server (server/bubble_relay.py) on localhost, // the desktop's RelayEngine on a scratch database, and the Rabbit's side played // here with the same sealing. Made-up numbers and texts only. import { spawn, type ChildProcess } from 'node:child_process' import fs from 'node:fs' import net from 'node:net' import os from 'node:os' import path from 'node:path' import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'relay-test-')) vi.mock('electron', () => ({ app: { getPath: () => tmp }, safeStorage: { isEncryptionAvailable: () => true, encryptString: (s: string) => Buffer.from(s), decryptString: (b: Buffer) => b.toString() }, nativeImage: { createFromBuffer: () => ({ getSize: () => ({ width: 0, height: 0 }) }) }, net: { fetch: () => Promise.reject(new Error('no network in tests')) } })) const { MessageDb } = await import('../src/main/db') const { MediaStore } = await import('../src/main/media') const { checkUrl, newKey, RelayEngine, seal, unseal } = await import('../src/main/relay') let server: ChildProcess let url = '' let token = '' async function freePort(): Promise { return new Promise((resolve) => { const s = net.createServer().listen(0, '127.0.0.1', () => { const p = (s.address() as net.AddressInfo).port s.close(() => resolve(p)) }) }) } beforeAll(async () => { const port = await freePort() const data = path.join(tmp, 'server') server = spawn('python3', [path.join(__dirname, '../server/bubble_relay.py'), '--port', String(port), '--data', data], { stdio: 'ignore' }) url = `http://127.0.0.1:${port}` for (let i = 0; i < 50; i++) { const ok = await fetch(`${url}/health`).then((r) => r.ok).catch(() => false) if (ok) break await new Promise((r) => setTimeout(r, 100)) } token = fs.readFileSync(path.join(data, 'token'), 'utf8').trim() }) afterAll(() => server?.kill()) // The Rabbit's half: one sync call with its sealed posts; returns what it got. let rabbitCursor = 0 async function rabbit(key: Buffer, push: unknown[] = [], raw: string[] = []): Promise>> { const res = await fetch(`${url}/sync`, { method: 'POST', headers: { Authorization: `Bearer ${token}` }, body: JSON.stringify({ device: 'rabbit', since: rabbitCursor, push: [...push.map((p) => seal(key, 'rabbit', p)), ...raw] }) }) const body = (await res.json()) as { cursor: number; events: string[] } rabbitCursor = body.cursor return body.events.map((b) => unseal(key, 'desktop', b) as Record) } describe('relay', () => { it('seals so that only the right key and author open it', () => { const k = Buffer.from(newKey(), 'base64') const blob = seal(k, 'desktop', { t: 'x', n: 1 }) expect(unseal(k, 'desktop', blob)).toEqual({ t: 'x', n: 1 }) expect(unseal(k, 'rabbit', blob)).toBeUndefined() // a reflected blob isn't the other side's expect(unseal(Buffer.from(newKey(), 'base64'), 'desktop', blob)).toBeUndefined() const b = Buffer.from(blob, 'base64') b[20] ^= 1 expect(unseal(k, 'desktop', b.toString('base64'))).toBeUndefined() }) it('only sends the token to tailscale or https', () => { expect(checkUrl('http://100.69.139.40:8080/')).toBe('http://100.69.139.40:8080') expect(() => checkUrl('http://example.com')).toThrow() expect(checkUrl('https://example.com')).toBe('https://example.com') }) it('carries texts, photos, sends and chat names both ways', async () => { const db = new MessageDb(path.join(tmp, 'messages.db')) const media = new MediaStore(path.join(tmp, 'media'), db, (u, at) => { if (u.startsWith('mmspart:') && at) engine.want(at.id, at.index, u) return Promise.reject(new Error('on the Rabbit')) }) const cfg = { url, token, key: newKey() } const key = Buffer.from(cfg.key, 'base64') const engine = new RelayEngine(db, media, cfg, 30) const got: number[] = [] engine.on('messages', (m: Array<{ id: number }>) => got.push(...m.map((x) => x.id))) ;(engine as unknown as { running: boolean }).running = true // Desktop → Rabbit: a text and a photo over the SIM; the state goes too. engine.stateChanged() const photo = media.save(Buffer.from('fake jpeg'), 'image/jpeg') const tempId = db.insertPending({ did: 'sim', contact: '5415550101', direction: 'out', body: 'hi from the desk', ts: Date.now(), kind: 'mms', media: [{ file: photo, mime: 'image/jpeg' }] }) engine.send(tempId, '5415550101', 'hi from the desk', [{ file: photo, mime: 'image/jpeg' }]) await engine.syncNow() const toRabbit = await rabbit(key) const sendReq = toRabbit.find((p) => p.t === 'send')! expect(sendReq).toMatchObject({ contact: '5415550101', text: 'hi from the desk' }) expect(Buffer.from((sendReq.media as Array<{ data: string }>)[0].data, 'base64').toString()).toBe('fake jpeg') expect(toRabbit.some((p) => p.t === 'state')).toBe(true) // Rabbit → desktop: it went out (as message 2^51+7), a text came in, an old photo stays on the Rabbit, a group got a name. const sentId = 2 ** 51 + 7 const inId = 2 ** 51 + 8 const oldMms = 2 ** 51 + 2 ** 49 + 3 await rabbit( key, [ { t: 'sent', id: sendReq.id, msgId: sentId, error: null }, { t: 'msgs', msgs: [ { id: sentId, did: 'sim', contact: '5415550101', direction: 'out', body: 'hi from the desk', ts: Date.now(), kind: 'mms' }, { id: inId, did: 'sim', contact: '5415550101', direction: 'in', body: 'hey!', ts: Date.now() + 1, kind: 'sms' }, { id: oldMms, did: 'sim', contact: '5415550102', direction: 'in', body: '', ts: Date.now() - 86_400_000, kind: 'mms', media: [{ url: 'mmspart:44', mime: 'image/png' }] }, { id: 99, did: '5415550100', contact: '5415550103', direction: 'in', body: 'not a SIM message', ts: Date.now() } ] }, { t: 'state', names: [{ did: 'sim', contact: '5415550101,5415550102', name: 'Made-up group', ts: Date.now() }], read: [] } ], ['AAAA'] // garbage from a stranger: ignored ) await engine.syncNow() expect(db.getMessage(tempId)).toBeUndefined() expect(db.getMessage(sentId)?.status).toBe('delivered') expect(db.getMessage(sentId)?.media?.[0].file).toBe(photo) // our copy kept expect(db.getConversationMessages('sim', '5415550101').map((m) => m.id)).toEqual([sentId, inId]) expect(db.getMessage(99)).toBeUndefined() // only did 'sim' comes this way expect(got).toContain(inId) expect(db.getName('sim', '5415550101,5415550102')).toBe('Made-up group') // The old photo: asked for when shown, delivered by the Rabbit's next check. expect(await media.resolve(oldMms, 0)).toBeUndefined() await engine.syncNow() const want = (await rabbit(key)).find((p) => p.t === 'want')! expect(want.items).toEqual([{ id: oldMms, index: 0, url: 'mmspart:44' }]) await rabbit(key, [{ t: 'media', id: oldMms, index: 0, mime: 'image/png', data: Buffer.from('fake png').toString('base64') }]) await engine.syncNow() const ref = await media.resolve(oldMms, 0) expect(fs.readFileSync(media.filePath(ref!.file!)).toString()).toBe('fake png') // Picked up = gone from jai. expect(await rabbit(key)).toEqual([]) engine.stop() db.close() }) })