LifeMate — Personal, Family & Learning Companion

feat/flutter-mobile-navigation
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 112 lines 8.28 KB
Raw
1 // Compiled Flutter + real local API/PostgreSQL acceptance substitute.
2 // Test fixture only. Never prints credentials, tokens, or request bodies.
3 const assert = require('node:assert/strict');
4 const fs = require('node:fs');
5 const path = require('node:path');
6 const https = require('node:https');
7 const {chromium} = require('playwright');
8 const {Client} = require('../../../backend/node_modules/pg');
9 const origin = 'https://127.0.0.1:8447';
10 const fixture = JSON.parse(fs.readFileSync(process.env.LG_NAVIGATION_FIXTURE, 'utf8'));
11 assert(fixture.syntheticOnly && fixture.email.endsWith('@example.test'));
12 const database = new URL(process.env.LG_NAVIGATION_DATABASE_URL);
13 assert(database.hostname === '127.0.0.1' && database.port === '55439' &&
14 database.pathname.startsWith('/lifeguide_navigation_'), 'Only the isolated local fixture DB is allowed.');
15 const out = path.resolve(process.argv[2] || '/tmp/lifeguide-navigation-browser-evidence');
16 fs.mkdirSync(out, {recursive:true});
17 const ca = fs.readFileSync(process.env.LG_TEST_CA_FILE);
18 const db = new Client({connectionString:database.href});
19 const checks = [], errors = [], origins = new Set();
20 let browser, currentPage, stage = 'startup';
21 const record = name => { checks.push({name,result:'PASS'}); console.log('PASS ' + name); };
22 function api(method, endpoint, body, token) {
23 return new Promise((resolve,reject)=>{
24 const serialized = body === undefined ? null : Buffer.from(JSON.stringify(body));
25 const req = https.request(origin + '/api' + endpoint, {method,ca,rejectUnauthorized:true,
26 headers:{...(serialized ? {'content-type':'application/json','content-length':serialized.length}:{}),
27 ...(token ? {authorization:'Bearer '+token}:{})}},res=>{
28 assert(res.socket.authorized);let data='';
29 res.on('data',chunk=>data+=chunk);res.on('end',()=>{
30 try {resolve({status:res.statusCode,body:JSON.parse(data)});}catch{reject(Error('Non-JSON API response'));}
31 });
32 });req.setTimeout(15000,()=>req.destroy(Error('API timeout')));req.on('error',reject);req.end(serialized);
33 });
34 }
35 async function click(locator) {
36 await locator.waitFor({state:'attached',timeout:20000});
37 // Flutter RTL semantics activation; widget tests separately check hit targets.
38 await locator.evaluate(e=>e.click());
39 }
40 async function text(page, value) {
41 await page.waitForFunction(v=>document.body.textContent.includes(v) ||
42 [...document.querySelectorAll('[aria-label]')].some(e=>e.getAttribute('aria-label').includes(v)),value,{timeout:20000});
43 }
44 (async()=>{
45 await db.connect();
46 const login = await api('POST','/v1/auth/login',{email:fixture.email,password:fixture.password});
47 assert.equal(login.status,200);const token = login.body.accessToken;
48 assert.equal(typeof token,'string');
49 browser=await chromium.launch({executablePath:process.env.LIFEGUIDE_TEST_CHROMIUM_PATH || '/usr/bin/chromium',args:['--no-sandbox']});
50 const context=await browser.newContext({viewport:{width:390,height:844},ignoreHTTPSErrors:false});
51 const page=await context.newPage();currentPage=page;
52 page.on('pageerror',()=>errors.push('JavaScript page error'));
53 page.on('request',r=>{const u=new URL(r.url());if(/^https?:/.test(u.protocol))origins.add(u.origin);});
54 const boot=async()=>{
55 const res=await page.goto(origin,{waitUntil:'networkidle',timeout:60000});assert.equal(res.status(),200);
56 await page.waitForFunction(()=>!document.getElementById('startup-status'),null,{timeout:60000});
57 const sem=page.locator('flt-semantics-placeholder');if(await sem.count())await sem.evaluate(e=>e.click());
58 };
59 const btn=name=>page.getByRole('button',{name,exact:typeof name==='string'});
60 stage='login';await boot();
61 await page.getByLabel('ایمیل یا شماره تلفن',{exact:true}).fill(fixture.email);
62 await page.getByLabel('رمز عبور',{exact:true}).fill(fixture.password);
63 await click(btn('ورود'));
64 await btn(/برنامه من/).waitFor({timeout:30000});
65 await page.screenshot({path:path.join(out,'LifeGuide-Flutter-home.png')});
66 record('HTTPS login and approved compact Flutter home');
67 stage='create';await click(btn(/برنامه من/));await click(btn('جدید'));
68 await page.getByLabel('عنوان',{exact:true}).waitFor({state:'attached'});
69 const title='تکلیف ساختگی ناوبری '+Date.now().toString(36);
70 await page.getByLabel('عنوان',{exact:true}).fill(title);
71 await click(btn(/^نوع/));await click(page.getByRole('menuitem',{name:'تکلیف',exact:true}));
72 await click(btn('ذخیره'));await text(page,title);
73 let rows=await db.query('select id,kind,status,version from plan_item where owner_user_id=$1 and title=$2',[fixture.userId,title]);
74 assert.equal(rows.rowCount,1);assert.equal(rows.rows[0].kind,'assignment');const id=rows.rows[0].id;
75 const read=await api('GET','/v1/plan-items/'+id,undefined,token);assert.equal(read.status,200);assert.equal(read.body.title,title);
76 record('UI homework create independently confirmed by API and PostgreSQL');
77 stage='restart';await page.reload({waitUntil:'networkidle'});
78 await page.waitForFunction(()=>!document.getElementById('startup-status'),null,{timeout:60000});
79 const semanticsAfterRestart=page.locator('flt-semantics-placeholder');
80 if(await semanticsAfterRestart.count())await semanticsAfterRestart.evaluate(e=>e.click());
81 await btn(/برنامه من/).waitFor({timeout:30000});await click(btn(/برنامه من/));await text(page,title);
82 record('page restart restores session and server-backed record');
83 stage='edit';await click(btn(new RegExp('^'+title)));await text(page,'جزئیات تکلیف');
84 await click(btn('ویرایش تکلیف'));await page.getByLabel('عنوان',{exact:true}).fill(title+' ویرایش');
85 await click(btn('ذخیره'));await text(page,title+' ویرایش');await text(page,'توسط سرور تأیید شد');
86 assert.equal((await api('GET','/v1/plan-items/'+id,undefined,token)).body.title,title+' ویرایش');
87 await page.screenshot({path:path.join(out,'LifeGuide-Flutter-task.png')});
88 record('selected detail edit persists with server acknowledgement');
89 stage='study';await click(btn('شروع مطالعه این تکلیف'));await click(btn('شروع مطالعه'));
90 await btn('مکث').waitFor({timeout:20000});await page.waitForTimeout(1200);await click(btn('مکث'));
91 await click(btn('ادامه'));await page.waitForTimeout(1200);await click(btn('پایان'));
92 await text(page,'جلسه پایان‌یافته');
93 await click(btn('برگشتن').last());await text(page,'جزئیات تکلیف');
94 await click(btn('انجام شد'));await text(page,'توسط سرور تأیید شد');
95 assert.equal((await api('GET','/v1/plan-items/'+id,undefined,token)).body.status,'completed');
96 const sessions=await db.query('select status,source,recorded_duration_seconds from study_session where plan_item_id=$1',[id]);
97 assert.equal(sessions.rowCount,1);assert.equal(sessions.rows[0].status,'completed');
98 record('real study start/pause/resume/stop then task completion uses refreshed version');
99 stage='archive';await click(btn('بایگانی'));await text(page,'بایگانی مورد');await click(btn('بایگانی').last());
100 await btn('جدید').waitFor({timeout:20000});
101 assert.equal((await api('GET','/v1/plan-items/'+id,undefined,token)).body.status,'cancelled');
102 assert.equal((await db.query('select status from plan_item where id=$1',[id])).rows[0].status,'cancelled');
103 record('confirmed archive persists in PostgreSQL');
104 assert.deepEqual(errors,[]);assert.deepEqual([...origins],[origin]);
105 fs.writeFileSync(path.join(out,'verification.json'),JSON.stringify({status:'VERIFIED_LOCAL_SYNTHETIC_ONLY',browser:await browser.version(),
106 tlsVerified:true,backend:'real local Node/PostgreSQL16; no intercepted API responses',checks,
107 javascriptErrors:errors,externalRuntimeOrigins:[...origins].filter(o=>o!==origin),
108 studySource:sessions.rows[0].source,recordedSeconds:sessions.rows[0].recorded_duration_seconds,
109 unverified:['physical Android/iPhone/Safari','production hosting/deployment','managed-child legacy planner access','real OTP/video/alarms','multi-parent acceptance']},null,2));
110 })().catch(async e=>{console.error('FAIL '+stage+': '+e.message);if(currentPage)await currentPage.screenshot({path:path.join(out,'failure-diagnostic.png')});process.exitCode=1;}).finally(async()=>{
111 if(browser)await browser.close();await db.end();
112 });