LifeMate — Personal, Family & Learning Companion

fix/personal-notification-controls
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
cjs 240 lines 15.3 KB
Raw
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;});