LifeMate — Personal, Family & Learning Companion
test/personal-notification-settings
chore/phase1-repository-cleanup
deploy/stable-web-apk
deployment-static
design/mobile-accessibility-v2
design/mobile-navigation-review
docs/child-education-access-decision
docs/offline-data-rescue-options
docs/owner-guide-and-delivery-plan
docs/phase1-policy-options
docs/public-review-live-2026-10-15
feat/aparat-learning-library
feat/child-device-safety
feat/child-identity-schema
feat/flutter-mobile-navigation
feat/learning-content-operations
feat/local-signing-preflight
feat/online-family-stage0
feat/personal-encrypted-recovery
feat/private-planner-series-api
feat/public-review-page
feat/standalone-weekly-planner
feat/weekly-planner-android
final-feature-1/iran-family-school
fix/auth-abuse-expiry-safety
fix/auth-expiry-after-lock
fix/backend-request-safety
fix/lifeguide-bootstrap-naming-ci
fix/lifeguide-pages-qa-base-preflight
fix/lifeguide-qa-pages-env-deployment
fix/local-task-persistence
fix/managed-child-session-boundary
fix/personal-jalali-dates
fix/personal-notification-controls
fix/personal-upgrade-delivery-guard
fix/sms-approval-gates
fix/study-duration-display
infra/cloudflare-neon-migration
infra/lifeguide-cloudflare-qa
infra/lifeguide-github-pages-qa
infra/lifeguide-supabase-qa
main
phase-1/foundation-completion
phase-2/product-foundation-identity
phase-3/planner-school-family-core
phase-4/ai-learning-wellbeing
phase-5/hardening-observability-release
test/android-reminder-acceptance
test/personal-notification-settings
test/personal-recovery-acceptance
test/role-entry-apk
| 1 | import test from 'node:test'; |
| 2 | import assert from 'node:assert/strict'; |
| 3 | import crypto from 'node:crypto'; |
| 4 | import net from 'node:net'; |
| 5 | import { spawn } from 'node:child_process'; |
| 6 | import { once } from 'node:events'; |
| 7 | import path from 'node:path'; |
| 8 | import { fileURLToPath } from 'node:url'; |
| 9 | import pg from 'pg'; |
| 10 | |
| 11 | // Real API/DB acceptance substitutes. These do not claim Flutter rendering, |
| 12 | // Android lifecycle, iPhone/Safari installation or reachability from Iran. |
| 13 | const databaseUrl = process.env.DATABASE_URL; |
| 14 | assert.ok(databaseUrl, 'Configure a separate synthetic PostgreSQL database'); |
| 15 | const pool = new pg.Pool({ connectionString: databaseUrl }); |
| 16 | const backendDir = path.dirname(path.dirname(fileURLToPath(import.meta.url))); |
| 17 | const secret = 'synthetic-online-acceptance-secret-32-characters'; |
| 18 | const uuid = () => crypto.randomUUID(); |
| 19 | const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); |
| 20 | const iso = (ms) => new Date(ms).toISOString(); |
| 21 | let apiProcess, base, port, output = ''; |
| 22 | |
| 23 | async function startApi() { |
| 24 | const reservation = net.createServer(); |
| 25 | await new Promise((resolve, reject) => { reservation.once('error', reject); reservation.listen(0, '127.0.0.1', resolve); }); |
| 26 | port = reservation.address().port; |
| 27 | await new Promise((resolve) => reservation.close(resolve)); |
| 28 | base = `http://127.0.0.1:${port}`; |
| 29 | output = ''; |
| 30 | apiProcess = spawn(process.execPath, ['src/entrypoint.js'], { |
| 31 | cwd: backendDir, |
| 32 | env: { ...process.env, NODE_ENV: 'test', DATABASE_URL: databaseUrl, JWT_SECRET: secret, PORT: String(port), |
| 33 | RATE_LIMIT_GENERAL_MAX: '2000', RATE_LIMIT_AUTH_MAX: '2000', ENABLE_SENSITIVE_FEATURES: 'false', |
| 34 | EMAIL_FROM: '', SMTP_HOST: '', SMTP_PORT: '', RESEND_API_KEY: '', |
| 35 | SMS_PROVIDER: 'disabled', SMS_PROVIDER_URL: '', SMS_PROVIDER_TOKEN: '', AI_API_KEY: '', AI_BASE_URL: '', AI_MODEL: '' }, |
| 36 | stdio: ['ignore', 'pipe', 'pipe'], |
| 37 | }); |
| 38 | apiProcess.stdout.on('data', (chunk) => { output += chunk.toString(); }); |
| 39 | apiProcess.stderr.on('data', (chunk) => { output += chunk.toString(); }); |
| 40 | for (let attempt = 0; attempt < 100; attempt++) { |
| 41 | if (apiProcess.exitCode !== null) throw new Error(`Synthetic API failed to start: ${output}`); |
| 42 | try { |
| 43 | const ready = await fetch(`${base}/ready`, { signal: AbortSignal.timeout(500) }); |
| 44 | if (ready.status === 200) return; |
| 45 | } catch { /* Poll only the loopback test process. */ } |
| 46 | await sleep(50); |
| 47 | } |
| 48 | throw new Error('Synthetic API readiness timed out'); |
| 49 | } |
| 50 | async function stopApi() { |
| 51 | if (!apiProcess || apiProcess.exitCode !== null) return; |
| 52 | const current = apiProcess; |
| 53 | const exited = once(current, 'exit'); |
| 54 | current.kill('SIGTERM'); |
| 55 | const killer = setTimeout(() => current.kill('SIGKILL'), 3000); |
| 56 | await exited; |
| 57 | clearTimeout(killer); |
| 58 | apiProcess = null; |
| 59 | } |
| 60 | async function request(route, { method = 'GET', body, actor, token = actor?.accessToken } = {}) { |
| 61 | const response = await fetch(base + route, { method, headers: { 'content-type': 'application/json', ...(token ? { authorization: `Bearer ${token}` } : {}) }, |
| 62 | body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(5000) }); |
| 63 | const raw = await response.text(); |
| 64 | return { status: response.status, body: raw ? JSON.parse(raw) : null }; |
| 65 | } |
| 66 | async function register(displayName) { |
| 67 | const email = `acceptance-${uuid()}@example.test`, password = 'SyntheticOnlinePass!123'; |
| 68 | const created = await request('/v1/auth/register', { method: 'POST', body: { displayName, email, password } }); |
| 69 | // Test-only delivery hook provides proof tokens. Real email/SMS delivery is |
| 70 | // deliberately unconfigured and remains UNVERIFIED by this acceptance test. |
| 71 | assert.equal(created.status, 201); |
| 72 | assert.equal((await request('/v1/auth/verify-email', { method: 'POST', body: { token: created.body.verificationToken, newPassword: password } })).status, 204); |
| 73 | const login = await request('/v1/auth/login', { method: 'POST', body: { email, password } }); |
| 74 | assert.equal(login.status, 200); |
| 75 | const profile = await request('/v1/profile', { token: login.body.accessToken }); |
| 76 | assert.equal(profile.status, 200); |
| 77 | return { id: profile.body.user_id, email, ...login.body }; |
| 78 | } |
| 79 | async function refresh(actor) { |
| 80 | const previous = actor.refreshToken; |
| 81 | const response = await request('/v1/auth/refresh', { method: 'POST', body: { refreshToken: previous } }); |
| 82 | assert.equal(response.status, 200); |
| 83 | assert.notEqual(response.body.refreshToken, previous); |
| 84 | Object.assign(actor, response.body); |
| 85 | } |
| 86 | async function invite(mother, member, familyId, role) { |
| 87 | const invitation = await request(`/v1/families/${familyId}/invitations`, { method: 'POST', actor: mother, body: { email: member.email, role } }); |
| 88 | assert.equal(invitation.status, 201); |
| 89 | assert.equal((await request('/v1/invitations/accept', { method: 'POST', actor: member, body: { token: invitation.body.invitationToken } })).status, 204); |
| 90 | } |
| 91 | const reportRoute = (familyId, childId) => `/v1/families/${familyId}/children/${childId}/learning-report`; |
| 92 | async function sync(actor, mutation) { |
| 93 | return request('/v1/sync/mutations', { method: 'POST', actor, body: { mutations: [mutation] } }); |
| 94 | } |
| 95 | |
| 96 | test('online eight-step family scenario: real entrypoint, independent HTTP clients and PostgreSQL; device/Safari UNVERIFIED', async (t) => { |
| 97 | try { |
| 98 | await startApi(); |
| 99 | const [child, mother, father, outsider] = await Promise.all(['فرزند آزمایشی', 'مادر آزمایشی', 'پدر آزمایشی', 'خانواده دیگر آزمایشی'].map(register)); |
| 100 | const createdFamily = await request('/v1/families', { method: 'POST', actor: mother, body: { name: 'خانواده مصنوعی پذیرش', role: 'parent_guardian' } }); |
| 101 | assert.equal(createdFamily.status, 201); |
| 102 | const familyId = createdFamily.body.id; |
| 103 | await invite(mother, child, familyId, 'teen_minor'); |
| 104 | await invite(mother, father, familyId, 'parent_guardian'); |
| 105 | for (const parent of [mother, father]) assert.equal((await request(`/v1/families/${familyId}/guardians`, { |
| 106 | method: 'POST', actor: mother, body: { guardianUserId: parent.id, minorUserId: child.id }, |
| 107 | })).status, 204); |
| 108 | const otherFamily = await request('/v1/families', { method: 'POST', actor: outsider, body: { name: 'خانواده مستقل مصنوعی', role: 'parent_guardian' } }); |
| 109 | assert.equal(otherFamily.status, 201); |
| 110 | const taskId = uuid(), createBody = { id: uuid(), entityType: 'plan_item', entityId: taskId, operation: 'create', expectedVersion: 0, payload: { |
| 111 | kind: 'assignment', title: 'تمرین ریاضی — فقط داده آزمایشی', notes: 'OWNER-PRIVATE-ACCEPTANCE-NOTE', |
| 112 | familyId, visibility: 'parent_guardian', plannedDurationSeconds: 1800, dueAt: iso(Date.now() + 3600000), |
| 113 | } }; |
| 114 | const reportPath = reportRoute(familyId, child.id); |
| 115 | |
| 116 | await t.test('A / step 1: child homework creation independently verified by API and PostgreSQL', async () => { |
| 117 | const created = await sync(child, createBody); |
| 118 | assert.equal(created.status, 200); |
| 119 | assert.equal(created.body.results[0].status, 'accepted'); |
| 120 | assert.equal(created.body.results[0].item.id, taskId); |
| 121 | const independentRead = await request(`/v1/plan-items/${taskId}`, { actor: child }); |
| 122 | assert.equal(independentRead.status, 200); |
| 123 | assert.equal(independentRead.body.notes, 'OWNER-PRIVATE-ACCEPTANCE-NOTE'); |
| 124 | const database = await pool.query('select id,owner_user_id,title,version from plan_item where id=$1', [taskId]); |
| 125 | assert.equal(database.rowCount, 1); |
| 126 | assert.equal(database.rows[0].owner_user_id, child.id); |
| 127 | assert.equal(Number(database.rows[0].version), 1); |
| 128 | }); |
| 129 | await t.test('B / step 2: mother receives permitted report with freshness; PWA rendering UNVERIFIED', async () => { |
| 130 | const report = await request(reportPath, { actor: mother }); |
| 131 | assert.equal(report.status, 200); |
| 132 | assert.ok(report.body.items.some((item) => item.id === taskId)); |
| 133 | assert.ok(Number.isFinite(Date.parse(report.body.asOf))); |
| 134 | assert.ok(Number.isFinite(Date.parse(report.body.lastSyncAt))); |
| 135 | assert.ok(report.body.sourceVersion); |
| 136 | assert.ok(!JSON.stringify(report.body).includes('OWNER-PRIVATE-ACCEPTANCE-NOTE')); |
| 137 | }); |
| 138 | const t0 = Date.now() - 3600000, startBody = { id: uuid(), mutationId: uuid(), planItemId: taskId, source: 'timer', startedAt: iso(t0) }; |
| 139 | let session; |
| 140 | await t.test('G / steps 3–4: timer pause survives full API process restart, resumes and stops without double counting', async () => { |
| 141 | const started = await request('/v1/study/sessions', { method: 'POST', actor: child, body: startBody }); |
| 142 | assert.equal(started.status, 201); session = started.body.session; |
| 143 | const overlap = await request('/v1/study/sessions', { method: 'POST', actor: child, body: { ...startBody, id: uuid(), mutationId: uuid(), startedAt: iso(t0 + 1000) } }); |
| 144 | assert.equal(overlap.status, 409); assert.equal(overlap.body.error, 'study_time_overlap'); |
| 145 | const paused = await request(`/v1/study/sessions/${session.id}/events`, { method: 'POST', actor: child, |
| 146 | body: { mutationId: uuid(), expectedVersion: session.version, action: 'pause', occurredAt: iso(t0 + 5 * 60000) } }); |
| 147 | assert.equal(paused.status, 200); session = paused.body.session; |
| 148 | await stopApi(); await startApi(); |
| 149 | for (const actor of [child, mother, father]) await refresh(actor); |
| 150 | const restored = await request(`/v1/study/sessions/${session.id}`, { actor: child }); |
| 151 | assert.equal(restored.status, 200); assert.equal(restored.body.session.status, 'paused'); |
| 152 | assert.equal(restored.body.session.recordedDurationSeconds, 300); |
| 153 | const resumed = await request(`/v1/study/sessions/${session.id}/events`, { method: 'POST', actor: child, |
| 154 | body: { mutationId: uuid(), expectedVersion: restored.body.session.version, action: 'resume', occurredAt: iso(t0 + 15 * 60000) } }); |
| 155 | assert.equal(resumed.status, 200); |
| 156 | const stopBody = { mutationId: uuid(), expectedVersion: resumed.body.session.version, action: 'stop', occurredAt: iso(t0 + 35 * 60000) }; |
| 157 | const stopped = await request(`/v1/study/sessions/${session.id}/events`, { method: 'POST', actor: child, body: stopBody }); |
| 158 | assert.equal(stopped.status, 200); session = stopped.body.session; |
| 159 | assert.equal(session.recordedDurationSeconds, 1500); assert.equal(session.isEvidenceOfStudy, false); |
| 160 | const replay = await request(`/v1/study/sessions/${session.id}/events`, { method: 'POST', actor: child, body: stopBody }); |
| 161 | assert.equal(replay.body.acknowledgement.status, 'already_applied'); |
| 162 | assert.equal(replay.body.session.recordedDurationSeconds, 1500); |
| 163 | const durations = await pool.query('select count(*)::int n,sum(extract(epoch from ends_at-starts_at))::int seconds from study_interval where session_id=$1', [session.id]); |
| 164 | assert.deepEqual(durations.rows[0], { n: 2, seconds: 1500 }); |
| 165 | t.diagnostic('G substitute: actual Node API process restart and timer HTTP replay; Flutter timer app exit/re-sync remains UNVERIFIED.'); |
| 166 | }); |
| 167 | await t.test('step 5: recorded duration appears only in permitted parent report and is not proof of study', async () => { |
| 168 | const report = await request(reportPath, { actor: mother }); |
| 169 | assert.equal(report.status, 200); |
| 170 | assert.equal(report.body.items.find((item) => item.id === taskId).recordedDurationSeconds, 1500); |
| 171 | assert.equal(report.body.items.find((item) => item.id === taskId).plannedDurationSeconds, 1800); |
| 172 | assert.equal(report.body.isEvidenceOfStudy, false); |
| 173 | assert.equal(report.body.recordingDisclaimerKey, 'recorded_time_is_not_proof_of_study'); |
| 174 | }); |
| 175 | await t.test('C / steps 6–7: child completion is observed by father through an independent authenticated API poll', async () => { |
| 176 | const current = await request(`/v1/plan-items/${taskId}`, { actor: child }); |
| 177 | const complete = await sync(child, { id: uuid(), entityType: 'plan_item', entityId: taskId, operation: 'complete', expectedVersion: Number(current.body.version), payload: {} }); |
| 178 | assert.equal(complete.body.results[0].status, 'accepted'); |
| 179 | const fatherReport = await request(reportPath, { actor: father }); |
| 180 | const task = fatherReport.body.items.find((item) => item.id === taskId); |
| 181 | assert.equal(task.status, 'completed'); assert.equal(task.activityState, 'completed'); |
| 182 | assert.equal(task.activitySource, 'self_reported'); |
| 183 | assert.equal(task.recordedDurationSeconds, 1500); |
| 184 | }); |
| 185 | await t.test('D / step 8: API process restart preserves all three accounts, refresh sessions and shared PostgreSQL records', async () => { |
| 186 | await stopApi(); await startApi(); |
| 187 | for (const actor of [child, mother, father]) { |
| 188 | await refresh(actor); |
| 189 | assert.equal((await request('/v1/profile', { actor })).status, 200); |
| 190 | const read = await request(`/v1/plan-items/${taskId}`, { actor }); |
| 191 | assert.equal(read.status, 200); assert.equal(read.body.status, 'completed'); |
| 192 | } |
| 193 | assert.equal((await pool.query('select status,recorded_duration_seconds from study_session where id=$1', [session.id])).rows[0].recorded_duration_seconds, 1500); |
| 194 | t.diagnostic('D substitute: actual API process restart and DB-backed refresh. Closing/reopening Android and installed iPhone PWA remains UNVERIFIED.'); |
| 195 | }); |
| 196 | await t.test('E: disconnected HTTP request stays queued and later identical replay creates exactly one durable task', async () => { |
| 197 | const offline = { id: uuid(), entityType: 'plan_item', entityId: uuid(), operation: 'create', expectedVersion: 0, payload: { |
| 198 | kind: 'assignment', title: 'تکلیف آفلاین مصنوعی', familyId, visibility: 'parent_guardian', plannedDurationSeconds: 600, |
| 199 | } }; |
| 200 | const retainedJournal = JSON.stringify(offline); |
| 201 | await stopApi(); |
| 202 | await assert.rejects(sync(child, JSON.parse(retainedJournal)), TypeError); |
| 203 | await startApi(); |
| 204 | const first = await sync(child, JSON.parse(retainedJournal)), second = await sync(child, JSON.parse(retainedJournal)); |
| 205 | assert.equal(first.body.results[0].status, 'accepted'); |
| 206 | assert.equal(second.body.results[0].status, 'already_applied'); |
| 207 | assert.deepEqual(second.body.results[0].item, first.body.results[0].item); |
| 208 | assert.equal((await pool.query('select count(*)::int n from plan_item where id=$1', [offline.entityId])).rows[0].n, 1); |
| 209 | t.diagnostic('E substitute: real HTTP disconnection and retained JSON mutation replay; Flutter persistent offline queue requires separate evidence, device offline acceptance UNVERIFIED.'); |
| 210 | }); |
| 211 | await t.test('F: other-family parent cannot read/write shared child data; private tasks/notes stay owner-only', async () => { |
| 212 | assert.equal((await request(reportPath, { actor: outsider })).status, 403); |
| 213 | assert.equal((await request(`/v1/plan-items/${taskId}`, { actor: outsider })).status, 404); |
| 214 | const current = await request(`/v1/plan-items/${taskId}`, { actor: child }); |
| 215 | assert.equal((await request(`/v1/plan-items/${taskId}`, { method: 'PATCH', actor: outsider, body: { title: 'Forbidden', expectedVersion: Number(current.body.version) } })).status, 403); |
| 216 | const privateTask = await request('/v1/plan-items', { method: 'POST', actor: child, body: { |
| 217 | kind: 'task', title: 'PRIVATE-TASK-ACCEPTANCE-TITLE', notes: 'PRIVATE-TASK-ACCEPTANCE-NOTE', visibility: 'private', |
| 218 | } }); |
| 219 | assert.equal(privateTask.status, 201); |
| 220 | for (const parent of [mother, father, outsider]) assert.equal((await request(`/v1/plan-items/${privateTask.body.id}`, { actor: parent })).status, 404); |
| 221 | for (const parent of [mother, father]) { |
| 222 | const calendar = await request(`/v1/families/${familyId}/calendar`, { actor: parent }); |
| 223 | const content = JSON.stringify(calendar.body); |
| 224 | assert.ok(!content.includes('OWNER-PRIVATE-ACCEPTANCE-NOTE')); |
| 225 | assert.ok(!content.includes('PRIVATE-TASK-ACCEPTANCE')); |
| 226 | } |
| 227 | assert.equal((await request(`/v1/study/sessions/${session.id}`, { actor: mother })).status, 404); |
| 228 | assert.equal((await request(`/v1/study/sessions/${session.id}`)).status, 401); |
| 229 | }); |
| 230 | t.diagnostic('H/Safari install, Android devices, PWA UI/session lifecycle, no-VPN Iran reachability, real SMS/email delivery: UNVERIFIED. Only synthetic data and loopback/local PostgreSQL were used.'); |
| 231 | } finally { await stopApi(); await pool.end(); } |
| 232 | }); |