LifeMate — Personal, Family & Learning Companion
fix: share request parsing and active-session checks across API
Codex committed
Oct 8, 2026 at 05:39 UTC
991635a0849bf1dce7897bf0d593765b5918b8f2
8 files changed
+458
-44
backend/package.json
+1
-1
@@ -7,7 +7,7 @@
7
"start": "node src/entrypoint.js",
8
"test": "node --test tests/*.test.js",
9
"migrate": "node scripts/migrate.js",
10
- "check": "node --check src/server.js && node --check src/phase3.js && node --check src/phase4.js && node --check src/phase6.js && node --check src/operations.js && node --check src/entrypoint.js"
10
+ "check": "node --check src/server.js && node --check src/phase3.js && node --check src/phase4.js && node --check src/phase6.js && node --check src/session_auth.js && node --check src/operations.js && node --check src/entrypoint.js"
11
},
12
"engines": {"node": ">=22"},
13
"dependencies": {
backend/src/entrypoint.js
-4
@@ -1,8 +1,6 @@
1
const publicPort = Number(process.env.PORT ?? 8080);
2
process.env.NODE_ENV = process.env.NODE_ENV || 'production';
3
-process.env.PORT = '0';
3
import express from 'express';
5
-import { createPhase6Router } from './phase6.js';
4
import {
5
operationalErrorHandler,
6
rateLimit,
@@ -11,7 +9,6 @@ import {
9
} from './operations.js';
10
11
const { app, pool } = await import('./server.js');
14
-process.env.PORT = String(publicPort);
12
13
const outer = express();
14
outer.disable('x-powered-by');
@@ -33,7 +30,6 @@ outer.get('/ready', async (_req, res) => {
30
}
31
});
32
36
-outer.use('/v1', createPhase6Router({ pool }));
33
outer.use(app);
34
outer.use(operationalErrorHandler);
35
outer.listen(publicPort, () => console.log(JSON.stringify({ type: 'startup', service: 'lifemate-api', port: publicPort })));
backend/src/operations.js
+14
-1
@@ -106,6 +106,19 @@ export function operationalErrorHandler(err, req, res, _next) {
106
errorClass: err?.name || 'Error',
107
};
108
if (process.env.NODE_ENV !== 'test') console.error(JSON.stringify(event));
109
- if (res.headersSent) return;
109
+ if (res.headersSent) {
110
+ // Passing the original error to Express would print its raw message/stack.
111
+ res.destroy();
112
+ return;
113
+ }
114
+ if (err?.type === 'entity.parse.failed') {
115
+ return res.status(400).json({ error: 'invalid_json', requestId: req.requestId });
116
+ }
117
+ if (err?.type === 'entity.too.large') {
118
+ return res.status(413).json({ error: 'request_body_too_large', requestId: req.requestId });
119
+ }
120
+ if (err?.code === 'CORS_ORIGIN_DENIED') {
121
+ return res.status(403).json({ error: 'cors_origin_denied', requestId: req.requestId });
122
+ }
123
res.status(500).json({ error: 'internal_error', requestId: req.requestId });
124
}
backend/src/phase6.js
+2
-12
@@ -1,23 +1,13 @@
1
import express from 'express';
2
-import jwt from 'jsonwebtoken';
2
+import { createSessionAuth } from './session_auth.js';
3
4
const stages = { primary_1:[1,3,0], primary_2:[4,6,3], secondary_1:[7,9,6], secondary_2:[10,12,9] };
5
function educationForGrade(grade){ const n=Number(grade); for(const [stage,[min,max,offset]] of Object.entries(stages)){ if(Number.isInteger(n)&&n>=min&&n<=max)return{stage,nationalGrade:n,localYear:n-offset}; } return null; }
6
function validPersona(value){ return ['mother','father','child','adult'].includes(value); }
7
function trustedTextbookUrl(value){ try{ const url=new URL(value); return url.protocol==='https:'&&['chap.sch.ir','medu.gov.ir'].includes(url.hostname); }catch{return false;} }
8
9
-function localAuth(pool){
10
- return async (req,res,next)=>{ try{
11
- const raw=req.headers.authorization?.replace(/^Bearer\s+/i,'');
12
- const identity=jwt.verify(raw,process.env.JWT_SECRET,{audience:'lifemate-api',issuer:'lifemate'});
13
- const session=await pool.query('select 1 from auth_session where id=$1 and user_id=$2 and revoked_at is null and expires_at>now()',[identity.sid,identity.sub]);
14
- if(!session.rowCount)return res.status(401).json({error:'session_invalid'});
15
- req.identity=identity; next();
16
- }catch{return res.status(401).json({error:'unauthorized'});} };
17
-}
18
-
9
export function createPhase6Router({pool,auth}){
20
- const router=express.Router(); const requireAuth=auth??localAuth(pool);
10
+ const router=express.Router(); const requireAuth=auth??createSessionAuth({pool,jwtSecret:process.env.JWT_SECRET});
11
router.get('/me/iran-profile',requireAuth,async(req,res)=>{ const r=await pool.query(`select p.user_id,p.display_name,p.birth_date,p.household_persona,p.sex,e.stage,e.national_grade,e.local_year,e.school_name,e.school_year from profile p left join education_profile e on e.user_id=p.user_id where p.user_id=$1`,[req.identity.sub]); res.json(r.rows[0]??{}); });
12
router.patch('/me/iran-profile',requireAuth,async(req,res)=>{ const persona=req.body.householdPersona,sex=req.body.sex; if(persona!=null&&!validPersona(persona))return res.status(400).json({error:'invalid_persona'}); if(sex!=null&&!['female','male','unspecified'].includes(sex))return res.status(400).json({error:'invalid_sex'}); await pool.query(`update profile set household_persona=coalesce($2,household_persona),sex=coalesce($3,sex),birth_date=coalesce($4::date,birth_date),updated_at=now() where user_id=$1`,[req.identity.sub,persona??null,sex??null,req.body.birthDate??null]); res.status(204).end(); });
13
router.put('/me/education',requireAuth,async(req,res)=>{ const mapped=educationForGrade(req.body.nationalGrade); if(!mapped||(req.body.stage&&req.body.stage!==mapped.stage))return res.status(400).json({error:'invalid_grade_stage'}); const schoolYear=String(req.body.schoolYear??'1405-1406'); const r=await pool.query(`insert into education_profile(user_id,stage,national_grade,local_year,school_name,school_year) values($1,$2,$3,$4,$5,$6) on conflict(user_id) do update set stage=excluded.stage,national_grade=excluded.national_grade,local_year=excluded.local_year,school_name=excluded.school_name,school_year=excluded.school_year,updated_at=now() returning *`,[req.identity.sub,mapped.stage,mapped.nationalGrade,mapped.localYear,req.body.schoolName??null,schoolYear]); res.json(r.rows[0]); });
backend/src/server.js
+16
-26
@@ -1,4 +1,5 @@
1
import crypto from 'node:crypto';
2
+import { pathToFileURL } from 'node:url';
3
import express from 'express';
4
import argon2 from 'argon2';
5
import jwt from 'jsonwebtoken';
@@ -7,6 +8,9 @@ import nodemailer from 'nodemailer';
8
import cors from 'cors';
9
import { createPhase3Router } from './phase3.js';
10
import { createPhase4Router } from './phase4.js';
11
+import { createPhase6Router } from './phase6.js';
12
+import { operationalErrorHandler } from './operations.js';
13
+import { createSessionAuth } from './session_auth.js';
14
15
const { Pool } = pg;
16
const app = express();
@@ -20,9 +24,11 @@ app.use(
24
if (!origin || testMode || allowedOrigins.includes(origin)) {
25
return callback(null, true);
26
}
23
- return callback(new Error('cors_origin_denied'));
27
+ const error = new Error('cors_origin_denied');
28
+ error.code = 'CORS_ORIGIN_DENIED';
29
+ return callback(error);
30
},
25
- methods: ['GET', 'POST', 'PATCH', 'OPTIONS'],
31
+ methods: ['GET', 'POST', 'PATCH', 'PUT', 'DELETE', 'OPTIONS'],
32
allowedHeaders: ['Content-Type', 'Authorization'],
33
maxAge: 86400,
34
}),
@@ -88,24 +94,7 @@ const issueAccess = (userId, sessionId) =>
94
{ expiresIn: '15m', issuer: 'lifemate' },
95
);
96
91
-async function auth(req, res, next) {
92
- const raw = req.headers.authorization?.replace(/^Bearer\s+/i, '');
93
- try {
94
- const identity = jwt.verify(raw, jwtSecret, {
95
- audience: 'lifemate-api',
96
- issuer: 'lifemate',
97
- });
98
- const session = await pool.query(
99
- 'select 1 from auth_session where id=$1 and user_id=$2 and revoked_at is null and expires_at>now()',
100
- [identity.sid, identity.sub],
101
- );
102
- if (!session.rowCount) return res.status(401).json({ error: 'session_invalid' });
103
- req.identity = identity;
104
- next();
105
- } catch {
106
- res.status(401).json({ error: 'unauthorized' });
107
- }
108
-}
97
+const auth = createSessionAuth({ pool, jwtSecret });
98
99
async function createOneTimeToken(client, userId, kind, minutes) {
100
const raw = randomToken();
@@ -252,7 +241,9 @@ app.post('/v1/auth/refresh', async (req, res) => {
241
try {
242
await client.query('begin');
243
const r = await client.query(
255
- 'select id,user_id from auth_session where refresh_digest=$1 and revoked_at is null and expires_at>now() for update',
244
+ `select s.id,s.user_id from auth_session s join app_user u on u.id=s.user_id
245
+ where s.refresh_digest=$1 and s.revoked_at is null and s.expires_at>now()
246
+ and u.disabled_at is null for update of s,u`,
247
[digest],
248
);
249
if (!r.rowCount) {
@@ -606,14 +597,13 @@ app.post('/v1/families/:familyId/guardians', auth, async (req, res) => {
597
598
app.use('/v1', createPhase3Router({ pool, auth }));
599
app.use('/v1', createPhase4Router({ pool, auth }));
600
+app.use('/v1', createPhase6Router({ pool, auth }));
601
610
-app.use((err, _req, res, _next) => {
611
- console.error(err);
612
- res.status(500).json({ error: 'internal_error' });
613
-});
602
+app.use(operationalErrorHandler);
603
604
const port = Number(process.env.PORT ?? 8080);
616
-if (!testMode) {
605
+const invokedDirectly = process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href;
606
+if (!testMode && invokedDirectly) {
607
app.listen(port, () => console.log(`LifeMate API listening on ${port}`));
608
}
609
backend/src/session_auth.js
new
+25
@@ -0,0 +1,25 @@
1
+import jwt from 'jsonwebtoken';
2
+
3
+// Every API router must check both the session and the current account state.
4
+export function createSessionAuth({ pool, jwtSecret }) {
5
+ return async (req, res, next) => {
6
+ const raw = req.headers.authorization?.replace(/^Bearer\s+/i, '');
7
+ try {
8
+ const identity = jwt.verify(raw, jwtSecret, {
9
+ audience: 'lifemate-api',
10
+ issuer: 'lifemate',
11
+ });
12
+ const session = await pool.query(
13
+ `select 1 from auth_session s join app_user u on u.id=s.user_id
14
+ where s.id=$1 and s.user_id=$2 and s.revoked_at is null
15
+ and s.expires_at>now() and u.disabled_at is null`,
16
+ [identity.sid, identity.sub],
17
+ );
18
+ if (!session.rowCount) return res.status(401).json({ error: 'session_invalid' });
19
+ req.identity = identity;
20
+ next();
21
+ } catch {
22
+ res.status(401).json({ error: 'unauthorized' });
23
+ }
24
+ };
25
+}
backend/tests/fixtures/partial_error_server.js
new
+25
@@ -0,0 +1,25 @@
1
+import express from 'express';
2
+import { operationalErrorHandler, requestContext } from '../../src/operations.js';
3
+
4
+// Exercise the actual error middleware over HTTP after response headers are sent.
5
+const app = express();
6
+app.use(requestContext);
7
+let failStream;
8
+let streamRequestId;
9
+app.get('/partial-error', (req, res, next) => {
10
+ streamRequestId = req.requestId;
11
+ failStream = () => next(new Error(process.env.STREAM_ERROR_MARKER));
12
+ res.setHeader('Content-Type', 'text/plain');
13
+ res.write('started');
14
+});
15
+app.post('/trigger-error', (_req, res) => {
16
+ res.status(204).end();
17
+ failStream();
18
+ // Express schedules fallback error logging during next(err). This later
19
+ // callback lets the client wait for that logging opportunity before shutdown.
20
+ setImmediate(() => console.error(JSON.stringify({ type: 'stream_error_drained', requestId: streamRequestId })));
21
+});
22
+app.use(operationalErrorHandler);
23
+const server = app.listen(0, '127.0.0.1', () => {
24
+ console.log(JSON.stringify({ type: 'stream_fixture_ready', port: server.address().port }));
25
+});
backend/tests/request_safety.test.js
new
+375
@@ -0,0 +1,375 @@
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
+});