LifeMate — Personal, Family & Learning Companion
feat: add authorized family, school and learning content operations
Quinn White committed
Oct 12, 2026 at 03:08 UTC
c826ae84da6960aabc45e9bf226809d762966aa6
32 files changed
+4635
-161
backend/content/drafts/grade1-math-pilot.json
new
+793
@@ -0,0 +1,793 @@
1
+{
2
+ "schemaVersion": 1,
3
+ "kind": "lifeguide_original_learning_pilot_draft",
4
+ "pilotId": "ir-105-1405-1406-theme-01",
5
+ "version": 1,
6
+ "publicationStatus": "draft",
7
+ "reviewRecord": null,
8
+ "createdAt": "2026-10-11",
9
+ "authorKind": "AI-authored original draft; not a licensed educator approval",
10
+ "language": "fa-IR",
11
+ "audience": {
12
+ "grade": 1,
13
+ "readAloudByTrustedAdultMayBeNeeded": true,
14
+ "noAgeInferenceFromGrade": true
15
+ },
16
+ "book": {
17
+ "bookCode": "105",
18
+ "grade": 1,
19
+ "subjectCode": "math",
20
+ "trackCodes": [
21
+ "common"
22
+ ],
23
+ "variant": "standard",
24
+ "titleFa": "ریاضی (اول)",
25
+ "schoolYear": "1405-1406",
26
+ "sourceUrl": "http://www.chap.sch.ir/books/14145",
27
+ "pdfUrl": "http://www.chap.sch.ir/sites/default/files/lbooks/1405-1406/8/C105.pdf",
28
+ "officialDetailHttpStatus": 200,
29
+ "officialPdfHttpStatus": 200,
30
+ "pdfBytes": 38215789,
31
+ "pdfSha256": "8c2323ce542adcb4e53d79287cccb16a050a2a63ef2484ac337addf076b118d4",
32
+ "pdfPageCount": 184,
33
+ "imprintVerified": "چاپ شانزدهم1405 — PDF page2 inspected as extracted text",
34
+ "pageInspection": {
35
+ "printedPages": [
36
+ 1,
37
+ 2,
38
+ 3,
39
+ 4,
40
+ 5,
41
+ 6,
42
+ 7
43
+ ],
44
+ "pdfPages": [
45
+ 7,
46
+ 8,
47
+ 9,
48
+ 10,
49
+ 11,
50
+ 12,
51
+ 13
52
+ ],
53
+ "method": "pdftotext layout + actual PNG render visual inspection",
54
+ "status": "verified_only_for_this_scope"
55
+ },
56
+ "excludedExperimentalBookCode": "1051"
57
+ },
58
+ "unit": {
59
+ "unitKey": "theme-01",
60
+ "titleFa": "تم۱: دستهبندی، شمارش، نمایش تعداد و الگو",
61
+ "orderIndex": 1,
62
+ "indexKind": "lesson",
63
+ "sourceEvidenceUrl": "http://www.chap.sch.ir/sites/default/files/lbooks/1405-1406/8/C105.pdf#page=7",
64
+ "printedPageRange": [
65
+ 1,
66
+ 7
67
+ ],
68
+ "pdfPageRange": [
69
+ 7,
70
+ 13
71
+ ],
72
+ "scopeNoteFa": "پایلوت تم نخست کتاب استاندارد105؛ یک سال کامل یا کتاب آزمایشی1051 نیست. هدفهای زیر طراحی اصلی لایفگاید بر مبنای صفحات بررسیشدهاند."
73
+ },
74
+ "objectives": [
75
+ {
76
+ "id": "sort_count",
77
+ "statementFa": "شکلهای همنوع را جدا کنم و هر کدام را فقط یکبار، تا پنج، بشمارم.",
78
+ "printedPages": [
79
+ 2
80
+ ]
81
+ },
82
+ {
83
+ "id": "cardinality",
84
+ "statementFa": "بگویم آخرین واژه شمارش، تعداد کل دسته را نشان میدهد؛ با جابهجایی بدون افزودن یا برداشتن، تعداد عوض نمیشود.",
85
+ "printedPages": [
86
+ 2,
87
+ 6
88
+ ],
89
+ "alignmentNoteFa": "پیامد آموزشی طراحیشده از شمارش و مقایسه دستهها؛ جمله عیناً از کتاب برداشته نشده است."
90
+ },
91
+ {
92
+ "id": "quantity_representation",
93
+ "statementFa": "برای هر شیء، یک خانه یا یک نشانه نشان دهم و تعداد را با نشانهها مقایسه کنم.",
94
+ "printedPages": [
95
+ 3,
96
+ 7
97
+ ]
98
+ },
99
+ {
100
+ "id": "same_quantity",
101
+ "statementFa": "دستههای همتعداد را حتی وقتی نوع شکل یا فاصله آنها متفاوت است، پیدا کنم.",
102
+ "printedPages": [
103
+ 6
104
+ ]
105
+ },
106
+ {
107
+ "id": "pattern",
108
+ "statementFa": "بخش تکراری یک الگوی ساده را توضیح دهم و همان ترتیب را ادامه بدهم.",
109
+ "printedPages": [
110
+ 4,
111
+ 5,
112
+ 7
113
+ ]
114
+ },
115
+ {
116
+ "id": "flexible_representation",
117
+ "statementFa": "یک تعداد کمتر از پنج را به بیش از یک روش با انگشتان یا کارتها نشان دهم.",
118
+ "printedPages": [
119
+ 7
120
+ ]
121
+ }
122
+ ],
123
+ "prerequisites": [
124
+ {
125
+ "id": "familiar_objects",
126
+ "statementFa": "تشخیص چند شیء یا شکل آشنا؛ در صورت نیاز بزرگسال نامها را میگوید."
127
+ },
128
+ {
129
+ "id": "single_touch",
130
+ "statementFa": "امکان اشاره، جابهجایی یا انتخاب یک شیء در هر نوبت؛ روش جایگزین متناسب با توانایی حرکتی فراهم شود."
131
+ }
132
+ ],
133
+ "notPrerequisitesFa": [
134
+ "خواندن روان",
135
+ "نوشتن ارقام",
136
+ "سرعت پاسخ",
137
+ "شمردن بیش از پنج",
138
+ "دسترسی به ویدیو یا هوش مصنوعی"
139
+ ],
140
+ "learnerIntroductionFa": "امروز چیزهای مثل هم را جدا میکنیم، یکییکی میشماریم و شکلهای تکرارشونده میسازیم. میتوانی فکر کنی، کمک بخواهی یا استراحت کنی؛ مسابقه سرعت نیست.",
141
+ "entryCheck": {
142
+ "mode": "adult_read_aloud_or_picture_based",
143
+ "purpose": "choose_support_not_grade_or_lockout",
144
+ "promptsFa": [
145
+ "دو کارت آشنا پیدا کن و نشان بده.",
146
+ "میتوانی این سه کارت را هرکدام فقط یکبار بشماری؟",
147
+ "در یک الگوی گردـمثلثـگردـمثلث، بخش تکراری را نشان بده."
148
+ ],
149
+ "noStoredDiagnosis": true
150
+ },
151
+ "sessionGuidance": {
152
+ "suggestedBlockMinutes": [
153
+ 5,
154
+ 10
155
+ ],
156
+ "policyStatus": "draft product scheduling suggestion; not a scientifically optimal duration for every child",
157
+ "breaksAllowed": true,
158
+ "startMidyearAllowed": true,
159
+ "allModulesNavigationAllowed": true,
160
+ "materialsFa": [
161
+ "کارت کاغذی بزرگ با لبه بیخطر",
162
+ "مداد و کاغذ",
163
+ "اشیای آشنای ایمن با نظارت بزرگسال؛ از اشیای کوچک یا تیز استفاده نشود"
164
+ ],
165
+ "fingerAlternativeRequired": true,
166
+ "noRecordingOrCameraRequired": true
167
+ },
168
+ "modules": [
169
+ {
170
+ "id": "notice_sort_count",
171
+ "titleFa": "با اشیای آشنا دسته بساز و بشمار",
172
+ "objectiveIds": [
173
+ "sort_count",
174
+ "cardinality"
175
+ ],
176
+ "printedPages": [
177
+ 1,
178
+ 2
179
+ ],
180
+ "workedExampleFa": "دو کارت گرد و سه کارت چهارگوش میچینیم. میگویم «فعلاً فقط کارتهای گرد را میشمارم». هر کارت گرد را یکبار به سمت دیگر میبرم و میگویم «یک، دو». سپس میگویم «دو کارت گرد داریم»؛ کارتهای چهارگوش را در شمارش این دسته وارد نمیکنم.",
181
+ "guidedPracticeFa": "دو تا پنج کارت بزرگ و آشنا آماده کن. بزرگسال یک دسته را نام ببرد و فقط برای شروع یادآوری کند که هر کارت یک اشاره و یک واژه میگیرد؛ پاسخ را از قبل نگوید.",
182
+ "independentPracticeFa": "خودت از میان چند شکل، یک دسته همنوع انتخاب کن؛ ابتدا بگو قرار است چه چیزی را بشماری، بعد تعداد را بگو. مجبور نیستی رقم بنویسی.",
183
+ "successEvidenceFa": "انتخاب درست دسته، یکبار شمردن هر عضو و گفتن تعداد کل؛ مشاهده ساختگی یا تایمر این رفتار را تأیید نمیکند.",
184
+ "metacognitivePromptFa": "چطور مطمئن شدی چیزی جا نیفتاده یا دوبار شمرده نشده؟"
185
+ },
186
+ {
187
+ "id": "one_object_one_cell",
188
+ "titleFa": "از کارت به خانههای نشانهدار",
189
+ "objectiveIds": [
190
+ "quantity_representation"
191
+ ],
192
+ "printedPages": [
193
+ 3
194
+ ],
195
+ "workedExampleFa": "سه کارت روی میز است و پنج خانه روی یک کاغذ داریم. برای هر کارت فقط یک خانه علامت میزنم. سه خانه علامتدار و دو خانه خالی میماند. میگویم «این سه خانه، سه کارت را نشان میدهند».",
196
+ "guidedPracticeFa": "با دو کارت، هر کارت را کنار یک خانه بگذار و همان خانه را علامت بزن. از کودک بپرس خانه خالی چه معنایی دارد؛ لازم نیست مفهوم عدد صفر را آموزش بدهی.",
197
+ "independentPracticeFa": "برای چهار کارت روی کاغذ خودت پنج خانه بکش و به تعداد کارتها علامت بزن؛ سپس دوباره با جفتکردن بررسی کن.",
198
+ "successEvidenceFa": "تعداد خانههای علامتدار دقیقاً برابر تعداد کارتها؛ توضیح پیوند یکبهیک."
199
+ },
200
+ {
201
+ "id": "repeat_and_explain",
202
+ "titleFa": "بخش تکراری الگو را پیدا کن",
203
+ "objectiveIds": [
204
+ "pattern"
205
+ ],
206
+ "printedPages": [
207
+ 4,
208
+ 5
209
+ ],
210
+ "workedExampleFa": "یک کارت گرد، یک کارت چهارگوش؛ دوباره یک گرد، یک چهارگوش. آغاز ردیف را با برچسب مشخص میکنم و هر جفت را کنار هم نشان میدهم. میگویم «بخش گردـچهارگوش تکرار میشود»؛ پس بعد از گرد، چهارگوش میآید.",
211
+ "guidedPracticeFa": "دو بخش «گردـگردـمثلث» بساز. هر بخش را با فاصله یا کادر مشخص کن؛ کودک بخش تازه را با کمک جزئی بچیند.",
212
+ "independentPracticeFa": "یک ردیف تکراری و یک ردیف نامنظم با کارتهای تازه بساز. کودک بخش تکراری ردیف درست را نشان دهد، قاعده را به زبان خودش بگوید و دو کارت دیگر اضافه کند.",
213
+ "successEvidenceFa": "قاعده توضیح داده میشود و ادامه با همان قاعده سازگار است؛ حدس یک شکل بهتنهایی کافی نیست.",
214
+ "accessibilityNoteFa": "رنگ بهتنهایی حامل اطلاعات نباشد؛ شکل و نام هم مشخص باشد. جهت آغاز ردیف صریح است، به LTR/RTL مبهم تکیه نشود."
215
+ },
216
+ {
217
+ "id": "equal_groups",
218
+ "titleFa": "نوع یا فاصله عوض میشود، تعداد نه",
219
+ "objectiveIds": [
220
+ "same_quantity",
221
+ "cardinality"
222
+ ],
223
+ "printedPages": [
224
+ 6
225
+ ],
226
+ "workedExampleFa": "سه کارت کوچک و سه کارت بزرگ را جفت میکنم. برای هر کوچک یک بزرگ هست و چیزی اضافه نمیماند؛ پس همتعدادند. سپس کارتهای بزرگ را با فاصله میچینم؛ هنوز سه جفت برقرار است.",
227
+ "guidedPracticeFa": "دو کارت گرد و دو کارت مثلث را جفت کن. سپس یک مثلث اضافه کن و از کودک بخواه کارت بدون جفت را نشان دهد.",
228
+ "independentPracticeFa": "میان دستههای دو، سه و چهارکارت، دسته همتعداد با سه شیء آشنا را پیدا کن و با جفتکردن دلیل بیاور.",
229
+ "successEvidenceFa": "همتعداد بودن از شمارش یا تناظر بررسی میشود، نه اندازه ظاهری."
230
+ },
231
+ {
232
+ "id": "show_in_two_ways",
233
+ "titleFa": "یک تعداد را به دو روش نشان بده",
234
+ "objectiveIds": [
235
+ "flexible_representation",
236
+ "quantity_representation"
237
+ ],
238
+ "printedPages": [
239
+ 7
240
+ ],
241
+ "workedExampleFa": "سه انگشت باز را میشمارم؛ بعد سه انگشت دیگر را باز میکنم. انتخاب انگشتها عوض شده ولی تعداد سه است. اگر دستورزی راحت نیست، سه کارت را یکبار در ردیف و یکبار در مثلث میچینم.",
242
+ "guidedPracticeFa": "کودک دو انگشت یا دو کارت را نشان دهد؛ بزرگسال بپرسد «راه دیگری هم میبینی؟» و فرصت فکر بدهد.",
243
+ "independentPracticeFa": "سه را با دو نمایش متفاوت نشان بده؛ هر نمایش را با شمارش بررسی کن.",
244
+ "successEvidenceFa": "هر دو نمایش یک تعداد دارند؛ توانایی حرکتی دست شرط قبولی نیست."
245
+ },
246
+ {
247
+ "id": "retrieve_and_transfer",
248
+ "titleFa": "از حافظه کمک بگیر و در موقعیت تازه امتحان کن",
249
+ "objectiveIds": [
250
+ "sort_count",
251
+ "quantity_representation",
252
+ "same_quantity",
253
+ "pattern",
254
+ "flexible_representation"
255
+ ],
256
+ "printedPages": [
257
+ 2,
258
+ 3,
259
+ 4,
260
+ 5,
261
+ 6,
262
+ 7
263
+ ],
264
+ "workedExampleFa": "بزرگسال با صدای بلند راهبرد خود را مدل میکند: «هدفم شمردن کارتهای گرد است. اول جدا میکنم، سپس کارت شمردهشده را جابهجا میکنم، در پایان با خانهها بررسی میکنم».",
265
+ "guidedPracticeFa": "در سؤال تازه فقط راهبرد پرسیده شود؛ اگر کودک نیاز داشت، از اشیای ملموس کمک بگیرد. کمکگرفتن ثبت شود، بهعنوان پاسخ مستقل جا زده نشود.",
266
+ "independentPracticeFa": "یکی از سؤالهای بازیابی با شکلهای تازه و یکی از موقعیتهای انتقال انجام شود؛ کودک بگوید کدام راهبرد کمک کرد.",
267
+ "successEvidenceFa": "پاسخها، دلیلها و میزان کمک در چند موقعیت ثبت میشوند؛ نه ادعای تسلط یا فهم تضمینی."
268
+ }
269
+ ],
270
+ "assessmentDraft": {
271
+ "publicationStatus": "draft",
272
+ "mode": "formative_multiple_choice",
273
+ "maxQuestionsPerSittingSuggestion": 3,
274
+ "readAloudAdultSupportMustBeLabelled": true,
275
+ "questionBankCount": 10,
276
+ "questions": [
277
+ {
278
+ "id": "count_three",
279
+ "objectiveId": "sort_count",
280
+ "promptFa": "این نشانهها را یکییکی بشمار: ○ ○ ○. چند نشانه داریم؟",
281
+ "choices": [
282
+ {
283
+ "id": "a",
284
+ "textFa": "دو"
285
+ },
286
+ {
287
+ "id": "b",
288
+ "textFa": "سه"
289
+ },
290
+ {
291
+ "id": "c",
292
+ "textFa": "چهار"
293
+ }
294
+ ],
295
+ "correctChoiceId": "b",
296
+ "explanationFa": "هر نشانه یک اشاره و یک واژه میگیرد: یک، دو، سه؛ آخرین واژه «سه» تعداد کل را میگوید.",
297
+ "remediationFa": "سه کارت بزرگ را از سمت نشمرده به سمت شمرده منتقل کن؛ برای هر کارت فقط یک واژه بگو.",
298
+ "printedPages": [
299
+ 2
300
+ ]
301
+ },
302
+ {
303
+ "id": "sort_circles",
304
+ "objectiveId": "sort_count",
305
+ "promptFa": "در این ردیف فقط دایرهها را بشمار: ○ □ ○ △. چند دایره داریم؟",
306
+ "choices": [
307
+ {
308
+ "id": "a",
309
+ "textFa": "دو"
310
+ },
311
+ {
312
+ "id": "b",
313
+ "textFa": "سه"
314
+ },
315
+ {
316
+ "id": "c",
317
+ "textFa": "چهار"
318
+ }
319
+ ],
320
+ "correctChoiceId": "a",
321
+ "explanationFa": "دو دایره داریم. مربع و مثلث در دسته دایرهها نیستند؛ آنها را در این پرسش نمیشماریم.",
322
+ "remediationFa": "روی کاغذ دو دایره و دو شکل دیگر بکش. نخست دور همه دایرهها علامت بگذار، بعد فقط همان دسته را بشمار.",
323
+ "printedPages": [
324
+ 2
325
+ ]
326
+ },
327
+ {
328
+ "id": "puppet_duplicate",
329
+ "objectiveId": "sort_count",
330
+ "promptFa": "چهار کارت داریم. عروسک کارت اول را دوبار شمرده و گفته «پنج کارت». کدام کار به او کمک میکند؟",
331
+ "choices": [
332
+ {
333
+ "id": "a",
334
+ "textFa": "هر کارت را یکبار جابهجا کند و یک واژه بگوید."
335
+ },
336
+ {
337
+ "id": "b",
338
+ "textFa": "واژهها را تندتر بگوید."
339
+ },
340
+ {
341
+ "id": "c",
342
+ "textFa": "همه کارتها را دوباره دوبار بشمارد."
343
+ }
344
+ ],
345
+ "correctChoiceId": "a",
346
+ "explanationFa": "وقتی یک کارت دوبار شمرده شود، پاسخ از تعداد واقعی بیشتر میشود. یک اشاره و یک واژه برای هر کارت، از تکرار جلوگیری میکند.",
347
+ "remediationFa": "با چهار کارت، خودت نقش عروسک را بازی کن. کارت شمردهشده را کنار بگذار و درباره جاافتادن یا تکرار کارت توضیح بده.",
348
+ "printedPages": [
349
+ 2
350
+ ]
351
+ },
352
+ {
353
+ "id": "four_cells",
354
+ "objectiveId": "quantity_representation",
355
+ "promptFa": "برای چهار کارت، به ازای هر کارت یک خانه پر میکنیم. کدام ردیف درست است؟ خانه پر با ■ نشان داده شده است.",
356
+ "choices": [
357
+ {
358
+ "id": "a",
359
+ "textFa": "■ ■ □ □ □"
360
+ },
361
+ {
362
+ "id": "b",
363
+ "textFa": "■ ■ ■ □ □"
364
+ },
365
+ {
366
+ "id": "c",
367
+ "textFa": "■ ■ ■ ■ □"
368
+ }
369
+ ],
370
+ "correctChoiceId": "c",
371
+ "explanationFa": "چهار کارت به چهار خانه پر نیاز دارند. خانه خالی را در شمارش خانههای پر حساب نمیکنیم.",
372
+ "remediationFa": "چهار کارت را یکییکی بالای پنج خانه بگذار. برای هر کارت یک خانه علامت بزن؛ باید یک خانه خالی بماند.",
373
+ "printedPages": [
374
+ 3
375
+ ]
376
+ },
377
+ {
378
+ "id": "match_three",
379
+ "objectiveId": "same_quantity",
380
+ "promptFa": "سه دایره داریم: ○ ○ ○. کدام دسته همان تعداد را دارد؟",
381
+ "choices": [
382
+ {
383
+ "id": "a",
384
+ "textFa": "△ △"
385
+ },
386
+ {
387
+ "id": "b",
388
+ "textFa": "□ □ □"
389
+ },
390
+ {
391
+ "id": "c",
392
+ "textFa": "○ ○ ○ ○"
393
+ }
394
+ ],
395
+ "correctChoiceId": "b",
396
+ "explanationFa": "دسته سه مربع همتعداد سه دایره است؛ نوع شکل تعداد را تغییر نمیدهد. میتوانی هر دایره را با یک مربع جفت کنی.",
397
+ "remediationFa": "سه کارت گرد و سه کارت چهارگوش را دوتادوتا جفت کن؛ اگر هیچ کارت اضافه نماند، تعداد دو دسته برابر است.",
398
+ "printedPages": [
399
+ 6
400
+ ]
401
+ },
402
+ {
403
+ "id": "spread_count",
404
+ "objectiveId": "cardinality",
405
+ "promptFa": "چهار کارت کنار هم است. فقط فاصله کارتها را بیشتر میکنیم و هیچ کارتی اضافه یا کم نمیکنیم. حالا چند کارت داریم؟",
406
+ "choices": [
407
+ {
408
+ "id": "a",
409
+ "textFa": "سه"
410
+ },
411
+ {
412
+ "id": "b",
413
+ "textFa": "چهار"
414
+ },
415
+ {
416
+ "id": "c",
417
+ "textFa": "پنج"
418
+ }
419
+ ],
420
+ "correctChoiceId": "b",
421
+ "explanationFa": "جای کارتها عوض شده، اما هیچ کارتی اضافه یا برداشته نشده است؛ هنوز چهار کارت داریم.",
422
+ "remediationFa": "چهار کارت را ابتدا کنار هم و بعد دور از هم بگذار. هر بار همه را یکبار بشمار و درباره یکسان ماندن تعداد توضیح بده.",
423
+ "printedPages": [
424
+ 2,
425
+ 6
426
+ ]
427
+ },
428
+ {
429
+ "id": "pattern_ab",
430
+ "objectiveId": "pattern",
431
+ "promptFa": "الگو از دایره شروع میشود و به ترتیب «دایره، مثلث» تکرار میشود: ○ △ ○ △ ○ … . شکل بعدی چیست؟",
432
+ "choices": [
433
+ {
434
+ "id": "a",
435
+ "textFa": "دایره"
436
+ },
437
+ {
438
+ "id": "b",
439
+ "textFa": "مثلث"
440
+ },
441
+ {
442
+ "id": "c",
443
+ "textFa": "مربع"
444
+ }
445
+ ],
446
+ "correctChoiceId": "b",
447
+ "explanationFa": "بخش تکراری، یک دایره و یک مثلث است. بعد از دایره، مثلث میآید؛ از همان ترتیب استفاده میکنیم.",
448
+ "remediationFa": "با کارتهای دارای شکل، هر جفت دایرهـمثلث را جدا کن و بلند بگو. بعد یک جفت تازه بساز.",
449
+ "printedPages": [
450
+ 4,
451
+ 5,
452
+ 7
453
+ ]
454
+ },
455
+ {
456
+ "id": "pattern_aab",
457
+ "objectiveId": "pattern",
458
+ "promptFa": "این ترتیب از سمت آغاز نوشتهشده تکرار میشود: «مربع، مربع، مثلث | مربع، مربع، مثلث | …». در آغاز بخش بعد چه شکلی میآید؟",
459
+ "choices": [
460
+ {
461
+ "id": "a",
462
+ "textFa": "مثلث"
463
+ },
464
+ {
465
+ "id": "b",
466
+ "textFa": "دایره"
467
+ },
468
+ {
469
+ "id": "c",
470
+ "textFa": "مربع"
471
+ }
472
+ ],
473
+ "correctChoiceId": "c",
474
+ "explanationFa": "بخش تکراری دو مربع و یک مثلث است؛ هر بخش تازه با مربع آغاز میشود. قاعده، یکیدرمیان نیست.",
475
+ "remediationFa": "شش کارت بساز و آنها را در دو دسته «مربع، مربع، مثلث» بچین. هر دسته را یک بخش بنام و بخش سوم را خودت بساز.",
476
+ "printedPages": [
477
+ 4,
478
+ 5,
479
+ 7
480
+ ]
481
+ },
482
+ {
483
+ "id": "fingers_three",
484
+ "objectiveId": "flexible_representation",
485
+ "promptFa": "نیما سه انگشت را نشان میدهد. سارا هم سه انگشت دیگر را باز کرده است. آیا میتوانند تعداد یکسانی را با انگشتهای متفاوت نشان بدهند؟",
486
+ "choices": [
487
+ {
488
+ "id": "a",
489
+ "textFa": "بله؛ تعداد انگشتهای باز مهم است."
490
+ },
491
+ {
492
+ "id": "b",
493
+ "textFa": "نه؛ باید دقیقاً همان انگشتها باز باشند."
494
+ }
495
+ ],
496
+ "correctChoiceId": "a",
497
+ "explanationFa": "اگر هر نفر سه انگشت باز داشته باشد، تعداد هر دو سه است؛ انتخاب انگشتها میتواند متفاوت باشد.",
498
+ "remediationFa": "اگر استفاده از دست برایت راحت است، سه انگشت را به دو روش نشان بده. در غیر این صورت سه کارت را به دو آرایش بچین؛ هر آرایش را بشمار.",
499
+ "printedPages": [
500
+ 7
501
+ ]
502
+ },
503
+ {
504
+ "id": "explain_same",
505
+ "objectiveId": "same_quantity",
506
+ "promptFa": "سه کارت کوچک و سه کارت بزرگ داریم. کدام دلیل نشان میدهد دو دسته همتعداد هستند؟",
507
+ "choices": [
508
+ {
509
+ "id": "a",
510
+ "textFa": "کارتهای بزرگ جای بیشتری میگیرند."
511
+ },
512
+ {
513
+ "id": "b",
514
+ "textFa": "میتوان هر کارت کوچک را با یک کارت بزرگ جفت کرد و هیچ کارت اضافه نماند."
515
+ },
516
+ {
517
+ "id": "c",
518
+ "textFa": "رنگ هر دو دسته باید یکسان باشد."
519
+ }
520
+ ],
521
+ "correctChoiceId": "b",
522
+ "explanationFa": "یک جفت برای هر کارت و بدون کارت اضافه، برابری تعداد را نشان میدهد. بزرگی، رنگ و فاصله شرط همتعداد بودن نیستند.",
523
+ "remediationFa": "سه کارت کوچک و سه کارت بزرگ را کنار هم جفت کن. سپس یک کارت بزرگ اضافه کن و توضیح بده چرا دیگر همتعداد نیستند.",
524
+ "printedPages": [
525
+ 6
526
+ ]
527
+ }
528
+ ],
529
+ "resultInterpretationFa": "پاسخ انتخابی یک نشانه محدود از یادگیری است. حدس، کمک بزرگسال و مهارت خواندن میتواند بر نتیجه اثر بگذارد. پاسخ صحیح یکباره مساوی تسلط نیست.",
530
+ "noPassingThresholdClaim": true
531
+ },
532
+ "retrievalDraft": {
533
+ "publicationStatus": "draft",
534
+ "questions": [
535
+ {
536
+ "id": "recall_count",
537
+ "objectiveId": "sort_count",
538
+ "promptFa": "بدون نگاه به پاسخ قبلی، این دسته تازه را بشمار: □ □ □ □. چند مربع است؟",
539
+ "choices": [
540
+ {
541
+ "id": "a",
542
+ "textFa": "سه"
543
+ },
544
+ {
545
+ "id": "b",
546
+ "textFa": "چهار"
547
+ },
548
+ {
549
+ "id": "c",
550
+ "textFa": "پنج"
551
+ }
552
+ ],
553
+ "correctChoiceId": "b",
554
+ "explanationFa": "چهار مربع داریم؛ هر مربع فقط یکبار شمرده میشود.",
555
+ "remediationFa": "یک مربع را پس از شمردن با مداد علامت بزن تا جا نیفتد یا دوبار شمرده نشود.",
556
+ "printedPages": [
557
+ 2
558
+ ]
559
+ },
560
+ {
561
+ "id": "recall_pattern",
562
+ "objectiveId": "pattern",
563
+ "promptFa": "الگو با مثلث شروع شده و «مثلث، مربع» تکرار میشود: △ □ △ □ △ … . شکل بعدی چیست؟",
564
+ "choices": [
565
+ {
566
+ "id": "a",
567
+ "textFa": "مربع"
568
+ },
569
+ {
570
+ "id": "b",
571
+ "textFa": "دایره"
572
+ },
573
+ {
574
+ "id": "c",
575
+ "textFa": "مثلث"
576
+ }
577
+ ],
578
+ "correctChoiceId": "a",
579
+ "explanationFa": "بخش تکراری مثلث و مربع است؛ بعد از مثلث، مربع میآید.",
580
+ "remediationFa": "دو جفت مثلثـمربع بساز و شروع الگو را با یک نشانه مشخص کن.",
581
+ "printedPages": [
582
+ 4,
583
+ 5,
584
+ 7
585
+ ]
586
+ },
587
+ {
588
+ "id": "recall_match",
589
+ "objectiveId": "same_quantity",
590
+ "promptFa": "چهار نشانه داریم: ○ ○ ○ ○. کدام دسته همتعداد است؟",
591
+ "choices": [
592
+ {
593
+ "id": "a",
594
+ "textFa": "□ □ □"
595
+ },
596
+ {
597
+ "id": "b",
598
+ "textFa": "△ △ △ △"
599
+ },
600
+ {
601
+ "id": "c",
602
+ "textFa": "○ ○"
603
+ }
604
+ ],
605
+ "correctChoiceId": "b",
606
+ "explanationFa": "چهار مثلث با چهار دایره همتعداد است؛ جفتکردن بدون کارت اضافه، راه بررسی است.",
607
+ "remediationFa": "چهار نشانه را با چهار کارت دیگر جفت کن و بعد فاصلهها را عوض کن؛ تعداد را دوباره بررسی کن.",
608
+ "printedPages": [
609
+ 6
610
+ ]
611
+ }
612
+ ],
613
+ "delayPlan": {
614
+ "firstCheckAfterDays": 1,
615
+ "secondCheckAfterDays": 7,
616
+ "laterMixedCheckAfterDays": 21,
617
+ "policyStatus": "original pilot policy; not validated optimal spacing, distinct from existing server pilot-1-or-3-days schedule"
618
+ },
619
+ "useFreshRepresentations": true,
620
+ "noReplayOfIdenticalAnswersAsMastery": true
621
+ },
622
+ "delayedTransferRubrics": [
623
+ {
624
+ "id": "serving_cards",
625
+ "objectiveIds": [
626
+ "same_quantity",
627
+ "sort_count"
628
+ ],
629
+ "promptFa": "برای سه عروسکِ اسباببازی، به هرکدام یک کارت «بشقاب» بده. چند کارت لازم است؟ بعد عروسکها را با فاصله دیگر بچین؛ توضیح بده آیا تعداد کارت لازم تغییر کرد.",
630
+ "expectedEvidenceFa": "سه کارت و یک کارت برای هر عروسک؛ توضیح حفظ تعداد بعد از تغییر فاصله.",
631
+ "ratingPolicy": "not_yet / with_support / independently_observed; adult observation is attributed, not automatic verified proof",
632
+ "noDataCollectionBeyondChosenLearningSummary": true
633
+ },
634
+ {
635
+ "id": "new_pattern",
636
+ "objectiveIds": [
637
+ "pattern"
638
+ ],
639
+ "promptFa": "با کارتهای «ستاره، دایره، دایره» دو بخش یک الگو بساز؛ یک بخش تازه اضافه کن و قاعده را به زبان خودت بگو.",
640
+ "expectedEvidenceFa": "سهعضوی بودن بخش تکراری و ادامه سازگار؛ ستارهـدایرهـدایره، سه مرتبه.",
641
+ "ratingPolicy": "not_yet / with_support / independently_observed; no diagnostic or mastery label"
642
+ },
643
+ {
644
+ "id": "count_to_marks",
645
+ "objectiveIds": [
646
+ "quantity_representation",
647
+ "flexible_representation"
648
+ ],
649
+ "promptFa": "چهار شیء آشنا را با چهار نشانه روی کاغذ نمایش بده؛ بعد همان تعداد را با کارت یا انگشتان به شیوه دیگری نشان بده.",
650
+ "expectedEvidenceFa": "یک نشانه برای هر شیء؛ هر دو نمایش چهارتایی و شرح کوتاه پیوند.",
651
+ "ratingPolicy": "not_yet / with_support / independently_observed; motor ability is not scored"
652
+ }
653
+ ],
654
+ "confidencePrompts": {
655
+ "beforeAnswerFa": "کدام مناسبتر است: هنوز مطمئن نیستم؛ کمی مطمئنم؛ میتوانم دلیلش را بگویم.",
656
+ "afterFeedbackFa": "پاسخ یا راه من کجا نیاز به تغییر داشت؟ دفعه بعد با چه روشی بررسی میکنم؟",
657
+ "noPunishmentForLowConfidence": true
658
+ },
659
+ "feedbackPolicyFa": "ابتدا فرصت پاسخ بده، سپس دلیل و تمرین اصلاحی را نشان بده. خطا را به روش حل مرتبط کن، نه هوش یا شخصیت کودک. زمان و تلاش را اثبات یادگیری معرفی نکن.",
660
+ "mediaCandidates": [
661
+ {
662
+ "hash": "Ux4Du",
663
+ "metadataUrl": "https://www.aparat.com/etc/api/video/videohash/Ux4Du",
664
+ "httpStatus": 200,
665
+ "checkedAt": "2026-10-11T16:57:52.300800+00:00",
666
+ "publicationStatus": "draft",
667
+ "titleFa": "آموزش صفحه 1 و 2 کتاب ریاضی اول دبستان",
668
+ "creatorName": "میکانیکی — نام نمایش کانال: آموزش دروس کلاس اول و دوم دبستان",
669
+ "creatorUrl": "https://www.aparat.com/MMikaniki",
670
+ "durationSeconds": 693,
671
+ "publishedDateFa": "22 شهریور 1399 13:34",
672
+ "providerCostType": "free",
673
+ "freeAccessEvidence": "Aparat metadata cost_type.type=free; full playback not performed",
674
+ "printedPageClaims": [
675
+ 1,
676
+ 2
677
+ ],
678
+ "officialCurrentEditionAlignment": "UNVERIFIED",
679
+ "fullVideoWatched": false,
680
+ "captionAvailability": "UNVERIFIED — no caption field exposed in fetched video metadata; absence is not proven",
681
+ "iframeUrl": "https://www.aparat.com/video/video/embed/videohash/Ux4Du/vt/frame",
682
+ "displayRights": "UNVERIFIED — creator description prohibits copying/changes; published iframe metadata is not a complete rights clearance",
683
+ "originalMetadataDescriptionReviewed": true,
684
+ "noMediaDownloaded": true
685
+ },
686
+ {
687
+ "hash": "l9713d3",
688
+ "metadataUrl": "https://www.aparat.com/etc/api/video/videohash/l9713d3",
689
+ "httpStatus": 200,
690
+ "checkedAt": "2026-10-11T16:57:53.323619+00:00",
691
+ "publicationStatus": "draft",
692
+ "titleFa": "آموزش صفحه 3 کتاب ریاضی اول دبستان",
693
+ "creatorName": "میکانیکی — نام نمایش کانال: آموزش دروس کلاس اول و دوم دبستان",
694
+ "creatorUrl": "https://www.aparat.com/MMikaniki",
695
+ "durationSeconds": 301,
696
+ "publishedDateFa": "23 شهریور 1399 12:19",
697
+ "providerCostType": "free",
698
+ "freeAccessEvidence": "Aparat metadata cost_type.type=free; full playback not performed",
699
+ "printedPageClaims": [
700
+ 3
701
+ ],
702
+ "officialCurrentEditionAlignment": "UNVERIFIED",
703
+ "fullVideoWatched": false,
704
+ "captionAvailability": "UNVERIFIED — no caption field exposed in fetched video metadata; absence is not proven",
705
+ "iframeUrl": "https://www.aparat.com/video/video/embed/videohash/l9713d3/vt/frame",
706
+ "displayRights": "UNVERIFIED — creator description prohibits copying/changes; published iframe metadata is not a complete rights clearance",
707
+ "originalMetadataDescriptionReviewed": true,
708
+ "noMediaDownloaded": true
709
+ },
710
+ {
711
+ "hash": "y93e145",
712
+ "metadataUrl": "https://www.aparat.com/etc/api/video/videohash/y93e145",
713
+ "httpStatus": 200,
714
+ "checkedAt": "2026-10-11T16:57:53.990053+00:00",
715
+ "publicationStatus": "draft",
716
+ "titleFa": "آموزش صفحه 4 و 5 کتاب ریاضی اول دبستان",
717
+ "creatorName": "میکانیکی — نام نمایش کانال: آموزش دروس کلاس اول و دوم دبستان",
718
+ "creatorUrl": "https://www.aparat.com/MMikaniki",
719
+ "durationSeconds": 551,
720
+ "publishedDateFa": "24 شهریور 1399 13:16",
721
+ "providerCostType": "free",
722
+ "freeAccessEvidence": "Aparat metadata cost_type.type=free; full playback not performed",
723
+ "printedPageClaims": [
724
+ 4,
725
+ 5
726
+ ],
727
+ "officialCurrentEditionAlignment": "UNVERIFIED",
728
+ "fullVideoWatched": false,
729
+ "captionAvailability": "UNVERIFIED — no caption field exposed in fetched video metadata; absence is not proven",
730
+ "iframeUrl": "https://www.aparat.com/video/video/embed/videohash/y93e145/vt/frame",
731
+ "displayRights": "UNVERIFIED — creator description prohibits copying/changes; published iframe metadata is not a complete rights clearance",
732
+ "originalMetadataDescriptionReviewed": true,
733
+ "noMediaDownloaded": true
734
+ },
735
+ {
736
+ "hash": "x95j64m",
737
+ "metadataUrl": "https://www.aparat.com/etc/api/video/videohash/x95j64m",
738
+ "httpStatus": 200,
739
+ "checkedAt": "2026-10-11T16:57:55.256622+00:00",
740
+ "publicationStatus": "draft",
741
+ "titleFa": "آموزش صفحه 6 و 7 کتاب ریاضی اول دبستان",
742
+ "creatorName": "میکانیکی — نام نمایش کانال: آموزش دروس کلاس اول و دوم دبستان",
743
+ "creatorUrl": "https://www.aparat.com/MMikaniki",
744
+ "durationSeconds": 449,
745
+ "publishedDateFa": "25 شهریور 1399 12:57",
746
+ "providerCostType": "free",
747
+ "freeAccessEvidence": "Aparat metadata cost_type.type=free; full playback not performed",
748
+ "printedPageClaims": [
749
+ 6,
750
+ 7
751
+ ],
752
+ "officialCurrentEditionAlignment": "UNVERIFIED",
753
+ "fullVideoWatched": false,
754
+ "captionAvailability": "UNVERIFIED — no caption field exposed in fetched video metadata; absence is not proven",
755
+ "iframeUrl": "https://www.aparat.com/video/video/embed/videohash/x95j64m/vt/frame",
756
+ "displayRights": "UNVERIFIED — creator description prohibits copying/changes; published iframe metadata is not a complete rights clearance",
757
+ "originalMetadataDescriptionReviewed": true,
758
+ "noMediaDownloaded": true
759
+ }
760
+ ],
761
+ "internationalEvidence": [
762
+ {
763
+ "url": "https://educationendowmentfoundation.org.uk/education-evidence/guidance-reports/early-maths",
764
+ "applicationFa": "فعالیت کوتاه هدفمند، شناخت پیشدانسته و زبان شمارش در موقعیت روزمره."
765
+ },
766
+ {
767
+ "url": "https://educationendowmentfoundation.org.uk/early-years/maths/use-manipulatives-and-representations-to-develop-understanding",
768
+ "applicationFa": "پیوند صریح ابزار ملموس و نمایش؛ انگشتان/کارتهای جایگزین؛ توجه به عامل حواسپرتی ابزار."
769
+ },
770
+ {
771
+ "url": "https://ies.ed.gov/ncee/WWC/PracticeGuide/1",
772
+ "applicationFa": "مثال حلشده همراه حل مستقل، بازیابی، مرور با فاصله، توضیح راهبرد؛ فاصله عددی این پایلوت مصداق اثباتشده منبع نیست."
773
+ }
774
+ ],
775
+ "remainingGates": [
776
+ "licensed_or_qualified_grade1_educator_review",
777
+ "independent_question_and_distractor_review",
778
+ "all_video_minutes_watched_and_logged",
779
+ "current_edition_video_alignment",
780
+ "creator_and_textbook_rights_review",
781
+ "real_child_pilot_with_required_consent",
782
+ "reading_and_motor_accessibility_device_review",
783
+ "actual_Android_Safari_playback_and_iran_reachability",
784
+ "learning_effectiveness_and_delayed_transfer_observation"
785
+ ],
786
+ "privacyLimits": {
787
+ "noPrivateChatsNotesHealthOrAbuseDisclosureCollection": true,
788
+ "noExternalAiVoice": true,
789
+ "feedbackOnlyExplicitChosenConsent": true,
790
+ "serverPrivateAttemptsRemainOwnerOnly": true
791
+ },
792
+ "licensingNoteFa": "تمام مثالها و پرسشهای این فایل بهصورت اصلی برای لایفگاید نوشته شدهاند؛ صفحات/تصاویر/تمرینهای کتاب یا فیلم کپی نشدهاند. استناد به صفحه، مجوز بازنشر اجزای کتاب یا clearance حقوق نشر فیلم نیست."
793
+}
backend/migrations/0016_content_review.sql
new
+65
@@ -0,0 +1,65 @@
1
+begin;
2
+
3
+-- Explicit content-operation capabilities are independent of family/profile/JWT roles.
4
+-- No default grants and no application HTTP grant endpoint.
5
+create table content_capability_grant (
6
+ user_id uuid not null references app_user(id) on delete cascade,
7
+ permission text not null check(permission in ('feedback.read','feedback.review','brief.prepare')),
8
+ granted_at timestamptz not null default now(),
9
+ expires_at timestamptz not null,
10
+ revoked_at timestamptz,
11
+ primary key(user_id,permission),
12
+ check(expires_at>granted_at)
13
+);
14
+
15
+-- Operator-only privilege history contains no copied feedback or contact details.
16
+create table content_capability_audit (
17
+ id uuid primary key default gen_random_uuid(),
18
+ target_user_id uuid not null references app_user(id) on delete cascade,
19
+ permission text not null check(permission in ('feedback.read','feedback.review','brief.prepare')),
20
+ action text not null check(action in ('grant','revoke')),
21
+ occurred_at timestamptz not null default now(),
22
+ expires_at timestamptz
23
+);
24
+
25
+create table content_review_brief (
26
+ id uuid primary key default gen_random_uuid(),
27
+ actor_user_id uuid not null references app_user(id) on delete cascade,
28
+ source_count integer not null check(source_count between 1 and 20),
29
+ created_at timestamptz not null default now()
30
+);
31
+create table content_review_brief_source (
32
+ brief_id uuid not null references content_review_brief(id) on delete cascade,
33
+ feedback_id uuid not null references learning_content_feedback(id) on delete cascade,
34
+ feedback_version integer not null check(feedback_version>0),
35
+ primary key(brief_id,feedback_id)
36
+);
37
+
38
+-- Store only references/hashes: retries always reconstruct CURRENT consenting state.
39
+create table content_review_mutation (
40
+ actor_user_id uuid not null references app_user(id) on delete cascade,
41
+ mutation_id uuid not null,
42
+ operation text not null check(operation in ('review','brief')),
43
+ request_hash text not null check(request_hash~'^[0-9a-f]{64}$'),
44
+ feedback_id uuid references learning_content_feedback(id) on delete cascade,
45
+ brief_id uuid references content_review_brief(id) on delete cascade,
46
+ accepted_at timestamptz not null default now(),
47
+ primary key(actor_user_id,mutation_id),
48
+ check((operation='review' and feedback_id is not null and brief_id is null)
49
+ or (operation='brief' and feedback_id is null and brief_id is not null))
50
+);
51
+create table content_review_audit (
52
+ id uuid primary key default gen_random_uuid(),
53
+ actor_user_id uuid not null references app_user(id) on delete cascade,
54
+ feedback_id uuid not null references learning_content_feedback(id) on delete cascade,
55
+ before_status text not null check(before_status in ('received','triaged','planned','declined')),
56
+ after_status text not null check(after_status in ('triaged','planned','declined')),
57
+ before_version integer not null check(before_version>0),
58
+ after_version integer not null check(after_version=before_version+1),
59
+ occurred_at timestamptz not null default now()
60
+);
61
+create index content_review_visible_idx on learning_content_feedback(status,created_at desc,id desc)
62
+ where withdrawn_at is null and share_with_content_team=true;
63
+create index content_review_brief_feedback_idx on content_review_brief_source(feedback_id);
64
+
65
+commit;
backend/migrations/0017_learning_goal_mutations.sql
new
+18
@@ -0,0 +1,18 @@
1
+alter table learning_goal add column version integer not null default 1 check(version > 0);
2
+alter table learning_goal add column archived_at timestamptz;
3
+update learning_goal set archived_at=updated_at where status='archived';
4
+alter table learning_goal add constraint learning_goal_archive_state check((status='archived')=(archived_at is not null));
5
+alter table learning_goal add constraint learning_goal_id_owner_unique unique(id,owner_user_id);
6
+
7
+create table learning_goal_mutation (
8
+ owner_user_id uuid not null references app_user(id) on delete cascade,
9
+ mutation_id uuid not null,
10
+ goal_id uuid not null,
11
+ operation text not null check(operation in ('create','update','archive')),
12
+ request_hash text not null check(request_hash ~ '^[a-f0-9]{64}$'),
13
+ applied_version integer not null check(applied_version > 0),
14
+ accepted_at timestamptz not null default now(),
15
+ primary key(owner_user_id,mutation_id),
16
+ foreign key(goal_id,owner_user_id) references learning_goal(id,owner_user_id) on delete cascade
17
+);
18
+create index learning_goal_mutation_goal_idx on learning_goal_mutation(owner_user_id,goal_id);
backend/migrations/0018_family_lifecycle.sql
new
+54
@@ -0,0 +1,54 @@
1
+begin;
2
+
3
+alter table family_membership add column version integer not null default 1 check(version>0),
4
+ add column updated_at timestamptz not null default now();
5
+update family_membership set updated_at=joined_at;
6
+create function membership_lifecycle_revision() returns trigger language plpgsql as $$
7
+begin
8
+ if new.role is distinct from old.role or new.is_admin is distinct from old.is_admin
9
+ or new.ended_at is distinct from old.ended_at or new.joined_at is distinct from old.joined_at then
10
+ new.version:=old.version+1;
11
+ new.updated_at:=statement_timestamp();
12
+ else
13
+ new.version:=old.version;
14
+ new.updated_at:=old.updated_at;
15
+ end if;
16
+ return new;
17
+end $$;
18
+create trigger family_membership_lifecycle_revision before update on family_membership
19
+ for each row execute function membership_lifecycle_revision();
20
+
21
+alter table family_invitation add column version integer not null default 1 check(version>0),
22
+ add column updated_at timestamptz not null default now();
23
+update family_invitation set updated_at=created_at;
24
+create function invitation_lifecycle_revision() returns trigger language plpgsql as $$
25
+begin
26
+ if new.status is distinct from old.status or new.expires_at is distinct from old.expires_at
27
+ or new.intended_role is distinct from old.intended_role or new.intended_theme is distinct from old.intended_theme
28
+ or new.invited_email_normalized is distinct from old.invited_email_normalized
29
+ or new.invited_phone_normalized is distinct from old.invited_phone_normalized
30
+ or new.invited_by is distinct from old.invited_by or new.token_digest is distinct from old.token_digest
31
+ or new.accepted_by is distinct from old.accepted_by or new.accepted_at is distinct from old.accepted_at then
32
+ new.version:=old.version+1;
33
+ new.updated_at:=statement_timestamp();
34
+ else
35
+ new.version:=old.version;
36
+ new.updated_at:=old.updated_at;
37
+ end if;
38
+ return new;
39
+end $$;
40
+create trigger family_invitation_lifecycle_revision before update on family_invitation
41
+ for each row execute function invitation_lifecycle_revision();
42
+
43
+create table family_lifecycle_mutation (
44
+ actor_user_id uuid not null references app_user(id) on delete cascade,
45
+ mutation_id uuid not null,
46
+ family_id uuid not null references family_workspace(id) on delete cascade,
47
+ operation text not null check(operation in ('role','admin_transfer','invitation_revoke')),
48
+ request_hash text not null check(request_hash~'^[0-9a-f]{64}$'),
49
+ target_id uuid not null,
50
+ accepted_at timestamptz not null default now(),
51
+ primary key(actor_user_id,mutation_id)
52
+);
53
+
54
+commit;
backend/migrations/0019_school_lifecycle.sql
new
+123
@@ -0,0 +1,123 @@
1
+begin;
2
+
3
+alter table life_context add column version integer not null default 1 check(version>0);
4
+alter table life_context add column updated_at timestamptz not null default now();
5
+alter table academic_year add column version integer not null default 1 check(version>0);
6
+alter table academic_year add column updated_at timestamptz not null default now();
7
+alter table academic_term add column active boolean not null default true;
8
+alter table academic_term add column version integer not null default 1 check(version>0);
9
+alter table academic_term add column updated_at timestamptz not null default now();
10
+
11
+create table school_lifecycle_mutation (
12
+ owner_user_id uuid not null references app_user(id) on delete cascade,
13
+ mutation_id uuid not null,
14
+ entity_type text not null check(entity_type in('contexts','years','terms')),
15
+ entity_id uuid not null,
16
+ operation text not null check(operation in('create','update','archive')),
17
+ request_hash text not null check(char_length(request_hash)=64),
18
+ applied_version integer not null check(applied_version>0),
19
+ accepted_at timestamptz not null default now(),
20
+ primary key(owner_user_id,mutation_id)
21
+);
22
+
23
+-- The same owner-row lock is used by the new router and these guards. It
24
+-- serializes ancestor archival/date edits against the old create APIs too.
25
+create function school_lifecycle_context_guard() returns trigger language plpgsql set search_path=public,pg_catalog as $$
26
+begin
27
+ perform 1 from app_user where id=new.user_id for update;
28
+ if tg_op='UPDATE' then
29
+ if new.user_id<>old.user_id then raise exception 'school_owner_immutable' using errcode='23514'; end if;
30
+ if new.kind<>old.kind and exists(select 1 from academic_year where life_context_id=old.id) then
31
+ raise exception 'school_context_kind_in_use' using errcode='23514';
32
+ end if;
33
+ new.version=old.version+1; new.updated_at=clock_timestamp();
34
+ end if;
35
+ return new;
36
+end $$;
37
+create trigger school_lifecycle_context_guard before insert or update on life_context for each row execute function school_lifecycle_context_guard();
38
+
39
+create function school_lifecycle_year_guard() returns trigger language plpgsql set search_path=public,pg_catalog as $$
40
+declare context_row life_context;
41
+begin
42
+ perform 1 from app_user where id=new.student_user_id for update;
43
+ if tg_op='UPDATE' and (new.student_user_id<>old.student_user_id or new.life_context_id<>old.life_context_id) then
44
+ raise exception 'school_parent_immutable' using errcode='23514';
45
+ end if;
46
+ select * into context_row from life_context where id=new.life_context_id for share;
47
+ if context_row.id is null or context_row.user_id<>new.student_user_id or context_row.kind<>'student' then
48
+ raise exception 'school_parent_forbidden' using errcode='23514';
49
+ end if;
50
+ if new.active and not context_row.active then raise exception 'school_parent_inactive' using errcode='23514'; end if;
51
+ if char_length(trim(new.title)) not between 1 and 120 then raise exception 'school_invalid_title' using errcode='23514'; end if;
52
+ if tg_op='UPDATE' then
53
+ if exists(select 1 from academic_term where academic_year_id=old.id and (starts_on<new.starts_on or ends_on>new.ends_on)) then
54
+ raise exception 'school_dates_in_use' using errcode='23514';
55
+ end if;
56
+ new.version=old.version+1; new.updated_at=clock_timestamp();
57
+ end if;
58
+ return new;
59
+end $$;
60
+create trigger school_lifecycle_year_guard before insert or update on academic_year for each row execute function school_lifecycle_year_guard();
61
+
62
+create function school_lifecycle_term_guard() returns trigger language plpgsql set search_path=public,pg_catalog as $$
63
+declare year_row academic_year; context_row life_context;
64
+begin
65
+ select * into year_row from academic_year where id=new.academic_year_id;
66
+ perform 1 from app_user where id=year_row.student_user_id for update;
67
+ select * into year_row from academic_year where id=new.academic_year_id for share;
68
+ select * into context_row from life_context where id=year_row.life_context_id for share;
69
+ if tg_op='UPDATE' and new.academic_year_id<>old.academic_year_id then raise exception 'school_parent_immutable' using errcode='23514'; end if;
70
+ if year_row.id is null or context_row.id is null or context_row.user_id<>year_row.student_user_id or context_row.kind<>'student' then
71
+ raise exception 'school_parent_forbidden' using errcode='23514';
72
+ end if;
73
+ if new.active and (not year_row.active or not context_row.active) then raise exception 'school_parent_inactive' using errcode='23514'; end if;
74
+ if new.starts_on<year_row.starts_on or new.ends_on>year_row.ends_on then raise exception 'school_dates_outside_parent' using errcode='23514'; end if;
75
+ if char_length(trim(new.title)) not between 1 and 120 then raise exception 'school_invalid_title' using errcode='23514'; end if;
76
+ if tg_op='UPDATE' then
77
+ if exists(select 1 from class_session c join subject s on s.id=c.subject_id where s.academic_term_id=old.id and c.recurrence_until is not null and (c.recurrence_until<new.starts_on or c.recurrence_until>new.ends_on)) then
78
+ raise exception 'school_dates_in_use' using errcode='23514';
79
+ end if;
80
+ new.version=old.version+1; new.updated_at=clock_timestamp();
81
+ end if;
82
+ return new;
83
+end $$;
84
+create trigger school_lifecycle_term_guard before insert or update on academic_term for each row execute function school_lifecycle_term_guard();
85
+
86
+create function school_lifecycle_subject_guard() returns trigger language plpgsql set search_path=public,pg_catalog as $$
87
+declare parent_row record;
88
+begin
89
+ perform 1 from app_user where id=new.student_user_id for update;
90
+ if tg_op='UPDATE' and new.student_user_id<>old.student_user_id then raise exception 'school_owner_immutable' using errcode='23514'; end if;
91
+ select t.active as term_active,y.active as year_active,l.active as context_active,y.student_user_id,l.user_id,l.kind
92
+ into parent_row from academic_term t join academic_year y on y.id=t.academic_year_id join life_context l on l.id=y.life_context_id where t.id=new.academic_term_id for share of t,y,l;
93
+ if not found or parent_row.student_user_id<>new.student_user_id or parent_row.user_id<>new.student_user_id then
94
+ raise exception 'school_parent_forbidden' using errcode='23514';
95
+ end if;
96
+ if new.archived_at is null and (not parent_row.term_active or not parent_row.year_active or not parent_row.context_active or parent_row.kind<>'student') then
97
+ raise exception 'school_parent_inactive' using errcode='23514';
98
+ end if;
99
+ return new;
100
+end $$;
101
+create trigger school_lifecycle_subject_guard before insert or update on subject for each row execute function school_lifecycle_subject_guard();
102
+
103
+create function school_lifecycle_class_guard() returns trigger language plpgsql set search_path=public,pg_catalog as $$
104
+declare parent_row record; owner_id uuid;
105
+begin
106
+ select student_user_id into owner_id from subject where id=new.subject_id;
107
+ perform 1 from app_user where id=owner_id for update;
108
+ select s.archived_at,t.active as term_active,y.active as year_active,l.active as context_active,t.starts_on,t.ends_on
109
+ into parent_row from subject s join academic_term t on t.id=s.academic_term_id join academic_year y on y.id=t.academic_year_id join life_context l on l.id=y.life_context_id where s.id=new.subject_id for share of s,t,y,l;
110
+ if not found then raise exception 'school_parent_forbidden' using errcode='23514'; end if;
111
+ if new.archived_at is null then
112
+ if parent_row.archived_at is not null or not parent_row.term_active or not parent_row.year_active or not parent_row.context_active then
113
+ raise exception 'school_parent_inactive' using errcode='23514';
114
+ end if;
115
+ if new.recurrence_until is not null and (new.recurrence_until<parent_row.starts_on or new.recurrence_until>parent_row.ends_on) then
116
+ raise exception 'school_dates_outside_parent' using errcode='23514';
117
+ end if;
118
+ end if;
119
+ return new;
120
+end $$;
121
+create trigger school_lifecycle_class_guard before insert or update on class_session for each row execute function school_lifecycle_class_guard();
122
+
123
+commit;
backend/migrations/0020_content_publication_audit.sql
new
+20
@@ -0,0 +1,20 @@
1
+begin;
2
+
3
+-- Identifier/hash-only journal. No chosen feedback, reviewer prose or private
4
+-- learner data is copied. HTTP runtime receives SELECT only on this table.
5
+create table content_publication_audit (
6
+ mutation_id uuid primary key,
7
+ entity_type text not null check(entity_type in ('video','assessment')),
8
+ entity_id uuid not null,
9
+ operation text not null check(operation in ('publish','withdraw','draft_assessment')),
10
+ request_hash text not null check(request_hash ~ '^[a-f0-9]{64}$'),
11
+ applied_content_hash text not null check(applied_content_hash ~ '^[a-f0-9]{64}$'),
12
+ applied_context_hash text not null check(applied_context_hash ~ '^[a-f0-9]{64}$'),
13
+ applied_version integer check(applied_version is null or applied_version>0),
14
+ applied_status text not null check(applied_status in ('draft','published','withdrawn')),
15
+ operator_role text not null,
16
+ accepted_at timestamptz not null default statement_timestamp(),
17
+ synthetic_only boolean not null default true check(synthetic_only)
18
+);
19
+
20
+commit;
backend/package-lock.json
+2
-2
@@ -1,12 +1,12 @@
1
{
2
"name": "lifemate-backend",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
"lockfileVersion": 3,
5
"requires": true,
6
"packages": {
7
"": {
8
"name": "lifemate-backend",
9
- "version": "0.6.0",
9
+ "version": "0.7.0",
10
"dependencies": {
11
"argon2": "^0.44.0",
12
"cors": "^2.8.5",
backend/package.json
+1
-1
@@ -1,7 +1,7 @@
1
{
2
"name": "lifemate-backend",
3
"private": true,
4
- "version": "0.6.0",
4
+ "version": "0.7.0",
5
"type": "module",
6
"scripts": {
7
"start": "node src/entrypoint.js",
backend/scripts/db-role-policy.js
+14
-2
@@ -10,8 +10,11 @@ export const applicationTables = [
10
'auth_token', 'class_session', 'curriculum_subject', 'education_profile',
11
'family_invitation', 'family_membership', 'family_workspace', 'guardian_relationship',
12
'iran_calendar_event', 'learning_checkin', 'learning_goal', 'life_context',
13
+ 'learning_goal_mutation', 'family_lifecycle_mutation', 'school_lifecycle_mutation',
14
'learning_unit', 'learning_video_resource', 'learning_progress', 'learning_progress_mutation',
15
'learning_content_feedback',
16
+ 'content_capability_grant', 'content_capability_audit', 'content_publication_audit', 'content_review_audit',
17
+ 'content_review_mutation', 'content_review_brief', 'content_review_brief_source',
18
'learning_assessment', 'learning_assessment_attempt', 'learning_review_schedule',
19
'menstrual_cycle_entry', 'notification_outbox', 'notification_preference',
20
'plan_item', 'profile', 'reminder', 'schema_migration', 'sharing_grant',
@@ -30,12 +33,20 @@ export const applicationFunctions = [
33
'plan_item_revision()', 'revoke_changed_plan_item_grants()',
34
'validate_learning_publication()',
35
'validate_learning_assessment_publication()',
36
+ 'membership_lifecycle_revision()', 'invitation_lifecycle_revision()',
37
+ 'school_lifecycle_context_guard()', 'school_lifecycle_year_guard()',
38
+ 'school_lifecycle_term_guard()', 'school_lifecycle_subject_guard()',
39
+ 'school_lifecycle_class_guard()',
40
'revoke_ended_membership_grants()', 'plan_item_legacy_activity()',
41
];
42
export const roleNames = Object.freeze({ api: 'lifeguide_api', migrator: 'lifeguide_migrator', backup: 'lifeguide_backup' });
43
// Only the separate migrator/importer can change reviewed teaching material.
44
export const readOnlyCatalogTables = new Set(['curriculum_subject', 'textbook_catalog',
38
- 'learning_unit', 'learning_video_resource', 'learning_assessment']);
45
+ 'learning_unit', 'learning_video_resource', 'learning_assessment',
46
+ 'content_capability_grant', 'content_capability_audit', 'content_publication_audit']);
47
+export const appendOnlyContentTables = new Set(['content_review_audit', 'content_review_mutation',
48
+ 'content_review_brief', 'content_review_brief_source',
49
+ 'learning_goal_mutation', 'family_lifecycle_mutation', 'school_lifecycle_mutation']);
50
const ident = (value) => `"${String(value).replaceAll('"', '""')}"`;
51
export function validateRoles(env) {
52
const configured = { api: env.API_DB_USER ?? roleNames.api, migrator: env.MIGRATOR_DB_USER ?? roleNames.migrator, backup: env.BACKUP_DB_USER ?? roleNames.backup };
@@ -209,7 +220,8 @@ export async function reconcileGrants(client, env = process.env) {
220
await client.query(`GRANT SELECT ON SEQUENCE ${relation} TO ${ident(roles.backup)}`);
221
} else {
222
if (object.name !== 'schema_migration') {
212
- const privileges = readOnlyCatalogTables.has(object.name) || !applicationTables.includes(object.name) ? 'SELECT' : 'SELECT,INSERT,UPDATE,DELETE';
223
+ const privileges = readOnlyCatalogTables.has(object.name) || !applicationTables.includes(object.name) ? 'SELECT' :
224
+ appendOnlyContentTables.has(object.name) ? 'SELECT,INSERT' : 'SELECT,INSERT,UPDATE,DELETE';
225
await client.query(`GRANT ${privileges} ON TABLE ${relation} TO ${ident(roles.api)}`);
226
}
227
await client.query(`GRANT SELECT ON TABLE ${relation} TO ${ident(roles.backup)}`);
backend/scripts/manage-content-capabilities.js
new
+82
@@ -0,0 +1,82 @@
1
+// No remote/live permission changes: this packet supports explicitly named,
2
+// local synthetic fixtures only. No default admin, family role or HTTP grant.
3
+import crypto from 'node:crypto';
4
+import pg from 'pg';
5
+import { fileURLToPath } from 'node:url';
6
+import path from 'node:path';
7
+
8
+const scopes=new Set(['feedback.read','feedback.review','brief.prepare']);
9
+const uuid=value=>typeof value==='string'&&/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(value);
10
+
11
+export function normalizeCapabilityOperation(args) {
12
+ const [action,userId,permission,expiresAt,...extra]=args;
13
+ if(!['grant','revoke'].includes(action)||!uuid(userId)||!scopes.has(permission)||extra.length||
14
+ (action==='revoke'&&expiresAt!==undefined)) return null;
15
+ if(action==='grant') {
16
+ if(typeof expiresAt!=='string'||!/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{3})?Z$/.test(expiresAt)||
17
+ !Number.isFinite(Date.parse(expiresAt))||Date.parse(expiresAt)<=Date.now()) return null;
18
+ }
19
+ return {action,userId:userId.toLowerCase(),permission,expiresAt:expiresAt??null};
20
+}
21
+
22
+export function localSyntheticConnection(env) {
23
+ if(!env.CONTENT_CAPABILITY_DATABASE_URL||env.CONTENT_CAPABILITY_SYNTHETIC_ONLY!=='true') {
24
+ throw new Error('Set separate CONTENT_CAPABILITY_DATABASE_URL and CONTENT_CAPABILITY_SYNTHETIC_ONLY=true');
25
+ }
26
+ let location;
27
+ try { location=new URL(env.CONTENT_CAPABILITY_DATABASE_URL); } catch { throw new Error('Invalid operator database configuration'); }
28
+ if(!['postgres:','postgresql:'].includes(location.protocol)||
29
+ !['localhost','127.0.0.1','[::1]','::1'].includes(location.hostname)||
30
+ !(location.pathname.includes('test')||location.pathname==='/lifemate_ci'||
31
+ /^\/lifeguide_roles_(?:source|target)_[a-f0-9]{16}$/.test(location.pathname))) {
32
+ throw new Error('Capability operator refuses a nonlocal or non-test database');
33
+ }
34
+ return location.toString();
35
+}
36
+
37
+export async function manageCapability(client,operation) {
38
+ await client.query('begin');
39
+ try {
40
+ const role=(await client.query(`select current_user,
41
+ has_table_privilege(current_user,'content_capability_grant','INSERT') can_grant,
42
+ has_table_privilege(current_user,'content_capability_grant','UPDATE') can_revoke`)).rows[0];
43
+ if(['lifeguide_api','lifeguide_backup'].includes(role.current_user)||!role.can_grant||!role.can_revoke) {
44
+ throw new Error('Use separate operator/migrator credentials, never runtime/backup credentials');
45
+ }
46
+ const actor=await client.query('select id from app_user where id=$1 and disabled_at is null for update',[operation.userId]);
47
+ if(!actor.rowCount) throw new Error('Active synthetic account not found');
48
+ if(operation.action==='grant') {
49
+ if(Date.parse(operation.expiresAt)<=Date.now()) throw new Error('Grant expiry must be in the future');
50
+ await client.query(`insert into content_capability_grant(user_id,permission,expires_at)
51
+ values($1,$2,$3) on conflict(user_id,permission) do update set
52
+ granted_at=statement_timestamp(),expires_at=excluded.expires_at,revoked_at=null`,
53
+ [operation.userId,operation.permission,operation.expiresAt]);
54
+ } else {
55
+ await client.query(`update content_capability_grant set revoked_at=coalesce(revoked_at,statement_timestamp())
56
+ where user_id=$1 and permission=$2`,[operation.userId,operation.permission]);
57
+ }
58
+ await client.query(`insert into content_capability_audit(id,target_user_id,permission,action,expires_at)
59
+ values($1,$2,$3,$4,$5)`,[crypto.randomUUID(),operation.userId,operation.permission,operation.action,operation.expiresAt]);
60
+ await client.query('commit');
61
+ return {action:operation.action,permission:operation.permission,expiresAt:operation.expiresAt};
62
+ } catch(error) { await client.query('rollback').catch(()=>{}); throw error; }
63
+}
64
+
65
+if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url)) {
66
+ const operation=normalizeCapabilityOperation(process.argv.slice(2));
67
+ if(!operation) {
68
+ console.error('Usage: node scripts/manage-content-capabilities.js grant USER_UUID SCOPE ISO_UTC_EXPIRY | revoke USER_UUID SCOPE');
69
+ process.exitCode=1;
70
+ } else {
71
+ let client;
72
+ try {
73
+ client=new pg.Client({connectionString:localSyntheticConnection(process.env)});
74
+ await client.connect();
75
+ console.log(JSON.stringify({type:'synthetic_content_capability',...(await manageCapability(client,operation))}));
76
+ } catch {
77
+ // Database URLs, account IDs, passwords and raw driver errors stay private.
78
+ console.error('Capability operation rejected; check explicit synthetic configuration and separate operator privileges.');
79
+ process.exitCode=1;
80
+ } finally { if(client) await client.end().catch(()=>{}); }
81
+ }
82
+}
backend/scripts/review-learning-content.js
new
+35
@@ -0,0 +1,35 @@
1
+// This command does not contact video providers, AI, email or live services.
2
+import fs from 'node:fs/promises';
3
+import pg from 'pg';
4
+import {localContentReviewConnection,inspectLearningContent,reviewLearningContent,ContentPublicationError} from '../src/content_publication.js';
5
+
6
+const [action,first,second,...extra]=process.argv.slice(2);
7
+let client;
8
+async function operationFile(filename) {
9
+ const maximum=1024*1024,file=await fs.open(filename,'r');
10
+ try {
11
+ const details=await file.stat();
12
+ if(!details.isFile()||details.size>maximum) throw new ContentPublicationError('invalid_operation_file');
13
+ const buffer=Buffer.alloc(maximum+1);let length=0;
14
+ while(length<buffer.length) {
15
+ const {bytesRead}=await file.read(buffer,length,buffer.length-length,null);
16
+ if(!bytesRead) break;length+=bytesRead;
17
+ }
18
+ if(length>maximum) throw new ContentPublicationError('invalid_operation_file');
19
+ return JSON.parse(buffer.subarray(0,length).toString('utf8'));
20
+ } finally {await file.close();}
21
+}
22
+try {
23
+ if(extra.length||!['inspect','dry-run','apply'].includes(action)||!first||
24
+ (action==='inspect'?!second:second!==undefined)) throw new ContentPublicationError('invalid_command');
25
+ const connection=localContentReviewConnection(process.env);
26
+ const body=action==='inspect'?null:await operationFile(first);
27
+ client=new pg.Client({connectionString:connection});await client.connect();
28
+ const result=action==='inspect'?await inspectLearningContent(client,first,second):
29
+ await reviewLearningContent(client,body,{apply:action==='apply'});
30
+ console.log(JSON.stringify(result));
31
+} catch(error) {
32
+ // Do not print database URLs, raw driver errors or the chosen JSON payload.
33
+ console.error(JSON.stringify({status:'rejected',code:error instanceof ContentPublicationError?error.code:'content_operation_rejected'}));
34
+ process.exitCode=1;
35
+} finally {if(client) await client.end().catch(()=>{});}
backend/scripts/test-db-roles.js
+23
-5
@@ -70,12 +70,23 @@ async function checkPolicy(database) {
70
await denied(runtime,'DELETE FROM public.schema_migration','runtime ledger DELETE');
71
await denied(runtime,'SELECT * FROM public.schema_migration','runtime ledger SELECT unnecessary');
72
await denied(runtime,'TRUNCATE public.plan_item','runtime TRUNCATE');
73
- for(const table of ['curriculum_subject','textbook_catalog','learning_unit','learning_video_resource','learning_assessment']) {
73
+ for(const table of ['curriculum_subject','textbook_catalog','learning_unit','learning_video_resource','learning_assessment',
74
+ 'content_capability_grant','content_capability_audit','content_publication_audit']) {
75
assert.equal((await runtime.query(`SELECT count(*)::int n FROM public.${ident(table)}`)).rows.length,1);
76
await denied(runtime,`INSERT INTO public.${ident(table)} DEFAULT VALUES`,`${table}: runtime catalog INSERT`);
76
- await denied(runtime,`UPDATE public.${ident(table)} SET id=id`,`${table}: runtime catalog UPDATE/publication`);
77
+ const field=table==='content_capability_grant'?'user_id':table==='content_publication_audit'?'mutation_id':'id';
78
+ await denied(runtime,`UPDATE public.${ident(table)} SET ${field}=${field}`,`${table}: runtime catalog UPDATE/publication`);
79
await denied(runtime,`DELETE FROM public.${ident(table)}`,`${table}: runtime catalog DELETE`);
80
}
81
+ for(const table of ['content_review_audit','content_review_mutation','content_review_brief','content_review_brief_source',
82
+ 'learning_goal_mutation','family_lifecycle_mutation','school_lifecycle_mutation']) {
83
+ const field=['learning_goal_mutation','school_lifecycle_mutation'].includes(table)?'owner_user_id':
84
+ ['content_review_mutation','family_lifecycle_mutation'].includes(table)?'actor_user_id':
85
+ table==='content_review_brief_source'?'brief_id':'id';
86
+ assert.equal((await runtime.query(`SELECT count(*)::int n FROM public.${ident(table)}`)).rows.length,1);
87
+ await denied(runtime,`UPDATE public.${ident(table)} SET ${field}=${field}`,`${table}: runtime immutable receipt UPDATE`);
88
+ await denied(runtime,`DELETE FROM public.${ident(table)}`,`${table}: runtime immutable receipt DELETE`);
89
+ }
90
await denied(backup,'UPDATE public.app_user SET id=id','backup UPDATE');
91
await denied(backup,'CREATE TABLE public.forbidden_backup_table(id integer)','backup CREATE TABLE');
92
await denied(backup,'CREATE TEMP TABLE forbidden_backup_temp(id integer)','backup TEMP');
@@ -170,15 +181,22 @@ try {
181
const url=new URL('postgresql://localhost'); url.hostname=adminConfig.host; url.port=String(adminConfig.port);
182
url.pathname=`/${state.source_db}`; url.username=roleNames.api; url.password=process.env.API_DB_PASSWORD;
183
const fixtureUrl=new URL(url); fixtureUrl.username=roleNames.migrator; fixtureUrl.password=process.env.MIGRATOR_DB_PASSWORD;
173
- const env={...process.env,TEST_FIXTURE_DATABASE_URL:fixtureUrl.toString(),DATABASE_URL:url.toString(),PGUSER:roleNames.api,PGPASSWORD:process.env.API_DB_PASSWORD,PGDATABASE:state.source_db};
184
+ const env={...process.env,TEST_FIXTURE_DATABASE_URL:fixtureUrl.toString(),DATABASE_URL:url.toString(),PGUSER:roleNames.api,PGPASSWORD:process.env.API_DB_PASSWORD,PGDATABASE:state.source_db,
185
+ JWT_SECRET:'synthetic-runtime-route-secret-at-least-32-characters',
186
+ SMS_PROVIDER:'disabled',EMAIL_PROVIDER:'disabled',ENABLE_SENSITIVE_FEATURES:'false'};
187
+ for(const key of ['SMS_PROVIDER_URL','SMS_PROVIDER_TOKEN','EMAIL_FROM','RESEND_API_KEY','SMTP_HOST','SMTP_USER','SMTP_PASSWORD',
188
+ 'AI_API_KEY','AI_BASE_URL','AI_MODEL','OPENAI_API_KEY']) env[key]='';
189
for(const key of ['API_DB_PASSWORD','MIGRATOR_DB_PASSWORD','BACKUP_DB_PASSWORD','POSTGRES_PASSWORD']) delete env[key];
190
const familyEnv={...env};delete familyEnv.TEST_FIXTURE_DATABASE_URL;
191
const family=spawnSync(process.execPath,['--test','tests/online_acceptance.test.js'],{cwd:backend,env:familyEnv,stdio:'inherit'});
192
assert.equal(family.status,0,'Runtime-role family HTTP/DB acceptance failed');
193
const acceptance=spawnSync(process.execPath,['--test',
179
- 'tests/learning_library.test.js','tests/learning_feedback.test.js','tests/learning_assessment.test.js'],{cwd:backend,env,stdio:'inherit'});
194
+ 'tests/learning_library.test.js','tests/learning_feedback.test.js','tests/learning_assessment.test.js',
195
+ 'tests/content_review.test.js','tests/content_review_validation.test.js',
196
+ 'tests/learning_goal_mutations.test.js','tests/family_lifecycle.test.js','tests/family_lifecycle_validation.test.js',
197
+ 'tests/school_lifecycle.test.js','tests/report_periods.test.js','tests/learning_unit_locator.test.js'],{cwd:backend,env,stdio:'inherit'});
198
assert.equal(acceptance.status,0,'Real family/learning HTTP/DB acceptance with runtime role failed');
181
- console.log('PASS role acceptance source: fresh checksum migrations + repeat, restrictive SQL capabilities and runtime family HTTP scenario');
199
+ console.log('PASS role acceptance source: fresh checksum migrations + repeat, restrictive SQL capabilities and runtime family/learning/goals/school/report/locator HTTP scenarios');
200
console.log(`Synthetic restore state saved; source=${state.source_db}; target=${state.target_db}`);
201
} else {
202
state=await readState();
backend/src/content_publication.js
new
+190
@@ -0,0 +1,190 @@
1
+// Operator-only local tooling. This module is never mounted on an HTTP router.
2
+import crypto from 'node:crypto';
3
+import {assessmentHash,assessmentContextHash,validateAssessmentDefinition} from './learning_assessment.js';
4
+
5
+const uuid=value=>typeof value==='string'&&/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(value);
6
+const hash=value=>typeof value==='string'&&/^[a-f0-9]{64}$/.test(value);
7
+const exact=(value,fields)=>value&&typeof value==='object'&&!Array.isArray(value)&&Object.keys(value).every(field=>fields.includes(field));
8
+const text=(value,max=12000)=>typeof value==='string'&&value.trim().length>0&&value.length<=max&&!value.includes('\u0000');
9
+function canonical(value){if(Array.isArray(value))return value.map(canonical);if(value&&typeof value==='object')return Object.fromEntries(Object.keys(value).sort().map(key=>[key,canonical(value[key])]));return value;}
10
+const digest=value=>crypto.createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex');
11
+export class ContentPublicationError extends Error {constructor(code){super(code);this.code=code;}}
12
+const fail=code=>{throw new ContentPublicationError(code);};
13
+
14
+export function localContentReviewConnection(env) {
15
+ if(env.CONTENT_REVIEW_SYNTHETIC_ONLY!=='true'||!env.CONTENT_REVIEW_DATABASE_URL) fail('synthetic_configuration_required');
16
+ let url;try{url=new URL(env.CONTENT_REVIEW_DATABASE_URL);}catch{fail('invalid_operator_configuration');}
17
+ // pg connection-string query parameters can override host/database/user or
18
+ // load TLS files. The checked URL is the only accepted connection source.
19
+ if(url.search||url.hash||!['postgres:','postgresql:'].includes(url.protocol)||!['localhost','127.0.0.1','[::1]'].includes(url.hostname)||
20
+ !/^\/(?:lifeguide_[a-z0-9_]*test(?:_[a-z0-9]+)*|lifemate_ci|lifeguide_roles_(?:source|target)_[a-f0-9]{16})$/.test(url.pathname)) fail('local_test_database_required');
21
+ return url.toString();
22
+}
23
+
24
+const videoReviewFields=['evidenceScope','reviewerName','reviewedAt','bookCode','schoolYear','unitKey','bookEvidenceUrl','unitEvidenceUrl','materialHash',
25
+ 'watchedEntireVideo','editionAligned','accuracyApproved','suitabilityApproved','embedRightsApproved','questionCoverageReviewed',
26
+ 'alignmentNotes','accuracyNotes','suitabilityNotes','embedRightsEvidence','questionCoverageNotes'];
27
+const assessmentReviewFields=['evidenceScope','reviewerName','reviewedAt','bookCode','schoolYear','unitKey','contentHash','contextHash',
28
+ 'accuracyApproved','suitabilityApproved','editionAligned','objectiveCoverageApproved','reviewNotes'];
29
+
30
+export function normalizePublicationOperation(body) {
31
+ const assessment=body?.entityType==='assessment',draft=body?.operation==='draft_assessment';
32
+ const fields=['schemaVersion','mutationId','entityType','entityId','operation','expectedStatus','expectedContentHash','expectedContextHash',
33
+ ...(assessment?['expectedVersion']:[]),...(draft?['unitId','questions']:[]),...(body?.operation==='publish'?['review']:[])];
34
+ if(!exact(body,fields)||body.schemaVersion!==1||!uuid(body.mutationId)||!uuid(body.entityId)||!['video','assessment'].includes(body.entityType)||
35
+ !['publish','withdraw','draft_assessment'].includes(body.operation)||(!assessment&&draft)||
36
+ !['absent','draft','published','withdrawn'].includes(body.expectedStatus)||!hash(body.expectedContextHash)||
37
+ (body.expectedStatus==='absent'?(!draft||body.expectedContentHash!==null):!hash(body.expectedContentHash))||
38
+ (assessment&&(!Number.isSafeInteger(body.expectedVersion)||body.expectedVersion<0||body.expectedVersion>=2147483647||
39
+ (body.expectedStatus==='absent'?body.expectedVersion!==0:body.expectedVersion===0)))) fail('invalid_publication_operation');
40
+ if(draft) {
41
+ if(!uuid(body.unitId)) fail('invalid_publication_operation');
42
+ try {
43
+ validateAssessmentDefinition(body.questions);
44
+ for(const question of body.questions) {
45
+ if(!exact(question,['id','objectiveId','promptFa','choices','correctChoiceId','explanationFa','remediationFa'])||
46
+ question.choices.some(choice=>!exact(choice,['id','textFa']))) fail('invalid_assessment_definition');
47
+ }
48
+ } catch { fail('invalid_assessment_definition'); }
49
+ }
50
+ if(body.operation==='publish'&&!exact(body.review,assessment?assessmentReviewFields:videoReviewFields)) fail('invalid_review_record');
51
+ return canonical({...body,mutationId:body.mutationId.toLowerCase(),entityId:body.entityId.toLowerCase(),...(draft?{unitId:body.unitId.toLowerCase()}:{} )});
52
+}
53
+
54
+// Same metadata fingerprint as the existing catalogue importer. This is not a
55
+// cryptographic fingerprint of provider-hosted video bytes or proof of viewing.
56
+export function videoMaterialHash(row) {
57
+ return crypto.createHash('sha256').update(JSON.stringify({bookKey:row.stable_book_key,bookTitle:row.book_title_fa,
58
+ editionVerification:row.edition_verification,bookEvidence:row.book_evidence_url,unitKey:row.unit_key,unitTitle:row.unit_title_fa,
59
+ indexKind:row.index_kind,orderIndex:row.order_index,unitEvidence:row.unit_evidence_url,aparatId:row.aparat_id,
60
+ canonicalAparatId:row.canonical_aparat_id??null,title:row.title_fa,creatorName:row.creator_name,creatorUrl:row.creator_url,
61
+ sourceEvidence:row.source_evidence_url,verification:row.verification_status,durationSeconds:row.duration_seconds,
62
+ freeAccess:row.free_access,qualityNotes:row.quality_notes_fa})).digest('hex');
63
+}
64
+export function videoContextHash(row) {
65
+ return digest({bookKey:row.stable_book_key,bookTitle:row.book_title_fa,bookCode:row.book_code,schoolYear:row.school_year,
66
+ bookEvidenceUrl:row.book_evidence_url,editionVerification:row.edition_verification,grade:row.national_grade,tracks:row.track_codes,
67
+ variant:row.variant,unitKey:row.unit_key,titleFa:row.unit_title_fa,indexKind:row.index_kind,orderIndex:row.order_index,
68
+ unitEvidenceUrl:row.unit_evidence_url,active:row.active});
69
+}
70
+
71
+async function operator(client,env,apply=false) {
72
+ const url=new URL(localContentReviewConnection(env));
73
+ const row=(await client.query(`select current_database() database,current_user role,
74
+ has_table_privilege(current_user,'learning_video_resource','UPDATE') video_write,
75
+ (has_table_privilege(current_user,'learning_assessment','INSERT') and
76
+ has_table_privilege(current_user,'learning_assessment','UPDATE')) assessment_write,
77
+ has_table_privilege(current_user,'content_publication_audit','INSERT') audit_write`)).rows[0];
78
+ if(row.database!==decodeURIComponent(url.pathname.slice(1))) fail('operator_database_mismatch');
79
+ if(['lifeguide_api','lifeguide_backup'].includes(row.role)||(apply&&(!row.video_write||!row.assessment_write||!row.audit_write))) fail('separate_operator_required');
80
+ return row.role;
81
+}
82
+const contextSelect=`select u.id unit_id,u.unit_key,u.title_fa unit_title_fa,u.order_index,u.index_kind,u.source_evidence_url unit_evidence_url,u.active,
83
+ t.id book_id,t.stable_book_key,t.title_fa book_title_fa,t.book_code,t.track_codes,t.variant,t.edition_verification,t.source_evidence_url book_evidence_url,
84
+ s.school_year,s.national_grade from learning_unit u join textbook_catalog t on t.id=u.textbook_id join curriculum_subject s on s.id=t.curriculum_subject_id`;
85
+async function load(client,type,id,{apply=false,unitId=null}={}) {
86
+ const table=type==='video'?'learning_video_resource':'learning_assessment';
87
+ const raw=(await client.query(`select * from ${table} where id=$1`,[id])).rows[0];
88
+ if(raw&&unitId&&raw.unit_id!==unitId) fail('assessment_unit_immutable');
89
+ const unit=raw?.unit_id??unitId;if(!unit) fail('material_not_found');
90
+ const context=(await client.query(contextSelect+' where u.id=$1'+(apply?' for share of u,t,s':''),[unit])).rows[0];
91
+ if(!context) fail('unit_not_found');
92
+ // The import lock serializes importer and operator; row locks additionally
93
+ // serialize direct catalogue corrections against approval snapshots.
94
+ const locked=apply?(await client.query(`select * from ${table} where id=$1 for update`,[id])).rows[0]:raw;
95
+ if(locked&&locked.unit_id!==unit) fail('assessment_unit_immutable');
96
+ return {...context,...locked,id,exists:Boolean(locked)};
97
+}
98
+function current(row,type) {
99
+ const contentHash=row.exists?(type==='video'?row.material_hash:row.content_hash):null;
100
+ const computedContentHash=row.exists?(type==='video'?videoMaterialHash(row):assessmentHash(row.questions)):null;
101
+ const contextHash=type==='video'?videoContextHash(row):assessmentContextHash(row);
102
+ let eligible=false;
103
+ try { if(row.publication_status==='published') { validateReview(row,type,row.review_record,false);eligible=contentHash===computedContentHash&&(type==='video'||row.context_hash===contextHash); } } catch {}
104
+ return {entityType:type,entityId:row.id,unitId:row.unit_id,publicationStatus:row.exists?row.publication_status:'absent',
105
+ version:type==='assessment'?(row.version??0):null,contentHash,computedContentHash,contextHash,
106
+ contextVerified:row.active&&row.edition_verification==='verified'&&row.school_year!=='unknown',eligibleForLearners:eligible};
107
+}
108
+function reviewTimestamp(value) {
109
+ if(typeof value!=='string'||!/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{3})?Z$/.test(value)) return false;
110
+ const date=new Date(value);return Number.isFinite(date.getTime())&&date.toISOString().slice(0,19)===value.slice(0,19)&&date.getTime()<=Date.now();
111
+}
112
+function validateReview(row,type,review,synthetic) {
113
+ if(!row.active||row.edition_verification!=='verified'||row.school_year==='unknown') fail('verified_edition_required');
114
+ if(synthetic&&(review?.evidenceScope!=='SYNTHETIC_TEST_ONLY'||!review?.reviewerName?.startsWith('SYNTHETIC'))) fail('synthetic_receipt_required');
115
+ if(!text(review?.reviewerName,240)||!reviewTimestamp(review?.reviewedAt)||review.bookCode!==row.book_code||
116
+ review.schoolYear!==row.school_year||review.unitKey!==row.unit_key) fail('review_context_mismatch');
117
+ if(type==='video') {
118
+ const flags=['watchedEntireVideo','editionAligned','accuracyApproved','suitabilityApproved','embedRightsApproved','questionCoverageReviewed'];
119
+ const notes=['alignmentNotes','accuracyNotes','suitabilityNotes','embedRightsEvidence','questionCoverageNotes'];
120
+ if(flags.some(field=>review[field]!==true)||notes.some(field=>!text(review[field]))||row.free_access!==true||
121
+ !['metadata_verified','embed_verified'].includes(row.verification_status)) fail('incomplete_video_review');
122
+ if(review.materialHash!==row.material_hash||review.bookEvidenceUrl!==row.book_evidence_url||review.unitEvidenceUrl!==row.unit_evidence_url) fail('review_context_mismatch');
123
+ if(videoMaterialHash(row)!==row.material_hash) fail('material_hash_mismatch');
124
+ } else {
125
+ if(['accuracyApproved','suitabilityApproved','editionAligned','objectiveCoverageApproved'].some(field=>review[field]!==true)||!text(review.reviewNotes)) fail('incomplete_assessment_review');
126
+ validateAssessmentDefinition(row.questions);
127
+ if(review.contentHash!==row.content_hash||review.contextHash!==row.context_hash||row.content_hash!==assessmentHash(row.questions)||
128
+ row.context_hash!==assessmentContextHash(row)) fail('assessment_hash_mismatch');
129
+ }
130
+}
131
+
132
+export async function inspectLearningContent(client,type,id,{env=process.env}={}) {
133
+ if(!['video','assessment'].includes(type)||!uuid(id)) fail('invalid_inspection');
134
+ await operator(client,env);
135
+ await client.query('begin isolation level repeatable read read only');
136
+ try {const state=current(await load(client,type,id),type);await client.query('rollback');return state;}
137
+ catch(error){await client.query('rollback').catch(()=>{});throw error;}
138
+}
139
+
140
+export async function reviewLearningContent(client,raw,{env=process.env,apply=false}={}) {
141
+ const body=normalizePublicationOperation(raw),requestHash=digest(body);
142
+ const role=await operator(client,env,apply);
143
+ await client.query(apply?'begin':'begin isolation level repeatable read read only');
144
+ try {
145
+ if(apply) await client.query("select pg_advisory_xact_lock(hashtextextended('learning_catalog_import',0))");
146
+ const previous=(await client.query('select * from content_publication_audit where mutation_id=$1',[body.mutationId])).rows[0];
147
+ if(previous&&previous.request_hash!==requestHash) fail('mutation_id_reused');
148
+ let row=await load(client,body.entityType,body.entityId,{apply,unitId:body.unitId});
149
+ if(apply&&!row.stable_book_key?.startsWith('synthetic-publication:')) fail('synthetic_material_required');
150
+ if(previous) {
151
+ const result={mode:apply?'synthetic-apply':'dry-run',current:current(row,body.entityType),acknowledgement:{mutationId:body.mutationId,
152
+ entityId:body.entityId,status:'already_applied',appliedStatus:previous.applied_status,appliedVersion:previous.applied_version,acceptedAt:previous.accepted_at}};
153
+ await client.query(apply?'commit':'rollback');return result;
154
+ }
155
+ const state=current(row,body.entityType);
156
+ if(state.publicationStatus!==body.expectedStatus) fail('publication_status_conflict');
157
+ if(state.contentHash!==body.expectedContentHash) fail('content_conflict');
158
+ if(state.contextHash!==body.expectedContextHash) fail('context_conflict');
159
+ if(body.entityType==='assessment'&&state.version!==body.expectedVersion) fail('assessment_version_conflict');
160
+ if(body.operation==='draft_assessment') {
161
+ if(row.publication_status==='published') fail('published_definition_immutable');
162
+ if(!row.active) fail('unit_inactive');
163
+ if(row.exists&&assessmentHash(body.questions)===row.content_hash&&assessmentContextHash(row)===row.context_hash) fail('definition_change_not_required');
164
+ } else {
165
+ if(!row.exists) fail('material_not_found');
166
+ if(body.operation==='publish') {
167
+ if(row.publication_status==='published') fail('publication_change_not_required');
168
+ validateReview(row,body.entityType,body.review,apply);
169
+ }
170
+ }
171
+ const proposedStatus=body.operation==='publish'?'published':body.operation==='withdraw'?'withdrawn':'draft';
172
+ if(!apply) {await client.query('rollback');return {mode:'dry-run',current:state,proposedStatus,proposedVersion:body.operation==='draft_assessment'?body.expectedVersion+1:state.version};}
173
+ if(body.operation==='draft_assessment') {
174
+ const values=[body.entityId,row.unit_id,body.expectedVersion+1,JSON.stringify(body.questions),assessmentHash(body.questions),assessmentContextHash(row)];
175
+ if(row.exists) await client.query("update learning_assessment set version=$3,questions=$4,content_hash=$5,context_hash=$6,publication_status='draft',review_record=null where id=$1 and unit_id=$2",values);
176
+ else await client.query('insert into learning_assessment(id,unit_id,version,questions,content_hash,context_hash) values($1,$2,$3,$4,$5,$6)',values);
177
+ } else {
178
+ const table=body.entityType==='video'?'learning_video_resource':'learning_assessment';
179
+ if(body.operation==='publish') await client.query(`update ${table} set publication_status='published',review_record=$2${body.entityType==='video'?",pedagogical_review='full_reviewed'":''} where id=$1`,[body.entityId,JSON.stringify(body.review)]);
180
+ else await client.query(`update ${table} set publication_status='withdrawn' where id=$1`,[body.entityId]);
181
+ }
182
+ row=await load(client,body.entityType,body.entityId,{apply});
183
+ const updated=current(row,body.entityType);
184
+ const receipt=(await client.query(`insert into content_publication_audit(mutation_id,entity_type,entity_id,operation,request_hash,
185
+ applied_content_hash,applied_context_hash,applied_version,applied_status,operator_role) values($1,$2,$3,$4,$5,$6,$7,$8,$9,$10) returning accepted_at`,
186
+ [body.mutationId,body.entityType,body.entityId,body.operation,requestHash,updated.contentHash,updated.contextHash,updated.version,updated.publicationStatus,role])).rows[0];
187
+ await client.query('commit');return {mode:'synthetic-apply',current:updated,acknowledgement:{mutationId:body.mutationId,entityId:body.entityId,
188
+ status:'accepted',appliedStatus:updated.publicationStatus,appliedVersion:updated.version,acceptedAt:receipt.accepted_at}};
189
+ } catch(error) {await client.query('rollback').catch(()=>{});throw error;}
190
+}
backend/src/content_review.js
new
+208
@@ -0,0 +1,208 @@
1
+import crypto from 'node:crypto';
2
+import express from 'express';
3
+
4
+const uuid=value=>typeof value==='string'&&/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(value);
5
+const statuses=new Set(['received','triaged','planned','declined','released']);
6
+const reviewStatuses=new Set(['triaged','planned','declined']);
7
+const transitions={received:new Set(['triaged','declined']),triaged:new Set(['planned','declined']),
8
+ planned:new Set(['triaged','declined']),declined:new Set(['triaged'])};
9
+const exact=(value,keys)=>value&&typeof value==='object'&&!Array.isArray(value)&&
10
+ Object.keys(value).every(key=>keys.includes(key));
11
+const version=value=>Number.isSafeInteger(value)&&value>0&&value<=2147483647;
12
+const error=(status,name)=>({status,body:{error:name}});
13
+const digest=value=>crypto.createHash('sha256').update(JSON.stringify(value)).digest('hex');
14
+const feedbackFields=`id,unit_id,category,summary,status,version,created_at,updated_at`;
15
+const visible=`withdrawn_at is null and share_with_content_team=true and summary is not null`;
16
+
17
+export function normalizeReviewMutation(body) {
18
+ if(!exact(body,['mutationId','expectedVersion','status'])||!uuid(body.mutationId)||
19
+ !version(body.expectedVersion)||!reviewStatuses.has(body.status)) return null;
20
+ return {mutationId:body.mutationId.toLowerCase(),expectedVersion:body.expectedVersion,status:body.status};
21
+}
22
+export function normalizeBriefRequest(body) {
23
+ if(!exact(body,['mutationId','feedback'])||!uuid(body.mutationId)||!Array.isArray(body.feedback)||
24
+ body.feedback.length<1||body.feedback.length>20||body.feedback.some(source=>
25
+ !exact(source,['id','expectedVersion'])||!uuid(source.id)||!version(source.expectedVersion))) return null;
26
+ const feedback=body.feedback.map(source=>({id:source.id.toLowerCase(),expectedVersion:source.expectedVersion}));
27
+ if(new Set(feedback.map(source=>source.id)).size!==feedback.length) return null;
28
+ feedback.sort((a,b)=>a.id.localeCompare(b.id));
29
+ return {mutationId:body.mutationId.toLowerCase(),feedback};
30
+}
31
+
32
+function feedbackBody(row) {
33
+ return {id:row.id,unitId:row.unit_id,category:row.category,summary:row.summary,status:row.status,
34
+ version:row.version,createdAt:row.created_at,updatedAt:row.updated_at};
35
+}
36
+async function transaction(pool,operation,authorization) {
37
+ const client=await pool.connect();
38
+ try {
39
+ await client.query('begin');
40
+ const result=await operation(client);
41
+ // A capability/session may expire while waiting for a source row lock.
42
+ // Refuse the response and rollback writes if it is no longer current.
43
+ if(authorization) {
44
+ const current=await permissions(client,authorization.identity,authorization.required);
45
+ if(current.status) { await client.query('rollback'); return current; }
46
+ if(Array.isArray(result.body?.permissions)) result.body.permissions=current.permissions;
47
+ }
48
+ await client.query('commit');
49
+ return result;
50
+ } catch(exception) { await client.query('rollback').catch(()=>{}); throw exception; }
51
+ finally { client.release(); }
52
+}
53
+function send(res,result) { res.status(result.status).json(result.body); }
54
+
55
+async function permissions(client,identity,required=[]) {
56
+ if(identity.exp!=null&&identity.exp*1000<=Date.now()) return error(401,'session_invalid');
57
+ // The offline operator uses this same account lock before grant/revoke. Runtime
58
+ // needs SELECT only on capability tables; no role claims or parent shortcuts.
59
+ const user=await client.query('select id from app_user where id=$1 and disabled_at is null for update',[identity.sub]);
60
+ const session=await client.query(`select 1 from auth_session where id=$1 and user_id=$2
61
+ and revoked_at is null and expires_at>statement_timestamp() for share`,[identity.sid,identity.sub]);
62
+ if(!user.rowCount||!session.rowCount) return error(401,'session_invalid');
63
+ const rows=await client.query(`select permission from content_capability_grant where user_id=$1
64
+ and revoked_at is null and expires_at>statement_timestamp() order by permission`,[identity.sub]);
65
+ const allowed=rows.rows.map(row=>row.permission);
66
+ if(required.some(permission=>!allowed.includes(permission))) return error(403,'content_permission_required');
67
+ return {permissions:allowed};
68
+}
69
+async function mutation(client,actor,id) {
70
+ return (await client.query(`select operation,request_hash,feedback_id,brief_id
71
+ from content_review_mutation where actor_user_id=$1 and mutation_id=$2`,[actor,id])).rows[0];
72
+}
73
+async function lockFeedback(client,id) {
74
+ return (await client.query(`select ${feedbackFields} from learning_content_feedback
75
+ where id=$1 and ${visible} for update`,[id])).rows[0];
76
+}
77
+
78
+const tasks=Object.freeze([
79
+ 'نسخه رسمی کتاب و هدف یادگیری این درس را بررسی کنید.',
80
+ 'محتوای پیشنهادی و سؤالهای تمرینی را بهطور کامل بازبینی کنید.',
81
+ 'برای تغییر پیشنهادی معیار پذیرش، آزمون و PR مستقل تهیه کنید.',
82
+ 'انتشار محتوا و استقرار فقط پس از بازبینی و مجوز جداگانه انجام شود.'
83
+]);
84
+async function briefBody(client,id) {
85
+ const brief=(await client.query('select id,created_at,source_count from content_review_brief where id=$1',[id])).rows[0];
86
+ if(!brief) return error(404,'brief_not_found');
87
+ // Sorted row locks share the same serialization boundary as owner withdrawal
88
+ // and review updates. No summaries are stored/copied in this brief.
89
+ const sources=(await client.query(`select f.id,f.version,f.status,f.withdrawn_at,
90
+ f.share_with_content_team,f.category,f.unit_id,s.feedback_version
91
+ from content_review_brief_source s join learning_content_feedback f on f.id=s.feedback_id
92
+ where s.brief_id=$1 order by f.id for update of f`,[id])).rows;
93
+ if(sources.length!==brief.source_count||sources.some(source=>source.withdrawn_at||!source.share_with_content_team||
94
+ source.status!=='planned'||source.version!==source.feedback_version)) return error(409,'brief_invalidated');
95
+ const categories=new Map();
96
+ for(const source of sources) categories.set(source.category,(categories.get(source.category)??0)+1);
97
+ const unitIds=[...new Set(sources.map(source=>source.unit_id).filter(Boolean))];
98
+ const units=(await client.query(`select u.id,u.title_fa,t.book_code,t.title_fa book_title,
99
+ t.track_codes,t.edition_verification,s.school_year,s.national_grade
100
+ from learning_unit u join textbook_catalog t on t.id=u.textbook_id
101
+ join curriculum_subject s on s.id=t.curriculum_subject_id where u.id=any($1::uuid[]) order by u.id`,[unitIds])).rows;
102
+ return {status:200,body:{brief:{id:brief.id,title:'پیشنهاد بررسی و توسعه محتوای آموزشی',createdAt:brief.created_at,
103
+ sourceCount:sources.length,categories:[...categories].sort(([a],[b])=>a.localeCompare(b)).map(([category,count])=>({category,count})),
104
+ units:units.map(unit=>({id:unit.id,title:unit.title_fa,bookCode:unit.book_code,bookTitle:unit.book_title,
105
+ gradeLevel:unit.national_grade,trackCode:unit.track_codes,editionYear:unit.school_year==='unknown'?null:unit.school_year,
106
+ editionStatus:unit.edition_verification})),tasks:[...tasks],
107
+ notice:'این پیشنهاد ساختاری فاقد متن بازخورد و اطلاعات خصوصی است؛ تأیید محتوا یا دستور انتشار نیست.'}}};
108
+}
109
+
110
+export function createContentReviewRouter({pool,auth}) {
111
+ const router=express.Router();
112
+ router.get('/me/content-capabilities',auth,async(req,res)=>{
113
+ if(Object.keys(req.query).length) return send(res,error(400,'invalid_content_query'));
114
+ send(res,await transaction(pool,async client=>{
115
+ const grant=await permissions(client,req.identity);
116
+ return grant.status?grant:{status:200,body:grant};
117
+ },{identity:req.identity,required:[]}));
118
+ });
119
+ router.get('/content-review/feedback',auth,async(req,res)=>{
120
+ const cursor=req.query.cursor??null,status=req.query.status??null;
121
+ const limit=req.query.limit===undefined?50:Number(req.query.limit);
122
+ if(Object.keys(req.query).some(key=>!['cursor','status','limit'].includes(key))||
123
+ (cursor!==null&&!uuid(cursor))||(status!==null&&!statuses.has(status))||
124
+ (req.query.limit!==undefined&&(typeof req.query.limit!=='string'||!/^\d+$/.test(req.query.limit)))||
125
+ !Number.isInteger(limit)||limit<1||limit>100) return send(res,error(400,'invalid_content_query'));
126
+ send(res,await transaction(pool,async client=>{
127
+ const grant=await permissions(client,req.identity,['feedback.read']); if(grant.status) return grant;
128
+ // Lock the consenting set once. Paging and count derive from the same
129
+ // statement snapshot; microseconds remain in PostgreSQL cursor comparisons.
130
+ const result=await client.query(`with consenting as materialized (
131
+ select ${feedbackFields} from learning_content_feedback where ${visible}
132
+ and ($2::text is null or status=$2) order by id for share
133
+ ), page as (
134
+ select * from consenting where $1::uuid is null or (created_at,id)<
135
+ (select created_at,id from consenting where id=$1)
136
+ order by created_at desc,id desc limit $3
137
+ ) select (select count(*)::int from consenting) total,
138
+ exists(select 1 from consenting where id=$1) cursor_exists,
139
+ coalesce((select jsonb_agg(to_jsonb(page) order by created_at desc,id desc) from page),'[]'::jsonb) rows`,
140
+ [cursor,status,limit+1]);
141
+ const row=result.rows[0];
142
+ if(cursor&&!row.cursor_exists) return error(404,'feedback_not_found');
143
+ return {status:200,body:{feedback:row.rows.slice(0,limit).map(feedbackBody),
144
+ nextCursor:row.rows.length>limit?row.rows[limit-1].id:null,total:row.total}};
145
+ },{identity:req.identity,required:['feedback.read']}));
146
+ });
147
+ router.patch('/content-review/feedback/:id',auth,async(req,res)=>{
148
+ const body=normalizeReviewMutation(req.body);
149
+ if(!uuid(req.params.id)||!body||Object.keys(req.query).length) return send(res,error(400,'invalid_review_mutation'));
150
+ const hash=digest({feedbackId:req.params.id.toLowerCase(),...body});
151
+ send(res,await transaction(pool,async client=>{
152
+ const grant=await permissions(client,req.identity,['feedback.read','feedback.review']); if(grant.status) return grant;
153
+ const previous=await mutation(client,req.identity.sub,body.mutationId);
154
+ if(previous&&(previous.operation!=='review'||previous.request_hash!==hash)) return error(409,'mutation_id_reused');
155
+ const row=await lockFeedback(client,req.params.id); if(!row) return error(404,'feedback_not_found');
156
+ if(previous) return {status:200,body:{feedback:feedbackBody(row),acknowledgement:{mutationId:body.mutationId,
157
+ feedbackId:row.id,status:'already_applied'}}};
158
+ if(row.version!==body.expectedVersion) return error(409,'feedback_version_conflict');
159
+ if(!transitions[row.status]?.has(body.status)) return error(409,'feedback_transition_invalid');
160
+ const updated=(await client.query(`update learning_content_feedback set status=$2,version=version+1,
161
+ updated_at=statement_timestamp() where id=$1 returning ${feedbackFields}`,[row.id,body.status])).rows[0];
162
+ await client.query(`insert into content_review_audit(actor_user_id,feedback_id,before_status,after_status,before_version,after_version)
163
+ values($1,$2,$3,$4,$5,$6)`,[req.identity.sub,row.id,row.status,updated.status,row.version,updated.version]);
164
+ await client.query(`insert into content_review_mutation(actor_user_id,mutation_id,operation,request_hash,feedback_id)
165
+ values($1,$2,'review',$3,$4)`,[req.identity.sub,body.mutationId,hash,row.id]);
166
+ return {status:200,body:{feedback:feedbackBody(updated),acknowledgement:{mutationId:body.mutationId,
167
+ feedbackId:row.id,status:'accepted'}}};
168
+ },{identity:req.identity,required:['feedback.read','feedback.review']}));
169
+ });
170
+ router.post('/content-review/briefs',auth,async(req,res)=>{
171
+ const body=normalizeBriefRequest(req.body);
172
+ if(!body||Object.keys(req.query).length) return send(res,error(400,'invalid_brief_request'));
173
+ const hash=digest(body);
174
+ send(res,await transaction(pool,async client=>{
175
+ const grant=await permissions(client,req.identity,['feedback.read','brief.prepare']); if(grant.status) return grant;
176
+ const previous=await mutation(client,req.identity.sub,body.mutationId);
177
+ if(previous&&(previous.operation!=='brief'||previous.request_hash!==hash)) return error(409,'mutation_id_reused');
178
+ if(previous) {
179
+ const existing=await briefBody(client,previous.brief_id);
180
+ if(existing.status!==200) return existing;
181
+ existing.body.acknowledgement={mutationId:body.mutationId,briefId:previous.brief_id,status:'already_applied'};
182
+ return existing;
183
+ }
184
+ for(const source of body.feedback) {
185
+ const row=await lockFeedback(client,source.id); if(!row) return error(404,'feedback_not_found');
186
+ if(row.status!=='planned'||row.version!==source.expectedVersion) return error(409,'brief_source_conflict');
187
+ }
188
+ const brief=(await client.query('insert into content_review_brief(actor_user_id,source_count) values($1,$2) returning id',
189
+ [req.identity.sub,body.feedback.length])).rows[0];
190
+ for(const source of body.feedback) await client.query(`insert into content_review_brief_source(brief_id,feedback_id,feedback_version)
191
+ values($1,$2,$3)`,[brief.id,source.id,source.expectedVersion]);
192
+ await client.query(`insert into content_review_mutation(actor_user_id,mutation_id,operation,request_hash,brief_id)
193
+ values($1,$2,'brief',$3,$4)`,[req.identity.sub,body.mutationId,hash,brief.id]);
194
+ const result=await briefBody(client,brief.id);
195
+ result.status=201;
196
+ result.body.acknowledgement={mutationId:body.mutationId,briefId:brief.id,status:'accepted'};
197
+ return result;
198
+ },{identity:req.identity,required:['feedback.read','brief.prepare']}));
199
+ });
200
+ router.get('/content-review/briefs/:id',auth,async(req,res)=>{
201
+ if(!uuid(req.params.id)||Object.keys(req.query).length) return send(res,error(400,'invalid_brief_query'));
202
+ send(res,await transaction(pool,async client=>{
203
+ const grant=await permissions(client,req.identity,['feedback.read','brief.prepare']); if(grant.status) return grant;
204
+ return briefBody(client,req.params.id);
205
+ },{identity:req.identity,required:['feedback.read','brief.prepare']}));
206
+ });
207
+ return router;
208
+}
backend/src/family_lifecycle.js
new
+197
@@ -0,0 +1,197 @@
1
+import crypto from 'node:crypto';
2
+import express from 'express';
3
+
4
+const uuid=value=>typeof value==='string'&&/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(value);
5
+const version=value=>Number.isInteger(value)&&value>0&&value<2147483647;
6
+const roles=new Set(['parent_guardian','teen_minor','adult_member']);
7
+const exact=(body,fields)=>body&&typeof body==='object'&&!Array.isArray(body)&&Object.keys(body).every(key=>fields.includes(key));
8
+const error=(status,name)=>({status,body:{error:name}});
9
+const hash=body=>crypto.createHash('sha256').update(JSON.stringify(body)).digest('hex');
10
+const memberColumns='m.user_id,m.role,m.is_admin,m.version,m.updated_at,m.ended_at';
11
+const send=(res,result)=>res.status(result.status).json(result.body);
12
+
13
+export function normalizeRoleMutation(body){
14
+ if(!exact(body,['mutationId','expectedVersion','role'])||!uuid(body.mutationId)||!version(body.expectedVersion)||!roles.has(body.role))return null;
15
+ return {mutationId:body.mutationId.toLowerCase(),expectedVersion:body.expectedVersion,role:body.role};
16
+}
17
+export function normalizeAdminTransfer(body){
18
+ if(!exact(body,['mutationId','targetUserId','expectedVersion','expectedActorVersion'])||!uuid(body.mutationId)||!uuid(body.targetUserId)||
19
+ !version(body.expectedVersion)||!version(body.expectedActorVersion))return null;
20
+ return {mutationId:body.mutationId.toLowerCase(),targetUserId:body.targetUserId.toLowerCase(),
21
+ expectedVersion:body.expectedVersion,expectedActorVersion:body.expectedActorVersion};
22
+}
23
+export function normalizeInvitationRevoke(body){
24
+ if(!exact(body,['mutationId','expectedVersion','action'])||!uuid(body.mutationId)||!version(body.expectedVersion)||body.action!=='revoke')return null;
25
+ return {mutationId:body.mutationId.toLowerCase(),expectedVersion:body.expectedVersion,action:'revoke'};
26
+}
27
+const memberBody=row=>({userId:row.user_id,role:row.role,isAdmin:row.is_admin,version:row.version,updatedAt:row.updated_at,endedAt:row.ended_at});
28
+const invitationBody=row=>({id:row.id,status:row.status,version:row.version,createdAt:row.created_at,expiresAt:row.expires_at});
29
+function hint(row){return row.invited_phone_normalized?`***${row.invited_phone_normalized.slice(-4)}`:
30
+ row.invited_email_normalized?`***@${row.invited_email_normalized.split('@').at(-1)}`:null;}
31
+
32
+async function sessionCurrent(client,identity,{lock=false}={}){
33
+ // Logout does not lock app_user. Hold the session row only at the final gate,
34
+ // then check fresh statement time after any session-row lock wait as well.
35
+ if(lock)await client.query('select id from auth_session where id=$1 and user_id=$2 for share',[identity.sid,identity.sub]);
36
+ return (await client.query(`select 1 from app_user u join auth_session s on s.user_id=u.id
37
+ where u.id=$1 and u.disabled_at is null and s.id=$2 and s.revoked_at is null
38
+ and s.expires_at>statement_timestamp()
39
+ and ($3::double precision is null or to_timestamp($3)>statement_timestamp())`,[identity.sub,identity.sid,identity.exp??null])).rowCount>0;
40
+}
41
+async function transaction(pool,identity,operation){
42
+ const client=await pool.connect();
43
+ try{
44
+ await client.query('begin');const result=await operation(client);
45
+ if(!await sessionCurrent(client,identity,{lock:true})){await client.query('rollback');return error(401,'session_invalid');}
46
+ await client.query('commit');return result;
47
+ }catch(exception){await client.query('rollback').catch(()=>{});throw exception;}
48
+ finally{client.release();}
49
+}
50
+async function familyMember(client,familyId,identity,targetId=null){
51
+ const family=await client.query('select id from family_workspace where id=$1 and archived_at is null for update',[familyId]);
52
+ if(!family.rowCount)return error(403,'forbidden');
53
+ const participants=[...new Set([identity.sub,...(targetId?[targetId]:[])])].sort();
54
+ // Multiple families may share these accounts. Lock all participating users in
55
+ // UUID order before individual memberships, rather than actor then target.
56
+ await client.query('select id from app_user where id=any($1::uuid[]) order by id for update',[participants]);
57
+ // Birth dates are editable independently of the account row. Freeze the age
58
+ // context until this explicit family change commits.
59
+ await client.query('select user_id from profile where user_id=any($1::uuid[]) order by user_id for update',[participants]);
60
+ await client.query('select user_id from family_membership where family_id=$1 and user_id=any($2::uuid[]) order by user_id for update',[familyId,participants]);
61
+ const member=(await client.query(`select ${memberColumns} from family_membership m join app_user u on u.id=m.user_id
62
+ where m.family_id=$1 and m.user_id=$2 and m.ended_at is null and u.disabled_at is null`,[familyId,identity.sub])).rows[0];
63
+ if(!member)return error(403,'forbidden');
64
+ if(!await sessionCurrent(client,identity))return error(401,'session_invalid');
65
+ return member;
66
+}
67
+const admin=member=>member.is_admin&&member.role!=='teen_minor';
68
+async function targetMember(client,familyId,id){
69
+ return (await client.query(`select ${memberColumns},u.disabled_at,p.birth_date,
70
+ (p.birth_date is not null and p.birth_date>(current_date-interval '18 years')::date) known_minor
71
+ from family_membership m join app_user u on u.id=m.user_id left join profile p on p.user_id=m.user_id
72
+ where m.family_id=$1 and m.user_id=$2`,[familyId,id])).rows[0];
73
+}
74
+async function receipt(client,identity,mutationId){
75
+ return (await client.query('select * from family_lifecycle_mutation where actor_user_id=$1 and mutation_id=$2',[identity.sub,mutationId])).rows[0];
76
+}
77
+async function saveReceipt(client,identity,body,familyId,operation,targetId,digest){
78
+ await client.query(`insert into family_lifecycle_mutation(actor_user_id,mutation_id,family_id,operation,target_id,request_hash)
79
+ values($1,$2,$3,$4,$5,$6)`,[identity.sub,body.mutationId,familyId,operation,targetId,digest]);
80
+}
81
+function acknowledgement(body,familyId,targetId,operation,applied){return {mutationId:body.mutationId,familyId,targetId,operation,
82
+ status:applied?'already_applied':'accepted'};}
83
+async function audit(client,identity,familyId,operation,targetId){
84
+ await client.query(`insert into access_audit(actor_user_id,family_id,action,target_type,target_id)
85
+ values($1,$2,$3,$4,$5)`,[identity.sub,familyId,`family.lifecycle.${operation}`,
86
+ operation==='invitation_revoke'?'invitation':'membership',targetId]);
87
+}
88
+async function invalidateRoleSharing(client,familyId,targetId){
89
+ await client.query(`update guardian_relationship g set active=false
90
+ where g.family_id=$1 and g.active and (g.guardian_user_id=$2 or g.minor_user_id=$2)
91
+ and not exists(select 1 from family_membership gm join family_membership mm on mm.family_id=gm.family_id
92
+ where gm.family_id=g.family_id and gm.user_id=g.guardian_user_id and gm.ended_at is null and gm.role='parent_guardian'
93
+ and mm.user_id=g.minor_user_id and mm.ended_at is null and mm.role='teen_minor')`,[familyId,targetId]);
94
+ // A role change is a new sharing context. Explicit selections must be chosen
95
+ // again; reversing a role never silently restores previous selections.
96
+ await client.query(`delete from sharing_grant sg using plan_item p where sg.resource_type='plan_item'
97
+ and sg.resource_id=p.id and p.family_id=$1 and (p.owner_user_id=$2 or sg.grantee_user_id=$2)`,[familyId,targetId]);
98
+}
99
+
100
+export function createFamilyLifecycleRouter({pool,auth}){
101
+ const router=express.Router();
102
+ router.get('/families/:familyId/invitations',auth,async(req,res)=>{
103
+ const cursor=req.query.cursor??null,limit=req.query.limit===undefined?100:Number(req.query.limit);
104
+ if(!uuid(req.params.familyId)||Object.keys(req.query).some(key=>!['limit','cursor'].includes(key))||
105
+ (cursor!==null&&!uuid(cursor))||!Number.isInteger(limit)||limit<1||limit>100||
106
+ (req.query.limit!==undefined&&(typeof req.query.limit!=='string'||!/^\d+$/.test(req.query.limit))))return send(res,error(400,'invalid_invitation_query'));
107
+ send(res,await transaction(pool,req.identity,async client=>{
108
+ const actor=await familyMember(client,req.params.familyId,req.identity);if(actor.status)return actor;
109
+ if(!admin(actor))return error(403,'forbidden');
110
+ const result=(await client.query(`with pending as materialized (
111
+ select id,intended_role,case when expires_at<=statement_timestamp() then 'expired' else 'pending' end status,
112
+ invited_email_normalized,invited_phone_normalized,version,created_at,expires_at
113
+ from family_invitation where family_id=$1 and status='pending'
114
+ ),page as (select * from pending where $2::uuid is null or (created_at,id)<(select created_at,id from pending where id=$2)
115
+ order by created_at desc,id desc limit $3)
116
+ select (select count(*)::int from pending) total,exists(select 1 from pending where id=$2) cursor_exists,
117
+ coalesce((select jsonb_agg(to_jsonb(page) order by created_at desc,id desc) from page),'[]'::jsonb) rows`,
118
+ [req.params.familyId,cursor,limit+1])).rows[0];
119
+ if(cursor&&!result.cursor_exists)return error(404,'invitation_not_found');
120
+ return {status:200,body:{invitations:result.rows.slice(0,limit).map(row=>({...invitationBody(row),
121
+ intendedRole:row.intended_role,recipientHint:hint(row)})),nextCursor:result.rows.length>limit?result.rows[limit-1].id:null,total:result.total}};
122
+ }));
123
+ });
124
+ router.patch('/families/:familyId/invitations/:id',auth,async(req,res)=>{
125
+ const body=normalizeInvitationRevoke(req.body),familyId=req.params.familyId,id=req.params.id;
126
+ if(!uuid(familyId)||!uuid(id)||!body||Object.keys(req.query).length)return send(res,error(400,'invalid_invitation_mutation'));
127
+ const digest=hash({familyId:familyId.toLowerCase(),id:id.toLowerCase(),operation:'invitation_revoke',...body});
128
+ send(res,await transaction(pool,req.identity,async client=>{
129
+ const actor=await familyMember(client,familyId,req.identity);if(actor.status)return actor;
130
+ const previous=await receipt(client,req.identity,body.mutationId);
131
+ if(previous&&previous.request_hash!==digest)return error(409,'mutation_id_reused');
132
+ if(!previous&&!admin(actor))return error(403,'forbidden');
133
+ const row=(await client.query('select id,status,version,created_at,expires_at from family_invitation where family_id=$1 and id=$2 for update',[familyId,id])).rows[0];
134
+ if(!row)return error(404,'invitation_not_found');
135
+ if(previous)return {status:200,body:{invitation:invitationBody(row),acknowledgement:acknowledgement(body,familyId,id,'invitation_revoke',true)}};
136
+ if(row.version!==body.expectedVersion)return error(409,'invitation_version_conflict');
137
+ if(row.status!=='pending')return error(409,'invitation_not_pending');
138
+ const updated=(await client.query("update family_invitation set status='revoked' where id=$1 returning id,status,version,created_at,expires_at",[id])).rows[0];
139
+ await saveReceipt(client,req.identity,body,familyId,'invitation_revoke',id,digest);await audit(client,req.identity,familyId,'invitation_revoke',id);
140
+ return {status:200,body:{invitation:invitationBody(updated),acknowledgement:acknowledgement(body,familyId,id,'invitation_revoke',false)}};
141
+ }));
142
+ });
143
+ router.patch('/families/:familyId/members/:userId/role',auth,async(req,res)=>{
144
+ const body=normalizeRoleMutation(req.body),familyId=req.params.familyId,id=req.params.userId;
145
+ if(!uuid(familyId)||!uuid(id)||!body||Object.keys(req.query).length)return send(res,error(400,'invalid_membership_mutation'));
146
+ const digest=hash({familyId:familyId.toLowerCase(),id:id.toLowerCase(),operation:'role',...body});
147
+ send(res,await transaction(pool,req.identity,async client=>{
148
+ const actor=await familyMember(client,familyId,req.identity,id);if(actor.status)return actor;
149
+ const previous=await receipt(client,req.identity,body.mutationId);
150
+ if(previous&&previous.request_hash!==digest)return error(409,'mutation_id_reused');
151
+ if(!previous&&!admin(actor))return error(403,'forbidden');
152
+ const target=await targetMember(client,familyId,id);if(!target)return error(404,'membership_not_found');
153
+ if(previous)return {status:200,body:{members:[memberBody(target)],acknowledgement:acknowledgement(body,familyId,id,'role',true)}};
154
+ if(target.ended_at||target.disabled_at)return error(409,'member_not_active');
155
+ if(target.version!==body.expectedVersion)return error(409,'membership_version_conflict');
156
+ if(target.role===body.role)return error(409,'membership_change_not_required');
157
+ if(body.role==='teen_minor'&&target.is_admin)return error(409,'minor_cannot_admin');
158
+ if(body.role!=='teen_minor'&&target.known_minor)return error(409,'minor_role_upgrade_forbidden');
159
+ if(target.role==='teen_minor'&&body.role!=='teen_minor'&&!target.birth_date)return error(409,'age_confirmation_required');
160
+ const updated=(await client.query(`update family_membership m set role=$3
161
+ where family_id=$1 and user_id=$2 returning ${memberColumns}`,[familyId,id,body.role])).rows[0];
162
+ await invalidateRoleSharing(client,familyId,id);
163
+ await saveReceipt(client,req.identity,body,familyId,'role',id,digest);await audit(client,req.identity,familyId,'role',id);
164
+ return {status:200,body:{members:[memberBody(updated)],acknowledgement:acknowledgement(body,familyId,id,'role',false)}};
165
+ }));
166
+ });
167
+ router.post('/families/:familyId/admin-transfer',auth,async(req,res)=>{
168
+ const body=normalizeAdminTransfer(req.body),familyId=req.params.familyId;
169
+ if(!uuid(familyId)||!body||Object.keys(req.query).length)return send(res,error(400,'invalid_admin_transfer'));
170
+ const digest=hash({familyId:familyId.toLowerCase(),operation:'admin_transfer',...body});
171
+ send(res,await transaction(pool,req.identity,async client=>{
172
+ const actor=await familyMember(client,familyId,req.identity,body.targetUserId);if(actor.status)return actor;
173
+ const previous=await receipt(client,req.identity,body.mutationId);
174
+ if(previous&&previous.request_hash!==digest)return error(409,'mutation_id_reused');
175
+ if(!previous&&!admin(actor))return error(403,'forbidden');
176
+ const target=await targetMember(client,familyId,body.targetUserId);if(!target)return error(404,'membership_not_found');
177
+ if(previous)return {status:200,body:{members:[memberBody(actor),memberBody(target)],
178
+ acknowledgement:acknowledgement(body,familyId,body.targetUserId,'admin_transfer',true)}};
179
+ if(target.user_id===actor.user_id)return error(409,'admin_target_invalid');
180
+ if(target.ended_at||target.disabled_at)return error(409,'member_not_active');
181
+ if(target.role==='teen_minor'||target.known_minor)return error(409,'minor_cannot_admin');
182
+ if(actor.version!==body.expectedActorVersion||target.version!==body.expectedVersion)return error(409,'membership_version_conflict');
183
+ if(target.is_admin)return error(409,'admin_target_already_admin');
184
+ const promoted=(await client.query(`update family_membership m set is_admin=true where family_id=$1 and user_id=$2 returning ${memberColumns}`,
185
+ [familyId,body.targetUserId])).rows[0];
186
+ const demoted=(await client.query(`update family_membership m set is_admin=false where family_id=$1 and user_id=$2 returning ${memberColumns}`,
187
+ [familyId,req.identity.sub])).rows[0];
188
+ // Existing invitations require a currently active inviter-admin. Revoke
189
+ // them on transfer; transferring back never revives an old bearer token.
190
+ await client.query("update family_invitation set status='revoked' where family_id=$1 and invited_by=$2 and status='pending'",[familyId,req.identity.sub]);
191
+ await saveReceipt(client,req.identity,body,familyId,'admin_transfer',body.targetUserId,digest);await audit(client,req.identity,familyId,'admin_transfer',body.targetUserId);
192
+ return {status:200,body:{members:[memberBody(demoted),memberBody(promoted)],
193
+ acknowledgement:acknowledgement(body,familyId,body.targetUserId,'admin_transfer',false)}};
194
+ }));
195
+ });
196
+ return router;
197
+}
backend/src/learning_library.js
+11
@@ -56,6 +56,17 @@ export function createLearningLibraryRouter({pool,auth}){
56
const mapped=units.map(u=>{const resources=videos.filter(v=>v.unit_id===u.id).map(v=>({aparatId:v.canonical_aparat_id??v.aparat_id,titleFa:v.title_fa,creatorName:v.creator_name,creatorUrl:v.creator_url,sourceEvidenceUrl:v.source_evidence_url,verificationStatus:v.verification_status,pedagogicalReview:v.pedagogical_review,freeAccess:v.free_access,durationSeconds:v.duration_seconds,checkedAt:v.checked_at,qualityNotesFa:v.quality_notes_fa}));return {id:u.id,titleFa:u.title_fa,orderIndex:u.order_index,indexKind:u.index_kind,unitKey:u.unit_key,sourceEvidenceUrl:officialUnitCitation(u.source_evidence_url),videos:resources,reviewCandidateCount:u.review_candidate_count,availability:resources.length?'available':'unavailable',progress:u.version==null?null:progress({...u,unit_id:u.id})};});
57
res.json({...course(r.rows[0]),units:mapped,fetchedAt:new Date().toISOString()});
58
});
59
+ // Catalogue navigation only. This locator deliberately excludes learner
60
+ // progress, attempt history, resource candidates and other account fields.
61
+ router.get('/education/units/:unitId',requireAuth,async(req,res)=>{
62
+ if(!validUuid(req.params.unitId))return res.status(400).json({error:'invalid_unit_id'});
63
+ const result=await pool.query(`select u.id,u.title_fa,u.textbook_id from learning_unit u
64
+ join textbook_catalog t on t.id=u.textbook_id join curriculum_subject s on s.id=t.curriculum_subject_id
65
+ where u.id=$1 and u.active and t.stable_book_key is not null`,[req.params.unitId]);
66
+ if(!result.rowCount)return res.status(404).json({error:'unit_not_found'});
67
+ const unit=result.rows[0];
68
+ res.json({unit:{id:unit.id,titleFa:unit.title_fa,courseId:unit.textbook_id},fetchedAt:new Date().toISOString()});
69
+ });
70
router.get('/me/learning-progress',requireAuth,async(req,res)=>{const r=await pool.query('select * from learning_progress where owner_user_id=$1 order by updated_at,unit_id',[req.identity.sub]);res.json({progress:r.rows.map(progress),fetchedAt:new Date().toISOString()});});
71
router.put('/me/learning-progress/:unitId',requireAuth,async(req,res)=>{
72
const body=req.body,allowed=['status','source','mutationId','expectedVersion'];
backend/src/phase3.js
+84
-55
@@ -1,5 +1,6 @@
1
import crypto from 'node:crypto';
2
import express from 'express';
3
+import { schoolLifecycleError, assertSchoolSession } from './school_lifecycle.js';
4
import { applyPlanMutation, createPlanItem, updatePlanItem, planTransaction, serializePlanItem, validUuid, PlanMutationError } from './plan_mutations.js';
5
6
const allowedKinds = new Set(['task','event','routine','goal','assignment','exam','study_session']);
@@ -11,6 +12,28 @@ function schoolDate(value) {
12
return Number.isFinite(date.getTime()) && date.toISOString().slice(0, 10) === value;
13
}
14
15
+
16
+// These legacy create paths retain their contracts; the database lifecycle
17
+// guards also serialize them with new archive/date changes.
18
+const schoolRoute = (pool, handler, write = true) => async (req, res, next) => {
19
+ const client = await pool.connect();
20
+ try {
21
+ await client.query('begin');
22
+ const account = await client.query(`select 1 from app_user where id=$1 and disabled_at is null for ${write ? 'update' : 'share'}`, [req.identity.sub]);
23
+ if (!account.rowCount) { await client.query('rollback'); return res.status(401).json({ error: 'session_invalid' }); }
24
+ await assertSchoolSession(client, req.identity);
25
+ const result = await handler(req, client);
26
+ await assertSchoolSession(client, req.identity);
27
+ await client.query('commit');
28
+ res.status(result.status).json(result.body);
29
+ } catch (raw) {
30
+ await client.query('rollback').catch(() => {});
31
+ const error = schoolLifecycleError(raw);
32
+ if (error.status && (error.code?.startsWith('school_') || error.code === 'session_invalid')) return res.status(error.status).json({ error: error.code });
33
+ next(error);
34
+ } finally { client.release(); }
35
+};
36
+
37
function asDate(value) {
38
if (value == null || value === '') return null;
39
const d = new Date(value);
@@ -198,125 +221,126 @@ export function createPhase3Router({ pool, auth }) {
221
res.json({ notifications: r.rows });
222
});
223
201
- router.get('/life-contexts', auth, async (req, res) => {
202
- const r = await pool.query(
224
+ router.get('/life-contexts', auth, schoolRoute(pool, async (req, client) => {
225
+ const r = await client.query(
226
'select * from life_context where user_id=$1 and active order by created_at',
227
[req.identity.sub],
228
);
206
- res.json({ contexts: r.rows });
207
- });
229
+ return { status: 200, body: { contexts: r.rows } };
230
+ }, false));
231
209
- router.post('/life-contexts', auth, async (req, res) => {
232
+ router.post('/life-contexts', auth, schoolRoute(pool, async (req, client) => {
233
const kind = String(req.body.kind ?? '');
234
const title = String(req.body.title ?? '').trim();
212
- if (!['student','work','personal'].includes(kind) || !title) {
213
- return res.status(400).json({ error: 'invalid_life_context' });
235
+ if (!['student','work','personal'].includes(kind) || !schoolText(req.body.title)) {
236
+ return { status: 400, body: { error: 'invalid_life_context' } };
237
}
215
- const r = await pool.query(
238
+ const r = await client.query(
239
'insert into life_context(user_id,kind,title) values($1,$2,$3) returning *',
240
[req.identity.sub, kind, title],
241
);
219
- res.status(201).json(r.rows[0]);
220
- });
242
+ return { status: 201, body: r.rows[0] };
243
+ }));
244
222
- router.post('/school/years', auth, async (req, res) => {
245
+ router.post('/school/years', auth, schoolRoute(pool, async (req, client) => {
246
const body = req.body ?? {};
247
const title = String(body.title ?? '').trim();
248
const startsOn = body.startsOn;
249
const endsOn = body.endsOn;
250
const lifeContextId = body.lifeContextId;
251
if (!validUuid(lifeContextId) || !schoolText(body.title) || !schoolDate(startsOn) || !schoolDate(endsOn) || endsOn < startsOn) {
229
- return res.status(400).json({ error: 'invalid_academic_year' });
252
+ return { status: 400, body: { error: 'invalid_academic_year' } };
253
}
231
- const ctx = await pool.query(
254
+ const ctx = await client.query(
255
`select 1 from life_context
256
where id=$1 and user_id=$2 and kind='student' and active`,
257
[lifeContextId, req.identity.sub],
258
);
259
if (!ctx.rowCount || !title || !startsOn || !endsOn) {
237
- return res.status(400).json({ error: 'invalid_academic_year' });
260
+ return { status: 400, body: { error: 'invalid_academic_year' } };
261
}
239
- const r = await pool.query(
262
+ const r = await client.query(
263
`insert into academic_year(student_user_id,life_context_id,title,starts_on,ends_on)
264
values($1,$2,$3,$4,$5) returning *`,
265
[req.identity.sub, lifeContextId, title, startsOn, endsOn],
266
);
244
- res.status(201).json(r.rows[0]);
245
- });
267
+ return { status: 201, body: r.rows[0] };
268
+ }));
269
247
- router.post('/school/years/:yearId/terms', auth, async (req, res) => {
270
+ router.post('/school/years/:yearId/terms', auth, schoolRoute(pool, async (req, client) => {
271
const body = req.body ?? {};
272
if (!validUuid(req.params.yearId) || !schoolText(body.title) || !schoolDate(body.startsOn) || !schoolDate(body.endsOn) || body.endsOn < body.startsOn) {
250
- return res.status(400).json({ error: 'invalid_academic_term' });
273
+ return { status: 400, body: { error: 'invalid_academic_term' } };
274
}
252
- const y = await pool.query(
275
+ const y = await client.query(
276
'select student_user_id,active,starts_on::text,ends_on::text from academic_year where id=$1',
277
[req.params.yearId],
278
);
256
- if (!y.rowCount) return res.status(404).json({ error: 'not_found' });
279
+ if (!y.rowCount) return { status: 404, body: { error: 'not_found' } };
280
if (y.rows[0].student_user_id !== req.identity.sub) {
258
- return res.status(403).json({ error: 'forbidden' });
281
+ return { status: 403, body: { error: 'forbidden' } };
282
}
283
if (!y.rows[0].active || body.startsOn < y.rows[0].starts_on || body.endsOn > y.rows[0].ends_on) {
261
- return res.status(400).json({ error: 'invalid_academic_term' });
284
+ return { status: 400, body: { error: 'invalid_academic_term' } };
285
}
263
- const r = await pool.query(
286
+ const r = await client.query(
287
`insert into academic_term(academic_year_id,title,starts_on,ends_on)
288
values($1,$2,$3,$4) returning *`,
289
[req.params.yearId, String(body.title ?? '').trim(), body.startsOn, body.endsOn],
290
);
268
- res.status(201).json(r.rows[0]);
269
- });
291
+ return { status: 201, body: r.rows[0] };
292
+ }));
293
271
- router.post('/school/terms/:termId/subjects', auth, async (req, res) => {
294
+ router.post('/school/terms/:termId/subjects', auth, schoolRoute(pool, async (req, client) => {
295
const body = req.body ?? {};
296
if (!validUuid(req.params.termId) || !schoolText(body.name) ||
297
!schoolOptionalText(body.teacherName) ||
275
- !schoolOptionalText(body.colorKey, 40)) return res.status(400).json({ error: 'invalid_subject' });
276
- const t = await pool.query(
298
+ !schoolOptionalText(body.colorKey, 40)) return { status: 400, body: { error: 'invalid_subject' } };
299
+ const t = await client.query(
300
`select y.student_user_id
301
from academic_term t
302
join academic_year y on y.id=t.academic_year_id
303
join life_context l on l.id=y.life_context_id
281
- where t.id=$1 and y.active and l.active`,
304
+ where t.id=$1 and t.active and y.active and l.active`,
305
[req.params.termId],
306
);
284
- if (!t.rowCount) return res.status(404).json({ error: 'not_found' });
307
+ if (!t.rowCount) return { status: 404, body: { error: 'not_found' } };
308
if (t.rows[0].student_user_id !== req.identity.sub) {
286
- return res.status(403).json({ error: 'forbidden' });
309
+ return { status: 403, body: { error: 'forbidden' } };
310
}
311
const name = String(body.name ?? '').trim();
289
- if (!name) return res.status(400).json({ error: 'invalid_subject' });
290
- const r = await pool.query(
312
+ if (!name) return { status: 400, body: { error: 'invalid_subject' } };
313
+ const r = await client.query(
314
`insert into subject(student_user_id,academic_term_id,name,teacher_name,color_key)
315
values($1,$2,$3,$4,$5) returning *`,
316
[req.identity.sub, req.params.termId, name, body.teacherName?.trim() || null, body.colorKey?.trim() || null],
317
);
295
- res.status(201).json(r.rows[0]);
296
- });
318
+ return { status: 201, body: r.rows[0] };
319
+ }));
320
298
- router.get('/school/:studentUserId/overview', auth, async (req, res) => {
321
+ router.get('/school/:studentUserId/overview', auth, schoolRoute(pool, async (req, client) => {
322
const studentUserId = req.params.studentUserId;
300
- if (!(await assertStudentAcademic(pool, studentUserId, req.identity.sub))) {
301
- return res.status(403).json({ error: 'forbidden' });
323
+ if (!(await assertStudentAcademic(client, studentUserId, req.identity.sub))) {
324
+ return { status: 403, body: { error: 'forbidden' } };
325
}
326
const [years, subjects, workload, grades] = await Promise.all([
304
- pool.query(
305
- `select y.* from academic_year y where y.student_user_id=$1 and y.active
327
+ client.query(
328
+ `select y.* from academic_year y join life_context l on l.id=y.life_context_id where y.student_user_id=$1 and l.user_id=$1 and y.active and l.active
329
and ($1=$2 or exists(select 1 from academic_term t join subject s on s.academic_term_id=t.id
330
join plan_item p on p.subject_id=s.id where t.academic_year_id=y.id and can_view_plan_item($2,p.id)))
331
order by y.starts_on desc`,
332
[studentUserId, req.identity.sub],
333
),
311
- pool.query(
334
+ client.query(
335
`select s.*,t.title as term_title,y.title as year_title
336
from subject s join academic_term t on t.id=s.academic_term_id
337
join academic_year y on y.id=t.academic_year_id
315
- where s.student_user_id=$1 and s.archived_at is null and ($1=$2 or exists(select 1 from plan_item p
338
+ join life_context l on l.id=y.life_context_id
339
+ where t.active and y.active and l.active and l.user_id=$1 and s.student_user_id=$1 and s.archived_at is null and ($1=$2 or exists(select 1 from plan_item p
340
where p.subject_id=s.id and can_view_plan_item($2,p.id))) order by s.name`,
341
[studentUserId, req.identity.sub],
342
),
319
- pool.query(
343
+ client.query(
344
`select *
345
from plan_item
346
where owner_user_id=$1 and can_view_plan_item($2,id)
@@ -325,7 +349,7 @@ export function createPhase3Router({ pool, auth }) {
349
order by coalesce(due_at,starts_at) nulls last`,
350
[studentUserId, req.identity.sub],
351
),
328
- pool.query(
352
+ client.query(
353
`select id,title,subject_id,grade_points,grade_out_of,due_at
354
from plan_item
355
where owner_user_id=$1 and can_view_plan_item($2,id)
@@ -335,29 +359,34 @@ export function createPhase3Router({ pool, auth }) {
359
[studentUserId, req.identity.sub],
360
),
361
]);
338
- res.json({
362
+ if (!(await assertStudentAcademic(client, studentUserId, req.identity.sub))) return { status: 403, body: { error: 'forbidden' } };
363
+ return { status: 200, body: {
364
years: years.rows,
365
subjects: subjects.rows,
366
workload: workload.rows.map((item) => serializePlanItem(item, req.identity.sub)),
367
grades: grades.rows,
343
- });
344
- });
368
+ } };
369
+ }, false));
370
346
- router.get('/school/:studentUserId/timetable', auth, async (req, res) => {
347
- if (!(await assertStudentAcademic(pool, req.params.studentUserId, req.identity.sub))) {
348
- return res.status(403).json({ error: 'forbidden' });
371
+ router.get('/school/:studentUserId/timetable', auth, schoolRoute(pool, async (req, client) => {
372
+ if (!(await assertStudentAcademic(client, req.params.studentUserId, req.identity.sub))) {
373
+ return { status: 403, body: { error: 'forbidden' } };
374
}
350
- const r = await pool.query(
375
+ const r = await client.query(
376
`select c.*,s.name as subject_name,s.color_key
377
from class_session c
378
join subject s on s.id=c.subject_id
354
- where s.student_user_id=$1 and s.archived_at is null and c.archived_at is null and ($1=$2 or exists(select 1 from plan_item p
379
+ join academic_term t on t.id=s.academic_term_id
380
+ join academic_year y on y.id=t.academic_year_id
381
+ join life_context l on l.id=y.life_context_id
382
+ where t.active and y.active and l.active and l.user_id=$1 and s.student_user_id=$1 and s.archived_at is null and c.archived_at is null and ($1=$2 or exists(select 1 from plan_item p
383
where p.subject_id=s.id and can_view_plan_item($2,p.id)))
384
order by c.weekday,c.starts_at`,
385
[req.params.studentUserId, req.identity.sub],
386
);
359
- res.json({ classes: r.rows });
360
- });
387
+ if (!(await assertStudentAcademic(client, req.params.studentUserId, req.identity.sub))) return { status: 403, body: { error: 'forbidden' } };
388
+ return { status: 200, body: { classes: r.rows } };
389
+ }, false));
390
391
router.patch('/school/plan-items/:itemId/grade', auth, async (req, res) => {
392
const access = await assertPlanWrite(pool, req.params.itemId, req.identity.sub);
backend/src/phase4.js
+177
-47
@@ -1,9 +1,139 @@
1
import express from 'express';
2
+import crypto from 'node:crypto';
3
4
const clampText = (value, max = 4000) =>
5
String(value ?? '').trim().slice(0, max);
6
const isUuid = (value) => typeof value === 'string' && /^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(value);
7
8
+const modernGoalRequest = body => body && ['mutationId','expectedVersion','id'].some(key=>Object.hasOwn(body,key));
9
+function normalizeGoalMutation(operation, id, body, legacy = false) {
10
+ const fields = new Set([...(legacy?[]:['mutationId','expectedVersion',...(operation==='create'?['id']:[])]),
11
+ ...(operation==='archive'?[]:['title','target','subjectId','status'])]);
12
+ if (!body || typeof body !== 'object' || Array.isArray(body) || Object.keys(body).some(key=>!fields.has(key)) ||
13
+ (!legacy && (!isUuid(body.mutationId) || !Number.isSafeInteger(body.expectedVersion) || body.expectedVersion<0 ||
14
+ body.expectedVersion>=2147483647 || (operation==='create' ? (!isUuid(body.id) || body.expectedVersion!==0) : body.expectedVersion===0))) ||
15
+ !isUuid(id)) return null;
16
+ const normalized = {operation,id:id.toLowerCase(),...(legacy?{}:{mutationId:body.mutationId.toLowerCase(),expectedVersion:body.expectedVersion})};
17
+ for (const field of ['title','target']) {
18
+ if (!Object.hasOwn(body,field)) continue;
19
+ if (field==='target' && body[field]===null) { normalized[field]=null; continue; }
20
+ if (typeof body[field]!=='string' || body[field].includes('\u0000') ||
21
+ body[field].trim().length>(field==='title'?240:1000) || (field==='title' && !body[field].trim())) return null;
22
+ normalized[field]=body[field].trim() || null;
23
+ }
24
+ if (operation==='create' && !normalized.title) return null;
25
+ if (Object.hasOwn(body,'subjectId')) {
26
+ if (body.subjectId!==null && !isUuid(body.subjectId)) return null;
27
+ normalized.subjectId=body.subjectId?.toLowerCase()??null;
28
+ }
29
+ if (Object.hasOwn(body,'status')) {
30
+ if (!['active','completed','archived'].includes(body.status) || (operation==='create' && body.status==='archived')) return null;
31
+ normalized.status=body.status;
32
+ }
33
+ if(operation==='update' && !['title','target','subjectId','status'].some(key=>Object.hasOwn(normalized,key))) return null;
34
+ return normalized;
35
+}
36
+
37
+function legacyGoalInputError(body) {
38
+ if(body && typeof body==='object' && !Array.isArray(body)) {
39
+ if(body.subjectId!=null && !isUuid(body.subjectId)) return 'invalid_subject_id';
40
+ if(Object.hasOwn(body,'status') && !['active','completed','archived'].includes(body.status)) return 'invalid_status';
41
+ }
42
+ return 'invalid_input';
43
+}
44
+
45
+async function goalSessionCurrent(client, identity) {
46
+ // Lock the session through commit so logout/revocation cannot race the final
47
+ // authorization decision. JWT expiry must also be checked after lock waits.
48
+ const session=await client.query(`select 1 from auth_session s join app_user u on u.id=s.user_id
49
+ where s.id=$1 and s.user_id=$2 and s.revoked_at is null
50
+ and s.expires_at>statement_timestamp() and u.disabled_at is null for share of s`,[identity.sid,identity.sub]);
51
+ return session.rowCount>0 && (identity.exp==null || identity.exp*1000>Date.now());
52
+}
53
+
54
+async function activeGoalSubject(client, id, owner) {
55
+ const subject=await client.query(`select s.id from subject s
56
+ join academic_term t on t.id=s.academic_term_id
57
+ join academic_year y on y.id=t.academic_year_id
58
+ join life_context l on l.id=y.life_context_id
59
+ where s.id=$1 and s.student_user_id=$2 and y.student_user_id=$2 and l.user_id=$2
60
+ and s.archived_at is null and t.active and y.active and l.active and l.kind='student'
61
+ for share of s,t,y,l`,[id,owner]);
62
+ return subject.rowCount>0;
63
+}
64
+
65
+async function legacyGoalWrite(pool, identity, operation) {
66
+ const client=await pool.connect();
67
+ try {
68
+ await client.query('begin');
69
+ const account=await client.query('select id from app_user where id=$1 and disabled_at is null for update',[identity.sub]);
70
+ if(!account.rowCount || !await goalSessionCurrent(client,identity)) {
71
+ await client.query('rollback'); return {status:401,body:{error:'session_invalid'}};
72
+ }
73
+ const result=await operation(client);
74
+ if(!await goalSessionCurrent(client,identity)) {
75
+ await client.query('rollback'); return {status:401,body:{error:'session_invalid'}};
76
+ }
77
+ await client.query('commit'); return result;
78
+ } catch(error) { await client.query('rollback').catch(()=>{}); throw error; }
79
+ finally { client.release(); }
80
+}
81
+
82
+async function mutateLearningGoal(pool, identity, operation, id, raw) {
83
+ const owner=identity.sub;
84
+ const body=normalizeGoalMutation(operation,id,raw);
85
+ if(!body) return {status:400,body:{error:'invalid_goal_mutation'}};
86
+ const hash=crypto.createHash('sha256').update(JSON.stringify(body)).digest('hex');
87
+ const client=await pool.connect();
88
+ const failure=(status,error)=>({status,body:{error}});
89
+ try {
90
+ await client.query('begin');
91
+ const active=await client.query('select id from app_user where id=$1 and disabled_at is null for update',[owner]);
92
+ if(!active.rowCount || !await goalSessionCurrent(client,identity)) { await client.query('rollback'); return failure(401,'session_invalid'); }
93
+ // Owner locks alone do not serialize two independent accounts that supply
94
+ // the same stable UUID. Lock that entity before checking/inserting it, then
95
+ // return the ordinary forbidden response instead of leaking a PK/500 race.
96
+ await client.query("select pg_advisory_xact_lock(hashtextextended('lifeguide:learning-goal:'||$1,0))",[body.id]);
97
+ const previous=(await client.query('select * from learning_goal_mutation where owner_user_id=$1 and mutation_id=$2',[owner,body.mutationId])).rows[0];
98
+ if(previous && previous.request_hash!==hash) { await client.query('rollback'); return failure(409,'mutation_id_reused'); }
99
+ let goal=(await client.query('select * from learning_goal where id=$1 and owner_user_id=$2 for update',[body.id,owner])).rows[0];
100
+ const acknowledgement = (row,ledger,status) => ({goal:row,acknowledgement:{mutationId:body.mutationId,
101
+ goalId:body.id,operation,appliedVersion:ledger.applied_version,acceptedAt:ledger.accepted_at,status}});
102
+ if(previous) {
103
+ // Return the current tombstone/current version, never resurrect an older response.
104
+ if(!goal) throw new Error('learning_goal_ledger_invariant');
105
+ if(!await goalSessionCurrent(client,identity)) { await client.query('rollback'); return failure(401,'session_invalid'); }
106
+ await client.query('commit');
107
+ return {status:200,body:acknowledgement(goal,previous,'already_applied')};
108
+ }
109
+ if(!goal) {
110
+ const foreign=await client.query('select 1 from learning_goal where id=$1',[body.id]);
111
+ if(foreign.rowCount || operation!=='create') { await client.query('rollback'); return failure(foreign.rowCount?403:404,foreign.rowCount?'goal_forbidden':'goal_not_found'); }
112
+ } else if(operation==='create') { await client.query('rollback'); return failure(409,'goal_id_exists'); }
113
+ if(goal && goal.status==='archived') { await client.query('rollback'); return failure(409,'goal_archived'); }
114
+ if(goal && goal.version!==body.expectedVersion) { await client.query('rollback'); return failure(409,'version_conflict'); }
115
+ if(body.subjectId!=null) {
116
+ if(!await activeGoalSubject(client,body.subjectId,owner)) { await client.query('rollback'); return failure(403,'subject_forbidden'); }
117
+ }
118
+ if(operation==='create') {
119
+ goal=(await client.query('insert into learning_goal(id,owner_user_id,subject_id,title,target,status) values($1,$2,$3,$4,$5,$6) returning *',
120
+ [body.id,owner,body.subjectId??null,body.title,body.target??null,body.status??'active'])).rows[0];
121
+ } else {
122
+ const status=operation==='archive'?'archived':body.status??goal.status;
123
+ goal=(await client.query(`update learning_goal set title=$3,target=$4,subject_id=$5,status=$6,
124
+ version=version+1,updated_at=now(),archived_at=case when $6='archived' then now() else null end
125
+ where id=$1 and owner_user_id=$2 returning *`,[body.id,owner,body.title??goal.title,
126
+ Object.hasOwn(body,'target')?body.target:goal.target,Object.hasOwn(body,'subjectId')?body.subjectId:goal.subject_id,status])).rows[0];
127
+ }
128
+ const ledger=(await client.query('insert into learning_goal_mutation(owner_user_id,mutation_id,goal_id,operation,request_hash,applied_version) values($1,$2,$3,$4,$5,$6) returning *',
129
+ [owner,body.mutationId,body.id,operation,hash,goal.version])).rows[0];
130
+ if(!await goalSessionCurrent(client,identity)) { await client.query('rollback'); return failure(401,'session_invalid'); }
131
+ await client.query('commit');
132
+ return {status:operation==='create'?201:200,body:acknowledgement(goal,ledger,'accepted')};
133
+ } catch(error) { await client.query('rollback').catch(()=>{}); throw error; }
134
+ finally { client.release(); }
135
+}
136
+
137
function safetyClass(text) {
138
const value = text.toLowerCase();
139
if (/(خودکشی|خودم را بکشم|آسیب به خود|self[- ]?harm|suicide|kill myself)/i.test(value)) {
@@ -51,26 +181,22 @@ export function createPhase4Router({ pool, auth, sensitiveFeaturesEnabled = proc
181
router.use(auth);
182
183
router.post('/learning/goals', async (req, res) => {
54
- const title = clampText(req.body.title, 240);
55
- if (!title) return res.status(400).json({ error: 'invalid_input' });
56
- if (req.body.subjectId != null && !isUuid(req.body.subjectId)) return res.status(400).json({ error: 'invalid_subject_id' });
57
- if (req.body.subjectId) {
58
- const subject = await pool.query(
59
- 'select 1 from subject where id=$1 and student_user_id=$2',
60
- [req.body.subjectId, req.identity.sub],
61
- );
62
- if (!subject.rowCount) return res.status(403).json({ error: 'subject_forbidden' });
184
+ if(Object.keys(req.query).length) return res.status(400).json({error:'invalid_goal_mutation'});
185
+ if(modernGoalRequest(req.body)) {
186
+ const result=await mutateLearningGoal(pool,req.identity,'create',req.body.id,req.body);
187
+ return res.status(result.status).json(result.body);
188
}
64
- const result = await pool.query(
65
- 'insert into learning_goal(owner_user_id,subject_id,title,target) values($1,$2,$3,$4) returning *',
66
- [
67
- req.identity.sub,
68
- req.body.subjectId || null,
69
- title,
70
- clampText(req.body.target, 1000) || null,
71
- ],
72
- );
73
- res.status(201).json(result.rows[0]);
189
+ const body=normalizeGoalMutation('create',crypto.randomUUID(),req.body,true);
190
+ if(!body) return res.status(400).json({error:legacyGoalInputError(req.body)});
191
+ const result=await legacyGoalWrite(pool,req.identity,async client=>{
192
+ if(body.subjectId!=null && !await activeGoalSubject(client,body.subjectId,req.identity.sub)) {
193
+ return {status:403,body:{error:'subject_forbidden'}};
194
+ }
195
+ const created=await client.query('insert into learning_goal(owner_user_id,subject_id,title,target,status) values($1,$2,$3,$4,$5) returning *',
196
+ [req.identity.sub,body.subjectId??null,body.title,body.target??null,body.status??'active']);
197
+ return {status:201,body:created.rows[0]};
198
+ });
199
+ res.status(result.status).json(result.body);
200
});
201
202
router.get('/learning/goals', async (req, res) => {
@@ -78,7 +204,7 @@ export function createPhase4Router({ pool, auth, sensitiveFeaturesEnabled = proc
204
"select * from learning_goal where owner_user_id=$1 and status<>'archived' order by created_at desc",
205
[req.identity.sub],
206
);
81
- res.json({ items: result.rows });
207
+ res.json({ items: result.rows, fetchedAt: new Date().toISOString() });
208
});
209
210
router.get('/learning/goals/:id', async (req, res) => {
@@ -90,54 +216,58 @@ export function createPhase4Router({ pool, auth, sensitiveFeaturesEnabled = proc
216
217
router.patch('/learning/goals/:id', async (req, res) => {
218
if (!isUuid(req.params.id)) return res.status(400).json({ error: 'invalid_goal_id' });
93
- const body = req.body ?? {};
219
+ if(Object.keys(req.query).length) return res.status(400).json({error:'invalid_goal_mutation'});
220
+ if(modernGoalRequest(req.body)) {
221
+ const result=await mutateLearningGoal(pool,req.identity,'update',req.params.id,req.body);
222
+ return res.status(result.status).json(result.body);
223
+ }
224
+ const body=normalizeGoalMutation('update',req.params.id,req.body,true);
225
+ if(!body) return res.status(400).json({error:legacyGoalInputError(req.body)});
226
const has = (field) => Object.hasOwn(body, field);
95
- if (has('title') && (typeof body.title !== 'string' || !body.title.trim() || body.title.trim().length > 240)) return res.status(400).json({ error: 'invalid_input' });
96
- if (has('target') && body.target != null && (typeof body.target !== 'string' || body.target.trim().length > 1000)) return res.status(400).json({ error: 'invalid_input' });
97
- if (has('subjectId') && body.subjectId != null && !isUuid(body.subjectId)) return res.status(400).json({ error: 'invalid_subject_id' });
98
- if (has('status') && !['active', 'completed', 'archived'].includes(body.status)) return res.status(400).json({ error: 'invalid_status' });
99
- const client = await pool.connect();
100
- try {
101
- await client.query('begin');
227
+ const result=await legacyGoalWrite(pool,req.identity,async client=>{
228
const goal = await client.query('select status from learning_goal where id=$1 and owner_user_id=$2 for update', [req.params.id, req.identity.sub]);
229
if (!goal.rowCount || goal.rows[0].status === 'archived') {
104
- await client.query('rollback');
105
- return res.status(goal.rowCount ? 409 : 404).json({ error: goal.rowCount ? 'goal_archived' : 'goal_not_found' });
230
+ return {status:goal.rowCount?409:404,body:{error:goal.rowCount?'goal_archived':'goal_not_found'}};
231
}
232
if (body.subjectId != null) {
108
- const subject = await client.query('select 1 from subject where id=$1 and student_user_id=$2', [body.subjectId, req.identity.sub]);
109
- if (!subject.rowCount) {
110
- await client.query('rollback');
111
- return res.status(403).json({ error: 'subject_forbidden' });
112
- }
233
+ if(!await activeGoalSubject(client,body.subjectId,req.identity.sub)) return {status:403,body:{error:'subject_forbidden'}};
234
}
114
- const result = await client.query(
235
+ const updated = await client.query(
236
`update learning_goal set title=case when $3 then $4 else title end,
237
target=case when $5 then $6 else target end,
238
subject_id=case when $7 then $8::uuid else subject_id end,
118
- status=coalesce($9,status),updated_at=now()
239
+ status=coalesce($9,status),updated_at=now(),version=version+1,
240
+ archived_at=case when $9='archived' then now() else null end
241
where id=$1 and owner_user_id=$2 returning *`,
242
[req.params.id, req.identity.sub, has('title'), has('title') ? body.title.trim() : null,
243
has('target'), body.target?.trim() || null, has('subjectId'), body.subjectId ?? null, body.status ?? null],
244
);
123
- await client.query('commit');
124
- res.json(result.rows[0]);
125
- } catch (error) {
126
- await client.query('rollback').catch(() => {});
127
- throw error;
128
- } finally { client.release(); }
245
+ return {status:200,body:updated.rows[0]};
246
+ });
247
+ res.status(result.status).json(result.body);
248
});
249
250
router.delete('/learning/goals/:id', async (req, res) => {
251
if (!isUuid(req.params.id)) return res.status(400).json({ error: 'invalid_goal_id' });
133
- const result = await pool.query(
252
+ if(Object.keys(req.query).length) return res.status(400).json({error:'invalid_goal_mutation'});
253
+ if(modernGoalRequest(req.body)) {
254
+ const result=await mutateLearningGoal(pool,req.identity,'archive',req.params.id,req.body);
255
+ return res.status(result.status).json(result.body);
256
+ }
257
+ if(!normalizeGoalMutation('archive',req.params.id,req.body??{},true)) return res.status(400).json({error:'invalid_input'});
258
+ const result=await legacyGoalWrite(pool,req.identity,async client=>{
259
+ const archived = await client.query(
260
`update learning_goal set status='archived',
261
+ archived_at=coalesce(archived_at,now()),
262
+ version=case when status='archived' then version else version+1 end,
263
updated_at=case when status='archived' then updated_at else now() end
264
where id=$1 and owner_user_id=$2 returning id`,
265
[req.params.id, req.identity.sub],
138
- );
139
- if (!result.rowCount) return res.status(404).json({ error: 'goal_not_found' });
140
- res.status(204).end();
266
+ );
267
+ return archived.rowCount?{status:204}:{status:404,body:{error:'goal_not_found'}};
268
+ });
269
+ if(result.body===undefined) return res.status(result.status).end();
270
+ res.status(result.status).json(result.body);
271
});
272
273
router.post('/wellbeing/checkins', requireSensitive, async (req, res) => {
backend/src/school_crud_router.js
+27
-20
@@ -1,4 +1,5 @@
1
import express from 'express';
2
+import { schoolLifecycleError, assertSchoolSession } from './school_lifecycle.js';
3
4
const uuid = (value) => typeof value === 'string' && /^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(value);
5
const has = (body, key) => Object.hasOwn(body, key);
@@ -31,16 +32,21 @@ function occurred(value) {
32
const checkinRow = (row) => ({ ...row, isEvidenceOfStudy: false });
33
const route = (handler) => async (req, res, next) => {
34
try { await handler(req, res); }
34
- catch (error) {
35
- if (error instanceof SchoolInputError) return res.status(error.status).json({ error: error.code });
35
+ catch (raw) {
36
+ const error = schoolLifecycleError(raw);
37
+ if (error instanceof SchoolInputError || (error.status && (error.code?.startsWith('school_') || error.code === 'session_invalid'))) return res.status(error.status).json({ error: error.code });
38
next(error);
39
}
40
};
39
-async function transaction(pool, operation) {
41
+async function transaction(pool, operation, identity, write = true) {
42
const client = await pool.connect();
43
try {
44
await client.query('begin');
45
+ const account = await client.query(`select 1 from app_user where id=$1 and disabled_at is null for ${write ? 'update' : 'share'}`, [identity.sub]);
46
+ if (!account.rowCount) fail(401, 'session_invalid');
47
+ await assertSchoolSession(client, identity);
48
const result = await operation(client);
49
+ await assertSchoolSession(client, identity);
50
await client.query('commit');
51
return result;
52
} catch (error) {
@@ -52,7 +58,7 @@ async function ownedTerm(client, termId, userId, status = 403) {
58
const result = await client.query(`select t.*,t.starts_on::text as first_day,t.ends_on::text as last_day
59
from academic_term t join academic_year y on y.id=t.academic_year_id
60
join life_context l on l.id=y.life_context_id
55
- where t.id=$1 and y.student_user_id=$2 and l.user_id=$2 and y.active and l.active
61
+ where t.id=$1 and y.student_user_id=$2 and l.user_id=$2 and t.active and y.active and l.active
62
for share of t,y,l`, [termId, userId]);
63
if (!result.rowCount) fail(status, status === 403 ? 'academic_term_forbidden' : 'school_parent_inactive');
64
return result.rows[0];
@@ -108,11 +114,11 @@ export function createSchoolCrudRouter({ pool, auth }) {
114
if (next.recurrence_until && (next.recurrence_until < term.first_day || next.recurrence_until > term.last_day)) fail(400, 'class_recurrence_outside_term');
115
return (await client.query(`insert into class_session(subject_id,weekday,starts_at,ends_at,location,recurrence_until)
116
values($1,$2,$3,$4,$5,$6) returning *`, [subjectId, next.weekday, next.starts_at, next.ends_at, next.location, next.recurrence_until])).rows[0];
111
- });
117
+ }, req.identity);
118
res.status(201).json(result);
119
}));
120
router.get('/school/subjects/:id', auth, route(async (req, res) => {
115
- const result = await pool.query('select * from subject where id=$1 and student_user_id=$2', [id(req.params.id), req.identity.sub]);
121
+ const result = await transaction(pool, (client) => client.query('select * from subject where id=$1 and student_user_id=$2', [id(req.params.id), req.identity.sub]), req.identity, false);
122
if (!result.rowCount) fail(404, 'subject_not_found');
123
res.json(result.rows[0]);
124
}));
@@ -127,6 +133,7 @@ export function createSchoolCrudRouter({ pool, auth }) {
133
const current = await client.query('select * from subject where id=$1 and student_user_id=$2 for update', [subjectId, req.identity.sub]);
134
if (!current.rowCount) fail(404, 'subject_not_found');
135
if (current.rows[0].archived_at) fail(409, 'subject_archived');
136
+ await ownedTerm(client, current.rows[0].academic_term_id, req.identity.sub, 409);
137
const termId = body.academicTermId ?? current.rows[0].academic_term_id;
138
const term = await ownedTerm(client, termId, req.identity.sub, has(body, 'academicTermId') ? 403 : 409);
139
const invalidClass = await client.query(`select 1 from class_session where subject_id=$1 and archived_at is null
@@ -136,19 +143,19 @@ export function createSchoolCrudRouter({ pool, auth }) {
143
teacher_name=case when $4 then $5 else teacher_name end,
144
color_key=case when $6 then $7 else color_key end,academic_term_id=$8,updated_at=now()
145
where id=$1 and student_user_id=$2 returning *`, [subjectId, req.identity.sub, name, has(body, 'teacherName'), teacher, has(body, 'colorKey'), color, termId])).rows[0];
139
- });
146
+ }, req.identity);
147
res.json(result);
148
}));
149
router.delete('/school/subjects/:id', auth, route(async (req, res) => {
143
- const result = await pool.query(`update subject set updated_at=case when archived_at is null then now() else updated_at end,
144
- archived_at=coalesce(archived_at,now()) where id=$1 and student_user_id=$2 returning id`, [id(req.params.id), req.identity.sub]);
150
+ const result = await transaction(pool, (client) => client.query(`update subject set updated_at=case when archived_at is null then now() else updated_at end,
151
+ archived_at=coalesce(archived_at,now()) where id=$1 and student_user_id=$2 returning id`, [id(req.params.id), req.identity.sub]), req.identity);
152
if (!result.rowCount) fail(404, 'subject_not_found');
153
res.status(204).end();
154
}));
155
156
router.get('/school/classes/:id', auth, route(async (req, res) => {
150
- const result = await pool.query(`select c.*,s.name as subject_name,s.archived_at as subject_archived_at
151
- from class_session c join subject s on s.id=c.subject_id where c.id=$1 and s.student_user_id=$2`, [id(req.params.id), req.identity.sub]);
157
+ const result = await transaction(pool, (client) => client.query(`select c.*,s.name as subject_name,s.archived_at as subject_archived_at
158
+ from class_session c join subject s on s.id=c.subject_id where c.id=$1 and s.student_user_id=$2`, [id(req.params.id), req.identity.sub]), req.identity, false);
159
if (!result.rowCount) fail(404, 'class_not_found');
160
res.json(result.rows[0]);
161
}));
@@ -169,13 +176,13 @@ export function createSchoolCrudRouter({ pool, auth }) {
176
if (next.recurrence_until && (next.recurrence_until < term.first_day || next.recurrence_until > term.last_day)) fail(400, 'class_recurrence_outside_term');
177
return (await client.query(`update class_session set subject_id=$2,weekday=$3,starts_at=$4,ends_at=$5,
178
location=$6,recurrence_until=$7,updated_at=now() where id=$1 returning *`, [classId, subjectId, next.weekday, next.starts_at, next.ends_at, next.location, next.recurrence_until])).rows[0];
172
- });
179
+ }, req.identity);
180
res.json(result);
181
}));
182
router.delete('/school/classes/:id', auth, route(async (req, res) => {
176
- const result = await pool.query(`update class_session c set updated_at=case when c.archived_at is null then now() else c.updated_at end,
183
+ const result = await transaction(pool, (client) => client.query(`update class_session c set updated_at=case when c.archived_at is null then now() else c.updated_at end,
184
archived_at=coalesce(c.archived_at,now()) from subject s
178
- where c.id=$1 and c.subject_id=s.id and s.student_user_id=$2 returning c.id`, [id(req.params.id), req.identity.sub]);
185
+ where c.id=$1 and c.subject_id=s.id and s.student_user_id=$2 returning c.id`, [id(req.params.id), req.identity.sub]), req.identity);
186
if (!result.rowCount) fail(404, 'class_not_found');
187
res.status(204).end();
188
}));
@@ -188,15 +195,15 @@ export function createSchoolCrudRouter({ pool, auth }) {
195
await ownedGoal(client, next.learning_goal_id, req.identity.sub);
196
return (await client.query(`insert into learning_checkin(owner_user_id,learning_goal_id,confidence,difficulty,note,occurred_at)
197
values($1,$2,$3,$4,$5,$6) returning *`, [req.identity.sub, next.learning_goal_id, next.confidence, next.difficulty, next.note, next.occurred_at])).rows[0];
191
- });
198
+ }, req.identity);
199
res.status(201).json(checkinRow(result));
200
}));
201
router.get('/learning/checkins', auth, route(async (req, res) => {
195
- const result = await pool.query('select * from learning_checkin where owner_user_id=$1 and archived_at is null order by occurred_at desc,id', [req.identity.sub]);
202
+ const result = await transaction(pool, (client) => client.query('select * from learning_checkin where owner_user_id=$1 and archived_at is null order by occurred_at desc,id', [req.identity.sub]), req.identity, false);
203
res.json({ items: result.rows.map(checkinRow) });
204
}));
205
router.get('/learning/checkins/:id', auth, route(async (req, res) => {
199
- const result = await pool.query('select * from learning_checkin where id=$1 and owner_user_id=$2', [id(req.params.id), req.identity.sub]);
206
+ const result = await transaction(pool, (client) => client.query('select * from learning_checkin where id=$1 and owner_user_id=$2', [id(req.params.id), req.identity.sub]), req.identity, false);
207
if (!result.rowCount) fail(404, 'checkin_not_found');
208
res.json(checkinRow(result.rows[0]));
209
}));
@@ -211,12 +218,12 @@ export function createSchoolCrudRouter({ pool, auth }) {
218
if (has(body, 'learningGoalId')) await ownedGoal(client, next.learning_goal_id, req.identity.sub);
219
return (await client.query(`update learning_checkin set learning_goal_id=$3,confidence=$4,difficulty=$5,note=$6,
220
occurred_at=$7,updated_at=now() where id=$1 and owner_user_id=$2 returning *`, [checkinId, req.identity.sub, next.learning_goal_id, next.confidence, next.difficulty, next.note, next.occurred_at])).rows[0];
214
- });
221
+ }, req.identity);
222
res.json(checkinRow(result));
223
}));
224
router.delete('/learning/checkins/:id', auth, route(async (req, res) => {
218
- const result = await pool.query(`update learning_checkin set updated_at=case when archived_at is null then now() else updated_at end,
219
- archived_at=coalesce(archived_at,now()) where id=$1 and owner_user_id=$2 returning id`, [id(req.params.id), req.identity.sub]);
225
+ const result = await transaction(pool, (client) => client.query(`update learning_checkin set updated_at=case when archived_at is null then now() else updated_at end,
226
+ archived_at=coalesce(archived_at,now()) where id=$1 and owner_user_id=$2 returning id`, [id(req.params.id), req.identity.sub]), req.identity);
227
if (!result.rowCount) fail(404, 'checkin_not_found');
228
res.status(204).end();
229
}));
backend/src/school_lifecycle.js
new
+143
@@ -0,0 +1,143 @@
1
+import crypto from 'node:crypto';
2
+import express from 'express';
3
+
4
+const UUID = /^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i;
5
+const TYPES = { contexts: 'life_context', years: 'academic_year', terms: 'academic_term' };
6
+class InputError extends Error { constructor(status, code) { super(code); this.status = status; this.code = code; } }
7
+const fail = (status, code) => { throw new InputError(status, code); };
8
+const owns = (raw, key) => Object.hasOwn(raw, key);
9
+const uuid = (raw) => { if (typeof raw !== 'string' || !UUID.test(raw)) fail(400, 'invalid_school_id'); return raw.toLowerCase(); };
10
+const title = (raw) => { if (typeof raw !== 'string' || !raw.trim() || raw.trim().length > 120) fail(400, 'invalid_school_title'); return raw.trim(); };
11
+function date(raw) {
12
+ if (typeof raw !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(raw) || raw.startsWith('0000-')) fail(400, 'invalid_school_date');
13
+ const parsed = new Date(`${raw}T00:00:00Z`);
14
+ if (!Number.isFinite(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== raw) fail(400, 'invalid_school_date');
15
+ return raw;
16
+}
17
+export const schoolLifecycleError = (error) => {
18
+ if (error instanceof InputError) return error;
19
+ if (error.code === '23505') return new InputError(409, 'school_entity_conflict');
20
+ if (error.code === '23514' && error.message.startsWith('school_')) {
21
+ const code = error.message.split('\n')[0];
22
+ return new InputError(code.includes('forbidden') ? 403 : code.includes('inactive') || code.includes('in_use') || code.includes('immutable') ? 409 : 400, code);
23
+ }
24
+ return error;
25
+};
26
+const route = (handler) => async (req, res, next) => {
27
+ try { await handler(req, res); }
28
+ catch (raw) { const error = schoolLifecycleError(raw); if (error instanceof InputError) return res.status(error.status).json({error: error.code}); next(error); }
29
+};
30
+export async function assertSchoolSession(client, identity) {
31
+ const session = await client.query(`select 1 from auth_session s join app_user u on u.id=s.user_id
32
+ where s.id=$1 and s.user_id=$2 and s.revoked_at is null
33
+ and s.expires_at>statement_timestamp() and u.disabled_at is null for share of s`, [identity.sid, identity.sub]);
34
+ // statement_timestamp() in the locking SELECT was sampled before any wait.
35
+ // Sample again after the lock is acquired rather than accepting stale time.
36
+ const current = session.rowCount && await client.query(`select 1 from auth_session s join app_user u on u.id=s.user_id
37
+ where s.id=$1 and s.user_id=$2 and s.revoked_at is null
38
+ and s.expires_at>statement_timestamp() and u.disabled_at is null`, [identity.sid, identity.sub]);
39
+ if (!current?.rowCount || (identity.exp != null && identity.exp * 1000 <= Date.now())) fail(401, 'session_invalid');
40
+}
41
+async function transaction(pool, operation, identity, write = false) {
42
+ const client = await pool.connect();
43
+ try {
44
+ await client.query('begin');
45
+ const account = await client.query(`select 1 from app_user where id=$1 and disabled_at is null for ${write ? 'update' : 'share'}`, [identity.sub]);
46
+ if (!account.rowCount) fail(401, 'session_invalid');
47
+ await assertSchoolSession(client, identity);
48
+ const result = await operation(client);
49
+ await assertSchoolSession(client, identity);
50
+ await client.query('commit'); return result;
51
+ }
52
+ catch (error) { await client.query('rollback').catch(() => {}); throw error; }
53
+ finally { client.release(); }
54
+}
55
+function mutation(raw, type) {
56
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw) || Object.keys(raw).some((key) => !['mutationId','entityId','operation','expectedVersion','data'].includes(key))) fail(400, 'invalid_school_mutation');
57
+ const result = { mutationId: uuid(raw.mutationId), entityId: uuid(raw.entityId), operation: raw.operation, expectedVersion: raw.expectedVersion, data: {} };
58
+ if (!['create','update','archive'].includes(result.operation) || !Number.isInteger(result.expectedVersion) || result.expectedVersion < 0 || result.expectedVersion > 2147483646 || (result.operation === 'create' ? result.expectedVersion !== 0 : result.expectedVersion < 1)) fail(400, 'invalid_school_mutation');
59
+ const data = raw.data ?? {};
60
+ if (!data || typeof data !== 'object' || Array.isArray(data)) fail(400, 'invalid_school_data');
61
+ const allowed = result.operation === 'archive' ? [] : type === 'contexts' ? ['title','kind'] : ['title','startsOn','endsOn', ...(result.operation === 'create' ? [type === 'years' ? 'lifeContextId' : 'academicYearId'] : [])];
62
+ if (Object.keys(data).some((key) => !allowed.includes(key))) fail(400, 'invalid_school_data');
63
+ for (const key of allowed) if (owns(data, key)) {
64
+ result.data[key] = key === 'title' ? title(data[key]) : key.endsWith('On') ? date(data[key]) : key.endsWith('Id') ? uuid(data[key]) : data[key];
65
+ }
66
+ if (owns(data, 'kind') && !['student','work','personal'].includes(data.kind)) fail(400, 'invalid_school_kind');
67
+ if (result.operation === 'create' && allowed.some((key) => !owns(data, key))) fail(400, 'invalid_school_data');
68
+ if (result.operation === 'update' && !Object.keys(data).length) fail(400, 'invalid_school_data');
69
+ if (result.data.startsOn && result.data.endsOn && result.data.endsOn < result.data.startsOn) fail(400, 'invalid_school_date_range');
70
+ return result;
71
+}
72
+const projection = (type, alias = 'e') => type === 'contexts' ? `${alias}.*` : `${alias}.*,${alias}.starts_on::text as starts_on,${alias}.ends_on::text as ends_on`;
73
+async function owned(client, type, id, ownerId, lock = false) {
74
+ const sql = type === 'contexts' ? `select ${projection(type)} from life_context e where e.id=$1 and e.user_id=$2` : type === 'years' ? `select ${projection(type)} from academic_year e where e.id=$1 and e.student_user_id=$2` : `select ${projection(type)} from academic_term e join academic_year y on y.id=e.academic_year_id join life_context l on l.id=y.life_context_id where e.id=$1 and y.student_user_id=$2 and l.user_id=$2`;
75
+ return (await client.query(sql + (lock ? ' for update of e' : ''), [id, ownerId])).rows[0];
76
+}
77
+async function parent(client, type, data, ownerId) {
78
+ if (type === 'contexts') return;
79
+ const raw = await owned(client, type === 'years' ? 'contexts' : 'years', type === 'years' ? data.lifeContextId : data.academicYearId, ownerId);
80
+ if (!raw) fail(403, 'school_parent_forbidden');
81
+ if (!raw.active || (type === 'years' && raw.kind !== 'student')) fail(409, 'school_parent_inactive');
82
+ if (type === 'terms') {
83
+ const context = await owned(client, 'contexts', raw.life_context_id, ownerId);
84
+ if (!context?.active || context.kind !== 'student') fail(409, 'school_parent_inactive');
85
+ if (data.startsOn < raw.starts_on || data.endsOn > raw.ends_on) fail(400, 'school_dates_outside_parent');
86
+ }
87
+}
88
+export function createSchoolLifecycleRouter({ pool, auth }) {
89
+ const router = express.Router();
90
+ router.get('/school/lifecycle', auth, route(async (req, res) => {
91
+ const result = await transaction(pool, async (client) => {
92
+ const contexts = (await client.query('select * from life_context where user_id=$1 order by created_at,id limit 501', [req.identity.sub])).rows;
93
+ const years = (await client.query(`select ${projection('years')} from academic_year e join life_context l on l.id=e.life_context_id where e.student_user_id=$1 and l.user_id=$1 order by e.starts_on desc,e.id limit 501`, [req.identity.sub])).rows;
94
+ const terms = (await client.query(`select ${projection('terms')} from academic_term e join academic_year y on y.id=e.academic_year_id join life_context l on l.id=y.life_context_id where y.student_user_id=$1 and l.user_id=$1 order by e.starts_on desc,e.id limit 501`, [req.identity.sub])).rows;
95
+ if ([contexts, years, terms].some((rows) => rows.length > 500)) fail(422, 'school_list_limit_exceeded');
96
+ const fetchedAt = (await client.query('select clock_timestamp() as now')).rows[0].now.toISOString();
97
+ return { contexts, years, terms, fetchedAt };
98
+ }, req.identity);
99
+ res.json(result);
100
+ }));
101
+ router.post('/school/lifecycle/:type/mutations', auth, route(async (req, res) => {
102
+ const type = req.params.type;
103
+ if (!owns(TYPES, type)) fail(404, 'school_entity_type_not_found');
104
+ const body = mutation(req.body, type);
105
+ const requestHash = crypto.createHash('sha256').update(JSON.stringify({ type, ...body })).digest('hex');
106
+ const result = await transaction(pool, async (client) => {
107
+ const ledger = (await client.query('select * from school_lifecycle_mutation where owner_user_id=$1 and mutation_id=$2', [req.identity.sub, body.mutationId])).rows[0];
108
+ if (ledger) {
109
+ if (ledger.request_hash !== requestHash) fail(409, 'school_mutation_reused');
110
+ const entity = await owned(client, type, body.entityId, req.identity.sub);
111
+ if (!entity) fail(404, 'school_entity_not_found');
112
+ return { entity, acknowledgement: { mutationId: body.mutationId, entityId: body.entityId, entityType: type, operation: body.operation, status: 'already_applied', appliedVersion: ledger.applied_version, acceptedAt: ledger.accepted_at.toISOString() } };
113
+ }
114
+ let entity;
115
+ if (body.operation === 'create') {
116
+ const counts = type === 'contexts' ? 'select count(*)::int as n from life_context where user_id=$1' : type === 'years' ? 'select count(*)::int as n from academic_year where student_user_id=$1' : 'select count(*)::int as n from academic_term t join academic_year y on y.id=t.academic_year_id where y.student_user_id=$1';
117
+ if ((await client.query(counts, [req.identity.sub])).rows[0].n >= 500) fail(422, 'school_list_limit_exceeded');
118
+ await parent(client, type, body.data, req.identity.sub);
119
+ if (type === 'contexts') await client.query('insert into life_context(id,user_id,kind,title) values($1,$2,$3,$4)', [body.entityId, req.identity.sub, body.data.kind, body.data.title]);
120
+ else if (type === 'years') await client.query('insert into academic_year(id,student_user_id,life_context_id,title,starts_on,ends_on) values($1,$2,$3,$4,$5,$6)', [body.entityId, req.identity.sub, body.data.lifeContextId, body.data.title, body.data.startsOn, body.data.endsOn]);
121
+ else await client.query('insert into academic_term(id,academic_year_id,title,starts_on,ends_on) values($1,$2,$3,$4,$5)', [body.entityId, body.data.academicYearId, body.data.title, body.data.startsOn, body.data.endsOn]);
122
+ } else {
123
+ const current = await owned(client, type, body.entityId, req.identity.sub, true);
124
+ if (!current) fail(404, 'school_entity_not_found');
125
+ if (current.version !== body.expectedVersion) fail(409, 'school_version_conflict');
126
+ if (!current.active) fail(409, 'school_entity_archived');
127
+ if (body.operation === 'archive') await client.query(`update ${TYPES[type]} set active=false where id=$1`, [body.entityId]);
128
+ else {
129
+ const data = { title: current.title, ...(type === 'contexts' ? { kind: current.kind } : { startsOn: current.starts_on, endsOn: current.ends_on, ...(type === 'years' ? { lifeContextId: current.life_context_id } : { academicYearId: current.academic_year_id }) }), ...body.data };
130
+ if (type !== 'contexts' && data.endsOn < data.startsOn) fail(400, 'invalid_school_date_range');
131
+ await parent(client, type, data, req.identity.sub);
132
+ if (type === 'contexts') await client.query('update life_context set title=$2,kind=$3 where id=$1', [body.entityId, data.title, data.kind]);
133
+ else await client.query(`update ${TYPES[type]} set title=$2,starts_on=$3,ends_on=$4 where id=$1`, [body.entityId, data.title, data.startsOn, data.endsOn]);
134
+ }
135
+ }
136
+ entity = await owned(client, type, body.entityId, req.identity.sub);
137
+ const inserted = (await client.query('insert into school_lifecycle_mutation(owner_user_id,mutation_id,entity_type,entity_id,operation,request_hash,applied_version) values($1,$2,$3,$4,$5,$6,$7) returning accepted_at', [req.identity.sub, body.mutationId, type, body.entityId, body.operation, requestHash, entity.version])).rows[0];
138
+ return { entity, acknowledgement: { mutationId: body.mutationId, entityId: body.entityId, entityType: type, operation: body.operation, status: 'accepted', appliedVersion: entity.version, acceptedAt: inserted.accepted_at.toISOString() } };
139
+ }, req.identity, true);
140
+ res.status(result.acknowledgement.status === 'accepted' && body.operation === 'create' ? 201 : 200).json(result);
141
+ }));
142
+ return router;
143
+}
backend/src/server.js
+100
-9
@@ -9,12 +9,15 @@ import { createPhase6Router } from './phase6.js';
9
import { createLearningLibraryRouter } from './learning_library.js';
10
import { createLearningFeedbackRouter } from './learning_feedback.js';
11
import { createLearningAssessmentRouter } from './learning_assessment.js';
12
+import { createContentReviewRouter } from './content_review.js';
13
+import { createFamilyLifecycleRouter } from './family_lifecycle.js';
14
import { configureTrustedProxy, operationalErrorHandler } from './operations.js';
15
import { createSessionAuth } from './session_auth.js';
16
import { createAuthRouter } from './auth_router.js';
17
import { createStudySessionsRouter } from './study_sessions.js';
18
import { createProfileRouter } from './profile_router.js';
19
import { createSchoolCrudRouter } from './school_crud_router.js';
20
+import { createSchoolLifecycleRouter } from './school_lifecycle.js';
21
import { normalizeEmail, normalizePhone, isEmail } from './auth_contacts.js';
22
import { createEmailProvider, safelyDeliver } from './auth_delivery.js';
23
@@ -65,7 +68,8 @@ async function familyAccess(familyId, userId, { roles = [], admin = false } = {}
68
return (admin && r.rows[0].is_admin) || roles.includes(r.rows[0].role);
69
}
70
68
-async function familyAdminTransaction(familyId, userId, operation) {
71
+async function familyAdminTransaction(familyId, identity, operation) {
72
+ const userId = identity.sub;
73
if (!uuid(familyId)) return { status: 403, body: { error: 'forbidden' } };
74
const client = await pool.connect();
75
try {
@@ -77,6 +81,15 @@ async function familyAdminTransaction(familyId, userId, operation) {
81
and m.is_admin and u.disabled_at is null for update of m,u`, [familyId, userId],
82
) : { rowCount: 0 };
83
const result = membership.rowCount ? await operation(client) : { status: 403, body: { error: 'forbidden' } };
84
+ const session = await client.query(`select 1 from auth_session s join app_user u on u.id=s.user_id
85
+ where s.id=$1 and s.user_id=$2 and s.revoked_at is null
86
+ and s.expires_at>statement_timestamp() and u.disabled_at is null for share of s`, [identity.sid, userId]);
87
+ const freshSession = session.rowCount ? await client.query(`select 1 from auth_session
88
+ where id=$1 and user_id=$2 and revoked_at is null and expires_at>statement_timestamp()`, [identity.sid,userId]) : {rowCount:0};
89
+ if (!freshSession.rowCount || (identity.exp != null && identity.exp * 1000 <= Date.now())) {
90
+ await client.query('rollback');
91
+ return { status: 401, body: { error: 'session_invalid' } };
92
+ }
93
await client.query('commit');
94
return result;
95
} catch (error) {
@@ -125,6 +138,27 @@ app.post('/v1/families', auth, async (req, res) => {
138
const c = await pool.connect();
139
try {
140
await c.query('begin');
141
+ const creator = await c.query('select id from app_user where id=$1 and disabled_at is null for update', [req.identity.sub]);
142
+ if (!creator.rowCount) {
143
+ await c.query('rollback');
144
+ return res.status(401).json({ error: 'session_invalid' });
145
+ }
146
+ // Profiles can be edited without an app_user lock. Acquire that row in a
147
+ // separate statement after the account lock, so a pre-wait join snapshot
148
+ // cannot confer administration using an obsolete birth date.
149
+ const profile = (await c.query(`select birth_date,
150
+ (birth_date is not null and birth_date>(current_date-interval '18 years')::date) known_minor
151
+ from profile where user_id=$1 for update`, [req.identity.sub])).rows[0];
152
+ if (profile?.known_minor) {
153
+ await c.query('rollback');
154
+ return res.status(403).json({ error: 'minor_cannot_admin' });
155
+ }
156
+ if (!profile?.birth_date && (await c.query(`select 1 from family_membership m
157
+ join family_workspace f on f.id=m.family_id where m.user_id=$1 and m.ended_at is null
158
+ and m.role='teen_minor' and f.archived_at is null limit 1`, [req.identity.sub])).rowCount) {
159
+ await c.query('rollback');
160
+ return res.status(403).json({ error: 'age_confirmation_required' });
161
+ }
162
const f = await c.query(
163
'insert into family_workspace(name,created_by) values($1,$2) returning id,name',
164
[name, req.identity.sub],
@@ -137,6 +171,14 @@ app.post('/v1/families', auth, async (req, res) => {
171
"insert into access_audit(actor_user_id,family_id,action,target_type,target_id) values($1,$2,'family.create','family',$3)",
172
[req.identity.sub, f.rows[0].id, String(f.rows[0].id)],
173
);
174
+ const session = await c.query(`select 1 from auth_session where id=$1 and user_id=$2
175
+ and revoked_at is null and expires_at>statement_timestamp() for share`, [req.identity.sid,req.identity.sub]);
176
+ const freshSession = session.rowCount ? await c.query(`select 1 from auth_session
177
+ where id=$1 and user_id=$2 and revoked_at is null and expires_at>statement_timestamp()`, [req.identity.sid,req.identity.sub]) : {rowCount:0};
178
+ if (!freshSession.rowCount || (req.identity.exp != null && req.identity.exp * 1000 <= Date.now())) {
179
+ await c.query('rollback');
180
+ return res.status(401).json({ error: 'session_invalid' });
181
+ }
182
await c.query('commit');
183
res.status(201).json(f.rows[0]);
184
} catch (e) {
@@ -159,7 +201,7 @@ app.get('/v1/families/:familyId', auth, async (req, res) => {
201
app.patch('/v1/families/:familyId', auth, async (req, res) => {
202
const name = String(req.body?.name ?? '').trim();
203
if (!name || name.length > 120) return res.status(400).json({ error: 'invalid_name' });
162
- const result = await familyAdminTransaction(req.params.familyId, req.identity.sub, async (client) => {
204
+ const result = await familyAdminTransaction(req.params.familyId, req.identity, async (client) => {
205
const updated = await client.query('update family_workspace set name=$2 where id=$1 returning id,name', [req.params.familyId, name]);
206
await familyAudit(client, req.params.familyId, req.identity.sub, 'family.rename', 'family', req.params.familyId);
207
return { status: 200, body: updated.rows[0] };
@@ -168,7 +210,7 @@ app.patch('/v1/families/:familyId', auth, async (req, res) => {
210
});
211
212
app.delete('/v1/families/:familyId', auth, async (req, res) => {
171
- const result = await familyAdminTransaction(req.params.familyId, req.identity.sub, async (client) => {
213
+ const result = await familyAdminTransaction(req.params.familyId, req.identity, async (client) => {
214
await client.query('update family_workspace set archived_at=now() where id=$1', [req.params.familyId]);
215
await client.query("update family_invitation set status='revoked' where family_id=$1 and status='pending'", [req.params.familyId]);
216
await client.query('update guardian_relationship set active=false where family_id=$1', [req.params.familyId]);
@@ -180,7 +222,7 @@ app.delete('/v1/families/:familyId', auth, async (req, res) => {
222
223
app.delete('/v1/families/:familyId/members/:userId', auth, async (req, res) => {
224
if (!uuid(req.params.userId)) return res.status(400).json({ error: 'invalid_member' });
183
- const result = await familyAdminTransaction(req.params.familyId, req.identity.sub, async (client) => {
225
+ const result = await familyAdminTransaction(req.params.familyId, req.identity, async (client) => {
226
const target = await client.query('select m.is_admin,u.disabled_at from family_membership m join app_user u on u.id=m.user_id where m.family_id=$1 and m.user_id=$2 and m.ended_at is null for update of m', [req.params.familyId, req.params.userId]);
227
if (!target.rowCount) return { status: 204 };
228
if (target.rows[0].is_admin && !target.rows[0].disabled_at) {
@@ -205,8 +247,10 @@ app.get('/v1/families/:familyId/members', auth, async (req, res) => {
247
if (!allowed) return res.status(403).json({ error: 'forbidden' });
248
249
const r = await pool.query(
208
- `select m.user_id,m.role,m.is_admin,p.display_name,p.theme_preference
250
+ `select m.user_id,m.role,m.is_admin,m.version,m.updated_at,
251
+ (u.disabled_at is not null) as account_disabled,p.display_name,p.theme_preference
252
from family_membership m
253
+ join app_user u on u.id=m.user_id
254
join profile p on p.user_id=m.user_id
255
join family_workspace f on f.id=m.family_id
256
where m.family_id=$1 and m.ended_at is null and f.archived_at is null
@@ -240,7 +284,7 @@ app.post('/v1/families/:familyId/invitations', auth, async (req, res) => {
284
}
285
286
const token = randomToken();
243
- const result = await familyAdminTransaction(req.params.familyId, req.identity.sub, async (client) => {
287
+ const result = await familyAdminTransaction(req.params.familyId, req.identity, async (client) => {
288
const activeMember = await client.query(
289
`select 1
290
from family_membership m
@@ -302,7 +346,7 @@ app.post('/v1/invitations/accept', auth, async (req, res) => {
346
join app_user u on u.id=$2
347
where i.token_digest=$1
348
and i.status='pending'
305
- and i.expires_at>now()
349
+ and i.expires_at>statement_timestamp()
350
and u.disabled_at is null
351
for update of i`,
352
[digest, req.identity.sub],
@@ -321,6 +365,36 @@ app.post('/v1/invitations/accept', auth, async (req, res) => {
365
return res.status(403).json({ error: 'invitation_contact_mismatch' });
366
}
367
368
+ // Preserve the existing active-member conflict before validating any new
369
+ // role. All membership changes for this family share the family row lock;
370
+ // an older invitation cannot replace an already active membership.
371
+ const activeMembership = await client.query(`select 1 from family_membership
372
+ where family_id=$1 and user_id=$2 and ended_at is null`, [row.family_id, req.identity.sub]);
373
+ if (activeMembership.rowCount) {
374
+ await client.query('rollback');
375
+ return res.status(409).json({ error: 'member_already_active' });
376
+ }
377
+
378
+ // The family/invitation locks above serialize acceptance with transfer and
379
+ // revocation. The recipient account is already locked; lock the editable
380
+ // profile separately so a waiting statement cannot use an obsolete age.
381
+ // Profile category and theme never grant adult family permissions.
382
+ const profile = (await client.query(`select birth_date,
383
+ (birth_date is not null and birth_date>(current_date-interval '18 years')::date) known_minor
384
+ from profile where user_id=$1 for update`, [req.identity.sub])).rows[0];
385
+ if (row.intended_role !== 'teen_minor') {
386
+ if (profile?.known_minor) {
387
+ await client.query('rollback');
388
+ return res.status(403).json({ error: 'minor_role_upgrade_forbidden' });
389
+ }
390
+ if (!profile?.birth_date && (await client.query(`select 1 from family_membership m
391
+ join family_workspace f on f.id=m.family_id where m.user_id=$1 and m.ended_at is null
392
+ and m.role='teen_minor' and f.archived_at is null limit 1`, [req.identity.sub])).rowCount) {
393
+ await client.query('rollback');
394
+ return res.status(403).json({ error: 'age_confirmation_required' });
395
+ }
396
+ }
397
+
398
const membership = await client.query(
399
`insert into family_membership(family_id,user_id,role)
400
values($1,$2,$3)
@@ -347,6 +421,20 @@ app.post('/v1/invitations/accept', auth, async (req, res) => {
421
"insert into access_audit(actor_user_id,family_id,action,target_type,target_id) values($1,$2,'invitation.accept','membership',$3)",
422
[req.identity.sub, row.family_id, String(req.identity.sub)],
423
);
424
+ const session = await client.query(`select 1 from app_user u join auth_session s on s.user_id=u.id
425
+ where u.id=$1 and u.disabled_at is null and s.id=$2 and s.revoked_at is null
426
+ and s.expires_at>statement_timestamp() for share of s`, [req.identity.sub, req.identity.sid]);
427
+ const freshSession = session.rowCount ? await client.query(`select 1 from auth_session
428
+ where id=$1 and user_id=$2 and revoked_at is null and expires_at>statement_timestamp()`, [req.identity.sid,req.identity.sub]) : {rowCount:0};
429
+ if (!freshSession.rowCount || (req.identity.exp != null && req.identity.exp * 1000 <= Date.now())) {
430
+ await client.query('rollback');
431
+ return res.status(401).json({ error: 'session_invalid' });
432
+ }
433
+ const unexpired = await client.query('select 1 from family_invitation where id=$1 and expires_at>statement_timestamp()', [row.id]);
434
+ if (!unexpired.rowCount) {
435
+ await client.query('rollback');
436
+ return res.status(400).json({ error: 'invalid_or_expired_invitation' });
437
+ }
438
await client.query('commit');
439
res.status(204).end();
440
} catch (error) {
@@ -361,7 +449,7 @@ app.post('/v1/families/:familyId/guardians', auth, async (req, res) => {
449
const guardianUserId = String(req.body?.guardianUserId ?? '');
450
const minorUserId = String(req.body?.minorUserId ?? '');
451
if (!uuid(guardianUserId) || !uuid(minorUserId)) return res.status(400).json({ error: 'invalid_guardian_relationship' });
364
- const result = await familyAdminTransaction(req.params.familyId, req.identity.sub, async (client) => {
452
+ const result = await familyAdminTransaction(req.params.familyId, req.identity, async (client) => {
453
const roles = await client.query(`select m.user_id,m.role from family_membership m
454
join app_user u on u.id=m.user_id where m.family_id=$1 and m.user_id in ($2,$3)
455
and m.ended_at is null and u.disabled_at is null for update of m`, [req.params.familyId, guardianUserId, minorUserId]);
@@ -379,7 +467,7 @@ app.delete('/v1/families/:familyId/guardians', auth, async (req, res) => {
467
const guardianUserId = String(req.body?.guardianUserId ?? '');
468
const minorUserId = String(req.body?.minorUserId ?? '');
469
if (!uuid(guardianUserId) || !uuid(minorUserId)) return res.status(400).json({ error: 'invalid_guardian_relationship' });
382
- const result = await familyAdminTransaction(req.params.familyId, req.identity.sub, async (client) => {
470
+ const result = await familyAdminTransaction(req.params.familyId, req.identity, async (client) => {
471
await client.query('update guardian_relationship set active=false where family_id=$1 and guardian_user_id=$2 and minor_user_id=$3', [req.params.familyId, guardianUserId, minorUserId]);
472
await familyAudit(client, req.params.familyId, req.identity.sub, 'guardian.deactivate', 'guardian_relationship', guardianUserId);
473
return { status: 204 };
@@ -388,12 +476,15 @@ app.delete('/v1/families/:familyId/guardians', auth, async (req, res) => {
476
});
477
478
app.use('/v1', createSchoolCrudRouter({ pool, auth }));
479
+app.use('/v1', createSchoolLifecycleRouter({ pool, auth }));
480
app.use('/v1', createPhase3Router({ pool, auth }));
481
app.use('/v1', createPhase4Router({ pool, auth }));
482
app.use('/v1', createPhase6Router({ pool, auth }));
483
app.use('/v1', createLearningLibraryRouter({ pool, auth }));
484
app.use('/v1', createLearningFeedbackRouter({ pool, auth }));
485
app.use('/v1', createLearningAssessmentRouter({ pool, auth }));
486
+app.use('/v1', createContentReviewRouter({ pool, auth }));
487
+app.use('/v1', createFamilyLifecycleRouter({ pool, auth }));
488
app.use('/v1', createStudySessionsRouter({ pool, auth }));
489
490
app.use(operationalErrorHandler);
backend/src/study_sessions.js
+54
-20
@@ -106,6 +106,40 @@ async function readSnapshot(pool, read) {
106
} catch (error) { await client.query('rollback').catch(() => {}); throw error; }
107
finally { client.release(); }
108
}
109
+function taskMetrics(items, asOf) {
110
+ const completedTasks = items.filter((item) => item.status === 'completed').length;
111
+ return {
112
+ totalTasks: items.length, completedTasks,
113
+ completionPercent: items.length ? Math.round(completedTasks * 100 / items.length) : 0,
114
+ overdueTasks: items.filter((item) => item.status !== 'completed' && item.dueAt && new Date(item.dueAt) < asOf).length,
115
+ plannedDurationSeconds: items.reduce((sum, item) => sum + item.plannedDurationSeconds, 0),
116
+ };
117
+}
118
+function examMetrics(items) {
119
+ const exams = items.filter((item) => item.kind === 'exam');
120
+ const graded = exams.filter((item) => item.gradePoints !== null && item.gradeOutOf !== null && item.gradeOutOf > 0);
121
+ const denominator = graded.reduce((sum, item) => sum + Number(item.gradeOutOf), 0);
122
+ const numerator = graded.reduce((sum, item) => sum + Number(item.gradePoints), 0);
123
+ return { examCount: exams.length, gradedExamCount: graded.length,
124
+ gradePercent: denominator ? Math.round(numerator * 10000 / denominator) / 100 : null };
125
+}
126
+function subjectMetrics(items, periodOnly = false) {
127
+ const groups = new Map();
128
+ for (const item of items) {
129
+ // Names can repeat across terms. A task belongs to exactly one subject;
130
+ // neither labels nor sharing grants multiply its counts or recorded time.
131
+ const key = item.subjectId;
132
+ if (!groups.has(key)) groups.set(key, []);
133
+ groups.get(key).push(item);
134
+ }
135
+ return [...groups.entries()].map(([subjectId, subjectItems]) => {
136
+ const cohort = periodOnly ? subjectItems.filter((item) => item.taskInRange) : subjectItems;
137
+ return { subjectId, subjectName: subjectItems[0].subjectName ?? 'بدون درس',
138
+ totalTasks: cohort.length, completedTasks: cohort.filter((item) => item.status === 'completed').length,
139
+ recordedDurationSeconds: subjectItems.reduce((sum, item) => sum + item.recordedDurationSeconds, 0),
140
+ ...(periodOnly ? examMetrics(cohort) : {}) };
141
+ });
142
+}
143
async function mutation(pool, req, res, resource, execute, authorize = null) {
144
if (!uuid(req.body?.mutationId)) return res.status(400).json({ error: 'mutation_id_required' });
145
const hash = crypto.createHash('sha256').update(JSON.stringify(canonical({ resource, payload: req.body }))).digest('hex');
@@ -311,7 +345,7 @@ export function createStudySessionsRouter({ pool, auth }) {
345
const asOf = (await client.query('select clock_timestamp() as ts')).rows[0].ts;
346
const items = (await client.query(
347
`select p.id,p.title,p.kind,p.status,p.priority,p.starts_at,p.due_at,p.duration_minutes,p.planned_duration_seconds,p.completed_at,p.updated_at,p.version,
314
- p.activity_version,sub.name as subject_name,p.grade_points,p.grade_out_of,
348
+ p.activity_version,p.subject_id,sub.name as subject_name,p.grade_points,p.grade_out_of,
349
e.state as activity_state,e.source as activity_source,e.occurred_at as activity_at
350
from plan_item p left join subject sub on sub.id=p.subject_id
351
left join lateral(select state,source,occurred_at from activity_state_event where plan_item_id=p.id order by version desc limit 1) e on true
@@ -326,7 +360,8 @@ export function createStudySessionsRouter({ pool, auth }) {
360
least(coalesce(i.ends_at,$4::timestamptz),$3::timestamptz,$4::timestamptz) as ends_at
361
from study_session s join study_interval i on i.session_id=s.id
362
where s.plan_item_id=any($1::uuid[]) and s.archived_at is null and i.starts_at<$3
329
- and coalesce(i.ends_at,$4)>$2`, [ids, from, to, asOf],
363
+ and coalesce(i.ends_at,$4)>$2
364
+ order by s.id,i.starts_at,i.id`, [ids, from, to, asOf],
365
)).rows.filter((x) => x.ends_at > x.starts_at);
366
const timeByItem = new Map();
367
const daily = new Map();
@@ -349,32 +384,31 @@ export function createStudySessionsRouter({ pool, auth }) {
384
}
385
const projected = items.map((x) => ({ id: x.id, title: x.title, kind: x.kind, status: x.status, priority: x.priority, version: Number(x.version),
386
startsAt: x.starts_at, dueAt: x.due_at, plannedDurationSeconds: x.planned_duration_seconds ?? (x.duration_minutes ?? 0) * 60,
387
+ scheduledAt: x.due_at ?? x.starts_at,
388
+ taskInRange: Boolean((x.due_at ?? x.starts_at) && (x.due_at ?? x.starts_at) >= from && (x.due_at ?? x.starts_at) < to),
389
recordedDurationSeconds: Math.floor((timeByItem.get(x.id) ?? 0) / 1000), completedAt: x.completed_at,
390
activityState: x.activity_state ?? (x.status === 'completed' ? 'completed' : x.status === 'in_progress' ? 'started' : 'planned'),
391
activitySource: x.activity_source ?? 'self_reported', activityAt: x.activity_at ?? x.updated_at,
355
- subjectName: x.subject_name, gradePoints: x.grade_points, gradeOutOf: x.grade_out_of }));
356
- const planned = projected.filter((x) => { const at = x.startsAt ?? x.dueAt; return at && new Date(at) >= from && new Date(at) < to; });
357
- const complete = projected.filter((x) => x.status === 'completed').length;
392
+ subjectId: x.subject_id, subjectName: x.subject_name, gradePoints: x.grade_points, gradeOutOf: x.grade_out_of }));
393
+ const planned = projected.filter((item) => item.taskInRange);
394
+ const allTimeTaskMetrics = taskMetrics(projected, asOf);
395
+ const periodMetrics = { ...taskMetrics(planned, asOf), recordedDurationSeconds: Math.floor(totalMilliseconds / 1000), ...examMetrics(planned) };
396
const latest = [...items.map((x) => x.updated_at), ...intervals.map((x) => x.last_sync_at)].sort((a, b) => b - a)[0] ?? null;
359
- const subjects = new Map();
360
- for (const item of projected) {
361
- const key = item.subjectName ?? 'بدون درس';
362
- const existing = subjects.get(key) ?? { subjectName: key, totalTasks: 0, completedTasks: 0, recordedDurationSeconds: 0 };
363
- existing.totalTasks++;
364
- if (item.status === 'completed') existing.completedTasks++;
365
- existing.recordedDurationSeconds += item.recordedDurationSeconds;
366
- subjects.set(key, existing);
367
- }
397
const response = { childId: req.params.childId, familyId: req.params.familyId, from, to, asOf, lastSyncAt: latest,
369
- sourceVersion: crypto.createHash('sha256').update(JSON.stringify({ items: items.map((x) => [x.id, x.updated_at, x.activity_version]), intervals: intervals.map((x) => [x.id, x.version, x.last_sync_at]) })).digest('hex'),
398
+ sourceVersion: crypto.createHash('sha256').update(JSON.stringify({ from, to, items: projected,
399
+ intervals: intervals.map((x) => [x.id, x.version, x.last_sync_at, x.starts_at, x.ends_at]) })).digest('hex'),
400
timezone: 'Asia/Tehran', recordingDisclaimerKey: 'recorded_time_is_not_proof_of_study', items: projected,
371
- metrics: { totalTasks: projected.length, completedTasks: complete, completionPercent: projected.length ? Math.round(complete * 100 / projected.length) : 0,
372
- overdueTasks: projected.filter((x) => x.status !== 'completed' && x.dueAt && new Date(x.dueAt) < asOf).length,
373
- plannedDurationSeconds: projected.reduce((sum, x) => sum + x.plannedDurationSeconds, 0),
374
- plannedInRangeDurationSeconds: planned.reduce((sum, x) => sum + x.plannedDurationSeconds, 0),
401
+ taskDatePolicy: 'due_at_then_starts_at', rangeConvention: 'inclusive_from_exclusive_to', completionBasis: 'current_status_of_period_tasks',
402
+ periodMetrics, allTimeTaskMetrics,
403
+ // Legacy task counters stay historical for existing consumers. New
404
+ // clients use periodMetrics, so a range selector cannot relabel history.
405
+ metrics: { ...allTimeTaskMetrics, plannedInRangeDurationSeconds: periodMetrics.plannedDurationSeconds,
406
recordedDurationSeconds: Math.floor(totalMilliseconds / 1000) },
407
daily: [...daily.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([date, ms]) => ({ date, recordedDurationSeconds: Math.floor(ms / 1000) })),
377
- subjects: [...subjects.values()], sources: [...new Set(intervals.map((x) => x.source))], isEvidenceOfStudy: false };
408
+ subjects: subjectMetrics(projected),
409
+ periodSubjects: subjectMetrics(projected.filter((item) => item.taskInRange || item.recordedDurationSeconds > 0), true),
410
+ periodExams: planned.filter((item) => item.kind === 'exam'),
411
+ sources: [...new Set(intervals.map((x) => x.source))].sort(), isEvidenceOfStudy: false };
412
await client.query('commit');
413
res.json(response);
414
} catch (error) { await client.query('rollback').catch(() => {}); throw error; }
backend/tests/content_publication.test.js
new
+213
@@ -0,0 +1,213 @@
1
+// Only public synthetic teaching fixtures; no real video is fetched or approved.
2
+import test,{before,after} from 'node:test';
3
+import assert from 'node:assert/strict';
4
+import crypto from 'node:crypto';
5
+import fs from 'node:fs/promises';
6
+import os from 'node:os';
7
+import path from 'node:path';
8
+import pg from 'pg';
9
+import {spawnSync} from 'node:child_process';
10
+import {assessmentHash,assessmentContextHash} from '../src/learning_assessment.js';
11
+import {inspectLearningContent,reviewLearningContent,videoMaterialHash,videoContextHash} from '../src/content_publication.js';
12
+
13
+assert.ok(process.env.DATABASE_URL,'Use local synthetic PostgreSQL fixture credentials');
14
+const source=new URL(process.env.TEST_FIXTURE_DATABASE_URL??process.env.DATABASE_URL);
15
+assert.ok(['localhost','127.0.0.1','[::1]'].includes(source.hostname)&&(/test/.test(source.pathname)||source.pathname==='/lifemate_ci'),'Refuse nonlocal/nontest fixture');
16
+const database='lifeguide_publication_test_'+crypto.randomBytes(6).toString('hex');
17
+const admin=new pg.Client({connectionString:source.toString()});
18
+const target=new URL(source);target.pathname='/'+database;
19
+const env={CONTENT_REVIEW_DATABASE_URL:target.toString(),CONTENT_REVIEW_SYNTHETIC_ONLY:'true'};
20
+const client=new pg.Client({connectionString:target.toString()});
21
+const testRoles=['api','backup'].map(kind=>'lifeguide_publication_'+kind+'_test_'+crypto.randomBytes(6).toString('hex'));
22
+const createdRoles=[];let databaseCreated=false,clientConnected=false;
23
+before(async()=>{
24
+ await admin.connect();await admin.query(`create database "${database}"`);databaseCreated=true;
25
+ await client.connect();clientConnected=true;
26
+ // CI runs this before DB-role provisioning. Unique NOLOGIN fixture roles
27
+ // avoid any mutation of shared runtime/backup roles or their credentials.
28
+ for(const role of testRoles) {
29
+ await admin.query(`create role "${role}" nologin`);createdRoles.push(role);
30
+ }
31
+ // Stable foundation only. Do not migrate concurrently changing0016–0019 here.
32
+ const names=(await fs.readdir(new URL('../migrations/',import.meta.url))).filter(name=>/^00(?:0\d|1[0-5])_/.test(name)).sort();
33
+ for(const filename of [...names,'0020_content_publication_audit.sql']) {
34
+ const sql=await fs.readFile(new URL('../migrations/'+filename,import.meta.url),'utf8');await client.query(sql);
35
+ }
36
+});
37
+after(async()=>{
38
+ if(clientConnected) await client.end();
39
+ try {
40
+ if(databaseCreated) await admin.query(`drop database "${database}"`);
41
+ for(const role of createdRoles) await admin.query(`drop role "${role}"`);
42
+ } finally {await admin.end();}
43
+});
44
+const q=[{id:'q1',objectiveId:'counting',promptFa:'SYNTHETIC counting prompt',choices:[{id:'a',textFa:'۲'},{id:'b',textFa:'۳'}],correctChoiceId:'a',explanationFa:'SYNTHETIC explanation',remediationFa:'SYNTHETIC remediation'}];
45
+async function fixture() {
46
+ const subject=crypto.randomUUID(),book=crypto.randomUUID(),unit=crypto.randomUUID(),video=crypto.randomUUID();
47
+ await client.query("insert into curriculum_subject(id,school_year,national_grade,code,name_fa) values($1,'1405-1406',1,$2,'SYNTHETIC publication subject')",[subject,'synthetic-publication-'+subject]);
48
+ await client.query("insert into textbook_catalog(id,curriculum_subject_id,title_fa,source_url,book_code,stable_book_key,edition_verification,source_evidence_url) values($1,$2,'SYNTHETIC publication textbook','https://chap.sch.ir/','999999',$3,'verified','https://chap.sch.ir/synthetic')",[book,subject,'synthetic-publication:'+book]);
49
+ await client.query("insert into learning_unit(id,textbook_id,unit_key,title_fa,order_index,index_kind,source_evidence_url) values($1,$2,'synthetic-counting','SYNTHETIC counting unit',1,'lesson','https://chap.sch.ir/synthetic-unit')",[unit,book]);
50
+ await client.query("insert into learning_video_resource(id,unit_id,aparat_id,title_fa,creator_name,creator_url,source_evidence_url,verification_status,duration_seconds,free_access,checked_at,quality_notes_fa,material_hash) values($1,$2,'SyN12','SYNTHETIC unobserved video','SYNTHETIC teacher','https://www.aparat.com/synthetic_teacher','https://www.aparat.com/v/SyN12','metadata_verified',60,true,'2026-10-01T00:00:00Z','SYNTHETIC only',$3)",[video,unit,'0'.repeat(64)]);
51
+ const row=(await client.query(`select v.*,u.unit_key,u.title_fa unit_title_fa,u.order_index,u.index_kind,u.source_evidence_url unit_evidence_url,u.active,
52
+ t.stable_book_key,t.title_fa book_title_fa,t.book_code,t.track_codes,t.variant,t.edition_verification,t.source_evidence_url book_evidence_url,s.school_year,s.national_grade
53
+ from learning_video_resource v join learning_unit u on u.id=v.unit_id join textbook_catalog t on t.id=u.textbook_id join curriculum_subject s on s.id=t.curriculum_subject_id where v.id=$1`,[video])).rows[0];
54
+ row.material_hash=videoMaterialHash(row);await client.query('update learning_video_resource set material_hash=$2 where id=$1',[video,row.material_hash]);
55
+ return {subject,book,unit,video,row};
56
+}
57
+const videoReview=row=>({evidenceScope:'SYNTHETIC_TEST_ONLY',reviewerName:'SYNTHETIC TEST REVIEWER — not real approval',reviewedAt:'2026-10-01T00:00:00Z',
58
+ bookCode:row.book_code,schoolYear:row.school_year,unitKey:row.unit_key,bookEvidenceUrl:row.book_evidence_url,unitEvidenceUrl:row.unit_evidence_url,
59
+ materialHash:row.material_hash,watchedEntireVideo:true,editionAligned:true,accuracyApproved:true,suitabilityApproved:true,embedRightsApproved:true,
60
+ questionCoverageReviewed:true,alignmentNotes:'SYNTHETIC alignment',accuracyNotes:'SYNTHETIC accuracy',suitabilityNotes:'SYNTHETIC suitability',
61
+ embedRightsEvidence:'SYNTHETIC rights',questionCoverageNotes:'SYNTHETIC questions'});
62
+const publishVideo=f=>({schemaVersion:1,mutationId:crypto.randomUUID(),entityType:'video',entityId:f.video,operation:'publish',expectedStatus:'draft',
63
+ expectedContentHash:f.row.material_hash,expectedContextHash:videoContextHash(f.row),review:videoReview(f.row)});
64
+
65
+test('inspection and complete synthetic dry-run perform zero persistent mutations',async()=>{
66
+ const f=await fixture(),body=publishVideo(f);
67
+ const inspected=await inspectLearningContent(client,'video',f.video,{env});assert.equal(inspected.publicationStatus,'draft');
68
+ assert.equal(inspected.contentHash,f.row.material_hash);
69
+ const before=(await client.query('select publication_status,pedagogical_review,review_record from learning_video_resource where id=$1',[f.video])).rows[0];
70
+ const result=await reviewLearningContent(client,body,{env});assert.equal(result.mode,'dry-run');assert.equal(result.proposedStatus,'published');
71
+ assert.deepEqual((await client.query('select publication_status,pedagogical_review,review_record from learning_video_resource where id=$1',[f.video])).rows[0],before);
72
+ assert.equal((await client.query('select count(*)::int n from content_publication_audit')).rows[0].n,0);
73
+});
74
+
75
+test('full review, metadata, edition and current context gates reject missing or stale approval without writes',async()=>{
76
+ const f=await fixture(),body=publishVideo(f);
77
+ for(const field of ['watchedEntireVideo','editionAligned','accuracyApproved','suitabilityApproved','embedRightsApproved','questionCoverageReviewed']) {
78
+ await assert.rejects(reviewLearningContent(client,{...body,review:{...body.review,[field]:false}},{env,apply:true}),e=>e.code==='incomplete_video_review');
79
+ }
80
+ await assert.rejects(reviewLearningContent(client,{...body,review:{...body.review,reviewedAt:'2026-02-30T00:00:00Z'}},{env,apply:true}));
81
+ await assert.rejects(reviewLearningContent(client,{...body,expectedContentHash:'a'.repeat(64)},{env,apply:true}),e=>e.code==='content_conflict');
82
+ await client.query("update textbook_catalog set edition_verification='unverified' where id=$1",[f.book]);
83
+ await assert.rejects(reviewLearningContent(client,body,{env,apply:true}),e=>e.code==='context_conflict'||e.code==='verified_edition_required');
84
+ await client.query("update textbook_catalog set edition_verification='verified' where id=$1",[f.book]);
85
+ await client.query("update learning_video_resource set title_fa='SYNTHETIC changed without refreshed hash' where id=$1",[f.video]);
86
+ await assert.rejects(reviewLearningContent(client,body,{env,apply:true}),e=>e.code==='material_hash_mismatch');
87
+ assert.equal((await client.query('select count(*)::int n from content_publication_audit where entity_id=$1',[f.video])).rows[0].n,0);
88
+});
89
+
90
+test('stable publication receipt replays current withdrawn state, and changed UUID intent is rejected',async()=>{
91
+ const f=await fixture(),body=publishVideo(f);
92
+ const applied=await reviewLearningContent(client,body,{env,apply:true});assert.equal(applied.acknowledgement.status,'accepted');assert.equal(applied.current.publicationStatus,'published');
93
+ const retry=await reviewLearningContent(client,body,{env,apply:true});assert.equal(retry.acknowledgement.status,'already_applied');
94
+ await assert.rejects(reviewLearningContent(client,{...body,review:{...body.review,accuracyNotes:'Changed intent'}},{env,apply:true}),e=>e.code==='mutation_id_reused');
95
+ const withdrawal={...body,mutationId:crypto.randomUUID(),operation:'withdraw',expectedStatus:'published'};delete withdrawal.review;
96
+ assert.equal((await reviewLearningContent(client,withdrawal,{env,apply:true})).current.publicationStatus,'withdrawn');
97
+ assert.equal((await reviewLearningContent(client,body,{env,apply:true})).current.publicationStatus,'withdrawn');
98
+ assert.equal((await client.query('select count(*)::int n from content_publication_audit where entity_id=$1',[f.video])).rows[0].n,2);
99
+ const columns=(await client.query("select column_name from information_schema.columns where table_name='content_publication_audit'")).rows.map(row=>row.column_name);
100
+ for(const forbidden of ['summary','review_record','questions','note','feedback_id','owner_user_id','chat']) assert.ok(!columns.includes(forbidden));
101
+});
102
+
103
+test('synthetic apply cannot publish real catalogue records or pretend a human reviewed them',async()=>{
104
+ const f=await fixture(),body=publishVideo(f);
105
+ await assert.rejects(reviewLearningContent(client,{...body,review:{...body.review,evidenceScope:'HUMAN_REVIEW',reviewerName:'Real reviewer'}},{env,apply:true}),e=>e.code==='synthetic_receipt_required');
106
+ await client.query("update textbook_catalog set stable_book_key=$2 where id=$1",[f.book,'IR-1-105-1405-1406-standard']);
107
+ await assert.rejects(reviewLearningContent(client,body,{env,apply:true}),e=>e.code==='synthetic_material_required');
108
+ assert.equal((await client.query('select publication_status from learning_video_resource where id=$1',[f.video])).rows[0].publication_status,'draft');
109
+});
110
+
111
+test('original assessment drafts are versioned, published definitions immutable, and old learner snapshots retained on revision',async()=>{
112
+ const f=await fixture(),id=crypto.randomUUID();
113
+ const draft={schemaVersion:1,mutationId:crypto.randomUUID(),entityType:'assessment',entityId:id,unitId:f.unit,operation:'draft_assessment',
114
+ expectedStatus:'absent',expectedVersion:0,expectedContentHash:null,expectedContextHash:assessmentContextHash(f.row),questions:q};
115
+ assert.equal((await reviewLearningContent(client,draft,{env})).mode,'dry-run');
116
+ assert.equal((await client.query('select count(*)::int n from learning_assessment where id=$1',[id])).rows[0].n,0);
117
+ const created=await reviewLearningContent(client,draft,{env,apply:true});assert.equal(created.current.version,1);assert.equal(created.current.contentHash,assessmentHash(q));
118
+ assert.equal((await reviewLearningContent(client,draft,{env,apply:true})).acknowledgement.status,'already_applied');
119
+ const review={evidenceScope:'SYNTHETIC_TEST_ONLY',reviewerName:'SYNTHETIC TEST REVIEWER',reviewedAt:'2026-10-01T00:00:00Z',accuracyApproved:true,suitabilityApproved:true,
120
+ editionAligned:true,objectiveCoverageApproved:true,contentHash:assessmentHash(q),contextHash:assessmentContextHash(f.row),reviewNotes:'SYNTHETIC question approval',
121
+ bookCode:f.row.book_code,schoolYear:f.row.school_year,unitKey:f.row.unit_key};
122
+ const publish={schemaVersion:1,mutationId:crypto.randomUUID(),entityType:'assessment',entityId:id,operation:'publish',expectedStatus:'draft',expectedVersion:1,
123
+ expectedContentHash:assessmentHash(q),expectedContextHash:assessmentContextHash(f.row),review};
124
+ assert.equal((await reviewLearningContent(client,publish,{env,apply:true})).current.publicationStatus,'published');
125
+ const owner=crypto.randomUUID();await client.query('insert into app_user(id,identity_subject,email_normalized) values($1,$2,$3)',[owner,'synthetic-publication:'+owner,'publication-'+owner+'@example.test']);
126
+ await client.query("insert into learning_assessment_attempt(owner_user_id,mutation_id,assessment_id,unit_id,assessment_version,request_hash,answers,confidence,question_snapshot,acknowledgement) values($1,$2,$3,$4,1,$5,'[]','unsure',$6,'{}')",
127
+ [owner,crypto.randomUUID(),id,f.unit,'a'.repeat(64),JSON.stringify(q)]);
128
+ const revised=[{...q[0],promptFa:'SYNTHETIC revised original question'}];
129
+ const revision={...draft,mutationId:crypto.randomUUID(),expectedStatus:'published',expectedVersion:1,expectedContentHash:assessmentHash(q),questions:revised};
130
+ await assert.rejects(reviewLearningContent(client,revision,{env,apply:true}),e=>e.code==='published_definition_immutable');
131
+ const withdrawal={...publish,mutationId:crypto.randomUUID(),operation:'withdraw',expectedStatus:'published'};delete withdrawal.review;
132
+ await reviewLearningContent(client,withdrawal,{env,apply:true});
133
+ const next=await reviewLearningContent(client,{...revision,mutationId:crypto.randomUUID(),expectedStatus:'withdrawn'},{env,apply:true});
134
+ assert.equal(next.current.version,2);assert.equal(next.current.publicationStatus,'draft');assert.equal(next.current.contentHash,assessmentHash(revised));
135
+ const stored=(await client.query('select questions,review_record from learning_assessment where id=$1',[id])).rows[0];assert.deepEqual(stored.questions,revised);assert.equal(stored.review_record,null);
136
+ assert.deepEqual((await client.query('select question_snapshot from learning_assessment_attempt where assessment_id=$1',[id])).rows[0].question_snapshot,q);
137
+ assert.equal((await reviewLearningContent(client,publish,{env,apply:true})).current.publicationStatus,'draft');
138
+});
139
+
140
+test('isolated runtime/backup permission fixtures cannot write teaching definitions or publication audit with SELECT-only grants',async()=>{
141
+ const f=await fixture(),body=publishVideo(f);
142
+ for(const role of testRoles) {
143
+ await client.query(`grant connect on database "${database}" to "${role}"`);
144
+ await client.query(`grant usage on schema public to "${role}"`);
145
+ await client.query(`grant select on all tables in schema public to "${role}"`);
146
+ await client.query(`set role "${role}"`);
147
+ try {
148
+ await assert.rejects(reviewLearningContent(client,body,{env,apply:true}),e=>e.code==='separate_operator_required');
149
+ await assert.rejects(client.query('update learning_video_resource set publication_status=publication_status where id=$1',[f.video]),e=>e.code==='42501');
150
+ await assert.rejects(client.query('delete from content_publication_audit'),e=>e.code==='42501');
151
+ } finally {await client.query('reset role');}
152
+ }
153
+});
154
+
155
+test('actual CLI inspection prints structural synthetic output, refuses remote env and hides driver secrets',async()=>{
156
+ const f=await fixture();
157
+ const inspected=spawnSync(process.execPath,['scripts/review-learning-content.js','inspect','video',f.video],{env:{...process.env,...env},encoding:'utf8'});
158
+ assert.equal(inspected.status,0,inspected.stderr);assert.equal(JSON.parse(inspected.stdout).publicationStatus,'draft');
159
+ const rejected=spawnSync(process.execPath,['scripts/review-learning-content.js','inspect','video',f.video],{env:{...process.env,...env,CONTENT_REVIEW_DATABASE_URL:'postgres://SECRET_PASSWORD@remote.example/lifeguide_test'},encoding:'utf8'});
160
+ assert.equal(rejected.status,1);assert.ok(!rejected.stderr.includes('SECRET_PASSWORD'));assert.equal(rejected.stdout,'');
161
+});
162
+
163
+test('actual CLI dry-run, apply, replay and withdrawal retain exactly two receipts without printing reviewer text',async()=>{
164
+ const f=await fixture(),body=publishVideo(f),directory=await fs.mkdtemp(path.join(os.tmpdir(),'lifeguide-publication-'));
165
+ const filename=path.join(directory,'operation.json');
166
+ const run=action=>spawnSync(process.execPath,['scripts/review-learning-content.js',action,filename],{env:{...process.env,...env},encoding:'utf8'});
167
+ try {
168
+ await fs.writeFile(filename,JSON.stringify(body),{mode:0o600});
169
+ let result=run('dry-run');assert.equal(result.status,0,result.stderr);assert.equal(JSON.parse(result.stdout).mode,'dry-run');
170
+ assert.equal((await client.query('select count(*)::int n from content_publication_audit where entity_id=$1',[f.video])).rows[0].n,0);
171
+ result=run('apply');assert.equal(result.status,0,result.stderr);assert.equal(JSON.parse(result.stdout).current.eligibleForLearners,true);
172
+ assert.equal(JSON.parse(result.stdout).acknowledgement.status,'accepted');assert.ok(!result.stdout.includes(body.review.reviewerName));
173
+ result=run('apply');assert.equal(result.status,0,result.stderr);assert.equal(JSON.parse(result.stdout).acknowledgement.status,'already_applied');
174
+ const withdrawal={...body,mutationId:crypto.randomUUID(),operation:'withdraw',expectedStatus:'published'};delete withdrawal.review;
175
+ await fs.writeFile(filename,JSON.stringify(withdrawal));
176
+ result=run('apply');assert.equal(result.status,0,result.stderr);assert.equal(JSON.parse(result.stdout).current.eligibleForLearners,false);
177
+ assert.equal((await client.query('select count(*)::int n from content_publication_audit where entity_id=$1',[f.video])).rows[0].n,2);
178
+ await fs.writeFile(filename,' '.repeat(1024*1024+1));
179
+ result=run('apply');assert.equal(result.status,1);assert.equal(JSON.parse(result.stderr).code,'invalid_operation_file');
180
+ assert.equal(result.stdout,'');
181
+ } finally {await fs.rm(directory,{recursive:true});}
182
+});
183
+
184
+test('concurrent exact publication retries serialize and produce one journal receipt',async()=>{
185
+ const f=await fixture(),body=publishVideo(f),other=new pg.Client({connectionString:target.toString()});
186
+ await other.connect();
187
+ try {
188
+ const results=await Promise.all([reviewLearningContent(client,body,{env,apply:true}),reviewLearningContent(other,body,{env,apply:true})]);
189
+ assert.deepEqual(results.map(result=>result.acknowledgement.status).sort(),['accepted','already_applied']);
190
+ assert.equal((await client.query('select count(*)::int n from content_publication_audit where mutation_id=$1',[body.mutationId])).rows[0].n,1);
191
+ assert.equal((await client.query('select publication_status from learning_video_resource where id=$1',[f.video])).rows[0].publication_status,'published');
192
+ } finally {await other.end();}
193
+});
194
+
195
+test('a catalogue correction committed while review waits invalidates its original approval context',async()=>{
196
+ const f=await fixture(),body=publishVideo(f),blocker=new pg.Client({connectionString:target.toString()});
197
+ await blocker.connect();
198
+ try {
199
+ const pid=(await client.query('select pg_backend_pid() pid')).rows[0].pid;
200
+ await blocker.query('begin');
201
+ await blocker.query("update learning_unit set title_fa='SYNTHETIC corrected during review' where id=$1",[f.unit]);
202
+ const pending=reviewLearningContent(client,body,{env,apply:true});
203
+ const rejected=assert.rejects(pending,error=>error.code==='context_conflict');
204
+ const deadline=Date.now()+3000;let observed=false;
205
+ while(Date.now()<deadline) {
206
+ if((await blocker.query('select cardinality(pg_blocking_pids($1))>0 blocked',[pid])).rows[0].blocked) {observed=true;break;}
207
+ await new Promise(resolve=>setTimeout(resolve,10));
208
+ }
209
+ await blocker.query('commit');await rejected;assert.equal(observed,true,'Observe the actual row-lock wait');
210
+ assert.equal((await client.query('select count(*)::int n from content_publication_audit where mutation_id=$1',[body.mutationId])).rows[0].n,0);
211
+ assert.equal((await client.query('select publication_status from learning_video_resource where id=$1',[f.video])).rows[0].publication_status,'draft');
212
+ } finally {await blocker.query('rollback').catch(()=>{});await blocker.end();}
213
+});
backend/tests/content_publication_validation.test.js
new
+26
@@ -0,0 +1,26 @@
1
+import test from 'node:test';
2
+import assert from 'node:assert/strict';
3
+import crypto from 'node:crypto';
4
+import {localContentReviewConnection,normalizePublicationOperation} from '../src/content_publication.js';
5
+
6
+test('publication operator rejects remote/default/runtime configuration and accepts only explicit loopback test URL',()=>{
7
+ for(const env of [{},{DATABASE_URL:'postgres://local@127.0.0.1/lifeguide_test'},
8
+ {CONTENT_REVIEW_DATABASE_URL:'postgres://local@127.0.0.1/production',CONTENT_REVIEW_SYNTHETIC_ONLY:'true'},
9
+ {CONTENT_REVIEW_DATABASE_URL:'postgres://local@remote.example/lifeguide_test',CONTENT_REVIEW_SYNTHETIC_ONLY:'true'},
10
+ {CONTENT_REVIEW_DATABASE_URL:'postgres://local@127.0.0.1/lifeguide_test?host=remote.example',CONTENT_REVIEW_SYNTHETIC_ONLY:'true'},
11
+ {CONTENT_REVIEW_DATABASE_URL:'postgres://local@127.0.0.1/lifeguide_test?sslkey=/private/path',CONTENT_REVIEW_SYNTHETIC_ONLY:'true'},
12
+ {CONTENT_REVIEW_DATABASE_URL:'postgres://local@127.0.0.1/lifeguide_test'},
13
+ {CONTENT_REVIEW_DATABASE_URL:'postgres://local@127.0.0.1/contest',CONTENT_REVIEW_SYNTHETIC_ONLY:'true'}]) {
14
+ assert.throws(()=>localContentReviewConnection(env));
15
+ }
16
+ assert.equal(new URL(localContentReviewConnection({CONTENT_REVIEW_DATABASE_URL:'postgres://operator@127.0.0.1/lifeguide_publication_test',CONTENT_REVIEW_SYNTHETIC_ONLY:'true'})).hostname,'127.0.0.1');
17
+});
18
+
19
+test('publication manifest accepts exact typed operation fields and refuses private or unbounded content',()=>{
20
+ const base={schemaVersion:1,mutationId:crypto.randomUUID(),entityType:'video',entityId:crypto.randomUUID(),operation:'withdraw',
21
+ expectedStatus:'published',expectedContentHash:'a'.repeat(64),expectedContextHash:'b'.repeat(64)};
22
+ assert.equal(normalizePublicationOperation(base).operation,'withdraw');
23
+ for(const value of [null,[],{...base,ownerUserId:crypto.randomUUID()},{...base,privateChat:'PRIVATE'},
24
+ {...base,review:{watchedEntireVideo:'true'}},{...base,expectedContentHash:'wrong'},
25
+ {...base,expectedVersion:1},{...base,operation:'deploy'},{...base,entityId:'wrong'}]) assert.throws(()=>normalizePublicationOperation(value));
26
+});
backend/tests/content_review.test.js
new
+338
@@ -0,0 +1,338 @@
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
+});
backend/tests/content_review_validation.test.js
new
+21
@@ -0,0 +1,21 @@
1
+import test from 'node:test';
2
+import assert from 'node:assert/strict';
3
+import crypto from 'node:crypto';
4
+import { normalizeReviewMutation, normalizeBriefRequest } from '../src/content_review.js';
5
+
6
+test('review mutations allow only explicit statuses and reject inferred identities or text', () => {
7
+ const body={mutationId:crypto.randomUUID(),expectedVersion:1,status:'triaged'};
8
+ assert.deepEqual(normalizeReviewMutation(body),body);
9
+ for(const extra of [{status:'released'},{status:'received'},{expectedVersion:0},
10
+ {expectedVersion:'1'},{mutationId:'bad'},{ownerUserId:crypto.randomUUID()},
11
+ {summary:'copied text'},{role:'admin'}]) assert.equal(normalizeReviewMutation({...body,...extra}),null);
12
+});
13
+
14
+test('brief requests are bounded source/version references, never private text', () => {
15
+ const body={mutationId:crypto.randomUUID(),feedback:[{id:crypto.randomUUID(),expectedVersion:2}]};
16
+ assert.deepEqual(normalizeBriefRequest(body),body);
17
+ for(const extra of [{feedback:[]},{feedback:Array.from({length:21},()=>({id:crypto.randomUUID(),expectedVersion:1}))},
18
+ {feedback:[body.feedback[0],body.feedback[0]]},{summary:'private text'},
19
+ {feedback:[{...body.feedback[0],ownerUserId:crypto.randomUUID()}]},
20
+ {feedback:[{...body.feedback[0],expectedVersion:'2'}]}]) assert.equal(normalizeBriefRequest({...body,...extra}),null);
21
+});
backend/tests/family_lifecycle.test.js
new
+555
@@ -0,0 +1,555 @@
1
+import test, { after, before, describe } from 'node:test';
2
+import assert from 'node:assert/strict';
3
+import crypto from 'node:crypto';
4
+import { spawn } from 'node:child_process';
5
+import { once } from 'node:events';
6
+import net from 'node:net';
7
+import pg from 'pg';
8
+import jwt from 'jsonwebtoken';
9
+
10
+const uuid = () => crypto.randomUUID();
11
+
12
+describe('family lifecycle real entrypoint and synthetic PostgreSQL', { concurrency: false }, () => {
13
+ let pool, child, base;
14
+ const users = [], families = [];
15
+ const applicationName = `family-lifecycle-fixture-${uuid()}`;
16
+ const secret = 'synthetic-family-lifecycle-signing-secret-not-for-production';
17
+
18
+ async function start() {
19
+ const listener = net.createServer().listen(0, '127.0.0.1');
20
+ await once(listener, 'listening');
21
+ const port = listener.address().port;
22
+ await new Promise(resolve => listener.close(resolve));
23
+ base = `http://127.0.0.1:${port}`;
24
+ const env = { ...process.env, JWT_SECRET: secret, NODE_ENV: 'production', PORT: String(port), PGAPPNAME: applicationName,
25
+ SMS_PROVIDER: 'disabled', SMS_PROVIDER_URL: '', SMS_PROVIDER_TOKEN: '', EMAIL_FROM: '', RESEND_API_KEY: '',
26
+ SMTP_HOST: '', SMTP_USER: '', SMTP_PASSWORD: '', AI_API_KEY: '', AI_BASE_URL: '', AI_MODEL: '', OPENAI_API_KEY: '',
27
+ CORS_ORIGINS: '', TRUSTED_PROXY_CIDRS: '', ENABLE_SENSITIVE_FEATURES: 'false',
28
+ RATE_LIMIT_AUTH_MAX: '2000', RATE_LIMIT_GENERAL_MAX: '8000' };
29
+ delete env.TEST_FIXTURE_DATABASE_URL;
30
+ child = spawn(process.execPath, ['src/entrypoint.js'], { cwd: new URL('../', import.meta.url), env,
31
+ stdio: ['ignore', 'pipe', 'pipe'] });
32
+ let startup = '';
33
+ // Do not print fixture HTTP telemetry, JWTs or database connection strings.
34
+ child.stderr.on('data', () => {});
35
+ await new Promise((resolve, reject) => {
36
+ const timeout = setTimeout(() => reject(new Error('Family fixture startup timed out')), 10000);
37
+ const ready = chunk => {
38
+ startup += chunk;
39
+ if (startup.includes('"type":"startup"')) {
40
+ clearTimeout(timeout); child.stdout.off('data', ready); child.stdout.on('data', () => {}); resolve();
41
+ }
42
+ };
43
+ child.stdout.on('data', ready);
44
+ child.once('error', () => { clearTimeout(timeout); reject(new Error('Family fixture start failed')); });
45
+ child.once('exit', () => {
46
+ if (!startup.includes('"type":"startup"')) { clearTimeout(timeout); reject(new Error('Family fixture exited early')); }
47
+ });
48
+ });
49
+ }
50
+ async function stop() {
51
+ if (child && child.exitCode === null && child.signalCode === null) {
52
+ const ended = once(child, 'close'); child.kill('SIGTERM'); await ended;
53
+ }
54
+ }
55
+ before(async () => {
56
+ assert.ok(process.env.DATABASE_URL, 'Migrated synthetic PostgreSQL fixture required');
57
+ const location = new URL(process.env.TEST_FIXTURE_DATABASE_URL ?? process.env.DATABASE_URL);
58
+ assert.ok(['localhost', '127.0.0.1', '[::1]', '::1'].includes(location.hostname), 'Only loopback test PostgreSQL allowed');
59
+ assert.ok(location.pathname.includes('test') || location.pathname === '/lifemate_ci' ||
60
+ /^\/lifeguide_roles_source_[a-f0-9]{16}$/.test(location.pathname), 'Explicit synthetic database required');
61
+ pool = new pg.Pool({ connectionString: process.env.TEST_FIXTURE_DATABASE_URL ?? process.env.DATABASE_URL });
62
+ await start();
63
+ });
64
+ after(async () => {
65
+ await stop(); if (!pool) return;
66
+ try {
67
+ await pool.query('delete from access_audit where family_id=any($1::uuid[]) or actor_user_id=any($2::uuid[])', [families, users]);
68
+ await pool.query('delete from family_workspace where id=any($1::uuid[])', [families]);
69
+ await pool.query('delete from app_user where id=any($1::uuid[])', [users]);
70
+ } finally { await pool.end(); }
71
+ });
72
+ async function actor({ birthDate = null, category = 'adult', claims = {} } = {}) {
73
+ const id = uuid(), sid = uuid(), email = `family-${id}@example.test`; users.push(id);
74
+ await pool.query('insert into app_user(id,identity_subject,email_normalized,email_verified_at) values($1,$2,$3,now())',
75
+ [id, `family-lifecycle:${id}`, email]);
76
+ await pool.query("insert into profile(user_id,display_name,birth_date,profile_category,theme_preference) values($1,'Synthetic Family',$2,$3,'adult_blue')", [id, birthDate, category]);
77
+ await pool.query("insert into auth_session(id,user_id,refresh_digest,expires_at) values($1,$2,$3,now()+interval '1 day')", [sid, id, uuid()]);
78
+ return { id, sid, email, token: jwt.sign({ ...claims, sub: id, sid, aud: 'lifemate-api' }, secret,
79
+ { issuer: 'lifemate', expiresIn: '15m' }) };
80
+ }
81
+ async function family(admin, members = []) {
82
+ const id = uuid(); families.push(id);
83
+ await pool.query("insert into family_workspace(id,name,created_by) values($1,'Synthetic Lifecycle Family',$2)", [id, admin.id]);
84
+ await pool.query("insert into family_membership(family_id,user_id,role,is_admin) values($1,$2,'parent_guardian',true)", [id, admin.id]);
85
+ for (const member of members) await pool.query('insert into family_membership(family_id,user_id,role,is_admin) values($1,$2,$3,$4)',
86
+ [id, member.user.id, member.role ?? 'adult_member', member.admin ?? false]);
87
+ return id;
88
+ }
89
+ async function request(user, method, path, body) {
90
+ const response = await fetch(base + '/v1' + path, { method, headers: { 'content-type': 'application/json',
91
+ ...(user ? { authorization: `Bearer ${user.token}` } : {}) }, body: body === undefined ? undefined : JSON.stringify(body) });
92
+ const raw = await response.text();
93
+ return { status: response.status, body: raw && response.headers.get('content-type')?.includes('application/json') ? JSON.parse(raw) : raw || null };
94
+ }
95
+ const members = (user, id) => request(user, 'GET', `/families/${id}/members`);
96
+ const role = (user, id, target, body) => request(user, 'PATCH', `/families/${id}/members/${target.id}/role`, body);
97
+ const transfer = (user, id, body) => request(user, 'POST', `/families/${id}/admin-transfer`, body);
98
+ const invitations = (user, id, query = '') => request(user, 'GET', `/families/${id}/invitations${query}`);
99
+ const revoke = (user, id, invitationId, body) => request(user, 'PATCH', `/families/${id}/invitations/${invitationId}`, body);
100
+ const accept = (user, token) => request(user, 'POST', '/invitations/accept', { token });
101
+ async function member(id, user) {
102
+ return (await pool.query('select user_id,role,is_admin,version,ended_at from family_membership where family_id=$1 and user_id=$2', [id, user.id])).rows[0];
103
+ }
104
+ async function invite(admin, id, recipient, intendedRole = 'adult_member') {
105
+ const result = await request(admin, 'POST', `/families/${id}/invitations`, { email: recipient.email, role: intendedRole });
106
+ assert.equal(result.status, 201, JSON.stringify(result.body)); return result.body;
107
+ }
108
+ async function blockedOn(client, minimum = 1) {
109
+ const pid = (await client.query('select pg_backend_pid() pid')).rows[0].pid, deadline = Date.now() + 5000;
110
+ while (Date.now() < deadline) {
111
+ const result = await pool.query(`with recursive waits as (
112
+ select pid from pg_stat_activity where $2=any(pg_blocking_pids(pid))
113
+ union select a.pid from pg_stat_activity a join waits w on w.pid=any(pg_blocking_pids(a.pid))
114
+ ) select count(*)::int n from pg_stat_activity a join waits w on w.pid=a.pid
115
+ where a.application_name=$1`, [applicationName, pid]);
116
+ if (result.rows[0].n >= minimum) return;
117
+ await new Promise(resolve => setTimeout(resolve, 15));
118
+ }
119
+ assert.fail('API did not reach the observed PostgreSQL lock wait');
120
+ }
121
+ async function withFamilyBlocked(id, action) {
122
+ const blocker = await pool.connect();
123
+ try {
124
+ await blocker.query('begin'); await blocker.query('select id from family_workspace where id=$1 for update', [id]);
125
+ await action(blocker);
126
+ } finally { await blocker.query('rollback').catch(() => {}); blocker.release(); }
127
+ }
128
+
129
+ test('current explicit administrator, not family role, profile type or JWT claims, controls every lifecycle route', async () => {
130
+ const owner = await actor(), parent = await actor({ claims: { is_admin: true, role: 'admin' } }),
131
+ child = await actor({ category: 'adult' }), outsider = await actor();
132
+ const id = await family(owner, [{ user: parent, role: 'parent_guardian' }, { user: child, role: 'teen_minor' }]);
133
+ const foreign = await family(outsider), recipient = await actor(), invitation = await invite(owner, id, recipient);
134
+ for (const unauthorized of [parent, child, outsider, null]) {
135
+ const expected = unauthorized ? 403 : 401;
136
+ assert.equal((await invitations(unauthorized, id)).status, expected);
137
+ assert.equal((await role(unauthorized, id, parent, { mutationId: uuid(), expectedVersion: 1, role: 'adult_member' })).status, expected);
138
+ assert.equal((await transfer(unauthorized, id, { mutationId: uuid(), targetUserId: parent.id, expectedVersion: 1, expectedActorVersion: 1 })).status, expected);
139
+ assert.equal((await revoke(unauthorized, id, invitation.id, { mutationId: uuid(), expectedVersion: 1, action: 'revoke' })).status, expected);
140
+ }
141
+ assert.equal((await invitations(owner, foreign)).status, 403);
142
+ for (const path of [`/families/${id}/invitations?limit=0`, `/families/${id}/invitations?limit=1.5`,
143
+ `/families/${id}/invitations?limit=1&limit=2`, `/families/${id}/invitations?cursor=bad`, `/families/${id}/invitations?email=x`])
144
+ assert.equal((await request(owner, 'GET', path)).status, 400);
145
+ assert.equal((await role(owner, id, parent, { mutationId: uuid(), expectedVersion: 1, role: 'adult_member', isAdmin: true })).status, 400);
146
+ assert.equal((await transfer(owner, id, { mutationId: uuid(), targetUserId: parent.id, expectedVersion: 1, expectedActorVersion: 1, ownerUserId: outsider.id })).status, 400);
147
+ assert.equal((await revoke(owner, id, invitation.id, { mutationId: uuid(), expectedVersion: 1, action: 'accept' })).status, 400);
148
+ });
149
+
150
+ test('administrator invitation pagination masks contact and never leaks bearer token or digest', async () => {
151
+ const owner = await actor(), id = await family(owner), recipients = await Promise.all([actor(), actor(), actor()]);
152
+ const rows = [];
153
+ for (const recipient of recipients) rows.push(await invite(owner, id, recipient));
154
+ const listed = await invitations(owner, id, '?limit=2'); assert.equal(listed.status, 200);
155
+ assert.equal(listed.body.total, 3); assert.equal(listed.body.invitations.length, 2); assert.ok(listed.body.nextCursor);
156
+ const serialized = JSON.stringify(listed.body);
157
+ for (const recipient of recipients) assert.ok(!serialized.includes(recipient.email));
158
+ for (const row of rows) {
159
+ assert.ok(!serialized.includes(row.invitationToken));
160
+ assert.ok(!serialized.includes(crypto.createHash('sha256').update(row.invitationToken).digest('hex')));
161
+ }
162
+ const next = await invitations(owner, id, `?limit=2&cursor=${listed.body.nextCursor}`);
163
+ assert.equal(next.body.invitations.length, 1); assert.equal(next.body.nextCursor, null);
164
+ assert.equal(new Set([...listed.body.invitations, ...next.body.invitations].map(row => row.id)).size, 3);
165
+ assert.ok(listed.body.invitations.every(row => row.version === 1 && row.recipientHint === '***@example.test'));
166
+ assert.equal((await invitations(owner, id, `?cursor=${uuid()}`)).status, 404);
167
+ });
168
+
169
+ test('role CAS increments one version, stable receipt survives API restart and rejects changed intent', async () => {
170
+ const owner = await actor(), target = await actor(), id = await family(owner, [{ user: target, role: 'parent_guardian' }]);
171
+ assert.equal((await members(owner, id)).body.members.find(row => row.user_id === target.id).version, 1);
172
+ const mutation = { mutationId: uuid(), expectedVersion: 1, role: 'adult_member' };
173
+ const first = await role(owner, id, target, mutation);
174
+ assert.equal(first.status, 200); assert.equal(first.body.members[0].version, 2); assert.equal(first.body.members[0].role, 'adult_member');
175
+ assert.equal(first.body.acknowledgement.status, 'accepted');
176
+ await stop(); await start();
177
+ const replay = await role(owner, id, target, mutation); assert.equal(replay.status, 200);
178
+ assert.equal(replay.body.acknowledgement.status, 'already_applied'); assert.equal(replay.body.members[0].version, 2);
179
+ assert.equal((await role(owner, id, target, { ...mutation, role: 'teen_minor' })).status, 409);
180
+ assert.equal((await role(owner, id, target, { mutationId: uuid(), expectedVersion: 1, role: 'parent_guardian' })).body.error, 'membership_version_conflict');
181
+ const second = { mutationId: uuid(), expectedVersion: 2, role: 'parent_guardian' };
182
+ assert.equal((await role(owner, id, target, second)).body.members[0].version, 3);
183
+ assert.equal((await role(owner, id, target, mutation)).body.members[0].version, 3, 'Retry returns current state, not obsolete role');
184
+ assert.equal((await member(id, target)).role, 'parent_guardian');
185
+ assert.equal((await pool.query('select count(*)::int n from family_lifecycle_mutation where actor_user_id=$1 and family_id=$2', [owner.id, id])).rows[0].n, 2);
186
+ assert.equal((await pool.query("select count(*)::int n from access_audit where actor_user_id=$1 and action='family.lifecycle.role'", [owner.id])).rows[0].n, 2);
187
+ });
188
+
189
+ test('known minors cannot take adult roles or administration; unknown legacy adult can receive explicit transfer', async () => {
190
+ const owner = await actor(), teen = await actor({ category: 'adult' }),
191
+ minorAdult = await actor({ birthDate: '2020-01-01', category: 'adult' }), adultTeen = await actor({ birthDate: '1990-01-01', category: 'girl_minor' }),
192
+ legacyAdult = await actor({ category: 'boy_minor' });
193
+ const id = await family(owner, [{ user: teen, role: 'teen_minor' }, { user: minorAdult },
194
+ { user: adultTeen, role: 'teen_minor' }, { user: legacyAdult }]);
195
+ assert.equal((await role(owner, id, teen, { mutationId: uuid(), expectedVersion: 1, role: 'adult_member' })).body.error, 'age_confirmation_required');
196
+ assert.equal((await role(owner, id, minorAdult, { mutationId: uuid(), expectedVersion: 1, role: 'parent_guardian' })).body.error, 'minor_role_upgrade_forbidden');
197
+ for (const target of [teen, minorAdult]) assert.equal((await transfer(owner, id, {
198
+ mutationId: uuid(), targetUserId: target.id, expectedVersion: 1, expectedActorVersion: 1 })).body.error, 'minor_cannot_admin');
199
+ assert.equal((await role(owner, id, adultTeen, { mutationId: uuid(), expectedVersion: 1, role: 'adult_member' })).status, 200);
200
+ assert.equal((await role(owner, id, owner, { mutationId: uuid(), expectedVersion: 1, role: 'teen_minor' })).body.error, 'minor_cannot_admin');
201
+ assert.equal((await transfer(owner, id, { mutationId: uuid(), targetUserId: legacyAdult.id, expectedVersion: 1, expectedActorVersion: 1 })).status, 200);
202
+ assert.equal((await member(id, legacyAdult)).is_admin, true);
203
+ assert.equal((await pool.query('select profile_category from profile where user_id=$1', [legacyAdult.id])).rows[0].profile_category, 'boy_minor', 'Profile category is not silently rewritten by family authority');
204
+ });
205
+
206
+ test('family creation denies known minors while profile category itself does not infer administrative age', async () => {
207
+ const knownMinor = await actor({ birthDate: '2020-01-01', category: 'adult' });
208
+ const rejected = await request(knownMinor, 'POST', '/families', { name: 'Synthetic denied family', role: 'parent_guardian' });
209
+ assert.equal(rejected.status, 403); assert.equal(rejected.body.error, 'minor_cannot_admin');
210
+ assert.equal((await pool.query('select count(*)::int n from family_workspace where created_by=$1', [knownMinor.id])).rows[0].n, 0);
211
+ for (const options of [{ birthDate: '1990-01-01', category: 'girl_minor' }, { category: 'boy_minor' }]) {
212
+ const creator = await actor(options), created = await request(creator, 'POST', '/families', { name: 'Synthetic allowed family', role: 'adult_member' });
213
+ if (created.status === 201) families.push(created.body.id);
214
+ assert.equal(created.status, 201, 'Explicit adult date or legacy unknown adult is not rejected by a UI profile category');
215
+ assert.equal((await member(created.body.id, creator)).is_admin, true);
216
+ }
217
+ });
218
+
219
+ test('new family creation cannot bypass unknown-age teen membership through an adult-looking profile', async () => {
220
+ const owner = await actor(), teen = await actor({ category: 'adult' });
221
+ await family(owner, [{ user: teen, role: 'teen_minor' }]);
222
+ const rejected = await request(teen, 'POST', '/families', { name: 'Synthetic age bypass attempt', role: 'adult_member' });
223
+ if (rejected.status === 201) families.push(rejected.body.id);
224
+ assert.equal(rejected.status, 403); assert.equal(rejected.body.error, 'age_confirmation_required');
225
+ assert.equal((await pool.query('select count(*)::int n from family_workspace where created_by=$1', [teen.id])).rows[0].n, 0);
226
+ });
227
+
228
+ test('new family admin age derives from locked fresh profile after account-row wait', async () => {
229
+ const creator = await actor({ birthDate: '1990-01-01' }), blocker = await pool.connect(); let pending;
230
+ try {
231
+ await blocker.query('begin'); await blocker.query('select id from app_user where id=$1 for update', [creator.id]);
232
+ await blocker.query('select user_id from profile where user_id=$1 for update', [creator.id]);
233
+ pending = request(creator, 'POST', '/families', { name: 'Synthetic age correction race' });
234
+ await blockedOn(blocker);
235
+ await blocker.query("update profile set birth_date='2020-01-01' where user_id=$1", [creator.id]);
236
+ await blocker.query('commit'); const response = await pending;
237
+ if (response.status === 201) families.push(response.body.id);
238
+ assert.equal(response.status, 403); assert.equal(response.body.error, 'minor_cannot_admin');
239
+ } finally { await blocker.query('rollback').catch(() => {}); blocker.release(); if (pending) await pending.catch(() => {}); }
240
+ assert.equal((await pool.query('select count(*)::int n from family_workspace where created_by=$1', [creator.id])).rows[0].n, 0);
241
+ });
242
+
243
+ test('invitation acceptance cannot assign known minors adult or guardian roles and leaves the invitation recoverable', async () => {
244
+ const owner = await actor(), id = await family(owner);
245
+ for (const intendedRole of ['adult_member', 'parent_guardian']) {
246
+ const recipient = await actor({ birthDate: '2020-01-01', category: 'adult' }), invitation = await invite(owner, id, recipient, intendedRole);
247
+ const rejected = await accept(recipient, invitation.invitationToken);
248
+ assert.equal(rejected.status, 403); assert.equal(rejected.body.error, 'minor_role_upgrade_forbidden');
249
+ assert.equal(await member(id, recipient), undefined);
250
+ assert.equal((await pool.query('select status,accepted_by,version from family_invitation where id=$1', [invitation.id])).rows[0].status, 'pending');
251
+ assert.equal((await pool.query("select count(*)::int n from access_audit where actor_user_id=$1 and action='invitation.accept'", [recipient.id])).rows[0].n, 0);
252
+ assert.equal((await pool.query('select profile_category,theme_preference from profile where user_id=$1', [recipient.id])).rows[0].profile_category, 'adult');
253
+ const correction = await invite(owner, id, recipient, 'teen_minor');
254
+ assert.equal((await accept(recipient, correction.invitationToken)).status, 204);
255
+ assert.equal((await member(id, recipient)).role, 'teen_minor');
256
+ const activeConflict = await accept(recipient, invitation.invitationToken);
257
+ assert.equal(activeConflict.status, 409); assert.equal(activeConflict.body.error, 'member_already_active');
258
+ assert.equal((await member(id, recipient)).role, 'teen_minor');
259
+ assert.equal((await pool.query('select status from family_invitation where id=$1', [invitation.id])).rows[0].status, 'pending');
260
+ }
261
+ });
262
+
263
+ test('invitation adult role requires age confirmation for an active unknown-age teen in another family', async () => {
264
+ const owner = await actor(), teen = await actor({ category: 'adult' }), existing = await family(owner, [{ user: teen, role: 'teen_minor' }]);
265
+ const newOwner = await actor(), target = await family(newOwner);
266
+ for (const intendedRole of ['adult_member', 'parent_guardian']) {
267
+ const invitation = await invite(newOwner, target, teen, intendedRole), rejected = await accept(teen, invitation.invitationToken);
268
+ assert.equal(rejected.status, 403); assert.equal(rejected.body.error, 'age_confirmation_required');
269
+ assert.equal(await member(target, teen), undefined); assert.equal((await member(existing, teen)).role, 'teen_minor');
270
+ assert.equal((await pool.query('select status from family_invitation where id=$1', [invitation.id])).rows[0].status, 'pending');
271
+ }
272
+ const correction = await invite(newOwner, target, teen, 'teen_minor');
273
+ assert.equal((await accept(teen, correction.invitationToken)).status, 204);
274
+ assert.equal((await member(target, teen)).role, 'teen_minor');
275
+ });
276
+
277
+ test('invitation age checks use birth date and current teen membership rather than profile category', async () => {
278
+ const owner = await actor(), id = await family(owner);
279
+ for (const options of [{ birthDate: '1990-01-01', category: 'girl_minor' }, { category: 'boy_minor' }]) {
280
+ const recipient = await actor(options), invitation = await invite(owner, id, recipient, 'parent_guardian');
281
+ assert.equal((await accept(recipient, invitation.invitationToken)).status, 204);
282
+ assert.equal((await member(id, recipient)).role, 'parent_guardian');
283
+ assert.equal((await pool.query('select profile_category from profile where user_id=$1', [recipient.id])).rows[0].profile_category, options.category);
284
+ }
285
+ const adultFormerTeen = await actor({ birthDate: '1990-01-01', category: 'girl_minor' });
286
+ await family(owner, [{ user: adultFormerTeen, role: 'teen_minor' }]);
287
+ const invitation = await invite(owner, id, adultFormerTeen, 'adult_member');
288
+ assert.equal((await accept(adultFormerTeen, invitation.invitationToken)).status, 204);
289
+ assert.equal((await member(id, adultFormerTeen)).role, 'adult_member');
290
+ });
291
+
292
+ test('invitation acceptance waits for editable birth date and rejects a newly known minor before membership', async () => {
293
+ const owner = await actor(), recipient = await actor({ birthDate: '1990-01-01' }), id = await family(owner),
294
+ invitation = await invite(owner, id, recipient, 'parent_guardian'), blocker = await pool.connect(); let pending;
295
+ try {
296
+ await blocker.query('begin'); await blocker.query('select user_id from profile where user_id=$1 for update', [recipient.id]);
297
+ pending = accept(recipient, invitation.invitationToken); await blockedOn(blocker);
298
+ await blocker.query("update profile set birth_date='2020-01-01' where user_id=$1", [recipient.id]);
299
+ await blocker.query('commit'); const rejected = await pending;
300
+ assert.equal(rejected.status, 403); assert.equal(rejected.body.error, 'minor_role_upgrade_forbidden');
301
+ } finally { await blocker.query('rollback').catch(() => {}); blocker.release(); if (pending) await pending.catch(() => {}); }
302
+ assert.equal(await member(id, recipient), undefined);
303
+ assert.equal((await pool.query('select status from family_invitation where id=$1', [invitation.id])).rows[0].status, 'pending');
304
+ });
305
+
306
+ test('atomic transfer preserves administrator, revokes old pending invitations and only exact old retry bypasses new-admin check', async () => {
307
+ const owner = await actor(), target = await actor(), recipient = await actor(), id = await family(owner, [{ user: target }]);
308
+ const invitation = await invite(owner, id, recipient), mutation = { mutationId: uuid(), targetUserId: target.id, expectedVersion: 1, expectedActorVersion: 1 };
309
+ const first = await transfer(owner, id, mutation); assert.equal(first.status, 200);
310
+ assert.deepEqual(first.body.members.map(row => [row.userId, row.isAdmin, row.version]), [[owner.id, false, 2], [target.id, true, 2]]);
311
+ assert.equal((await pool.query('select status,version from family_invitation where id=$1', [invitation.id])).rows[0].status, 'revoked');
312
+ assert.equal((await accept(recipient, invitation.invitationToken)).status, 400);
313
+ assert.equal((await invitations(owner, id)).status, 403);
314
+ assert.equal((await role(owner, id, target, { mutationId: uuid(), expectedVersion: 2, role: 'parent_guardian' })).status, 403);
315
+ const replay = await transfer(owner, id, mutation); assert.equal(replay.status, 200); assert.equal(replay.body.acknowledgement.status, 'already_applied');
316
+ assert.equal((await transfer(owner, id, { ...mutation, expectedVersion: 2 })).body.error, 'mutation_id_reused');
317
+ assert.equal((await transfer(target, id, { mutationId: uuid(), targetUserId: owner.id, expectedVersion: 2, expectedActorVersion: 2 })).status, 200);
318
+ assert.equal((await accept(recipient, invitation.invitationToken)).status, 400, 'Transfer back must not revive old invitation');
319
+ assert.equal((await transfer(owner, id, mutation)).body.members.find(row => row.userId === target.id).isAdmin, false, 'Exact old retry reports current authority');
320
+ assert.equal((await request(owner, 'DELETE', `/families/${id}/members/${owner.id}`)).body.error, 'last_admin_required');
321
+ });
322
+
323
+ test('concurrent transfer/role CAS keeps one administrator and one accepted version', async () => {
324
+ const owner = await actor(), first = await actor(), second = await actor(), id = await family(owner, [{ user: first }, { user: second }]);
325
+ const results = await Promise.all([first, second].map(target => transfer(owner, id, {
326
+ mutationId: uuid(), targetUserId: target.id, expectedVersion: 1, expectedActorVersion: 1 })));
327
+ assert.deepEqual(results.map(result => result.status).sort(), [200, 403]);
328
+ const active = (await pool.query('select user_id from family_membership where family_id=$1 and ended_at is null and is_admin', [id])).rows;
329
+ assert.equal(active.length, 1); assert.notEqual(active[0].user_id, owner.id);
330
+ const newAdmin = active[0].user_id === first.id ? first : second, target = newAdmin === first ? second : first;
331
+ const writes = await Promise.all(['parent_guardian', 'teen_minor'].map(newRole => role(newAdmin, id, target, {
332
+ mutationId: uuid(), expectedVersion: 1, role: newRole })));
333
+ assert.deepEqual(writes.map(result => result.status).sort(), [200, 409]);
334
+ assert.equal((await member(id, target)).version, 2);
335
+ });
336
+
337
+ test('role changes revoke affected guardian/selected sharing; reversal or removal/rejoin never resurrects access', async () => {
338
+ const owner = await actor(), parent = await actor(), child = await actor({ birthDate: '1990-01-01', category: 'girl_minor' });
339
+ const id = await family(owner, [{ user: parent, role: 'parent_guardian' }, { user: child, role: 'teen_minor' }]);
340
+ await pool.query('insert into guardian_relationship(family_id,guardian_user_id,minor_user_id) values($1,$2,$3)', [id, parent.id, child.id]);
341
+ const task = await request(child, 'POST', '/plan-items', { title: 'Synthetic selected task', kind: 'assignment', familyId: id,
342
+ visibility: 'selected_members', selectedMemberIds: [parent.id], notes: 'SYNTHETIC-PRIVATE-NOTE' });
343
+ assert.equal(task.status, 201, JSON.stringify(task.body));
344
+ // Verify a real grant independently; some legacy clients omit the grant list.
345
+ await pool.query("insert into sharing_grant(resource_type,resource_id,grantee_user_id,granted_by) values('plan_item',$1,$2,$3) on conflict do nothing", [task.body.id, parent.id, child.id]);
346
+ assert.equal((await request(parent, 'GET', `/plan-items/${task.body.id}`)).status, 200);
347
+ assert.equal((await role(owner, id, parent, { mutationId: uuid(), expectedVersion: 1, role: 'adult_member' })).status, 200);
348
+ assert.equal((await pool.query('select active from guardian_relationship where family_id=$1 and guardian_user_id=$2', [id, parent.id])).rows[0].active, false);
349
+ assert.equal((await pool.query('select count(*)::int n from sharing_grant where resource_id=$1', [task.body.id])).rows[0].n, 0);
350
+ assert.equal((await role(owner, id, parent, { mutationId: uuid(), expectedVersion: 2, role: 'parent_guardian' })).status, 200);
351
+ assert.equal((await request(parent, 'GET', `/plan-items/${task.body.id}`)).status, 404);
352
+ await pool.query("insert into sharing_grant(resource_type,resource_id,grantee_user_id,granted_by) values('plan_item',$1,$2,$3)", [task.body.id, parent.id, child.id]);
353
+ assert.equal((await request(owner, 'DELETE', `/families/${id}/members/${parent.id}`)).status, 204);
354
+ const invitation = await invite(owner, id, parent, 'parent_guardian'); assert.equal((await accept(parent, invitation.invitationToken)).status, 204);
355
+ assert.equal((await member(id, parent)).version, 5, 'Legacy end and rejoin revisions are tracked');
356
+ assert.equal((await request(parent, 'GET', `/plan-items/${task.body.id}`)).status, 404);
357
+ assert.equal((await pool.query('select active from guardian_relationship where family_id=$1 and guardian_user_id=$2', [id, parent.id])).rows[0].active, false);
358
+ const progress = (await pool.query('select profile_category from profile where user_id=$1', [child.id])).rows[0];
359
+ assert.equal(progress.profile_category, 'girl_minor');
360
+ });
361
+
362
+ test('inactive target, disabled target and archived family reject new mutations; removal prevents historical retry', async () => {
363
+ const owner = await actor(), target = await actor(), id = await family(owner, [{ user: target }]);
364
+ const mutation = { mutationId: uuid(), expectedVersion: 1, role: 'parent_guardian' };
365
+ await pool.query('update app_user set disabled_at=now() where id=$1', [target.id]);
366
+ assert.equal((await role(owner, id, target, mutation)).body.error, 'member_not_active');
367
+ assert.equal((await transfer(owner, id, { mutationId: uuid(), targetUserId: target.id, expectedVersion: 1, expectedActorVersion: 1 })).body.error, 'member_not_active');
368
+ await pool.query('update app_user set disabled_at=null where id=$1', [target.id]);
369
+ assert.equal((await role(owner, id, target, mutation)).status, 200);
370
+ assert.equal((await request(owner, 'DELETE', `/families/${id}/members/${target.id}`)).status, 204);
371
+ assert.equal((await role(owner, id, target, { mutationId: uuid(), expectedVersion: 3, role: 'adult_member' })).body.error, 'member_not_active');
372
+ assert.equal((await request(owner, 'DELETE', `/families/${id}`)).status, 204);
373
+ assert.equal((await role(owner, id, target, mutation)).status, 403);
374
+ assert.equal((await invitations(owner, id)).status, 403);
375
+ });
376
+
377
+ test('invitation revoke receipt persists, returns current state and rejects concurrent accept without contact/token disclosure', async () => {
378
+ const owner = await actor(), recipient = await actor(), id = await family(owner), invitation = await invite(owner, id, recipient);
379
+ const mutation = { mutationId: uuid(), expectedVersion: 1, action: 'revoke' };
380
+ const result = await revoke(owner, id, invitation.id, mutation); assert.equal(result.status, 200);
381
+ assert.equal(result.body.invitation.status, 'revoked'); assert.equal(result.body.invitation.version, 2);
382
+ assert.ok(!JSON.stringify(result.body).includes(recipient.email)); assert.ok(!JSON.stringify(result.body).includes(invitation.invitationToken));
383
+ assert.equal((await accept(recipient, invitation.invitationToken)).status, 400);
384
+ await stop(); await start();
385
+ const replay = await revoke(owner, id, invitation.id, mutation); assert.equal(replay.status, 200);
386
+ assert.equal(replay.body.acknowledgement.status, 'already_applied'); assert.equal(replay.body.invitation.version, 2);
387
+ assert.equal((await revoke(owner, id, invitation.id, { ...mutation, expectedVersion: 2 })).body.error, 'mutation_id_reused');
388
+ assert.equal((await revoke(owner, id, invitation.id, { mutationId: uuid(), expectedVersion: 2, action: 'revoke' })).body.error, 'invitation_not_pending');
389
+ assert.equal((await invitations(owner, id)).body.total, 0);
390
+ });
391
+
392
+ test('invitation expiry is rechecked after an observed family-row wait, not frozen transaction time', async () => {
393
+ const owner = await actor(), recipient = await actor(), id = await family(owner), invitation = await invite(owner, id, recipient);
394
+ await pool.query("update family_invitation set created_at=now()-interval '1 minute' where id=$1", [invitation.id]);
395
+ await withFamilyBlocked(id, async blocker => {
396
+ const pending = accept(recipient, invitation.invitationToken); await blockedOn(blocker);
397
+ await blocker.query("update family_invitation set expires_at=statement_timestamp()-interval '1 millisecond' where id=$1", [invitation.id]);
398
+ await blocker.query('commit');
399
+ assert.equal((await pending).status, 400, 'Expired invitation must not commit membership after lock wait');
400
+ });
401
+ assert.equal((await pool.query('select count(*)::int n from family_membership where family_id=$1 and user_id=$2', [id, recipient.id])).rows[0].n, 0);
402
+ assert.equal((await invitations(owner, id)).body.invitations[0].status, 'expired');
403
+ });
404
+
405
+ test('acceptance waiting behind revoke sees committed revocation and creates no membership', async () => {
406
+ const owner = await actor(), recipient = await actor(), id = await family(owner), invitation = await invite(owner, id, recipient);
407
+ await withFamilyBlocked(id, async blocker => {
408
+ const pending = accept(recipient, invitation.invitationToken); await blockedOn(blocker);
409
+ await blocker.query("update family_invitation set status='revoked' where id=$1", [invitation.id]);
410
+ await blocker.query('commit'); assert.equal((await pending).status, 400);
411
+ });
412
+ assert.equal((await pool.query('select count(*)::int n from family_membership where family_id=$1 and user_id=$2', [id, recipient.id])).rows[0].n, 0);
413
+ });
414
+
415
+ test('role/transfer/revoke reject session expiry or revocation that occurs during an observed family lock wait', async () => {
416
+ for (const operation of ['role', 'transfer', 'revoke']) {
417
+ for (const invalidation of ['expiry', 'revocation']) {
418
+ const owner = await actor(), target = await actor(), id = await family(owner, [{ user: target }]),
419
+ invitation = operation === 'revoke' ? await invite(owner, id, await actor()) : null;
420
+ await withFamilyBlocked(id, async blocker => {
421
+ const pending = operation === 'role' ? role(owner, id, target, { mutationId: uuid(), expectedVersion: 1, role: 'parent_guardian' }) :
422
+ operation === 'transfer' ? transfer(owner, id, { mutationId: uuid(), targetUserId: target.id, expectedVersion: 1, expectedActorVersion: 1 }) :
423
+ revoke(owner, id, invitation.id, { mutationId: uuid(), expectedVersion: 1, action: 'revoke' });
424
+ await blockedOn(blocker);
425
+ await blocker.query(invalidation === 'expiry' ? "update auth_session set expires_at=statement_timestamp()-interval '1 millisecond' where id=$1" :
426
+ 'update auth_session set revoked_at=statement_timestamp() where id=$1', [owner.sid]);
427
+ await blocker.query('commit'); assert.equal((await pending).status, 401, `${operation}/${invalidation}`);
428
+ });
429
+ assert.equal((await member(id, target)).version, 1);
430
+ assert.equal((await pool.query('select count(*)::int n from family_lifecycle_mutation where actor_user_id=$1', [owner.id])).rows[0].n, 0);
431
+ if (invitation) assert.equal((await pool.query('select status from family_invitation where id=$1', [invitation.id])).rows[0].status, 'pending');
432
+ }
433
+ }
434
+ });
435
+
436
+ test('legacy invitation acceptance and membership removal roll back session expiry during observed lock wait', async () => {
437
+ for (const operation of ['accept', 'remove']) {
438
+ const owner = await actor(), recipient = await actor(), id = await family(owner, operation === 'remove' ? [{ user: recipient }] : []);
439
+ const invitation = operation === 'accept' ? await invite(owner, id, recipient) : null, acting = operation === 'accept' ? recipient : owner;
440
+ await withFamilyBlocked(id, async blocker => {
441
+ const pending = operation === 'accept' ? accept(recipient, invitation.invitationToken) : request(owner, 'DELETE', `/families/${id}/members/${recipient.id}`);
442
+ await blockedOn(blocker);
443
+ await blocker.query("update auth_session set expires_at=statement_timestamp()-interval '1 millisecond' where id=$1", [acting.sid]);
444
+ await blocker.query('commit'); assert.equal((await pending).status, 401, `${operation}: expired session must not commit`);
445
+ });
446
+ const record = await member(id, recipient);
447
+ assert.ok(operation === 'accept' ? !record : record.ended_at === null);
448
+ }
449
+ });
450
+
451
+ test('JWT expiry during an observed family-row wait rolls back an otherwise active session', async () => {
452
+ const owner = await actor(), target = await actor(), id = await family(owner, [{ user: target }]);
453
+ const expiration = Math.floor(Date.now() / 1000) + 2;
454
+ owner.token = jwt.sign({ sub: owner.id, sid: owner.sid, aud: 'lifemate-api', exp: expiration }, secret, { issuer: 'lifemate' });
455
+ await withFamilyBlocked(id, async blocker => {
456
+ const pending = role(owner, id, target, { mutationId: uuid(), expectedVersion: 1, role: 'parent_guardian' });
457
+ await blockedOn(blocker);
458
+ const deadline = Date.now() + 4000;
459
+ while (Date.now() < deadline) {
460
+ if ((await blocker.query('select statement_timestamp()>=to_timestamp($1) expired', [expiration])).rows[0].expired) break;
461
+ await new Promise(resolve => setTimeout(resolve, 15));
462
+ }
463
+ assert.equal((await blocker.query('select statement_timestamp()>=to_timestamp($1) expired', [expiration])).rows[0].expired, true);
464
+ await blocker.query('commit'); assert.equal((await pending).status, 401);
465
+ });
466
+ assert.equal((await member(id, target)).version, 1);
467
+ });
468
+
469
+ test('final session-row lock serializes logout and uses fresh time after a session-row wait', async () => {
470
+ for (const invalidation of ['expiry', 'revocation']) {
471
+ const owner = await actor(), target = await actor(), id = await family(owner, [{ user: target }]), blocker = await pool.connect();
472
+ try {
473
+ await blocker.query('begin'); await blocker.query('select id from auth_session where id=$1 for update', [owner.sid]);
474
+ const pending = role(owner, id, target, { mutationId: uuid(), expectedVersion: 1, role: 'parent_guardian' });
475
+ await blockedOn(blocker);
476
+ await blocker.query(invalidation === 'expiry' ? "update auth_session set expires_at=statement_timestamp()-interval '1 millisecond' where id=$1" :
477
+ 'update auth_session set revoked_at=statement_timestamp() where id=$1', [owner.sid]);
478
+ await blocker.query('commit'); assert.equal((await pending).status, 401);
479
+ } finally { await blocker.query('rollback').catch(() => {}); blocker.release(); }
480
+ assert.equal((await member(id, target)).version, 1, 'Even earlier writes must roll back at the final session gate');
481
+ assert.equal((await pool.query('select count(*)::int n from family_lifecycle_mutation where actor_user_id=$1', [owner.id])).rows[0].n, 0);
482
+ }
483
+ });
484
+
485
+ test('legacy family helper, invitation acceptance and family creation reject expiry after their final session-row wait', async () => {
486
+ for (const operation of ['rename', 'accept', 'create']) {
487
+ const owner = await actor(), recipient = await actor(), id = operation === 'create' ? null : await family(owner),
488
+ invitation = operation === 'accept' ? await invite(owner, id, recipient) : null,
489
+ acting = operation === 'accept' ? recipient : owner, blocker = await pool.connect();
490
+ try {
491
+ await blocker.query('begin'); await blocker.query('select id from auth_session where id=$1 for update', [acting.sid]);
492
+ const pending = operation === 'rename' ? request(owner, 'PATCH', `/families/${id}`, { name: 'Expired mutation' }) :
493
+ operation === 'accept' ? accept(recipient, invitation.invitationToken) : request(owner, 'POST', '/families', { name: 'Expired new family' });
494
+ await blockedOn(blocker);
495
+ await blocker.query("update auth_session set expires_at=statement_timestamp()-interval '1 millisecond' where id=$1", [acting.sid]);
496
+ await blocker.query('commit'); const response = await pending;
497
+ if (operation === 'create' && response.status === 201) families.push(response.body.id);
498
+ assert.equal(response.status, 401, `${operation}: initial valid session must not authorize a write after final row wait expiry`);
499
+ } finally { await blocker.query('rollback').catch(() => {}); blocker.release(); }
500
+ if (operation === 'rename') assert.equal((await pool.query('select name from family_workspace where id=$1', [id])).rows[0].name, 'Synthetic Lifecycle Family');
501
+ if (operation === 'accept') {
502
+ assert.equal(await member(id, recipient), undefined);
503
+ assert.equal((await pool.query('select status from family_invitation where id=$1', [invitation.id])).rows[0].status, 'pending');
504
+ }
505
+ if (operation === 'create') assert.equal((await pool.query('select count(*)::int n from family_workspace where created_by=$1', [owner.id])).rows[0].n, 0);
506
+ }
507
+ });
508
+
509
+ test('admin transfer waits for concurrent editable birth date and denies newly known minor context', async () => {
510
+ const owner = await actor(), target = await actor({ birthDate: '1990-01-01' }), id = await family(owner, [{ user: target }]), blocker = await pool.connect();
511
+ try {
512
+ await blocker.query('begin'); await blocker.query('select user_id from profile where user_id=$1 for update', [target.id]);
513
+ const pending = transfer(owner, id, { mutationId: uuid(), targetUserId: target.id, expectedVersion: 1, expectedActorVersion: 1 });
514
+ await blockedOn(blocker);
515
+ await blocker.query("update profile set birth_date='2020-01-01' where user_id=$1", [target.id]);
516
+ await blocker.query('commit'); assert.equal((await pending).body.error, 'minor_cannot_admin');
517
+ } finally { await blocker.query('rollback').catch(() => {}); blocker.release(); }
518
+ assert.equal((await member(id, owner)).is_admin, true); assert.equal((await member(id, target)).version, 1);
519
+ });
520
+
521
+ test('active admin authority is rechecked after an observed lock wait, and transfer/removal cannot remove the last admin', async () => {
522
+ const owner = await actor(), successor = await actor(), target = await actor(), id = await family(owner, [{ user: successor, admin: true }, { user: target }]);
523
+ await withFamilyBlocked(id, async blocker => {
524
+ const pending = role(owner, id, target, { mutationId: uuid(), expectedVersion: 1, role: 'parent_guardian' }); await blockedOn(blocker);
525
+ await blocker.query('update family_membership set is_admin=false where family_id=$1 and user_id=$2', [id, owner.id]);
526
+ await blocker.query('commit'); assert.equal((await pending).status, 403);
527
+ });
528
+ const results = await Promise.all([
529
+ transfer(successor, id, { mutationId: uuid(), targetUserId: target.id, expectedVersion: 1, expectedActorVersion: 1 }),
530
+ request(successor, 'DELETE', `/families/${id}/members/${successor.id}`),
531
+ ]);
532
+ assert.equal(results[0].status, 200);
533
+ assert.ok([403, 409].includes(results[1].status));
534
+ assert.equal((await pool.query('select count(*)::int n from family_membership m join app_user u on u.id=m.user_id where m.family_id=$1 and m.is_admin and m.ended_at is null and u.disabled_at is null', [id])).rows[0].n, 1);
535
+ });
536
+
537
+ test('cross-family reciprocal writes lock participating accounts in a stable order without deadlock', async () => {
538
+ const pair = (await Promise.all([actor(), actor()])).sort((a, b) => a.id.localeCompare(b.id));
539
+ const [low, high] = pair;
540
+ const first = await family(high, [{ user: low, role: 'parent_guardian', admin: true }]);
541
+ const second = await family(low, [{ user: high, role: 'parent_guardian', admin: true }]);
542
+ const blocker = await pool.connect(); let writes = [];
543
+ try {
544
+ await blocker.query('begin'); await blocker.query('select id from app_user where id=$1 for update', [low.id]);
545
+ await blocker.query('savepoint high_lock'); await blocker.query('select id from app_user where id=$1 for update', [high.id]);
546
+ writes = [role(high, first, low, { mutationId: uuid(), expectedVersion: 1, role: 'adult_member' }),
547
+ role(low, second, high, { mutationId: uuid(), expectedVersion: 1, role: 'adult_member' })];
548
+ await blockedOn(blocker, 2); await blocker.query('rollback to savepoint high_lock');
549
+ await blockedOn(blocker, 2); // Both must now wait for low, without retaining a higher account lock.
550
+ await blocker.query('commit');
551
+ const result = await Promise.all(writes); assert.deepEqual(result.map(row => row.status), [200, 200]);
552
+ assert.equal((await member(first, low)).version, 2); assert.equal((await member(second, high)).version, 2);
553
+ } finally { await blocker.query('rollback').catch(() => {}); blocker.release(); await Promise.allSettled(writes); }
554
+ });
555
+});
backend/tests/family_lifecycle_validation.test.js
new
+16
@@ -0,0 +1,16 @@
1
+import test from 'node:test';
2
+import assert from 'node:assert/strict';
3
+import crypto from 'node:crypto';
4
+import {normalizeRoleMutation,normalizeAdminTransfer,normalizeInvitationRevoke} from '../src/family_lifecycle.js';
5
+
6
+test('family lifecycle mutations require explicit stable IDs and integer versions, never role inference',()=>{
7
+ const mutationId=crypto.randomUUID(),targetUserId=crypto.randomUUID();
8
+ assert.deepEqual(normalizeRoleMutation({mutationId,expectedVersion:1,role:'adult_member'}),{mutationId,expectedVersion:1,role:'adult_member'});
9
+ assert.ok(normalizeAdminTransfer({mutationId,targetUserId,expectedVersion:1,expectedActorVersion:2}));
10
+ assert.ok(normalizeInvitationRevoke({mutationId,expectedVersion:1,action:'revoke'}));
11
+ for(const extra of [{role:'mother'},{isAdmin:true},{ownerUserId:targetUserId},{expectedVersion:'1'},{expectedVersion:0}]){
12
+ assert.equal(normalizeRoleMutation({mutationId,expectedVersion:1,role:'adult_member',...extra}),null);
13
+ }
14
+ assert.equal(normalizeAdminTransfer({mutationId,targetUserId,expectedVersion:1}),null);
15
+ assert.equal(normalizeInvitationRevoke({mutationId,expectedVersion:1,action:'accept'}),null);
16
+});
backend/tests/learning_goal_mutations.test.js
new
+263
@@ -0,0 +1,263 @@
1
+import test, { after } from 'node:test';
2
+import assert from 'node:assert/strict';
3
+import crypto from 'node:crypto';
4
+import jwt from 'jsonwebtoken';
5
+import pg from 'pg';
6
+import net from 'node:net';
7
+import {spawn} from 'node:child_process';
8
+import {once} from 'node:events';
9
+
10
+assert.ok(process.env.DATABASE_URL && process.env.JWT_SECRET?.length >= 32,
11
+ 'Use a migrated synthetic PostgreSQL database and synthetic signing secret');
12
+const pool=new pg.Pool({connectionString:process.env.DATABASE_URL});
13
+const users = [], families = [];
14
+let server, base;
15
+async function restart() {
16
+ if(server) { const closed=once(server,'close'); server.kill('SIGTERM'); await closed; }
17
+ const reservation=net.createServer().listen(0,'127.0.0.1');
18
+ await once(reservation,'listening'); const port=reservation.address().port;
19
+ await new Promise(resolve=>reservation.close(resolve));
20
+ base=`http://127.0.0.1:${port}`;
21
+ server=spawn(process.execPath,['src/entrypoint.js'],{stdio:['ignore','pipe','pipe'],env:{...process.env,
22
+ NODE_ENV:'production',PORT:String(port),SMS_PROVIDER:'disabled',SMS_PROVIDER_URL:'',SMS_PROVIDER_TOKEN:'',
23
+ EMAIL_FROM:'',RESEND_API_KEY:'',SMTP_HOST:'',SMTP_PASSWORD:'',ENABLE_SENSITIVE_FEATURES:'false',
24
+ CORS_ORIGINS:'',TRUSTED_PROXY_CIDRS:'',RATE_LIMIT_AUTH_MAX:'2000',RATE_LIMIT_GENERAL_MAX:'4000'}});
25
+ await new Promise((resolve,reject)=>{
26
+ let output=''; const timeout=setTimeout(()=>reject(new Error('Goal API process startup timed out')),10000);
27
+ server.stdout.on('data',chunk=>{output+=chunk.toString();if(output.includes('"type":"startup"')) {clearTimeout(timeout);resolve();}});
28
+ server.once('error',error=>{clearTimeout(timeout);reject(error);});
29
+ server.once('exit',code=>{clearTimeout(timeout);reject(new Error(`Goal API process stopped before startup (${code})`));});
30
+ });
31
+}
32
+await restart();
33
+after(async () => {
34
+ if(server && server.exitCode===null && server.signalCode===null) {
35
+ const closed=once(server,'close'); server.kill('SIGTERM'); await closed;
36
+ }
37
+ try {
38
+ if (families.length) await pool.query('delete from family_workspace where id=any($1::uuid[])', [families]);
39
+ if (users.length) await pool.query('delete from app_user where id=any($1::uuid[])', [users]);
40
+ } finally { await pool.end(); }
41
+});
42
+async function actor() {
43
+ const id = crypto.randomUUID(), sid = crypto.randomUUID(); users.push(id);
44
+ await pool.query('insert into app_user(id,identity_subject,email_normalized,email_verified_at) values($1,$2,$3,now())', [id, `goal-test:${id}`, `goal-${id}@example.test`]);
45
+ await pool.query("insert into profile(user_id,display_name) values($1,'Synthetic Goal')", [id]);
46
+ 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.randomUUID()]);
47
+ return {id,sid, token: jwt.sign({sub:id,sid,aud:'lifemate-api'},process.env.JWT_SECRET,{issuer:'lifemate',expiresIn:'15m'})};
48
+}
49
+async function request(actor, method, path, body) {
50
+ const response = await fetch(base+'/v1/learning/goals'+path,{method,
51
+ headers:{'content-type':'application/json',...(actor?{authorization:`Bearer ${actor.token}`}:{})},
52
+ ...(body===undefined?{}:{body:JSON.stringify(body)})});
53
+ const raw = await response.text();
54
+ return {status:response.status,body:raw?JSON.parse(raw):null};
55
+}
56
+const create = () => ({id:crypto.randomUUID(),mutationId:crypto.randomUUID(),expectedVersion:0,title:'هدف ساختگی',target:'Private synthetic target'});
57
+
58
+test('modern goal creates one stable record, retries lost acknowledgement after real API process restart and retains archive tombstone/history',async()=>{
59
+ const owner=await actor(), body=create();
60
+ const first=await request(owner,'POST','',body);
61
+ assert.equal(first.status,201); assert.ok(first.body.goal,'Canonical goal acknowledgement is required'); assert.equal(first.body.goal.id,body.id);
62
+ assert.equal(first.body.goal.version,1); assert.equal(first.body.acknowledgement.mutationId,body.mutationId);
63
+ const firstProcess=server.pid; await restart(); assert.notEqual(server.pid,firstProcess);
64
+ const retry=await request(owner,'POST','',body); assert.equal(retry.status,200);
65
+ assert.equal(retry.body.acknowledgement.status,'already_applied');
66
+ assert.equal((await pool.query('select count(*)::int n from learning_goal where id=$1',[body.id])).rows[0].n,1);
67
+ const checkin=(await pool.query('insert into learning_checkin(owner_user_id,learning_goal_id,confidence,note) values($1,$2,3,$3) returning id',[owner.id,body.id,'PRIVATE-SYNTHETIC-NOTE'])).rows[0];
68
+ const edit={mutationId:crypto.randomUUID(),expectedVersion:1,title:'ویرایش ساختگی',target:null,status:'completed'};
69
+ assert.equal((await request(owner,'PATCH','/'+body.id,edit)).body.goal.version,2);
70
+ const archive={mutationId:crypto.randomUUID(),expectedVersion:2};
71
+ const archived=await request(owner,'DELETE','/'+body.id,archive); assert.equal(archived.status,200); assert.equal(archived.body.goal.status,'archived');
72
+ const oldCreate=await request(owner,'POST','',body); assert.equal(oldCreate.body.goal.status,'archived');
73
+ assert.equal(oldCreate.body.goal.version,3); assert.equal(oldCreate.body.acknowledgement.appliedVersion,1);
74
+ assert.equal((await request(owner,'DELETE','/'+body.id,archive)).body.goal.version,3);
75
+ assert.equal((await request(owner,'GET','')).body.items.length,0);
76
+ assert.equal((await request(owner,'GET','/'+body.id)).body.status,'archived');
77
+ const retained=(await pool.query('select learning_goal_id,note from learning_checkin where id=$1',[checkin.id])).rows[0];
78
+ assert.deepEqual(retained,{learning_goal_id:body.id,note:'PRIVATE-SYNTHETIC-NOTE'});
79
+});
80
+
81
+test('goal mutation hash and expected version reject reuse, concurrent stale edits and archived revival',async()=>{
82
+ const owner=await actor(),body=create(); await request(owner,'POST','',body);
83
+ assert.equal((await request(owner,'POST','',{...body,title:'Changed intent'})).status,409);
84
+ const results=await Promise.all(['One','Two'].map(title=>request(owner,'PATCH','/'+body.id,{title,mutationId:crypto.randomUUID(),expectedVersion:1})));
85
+ assert.deepEqual(results.map(x=>x.status).sort(),[200,409]);
86
+ await request(owner,'DELETE','/'+body.id,{mutationId:crypto.randomUUID(),expectedVersion:2});
87
+ assert.equal((await request(owner,'PATCH','/'+body.id,{status:'active',mutationId:crypto.randomUUID(),expectedVersion:3})).status,409);
88
+ assert.equal((await pool.query('select count(*)::int n from learning_goal_mutation where owner_user_id=$1',[owner.id])).rows[0].n,3);
89
+});
90
+
91
+test('guardian and other family cannot read or mutate private goals, including request-owner injection',async()=>{
92
+ const owner=await actor(),guardian=await actor(),other=await actor(),family=crypto.randomUUID(); families.push(family);
93
+ await pool.query("insert into family_workspace(id,name,created_by) values($1,'Synthetic Goal Family',$2)",[family,guardian.id]);
94
+ await pool.query("insert into family_membership(family_id,user_id,role) values($1,$2,'teen_minor'),($1,$3,'parent_guardian')",[family,owner.id,guardian.id]);
95
+ await pool.query('insert into guardian_relationship(family_id,guardian_user_id,minor_user_id) values($1,$2,$3)',[family,guardian.id,owner.id]);
96
+ const body=create(); await request(owner,'POST','',body);
97
+ for(const viewer of [guardian,other]) {
98
+ assert.equal((await request(viewer,'GET','/'+body.id)).status,404);
99
+ assert.deepEqual((await request(viewer,'GET','')).body.items,[]);
100
+ assert.equal((await request(viewer,'PATCH','/'+body.id,{title:'Forbidden',mutationId:crypto.randomUUID(),expectedVersion:1})).status,403);
101
+ assert.equal((await request(viewer,'DELETE','/'+body.id,{mutationId:crypto.randomUUID(),expectedVersion:1})).status,403);
102
+ }
103
+ assert.equal((await request(owner,'POST','',{...create(),ownerUserId:other.id})).status,400);
104
+ for(const method of ['GET','POST','PATCH','DELETE']) assert.equal((await request(null,method,method==='POST'?'':'/'+body.id,method==='GET'?undefined:{})).status,401);
105
+});
106
+
107
+async function schoolSubject(owner, {subjectOwner=owner,activeContext=true,activeYear=true,activeTerm=true,archived=false}={}) {
108
+ const context=crypto.randomUUID(),year=crypto.randomUUID(),term=crypto.randomUUID(),subject=crypto.randomUUID();
109
+ await pool.query("insert into life_context(id,user_id,kind,title) values($1,$2,'student','Synthetic Goal Context')",[context,subjectOwner.id]);
110
+ await pool.query("insert into academic_year(id,student_user_id,life_context_id,title,starts_on,ends_on) values($1,$2,$3,'Synthetic Year','2026-09-23','2027-06-22')",[year,subjectOwner.id,context]);
111
+ await pool.query("insert into academic_term(id,academic_year_id,title,starts_on,ends_on) values($1,$2,'Synthetic Term','2026-09-23','2027-01-22')",[term,year]);
112
+ await pool.query("insert into subject(id,student_user_id,academic_term_id,name,archived_at) values($1,$2,$3,'Synthetic Math',case when $4 then now() else null end)",[subject,subjectOwner.id,term,archived]);
113
+ if(!activeContext) await pool.query('update life_context set active=false where id=$1',[context]);
114
+ if(!activeYear) await pool.query('update academic_year set active=false where id=$1',[year]);
115
+ if(!activeTerm) await pool.query('update academic_term set active=false where id=$1',[term]);
116
+ return {id:subject,context,year};
117
+}
118
+
119
+test('legacy and modern goals reject archived, inactive and foreign-owned school ancestry',async()=>{
120
+ const owner=await actor(),other=await actor();
121
+ const cases=[{archived:true},{activeContext:false},{activeYear:false},{activeTerm:false},{subjectOwner:other}];
122
+ for(const scenario of cases) {
123
+ const subject=await schoolSubject(owner,scenario);
124
+ const legacy=await request(owner,'POST','',{title:'Forbidden ancestry',subjectId:subject.id});
125
+ assert.equal(legacy.status,403,`legacy POST must reject ${Object.keys(scenario)[0]}`);
126
+ const modern=await request(owner,'POST','',{...create(),subjectId:subject.id});
127
+ assert.equal(modern.status,403,`modern POST must reject ${Object.keys(scenario)[0]}`);
128
+ const goal=await request(owner,'POST','',create());
129
+ assert.equal((await request(owner,'PATCH','/'+goal.body.goal.id,{subjectId:subject.id})).status,403);
130
+ assert.equal((await request(owner,'PATCH','/'+goal.body.goal.id,{subjectId:subject.id,mutationId:crypto.randomUUID(),expectedVersion:1})).status,403);
131
+ assert.equal((await request(owner,'GET','/'+goal.body.goal.id)).body.version,1);
132
+ }
133
+ const subject=await schoolSubject(owner);
134
+ const linked=await request(owner,'POST','',{...create(),subjectId:subject.id});
135
+ assert.equal(linked.status,201); assert.equal(linked.body.goal.subject_id,subject.id);
136
+ // Historical goal text remains editable after its school parent is inactive;
137
+ // only a new/reassigned subject link requires the currently active ancestry.
138
+ await pool.query('update academic_year set active=false where id=$1',[subject.year]);
139
+ const edited=await request(owner,'PATCH','/'+linked.body.goal.id,{mutationId:crypto.randomUUID(),expectedVersion:1,title:'Historical goal correction'});
140
+ assert.equal(edited.status,200); assert.equal(edited.body.goal.subject_id,subject.id);
141
+});
142
+
143
+test('legacy response shapes retain CRUD while versions and archive timestamps remain consistent',async()=>{
144
+ const owner=await actor();
145
+ const created=await request(owner,'POST','',{title:'Legacy goal',target:'Legacy target'});
146
+ assert.equal(created.status,201); assert.equal(created.body.version,1); assert.ok(created.body.id); assert.equal(created.body.goal,undefined);
147
+ const edited=await request(owner,'PATCH','/'+created.body.id,{target:null,status:'completed'});
148
+ assert.equal(edited.status,200); assert.equal(edited.body.version,2); assert.equal(edited.body.target,null); assert.equal(edited.body.archived_at,null);
149
+ const archived=await request(owner,'PATCH','/'+created.body.id,{status:'archived'});
150
+ assert.equal(archived.body.version,3); assert.ok(archived.body.archived_at);
151
+ assert.equal((await request(owner,'DELETE','/'+created.body.id)).status,204);
152
+ assert.equal((await request(owner,'DELETE','/'+created.body.id)).status,204);
153
+ const tombstone=await request(owner,'GET','/'+created.body.id);
154
+ assert.equal(tombstone.body.version,3); assert.equal(tombstone.body.archived_at,archived.body.archived_at);
155
+ assert.equal((await request(owner,'PATCH','/'+created.body.id,{status:'active'})).status,409);
156
+});
157
+
158
+test('goals validate exact write fields, text types, status and bounded versions without silently applying them',async()=>{
159
+ const owner=await actor(),goal=await request(owner,'POST','',create()),id=goal.body.goal.id;
160
+ const invalidCreates=[null,[],{title:{text:'Coercion'}},{title:'Too long',target:'x'.repeat(1001)},
161
+ {title:'Injected owner',ownerUserId:owner.id},{title:'Claimed verification',source:'verified'},
162
+ {title:'Invalid status',status:'verified'},{title:'Nul\u0000byte'}];
163
+ for(const body of invalidCreates) assert.equal((await request(owner,'POST','',body)).status,400);
164
+ for(const body of [{},[],{source:'verified'},{ownerUserId:owner.id},{title:'Nul\u0000byte'},
165
+ {status:'verified'},{title:'Valid',mutationId:crypto.randomUUID(),expectedVersion:0},
166
+ {title:'Valid',mutationId:crypto.randomUUID(),expectedVersion:2147483647},
167
+ {title:'Valid',mutationId:crypto.randomUUID(),expectedVersion:2147483648}]) {
168
+ assert.equal((await request(owner,'PATCH','/'+id,body)).status,400);
169
+ }
170
+ assert.equal((await request(owner,'DELETE','/'+id,{source:'verified'})).status,400);
171
+ assert.equal((await request(owner,'PATCH','/'+id+'?ownerUserId='+owner.id,{title:'Valid'})).status,400);
172
+ assert.equal((await request(owner,'GET','/'+id)).body.version,1);
173
+});
174
+
175
+async function waitForBlockedRequest(blockerPid) {
176
+ for(let tries=0;tries<100;tries++) {
177
+ const blocked=await pool.query('select 1 from pg_stat_activity where $1::int=any(pg_blocking_pids(pid))',[blockerPid]);
178
+ if(blocked.rowCount) return;
179
+ await new Promise(resolve=>setTimeout(resolve,10));
180
+ }
181
+ assert.fail('The real HTTP write never reached the PostgreSQL lock wait');
182
+}
183
+
184
+test('legacy and modern goal writes recheck expired/revoked sessions and JWT after an actual account lock wait',async()=>{
185
+ for(const modern of [false,true]) for(const reason of ['session_expiry','revocation','jwt_expiry']) {
186
+ const owner=await actor(),body=modern?create():{title:'Blocked synthetic goal'};
187
+ let expiresAt;
188
+ if(reason==='jwt_expiry') {
189
+ expiresAt=Math.floor(Date.now()/1000)+2;
190
+ owner.token=jwt.sign({sub:owner.id,sid:owner.sid,aud:'lifemate-api',exp:expiresAt},process.env.JWT_SECRET,{issuer:'lifemate'});
191
+ }
192
+ const blocker=await pool.connect();
193
+ let pending;
194
+ try {
195
+ await blocker.query('begin');
196
+ const pid=(await blocker.query('select pg_backend_pid() pid')).rows[0].pid;
197
+ await blocker.query('select id from app_user where id=$1 for update',[owner.id]);
198
+ pending=request(owner,'POST','',body);
199
+ await waitForBlockedRequest(pid);
200
+ if(reason==='session_expiry') await pool.query("update auth_session set expires_at=statement_timestamp()-interval '1 second' where id=$1",[owner.sid]);
201
+ if(reason==='revocation') await pool.query('update auth_session set revoked_at=statement_timestamp() where id=$1',[owner.sid]);
202
+ if(reason==='jwt_expiry') await new Promise(resolve=>setTimeout(resolve,Math.max(0,expiresAt*1000-Date.now()+20)));
203
+ await blocker.query('commit');
204
+ const result=await pending;
205
+ assert.equal(result.status,401,`${modern?'modern':'legacy'} ${reason} must rollback after waiting`);
206
+ assert.equal((await pool.query('select count(*)::int n from learning_goal where owner_user_id=$1',[owner.id])).rows[0].n,0);
207
+ } finally {
208
+ await blocker.query('rollback'); blocker.release();
209
+ if(pending) await pending;
210
+ }
211
+ }
212
+});
213
+
214
+test('goal final authorization rolls back a legacy or modern edit when JWT expires during the goal row wait',async()=>{
215
+ for(const modern of [false,true]) {
216
+ const owner=await actor(),created=await request(owner,'POST','',create());
217
+ const id=created.body.goal.id,expiresAt=Math.floor(Date.now()/1000)+2;
218
+ owner.token=jwt.sign({sub:owner.id,sid:owner.sid,aud:'lifemate-api',exp:expiresAt},process.env.JWT_SECRET,{issuer:'lifemate'});
219
+ const blocker=await pool.connect(); let pending;
220
+ try {
221
+ await blocker.query('begin');
222
+ const pid=(await blocker.query('select pg_backend_pid() pid')).rows[0].pid;
223
+ await blocker.query('select id from learning_goal where id=$1 for update',[id]);
224
+ pending=request(owner,'PATCH','/'+id,{title:'Must roll back',...(modern?{mutationId:crypto.randomUUID(),expectedVersion:1}:{})});
225
+ await waitForBlockedRequest(pid);
226
+ await new Promise(resolve=>setTimeout(resolve,Math.max(0,expiresAt*1000-Date.now()+20)));
227
+ await blocker.query('commit');
228
+ assert.equal((await pending).status,401);
229
+ const stored=(await pool.query('select title,version from learning_goal where id=$1',[id])).rows[0];
230
+ assert.deepEqual(stored,{title:'هدف ساختگی',version:1});
231
+ assert.equal((await pool.query('select count(*)::int n from learning_goal_mutation where owner_user_id=$1',[owner.id])).rows[0].n,1);
232
+ } finally {
233
+ await blocker.query('rollback'); blocker.release();
234
+ if(pending) await pending;
235
+ }
236
+ }
237
+});
238
+
239
+test('two owners concurrently using the same stable goal ID get one create and one denied conflict without a server error',async()=>{
240
+ const first=await actor(),second=await actor(),id=crypto.randomUUID();
241
+ const blocker=await pool.connect(); let pending;
242
+ try {
243
+ await blocker.query('begin'); await blocker.query('lock table learning_goal in share mode');
244
+ const blockerPid=(await blocker.query('select pg_backend_pid() pid')).rows[0].pid;
245
+ pending=Promise.all([first,second].map(owner=>request(owner,'POST','',{...create(),id})));
246
+ // Without entity serialization both creates reach the blocked INSERT after
247
+ // independently seeing no row. With serialization the second waits at the
248
+ // advisory lock, and observes the first committed row after release.
249
+ await waitForBlockedRequest(blockerPid);
250
+ await new Promise(resolve=>setTimeout(resolve,50));
251
+ await blocker.query('commit');
252
+ const results=await pending;
253
+ assert.deepEqual(results.map(result=>result.status).sort(),[201,403]);
254
+ assert.equal((await pool.query('select count(*)::int n from learning_goal where id=$1',[id])).rows[0].n,1);
255
+ const journal=await pool.query('select owner_user_id from learning_goal_mutation where goal_id=$1',[id]);
256
+ const goal=(await pool.query('select owner_user_id from learning_goal where id=$1',[id])).rows[0];
257
+ assert.deepEqual(journal.rows,[goal]);
258
+ const denied=results.find(result=>result.status===403);
259
+ assert.deepEqual(denied.body,{error:'goal_forbidden'});
260
+ } finally {
261
+ await blocker.query('rollback');blocker.release();if(pending) await pending;
262
+ }
263
+});
backend/tests/learning_unit_locator.test.js
new
+142
@@ -0,0 +1,142 @@
1
+import test, { before, after } from 'node:test';
2
+import assert from 'node:assert/strict';
3
+import crypto from 'node:crypto';
4
+import net from 'node:net';
5
+import { spawn } from 'node:child_process';
6
+import { once } from 'node:events';
7
+import pg from 'pg';
8
+import jwt from 'jsonwebtoken';
9
+
10
+// Real HTTP/SQL against a local synthetic test DB; no teaching approval.
11
+const fixtureUrl = process.env.TEST_FIXTURE_DATABASE_URL ?? process.env.DATABASE_URL;
12
+assert.ok(fixtureUrl, 'Locator tests require a migrated synthetic PostgreSQL fixture');
13
+const location = new URL(fixtureUrl);
14
+assert.ok(['127.0.0.1', 'localhost', '[::1]', '::1'].includes(location.hostname));
15
+assert.ok(location.pathname.includes('test') || location.pathname === '/lifemate_ci' ||
16
+ /^\/lifeguide_roles_source_[a-f0-9]{16}$/.test(location.pathname), 'Synthetic test database required');
17
+const pool = new pg.Pool({ connectionString: fixtureUrl });
18
+const secret = 'synthetic-unit-locator-secret-at-least-32-characters';
19
+const ids = { subject: crypto.randomUUID(), course: crypto.randomUUID(), unit: crypto.randomUUID() };
20
+const actors = [];
21
+let child, base;
22
+
23
+before(async () => {
24
+ const reservation = net.createServer();
25
+ reservation.listen(0, '127.0.0.1'); await once(reservation, 'listening');
26
+ const port = reservation.address().port;
27
+ await new Promise(resolve => reservation.close(resolve));
28
+ const env = { ...process.env, PORT: String(port), JWT_SECRET: secret, NODE_ENV: 'production',
29
+ SMS_PROVIDER: 'disabled', EMAIL_PROVIDER: 'disabled', ENABLE_SENSITIVE_FEATURES: 'false' };
30
+ delete env.TEST_FIXTURE_DATABASE_URL;
31
+ for (const key of ['SMS_PROVIDER_URL', 'SMS_PROVIDER_TOKEN', 'EMAIL_FROM', 'RESEND_API_KEY',
32
+ 'SMTP_HOST', 'SMTP_USER', 'SMTP_PASSWORD', 'AI_API_KEY', 'AI_BASE_URL', 'AI_MODEL', 'OPENAI_API_KEY']) env[key] = '';
33
+ child = spawn(process.execPath, ['src/entrypoint.js'], {
34
+ cwd: new URL('../', import.meta.url), env, stdio: ['ignore', 'pipe', 'pipe'],
35
+ });
36
+ let ready = false;
37
+ child.stdout.on('data', chunk => { if (chunk.toString().includes('"type":"startup"')) ready = true; });
38
+ child.stderr.on('data', () => {});
39
+ for (let retry = 0; retry < 200 && !ready; retry++) await new Promise(resolve => setTimeout(resolve, 25));
40
+ assert.ok(ready, 'Synthetic API must start'); base = `http://127.0.0.1:${port}`;
41
+ await pool.query(`insert into curriculum_subject(id,school_year,national_grade,code,name_fa)
42
+ values($1,'1405-1406',5,$2,'Synthetic locator subject')`, [ids.subject, `locator-${ids.subject}`]);
43
+ await pool.query(`insert into textbook_catalog(id,curriculum_subject_id,title_fa,source_url,stable_book_key)
44
+ values($1,$2,'Synthetic locator course','https://chap.sch.ir/',$3)`, [ids.course, ids.subject, `locator:${ids.course}`]);
45
+ await pool.query(`insert into learning_unit(id,textbook_id,unit_key,title_fa,order_index,index_kind,source_evidence_url)
46
+ values($1,$2,'locator-unit','درس صرفاً آزمایشی',1,'lesson','https://chap.sch.ir/')`, [ids.unit, ids.course]);
47
+ for (let index = 0; index < 2; index++) {
48
+ const id = crypto.randomUUID(), sid = crypto.randomUUID(); actors.push({ id, sid });
49
+ await pool.query(`insert into app_user(id,identity_subject,email_normalized,email_verified_at)
50
+ values($1,$2,$3,now())`, [id, `locator:${id}`, `${id}@example.test`]);
51
+ await pool.query(`insert into profile(user_id,display_name,theme_preference)
52
+ values($1,'Synthetic locator learner','adult_blue')`, [id]);
53
+ await pool.query(`insert into auth_session(id,user_id,refresh_digest,expires_at)
54
+ values($1,$2,$3,now()+interval '1 day')`, [sid, id, crypto.randomUUID()]);
55
+ actors[index].token = jwt.sign({ sub: id, sid, aud: 'lifemate-api' }, secret,
56
+ { issuer: 'lifemate', expiresIn: '15m' });
57
+ }
58
+ await pool.query(`insert into learning_progress(owner_user_id,unit_id,status,source,version)
59
+ values($1,$2,'in_progress','self_reported',1)`, [actors[0].id, ids.unit]);
60
+});
61
+
62
+after(async () => {
63
+ if (child && child.exitCode === null) { const closed = once(child, 'close'); child.kill('SIGTERM'); await closed; }
64
+ try {
65
+ await pool.query('delete from app_user where id=any($1::uuid[])', [actors.map(actor => actor.id)]);
66
+ await pool.query('delete from learning_unit where id=$1', [ids.unit]);
67
+ await pool.query('delete from textbook_catalog where id=$1', [ids.course]);
68
+ await pool.query('delete from curriculum_subject where id=$1', [ids.subject]);
69
+ } finally { await pool.end(); }
70
+});
71
+
72
+async function get(unit, actor, query = '') {
73
+ const response = await fetch(`${base}/v1/education/units/${unit}${query}`, {
74
+ headers: actor ? { authorization: `Bearer ${actor.token}` } : {},
75
+ });
76
+ return { status: response.status, body: response.headers.get('content-type')?.includes('application/json')
77
+ ? await response.json() : null };
78
+}
79
+
80
+test('locator gives authenticated catalogue navigation without owner or progress data', async () => {
81
+ const expected = { id: ids.unit, titleFa: 'درس صرفاً آزمایشی', courseId: ids.course };
82
+ for (const actor of actors) {
83
+ const result = await get(ids.unit, actor, `?ownerUserId=${actors[0].id}`);
84
+ assert.equal(result.status, 200); assert.deepEqual(result.body.unit, expected);
85
+ assert.deepEqual(Object.keys(result.body).sort(), ['fetchedAt', 'unit']);
86
+ assert.ok(Number.isFinite(Date.parse(result.body.fetchedAt)));
87
+ assert.equal(JSON.stringify(result.body).includes(actors[0].id), false);
88
+ assert.equal(JSON.stringify(result.body).includes('in_progress'), false);
89
+ }
90
+});
91
+
92
+test('locator requires current session and bounds UUID and absent catalogue items', async () => {
93
+ assert.equal((await get(ids.unit)).status, 401);
94
+ assert.equal((await get('not-a-uuid', actors[0])).status, 400);
95
+ assert.equal((await get(crypto.randomUUID(), actors[0])).status, 404);
96
+});
97
+
98
+test('inactive units and non-library legacy books cannot be located', async () => {
99
+ await pool.query('update learning_unit set active=false where id=$1', [ids.unit]);
100
+ try { assert.equal((await get(ids.unit, actors[0])).status, 404); }
101
+ finally { await pool.query('update learning_unit set active=true where id=$1', [ids.unit]); }
102
+ await pool.query('update textbook_catalog set stable_book_key=null where id=$1', [ids.course]);
103
+ try { assert.equal((await get(ids.unit, actors[0])).status, 404); }
104
+ finally { await pool.query('update textbook_catalog set stable_book_key=$2 where id=$1', [ids.course, `locator:${ids.course}`]); }
105
+});
106
+
107
+test('locator reflects current public title but neither private progress nor injected owner context', async () => {
108
+ const original = await get(ids.unit, actors[1]);
109
+ await pool.query("update learning_progress set status='completed',version=version+1,updated_at=now() where owner_user_id=$1 and unit_id=$2", [actors[0].id, ids.unit]);
110
+ const afterProgress = await get(ids.unit, actors[1], `?ownerUserId=${actors[0].id}&childId=${actors[0].id}&role=parent_guardian`);
111
+ assert.equal(afterProgress.status, 200); assert.deepEqual(afterProgress.body.unit, original.body.unit);
112
+ assert.deepEqual(Object.keys(afterProgress.body).sort(), ['fetchedAt', 'unit']);
113
+ assert.equal(JSON.stringify(afterProgress.body).includes('completed'), false);
114
+ assert.equal(JSON.stringify(afterProgress.body).includes(actors[0].id), false);
115
+ await pool.query('update learning_unit set title_fa=$2 where id=$1', [ids.unit, 'عنوان عمومی اصلاحشده']);
116
+ try {
117
+ const changed = await get(ids.unit, actors[1]);
118
+ assert.equal(changed.status, 200);
119
+ assert.deepEqual(changed.body.unit, { ...original.body.unit, titleFa: 'عنوان عمومی اصلاحشده' });
120
+ } finally { await pool.query('update learning_unit set title_fa=$2 where id=$1', [ids.unit, original.body.unit.titleFa]); }
121
+});
122
+
123
+test('locator rechecks token expiry, session expiry and disabled account state on each read', async () => {
124
+ const actor = actors[0];
125
+ const expired = { ...actor, token: jwt.sign({ sub: actor.id, sid: actor.sid, aud: 'lifemate-api' }, secret, { issuer: 'lifemate', expiresIn: -1 }) };
126
+ const expiredResult = await get(ids.unit, expired);
127
+ assert.equal(expiredResult.status, 401); assert.deepEqual(Object.keys(expiredResult.body), ['error']);
128
+ await pool.query("update auth_session set expires_at=now()-interval '1 second' where id=$1", [actor.sid]);
129
+ try { assert.equal((await get(ids.unit, actor)).status, 401); }
130
+ finally { await pool.query("update auth_session set expires_at=now()+interval '1 day' where id=$1", [actor.sid]); }
131
+ await pool.query('update app_user set disabled_at=now() where id=$1', [actor.id]);
132
+ try {
133
+ const disabled = await get(ids.unit, actor);
134
+ assert.equal(disabled.status, 401); assert.deepEqual(Object.keys(disabled.body), ['error']);
135
+ } finally { await pool.query('update app_user set disabled_at=null where id=$1', [actor.id]); }
136
+ assert.equal((await get(ids.unit, actor)).status, 200);
137
+});
138
+
139
+test('revoked session cannot resolve lesson metadata', async () => {
140
+ await pool.query('update auth_session set revoked_at=now() where id=$1', [actors[1].sid]);
141
+ assert.equal((await get(ids.unit, actors[1])).status, 401);
142
+});
backend/tests/report_periods.test.js
new
+277
@@ -0,0 +1,277 @@
1
+import test, { after } from 'node:test';
2
+import assert from 'node:assert/strict';
3
+import crypto from 'node:crypto';
4
+import express from 'express';
5
+import jwt from 'jsonwebtoken';
6
+import pg from 'pg';
7
+import { createSessionAuth } from '../src/session_auth.js';
8
+import { createPhase3Router } from '../src/phase3.js';
9
+import { createStudySessionsRouter } from '../src/study_sessions.js';
10
+
11
+assert.ok(process.env.DATABASE_URL, 'Report-period tests require synthetic PostgreSQL');
12
+const database = new URL(process.env.DATABASE_URL);
13
+assert.ok(['localhost', '127.0.0.1', '::1'].includes(database.hostname), 'Report tests refuse a nonlocal database');
14
+assert.match(database.pathname, /^\/(?:lifeguide_[a-z_]*test[a-z_]*|lifemate_ci|lifeguide_roles_source_[a-f0-9]{16})$/);
15
+const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
16
+const secret = 'synthetic-report-period-secret-32-characters';
17
+const auth = createSessionAuth({ pool, jwtSecret: secret });
18
+const app = express();
19
+app.use(express.json());
20
+app.use('/v1', createPhase3Router({ pool, auth }));
21
+app.use('/v1', createStudySessionsRouter({ pool, auth }));
22
+app.use((error, _req, res, _next) => { console.error(error); res.status(500).json({ error: 'internal_error' }); });
23
+const server = app.listen(0, '127.0.0.1');
24
+await new Promise((resolve) => server.on('listening', resolve));
25
+const base = `http://127.0.0.1:${server.address().port}`;
26
+const users = [], families = [];
27
+after(async () => {
28
+ await new Promise((resolve) => server.close(resolve));
29
+ try {
30
+ await pool.query('delete from access_audit where family_id=any($1::uuid[]) or actor_user_id=any($2::uuid[])', [families, users]);
31
+ await pool.query('delete from family_workspace where id=any($1::uuid[])', [families]);
32
+ await pool.query('delete from app_user where id=any($1::uuid[])', [users]);
33
+ } finally { await pool.end(); }
34
+});
35
+const iso = (ms) => new Date(ms).toISOString();
36
+const day = 86400000;
37
+function range() {
38
+ const local = new Date(Date.now() + 210 * 60000);
39
+ const to = Date.UTC(local.getUTCFullYear(), local.getUTCMonth(), local.getUTCDate()) - 210 * 60000;
40
+ return { from: to - 7 * day, to };
41
+}
42
+async function user() {
43
+ const id = crypto.randomUUID(), sid = crypto.randomUUID(); users.push(id);
44
+ await pool.query('insert into app_user(id,identity_subject,email_normalized,email_verified_at) values($1,$2,$3,now())', [id, `report-period:${id}`, `report-period-${id}@example.test`]);
45
+ await pool.query("insert into profile(user_id,display_name,theme_preference) values($1,'Synthetic report account','adult_blue')", [id]);
46
+ 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.randomUUID()]);
47
+ return { id, sid, token: jwt.sign({ sub: id, sid, aud: 'lifemate-api' }, secret, { issuer: 'lifemate', expiresIn: '15m' }) };
48
+}
49
+async function fixture() {
50
+ const child = await user(), mother = await user(), father = await user(), outsider = await user();
51
+ const familyId = crypto.randomUUID(); families.push(familyId);
52
+ await pool.query("insert into family_workspace(id,name,created_by) values($1,'Synthetic report family',$2)", [familyId, mother.id]);
53
+ for (const [actor, role] of [[child, 'teen_minor'], [mother, 'parent_guardian'], [father, 'parent_guardian']]) {
54
+ await pool.query('insert into family_membership(family_id,user_id,role,is_admin) values($1,$2,$3,$4)', [familyId, actor.id, role, actor === mother]);
55
+ }
56
+ for (const actor of [mother, father]) await pool.query('insert into guardian_relationship(family_id,guardian_user_id,minor_user_id) values($1,$2,$3)', [familyId, actor.id, child.id]);
57
+ return { child, mother, father, outsider, familyId };
58
+}
59
+async function request(path, actor, method = 'GET', body) {
60
+ const response = await fetch(base + path, { method, headers: { 'content-type': 'application/json', ...(actor ? { authorization: `Bearer ${actor.token}` } : {}) }, body: body === undefined ? undefined : JSON.stringify(body) });
61
+ return { status: response.status, body: await response.json() };
62
+}
63
+async function task(f, fields = {}) {
64
+ const { status, ...createFields } = fields;
65
+ const response = await request('/v1/plan-items', f.child, 'POST', { kind: 'assignment', title: 'Synthetic period assignment', familyId: f.familyId, visibility: 'parent_guardian', plannedDurationSeconds: 600, notes: 'PRIVATE-REPORT-DETAIL', ...createFields });
66
+ assert.equal(response.status, 201, JSON.stringify(response.body));
67
+ if (status === 'completed') {
68
+ const completed = await request(`/v1/plan-items/${response.body.id}/activity-state`, f.child, 'POST', { mutationId: crypto.randomUUID(), expectedVersion: 0, state: 'completed', source: 'self_reported', occurredAt: iso(Date.now() - 1000) });
69
+ assert.equal(completed.status, 200, JSON.stringify(completed.body));
70
+ }
71
+ return response.body;
72
+}
73
+async function report(f, actor = f.mother, window = range()) {
74
+ return request(`/v1/families/${f.familyId}/children/${f.child.id}/learning-report?from=${encodeURIComponent(iso(window.from))}&to=${encodeURIComponent(iso(window.to))}`, actor);
75
+}
76
+async function subject(f, name = 'Same-named subject') {
77
+ const context = await request('/v1/life-contexts', f.child, 'POST', { kind: 'student', title: 'Synthetic report school' });
78
+ assert.equal(context.status, 201);
79
+ const year = await request('/v1/school/years', f.child, 'POST', { lifeContextId: context.body.id, title: 'Synthetic year', startsOn: '2026-01-01', endsOn: '2026-12-31' });
80
+ assert.equal(year.status, 201);
81
+ const term = await request(`/v1/school/years/${year.body.id}/terms`, f.child, 'POST', { title: 'Synthetic term', startsOn: '2026-01-01', endsOn: '2026-12-31' });
82
+ assert.equal(term.status, 201);
83
+ const result = await request(`/v1/school/terms/${term.body.id}/subjects`, f.child, 'POST', { name });
84
+ assert.equal(result.status, 201); return result.body.id;
85
+}
86
+async function recorded(f, taskId, start, end) {
87
+ const result = await request('/v1/study/sessions', f.child, 'POST', { id: crypto.randomUUID(), mutationId: crypto.randomUUID(), planItemId: taskId, source: 'self_reported', startedAt: iso(start), endedAt: iso(end) });
88
+ assert.equal(result.status, 201, JSON.stringify(result.body));
89
+ return result.body.session;
90
+}
91
+
92
+test('period task cohort uses inclusive due/start boundaries, excludes undated and keeps explicit historical totals', async () => {
93
+ const f = await fixture(), window = range();
94
+ const atStart = await task(f, { dueAt: iso(window.from), status: 'completed', plannedDurationSeconds: 120 });
95
+ const startOnly = await task(f, { startsAt: iso(window.from + day), plannedDurationSeconds: 180 });
96
+ const old = await task(f, { dueAt: iso(window.from - 1), status: 'completed', plannedDurationSeconds: 900 });
97
+ const atEnd = await task(f, { dueAt: iso(window.to), plannedDurationSeconds: 300 });
98
+ const differentDates = await task(f, { startsAt: iso(window.from + day), dueAt: iso(window.to + day), plannedDurationSeconds: 360 });
99
+ const undated = await task(f, { plannedDurationSeconds: 420 });
100
+ const result = await report(f, f.mother, window);
101
+ assert.equal(result.status, 200);
102
+ assert.deepEqual(result.body.periodMetrics, {
103
+ totalTasks: 2, completedTasks: 1, completionPercent: 50, overdueTasks: 0,
104
+ plannedDurationSeconds: 300, recordedDurationSeconds: 0,
105
+ examCount: 0, gradedExamCount: 0, gradePercent: null,
106
+ });
107
+ assert.equal(result.body.allTimeTaskMetrics.totalTasks, 6);
108
+ assert.equal(result.body.allTimeTaskMetrics.completedTasks, 2);
109
+ assert.equal(result.body.metrics.totalTasks, 6, 'legacy field remains historical');
110
+ assert.equal(result.body.metrics.plannedInRangeDurationSeconds, 300);
111
+ assert.equal(result.body.taskDatePolicy, 'due_at_then_starts_at');
112
+ assert.equal(result.body.rangeConvention, 'inclusive_from_exclusive_to');
113
+ assert.equal(result.body.completionBasis, 'current_status_of_period_tasks');
114
+ assert.equal(result.body.timezone, 'Asia/Tehran');
115
+ assert.ok(Number.isFinite(Date.parse(result.body.asOf)));
116
+ const included = result.body.items.filter((row) => row.taskInRange).map((row) => row.id).sort();
117
+ assert.deepEqual(included, [atStart.id, startOnly.id].sort());
118
+ assert.ok([old, atEnd, differentDates, undated].every((row) => !result.body.items.find((item) => item.id === row.id).taskInRange));
119
+ assert.equal(JSON.stringify(result.body).includes('PRIVATE-REPORT-DETAIL'), false);
120
+});
121
+
122
+test('period time clips Tehran midnight even for older tasks and subject/exam aggregates only include authorized items once', async () => {
123
+ const f = await fixture(), window = range();
124
+ const firstSubject = await subject(f), secondSubject = await subject(f);
125
+ const firstExam = await task(f, { kind: 'exam', title: 'Allowed exam one', subjectId: firstSubject, dueAt: iso(window.from + day), gradePoints: 15, gradeOutOf: 20 });
126
+ const secondExam = await task(f, { kind: 'exam', title: 'Allowed exam two', subjectId: secondSubject, dueAt: iso(window.from + 2 * day), gradePoints: 30, gradeOutOf: 40 });
127
+ const older = await task(f, { subjectId: firstSubject, dueAt: iso(window.from - day) });
128
+ const privateExam = await task(f, { kind: 'exam', title: 'PRIVATE-EXAM-NOT-SHARED', subjectId: firstSubject, dueAt: iso(window.from + day), gradePoints: 0, gradeOutOf: 100, visibility: 'private' });
129
+ const selected = await task(f, { kind: 'exam', title: 'Mother-only exam', subjectId: firstSubject, dueAt: iso(window.from + 2 * day), gradePoints: 10, gradeOutOf: 10, visibility: 'selected_members', selectedMemberIds: [f.mother.id] });
130
+ await recorded(f, older.id, window.from - 5 * 60000, window.from + 10 * 60000);
131
+ await recorded(f, firstExam.id, window.from + 2 * day - 5 * 60000, window.from + 2 * day + 5 * 60000);
132
+ await recorded(f, secondExam.id, window.to - 5 * 60000, window.to + 5 * 60000);
133
+ await recorded(f, privateExam.id, window.from + 3 * day, window.from + 3 * day + 20 * 60000);
134
+ const mother = await report(f, f.mother, window);
135
+ assert.equal(mother.status, 200);
136
+ assert.equal(mother.body.periodMetrics.totalTasks, 3);
137
+ assert.equal(mother.body.periodMetrics.recordedDurationSeconds, 1500);
138
+ assert.equal(mother.body.periodMetrics.examCount, 3);
139
+ assert.equal(mother.body.periodMetrics.gradedExamCount, 3);
140
+ assert.equal(mother.body.periodMetrics.gradePercent, 78.57);
141
+ assert.deepEqual(mother.body.periodExams.map((row) => row.id).sort(), [firstExam.id, secondExam.id, selected.id].sort());
142
+ assert.equal(mother.body.periodSubjects.length, 2, 'same labels do not merge distinct subjects');
143
+ const first = mother.body.periodSubjects.find((row) => row.subjectId === firstSubject);
144
+ const second = mother.body.periodSubjects.find((row) => row.subjectId === secondSubject);
145
+ assert.equal(first.totalTasks, 2); assert.equal(first.recordedDurationSeconds, 1200); assert.equal(first.gradePercent, 83.33);
146
+ assert.equal(second.totalTasks, 1); assert.equal(second.recordedDurationSeconds, 300); assert.equal(second.gradePercent, 75);
147
+ assert.equal(mother.body.daily.reduce((sum, row) => sum + row.recordedDurationSeconds, 0), 1500);
148
+ assert.equal(mother.body.isEvidenceOfStudy, false);
149
+ assert.equal(mother.body.recordingDisclaimerKey, 'recorded_time_is_not_proof_of_study');
150
+ const father = await report(f, f.father, window);
151
+ assert.equal(father.body.periodMetrics.totalTasks, 2); assert.equal(father.body.periodMetrics.gradePercent, 75);
152
+ assert.equal(father.body.periodExams.length, 2);
153
+ assert.equal(JSON.stringify(mother.body).includes('PRIVATE-EXAM-NOT-SHARED'), false);
154
+ assert.equal(JSON.stringify(mother.body).includes('PRIVATE-REPORT-DETAIL'), false);
155
+ assert.equal(JSON.stringify(father.body).includes('Mother-only exam'), false);
156
+ assert.equal((await report(f, f.outsider, window)).status, 403);
157
+});
158
+
159
+test('period fields recheck current membership, guardian relationship, family state and sharing on every read', async () => {
160
+ const f = await fixture(), window = range();
161
+ const otherFamily = await fixture();
162
+ assert.equal((await report(f, otherFamily.mother, window)).status, 403, 'a guardian of another family cannot read this child');
163
+ const shared = await task(f, { dueAt: iso(window.from + day) });
164
+ assert.equal((await report(f, f.mother, window)).body.periodMetrics.totalTasks, 1);
165
+ await pool.query("update plan_item set visibility='private' where id=$1", [shared.id]);
166
+ const hidden = await report(f, f.mother, window);
167
+ assert.equal(hidden.body.periodMetrics.totalTasks, 0);
168
+ assert.deepEqual(hidden.body.periodExams, []); assert.deepEqual(hidden.body.periodSubjects, []);
169
+ await pool.query("update plan_item set visibility='parent_guardian' where id=$1", [shared.id]);
170
+ await pool.query('update guardian_relationship set active=false where family_id=$1 and guardian_user_id=$2', [f.familyId, f.mother.id]);
171
+ assert.equal((await report(f, f.mother, window)).status, 403);
172
+ await pool.query('update guardian_relationship set active=true where family_id=$1 and guardian_user_id=$2', [f.familyId, f.mother.id]);
173
+ await pool.query('update family_membership set ended_at=now() where family_id=$1 and user_id=$2', [f.familyId, f.child.id]);
174
+ assert.equal((await report(f, f.mother, window)).status, 403);
175
+ await pool.query('update family_membership set ended_at=null where family_id=$1 and user_id=$2', [f.familyId, f.child.id]);
176
+ await pool.query('update family_workspace set archived_at=now() where id=$1', [f.familyId]);
177
+ assert.equal((await report(f, f.mother, window)).status, 403);
178
+});
179
+
180
+test('report version reflects the period and authorized subject label rather than only task timestamps', async () => {
181
+ const f = await fixture(), window = range();
182
+ const subjectId = await subject(f, 'Original report label');
183
+ await task(f, { subjectId, dueAt: iso(window.from + day) });
184
+ const original = await report(f, f.mother, window);
185
+ const changedRange = await report(f, f.mother, { ...window, from: window.from + 2 * day });
186
+ assert.notEqual(original.body.sourceVersion, changedRange.body.sourceVersion);
187
+ await pool.query('update subject set name=$2 where id=$1', [subjectId, 'Renamed report label']);
188
+ const renamed = await report(f, f.mother, window);
189
+ assert.equal(renamed.body.periodSubjects[0].subjectName, 'Renamed report label');
190
+ assert.notEqual(original.body.sourceVersion, renamed.body.sourceVersion);
191
+});
192
+
193
+test('period reports reject expired credentials, database sessions and disabled accounts before returning data', async () => {
194
+ const f = await fixture(), window = range();
195
+ await task(f, { title: 'SESSION-PRIVATE-REPORT-TITLE', dueAt: iso(window.from + day) });
196
+ const expired = { ...f.mother, token: jwt.sign({ sub: f.mother.id, sid: f.mother.sid, aud: 'lifemate-api' }, secret, { issuer: 'lifemate', expiresIn: -1 }) };
197
+ for (const actor of [null, expired]) {
198
+ const result = await report(f, actor, window);
199
+ assert.equal(result.status, 401); assert.deepEqual(Object.keys(result.body), ['error']);
200
+ }
201
+ await pool.query("update auth_session set expires_at=now()-interval '1 second' where id=$1", [f.mother.sid]);
202
+ assert.equal((await report(f, f.mother, window)).status, 401);
203
+ await pool.query("update auth_session set expires_at=now()+interval '1 day',revoked_at=now() where id=$1", [f.mother.sid]);
204
+ assert.equal((await report(f, f.mother, window)).status, 401);
205
+ await pool.query('update auth_session set revoked_at=null where id=$1', [f.mother.sid]);
206
+ await pool.query('update app_user set disabled_at=now() where id=$1', [f.mother.id]);
207
+ const disabled = await report(f, f.mother, window);
208
+ assert.equal(disabled.status, 401); assert.deepEqual(Object.keys(disabled.body), ['error']);
209
+ assert.equal(JSON.stringify(disabled.body).includes('SESSION-PRIVATE-REPORT-TITLE'), false);
210
+});
211
+
212
+test('report requests validate UTC ranges, duration bounds, defaults and repeated parameters', async () => {
213
+ const f = await fixture(), window = range();
214
+ const path = `/v1/families/${f.familyId}/children/${f.child.id}/learning-report`;
215
+ const query = (from, to) => `${path}?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}`;
216
+ for (const [from, to] of [
217
+ ['broken', iso(window.to)], [iso(window.from), 'broken'],
218
+ [iso(window.from), iso(window.from)], [iso(window.to), iso(window.from)],
219
+ [iso(window.to - 367 * day), iso(window.to)],
220
+ ['2026-02-30T00:00:00Z', '2026-03-01T00:00:00Z'],
221
+ ['2026-01-01T00:00:00+03:30', '2026-01-02T00:00:00Z'],
222
+ ]) {
223
+ const invalid = await request(query(from, to), f.mother);
224
+ assert.equal(invalid.status, 400, `${from} → ${to}`);
225
+ assert.deepEqual(invalid.body, { error: 'invalid_report_range' });
226
+ }
227
+ const duplicate = await request(`${query(iso(window.from), iso(window.to))}&from=${encodeURIComponent(iso(window.from))}`, f.mother);
228
+ assert.equal(duplicate.status, 400);
229
+ const maximum = await request(query(iso(window.to - 366 * day), iso(window.to)), f.mother);
230
+ assert.equal(maximum.status, 200); assert.equal(Date.parse(maximum.body.to) - Date.parse(maximum.body.from), 366 * day);
231
+ const onlyTo = await request(`${path}?to=${encodeURIComponent(iso(window.to))}`, f.mother);
232
+ assert.equal(onlyTo.status, 200); assert.equal(Date.parse(onlyTo.body.to) - Date.parse(onlyTo.body.from), 30 * day);
233
+ const before = Date.now(), defaults = await request(path, f.mother), after = Date.now();
234
+ assert.equal(defaults.status, 200);
235
+ assert.equal(Date.parse(defaults.body.to) - Date.parse(defaults.body.from), 30 * day);
236
+ assert.ok(Date.parse(defaults.body.to) >= before && Date.parse(defaults.body.to) <= after);
237
+});
238
+
239
+test('report fingerprints change only for current visible source data and preserve no private mutation signal', async () => {
240
+ const f = await fixture(), window = range();
241
+ const shared = await task(f, { title: 'Visible source', dueAt: iso(window.from + day) });
242
+ const hidden = await task(f, { title: 'PRIVATE-HIDDEN-SOURCE', visibility: 'private', dueAt: iso(window.from + day) });
243
+ const original = await report(f, f.mother, window), repeated = await report(f, f.mother, window);
244
+ assert.match(original.body.sourceVersion, /^[a-f0-9]{64}$/);
245
+ assert.equal(repeated.body.sourceVersion, original.body.sourceVersion);
246
+ await pool.query('update plan_item set title=$2,version=version+1,updated_at=now() where id=$1', [hidden.id, 'PRIVATE-HIDDEN-CHANGED']);
247
+ const hiddenChanged = await report(f, f.mother, window);
248
+ assert.equal(hiddenChanged.body.sourceVersion, original.body.sourceVersion);
249
+ assert.equal(hiddenChanged.body.lastSyncAt, original.body.lastSyncAt);
250
+ assert.equal(JSON.stringify(hiddenChanged.body).includes('PRIVATE-HIDDEN-CHANGED'), false);
251
+ await pool.query('update plan_item set title=$2,version=version+1,updated_at=now() where id=$1', [shared.id, 'Visible source changed']);
252
+ const visibleChanged = await report(f, f.mother, window);
253
+ assert.notEqual(visibleChanged.body.sourceVersion, original.body.sourceVersion);
254
+ await pool.query("update plan_item set visibility='private' where id=$1", [shared.id]);
255
+ const revoked = await report(f, f.mother, window);
256
+ assert.equal(revoked.body.periodMetrics.totalTasks, 0); assert.deepEqual(revoked.body.items, []);
257
+ assert.notEqual(revoked.body.sourceVersion, visibleChanged.body.sourceVersion);
258
+ assert.equal(revoked.body.lastSyncAt, null);
259
+ await pool.query("update family_membership set role='adult_member' where family_id=$1 and user_id=$2", [f.familyId, f.mother.id]);
260
+ assert.equal((await report(f, f.mother, window)).status, 403, 'family administration is not guardian authority');
261
+});
262
+
263
+test('report fingerprint is stable when only fixture interval physical row order changes', async () => {
264
+ const f = await fixture(), window = range();
265
+ const shared = await task(f, { dueAt: iso(window.from + day) });
266
+ const first = await recorded(f, shared.id, window.from + day, window.from + day + 5 * 60000);
267
+ await recorded(f, shared.id, window.from + 2 * day, window.from + 2 * day + 7 * 60000);
268
+ const original = await report(f, f.mother, window);
269
+ // A no-op SQL update changes the physical heap position without changing
270
+ // any logical report input. Only this randomized fixture's row is touched.
271
+ await pool.query('update study_interval set starts_at=starts_at where session_id=$1', [first.id]);
272
+ const reordered = await report(f, f.mother, window);
273
+ assert.deepEqual(reordered.body.items, original.body.items);
274
+ assert.deepEqual(reordered.body.periodMetrics, original.body.periodMetrics);
275
+ assert.deepEqual(reordered.body.daily, original.body.daily);
276
+ assert.equal(reordered.body.sourceVersion, original.body.sourceVersion);
277
+});
backend/tests/school_lifecycle.test.js
new
+363
@@ -0,0 +1,363 @@
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 pg from 'pg';
8
+import jwt from 'jsonwebtoken';
9
+import fs from 'node:fs/promises';
10
+import { assertSchoolSession } from '../src/school_lifecycle.js';
11
+
12
+assert.ok(process.env.DATABASE_URL, 'School lifecycle tests require migrated synthetic PostgreSQL');
13
+assert.ok(process.env.JWT_SECRET?.length >= 32, 'School lifecycle tests require a synthetic JWT secret');
14
+const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
15
+const users = [], families = [];
16
+let child, base, output = '', errors = '';
17
+
18
+async function start() {
19
+ const reservation = net.createServer().listen(0, '127.0.0.1');
20
+ await once(reservation, 'listening');
21
+ const port = reservation.address().port;
22
+ await new Promise((resolve) => reservation.close(resolve));
23
+ base = `http://127.0.0.1:${port}`;
24
+ let startup = '';
25
+ child = spawn(process.execPath, ['src/entrypoint.js'], {
26
+ env: { ...process.env, NODE_ENV: 'production', PORT: String(port),
27
+ SMS_PROVIDER: 'disabled', SMS_PROVIDER_URL: '', SMS_PROVIDER_TOKEN: '', EMAIL_FROM: '', RESEND_API_KEY: '', SMTP_HOST: '',
28
+ CORS_ORIGINS: '', TRUSTED_PROXY_CIDRS: '', ENABLE_SENSITIVE_FEATURES: 'false',
29
+ RATE_LIMIT_AUTH_MAX: '2000', RATE_LIMIT_GENERAL_MAX: '4000', RATE_LIMIT_AI_MAX: '2000' },
30
+ stdio: ['ignore', 'pipe', 'pipe'],
31
+ });
32
+ child.stdout.on('data', (chunk) => { output += chunk.toString(); startup += chunk.toString(); });
33
+ child.stderr.on('data', (chunk) => { errors += chunk.toString(); });
34
+ await new Promise((resolve, reject) => {
35
+ const timer = setTimeout(() => reject(new Error('School lifecycle fixture startup timed out')), 10000);
36
+ const onData = () => {
37
+ if (!startup.includes('"type":"startup"')) return;
38
+ clearTimeout(timer); child.stdout.off('data', onData); resolve();
39
+ };
40
+ child.stdout.on('data', onData);
41
+ child.once('error', (error) => { clearTimeout(timer); reject(error); });
42
+ });
43
+}
44
+async function stop() {
45
+ if (child && child.exitCode === null && child.signalCode === null) {
46
+ const closed = once(child, 'close'); child.kill('SIGTERM'); await closed;
47
+ }
48
+}
49
+before(start);
50
+after(async () => {
51
+ await stop();
52
+ try {
53
+ await pool.query('delete from access_audit where family_id=any($1::uuid[]) or actor_user_id=any($2::uuid[])', [families, users]);
54
+ await pool.query('delete from family_workspace where id=any($1::uuid[])', [families]);
55
+ await pool.query('delete from app_user where id=any($1::uuid[])', [users]);
56
+ } finally { await pool.end(); }
57
+});
58
+async function user() {
59
+ const id = crypto.randomUUID(), sid = crypto.randomUUID();
60
+ users.push(id);
61
+ await pool.query('insert into app_user(id,identity_subject,email_normalized,email_verified_at) values($1,$2,$3,now())', [id, `school-fixture:${id}`, `school-${id}@example.test`]);
62
+ await pool.query("insert into profile(user_id,display_name,theme_preference) values($1,'Synthetic School User','adult_blue')", [id]);
63
+ 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')]);
64
+ return { id, token: jwt.sign({ sub: id, sid, aud: 'lifemate-api' }, process.env.JWT_SECRET, { issuer: 'lifemate', expiresIn: '15m' }) };
65
+}
66
+async function request(path, { method = 'GET', actor, body } = {}) {
67
+ const response = await fetch(base + path, { method, headers: { 'content-type': 'application/json', ...(actor ? { authorization: `Bearer ${actor.token}` } : {}) }, body: body === undefined ? undefined : JSON.stringify(body) });
68
+ const text = await response.text();
69
+ return { status: response.status, body: text && response.headers.get('content-type')?.includes('application/json') ? JSON.parse(text) : text || null };
70
+}
71
+
72
+async function observedBlock(blocker) {
73
+ const pid = (await blocker.query('select pg_backend_pid() as pid')).rows[0].pid;
74
+ const deadline = Date.now() + 3000;
75
+ while (Date.now() < deadline) {
76
+ const waiting = await pool.query('select 1 from pg_stat_activity where $1=any(pg_blocking_pids(pid))', [pid]);
77
+ if (waiting.rowCount) return;
78
+ await new Promise((resolve) => setTimeout(resolve, 15));
79
+ }
80
+ throw new Error('Request never reached the observed PostgreSQL row-lock wait');
81
+}
82
+
83
+async function expireAfterObservedWait(blocker, expiresAt) {
84
+ await observedBlock(blocker);
85
+ while (Date.now() <= expiresAt + 25) await new Promise((resolve) => setTimeout(resolve, Math.min(25, expiresAt + 26 - Date.now())));
86
+ await blocker.query('commit');
87
+}
88
+
89
+
90
+test('owner lifecycle list starts empty and rejects anonymous access', async () => {
91
+ const actor = await user();
92
+ assert.equal((await request('/v1/school/lifecycle')).status, 401);
93
+ const result = await request('/v1/school/lifecycle', { actor });
94
+ assert.equal(result.status, 200);
95
+ assert.deepEqual(result.body.contexts, []);
96
+ assert.deepEqual(result.body.years, []);
97
+ assert.deepEqual(result.body.terms, []);
98
+ assert.ok(Date.parse(result.body.fetchedAt));
99
+});
100
+
101
+function intent(operation = 'create', data = {}, entityId = crypto.randomUUID(), expectedVersion = operation === 'create' ? 0 : 1) {
102
+ return { mutationId: crypto.randomUUID(), entityId, operation, expectedVersion, data };
103
+}
104
+const mutate = (actor, type, body) => request(`/v1/school/lifecycle/${type}/mutations`, { method: 'POST', actor, body });
105
+async function lifecycle(actor = undefined) {
106
+ actor ??= await user();
107
+ const contextIntent = intent('create', { kind: 'student', title: 'مدرسه آزمایشی' });
108
+ const context = await mutate(actor, 'contexts', contextIntent); assert.equal(context.status, 201);
109
+ const yearIntent = intent('create', { lifeContextId: context.body.entity.id, title: 'سال انتخابی', startsOn: '2026-08-12', endsOn: '2027-07-05' });
110
+ const year = await mutate(actor, 'years', yearIntent); assert.equal(year.status, 201);
111
+ const termIntent = intent('create', { academicYearId: year.body.entity.id, title: 'دوره انتخابی', startsOn: '2026-08-15', endsOn: '2027-02-10' });
112
+ const term = await mutate(actor, 'terms', termIntent); assert.equal(term.status, 201);
113
+ return { actor, context: context.body.entity, year: year.body.entity, term: term.body.entity, contextIntent, yearIntent, termIntent };
114
+}
115
+
116
+test('stable school creates survive lost ACK, process restart and old retry returns current version', async () => {
117
+ const f = await lifecycle();
118
+ await stop(); await start();
119
+ const retry = await mutate(f.actor, 'years', f.yearIntent);
120
+ assert.equal(retry.status, 200); assert.equal(retry.body.acknowledgement.status, 'already_applied');
121
+ assert.equal(retry.body.acknowledgement.appliedVersion, 1);
122
+ const edited = await mutate(f.actor, 'years', intent('update', { title: 'سال ویرایششده' }, f.year.id, 1));
123
+ assert.equal(edited.status, 200); assert.equal(edited.body.entity.version, 2);
124
+ const oldRetry = await mutate(f.actor, 'years', f.yearIntent);
125
+ assert.equal(oldRetry.body.entity.title, 'سال ویرایششده'); assert.equal(oldRetry.body.entity.version, 2);
126
+ assert.equal(oldRetry.body.acknowledgement.appliedVersion, 1);
127
+ assert.equal((await pool.query('select count(*)::int as n from academic_year where student_user_id=$1', [f.actor.id])).rows[0].n, 1);
128
+ assert.equal((await mutate(f.actor, 'years', { ...f.yearIntent, data: { ...f.yearIntent.data, title: 'UUID reused with changed content' } })).status, 409);
129
+ const reopened = await request('/v1/school/lifecycle', { actor: f.actor });
130
+ assert.equal(reopened.body.years[0].starts_on, '2026-08-12');
131
+ assert.equal(reopened.body.terms[0].starts_on, '2026-08-15');
132
+});
133
+
134
+test('school version conflicts reject stale edits and archive preserves linked tasks and history', async () => {
135
+ const f = await lifecycle();
136
+ const subject = await request(`/v1/school/terms/${f.term.id}/subjects`, { method: 'POST', actor: f.actor, body: { name: 'فیزیک انتخابی' } });
137
+ assert.equal(subject.status, 201);
138
+ const homework = await request('/v1/plan-items', { method: 'POST', actor: f.actor, body: { kind: 'assignment', title: 'تکلیف تاریخی', subjectId: subject.body.id, visibility: 'private' } });
139
+ assert.equal(homework.status, 201);
140
+ const edit = await mutate(f.actor, 'contexts', intent('update', { title: 'نام تازه' }, f.context.id));
141
+ assert.equal(edit.status, 200);
142
+ assert.equal((await mutate(f.actor, 'contexts', intent('update', { title: 'stale' }, f.context.id))).status, 409);
143
+ const archivedIntent = intent('archive', {}, f.context.id, 2);
144
+ const archived = await mutate(f.actor, 'contexts', archivedIntent);
145
+ assert.equal(archived.status, 200); assert.equal(archived.body.entity.active, false);
146
+ await stop(); await start();
147
+ assert.equal((await mutate(f.actor, 'contexts', archivedIntent)).body.acknowledgement.status, 'already_applied');
148
+ const list = await request('/v1/school/lifecycle', { actor: f.actor });
149
+ assert.equal(list.body.contexts[0].active, false);
150
+ assert.equal(list.body.years[0].id, f.year.id);
151
+ assert.equal(list.body.terms[0].id, f.term.id);
152
+ const retained = (await pool.query('select p.subject_id,s.name from plan_item p join subject s on s.id=p.subject_id where p.id=$1', [homework.body.id])).rows[0];
153
+ assert.equal(retained.subject_id, subject.body.id); assert.equal(retained.name, 'فیزیک انتخابی');
154
+ const overview = await request(`/v1/school/${f.actor.id}/overview`, { actor: f.actor });
155
+ assert.deepEqual(overview.body.years, []); assert.deepEqual(overview.body.subjects, []);
156
+ assert.ok(overview.body.workload.some((row) => row.id === homework.body.id));
157
+ assert.equal((await mutate(f.actor, 'terms', intent('update', { title: 'Cannot edit archived ancestor' }, f.term.id))).status, 409);
158
+ assert.equal((await mutate(f.actor, 'contexts', intent('update', { title: 'Cannot unarchive' }, f.context.id, 3))).status, 409);
159
+});
160
+
161
+test('guardian and other-family actors cannot read or write another owner lifecycle', async () => {
162
+ const f = await lifecycle(), parent = await user(), outsider = await user();
163
+ const familyId = crypto.randomUUID(); families.push(familyId);
164
+ await pool.query("insert into family_workspace(id,name,created_by) values($1,'Lifecycle Synthetic Family',$2)", [familyId, parent.id]);
165
+ await pool.query("insert into family_membership(family_id,user_id,role) values($1,$2,'teen_minor'),($1,$3,'parent_guardian')", [familyId, f.actor.id, parent.id]);
166
+ await pool.query('insert into guardian_relationship(family_id,guardian_user_id,minor_user_id) values($1,$2,$3)', [familyId, parent.id, f.actor.id]);
167
+ for (const actor of [parent, outsider]) {
168
+ const list = await request('/v1/school/lifecycle', { actor });
169
+ assert.deepEqual(list.body.contexts, []); assert.deepEqual(list.body.years, []); assert.deepEqual(list.body.terms, []);
170
+ for (const [type, entity] of [['contexts', f.context], ['years', f.year], ['terms', f.term]]) {
171
+ assert.equal((await mutate(actor, type, intent('update', { title: 'forged' }, entity.id))).status, 404);
172
+ assert.equal((await mutate(actor, type, intent('archive', {}, entity.id))).status, 404);
173
+ }
174
+ assert.equal((await mutate(actor, 'years', intent('create', { lifeContextId: f.context.id, title: 'forged', startsOn: '2026-09-01', endsOn: '2027-01-01' }))).status, 403);
175
+ assert.equal((await mutate(actor, 'terms', intent('create', { academicYearId: f.year.id, title: 'forged', startsOn: '2026-09-01', endsOn: '2027-01-01' }))).status, 403);
176
+ }
177
+});
178
+
179
+test('date nesting and historical class recurrence prevent invalid parent date edits', async () => {
180
+ const f = await lifecycle();
181
+ for (const date of ['2026-02-30', '0000-01-01', '2026-8-01', '۱۴۰۵-۰۶-۰۱']) {
182
+ assert.equal((await mutate(f.actor, 'years', intent('create', { lifeContextId: f.context.id, title: 'invalid', startsOn: date, endsOn: '2027-01-01' }))).status, 400);
183
+ }
184
+ assert.equal((await mutate(f.actor, 'terms', intent('create', { academicYearId: f.year.id, title: 'outside', startsOn: '2026-08-11', endsOn: '2027-01-01' }))).status, 400);
185
+ assert.equal((await mutate(f.actor, 'years', intent('update', { startsOn: '2026-09-01' }, f.year.id))).status, 409);
186
+ const subject = await request(`/v1/school/terms/${f.term.id}/subjects`, { method: 'POST', actor: f.actor, body: { name: 'درس' } });
187
+ const lesson = await request(`/v1/school/subjects/${subject.body.id}/classes`, { method: 'POST', actor: f.actor, body: { weekday: 1, startsAt: '09:00', endsAt: '10:00', recurrenceUntil: '2027-02-10' } });
188
+ assert.equal(lesson.status, 201);
189
+ assert.equal((await mutate(f.actor, 'terms', intent('update', { endsOn: '2027-02-09' }, f.term.id))).status, 409);
190
+ await request(`/v1/school/classes/${lesson.body.id}`, { method: 'DELETE', actor: f.actor });
191
+ assert.equal((await mutate(f.actor, 'terms', intent('update', { endsOn: '2027-02-09' }, f.term.id))).status, 409);
192
+ assert.equal((await mutate(f.actor, 'contexts', intent('update', { kind: 'work' }, f.context.id))).status, 409);
193
+});
194
+
195
+test('term archive blocks both new and legacy child writes and hides active timetable', async () => {
196
+ const f = await lifecycle();
197
+ const subject = await request(`/v1/school/terms/${f.term.id}/subjects`, { method: 'POST', actor: f.actor, body: { name: 'درس تاریخی' } });
198
+ const lesson = await request(`/v1/school/subjects/${subject.body.id}/classes`, { method: 'POST', actor: f.actor, body: { weekday: 2, startsAt: '12:00', endsAt: '13:00' } });
199
+ assert.equal(lesson.status, 201);
200
+ assert.equal((await mutate(f.actor, 'terms', intent('archive', {}, f.term.id))).status, 200);
201
+ assert.equal((await request(`/v1/school/terms/${f.term.id}/subjects`, { method: 'POST', actor: f.actor, body: { name: 'Must not create' } })).status, 404);
202
+ assert.equal((await request(`/v1/school/subjects/${subject.body.id}`, { method: 'PATCH', actor: f.actor, body: { name: 'Must not edit' } })).status, 409);
203
+ assert.equal((await request(`/v1/school/subjects/${subject.body.id}/classes`, { method: 'POST', actor: f.actor, body: { weekday: 2, startsAt: '14:00', endsAt: '15:00' } })).status, 409);
204
+ assert.equal((await request(`/v1/school/classes/${lesson.body.id}`, { method: 'PATCH', actor: f.actor, body: { location: 'Must not edit' } })).status, 409);
205
+ assert.deepEqual((await request(`/v1/school/${f.actor.id}/timetable`, { actor: f.actor })).body.classes, []);
206
+ assert.equal((await request(`/v1/school/subjects/${subject.body.id}`, { method: 'DELETE', actor: f.actor })).status, 204);
207
+ assert.equal((await request(`/v1/school/classes/${lesson.body.id}`, { method: 'DELETE', actor: f.actor })).status, 204);
208
+});
209
+
210
+test('legacy inserts waiting behind ancestor archival recheck current state without a 500 or duplicate', async () => {
211
+ const f = await lifecycle();
212
+ const locking = await pool.connect();
213
+ try {
214
+ await locking.query('begin');
215
+ await locking.query('select 1 from app_user where id=$1 for update', [f.actor.id]);
216
+ await locking.query('update life_context set active=false where id=$1', [f.context.id]);
217
+ const pending = request('/v1/school/years', { method: 'POST', actor: f.actor, body: { lifeContextId: f.context.id, title: 'Racing legacy insert', startsOn: '2028-01-01', endsOn: '2028-12-31' } });
218
+ await new Promise((resolve) => setTimeout(resolve, 100));
219
+ await locking.query('commit');
220
+ const result = await pending;
221
+ assert.equal(result.status, 400);
222
+ assert.equal(result.body.error, 'invalid_academic_year');
223
+ assert.equal((await pool.query('select count(*)::int as n from academic_year where student_user_id=$1', [f.actor.id])).rows[0].n, 1);
224
+ } finally { await locking.query('rollback').catch(() => {}); locking.release(); }
225
+});
226
+
227
+test('lifecycle input rejects excess fields, invalid versions and malformed IDs', async () => {
228
+ const actor = await user();
229
+ const good = intent('create', { kind: 'student', title: 'school' });
230
+ for (const raw of [{ ...good, extra: 'ignored' }, { ...good, expectedVersion: 1 }, { ...good, entityId: 'not-uuid' }, { ...good, data: { ...good.data, active: false } }, { ...good, data: { ...good.data, title: 'x'.repeat(121) } }]) {
231
+ assert.equal((await mutate(actor, 'contexts', raw)).status, 400);
232
+ }
233
+ assert.equal((await mutate(actor, 'unknown', good)).status, 404);
234
+});
235
+
236
+
237
+test('revoked session after an owner lock wait cannot commit a lifecycle or legacy write', async () => {
238
+ for (const legacy of [false, true]) {
239
+ const actor = await user(), locking = await pool.connect();
240
+ const claims = jwt.decode(actor.token);
241
+ try {
242
+ await locking.query('begin');
243
+ await locking.query('select 1 from app_user where id=$1 for update', [actor.id]);
244
+ const body = legacy ? { kind: 'student', title: 'Revoked legacy create' } : intent('create', { kind: 'student', title: 'Revoked lifecycle create' });
245
+ const pending = legacy ? request('/v1/life-contexts', { method: 'POST', actor, body }) : mutate(actor, 'contexts', body);
246
+ await new Promise((resolve) => setTimeout(resolve, 100));
247
+ await locking.query('update auth_session set revoked_at=clock_timestamp() where id=$1', [claims.sid]);
248
+ await locking.query('commit');
249
+ assert.equal((await pending).status, 401);
250
+ assert.equal((await pool.query('select count(*)::int as n from life_context where user_id=$1', [actor.id])).rows[0].n, 0);
251
+ } finally { await locking.query('rollback').catch(() => {}); locking.release(); }
252
+ }
253
+});
254
+
255
+test('session expiry after a read lock wait returns 401 rather than private lifecycle data', async () => {
256
+ const f = await lifecycle(), locking = await pool.connect(), claims = jwt.decode(f.actor.token);
257
+ try {
258
+ await locking.query('begin');
259
+ await locking.query('select 1 from app_user where id=$1 for update', [f.actor.id]);
260
+ const pending = request('/v1/school/lifecycle', { actor: f.actor });
261
+ await new Promise((resolve) => setTimeout(resolve, 100));
262
+ await locking.query("update auth_session set expires_at=clock_timestamp()-interval '1 second' where id=$1", [claims.sid]);
263
+ await locking.query('commit');
264
+ const result = await pending;
265
+ assert.equal(result.status, 401); assert.equal(result.body.contexts, undefined);
266
+ } finally { await locking.query('rollback').catch(() => {}); locking.release(); }
267
+});
268
+
269
+test('private check-in create, edit and archive roll back JWT expiry after observed record waits', async () => {
270
+ const actor = await user();
271
+ const goal = await request('/v1/learning/goals', { method: 'POST', actor, body: { title: 'SYNTHETIC wait goal' } });
272
+ assert.equal(goal.status, 201);
273
+ const checkin = await request('/v1/learning/checkins', { method: 'POST', actor, body: { learningGoalId: goal.body.id, confidence: 2, difficulty: 3, note: 'SYNTHETIC private original' } });
274
+ assert.equal(checkin.status, 201);
275
+ const claims = jwt.decode(actor.token);
276
+ for (const method of ['POST', 'PATCH', 'DELETE']) {
277
+ const token = jwt.sign({ sub: actor.id, sid: claims.sid, aud: 'lifemate-api' }, process.env.JWT_SECRET, { issuer: 'lifemate', expiresIn: 2 });
278
+ const exp = jwt.decode(token).exp * 1000;
279
+ const locking = await pool.connect();
280
+ try {
281
+ await locking.query('begin');
282
+ await locking.query(method === 'POST' ? 'select 1 from learning_goal where id=$1 for update' : 'select 1 from learning_checkin where id=$1 for update', [method === 'POST' ? goal.body.id : checkin.body.id]);
283
+ const pending = request(method === 'POST' ? '/v1/learning/checkins' : `/v1/learning/checkins/${checkin.body.id}`, {
284
+ method, actor: { ...actor, token }, body: method === 'POST' ? { learningGoalId: goal.body.id, confidence: 1, difficulty: 1 } : method === 'PATCH' ? { note: 'SYNTHETIC must roll back' } : undefined,
285
+ });
286
+ await expireAfterObservedWait(locking, exp);
287
+ const result = await pending;
288
+ assert.equal(result.status, 401, method + ' cannot commit an expired bearer');
289
+ const stored = (await pool.query('select note,archived_at from learning_checkin where id=$1', [checkin.body.id])).rows[0];
290
+ assert.equal(stored.note, 'SYNTHETIC private original'); assert.equal(stored.archived_at, null);
291
+ assert.equal((await pool.query('select count(*)::int n from learning_checkin where owner_user_id=$1', [actor.id])).rows[0].n, 1);
292
+ } finally { await locking.query('rollback').catch(() => {}); locking.release(); }
293
+ }
294
+});
295
+
296
+test('private check-in edit and read reject database session expiry after an observed row wait', async () => {
297
+ const actor = await user(), claims = jwt.decode(actor.token);
298
+ const created = await request('/v1/learning/checkins', { method: 'POST', actor, body: { confidence: 2, difficulty: 3, note: 'SYNTHETIC private original' } });
299
+ assert.equal(created.status, 201);
300
+ for (const method of ['PATCH', 'GET']) {
301
+ const expiresAt = Date.now() + 1700;
302
+ await pool.query('update auth_session set expires_at=$2 where id=$1', [claims.sid, new Date(expiresAt)]);
303
+ const locking = await pool.connect();
304
+ try {
305
+ await locking.query('begin');
306
+ // UPDATE waits on the private row; GET must serialize with account state.
307
+ await locking.query(method === 'PATCH' ? 'select 1 from learning_checkin where id=$1 for update' : 'select 1 from app_user where id=$1 for update', [method === 'PATCH' ? created.body.id : actor.id]);
308
+ const pending = request(`/v1/learning/checkins/${created.body.id}`, { method, actor, body: method === 'PATCH' ? { note: 'SYNTHETIC must roll back' } : undefined });
309
+ await expireAfterObservedWait(locking, expiresAt);
310
+ const result = await pending;
311
+ assert.equal(result.status, 401); assert.equal(result.body.note, undefined);
312
+ assert.equal((await pool.query('select note from learning_checkin where id=$1', [created.body.id])).rows[0].note, 'SYNTHETIC private original');
313
+ } finally { await locking.query('rollback').catch(() => {}); locking.release(); }
314
+ }
315
+});
316
+
317
+test('school session validation samples fresh database time after the observed session-row lock wait', async () => {
318
+ const actor = await user(), claims = jwt.decode(actor.token), locking = await pool.connect();
319
+ const expiresAt = Date.now() + 1700;
320
+ await pool.query('update auth_session set expires_at=$2 where id=$1', [claims.sid, new Date(expiresAt)]);
321
+ try {
322
+ await locking.query('begin');
323
+ await locking.query('select 1 from auth_session where id=$1 for update', [claims.sid]);
324
+ const pending = request('/v1/school/lifecycle', { actor });
325
+ await expireAfterObservedWait(locking, expiresAt);
326
+ const result = await pending;
327
+ assert.equal(result.status, 401); assert.equal(result.body.contexts, undefined);
328
+ } finally { await locking.query('rollback').catch(() => {}); locking.release(); }
329
+});
330
+
331
+test('school session guard itself rejects elapsed expiry after its locking statement began', async () => {
332
+ const actor = await user(), claims = jwt.decode(actor.token), locking = await pool.connect(), validating = await pool.connect();
333
+ const expiresAt = Date.now() + 1700;
334
+ await pool.query('update auth_session set expires_at=$2 where id=$1', [claims.sid, new Date(expiresAt)]);
335
+ try {
336
+ await locking.query('begin'); await validating.query('begin');
337
+ await locking.query('select 1 from auth_session where id=$1 for update', [claims.sid]);
338
+ const pending = assertSchoolSession(validating, claims).then(() => ({ accepted: true }), (error) => ({ error }));
339
+ await expireAfterObservedWait(locking, expiresAt);
340
+ const result = await pending;
341
+ assert.equal(result.error?.code, 'session_invalid');
342
+ } finally {
343
+ await locking.query('rollback').catch(() => {}); locking.release();
344
+ await validating.query('rollback').catch(() => {}); validating.release();
345
+ }
346
+});
347
+
348
+test('legacy academic reads reject session expiry at observed account waits', async () => {
349
+ const f = await lifecycle(), claims = jwt.decode(f.actor.token), locking = await pool.connect();
350
+ const expiresAt = Date.now() + 1700;
351
+ await pool.query('update auth_session set expires_at=$2 where id=$1', [claims.sid, new Date(expiresAt)]);
352
+ try {
353
+ await locking.query('begin');
354
+ await locking.query('select 1 from app_user where id=$1 for update', [f.actor.id]);
355
+ const pending = Promise.all(['/v1/life-contexts', `/v1/school/${f.actor.id}/overview`, `/v1/school/${f.actor.id}/timetable`]
356
+ .map((path) => request(path, { actor: f.actor })));
357
+ await expireAfterObservedWait(locking, expiresAt);
358
+ for (const result of await pending) {
359
+ assert.equal(result.status, 401); assert.equal(result.body.contexts, undefined);
360
+ assert.equal(result.body.subjects, undefined); assert.equal(result.body.classes, undefined);
361
+ }
362
+ } finally { await locking.query('rollback').catch(() => {}); locking.release(); }
363
+});