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
js 378 lines 18.9 KB
Raw
1 import test, { after, before } 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 http from 'node:http';
8 import jwt from 'jsonwebtoken';
9 import pg from 'pg';
10
11 // Real production entrypoint, HTTP, sessions and PostgreSQL; no skipped tests or mocks.
12 assert.ok(process.env.DATABASE_URL, 'DATABASE_URL is required for request safety tests');
13 assert.ok(process.env.JWT_SECRET?.length >= 32, 'JWT_SECRET must be configured for tests');
14 const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
15 const allowedOrigin = 'https://client.example.test';
16 const users = [];
17 let child;
18 let base;
19 let output = '';
20 let errors = '';
21
22 before(async () => {
23 const reservation = net.createServer();
24 reservation.listen(0, '127.0.0.1');
25 await once(reservation, 'listening');
26 const port = reservation.address().port;
27 await new Promise((resolve) => reservation.close(resolve));
28 base = `http://127.0.0.1:${port}`;
29 child = spawn(process.execPath, ['src/entrypoint.js'], {
30 cwd: new URL('..', import.meta.url),
31 env: {
32 ...process.env,
33 PORT: String(port),
34 NODE_ENV: 'production',
35 SMS_PROVIDER: 'disabled', SMS_PROVIDER_URL: '', SMS_PROVIDER_TOKEN: '',
36 EMAIL_FROM: '', RESEND_API_KEY: '', SMTP_HOST: '',
37 ENABLE_SENSITIVE_FEATURES: 'true', // Explicit synthetic cycle/error fixtures only.
38 CORS_ORIGINS: allowedOrigin,
39 RATE_LIMIT_AUTH_MAX: '2000',
40 RATE_LIMIT_GENERAL_MAX: '2000',
41 },
42 stdio: ['ignore', 'pipe', 'pipe'],
43 });
44 child.stdout.on('data', (chunk) => { output += chunk.toString(); });
45 child.stderr.on('data', (chunk) => { errors += chunk.toString(); });
46 await new Promise((resolve, reject) => {
47 const timer = setTimeout(() => reject(new Error('Production entrypoint startup timed out')), 10000);
48 const onData = () => {
49 if (!output.includes('"type":"startup"')) return;
50 clearTimeout(timer);
51 child.stdout.off('data', onData);
52 resolve();
53 };
54 child.stdout.on('data', onData);
55 child.once('error', (error) => { clearTimeout(timer); reject(error); });
56 child.once('exit', () => { clearTimeout(timer); reject(new Error('Production entrypoint exited before readiness')); });
57 });
58 assert.equal((await request('/ready')).status, 200);
59 });
60
61 after(async () => {
62 if (child && child.exitCode === null) {
63 const exited = once(child, 'exit');
64 child.kill('SIGTERM');
65 await exited;
66 }
67 if (users.length) await pool.query('delete from app_user where id=any($1::uuid[])', [users]);
68 await pool.end();
69 });
70
71 async function request(path, { method = 'GET', body, rawBody, token, origin = allowedOrigin, headers = {} } = {}) {
72 const response = await fetch(base + path, {
73 method,
74 headers: {
75 'content-type': 'application/json',
76 origin,
77 ...(token ? { authorization: `Bearer ${token}` } : {}),
78 ...headers,
79 },
80 body: rawBody ?? (body === undefined ? undefined : JSON.stringify(body)),
81 });
82 const text = await response.text();
83 return { status: response.status, body: text ? JSON.parse(text) : null, headers: response.headers };
84 }
85
86 async function fixture() {
87 const id = crypto.randomUUID();
88 const sessionId = crypto.randomUUID();
89 const refreshToken = crypto.randomBytes(32).toString('base64url');
90 await pool.query(
91 'insert into app_user(id,identity_subject,email_normalized,email_verified_at) values($1,$2,$3,now())',
92 [id, `request-safety:${id}`, `request-safety-${id}@example.test`],
93 );
94 users.push(id);
95 await pool.query("insert into profile(user_id,display_name,theme_preference) values($1,'Request Safety','adult_blue')", [id]);
96 await pool.query(
97 "insert into auth_session(id,user_id,refresh_digest,expires_at) values($1,$2,$3,now()+interval '1 day')",
98 [sessionId, id, crypto.createHash('sha256').update(refreshToken).digest('hex')],
99 );
100 const token = jwt.sign({ sub: id, sid: sessionId, aud: 'lifemate-api' }, process.env.JWT_SECRET, { expiresIn: '15m', issuer: 'lifemate' });
101 return { id, sessionId, token, refreshToken };
102 }
103
104 async function errorEvent(requestId, { errorProcess = child, readErrors = () => errors, eventType = 'http_error' } = {}) {
105 const find = () => readErrors().split('\n').flatMap((line) => {
106 try { return [JSON.parse(line)]; } catch { return []; }
107 }).find((event) => event.type === eventType && event.requestId === requestId);
108 if (find()) return find();
109 return new Promise((resolve, reject) => {
110 const cleanup = () => { clearTimeout(timer); errorProcess.stderr.off('data', onData); };
111 const onData = () => {
112 const event = find();
113 if (!event) return;
114 cleanup();
115 resolve(event);
116 };
117 const timer = setTimeout(() => { cleanup(); reject(new Error('Correlated sanitized error event was not emitted')); }, 2000);
118 errorProcess.stderr.on('data', onData);
119 });
120 }
121
122 test('importing the shared app in production does not leave a second listener open', async () => {
123 const imported = spawn(process.execPath, ['--input-type=module', '-e', 'const { pool } = await import("./src/server.js"); await pool.end();'], {
124 cwd: new URL('..', import.meta.url),
125 env: { ...process.env, NODE_ENV: 'production', SMS_PROVIDER: 'disabled', SMS_PROVIDER_URL: '', SMS_PROVIDER_TOKEN: '', PORT: '0' },
126 stdio: 'ignore',
127 });
128 let timedOut = false;
129 const timer = setTimeout(() => { timedOut = true; imported.kill('SIGKILL'); }, 5000);
130 const [code] = await once(imported, 'exit');
131 clearTimeout(timer);
132 assert.equal(timedOut, false, 'Import must not keep a network listener alive');
133 assert.equal(code, 0);
134 });
135
136 test('production Phase 6 PATCH persists Iran profile through the shared JSON pipeline', async () => {
137 const user = await fixture();
138 const changed = await request('/v1/me/iran-profile', {
139 method: 'PATCH', token: user.token, body: { householdPersona: 'adult', sex: 'unspecified', birthDate: '1990-01-02' },
140 });
141 assert.equal(changed.status, 204);
142 const read = await request('/v1/me/iran-profile', { token: user.token });
143 assert.equal(read.status, 200);
144 assert.equal(read.body.household_persona, 'adult');
145 assert.equal(read.body.birth_date.slice(0, 10), '1990-01-02');
146 assert.equal((await pool.query('select household_persona from profile where user_id=$1', [user.id])).rows[0].household_persona, 'adult');
147 });
148
149 test('production Phase 6 PUT persists education and reads it again', async () => {
150 const user = await fixture();
151 const write = await request('/v1/me/education', {
152 method: 'PUT', token: user.token, body: { nationalGrade: 7, schoolName: 'Synthetic School', schoolYear: '1405-1406' },
153 });
154 assert.equal(write.status, 200);
155 assert.equal(write.body.stage, 'secondary_1');
156 const read = await request('/v1/me/iran-profile', { token: user.token });
157 assert.equal(read.body.national_grade, 7);
158 assert.equal(read.body.school_name, 'Synthetic School');
159 });
160
161 test('production Phase 6 PATCH persists notification preferences', async () => {
162 const user = await fixture();
163 const changed = await request('/v1/me/notification-preferences', {
164 method: 'PATCH', token: user.token, body: { pushEnabled: false, plannerReminders: false },
165 });
166 assert.equal(changed.status, 200);
167 const read = await request('/v1/me/notification-preferences', { token: user.token });
168 assert.equal(read.body.push_enabled, false);
169 assert.equal(read.body.planner_reminders, false);
170 });
171
172 test('production Phase 6 POST/read/DELETE uses real owner-private storage', async () => {
173 const user = await fixture();
174 const other = await fixture();
175 const write = await request('/v1/me/menstrual-cycles', {
176 method: 'POST', token: user.token, body: { startsOn: '2026-10-01', endsOn: '2026-10-04', notes: 'Synthetic owner-private note' },
177 });
178 assert.equal(write.status, 201);
179 const read = await request('/v1/me/menstrual-cycles', { token: user.token });
180 assert.equal(read.body.entries[0].id, write.body.id);
181 assert.equal(read.body.entries[0].notes, 'Synthetic owner-private note');
182 assert.equal((await request('/v1/me/menstrual-cycles', { token: other.token })).body.entries.length, 0);
183 assert.equal((await request(`/v1/me/menstrual-cycles/${write.body.id}`, { method: 'DELETE', token: other.token })).status, 204);
184 assert.equal((await pool.query('select 1 from menstrual_cycle_entry where id=$1', [write.body.id])).rowCount, 1);
185 assert.equal((await request(`/v1/me/menstrual-cycles/${write.body.id}`, { method: 'DELETE', token: user.token })).status, 204);
186 assert.equal((await request('/v1/me/menstrual-cycles', { token: user.token })).body.entries.length, 0);
187 assert.equal((await pool.query('select 1 from menstrual_cycle_entry where id=$1', [write.body.id])).rowCount, 0);
188 });
189
190 test('production standard and Phase 6 responses share allowed-origin CORS', async () => {
191 const user = await fixture();
192 for (const path of ['/v1/profile', '/v1/me/iran-profile', '/v1/me/menstrual-cycles']) {
193 const response = await request(path, { token: user.token });
194 assert.equal(response.status, 200);
195 assert.equal(response.headers.get('access-control-allow-origin'), allowedOrigin);
196 }
197 });
198
199 test('production CORS preflight supports PATCH, PUT, POST and DELETE before authentication', async () => {
200 for (const [method, path] of [
201 ['PATCH', '/v1/me/iran-profile'], ['PUT', '/v1/me/education'],
202 ['POST', '/v1/me/menstrual-cycles'], ['DELETE', '/v1/me/menstrual-cycles/unused'],
203 ]) {
204 const response = await fetch(base + path, {
205 method: 'OPTIONS', headers: { origin: allowedOrigin, 'access-control-request-method': method, 'access-control-request-headers': 'authorization,content-type' },
206 });
207 assert.equal(response.status, 204);
208 assert.equal(response.headers.get('access-control-allow-origin'), allowedOrigin);
209 assert.ok(response.headers.get('access-control-allow-methods').split(',').includes(method));
210 }
211 });
212
213 test('production rejects unapproved origins consistently in standard and Phase 6 routes', async () => {
214 const user = await fixture();
215 for (const path of ['/v1/profile', '/v1/me/iran-profile']) {
216 const response = await request(path, { token: user.token, origin: 'https://denied.example.test' });
217 assert.equal(response.status, 403);
218 assert.equal(response.headers.get('access-control-allow-origin'), null);
219 assert.equal(response.body.error, 'cors_origin_denied');
220 }
221 });
222
223 test('malformed JSON returns correlated 400 in either route', async () => {
224 const user = await fixture();
225 for (const [method, path] of [['POST', '/v1/auth/login'], ['PATCH', '/v1/me/iran-profile']]) {
226 const response = await request(path, { method, token: user.token, rawBody: '{"password":"synthetic",' });
227 await errorEvent(response.headers.get('x-request-id'));
228 assert.equal(response.status, 400);
229 assert.equal(response.body.error, 'invalid_json');
230 assert.equal(response.body.requestId, response.headers.get('x-request-id'));
231 }
232 });
233
234 test('malformed sensitive request bodies never enter production logs', async () => {
235 const user = await fixture();
236 const marker = `synthetic-sensitive-${crypto.randomUUID()}`;
237 for (const [method, path] of [['POST', '/v1/auth/login'], ['PATCH', '/v1/me/iran-profile']]) {
238 const response = await request(path, { method, token: user.token, rawBody: `{"password":"${marker}",` });
239 const event = await errorEvent(response.headers.get('x-request-id'));
240 assert.deepEqual(Object.keys(event).sort(), ['errorClass', 'method', 'path', 'requestId', 'type']);
241 }
242 assert.equal(errors.includes(marker), false, 'Sensitive request body must not enter stderr');
243 assert.equal(output.includes(marker), false, 'Sensitive request body must not enter stdout');
244 });
245
246 test('production body limit returns 413 consistently before either router writes', async () => {
247 const user = await fixture();
248 for (const [method, path] of [['POST', '/v1/auth/login'], ['PATCH', '/v1/me/iran-profile']]) {
249 const response = await request(path, { method, token: user.token, body: { notes: 'x'.repeat(66000) } });
250 assert.equal(response.status, 413);
251 assert.equal(response.body.error, 'request_body_too_large');
252 }
253 });
254
255 test('unexpected database errors use sanitized correlated logs and responses', async () => {
256 const user = await fixture();
257 const marker = `synthetic-private-note-${crypto.randomUUID()}`;
258 const errorStart = errors.length;
259 const response = await request('/v1/me/menstrual-cycles', {
260 method: 'POST', token: user.token, body: { startsOn: '2026-10-04', endsOn: '2026-10-01', notes: marker },
261 });
262 await errorEvent(response.headers.get('x-request-id'));
263 assert.equal(response.status, 500);
264 assert.deepEqual(Object.keys(response.body).sort(), ['error', 'requestId']);
265 assert.equal(response.body.error, 'internal_error');
266 assert.equal(errors.includes(marker), false, 'Database row detail must not enter stderr');
267 const lines = errors.slice(errorStart).trim().split('\n').filter(Boolean);
268 assert.ok(lines.every((line) => { try { JSON.parse(line); return true; } catch { return false; } }), 'Error logs must contain only sanitized JSON events');
269 const events = lines.map((line) => JSON.parse(line));
270 assert.ok(events.some((event) => event.type === 'http_error' && event.requestId === response.body.requestId));
271 assert.ok(events.some((event) => event.errorClass !== 'TypeError'), 'The write must reach PostgreSQL rather than fail before body parsing');
272 });
273
274 test('errors after a partial HTTP response terminate the stream without leaking the raw error', { timeout: 10000 }, async () => {
275 const marker = `synthetic-stream-secret-${crypto.randomUUID()}`;
276 let fixtureOutput = '';
277 let fixtureErrors = '';
278 const streamServer = spawn(process.execPath, ['tests/fixtures/partial_error_server.js'], {
279 cwd: new URL('..', import.meta.url),
280 env: { ...process.env, NODE_ENV: 'production', SMS_PROVIDER: 'disabled', SMS_PROVIDER_URL: '', SMS_PROVIDER_TOKEN: '', STREAM_ERROR_MARKER: marker },
281 stdio: ['ignore', 'pipe', 'pipe'],
282 });
283 streamServer.stdout.on('data', (chunk) => { fixtureOutput += chunk.toString(); });
284 streamServer.stderr.on('data', (chunk) => { fixtureErrors += chunk.toString(); });
285 try {
286 const port = await new Promise((resolve, reject) => {
287 const timer = setTimeout(() => reject(new Error('Streaming HTTP fixture startup timed out')), 5000);
288 const onData = () => {
289 const line = fixtureOutput.split('\n').find((value) => value.includes('"stream_fixture_ready"'));
290 if (!line) return;
291 clearTimeout(timer);
292 streamServer.stdout.off('data', onData);
293 resolve(JSON.parse(line).port);
294 };
295 streamServer.stdout.on('data', onData);
296 streamServer.once('error', (error) => { clearTimeout(timer); reject(error); });
297 });
298 const fixtureBase = `http://127.0.0.1:${port}`;
299 const response = await new Promise((resolve, reject) => {
300 http.get(fixtureBase + '/partial-error', resolve).once('error', reject);
301 });
302 const terminated = new Promise((resolve) => {
303 response.once('aborted', () => resolve(true));
304 response.once('end', () => resolve(false));
305 response.on('error', () => {});
306 });
307 const [chunk] = await once(response, 'data');
308 assert.equal(chunk.toString(), 'started');
309 assert.equal((await fetch(fixtureBase + '/trigger-error', { method: 'POST' })).status, 204);
310 assert.equal(await terminated, true, 'Partially written response must be terminated');
311 const event = await errorEvent(response.headers['x-request-id'], { errorProcess: streamServer, readErrors: () => fixtureErrors });
312 assert.deepEqual(Object.keys(event).sort(), ['errorClass', 'method', 'path', 'requestId', 'type']);
313 // Wait for a callback queued after Express's deferred logging, then drain.
314 await errorEvent(response.headers['x-request-id'], {
315 errorProcess: streamServer, readErrors: () => fixtureErrors, eventType: 'stream_error_drained',
316 });
317 const closed = once(streamServer, 'close');
318 streamServer.kill('SIGTERM');
319 await closed;
320 assert.equal(fixtureErrors.includes(marker), false, 'Raw error message or stack must never enter stderr');
321 assert.equal(fixtureOutput.includes(marker), false, 'Raw error message or stack must never enter stdout');
322 } finally {
323 if (streamServer.exitCode === null && streamServer.signalCode === null) {
324 const exited = once(streamServer, 'close');
325 streamServer.kill('SIGTERM');
326 await exited;
327 }
328 }
329 });
330
331 for (const path of ['/v1/profile', '/v1/me/iran-profile']) {
332 test(`disabled account immediately rejects its existing session at ${path}`, async () => {
333 const user = await fixture();
334 assert.equal((await request(path, { token: user.token })).status, 200);
335 await pool.query('update app_user set disabled_at=now() where id=$1', [user.id]);
336 const response = await request(path, { token: user.token });
337 assert.equal(response.status, 401);
338 assert.equal(response.body.error, 'session_invalid');
339 });
340 }
341
342 test('disabled account cannot rotate a valid refresh token or create a new session', async () => {
343 const user = await fixture();
344 const first = await request('/v1/auth/refresh', { method: 'POST', body: { refreshToken: user.refreshToken } });
345 assert.equal(first.status, 200);
346 await pool.query('update app_user set disabled_at=now() where id=$1', [user.id]);
347 const beforeCount = (await pool.query('select count(*)::int as n from auth_session where user_id=$1', [user.id])).rows[0].n;
348 const response = await request('/v1/auth/refresh', { method: 'POST', body: { refreshToken: first.body.refreshToken } });
349 assert.equal(response.status, 401);
350 assert.equal(response.body.error, 'invalid_refresh_token');
351 assert.equal((await pool.query('select count(*)::int as n from auth_session where user_id=$1', [user.id])).rows[0].n, beforeCount);
352 });
353
354 test('disabled account cannot mutate a Phase 6 record with its existing session', async () => {
355 const user = await fixture();
356 assert.equal((await request('/v1/me/education', {
357 method: 'PUT', token: user.token, body: { nationalGrade: 7, schoolName: 'Before Disable' },
358 })).status, 200);
359 await pool.query('update app_user set disabled_at=now() where id=$1', [user.id]);
360 const blocked = await request('/v1/me/education', {
361 method: 'PUT', token: user.token, body: { nationalGrade: 8, schoolName: 'Must Not Persist' },
362 });
363 assert.equal(blocked.status, 401);
364 const row = (await pool.query('select national_grade,school_name from education_profile where user_id=$1', [user.id])).rows[0];
365 assert.equal(row.national_grade, 7);
366 assert.equal(row.school_name, 'Before Disable');
367 });
368
369 test('revoked and expired sessions are rejected consistently across both routers', async () => {
370 for (const reason of ['revoked', 'expired']) {
371 const user = await fixture();
372 if (reason === 'revoked') await pool.query('update auth_session set revoked_at=now() where id=$1', [user.sessionId]);
373 else await pool.query("update auth_session set expires_at=now()-interval '1 minute' where id=$1", [user.sessionId]);
374 for (const path of ['/v1/profile', '/v1/me/iran-profile']) {
375 assert.equal((await request(path, { token: user.token })).status, 401);
376 }
377 }
378 });