diet-guard/app/lib/services/export_keyring_sync.dart
Krzysztof kuhy Rudnicki 617e1ec879
Some checks failed
dependency freshness / dependencies on newest stable (push) Has been cancelled
file-length / file length <= 250 lines (push) Has been cancelled
md-naming / markdown naming convention (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Has been cancelled
Tests / test (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
repo-contract / repo contract (push) Has been cancelled
E2E-encrypt diet_guard sync and export keys
Every sync payload (food log, banks, budget, catering credential,
Body, export keyring) now lives on diet-guard-sync/devices-e2e, sealed
with the Argon2id key from the shared crdt-sync passphrase; record
ids, tombstones and clocks stay clear. Old plaintext nodes are copied
once and never written or deleted. Locked = no pull, no push.

- PC: _sync_e2e.open_e2e over crdt-sync 0.11.0, key and copy memo in
  ~/.local/share/diet_guard/e2e; undecryptable peers are skipped.
- Phone/desktop: sync_e2e.dart, crdt_sync_flutter 0.8.1, lock icon
  in Settings; pullExportKeys goes through the same open.
- wake-alarm weigh-ins read from wake-alarm-sync/devices-e2e (own
  header), on both sides.

Todo: fda71ed1

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 10:31:44 +01:00

88 lines
2.5 KiB
Dart

/// The `export_keys` document: the keyring as a crdt_sync log.
///
/// One record per key id, never deleted, so the merge is a plain union and
/// concurrent mints on two devices both survive. [syncExportKeys] must be
/// handed the end-to-end encrypted store (`sync_e2e.dart`): these are the
/// keys that open every export.
library;
import 'dart:convert';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:diet_guard_app/services/export_keyring.dart';
import 'package:diet_guard_app/services/sync_device_id.dart';
const _keyField = 'k';
const _createdField = 't';
Log _toLog(Iterable<ExportKey> keys, String deviceId) => {
for (final key in keys)
key.kid: Record(
id: key.kid,
fields: {
_keyField: (
base64Encode(key.bytes),
Hlc.newTick(
deviceId,
wallTimeMsOverride: key.createdAt.millisecondsSinceEpoch,
),
),
_createdField: (
key.createdAt.toIso8601String(),
Hlc.newTick(
deviceId,
wallTimeMsOverride: key.createdAt.millisecondsSinceEpoch,
),
),
},
),
};
List<ExportKey> _fromLog(Log log) {
final keys = <ExportKey>[];
for (final record in log.values) {
try {
keys.add(
ExportKey(
record.id,
base64Decode(record.fields[_keyField]!.$1! as String),
DateTime.parse(record.fields[_createdField]!.$1! as String).toUtc(),
),
);
} on Object {
continue; // a malformed peer record is skipped, never fatal
}
}
return keys;
}
/// Pulls peers' keys into [keyring], pushes this device's keys.
///
/// Runs even when the ring is empty, so a fresh device still receives keys.
Future<void> syncExportKeys(
RemoteStore client, {
required ExportKeyring keyring,
required String devicesDir,
String? deviceId,
}) async {
final id = deviceId ?? currentSyncDeviceId;
final merged = await syncLog(
client: client,
deviceId: id,
legacyDeviceId: deviceId == null ? legacySyncDeviceId : null,
pathPrefix: devicesDir,
revsPath: syncRevsDir,
localLog: _toLog(await keyring.all(), id),
encode: (log) => jsonEncode({
for (final entry in log.entries) entry.key: entry.value.toJson(),
}),
decode: (text) => (jsonDecode(text) as Map).cast<String, dynamic>().map(
(kid, data) =>
MapEntry(kid, Record.fromJson(data as Map<String, dynamic>)),
),
filename: 'export_keys.json',
commitMessage: 'diet_guard_app sync',
);
await keyring.mergeKeys(_fromLog(merged));
}