LifeMate — Personal, Family & Learning Companion
infra/lifeguide-supabase-qa
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, { describe, before, after } from 'node:test'; |
| 2 | import assert from 'node:assert/strict'; |
| 3 | import crypto from 'node:crypto'; |
| 4 | import { spawn } from 'node:child_process'; |
| 5 | import { once } from 'node:events'; |
| 6 | import net from 'node:net'; |
| 7 | import pg from 'pg'; |
| 8 | import jwt from 'jsonwebtoken'; |
| 9 | import { normalizeFeedbackSubmission } from '../src/learning_feedback.js'; |
| 10 | |
| 11 | const uuid = () => crypto.randomUUID(); |
| 12 | const submission = (extra = {}) => ({ mutationId: uuid(), unitId: null, |
| 13 | category: 'topic_request', summary: 'Synthetic content feedback, no private data.', |
| 14 | shareWithContentTeam: true, ...extra }); |
| 15 | |
| 16 | test('feedback submission needs explicit consent and rejects private/owner attachments', () => { |
| 17 | for (const consent of [undefined, null, false, 'true', 1]) { |
| 18 | assert.equal(normalizeFeedbackSubmission(submission({ shareWithContentTeam: consent })), null); |
| 19 | } |
| 20 | for (const key of ['ownerUserId', 'childId', 'chat', 'conversationId', 'notes', 'health', 'status']) { |
| 21 | assert.equal(normalizeFeedbackSubmission(submission({ [key]: 'not accepted' })), null, key); |
| 22 | } |
| 23 | }); |
| 24 | |
| 25 | test('feedback summary is bounded plain text, with canonical owner-scoped UUID payload', () => { |
| 26 | const mutationId = uuid(), unitId = uuid(); |
| 27 | const valid = normalizeFeedbackSubmission(submission({ |
| 28 | mutationId: mutationId.toUpperCase(), unitId: unitId.toUpperCase(), summary: ' توضیح انتخابشده ' |
| 29 | })); |
| 30 | assert.equal(valid.mutationId, mutationId); |
| 31 | assert.equal(valid.unitId, unitId); |
| 32 | assert.equal(valid.summary, 'توضیح انتخابشده'); |
| 33 | assert.equal(valid.shareWithContentTeam, true); |
| 34 | assert.ok(normalizeFeedbackSubmission(submission({ summary: '🙂'.repeat(1000) }))); |
| 35 | for (const summary of ['', ' ', 123, null, 'a'.repeat(1001), '🙂'.repeat(1001), 'bad\u0000value']) { |
| 36 | assert.equal(normalizeFeedbackSubmission(submission({ summary })), null); |
| 37 | } |
| 38 | for (const body of [null, [], { ...submission(), mutationId: 'bad' }, |
| 39 | { ...submission(), unitId: 'bad' }, { ...submission(), category: 'diagnosis' }]) { |
| 40 | assert.equal(normalizeFeedbackSubmission(body), null); |
| 41 | } |
| 42 | }); |
| 43 | |
| 44 | describe('learning feedback authenticated real HTTP and synthetic PostgreSQL', { concurrency: false }, () => { |
| 45 | const serviceEnv = {...process.env}; delete serviceEnv.TEST_FIXTURE_DATABASE_URL; |
| 46 | let pool, child, base; |
| 47 | let output = '', errors = ''; |
| 48 | const users = [], families = []; |
| 49 | |
| 50 | async function start() { |
| 51 | const reservation = net.createServer().listen(0, '127.0.0.1'); |
| 52 | await once(reservation, 'listening'); |
| 53 | const port = reservation.address().port; |
| 54 | await new Promise(resolve => reservation.close(resolve)); |
| 55 | base = `http://127.0.0.1:${port}`; |
| 56 | let startup = ''; |
| 57 | child = spawn(process.execPath, ['src/entrypoint.js'], { |
| 58 | env: { ...serviceEnv, NODE_ENV: 'production', PORT: String(port), |
| 59 | SMS_PROVIDER: 'disabled', SMS_PROVIDER_URL: '', SMS_PROVIDER_TOKEN: '', |
| 60 | EMAIL_FROM: '', RESEND_API_KEY: '', SMTP_HOST: '', SMTP_USER: '', SMTP_PASSWORD: '', |
| 61 | AI_API_KEY: '', AI_BASE_URL: '', AI_MODEL: '', OPENAI_API_KEY: '', |
| 62 | CORS_ORIGINS: '', TRUSTED_PROXY_CIDRS: '', ENABLE_SENSITIVE_FEATURES: 'false', |
| 63 | RATE_LIMIT_AUTH_MAX: '2000', RATE_LIMIT_GENERAL_MAX: '8000', RATE_LIMIT_AI_MAX: '2000' }, |
| 64 | stdio: ['ignore', 'pipe', 'pipe'], |
| 65 | }); |
| 66 | child.stdout.on('data', chunk => { output += chunk.toString(); startup += chunk.toString(); }); |
| 67 | child.stderr.on('data', chunk => { errors += chunk.toString(); }); |
| 68 | await new Promise((resolve, reject) => { |
| 69 | const timer = setTimeout(() => reject(new Error('Feedback fixture startup timed out')), 10000); |
| 70 | const onData = () => { |
| 71 | if (!startup.includes('"type":"startup"')) return; |
| 72 | clearTimeout(timer); child.stdout.off('data', onData); resolve(); |
| 73 | }; |
| 74 | child.stdout.on('data', onData); |
| 75 | child.once('error', () => { clearTimeout(timer); reject(new Error('Feedback fixture start failed')); }); |
| 76 | child.once('exit', () => { |
| 77 | if (!startup.includes('"type":"startup"')) { |
| 78 | clearTimeout(timer); reject(new Error('Feedback fixture exited before startup')); |
| 79 | } |
| 80 | }); |
| 81 | }); |
| 82 | } |
| 83 | |
| 84 | async function stop() { |
| 85 | if (child && child.exitCode === null && child.signalCode === null) { |
| 86 | const closed = once(child, 'close'); child.kill('SIGTERM'); await closed; |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | before(async () => { |
| 91 | assert.ok(process.env.DATABASE_URL && process.env.JWT_SECRET?.length >= 32, |
| 92 | 'Feedback tests require a migrated synthetic PostgreSQL fixture and JWT secret'); |
| 93 | const location = new URL(process.env.TEST_FIXTURE_DATABASE_URL ?? process.env.DATABASE_URL); |
| 94 | assert.ok(['localhost', '127.0.0.1', '[::1]', '::1'].includes(location.hostname), |
| 95 | 'Feedback tests refuse a nonlocal database'); |
| 96 | // Keep the local-host gate above. The workflow's existing synthetic database |
| 97 | // has a protocol/history name; admitting that exact name does not admit arbitrary DBs. |
| 98 | assert.ok(location.pathname.includes('test') || location.pathname === '/lifemate_ci' || |
| 99 | /^\/lifeguide_roles_source_[a-f0-9]{16}$/.test(location.pathname), |
| 100 | 'Feedback tests require an explicit synthetic test database'); |
| 101 | pool = new pg.Pool({ connectionString: process.env.TEST_FIXTURE_DATABASE_URL ?? process.env.DATABASE_URL }); |
| 102 | await start(); |
| 103 | }); |
| 104 | |
| 105 | after(async () => { |
| 106 | await stop(); |
| 107 | if (!pool) return; |
| 108 | try { |
| 109 | await pool.query('delete from access_audit where family_id=any($1::uuid[]) or actor_user_id=any($2::uuid[])', [families, users]); |
| 110 | await pool.query('delete from family_workspace where id=any($1::uuid[])', [families]); |
| 111 | await pool.query('delete from app_user where id=any($1::uuid[])', [users]); |
| 112 | } finally { await pool.end(); } |
| 113 | }); |
| 114 | |
| 115 | async function actor() { |
| 116 | const id = uuid(), sid = uuid(); |
| 117 | users.push(id); |
| 118 | await pool.query('insert into app_user(id,identity_subject,email_normalized,email_verified_at) values($1,$2,$3,now())', |
| 119 | [id, `feedback-fixture:${id}`, `feedback-${id}@example.test`]); |
| 120 | await pool.query("insert into profile(user_id,display_name,theme_preference) values($1,'Synthetic Feedback User','adult_blue')", [id]); |
| 121 | await pool.query("insert into auth_session(id,user_id,refresh_digest,expires_at) values($1,$2,$3,now()+interval '1 day')", |
| 122 | [sid, id, crypto.randomBytes(32).toString('hex')]); |
| 123 | return { id, sid, token: jwt.sign({ sub: id, sid, aud: 'lifemate-api' }, process.env.JWT_SECRET, |
| 124 | { issuer: 'lifemate', expiresIn: '15m' }) }; |
| 125 | } |
| 126 | |
| 127 | async function request(path, { method = 'GET', user, body } = {}) { |
| 128 | const response = await fetch(base + path, { method, |
| 129 | headers: { 'content-type': 'application/json', ...(user ? { authorization: `Bearer ${user.token}` } : {}) }, |
| 130 | body: body === undefined ? undefined : JSON.stringify(body) }); |
| 131 | const text = await response.text(); |
| 132 | return { status: response.status, |
| 133 | body: text && response.headers.get('content-type')?.includes('application/json') ? JSON.parse(text) : text || null, |
| 134 | retryAfter: response.headers.get('retry-after') }; |
| 135 | } |
| 136 | const post = (user, body) => request('/v1/education/feedback', { method: 'POST', user, body }); |
| 137 | const list = (user, query = '') => request('/v1/me/education-feedback' + query, { user }); |
| 138 | |
| 139 | test('authentication, consent and strict request bounds reject without storing', async () => { |
| 140 | const user = await actor(); |
| 141 | assert.equal((await post(undefined, submission())).status, 401); |
| 142 | assert.equal((await list(undefined)).status, 401); |
| 143 | assert.equal((await request(`/v1/me/education-feedback/${uuid()}`, { method: 'DELETE' })).status, 401); |
| 144 | for (const body of [submission({ shareWithContentTeam: false }), submission({ summary: 'a'.repeat(1001) }), |
| 145 | submission({ summary: 'bad\u0000text' }), submission({ ownerUserId: user.id }), submission({ childId: user.id }), |
| 146 | submission({ chat: 'PRIVATE-CHAT-MUST-NOT-BE-ATTACHED' }), submission({ unitId: 'invalid' })]) { |
| 147 | assert.equal((await post(user, body)).status, 400); |
| 148 | } |
| 149 | assert.equal((await post(user, submission({ unitId: uuid() }))).status, 404); |
| 150 | assert.equal((await pool.query('select count(*)::int n from learning_content_feedback where owner_user_id=$1', [user.id])).rows[0].n, 0); |
| 151 | await pool.query('update auth_session set revoked_at=now() where id=$1', [user.sid]); |
| 152 | assert.equal((await post(user, submission())).status, 401); |
| 153 | }); |
| 154 | |
| 155 | test('real submission stores only chosen text and an existing draft unit can be referenced', async () => { |
| 156 | const user = await actor(); |
| 157 | const units = await pool.query('select id from learning_unit order by id limit 1'); |
| 158 | assert.equal(units.rowCount, 1, 'Library fixture must import a public catalogue unit'); |
| 159 | const body = submission({ unitId: units.rows[0].id, category: 'unclear', summary: '<b>SYNTHETIC-CHOSEN-FEEDBACK</b>' }); |
| 160 | const created = await post(user, body); |
| 161 | assert.equal(created.status, 201); |
| 162 | assert.equal(created.body.feedback.summary, body.summary); |
| 163 | assert.equal(created.body.feedback.unitId, body.unitId); |
| 164 | assert.equal(created.body.feedback.status, 'received'); |
| 165 | assert.equal(created.body.feedback.version, 1); |
| 166 | assert.deepEqual(created.body.acknowledgement, |
| 167 | { mutationId: body.mutationId, feedbackId: created.body.feedback.id, status: 'accepted' }); |
| 168 | const stored = (await pool.query('select * from learning_content_feedback where id=$1', [created.body.feedback.id])).rows[0]; |
| 169 | assert.equal(stored.owner_user_id, user.id); |
| 170 | assert.equal(stored.summary, body.summary); |
| 171 | assert.equal(stored.request_hash.length, 64); |
| 172 | const own = await list(user); |
| 173 | assert.equal(own.status, 200); |
| 174 | assert.equal(own.body.feedback.length, 1); |
| 175 | assert.equal(own.body.feedback[0].id, stored.id); |
| 176 | assert.ok(!JSON.stringify(own.body).includes(user.id)); |
| 177 | assert.ok(!JSON.stringify(own.body).includes('request_hash')); |
| 178 | }); |
| 179 | |
| 180 | test('concurrent stable mutations make one row; changed UUID reuse conflicts and another owner is isolated', async () => { |
| 181 | const user = await actor(), other = await actor(), body = submission(); |
| 182 | const results = await Promise.all([post(user, body), post(user, body), post(user, body)]); |
| 183 | assert.deepEqual(results.map(r => r.status).sort(), [200, 200, 201]); |
| 184 | assert.equal(new Set(results.map(r => r.body.feedback.id)).size, 1); |
| 185 | assert.equal((await post(user, { ...body, summary: 'Different chosen summary' })).status, 409); |
| 186 | assert.equal((await pool.query('select count(*)::int n from learning_content_feedback where owner_user_id=$1 and mutation_id=$2', [user.id, body.mutationId])).rows[0].n, 1); |
| 187 | const otherResult = await post(other, body); |
| 188 | assert.equal(otherResult.status, 201); |
| 189 | assert.notEqual(otherResult.body.feedback.id, results[0].body.feedback.id); |
| 190 | }); |
| 191 | |
| 192 | test('family admin/guardian and outsider cannot read or withdraw child feedback; private records never attach', async () => { |
| 193 | const minor = await actor(), parent = await actor(), outsider = await actor(); |
| 194 | const family = uuid(); families.push(family); |
| 195 | await pool.query("insert into family_workspace(id,name,created_by) values($1,'Synthetic Feedback Family',$2)", [family, parent.id]); |
| 196 | await pool.query("insert into family_membership(family_id,user_id,role,is_admin) values($1,$2,'parent_guardian',true),($1,$3,'teen_minor',false)", [family, parent.id, minor.id]); |
| 197 | await pool.query('insert into guardian_relationship(family_id,guardian_user_id,minor_user_id) values($1,$2,$3)', [family, parent.id, minor.id]); |
| 198 | await pool.query("insert into plan_item(owner_user_id,kind,title,notes) values($1,'task','Private synthetic task','PRIVATE-NOTE-FEEDBACK-SENTINEL')", [minor.id]); |
| 199 | await pool.query("insert into wellbeing_checkin(owner_user_id,mood,note) values($1,3,'PRIVATE-HEALTH-FEEDBACK-SENTINEL')", [minor.id]); |
| 200 | const conversation = (await pool.query("insert into ai_guide_session(owner_user_id,guide_kind) values($1,'study') returning id", [minor.id])).rows[0].id; |
| 201 | await pool.query("insert into ai_guide_message(session_id,author,body) values($1,'user','PRIVATE-CHAT-FEEDBACK-SENTINEL')", [conversation]); |
| 202 | const created = await post(minor, submission()); |
| 203 | assert.equal(created.status, 201); |
| 204 | for (const user of [parent, outsider]) { |
| 205 | assert.deepEqual((await list(user)).body.feedback, []); |
| 206 | assert.equal((await list(user, `?childId=${minor.id}`)).status, 400); |
| 207 | assert.equal((await list(user, `?ownerUserId=${minor.id}`)).status, 400); |
| 208 | assert.equal((await list(user, `?cursor=${created.body.feedback.id}`)).status, 404); |
| 209 | assert.equal((await request(`/v1/me/education-feedback/${created.body.feedback.id}`, { method: 'DELETE', user })).status, 404); |
| 210 | } |
| 211 | assert.equal((await request('/v1/education/feedback', { user: parent })).status, 404); |
| 212 | const visible = JSON.stringify((await list(minor)).body) + JSON.stringify(created.body); |
| 213 | for (const sentinel of ['PRIVATE-NOTE-FEEDBACK-SENTINEL', 'PRIVATE-HEALTH-FEEDBACK-SENTINEL', 'PRIVATE-CHAT-FEEDBACK-SENTINEL']) { |
| 214 | assert.ok(!visible.includes(sentinel)); |
| 215 | assert.ok(!output.includes(sentinel)); |
| 216 | assert.ok(!errors.includes(sentinel)); |
| 217 | } |
| 218 | }); |
| 219 | |
| 220 | test('withdrawal redacts the stored text; retries return tombstone and never restore consent', async () => { |
| 221 | const user = await actor(), body = submission({ summary: 'SYNTHETIC-TO-WITHDRAW' }); |
| 222 | const created = await post(user, body), id = created.body.feedback.id; |
| 223 | const original = (await pool.query('select request_hash from learning_content_feedback where id=$1', [id])).rows[0].request_hash; |
| 224 | const path = `/v1/me/education-feedback/${id}`; |
| 225 | assert.equal((await request(path, { method: 'DELETE', user })).status, 204); |
| 226 | assert.equal((await request(path, { method: 'DELETE', user })).status, 204); |
| 227 | const stored = (await pool.query('select * from learning_content_feedback where id=$1', [id])).rows[0]; |
| 228 | assert.equal(stored.summary, null); assert.equal(stored.share_with_content_team, false); |
| 229 | assert.ok(stored.withdrawn_at); assert.equal(stored.version, 2); assert.equal(stored.request_hash, original); |
| 230 | const replay = await post(user, body); |
| 231 | assert.equal(replay.status, 200); assert.equal(replay.body.feedback.id, id); |
| 232 | assert.equal(replay.body.feedback.summary, null); assert.equal(replay.body.feedback.shareWithContentTeam, false); |
| 233 | assert.equal(replay.body.acknowledgement.status, 'already_applied'); |
| 234 | assert.ok(!JSON.stringify(replay.body).includes(body.summary)); |
| 235 | assert.equal((await post(user, { ...body, summary: 'New summary with old UUID' })).status, 409); |
| 236 | assert.equal((await request(`/v1/me/education-feedback/${uuid()}`, { method: 'DELETE', user })).status, 404); |
| 237 | }); |
| 238 | |
| 239 | test('per-user hourly quota is atomic, survives process restart, and retries/withdrawal cannot bypass it', async () => { |
| 240 | const user = await actor(), other = await actor(); |
| 241 | const bodies = Array.from({ length: 6 }, () => submission()); |
| 242 | const created = await Promise.all(bodies.map(body => post(user, body))); |
| 243 | assert.equal(created.filter(r => r.status === 201).length, 5); |
| 244 | assert.equal(created.filter(r => r.status === 429).length, 1); |
| 245 | const limited = created.find(r => r.status === 429); |
| 246 | assert.ok(Number(limited.retryAfter) > 0 && Number(limited.retryAfter) <= 3600); |
| 247 | const index = created.findIndex(r => r.status === 201), original = created[index].body.feedback; |
| 248 | await stop(); await start(); |
| 249 | const replay = await post(user, bodies[index]); |
| 250 | assert.equal(replay.status, 200); assert.deepEqual(replay.body.feedback, original); |
| 251 | assert.equal((await post(user, submission())).status, 429); |
| 252 | assert.equal((await request(`/v1/me/education-feedback/${original.id}`, { method: 'DELETE', user })).status, 204); |
| 253 | assert.equal((await post(user, submission())).status, 429); |
| 254 | assert.equal((await post(other, submission())).status, 201); |
| 255 | assert.equal((await pool.query('select count(*)::int n from learning_content_feedback where owner_user_id=$1', [user.id])).rows[0].n, 5); |
| 256 | }); |
| 257 | |
| 258 | test('rolling daily quota uses persisted rows even when hourly windows have expired', async () => { |
| 259 | const user = await actor(); |
| 260 | for (let batch = 1; batch <= 4; batch++) { |
| 261 | const ids = []; |
| 262 | for (let n = 0; n < 5; n++) { |
| 263 | const made = await post(user, submission({ summary: `Synthetic daily feedback ${batch}-${n}` })); |
| 264 | assert.equal(made.status, 201); ids.push(made.body.feedback.id); |
| 265 | } |
| 266 | // Only synthetic fixture timestamps advance the window; no production clock override. |
| 267 | await pool.query("update learning_content_feedback set created_at=now()-($1 || ' hours')::interval where id=any($2::uuid[])", [String(batch * 2), ids]); |
| 268 | } |
| 269 | const limited = await post(user, submission()); |
| 270 | assert.equal(limited.status, 429); |
| 271 | assert.ok(Number(limited.retryAfter) > 3600 && Number(limited.retryAfter) <= 86400); |
| 272 | assert.equal((await pool.query('select count(*)::int n from learning_content_feedback where owner_user_id=$1', [user.id])).rows[0].n, 20); |
| 273 | }); |
| 274 | |
| 275 | test('cursor paging stays in caller scope, bounds rows and preserves microsecond page boundaries', async () => { |
| 276 | const user = await actor(); |
| 277 | const a = await post(user, submission()), b = await post(user, submission()); |
| 278 | assert.equal(a.status, 201); assert.equal(b.status, 201); |
| 279 | const first = await list(user); |
| 280 | assert.deepEqual(first.body.feedback.map(row => row.id), [b.body.feedback.id, a.body.feedback.id]); |
| 281 | const second = await list(user, `?cursor=${b.body.feedback.id}`); |
| 282 | assert.deepEqual(second.body.feedback.map(row => row.id), [a.body.feedback.id]); |
| 283 | assert.equal(second.body.nextCursor, null); |
| 284 | assert.equal((await list(user, '?cursor=bad')).status, 400); |
| 285 | assert.equal((await list(user, '?includePrivateChat=true')).status, 400); |
| 286 | // A bounded page must not round its cursor timestamp through JavaScript Date. |
| 287 | // These older, synthetic records all occupy different microseconds of one millisecond. |
| 288 | await pool.query( |
| 289 | `insert into learning_content_feedback(owner_user_id,mutation_id,request_hash,category,summary,share_with_content_team,created_at) |
| 290 | select $1,gen_random_uuid(),repeat('a',64),'topic_request','Synthetic pagination feedback',true, |
| 291 | timestamptz '2000-01-01 00:00:00+00'+n*interval '1 microsecond' |
| 292 | from generate_series(1,100) n`, [user.id]); |
| 293 | const bounded = await list(user); |
| 294 | assert.equal(bounded.body.feedback.length, 100); |
| 295 | assert.ok(bounded.body.nextCursor); |
| 296 | const tail = await list(user, `?cursor=${bounded.body.nextCursor}`); |
| 297 | assert.equal(tail.body.feedback.length, 2); |
| 298 | assert.equal(tail.body.nextCursor, null); |
| 299 | assert.equal(new Set([...bounded.body.feedback, ...tail.body.feedback].map(row => row.id)).size, 102); |
| 300 | }); |
| 301 | }); |