LifeMate — Personal, Family & Learning Companion

feat/aparat-learning-library
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 276 lines 18.7 KB
Raw
1 // Developer acceptance substitute: compiled PWA, real local HTTPS/API/Postgres.
2 // Requires a normally trusted public local CA and a NEW synthetic fixture.
3 // Does not intercept responses, disable TLS, publish lessons or play media.
4 const assert = require('node:assert/strict');
5 const fs = require('node:fs/promises');
6 const path = require('node:path');
7 const os = require('node:os');
8 const https = require('node:https');
9 const {spawnSync} = require('node:child_process');
10 const {chromium} = require('../apps/lifemate/node_modules/playwright');
11
12 const root = path.resolve(__dirname, '..');
13 const origin = process.env.LEARNING_BROWSER_ORIGIN || 'https://127.0.0.1:8445';
14 const parsed = new URL(origin);
15 assert(parsed.protocol === 'https:' && parsed.hostname === '127.0.0.1' &&
16 parsed.port === '8445' && parsed.pathname === '/' && !parsed.username &&
17 !parsed.password && !parsed.search && !parsed.hash,
18 'This test is restricted to the isolated local synthetic HTTPS stack on8445.');
19 const email = process.env.SMOKE_EMAIL || '';
20 const password = process.env.SMOKE_PASSWORD || '';
21 assert(/^learning-browser-[a-f0-9]+@example\.test$/.test(email) && password.length >= 10,
22 'Provide the dedicated synthetic fixture through SMOKE_EMAIL/SMOKE_PASSWORD.');
23 assert(process.env.ROOT_CA && process.env.LEARNING_COMPOSE_ENV,
24 'ROOT_CA and private LEARNING_COMPOSE_ENV paths are required.');
25 const receiptFile = path.resolve(process.argv[2] || path.join(root,
26 'docs/audits/evidence/learning-browser-2026-10-11.json'));
27 const screenshotFile = receiptFile.replace(/\.json$/, '.png');
28 const uuid = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;
29 const escaped = value => value.replace(/[.*+?^${}()|[\]\\]/g,'\\$&');
30 const paths = [], errors = [], failures = [], auth = [], checks = [];
31 let stage = 'startup';
32 let ca;
33 const check = name => { checks.push({name, status:'PASS'}); console.log(`PASS ${name}`); };
34
35 function api(method, endpoint, body, accessToken) {
36 return new Promise((resolve,reject) => {
37 const serialized = body === undefined ? null : Buffer.from(JSON.stringify(body));
38 const req = https.request(new URL('/api' + endpoint, origin), {
39 method, ca, rejectUnauthorized:true,
40 headers:{...(serialized ? {'content-type':'application/json','content-length':serialized.length} : {}),
41 ...(accessToken ? {authorization:`Bearer ${accessToken}`} : {})}
42 }, response => {
43 assert(response.socket.authorized, 'Independent API socket must verify TLS.');
44 let content = '';
45 response.setEncoding('utf8'); response.on('data', part => content += part);
46 response.on('end', () => {
47 try {resolve({status:response.statusCode,json:content ? JSON.parse(content) : null});}
48 catch {reject(new Error('Independent API returned non-JSON content'));}
49 });
50 });
51 req.setTimeout(15000, () => req.destroy(new Error('Independent HTTPS API timed out')));
52 req.on('error', reject); req.end(serialized);
53 });
54 }
55
56 function dbJson(query) {
57 const result = spawnSync('docker', ['compose','--env-file',process.env.LEARNING_COMPOSE_ENV,
58 'exec','-T','postgres','sh','-c',
59 'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -At -v ON_ERROR_STOP=1'],
60 {cwd:root,input:query,encoding:'utf8',timeout:15000});
61 assert.equal(result.status,0,'Independent synthetic DB assertion failed.');
62 return JSON.parse(result.stdout.trim());
63 }
64
65 function observe(page) {
66 page.on('request', request => {
67 const url = new URL(request.url());
68 paths.push({origin:url.origin,path:url.pathname.replace(/[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}/gi,':fixture-id'),method:request.method()});
69 });
70 page.on('requestfailed', request => failures.push({path:new URL(request.url()).pathname,
71 failure:request.failure()?.errorText || 'network failure'}));
72 page.on('pageerror', () => errors.push('Browser page error'));
73 page.on('response', response => {
74 const endpoint = new URL(response.url()).pathname;
75 if (['/api/v1/auth/login','/api/v1/auth/refresh'].includes(endpoint))
76 auth.push({path:endpoint,status:response.status()});
77 if (response.status() >= 400) errors.push(`HTTP ${response.status()} ${endpoint.replace(/[a-f0-9-]{36}/gi,':fixture-id')}`);
78 });
79 }
80
81 async function boot(context) {
82 const page = context.pages()[0] || await context.newPage(); observe(page);
83 const response = await page.goto(origin,{waitUntil:'networkidle',timeout:60000});
84 assert.equal(response.status(),200);
85 await page.waitForFunction(() => !document.getElementById('startup-status'),null,{timeout:60000});
86 await page.locator('flt-glass-pane').waitFor({state:'attached'});
87 const accessibility = page.locator('flt-semantics-placeholder');
88 if (await accessibility.count()) await accessibility.evaluate(element => element.click());
89 await page.waitForLoadState('networkidle');
90 return page;
91 }
92
93 async function click(locator) {
94 await locator.waitFor({state:'attached',timeout:20000});
95 // Flutter RTL semantics nodes may have transformed DOM hit rectangles.
96 // Activates the rendered semantic control; never injects API/state data.
97 await locator.evaluate(element => element.click());
98 }
99 async function bodyIncludes(page, text) {
100 await page.waitForFunction(needle => document.body.textContent.includes(needle) ||
101 [...document.querySelectorAll('[aria-label]')].some(element =>
102 element.getAttribute('aria-label').includes(needle)),text,{timeout:20000});
103 }
104 async function school(page) {
105 await click(page.getByRole('button',{name:'مدرسه من',exact:true}));
106 await bodyIncludes(page,'انتخاب پایه و رشته');
107 }
108 async function lesson(page, course, unit) {
109 await page.getByLabel('جستجوی کتاب',{exact:true}).fill(course.titleFa);
110 await click(page.getByRole('button',{name:new RegExp('^' + escaped(course.titleFa) + ' ')}));
111 await bodyIncludes(page,'جستجوی درس یا صفحه');
112 await page.getByLabel('جستجوی درس یا صفحه',{exact:true}).fill(unit.titleFa);
113 await click(page.getByRole('button',{name:new RegExp('^' + escaped(unit.titleFa) + ' ')}));
114 await bodyIncludes(page,'پیشرفت شخصی:');
115 }
116
117 (async () => {
118 ca = await fs.readFile(process.env.ROOT_CA);
119 const profile = await fs.mkdtemp(path.join(os.tmpdir(),'lifeguide-learning-browser-'));
120 const launch = () => chromium.launchPersistentContext(profile,{headless:true,
121 executablePath:process.env.LIFEGUIDE_TEST_CHROMIUM_PATH || '/usr/bin/chromium',
122 ignoreHTTPSErrors:false,serviceWorkers:'allow',timezoneId:'Asia/Tehran',
123 viewport:{width:1100,height:1050}});
124 let context;
125 try {
126 stage = 'realTLS';
127 assert.equal((await api('GET','/health')).status,200); check('independent verified HTTPS health');
128 const loggedIn = await api('POST','/v1/auth/login',{email,password});
129 assert.equal(loggedIn.status,200); const token = loggedIn.json.accessToken;
130 const profileResult = await api('GET','/v1/profile',undefined,token);
131 assert.equal(profileResult.status,200); const owner = profileResult.json.user_id;
132 assert(uuid.test(owner));
133 assert.equal((await api('GET','/v1/education/library',undefined,token)).json.education,null,
134 'Use a new fixture with no preselected education.');
135
136 context = await launch(); let page = await boot(context);
137 stage = 'realLogin';
138 await page.getByLabel('ایمیل یا شماره تلفن',{exact:true}).fill(email);
139 await page.getByLabel('ایمیل یا شماره تلفن',{exact:true}).press('Tab');
140 await page.getByLabel('رمز عبور',{exact:true}).fill(password);
141 await page.getByLabel('رمز عبور',{exact:true}).press('Tab');
142 const loginResponse = page.waitForResponse(response => response.url().endsWith('/api/v1/auth/login') && response.request().method() === 'POST');
143 await click(page.getByRole('button',{name:'ورود',exact:true}));
144 const browserLogin = await loginResponse;
145 const entered = browserLogin.request().postDataJSON();
146 assert(entered.password === password,'Synthetic browser password field was not committed.');
147 assert((entered.email ?? entered.identifier) === email,'Synthetic browser contact field was not committed.');
148 assert.equal(browserLogin.status(),200);
149 await school(page); check('compiled PWA actual synthetic account login');
150
151 stage = 'educationSelection';
152 await click(page.getByRole('button',{name:'انتخاب پایه و رشته',exact:true}));
153 // The dropdown is an actual Flutter semantic button, not a native select.
154 await click(page.getByRole('button',{name:'پایه',exact:true}));
155 await click(page.getByRole('menuitem',{name:'پایه 1',exact:true}));
156 const educationResponse = page.waitForResponse(response => response.url().endsWith('/api/v1/me/education') && response.request().method() === 'PUT');
157 await click(page.getByRole('button',{name:'ذخیره',exact:true}));
158 assert.equal((await educationResponse).status(),200);
159 const library = (await api('GET','/v1/education/library',undefined,token)).json;
160 assert.deepEqual(library.education,{nationalGrade:1,trackCode:'common',schoolYear:'1405-1406'});
161 const course = library.courses.find(item => item.unitCount > 0 && item.reviewCandidateCount > 0);
162 assert(course); const detail = (await api('GET',`/v1/education/courses/${course.id}`,undefined,token)).json;
163 const unit = detail.units.find(item => item.reviewCandidateCount > 0);
164 assert(unit && uuid.test(unit.id),'A real draft resource must exist behind the publication gate.');
165 assert(detail.units.every(item => item.videos.length === 0));
166 assert.equal((await api('GET','/v1/me/learning-progress',undefined,token)).json.progress.length,0,
167 'Browsing a library must not fabricate learning progress.');
168 check('grade1 common1405-1406 saved through UI and read by independent API');
169
170 stage = 'libraryLesson'; await lesson(page,course,unit);
171 await bodyIncludes(page,'ویدیوی بازبینی‌شده و منتشرشده هنوز ثبت نشده');
172 assert.equal(await page.locator('iframe').count(),0);
173 assert.equal((await api('GET','/v1/me/learning-progress',undefined,token)).json.progress.length,0,
174 'Opening a lesson must not automatically record learning progress.');
175 check('actual imported lesson renders with draft videos unavailable, no iframe');
176
177 stage = 'progress';
178 const progressResponse = page.waitForResponse(response => response.url().includes('/api/v1/me/learning-progress/') && response.request().method() === 'PUT');
179 await click(page.getByRole('button',{name:'در حال یادگیری',exact:true}));
180 const ackResponse = await progressResponse; assert.equal(ackResponse.status(),200);
181 const ack = await ackResponse.json(); assert.equal(ack.source,'self_reported');
182 assert.equal(ack.unitId,unit.id); assert.equal(ack.status,'in_progress'); assert.equal(ack.version,1);
183 const independent = (await api('GET','/v1/me/learning-progress',undefined,token)).json.progress;
184 assert.equal(independent.length,1); assert.equal(independent[0].status,'in_progress');
185 const stored = dbJson(`select json_build_object('count',count(*),'status',max(status),'source',max(source),'version',max(version)) from learning_progress where owner_user_id='${owner}' and unit_id='${unit.id}';`);
186 assert.deepEqual(stored,{count:1,status:'in_progress',source:'self_reported',version:1});
187 await page.waitForLoadState('networkidle');
188 await fs.mkdir(path.dirname(receiptFile),{recursive:true});
189 await page.screenshot({path:receiptFile.replace(/\.json$/, '-progress.png'),fullPage:false});
190 check('UI progress acknowledgement independently verified through API and PostgreSQL');
191
192 stage = 'quizGate';
193 const quizResponse = page.waitForResponse(response => response.url().endsWith(`/api/v1/education/units/${unit.id}/assessment`));
194 await click(page.getByRole('button',{name:'تمرین فهم درس و مرور',exact:true}));
195 const quiz = await quizResponse; assert.equal(quiz.status(),200);
196 assert.deepEqual(await quiz.json(),{assessment:null,reason:'review_pending'});
197 await bodyIncludes(page,'آزمون این درس در انتظار بازبینی است');
198 check('real draft assessment gate shows no invented question bank');
199 await click(page.getByRole('button',{name:'برگشتن',exact:true}));
200
201 stage = 'feedback';
202 await click(page.getByRole('button',{name:'گزارش ایراد این درس',exact:true}));
203 const syntheticSummary = 'SYNTHETIC_BROWSER_FEEDBACK_NO_PERSONAL_DATA';
204 const summaryInput = page.getByLabel('خلاصه ایراد یا پیشنهاد',{exact:true});
205 await summaryInput.pressSequentially(syntheticSummary,{delay:5});
206 await summaryInput.press('Tab');
207 const postsBefore = paths.filter(item => item.path === '/api/v1/education/feedback' && item.method === 'POST').length;
208 await click(page.getByRole('button',{name:'ارسال بازخورد',exact:true}));
209 await bodyIncludes(page,'خلاصه و رضایت ارسال را تکمیل کن.');
210 assert.equal(paths.filter(item => item.path === '/api/v1/education/feedback' && item.method === 'POST').length,postsBefore);
211 await click(page.getByRole('checkbox'));
212 const feedbackResponse = page.waitForResponse(response => response.url().endsWith('/api/v1/education/feedback') && response.request().method() === 'POST');
213 await click(page.getByRole('button',{name:'ارسال بازخورد',exact:true}));
214 const sent = await feedbackResponse; assert.equal(sent.status(),201);
215 const feedback = (await sent.json()).feedback; assert(uuid.test(feedback.id));
216 await bodyIncludes(page,'بازخورد در سرور ثبت شد');
217 assert.equal((await api('GET','/v1/me/education-feedback',undefined,token)).json.feedback[0].summary,syntheticSummary);
218 check('feedback blocked without explicit consent then acknowledged by real server');
219 const withdrawnResponse = page.waitForResponse(response => response.url().endsWith(`/api/v1/me/education-feedback/${feedback.id}`) && response.request().method() === 'DELETE');
220 await click(page.getByRole('button',{name:'پس‌گرفتن رضایت',exact:true}));
221 assert.equal((await withdrawnResponse).status(),204);
222 await bodyIncludes(page,'رضایت ارسال پس گرفته شد');
223 const withdrawn = (await api('GET','/v1/me/education-feedback',undefined,token)).json.feedback[0];
224 assert.equal(withdrawn.summary,null); assert.equal(withdrawn.shareWithContentTeam,false); assert(withdrawn.withdrawnAt);
225 const redacted = dbJson(`select json_build_object('count',count(*),'summaryRedacted',bool_and(summary is null),'consentWithdrawn',bool_and(not share_with_content_team),'withdrawn',bool_and(withdrawn_at is not null)) from learning_content_feedback where owner_user_id='${owner}' and id='${feedback.id}';`);
226 assert.deepEqual(redacted,{count:1,summaryRedacted:true,consentWithdrawn:true,withdrawn:true});
227 check('withdrawal redacts chosen text and consent in independent API and PostgreSQL');
228
229 stage = 'restart';
230 await page.goto('about:blank'); await context.close(); context = null;
231 context = await launch(); page = await boot(context);
232 await school(page); await lesson(page,course,unit);
233 await page.waitForLoadState('networkidle');
234 assert(auth.some(item => item.path === '/api/v1/auth/refresh' && item.status === 200));
235 const afterRestart = (await api('GET','/v1/me/learning-progress',undefined,token)).json.progress;
236 assert.equal(afterRestart.length,1); assert.equal(afterRestart[0].version,1);
237 assert.equal(await page.locator('iframe').count(),0);
238 check('closed and reopened Chromium refreshes persisted session; independent API retains one acknowledged progress record');
239
240 stage = 'networkAudit';
241 assert.equal(paths.filter(item => item.origin !== origin).length,0);
242 assert.equal(errors.length,0); assert.equal(failures.length,0);
243 assert(paths.some(item => item.path.includes('/canvaskit/') && item.path.endsWith('.wasm')));
244 for (const font of ['LifeGuidePersian.ttf','LifeGuideLatin.ttf','LifeGuideEmoji.ttf'])
245 assert(paths.some(item => item.path.endsWith(font)));
246 check('real compiled runtime uses only local API, fonts and CanvasKit without errors');
247 await fs.mkdir(path.dirname(receiptFile),{recursive:true});
248 await page.screenshot({path:screenshotFile,fullPage:false});
249 const receipt = {date:new Date().toISOString(),mode:'Actual isolated local Compose HTTPS; normal Node and Chromium CA trust; no network interception or TLS bypass',
250 origin,browser:'Chromium',checks,fixture:'Dedicated synthetic account; no real family/private/media data',
251 counts:{requests:paths.length,externalRequests:0,iframes:0,browserErrors:0,failedRequests:0},
252 realApprovedVideoCount:0,realApprovedQuestionBankCount:0,
253 visualEvidence:{progressScreenshot:path.basename(receiptFile.replace(/\.json$/, '-progress.png')),
254 reopenedLessonScreenshot:path.basename(screenshotFile),
255 automatedDynamicProgressSemantics:'UNVERIFIED: dynamic progress/timestamp text was absent from Chromium ARIA after updates; inspect rendered screenshots separately'},
256 interactionMode:'Rendered Flutter semantic controls activated with DOM element.click because RTL hit rectangles are transformed; text entered through rendered fields and keyboard. No API or state injection. Physical touch/pointer/accessibility acceptance is UNVERIFIED.',
257 authResponses:auth,fonts:[...new Set(paths.filter(item => /\.(ttf|otf|woff2)$/.test(item.path)).map(item => item.path))],
258 limitations:['Real Android devices UNVERIFIED','Safari/Add to Home Screen UNVERIFIED','Video playback and teaching quality UNVERIFIED','Iran VPN-free reachability UNVERIFIED','Offline cold startup UNVERIFIED','Dynamic progress accessibility semantics after updates remain unverified; screenshots require separate visual review']};
259 await fs.writeFile(receiptFile,JSON.stringify(receipt,null,2)+'\n');
260 console.log(JSON.stringify(receipt,null,2));
261 } catch (error) {
262 if (process.env.LEARNING_BROWSER_DIAGNOSTICS && context && stage !== 'realLogin') {
263 const page = context.pages()[0];
264 const file = path.resolve(process.env.LEARNING_BROWSER_DIAGNOSTICS);
265 assert(!file.startsWith(root + path.sep), 'Private diagnostics must stay outside the repo.');
266 if (page) await fs.writeFile(file,(await page.locator('body').ariaSnapshot())
267 .replaceAll(email,'[synthetic fixture]').replaceAll(password,'[redacted]'),{mode:0o600});
268 if (page) await page.screenshot({path:file + '.png',fullPage:false});
269 }
270 console.error(`FAIL ${stage}: ${error.message.replaceAll(email,'[synthetic fixture]').replaceAll(password,'[redacted]')}`);
271 throw new Error(`Local learning browser acceptance failed at ${stage}`);
272 } finally {
273 if(context) { for(const page of context.pages()) await page.goto('about:blank').catch(()=>{}); await context.close(); }
274 await fs.rm(profile,{recursive:true,force:true});
275 }
276 })().catch(error => {console.error(error.message);process.exitCode=1;});