LifeMate — Personal, Family & Learning Companion

fix/backend-request-safety
chore/phase1-repository-cleanup deploy/stable-web-apk deployment-static design/mobile-accessibility-v2 design/mobile-navigation-review docs/child-education-access-decision docs/offline-data-rescue-options docs/owner-guide-and-delivery-plan docs/phase1-policy-options docs/public-review-live-2026-10-15 feat/aparat-learning-library feat/child-device-safety feat/child-identity-schema feat/flutter-mobile-navigation feat/learning-content-operations feat/local-signing-preflight feat/online-family-stage0 feat/personal-encrypted-recovery feat/private-planner-series-api feat/public-review-page feat/standalone-weekly-planner feat/weekly-planner-android final-feature-1/iran-family-school fix/auth-abuse-expiry-safety fix/auth-expiry-after-lock fix/backend-request-safety fix/lifeguide-bootstrap-naming-ci fix/lifeguide-pages-qa-base-preflight fix/lifeguide-qa-pages-env-deployment fix/local-task-persistence fix/managed-child-session-boundary fix/personal-jalali-dates fix/personal-notification-controls fix/personal-upgrade-delivery-guard fix/sms-approval-gates fix/study-duration-display infra/cloudflare-neon-migration infra/lifeguide-cloudflare-qa infra/lifeguide-github-pages-qa infra/lifeguide-supabase-qa main phase-1/foundation-completion phase-2/product-foundation-identity phase-3/planner-school-family-core phase-4/ai-learning-wellbeing phase-5/hardening-observability-release test/android-reminder-acceptance test/personal-notification-settings test/personal-recovery-acceptance test/role-entry-apk
dart 214 lines 7.24 KB
Raw
1 import 'dart:async';
2 import 'dart:convert';
3 import 'dart:math';
4
5 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 {
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;
49 static const key = 'lifeguide.local_data.v1';
50 static const categories = {'girl_minor', 'boy_minor', 'adult'};
51 static const themes = {'girl_pink', 'boy_blue', 'adult_blue'};
52 static const kinds = {
53 'task',
54 'assignment',
55 'exam',
56 'event',
57 'routine',
58 'goal',
59 'study_session'
60 };
61 static const statuses = {'planned', 'in_progress', 'completed', 'cancelled'};
62 static const priorities = {'low', 'normal', 'high', 'urgent'};
63 static final _processSession = LocalDataSession();
64 final LocalDataSession session;
65
66 Future<T> _locked<T>(Future<T> Function() operation) =>
67 session._run(operation);
68
69 static String newId() {
70 final random = Random.secure();
71 return List.generate(
72 16, (_) => random.nextInt(256).toRadixString(16).padLeft(2, '0'))
73 .join();
74 }
75
76 static Map<String, dynamic> _copy(Map<String, dynamic> value) =>
77 jsonDecode(jsonEncode(value)) as Map<String, dynamic>;
78
79 static Map<String, dynamic> _decode(String raw) {
80 try {
81 final data = jsonDecode(raw) as Map<String, dynamic>;
82 final profile = data['profile'] as Map<String, dynamic>;
83 final items = data['items'] as List<dynamic>;
84 if (data['version'] != 1 ||
85 !categories.contains(profile['profile_category']) ||
86 profile['user_id'] is! String ||
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 }
94 final ids = <String>{};
95 for (final rawItem in items) {
96 final item = rawItem as Map<String, dynamic>;
97 if (item['id'] is! String ||
98 (item['id'] as String).isEmpty ||
99 !ids.add(item['id'] as String) ||
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']) ||
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 &&
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 (_) {
128 throw const ApiException(500, 'local_data_corrupt');
129 }
130 }
131
132 static Future<SharedPreferencesAsync> _preferences() async {
133 try {
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
141 static Future<String?> _raw(SharedPreferencesAsync prefs) async {
142 try {
143 return await prefs.getString(key);
144 } catch (_) {
145 throw const ApiException(500, 'local_storage_failed');
146 }
147 }
148
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();
169 final raw = await _raw(prefs);
170 if (raw == null) return null;
171 return _copy(_decode(raw)['profile'] as Map<String, dynamic>);
172 });
173
174 Future<Map<String, dynamic>> _load(String? raw) async {
175 if (raw != null) return _decode(raw);
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 {
182 'version': 1,
183 'profile': {
184 'user_id': newId(),
185 'profile_category': category,
186 'display_name': displayName.trim(),
187 'theme_preference': category == 'girl_minor'
188 ? 'girl_pink'
189 : category == 'boy_minor'
190 ? 'boy_blue'
191 : 'adult_blue',
192 },
193 'items': <Map<String, dynamic>>[],
194 };
195 }
196
197 Future<Map<String, dynamic>> read() => _locked(() async {
198 final prefs = await _preferences();
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 });
205
206 Future<T> mutate<T>(T Function(Map<String, dynamic> data) change) =>
207 _locked(() async {
208 final prefs = await _preferences();
209 final data = await _load(await _raw(prefs));
210 final result = change(data);
211 await _write(prefs, data);
212 return result;
213 });
214 }