From d36826e2b5f41f9aa2ec0459a3bd5e1d08563858 Mon Sep 17 00:00:00 2001 From: Krzysztof kuhy Rudnicki Date: Wed, 18 Nov 2026 20:52:20 +0100 Subject: [PATCH] rtdb_relay 0.2.1: recover the e2e passphrase E2eGate takes an optional recover callback. When the key stays locked for want of a passphrase (needsPassphrase or wrongKey), the gate asks it once, saves what it returns into the keystore and opens again. A bad header never asks; a wrong answer leaves the lock button. fetchWrapperPassphrase reads /sync-passphrase from the desktop app's PC wrapper (null on 404, a malformed body, or no wrapper). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WzxdWY91NZkk1AH6ugi6ya --- rtdb_relay/README.md | 2 +- rtdb_relay/dart/lib/src/e2e_gate.dart | 42 ++++++-- .../dart/lib/src/wrapper_credentials.dart | 24 +++++ rtdb_relay/dart/pubspec.yaml | 2 +- rtdb_relay/dart/test/e2e_gate_test.dart | 98 ++++++++++++++++++- .../dart/test/wrapper_credentials_test.dart | 27 +++++ rtdb_relay/pyproject.toml | 2 +- 7 files changed, 186 insertions(+), 11 deletions(-) diff --git a/rtdb_relay/README.md b/rtdb_relay/README.md index 150452f..ff68579 100644 --- a/rtdb_relay/README.md +++ b/rtdb_relay/README.md @@ -13,7 +13,7 @@ check that the package seals and opens exactly those bytes. Python 3.14+ (tested on 3.15.2). Install from a release tag: ```toml -"rtdb-relay @ git+https://github.com/kuhyx/utils@rtdb-relay-v0.2.0#subdirectory=rtdb_relay" +"rtdb-relay @ git+https://github.com/kuhyx/utils@rtdb-relay-v0.2.1#subdirectory=rtdb_relay" ``` ## Wire format (under the app's root, e.g. `todoimpl/v1-e2e`) diff --git a/rtdb_relay/dart/lib/src/e2e_gate.dart b/rtdb_relay/dart/lib/src/e2e_gate.dart index 32e21de..3240a07 100644 --- a/rtdb_relay/dart/lib/src/e2e_gate.dart +++ b/rtdb_relay/dart/lib/src/e2e_gate.dart @@ -6,13 +6,14 @@ library; import 'package:crdt_sync/crdt_sync.dart' show Argon2Params, + E2eLockReason, E2eLocked, E2eReady, E2eState, RemoteStore, RemoteSyncError; import 'package:crdt_sync_flutter/crdt_sync_flutter.dart' - show kSecureStorage, openEncryptedStoreFromKeystore; + show kSecureStorage, openEncryptedStoreFromKeystore, saveE2ePassphrase; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:rtdb_relay/src/rtdb_client.dart'; import 'package:rtdb_relay/src/sealer.dart'; @@ -24,6 +25,7 @@ class E2eGate { required this.client, this.storage = kSecureStorage, this.params = Argon2Params.recommended, + this.recover, }); /// The client whose sealer this sets. @@ -35,6 +37,13 @@ class E2eGate { /// Argon2id cost for a header this device creates. final Argon2Params params; + /// Where a missing or wrong passphrase can be fetched from (the desktop: + /// its PC wrapper, `fetchWrapperPassphrase`). Asked at most once per gate, + /// so a wrong answer cannot loop; the manual entry stays the fallback. + final Future Function()? recover; + + bool _recovered = false; + /// Why the last [unlock] stayed locked; null once open. E2eState? last; @@ -49,12 +58,16 @@ class E2eGate { /// not a crdt log; the PC worker copies the old root itself. Future unlock() async { if (!locked) return true; - final state = await openEncryptedStoreFromKeystore( - store: E2eHeaderStore(client), - oldPrefix: client.layout.base, - storage: storage, - params: params, - ); + var state = await _open(); + final fetch = recover; + if (fetch != null && !_recovered && _passphraseIsTheProblem(state)) { + _recovered = true; + final secret = await fetch(); + if (secret != null) { + await saveE2ePassphrase(secret, storage: storage); + state = await _open(); + } + } last = state; if (state is E2eReady) { client.sealer = RelaySealer( @@ -66,6 +79,21 @@ class E2eGate { return false; } + Future _open() => openEncryptedStoreFromKeystore( + store: E2eHeaderStore(client), + oldPrefix: client.layout.base, + storage: storage, + params: params, + ); + + static bool _passphraseIsTheProblem(E2eState state) => switch (state) { + E2eLocked( + reason: E2eLockReason.needsPassphrase || E2eLockReason.wrongKey, + ) => + true, + _ => false, + }; + /// The lock reason of the last attempt, for the spoken label. String get reason => switch (last) { E2eLocked(:final reason) => reason.name, diff --git a/rtdb_relay/dart/lib/src/wrapper_credentials.dart b/rtdb_relay/dart/lib/src/wrapper_credentials.dart index 2d12462..aee4e4b 100644 --- a/rtdb_relay/dart/lib/src/wrapper_credentials.dart +++ b/rtdb_relay/dart/lib/src/wrapper_credentials.dart @@ -7,6 +7,9 @@ /// `~/.config/tutor/firebase_auth.json`, written by crdt-sync's /// `link_google.py`) ONCE, at `/sync-credentials`, and the page keeps it /// in its own credential store from then on. +/// +/// The e2e passphrase comes the same way (`/sync-passphrase`, the PC's +/// `~/.config/crdt-sync/password`), asked for only while the key is locked. library; import 'dart:convert'; @@ -19,6 +22,27 @@ import 'package:http/http.dart' as http; /// Route, relative to the app's base URL (`/app/sync-credentials`). const kSyncCredentialsRoute = 'sync-credentials'; +/// Route, relative to the app's base URL (`/app/sync-passphrase`). +const kSyncPassphraseRoute = 'sync-passphrase'; + +/// The crdt-sync passphrase the wrapper at [base] hands out, or null when it +/// has none to give (404, malformed, empty, no wrapper at all). +Future fetchWrapperPassphrase({ + required Uri base, + required http.Client client, +}) async { + try { + final res = await client.get(base.resolve(kSyncPassphraseRoute)); + if (res.statusCode != 200) return null; + final body = jsonDecode(utf8.decode(res.bodyBytes)); + final secret = body is Map ? body['passphrase'] : null; + return secret is String && secret.isNotEmpty ? secret : null; + } on Object catch (error) { + log('wrapper passphrase unavailable', level: 800, error: error); + return null; + } +} + /// The Firebase uid inside [idToken] (JWT `user_id`, else `sub`), or null. String? uidOfIdToken(String idToken) { final parts = idToken.split('.'); diff --git a/rtdb_relay/dart/pubspec.yaml b/rtdb_relay/dart/pubspec.yaml index 9d72fa1..194f6ff 100644 --- a/rtdb_relay/dart/pubspec.yaml +++ b/rtdb_relay/dart/pubspec.yaml @@ -4,7 +4,7 @@ description: >- half is the Python rtdb_relay next to this directory). Extracted from the tutor app; any app that talks to a PC worker over RTDB reuses it. publish_to: 'none' -version: 0.2.0 +version: 0.2.1 environment: sdk: ^3.13.5 diff --git a/rtdb_relay/dart/test/e2e_gate_test.dart b/rtdb_relay/dart/test/e2e_gate_test.dart index 9e7538e..3bd9e80 100644 --- a/rtdb_relay/dart/test/e2e_gate_test.dart +++ b/rtdb_relay/dart/test/e2e_gate_test.dart @@ -2,7 +2,7 @@ import 'dart:convert'; import 'package:crdt_sync/crdt_sync.dart' show E2eLayout, E2eLockReason; import 'package:crdt_sync_flutter/crdt_sync_flutter.dart' - show kE2ePassphraseKey; + show kE2ePassphraseKey, kSecureStorage; import 'package:crdt_sync_flutter/testing/fake_secure_storage.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:rtdb_relay/src/e2e_gate.dart'; @@ -109,6 +109,102 @@ void main() { }); }); + group('E2eGate recovery', () { + RtdbClient needy(FakeRtdb db) => RtdbClient( + layout: tutorLayout, + databaseUrl: 'https://fake', + idToken: () async => 'tok', + httpClient: db.client().httpClient, + namespace: '', + sealRequired: true, + ); + + Future headerFor(String passphrase) async { + installFakeSecureStorage(initial: {kE2ePassphraseKey: passphrase}); + final db = FakeRtdb(); + expect( + await E2eGate(client: needy(db), params: fastArgon).unlock(), + isTrue, + ); + return db; + } + + test('a missing passphrase is fetched, kept and opens the key', () async { + final db = await headerFor('right'); + installFakeSecureStorage(); + var asked = 0; + final gate = E2eGate( + client: needy(db), + params: fastArgon, + recover: () async { + asked++; + return 'right'; + }, + ); + expect(await gate.unlock(), isTrue); + expect(asked, 1); + expect(await kSecureStorage.read(key: kE2ePassphraseKey), 'right'); + }); + + test('a wrong stored passphrase is replaced by the fetched one', () async { + final db = await headerFor('right'); + installFakeSecureStorage(initial: {kE2ePassphraseKey: 'wrong'}); + final gate = E2eGate( + client: needy(db), + params: fastArgon, + recover: () async => 'right', + ); + expect(await gate.unlock(), isTrue); + }); + + test( + 'nothing fetched, or fetched wrong, stays locked; asks once', + () async { + final db = await headerFor('right'); + installFakeSecureStorage(); + final none = E2eGate( + client: needy(db), + params: fastArgon, + recover: () async => null, + ); + expect(await none.unlock(), isFalse); + expect(none.reason, E2eLockReason.needsPassphrase.name); + var asked = 0; + final wrong = E2eGate( + client: needy(db), + params: fastArgon, + recover: () async { + asked++; + return 'also-wrong'; + }, + ); + expect(await wrong.unlock(), isFalse); + expect(wrong.reason, E2eLockReason.wrongKey.name); + expect(await wrong.unlock(), isFalse); + expect(asked, 1); + }, + ); + + test('a bad header is not a passphrase problem: never asks', () async { + installFakeSecureStorage(initial: {kE2ePassphraseKey: 'x'}); + final db = FakeRtdb(); + db.root = setAt(db.root, E2eLayout.of(tutorLayout.base).e2ePath, { + 'not': 'a header', + }); + var asked = 0; + final gate = E2eGate( + client: needy(db), + params: fastArgon, + recover: () async { + asked++; + return 'x'; + }, + ); + expect(await gate.unlock(), isFalse); + expect(asked, 0); + }); + }); + test('the header store reads strings only and never deletes', () async { final db = FakeRtdb()..root = setAt(null, 'tutor/e2e', {'x': 1}); final store = E2eHeaderStore(db.client()); diff --git a/rtdb_relay/dart/test/wrapper_credentials_test.dart b/rtdb_relay/dart/test/wrapper_credentials_test.dart index ead3d2d..a00bfe3 100644 --- a/rtdb_relay/dart/test/wrapper_credentials_test.dart +++ b/rtdb_relay/dart/test/wrapper_credentials_test.dart @@ -70,6 +70,33 @@ void main() { ); }); + Future fetch(http.Response Function(http.Request) answer) => + fetchWrapperPassphrase( + base: base, + client: MockClient((r) async { + expect(r.url.path, '/app/sync-passphrase'); + return answer(r); + }), + ); + + test('fetches the PC passphrase, or null', () async { + expect( + await fetch((_) => http.Response(jsonEncode({'passphrase': 'p'}), 200)), + 'p', + ); + expect(await fetch((_) => http.Response('', 404)), isNull); + expect(await fetch((_) => http.Response('[1]', 200)), isNull); + expect( + await fetch((_) => http.Response(jsonEncode({'passphrase': ''}), 200)), + isNull, + ); + expect( + await fetch((_) => http.Response(jsonEncode({'passphrase': 1}), 200)), + isNull, + ); + expect(await fetch((_) => throw http.ClientException('none')), isNull); + }); + test('auth: the desktop adopts on the first session probe', () async { final token = _jwt({'user_id': 'u'}); final store = InMemoryCredentialStore(); diff --git a/rtdb_relay/pyproject.toml b/rtdb_relay/pyproject.toml index 8d62b7b..2c48505 100644 --- a/rtdb_relay/pyproject.toml +++ b/rtdb_relay/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "rtdb-relay" -version = "0.2.0" +version = "0.2.1" description = "Sealed request relay over Firebase RTDB: PC worker (Python) + Flutter client (Dart)" requires-python = ">=3.14" dependencies = [