v0.5.0: bubble for Android 0.5.0 — text from the Rabbit's SIM on the desktop, and chat names and read status sync, through jai

A relay on jai (server/bubble_relay.py, stdlib + SQLite, tailscale address
only, bearer token) carries sealed blobs between the desktop and the Rabbit:
AES-256-GCM with a key the desktop makes and hands over USB (Sync to Rabbit),
so jai can neither read nor forge anything. It deletes what's been picked up,
and anything after 14 days.

- Desktop (src/main/relay.ts): "Rabbit SIM" is a number to text from, groups
  included; the SIM's history and new texts arrive; older photos are fetched
  when shown; names and read/unread/archived go both ways. Settings → Rabbit
  relay connects it.
- Rabbit (Relay.java, RelayJob): no timer of its own for the battery; it rides
  along with the background checks, plus one network job after a text, a send
  or a swipe. Each send from the desktop goes out at most once and not after a
  day. Plain http only to jai and localhost (network_security_config).
- scripts/deploy-jai.sh; tests: server unit tests, an end-to-end relay test,
  and DEVICE=1 relay.device.test.ts against the dev app.
This commit is contained in:
2026-11-06 17:35:00 -08:00
parent e1bceb06a3
commit 96c368dfd1
39 changed files with 1638 additions and 53 deletions
+77 -5
View File
@@ -27,6 +27,7 @@ import { gvMessageId, GvSyncEngine } from './gvoice/sync'
import { WaaSigner } from './gvoice/waa'
import { clearNotifications, notifyNew } from './notify'
import * as rabbit from './rabbit'
import { checkUrl, clearRelayConfig, loadRelayConfig, newKey, RelayEngine, saveRelayConfig, SIM_DID } from './relay'
protocol.registerSchemesAsPrivileged([
{ scheme: 'contact-photo', privileges: { standard: true, secure: true, supportFetchAPI: true } },
@@ -47,6 +48,8 @@ let dids: Did[] = []
let gv: GVoice | undefined
let gvSync: GvSyncEngine | undefined
let waa: WaaSigner | undefined
// The relay through jai: the Rabbit's SIM, names and read state (relay.ts).
let relay: RelayEngine | undefined
const send = (channel: string, ...args: unknown[]): void => {
if (win && !win.isDestroyed()) win.webContents.send(channel, ...args)
@@ -107,13 +110,38 @@ function openFromNotification(key: { did: string; contact: string }): void {
const gvNumber = (): string | undefined => db.get('gv_number') || undefined
// Every number we can text from: voip.ms's DIDs, then Google Voice's.
// Every number we can text from: voip.ms's DIDs, then Google Voice's, then
// the Rabbit's SIM (through jai).
function allDids(): Did[] {
const n = gvNumber()
return n ? [...dids, { did: n, description: 'Google Voice', smsEnabled: true, provider: 'gvoice' }] : dids
const out: Did[] = n ? [...dids, { did: n, description: 'Google Voice', smsEnabled: true, provider: 'gvoice' }] : [...dids]
if (relay) out.push({ did: SIM_DID, description: 'Rabbit SIM', smsEnabled: true, provider: 'sim' })
return out
}
const providerOf = (did: string): Provider => (did === gvNumber() ? 'gvoice' : 'voipms')
const providerOf = (did: string): Provider => (did === SIM_DID ? 'sim' : did === gvNumber() ? 'gvoice' : 'voipms')
function startRelay(): void {
relay?.stop()
relay = undefined
const cfg = loadRelayConfig()
if (!cfg) return
relay = new RelayEngine(db, media, cfg, settings.pollSeconds)
relay.on('messages', onNewMessages)
relay.on('changed', () => send('conversationsChanged'))
relay.on('status', () => send('relayStatus', relay?.status()))
relay.start()
}
// A text over the Rabbit's SIM: pending here until the Rabbit's next check
// sends it and says how it went (relay.ts).
function relaySend(contact: string, text: string, refs: MediaRef[]): void {
if (!relay) throw new Error('The Rabbit relay is off: connect it in Settings → Rabbit.')
const kind = refs.length || isGroup(contact) ? 'mms' : 'sms'
const tempId = db.insertPending({ did: SIM_DID, contact, direction: 'out', body: text, ts: Date.now(), kind, ...(refs.length ? { media: refs } : {}) })
relay.send(tempId, contact, text, refs)
send('conversationsChanged')
}
function syncStatus(): SyncStatus {
const base: SyncStatus = sync?.getStatus() ?? { phase: 'unconfigured', backfillDone: false, total: db.count() }
@@ -170,6 +198,10 @@ async function rabbitConfig(): Promise<rabbit.RabbitConfig> {
...(SANDBOX ? { sandbox: true } : {}),
voipms: SANDBOX ? { username: 'sandbox', password: 'sandbox' } : creds ? { username: creds.username, password: creds.password } : null,
gvoice: gv ? { number: gv, cookies: SANDBOX ? {} : await exportCookies() } : null,
relay: (() => {
const r = loadRelayConfig()
return r ? { url: r.url, token: r.token, key: r.key } : null
})(),
dids: voipDids.map((d) => ({ did: d.did, description: d.description })),
defaultDid: settings.defaultDid ?? voipDids[0]?.did ?? gv
}
@@ -393,6 +425,7 @@ async function gvSend(did: string, contact: string, text: string, ref?: MediaRef
// Anything longer than one SMS goes out as a single text-only MMS (voip.ms;
// Google Voice has no such limit).
async function sendText(did: string, contact: string, text: string): Promise<void> {
if (did === SIM_DID) return relaySend(contact, text, [])
const from = normalizeNumber(did)
const m: Omit<NewMessage, 'id'> = { did: from, contact, direction: 'out', body: text, ts: Date.now() }
if (providerOf(from) === 'gvoice') return deliver(m, () => gvSend(from, contact, text))
@@ -410,6 +443,7 @@ async function sendMms(did: string, contact: string, text: string, attachments:
}
async function sendMmsRefs(did: string, contact: string, text: string, refs: MediaRef[]): Promise<void> {
if (did === SIM_DID) return relaySend(contact, text, refs)
const from = normalizeNumber(did)
if (providerOf(from) === 'gvoice') {
if (refs.some((r) => !SendMediaType[r.mime ?? ''])) throw new Error('Google Voice can only send photos.')
@@ -537,20 +571,25 @@ function registerIpc(): void {
// Clear the unread badge on the phone too.
const thread = providerOf(did) === 'gvoice' && db.hasUnread(did, contact) ? db.getGvThread(did, contact) : undefined
if (thread) gv?.markRead(thread).catch((e: Error) => console.warn('[gvoice] mark read failed:', e.message))
const had = db.hasUnread(did, contact)
db.markRead(did, contact)
clearNotifications(did, contact)
if (had) relay?.stateChanged()
send('conversationsChanged')
})
ipcMain.handle('markUnread', (_e, did: string, contact: string) => {
db.markUnread(did, contact)
relay?.stateChanged()
send('conversationsChanged')
})
ipcMain.handle('setArchived', (_e, did: string, contact: string, archived: boolean) => {
db.setArchived(did, contact, archived)
relay?.stateChanged()
send('conversationsChanged')
})
ipcMain.handle('setName', (_e, did: string, contact: string, name: string | null) => {
db.setName(did, contact, name)
relay?.stateChanged()
send('conversationsChanged')
})
ipcMain.handle('getDrafts', () => db.getDrafts())
@@ -577,8 +616,34 @@ function registerIpc(): void {
clipboard.write([new ClipboardItem({ 'image/png': new Blob([png], { type: 'image/png' }) })])
)
ipcMain.handle('relayStatus', () => relay?.status() ?? { connected: false, waiting: 0, url: loadRelayConfig()?.url })
ipcMain.handle('relayConnect', async (_e, url: string, token: string) => {
const origin = checkUrl(url)
const tok = token.trim()
if (!/^[A-Za-z0-9_-]{20,200}$/.test(tok)) throw new Error("That doesn't look like the relay's token.")
// A harmless call that needs the token: acknowledges nothing, posts nothing.
const res = await fetch(`${origin}/sync`, {
method: 'POST',
headers: { Authorization: `Bearer ${tok}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ device: 'desktop', since: Number(db.get('relay_cursor') ?? 0), push: [] }),
signal: AbortSignal.timeout(15_000)
}).catch(() => undefined)
if (!res) throw new Error(`Couldn't reach ${origin}. Is tailscale up?`)
if (res.status === 401) throw new Error('jai turned down that token.')
if (!res.ok) throw new Error(`jai answered ${res.status}.`)
// Keep the key across reconnects so the Rabbit's copy stays good.
saveRelayConfig({ url: origin, token: tok, key: loadRelayConfig()?.key ?? newKey() })
startRelay()
send('stateChanged')
})
ipcMain.handle('relayDisconnect', () => {
relay?.stop()
relay = undefined
clearRelayConfig()
send('stateChanged')
})
ipcMain.handle('syncStatus', () => syncStatus())
ipcMain.handle('pollNow', () => Promise.all([sync?.pollNow(), gvSync?.pollNow()]))
ipcMain.handle('pollNow', () => Promise.all([sync?.pollNow(), gvSync?.pollNow(), relay?.syncNow()]))
ipcMain.handle('openDataFolder', () => shell.openPath(getDataDir()))
ipcMain.handle('snapshotNow', () => db.snapshot(snapshotDir()))
ipcMain.handle('chooseDataDir', async () => {
@@ -679,7 +744,12 @@ app.whenReady().then(async () => {
db = new MessageDb(path.join(getDataDir(), 'messages.db'))
if (SANDBOX) seedDemo(db)
dids = JSON.parse(db.get('dids') ?? '[]') as Did[]
media = new MediaStore(path.join(getDataDir(), 'media'), db, (url) => {
media = new MediaStore(path.join(getDataDir(), 'media'), db, (url, at) => {
if (url.startsWith('mmspart:')) {
// On the Rabbit: ask for it; it shows up after the Rabbit's next check.
if (at) relay?.want(at.id, at.index, url)
return Promise.reject(new Error('on the Rabbit'))
}
if (!url.startsWith('gv:')) return net.fetch(url)
if (!gv) return Promise.reject(new Error('Google Voice is not connected'))
return gv.downloadMedia(url.slice(3))
@@ -698,6 +768,7 @@ app.whenReady().then(async () => {
const creds = loadCredentials()
if (creds) startSync(creds)
if (gvNumber() && (await hasGvSession())) startGvSync()
startRelay()
void dailySnapshot()
setInterval(() => void dailySnapshot(), 60 * 60 * 1000)
@@ -710,6 +781,7 @@ app.on('before-quit', (e) => {
quitting = true
sync?.stop()
stopGv()
relay?.stop()
contacts?.close()
db.snapshot(snapshotDir())
.catch((err) => console.error('[snapshot] on quit failed:', err))