@davoodmehraban89 / LifeMate / commits / 12507ec
Fork 0

LifeMate — Personal, Family & Learning Companion

fix: guard local storage after uncertain native writes

Codex committed Oct 8, 2026 at 05:24 UTC 12507ec10b65a8f6646de7bc35d4aa4eda5ce657
4 files changed +231 -56
apps/lifemate/lib/local_data_store.dart
+89 -32
@@ -1,3 +1,4 @@
1 +import 'dart:async';
2 import 'dart:convert';
3 import 'dart:math';
4
@@ -5,10 +6,43 @@ import 'package:shared_preferences/shared_preferences.dart';
6
7 import 'api.dart';
8
9 +/// One local runtime session: shared by all production stores in this isolate.
10 +/// A failed native write leaves the session unavailable until a real app restart.
11 +class LocalDataSession {
12 + bool _uncertain = false;
13 + // All instances share the writer lock: read/modify/write cannot lose a record.
14 + Future<void>? _tail;
15 +
16 + Future<T> _run<T>(Future<T> Function() operation) {
17 + final previous = _tail;
18 + final release = Completer<void>();
19 + _tail = release.future;
20 + Future<T> run() async {
21 + if (previous != null) await previous;
22 + try {
23 + if (_uncertain) {
24 + throw const ApiException(500, 'local_storage_restart_required');
25 + }
26 + return await operation();
27 + } finally {
28 + // Don't retain a completed future and its caller's async zone forever.
29 + if (identical(_tail, release.future)) _tail = null;
30 + release.complete();
31 + }
32 + }
33 +
34 + return run();
35 + }
36 +}
37 +
38 /// Device-only data for the explicitly separate, unauthenticated test entrypoint.
39 /// Never used as an authorization boundary or as a production sync cache.
40 class LocalDataStore {
11 - LocalDataStore({required this.category, required this.displayName});
41 + LocalDataStore(
42 + {required this.category,
43 + required this.displayName,
44 + LocalDataSession? session})
45 + : session = session ?? _processSession;
46
47 final String category;
48 final String displayName;
@@ -25,14 +59,12 @@ class LocalDataStore {
59 'study_session'
60 };
61 static const statuses = {'planned', 'in_progress', 'completed', 'cancelled'};
28 - // All instances share the writer lock: read/modify/write cannot lose a record.
29 - static Future<void> _tail = Future.value();
62 + static const priorities = {'low', 'normal', 'high', 'urgent'};
63 + static final _processSession = LocalDataSession();
64 + final LocalDataSession session;
65
31 - static Future<T> _locked<T>(Future<T> Function() operation) {
32 - final task = _tail.then((_) => operation());
33 - _tail = task.then<void>((_) {}, onError: (Object _, StackTrace __) {});
34 - return task;
35 - }
66 + Future<T> _locked<T>(Future<T> Function() operation) =>
67 + session._run(operation);
68
69 static String newId() {
70 final random = Random.secure();
@@ -55,6 +87,7 @@ class LocalDataStore {
87 (profile['user_id'] as String).isEmpty ||
88 profile['display_name'] is! String ||
89 (profile['display_name'] as String).trim().isEmpty ||
90 + (profile['display_name'] as String).trim().length > 120 ||
91 !themes.contains(profile['theme_preference'])) {
92 throw const FormatException();
93 }
@@ -67,15 +100,28 @@ class LocalDataStore {
100 item['owner_user_id'] != profile['user_id'] ||
101 item['title'] is! String ||
102 (item['title'] as String).trim().isEmpty ||
103 + (item['title'] as String).trim().length > 240 ||
104 !kinds.contains(item['kind']) ||
105 !statuses.contains(item['status']) ||
72 - item['visibility'] != 'private') throw const FormatException();
106 + !priorities.contains(item['priority']) ||
107 + (item['notes'] != null &&
108 + (item['notes'] is! String ||
109 + (item['notes'] as String).length > 10000)) ||
110 + item['visibility'] != 'private') {
111 + throw const FormatException();
112 + }
113 for (final field in ['starts_at', 'due_at']) {
114 if (item[field] != null &&
75 - DateTime.tryParse(item[field].toString()) == null) {
115 + (item[field] is! String ||
116 + DateTime.tryParse(item[field] as String) == null)) {
117 throw const FormatException();
118 }
119 }
120 + final start = DateTime.tryParse(item['starts_at'] as String? ?? '');
121 + final due = DateTime.tryParse(item['due_at'] as String? ?? '');
122 + if (start != null && due != null && due.isBefore(start)) {
123 + throw const FormatException();
124 + }
125 }
126 return data;
127 } catch (_) {
@@ -83,43 +129,53 @@ class LocalDataStore {
129 }
130 }
131
86 - static Future<SharedPreferences> _preferences() async {
132 + static Future<SharedPreferencesAsync> _preferences() async {
133 try {
88 - final prefs = await SharedPreferences.getInstance();
89 - // Legacy SharedPreferences caches a value even if the platform write fails.
90 - // Always reload the durable platform state before reading it.
91 - await prefs.reload();
92 - return prefs;
134 + // Android default is transactional DataStore. No legacy native/Dart cache.
135 + return SharedPreferencesAsync();
136 } catch (_) {
137 throw const ApiException(500, 'local_storage_failed');
138 }
139 }
140
98 - static Future<void> _write(
99 - SharedPreferences prefs, Map<String, dynamic> data) async {
141 + static Future<String?> _raw(SharedPreferencesAsync prefs) async {
142 try {
101 - final raw = jsonEncode(data);
102 - // Bounded test storage; fail explicitly rather than risk silent truncation.
103 - if (utf8.encode(raw).length > 1024 * 1024 ||
104 - !await prefs.setString(key, raw)) {
105 - throw const ApiException(500, 'local_storage_failed');
106 - }
143 + return await prefs.getString(key);
144 } catch (_) {
145 throw const ApiException(500, 'local_storage_failed');
146 }
147 }
148
112 - static Future<Map<String, dynamic>?> readSavedProfile() => _locked(() async {
149 + Future<void> _write(
150 + SharedPreferencesAsync prefs, Map<String, dynamic> data) async {
151 + final raw = jsonEncode(data);
152 + // Prevalidation does not attempt native I/O and must not poison the session.
153 + if (utf8.encode(raw).length > 1024 * 1024) {
154 + throw const ApiException(500, 'local_storage_failed');
155 + }
156 + try {
157 + await prefs.setString(key, raw);
158 + } catch (_) {
159 + // Even DataStore may have published a native cache before a rename error.
160 + // Prevent later reads/writes from treating that uncertain value as durable.
161 + session._uncertain = true;
162 + throw const ApiException(500, 'local_storage_restart_required');
163 + }
164 + }
165 +
166 + static Future<Map<String, dynamic>?> readSavedProfile() =>
167 + _processSession._run(() async {
168 final prefs = await _preferences();
114 - final raw = prefs.getString(key);
169 + final raw = await _raw(prefs);
170 if (raw == null) return null;
171 return _copy(_decode(raw)['profile'] as Map<String, dynamic>);
172 });
173
119 - Future<Map<String, dynamic>> _load(SharedPreferences prefs) async {
120 - final raw = prefs.getString(key);
174 + Future<Map<String, dynamic>> _load(String? raw) async {
175 if (raw != null) return _decode(raw);
122 - if (!categories.contains(category) || displayName.trim().isEmpty) {
176 + if (!categories.contains(category) ||
177 + displayName.trim().isEmpty ||
178 + displayName.trim().length > 120) {
179 throw const ApiException(400, 'local_invalid_profile');
180 }
181 return {
@@ -140,8 +196,9 @@ class LocalDataStore {
196
197 Future<Map<String, dynamic>> read() => _locked(() async {
198 final prefs = await _preferences();
143 - final missing = prefs.getString(key) == null;
144 - final data = await _load(prefs);
199 + final raw = await _raw(prefs);
200 + final missing = raw == null;
201 + final data = await _load(raw);
202 if (missing) await _write(prefs, data);
203 return _copy(data);
204 });
@@ -149,7 +206,7 @@ class LocalDataStore {
206 Future<T> mutate<T>(T Function(Map<String, dynamic> data) change) =>
207 _locked(() async {
208 final prefs = await _preferences();
152 - final data = await _load(prefs);
209 + final data = await _load(await _raw(prefs));
210 final result = change(data);
211 await _write(prefs, data);
212 return result;
apps/lifemate/lib/local_only_api.dart
+18 -7
@@ -4,8 +4,12 @@ import 'local_data_store.dart';
4 /// Real device storage, without login, networking, family sharing or server sync.
5 /// The authenticated application continues to use HttpIdentityApi exclusively.
6 class LocalOnlyApi implements IdentityApi {
7 - LocalOnlyApi({required String category, required String displayName})
8 - : store = LocalDataStore(category: category, displayName: displayName);
7 + LocalOnlyApi(
8 + {required String category,
9 + required String displayName,
10 + LocalDataStore? store})
11 + : store = store ??
12 + LocalDataStore(category: category, displayName: displayName);
13
14 final LocalDataStore store;
15
@@ -32,8 +36,9 @@ class LocalOnlyApi implements IdentityApi {
36 return store.mutate((data) {
37 final profile = data['profile'] as Map<String, dynamic>;
38 if (displayName != null) profile['display_name'] = displayName.trim();
35 - if (themePreference != null)
39 + if (themePreference != null) {
40 profile['theme_preference'] = themePreference;
41 + }
42 return Map<String, dynamic>.from(profile);
43 });
44 }
@@ -74,9 +79,13 @@ class LocalOnlyApi implements IdentityApi {
79 for (final entry in input.entries) {
80 if (entry.key == 'startsAt' || entry.key == 'dueAt') {
81 final value = entry.value;
77 - final date = value == null ? null : DateTime.tryParse(value.toString());
78 - if (value != null && date == null)
82 + if (value != null && value is! String) {
83 + throw const ApiException(400, 'local_invalid_item');
84 + }
85 + final date = value == null ? null : DateTime.tryParse(value as String);
86 + if (value != null && date == null) {
87 throw const ApiException(400, 'local_invalid_item');
88 + }
89 fields[entry.key == 'startsAt' ? 'starts_at' : 'due_at'] =
90 date?.toUtc().toIso8601String();
91 } else {
@@ -147,9 +156,11 @@ class LocalOnlyApi implements IdentityApi {
156 .map((item) => Map<String, dynamic>.from(item as Map));
157 return items.where((item) {
158 if (item['status'] == 'cancelled' ||
150 - (kind != null && kind != item['kind'])) return false;
159 + (kind != null && kind != item['kind'])) {
160 + return false;
161 + }
162 final date = DateTime.tryParse(
152 - (item['due_at'] ?? item['starts_at'])?.toString() ?? '');
163 + (item['starts_at'] ?? item['due_at'])?.toString() ?? '');
164 // Undated records remain visible in the planner; dates use [from, to).
165 if (date == null) return true;
166 return (from == null || !date.isBefore(from)) &&
apps/lifemate/test/local_persistence_test.dart
+112 -17
@@ -1,23 +1,45 @@
1 import 'package:flutter_test/flutter_test.dart';
2 +import 'dart:convert';
3 +import 'local_test_preferences.dart';
4 import 'package:lifemate/local_only_api.dart';
5 import 'package:lifemate/api.dart';
6 import 'package:lifemate/local_data_store.dart';
7 import 'package:shared_preferences/shared_preferences.dart';
8 import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart';
9 +import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
10 +import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
11
8 -class FailedWrites extends InMemorySharedPreferencesStore {
9 - FailedWrites(Map<String, Object> data) : super.withData(data);
12 +final class FailedWrites extends InMemorySharedPreferencesAsync {
13 + FailedWrites(super.data) : super.withData();
14 + @override
15 + Future<bool> setString(
16 + String key, String value, SharedPreferencesOptions options) async {
17 + await super.setString(key, value, options);
18 + throw StateError('Synthetic native cache publication then rename failure');
19 + }
20 +}
21
22 +class FailedNativeCommit extends InMemorySharedPreferencesStore {
23 + FailedNativeCommit(super.data) : super.withData();
24 @override
12 - Future<bool> setValue(String valueType, String key, Object value) async =>
13 - false;
25 + Future<bool> setValue(String type, String key, Object value) async {
26 + await super.setValue(type, key, value);
27 + return false; // Android legacy commit can publish memory before disk fails.
28 + }
29 }
30
31 void main() {
17 - setUp(() => SharedPreferences.setMockInitialValues({}));
32 + late LocalDataSession session;
33 + setUp(() {
34 + resetLocalPreferences();
35 + session = LocalDataSession();
36 + });
37
19 - LocalOnlyApi open() =>
20 - LocalOnlyApi(displayName: 'آرام', category: 'girl_minor');
38 + LocalOnlyApi open() => LocalOnlyApi(
39 + displayName: 'آرام',
40 + category: 'girl_minor',
41 + store: LocalDataStore(
42 + category: 'girl_minor', displayName: 'آرام', session: session));
43
44 test('assignment survives recreation, update and safe archive', () async {
45 final created = await open().createPlanItem({
@@ -97,31 +119,104 @@ void main() {
119 expect(await open().getToday(from: from, to: to), isEmpty);
120 });
121
122 + test('today uses start time when a deadline is on another day', () async {
123 + final from = DateTime.utc(2026, 10, 8);
124 + await open().createPlanItem({
125 + 'kind': 'assignment',
126 + 'title': 'امروز',
127 + 'startsAt': from.add(const Duration(hours: 10)).toIso8601String(),
128 + 'dueAt': from.add(const Duration(days: 1)).toIso8601String(),
129 + });
130 + expect(
131 + await open()
132 + .getToday(from: from, to: from.add(const Duration(days: 1))),
133 + hasLength(1));
134 + });
135 +
136 + test('numeric dates are rejected instead of coerced into strings', () async {
137 + await expectLater(
138 + open().createPlanItem({
139 + 'kind': 'task',
140 + 'title': 'زمان نامعتبر',
141 + 'dueAt': 20261008,
142 + }),
143 + throwsA(isA<ApiException>()));
144 + });
145 +
146 + test('valid JSON with corrupt fields cannot be read or overwritten',
147 + () async {
148 + await open().createPlanItem({'kind': 'task', 'title': 'اول'});
149 + final original = await open().store.read();
150 + for (final corrupt in <Map<String, dynamic>>[
151 + {'notes': <String, dynamic>{}},
152 + {'priority': 'wrong'},
153 + {'due_at': 20261008},
154 + {'starts_at': '2026-10-09T10:00:00Z', 'due_at': '2026-10-08T10:00:00Z'},
155 + ]) {
156 + final data = jsonDecode(jsonEncode(original)) as Map<String, dynamic>;
157 + (data['items'] as List).first.addAll(corrupt);
158 + final raw = jsonEncode(data);
159 + resetLocalPreferences({LocalDataStore.key: raw});
160 + await expectLater(
161 + open().listPlanItems(),
162 + throwsA(isA<ApiException>()
163 + .having((e) => e.code, 'code', 'local_data_corrupt')));
164 + await expectLater(open().updateProfile(displayName: 'دوم'),
165 + throwsA(isA<ApiException>()));
166 + expect(await SharedPreferencesAsync().getString(LocalDataStore.key), raw);
167 + }
168 + });
169 +
170 test('corrupt data raises error and is never overwritten', () async {
171 const bad = '{invalid';
102 - SharedPreferences.setMockInitialValues({LocalDataStore.key: bad});
172 + resetLocalPreferences({LocalDataStore.key: bad});
173 await expectLater(
174 open().listPlanItems(),
175 throwsA(isA<ApiException>()
176 .having((e) => e.code, 'code', 'local_data_corrupt')));
177 await expectLater(open().createPlanItem({'kind': 'task', 'title': 'new'}),
178 throwsA(isA<ApiException>()));
109 - expect(
110 - (await SharedPreferences.getInstance()).getString(LocalDataStore.key),
111 - bad);
179 + expect(await SharedPreferencesAsync().getString(LocalDataStore.key), bad);
180 });
181
114 - test('failed write reports error and preserves last durable version',
182 + test('failed native write requires restart and blocks further operations',
183 () async {
184 final item = await open().createPlanItem({'kind': 'task', 'title': 'اول'});
117 - final raw =
118 - (await SharedPreferences.getInstance()).getString(LocalDataStore.key)!;
119 - SharedPreferencesStorePlatform.instance =
120 - FailedWrites({'flutter.${LocalDataStore.key}': raw});
185 + final raw = (await SharedPreferencesAsync().getString(LocalDataStore.key))!;
186 + SharedPreferencesAsyncPlatform.instance =
187 + FailedWrites({LocalDataStore.key: raw});
188 await expectLater(
189 open().updatePlanItem(item['id'] as String, {'title': 'دوم'}),
190 throwsA(isA<ApiException>()
124 - .having((e) => e.code, 'code', 'local_storage_failed')));
191 + .having((e) => e.code, 'code', 'local_storage_restart_required')));
192 + await expectLater(
193 + open().listPlanItems(),
194 + throwsA(isA<ApiException>()
195 + .having((e) => e.code, 'code', 'local_storage_restart_required')));
196 + final uncertain = jsonDecode(
197 + (await SharedPreferencesAsync().getString(LocalDataStore.key))!) as Map;
198 + expect((uncertain['items'] as List).first['title'], 'دوم');
199 + resetLocalPreferences({
200 + LocalDataStore.key: raw
201 + }); // simulate native process restart + disk read
202 + await expectLater(open().listPlanItems(), throwsA(isA<ApiException>()));
203 + session = LocalDataSession();
204 + expect((await open().listPlanItems()).single['title'], 'اول');
205 + });
206 +
207 + test('reads never trust legacy memory published by a failed commit',
208 + () async {
209 + await open().createPlanItem({'kind': 'task', 'title': 'اول'});
210 + final original = await open().store.read();
211 + final raw = jsonEncode(original);
212 + SharedPreferencesAsyncPlatform.instance =
213 + InMemorySharedPreferencesAsync.withData({LocalDataStore.key: raw});
214 + SharedPreferencesStorePlatform.instance =
215 + FailedNativeCommit({'flutter.${LocalDataStore.key}': raw});
216 + (original['items'] as List).first['title'] = 'ذخیره ناموفق';
217 + final prefs = await SharedPreferences.getInstance();
218 + expect(await prefs.setString(LocalDataStore.key, jsonEncode(original)),
219 + isFalse);
220 expect((await open().listPlanItems()).single['title'], 'اول');
221 });
222
apps/lifemate/test/local_test_preferences.dart new
+12
@@ -0,0 +1,12 @@
1 +import 'package:shared_preferences/shared_preferences.dart';
2 +import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
3 +import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
4 +
5 +/// Unit/widget plugin substitutes only. Real Android integration never calls this.
6 +void resetLocalPreferences([Map<String, Object> values = const {}]) {
7 + SharedPreferences.setMockInitialValues(
8 + values); // legacy profile/production cache
9 + SharedPreferencesAsyncPlatform.instance =
10 + InMemorySharedPreferencesAsync.withData(
11 + values); // local DataStore adapter
12 +}