LifeMate — Personal, Family & Learning Companion

feat/weekly-planner-android
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 338 lines 25.9 KB
Raw
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,spawnSync} 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 {manageCapability,localSyntheticConnection,normalizeCapabilityOperation} from '../scripts/manage-content-capabilities.js';
10
11 const uuid=()=>crypto.randomUUID();
12 const privateMarker='SYNTHETIC-CHOSEN-SUMMARY-NEVER-IN-BRIEF';
13
14 test('operator CLI is explicit, separate, local-test-only and scope/expiry bounded',()=>{
15 const expiry=new Date(Date.now()+60000).toISOString();
16 assert.ok(normalizeCapabilityOperation(['grant',uuid(),'feedback.read',expiry]));
17 assert.ok(normalizeCapabilityOperation(['revoke',uuid(),'brief.prepare']));
18 for(const args of [['grant',uuid(),'admin',expiry],['grant',uuid(),'feedback.read','2020-01-01T00:00:00Z'],
19 ['grant',uuid(),'feedback.read'],['revoke',uuid(),'feedback.read',expiry]]) assert.equal(normalizeCapabilityOperation(args),null);
20 assert.throws(()=>localSyntheticConnection({DATABASE_URL:'postgresql://localhost/test'}));
21 assert.throws(()=>localSyntheticConnection({CONTENT_CAPABILITY_DATABASE_URL:'postgresql://foreign.example/test',CONTENT_CAPABILITY_SYNTHETIC_ONLY:'true'}));
22 assert.throws(()=>localSyntheticConnection({CONTENT_CAPABILITY_DATABASE_URL:'postgresql://localhost/production',CONTENT_CAPABILITY_SYNTHETIC_ONLY:'true'}));
23 assert.ok(localSyntheticConnection({CONTENT_CAPABILITY_DATABASE_URL:'postgresql://localhost/lifeguide_library_test',CONTENT_CAPABILITY_SYNTHETIC_ONLY:'true'}));
24 });
25
26 describe('content operations real entrypoint HTTP and synthetic PostgreSQL', {concurrency:false},()=>{
27 let pool,child,base;
28 let output='',errors='';
29 const users=[],families=[];
30 const serviceEnv={...process.env};delete serviceEnv.TEST_FIXTURE_DATABASE_URL;
31 const applicationName=`content-review-fixture-${uuid()}`;
32 async function start() {
33 const listener=net.createServer().listen(0,'127.0.0.1');await once(listener,'listening');
34 const port=listener.address().port;await new Promise(resolve=>listener.close(resolve));
35 base=`http://127.0.0.1:${port}`;
36 let startup='';
37 child=spawn(process.execPath,['src/entrypoint.js'],{env:{...serviceEnv,NODE_ENV:'production',PORT:String(port),PGAPPNAME:applicationName,
38 SMS_PROVIDER:'disabled',SMS_PROVIDER_URL:'',SMS_PROVIDER_TOKEN:'',EMAIL_FROM:'',RESEND_API_KEY:'',
39 SMTP_HOST:'',SMTP_USER:'',SMTP_PASSWORD:'',AI_API_KEY:'',AI_BASE_URL:'',AI_MODEL:'',OPENAI_API_KEY:'',
40 CORS_ORIGINS:'',TRUSTED_PROXY_CIDRS:'',ENABLE_SENSITIVE_FEATURES:'false',
41 RATE_LIMIT_AUTH_MAX:'2000',RATE_LIMIT_GENERAL_MAX:'8000'},stdio:['ignore','pipe','pipe']});
42 child.stdout.on('data',chunk=>{output+=chunk;startup+=chunk;});child.stderr.on('data',chunk=>{errors+=chunk;});
43 await new Promise((resolve,reject)=>{
44 const timeout=setTimeout(()=>reject(new Error('Content fixture startup timed out')),10000);
45 const ready=()=>{if(startup.includes('"type":"startup"')){clearTimeout(timeout);child.stdout.off('data',ready);resolve();}};
46 child.stdout.on('data',ready);child.once('error',()=>{clearTimeout(timeout);reject(new Error('Content fixture start failed'));});
47 child.once('exit',()=>{if(!startup.includes('"type":"startup"')){clearTimeout(timeout);reject(new Error('Content fixture exited early'));}});
48 });
49 }
50 async function stop(){if(child&&child.exitCode===null&&child.signalCode===null){const ended=once(child,'close');child.kill('SIGTERM');await ended;}}
51 before(async()=>{
52 assert.ok(process.env.DATABASE_URL&&process.env.JWT_SECRET?.length>=32,'Migrated synthetic fixture required');
53 const location=new URL(process.env.TEST_FIXTURE_DATABASE_URL??process.env.DATABASE_URL);
54 assert.ok(['localhost','127.0.0.1','[::1]','::1'].includes(location.hostname),'Only loopback synthetic PostgreSQL is allowed');
55 assert.ok(location.pathname.includes('test')||location.pathname==='/lifemate_ci'||
56 /^\/lifeguide_roles_source_[a-f0-9]{16}$/.test(location.pathname),'Explicit test database required');
57 pool=new pg.Pool({connectionString:process.env.TEST_FIXTURE_DATABASE_URL??process.env.DATABASE_URL});
58 await start();
59 });
60 after(async()=>{
61 await stop();if(!pool)return;
62 try {
63 await pool.query('delete from access_audit where family_id=any($1::uuid[]) or actor_user_id=any($2::uuid[])',[families,users]);
64 await pool.query('delete from family_workspace where id=any($1::uuid[])',[families]);
65 await pool.query('delete from app_user where id=any($1::uuid[])',[users]);
66 } finally {await pool.end();}
67 });
68 async function actor(extraClaims={},expiresIn='15m'){
69 const id=uuid(),sid=uuid();users.push(id);
70 await pool.query('insert into app_user(id,identity_subject,email_normalized,email_verified_at) values($1,$2,$3,now())',
71 [id,`content-review-fixture:${id}`,`content-review-${id}@example.test`]);
72 await pool.query("insert into profile(user_id,display_name,theme_preference) values($1,'Synthetic Reviewer','adult_blue')",[id]);
73 await pool.query("insert into auth_session(id,user_id,refresh_digest,expires_at) values($1,$2,$3,now()+interval '1 day')",[sid,id,crypto.randomBytes(32).toString('hex')]);
74 return {id,sid,token:jwt.sign({...extraClaims,sub:id,sid,aud:'lifemate-api'},process.env.JWT_SECRET,{issuer:'lifemate',expiresIn})};
75 }
76 async function grant(user,scopes=['feedback.read','feedback.review','brief.prepare'],duration=3600000){
77 const client=await pool.connect();
78 try {for(const permission of scopes)await manageCapability(client,{action:'grant',userId:user.id,permission,
79 expiresAt:new Date(Date.now()+duration).toISOString()});} finally {client.release();}
80 }
81 async function revoke(user,permission){const client=await pool.connect();try{await manageCapability(client,{action:'revoke',userId:user.id,permission,expiresAt:null});}finally{client.release();}}
82 async function request(path,{method='GET',user,body}={}){
83 const response=await fetch(base+path,{method,headers:{'content-type':'application/json',...(user?{authorization:`Bearer ${user.token}`}:{})},
84 body:body===undefined?undefined:JSON.stringify(body)});
85 const raw=await response.text();return {status:response.status,body:raw&&response.headers.get('content-type')?.includes('application/json')?JSON.parse(raw):raw||null};
86 }
87 async function feedback(user,{unitId=null,summary=privateMarker,category='topic_request'}={}){
88 const created=await request('/v1/education/feedback',{method:'POST',user,body:{mutationId:uuid(),unitId,category,summary,shareWithContentTeam:true}});
89 assert.equal(created.status,201);return created.body.feedback;
90 }
91 const list=(user,query='')=>request('/v1/content-review/feedback'+query,{user});
92 const review=(user,row,status,mutationId=uuid())=>request(`/v1/content-review/feedback/${row.id}`,{method:'PATCH',user,
93 body:{mutationId,expectedVersion:row.version,status}});
94 const prepare=(user,rows,mutationId=uuid())=>request('/v1/content-review/briefs',{method:'POST',user,
95 body:{mutationId,feedback:rows.map(row=>({id:row.id,expectedVersion:row.version}))}});
96 const withdraw=(user,row)=>request(`/v1/me/education-feedback/${row.id}`,{method:'DELETE',user});
97 async function planned(reviewer,row){
98 const triaged=await review(reviewer,row,'triaged');assert.equal(triaged.status,200);
99 const planned=await review(reviewer,triaged.body.feedback,'planned');assert.equal(planned.status,200);return planned.body.feedback;
100 }
101 async function blockedOn(client){
102 const pid=(await client.query('select pg_backend_pid() pid')).rows[0].pid;
103 const deadline=Date.now()+4000;
104 while(Date.now()<deadline){
105 const result=await pool.query(`select 1 from pg_stat_activity
106 where application_name=$1 and $2=any(pg_blocking_pids(pid))`,[applicationName,pid]);
107 if(result.rowCount)return;
108 await new Promise(resolve=>setTimeout(resolve,20));
109 }
110 assert.fail('Real API request did not reach the expected PostgreSQL row-lock wait');
111 }
112
113 test('all capabilities default empty, family/admin/JWT claims do not authorize or grant',async()=>{
114 const child=await actor(),parent=await actor({role:'admin',permissions:['feedback.read','feedback.review','brief.prepare']});
115 const family=uuid();families.push(family);
116 await pool.query("insert into family_workspace(id,name,created_by) values($1,'Synthetic Content Family',$2)",[family,parent.id]);
117 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,child.id]);
118 await pool.query('insert into guardian_relationship(family_id,guardian_user_id,minor_user_id) values($1,$2,$3)',[family,parent.id,child.id]);
119 const row=await feedback(child);
120 assert.deepEqual((await request('/v1/me/content-capabilities',{user:parent})).body,{permissions:[]});
121 assert.equal((await list(parent)).status,403);
122 assert.equal((await review(parent,row,'triaged')).status,403);
123 assert.equal((await prepare(parent,[row])).status,403);
124 assert.equal((await request(`/v1/content-review/briefs/${uuid()}`,{user:parent})).status,403);
125 assert.equal((await request('/v1/me/content-capabilities')).status,401);
126 assert.equal((await request('/v1/content-review/capabilities',{method:'POST',user:parent,body:{userId:parent.id,permission:'feedback.read'}})).status,404);
127 assert.equal((await pool.query('select count(*)::int n from content_capability_grant where user_id=$1',[parent.id])).rows[0].n,0);
128 });
129
130 test('explicit permissions are independently scoped and revocation/expiry is checked on every route',async()=>{
131 const owner=await actor(),reader=await actor();const row=await feedback(owner);
132 await grant(reader,['feedback.read']);
133 assert.deepEqual((await request('/v1/me/content-capabilities',{user:reader})).body,{permissions:['feedback.read']});
134 assert.equal((await list(reader)).status,200);
135 assert.equal((await review(reader,row,'triaged')).status,403);
136 assert.equal((await prepare(reader,[row])).status,403);
137 await grant(reader,['feedback.review','brief.prepare']);
138 assert.equal((await review(reader,row,'triaged')).status,200);
139 await revoke(reader,'feedback.read');
140 for(const call of [()=>list(reader),()=>review(reader,row,'triaged'),()=>prepare(reader,[row]),
141 ()=>request(`/v1/content-review/briefs/${uuid()}`,{user:reader})])assert.equal((await call()).status,403);
142 await grant(reader,['feedback.read']);
143 await pool.query("update content_capability_grant set granted_at=now()-interval '2 minutes',expires_at=now()-interval '1 minute' where user_id=$1",[reader.id]);
144 assert.deepEqual((await request('/v1/me/content-capabilities',{user:reader})).body,{permissions:[]});
145 assert.equal((await list(reader)).status,403);
146 });
147
148 test('standalone local synthetic operator CLI changes exact scopes without logging account or secrets',async()=>{
149 const user=await actor();
150 const env={...process.env,CONTENT_CAPABILITY_SYNTHETIC_ONLY:'true',
151 CONTENT_CAPABILITY_DATABASE_URL:process.env.TEST_FIXTURE_DATABASE_URL??process.env.DATABASE_URL};
152 const execute=args=>spawnSync(process.execPath,['scripts/manage-content-capabilities.js',...args],{env,encoding:'utf8'});
153 const expiry=new Date(Date.now()+3600000).toISOString();
154 const granted=execute(['grant',user.id,'feedback.read',expiry]);assert.equal(granted.status,0);
155 const logged=JSON.parse(granted.stdout);assert.equal(logged.permission,'feedback.read');assert.equal(logged.action,'grant');
156 assert.ok(!granted.stdout.includes(user.id));assert.ok(!granted.stdout.includes('postgres'));assert.equal(granted.stderr,'');
157 assert.deepEqual((await request('/v1/me/content-capabilities',{user})).body,{permissions:['feedback.read']});
158 const revoked=execute(['revoke',user.id,'feedback.read']);assert.equal(revoked.status,0);
159 assert.deepEqual((await request('/v1/me/content-capabilities',{user})).body,{permissions:[]});
160 assert.equal((await pool.query('select count(*)::int n from content_capability_audit where target_user_id=$1',[user.id])).rows[0].n,2);
161 const rejected=spawnSync(process.execPath,['scripts/manage-content-capabilities.js','grant',user.id,'feedback.read',expiry],
162 {env:{...env,CONTENT_CAPABILITY_DATABASE_URL:'postgresql://localhost/production'},encoding:'utf8'});
163 assert.equal(rejected.status,1);assert.ok(!rejected.stderr.includes(user.id));assert.ok(!rejected.stderr.includes('postgresql://'));
164 });
165
166 test('review listing exposes only consented chosen summaries, strict projection, stable paging and count',async()=>{
167 const owner=await actor(),reviewer=await actor();await grant(reviewer);
168 const rows=[];for(let n=0;n<3;n++)rows.push(await feedback(owner,{category:'broken_video',summary:`Synthetic page ${n}`}));
169 await withdraw(owner,rows[1]);
170 const page=await list(reviewer,'?status=received&limit=1');assert.equal(page.status,200);
171 const seen=new Set();let cursor=null,total=page.body.total;
172 do{
173 const next=await list(reviewer,`?status=received&limit=1${cursor?`&cursor=${cursor}`:''}`);assert.equal(next.status,200);
174 for(const row of next.body.feedback){assert.ok(!seen.has(row.id));seen.add(row.id);
175 assert.deepEqual(Object.keys(row).sort(),['id','unitId','category','summary','status','version','createdAt','updatedAt'].sort());}
176 cursor=next.body.nextCursor;
177 }while(cursor);
178 assert.equal(seen.size,total);assert.ok(seen.has(rows[0].id)&&seen.has(rows[2].id));assert.ok(!seen.has(rows[1].id));
179 assert.equal((await list(reviewer,`?cursor=${rows[1].id}`)).status,404);
180 for(const query of ['?limit=0','?limit=101','?limit=2.2','?limit[]=1','?status=invalid','?ownerUserId='+owner.id,'?cursor=bad'])assert.equal((await list(reviewer,query)).status,400);
181 await pool.query("insert into plan_item(owner_user_id,kind,title,notes) values($1,'task','Synthetic private','PRIVATE-NOTE-REVIEW-SENTINEL')",[owner.id]);
182 await pool.query("insert into wellbeing_checkin(owner_user_id,mood,note) values($1,3,'PRIVATE-HEALTH-REVIEW-SENTINEL')",[owner.id]);
183 const chat=(await pool.query("insert into ai_guide_session(owner_user_id,guide_kind) values($1,'study') returning id",[owner.id])).rows[0].id;
184 await pool.query("insert into ai_guide_message(session_id,author,body) values($1,'user','PRIVATE-CHAT-REVIEW-SENTINEL')",[chat]);
185 const visible=JSON.stringify((await list(reviewer)).body);
186 for(const text of [owner.id,`content-review-${owner.id}@example.test`,'PRIVATE-NOTE-REVIEW-SENTINEL','PRIVATE-HEALTH-REVIEW-SENTINEL','PRIVATE-CHAT-REVIEW-SENTINEL']){
187 assert.ok(!visible.includes(text));assert.ok(!output.includes(text));assert.ok(!errors.includes(text));}
188 });
189
190 test('CAS transitions, durable exact retry, concurrent duplicate, current-state replay and textless audit',async()=>{
191 const owner=await actor(),reviewer=await actor();await grant(reviewer);
192 const row=await feedback(owner),mutationId=uuid();
193 const concurrent=await Promise.all(Array.from({length:4},()=>review(reviewer,row,'triaged',mutationId)));
194 assert.ok(concurrent.every(result=>result.status===200));
195 assert.equal(concurrent.filter(result=>result.body.acknowledgement.status==='accepted').length,1);
196 assert.equal((await pool.query('select count(*)::int n from content_review_mutation where actor_user_id=$1 and mutation_id=$2',[reviewer.id,mutationId])).rows[0].n,1);
197 const next=concurrent[0].body.feedback;
198 assert.equal(next.version,2);assert.equal((await review(reviewer,row,'declined')).status,409);
199 assert.equal((await review(reviewer,row,'declined',mutationId)).body.error,'mutation_id_reused');
200 const plannedRow=(await review(reviewer,next,'planned')).body.feedback;
201 await stop();await start();
202 const replay=await review(reviewer,row,'triaged',mutationId);assert.equal(replay.status,200);
203 assert.equal(replay.body.feedback.version,3);assert.equal(replay.body.feedback.status,'planned');
204 assert.equal(replay.body.acknowledgement.status,'already_applied');
205 assert.equal((await review(reviewer,plannedRow,'released')).status,400);
206 const audit=(await pool.query('select * from content_review_audit where feedback_id=$1 order by occurred_at',[row.id])).rows;
207 assert.equal(audit.length,2);assert.equal(audit[0].before_status,'received');assert.equal(audit[1].after_status,'planned');
208 assert.ok(!JSON.stringify(audit).includes(privateMarker));
209 assert.equal((await withdraw(owner,row)).status,204);
210 const withdrawnRetry=await review(reviewer,row,'triaged',mutationId);assert.equal(withdrawnRetry.status,404);
211 assert.ok(!JSON.stringify(withdrawnRetry).includes(privateMarker));
212 });
213
214 test('allowed transition matrix prevents release and concurrent competing versions update once',async()=>{
215 const owner=await actor(),a=await actor(),b=await actor();await grant(a);await grant(b);
216 const row=await feedback(owner);
217 assert.equal((await review(a,row,'planned')).body.error,'feedback_transition_invalid');
218 const results=await Promise.all([review(a,row,'triaged'),review(b,row,'declined')]);
219 assert.deepEqual(results.map(result=>result.status).sort(),[200,409]);
220 let current=results.find(result=>result.status===200).body.feedback;
221 if(current.status==='declined')current=(await review(a,current,'triaged')).body.feedback;
222 current=(await review(a,current,'planned')).body.feedback;
223 current=(await review(a,current,'triaged')).body.feedback;
224 current=(await review(a,current,'declined')).body.feedback;
225 assert.equal((await review(a,current,'planned')).status,409);
226 current=(await review(a,current,'triaged')).body.feedback;assert.equal(current.status,'triaged');
227 });
228
229 test('briefs contain only structural public context, persist/replay once, never chosen or private text',async()=>{
230 const owner=await actor(),reviewer=await actor();await grant(reviewer);
231 const unit=(await pool.query('select id from learning_unit order by id limit 1')).rows[0].id;
232 const rows=[await planned(reviewer,await feedback(owner,{unitId:unit,summary:privateMarker})),
233 await planned(reviewer,await feedback(owner,{category:'unclear',summary:'SYNTHETIC-SECOND-PRIVATE-SUMMARY'}))];
234 const mutationId=uuid();
235 const results=await Promise.all([prepare(reviewer,rows,mutationId),prepare(reviewer,[...rows].reverse(),mutationId)]);
236 assert.deepEqual(results.map(result=>result.status).sort(),[200,201]);
237 const brief=results[0].body.brief;assert.equal(brief.sourceCount,2);assert.equal(brief.units.length,1);
238 assert.equal(brief.units[0].id,unit);assert.equal(brief.tasks.length,4);
239 const serialized=JSON.stringify(brief);
240 for(const privateText of [privateMarker,'SYNTHETIC-SECOND-PRIVATE-SUMMARY',owner.id,reviewer.id,...rows.map(row=>row.id)])assert.ok(!serialized.includes(privateText));
241 assert.equal((await pool.query('select count(*)::int n from content_review_brief where actor_user_id=$1',[reviewer.id])).rows[0].n,1);
242 await stop();await start();
243 const replay=await prepare(reviewer,rows,mutationId);assert.equal(replay.status,200);assert.deepEqual(replay.body.brief,brief);
244 assert.equal(replay.body.acknowledgement.status,'already_applied');
245 assert.deepEqual((await request(`/v1/content-review/briefs/${brief.id}`,{user:reviewer})).body.brief,brief);
246 assert.equal((await prepare(reviewer,[rows[0]],mutationId)).body.error,'mutation_id_reused');
247 });
248
249 test('brief preconditions and source withdrawal/review changes invalidate every GET and replay',async()=>{
250 const owner=await actor(),reviewer=await actor();await grant(reviewer);
251 const raw=await feedback(owner);
252 assert.equal((await prepare(reviewer,[raw])).body.error,'brief_source_conflict');
253 const row=await planned(reviewer,raw),mutationId=uuid();
254 const created=await prepare(reviewer,[row],mutationId);assert.equal(created.status,201);
255 const id=created.body.brief.id;
256 const changed=await review(reviewer,row,'triaged');assert.equal(changed.status,200);
257 for(const response of [await request(`/v1/content-review/briefs/${id}`,{user:reviewer}),await prepare(reviewer,[row],mutationId)]){
258 assert.equal(response.status,409);assert.equal(response.body.error,'brief_invalidated');assert.ok(!JSON.stringify(response).includes(privateMarker));}
259 const row2=await planned(reviewer,await feedback(owner)),mutation2=uuid();
260 const created2=await prepare(reviewer,[row2],mutation2);assert.equal(created2.status,201);
261 await withdraw(owner,row2);
262 assert.equal((await request(`/v1/content-review/briefs/${created2.body.brief.id}`,{user:reviewer})).status,409);
263 assert.equal((await prepare(reviewer,[row2],mutation2)).status,409);
264 const db=(await pool.query('select summary,share_with_content_team from learning_content_feedback where id=$1',[row2.id])).rows[0];
265 assert.equal(db.summary,null);assert.equal(db.share_with_content_team,false);
266 await revoke(reviewer,'brief.prepare');
267 assert.equal((await request(`/v1/content-review/briefs/${id}`,{user:reviewer})).status,403);
268 assert.equal((await prepare(reviewer,[row],mutationId)).status,403);
269 });
270
271 test('source deletion invalidates a multiple-source brief instead of silently returning a partial old result',async()=>{
272 const owner1=await actor(),owner2=await actor(),reviewer=await actor();await grant(reviewer);
273 const row1=await planned(reviewer,await feedback(owner1)),row2=await planned(reviewer,await feedback(owner2));
274 const created=await prepare(reviewer,[row1,row2]);assert.equal(created.status,201);
275 await pool.query('delete from app_user where id=$1',[owner1.id]);
276 assert.equal((await request(`/v1/content-review/briefs/${created.body.brief.id}`,{user:reviewer})).body.error,'brief_invalidated');
277 });
278
279 test('withdrawal wins races: blocked review retry and brief read cannot reveal an old consenting summary',async()=>{
280 const owner=await actor(),reviewer=await actor();await grant(reviewer);
281 const row=await planned(reviewer,await feedback(owner)),created=await prepare(reviewer,[row]);
282 const blocker=await pool.connect();
283 try{
284 await blocker.query('begin');
285 await blocker.query('select id from learning_content_feedback where id=$1 for update',[row.id]);
286 const pending=request(`/v1/content-review/briefs/${created.body.brief.id}`,{user:reviewer});
287 await blockedOn(blocker);
288 await blocker.query(`update learning_content_feedback set summary=null,share_with_content_team=false,
289 withdrawn_at=now(),updated_at=now(),version=version+1 where id=$1`,[row.id]);
290 await blocker.query('commit');
291 const response=await pending;assert.equal(response.status,409);assert.ok(!JSON.stringify(response).includes(privateMarker));
292 }finally{await blocker.query('rollback').catch(()=>{});blocker.release();}
293 assert.equal((await review(reviewer,row,'triaged')).status,404);
294 });
295
296 test('permission expiry while source-lock blocked rolls back a pending review write and audit',async()=>{
297 const owner=await actor(),reviewer=await actor();await grant(reviewer,['feedback.read','feedback.review'],3000);
298 const row=await feedback(owner),blocker=await pool.connect();
299 try{
300 await blocker.query('begin');await blocker.query('select id from learning_content_feedback where id=$1 for update',[row.id]);
301 const pending=review(reviewer,row,'triaged');
302 await blockedOn(blocker);
303 // Separate operator simulation for expiry. No grant mutation is done by the API.
304 await pool.query("update content_capability_grant set expires_at=statement_timestamp()+interval '150 milliseconds' where user_id=$1",[reviewer.id]);
305 await new Promise(resolve=>setTimeout(resolve,220));await blocker.query('commit');
306 assert.equal((await pending).status,403);
307 assert.equal((await pool.query('select status,version from learning_content_feedback where id=$1',[row.id])).rows[0].status,'received');
308 assert.equal((await pool.query('select count(*)::int n from content_review_audit where feedback_id=$1',[row.id])).rows[0].n,0);
309 }finally{await blocker.query('rollback').catch(()=>{});blocker.release();}
310 });
311
312 test('direct concurrent capability revocation during a blocked write is rechecked before commit',async()=>{
313 const owner=await actor(),reviewer=await actor();await grant(reviewer);
314 const row=await feedback(owner),blocker=await pool.connect();
315 try{
316 await blocker.query('begin');await blocker.query('select id from learning_content_feedback where id=$1 for update',[row.id]);
317 const pending=review(reviewer,row,'triaged');await blockedOn(blocker);
318 await pool.query("update content_capability_grant set revoked_at=statement_timestamp() where user_id=$1 and permission='feedback.review'",[reviewer.id]);
319 await blocker.query('commit');assert.equal((await pending).status,403);
320 assert.equal((await pool.query('select version from learning_content_feedback where id=$1',[row.id])).rows[0].version,1);
321 assert.equal((await pool.query('select count(*)::int n from content_review_mutation where actor_user_id=$1',[reviewer.id])).rows[0].n,0);
322 }finally{await blocker.query('rollback').catch(()=>{});blocker.release();}
323 });
324
325 test('JWT expiry while waiting for a source row rolls back review and receipt',async()=>{
326 const owner=await actor(),reviewer=await actor({},'2s');await grant(reviewer);
327 const row=await feedback(owner),blocker=await pool.connect();
328 try{
329 await blocker.query('begin');await blocker.query('select id from learning_content_feedback where id=$1 for update',[row.id]);
330 const pending=review(reviewer,row,'triaged');await blockedOn(blocker);
331 const expiry=jwt.decode(reviewer.token).exp*1000;
332 while(Date.now()<=expiry)await new Promise(resolve=>setTimeout(resolve,25));
333 await blocker.query('commit');assert.equal((await pending).status,401);
334 assert.equal((await pool.query('select version from learning_content_feedback where id=$1',[row.id])).rows[0].version,1);
335 assert.equal((await pool.query('select count(*)::int n from content_review_mutation where actor_user_id=$1',[reviewer.id])).rows[0].n,0);
336 }finally{await blocker.query('rollback').catch(()=>{});blocker.release();}
337 });
338 });