LifeMate — Personal, Family & Learning Companion

fix/study-duration-display
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 240 lines 9.68 KB
Raw
1 import 'dart:convert';
2
3 import 'package:flutter/services.dart';
4 import 'package:flutter/material.dart';
5 import 'package:flutter_test/flutter_test.dart';
6 import 'package:http/http.dart' as http;
7 import 'package:http/testing.dart';
8 import 'package:lifemate/api.dart';
9 import 'package:lifemate/offline_store.dart';
10 import 'package:lifemate/plan_sync.dart';
11 import 'package:lifemate/runtime_config.dart';
12 import 'package:lifemate/runtime_controller.dart';
13 import 'package:lifemate/session_store.dart';
14 import 'package:lifemate/main.dart';
15 import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
16 import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
17
18 class _SessionStore implements SessionStore {
19 String? value;
20 @override
21 Future<String?> read() async => value;
22 @override
23 Future<void> write(String next) async => value = next;
24 @override
25 Future<void> clear() async => value = null;
26 }
27
28 class _ConfigStore extends RuntimeConfigStore {
29 _ConfigStore(this.value);
30 RuntimeConfig value;
31 @override
32 Future<RuntimeConfig> load() async => value;
33 @override
34 Future<void> saveAndroid(RuntimeConfig next) async => value = next;
35 }
36
37 http.Response _tokens(String user) => http.Response(
38 jsonEncode({
39 'accessToken': 'synthetic.${base64Url.encode(utf8.encode(jsonEncode({
40 'sub': user
41 })))}.synthetic',
42 'refreshToken': 'synthetic-refresh-$user'
43 }),
44 200);
45
46 void main() {
47 TestWidgetsFlutterBinding.ensureInitialized();
48 setUp(() {
49 SharedPreferencesAsyncPlatform.instance =
50 InMemorySharedPreferencesAsync.withData({});
51 String? pending;
52 TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
53 .setMockMethodCallHandler(
54 const MethodChannel('lifeguide/local_write_guard'), (call) async {
55 if (call.method == 'getBlocked') return pending != null;
56 if (call.method == 'beginWrite') return pending = 'synthetic-write';
57 if (call.method == 'completeWrite' && call.arguments == pending) {
58 pending = null;
59 return true;
60 }
61 throw PlatformException(code: 'local_storage_restart_required');
62 });
63 });
64
65 for (final status in [401, 403]) {
66 test(
67 'forced refresh $status seals rather than erases the pending namespace',
68 () async {
69 const endpoint = 'https://family.example.test/api';
70 const user = 'synthetic-owner';
71 const scope = '$endpoint|$user';
72 final credentials = _SessionStore()
73 ..value = jsonEncode({
74 'endpoint': endpoint,
75 'refreshToken': 'synthetic-lost-rotation',
76 'userId': user
77 });
78 final store = OfflineStore.forNamespace(scope);
79 const mutation = {
80 'id': '11111111-1111-4111-8111-111111111111',
81 'entityId': '22222222-2222-4222-8222-222222222222',
82 'entityType': 'plan_item',
83 'operation': 'create',
84 'expectedVersion': 0,
85 'clientUpdatedAt': '2026-10-09T01:00:00Z',
86 'payload': {'kind': 'assignment', 'title': 'synthetic private work'}
87 };
88 await store.enqueue(mutation);
89 final before = await store.readQueue();
90 final sent = <Map<String, dynamic>>[];
91 var authenticatingUser = user;
92 final api = HttpIdentityApi(
93 baseUrl: endpoint,
94 sessionStore: credentials,
95 onScopeDiscarded: OfflineStore.clearNamespace,
96 onScopeQuarantined: OfflineStore.invalidateNamespace,
97 client: MockClient((request) async {
98 if (request.url.path.endsWith('/auth/refresh')) {
99 return http.Response('{"error":"invalid_refresh_token"}', status);
100 }
101 if (request.url.path.endsWith('/auth/login')) {
102 return _tokens(authenticatingUser);
103 }
104 if (request.url.path.endsWith('/sync/mutations')) {
105 final changes =
106 (jsonDecode(request.body)['mutations'] as List).cast<Map>();
107 sent.addAll(changes.map(Map<String, dynamic>.from));
108 return http.Response(
109 jsonEncode({
110 'results': changes
111 .map((change) => {
112 'id': change['id'],
113 'status': 'accepted',
114 'acceptedAt': '2026-10-09T01:01:00Z',
115 'item': {
116 'id': change['entityId'],
117 'version': 1,
118 'kind': 'assignment',
119 'title': 'synthetic private work'
120 }
121 })
122 .toList()
123 }),
124 200);
125 }
126 throw StateError('Unexpected synthetic request');
127 }));
128 addTearDown(api.close);
129 expect(await api.restoreSession(), false);
130 expect(credentials.value, isNull);
131 expect(api.accessToken, isNull);
132 expect(api.cacheNamespace, isNull);
133 final sealed = OfflineStore.forNamespace(scope);
134 expect(await sealed.readQueue(), before,
135 reason: 'Forced expiry must preserve every original queued payload');
136 await expectLater(
137 store.readQueue(),
138 throwsA(isA<ApiException>()
139 .having((e) => e.code, 'code', 'cache_scope_closed')));
140 expect(() => OfflineStore.forApi(api), throwsA(isA<ApiException>()));
141
142 authenticatingUser = 'synthetic-other-account';
143 await api.login('other@example.test', 'synthetic-password');
144 expect(await OfflineStore.forApi(api).readQueue(), isEmpty);
145 await PlanSync(api).flush();
146 expect(sent, isEmpty);
147 expect(await sealed.readQueue(), before);
148 await api.logout(revoke: false);
149
150 authenticatingUser = user;
151 await api.login('owner@example.test', 'synthetic-password');
152 expect(await OfflineStore.forApi(api).readQueue(), before);
153 await PlanSync(api).flush();
154 await PlanSync(api).flush();
155 expect(sent, hasLength(1));
156 expect(sent.single['id'], mutation['id']);
157 expect(sent.single['entityId'], mutation['entityId']);
158 expect(sent.single['payload'], mutation['payload']);
159 expect(await OfflineStore.forApi(api).pendingCount(), 0);
160 });
161 }
162
163 test('deliberate sign-out and endpoint changes still discard active work',
164 () async {
165 for (final switchServer in [false, true]) {
166 final credentials = _SessionStore();
167 final controller = RuntimeController(
168 configStore: _ConfigStore(
169 RuntimeConfig(apiBaseUrl: 'https://family.example.test/api')),
170 sessionStore: credentials,
171 onScopeDiscarded: OfflineStore.clearNamespace,
172 onScopeQuarantined: OfflineStore.invalidateNamespace,
173 apiFactory: (config) => HttpIdentityApi(
174 baseUrl: config.apiBaseUrl,
175 sessionStore: credentials,
176 client: MockClient((request) async =>
177 request.url.path.endsWith('/auth/logout')
178 ? http.Response('', 204)
179 : _tokens('synthetic-owner'))));
180 await controller.initialize();
181 await controller.api!.login('owner@example.test', 'synthetic-password');
182 final scope = controller.cacheNamespace!;
183 final previous = OfflineStore.forApi(controller.api!);
184 await previous.enqueue({
185 'id': '11111111-1111-4111-8111-111111111111',
186 'entityId': '22222222-2222-4222-8222-222222222222',
187 'payload': {'title': 'synthetic private work'}
188 });
189 if (switchServer) {
190 await controller.updateEndpoints(
191 RuntimeConfig(apiBaseUrl: 'https://new.example.test/api'));
192 } else {
193 await controller.signOut();
194 }
195 expect(credentials.value, isNull);
196 expect(controller.cacheNamespace, isNull);
197 expect(await OfflineStore.forNamespace(scope).pendingCount(), 0);
198 await expectLater(previous.readQueue(), throwsA(isA<ApiException>()));
199 controller.dispose();
200 }
201 });
202
203 testWidgets('forced expiry returns to login with only a retained-work notice',
204 (tester) async {
205 const endpoint = 'https://family.example.test/api';
206 const scope = '$endpoint|synthetic-owner';
207 final credentials = _SessionStore()
208 ..value = jsonEncode({
209 'endpoint': endpoint,
210 'refreshToken': 'synthetic-revoked',
211 'userId': 'synthetic-owner'
212 });
213 await OfflineStore.forNamespace(scope).enqueue({
214 'id': '11111111-1111-4111-8111-111111111111',
215 'entityId': '22222222-2222-4222-8222-222222222222',
216 'payload': {'title': 'DO NOT DISPLAY SYNTHETIC PRIVATE TITLE'}
217 });
218 final controller = RuntimeController(
219 configStore: _ConfigStore(RuntimeConfig(apiBaseUrl: endpoint)),
220 sessionStore: credentials,
221 onScopeDiscarded: OfflineStore.clearNamespace,
222 onScopeQuarantined: OfflineStore.invalidateNamespace,
223 apiFactory: (config) => HttpIdentityApi(
224 baseUrl: config.apiBaseUrl,
225 sessionStore: credentials,
226 client: MockClient((_) async =>
227 http.Response('{"error":"invalid_refresh_token"}', 401))));
228 await tester.runAsync(controller.initialize);
229 await tester.pumpWidget(LifeMateApp(runtime: controller));
230 await tester.pumpAndSettle();
231 expect(find.textContaining('تغییرهای ارسال‌نشده این دستگاه حذف نشده‌اند'),
232 findsOneWidget);
233 expect(find.text('DO NOT DISPLAY SYNTHETIC PRIVATE TITLE'), findsNothing);
234 expect(find.byType(HomeShell), findsNothing);
235 expect(controller.api!.accessToken, isNull);
236 expect(await OfflineStore.forNamespace(scope).pendingCount(), 1);
237 await tester.pumpWidget(const SizedBox.shrink());
238 controller.dispose();
239 });
240 }