LifeMate — Personal, Family & Learning Companion

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