// Talking to the dash-sync mailbox (PROTOCOL.md "HTTP"): join with a device token + the // passphrase, then pull everyone else's batches and push ours — what the dashboard's // sync.py does every 5 minutes. The token and the data key live in Android's secure storage // (Keystore-backed); the rest (clock, how far we've read) in the store. import 'dart:convert'; import 'dart:typed_data'; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:http/http.dart' as http; import 'crypto.dart'; import 'store.dart'; const chunk = 2000; // changes per batch, like sync.py class SyncSettings { SyncSettings({required this.server, required this.token, required this.account, required this.name, required this.device, required this.key}); final String server, token, account, name, device; final Uint8List key; static const _storage = FlutterSecureStorage(); static Future load() async { final j = await _storage.read(key: 'sync'); if (j == null) return null; final m = jsonDecode(j) as Map; return SyncSettings(server: m['server'], token: m['token'], account: m['account'], name: m['name'], device: m['device'], key: base64Decode(m['key'])); } Future save() => _storage.write( key: 'sync', value: jsonEncode({'server': server, 'token': token, 'account': account, 'name': name, 'device': device, 'key': base64Encode(key)})); static Future forget() => _storage.delete(key: 'sync'); } class SyncError implements Exception { SyncError(this.message); final String message; @override String toString() => message; } Future> _call(String server, String token, String method, String path, {Uint8List? body}) async { final uri = Uri.parse(server.replaceAll(RegExp(r'/+$'), '') + path); final headers = {'Authorization': 'Bearer $token', 'Accept': 'application/json'}; late http.Response r; try { r = method == 'POST' ? await http.post(uri, headers: {...headers, 'Content-Type': 'application/octet-stream'}, body: body) : await http.get(uri, headers: headers); } catch (e) { throw SyncError("Can't reach the server ($e)"); } final j = r.body.isEmpty ? {} : jsonDecode(r.body) as Map; if (r.statusCode >= 400) throw SyncError('Server: ${r.statusCode} ${j['error'] ?? r.body}'); return j; } /// First start: check the token, fetch the wrapped key, unlock it with the passphrase (or take /// the recovery key). The server must already have a key — the dashboard makes it (sync.py setup). Future join(String server, String token, {String? passphrase, String? recovery}) async { final hello = await _call(server, token, 'GET', '/v1/hello'); final Uint8List key; if (recovery != null && recovery.trim().isNotEmpty) { key = SyncCrypto.fromRecovery(recovery); } else { final Map wrapped; try { wrapped = await _call(server, token, 'GET', '/v1/key'); } on SyncError catch (e) { if (e.message.contains('404')) throw SyncError('No key on the server yet — set up the dashboard first.'); rethrow; } key = await SyncCrypto.unwrap(wrapped, passphrase ?? ''); } return SyncSettings(server: server, token: token, account: hello['account'], name: hello['device'], device: SyncStore.randomId().substring(0, 12), key: key); } class SyncResult { int batches = 0, applied = 0, skipped = 0, pushed = 0; @override String toString() => '$batches batches in ($applied applied, $skipped skipped), $pushed changes out'; } /// Pull everyone else's batches since the last one read, then push ours. Future runSync(SyncSettings s, SyncStore store, SyncCrypto crypto) async { final res = SyncResult(); while (true) { final j = await _call(s.server, s.token, 'GET', '/v1/batches?after=${store.meta('pulled')}&limit=50'); final batches = (j['batches'] as List).cast>(); if (batches.isEmpty) break; for (final b in batches) { if (b['device'] != s.name) { final batch = crypto.openBatch(s.key, base64Decode(b['blob'] as String), s.account); if (batch['dev'] != s.device) { final st = store.apply(batch['changes'] as List); res.applied += st['applied']!; res.skipped += st['skipped']!; } res.batches++; } store.setMeta('pulled', b['seq'] as int); // only after the batch is in (applying again is harmless) } } final (items, mark) = store.changes(); for (var i = 0; i < items.length; i += chunk) { final part = items.sublist(i, i + chunk > items.length ? items.length : i + chunk); final blob = crypto.sealBatch(s.key, {'v': 1, 'dev': s.device, 'made': DateTime.now().millisecondsSinceEpoch, 'changes': part}, s.account); await _call(s.server, s.token, 'POST', '/v1/batches', body: blob); res.pushed += part.length; } if (items.isNotEmpty) store.markPushed(mark); return res; }