LifeMate — Personal, Family & Learning Companion
feat/weekly-planner-android
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
| 1 | import 'dart:async'; |
| 2 | import 'dart:convert'; |
| 3 | import 'package:flutter_test/flutter_test.dart'; |
| 4 | import 'package:http/http.dart' as http; |
| 5 | import 'package:http/testing.dart'; |
| 6 | import 'package:lifemate/api.dart'; |
| 7 | import 'package:lifemate/runtime_config.dart'; |
| 8 | import 'package:lifemate/runtime_controller.dart'; |
| 9 | import 'package:lifemate/session_store.dart'; |
| 10 | |
| 11 | class MemorySessionStore implements SessionStore { |
| 12 | String? value; |
| 13 | @override |
| 14 | Future<String?> read() async => value; |
| 15 | @override |
| 16 | Future<void> write(String next) async { |
| 17 | value = next; |
| 18 | } |
| 19 | |
| 20 | @override |
| 21 | Future<void> clear() async { |
| 22 | value = null; |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | class MemoryConfigStore extends RuntimeConfigStore { |
| 27 | MemoryConfigStore(this.value); |
| 28 | RuntimeConfig value; |
| 29 | final saved = <RuntimeConfig>[]; |
| 30 | @override |
| 31 | Future<RuntimeConfig> load() async => value; |
| 32 | @override |
| 33 | Future<void> saveAndroid(RuntimeConfig next) async { |
| 34 | saved.add(next); |
| 35 | value = next; |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | class DelayedConfigStore extends RuntimeConfigStore { |
| 40 | final result = Completer<RuntimeConfig>(); |
| 41 | @override |
| 42 | Future<RuntimeConfig> load() => result.future; |
| 43 | } |
| 44 | |
| 45 | class FailingClearSessionStore extends MemorySessionStore { |
| 46 | @override |
| 47 | Future<void> clear() async => throw StateError('storage unavailable'); |
| 48 | } |
| 49 | |
| 50 | String token(String user, String version) => |
| 51 | 'header.${base64Url.encode(utf8.encode(jsonEncode({ |
| 52 | 'sub': user, |
| 53 | 'version': version |
| 54 | })))}.signature'; |
| 55 | http.Response tokens( |
| 56 | String user, String version, String refresh) => |
| 57 | http.Response( |
| 58 | jsonEncode( |
| 59 | {'accessToken': token(user, version), 'refreshToken': refresh}), |
| 60 | 200); |
| 61 | |
| 62 | void main() { |
| 63 | test('an insecure web page cannot load configuration or persisted sessions', |
| 64 | () async { |
| 65 | var requested = false; |
| 66 | final store = RuntimeConfigStore( |
| 67 | web: true, |
| 68 | webOrigin: Uri.parse('http://family.example.test/'), |
| 69 | client: MockClient((_) async { |
| 70 | requested = true; |
| 71 | return http.Response( |
| 72 | '{"apiBaseUrl":"https://api.example.test","apiFallbackUrls":[]}', |
| 73 | 200); |
| 74 | })); |
| 75 | await expectLater(store.load(), throwsStateError); |
| 76 | expect(requested, isFalse); |
| 77 | }); |
| 78 | test( |
| 79 | 'failed cache clear blocks endpoint activation and exposes storage error', |
| 80 | () async { |
| 81 | final store = MemorySessionStore(); |
| 82 | final configStore = MemoryConfigStore( |
| 83 | RuntimeConfig(apiBaseUrl: 'https://old.example.test')); |
| 84 | final controller = RuntimeController( |
| 85 | configStore: configStore, |
| 86 | sessionStore: store, |
| 87 | onScopeDiscarded: (_) async => |
| 88 | throw StateError('cache write uncertain'), |
| 89 | apiFactory: (config) => HttpIdentityApi( |
| 90 | baseUrl: config.apiBaseUrl, |
| 91 | sessionStore: store, |
| 92 | client: MockClient( |
| 93 | (_) async => tokens('user-1', '1', 'fixture-refresh')))); |
| 94 | await controller.initialize(); |
| 95 | await controller.api!.login('fixture@example.test', 'fixture-password'); |
| 96 | await expectLater( |
| 97 | controller.updateEndpoints( |
| 98 | RuntimeConfig(apiBaseUrl: 'https://new.example.test')), |
| 99 | throwsStateError); |
| 100 | expect(controller.error, isA<StateError>()); |
| 101 | expect(controller.api!.accessToken, isNull); |
| 102 | expect(controller.config.apiBaseUrl, 'https://old.example.test'); |
| 103 | expect(configStore.saved, isEmpty); |
| 104 | controller.dispose(); |
| 105 | }); |
| 106 | test('account changes discard the old authenticated cache scope', () async { |
| 107 | final scopes = <String>[]; |
| 108 | var loginCount = 0; |
| 109 | final api = HttpIdentityApi( |
| 110 | baseUrl: 'https://api.example.test', |
| 111 | sessionStore: MemorySessionStore(), |
| 112 | onScopeDiscarded: (scope) async => scopes.add(scope), |
| 113 | client: MockClient((_) async { |
| 114 | loginCount++; |
| 115 | return tokens( |
| 116 | 'user-$loginCount', '$loginCount', 'refresh-$loginCount'); |
| 117 | })); |
| 118 | await api.login('first@example.test', 'fixture-password'); |
| 119 | await api.login('second@example.test', 'fixture-password'); |
| 120 | expect(scopes, ['https://api.example.test|user-1']); |
| 121 | expect(api.cacheNamespace, 'https://api.example.test|user-2'); |
| 122 | }); |
| 123 | test('logout notifies signed-out UI and clears cache even when storage fails', |
| 124 | () async { |
| 125 | final store = FailingClearSessionStore(); |
| 126 | final discarded = <String>[]; |
| 127 | final api = HttpIdentityApi( |
| 128 | baseUrl: 'https://api.example.test', |
| 129 | sessionStore: store, |
| 130 | onScopeDiscarded: (scope) async => discarded.add(scope), |
| 131 | client: |
| 132 | MockClient((_) async => tokens('user-1', '1', 'fixture-refresh'))); |
| 133 | await api.login('fixture@example.test', 'fixture-password'); |
| 134 | var notified = false; |
| 135 | api.onSessionChanged = () { |
| 136 | notified = true; |
| 137 | expect(api.accessToken, isNull); |
| 138 | }; |
| 139 | await expectLater(api.logout(revoke: false), throwsStateError); |
| 140 | expect(notified, isTrue); |
| 141 | expect(api.cacheNamespace, isNull); |
| 142 | expect(discarded, ['https://api.example.test|user-1']); |
| 143 | }); |
| 144 | test('disposed startup never constructs a new client or notifies listeners', |
| 145 | () async { |
| 146 | final store = DelayedConfigStore(); |
| 147 | var constructed = 0; |
| 148 | final controller = RuntimeController( |
| 149 | configStore: store, |
| 150 | sessionStore: MemorySessionStore(), |
| 151 | apiFactory: (_) { |
| 152 | constructed++; |
| 153 | throw StateError('Must not construct after disposal.'); |
| 154 | }); |
| 155 | final loading = controller.initialize(); |
| 156 | controller.dispose(); |
| 157 | store.result |
| 158 | .complete(RuntimeConfig(apiBaseUrl: 'https://api.example.test')); |
| 159 | await loading; |
| 160 | expect(constructed, 0); |
| 161 | expect(controller.api, isNull); |
| 162 | }); |
| 163 | test('endpoint changes clear old credentials and scope before using new API', |
| 164 | () async { |
| 165 | final store = MemorySessionStore(); |
| 166 | final configStore = MemoryConfigStore( |
| 167 | RuntimeConfig(apiBaseUrl: 'https://old.example.test')); |
| 168 | final discarded = <String>[]; |
| 169 | final requestedHosts = <String>[]; |
| 170 | final controller = RuntimeController( |
| 171 | configStore: configStore, |
| 172 | sessionStore: store, |
| 173 | onScopeDiscarded: (scope) async { |
| 174 | expect(store.value, isNull); |
| 175 | discarded.add(scope); |
| 176 | }, |
| 177 | apiFactory: (config) => HttpIdentityApi( |
| 178 | baseUrl: config.apiBaseUrl, |
| 179 | sessionStore: store, |
| 180 | client: MockClient((request) async { |
| 181 | requestedHosts.add(request.url.host); |
| 182 | return tokens('user-1', '1', 'old-refresh'); |
| 183 | }))); |
| 184 | await controller.initialize(); |
| 185 | await controller.api!.login('fixture@example.test', 'fixture-password'); |
| 186 | await controller |
| 187 | .updateEndpoints(RuntimeConfig(apiBaseUrl: 'https://new.example.test')); |
| 188 | expect(discarded, ['https://old.example.test|user-1']); |
| 189 | expect(store.value, isNull); |
| 190 | expect(controller.cacheNamespace, isNull); |
| 191 | expect(controller.api!.baseUrl, 'https://new.example.test'); |
| 192 | expect(configStore.saved.single.apiBaseUrl, 'https://new.example.test'); |
| 193 | expect(requestedHosts, ['old.example.test']); |
| 194 | controller.dispose(); |
| 195 | }); |
| 196 | test('HTTP and embedded credentials are rejected before client use', () { |
| 197 | for (final address in [ |
| 198 | 'http://api.example.test', |
| 199 | 'https://user:pass@api.example.test', |
| 200 | 'https://api.example.test?q=1', |
| 201 | 'https://api.example.test#token' |
| 202 | ]) { |
| 203 | expect(() => HttpIdentityApi(baseUrl: address), throwsArgumentError); |
| 204 | } |
| 205 | expect(() => HttpIdentityApi(), throwsArgumentError); |
| 206 | }); |
| 207 | test('HTTPS same-origin config resolves and fallback URLs are deduplicated', |
| 208 | () { |
| 209 | final config = RuntimeConfig.fromJson({ |
| 210 | 'apiBaseUrl': '/api', |
| 211 | 'apiFallbackUrls': [ |
| 212 | 'https://backup.example.test/', |
| 213 | 'https://backup.example.test' |
| 214 | ] |
| 215 | }, webOrigin: Uri.parse('https://family.example.test/')); |
| 216 | expect(config.endpoints, |
| 217 | ['https://family.example.test/api', 'https://backup.example.test']); |
| 218 | expect( |
| 219 | () => RuntimeConfig( |
| 220 | apiBaseUrl: '/api', |
| 221 | webOrigin: Uri.parse('http://family.example.test/')), |
| 222 | throwsArgumentError); |
| 223 | expect(RuntimeConfig().isConfigured, isFalse); |
| 224 | }); |
| 225 | test('runtime web config is fetched fresh from hosting origin', () async { |
| 226 | final store = RuntimeConfigStore( |
| 227 | web: true, |
| 228 | webOrigin: Uri.parse( |
| 229 | 'https://family.example.test/reset-password?token=private'), |
| 230 | client: MockClient((request) async { |
| 231 | expect(request.url.path, '/config.json'); |
| 232 | expect(request.url.queryParameters.containsKey('fresh'), isTrue); |
| 233 | expect(request.headers['Cache-Control'], 'no-store'); |
| 234 | expect(request.url.query, isNot(contains('private'))); |
| 235 | return http.Response( |
| 236 | '{"apiBaseUrl":"/api","apiFallbackUrls":[]}', 200); |
| 237 | })); |
| 238 | expect((await store.load()).apiBaseUrl, 'https://family.example.test/api'); |
| 239 | }); |
| 240 | test('refresh token survives API recreation and rotates before logout', |
| 241 | () async { |
| 242 | final store = MemorySessionStore(); |
| 243 | final requests = <http.Request>[]; |
| 244 | final client = MockClient((request) async { |
| 245 | requests.add(request); |
| 246 | if (request.url.path.endsWith('/login')) { |
| 247 | return tokens('user-1', '1', 'opaque-old'); |
| 248 | } |
| 249 | if (request.url.path.endsWith('/refresh')) { |
| 250 | expect(jsonDecode(request.body)['refreshToken'], 'opaque-old'); |
| 251 | return tokens('user-1', '2', 'opaque-new'); |
| 252 | } |
| 253 | if (request.url.path.endsWith('/logout')) return http.Response('', 204); |
| 254 | return http.Response('{"user_id":"user-1"}', 200); |
| 255 | }); |
| 256 | final first = HttpIdentityApi( |
| 257 | baseUrl: 'https://api.example.test/api', |
| 258 | client: client, |
| 259 | sessionStore: store); |
| 260 | await first.login('name@example.test', 'fixture-password'); |
| 261 | expect(store.value, isNot(contains(token('user-1', '1')))); |
| 262 | expect(first.cacheNamespace, 'https://api.example.test/api|user-1'); |
| 263 | final reopened = HttpIdentityApi( |
| 264 | baseUrl: first.baseUrl, client: client, sessionStore: store); |
| 265 | expect(reopened.cacheNamespace, isNull); |
| 266 | expect(await reopened.restoreSession(), isTrue); |
| 267 | expect(reopened.accessToken, token('user-1', '2')); |
| 268 | await reopened.getProfile(); |
| 269 | expect(requests.last.headers['authorization'], |
| 270 | 'Bearer ${token('user-1', '2')}'); |
| 271 | final cleared = <String>[]; |
| 272 | reopened.onScopeDiscarded = (scope) async { |
| 273 | cleared.add(scope); |
| 274 | }; |
| 275 | await reopened.logout(); |
| 276 | expect(store.value, isNull); |
| 277 | expect(reopened.cacheNamespace, isNull); |
| 278 | expect(cleared, ['https://api.example.test/api|user-1']); |
| 279 | }); |
| 280 | test('a stored session is never sent to another configured server', () async { |
| 281 | final store = MemorySessionStore() |
| 282 | ..value = jsonEncode({ |
| 283 | 'endpoint': 'https://old.example.test', |
| 284 | 'refreshToken': 'old-refresh', |
| 285 | 'userId': 'user-1' |
| 286 | }); |
| 287 | var sent = 0; |
| 288 | final discarded = <String>[]; |
| 289 | final quarantined = <String>[]; |
| 290 | final api = HttpIdentityApi( |
| 291 | baseUrl: 'https://new.example.test', |
| 292 | sessionStore: store, |
| 293 | onScopeDiscarded: (scope) async { |
| 294 | discarded.add(scope); |
| 295 | }, |
| 296 | onScopeQuarantined: (scope) async => quarantined.add(scope), |
| 297 | client: MockClient((_) async { |
| 298 | sent++; |
| 299 | return http.Response('{}', 200); |
| 300 | })); |
| 301 | expect(await api.restoreSession(), isFalse); |
| 302 | expect(sent, 0); |
| 303 | expect(store.value, isNull); |
| 304 | expect(discarded, isEmpty); |
| 305 | expect(quarantined, ['https://old.example.test|user-1']); |
| 306 | }); |
| 307 | test( |
| 308 | 'revoked refresh token quarantines the old scope without anonymous access', |
| 309 | () async { |
| 310 | final store = MemorySessionStore() |
| 311 | ..value = jsonEncode({ |
| 312 | 'endpoint': 'https://api.example.test', |
| 313 | 'refreshToken': 'revoked', |
| 314 | 'userId': 'user-1' |
| 315 | }); |
| 316 | final discarded = <String>[]; |
| 317 | final quarantined = <String>[]; |
| 318 | final api = HttpIdentityApi( |
| 319 | baseUrl: 'https://api.example.test', |
| 320 | sessionStore: store, |
| 321 | onScopeDiscarded: (scope) async { |
| 322 | discarded.add(scope); |
| 323 | }, |
| 324 | onScopeQuarantined: (scope) async => quarantined.add(scope), |
| 325 | client: MockClient((_) async => |
| 326 | http.Response('{"error":"invalid_refresh_token"}', 401))); |
| 327 | expect(await api.restoreSession(), isFalse); |
| 328 | expect(store.value, isNull); |
| 329 | expect(api.cacheNamespace, isNull); |
| 330 | expect(discarded, isEmpty); |
| 331 | expect(quarantined, ['https://api.example.test|user-1']); |
| 332 | }); |
| 333 | test('late refresh after logout cannot revive or overwrite a new session', |
| 334 | () async { |
| 335 | final store = MemorySessionStore() |
| 336 | ..value = jsonEncode({ |
| 337 | 'endpoint': 'https://old.example.test', |
| 338 | 'refreshToken': 'old-refresh', |
| 339 | 'userId': 'old-user' |
| 340 | }); |
| 341 | final entered = Completer<void>(); |
| 342 | final response = Completer<http.Response>(); |
| 343 | final old = HttpIdentityApi( |
| 344 | baseUrl: 'https://old.example.test', |
| 345 | sessionStore: store, |
| 346 | client: MockClient((_) { |
| 347 | entered.complete(); |
| 348 | return response.future; |
| 349 | })); |
| 350 | final restoring = old.restoreSession(); |
| 351 | await entered.future; |
| 352 | await old.logout(revoke: false); |
| 353 | final next = HttpIdentityApi( |
| 354 | baseUrl: 'https://new.example.test', |
| 355 | sessionStore: store, |
| 356 | client: |
| 357 | MockClient((_) async => tokens('new-user', '1', 'new-refresh'))); |
| 358 | await next.login('next@example.test', 'fixture-password'); |
| 359 | response.complete(tokens('old-user', '2', 'late-old-refresh')); |
| 360 | expect(await restoring, isFalse); |
| 361 | expect(old.accessToken, isNull); |
| 362 | expect(jsonDecode(store.value!)['endpoint'], 'https://new.example.test'); |
| 363 | expect(jsonDecode(store.value!)['refreshToken'], 'new-refresh'); |
| 364 | }); |
| 365 | test('transport failure does not retry a mutation on a fallback server', |
| 366 | () async { |
| 367 | var requests = 0; |
| 368 | final config = RuntimeConfig( |
| 369 | apiBaseUrl: 'https://primary.example.test', |
| 370 | apiFallbackUrls: ['https://backup.example.test']); |
| 371 | final api = HttpIdentityApi( |
| 372 | baseUrl: config.apiBaseUrl, |
| 373 | sessionStore: MemorySessionStore(), |
| 374 | client: MockClient((request) async { |
| 375 | requests++; |
| 376 | expect(request.url.host, 'primary.example.test'); |
| 377 | if (request.url.path.endsWith('/login')) { |
| 378 | return tokens('user-1', '1', 'fixture-refresh'); |
| 379 | } |
| 380 | throw http.ClientException('offline'); |
| 381 | })); |
| 382 | await api.login('name@example.test', 'fixture-password'); |
| 383 | await expectLater( |
| 384 | api.createPlanItem({'kind': 'task', 'title': 'Durable queued task'}), |
| 385 | throwsA(isA<ApiException>() |
| 386 | .having((error) => error.code, 'code', 'network_unavailable'))); |
| 387 | expect(requests, 2); |
| 388 | }); |
| 389 | } |