mirror of
https://github.com/kuhyx/todo-app.git
synced 2026-11-26 18:07:12 +01:00
E2E-encrypt todo sync
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
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
Todo: fda71ed1 Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
c9eb4d6cff
commit
f4913daaa8
@ -46,7 +46,16 @@ Set<String> claudeNodeIds(Map<String, String> env) {
|
|||||||
class CliSession {
|
class CliSession {
|
||||||
/// Wraps already-open parts; [open] is the normal way in. Public so a test
|
/// Wraps already-open parts; [open] is the normal way in. Public so a test
|
||||||
/// can subclass the session and script [sync]'s outcome.
|
/// can subclass the session and script [sync]'s outcome.
|
||||||
CliSession(this.dataDir, this.repository, this._firebase);
|
CliSession(
|
||||||
|
this.dataDir,
|
||||||
|
this.repository,
|
||||||
|
this._firebase, {
|
||||||
|
this.passphraseFile,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// Where the passphrase is read from besides the environment: next to the
|
||||||
|
/// seeded Firebase session, e.g. `~/.config/todo/e2e_passphrase`.
|
||||||
|
final File? passphraseFile;
|
||||||
|
|
||||||
/// File holding this install's persisted CRDT node id.
|
/// File holding this install's persisted CRDT node id.
|
||||||
static const nodeIdFileName = 'node_id';
|
static const nodeIdFileName = 'node_id';
|
||||||
@ -105,7 +114,14 @@ class CliSession {
|
|||||||
auth: auth,
|
auth: auth,
|
||||||
httpClient: httpClient,
|
httpClient: httpClient,
|
||||||
);
|
);
|
||||||
return CliSession(dataDir, repository, firebase);
|
return CliSession(
|
||||||
|
dataDir,
|
||||||
|
repository,
|
||||||
|
firebase,
|
||||||
|
passphraseFile: File(
|
||||||
|
p.join(p.dirname(seedCredentials), e2ePassphraseFileName),
|
||||||
|
),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Pull every peer's log and merge it; with [push], also publish this
|
/// Pull every peer's log and merge it; with [push], also publish this
|
||||||
@ -113,15 +129,53 @@ class CliSession {
|
|||||||
///
|
///
|
||||||
/// Without [push] nothing is written anywhere remote, and the revision cache
|
/// Without [push] nothing is written anywhere remote, and the revision cache
|
||||||
/// is bypassed so a read always sees every peer's current log.
|
/// is bypassed so a read always sees every peer's current log.
|
||||||
Future<SyncResult> sync({required bool push}) {
|
Future<SyncResult> sync({required bool push}) async {
|
||||||
if (!push) {
|
final plainService = SyncService(
|
||||||
return const SyncService().sync(repository, PullOnlyStore(_firebase));
|
stateStore: push
|
||||||
|
? PersistedSyncStateStore(
|
||||||
|
FileLogPersistence(File(p.join(dataDir, syncStateFileName))),
|
||||||
|
)
|
||||||
|
: null,
|
||||||
|
);
|
||||||
|
final e2e = await openEncryptedStore(
|
||||||
|
store: _remote(push: push),
|
||||||
|
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));
|
||||||
}
|
}
|
||||||
return SyncService(
|
if (e2e is! E2eReady) {
|
||||||
stateStore: PersistedSyncStateStore(
|
throw StateError(
|
||||||
FileLogPersistence(File(p.join(dataDir, syncStateFileName))),
|
'sync is locked: put the crdt-sync passphrase in '
|
||||||
),
|
'$e2ePassphraseEnv or ${passphraseFile?.path ?? e2ePassphraseFileName}',
|
||||||
).sync(repository, _firebase);
|
);
|
||||||
|
}
|
||||||
|
final layout = E2eLayout.of(plainService.notesDir);
|
||||||
|
return await SyncService(
|
||||||
|
notesDir: layout.prefix,
|
||||||
|
revsPath: layout.revsPath,
|
||||||
|
stateStore: plainService.stateStore,
|
||||||
|
).sync(repository, e2e.store);
|
||||||
|
}
|
||||||
|
|
||||||
|
RemoteStore _remote({required bool push}) =>
|
||||||
|
push ? _firebase : PullOnlyStore(_firebase);
|
||||||
|
|
||||||
|
/// Environment variable holding the shared crdt-sync passphrase.
|
||||||
|
static const e2ePassphraseEnv = 'TODO_E2E_PASSPHRASE';
|
||||||
|
|
||||||
|
/// File name of the passphrase, beside the seeded Firebase session.
|
||||||
|
static const e2ePassphraseFileName = 'e2e_passphrase';
|
||||||
|
|
||||||
|
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();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Releases the log and the HTTP client.
|
/// Releases the log and the HTTP client.
|
||||||
|
|||||||
@ -73,11 +73,7 @@ class LegacySqliteMigration {
|
|||||||
}
|
}
|
||||||
// coverage:ignore-end
|
// coverage:ignore-end
|
||||||
|
|
||||||
static Future<void> _onUpgrade(
|
static Future<void> _onUpgrade(CrdtTableExecutor db, int from, int to) async {
|
||||||
CrdtTableExecutor db,
|
|
||||||
int from,
|
|
||||||
int to,
|
|
||||||
) async {
|
|
||||||
if (from < 2) {
|
if (from < 2) {
|
||||||
await db.execute(
|
await db.execute(
|
||||||
'ALTER TABLE notes ADD COLUMN status INTEGER NOT NULL DEFAULT 0',
|
'ALTER TABLE notes ADD COLUMN status INTEGER NOT NULL DEFAULT 0',
|
||||||
|
|||||||
@ -7,6 +7,9 @@
|
|||||||
library;
|
library;
|
||||||
|
|
||||||
import 'package:crdt_sync/crdt_sync.dart';
|
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:http/http.dart' as http;
|
import 'package:http/http.dart' as http;
|
||||||
import 'package:todo/analytics/analytics_service.dart';
|
import 'package:todo/analytics/analytics_service.dart';
|
||||||
import 'package:todo/data/app_settings.dart';
|
import 'package:todo/data/app_settings.dart';
|
||||||
@ -16,6 +19,10 @@ import 'package:todo/sync/sync_service.dart';
|
|||||||
import 'package:todo/sync/sync_settings.dart';
|
import 'package:todo/sync/sync_settings.dart';
|
||||||
import 'package:todo/sync/sync_state_factory.dart';
|
import 'package:todo/sync/sync_state_factory.dart';
|
||||||
|
|
||||||
|
/// Argon2id cost for new headers; only tests lower it.
|
||||||
|
@visibleForTesting
|
||||||
|
Argon2Params e2eArgon2Params = Argon2Params.recommended;
|
||||||
|
|
||||||
/// Bundles a [SyncResult] with the [AppSettings] as reconciled against the
|
/// Bundles a [SyncResult] with the [AppSettings] as reconciled against the
|
||||||
/// same Firebase session — so a settings change made on another device is
|
/// same Firebase session — so a settings change made on another device is
|
||||||
/// picked up without a second authenticated round trip.
|
/// picked up without a second authenticated round trip.
|
||||||
@ -44,8 +51,12 @@ class SyncRunResult {
|
|||||||
/// rather than each concern (notes, settings, analytics) opening and
|
/// rather than each concern (notes, settings, analytics) opening and
|
||||||
/// closing its own.
|
/// closing its own.
|
||||||
///
|
///
|
||||||
/// [firebaseFactory] and [stateStore] exist for tests, which must not reach
|
/// [firebaseFactory], [stateStore] and [readPassphrase] exist for tests, which
|
||||||
/// the OS keystore or an application-support directory.
|
/// must not reach the OS keystore or an application-support directory.
|
||||||
|
///
|
||||||
|
/// Everything pushed is end-to-end encrypted under the shared crdt-sync
|
||||||
|
/// passphrase; without a usable key the run is a no-op flagged
|
||||||
|
/// [SyncResult.locked] rather than a plaintext sync.
|
||||||
Future<SyncRunResult> runSync(
|
Future<SyncRunResult> runSync(
|
||||||
NoteRepository repository,
|
NoteRepository repository,
|
||||||
SyncSettings settings, {
|
SyncSettings settings, {
|
||||||
@ -54,6 +65,7 @@ Future<SyncRunResult> runSync(
|
|||||||
http.Client? httpClient,
|
http.Client? httpClient,
|
||||||
Future<FirebaseRestClient?> Function()? firebaseFactory,
|
Future<FirebaseRestClient?> Function()? firebaseFactory,
|
||||||
SyncStateStore? stateStore,
|
SyncStateStore? stateStore,
|
||||||
|
Future<String?> Function()? readPassphrase,
|
||||||
}) async {
|
}) async {
|
||||||
final github = GitHubClient(
|
final github = GitHubClient(
|
||||||
owner: settings.owner,
|
owner: settings.owner,
|
||||||
@ -72,12 +84,27 @@ Future<SyncRunResult> runSync(
|
|||||||
stateStore: stateStore ?? await openSyncStateStore(),
|
stateStore: stateStore ?? await openSyncStateStore(),
|
||||||
// coverage:ignore-end
|
// coverage:ignore-end
|
||||||
);
|
);
|
||||||
final result = await service.sync(
|
final backend = firebase == null
|
||||||
repository,
|
? github
|
||||||
firebase == null
|
: MirrorStore(primary: firebase, mirror: github);
|
||||||
? github
|
final e2e = await openEncryptedStore(
|
||||||
: MirrorStore(primary: firebase, mirror: github),
|
store: backend,
|
||||||
|
oldPrefix: service.notesDir,
|
||||||
|
readPassphrase:
|
||||||
|
readPassphrase ?? () => kSecureStorage.read(key: kE2ePassphraseKey),
|
||||||
|
params: e2eArgon2Params,
|
||||||
);
|
);
|
||||||
|
if (e2e is! E2eReady) {
|
||||||
|
return const SyncRunResult(
|
||||||
|
syncResult: SyncResult(mergedDevices: 0, pushed: false, locked: true),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
final layout = E2eLayout.of(service.notesDir);
|
||||||
|
final result = await SyncService(
|
||||||
|
notesDir: layout.prefix,
|
||||||
|
revsPath: layout.revsPath,
|
||||||
|
stateStore: service.stateStore,
|
||||||
|
).sync(repository, e2e.store);
|
||||||
await analytics?.flush(firebase);
|
await analytics?.flush(firebase);
|
||||||
return SyncRunResult(
|
return SyncRunResult(
|
||||||
syncResult: result.withFirebaseConnected(value: firebase != null),
|
syncResult: result.withFirebaseConnected(value: firebase != null),
|
||||||
|
|||||||
@ -11,6 +11,7 @@ class SyncResult {
|
|||||||
this.skippedFiles = const [],
|
this.skippedFiles = const [],
|
||||||
this.skippedUnchanged = 0,
|
this.skippedUnchanged = 0,
|
||||||
this.firebaseConnected = false,
|
this.firebaseConnected = false,
|
||||||
|
this.locked = false,
|
||||||
});
|
});
|
||||||
|
|
||||||
/// How many other devices' logs were pulled and merged.
|
/// How many other devices' logs were pulled and merged.
|
||||||
@ -41,6 +42,10 @@ class SyncResult {
|
|||||||
/// device dropping out.
|
/// device dropping out.
|
||||||
final int skippedUnchanged;
|
final int skippedUnchanged;
|
||||||
|
|
||||||
|
/// True when end-to-end encryption has no usable key on this device, so
|
||||||
|
/// nothing was pulled, merged or pushed.
|
||||||
|
final bool locked;
|
||||||
|
|
||||||
/// Returns a copy with [firebaseConnected] set. [SyncService] never sets
|
/// Returns a copy with [firebaseConnected] set. [SyncService] never sets
|
||||||
/// it -- only [runSync], which is the layer that knows which [RemoteStore]
|
/// it -- only [runSync], which is the layer that knows which [RemoteStore]
|
||||||
/// it built -- so this is the seam that lets it do that without
|
/// it built -- so this is the seam that lets it do that without
|
||||||
@ -51,6 +56,7 @@ class SyncResult {
|
|||||||
skippedFiles: skippedFiles,
|
skippedFiles: skippedFiles,
|
||||||
skippedUnchanged: skippedUnchanged,
|
skippedUnchanged: skippedUnchanged,
|
||||||
firebaseConnected: value,
|
firebaseConnected: value,
|
||||||
|
locked: locked,
|
||||||
);
|
);
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@ -73,7 +79,11 @@ class SyncResult {
|
|||||||
/// two never share a path and an old client can't misread a new file.
|
/// two never share a path and an old client can't misread a new file.
|
||||||
class SyncService {
|
class SyncService {
|
||||||
/// Creates a [SyncService], optionally overriding [notesDir].
|
/// Creates a [SyncService], optionally overriding [notesDir].
|
||||||
const SyncService({this.notesDir = 'todo-sync/notes', this.stateStore});
|
const SyncService({
|
||||||
|
this.notesDir = 'todo-sync/notes',
|
||||||
|
this.stateStore,
|
||||||
|
this.revsPath,
|
||||||
|
});
|
||||||
|
|
||||||
/// Directory in the repo under which per-device note-log files live.
|
/// Directory in the repo under which per-device note-log files live.
|
||||||
final String notesDir;
|
final String notesDir;
|
||||||
@ -87,7 +97,11 @@ class SyncService {
|
|||||||
final SyncStateStore? stateStore;
|
final SyncStateStore? stateStore;
|
||||||
|
|
||||||
/// Where revisions live, as a sibling of [notesDir].
|
/// Where revisions live, as a sibling of [notesDir].
|
||||||
String get revsDir => defaultRevsPath(notesDir);
|
/// Revision cache directory; null derives it from [notesDir].
|
||||||
|
final String? revsPath;
|
||||||
|
|
||||||
|
/// Where peers publish their revisions.
|
||||||
|
String get revsDir => revsPath ?? defaultRevsPath(notesDir);
|
||||||
|
|
||||||
/// Runs a full pull-merge-push cycle. Safe to call repeatedly.
|
/// Runs a full pull-merge-push cycle. Safe to call repeatedly.
|
||||||
///
|
///
|
||||||
@ -123,7 +137,15 @@ class SyncService {
|
|||||||
skippedUnchanged++;
|
skippedUnchanged++;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
final text = await remote.getFileText('$notesDir/$name');
|
final String? text;
|
||||||
|
try {
|
||||||
|
text = await remote.getFileText('$notesDir/$name');
|
||||||
|
} on E2eDecryptError {
|
||||||
|
// Wrong key, tampered blob or a newer format: skipped and reported,
|
||||||
|
// never merged and never fatal.
|
||||||
|
skipped.add(name);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
final remoteLog = text == null ? null : _decodeLog(text);
|
final remoteLog = text == null ? null : _decodeLog(text);
|
||||||
if (remoteLog == null) {
|
if (remoteLog == null) {
|
||||||
// A vanished or undecodable peer file must not abort the sync, but
|
// A vanished or undecodable peer file must not abort the sync, but
|
||||||
|
|||||||
@ -98,6 +98,7 @@ class SyncStatusStore {
|
|||||||
/// precisely how a desktop stuck syncing over the GitHub mirror alone
|
/// precisely how a desktop stuck syncing over the GitHub mirror alone
|
||||||
/// went unnoticed for days.
|
/// went unnoticed for days.
|
||||||
String describeSyncResult(SyncResult result) {
|
String describeSyncResult(SyncResult result) {
|
||||||
|
if (result.locked) return '🔒';
|
||||||
final skipped = result.skippedFiles.length;
|
final skipped = result.skippedFiles.length;
|
||||||
final backend = result.firebaseConnected
|
final backend = result.firebaseConnected
|
||||||
? ''
|
? ''
|
||||||
|
|||||||
@ -100,7 +100,10 @@ class CaptureSyncRunner {
|
|||||||
ok: true,
|
ok: true,
|
||||||
detail: detail,
|
detail: detail,
|
||||||
reconciled: result.appSettings,
|
reconciled: result.appSettings,
|
||||||
degraded: !synced.firebaseConnected || synced.skippedFiles.isNotEmpty,
|
degraded:
|
||||||
|
synced.locked ||
|
||||||
|
!synced.firebaseConnected ||
|
||||||
|
synced.skippedFiles.isNotEmpty,
|
||||||
);
|
);
|
||||||
} on Exception catch (e) {
|
} on Exception catch (e) {
|
||||||
await status.record(ok: false, detail: '$e', live: live());
|
await status.record(ok: false, detail: '$e', live: live());
|
||||||
|
|||||||
@ -1,6 +1,8 @@
|
|||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
|
||||||
import 'package:crdt_sync/crdt_sync.dart';
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart'
|
||||||
|
show E2ePassphraseButton;
|
||||||
import 'package:file_selector/file_selector.dart';
|
import 'package:file_selector/file_selector.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:http/http.dart' as http;
|
import 'package:http/http.dart' as http;
|
||||||
@ -223,6 +225,10 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
|||||||
const Icon(Icons.sync, semanticLabel: 'Sync settings: Firebase'),
|
const Icon(Icons.sync, semanticLabel: 'Sync settings: Firebase'),
|
||||||
_openSyncSettings,
|
_openSyncSettings,
|
||||||
),
|
),
|
||||||
|
const ListTile(
|
||||||
|
contentPadding: EdgeInsets.zero,
|
||||||
|
leading: E2ePassphraseButton(locked: true),
|
||||||
|
),
|
||||||
CloudImagesTile(httpClient: widget.httpClient),
|
CloudImagesTile(httpClient: widget.httpClient),
|
||||||
_link(
|
_link(
|
||||||
Icon(
|
Icon(
|
||||||
|
|||||||
29
pubspec.lock
29
pubspec.lock
@ -109,11 +109,20 @@ packages:
|
|||||||
dependency: "direct main"
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
path: crdt_sync_dart
|
path: crdt_sync_dart
|
||||||
ref: "crdt_sync_dart-v0.12.1"
|
ref: "crdt_sync_dart-v0.13.1"
|
||||||
resolved-ref: "6641d85f0550ca60433fc8e0d13a3dafdbb664d6"
|
resolved-ref: eebeb0b51053f160f163140141aba10a447ba1e8
|
||||||
url: "https://github.com/kuhyx/utils"
|
url: "https://github.com/kuhyx/utils"
|
||||||
source: git
|
source: git
|
||||||
version: "0.12.1"
|
version: "0.13.1"
|
||||||
|
crdt_sync_flutter:
|
||||||
|
dependency: "direct main"
|
||||||
|
description:
|
||||||
|
path: crdt_sync_flutter
|
||||||
|
ref: "crdt_sync_flutter-v0.7.0"
|
||||||
|
resolved-ref: "307248b60bbb4e71f8625047a379c5aa275b147e"
|
||||||
|
url: "https://github.com/kuhyx/utils"
|
||||||
|
source: git
|
||||||
|
version: "0.7.0"
|
||||||
cross_file:
|
cross_file:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@ -130,6 +139,14 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "3.0.8"
|
version: "3.0.8"
|
||||||
|
cryptography:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: cryptography
|
||||||
|
sha256: "3eda3029d34ec9095a27a198ac9785630fe525c0eb6a49f3d575272f8e792ef0"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "2.9.0"
|
||||||
cupertino_icons:
|
cupertino_icons:
|
||||||
dependency: "direct main"
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
@ -1006,11 +1023,11 @@ packages:
|
|||||||
dependency: "direct main"
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
path: sync_settings_ui
|
path: sync_settings_ui
|
||||||
ref: "sync_settings_ui-v0.7.0"
|
ref: "sync_settings_ui-v0.7.1"
|
||||||
resolved-ref: "3084080d744c348a217727e26a6be838e7d5a4ff"
|
resolved-ref: eb9bdc5796755c4e02b7a54d83efcdeb4db91af1
|
||||||
url: "https://github.com/kuhyx/utils"
|
url: "https://github.com/kuhyx/utils"
|
||||||
source: git
|
source: git
|
||||||
version: "0.7.0"
|
version: "0.7.1"
|
||||||
synchronized:
|
synchronized:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
|
|||||||
11
pubspec.yaml
11
pubspec.yaml
@ -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
|
# 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
|
# 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.
|
# of the product and file versions while build-number is used as the build suffix.
|
||||||
version: 1.0.83+1
|
version: 1.0.84+1
|
||||||
|
|
||||||
environment:
|
environment:
|
||||||
sdk: ^3.12.2
|
sdk: ^3.12.2
|
||||||
@ -33,8 +33,13 @@ dependencies:
|
|||||||
crdt_sync:
|
crdt_sync:
|
||||||
git:
|
git:
|
||||||
url: https://github.com/kuhyx/utils
|
url: https://github.com/kuhyx/utils
|
||||||
ref: crdt_sync_dart-v0.12.1
|
ref: crdt_sync_dart-v0.13.1
|
||||||
path: crdt_sync_dart
|
path: crdt_sync_dart
|
||||||
|
crdt_sync_flutter:
|
||||||
|
git:
|
||||||
|
url: https://github.com/kuhyx/utils
|
||||||
|
ref: crdt_sync_flutter-v0.7.0
|
||||||
|
path: crdt_sync_flutter
|
||||||
|
|
||||||
# The following adds the Cupertino Icons font to your application.
|
# The following adds the Cupertino Icons font to your application.
|
||||||
# Use with the CupertinoIcons class for iOS style icons.
|
# Use with the CupertinoIcons class for iOS style icons.
|
||||||
@ -97,7 +102,7 @@ dependencies:
|
|||||||
sync_settings_ui:
|
sync_settings_ui:
|
||||||
git:
|
git:
|
||||||
url: https://github.com/kuhyx/utils
|
url: https://github.com/kuhyx/utils
|
||||||
ref: sync_settings_ui-v0.7.0
|
ref: sync_settings_ui-v0.7.1
|
||||||
path: sync_settings_ui
|
path: sync_settings_ui
|
||||||
url_launcher: 6.3.3
|
url_launcher: 6.3.3
|
||||||
uuid: 4.6.0
|
uuid: 4.6.0
|
||||||
|
|||||||
@ -47,8 +47,9 @@ void main() {
|
|||||||
expect(pubspec, contains('google_account_token-v0.1.0'));
|
expect(pubspec, contains('google_account_token-v0.1.0'));
|
||||||
expect(pubspec, isNot(contains('google_sign_in')));
|
expect(pubspec, isNot(contains('google_sign_in')));
|
||||||
expect(
|
expect(
|
||||||
File('android/app/src/main/kotlin/dev/kuhy/todo/AccountTokenChannel.kt')
|
File(
|
||||||
.existsSync(),
|
'android/app/src/main/kotlin/dev/kuhy/todo/AccountTokenChannel.kt',
|
||||||
|
).existsSync(),
|
||||||
isFalse,
|
isFalse,
|
||||||
);
|
);
|
||||||
expect(File('lib/sync/account_token.dart').existsSync(), isFalse);
|
expect(File('lib/sync/account_token.dart').existsSync(), isFalse);
|
||||||
|
|||||||
@ -95,10 +95,7 @@ void main() {
|
|||||||
const service = AnalyticsService(nodeId: 'device-a');
|
const service = AnalyticsService(nodeId: 'device-a');
|
||||||
for (var i = 0; i < AnalyticsService.maxBufferedEvents + 5; i++) {
|
for (var i = 0; i < AnalyticsService.maxBufferedEvents + 5; i++) {
|
||||||
await service.logEvent(
|
await service.logEvent(
|
||||||
AnalyticsEvent(
|
AnalyticsEvent(name: 'event_$i', timestamp: DateTime.now()),
|
||||||
name: 'event_$i',
|
|
||||||
timestamp: DateTime.now(),
|
|
||||||
),
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -135,42 +135,39 @@ void main() {
|
|||||||
expect((remaining.single as Map)['name'], 'mid_flush_event');
|
expect((remaining.single as Map)['name'], 'mid_flush_event');
|
||||||
});
|
});
|
||||||
|
|
||||||
test(
|
test('restores the claimed batch ahead of events logged mid-flush on '
|
||||||
'restores the claimed batch ahead of events logged mid-flush on '
|
'failure', () async {
|
||||||
'failure',
|
// The HTTP handler runs mid-`putFileText`, strictly after flush()
|
||||||
() async {
|
// has already claimed (cleared) the buffer, so writing here is a
|
||||||
// The HTTP handler runs mid-`putFileText`, strictly after flush()
|
// genuine race rather than something that could instead land before
|
||||||
// has already claimed (cleared) the buffer, so writing here is a
|
// or after `flush()` depending on scheduling.
|
||||||
// genuine race rather than something that could instead land before
|
final client = _fakeClient((_) async {
|
||||||
// or after `flush()` depending on scheduling.
|
|
||||||
final client = _fakeClient((_) async {
|
|
||||||
final prefs = await SharedPreferences.getInstance();
|
|
||||||
await prefs.setString(
|
|
||||||
'analytics.buffer',
|
|
||||||
jsonEncode([
|
|
||||||
AnalyticsEvent(
|
|
||||||
name: 'mid_flush_event',
|
|
||||||
timestamp: DateTime(2026),
|
|
||||||
).toJson(),
|
|
||||||
]),
|
|
||||||
);
|
|
||||||
return http.Response('error', 500);
|
|
||||||
});
|
|
||||||
const service = AnalyticsService(nodeId: 'device-a');
|
|
||||||
await service.logEvent(
|
|
||||||
AnalyticsEvent(name: 'app_open', timestamp: DateTime(2026)),
|
|
||||||
);
|
|
||||||
|
|
||||||
await service.flush(client);
|
|
||||||
|
|
||||||
final prefs = await SharedPreferences.getInstance();
|
final prefs = await SharedPreferences.getInstance();
|
||||||
final remaining =
|
await prefs.setString(
|
||||||
jsonDecode(prefs.getString('analytics.buffer')!) as List;
|
'analytics.buffer',
|
||||||
expect(remaining, hasLength(2));
|
jsonEncode([
|
||||||
expect((remaining[0] as Map)['name'], 'app_open');
|
AnalyticsEvent(
|
||||||
expect((remaining[1] as Map)['name'], 'mid_flush_event');
|
name: 'mid_flush_event',
|
||||||
},
|
timestamp: DateTime(2026),
|
||||||
);
|
).toJson(),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
return http.Response('error', 500);
|
||||||
|
});
|
||||||
|
const service = AnalyticsService(nodeId: 'device-a');
|
||||||
|
await service.logEvent(
|
||||||
|
AnalyticsEvent(name: 'app_open', timestamp: DateTime(2026)),
|
||||||
|
);
|
||||||
|
|
||||||
|
await service.flush(client);
|
||||||
|
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
final remaining =
|
||||||
|
jsonDecode(prefs.getString('analytics.buffer')!) as List;
|
||||||
|
expect(remaining, hasLength(2));
|
||||||
|
expect((remaining[0] as Map)['name'], 'app_open');
|
||||||
|
expect((remaining[1] as Map)['name'], 'mid_flush_event');
|
||||||
|
});
|
||||||
|
|
||||||
test(
|
test(
|
||||||
'a RemoteSyncError from an expired session restores the buffer',
|
'a RemoteSyncError from an expired session restores the buffer',
|
||||||
|
|||||||
@ -91,9 +91,7 @@ void main() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('swallows a push failure and keeps the local write', () async {
|
test('swallows a push failure and keeps the local write', () async {
|
||||||
final client = _fakeClient(
|
final client = _fakeClient((_) async => http.Response('error', 500));
|
||||||
(_) async => http.Response('error', 500),
|
|
||||||
);
|
|
||||||
const initial = AppSettings(advancedMode: false);
|
const initial = AppSettings(advancedMode: false);
|
||||||
|
|
||||||
final updated = await initial.withAdvancedMode(
|
final updated = await initial.withAdvancedMode(
|
||||||
@ -107,22 +105,19 @@ void main() {
|
|||||||
expect(reloaded.advancedMode, isTrue);
|
expect(reloaded.advancedMode, isTrue);
|
||||||
});
|
});
|
||||||
|
|
||||||
test(
|
test('swallows a FirebaseAuthError (expired session) and keeps the local '
|
||||||
'swallows a FirebaseAuthError (expired session) and keeps the local '
|
'write', () async {
|
||||||
'write',
|
const initial = AppSettings(advancedMode: false);
|
||||||
() async {
|
|
||||||
const initial = AppSettings(advancedMode: false);
|
|
||||||
|
|
||||||
final updated = await initial.withAdvancedMode(
|
final updated = await initial.withAdvancedMode(
|
||||||
value: true,
|
value: true,
|
||||||
client: _authFailingClient(),
|
client: _authFailingClient(),
|
||||||
);
|
);
|
||||||
|
|
||||||
expect(updated.advancedMode, isTrue);
|
expect(updated.advancedMode, isTrue);
|
||||||
final reloaded = await AppSettings.load();
|
final reloaded = await AppSettings.load();
|
||||||
expect(reloaded.advancedMode, isTrue);
|
expect(reloaded.advancedMode, isTrue);
|
||||||
},
|
});
|
||||||
);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
group('reconcileWithRemote', () {
|
group('reconcileWithRemote', () {
|
||||||
@ -220,9 +215,7 @@ void main() {
|
|||||||
() async {
|
() async {
|
||||||
const initial = AppSettings(advancedMode: false);
|
const initial = AppSettings(advancedMode: false);
|
||||||
|
|
||||||
final result = await initial.reconcileWithRemote(
|
final result = await initial.reconcileWithRemote(_authFailingClient());
|
||||||
_authFailingClient(),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(identical(result, initial), isTrue);
|
expect(identical(result, initial), isTrue);
|
||||||
},
|
},
|
||||||
|
|||||||
@ -20,61 +20,59 @@ import 'fake_note_repository.dart';
|
|||||||
import 'fake_secure_storage.dart';
|
import 'fake_secure_storage.dart';
|
||||||
|
|
||||||
import 'capture_screen_harness.dart';
|
import 'capture_screen_harness.dart';
|
||||||
|
import 'e2e_github_header.dart';
|
||||||
import 'text_free_guard.dart';
|
import 'text_free_guard.dart';
|
||||||
|
|
||||||
void main() {
|
void main() {
|
||||||
testWidgets(
|
testWidgets('auto-sync adopts a newer advancedMode value from Firebase', (
|
||||||
'auto-sync adopts a newer advancedMode value from Firebase',
|
tester,
|
||||||
(tester) async {
|
) async {
|
||||||
final remoteTime = DateTime(2026, 6);
|
final remoteTime = DateTime(2026, 6);
|
||||||
final firebase = FirebaseRestClient(
|
final firebase = FirebaseRestClient(
|
||||||
databaseUrl: 'https://x-rtdb.europe-west1.firebasedatabase.app',
|
databaseUrl: 'https://x-rtdb.europe-west1.firebasedatabase.app',
|
||||||
auth: FirebaseTokenProvider(
|
auth: FirebaseTokenProvider(
|
||||||
apiKey: 'AIzaKey',
|
apiKey: 'AIzaKey',
|
||||||
store: InMemoryCredentialStore(
|
store: InMemoryCredentialStore(
|
||||||
FirebaseCredentials(
|
FirebaseCredentials(
|
||||||
idToken: 'id',
|
idToken: 'id',
|
||||||
refreshToken: 'refresh',
|
refreshToken: 'refresh',
|
||||||
expiresAt: DateTime.now().add(const Duration(hours: 1)),
|
expiresAt: DateTime.now().add(const Duration(hours: 1)),
|
||||||
),
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
httpClient: MockClient((request) async {
|
),
|
||||||
if (request.url.path == '/settings/advancedMode.json') {
|
httpClient: e2eMock((request) async {
|
||||||
return http.Response(
|
if (request.url.path == '/settings/advancedMode.json') {
|
||||||
'{"value": "true", '
|
return http.Response(
|
||||||
'"updatedAtMillis": "${remoteTime.millisecondsSinceEpoch}"}',
|
'{"value": "true", '
|
||||||
200,
|
'"updatedAtMillis": "${remoteTime.millisecondsSinceEpoch}"}',
|
||||||
);
|
200,
|
||||||
}
|
);
|
||||||
if (request.method == 'PUT') return http.Response(request.body, 200);
|
}
|
||||||
return http.Response('null', 200);
|
if (request.method == 'PUT') return http.Response(request.body, 200);
|
||||||
}),
|
return http.Response('null', 200);
|
||||||
);
|
}),
|
||||||
final appSettings = ValueNotifier(
|
);
|
||||||
AppSettings(
|
final appSettings = ValueNotifier(
|
||||||
advancedMode: false,
|
AppSettings(
|
||||||
// Older than remoteTime, and non-null, so the reconciliation
|
advancedMode: false,
|
||||||
// guard's `currentAt != null && !reconciledAt.isAfter(currentAt)`
|
// Older than remoteTime, and non-null, so the reconciliation
|
||||||
// check actually evaluates both operands.
|
// guard's `currentAt != null && !reconciledAt.isAfter(currentAt)`
|
||||||
advancedModeUpdatedAt: remoteTime.subtract(
|
// check actually evaluates both operands.
|
||||||
const Duration(days: 1),
|
advancedModeUpdatedAt: remoteTime.subtract(const Duration(days: 1)),
|
||||||
),
|
),
|
||||||
),
|
);
|
||||||
);
|
|
||||||
|
|
||||||
await pumpCapture(
|
await pumpCapture(
|
||||||
tester,
|
tester,
|
||||||
prefs: configuredPrefs,
|
prefs: configuredPrefs,
|
||||||
firebaseFactory: () async => firebase,
|
firebaseFactory: () async => firebase,
|
||||||
appSettings: appSettings,
|
appSettings: appSettings,
|
||||||
);
|
);
|
||||||
await tester.pump(); // settings load → auto-sync (pull) …
|
await tester.pump(); // settings load → auto-sync (pull) …
|
||||||
await tester.pump(); // … then push, then reconcile
|
await tester.pump(); // … then push, then reconcile
|
||||||
|
|
||||||
expect(appSettings.value.advancedMode, isTrue);
|
expect(appSettings.value.advancedMode, isTrue);
|
||||||
},
|
});
|
||||||
);
|
|
||||||
|
|
||||||
testWidgets('logs app_open when analytics is injected', (tester) async {
|
testWidgets('logs app_open when analytics is injected', (tester) async {
|
||||||
const analytics = AnalyticsService(nodeId: 'device-a');
|
const analytics = AnalyticsService(nodeId: 'device-a');
|
||||||
|
|||||||
@ -31,6 +31,7 @@ import 'package:todo/ui/settings_screen.dart';
|
|||||||
import 'package:todo/ui/text_free_localizations.dart';
|
import 'package:todo/ui/text_free_localizations.dart';
|
||||||
|
|
||||||
import 'fake_note_repository.dart';
|
import 'fake_note_repository.dart';
|
||||||
|
import 'e2e_github_header.dart';
|
||||||
import 'fake_secure_storage.dart';
|
import 'fake_secure_storage.dart';
|
||||||
|
|
||||||
// A real CRDT DB schedules sqflite timers that never drain under the
|
// A real CRDT DB schedules sqflite timers that never drain under the
|
||||||
@ -108,7 +109,7 @@ const configuredPrefs = {
|
|||||||
// A MockClient that records request methods and answers the sync flow:
|
// A MockClient that records request methods and answers the sync flow:
|
||||||
// repo-exists GET (not /contents/) → 200, the (empty) log listing → 404,
|
// repo-exists GET (not /contents/) → 200, the (empty) log listing → 404,
|
||||||
// and the device's own PUT → 200.
|
// and the device's own PUT → 200.
|
||||||
MockClient recordingMock(List<String> methods) => MockClient((req) async {
|
MockClient recordingMock(List<String> methods) => e2eMock((req) async {
|
||||||
methods.add(req.method);
|
methods.add(req.method);
|
||||||
if (req.method == 'PUT') return http.Response('{}', 200);
|
if (req.method == 'PUT') return http.Response('{}', 200);
|
||||||
if (!req.url.path.contains('/contents/')) return http.Response('{}', 200);
|
if (!req.url.path.contains('/contents/')) return http.Response('{}', 200);
|
||||||
|
|||||||
@ -17,6 +17,7 @@ import 'package:todo/ui/github_mirror_screen.dart';
|
|||||||
import 'package:todo/ui/settings_screen.dart';
|
import 'package:todo/ui/settings_screen.dart';
|
||||||
|
|
||||||
import 'fake_note_repository.dart';
|
import 'fake_note_repository.dart';
|
||||||
|
import 'e2e_github_header.dart';
|
||||||
import 'fake_secure_storage.dart';
|
import 'fake_secure_storage.dart';
|
||||||
|
|
||||||
import 'capture_screen_harness.dart';
|
import 'capture_screen_harness.dart';
|
||||||
@ -29,7 +30,7 @@ void main() {
|
|||||||
// Empty remote directory → the service has nothing to merge and pushes
|
// Empty remote directory → the service has nothing to merge and pushes
|
||||||
// this device's own log (PUT). The bare repo GET (not /contents/) returns
|
// this device's own log (PUT). The bare repo GET (not /contents/) returns
|
||||||
// 200 so crdt_sync's client treats the 404 dir as "empty", not missing.
|
// 200 so crdt_sync's client treats the 404 dir as "empty", not missing.
|
||||||
final mock = MockClient((req) async {
|
final mock = e2eMock((req) async {
|
||||||
if (req.method == 'PUT') return http.Response('{}', 200);
|
if (req.method == 'PUT') return http.Response('{}', 200);
|
||||||
if (!req.url.path.contains('/contents/')) return http.Response('{}', 200);
|
if (!req.url.path.contains('/contents/')) return http.Response('{}', 200);
|
||||||
return http.Response('', 404);
|
return http.Response('', 404);
|
||||||
@ -70,10 +71,10 @@ void main() {
|
|||||||
tester,
|
tester,
|
||||||
) async {
|
) async {
|
||||||
// One peer file exists but holds garbage → merged 0, skipped 1.
|
// One peer file exists but holds garbage → merged 0, skipped 1.
|
||||||
final mock = MockClient((req) async {
|
final mock = e2eMock((req) async {
|
||||||
if (req.method == 'PUT') return http.Response('{}', 200);
|
if (req.method == 'PUT') return http.Response('{}', 200);
|
||||||
if (!req.url.path.contains('/contents/')) return http.Response('{}', 200);
|
if (!req.url.path.contains('/contents/')) return http.Response('{}', 200);
|
||||||
if (req.url.path.endsWith('/todo-sync/notes')) {
|
if (req.url.path.endsWith('/todo-sync/notes-e2e')) {
|
||||||
return http.Response('[{"name": "bad.json"}]', 200);
|
return http.Response('[{"name": "bad.json"}]', 200);
|
||||||
}
|
}
|
||||||
if (req.url.path.endsWith('/bad.json')) {
|
if (req.url.path.endsWith('/bad.json')) {
|
||||||
@ -132,7 +133,7 @@ void main() {
|
|||||||
// A MockClient that records request methods and answers the sync flow:
|
// A MockClient that records request methods and answers the sync flow:
|
||||||
// repo-exists GET (not /contents/) → 200, the (empty) log listing → 404,
|
// repo-exists GET (not /contents/) → 200, the (empty) log listing → 404,
|
||||||
// and the device's own PUT → 200.
|
// and the device's own PUT → 200.
|
||||||
MockClient recordingMock(List<String> methods) => MockClient((req) async {
|
MockClient recordingMock(List<String> methods) => e2eMock((req) async {
|
||||||
methods.add(req.method);
|
methods.add(req.method);
|
||||||
if (req.method == 'PUT') return http.Response('{}', 200);
|
if (req.method == 'PUT') return http.Response('{}', 200);
|
||||||
if (!req.url.path.contains('/contents/')) return http.Response('{}', 200);
|
if (!req.url.path.contains('/contents/')) return http.Response('{}', 200);
|
||||||
|
|||||||
@ -19,6 +19,9 @@ class CliHarness {
|
|||||||
writeSeedCredentials(
|
writeSeedCredentials(
|
||||||
tmp,
|
tmp,
|
||||||
).copySync('${home.path}/.config/todo/firebase_auth.json');
|
).copySync('${home.path}/.config/todo/firebase_auth.json');
|
||||||
|
File(
|
||||||
|
'${tmp.path}/e2e_passphrase',
|
||||||
|
).copySync('${home.path}/.config/todo/e2e_passphrase');
|
||||||
env = {'HOME': home.path, 'XDG_DATA_HOME': '${tmp.path}/xdg'};
|
env = {'HOME': home.path, 'XDG_DATA_HOME': '${tmp.path}/xdg'};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -22,6 +22,9 @@ void main() {
|
|||||||
writeSeedCredentials(
|
writeSeedCredentials(
|
||||||
tmp,
|
tmp,
|
||||||
).copySync('${home.path}/.config/todo/firebase_auth.json');
|
).copySync('${home.path}/.config/todo/firebase_auth.json');
|
||||||
|
File(
|
||||||
|
'${tmp.path}/e2e_passphrase',
|
||||||
|
).copySync('${home.path}/.config/todo/e2e_passphrase');
|
||||||
env = {'HOME': home.path, 'XDG_DATA_HOME': '${tmp.path}/xdg'};
|
env = {'HOME': home.path, 'XDG_DATA_HOME': '${tmp.path}/xdg'};
|
||||||
out = StringBuffer();
|
out = StringBuffer();
|
||||||
err = StringBuffer();
|
err = StringBuffer();
|
||||||
@ -86,7 +89,10 @@ void main() {
|
|||||||
test('pushes an ordinary CRDT log and prints the new id', () async {
|
test('pushes an ordinary CRDT log and prints the new id', () async {
|
||||||
final id = await add('a', 'Title\n\nbody', ['--priority', 'high']);
|
final id = await add('a', 'Title\n\nbody', ['--priority', 'high']);
|
||||||
expect(id, matches(RegExp(r'^[0-9a-f-]{36}$')));
|
expect(id, matches(RegExp(r'^[0-9a-f-]{36}$')));
|
||||||
expect(db.files.keys.where((k) => k.contains('notes/')), hasLength(1));
|
expect(
|
||||||
|
db.files.keys.where((k) => k.contains('notes-e2e/')),
|
||||||
|
hasLength(1),
|
||||||
|
);
|
||||||
expect(err.toString(), isEmpty);
|
expect(err.toString(), isEmpty);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@ -117,8 +117,8 @@ void main() {
|
|||||||
final first = await session.sync(push: true);
|
final first = await session.sync(push: true);
|
||||||
expect(first.pushed, isTrue);
|
expect(first.pushed, isTrue);
|
||||||
final node = session.repository.nodeId;
|
final node = session.repository.nodeId;
|
||||||
expect(db.files.keys, contains('todo-sync/notes/$node~2Ejson'));
|
expect(db.files.keys, contains('todo-sync/notes-e2e/$node~2Ejson'));
|
||||||
expect(db.files.keys, contains('todo-sync/revs/$node'));
|
expect(db.files.keys, contains('todo-sync/revs-e2e/$node'));
|
||||||
expect(
|
expect(
|
||||||
File('${tmp.path}/push/${CliSession.syncStateFileName}').existsSync(),
|
File('${tmp.path}/push/${CliSession.syncStateFileName}').existsSync(),
|
||||||
isTrue,
|
isTrue,
|
||||||
|
|||||||
@ -64,6 +64,8 @@ class FakeRtdb {
|
|||||||
|
|
||||||
/// Writes a Firebase session that does not expire during a test run.
|
/// Writes a Firebase session that does not expire during a test run.
|
||||||
File writeSeedCredentials(Directory dir, {String name = 'seed.json'}) {
|
File writeSeedCredentials(Directory dir, {String name = 'seed.json'}) {
|
||||||
|
// 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(
|
return File('${dir.path}/$name')..writeAsStringSync(
|
||||||
jsonEncode({
|
jsonEncode({
|
||||||
'id_token': 'seed-id-token',
|
'id_token': 'seed-id-token',
|
||||||
|
|||||||
35
test/e2e_github_header.dart
Normal file
35
test/e2e_github_header.dart
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
/// A GitHub stand-in that persists the end-to-end encryption header, which
|
||||||
|
/// the sync service writes and re-reads; every other request goes to [inner].
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:http/testing.dart';
|
||||||
|
|
||||||
|
/// Wraps [inner] so `…/e2e` PUTs are stored and served back on GET.
|
||||||
|
MockClient e2eMock(Future<http.Response> Function(http.Request) inner) {
|
||||||
|
String? header;
|
||||||
|
return MockClient((request) async {
|
||||||
|
if (request.url.path.endsWith('/e2e.json')) {
|
||||||
|
// Firebase REST: the value is a JSON-encoded string.
|
||||||
|
if (request.method == 'PUT') {
|
||||||
|
header = jsonDecode(request.body) as String;
|
||||||
|
return http.Response(request.body, 200);
|
||||||
|
}
|
||||||
|
return http.Response(jsonEncode(header), 200);
|
||||||
|
}
|
||||||
|
if (!request.url.path.endsWith('/e2e')) return inner(request);
|
||||||
|
if (request.method == 'PUT') {
|
||||||
|
final body = jsonDecode(request.body) as Map<String, dynamic>;
|
||||||
|
header = utf8.decode(base64.decode(body['content'] as String));
|
||||||
|
return http.Response(jsonEncode({'content': {}, 'sha': 'h'}), 200);
|
||||||
|
}
|
||||||
|
final text = header;
|
||||||
|
if (text == null) return http.Response('', 404);
|
||||||
|
return http.Response(
|
||||||
|
jsonEncode({'content': base64.encode(utf8.encode(text)), 'sha': 'h'}),
|
||||||
|
200,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -1,4 +1,6 @@
|
|||||||
|
import 'package:crdt_sync/crdt_sync.dart' show Argon2Params;
|
||||||
import 'package:flutter/services.dart';
|
import 'package:flutter/services.dart';
|
||||||
|
import 'package:todo/sync/run_sync.dart' show e2eArgon2Params;
|
||||||
import 'package:flutter_test/flutter_test.dart';
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
|
||||||
/// In-memory fake for the `flutter_secure_storage` platform channel so tests
|
/// In-memory fake for the `flutter_secure_storage` platform channel so tests
|
||||||
@ -13,7 +15,17 @@ void installFakeSecureStorage({
|
|||||||
bool throwing = false,
|
bool throwing = false,
|
||||||
}) {
|
}) {
|
||||||
const channel = MethodChannel('plugins.it_nomads.com/flutter_secure_storage');
|
const channel = MethodChannel('plugins.it_nomads.com/flutter_secure_storage');
|
||||||
final store = <String, String>{...?initial};
|
e2eArgon2Params = const Argon2Params(
|
||||||
|
memoryKiB: 8,
|
||||||
|
iterations: 1,
|
||||||
|
parallelism: 1,
|
||||||
|
);
|
||||||
|
// Sync is end-to-end encrypted, so a device with no passphrase is locked;
|
||||||
|
// tests that sync start with one unless they pass their own `initial`.
|
||||||
|
final store = <String, String>{
|
||||||
|
'crdt_sync_e2e_passphrase': 'test-passphrase',
|
||||||
|
...?initial,
|
||||||
|
};
|
||||||
final messenger =
|
final messenger =
|
||||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
|
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
|
||||||
|
|
||||||
|
|||||||
@ -6,10 +6,7 @@ void main() {
|
|||||||
test('returns the token the sign-in function yields', () async {
|
test('returns the token the sign-in function yields', () async {
|
||||||
// The injected path: proves the closure is what feeds crdt_sync, and
|
// The injected path: proves the closure is what feeds crdt_sync, and
|
||||||
// that no platform channel is touched to get there.
|
// that no platform channel is touched to get there.
|
||||||
expect(
|
expect(await googleIdToken(signInFn: () async => 'a-token'), 'a-token');
|
||||||
await googleIdToken(signInFn: () async => 'a-token'),
|
|
||||||
'a-token',
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test('passes a null cancellation straight through', () async {
|
test('passes a null cancellation straight through', () async {
|
||||||
|
|||||||
@ -62,8 +62,8 @@ void main() {
|
|||||||
final stop = await start();
|
final stop = await start();
|
||||||
expect(stop, isNotNull);
|
expect(stop, isNotNull);
|
||||||
expect(err.toString(), contains('serving http://127.0.0.1:'));
|
expect(err.toString(), contains('serving http://127.0.0.1:'));
|
||||||
expect(db.files.keys, contains(startsWith('todo-sync/notes/')));
|
expect(db.files.keys, contains(startsWith('todo-sync/notes-e2e/')));
|
||||||
expect(db.files.keys, contains(startsWith('todo-sync/revs/')));
|
expect(db.files.keys, contains(startsWith('todo-sync/revs-e2e/')));
|
||||||
await stop!();
|
await stop!();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@ -61,7 +61,7 @@ void main() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('an unmergeable peer log is reported, not hidden', () async {
|
test('an unmergeable peer log is reported, not hidden', () async {
|
||||||
h.db.files['todo-sync/notes/broken~2Ejson'] = 'not a log';
|
h.db.files['todo-sync/notes-e2e/broken~2Ejson'] = 'not a log';
|
||||||
expect(await h.refused(c, 'list_tasks', {}), contains('unmergeable'));
|
expect(await h.refused(c, 'list_tasks', {}), contains('unmergeable'));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@ -109,10 +109,7 @@ void main() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('accepts a binary replaced by an upgrade', () {
|
test('accepts a binary replaced by an upgrade', () {
|
||||||
expect(
|
expect(isTodoWrapper('/opt/todo/bin/todo_desktop (deleted)', []), isTrue);
|
||||||
isTodoWrapper('/opt/todo/bin/todo_desktop (deleted)', []),
|
|
||||||
isTrue,
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test('accepts a development run out of the repo', () {
|
test('accepts a development run out of the repo', () {
|
||||||
@ -155,48 +152,36 @@ void main() {
|
|||||||
|
|
||||||
test('matches a normally separated argument vector', () {
|
test('matches a normally separated argument vector', () {
|
||||||
expect(
|
expect(
|
||||||
hasWindowAttached(
|
hasWindowAttached([
|
||||||
[
|
['thorium', '--user-data-dir=$_profile', '--class=todo'],
|
||||||
['thorium', '--user-data-dir=$_profile', '--class=todo'],
|
], _profile),
|
||||||
],
|
|
||||||
_profile,
|
|
||||||
),
|
|
||||||
isTrue,
|
isTrue,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('matches when the flag is the final argument', () {
|
test('matches when the flag is the final argument', () {
|
||||||
expect(
|
expect(
|
||||||
hasWindowAttached(
|
hasWindowAttached([
|
||||||
[
|
['thorium', '--user-data-dir=$_profile'],
|
||||||
['thorium', '--user-data-dir=$_profile'],
|
], _profile),
|
||||||
],
|
|
||||||
_profile,
|
|
||||||
),
|
|
||||||
isTrue,
|
isTrue,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('does not match a sibling profile directory', () {
|
test('does not match a sibling profile directory', () {
|
||||||
expect(
|
expect(
|
||||||
hasWindowAttached(
|
hasWindowAttached([
|
||||||
[
|
['thorium', '--user-data-dir=${_profile}2'],
|
||||||
['thorium', '--user-data-dir=${_profile}2'],
|
], _profile),
|
||||||
],
|
|
||||||
_profile,
|
|
||||||
),
|
|
||||||
isFalse,
|
isFalse,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('does not match when no process mentions the profile', () {
|
test('does not match when no process mentions the profile', () {
|
||||||
expect(
|
expect(
|
||||||
hasWindowAttached(
|
hasWindowAttached([
|
||||||
[
|
['bash', '-c', 'sleep 1'],
|
||||||
['bash', '-c', 'sleep 1'],
|
], _profile),
|
||||||
],
|
|
||||||
_profile,
|
|
||||||
),
|
|
||||||
isFalse,
|
isFalse,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|||||||
@ -91,17 +91,11 @@ void main() {
|
|||||||
);
|
);
|
||||||
final action = await guard.resolve(8730);
|
final action = await guard.resolve(8730);
|
||||||
expect(action, isA<AbortWithOwner>());
|
expect(action, isA<AbortWithOwner>());
|
||||||
expect(
|
expect((action as AbortWithOwner).description, contains('unidentified'));
|
||||||
(action as AbortWithOwner).description,
|
|
||||||
contains('unidentified'),
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test('retries when the owner exited mid-probe', () async {
|
test('retries when the owner exited mid-probe', () async {
|
||||||
final guard = PortGuard(
|
final guard = PortGuard(profileDir: _profile, probe: FakeProbe(pid: 42));
|
||||||
profileDir: _profile,
|
|
||||||
probe: FakeProbe(pid: 42),
|
|
||||||
);
|
|
||||||
expect(await guard.resolve(8730), isA<BindNow>());
|
expect(await guard.resolve(8730), isA<BindNow>());
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -202,20 +196,14 @@ void main() {
|
|||||||
final probe = FakeProbe(freeAfter: ProcessSignal.sigkill);
|
final probe = FakeProbe(freeAfter: ProcessSignal.sigkill);
|
||||||
final guard = PortGuard(profileDir: _profile, probe: probe);
|
final guard = PortGuard(profileDir: _profile, probe: probe);
|
||||||
expect(await _reap(guard, 42, 8730), isTrue);
|
expect(await _reap(guard, 42, 8730), isTrue);
|
||||||
expect(probe.signalsSent, [
|
expect(probe.signalsSent, [ProcessSignal.sigterm, ProcessSignal.sigkill]);
|
||||||
ProcessSignal.sigterm,
|
|
||||||
ProcessSignal.sigkill,
|
|
||||||
]);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test('reports failure when the port never comes free', () async {
|
test('reports failure when the port never comes free', () async {
|
||||||
final probe = FakeProbe(inUse: [true]);
|
final probe = FakeProbe(inUse: [true]);
|
||||||
final guard = PortGuard(profileDir: _profile, probe: probe);
|
final guard = PortGuard(profileDir: _profile, probe: probe);
|
||||||
expect(await _reap(guard, 42, 8730), isFalse);
|
expect(await _reap(guard, 42, 8730), isFalse);
|
||||||
expect(probe.signalsSent, [
|
expect(probe.signalsSent, [ProcessSignal.sigterm, ProcessSignal.sigkill]);
|
||||||
ProcessSignal.sigterm,
|
|
||||||
ProcessSignal.sigkill,
|
|
||||||
]);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@ -19,12 +19,36 @@ import 'package:todo/data/note_repository.dart';
|
|||||||
import 'package:todo/sync/run_sync.dart';
|
import 'package:todo/sync/run_sync.dart';
|
||||||
import 'package:todo/sync/sync_settings.dart';
|
import 'package:todo/sync/sync_settings.dart';
|
||||||
|
|
||||||
|
import 'fake_secure_storage.dart';
|
||||||
|
|
||||||
|
final _headers = <String, String>{};
|
||||||
|
|
||||||
|
/// Stateful GitHub stand-in for the encryption header, the one file the
|
||||||
|
/// sync service itself does not own: PUT stores it, GET serves it back.
|
||||||
|
http.Response? _headerReply(http.Request request) {
|
||||||
|
if (!request.url.path.endsWith('/e2e')) return null;
|
||||||
|
if (request.method == 'PUT') {
|
||||||
|
final body = jsonDecode(request.body) as Map<String, dynamic>;
|
||||||
|
_headers['e2e'] = utf8.decode(base64.decode(body['content'] as String));
|
||||||
|
return http.Response(jsonEncode({'content': {}, 'sha': 'h'}), 200);
|
||||||
|
}
|
||||||
|
final text = _headers['e2e'];
|
||||||
|
if (text == null) return http.Response('', 404);
|
||||||
|
return http.Response(
|
||||||
|
jsonEncode({'content': base64.encode(utf8.encode(text)), 'sha': 'h'}),
|
||||||
|
200,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const _settings = SyncSettings(owner: 'kuhyx', repo: 'syncs', token: 'tok');
|
const _settings = SyncSettings(owner: 'kuhyx', repo: 'syncs', token: 'tok');
|
||||||
|
|
||||||
void main() {
|
void main() {
|
||||||
late NoteRepository repo;
|
late NoteRepository repo;
|
||||||
|
|
||||||
setUp(() async {
|
setUp(() async {
|
||||||
|
TestWidgetsFlutterBinding.ensureInitialized();
|
||||||
|
installFakeSecureStorage();
|
||||||
|
_headers.clear();
|
||||||
SharedPreferences.setMockInitialValues({});
|
SharedPreferences.setMockInitialValues({});
|
||||||
repo = await NoteRepository.openInMemory(nodeId: 'me');
|
repo = await NoteRepository.openInMemory(nodeId: 'me');
|
||||||
});
|
});
|
||||||
@ -39,6 +63,8 @@ void main() {
|
|||||||
_settings,
|
_settings,
|
||||||
httpClient: http_testing.MockClient((request) async {
|
httpClient: http_testing.MockClient((request) async {
|
||||||
paths.add('${request.method} ${request.url.host}');
|
paths.add('${request.method} ${request.url.host}');
|
||||||
|
final header = _headerReply(request);
|
||||||
|
if (header != null) return header;
|
||||||
return http.Response(jsonEncode({'content': '', 'sha': 'x'}), 200);
|
return http.Response(jsonEncode({'content': '', 'sha': 'x'}), 200);
|
||||||
}),
|
}),
|
||||||
firebaseFactory: () async => null,
|
firebaseFactory: () async => null,
|
||||||
@ -83,6 +109,8 @@ void main() {
|
|||||||
_settings,
|
_settings,
|
||||||
httpClient: http_testing.MockClient((request) async {
|
httpClient: http_testing.MockClient((request) async {
|
||||||
githubPaths.add(request.method);
|
githubPaths.add(request.method);
|
||||||
|
final header = _headerReply(request);
|
||||||
|
if (header != null) return header;
|
||||||
return http.Response(jsonEncode({'content': '', 'sha': 'x'}), 200);
|
return http.Response(jsonEncode({'content': '', 'sha': 'x'}), 200);
|
||||||
}),
|
}),
|
||||||
firebaseFactory: () async => firebase,
|
firebaseFactory: () async => firebase,
|
||||||
@ -108,6 +136,8 @@ void main() {
|
|||||||
repo,
|
repo,
|
||||||
_settings,
|
_settings,
|
||||||
httpClient: http_testing.MockClient((request) async {
|
httpClient: http_testing.MockClient((request) async {
|
||||||
|
final header = _headerReply(request);
|
||||||
|
if (header != null) return header;
|
||||||
return http.Response(jsonEncode({'content': '', 'sha': 'x'}), 200);
|
return http.Response(jsonEncode({'content': '', 'sha': 'x'}), 200);
|
||||||
}),
|
}),
|
||||||
firebaseFactory: () async => null,
|
firebaseFactory: () async => null,
|
||||||
@ -158,6 +188,8 @@ void main() {
|
|||||||
appSettings: const AppSettings(advancedMode: false),
|
appSettings: const AppSettings(advancedMode: false),
|
||||||
analytics: analytics,
|
analytics: analytics,
|
||||||
httpClient: http_testing.MockClient((request) async {
|
httpClient: http_testing.MockClient((request) async {
|
||||||
|
final header = _headerReply(request);
|
||||||
|
if (header != null) return header;
|
||||||
return http.Response(jsonEncode({'content': '', 'sha': 'x'}), 200);
|
return http.Response(jsonEncode({'content': '', 'sha': 'x'}), 200);
|
||||||
}),
|
}),
|
||||||
firebaseFactory: () async => firebase,
|
firebaseFactory: () async => firebase,
|
||||||
|
|||||||
@ -64,10 +64,7 @@ void main() {
|
|||||||
|
|
||||||
final first = await SyncService(stateStore: store).sync(repo, remote);
|
final first = await SyncService(stateStore: store).sync(repo, remote);
|
||||||
expect(first.pushed, isTrue);
|
expect(first.pushed, isTrue);
|
||||||
expect(remote.writes, [
|
expect(remote.writes, ['todo-sync/notes/me.json', 'todo-sync/revs/me']);
|
||||||
'todo-sync/notes/me.json',
|
|
||||||
'todo-sync/revs/me',
|
|
||||||
]);
|
|
||||||
remote.writes.clear();
|
remote.writes.clear();
|
||||||
|
|
||||||
final second = await SyncService(stateStore: store).sync(repo, remote);
|
final second = await SyncService(stateStore: store).sync(repo, remote);
|
||||||
|
|||||||
@ -27,9 +27,9 @@ void main() {
|
|||||||
test('persists revisions across a restart', () async {
|
test('persists revisions across a restart', () async {
|
||||||
// A fresh store instance stands in for the next app launch: an
|
// A fresh store instance stands in for the next app launch: an
|
||||||
// in-memory cache would forget every peer and re-download everything.
|
// in-memory cache would forget every peer and re-download everything.
|
||||||
await openSyncStateStoreIn(dir.path).save(
|
await openSyncStateStoreIn(
|
||||||
const SyncState(pushedRev: 'mine', peerRevs: {'phone': 'theirs'}),
|
dir.path,
|
||||||
);
|
).save(const SyncState(pushedRev: 'mine', peerRevs: {'phone': 'theirs'}));
|
||||||
|
|
||||||
final reloaded = await openSyncStateStoreIn(dir.path).load();
|
final reloaded = await openSyncStateStoreIn(dir.path).load();
|
||||||
|
|
||||||
@ -38,9 +38,7 @@ void main() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('writes beside the log it describes', () async {
|
test('writes beside the log it describes', () async {
|
||||||
await openSyncStateStoreIn(
|
await openSyncStateStoreIn(dir.path).save(const SyncState(pushedRev: 'x'));
|
||||||
dir.path,
|
|
||||||
).save(const SyncState(pushedRev: 'x'));
|
|
||||||
|
|
||||||
expect(File(p.join(dir.path, kSyncStateFileName)).existsSync(), isTrue);
|
expect(File(p.join(dir.path, kSyncStateFileName)).existsSync(), isTrue);
|
||||||
});
|
});
|
||||||
|
|||||||
@ -69,9 +69,7 @@ void main() {
|
|||||||
expect(response.statusCode, 500);
|
expect(response.statusCode, 500);
|
||||||
|
|
||||||
// Still alive afterwards.
|
// Still alive afterwards.
|
||||||
final after = await http.get(
|
final after = await http.get(Uri.parse('http://localhost:${wedged.port}/'));
|
||||||
Uri.parse('http://localhost:${wedged.port}/'),
|
|
||||||
);
|
|
||||||
expect(after.statusCode, 200);
|
expect(after.statusCode, 200);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user