Compare commits

...

2 Commits

Author SHA1 Message Date
f7e24bbb1a Desktop adopts the E2E passphrase once
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
The wrapper serves ~/.config/crdt-sync/password once on
/sync-e2e-passphrase; the web app stores it in its keystore, so desktop
todo never asks. Android still unlocks via the lock tile.

Todo: fda71ed1

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 09:56:07 +01:00
4423937f5c E2E: key cache, CLI password, lock tile
Argon2id runs once per device (keystore key cache); the CLI/MCP read
~/.config/crdt-sync/password; pull-only merges old and encrypted
prefixes; the settings lock tile follows the last sync and resyncs on
save. Pins crdt_sync 0.14.0, crdt_sync_flutter 0.8.0, sync_settings_ui
0.7.2.

Todo: fda71ed1

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 09:52:15 +01:00
13 changed files with 260 additions and 29 deletions

View File

@ -51,8 +51,13 @@ class CliSession {
this.repository,
this._firebase, {
this.passphraseFile,
this.sharedPasswordFile,
});
/// The fleet-wide crdt-sync password the Python daemons read too
/// (`~/.config/crdt-sync/password`), found from the seed's config root.
final File? sharedPasswordFile;
/// Where the passphrase is read from besides the environment: next to the
/// seeded Firebase session, e.g. `~/.config/todo/e2e_passphrase`.
final File? passphraseFile;
@ -121,6 +126,9 @@ class CliSession {
passphraseFile: File(
p.join(p.dirname(seedCredentials), e2ePassphraseFileName),
),
sharedPasswordFile: File(
p.join(p.dirname(p.dirname(seedCredentials)), 'crdt-sync', 'password'),
),
);
}
@ -142,10 +150,19 @@ class CliSession {
oldPrefix: plainService.notesDir,
readPassphrase: _readPassphrase,
);
if (e2e is! E2eReady && !push) {
// Read-only: nothing encrypted yet (or no key) falls back to the old
// plaintext prefix, which still holds the pre-migration data.
return await const SyncService().sync(repository, _remote(push: false));
if (!push) {
// Read-only during the migration: old builds still write the plaintext
// prefix, so merge it, then the encrypted one when this host has a key.
final plain = await const SyncService().sync(
repository,
_remote(push: false),
);
if (e2e is! E2eReady) return plain;
final layout = E2eLayout.of(plainService.notesDir);
return await SyncService(
notesDir: layout.prefix,
revsPath: layout.revsPath,
).sync(repository, e2e.store);
}
if (e2e is! E2eReady) {
throw StateError(
@ -173,9 +190,13 @@ class CliSession {
Future<String?> _readPassphrase() async {
final fromEnv = Platform.environment[e2ePassphraseEnv];
if (fromEnv != null && fromEnv.isNotEmpty) return fromEnv;
final file = passphraseFile;
if (file == null || !file.existsSync()) return null;
return (await file.readAsString()).trim();
for (final file in [passphraseFile, sharedPasswordFile]) {
if (file != null && file.existsSync()) {
final text = (await file.readAsString()).trim();
if (text.isNotEmpty) return text;
}
}
return null;
}
/// Releases the log and the HTTP client.

View File

@ -7,6 +7,11 @@ import 'package:path/path.dart' as p;
import 'package:todo/desktop/static_content_type.dart';
import 'package:todo/desktop/wrapper_image_routes.dart';
import 'package:todo/sync/e2e_passphrase_source.dart'
show kSyncE2ePassphrasePath;
export 'package:todo/sync/e2e_passphrase_source.dart'
show kSyncE2ePassphrasePath;
export 'wrapper_paths.dart';
@ -86,6 +91,9 @@ class WrapperServer {
/// wrappers also serve, which stays opt-in.
bool _todoCredentialsServed = false;
/// Whether [kSyncE2ePassphrasePath] has served the passphrase yet.
bool _e2ePassphraseServed = false;
/// `todo`'s own seeded Firebase session, written by
/// `crdt-sync/tool/seed_session.py --app todo` in the same
/// `{id_token, refresh_token, expires_at}` shape every other app's
@ -184,6 +192,9 @@ class WrapperServer {
if (path == kSyncCredentialsPath) {
return await _syncCredentials(request);
}
if (path == kSyncE2ePassphrasePath) {
return await _syncE2ePassphrase(request);
}
if (await images.handle(request)) return;
return await _static(request, path);
}

View File

@ -121,4 +121,23 @@ extension _SyncRoutes on WrapperServer {
// through must remain retryable rather than burning the one serve.
_todoCredentialsServed = true;
}
/// Serves the shared crdt-sync password as the E2E passphrase, once per
/// wrapper process, like [_syncCredentials]: the web app stores it in its
/// keystore on first sync and never asks for it.
Future<void> _syncE2ePassphrase(HttpRequest request) async {
final passwordFile = File(p.join(syncConfigDir, 'password'));
if (_e2ePassphraseServed || !passwordFile.existsSync()) {
request.response.statusCode = HttpStatus.notFound;
return;
}
final text = (await passwordFile.readAsString()).trim();
if (text.isEmpty) {
request.response.statusCode = HttpStatus.notFound;
return;
}
request.response.headers.contentType = ContentType.text;
request.response.write(text);
_e2ePassphraseServed = true;
}
}

View File

@ -0,0 +1,38 @@
/// Where todo gets the shared crdt-sync passphrase its E2E key comes from.
///
/// The keystore first. On the desktop (a web build behind the local
/// wrapper) an empty keystore adopts the wrapper's one-shot
/// `/sync-e2e-passphrase` route, which serves `~/.config/crdt-sync/password`,
/// so the desktop app never asks. Android has no wrapper (`Uri.base` is
/// `file:///`) and is unlocked through the settings lock tile instead.
library;
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart'
show kE2ePassphraseKey, kSecureStorage, saveE2ePassphrase;
import 'package:http/http.dart' as http;
/// Path of the wrapper's one-shot passphrase route.
const kSyncE2ePassphrasePath = '/sync-e2e-passphrase';
/// Returns the passphrase, adopting the wrapper's once; null when none.
Future<String?> readE2ePassphrase({Uri? base, http.Client? client}) async {
final stored = await kSecureStorage.read(key: kE2ePassphraseKey);
if (stored != null && stored.isNotEmpty) return stored;
final origin = base ?? Uri.base;
if (origin.scheme != 'http' && origin.scheme != 'https') return null;
final httpClient = client ?? http.Client();
try {
final response = await httpClient.get(
origin.resolve(kSyncE2ePassphrasePath),
);
final text = response.body.trim();
if (response.statusCode != 200 || text.isEmpty) return null;
await saveE2ePassphrase(text);
return text;
} on Object {
// No wrapper, or it already served: this device is simply locked.
return null;
} finally {
if (client == null) httpClient.close();
}
}

View File

@ -7,13 +7,13 @@
library;
import 'package:crdt_sync/crdt_sync.dart';
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart'
show kE2ePassphraseKey, kSecureStorage;
import 'package:flutter/foundation.dart' show visibleForTesting;
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart' show keystoreKeyCache;
import 'package:flutter/foundation.dart' show ValueNotifier, visibleForTesting;
import 'package:http/http.dart' as http;
import 'package:todo/analytics/analytics_service.dart';
import 'package:todo/data/app_settings.dart';
import 'package:todo/data/note_repository.dart';
import 'package:todo/sync/e2e_passphrase_source.dart';
import 'package:todo/sync/firebase_backend.dart';
import 'package:todo/sync/sync_service.dart';
import 'package:todo/sync/sync_settings.dart';
@ -23,6 +23,10 @@ import 'package:todo/sync/sync_state_factory.dart';
@visibleForTesting
Argon2Params e2eArgon2Params = Argon2Params.recommended;
/// Whether the last sync found no usable end-to-end key; drives the lock
/// tile in settings.
final ValueNotifier<bool> e2eLocked = ValueNotifier<bool>(false);
/// Bundles a [SyncResult] with the [AppSettings] as reconciled against the
/// same Firebase session — so a settings change made on another device is
/// picked up without a second authenticated round trip.
@ -90,10 +94,12 @@ Future<SyncRunResult> runSync(
final e2e = await openEncryptedStore(
store: backend,
oldPrefix: service.notesDir,
readPassphrase:
readPassphrase ?? () => kSecureStorage.read(key: kE2ePassphraseKey),
readPassphrase: readPassphrase ?? readE2ePassphrase,
params: e2eArgon2Params,
// Argon2id once per device, not once per tick.
keyCache: keystoreKeyCache(service.notesDir),
);
e2eLocked.value = e2e is! E2eReady;
if (e2e is! E2eReady) {
return const SyncRunResult(
syncResult: SyncResult(mergedDevices: 0, pushed: false, locked: true),

View File

@ -15,6 +15,7 @@ import 'package:todo/sync/backlog_export.dart';
import 'package:todo/sync/firebase_backend.dart';
import 'package:todo/sync/google_sign_in_backend.dart';
import 'package:todo/sync/notes_markdown.dart';
import 'package:todo/sync/run_sync.dart';
import 'package:todo/sync/sync_settings.dart';
import 'package:todo/ui/app_route.dart';
import 'package:todo/ui/cloud_images_settings.dart';
@ -166,6 +167,22 @@ class _SettingsScreenState extends State<SettingsScreen> {
await widget.repository.importNotes(notes);
}
/// Retries the sync after a passphrase is entered; the lock tile follows
/// [e2eLocked], which the run updates.
Future<void> _syncNow() async {
try {
await runSync(
widget.repository,
widget.initial,
httpClient: widget.httpClient,
firebaseFactory: widget.firebaseFactory,
stateStore: widget.stateStore,
);
} on Exception {
// The capture screen's status line reports sync failures.
}
}
Future<void> _openSyncSettings() async {
await Navigator.of(context).push<void>(
appRoute(
@ -225,9 +242,16 @@ class _SettingsScreenState extends State<SettingsScreen> {
const Icon(Icons.sync, semanticLabel: 'Sync settings: Firebase'),
_openSyncSettings,
),
const ListTile(
contentPadding: EdgeInsets.zero,
leading: E2ePassphraseButton(locked: true),
ValueListenableBuilder<bool>(
valueListenable: e2eLocked,
builder: (context, locked, _) => ListTile(
contentPadding: EdgeInsets.zero,
leading: E2ePassphraseButton(
locked: locked,
// A new passphrase is only proven by a sync that unlocks.
onSaved: () => unawaited(_syncNow()),
),
),
),
CloudImagesTile(httpClient: widget.httpClient),
_link(

View File

@ -109,20 +109,20 @@ packages:
dependency: "direct main"
description:
path: crdt_sync_dart
ref: "crdt_sync_dart-v0.13.1"
resolved-ref: eebeb0b51053f160f163140141aba10a447ba1e8
ref: "crdt_sync_dart-v0.14.0"
resolved-ref: "84343aec2dd07c38cba40690c3b5f2c84ae9cdf6"
url: "https://github.com/kuhyx/utils"
source: git
version: "0.13.1"
version: "0.14.0"
crdt_sync_flutter:
dependency: "direct main"
description:
path: crdt_sync_flutter
ref: "crdt_sync_flutter-v0.7.0"
resolved-ref: "307248b60bbb4e71f8625047a379c5aa275b147e"
ref: "crdt_sync_flutter-v0.8.0"
resolved-ref: e5990c9c15761934110f955529bc1d68479b06ff
url: "https://github.com/kuhyx/utils"
source: git
version: "0.7.0"
version: "0.8.0"
cross_file:
dependency: transitive
description:
@ -1023,11 +1023,11 @@ packages:
dependency: "direct main"
description:
path: sync_settings_ui
ref: "sync_settings_ui-v0.7.1"
resolved-ref: eb9bdc5796755c4e02b7a54d83efcdeb4db91af1
ref: "sync_settings_ui-v0.7.2"
resolved-ref: "4567e7ca3042e683befdf6697ace1c8be9c829fc"
url: "https://github.com/kuhyx/utils"
source: git
version: "0.7.1"
version: "0.7.2"
synchronized:
dependency: transitive
description:

View File

@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 1.0.84+1
version: 1.0.86+1
environment:
sdk: ^3.12.2
@ -33,12 +33,12 @@ dependencies:
crdt_sync:
git:
url: https://github.com/kuhyx/utils
ref: crdt_sync_dart-v0.13.1
ref: crdt_sync_dart-v0.14.0
path: crdt_sync_dart
crdt_sync_flutter:
git:
url: https://github.com/kuhyx/utils
ref: crdt_sync_flutter-v0.7.0
ref: crdt_sync_flutter-v0.8.0
path: crdt_sync_flutter
# The following adds the Cupertino Icons font to your application.
@ -102,7 +102,7 @@ dependencies:
sync_settings_ui:
git:
url: https://github.com/kuhyx/utils
ref: sync_settings_ui-v0.7.1
ref: sync_settings_ui-v0.7.2
path: sync_settings_ui
url_launcher: 6.3.3
uuid: 4.6.0

View File

@ -69,6 +69,7 @@ class CliHarness {
/// Publishes [notes] as device [node]'s log.
void seedPeer(List<Note> notes, {String node = 'peer'}) {
resetE2eCopyMemo();
db.files['todo-sync/notes/$node~2Ejson'] = logToJson({
for (final n in notes) n.id: NoteRepository.recordAtNoteTime(n, node),
});

View File

@ -8,6 +8,7 @@ library;
import 'dart:convert';
import 'dart:io';
import 'package:crdt_sync/crdt_sync.dart' show resetE2eCopyMemo;
import 'package:http/http.dart' as http;
import 'package:http/testing.dart' as http_testing;
@ -64,6 +65,8 @@ class FakeRtdb {
/// Writes a Firebase session that does not expire during a test run.
File writeSeedCredentials(Directory dir, {String name = 'seed.json'}) {
// A fresh fake database: the one-time copy must run again for it.
resetE2eCopyMemo();
// The CLI reads its crdt-sync passphrase from beside the seed file.
File('${dir.path}/e2e_passphrase').writeAsStringSync('test-passphrase');
return File('${dir.path}/$name')..writeAsStringSync(

View File

@ -1,4 +1,4 @@
import 'package:crdt_sync/crdt_sync.dart' show Argon2Params;
import 'package:crdt_sync/crdt_sync.dart' show Argon2Params, resetE2eCopyMemo;
import 'package:flutter/services.dart';
import 'package:todo/sync/run_sync.dart' show e2eArgon2Params;
import 'package:flutter_test/flutter_test.dart';
@ -15,6 +15,7 @@ void installFakeSecureStorage({
bool throwing = false,
}) {
const channel = MethodChannel('plugins.it_nomads.com/flutter_secure_storage');
resetE2eCopyMemo();
e2eArgon2Params = const Argon2Params(
memoryKiB: 8,
iterations: 1,

View File

@ -0,0 +1,35 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:todo/sync/run_sync.dart';
import 'capture_screen_harness.dart' show recordingMock;
import 'settings_screen_harness.dart';
void main() {
tearDown(() => e2eLocked.value = false);
testWidgets('the lock tile follows the last sync', (tester) async {
e2eLocked.value = true;
await pumpSettings(tester);
expect(find.byIcon(Icons.lock), findsOneWidget);
e2eLocked.value = false;
await tester.pump();
expect(find.byIcon(Icons.lock_open), findsOneWidget);
});
testWidgets('saving a passphrase retries the sync, which unlocks', (
tester,
) async {
e2eLocked.value = true;
await pumpSettings(tester, httpClient: recordingMock(<String>[]));
await tester.tap(find.byIcon(Icons.lock));
await tester.pumpAndSettle();
await tester.enterText(find.byType(TextField).last, 'test-passphrase');
await tester.tap(find.byIcon(Icons.check));
await tester.runAsync(
() => Future<void>.delayed(const Duration(seconds: 1)),
);
await tester.pump();
expect(e2eLocked.value, isFalse);
});
}

View File

@ -0,0 +1,72 @@
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart' as http_testing;
import 'package:todo/desktop/wrapper_server.dart';
import 'package:todo/sync/e2e_passphrase_source.dart';
import 'fake_secure_storage.dart';
import 'wrapper_server_harness.dart';
void main() {
final h = WrapperHarness()..install();
group('wrapper e2e passphrase route', () {
test('serves the shared password once, then 404s', () async {
final origin = await h.enabledOrigin({'password': 'shared-pw\n'});
final url = Uri.parse('$origin$kSyncE2ePassphrasePath');
final first = await http.get(url);
expect(first.statusCode, HttpStatus.ok);
expect(first.body, 'shared-pw');
expect((await http.get(url)).statusCode, HttpStatus.notFound);
});
test('is 404 without a password file', () async {
final origin = await h.enabledOrigin({});
final url = Uri.parse('$origin$kSyncE2ePassphrasePath');
expect((await http.get(url)).statusCode, HttpStatus.notFound);
});
});
group('readE2ePassphrase', () {
setUp(() {
TestWidgetsFlutterBinding.ensureInitialized();
installFakeSecureStorage(initial: {'crdt_sync_e2e_passphrase': ''});
});
test('adopts the wrapper passphrase into the keystore once', () async {
var calls = 0;
final client = http_testing.MockClient((request) async {
calls++;
return http.Response('from-wrapper', 200);
});
final base = Uri.parse('http://127.0.0.1:1/');
expect(
await readE2ePassphrase(base: base, client: client),
'from-wrapper',
);
expect(
await readE2ePassphrase(base: base, client: client),
'from-wrapper',
);
expect(calls, 1);
});
test('no wrapper (file:// on Android) is just no passphrase', () async {
expect(await readE2ePassphrase(base: Uri.parse('file:///')), isNull);
});
test('a failing wrapper is no passphrase, not a crash', () async {
final client = http_testing.MockClient(
(_) async => http.Response('', 404),
);
final base = Uri.parse('http://127.0.0.1:1/');
expect(await readE2ePassphrase(base: base, client: client), isNull);
final down = http_testing.MockClient(
(_) async => throw const SocketException('x'),
);
expect(await readE2ePassphrase(base: base, client: down), isNull);
});
});
}