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 ec9e472265
commit 950b8ce067
41 changed files with 1646 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))
+2 -2
View File
@@ -16,7 +16,7 @@ export class MediaStore {
readonly dir: string,
private db: MessageDb,
// How to fetch a MediaRef.url; Google Voice's gv:<id> refs need its session.
private fetchUrl: (url: string) => Promise<Response> = (url) => net.fetch(url)
private fetchUrl: (url: string, at?: { id: number; index: number }) => Promise<Response> = (url) => net.fetch(url)
) {}
filePath(file: string): string {
@@ -49,7 +49,7 @@ export class MediaStore {
private async download(id: number, index: number, url: string): Promise<MediaRef | undefined> {
try {
const res = await this.fetchUrl(url)
const res = await this.fetchUrl(url, { id, index })
const header = res.headers.get('content-type')?.split(';')[0].trim()
// voip.ms answers expired/unknown media with a 200 HTML page.
if (!res.ok || header === 'text/html') return undefined
+4
View File
@@ -22,6 +22,8 @@ export interface RabbitConfig {
gvoice: { number: string; cookies: Record<string, string> } | null
dids: Array<{ did: string; description: string }>
defaultDid?: string
// The relay through jai (relay.ts): address, token, and the key that seals everything.
relay?: { url: string; token: string; key: string } | null
}
export interface RabbitTarget {
@@ -146,6 +148,8 @@ async function historyCopy(db: MessageDb): Promise<string> {
copy.exec(`
DROP TRIGGER IF EXISTS messages_ai; DROP TRIGGER IF EXISTS messages_ad; DROP TRIGGER IF EXISTS messages_au;
DROP TABLE IF EXISTS messages_fts;
DROP TABLE IF EXISTS relay_outbox;
DELETE FROM kv WHERE key LIKE 'relay%';
`)
copy.pragma('journal_mode = DELETE')
copy.exec('VACUUM')
+316
View File
@@ -0,0 +1,316 @@
// The relay through jai: the Rabbit's SIM texts reach this computer, texts
// typed here go out over the Rabbit's SIM, and chat names and read/unread/
// archived stay in step between the two, all without a USB cable.
//
// jai only ever holds sealed blobs: AES-256-GCM with a key made here and handed
// to the Rabbit over USB (Install/Sync to Rabbit puts it in the app's private
// config.json). The bearer token only lets a device talk to the mailbox; the
// key is what keeps jai (and anyone else on it) from reading or forging
// anything. Server: server/bubble_relay.py. Android side: Relay.java.
//
// What travels (inside the seal; `t` is the kind):
// rabbit → desktop msgs {msgs: NewMessage[] (did 'sim'), media inline as {data} or lazy {url: 'mmspart:N'}}
// sent {id, msgId | null, error | null} a send from here, done
// media {id, index, mime, data} | {.., missing: true}
// desktop → rabbit send {id (uuid), ts, contact, text, media: [{mime, data, width, height}]}
// want {items: [{id, index, url}]} a lazy photo, please
// both ways state {names, read} merged newest-wins (db.namesImport/readStateImport)
import { app, safeStorage } from 'electron'
import crypto from 'node:crypto'
import { EventEmitter } from 'node:events'
import fs from 'node:fs'
import path from 'node:path'
import type { RelayStatus } from '@shared/api'
import { SIM_DID } from '@shared/phone'
import type { MediaRef } from '@shared/types'
import type { MessageDb, NameChange, NewMessage, ReadState } from './db'
import type { MediaStore } from './media'
export { SIM_DID } from '@shared/phone'
export const DEFAULT_URL = 'http://100.69.139.40:8080'
export interface RelayConfig {
url: string
token: string
key: string // base64, 32 bytes
}
// ---- the config, encrypted with the system keyring like the voip.ms login ----
const file = (): string => path.join(app.getPath('userData'), 'relay.bin')
export function loadRelayConfig(): RelayConfig | undefined {
try {
return JSON.parse(safeStorage.decryptString(fs.readFileSync(file()))) as RelayConfig
} catch {
return undefined
}
}
export function saveRelayConfig(c: RelayConfig): void {
if (!safeStorage.isEncryptionAvailable()) throw new Error('No system keyring available to keep the relay key safe.')
fs.mkdirSync(path.dirname(file()), { recursive: true })
fs.writeFileSync(file(), safeStorage.encryptString(JSON.stringify(c)), { mode: 0o600 })
}
export function clearRelayConfig(): void {
fs.rmSync(file(), { force: true })
}
export function newKey(): string {
return crypto.randomBytes(32).toString('base64')
}
// Plain http is fine only because tailscale encrypts the hop and the payload is
// sealed anyway; still, don't send the token just anywhere.
export function checkUrl(url: string): string {
const u = new URL(url.trim())
if (u.protocol !== 'http:' && u.protocol !== 'https:') throw new Error('The relay address should start with http:// or https://')
const host = u.hostname
const tailnet = /^100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.\d+\.\d+$/.test(host) || host.endsWith('.ts.net')
const local = host === '127.0.0.1' || host === 'localhost'
if (u.protocol === 'http:' && !tailnet && !local) throw new Error('Plain http only to a tailscale (100.x) address; use https otherwise.')
return u.origin
}
// ---- sealing ----
type Device = 'desktop' | 'rabbit'
const aad = (author: Device): Buffer => Buffer.from(`bubble-relay/1/${author}`)
export function seal(key: Buffer, author: Device, payload: unknown): string {
const nonce = crypto.randomBytes(12)
const c = crypto.createCipheriv('aes-256-gcm', key, nonce)
c.setAAD(aad(author))
const ct = Buffer.concat([c.update(JSON.stringify(payload), 'utf8'), c.final()])
return Buffer.concat([Buffer.from([1]), nonce, ct, c.getAuthTag()]).toString('base64')
}
// Undefined for anything not sealed with our key by `author` (tampered, foreign, garbage).
export function unseal(key: Buffer, author: Device, blob: string): unknown {
try {
const b = Buffer.from(blob, 'base64')
if (b.length < 1 + 12 + 16 || b[0] !== 1) return undefined
const d = crypto.createDecipheriv('aes-256-gcm', key, b.subarray(1, 13))
d.setAAD(aad(author))
d.setAuthTag(b.subarray(b.length - 16))
return JSON.parse(Buffer.concat([d.update(b.subarray(13, b.length - 16)), d.final()]).toString('utf8'))
} catch {
return undefined
}
}
// ---- payloads ----
interface RelayMedia {
url?: string
mime?: string
data?: string
width?: number
height?: number
}
type Incoming =
| { t: 'msgs'; msgs: Array<NewMessage & { media?: RelayMedia[] }> }
| { t: 'sent'; id: string; msgId: number | null; error: string | null }
| { t: 'media'; id: number; index: number; mime?: string; data?: string; width?: number; height?: number; missing?: boolean }
| { t: 'state'; names: NameChange[]; read: ReadState[] }
const MAX_PUSH_BYTES = 8 * 1024 * 1024
const isInt = (n: unknown): n is number => typeof n === 'number' && Number.isSafeInteger(n)
export class RelayEngine extends EventEmitter {
private key: Buffer
private timer?: NodeJS.Timeout
private kickTimer?: NodeJS.Timeout
private running = false
private syncing?: Promise<void>
private stateDirty = false
private wanted = new Set<string>()
private lastSync?: number
private error?: string
constructor(
private db: MessageDb,
private media: MediaStore,
private cfg: RelayConfig,
private pollSeconds: number
) {
super()
this.key = Buffer.from(cfg.key, 'base64')
if (this.key.length !== 32) throw new Error('bad relay key')
db.db.exec('CREATE TABLE IF NOT EXISTS relay_outbox (seq INTEGER PRIMARY KEY AUTOINCREMENT, blob TEXT NOT NULL)')
}
start(): void {
if (this.running) return
this.running = true
// The Rabbit should know where things stand here as soon as it can.
this.stateDirty = true
this.loop(1000)
}
stop(): void {
this.running = false
clearTimeout(this.timer)
clearTimeout(this.kickTimer)
}
status(): RelayStatus {
const waiting = (this.db.db.prepare(`SELECT COUNT(*) AS n FROM kv WHERE key LIKE 'relay_send:%'`).get() as { n: number }).n
return { connected: true, url: this.cfg.url, lastSync: this.lastSync, error: this.error, waiting }
}
private loop(delay: number): void {
clearTimeout(this.timer)
if (!this.running) return
this.timer = setTimeout(() => void this.syncNow().finally(() => this.loop(Math.max(15, this.pollSeconds) * 1000)), delay)
}
// Something to send: go soon, but gather a burst of changes into one call.
kick(): void {
clearTimeout(this.kickTimer)
this.kickTimer = setTimeout(() => void this.syncNow(), 1500)
}
syncNow(): Promise<void> {
this.syncing ??= this.syncLoop().finally(() => (this.syncing = undefined))
return this.syncing
}
// Names or read/unread/archived changed here.
stateChanged(): void {
this.stateDirty = true
this.kick()
}
private queue(payload: unknown): void {
this.db.db.prepare('INSERT INTO relay_outbox (blob) VALUES (?)').run(seal(this.key, 'desktop', payload))
}
// A pending message (already in the db as `tempId`) to go out over the Rabbit's SIM.
send(tempId: number, contact: string, text: string, refs: MediaRef[]): void {
const id = crypto.randomUUID()
const media = refs.map((r) => ({
mime: r.mime ?? 'application/octet-stream',
data: fs.readFileSync(this.media.filePath(r.file!)).toString('base64'),
...(r.width ? { width: r.width, height: r.height } : {})
}))
this.db.set(`relay_send:${id}`, String(tempId))
this.queue({ t: 'send', id, ts: Date.now(), contact, text, media })
this.kick()
}
// A photo the Rabbit has but we don't (history comes over without them).
want(id: number, index: number, url: string): void {
const k = `${id}/${index}`
if (this.wanted.has(k)) return
this.wanted.add(k)
this.queue({ t: 'want', items: [{ id, index, url }] })
this.kick()
}
private async syncLoop(): Promise<void> {
try {
if (this.stateDirty) {
this.stateDirty = false
this.queue({ t: 'state', names: this.db.namesExport(), read: this.db.readStateExport() })
}
for (let round = 0; round < 50 && this.running; round++) {
const rows = this.db.db.prepare('SELECT seq, blob FROM relay_outbox ORDER BY seq').all() as Array<{ seq: number; blob: string }>
const push: typeof rows = []
let size = 0
for (const r of rows) {
if (push.length && size + r.blob.length > MAX_PUSH_BYTES) break
push.push(r)
size += r.blob.length
}
const since = Number(this.db.get('relay_cursor') ?? 0)
const res = await fetch(`${this.cfg.url}/sync`, {
method: 'POST',
headers: { Authorization: `Bearer ${this.cfg.token}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ device: 'desktop', since, push: push.map((r) => r.blob) }),
signal: AbortSignal.timeout(120_000)
})
if (res.status === 401) throw new Error('jai turned down the token. Check it in Settings → Rabbit.')
if (!res.ok) throw new Error(`jai answered ${res.status}`)
const body = (await res.json()) as { cursor: number; events: string[]; more: boolean }
// Only now that jai has them: out of the outbox.
if (push.length) this.db.db.prepare('DELETE FROM relay_outbox WHERE seq <= ?').run(push.at(-1)!.seq)
for (const blob of body.events) this.handle(unseal(this.key, 'rabbit', blob) as Incoming | undefined)
this.db.set('relay_cursor', String(body.cursor))
if (!body.more && rows.length === push.length) break
}
this.lastSync = Date.now()
this.error = undefined
} catch (e) {
// Can't reach jai: an ordinary, quiet outcome; try again next round.
this.error = (e as Error).name === 'TimeoutError' ? "jai didn't answer" : (e as Error).message
}
this.emit('status', this.status())
}
private handle(p: Incoming | undefined): void {
if (!p || typeof p !== 'object') return
try {
if (p.t === 'msgs' && Array.isArray(p.msgs)) this.onMsgs(p.msgs)
else if (p.t === 'sent') this.onSent(p)
else if (p.t === 'media') this.onMedia(p)
else if (p.t === 'state') {
const n = this.db.namesImport(Array.isArray(p.names) ? p.names : []) + this.db.readStateImport(Array.isArray(p.read) ? p.read : [])
if (n) this.emit('changed', 'state')
}
} catch (e) {
console.warn('[relay] skipped a message from the Rabbit:', (e as Error).message)
}
}
private onMsgs(raw: Array<NewMessage & { media?: RelayMedia[] }>): void {
const msgs: NewMessage[] = []
for (const m of raw) {
// Only the SIM's own conversations come this way, whatever a message claims.
if (!isInt(m.id) || m.did !== SIM_DID || typeof m.contact !== 'string' || !m.contact || !isInt(m.ts)) continue
if (m.direction !== 'in' && m.direction !== 'out') continue
const media: MediaRef[] = []
for (const r of Array.isArray(m.media) ? m.media : []) {
const mime = typeof r.mime === 'string' ? r.mime : 'application/octet-stream'
if (typeof r.data === 'string') {
const ref: MediaRef = { file: this.media.save(Buffer.from(r.data, 'base64'), mime), mime }
if (isInt(r.width) && isInt(r.height)) Object.assign(ref, { width: r.width, height: r.height })
media.push(ref)
} else if (typeof r.url === 'string' && r.url.startsWith('mmspart:')) media.push({ url: r.url, mime })
}
msgs.push({
id: m.id,
did: SIM_DID,
contact: m.contact,
direction: m.direction,
body: typeof m.body === 'string' ? m.body : '',
ts: m.ts,
kind: m.kind === 'mms' ? 'mms' : 'sms',
...(media.length ? { media } : {}),
...(typeof m.sender === 'string' ? { sender: m.sender } : {})
})
}
const added = this.db.upsertMessages(msgs)
if (added.length) this.emit('messages', added)
}
private onSent(p: { id: string; msgId: number | null; error: string | null }): void {
const key = `relay_send:${p.id}`
const temp = this.db.get(key)
if (temp === undefined || temp === null) return
const tempId = Number(temp)
if (isInt(p.msgId)) this.db.confirmPending(tempId, p.msgId)
else this.db.markFailed(tempId, typeof p.error === 'string' ? `Rabbit: ${p.error}` : "The Rabbit couldn't send it.")
this.db.db.prepare('DELETE FROM kv WHERE key = ?').run(key)
this.emit('changed', 'sent')
}
private onMedia(p: { id: number; index: number; mime?: string; data?: string; width?: number; height?: number; missing?: boolean }): void {
if (!isInt(p.id) || !isInt(p.index)) return
this.wanted.delete(`${p.id}/${p.index}`)
if (typeof p.data !== 'string') return
const mime = typeof p.mime === 'string' ? p.mime : 'application/octet-stream'
const patch: MediaRef = { file: this.media.save(Buffer.from(p.data, 'base64'), mime), mime }
if (isInt(p.width) && isInt(p.height)) Object.assign(patch, { width: p.width, height: p.height })
this.db.setMediaFile(p.id, p.index, patch)
this.emit('changed', 'media')
}
}
+4
View File
@@ -22,6 +22,10 @@ const api: Api = {
rabbitInstall: (mode) => ipcRenderer.invoke('rabbitInstall', mode),
rabbitSync: () => ipcRenderer.invoke('rabbitSync'),
onRabbitProgress: (cb) => on('rabbitProgress', cb),
relayStatus: () => ipcRenderer.invoke('relayStatus'),
relayConnect: (url, token) => ipcRenderer.invoke('relayConnect', url, token),
relayDisconnect: () => ipcRenderer.invoke('relayDisconnect'),
onRelayStatus: (cb) => on('relayStatus', cb),
listContacts: () => ipcRenderer.invoke('listContacts'),
listAddressBooks: () => ipcRenderer.invoke('listAddressBooks'),
+1 -1
View File
@@ -72,7 +72,7 @@ export function App() {
const all = state?.dids.filter((d) => d.smsEnabled) ?? []
const chosen = state?.settings.dids ?? []
// The sync list is voip.ms's; Google Voice is on whenever it's connected.
return chosen.length ? all.filter((d) => d.provider === 'gvoice' || chosen.includes(d.did)) : all
return chosen.length ? all.filter((d) => d.provider === 'gvoice' || d.provider === 'sim' || chosen.includes(d.did)) : all
}, [state])
const open = useCallback((key: ConvKey, jumpTo?: number) => {
+2 -2
View File
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { Virtuoso, type VirtuosoHandle } from 'react-virtuoso'
import { formatNumber, groupMembers, isGroup } from '@shared/phone'
import { formatNumber, groupMembers, isGroup, didName } from '@shared/phone'
import type { ContactInfo, Conversation, Did, Message, SearchHit } from '@shared/types'
import type { ConvKey, Jump } from '../App'
import { chatsWith, convName, dayLabel, sameDay, senderName, senderShortName } from '../format'
@@ -70,7 +70,7 @@ export function ChatView({ conv, contact, contactMap, conversations, onOpen, nam
if (!chats.length) return [{ label: `No other chats with ${senderShortName(number, contactMap)}`, onSelect: () => undefined, disabled: true }]
return chats.map((c) => ({
label:
(isGroup(c.contact) ? convName(c.contact, contactMap, c.name) : `${senderName(c.contact, contactMap)} (just you two, from ${formatNumber(c.did)})`) +
(isGroup(c.contact) ? convName(c.contact, contactMap, c.name) : `${senderName(c.contact, contactMap)} (just you two, from ${didName(c.did)})`) +
(c.archived ? ' — archived' : ''),
onSelect: () => onOpen({ did: c.did, contact: c.contact })
}))
+5 -5
View File
@@ -1,5 +1,5 @@
import { useEffect, useImperativeHandle, useLayoutEffect, useRef, useState, type ChangeEvent, type Ref } from 'react'
import { charCount, formatNumber, isGroup, SMS_TEXT_LIMIT } from '@shared/phone'
import { charCount, formatNumber, isGroup, SMS_TEXT_LIMIT, didName, groupsFrom, SIM_DID } from '@shared/phone'
import type { Did } from '@shared/types'
import type { ConvKey } from '../App'
import { emojiQuery, exactEmoji, searchEmoji } from '../emoji'
@@ -37,8 +37,8 @@ export function Composer({ conv, isNew, smsDids, gvNumber, onChangeDid, ref }: P
const key = conv.contact
// Google Voice: no SMS/MMS split to count toward, and photos only.
const gv = conv.did === gvNumber
// A group thread lives on Google Voice; it can't switch numbers.
const fromDids = isGroup(conv.contact) ? smsDids.filter((d) => d.did === gvNumber) : smsDids
// A group lives on Google Voice or the Rabbit's SIM; only those can carry it.
const fromDids = isGroup(conv.contact) ? smsDids.filter((d) => groupsFrom(d.did, gvNumber)) : smsDids
const [text, setText] = useState(() => drafts.get(key) ?? '')
const [attachments, setAttachments] = useState<Attachment[]>(() => attachmentDrafts.get(key) ?? [])
const [preparing, setPreparing] = useState(0)
@@ -187,8 +187,8 @@ export function Composer({ conv, isNew, smsDids, gvNumber, onChangeDid, ref }: P
<select value={conv.did} onChange={(e) => onChangeDid(e.target.value)}>
{fromDids.map((d) => (
<option key={d.did} value={d.did}>
{formatNumber(d.did)}
{d.provider === 'gvoice' ? ' — Google Voice' : d.description ? ` — ${d.description}` : ''}
{didName(d.did)}
{d.provider === 'gvoice' ? ' — Google Voice' : d.provider !== 'sim' && d.description ? ` — ${d.description}` : ''}
</option>
))}
</select>
@@ -42,6 +42,8 @@ function Attachment({ id, index, media, onOpen, onMenu, onLoad }: { id: number;
const [broken, setBroken] = useState(false)
const src = mediaSrc(id, index)
const kind = mediaKind(media)
// Still on the Rabbit (relayed history): asked for, it arrives after the Rabbit's next check.
if (broken && media.url?.startsWith('mmspart:') && !media.file) return <div className="media-missing">On the Rabbit — it'll appear after its next check</div>
if (broken) return <div className="media-missing">Media unavailable</div>
if (kind === 'image')
return (
@@ -107,7 +109,7 @@ export const MessageBubble = memo(function MessageBubble({ m, sender, onSenderMe
{media.length > 0 && (
<div className="media">
{media.map((ref, i) => (
<Attachment key={i} id={m.id} index={i} media={ref} onOpen={() => onOpenMedia(m.id, i)} onMenu={(e) => onMediaMenu(m.id, i, e)} onLoad={onMediaLoad} />
<Attachment key={`${i}:${ref.file ?? ''}`} id={m.id} index={i} media={ref} onOpen={() => onOpenMedia(m.id, i)} onMenu={(e) => onMediaMenu(m.id, i, e)} onLoad={onMediaLoad} />
))}
</div>
)}
+13 -11
View File
@@ -1,5 +1,5 @@
import { useEffect, useMemo, useRef, useState } from 'react'
import { formatNumber, groupKey, normalizeNumber } from '@shared/phone'
import { formatNumber, groupKey, normalizeNumber, didName, groupsFrom, SIM_DID } from '@shared/phone'
import type { ContactInfo, Conversation, Did } from '@shared/types'
import type { ConvKey } from '../App'
import { Avatar } from './Avatar'
@@ -26,7 +26,9 @@ export function NewChat({ contacts, conversations, smsDids, gvNumber, defaultDid
const [members, setMembers] = useState<string[]>([])
const inputRef = useRef<HTMLInputElement>(null)
const listRef = useRef<HTMLDivElement>(null)
const canGroup = !!from && from === gvNumber
const canGroup = groupsFrom(from, gvNumber)
// Where a new group goes from: Google Voice if it's connected, else the Rabbit's SIM.
const groupDid = gvNumber ?? smsDids.find((d) => d.did === SIM_DID)?.did
useEffect(() => inputRef.current?.focus(), [])
@@ -66,10 +68,10 @@ export function NewChat({ contacts, conversations, smsDids, gvNumber, defaultDid
onPick({ did: existing?.did ?? from, contact })
}
// Groups only exist on Google Voice, so starting one sends from there.
// Groups go from Google Voice or the Rabbit's SIM (voip.ms has none).
const startGroup = (): void => {
if (!gvNumber) return
setFrom(gvNumber)
if (!groupDid) return
if (!groupsFrom(from, gvNumber)) setFrom(groupDid)
setFromChosen(true)
setGrouping(true)
setQ('')
@@ -111,7 +113,7 @@ export function NewChat({ contacts, conversations, smsDids, gvNumber, defaultDid
onChange={(e) => {
setFrom(e.target.value)
setFromChosen(true)
if (e.target.value !== gvNumber) {
if (!groupsFrom(e.target.value, gvNumber)) {
setMembers([])
setGrouping(false)
}
@@ -119,8 +121,8 @@ export function NewChat({ contacts, conversations, smsDids, gvNumber, defaultDid
>
{smsDids.map((d) => (
<option key={d.did} value={d.did}>
{formatNumber(d.did)}
{d.provider === 'gvoice' ? ' — Google Voice' : d.description ? ` — ${d.description}` : ''}
{didName(d.did)}
{d.provider === 'gvoice' ? ' — Google Voice' : d.provider !== 'sim' && d.description ? ` — ${d.description}` : ''}
</option>
))}
</select>
@@ -164,8 +166,8 @@ export function NewChat({ contacts, conversations, smsDids, gvNumber, defaultDid
{!grouping && !q.trim() && (
<button
className="row group-row"
disabled={!gvNumber}
title={gvNumber ? undefined : 'Group chats need Google Voice — connect it in Settings.'}
disabled={!groupDid}
title={groupDid ? undefined : 'Group chats need Google Voice or the Rabbit relay — connect one in Settings.'}
onClick={startGroup}
>
<span className="group-row-icon">
@@ -176,7 +178,7 @@ export function NewChat({ contacts, conversations, smsDids, gvNumber, defaultDid
<span className="row-name">Group chat</span>
</div>
<div className="row-bottom">
<span className="row-preview">{gvNumber ? 'Pick several people, then Done' : 'Needs Google Voice (Settings)'}</span>
<span className="row-preview">{groupDid ? 'Pick several people, then Done' : 'Needs Google Voice or the Rabbit relay (Settings)'}</span>
</div>
</div>
</button>
+103 -4
View File
@@ -1,6 +1,6 @@
import { useEffect, useState } from 'react'
import type { AppState, RabbitStatus } from '@shared/api'
import { formatNumber } from '@shared/phone'
import type { AppState, RabbitStatus, RelayStatus } from '@shared/api'
import { didName, formatNumber } from '@shared/phone'
import type { AddressBook, GvStatus, IconStyle, Settings, SyncStatus, Theme } from '@shared/types'
import { CloseIcon } from './Icons'
@@ -35,7 +35,7 @@ export function SettingsDialog({ state, sync, onClose, onChanged }: Props) {
}
const synced = s.dids.length ? s.dids : smsDids.map((d) => d.did)
const sendFrom = state.gvoiceNumber ? [...synced, state.gvoiceNumber] : synced
const sendFrom = [...synced, ...(state.gvoiceNumber ? [state.gvoiceNumber] : []), ...state.dids.filter((d) => d.provider === 'sim').map((d) => d.did)]
return (
<div className="modal-backdrop" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
@@ -129,6 +129,7 @@ export function SettingsDialog({ state, sync, onClose, onChanged }: Props) {
<ContactsSection value={s.contactBook} onChange={(contactBook) => setS({ ...s, contactBook })} />
<RabbitSection onChanged={onChanged} />
<RelaySection onChanged={onChanged} />
{smsDids.length > 0 && (
<section>
@@ -153,7 +154,7 @@ export function SettingsDialog({ state, sync, onClose, onChanged }: Props) {
<select value={s.defaultDid ?? sendFrom[0]} onChange={(e) => setS({ ...s, defaultDid: e.target.value })}>
{sendFrom.map((d) => (
<option key={d} value={d}>
{formatNumber(d)}
{didName(d)}
{d === state.gvoiceNumber ? ' — Google Voice' : ''}
</option>
))}
@@ -414,3 +415,101 @@ function RabbitSection({ onChanged }: { onChanged: () => void }) {
</section>
)
}
// The Rabbit's SIM (and names + read status) through jai, no cable needed.
function RelaySection({ onChanged }: { onChanged: () => void }) {
const [st, setSt] = useState<RelayStatus>()
const [url, setUrl] = useState('http://100.69.139.40:8080')
const [token, setToken] = useState('')
const [busy, setBusy] = useState(false)
const [error, setError] = useState<string>()
const [done, setDone] = useState<string>()
const refresh = (): void =>
void window.api.relayStatus().then((s) => {
setSt(s)
if (s.url) setUrl(s.url)
})
useEffect(() => {
refresh()
return window.api.onRelayStatus(setSt)
}, [])
const connect = (): void => {
setBusy(true)
setError(undefined)
setDone(undefined)
window.api
.relayConnect(url, token)
.then(() => {
setToken('')
setDone('Connected. Now use Sync to Rabbit (above) once, with the Rabbit plugged in, so it gets the key.')
refresh()
onChanged()
})
.catch((e: Error) => setError(cleanError(e)))
.finally(() => setBusy(false))
}
const disconnect = (): void => {
void window.api.relayDisconnect().then(() => {
setDone(undefined)
refresh()
onChanged()
})
}
const last = st?.lastSync ? new Date(st.lastSync).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }) : undefined
return (
<section>
<h3>Rabbit relay (jai)</h3>
<p className="muted small">
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.
</p>
{st?.connected ? (
<>
<div className="kv">
<span>Relay</span>
<span>{st.url}</span>
</div>
<div className="kv">
<span>Last check</span>
<span>{st.error ? `⚠ ${st.error}` : last ?? 'Not yet'}</span>
</div>
{st.waiting > 0 && (
<div className="kv">
<span>Waiting for the Rabbit</span>
<span>
{st.waiting} text{st.waiting === 1 ? '' : 's'}
</span>
</div>
)}
<div className="btn-row">
<button onClick={disconnect}>Disconnect</button>
</div>
</>
) : (
<>
<label className="field">
Address
<input value={url} onChange={(e) => setUrl(e.target.value)} spellCheck={false} />
</label>
<label className="field">
Token
<input type="password" value={token} onChange={(e) => setToken(e.target.value)} placeholder="from scripts/deploy-jai.sh --token" autoComplete="off" />
</label>
<div className="btn-row">
<button className="primary" disabled={busy || !token.trim()} onClick={connect}>
Connect
</button>
</div>
</>
)}
{done && <p className="muted small">{done}</p>}
{error && <p className="form-error">{error}</p>}
</section>
)
}
+7 -1
View File
@@ -1,7 +1,13 @@
import { formatNumber } from '@shared/phone'
import { formatNumber, SIM_DID } from '@shared/phone'
// "via <number>", 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 <span className="gv-tag">SIM</span>Rabbit
</>
)
return (
<>
via {did === gvNumber && <span className="gv-tag">GV</span>}
+12
View File
@@ -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<AppState>
testCredentials(creds: Credentials): Promise<Did[]>
@@ -32,6 +40,10 @@ export interface Api {
rabbitStatus(): Promise<RabbitStatus>
rabbitInstall(mode?: 'full' | 'update'): Promise<void> // update: app only, keeps its data
rabbitSync(): Promise<void>
relayStatus(): Promise<RelayStatus>
relayConnect(url: string, token: string): Promise<void>
relayDisconnect(): Promise<void>
onRelayStatus(cb: (s: RelayStatus) => void): () => void
onRabbitProgress(cb: (step: string) => void): () => void
listContacts(): Promise<ContactInfo[]>
+14
View File
@@ -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)}`
+1 -1
View File
@@ -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