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
+178
View File
@@ -0,0 +1,178 @@
#!/usr/bin/env python3
"""bubble-relay: a mailbox between the desktop app and the Rabbit R1. Runs on jai.
It never sees a message: every blob is AES-256-GCM sealed by the apps with a
key jai doesn't have (the desktop makes it and hands it to the Rabbit over
USB). This only stores opaque base64 strings, hands each device what the
other one posted, and forgets them once picked up (or after KEEP_DAYS).
Standard library only. Bind it to the tailscale address; every request but
/health needs "Authorization: Bearer <token>" (made on first start in
<data>/token, mode 600).
GET /health -> {"ok": true}
POST /sync {"device": "desktop"|"rabbit", "since": <cursor>, "push": ["<blob>", ...]}
-> {"cursor": <n>, "events": ["<blob>", ...], "more": bool}
`since` is the cursor the last answer gave; it also acknowledges everything up
to it, which the other side posted, so those are deleted. `more` = there's
more than fits in one answer: call again with the new cursor. A cursor past
anything this server ever issued (a wiped server) means "from the start".
python3 bubble_relay.py --host 100.69.139.40 --port 8080 --data DIR
"""
import argparse
import json
import os
import re
import secrets
import sqlite3
import sys
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
DEVICES = ("desktop", "rabbit")
KEEP_DAYS = 14
MAX_BODY = 24 * 1024 * 1024 # one request
MAX_BLOB = 12 * 1024 * 1024 # one sealed blob (a few photos)
MAX_PUSH = 2000 # blobs in one request
MAX_ANSWER = 8 * 1024 * 1024 # roughly, per answer (`more` past it)
MAX_STORED = 512 * 1024 * 1024 # everything waiting; pushes past it are refused
BLOB_RE = re.compile(r"^[A-Za-z0-9+/]+={0,2}$")
LOCK = threading.Lock()
class Store:
def __init__(self, path):
self.db = sqlite3.connect(path, check_same_thread=False)
self.db.execute("PRAGMA journal_mode=WAL")
self.db.execute("CREATE TABLE IF NOT EXISTS events (seq INTEGER PRIMARY KEY AUTOINCREMENT,"
" author TEXT NOT NULL, blob TEXT NOT NULL, size INTEGER NOT NULL, created INTEGER NOT NULL)")
self.db.commit()
def issued(self):
"""The highest cursor ever handed out (survives deletions)."""
row = self.db.execute("SELECT seq FROM sqlite_sequence WHERE name = 'events'").fetchone()
return row[0] if row else 0
def stored(self):
return self.db.execute("SELECT COALESCE(SUM(size), 0) FROM events").fetchone()[0]
def sync(self, device, since, pushed):
with LOCK:
now = int(time.time())
issued = self.issued()
if since > issued:
since = 0
# Picked up by this device: gone. Too old for anyone: gone.
self.db.execute("DELETE FROM events WHERE author != ? AND seq <= ?", (device, since))
self.db.execute("DELETE FROM events WHERE created < ?", (now - KEEP_DAYS * 86400,))
if pushed:
incoming = sum(len(b) for b in pushed)
if self.stored() + incoming > MAX_STORED:
self.db.commit()
return None
self.db.executemany("INSERT INTO events (author, blob, size, created) VALUES (?, ?, ?, ?)",
[(device, b, len(b), now) for b in pushed])
self.db.commit()
events, size, cursor, more = [], 0, since, False
for seq, blob in self.db.execute("SELECT seq, blob FROM events WHERE author != ? AND seq > ? ORDER BY seq",
(device, since)):
if events and size + len(blob) > MAX_ANSWER:
more = True
break
events.append(blob)
size += len(blob)
cursor = seq
if not more:
# Nothing left for this device: skip past the other device's own posts too.
cursor = max(cursor, self.issued())
return {"cursor": cursor, "events": events, "more": more}
class Handler(BaseHTTPRequestHandler):
server_version = "bubble-relay"
sys_version = ""
timeout = 60 # a stalled client doesn't hold a thread forever
def _send(self, code, obj):
body = json.dumps(obj, separators=(",", ":")).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(body)
def _authed(self):
got = self.headers.get("Authorization", "")
return secrets.compare_digest(got.encode(), ("Bearer " + self.server.token).encode())
def do_GET(self):
if self.path == "/health":
return self._send(200, {"ok": True})
self._send(404, {"error": "not found"})
def do_POST(self):
if self.path != "/sync":
return self._send(404, {"error": "not found"})
if not self._authed():
return self._send(401, {"error": "unauthorized"})
try:
n = int(self.headers.get("Content-Length") or 0)
except ValueError:
return self._send(400, {"error": "bad length"})
if n < 0 or n > MAX_BODY:
return self._send(413, {"error": "too large"})
try:
req = json.loads(self.rfile.read(n) or b"{}")
device = req.get("device")
since = int(req.get("since", 0))
push = req.get("push", [])
if device not in DEVICES:
raise ValueError("device")
if since < 0:
raise ValueError("since")
if not isinstance(push, list) or len(push) > MAX_PUSH:
raise ValueError("push")
for b in push:
if not isinstance(b, str) or not b or len(b) > MAX_BLOB or not BLOB_RE.match(b):
raise ValueError("blob")
except (ValueError, TypeError, AttributeError) as e:
return self._send(400, {"error": "bad request: %s" % e})
out = self.server.store.sync(device, since, push)
if out is None:
return self._send(507, {"error": "relay full"})
self._send(200, out)
def log_message(self, fmt, *args):
# Method, path and status only: nothing a request carries.
sys.stderr.write("%s %s\n" % (self.log_date_time_string(), fmt % args))
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--host", default="127.0.0.1")
ap.add_argument("--port", type=int, default=8080)
ap.add_argument("--data", required=True)
a = ap.parse_args()
os.makedirs(a.data, mode=0o700, exist_ok=True)
os.chmod(a.data, 0o700)
os.umask(0o077)
tok_path = os.path.join(a.data, "token")
if not os.path.exists(tok_path):
fd = os.open(tok_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, "w") as f:
f.write(secrets.token_urlsafe(32))
srv = ThreadingHTTPServer((a.host, a.port), Handler)
srv.daemon_threads = True
srv.token = open(tok_path).read().strip()
srv.store = Store(os.path.join(a.data, "relay.db"))
print("bubble-relay on %s:%d" % (a.host, a.port), flush=True)
srv.serve_forever()
if __name__ == "__main__":
main()
Executable
+4
View File
@@ -0,0 +1,4 @@
#!/bin/bash
# The one real command line for bubble-relay on jai (~/startup.sh and scripts/deploy-jai.sh both run this).
cd /home/jai/Documents/bubble-server/app || exit 1
exec python3 bubble_relay.py --host 100.69.139.40 --port 8080 --data /home/jai/Documents/bubble-server/data
+80
View File
@@ -0,0 +1,80 @@
"""python3 -m unittest server/test_bubble_relay.py (a real server on localhost, made-up blobs)"""
import json
import os
import socket
import subprocess
import sys
import tempfile
import time
import unittest
import urllib.error
import urllib.request
HERE = os.path.dirname(os.path.abspath(__file__))
class RelayTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.dir = tempfile.mkdtemp()
s = socket.socket()
s.bind(("127.0.0.1", 0))
cls.port = s.getsockname()[1]
s.close()
cls.proc = subprocess.Popen([sys.executable, os.path.join(HERE, "bubble_relay.py"), "--port", str(cls.port),
"--data", cls.dir], stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL)
for _ in range(50):
try:
urllib.request.urlopen("http://127.0.0.1:%d/health" % cls.port, timeout=1)
break
except OSError:
time.sleep(0.1)
cls.token = open(os.path.join(cls.dir, "token")).read().strip()
@classmethod
def tearDownClass(cls):
cls.proc.terminate()
cls.proc.wait()
def call(self, body, token=None, raw=None):
data = raw if raw is not None else json.dumps(body).encode()
req = urllib.request.Request("http://127.0.0.1:%d/sync" % self.port, data=data, method="POST",
headers={"Authorization": "Bearer " + (token or self.token)})
try:
with urllib.request.urlopen(req, timeout=5) as r:
return r.status, json.loads(r.read())
except urllib.error.HTTPError as e:
return e.code, json.loads(e.read())
def test_flow(self):
st, d = self.call({"device": "desktop", "since": 0, "push": ["QUJD", "REVG"]})
self.assertEqual(st, 200)
self.assertEqual(d["events"], []) # never your own
st, r = self.call({"device": "rabbit", "since": 0, "push": ["R0hJ"]})
self.assertEqual(r["events"], ["QUJD", "REVG"])
st, d2 = self.call({"device": "desktop", "since": d["cursor"]})
self.assertEqual(d2["events"], ["R0hJ"])
# Acknowledged by the rabbit: deleted, so nobody gets them again.
self.call({"device": "rabbit", "since": r["cursor"]})
st, again = self.call({"device": "rabbit", "since": 0})
self.assertEqual(again["events"], [])
# A cursor from a wiped server means "from the start".
st, w = self.call({"device": "desktop", "since": 10 ** 9})
self.assertEqual(w["events"], ["R0hJ"])
def test_rejects(self):
self.assertEqual(self.call({"device": "desktop", "since": 0}, token="wrong")[0], 401)
self.assertEqual(self.call({"device": "laptop", "since": 0})[0], 400)
self.assertEqual(self.call({"device": "desktop", "since": 0, "push": ["not base64!"]})[0], 400)
self.assertEqual(self.call({"device": "desktop", "since": 0, "push": [5]})[0], 400)
self.assertEqual(self.call(None, raw=b"{nope")[0], 400)
with urllib.request.urlopen("http://127.0.0.1:%d/health" % self.port) as r:
self.assertEqual(json.loads(r.read()), {"ok": True})
def test_token_file_private(self):
self.assertEqual(os.stat(os.path.join(self.dir, "token")).st_mode & 0o777, 0o600)
self.assertEqual(os.stat(self.dir).st_mode & 0o777, 0o700)
if __name__ == "__main__":
unittest.main()