@davoodmehraban89 / LifeMate / commits / 05cc1fb
Fork 0

LifeMate — Personal, Family & Learning Companion

fix(web): isolate active instances and preserve unsent work on expiry

Codex committed Oct 9, 2026 at 06:23 UTC 05cc1fb94d0832f800944680281707abf455dcdf
17 files changed +860 -38
apps/lifemate/lib/api.dart
+45 -14
@@ -5,6 +5,7 @@ import 'package:http/http.dart' as http;
5 import 'runtime_config.dart';
6 import 'runtime_http_client.dart';
7 import 'session_store.dart';
8 +import 'web_instance.dart';
9
10 abstract class IdentityApi {
11 String? get accessToken;
@@ -145,6 +146,7 @@ class HttpIdentityApi implements IdentityApi {
146 SessionStore? sessionStore,
147 this.onSessionChanged,
148 this.onScopeDiscarded,
149 + this.onScopeQuarantined,
150 }) : baseUrl = normalizeApiUrl(
151 baseUrl ?? (throw ArgumentError('API configuration is required.'))),
152 _client = client ?? createRuntimeHttpClient(),
@@ -159,6 +161,8 @@ class HttpIdentityApi implements IdentityApi {
161 final SessionStore _sessionStore;
162 void Function()? onSessionChanged;
163 Future<void> Function(String)? onScopeDiscarded;
164 + Future<void> Function(String)? onScopeQuarantined;
165 + bool hasQuarantinedSession = false;
166 Future<void>? _refreshing;
167 int _sessionGeneration = 0;
168 String? currentUserId;
@@ -227,6 +231,7 @@ class HttpIdentityApi implements IdentityApi {
231 accessToken = access;
232 _refreshToken = refresh;
233 currentUserId = userId;
234 + hasQuarantinedSession = false;
235 onSessionChanged?.call();
236 }
237
@@ -237,18 +242,18 @@ class HttpIdentityApi implements IdentityApi {
242 try {
243 session = jsonDecode(raw) as Map<String, dynamic>;
244 } catch (_) {
240 - await logout(revoke: false);
245 + await _expireSession();
246 return false;
247 }
248 if (session['endpoint'] != endpointIdentity ||
249 session['refreshToken'] is! String ||
250 (session['refreshToken'] as String).isEmpty ||
251 session['userId'] is! String) {
247 - if (session['endpoint'] is String && session['userId'] is String) {
248 - await onScopeDiscarded
249 - ?.call('${session['endpoint']}|${session['userId']}');
250 - }
251 - await logout(revoke: false);
252 + final oldScope =
253 + session['endpoint'] is String && session['userId'] is String
254 + ? '${session['endpoint']}|${session['userId']}'
255 + : null;
256 + await _expireSession(scopeOverride: oldScope);
257 return false;
258 }
259 _refreshToken = session['refreshToken'] as String;
@@ -265,6 +270,7 @@ class HttpIdentityApi implements IdentityApi {
270 Future<void> logout({bool revoke = true}) async {
271 final token = _refreshToken;
272 _sessionGeneration++;
273 + hasQuarantinedSession = false;
274 await _clearSession();
275 if (revoke && token != null) {
276 try {
@@ -274,23 +280,46 @@ class HttpIdentityApi implements IdentityApi {
280 }
281 }
282
277 - Future<void> _clearSession() async {
278 - final scope =
279 - currentUserId == null ? null : '$endpointIdentity|$currentUserId';
283 + /// Forced expiry never represents user consent to erase unsent work.
284 + Future<void> _expireSession({String? scopeOverride}) async {
285 + _sessionGeneration++;
286 + hasQuarantinedSession = true;
287 + await _clearSession(quarantine: true, scopeOverride: scopeOverride);
288 + }
289 +
290 + Future<void> _clearSession(
291 + {bool quarantine = false, String? scopeOverride}) async {
292 + final scope = scopeOverride ??
293 + (currentUserId == null ? null : '$endpointIdentity|$currentUserId');
294 accessToken = null;
295 _refreshToken = null;
296 currentUserId = null;
283 - onSessionChanged?.call();
297 Object? failure;
298 StackTrace? failureStack;
299 + Future<void>? quarantinePending;
300 + // Invalidate old cache handles synchronously, before notifying the signed
301 + // out UI or awaiting credential storage. Quarantine performs no disk writes.
302 try {
287 - await _sessionStore.clear();
303 + if (quarantine && scope != null) {
304 + quarantinePending = onScopeQuarantined?.call(scope);
305 + }
306 } catch (error, stack) {
307 failure = error;
308 failureStack = stack;
309 }
310 + onSessionChanged?.call();
311 try {
293 - if (scope != null) await onScopeDiscarded?.call(scope);
312 + await _sessionStore.clear();
313 + } catch (error, stack) {
314 + failure ??= error;
315 + failureStack ??= stack;
316 + }
317 + try {
318 + if (quarantine) {
319 + await quarantinePending;
320 + } else if (scope != null) {
321 + await onScopeDiscarded?.call(scope);
322 + }
323 } catch (error, stack) {
324 failure ??= error;
325 failureStack ??= stack;
@@ -312,6 +341,7 @@ class HttpIdentityApi implements IdentityApi {
341 bool auth = false,
342 bool retry = true,
343 }) async {
344 + requireWebInstanceOwnership();
345 final requestGeneration = _sessionGeneration;
346 if (auth && accessToken == null) {
347 throw const ApiException(401, 'session_expired');
@@ -331,6 +361,7 @@ class HttpIdentityApi implements IdentityApi {
361 throw const ApiException(0, 'network_unavailable');
362 }
363
364 + requireWebInstanceOwnership();
365 if (auth && requestGeneration != _sessionGeneration) {
366 throw const ApiException(401, 'session_changed');
367 }
@@ -341,7 +372,7 @@ class HttpIdentityApi implements IdentityApi {
372 }
373
374 if (response.statusCode < 200 || response.statusCode >= 300) {
344 - if (response.statusCode == 401 && auth) await logout(revoke: false);
375 + if (response.statusCode == 401 && auth) await _expireSession();
376 var code = 'request_failed';
377 var details = <String, dynamic>{};
378 if (response.body.isNotEmpty) {
@@ -379,7 +410,7 @@ class HttpIdentityApi implements IdentityApi {
410 } on ApiException catch (error) {
411 if (generation == _sessionGeneration &&
412 (error.statusCode == 401 || error.statusCode == 403)) {
382 - await logout(revoke: false);
413 + await _expireSession();
414 }
415 rethrow;
416 }
apps/lifemate/lib/local_write_guard.dart
+4
@@ -1,5 +1,6 @@
1 import 'package:flutter/foundation.dart';
2 import 'package:flutter/services.dart';
3 +import 'web_instance.dart';
4
5 /// Android process lifetime protection, independent of a Flutter engine/isolate.
6 /// An unconfirmed write can only be recovered by killing the Android process.
@@ -11,12 +12,14 @@ final class LocalWriteGuard {
12 !kIsWeb && defaultTargetPlatform == TargetPlatform.android;
13
14 Future<bool> getBlocked() async {
15 + requireWebInstanceOwnership();
16 if (!_native) return false;
17 // A missing/invalid native response must never grant access to cached data.
18 return await _channel.invokeMethod<bool>('getBlocked') ?? true;
19 }
20
21 Future<String?> beginWrite() async {
22 + requireWebInstanceOwnership();
23 if (!_native) return null;
24 final token = await _channel.invokeMethod<String>('beginWrite');
25 if (token == null || token.isEmpty) {
@@ -26,6 +29,7 @@ final class LocalWriteGuard {
29 }
30
31 Future<void> completeWrite(String? token) async {
32 + requireWebInstanceOwnership();
33 if (!_native) return;
34 if (token == null ||
35 await _channel.invokeMethod<bool>('completeWrite', token) != true) {
apps/lifemate/lib/main.dart
+18 -1
@@ -10,9 +10,11 @@ import 'endpoint_settings.dart';
10 import 'offline_store.dart';
11 import 'notifications_ui.dart';
12 import 'sync_changes_ui.dart';
13 +import 'web_instance.dart';
14 import 'package:flutter/foundation.dart';
15
16 void main() {
17 + requireWebInstanceOwnership();
18 WidgetsFlutterBinding.ensureInitialized();
19 runApp(const LifeMateApp());
20 }
@@ -37,7 +39,9 @@ class _LifeMateAppState extends State<LifeMateApp> {
39 super.initState();
40 if (widget.api == null) {
41 runtime = widget.runtime ??
40 - RuntimeController(onScopeDiscarded: OfflineStore.clearNamespace);
42 + RuntimeController(
43 + onScopeDiscarded: OfflineStore.clearNamespace,
44 + onScopeQuarantined: OfflineStore.invalidateNamespace);
45 if (!runtime!.initialized) runtime!.initialize();
46 }
47 }
@@ -95,6 +99,7 @@ class _LifeMateAppState extends State<LifeMateApp> {
99 api: api,
100 invitationToken: invitation,
101 runtimeManaged: managed,
102 + sessionQuarantined: api is HttpIdentityApi && api.hasQuarantinedSession,
103 onEndpointSettings: managed ? editEndpoints : null);
104 }
105
@@ -291,10 +296,12 @@ class SignInPage extends StatefulWidget {
296 required this.api,
297 this.invitationToken,
298 this.runtimeManaged = false,
299 + this.sessionQuarantined = false,
300 this.onEndpointSettings});
301 final IdentityApi api;
302 final String? invitationToken;
303 final bool runtimeManaged;
304 + final bool sessionQuarantined;
305 final Future<void> Function()? onEndpointSettings;
306 @override
307 State<SignInPage> createState() => _SignInPageState();
@@ -346,6 +353,16 @@ class _SignInPageState extends State<SignInPage> {
353 const Text('لایف‌گاید · همراه تحصیلی و خانوادگی',
354 textAlign: TextAlign.center),
355 const SizedBox(height: 28),
356 + if (widget.sessionQuarantined) ...[
357 + const Card(
358 + child: Padding(
359 + padding: EdgeInsets.all(12),
360 + child: Text(
361 + 'نشستت پایان یافته است. تغییرهای ارسال‌نشده این دستگاه حذف نشده‌اند. برای ادامه با همان حساب و سرویس دوباره وارد شو.'),
362 + ),
363 + ),
364 + const SizedBox(height: 12),
365 + ],
366 if (widget.invitationToken != null) ...[
367 const Card(
368 child: Padding(
apps/lifemate/lib/offline_store.dart
+8
@@ -88,6 +88,14 @@ class OfflineStore {
88 final String scope;
89 String get _key =>
90 'lifeguide.offline.v2.${base64Url.encode(utf8.encode(scope))}';
91 +
92 + /// Stop every existing handle before identity changes without deleting its
93 + /// durable work. A fresh authenticated handle can reopen the same namespace.
94 + static Future<void> invalidateNamespace(String scope) {
95 + _generations[scope] = (_generations[scope] ?? 0) + 1;
96 + return Future<void>.value();
97 + }
98 +
99 static Future<void> clearNamespace(String scope) {
100 // Invalidate old stores immediately, including futures waiting for the lock.
101 _generations[scope] = (_generations[scope] ?? 0) + 1;
apps/lifemate/lib/runtime_controller.dart
+7
@@ -2,12 +2,14 @@ import 'package:flutter/foundation.dart';
2 import 'api.dart';
3 import 'runtime_config.dart';
4 import 'session_store.dart';
5 +import 'web_instance.dart';
6
7 class RuntimeController extends ChangeNotifier {
8 RuntimeController(
9 {RuntimeConfigStore? configStore,
10 SessionStore? sessionStore,
11 this.onScopeDiscarded,
12 + this.onScopeQuarantined,
13 HttpIdentityApi Function(RuntimeConfig)? apiFactory})
14 : _configStore = configStore ?? RuntimeConfigStore(),
15 _sessionStore = sessionStore ?? createSessionStore(),
@@ -15,6 +17,7 @@ class RuntimeController extends ChangeNotifier {
17 final RuntimeConfigStore _configStore;
18 final SessionStore _sessionStore;
19 final Future<void> Function(String)? onScopeDiscarded;
20 + final Future<void> Function(String)? onScopeQuarantined;
21 final HttpIdentityApi Function(RuntimeConfig)? _apiFactory;
22 RuntimeConfig config = RuntimeConfig();
23 HttpIdentityApi? api;
@@ -33,6 +36,7 @@ class RuntimeController extends ChangeNotifier {
36 baseUrl: config.apiBaseUrl!, sessionStore: _sessionStore);
37 next.onSessionChanged = _notify;
38 next.onScopeDiscarded = onScopeDiscarded;
39 + next.onScopeQuarantined = onScopeQuarantined;
40 return next;
41 }
42
@@ -43,6 +47,7 @@ class RuntimeController extends ChangeNotifier {
47 api?.close();
48 api = null;
49 try {
50 + requireWebInstanceOwnership();
51 final loaded = await _configStore.load();
52 if (_disposed || generation != _generation) return;
53 config = loaded;
@@ -62,6 +67,7 @@ class RuntimeController extends ChangeNotifier {
67 /// Server switches invalidate the session before any new endpoint is used.
68 /// Caller discards its previous user/endpoint cache and queued mutations.
69 Future<void> updateEndpoints(RuntimeConfig next) async {
70 + requireWebInstanceOwnership();
71 if (_disposed) return;
72 _generation++;
73 try {
@@ -84,6 +90,7 @@ class RuntimeController extends ChangeNotifier {
90 }
91
92 Future<void> signOut() async {
93 + requireWebInstanceOwnership();
94 try {
95 await api?.logout();
96 error = null;
apps/lifemate/lib/session_store_web.dart
+15 -4
@@ -1,5 +1,6 @@
1 import 'dart:js_interop';
2 import 'session_store.dart';
3 +import 'web_instance.dart';
4
5 @JS('localStorage')
6 external _Storage get _storage;
@@ -13,10 +14,20 @@ extension type _Storage(JSObject _) implements JSObject {
14 /// tokens stay in memory. This requires the host's HTTPS and strict CSP gates.
15 class PlatformSessionStore implements SessionStore {
16 @override
16 - Future<String?> read() async => _storage.getItem(sessionStorageKey);
17 + Future<String?> read() async {
18 + requireWebInstanceOwnership();
19 + return _storage.getItem(sessionStorageKey);
20 + }
21 +
22 @override
18 - Future<void> write(String value) async =>
19 - _storage.setItem(sessionStorageKey, value);
23 + Future<void> write(String value) async {
24 + requireWebInstanceOwnership();
25 + _storage.setItem(sessionStorageKey, value);
26 + }
27 +
28 @override
21 - Future<void> clear() async => _storage.removeItem(sessionStorageKey);
29 + Future<void> clear() async {
30 + requireWebInstanceOwnership();
31 + _storage.removeItem(sessionStorageKey);
32 + }
33 }
apps/lifemate/lib/web_instance.dart new
+6
@@ -0,0 +1,6 @@
1 +import 'web_instance_native.dart'
2 + if (dart.library.js_interop) 'web_instance_browser.dart' as platform;
3 +
4 +/// Web credentials, personal caches and API access require the bootstrap's
5 +/// document-lifetime origin lock. Native platforms have their own coordination.
6 +void requireWebInstanceOwnership() => platform.requireWebInstanceOwnership();
apps/lifemate/lib/web_instance_browser.dart new
+10
@@ -0,0 +1,10 @@
1 +import 'dart:js_interop';
2 +
3 +@JS('lifeguideInstanceOwned')
4 +external bool? get _instanceOwned;
5 +
6 +void requireWebInstanceOwnership() {
7 + if (_instanceOwned != true) {
8 + throw StateError('LifeGuide web instance does not own its origin lock');
9 + }
10 +}
apps/lifemate/lib/web_instance_native.dart new
+1
@@ -0,0 +1 @@
1 +void requireWebInstanceOwnership() {}
apps/lifemate/pubspec.yaml
+1 -1
@@ -1,5 +1,5 @@
1 name: lifemate
2 -version: 0.5.0+3
2 +version: 0.5.1+4
3 publish_to: none
4 description: LifeGuide personal, family and learning companion.
5 environment:
apps/lifemate/test/runtime_config_test.dart
+9 -3
@@ -286,12 +286,14 @@ void main() {
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);
@@ -299,10 +301,11 @@ void main() {
301 expect(await api.restoreSession(), isFalse);
302 expect(sent, 0);
303 expect(store.value, isNull);
302 - expect(discarded, ['https://old.example.test|user-1']);
304 + expect(discarded, isEmpty);
305 + expect(quarantined, ['https://old.example.test|user-1']);
306 });
307 test(
305 - 'revoked refresh token clears the old cache scope without anonymous access',
308 + 'revoked refresh token quarantines the old scope without anonymous access',
309 () async {
310 final store = MemorySessionStore()
311 ..value = jsonEncode({
@@ -311,18 +314,21 @@ void main() {
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);
325 - expect(discarded, ['https://api.example.test|user-1']);
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 {
apps/lifemate/test/session_expiry_test.dart new
+240
@@ -0,0 +1,240 @@
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 +}
apps/lifemate/test/web/instance_guard_browser.dart new
+87
@@ -0,0 +1,87 @@
1 +// Browser-only focused tests of the actual Dart access paths. The test runner
2 +// supplies controlled ownership; production ownership comes from Web Locks.
3 +import 'dart:js_interop';
4 +
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/local_write_guard.dart';
10 +import 'package:lifemate/offline_store.dart';
11 +import 'package:lifemate/session_store.dart';
12 +
13 +@JS('lifeguideInstanceOwned')
14 +external set _owned(bool value);
15 +
16 +@JS('localStorage')
17 +external _Storage get _storage;
18 +extension type _Storage(JSObject _) implements JSObject {
19 + external String? getItem(String key);
20 + external void setItem(String key, String value);
21 + external void removeItem(String key);
22 +}
23 +
24 +void main() {
25 + setUp(() {
26 + _owned = false;
27 + _storage.setItem(sessionStorageKey, 'synthetic-existing-session');
28 + });
29 + tearDown(() {
30 + _storage.removeItem(sessionStorageKey);
31 + _owned = false;
32 + });
33 +
34 + test('unowned web session cannot read, replace or erase owner credentials',
35 + () async {
36 + final store = createSessionStore();
37 + await expectLater(store.read(), throwsStateError);
38 + await expectLater(store.write('synthetic-replacement'), throwsStateError);
39 + await expectLater(store.clear(), throwsStateError);
40 + expect(_storage.getItem(sessionStorageKey), 'synthetic-existing-session');
41 + _owned = true;
42 + expect(await store.read(), 'synthetic-existing-session');
43 + });
44 +
45 + test(
46 + 'unowned web API never sends a request; late response cannot be accepted',
47 + () async {
48 + var requests = 0;
49 + final api = HttpIdentityApi(
50 + baseUrl: 'https://family.example.test/api',
51 + client: MockClient((request) async {
52 + requests++;
53 + // Simulate document suspension while an owned request was in flight.
54 + _owned = false;
55 + return http.Response('{"synthetic":true}', 200);
56 + }));
57 + addTearDown(api.close);
58 + await expectLater(
59 + api.requestJson('GET', '/v1/profile', auth: false), throwsStateError);
60 + expect(requests, 0);
61 + _owned = true;
62 + await expectLater(
63 + api.requestJson('GET', '/v1/profile', auth: false), throwsStateError);
64 + expect(requests, 1);
65 + });
66 +
67 + test('unowned personal-cache read and write fail before storage access',
68 + () async {
69 + const guard = LocalWriteGuard();
70 + await expectLater(guard.getBlocked(), throwsStateError);
71 + await expectLater(guard.beginWrite(), throwsStateError);
72 + final store = OfflineStore.forNamespace('synthetic-owner-cache',
73 + session: OfflineSession());
74 + final blocked = isA<ApiException>().having(
75 + (error) => error.code, 'code', 'local_storage_restart_required');
76 + await expectLater(store.readList('planner'), throwsA(blocked));
77 + await expectLater(
78 + store.writeList('planner', [
79 + {'id': 'synthetic-item', 'title': 'synthetic'}
80 + ]),
81 + throwsA(blocked));
82 + expect(
83 + isOfflineFailure(
84 + const ApiException(500, 'local_storage_restart_required')),
85 + false);
86 + });
87 +}
apps/lifemate/tool/test_web_bootstrap.mjs
+17 -4
@@ -7,19 +7,32 @@ const script = (await readFile(new URL('../web/flutter_bootstrap.js', import.met
7 let engineConfig;
8 let removed = false;
9 const status = {remove() { removed = true; }};
10 -const result = vm.runInNewContext(script, {
10 +let ready;
11 +const started = new Promise(resolve => { ready = resolve; });
12 +const window = {isSecureContext:true,addEventListener() {}};
13 +vm.runInNewContext(script, {
14 URL,
12 - navigator: {},
13 - document: {baseURI: 'https://family.example.test/', getElementById: () => status},
15 + window,
16 + navigator: {locks: {request(name, options, callback) {
17 + assert.equal(name,'lifeguide.active-instance.v1');
18 + assert.equal(options.mode,'exclusive');
19 + assert.equal(options.ifAvailable,true);
20 + callback({name});
21 + return new Promise(() => {});
22 + }}},
23 + document: {baseURI: 'https://family.example.test/',
24 + getElementById: id => id === 'startup-status' ? status : null},
25 _flutter: {loader: {async load(options) {
26 assert.equal(options.config.canvasKitBaseUrl, 'https://family.example.test/canvaskit/');
27 await options.onEntrypointLoaded({async initializeEngine(config) {
28 engineConfig = config;
29 return {async runApp() {}};
30 }});
31 + ready();
32 }}},
33 });
22 -await result;
34 +await started;
35 +assert.equal(window.lifeguideInstanceOwned,true);
36 assert.equal(engineConfig?.fontFallbackBaseUrl, 'https://family.example.test/assets/fonts/fallback/');
37 assert.equal(removed, true);
38 console.log('Custom bootstrap passes the local font configuration to the Flutter engine.');
apps/lifemate/tool/test_web_instance.cjs new
+240
@@ -0,0 +1,240 @@
1 +// Real Chromium Web Locks at intercepted synthetic HTTPS origins. Fixture mode
2 +// uses the production bootstrap; compiled mode additionally runs Flutter itself.
3 +// This does not establish real TLS, installed-PWA, Safari or device acceptance.
4 +const assert = require('node:assert/strict');
5 +const {readFile} = require('node:fs/promises');
6 +const path = require('node:path');
7 +const {chromium} = require('playwright');
8 +
9 +const compiled = process.argv.includes('--compiled');
10 +const artifactRoot = path.resolve(process.argv[process.argv.indexOf('--compiled') + 1] || 'build/web');
11 +const origin = 'https://family.example.test';
12 +const otherOrigin = 'https://independent.example.test';
13 +const sessionKey = 'lifeguide.refresh_session.v1';
14 +const userId = '11111111-1111-4111-8111-111111111111';
15 +const accessToken = 'synthetic.' + Buffer.from(JSON.stringify({sub:userId})).toString('base64url') + '.synthetic';
16 +const mime = {'.html':'text/html','.js':'application/javascript','.json':'application/json',
17 + '.wasm':'application/wasm','.ttf':'font/ttf','.otf':'font/otf','.woff2':'font/woff2',
18 + '.png':'image/png','.svg':'image/svg+xml'};
19 +const csp = "default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self'; connect-src 'self'; worker-src 'self' blob:; object-src 'none'; base-uri 'self'; frame-ancestors 'none'; form-action 'self'";
20 +
21 +async function main() {
22 + const bootstrap = (await readFile(path.resolve('web/flutter_bootstrap.js'),'utf8'))
23 + .replace('{{flutter_js}}','').replace('{{flutter_build_config}}','');
24 + const browser = await chromium.launch({headless:true,
25 + // Playwright otherwise disables BFCache, which would weaken the history check.
26 + ignoreDefaultArgs:['--disable-back-forward-cache'],
27 + ...(process.env.LIFEGUIDE_TEST_CHROMIUM_PATH ? {executablePath:process.env.LIFEGUIDE_TEST_CHROMIUM_PATH} : {})});
28 + const checks = [];
29 + let historyEvidence;
30 + try {
31 + async function context({unsupported=false}={}) {
32 + const ctx = await browser.newContext({serviceWorkers:'block',ignoreHTTPSErrors:false});
33 + const restoredPages = new Set();
34 + await ctx.exposeBinding('instanceRestorationObserved',({page},persisted) => {
35 + if (persisted) restoredPages.add(page);
36 + });
37 + await ctx.addInitScript(({sessionKey,unsupported}) => {
38 + window.instanceProbe = {reads:0,writes:0,removes:0,starts:0};
39 + window.addEventListener('pageshow',event =>
40 + window.instanceRestorationObserved(event.persisted).catch(() => {}));
41 + for (const [method,counter] of [['getItem','reads'],['setItem','writes'],['removeItem','removes']]) {
42 + const original = Storage.prototype[method];
43 + Storage.prototype[method] = function(key,...rest) {
44 + if (key === sessionKey || String(key).includes('lifeguide.offline')) window.instanceProbe[counter]++;
45 + return original.call(this,key,...rest);
46 + };
47 + }
48 + if (unsupported) Object.defineProperty(navigator,'locks',{value:undefined});
49 + },{sessionKey,unsupported});
50 + const requests = new Map();
51 + await ctx.route('**/*',async route => {
52 + const request = route.request(), url = new URL(request.url());
53 + assert([origin,otherOrigin].includes(url.origin),'No external requests are permitted');
54 + let page;
55 + try { page = request.frame().page(); } catch {}
56 + if (page && (url.pathname.startsWith('/api/') || url.pathname === '/config.json')) {
57 + const counts = requests.get(page) || {api:0,refresh:0,config:0};
58 + if (url.pathname === '/config.json') counts.config++;
59 + else { counts.api++; if (url.pathname.endsWith('/auth/refresh')) counts.refresh++; }
60 + requests.set(page,counts);
61 + }
62 + const respond = body => route.fulfill({contentType:'application/json',body:JSON.stringify(body)});
63 + if (url.pathname === '/setup') return route.fulfill({contentType:'text/html',body:'<!doctype html><title>Synthetic setup</title>'});
64 + if (url.pathname === '/config.json') return respond({apiBaseUrl:'/api',apiFallbackUrls:[]});
65 + if (url.pathname.endsWith('/auth/refresh')) return respond({accessToken,refreshToken:'synthetic-rotated-refresh'});
66 + if (url.pathname.endsWith('/auth/capabilities')) return respond({emailDeliveryAvailable:false,smsAvailable:false,smsStatus:'UNVERIFIED'});
67 + if (url.pathname === '/api/v1/profile') return respond({user_id:userId,display_name:'آزمون ساختگی',theme_preference:'neutral',profile_category:'adult'});
68 + if (url.pathname.startsWith('/api/')) {
69 + if (url.pathname.includes('/families')) return respond({families:[]});
70 + if (url.pathname.includes('/plan-items')) return respond({items:[]});
71 + if (url.pathname.includes('/life-contexts')) return respond({contexts:[]});
72 + if (url.pathname.includes('/notifications')) return respond({notifications:[]});
73 + return respond({});
74 + }
75 + if (!compiled) {
76 + if (url.pathname === '/flutter_bootstrap.js') return route.fulfill({contentType:'application/javascript',body:bootstrap});
77 + if (url.pathname === '/fixture-loader.js') return route.fulfill({contentType:'application/javascript',body:`
78 + window._flutter={loader:{async load(options){
79 + window.instanceProbe.starts++;
80 + localStorage.getItem('${sessionKey}');
81 + await fetch('/api/v1/auth/refresh',{method:'POST'});
82 + localStorage.setItem('${sessionKey}','synthetic-fixture-session');
83 + await options.onEntrypointLoaded({async initializeEngine(){return {async runApp(){
84 + document.body.appendChild(document.createElement('flt-glass-pane'));
85 + }}}});
86 + }}};`});
87 + return route.fulfill({contentType:'text/html',headers:{'content-security-policy':csp},body:
88 + '<!doctype html><html lang="fa" dir="rtl"><head><meta charset="utf-8"><title>LifeGuide fixture</title></head><body><p id="startup-status" role="status">در حال بارگذاری</p><script src="/fixture-loader.js"></script><script src="/flutter_bootstrap.js"></script></body></html>'});
89 + }
90 + const local = path.resolve(artifactRoot,'.' + (url.pathname === '/' ? '/index.html' : decodeURIComponent(url.pathname)));
91 + assert(local.startsWith(artifactRoot + path.sep),'Artifact path must remain in the output directory');
92 + try { return await route.fulfill({contentType:mime[path.extname(local)] || 'application/octet-stream',headers:{'content-security-policy':csp,'cache-control':'no-store'},body:await readFile(local)}); }
93 + catch { return route.fulfill({status:404,body:'Missing synthetic artifact resource'}); }
94 + });
95 + // Seed only once through an explicit setup document, never from tab init.
96 + const setup = await ctx.newPage();
97 + await setup.goto(origin + '/setup');
98 + await setup.evaluate(({sessionKey,userId,origin}) => localStorage.setItem(sessionKey,
99 + JSON.stringify({endpoint:origin + '/api',refreshToken:'synthetic-refresh',userId})),{sessionKey,userId,origin});
100 + await setup.close();
101 + return {ctx,requests,restoredPages};
102 + }
103 + const counts = (fixture,page) => fixture.requests.get(page) || {api:0,refresh:0,config:0};
104 + async function settle(page) {
105 + await page.waitForFunction(() => document.querySelector('flt-glass-pane') ||
106 + document.querySelector('#startup-retry'),null,{timeout:60000});
107 + await page.waitForLoadState('networkidle');
108 + }
109 + async function open(fixture,url=origin) {
110 + const page = await fixture.ctx.newPage();
111 + await page.goto(url,{timeout:60000});
112 + await settle(page);
113 + return page;
114 + }
115 + async function owner(fixture,page) {
116 + assert.equal(await page.locator('flt-glass-pane').count(),1,'The owner must start Flutter');
117 + assert.equal(await page.evaluate(() => window.lifeguideInstanceOwned),true,'Only an acquired lock grants ownership');
118 + if (new URL(page.url()).origin === origin) {
119 + // Engine DOM appears before RuntimeController's asynchronous restore.
120 + // In particular, retry starts in a document already marked network-idle.
121 + try {
122 + await page.waitForFunction(() => window.instanceProbe.reads >= 1 &&
123 + window.instanceProbe.writes >= 1,null,{timeout:60000});
124 + } catch (error) {
125 + const diagnostics = await page.evaluate(sessionKey => ({
126 + owned:window.lifeguideInstanceOwned,probe:{...window.instanceProbe},
127 + sessionPresent:localStorage.getItem(sessionKey) !== null,
128 + engineCount:document.querySelectorAll('flt-glass-pane').length,
129 + startupStatusPresent:!!document.querySelector('#startup-status'),
130 + }),sessionKey);
131 + throw new Error('Session restore did not complete: ' + JSON.stringify({
132 + requests:counts(fixture,page),...diagnostics,reason:error.name}));
133 + }
134 + assert.equal(counts(fixture,page).refresh,1,'The owner restores and rotates the synthetic session exactly once');
135 + const probe = await page.evaluate(() => window.instanceProbe);
136 + assert(probe.reads >= 1 && probe.writes >= 1,'Owner session store is exercised');
137 + }
138 + }
139 + async function blocked(fixture,page,unsupported=false) {
140 + assert.equal(await page.locator('flt-glass-pane').count(),0,'A blocked instance must never start Flutter');
141 + assert.equal(await page.evaluate(() => window.lifeguideInstanceOwned),false);
142 + assert.deepEqual(counts(fixture,page),{api:0,refresh:0,config:0},'Blocked tabs make no runtime/API/auth requests');
143 + assert.deepEqual(await page.evaluate(() => window.instanceProbe),{reads:0,writes:0,removes:0,starts:0},'Blocked tabs do not read, write or erase personal storage');
144 + assert.match(await page.locator('#startup-status').textContent(),unsupported ? /مرورگر/ : /پنجره/);
145 + assert(await page.locator('#startup-retry').isVisible(),'Blocked user can retry');
146 + }
147 +
148 + const sequential = await context();
149 + const first = await open(sequential);
150 + const second = await open(sequential);
151 + // This assertion deliberately fails against the pre-gate production bootstrap.
152 + assert.equal(await second.locator('flt-glass-pane').count(),0,'Second same-origin tab must not initialize Flutter');
153 + await owner(sequential,first); await blocked(sequential,second);
154 + await first.bringToFront(); await second.bringToFront();
155 + await second.locator('#startup-retry').click(); await settle(second);
156 + await blocked(sequential,second);
157 + checks.push('same-origin contention + background ownership + retry denied');
158 + await first.close();
159 + await second.locator('#startup-retry').click(); await settle(second);
160 + await owner(sequential,second);
161 + checks.push('owner close then blocked-tab retry acquires without erasure');
162 + const separateOrigin = await open(sequential,otherOrigin);
163 + assert.equal(await separateOrigin.evaluate(() => window.lifeguideInstanceOwned),true,'Independent origins acquire their own lock');
164 + await sequential.ctx.close();
165 + checks.push('independent origin unaffected');
166 +
167 + const racing = await context();
168 + const [raceA,raceB] = await Promise.all([open(racing),open(racing)]);
169 + const ownsA = await raceA.evaluate(() => window.lifeguideInstanceOwned);
170 + assert.notEqual(ownsA,await raceB.evaluate(() => window.lifeguideInstanceOwned),'Simultaneous opens have exactly one owner');
171 + await owner(racing,ownsA ? raceA : raceB);
172 + await blocked(racing,ownsA ? raceB : raceA);
173 + const independent = await context();
174 + await owner(independent,await open(independent));
175 + await independent.ctx.close(); await racing.ctx.close();
176 + checks.push('simultaneous race has one owner; separate browser profile unaffected');
177 +
178 + const missing = await context({unsupported:true});
179 + await blocked(missing,await open(missing),true);
180 + await missing.ctx.close();
181 + checks.push('unsupported Web Locks fails closed');
182 +
183 + const crashed = await context();
184 + const crashOwner = await open(crashed); await owner(crashed,crashOwner);
185 + const cdp = await crashed.ctx.newCDPSession(crashOwner);
186 + const observedCrash = new Promise(resolve => crashOwner.once('crash',resolve));
187 + // A crashed renderer need not answer the CDP command. Observe its actual
188 + // crash event, then acquire from a new document before closing the old tab.
189 + cdp.send('Page.crash').catch(() => {});
190 + let crashTimeout;
191 + try {
192 + await Promise.race([observedCrash,new Promise((_,reject) => {
193 + crashTimeout = setTimeout(() => reject(new Error('Renderer crash was not observed')),15000);
194 + })]);
195 + } finally { clearTimeout(crashTimeout); }
196 + await owner(crashed,await open(crashed));
197 + await crashed.ctx.close();
198 + checks.push('actual renderer crash releases lock for a fresh tab');
199 +
200 + const history = await context();
201 + const historyOwner = await open(history); await owner(history,historyOwner);
202 + await historyOwner.goto(otherOrigin + '/setup');
203 + const replacement = await open(history); await owner(history,replacement);
204 + history.requests.delete(historyOwner);
205 + await historyOwner.goBack(); await settle(historyOwner);
206 + await blocked(history,historyOwner);
207 + historyEvidence = await historyOwner.evaluate(() => {
208 + const navigation = performance.getEntriesByType('navigation')[0];
209 + return {navigationType:navigation?.type,notRestoredReasons:navigation?.notRestoredReasons?.toJSON?.() || null};
210 + });
211 + historyEvidence.persistedPageshowObserved = history.restoredPages.has(historyOwner);
212 + historyEvidence.restoration = historyEvidence.persistedPageshowObserved
213 + ? 'actual persisted restoration followed by guarded rebootstrap'
214 + : 'ordinary history rebootstrap; actual BFCache restoration UNVERIFIED';
215 + await history.ctx.close();
216 + checks.push('history navigation cannot restore an owner while another tab owns');
217 +
218 + const restoration = await context();
219 + const stale = await open(restoration); await owner(restoration,stale);
220 + await stale.evaluate(() => window.dispatchEvent(new PageTransitionEvent('pagehide',{persisted:true})));
221 + assert.equal(await stale.evaluate(() => window.lifeguideInstanceOwned),false,'A suspended document immediately loses its ownership assertion');
222 + const suspendedContender = await open(restoration); await blocked(restoration,suspendedContender);
223 + // Explicitly exercise the persisted event as a separate synthetic lifecycle
224 + // case; the history test above uses actual browser navigation.
225 + restoration.requests.delete(stale);
226 + await Promise.all([
227 + stale.waitForEvent('framenavigated',{predicate:frame => frame === stale.mainFrame()}),
228 + stale.evaluate(() => window.dispatchEvent(new PageTransitionEvent('pageshow',{persisted:true}))).catch(error => {
229 + if (!/context was destroyed|navigation/i.test(error.message)) throw error;
230 + }),
231 + ]);
232 + await settle(stale); await owner(restoration,stale);
233 + await blocked(restoration,suspendedContender);
234 + await restoration.ctx.close();
235 + checks.push('synthetic persisted pagehide invalidates; pageshow replaces old engine before re-entry');
236 + console.log(JSON.stringify({mode:compiled ? 'compiled Flutter artifact' : 'production bootstrap with instrumented loader',
237 + browser:'real Chromium; synthetic intercepted HTTPS; TLS/PWA/Safari/device UNVERIFIED',checks,historyEvidence},null,2));
238 + } finally { await browser.close(); }
239 +}
240 +main().catch(error => {console.error(error.stack);process.exitCode=1;});
apps/lifemate/tool/test_web_session_expiry.cjs new
+76
@@ -0,0 +1,76 @@
1 +// Compiled-client regression adapted from the independent security probe.
2 +// Synthetic held refresh + explicit pagehide + HTTP401; no live backend, TLS,
3 +// true BFCache restoration or in-flight real renderer crash is claimed.
4 +const assert = require('node:assert/strict');
5 +const { readFile } = require('node:fs/promises');
6 +const path = require('node:path');
7 +const { chromium } = require('playwright');
8 +const root = path.resolve(process.argv.find(arg => arg.startsWith('--artifact='))?.slice('--artifact='.length) || 'build/web');
9 +const expectedPending = Number(process.argv.find(arg => arg.startsWith('--expected-pending='))?.slice('--expected-pending='.length) ?? 1);
10 +assert([0,1].includes(expectedPending), 'Use --expected-pending=0 or 1');
11 +const origin = 'https://review.example.test';
12 +const userId = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
13 +const sessionKey = 'lifeguide.refresh_session.v1';
14 +const scope = origin + '/api|' + userId;
15 +const offlineKey = 'lifeguide.offline.v2.' + Buffer.from(scope).toString('base64').replaceAll('+','-').replaceAll('/','_');
16 +const access = 'synthetic.' + Buffer.from(JSON.stringify({ sub: userId })).toString('base64url') + '.synthetic';
17 +const types = { '.html':'text/html', '.js':'application/javascript', '.json':'application/json', '.wasm':'application/wasm', '.ttf':'font/ttf', '.otf':'font/otf', '.png':'image/png' };
18 +(async () => {
19 + const browser = await chromium.launch({ headless: true, ...(process.env.LIFEGUIDE_TEST_CHROMIUM_PATH ? {executablePath:process.env.LIFEGUIDE_TEST_CHROMIUM_PATH} : {}) });
20 + try {
21 + const ctx = await browser.newContext({ serviceWorkers:'block' });
22 + let refreshes = 0, releaseFirst, firstObserved;
23 + const observed = new Promise(resolve => firstObserved = resolve);
24 + const released = new Promise(resolve => releaseFirst = resolve);
25 + await ctx.route('**/*', async route => {
26 + const url = new URL(route.request().url());
27 + assert.equal(url.origin, origin, 'External requests are forbidden');
28 + const json = (body, status=200) => route.fulfill({ status, contentType:'application/json', body:JSON.stringify(body) });
29 + if (url.pathname === '/setup') return route.fulfill({ contentType:'text/html', body:'<!doctype html><title>Synthetic setup</title>' });
30 + if (url.pathname === '/config.json') return json({ apiBaseUrl:'/api', apiFallbackUrls:[] });
31 + if (url.pathname === '/api/v1/auth/refresh') {
32 + refreshes++;
33 + if (refreshes === 1) { firstObserved(); await released; return json({ accessToken:access, refreshToken:'synthetic-new-token-after-rotation' }); }
34 + return json({ error:'invalid_refresh' }, 401);
35 + }
36 + if (url.pathname.startsWith('/api/')) return json({ emailDeliveryAvailable:false, smsAvailable:false, smsStatus:'UNVERIFIED' });
37 + const file = path.resolve(root, '.' + (url.pathname === '/' ? '/index.html' : url.pathname));
38 + assert(file.startsWith(root + path.sep));
39 + try { return route.fulfill({ contentType:types[path.extname(file)] || 'application/octet-stream', body:await readFile(file) }); }
40 + catch { return route.fulfill({ status:404, body:'Missing synthetic resource' }); }
41 + });
42 + const page = await ctx.newPage();
43 + await page.goto(origin + '/setup');
44 + await page.evaluate(({sessionKey,userId,origin,offlineKey,scope}) => {
45 + localStorage.setItem(sessionKey, JSON.stringify({ endpoint:origin+'/api', userId, refreshToken:'synthetic-old-token' }));
46 + localStorage.setItem(offlineKey, JSON.stringify(JSON.stringify({ version:2, scope, caches:{}, queue:[{ id:'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb',entityId:'cccccccc-cccc-4ccc-8ccc-cccccccccccc',payload:{title:'Synthetic unsent item'},queueStatus:'queued' }],lastSyncAt:null,lastAckAt:null })));
47 + }, {sessionKey,userId,origin,offlineKey,scope});
48 + const snapshot = () => page.evaluate(({sessionKey,offlineKey}) => {
49 + const raw = localStorage.getItem(offlineKey);
50 + return { sessionPresent:localStorage.getItem(sessionKey)!==null, pending:raw ? JSON.parse(JSON.parse(raw)).queue.length : null };
51 + }, {sessionKey,offlineKey});
52 + await page.goto(origin, {waitUntil:'domcontentloaded'});
53 + let observedTimeout;
54 + try { await Promise.race([observed, new Promise((_,reject) => { observedTimeout=setTimeout(() => reject(new Error('No first refresh within 30 seconds')),30000); })]); } finally { clearTimeout(observedTimeout); }
55 + const before = await snapshot();
56 + const originalCache = await page.evaluate(key => localStorage.getItem(key), offlineKey);
57 + await page.evaluate(() => window.dispatchEvent(new PageTransitionEvent('pagehide',{persisted:true})));
58 + assert.equal(await page.evaluate(() => window.lifeguideInstanceOwned), false);
59 + releaseFirst();
60 + await page.waitForLoadState('networkidle');
61 + const afterLateResponse = await snapshot();
62 + await page.reload({waitUntil:'networkidle'});
63 + await page.waitForFunction(() => !localStorage.getItem('lifeguide.refresh_session.v1'));
64 + // Network idle plus a bounded drain allows expiry's local async cleanup to finish.
65 + await page.waitForTimeout(1000);
66 + const afterReopen = await snapshot();
67 + assert.equal(before.pending,1);
68 + assert.equal(afterLateResponse.pending,1);
69 + assert.equal(refreshes,2);
70 + assert.equal(afterReopen.sessionPresent,false);
71 + assert.equal(afterReopen.pending,expectedPending,'Forced expiry must preserve unsent account-scoped mutations when expected-pending=1');
72 + if (expectedPending === 1) assert.equal(await page.evaluate(key => localStorage.getItem(key),offlineKey), originalCache, 'Forced expiry cannot rewrite any durable private payload');
73 + console.log(JSON.stringify({ evidence:'compiled current artifact; actual Chromium; synthetic intercepted refresh commit; explicit pagehide; no live server/TLS/Safari proof', before, afterLateResponse, afterReopen, refreshes }));
74 + await ctx.close();
75 + } finally { await browser.close(); }
76 +})().catch(error => { console.error(error.stack); process.exitCode=1; });
apps/lifemate/web/flutter_bootstrap.js
+76 -11
@@ -12,6 +12,43 @@ const showFailure = () => {
12 'لایف‌گاید بارگذاری نشد. اتصال را بررسی کنید و صفحه را دوباره باز کنید.';
13 };
14
15 +// A document must own the origin-wide lock before Flutter can read credentials
16 +// or personal caches. Keep the callback pending for the entire document lifetime.
17 +// Browser teardown/crash releases the lock; backgrounding must not release it.
18 +let instanceOwned = false;
19 +let documentInvalidated = false;
20 +let requestInFlight = false;
21 +Object.defineProperty(window, 'lifeguideInstanceOwned', {get: () => instanceOwned});
22 +
23 +window.addEventListener('pagehide', () => {
24 + documentInvalidated = true;
25 + instanceOwned = false;
26 +});
27 +window.addEventListener('pageshow', (event) => {
28 + // A cached engine must never resume with a stale ownership assertion. Keep
29 + // the old lock held until this document is replaced by a fresh bootstrap.
30 + if (event.persisted || documentInvalidated) window.location.reload();
31 +});
32 +
33 +function showInstanceNotice(unsupported) {
34 + const status = document.getElementById('startup-status');
35 + if (!status) return;
36 + status.setAttribute('role', 'alert');
37 + status.textContent = unsupported
38 + ? 'این مرورگر از اجرای امن لایف‌گاید پشتیبانی نمی‌کند. از یک مرورگر به‌روز و سازگار استفاده کنید.'
39 + : 'لایف‌گاید در پنجره دیگری باز است. برای ادامه، آن پنجره را ببندید و دوباره تلاش کنید.';
40 + let retry = document.getElementById('startup-retry');
41 + if (!retry) {
42 + retry = document.createElement('button');
43 + retry.id = 'startup-retry';
44 + retry.type = 'button';
45 + retry.textContent = 'تلاش دوباره';
46 + retry.style.cssText = 'display:block;margin:16px auto;padding:12px 24px;font:inherit;cursor:pointer';
47 + retry.addEventListener('click', startInstance);
48 + status.after(retry);
49 + }
50 +}
51 +
52 // Retire the legacy generated worker, which could serve stale runtime settings.
53 async function prepareWorker() {
54 if (!('serviceWorker' in navigator)) return;
@@ -27,14 +64,42 @@ async function prepareWorker() {
64 } catch (_) { /* Network-only startup still works when worker setup fails. */ }
65 }
66
30 -prepareWorker();
31 -_flutter.loader.load({
32 - config: engineConfig,
33 - onEntrypointLoaded: async (initializer) => {
34 - try {
35 - const runner = await initializer.initializeEngine(engineConfig);
36 - await runner.runApp();
37 - document.getElementById('startup-status')?.remove();
38 - } catch (_) { showFailure(); }
39 - },
40 -}).catch(showFailure);
67 +async function startInstance() {
68 + if (requestInFlight) return;
69 + if (documentInvalidated) { window.location.reload(); return; }
70 + if (!window.isSecureContext || !navigator.locks?.request) {
71 + showInstanceNotice(true);
72 + return;
73 + }
74 + requestInFlight = true;
75 + document.getElementById('startup-retry')?.remove();
76 + try {
77 + await navigator.locks.request('lifeguide.active-instance.v1',
78 + {mode: 'exclusive', ifAvailable: true}, async (lock) => {
79 + if (!lock) { showInstanceNotice(false); return; }
80 + if (documentInvalidated) return;
81 + instanceOwned = true;
82 + prepareWorker();
83 + _flutter.loader.load({
84 + config: engineConfig,
85 + onEntrypointLoaded: async (initializer) => {
86 + try {
87 + if (!instanceOwned) return;
88 + const runner = await initializer.initializeEngine(engineConfig);
89 + if (!instanceOwned) return;
90 + await runner.runApp();
91 + document.getElementById('startup-status')?.remove();
92 + } catch (_) { showFailure(); }
93 + },
94 + }).catch(showFailure);
95 + await new Promise(() => {});
96 + });
97 + } catch (_) {
98 + instanceOwned = false;
99 + showInstanceNotice(true);
100 + } finally {
101 + requestInFlight = false;
102 + }
103 +}
104 +
105 +startInstance();