dashboard/dashboard/sync.py
bashynx fb3c01cdd7 dashPi: a self-hosted home dashboard, its sync server and phone app
The dashboard (Raspberry Pi 3.5" screen + web pages), the end-to-end
encrypted sync mailbox (PHP + SQLite) and the Android companion app
(Flutter), with docs, clean-install checks and screenshots made from
demo data.

Built mostly with an AI coding assistant; not yet reviewed line by line
by a human (see README and SECURITY.md).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 09:56:19 +02:00

622 lines
24 KiB
Python

"""Sync between the dashboard and other devices (the phone app) through a mailbox server
(dash-sync-server: stores encrypted batches it can't read). Each device keeps its own copy of
the data; syncdb.py stamps every change in the plugins' databases, this sends this device's
changes and applies everyone else's — the last change of a row wins.
python3 sync.py setup <server url> [<device token>] the first device: makes the data key,
asks for a passphrase, prints the recovery key
python3 sync.py join <server url> [<device token>] another device: unlocks the key with the passphrase
(no token on the line: it's asked for, not echoed)
python3 sync.py now push + pull once
python3 sync.py status
python3 sync.py passphrase a new passphrase (needs the old one or the recovery key)
Encryption (libsodium, PyNaCl): one random 32-byte data key; each batch = zlib(JSON) sealed with
XChaCha20-Poly1305 (24-byte random nonce, the account in the additional data). The server keeps
the data key only wrapped with a key made from the passphrase (Argon2id), so a new device can
join with the passphrase; the recovery key (the data key itself, base32) replaces a forgotten
passphrase. See dash-sync-server/PROTOCOL.md — the app speaks the same.
State: dash_data/sync/state.json (chmod 600): this device's id, and once set up the server,
token, data key and how far it has read. Without it the databases are still stamped (sync-ready),
nothing is sent.
"""
import base64
import getpass
import hashlib
import importlib
import json
import os
import sys
import threading
import time
import traceback
import urllib.error
import urllib.request
import zlib
import syncdb
HERE = os.path.dirname(os.path.abspath(__file__))
DATA = os.path.join(HERE, "dash_data")
STATE = os.path.join(DATA, "sync", "state.json")
INTERVAL = 300 # s between syncs
CHUNK = 2000 # changes per batch
MAGIC = b"DS1\x00"
KEY_AD = b"dash-sync/key/1"
CHECK_AD = b"dash-sync/key-check/1" # "check" in the wrapped key: proves a recovery key without the passphrase
OPS, MEM = 3, 64 * 1024 * 1024 # Argon2id: fine on a Pi 3 (≈ 1 s) and a phone
status = {"last": None, "error": None, "result": None}
_lock = threading.Lock()
kick_hooks = [] # plugins' steps after a kick's pull (ctx.on_sync)
KICK_EVERY = 60 # s: at most one kick a minute
KICK_AGE = 120 # s a kick message stays valid
_kick = {"t": 0, "made": 0}
# ---- state ------------------------------------------------------------------------------------
def load_state():
try:
with open(STATE) as f:
st = json.load(f)
except (OSError, ValueError):
st = {}
if not st.get("device"):
st["device"] = syncdb.device_id()
save_state(st)
return st
def save_state(st):
os.makedirs(os.path.dirname(STATE), exist_ok=True)
tmp = STATE + ".tmp"
with open(os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), "w") as f:
json.dump(st, f, indent=1)
os.replace(tmp, STATE)
def configured(st=None):
st = st or load_state()
return bool(st.get("server") and st.get("token") and st.get("key"))
# ---- what syncs (the plugins' META["sync"]) ----------------------------------------------------
def specs():
"""[(plugin, db path, tables)] — from the loaded plugins, or (command line) their modules."""
import pluginhost
metas = {n: p.meta for n, p in pluginhost._plugins.items() if not p.error}
if not metas:
for n in pluginhost.discover():
try:
metas[n] = getattr(importlib.import_module(f"plugins.{n}"), "META", {})
except Exception:
continue
out = []
for name, meta in metas.items():
for fname, tables in (meta.get("sync") or {}).items():
out.append((name, os.path.join(DATA, name, fname), tables))
return out
_prepared = set() # the database files stamped since start (prepare_all / push)
def _prepare(name, path, tables, dev):
try:
syncdb.prepare(path, tables, dev)
_prepared.add(path)
except Exception:
print(f"sync: preparing {name}: {traceback.format_exc()}", flush=True)
def prepare_all():
"""Stamp the plugins' databases (at start-up, whether sync is set up or not)."""
dev = load_state()["device"]
for name, path, tables in specs():
if os.path.exists(path): # made on first use: stamped by the first push after that
_prepare(name, path, tables, dev)
# ---- crypto -----------------------------------------------------------------------------------
def _nacl():
try:
from nacl import bindings, pwhash, utils
except ImportError:
sys.exit("sync needs PyNaCl: sudo apt install python3-nacl")
return bindings, pwhash, utils
def seal(key, data, ad):
b, _, u = _nacl()
nonce = u.random(24)
return MAGIC + nonce + b.crypto_aead_xchacha20poly1305_ietf_encrypt(data, ad, nonce, key)
def unseal(key, blob, ad):
b, _, _ = _nacl()
if blob[:4] != MAGIC:
raise ValueError("not a sync batch")
return b.crypto_aead_xchacha20poly1305_ietf_decrypt(blob[28:], ad, blob[4:28], key)
def wrap(key, passphrase):
b, pw, u = _nacl()
salt = u.random(16)
kek = pw.argon2id.kdf(32, passphrase.encode(), salt, opslimit=OPS, memlimit=MEM)
nonce = u.random(24)
box = b.crypto_aead_xchacha20poly1305_ietf_encrypt(key, KEY_AD, nonce, kek)
e = lambda x: base64.b64encode(x).decode()
return {"v": 1, "kdf": "argon2id13", "ops": OPS, "mem": MEM, "salt": e(salt), "nonce": e(nonce), "box": e(box),
"check": e(seal(key, b"ok", CHECK_AD))}
def unwrap(w, passphrase):
b, pw, _ = _nacl()
d = lambda x: base64.b64decode(x)
kek = pw.argon2id.kdf(32, passphrase.encode(), d(w["salt"]), opslimit=w["ops"], memlimit=w["mem"])
try:
return b.crypto_aead_xchacha20poly1305_ietf_decrypt(d(w["box"]), KEY_AD, d(w["nonce"]), kek)
except Exception:
raise ValueError("wrong passphrase")
def recovery_code(key):
s = base64.b32encode(key).decode().rstrip("=")
return "-".join(s[i:i + 4] for i in range(0, len(s), 4))
def from_recovery(code):
s = code.replace("-", "").replace(" ", "").upper()
key = base64.b32decode(s + "=" * (-len(s) % 8))
if len(key) != 32:
raise ValueError("that's not a recovery key")
return key
def _ad(st):
return f"dash-sync/1/{st['account']}".encode()
# ---- the server -------------------------------------------------------------------------------
def call(st, method, path, body=None, raw=False):
url = st["server"].rstrip("/") + path
data, headers = None, {"Authorization": "Bearer " + st["token"], "Accept": "application/json"}
if isinstance(body, bytes):
data, headers["Content-Type"] = body, "application/octet-stream"
elif body is not None:
data, headers["Content-Type"] = json.dumps(body).encode(), "application/json"
req = urllib.request.Request(url, data=data, method=method, headers=headers)
try:
with urllib.request.urlopen(req, timeout=60) as r:
out = r.read()
except urllib.error.HTTPError as e:
msg = e.read().decode(errors="replace")
try:
msg = json.loads(msg).get("error", msg)
except ValueError:
pass
raise RuntimeError(f"server: {e.code} {msg}") from None
return out if raw else json.loads(out or b"{}")
# ---- push / pull ------------------------------------------------------------------------------
def push(st):
"""This device's changes → batches. Marked as sent only after every batch of a file is in."""
sent = 0
for name, path, tables in specs():
if not os.path.exists(path):
continue
if path not in _prepared: # a plugin made it since start: its rows so far get stamped now
_prepare(name, path, tables, st["device"])
items, mark = syncdb.changes(path, tables, name)
for i in range(0, len(items), CHUNK):
part = items[i:i + CHUNK]
plain = zlib.compress(json.dumps({"v": 1, "dev": st["device"], "made": int(time.time() * 1000),
"changes": part}, separators=(",", ":")).encode(), 6)
call(st, "POST", "/v1/batches", seal(st["key_bytes"], plain, _ad(st)))
sent += len(part)
if items:
syncdb.mark_pushed(path, mark)
return sent
def pull(st):
"""Everyone else's batches since the last pull, applied in order. A synced file that's new here
and empty (a plugin installed after the phone already wrote to it) reads from the start, once —
else the batches before it would be passed by for good. state: "files" = the files seen at the
last pull, "behind" = {file: seq} for those still catching up (the rest are at "pulled")."""
got = {"batches": 0, "applied": 0, "skipped": 0, "failed": 0}
sp = [(name, path, tables) for name, path, tables in specs() if os.path.exists(path)]
for name, path, tables in sp:
if path not in _prepared: # made since start: columns + triggers before anything lands
_prepare(name, path, tables, st["device"])
rel = lambda p: os.path.relpath(p, DATA)
pulled, known, behind = st.get("pulled", 0), st.get("files"), dict(st.get("behind") or {})
for _, path, tables in sp:
if pulled and (known is None or rel(path) not in known) and rel(path) not in behind \
and syncdb.is_empty(path, tables):
behind[rel(path)] = 0
st["files"] = [rel(p) for _, p, _ in sp]
at = {path: behind.get(rel(path), pulled) for _, path, _ in sp}
after = min([*at.values(), pulled])
if after < pulled:
print(f"sync: reading from {after} again for {', '.join(rel(p) for p, s in at.items() if s < pulled)}", flush=True)
while True:
j = call(st, "GET", f"/v1/batches?after={after}&limit=50")
if not j["batches"]:
break
for b in j["batches"]:
late = [(n, p, t) for n, p, t in sp if at[p] < b["seq"]]
if b["device"] != st["device_name"] and late:
batch = json.loads(zlib.decompress(unseal(st["key_bytes"], base64.b64decode(b["blob"]), _ad(st))))
if batch.get("dev") != st["device"]:
for name, path, tables in late:
for k, v in syncdb.apply(path, tables, name, batch["changes"]).items():
got[k] += v
if b["seq"] > st.get("pulled", 0):
got["batches"] += 1
for _, path, _ in late:
at[path] = b["seq"]
after = b["seq"]
st["pulled"] = max(st.get("pulled", 0), b["seq"])
st["behind"] = {rel(p): s for p, s in at.items() if s < st["pulled"]}
save_state({k: v for k, v in st.items() if k != "key_bytes"})
st["behind"] = {rel(p): s for p, s in at.items() if s < st.get("pulled", 0)}
save_state({k: v for k, v in st.items() if k != "key_bytes"})
return got
def sync_now():
with _lock:
st = load_state()
if not configured(st):
raise RuntimeError("sync isn't set up (python3 sync.py setup …)")
st["key_bytes"] = base64.b64decode(st["key"])
res = {"pulled": pull(st), "pushed": push(st)}
status.update(last=time.time(), error=None, result=res)
return res
def kick(blob):
"""The phone app's "sync now" over the LAN (POST /api/sync/kick, right after it sent something):
pull, let the plugins work on what came (the band relay → import → summaries), push their
results — so the app gets them at its next pull instead of in 5-15 minutes. blob = a batch
sealed with the data key ({"kick": ms}) — only a device that has the key can send one; it must
be fresh and newer than the last. → (http status, answer)."""
st = load_state()
if not configured(st):
return 409, {"error": "sync isn't set up"}
try:
msg = json.loads(zlib.decompress(unseal(base64.b64decode(st["key"]), blob, _ad(st))))
made = int(msg["kick"])
except Exception:
return 403, {"error": "not a kick"}
now = time.time()
if abs(now * 1000 - made) > KICK_AGE * 1000 or made <= _kick["made"]:
return 403, {"error": "stale kick"}
if now - _kick["t"] < KICK_EVERY:
return 429, {"error": "kicked a moment ago"}
_kick.update(t=now, made=made)
res = sync_now()
wrote = False
for fn in kick_hooks:
try:
wrote = bool(fn()) or wrote
except Exception as e:
print(f"sync: kick step failed: {e}", flush=True)
if wrote:
res["pushed"] += sync_now()["pushed"]
print(f"sync: kick {res}, {round(time.time() - now, 1)} s", flush=True)
return 200, {"ok": True, "pushed": res["pushed"]}
# ---- the phone app's newest build, mirrored for the home network (web /app) -------------------
# The app updates itself from the server (dash-app lib/app/updater.dart); this copy is for a first install /
# a phone that can't update itself yet: http://<the Pi>:8080/app. Only the primary dashboard keeps one.
APP_DIR = os.path.join(DATA, "app")
APP_EVERY = 3600 # s between looks at the server's app.json
def app_info():
"""The mirrored build's app.json (+ "file"), or None."""
try:
with open(os.path.join(APP_DIR, "app.json")) as f:
info = json.load(f)
except (OSError, ValueError):
return None
apk = os.path.join(APP_DIR, "dash-app.apk")
return dict(info, file=apk) if os.path.exists(apk) and os.path.getsize(apk) == info.get("size") else None
def app_mirror():
"""Fetch a newer build than the one here (checksum checked) → its app.json, or None (nothing new)."""
st = load_state()
if not configured(st):
return None
try:
info = call(st, "GET", "/v1/app")
except RuntimeError as e:
if "404" in str(e):
return None
raise
have = app_info()
if have and have.get("build") == info.get("build"):
return None
os.makedirs(APP_DIR, exist_ok=True)
part = os.path.join(APP_DIR, "dash-app.apk.part")
req = urllib.request.Request(st["server"].rstrip("/") + "/v1/app/apk", headers={"Authorization": "Bearer " + st["token"]})
h = hashlib.sha256()
with urllib.request.urlopen(req, timeout=120) as r, open(part, "wb") as f:
while chunk := r.read(1 << 16):
f.write(chunk)
h.update(chunk)
if os.path.getsize(part) != info.get("size") or h.hexdigest() != info.get("sha256"):
os.remove(part)
raise RuntimeError("the app download didn't check out")
os.replace(part, os.path.join(APP_DIR, "dash-app.apk"))
with open(os.path.join(APP_DIR, "app.json.tmp"), "w") as f:
json.dump(info, f)
os.replace(os.path.join(APP_DIR, "app.json.tmp"), os.path.join(APP_DIR, "app.json"))
return info
def worker(store=None):
time.sleep(30)
mirrored = 0
while True:
if configured():
try:
sync_now()
except Exception as e:
status.update(last=time.time(), error=str(e))
print(f"sync: {e}", flush=True)
primary = ((store.cfg.get("sync") or {}).get("primary", True)) if store is not None else True
if primary and time.time() - mirrored > APP_EVERY:
mirrored = time.time()
try:
got = app_mirror()
if got:
print(f"sync: app {got.get('version')} ({got.get('build')}) mirrored for /app", flush=True)
except Exception as e:
print(f"sync: app mirror: {e}", flush=True)
time.sleep(INTERVAL)
_booted = False
def boot(store=None):
"""At start-up (pluginhost.load): stamp the databases, start the worker."""
global _booted
if _booted:
return
_booted = True
prepare_all()
threading.Thread(target=worker, args=(store,), daemon=True, name="sync").start()
# ---- setting up (the command line below and Settings ▸ General ▸ Sync, web.py) ----------------------------
PASS_MIN = 10
def _connect(url, token):
st = load_state()
st.update(server=url.strip().rstrip("/"), token=token.strip())
hello = call(st, "GET", "/v1/hello")
st.update(account=hello["account"], device_name=hello["device"])
return st
def probe(url, token):
"""Is the token good, and does the account have a data key yet? → {account, device, has_key}."""
st = _connect(url, token)
try:
call(st, "GET", "/v1/key")
has = True
except RuntimeError as e:
if "404" not in str(e):
raise
has = False
return {"account": st["account"], "device": st["device_name"], "has_key": has}
def connect(url, token, passphrase=None, recovery=None):
"""Join this dashboard to the sync account. The account's first device makes the data key (wrapped with
`passphrase`) and gets the recovery key back; the others unlock it with the passphrase or the recovery
key. → {"recovery": code or None, "account", "device"} (raises ValueError / RuntimeError)."""
if configured():
raise ValueError("This dashboard is set up already — disconnect it first.")
st = _connect(url, token)
try:
w = call(st, "GET", "/v1/key")
except RuntimeError as e:
if "404" not in str(e):
raise
w = None
code = None
if w is None:
if len(passphrase or "") < PASS_MIN:
raise ValueError(f"The passphrase needs at least {PASS_MIN} characters.")
_, _, u = _nacl()
key = u.random(32)
call(st, "PUT", "/v1/key", wrap(key, passphrase))
code = recovery_code(key)
elif recovery:
key = from_recovery(recovery)
if not recovery_fits(st, w, key):
raise ValueError("That recovery key doesn't open this account's data.")
else:
key = unwrap(w, passphrase or "")
st["key"] = base64.b64encode(key).decode()
st.setdefault("pulled", 0)
save_state(st)
prepare_all()
return {"recovery": code, "account": st["account"], "device": st["device_name"]}
def recovery_fits(st, w, key):
"""Does this key open the account? The wrapped key's "check" says; keys wrapped before it existed: the first
batch (none yet = can't tell, accepted)."""
try:
if w.get("check"):
unseal(key, base64.b64decode(w["check"]), CHECK_AD)
return True
first = call(st, "GET", "/v1/batches?after=0&limit=1").get("batches") or []
if first:
unseal(key, base64.b64decode(first[0]["blob"]), _ad(st))
return True
except Exception: # a wrong key fails to open it (nacl's CryptoError)
return False
def new_passphrase(new, old=None, recovery=None):
"""A new passphrase for the account's key (needs the old one or the recovery key)."""
st = load_state()
if not configured(st):
raise ValueError("Sync isn't set up.")
if len(new or "") < PASS_MIN:
raise ValueError(f"The passphrase needs at least {PASS_MIN} characters.")
key = from_recovery(recovery) if recovery else unwrap(call(st, "GET", "/v1/key"), old or "")
if key != base64.b64decode(st["key"]):
raise ValueError("That doesn't match this dashboard's key.")
call(st, "PUT", "/v1/key?replace=1", wrap(key, new))
def disconnect():
"""Forget the server, token and key here (the data and its stamps stay; joining again resumes)."""
with _lock:
st = load_state()
for k in ("server", "token", "key", "account", "device_name", "pulled", "files", "behind"):
st.pop(k, None)
save_state(st)
status.update(last=None, error=None, result=None)
def devices():
"""The account's devices from the server ([{name, created, last_seen, revoked, you, manager}]) and
whether this one may add / revoke (the one that made the key)."""
j = call(load_state(), "GET", "/v1/devices")
return j.get("devices") or [], bool(j.get("manager"))
def add_device(name):
"""A new device token (only the managing device may) → {name, token, server}."""
st = load_state()
j = call(st, "POST", "/v1/devices", {"name": name})
return {"name": j["name"], "token": j["token"], "server": st["server"]}
def revoke_device(name):
call(load_state(), "POST", "/v1/devices/revoke", {"name": name})
def pair_link(server, token):
"""What the app's connect screen scans: dashpi://connect?server=…&token=… (no passphrase in it)."""
from urllib.parse import urlencode
return "dashpi://connect?" + urlencode({"server": server, "token": token})
def qr_png(text):
"""A PNG of the QR code (python3-qrcode), or None without it."""
try:
import io
import qrcode
except ImportError:
return None
img = qrcode.make(text, box_size=8, border=2)
buf = io.BytesIO()
img.save(buf, format="PNG")
return buf.getvalue()
def view():
"""Settings ▸ General ▸ Sync: where things stand (no secrets)."""
st = load_state()
on = configured(st)
return {"configured": on, "server": st.get("server"), "account": st.get("account"),
"device": st.get("device_name"), "pulled": st.get("pulled"), "last": status["last"],
"error": status["error"], "result": status["result"], "nacl": _have_nacl(), "qr": _have_qr()}
def _have_nacl():
try:
import nacl # noqa: F401
return True
except ImportError:
return False
def _have_qr():
try:
import qrcode # noqa: F401
return True
except ImportError:
return False
# ---- command line -----------------------------------------------------------------------------
def _ask_new_passphrase():
while True:
p = getpass.getpass("New sync passphrase (at least 10 characters): ")
if len(p) < 10:
print("Too short.")
elif p != getpass.getpass("Again: "):
print("They don't match.")
else:
return p
def main(argv):
if len(argv) < 2 or argv[1] not in ("setup", "join", "now", "status", "passphrase"):
sys.exit(__doc__)
cmd = argv[1]
if cmd in ("setup", "join"):
if len(argv) not in (3, 4):
sys.exit(f"python3 sync.py {cmd} <server url> [<device token>]")
token = argv[3] if len(argv) == 4 else getpass.getpass("Device token: ").strip() # left out: asked, not echoed
has = probe(argv[2], token)["has_key"]
if cmd == "setup" and has:
sys.exit("This account already has a data key — use: python3 sync.py join …")
if cmd == "join" and not has:
sys.exit("No data key on the server yet — set up the first device with: python3 sync.py setup …")
try:
res = connect(argv[2], token, _ask_new_passphrase() if cmd == "setup" else getpass.getpass("Sync passphrase: "))
except ValueError as e:
sys.exit(str(e))
if res["recovery"]:
print("\nRecovery key — write it down and keep it somewhere safe. With it you can set a new\n"
"passphrase if you forget yours; without both, the synced data can't be read:\n\n "
+ res["recovery"] + "\n")
print(f"Set up as “{res['device']}” (account {res['account']}). Syncing…")
print(json.dumps(sync_now(), indent=1))
elif cmd == "now":
prepare_all()
print(json.dumps(sync_now(), indent=1))
elif cmd == "status":
st = load_state()
print(json.dumps({"device": st["device"], "configured": configured(st), "server": st.get("server"),
"account": st.get("account"), "name": st.get("device_name"), "pulled": st.get("pulled")}, indent=1))
if configured(st):
print(json.dumps(call(st, "GET", "/v1/hello"), indent=1))
elif cmd == "passphrase":
how = input("Old passphrase (p) or recovery key (r)? ").strip().lower()
rec = input("Recovery key: ") if how == "r" else None
old = None if rec else getpass.getpass("Old passphrase: ")
try:
new_passphrase(_ask_new_passphrase(), old=old, recovery=rec)
except ValueError as e:
sys.exit(str(e))
print("New passphrase set. Devices already set up keep working; new ones join with the new one.")
if __name__ == "__main__":
main(sys.argv)