LifeMate — Personal, Family & Learning Companion

feat/weekly-planner-android
chore/phase1-repository-cleanup deploy/stable-web-apk deployment-static design/mobile-accessibility-v2 design/mobile-navigation-review docs/child-education-access-decision docs/offline-data-rescue-options docs/owner-guide-and-delivery-plan docs/phase1-policy-options docs/public-review-live-2026-10-15 feat/aparat-learning-library feat/child-device-safety feat/child-identity-schema feat/flutter-mobile-navigation feat/learning-content-operations feat/local-signing-preflight feat/online-family-stage0 feat/personal-encrypted-recovery feat/private-planner-series-api feat/public-review-page feat/standalone-weekly-planner feat/weekly-planner-android final-feature-1/iran-family-school fix/auth-abuse-expiry-safety fix/auth-expiry-after-lock fix/backend-request-safety fix/lifeguide-bootstrap-naming-ci fix/lifeguide-pages-qa-base-preflight fix/lifeguide-qa-pages-env-deployment fix/local-task-persistence fix/managed-child-session-boundary fix/personal-jalali-dates fix/personal-notification-controls fix/personal-upgrade-delivery-guard fix/sms-approval-gates fix/study-duration-display infra/cloudflare-neon-migration infra/lifeguide-cloudflare-qa infra/lifeguide-github-pages-qa infra/lifeguide-supabase-qa main phase-1/foundation-completion phase-2/product-foundation-identity phase-3/planner-school-family-core phase-4/ai-learning-wellbeing phase-5/hardening-observability-release test/android-reminder-acceptance test/personal-notification-settings test/personal-recovery-acceptance test/role-entry-apk
js 155 lines 7.42 KB
Raw
1 import crypto from 'node:crypto';
2 import express from 'express';
3
4 const uuid = value => typeof value === 'string' &&
5 /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value);
6 const categories = new Set(['inaccurate', 'edition_mismatch', 'broken_video', 'unclear', 'topic_request']);
7 const submissionFields = new Set(['mutationId', 'unitId', 'category', 'summary', 'shareWithContentTeam']);
8
9 export function normalizeFeedbackSubmission(body) {
10 if (!body || typeof body !== 'object' || Array.isArray(body) ||
11 Object.keys(body).some(key => !submissionFields.has(key)) ||
12 !uuid(body.mutationId) || (body.unitId != null && !uuid(body.unitId)) ||
13 !categories.has(body.category) || body.shareWithContentTeam !== true ||
14 typeof body.summary !== 'string' || Array.from(body.summary).length > 1000 ||
15 !body.summary.trim() || body.summary.includes('\u0000')) return null;
16 return {
17 mutationId: body.mutationId.toLowerCase(),
18 unitId: body.unitId?.toLowerCase() ?? null,
19 category: body.category,
20 summary: body.summary.trim(),
21 shareWithContentTeam: true,
22 };
23 }
24
25 async function transaction(pool, operation) {
26 const client = await pool.connect();
27 try {
28 await client.query('begin');
29 const result = await operation(client);
30 await client.query('commit');
31 return result;
32 } catch (error) {
33 await client.query('rollback').catch(() => {});
34 throw error;
35 } finally { client.release(); }
36 }
37
38 function feedbackBody(row) {
39 return {
40 id: row.id,
41 mutationId: row.mutation_id,
42 unitId: row.unit_id,
43 category: row.category,
44 summary: row.summary,
45 shareWithContentTeam: row.share_with_content_team,
46 status: row.status,
47 version: row.version,
48 createdAt: row.created_at,
49 updatedAt: row.updated_at,
50 withdrawnAt: row.withdrawn_at,
51 };
52 }
53
54 function acknowledgement(row, status) {
55 return { feedback: feedbackBody(row),
56 acknowledgement: { mutationId: row.mutation_id, feedbackId: row.id, status } };
57 }
58
59 async function activeOwnerLock(client, owner) {
60 const result = await client.query(
61 'select id from app_user where id=$1 and disabled_at is null for update', [owner]);
62 return result.rowCount > 0;
63 }
64
65 export function createLearningFeedbackRouter({ pool, auth }) {
66 const router = express.Router();
67
68 router.post('/education/feedback', auth, async (req, res) => {
69 const body = normalizeFeedbackSubmission(req.body);
70 if (!body || Object.keys(req.query).length) return res.status(400).json({ error: 'invalid_feedback' });
71 const owner = req.identity.sub;
72 const digest = crypto.createHash('sha256').update(JSON.stringify(body)).digest('hex');
73 const result = await transaction(pool, async client => {
74 // One durable owner lock serializes duplicate claims and rolling quota.
75 // No IP-based identity, in-memory counter or family/admin override exists.
76 if (!await activeOwnerLock(client, owner)) return { status: 401, body: { error: 'session_invalid' } };
77 const previous = await client.query(
78 'select * from learning_content_feedback where owner_user_id=$1 and mutation_id=$2',
79 [owner, body.mutationId]);
80 if (previous.rowCount) {
81 const row = previous.rows[0];
82 if (row.request_hash !== digest) return { status: 409, body: { error: 'mutation_id_reused' } };
83 // Serialize current state, not the original response: a withdrawn
84 // summary/consent can never be restored or leaked by a valid retry.
85 return { status: 200, body: acknowledgement(row, 'already_applied') };
86 }
87 if (body.unitId != null) {
88 const unit = await client.query('select id from learning_unit where id=$1', [body.unitId]);
89 if (!unit.rowCount) return { status: 404, body: { error: 'learning_unit_not_found' } };
90 }
91 const quota = (await client.query(
92 `select count(*) filter(where created_at>now()-interval '1 hour')::int as hour_count,
93 count(*)::int as day_count,
94 ceil(extract(epoch from ((min(created_at) filter(where created_at>now()-interval '1 hour'))
95 +interval '1 hour'-now())))::int as hour_wait,
96 ceil(extract(epoch from (min(created_at)+interval '1 day'-now())))::int as day_wait
97 from learning_content_feedback where owner_user_id=$1 and created_at>now()-interval '1 day'`,
98 [owner])).rows[0];
99 const wait = Math.max(quota.hour_count >= 5 ? quota.hour_wait : 0,
100 quota.day_count >= 20 ? quota.day_wait : 0);
101 if (wait > 0) return { status: 429, retryAfter: Math.max(1, wait), body: { error: 'feedback_rate_limited' } };
102 const inserted = await client.query(
103 `insert into learning_content_feedback(owner_user_id,mutation_id,request_hash,unit_id,category,summary,share_with_content_team)
104 values($1,$2,$3,$4,$5,$6,true) returning *`,
105 [owner, body.mutationId, digest, body.unitId, body.category, body.summary]);
106 return { status: 201, body: acknowledgement(inserted.rows[0], 'accepted') };
107 });
108 if (result.retryAfter) res.setHeader('Retry-After', String(result.retryAfter));
109 res.status(result.status).json(result.body);
110 });
111
112 router.get('/me/education-feedback', auth, async (req, res) => {
113 const cursor = req.query.cursor ?? null;
114 if (Object.keys(req.query).some(key => key !== 'cursor') ||
115 (cursor !== null && !uuid(cursor))) return res.status(400).json({ error: 'invalid_feedback_query' });
116 const owner = req.identity.sub;
117 if (cursor !== null) {
118 const known = await pool.query(
119 'select id from learning_content_feedback where owner_user_id=$1 and id=$2', [owner, cursor]);
120 if (!known.rowCount) return res.status(404).json({ error: 'feedback_not_found' });
121 }
122 // Compare PostgreSQL timestamps in PostgreSQL, preserving microseconds.
123 // A parsed JavaScript Date cursor could skip rows from the same millisecond.
124 const rows = (await pool.query(
125 `select f.* from learning_content_feedback f where f.owner_user_id=$1
126 and ($2::uuid is null or (f.created_at,f.id)<
127 (select created_at,id from learning_content_feedback where owner_user_id=$1 and id=$2))
128 order by f.created_at desc,f.id desc limit 101`, [owner, cursor])).rows;
129 res.json({ feedback: rows.slice(0, 100).map(feedbackBody),
130 nextCursor: rows.length > 100 ? rows[99].id : null });
131 });
132
133 router.delete('/me/education-feedback/:id', auth, async (req, res) => {
134 if (!uuid(req.params.id) || Object.keys(req.query).length ||
135 (req.body != null && (typeof req.body !== 'object' || Array.isArray(req.body) || Object.keys(req.body).length))) {
136 return res.status(400).json({ error: 'invalid_feedback' });
137 }
138 const status = await transaction(pool, async client => {
139 if (!await activeOwnerLock(client, req.identity.sub)) return 401;
140 const found = await client.query(
141 'select withdrawn_at from learning_content_feedback where owner_user_id=$1 and id=$2 for update',
142 [req.identity.sub, req.params.id]);
143 if (!found.rowCount) return 404;
144 if (!found.rows[0].withdrawn_at) await client.query(
145 `update learning_content_feedback set summary=null,share_with_content_team=false,
146 withdrawn_at=now(),updated_at=now(),version=version+1 where owner_user_id=$1 and id=$2`,
147 [req.identity.sub, req.params.id]);
148 return 204;
149 });
150 if (status === 204) return res.status(204).end();
151 res.status(status).json({ error: status === 401 ? 'session_invalid' : 'feedback_not_found' });
152 });
153
154 return router;
155 }