rtdb_relay 0.2.1: recover the e2e passphrase
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file length / file-length (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
palette drift / palette (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
rtdb_relay dart tests / test (push) Waiting to run
shared gate tests / gate unit tests (push) Waiting to run

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 <app>/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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWY91NZkk1AH6ugi6ya
This commit is contained in:
Krzysztof Rudnicki 2026-11-18 20:52:20 +01:00
parent 073cc24468
commit d36826e2b5
7 changed files with 186 additions and 11 deletions

View File

@ -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`)

View File

@ -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<String?> 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<bool> 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<E2eState> _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,

View File

@ -7,6 +7,9 @@
/// `~/.config/tutor/firebase_auth.json`, written by crdt-sync's
/// `link_google.py`) ONCE, at `<app>/sync-credentials`, and the page keeps it
/// in its own credential store from then on.
///
/// The e2e passphrase comes the same way (`<app>/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<String?> 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<String, dynamic> ? 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('.');

View File

@ -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

View File

@ -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<FakeRtdb> 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());

View File

@ -70,6 +70,33 @@ void main() {
);
});
Future<String?> 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();

View File

@ -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 = [