+ Texts the Rabbit's SIM card sends and gets show up here, you can text from it here (as "Rabbit SIM"), and chat names
+ and read/unread/archived stay in step with the Rabbit without plugging it in. It goes through jai, which only passes on
+ sealed messages it can't read: the key stays on this computer and the Rabbit. A text sent from here goes out at the
+ Rabbit's next background check (Settings there: how often), so it can take a while.
+
+ {st?.connected ? (
+ <>
+
+ Relay
+ {st.url}
+
+
+ Last check
+ {st.error ? `⚠ ${st.error}` : last ?? 'Not yet'}
+
+ {st.waiting > 0 && (
+
+ Waiting for the Rabbit
+
+ {st.waiting} text{st.waiting === 1 ? '' : 's'}
+
+
+ )}
+
+
+
+ >
+ ) : (
+ <>
+
+
+
+
+
+ >
+ )}
+ {done &&
{done}
}
+ {error &&
{error}
}
+
+ )
+}
diff --git a/src/renderer/src/components/Via.tsx b/src/renderer/src/components/Via.tsx
index 9634d7e..701336c 100644
--- a/src/renderer/src/components/Via.tsx
+++ b/src/renderer/src/components/Via.tsx
@@ -1,7 +1,13 @@
-import { formatNumber } from '@shared/phone'
+import { formatNumber, SIM_DID } from '@shared/phone'
// "via ", with a GV tag when it's the Google Voice number.
export function Via({ did, gvNumber }: { did: string; gvNumber?: string }) {
+ if (did === SIM_DID)
+ return (
+ <>
+ via SIMRabbit
+ >
+ )
return (
<>
via {did === gvNumber && GV}
diff --git a/src/shared/api.ts b/src/shared/api.ts
index 0880b1e..d908c52 100644
--- a/src/shared/api.ts
+++ b/src/shared/api.ts
@@ -17,6 +17,14 @@ export interface RabbitStatus {
device?: { serial: string; model: string; installedVersion?: string }
}
+export interface RelayStatus {
+ connected: boolean
+ url?: string
+ lastSync?: number
+ error?: string
+ waiting: number // texts sent here via the Rabbit's SIM, not yet done
+}
+
export interface Api {
getState(): Promise
testCredentials(creds: Credentials): Promise
@@ -32,6 +40,10 @@ export interface Api {
rabbitStatus(): Promise
rabbitInstall(mode?: 'full' | 'update'): Promise // update: app only, keeps its data
rabbitSync(): Promise
+ relayStatus(): Promise
+ relayConnect(url: string, token: string): Promise
+ relayDisconnect(): Promise
+ onRelayStatus(cb: (s: RelayStatus) => void): () => void
onRabbitProgress(cb: (step: string) => void): () => void
listContacts(): Promise
diff --git a/src/shared/phone.ts b/src/shared/phone.ts
index fd093f0..fb047df 100644
--- a/src/shared/phone.ts
+++ b/src/shared/phone.ts
@@ -8,6 +8,20 @@ export function normalizeNumber(raw: string): string {
return digits
}
+// The Rabbit's SIM, reached through jai (main/relay.ts): a number we text
+// from that isn't a phone number here.
+export const SIM_DID = 'sim'
+
+// A number to send from, as pickers and "via" show it.
+export function didName(did: string): string {
+ return did === SIM_DID ? 'Rabbit SIM' : formatNumber(did)
+}
+
+// Group chats: Google Voice threads, or MMS over the Rabbit's SIM.
+export function groupsFrom(did: string | undefined, gvNumber: string | undefined): boolean {
+ return !!did && (did === gvNumber || did === SIM_DID)
+}
+
export function formatNumber(n: string): string {
const d = normalizeNumber(n)
if (d.length === 10) return `(${d.slice(0, 3)}) ${d.slice(3, 6)}-${d.slice(6)}`
diff --git a/src/shared/types.ts b/src/shared/types.ts
index d9b6757..da13c17 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -96,7 +96,7 @@ export interface SearchHit {
snippet: string // contains / markers around matched text
}
-export type Provider = 'voipms' | 'gvoice'
+export type Provider = 'voipms' | 'gvoice' | 'sim'
export interface Did {
did: string
diff --git a/test/relay.device.test.ts b/test/relay.device.test.ts
new file mode 100644
index 0000000..00d0557
--- /dev/null
+++ b/test/relay.device.test.ts
@@ -0,0 +1,88 @@
+// The relay against the dev app on a plugged-in Rabbit (DEVICE=1 npm test --
+// test/relay.device.test.ts). A throwaway local relay, reached from the Rabbit
+// through adb reverse; the dev app's made-up data (tools/push_sandbox.py).
+// Never the real app, never jai.
+import { execFileSync, 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, describe, expect, it, vi } from 'vitest'
+
+const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'relay-device-'))
+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 { newKey, RelayEngine } = await import('../src/main/relay')
+
+const PKG = 'me.teafry.voipmessages.dev'
+const DEVICE_PORT = 18080
+let server: ChildProcess | undefined
+afterAll(() => {
+ server?.kill()
+ try {
+ execFileSync('adb', ['reverse', '--remove', `tcp:${DEVICE_PORT}`])
+ } catch {
+ /* gone already */
+ }
+})
+
+const sleep = (ms: number): Promise => new Promise((r) => setTimeout(r, ms))
+
+describe.skipIf(!process.env['DEVICE'])('relay with the dev app on the Rabbit', () => {
+ it('seals in Java and opens in Node, and back', { timeout: 240_000 }, async () => {
+ const port = await 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))
+ })
+ })
+ const data = path.join(tmp, 'server')
+ server = spawn('python3', [path.join(__dirname, '../server/bubble_relay.py'), '--port', String(port), '--data', data], { stdio: 'ignore' })
+ const url = `http://127.0.0.1:${port}`
+ for (let i = 0; i < 50 && !(await fetch(`${url}/health`).then((r) => r.ok).catch(() => false)); i++) await sleep(100)
+ const token = fs.readFileSync(path.join(data, 'token'), 'utf8').trim()
+ const key = newKey()
+ execFileSync('adb', ['reverse', `tcp:${DEVICE_PORT}`, `tcp:${port}`])
+ execFileSync('python3', [path.join(__dirname, '../android/tools/push_sandbox.py'), '--relay', `http://127.0.0.1:${DEVICE_PORT}`], {
+ env: { ...process.env, RELAY_TOKEN: token, RELAY_KEY: key },
+ stdio: 'ignore'
+ })
+
+ const db = new MessageDb(path.join(tmp, 'messages.db'))
+ const media = new MediaStore(path.join(tmp, 'media'), db)
+ const engine = new RelayEngine(db, media, { url, token, key }, 30)
+ ;(engine as unknown as { running: boolean }).running = true
+ db.setName('sim', '5415550150', 'Made-up SIM friend')
+ engine.stateChanged()
+ const tempId = db.insertPending({ did: 'sim', contact: '5415550150', direction: 'out', body: 'from the desk', ts: Date.now() })
+ engine.send(tempId, '5415550150', 'from the desk', [])
+ await engine.syncNow()
+
+ // Opening the app has it check the relay (a job a few seconds later).
+ execFileSync('adb', ['shell', 'am', 'start', '-n', `${PKG}/me.teafry.voipmessages.MainActivity`])
+ let simIds: number[] = []
+ for (let i = 0; i < 40; i++) {
+ await sleep(4000)
+ await engine.syncNow()
+ simIds = db.getConversationMessages('sim', '5415550150').map((m) => m.id)
+ if (simIds.includes(2 ** 51 + 1) && db.getMessage(tempId)?.status === 'failed') break
+ // The send's answer comes on the Rabbit's next round: nudge it.
+ if (i % 5 === 4) execFileSync('adb', ['shell', 'am', 'start', '-S', '-n', `${PKG}/me.teafry.voipmessages.MainActivity`])
+ }
+ // The made-up SIM history came over, decrypted.
+ expect(simIds).toEqual(expect.arrayContaining([2 ** 51 + 1, 2 ** 51 + 2]))
+ expect(db.getConversationMessages('sim', '5415550150').find((m) => m.id === 2 ** 51 + 1)?.body).toBe('Texting your SIM number now')
+ // The send was read and answered (the dev app isn't the default SMS app, so: a reason).
+ expect(db.getMessage(tempId)?.status).toBe('failed')
+ expect(db.getMessage(tempId)?.error).toMatch(/texting app/)
+ engine.stop()
+ db.close()
+ })
+})
diff --git a/test/relay.test.ts b/test/relay.test.ts
new file mode 100644
index 0000000..bf98764
--- /dev/null
+++ b/test/relay.test.ts
@@ -0,0 +1,151 @@
+// 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()
+ })
+})