@davoodmehraban89 / LifeMate / commits / e35ebed
Fork 0

LifeMate — Personal, Family & Learning Companion

feat(identity): add gated synthetic child and guardian device flow

Quinn White committed Oct 16, 2026 at 06:56 UTC e35ebed94fa326b59e13f5cea34e14064c4cf419
11 files changed +1051 -3
.env.example
+2
@@ -52,3 +52,5 @@ SMS_PROVIDER_TOKEN=
52 BACKUP_SCHEDULE=0 2 * * *
53 BACKUP_KEEP_DAYS=14
54 BACKUP_MAX_AGE_SECONDS=93600
55 +# Experimental child identity: synthetic local fixtures ONLY; production always denies.
56 +ENABLE_CHILD_IDENTITY_SANDBOX=false
CHANGELOG.md
+7
@@ -1,5 +1,12 @@
1 # LifeGuide Changelog
2
3 +## Unreleased — synthetic child identity sandbox
4 +
5 +- Add local-only managed child creation with required date of birth, explicit synthetic consent and creator/recipient guardian approval; no real-data or legal-consent approval.
6 +- Bind parent-issued devices to restricted database scope and issuer, revoke prior devices on recovery and preserve restrictions through refresh. Deny private legacy routes and managed-child age/role upgrades.
7 +- Add local migrations0024/0025 and real PostgreSQL authorization, concurrency, expiry and restricted-role regressions. Production remains disabled even with the sandbox flag.
8 +- Backend package remains0.7.1; this is not a release. [Evidence and limits](docs/audits/2026-10-16-child-identity-sandbox.md).
9 +
10 ## Unreleased — Phase 1 auth hardening
11
12 - Share auth/session IP quotas in PostgreSQL across processes and restart, storing domain-separated HMAC metadata rather than raw addresses; retain separate contact cooldowns.
PROJECT_STATE.md
+8
@@ -1,5 +1,13 @@
1 # LifeGuide / لایف‌گاید — وضعیت واقعی پروژه
2
3 +## فاز۱ — هویت کودکِ صرفاً ساختگی، بدون انتشار — ۲۰۲۶-۱۰-۱۶
4 +
5 +سه بخش وابسته بر PR24 آماده شد: [schema در PR27](https://github.com/davoodmehraban89/LifeMate/pull/27)، [مرز نشست در PR28](https://github.com/davoodmehraban89/LifeMate/pull/28) و جریان `feat/child-device-safety` روی آن‌ها. ساخت کودک با DOB اجباری و رضایتِ صریحاً غیرحقوقیِ sandbox، سرپرست دوم با دعوت سازنده/پذیرش گیرنده، بازیابی با ابطال نشست‌های قبلی، scope محدود در DB و refresh و API دیدپذیری پیاده شد. Production حتی با flag فعال503؛ داده واقعی مجاز نیست.
6 +
7 +**VERIFIED محلی:** npm ci؛23migration و تکرار/import تکراری؛ چهار SQL assertion موفق؛ Backend **297pass/0fail/0skip**، runtime30 و regression96 موفق؛ backup/restore مستقل و کنترل مجوز پس از restore؛ syntax82، audit0 و بررسی diff. [گزارش، شکست اولیه و حدود شواهد](docs/audits/2026-10-16-child-identity-sandbox.md).
8 +
9 +۲۱ migration قبلی و bundleهای تاریخی Supabase حفظ شدند؛ live QA تغییر نکرد. هیچ merge/deploy/DNS/SMS یا داده زنده‌ای تغییر نکرد. UI/QR، Android/Safari، آنلاین عمومی، رضایت حقوقی و مسیر آموزشی مجاز جدید هنوز **UNVERIFIED/تکمیل‌نشده** هستند. مسیرهای خصوصی قدیمی برای نشست جدید بسته‌اند؛ کامل‌شدن Backend این بسته، آماده‌بودن نرم‌افزار خانواده نیست. **فاز۱ کامل نیست و فاز۲ شروع نشده است.** Feature1، نام LifeGuide و شناسه‌های فنی موجود حفظ شدند.
10 +
11 ## فاز۱ — اصلاح هویت در PR وابسته؛ بدون انتشار
12
13 مالک پس از گزارش فاز۰ شروع فاز۱ را تأیید کرد. شاخه `fix/auth-abuse-expiry-safety` از PR14 در `5da6c4290e422162c13c3fe5260345770dde7ffa` منشعب است؛ به main یا سرویس زنده منتقل نشده است. محدودیت IP مشترک PostgreSQL، بررسی تازه انقضا پس از قفل و gate تأیید ارسال SMS پیاده شد. **VERIFIED محلی:** `npm test -- --test-concurrency=1` →271pass/0fail/0skip؛ migration و import تکراری، چهار SQL matrix و syntax موفق. [گزارش و محدودیت‌ها](docs/audits/2026-10-15-phase1-auth-hardening.md).
backend/scripts/test-db-roles.js
+4 -1
@@ -188,7 +188,10 @@ try {
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'});
191 + // These new identity tests must use the runtime role directly. The broader
192 + // catalog suite below uses a separate migrator only for fixture setup.
193 + const family=spawnSync(process.execPath,['--test','--test-concurrency=1','tests/online_acceptance.test.js',
194 + 'tests/child_identity.test.js','tests/managed_child_server.test.js'],{cwd:backend,env:familyEnv,stdio:'inherit'});
195 assert.equal(family.status,0,'Runtime-role family HTTP/DB acceptance failed');
196 const acceptance=spawnSync(process.execPath,['--test',
197 'tests/learning_library.test.js','tests/learning_feedback.test.js','tests/learning_assessment.test.js',
backend/src/child_identity.js new
+270
@@ -0,0 +1,270 @@
1 +import crypto from 'node:crypto';
2 +import express from 'express';
3 +import jwt from 'jsonwebtoken';
4 +
5 +export const SANDBOX_CONSENT_VERSION = 'sandbox-child-consent-v1-not-legal';
6 +export const SANDBOX_CONSENT_TEXT = 'SYNTHETIC TEST ONLY: I confirm these are invented test identities. This is not legal consent and authorizes no real child data, deployment or private-data access.';
7 +export const SANDBOX_CONSENT_DIGEST = crypto.createHash('sha256').update(SANDBOX_CONSENT_TEXT).digest('hex');
8 +const digest = value => crypto.createHash('sha256').update(value).digest('hex');
9 +const token = () => crypto.randomBytes(32).toString('base64url');
10 +const uuid = value => typeof value === 'string' && /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(value);
11 +const exact = (body, fields) => body && typeof body === 'object' && !Array.isArray(body) && Object.keys(body).every(key => fields.includes(key));
12 +const bodyToken = body => exact(body, ['token']) && typeof body.token === 'string' && /^[A-Za-z0-9_-]{43}$/.test(body.token);
13 +const failure = (status, error) => ({ status, body: { error } });
14 +const invalidInvitation = () => failure(400, 'invalid_or_expired_invitation');
15 +const send = (res, result) => res.status(result.status).json(result.body);
16 +const date = value => typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value) &&
17 + Number(value.slice(0, 4)) >= 1900 && Number.isFinite(Date.parse(value + 'T00:00:00.000Z')) &&
18 + new Date(value + 'T00:00:00.000Z').toISOString().slice(0, 10) === value;
19 +
20 +async function sessionCurrent(client, identity, lock = false) {
21 + if (lock) await client.query('select id from auth_session where id=$1 and user_id=$2 for share', [identity.sid, identity.sub]);
22 + return (await client.query(`select 1 from auth_session s join app_user u on u.id=s.user_id
23 + where s.id=$1 and s.user_id=$2 and s.revoked_at is null and s.expires_at>clock_timestamp()
24 + and u.disabled_at is null and to_timestamp($3)>clock_timestamp()`, [identity.sid, identity.sub, identity.exp])).rowCount > 0;
25 +}
26 +async function transact(pool, identity, operation) {
27 + const client = await pool.connect();
28 + try {
29 + await client.query('begin');
30 + await client.query("set local lock_timeout='4s'");
31 + await client.query("set local statement_timeout='6s'");
32 + const result = await operation(client);
33 + if (identity && !await sessionCurrent(client, identity, true)) {
34 + await client.query('rollback'); return failure(401, 'session_invalid');
35 + }
36 + if (result.status >= 400) await client.query('rollback');
37 + else await client.query('commit');
38 + return result;
39 + } catch (error) {
40 + await client.query('rollback').catch(() => {});
41 + // SQL/constraint details may contain profile information. Never return them.
42 + if (['55P03', '57014', '40P01'].includes(error.code)) return failure(503, 'child_identity_busy');
43 + throw error;
44 + } finally { client.release(); }
45 +}
46 +
47 +async function context(client, familyId, participants) {
48 + const family = await client.query('select id from family_workspace where id=$1 and archived_at is null for update', [familyId]);
49 + if (!family.rowCount) return false;
50 + const ids = [...new Set(participants)].sort();
51 + // Stable order shared with family lifecycle: family, users, profiles,
52 + // memberships, managed child, consent, invitation, final actor session.
53 + await client.query('select id from app_user where id=any($1::uuid[]) order by id for update', [ids]);
54 + await client.query('select user_id from profile where user_id=any($1::uuid[]) order by user_id for update', [ids]);
55 + 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, ids]);
56 + return true;
57 +}
58 +async function adultParent(client, familyId, userId, { admin = false } = {}) {
59 + return (await client.query(`select 1 from family_membership m join app_user u on u.id=m.user_id
60 + join profile p on p.user_id=m.user_id where m.family_id=$1 and m.user_id=$2
61 + and m.ended_at is null and m.role='parent_guardian' and (not $3::boolean or m.is_admin)
62 + and u.disabled_at is null and not u.is_managed_child and p.birth_date is not null
63 + and p.birth_date<=(current_date-interval '18 years')::date`, [familyId, userId, admin])).rowCount > 0;
64 +}
65 +async function activeChild(client, familyId, childId) {
66 + await client.query('select user_id from managed_child where family_id=$1 and user_id=$2 for update', [familyId, childId]);
67 + await client.query('select child_user_id from child_consent where child_user_id=$1 for update', [childId]);
68 + return (await client.query(`select mc.* from managed_child mc join app_user u on u.id=mc.user_id
69 + join profile p on p.user_id=mc.user_id join child_consent c on c.child_user_id=mc.user_id
70 + join family_membership m on m.family_id=mc.family_id and m.user_id=mc.user_id
71 + where mc.family_id=$1 and mc.user_id=$2 and u.is_managed_child and u.disabled_at is null
72 + and m.role='teen_minor' and not m.is_admin and m.ended_at is null and c.revoked_at is null
73 + and p.birth_date is not null and p.birth_date<=current_date
74 + and p.birth_date>(current_date-interval '18 years')::date
75 + and c.text_version=$3 and c.text_digest=$4`, [familyId, childId, SANDBOX_CONSENT_VERSION, SANDBOX_CONSENT_DIGEST])).rows[0];
76 +}
77 +async function guardian(client, familyId, guardianId, childId) {
78 + return await adultParent(client, familyId, guardianId) &&
79 + (await client.query('select is_active_guardian($1,$2,$3) active', [familyId, guardianId, childId])).rows[0].active;
80 +}
81 +async function audit(client, familyId, actorId, childId, action) {
82 + await client.query(`insert into access_audit(actor_user_id,family_id,action,target_type,target_id,metadata)
83 + values($1,$2,$3,'managed_child',$4,'{"synthetic":true}'::jsonb)`, [actorId, familyId, 'child.sandbox.' + action, childId]);
84 +}
85 +const validPath = req => uuid(req.params.familyId) && uuid(req.params.childId) && Object.keys(req.query).length === 0;
86 +
87 +export function createChildIdentityRouter({ pool, auth, jwtSecret, env = process.env }) {
88 + const router = express.Router();
89 + // This router is mounted ahead of legacy /v1 routes. A use('/') gate would
90 + // disable unrelated APIs; gate only these explicit identity paths.
91 + const gate = (_req, res, next) => {
92 + res.set('Cache-Control', 'no-store');
93 + if (!['test', 'development'].includes(env.NODE_ENV) || env.ENABLE_CHILD_IDENTITY_SANDBOX !== 'true')
94 + return send(res, failure(503, 'child_identity_sandbox_disabled'));
95 + next();
96 + };
97 + router.post('/families/:familyId/children', gate, auth, async (req, res) => {
98 + const body = req.body;
99 + if (!uuid(req.params.familyId) || Object.keys(req.query).length || !exact(body,
100 + ['displayName', 'birthDate', 'profileCategory', 'consentVersion', 'consentAccepted', 'synthetic']) ||
101 + typeof body.displayName !== 'string' || body.displayName.trim().length < 1 || body.displayName.trim().length > 100 ||
102 + body.displayName.includes('\u0000') ||
103 + !date(body.birthDate) || !['girl_minor', 'boy_minor'].includes(body.profileCategory) || body.consentVersion !== SANDBOX_CONSENT_VERSION ||
104 + body.consentAccepted !== true || body.synthetic !== true) return send(res, failure(400, 'invalid_child_profile'));
105 + send(res, await transact(pool, req.identity, async client => {
106 + const age = (await client.query("select $1::date<=current_date and $1::date>(current_date-interval '18 years')::date valid", [body.birthDate])).rows[0].valid;
107 + if (!age) return failure(400, 'invalid_child_profile');
108 + if (!await context(client, req.params.familyId, [req.identity.sub])) return failure(403, 'forbidden');
109 + if (!await adultParent(client, req.params.familyId, req.identity.sub, { admin: true })) return failure(403, 'forbidden');
110 + const childId = crypto.randomUUID();
111 + await client.query('insert into app_user(id,identity_subject,is_managed_child) values($1,$2,true)', [childId, 'managed-child:' + childId]);
112 + await client.query('insert into profile(user_id,display_name,birth_date,profile_category,theme_preference) values($1,$2,$3,$4,$5)',
113 + [childId, body.displayName.trim(), body.birthDate, body.profileCategory, body.profileCategory === 'girl_minor' ? 'girl_pink' : 'boy_blue']);
114 + await client.query("insert into family_membership(family_id,user_id,role) values($1,$2,'teen_minor')", [req.params.familyId, childId]);
115 + await client.query('insert into managed_child(user_id,family_id,creator_user_id) values($1,$2,$3)', [childId, req.params.familyId, req.identity.sub]);
116 + await client.query('insert into child_consent(child_user_id,actor_user_id,text_version,text_digest) values($1,$2,$3,$4)',
117 + [childId, req.identity.sub, SANDBOX_CONSENT_VERSION, SANDBOX_CONSENT_DIGEST]);
118 + await client.query('insert into guardian_relationship(family_id,guardian_user_id,minor_user_id) values($1,$2,$3)', [req.params.familyId, req.identity.sub, childId]);
119 + await audit(client, req.params.familyId, req.identity.sub, childId, 'create');
120 + return { status: 201, body: { child: { userId: childId, familyId: req.params.familyId, displayName: body.displayName.trim(), profileCategory: body.profileCategory },
121 + consent: { version: SANDBOX_CONSENT_VERSION, digest: SANDBOX_CONSENT_DIGEST, synthetic: true } } };
122 + }));
123 + });
124 +
125 + router.post('/families/:familyId/children/:childId/device-invitations', gate, auth, async (req, res) => {
126 + if (!validPath(req) || !exact(req.body, ['synthetic']) || req.body.synthetic !== true) return send(res, failure(400, 'invalid_device_invitation'));
127 + const { familyId, childId } = req.params;
128 + send(res, await transact(pool, req.identity, async client => {
129 + if (!await context(client, familyId, [req.identity.sub, childId])) return failure(403, 'forbidden');
130 + if (!await activeChild(client, familyId, childId) || !await guardian(client, familyId, req.identity.sub, childId)) return failure(403, 'forbidden');
131 + // Every parent-issued device is recovery-capable. Retire all prior devices
132 + // before creating a replacement, even when this is the first issuance.
133 + await client.query('update auth_session set revoked_at=clock_timestamp() where user_id=$1 and revoked_at is null', [childId]);
134 + await client.query('update child_device_invitation set revoked_at=clock_timestamp() where child_user_id=$1 and used_at is null and revoked_at is null', [childId]);
135 + const raw = token();
136 + const row = (await client.query(`insert into child_device_invitation(family_id,child_user_id,issuer_user_id,token_digest,expires_at)
137 + values($1,$2,$3,$4,clock_timestamp()+interval '10 minutes') returning expires_at`, [familyId, childId, req.identity.sub, digest(raw)])).rows[0];
138 + await audit(client, familyId, req.identity.sub, childId, 'device_issue');
139 + return { status: 201, body: { token: raw, expiresAt: row.expires_at, accessScope: 'child_education', synthetic: true } };
140 + }));
141 + });
142 +
143 + router.post('/child-devices/accept', gate, async (req, res) => {
144 + if (!bodyToken(req.body) || Object.keys(req.query).length) return send(res, invalidInvitation());
145 + const key = digest(req.body.token);
146 + send(res, await transact(pool, null, async client => {
147 + const preliminary = (await client.query('select family_id,child_user_id,issuer_user_id from child_device_invitation where token_digest=$1', [key])).rows[0];
148 + if (!preliminary || !await context(client, preliminary.family_id, [preliminary.child_user_id, preliminary.issuer_user_id])) return invalidInvitation();
149 + if (!await activeChild(client, preliminary.family_id, preliminary.child_user_id) ||
150 + !await guardian(client, preliminary.family_id, preliminary.issuer_user_id, preliminary.child_user_id)) return invalidInvitation();
151 + await client.query('select id from child_device_invitation where token_digest=$1 for update', [key]);
152 + // Fresh SQL AFTER every lock: a token expiring while blocked is unusable.
153 + const invitation = (await client.query(`select id from child_device_invitation where token_digest=$1
154 + and used_at is null and revoked_at is null and expires_at>clock_timestamp()`, [key])).rows[0];
155 + if (!invitation) return invalidInvitation();
156 + await client.query('update child_device_invitation set used_at=clock_timestamp() where id=$1', [invitation.id]);
157 + const refreshToken = token();
158 + const session = (await client.query(`insert into auth_session(user_id,refresh_digest,expires_at,access_scope,child_issuer_user_id)
159 + values($1,$2,clock_timestamp()+interval '30 days','child_education',$3) returning id`, [preliminary.child_user_id, digest(refreshToken), preliminary.issuer_user_id])).rows[0];
160 + await audit(client, preliminary.family_id, preliminary.child_user_id, preliminary.child_user_id, 'device_accept');
161 + return { status: 200, body: { accessToken: jwt.sign({ sub: preliminary.child_user_id, sid: session.id, scope: 'child_education', aud: 'lifemate-api' },
162 + jwtSecret, { issuer: 'lifemate', expiresIn: '15m' }), refreshToken, accessScope: 'child_education', synthetic: true } };
163 + }));
164 + });
165 +
166 + router.post('/families/:familyId/children/:childId/guardian-invitations', gate, auth, async (req, res) => {
167 + if (!validPath(req) || !exact(req.body, ['guardianUserId']) || !uuid(req.body.guardianUserId)) return send(res, failure(400, 'invalid_guardian_invitation'));
168 + const { familyId, childId } = req.params, recipient = req.body.guardianUserId;
169 + send(res, await transact(pool, req.identity, async client => {
170 + if (!await context(client, familyId, [req.identity.sub, childId, recipient])) return failure(403, 'forbidden');
171 + const child = await activeChild(client, familyId, childId);
172 + if (!child || child.creator_user_id !== req.identity.sub || !await guardian(client, familyId, req.identity.sub, childId) ||
173 + recipient === req.identity.sub || !await adultParent(client, familyId, recipient)) return failure(403, 'forbidden');
174 + const raw = token();
175 + await client.query('update guardian_invitation set revoked_at=clock_timestamp() where child_user_id=$1 and guardian_user_id=$2 and used_at is null and revoked_at is null', [childId, recipient]);
176 + const row = (await client.query(`insert into guardian_invitation(family_id,child_user_id,issuer_user_id,guardian_user_id,token_digest,expires_at)
177 + values($1,$2,$3,$4,$5,clock_timestamp()+interval '10 minutes') returning expires_at`, [familyId, childId, req.identity.sub, recipient, digest(raw)])).rows[0];
178 + await audit(client, familyId, req.identity.sub, childId, 'guardian_invite');
179 + return { status: 201, body: { token: raw, expiresAt: row.expires_at, synthetic: true } };
180 + }));
181 + });
182 +
183 + router.post('/guardian-invitations/accept', gate, auth, async (req, res) => {
184 + if (!bodyToken(req.body) || Object.keys(req.query).length) return send(res, invalidInvitation());
185 + const key = digest(req.body.token);
186 + send(res, await transact(pool, req.identity, async client => {
187 + const preliminary = (await client.query('select * from guardian_invitation where token_digest=$1', [key])).rows[0];
188 + if (!preliminary || preliminary.guardian_user_id !== req.identity.sub ||
189 + !await context(client, preliminary.family_id, [preliminary.child_user_id, preliminary.issuer_user_id, req.identity.sub])) return invalidInvitation();
190 + const child = await activeChild(client, preliminary.family_id, preliminary.child_user_id);
191 + if (!child || child.creator_user_id !== preliminary.issuer_user_id ||
192 + !await guardian(client, preliminary.family_id, preliminary.issuer_user_id, preliminary.child_user_id) ||
193 + !await adultParent(client, preliminary.family_id, req.identity.sub)) return invalidInvitation();
194 + await client.query('select id from guardian_invitation where token_digest=$1 for update', [key]);
195 + // Freeze logout before the last expiry gate. A session-row lock wait must
196 + // not allow an invitation that expired during that wait to be consumed.
197 + if (!await sessionCurrent(client, req.identity, true)) return failure(401, 'session_invalid');
198 + const current = (await client.query(`select id from guardian_invitation where token_digest=$1
199 + and used_at is null and revoked_at is null and expires_at>clock_timestamp()`, [key])).rows[0];
200 + if (!current) return invalidInvitation();
201 + await client.query('insert into guardian_relationship(family_id,guardian_user_id,minor_user_id) values($1,$2,$3) on conflict(family_id,guardian_user_id,minor_user_id) do update set active=true',
202 + [preliminary.family_id, req.identity.sub, preliminary.child_user_id]);
203 + await client.query('update guardian_invitation set used_at=clock_timestamp() where id=$1', [current.id]);
204 + await audit(client, preliminary.family_id, req.identity.sub, preliminary.child_user_id, 'guardian_accept');
205 + return { status: 200, body: { accepted: true, synthetic: true } };
206 + }));
207 + });
208 +
209 + router.delete('/families/:familyId/children/:childId/consent', gate, auth, async (req, res) => {
210 + if (!validPath(req) || (req.body !== undefined && !exact(req.body, []))) return send(res, failure(400, 'invalid_consent_revocation'));
211 + const { familyId, childId } = req.params;
212 + send(res, await transact(pool, req.identity, async client => {
213 + if (!await context(client, familyId, [req.identity.sub, childId])) return failure(403, 'forbidden');
214 + const child = await activeChild(client, familyId, childId);
215 + if (!child || child.creator_user_id !== req.identity.sub || !await adultParent(client, familyId, req.identity.sub)) return failure(403, 'forbidden');
216 + await client.query('update child_consent set revoked_at=clock_timestamp() where child_user_id=$1', [childId]);
217 + await client.query('update auth_session set revoked_at=clock_timestamp() where user_id=$1 and revoked_at is null', [childId]);
218 + await client.query('update child_device_invitation set revoked_at=clock_timestamp() where child_user_id=$1 and used_at is null and revoked_at is null', [childId]);
219 + await client.query('update guardian_invitation set revoked_at=clock_timestamp() where child_user_id=$1 and used_at is null and revoked_at is null', [childId]);
220 + await client.query('update guardian_relationship set active=false where family_id=$1 and minor_user_id=$2', [familyId, childId]);
221 + await audit(client, familyId, req.identity.sub, childId, 'consent_revoke');
222 + return { status: 200, body: { revoked: true, synthetic: true } };
223 + }));
224 + });
225 +
226 + router.delete('/families/:familyId/children/:childId/guardians/:guardianId', gate, auth, async (req, res) => {
227 + if (!validPath(req) || !uuid(req.params.guardianId) || (req.body !== undefined && !exact(req.body, [])))
228 + return send(res, failure(400, 'invalid_guardian_revocation'));
229 + const { familyId, childId, guardianId } = req.params;
230 + send(res, await transact(pool, req.identity, async client => {
231 + if (!await context(client, familyId, [req.identity.sub, childId, guardianId])) return failure(403, 'forbidden');
232 + const child = await activeChild(client, familyId, childId);
233 + if (!child || child.creator_user_id !== req.identity.sub || !await guardian(client, familyId, req.identity.sub, childId))
234 + return failure(403, 'forbidden');
235 + if (guardianId === child.creator_user_id) return failure(409, 'creator_requires_consent_revocation');
236 + const relationship = await client.query(`update guardian_relationship set active=false
237 + where family_id=$1 and guardian_user_id=$2 and minor_user_id=$3 returning guardian_user_id`, [familyId, guardianId, childId]);
238 + if (!relationship.rowCount) return failure(403, 'forbidden');
239 + // Accepted invitation evidence must also be retired, preventing legacy
240 + // relation reactivation from silently restoring a revoked grant.
241 + await client.query('update guardian_invitation set revoked_at=clock_timestamp() where child_user_id=$1 and guardian_user_id=$2 and revoked_at is null', [childId, guardianId]);
242 + await client.query('update auth_session set revoked_at=clock_timestamp() where user_id=$1 and child_issuer_user_id=$2 and revoked_at is null', [childId, guardianId]);
243 + await client.query('update child_device_invitation set revoked_at=clock_timestamp() where child_user_id=$1 and issuer_user_id=$2 and used_at is null and revoked_at is null', [childId, guardianId]);
244 + await audit(client, familyId, req.identity.sub, childId, 'guardian_revoke');
245 + return { status: 200, body: { revoked: true, synthetic: true } };
246 + }));
247 + });
248 +
249 + router.get('/child-visibility', gate, auth, async (req, res) => {
250 + if (Object.keys(req.query).length) return send(res, failure(400, 'invalid_visibility_query'));
251 + send(res, await transact(pool, req.identity, async client => {
252 + const preliminary = (await client.query('select family_id from managed_child where user_id=$1', [req.identity.sub])).rows[0];
253 + if (!preliminary) return failure(403, 'forbidden');
254 + const guardianIds = (await client.query('select guardian_user_id from guardian_relationship where family_id=$1 and minor_user_id=$2', [preliminary.family_id, req.identity.sub])).rows.map(row => row.guardian_user_id);
255 + if (!await context(client, preliminary.family_id, [req.identity.sub, ...guardianIds]) || !await activeChild(client, preliminary.family_id, req.identity.sub)) return failure(403, 'forbidden');
256 + const guardians = (await client.query(`select g.guardian_user_id "userId",p.display_name "displayName" from guardian_relationship g
257 + join family_membership m on m.family_id=g.family_id and m.user_id=g.guardian_user_id
258 + join profile p on p.user_id=g.guardian_user_id join app_user u on u.id=g.guardian_user_id
259 + where g.family_id=$1 and g.minor_user_id=$2 and is_active_guardian(g.family_id,g.guardian_user_id,g.minor_user_id)
260 + and m.ended_at is null and m.role='parent_guardian'
261 + and u.disabled_at is null and p.birth_date<=(current_date-interval '18 years')::date
262 + order by g.guardian_user_id`, [preliminary.family_id, req.identity.sub])).rows;
263 + await audit(client, preliminary.family_id, req.identity.sub, req.identity.sub, 'visibility_read');
264 + return { status: 200, body: { guardians, accessScope: 'child_education', privateScopeGrantedByThisFlow: false,
265 + guardianVisibility: ['explicitly_shared_academic_summary'], excluded: ['private_notes', 'private_chat', 'health', 'cycle'],
266 + synthetic: true, notice: 'این محیط فقط برای هویت ساختگی آزمایشی است؛ دستگاه صادرشده توسط سرپرست به فضای خصوصی دسترسی ندارد.' } };
267 + }));
268 + });
269 + return router;
270 +}
backend/src/server.js
+12
@@ -20,6 +20,7 @@ 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 +import { createChildIdentityRouter } from './child_identity.js';
24
25 const { Pool } = pg;
26 const app = express();
@@ -115,6 +116,7 @@ app.get('/health', async (_req, res) => {
116 app.use('/v1/auth', createAuthRouter({ pool, jwtSecret, auth, emailProvider }));
117
118 app.use('/v1/profile', createProfileRouter({ pool, auth }));
119 +app.use('/v1', createChildIdentityRouter({ pool, auth, jwtSecret }));
120
121 app.get('/v1/families', auth, async (req, res) => {
122 const r = await pool.query(
@@ -338,6 +340,10 @@ app.post('/v1/invitations/accept', auth, async (req, res) => {
340 return res.status(400).json({ error: 'invalid_or_expired_invitation' });
341 }
342 await client.query('select id from app_user where id=$1 for update', [req.identity.sub]);
343 + if ((await client.query('select 1 from managed_child where user_id=$1', [req.identity.sub])).rowCount) {
344 + await client.query('rollback');
345 + return res.status(403).json({ error: 'managed_child_membership_locked' });
346 + }
347 const invitation = await client.query(
348 `select i.id,i.family_id,i.intended_role,i.intended_theme,
349 i.invited_email_normalized,i.invited_phone_normalized,
@@ -450,6 +456,9 @@ app.post('/v1/families/:familyId/guardians', auth, async (req, res) => {
456 const minorUserId = String(req.body?.minorUserId ?? '');
457 if (!uuid(guardianUserId) || !uuid(minorUserId)) return res.status(400).json({ error: 'invalid_guardian_relationship' });
458 const result = await familyAdminTransaction(req.params.familyId, req.identity, async (client) => {
459 + if ((await client.query('select 1 from managed_child where user_id=$1', [minorUserId])).rowCount) {
460 + return { status: 403, body: { error: 'managed_guardian_invitation_required' } };
461 + }
462 const roles = await client.query(`select m.user_id,m.role from family_membership m
463 join app_user u on u.id=m.user_id where m.family_id=$1 and m.user_id in ($2,$3)
464 and m.ended_at is null and u.disabled_at is null for update of m`, [req.params.familyId, guardianUserId, minorUserId]);
@@ -468,6 +477,9 @@ app.delete('/v1/families/:familyId/guardians', auth, async (req, res) => {
477 const minorUserId = String(req.body?.minorUserId ?? '');
478 if (!uuid(guardianUserId) || !uuid(minorUserId)) return res.status(400).json({ error: 'invalid_guardian_relationship' });
479 const result = await familyAdminTransaction(req.params.familyId, req.identity, async (client) => {
480 + if ((await client.query('select 1 from managed_child where user_id=$1', [minorUserId])).rowCount) {
481 + return { status: 403, body: { error: 'managed_guardian_flow_required' } };
482 + }
483 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]);
484 await familyAudit(client, req.params.familyId, req.identity.sub, 'guardian.deactivate', 'guardian_relationship', guardianUserId);
485 return { status: 204 };
backend/tests/child_identity.test.js new
+266
@@ -0,0 +1,266 @@
1 +// Synthetic accounts on loopback PostgreSQL only; never invokes SMS, email or AI.
2 +import test, { after } from 'node:test';
3 +import assert from 'node:assert/strict';
4 +import crypto from 'node:crypto';
5 +import express from 'express';
6 +import jwt from 'jsonwebtoken';
7 +import pg from 'pg';
8 +import { createSessionAuth } from '../src/session_auth.js';
9 +import { createChildIdentityRouter } from '../src/child_identity.js';
10 +
11 +const location = new URL(process.env.TEST_FIXTURE_DATABASE_URL ?? process.env.DATABASE_URL);
12 +assert.ok(['127.0.0.1', 'localhost', '[::1]'].includes(location.hostname));
13 +assert.match(location.pathname, /^\/(?:lifeguide_roles_source_[a-f0-9]{16}|lifemate_ci|lifeguide_\w*test\w*)$/);
14 +const marker = 'child-sandbox-' + crypto.randomUUID();
15 +const pool = new pg.Pool({ connectionString: location.href, application_name: marker });
16 +const secret = 'synthetic-child-sandbox-signing-fixture-not-a-live-key';
17 +const users = [], families = [], servers = [];
18 +const consentVersion = 'sandbox-child-consent-v1-not-legal';
19 +async function start(env = { NODE_ENV: 'test', ENABLE_CHILD_IDENTITY_SANDBOX: 'true' }) {
20 + const app = express(); app.use(express.json());
21 + app.use('/v1', createChildIdentityRouter({ pool, jwtSecret: secret,
22 + auth: createSessionAuth({ pool, jwtSecret: secret, env }), env }));
23 + app.use((_req, res) => res.status(404).json({ error: 'not_found' }));
24 + app.use((_error, _req, res, _next) => res.status(500).json({ error: 'test_unexpected_server_error' }));
25 + const server = app.listen(0, '127.0.0.1'); servers.push(server);
26 + await new Promise(resolve => server.once('listening', resolve));
27 + return 'http://127.0.0.1:' + server.address().port + '/v1';
28 +}
29 +const base = await start();
30 +after(async () => {
31 + await Promise.all(servers.map(server => new Promise(resolve => server.close(resolve))));
32 + try {
33 + await pool.query('delete from access_audit where family_id=any($1::uuid[]) or actor_user_id=any($2::uuid[])', [families, users]);
34 + await pool.query('delete from family_workspace where id=any($1::uuid[])', [families]);
35 + await pool.query('delete from auth_session where user_id=any($1::uuid[])', [users]);
36 + await pool.query('delete from app_user where id=any($1::uuid[])', [users]);
37 + } finally { await pool.end(); }
38 +});
39 +async function actor({ birthDate = '1985-01-01' } = {}) {
40 + const id = crypto.randomUUID(), sid = crypto.randomUUID(); users.push(id);
41 + await pool.query('insert into app_user(id,identity_subject,email_normalized) values($1,$2,$3)',
42 + [id, marker + ':' + id, 'sandbox-' + id + '@example.test']);
43 + await pool.query("insert into profile(user_id,display_name,birth_date) values($1,'Synthetic Adult',$2)", [id, birthDate]);
44 + await pool.query("insert into auth_session(id,user_id,refresh_digest,expires_at) values($1,$2,$3,clock_timestamp()+interval '1 day')", [sid, id, crypto.randomUUID()]);
45 + return { id, sid, token: jwt.sign({ sub: id, sid, aud: 'lifemate-api' }, secret, { issuer: 'lifemate', expiresIn: '15m' }) };
46 +}
47 +async function family(owner, members = []) {
48 + const id = crypto.randomUUID(); families.push(id);
49 + await pool.query("insert into family_workspace(id,name,created_by) values($1,'Synthetic child sandbox',$2)", [id, owner.id]);
50 + await pool.query("insert into family_membership(family_id,user_id,role,is_admin) values($1,$2,'parent_guardian',true)", [id, owner.id]);
51 + for (const member of members) await pool.query('insert into family_membership(family_id,user_id,role,is_admin) values($1,$2,$3,$4)',
52 + [id, member.user.id, member.role ?? 'parent_guardian', member.admin ?? false]);
53 + return id;
54 +}
55 +async function request(who, method, path, body, origin = base) {
56 + const response = await fetch(origin + path, { method, headers: { 'content-type': 'application/json',
57 + ...(who ? { authorization: 'Bearer ' + who.token } : {}) }, body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(10000) });
58 + return { status: response.status, body: await response.json(), cache: response.headers.get('cache-control') };
59 +}
60 +const createBody = () => ({ displayName: 'Synthetic Child', birthDate: '2015-03-12', profileCategory: 'girl_minor',
61 + consentVersion, consentAccepted: true, synthetic: true });
62 +async function child(owner, familyId) {
63 + const result = await request(owner, 'POST', `/families/${familyId}/children`, createBody());
64 + assert.equal(result.status, 201); users.push(result.body.child.userId); return result.body.child;
65 +}
66 +const issueDevice = (owner, familyId, childId) => request(owner, 'POST', `/families/${familyId}/children/${childId}/device-invitations`, { synthetic: true });
67 +const acceptDevice = token => request(null, 'POST', '/child-devices/accept', { token });
68 +const issueGuardian = (owner, familyId, childId, recipient) => request(owner, 'POST', `/families/${familyId}/children/${childId}/guardian-invitations`, { guardianUserId: recipient.id });
69 +const acceptGuardian = (recipient, token) => request(recipient, 'POST', '/guardian-invitations/accept', { token });
70 +async function observedWait() {
71 + for (let i = 0; i < 300; i++) {
72 + if ((await pool.query("select 1 from pg_stat_activity where application_name=$1 and wait_event_type='Lock'", [marker])).rowCount) return;
73 + await new Promise(resolve => setTimeout(resolve, 10));
74 + }
75 + assert.fail('Expected real PostgreSQL lock wait');
76 +}
77 +async function blockFamily(familyId, operation, mutation) {
78 + const blocker = await pool.connect();
79 + try {
80 + await blocker.query('begin'); await blocker.query('select id from family_workspace where id=$1 for update', [familyId]);
81 + const pending = operation(); await observedWait(); await mutation(blocker); await blocker.query('commit'); return await pending;
82 + } finally { await blocker.query('rollback'); blocker.release(); }
83 +}
84 +
85 +test('sandbox is disabled unless explicitly enabled in test/development; production cannot opt in', async () => {
86 + for (const env of [{ NODE_ENV: 'production', ENABLE_CHILD_IDENTITY_SANDBOX: 'true' }, { NODE_ENV: 'test' },
87 + { NODE_ENV: 'staging', ENABLE_CHILD_IDENTITY_SANDBOX: 'true' }]) {
88 + const origin = await start(env);
89 + const result = await request(null, 'POST', '/child-devices/accept', { token: 'synthetic' }, origin);
90 + assert.equal(result.status, 503); assert.equal(result.body.error, 'child_identity_sandbox_disabled');
91 + }
92 +});
93 +
94 +test('adult parent admin creates contactless child, initial guardian and versioned synthetic consent atomically', async () => {
95 + const owner = await actor(), id = await family(owner), created = await child(owner, id);
96 + const row = (await pool.query(`select u.email_normalized,u.phone_normalized,u.is_managed_child,p.birth_date::text,p.profile_category,
97 + m.role,m.is_admin,g.active,c.text_version,c.text_digest,mc.creator_user_id,
98 + exists(select 1 from auth_credential where user_id=u.id) has_credential
99 + from app_user u join profile p on p.user_id=u.id join family_membership m on m.user_id=u.id
100 + join managed_child mc on mc.user_id=u.id join child_consent c on c.child_user_id=u.id
101 + join guardian_relationship g on g.minor_user_id=u.id where u.id=$1`, [created.userId])).rows[0];
102 + assert.equal(row.email_normalized, null); assert.equal(row.phone_normalized, null); assert.equal(row.is_managed_child, true);
103 + assert.equal(row.birth_date, '2015-03-12'); assert.equal(row.profile_category, 'girl_minor'); assert.equal(row.role, 'teen_minor');
104 + assert.equal(row.is_admin, false); assert.equal(row.active, true); assert.equal(row.has_credential, false);
105 + assert.equal(row.creator_user_id, owner.id); assert.equal(row.text_version, consentVersion); assert.match(row.text_digest, /^[a-f0-9]{64}$/);
106 + assert.equal((await pool.query('select count(*)::int n from auth_session where user_id=$1', [created.userId])).rows[0].n, 0);
107 +});
108 +
109 +test('creation rejects malformed DOB/category/consent and unauthorized or age-unknown parent without rows', async () => {
110 + const owner = await actor(), unknown = await actor({ birthDate: null }), minor = await actor({ birthDate: '2015-01-01' }), outsider = await actor();
111 + const id = await family(owner, [{ user: unknown, admin: true }, { user: minor, admin: true }]);
112 + for (const patch of [{ birthDate: '2015-02-30' }, { birthDate: '2999-01-01' }, { birthDate: '1980-01-01' },
113 + { birthDate: null }, { profileCategory: 'adult' }, { consentAccepted: false }, { consentVersion: 'unapproved' }, { synthetic: false },
114 + { phone: '+000' }, { birthDate: ['2015-03-12'] }, { displayName: '\u0000' }]) {
115 + assert.equal((await request(owner, 'POST', `/families/${id}/children`, { ...createBody(), ...patch })).status, 400);
116 + }
117 + for (const candidate of [unknown, minor, outsider]) assert.equal((await request(candidate, 'POST', `/families/${id}/children`, createBody())).status, 403);
118 + assert.equal((await pool.query('select count(*)::int n from managed_child where family_id=$1', [id])).rows[0].n, 0);
119 +});
120 +
121 +test('device redemption stores only digest, is single-use under concurrency and mints education scope', async () => {
122 + const owner = await actor(), id = await family(owner), created = await child(owner, id), invitation = await issueDevice(owner, id, created.userId);
123 + assert.equal(invitation.status, 201); assert.equal(invitation.cache, 'no-store');
124 + assert.match(invitation.body.token, /^[A-Za-z0-9_-]{43}$/);
125 + const stored = (await pool.query('select token_digest from child_device_invitation where child_user_id=$1', [created.userId])).rows[0];
126 + assert.equal(stored.token_digest, crypto.createHash('sha256').update(invitation.body.token).digest('hex'));
127 + const responses = await Promise.all([acceptDevice(invitation.body.token), acceptDevice(invitation.body.token)]);
128 + assert.deepEqual(responses.map(r => r.status).sort(), [200, 400]);
129 + const accepted = responses.find(r => r.status === 200); assert.equal(accepted.cache, 'no-store');
130 + const claims = jwt.verify(accepted.body.accessToken, secret, { issuer: 'lifemate', audience: 'lifemate-api' });
131 + assert.equal(claims.sub, created.userId); assert.equal(claims.scope, 'child_education');
132 + const session = (await pool.query('select access_scope from auth_session where id=$1', [claims.sid])).rows[0];
133 + assert.equal(session.access_scope, 'child_education');
134 + const visibility = await request({ token: accepted.body.accessToken }, 'GET', '/child-visibility');
135 + assert.equal(visibility.status, 200); assert.equal(visibility.body.guardians[0].userId, owner.id);
136 + assert.equal(visibility.body.privateScopeGrantedByThisFlow, false);
137 + assert.equal((await request(owner, 'GET', '/child-visibility')).status, 403);
138 +});
139 +
140 +test('recovery issuance revokes all child sessions and old invitations before new code is returned', async () => {
141 + const owner = await actor(), id = await family(owner), created = await child(owner, id), first = await issueDevice(owner, id, created.userId);
142 + const accepted = await acceptDevice(first.body.token); assert.equal(accepted.status, 200);
143 + const pending = await issueDevice(owner, id, created.userId); assert.equal(pending.status, 201);
144 + assert.equal((await request({ token: accepted.body.accessToken }, 'GET', '/child-visibility')).status, 401);
145 + const last = await issueDevice(owner, id, created.userId); assert.equal((await acceptDevice(pending.body.token)).status, 400);
146 + const restored = await acceptDevice(last.body.token); assert.equal(restored.status, 200);
147 + assert.equal(jwt.decode(restored.body.accessToken).scope, 'child_education');
148 + assert.equal((await pool.query('select count(*)::int n from auth_session where user_id=$1 and revoked_at is null', [created.userId])).rows[0].n, 1);
149 +});
150 +
151 +test('creator confirmation plus recipient acceptance is required for second guardian; other admin cannot assign', async () => {
152 + const owner = await actor(), recipient = await actor(), admin = await actor(), outsider = await actor();
153 + const id = await family(owner, [{ user: recipient }, { user: admin, admin: true }]), created = await child(owner, id);
154 + assert.equal((await issueGuardian(admin, id, created.userId, recipient)).status, 403);
155 + assert.equal((await issueGuardian(owner, id, created.userId, outsider)).status, 403);
156 + const invitation = await issueGuardian(owner, id, created.userId, recipient); assert.equal(invitation.status, 201);
157 + assert.equal((await pool.query('select count(*)::int n from guardian_relationship where family_id=$1 and minor_user_id=$2', [id, created.userId])).rows[0].n, 1);
158 + assert.equal((await acceptGuardian(admin, invitation.body.token)).status, 400);
159 + assert.equal((await acceptGuardian(recipient, invitation.body.token)).status, 200);
160 + assert.equal((await acceptGuardian(recipient, invitation.body.token)).status, 400);
161 + assert.equal((await pool.query('select count(*)::int n from guardian_relationship where family_id=$1 and minor_user_id=$2 and active', [id, created.userId])).rows[0].n, 2);
162 + assert.equal((await issueDevice(recipient, id, created.userId)).status, 201);
163 +});
164 +
165 +test('consent revocation is creator-only and revokes sessions, relationships and every outstanding invitation', async () => {
166 + const owner = await actor(), recipient = await actor(), id = await family(owner, [{ user: recipient }]), created = await child(owner, id);
167 + const code = await issueDevice(owner, id, created.userId), accepted = await acceptDevice(code.body.token);
168 + const device = await issueDevice(owner, id, created.userId), guardian = await issueGuardian(owner, id, created.userId, recipient);
169 + assert.equal((await request(recipient, 'DELETE', `/families/${id}/children/${created.userId}/consent`)).status, 403);
170 + assert.equal((await request(owner, 'DELETE', `/families/${id}/children/${created.userId}/consent`)).status, 200);
171 + assert.equal((await acceptDevice(device.body.token)).status, 400); assert.equal((await acceptGuardian(recipient, guardian.body.token)).status, 400);
172 + assert.equal((await request({ token: accepted.body.accessToken }, 'GET', '/child-visibility')).status, 401);
173 + assert.equal((await issueDevice(owner, id, created.userId)).status, 403);
174 + assert.equal((await pool.query('select count(*)::int n from guardian_relationship where family_id=$1 and minor_user_id=$2 and active', [id, created.userId])).rows[0].n, 0);
175 +});
176 +
177 +test('device expiry and guardian revocation after actual lock waits prevent redemption without consuming tokens', async () => {
178 + const owner = await actor(), recipient = await actor(), id = await family(owner, [{ user: recipient }]), created = await child(owner, id);
179 + const device = await issueDevice(owner, id, created.userId);
180 + const expired = await blockFamily(id, () => acceptDevice(device.body.token), blocker => blocker.query('update child_device_invitation set expires_at=clock_timestamp() where child_user_id=$1', [created.userId]));
181 + assert.equal(expired.status, 400);
182 + assert.equal((await pool.query('select used_at from child_device_invitation where token_digest=$1', [crypto.createHash('sha256').update(device.body.token).digest('hex')])).rows[0].used_at, null);
183 + const guardian = await issueGuardian(owner, id, created.userId, recipient);
184 + const revoked = await blockFamily(id, () => acceptGuardian(recipient, guardian.body.token), blocker => blocker.query('update guardian_relationship set active=false where family_id=$1 and guardian_user_id=$2', [id, owner.id]));
185 + assert.equal(revoked.status, 400);
186 +});
187 +
188 +test('parent session expiry or authority change during family wait rolls back child creation', async () => {
189 + for (const invalidation of ['session', 'membership', 'birth_date']) {
190 + const owner = await actor(), id = await family(owner);
191 + const result = await blockFamily(id, () => request(owner, 'POST', `/families/${id}/children`, createBody()), blocker =>
192 + invalidation === 'session' ? blocker.query('update auth_session set expires_at=clock_timestamp() where id=$1', [owner.sid]) :
193 + invalidation === 'membership' ? blocker.query('update family_membership set is_admin=false where family_id=$1 and user_id=$2', [id, owner.id]) :
194 + blocker.query("update profile set birth_date='2015-01-01' where user_id=$1", [owner.id]));
195 + assert.equal(result.status, invalidation === 'session' ? 401 : 403);
196 + assert.equal((await pool.query('select count(*)::int n from managed_child where family_id=$1', [id])).rows[0].n, 0);
197 + }
198 +});
199 +
200 +test('strict route identifiers and token bodies return 400 without PostgreSQL cast errors', async () => {
201 + const owner = await actor(), id = await family(owner), created = await child(owner, id);
202 + assert.equal((await request(owner, 'POST', '/families/not-a-uuid/children', createBody())).status, 400);
203 + assert.equal((await request(owner, 'POST', `/families/${id}/children/not-a-uuid/device-invitations`, { synthetic: true })).status, 400);
204 + assert.equal((await request(owner, 'POST', `/families/${id}/children/${created.userId}/guardian-invitations`, { guardianUserId: ['invalid'] })).status, 400);
205 + for (const body of [{ token: null }, { token: [] }, { token: 'unknown' }, { token: 'a'.repeat(43), extra: true }]) {
206 + assert.equal((await request(null, 'POST', '/child-devices/accept', body)).status, 400);
207 + }
208 + assert.equal((await acceptDevice('a'.repeat(43))).body.error, 'invalid_or_expired_invitation');
209 +});
210 +
211 +test('cross-family child and inactive guardian cannot issue or redeem an existing device invitation', async () => {
212 + const owner = await actor(), outsider = await actor(), first = await family(owner), second = await family(outsider), created = await child(owner, first);
213 + assert.equal((await issueDevice(outsider, second, created.userId)).status, 403);
214 + assert.equal((await issueDevice(outsider, first, created.userId)).status, 403);
215 + const invitation = await issueDevice(owner, first, created.userId);
216 + await pool.query('update family_membership set ended_at=clock_timestamp() where family_id=$1 and user_id=$2', [first, owner.id]);
217 + assert.equal((await acceptDevice(invitation.body.token)).status, 400);
218 + assert.equal((await pool.query('select count(*)::int n from auth_session where user_id=$1', [created.userId])).rows[0].n, 0);
219 +});
220 +
221 +test('final parent session-row wait rechecks expiry and rolls back earlier creation writes and audit', async () => {
222 + const owner = await actor(), id = await family(owner), blocker = await pool.connect();
223 + try {
224 + await blocker.query('begin'); await blocker.query('select id from auth_session where id=$1 for update', [owner.sid]);
225 + const pending = request(owner, 'POST', `/families/${id}/children`, createBody()); await observedWait();
226 + await blocker.query('update auth_session set expires_at=clock_timestamp() where id=$1', [owner.sid]);
227 + await blocker.query('commit'); assert.equal((await pending).status, 401);
228 + assert.equal((await pool.query('select count(*)::int n from managed_child where family_id=$1', [id])).rows[0].n, 0);
229 + assert.equal((await pool.query('select count(*)::int n from access_audit where family_id=$1', [id])).rows[0].n, 0);
230 + } finally { await blocker.query('rollback'); blocker.release(); }
231 +});
232 +
233 +test('guardian token expiration during final recipient session-row wait is rechecked before consumption', async () => {
234 + const owner = await actor(), recipient = await actor(), id = await family(owner, [{ user: recipient }]), created = await child(owner, id);
235 + const invitation = await issueGuardian(owner, id, created.userId, recipient), blocker = await pool.connect();
236 + const tokenDigest = crypto.createHash('sha256').update(invitation.body.token).digest('hex');
237 + const deadline = (await pool.query("update guardian_invitation set expires_at=clock_timestamp()+interval '2 seconds' where token_digest=$1 returning expires_at", [tokenDigest])).rows[0].expires_at;
238 + try {
239 + await blocker.query('begin'); await blocker.query('select id from auth_session where id=$1 for update', [recipient.sid]);
240 + const pending = acceptGuardian(recipient, invitation.body.token); await observedWait();
241 + // Invitation row is held by the request. Observe the real DB wall clock
242 + // passing its deadline without trying to mutate the locked invitation.
243 + while (!(await blocker.query('select clock_timestamp()>=$1::timestamptz expired', [deadline])).rows[0].expired)
244 + await new Promise(resolve => setTimeout(resolve, 10));
245 + await blocker.query('commit'); assert.equal((await pending).status, 400);
246 + assert.equal((await pool.query('select used_at from guardian_invitation where token_digest=$1', [tokenDigest])).rows[0].used_at, null);
247 + } finally { await blocker.query('rollback'); blocker.release(); }
248 +});
249 +
250 +test('creator can revoke accepted second guardian and its issued devices; another admin cannot', async () => {
251 + const owner = await actor(), recipient = await actor(), admin = await actor(), id = await family(owner, [{ user: recipient }, { user: admin, admin: true }]);
252 + const created = await child(owner, id), invitation = await issueGuardian(owner, id, created.userId, recipient);
253 + assert.equal((await acceptGuardian(recipient, invitation.body.token)).status, 200);
254 + const device = await issueDevice(recipient, id, created.userId), accepted = await acceptDevice(device.body.token);
255 + assert.equal(accepted.status, 200);
256 + const pending = await issueDevice(recipient, id, created.userId);
257 + const revoke = who => request(who, 'DELETE', `/families/${id}/children/${created.userId}/guardians/${recipient.id}`);
258 + assert.equal((await revoke(admin)).status, 403);
259 + assert.equal((await request(owner, 'DELETE', `/families/${id}/children/${created.userId}/guardians/${owner.id}`)).status, 409);
260 + assert.equal((await revoke(owner)).status, 200);
261 + assert.equal((await pool.query('select active from guardian_relationship where family_id=$1 and guardian_user_id=$2 and minor_user_id=$3', [id, recipient.id, created.userId])).rows[0].active, false);
262 + assert.ok((await pool.query('select revoked_at from guardian_invitation where token_digest=$1', [crypto.createHash('sha256').update(invitation.body.token).digest('hex')])).rows[0].revoked_at);
263 + assert.equal((await acceptDevice(pending.body.token)).status, 400);
264 + assert.equal((await request({ token: accepted.body.accessToken }, 'GET', '/child-visibility')).status, 401);
265 + assert.equal((await issueDevice(recipient, id, created.userId)).status, 403);
266 +});
backend/tests/managed_child_server.test.js new
+183
@@ -0,0 +1,183 @@
1 +// Real app/HTTP/PostgreSQL integration; only invented identities on loopback.
2 +import test, { after } from 'node:test';
3 +import assert from 'node:assert/strict';
4 +import crypto from 'node:crypto';
5 +import jwt from 'jsonwebtoken';
6 +import pg from 'pg';
7 +import { rateLimitProfile } from '../src/operations.js';
8 +
9 +const location = new URL(process.env.TEST_FIXTURE_DATABASE_URL ?? process.env.DATABASE_URL);
10 +assert.ok(['127.0.0.1', 'localhost', '[::1]'].includes(location.hostname), 'Loopback database only');
11 +assert.match(location.pathname, /^\/(?:lifeguide_roles_source_[a-f0-9]{16}|lifemate_ci|lifeguide_\w*test\w*)$/);
12 +const marker = 'managed-child-http-' + crypto.randomUUID();
13 +const secret = 'synthetic-managed-child-http-fixture-not-a-live-signing-key';
14 +process.env.DATABASE_URL = location.href;
15 +process.env.JWT_SECRET = secret;
16 +process.env.PGAPPNAME = marker;
17 +process.env.NODE_ENV = 'test';
18 +process.env.ENABLE_CHILD_IDENTITY_SANDBOX = 'true';
19 +process.env.ENABLE_SENSITIVE_FEATURES = 'false';
20 +process.env.SMS_PROVIDER = 'disabled';
21 +for (const name of ['SMS_PROVIDER_URL', 'SMS_PROVIDER_TOKEN', 'KAVENEGAR_API_KEY', 'EMAIL_FROM', 'RESEND_API_KEY',
22 + 'SMTP_HOST', 'SMTP_USER', 'SMTP_PASSWORD', 'AI_API_KEY', 'AI_BASE_URL', 'AI_MODEL', 'OPENAI_API_KEY']) process.env[name] = '';
23 +const { app, pool } = await import('../src/server.js');
24 +const observer = new pg.Pool({ connectionString: location.href, application_name: marker + '-observer' });
25 +const server = app.listen(0, '127.0.0.1');
26 +await new Promise(resolve => server.once('listening', resolve));
27 +const base = 'http://127.0.0.1:' + server.address().port + '/v1';
28 +const users = [], families = [];
29 +const hash = raw => crypto.createHash('sha256').update(raw).digest('hex');
30 +const claims = (id, sid, extra = {}) => jwt.sign({ ...extra, sub: id, sid, aud: 'lifemate-api' }, secret, { issuer: 'lifemate', expiresIn: '15m' });
31 +after(async () => {
32 + await new Promise(resolve => server.close(resolve));
33 + try {
34 + await pool.query('delete from access_audit where family_id=any($1::uuid[]) or actor_user_id=any($2::uuid[])', [families, users]);
35 + await pool.query('delete from family_workspace where id=any($1::uuid[])', [families]);
36 + await pool.query('delete from auth_session where user_id=any($1::uuid[])', [users]);
37 + await pool.query('delete from app_user where id=any($1::uuid[])', [users]);
38 + } finally { await pool.end(); await observer.end(); }
39 +});
40 +async function request(who, method, path, body) {
41 + const response = await fetch(base + path, { method, headers: { 'content-type': 'application/json',
42 + ...(who ? { authorization: 'Bearer ' + who.accessToken } : {}) },
43 + body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(10000) });
44 + const text = await response.text();
45 + return { status: response.status, body: text ? JSON.parse(text) : null, cache: response.headers.get('cache-control') };
46 +}
47 +async function adult() {
48 + const id = crypto.randomUUID(), sid = crypto.randomUUID(); users.push(id);
49 + await pool.query('insert into app_user(id,identity_subject,email_normalized,email_verified_at) values($1,$2,$3,clock_timestamp())',
50 + [id, marker + ':' + id, 'synthetic-' + id + '@example.test']);
51 + await pool.query("insert into profile(user_id,display_name,birth_date) values($1,'Synthetic Adult','1985-01-01')", [id]);
52 + await pool.query("insert into auth_session(id,user_id,refresh_digest,expires_at) values($1,$2,$3,clock_timestamp()+interval '1 day')", [sid, id, crypto.randomUUID()]);
53 + return { id, sid, accessToken: claims(id, sid) };
54 +}
55 +async function fixture() {
56 + const owner = await adult(), other = await adult(), familyId = crypto.randomUUID(); families.push(familyId);
57 + await pool.query("insert into family_workspace(id,name,created_by) values($1,'Synthetic server fixture',$2)", [familyId, owner.id]);
58 + for (const member of [owner, other]) await pool.query("insert into family_membership(family_id,user_id,role,is_admin) values($1,$2,'parent_guardian',true)", [familyId, member.id]);
59 + const result = await request(owner, 'POST', `/families/${familyId}/children`, {
60 + displayName: 'Synthetic Child', birthDate: '2015-03-12', profileCategory: 'girl_minor',
61 + consentVersion: 'sandbox-child-consent-v1-not-legal', consentAccepted: true, synthetic: true });
62 + assert.equal(result.status, 201, 'Real app child creation');
63 + const childId = result.body.child.userId; users.push(childId);
64 + const issued = await request(owner, 'POST', `/families/${familyId}/children/${childId}/device-invitations`, { synthetic: true });
65 + assert.equal(issued.status, 201);
66 + const accepted = await request(null, 'POST', '/child-devices/accept', { token: issued.body.token });
67 + assert.equal(accepted.status, 200);
68 + return { owner, other, familyId, childId, child: accepted.body };
69 +}
70 +const refresh = child => request(null, 'POST', '/auth/refresh', { refreshToken: child.refreshToken });
71 +async function privateDenied(child, planId) {
72 + for (const [method, path, body] of [
73 + ['GET', '/today'], ['GET', '/plan-items'], ['GET', '/plan-items/' + planId], ['GET', '/study/sessions'],
74 + ['GET', '/me/learning-attempts'], ['GET', '/me/iran-profile'], ['GET', '/me/menstrual-cycles'],
75 + ['POST', '/ai/sessions', {}], ['POST', '/plan-items', { title: 'Synthetic', kind: 'task' }],
76 + ]) {
77 + const result = await request(child, method, path, body);
78 + assert.equal(result.status, 403, 'Managed device denied ' + method + ' ' + path);
79 + assert.equal(result.body.error, 'child_session_scope_denied');
80 + assert.equal(result.cache, 'no-store');
81 + }
82 +}
83 +async function privatePlan(f) {
84 + return (await pool.query(`insert into plan_item(owner_user_id,family_id,kind,title,notes,visibility)
85 + values($1,$2,'task','Synthetic private task','SYNTHETIC-PRIVATE-MARKER','private') returning id`, [f.childId, f.familyId])).rows[0].id;
86 +}
87 +
88 +test('real app child device reads only minimal profile/families; legacy privileges and private APIs remain denied', async () => {
89 + const f = await fixture(), planId = await privatePlan(f);
90 + const profile = await request(f.child, 'GET', '/profile'); assert.equal(profile.status, 200); assert.equal(profile.cache, 'no-store');
91 + assert.deepEqual(Object.keys(profile.body).sort(), ['accessScope', 'display_name', 'profile_category', 'theme_preference', 'user_id'].sort());
92 + assert.equal(profile.body.user_id, f.childId);
93 + const familiesResult = await request(f.child, 'GET', '/families'); assert.equal(familiesResult.status, 200); assert.equal(familiesResult.cache, 'no-store');
94 + await privateDenied(f.child, planId);
95 + for (const who of [f.owner, f.other]) for (const method of ['POST', 'DELETE'])
96 + assert.equal((await request(who, method, `/families/${f.familyId}/guardians`, { guardianUserId: f.other.id, minorUserId: f.childId })).status, 403);
97 + assert.equal((await request(f.owner, 'PATCH', `/families/${f.familyId}/members/${f.childId}/role`, {
98 + mutationId: crypto.randomUUID(), expectedVersion: 1, role: 'adult_member' })).status, 403);
99 + assert.equal((await request(f.owner, 'POST', `/families/${f.familyId}/admin-transfer`, {
100 + mutationId: crypto.randomUUID(), targetUserId: f.childId, expectedVersion: 1, expectedActorVersion: 1 })).status, 403);
101 + for (const path of ['/profile', '/me/iran-profile']) assert.equal((await request(f.child, 'PATCH', path, { birthDate: '1980-01-01', profileCategory: 'adult' })).status, 403);
102 + const unchanged = (await pool.query('select birth_date::text,profile_category from profile where user_id=$1', [f.childId])).rows[0];
103 + assert.deepEqual(unchanged, { birth_date: '2015-03-12', profile_category: 'girl_minor' });
104 + const identity = jwt.decode(f.child.accessToken);
105 + await privateDenied({ accessToken: claims(f.childId, identity.sid, { scope: 'standard', accessScope: 'standard', managedChild: false }) }, planId);
106 +});
107 +
108 +test('real refresh rotates once under concurrency, retains DB scope/issuer and rejects standard managed-child sessions', async () => {
109 + const f = await fixture(), planId = await privatePlan(f);
110 + const results = await Promise.all([refresh(f.child), refresh(f.child)]);
111 + assert.deepEqual(results.map(r => r.status).sort(), [200, 401]);
112 + for (const result of results) assert.equal(result.cache, 'no-store');
113 + const replacement = results.find(r => r.status === 200).body;
114 + const sid = jwt.decode(replacement.accessToken).sid;
115 + const row = (await pool.query('select access_scope,child_issuer_user_id from auth_session where id=$1', [sid])).rows[0];
116 + assert.deepEqual(row, { access_scope: 'child_education', child_issuer_user_id: f.owner.id });
117 + assert.equal((await refresh(f.child)).status, 401); await privateDenied(replacement, planId);
118 + const injectedSid = crypto.randomUUID(), raw = crypto.randomBytes(32).toString('base64url');
119 + await pool.query("insert into auth_session(id,user_id,refresh_digest,expires_at,access_scope) values($1,$2,$3,clock_timestamp()+interval '1 day','standard')", [injectedSid, f.childId, hash(raw)]);
120 + assert.equal((await request({ accessToken: claims(f.childId, injectedSid, { scope: 'standard' }) }, 'GET', '/profile')).status, 401);
121 + assert.equal((await refresh({ refreshToken: raw })).status, 401);
122 +});
123 +
124 +test('forged guardian relationship without creator invitation acceptance cannot read summary or issue child devices', async () => {
125 + const f = await fixture();
126 + await pool.query('insert into guardian_relationship(family_id,guardian_user_id,minor_user_id) values($1,$2,$3)', [f.familyId, f.other.id, f.childId]);
127 + assert.equal((await pool.query('select is_active_guardian($1,$2,$3) active', [f.familyId, f.other.id, f.childId])).rows[0].active, false);
128 + assert.equal((await request(f.other, 'GET', `/families/${f.familyId}/children/${f.childId}/support-summary`)).status, 403);
129 + assert.equal((await request(f.other, 'POST', `/families/${f.familyId}/children/${f.childId}/device-invitations`, { synthetic: true })).status, 403);
130 + const visibility = await request(f.child, 'GET', '/child-visibility'); assert.equal(visibility.status, 200);
131 + assert.deepEqual(visibility.body.guardians.map(g => g.userId), [f.owner.id]);
132 +});
133 +
134 +test('issuer role/relation removal, tampered consent digest and archived family invalidate next access and refresh', async () => {
135 + for (const change of ['role', 'relationship', 'consent_digest', 'archive']) {
136 + const f = await fixture();
137 + if (change === 'role') await pool.query("update family_membership set role='adult_member' where family_id=$1 and user_id=$2", [f.familyId, f.owner.id]);
138 + if (change === 'relationship') await pool.query('update guardian_relationship set active=false where family_id=$1 and guardian_user_id=$2', [f.familyId, f.owner.id]);
139 + if (change === 'consent_digest') await pool.query('update child_consent set text_digest=$2 where child_user_id=$1', [f.childId, '0'.repeat(64)]);
140 + if (change === 'archive') await pool.query('update family_workspace set archived_at=clock_timestamp() where id=$1', [f.familyId]);
141 + assert.equal((await request(f.child, 'GET', '/profile')).status, 401, change + ' invalidates access');
142 + assert.equal((await refresh(f.child)).status, 401, change + ' invalidates refresh');
143 + assert.equal((await pool.query('select count(*)::int n from auth_session where user_id=$1', [f.childId])).rows[0].n, 1);
144 + }
145 +});
146 +
147 +async function observedLock() {
148 + for (let i = 0; i < 300; i++) {
149 + if ((await observer.query("select 1 from pg_stat_activity where application_name=$1 and wait_event_type='Lock'", [marker])).rowCount) return;
150 + await new Promise(resolve => setTimeout(resolve, 10));
151 + }
152 + assert.fail('Expected actual refresh PostgreSQL lock wait');
153 +}
154 +test('refresh waiting on family lock rechecks guardian/session revocation and cannot mint a replacement', async () => {
155 + for (const change of ['relationship', 'session']) {
156 + const f = await fixture(), blocker = await observer.connect();
157 + try {
158 + await blocker.query('begin'); await blocker.query('select id from family_workspace where id=$1 for update', [f.familyId]);
159 + const pending = refresh(f.child); await observedLock();
160 + if (change === 'relationship') await blocker.query('update guardian_relationship set active=false where family_id=$1 and guardian_user_id=$2', [f.familyId, f.owner.id]);
161 + else await blocker.query('update auth_session set revoked_at=clock_timestamp() where id=$1', [jwt.decode(f.child.accessToken).sid]);
162 + await blocker.query('commit'); assert.equal((await pending).status, 401);
163 + assert.equal((await pool.query('select count(*)::int n from auth_session where user_id=$1', [f.childId])).rows[0].n, 1);
164 + } finally { await blocker.query('rollback'); blocker.release(); }
165 + }
166 +});
167 +
168 +test('creator revokes second guardian through real app; its child device and refresh immediately stop working', async () => {
169 + const f = await fixture();
170 + const invitation = await request(f.owner, 'POST', `/families/${f.familyId}/children/${f.childId}/guardian-invitations`, { guardianUserId: f.other.id });
171 + assert.equal(invitation.status, 201);
172 + assert.equal((await request(f.other, 'POST', '/guardian-invitations/accept', { token: invitation.body.token })).status, 200);
173 + const code = await request(f.other, 'POST', `/families/${f.familyId}/children/${f.childId}/device-invitations`, { synthetic: true });
174 + const accepted = await request(null, 'POST', '/child-devices/accept', { token: code.body.token }); assert.equal(accepted.status, 200);
175 + assert.equal((await request(f.owner, 'DELETE', `/families/${f.familyId}/children/${f.childId}/guardians/${f.other.id}`)).status, 200);
176 + assert.equal((await request(accepted.body, 'GET', '/profile')).status, 401); assert.equal((await refresh(accepted.body)).status, 401);
177 +});
178 +
179 +test('device acceptance exact and Express case/slash variants retain strict authentication quota profile', () => {
180 + for (const path of ['/v1/child-devices/accept', '/V1/CHILD-DEVICES/ACCEPT', '/v1/child-devices/accept/', '/V1/child-devices/Accept/']) {
181 + for (const method of ['POST', 'GET', 'PUT']) assert.equal(rateLimitProfile({ path, method }, {}).name, 'auth');
182 + }
183 +});
docs/audits/2026-10-16-child-identity-sandbox.md new
+72
@@ -0,0 +1,72 @@
1 +# فاز۱ — زیربنای آزمایشی هویت کودک
2 +
3 +**VERIFIED محلی:** `npm test -- --test-concurrency=1` → **297pass،0fail،0skip**. نقش محدود DB:30 و96 تست موفق؛ backup/restore با نقش‌های جدا موفق. این نتیجه برای Backend ساختگی محلی است؛ فاز۱ کامل و محصول آماده استفاده نیست.
4 +
5 +## تغییر قابل بررسی
6 +
7 +زنجیرهٔ جدید بر PR24 در `ef1205417b6523e199ace4ac3d3667a8aaf9cab5` متکی است، نه main قدیمی:
8 +
9 +1. [PR27 — schema](https://github.com/davoodmehraban89/LifeMate/pull/27)، شاخه `feat/child-identity-schema`، commit `6050a422598c3a575bf5a1f8a49fbfe262de843d`: migration0024/0025، رضایت صرفاً ساختگی، دعوت و scope؛ تابع مشترک سرپرستی برای مدل جدید، نیازمند رضایت و شاهد پذیرش است.
10 +2. [PR28 — مرز نشست](https://github.com/davoodmehraban89/LifeMate/pull/28)، شاخه `fix/managed-child-session-boundary`، commit `c72621fade774576ab9038f27e61670f5ba73335`: scope و صادرکننده از DB، حفظ محدودیت در refresh، no-store و منع مسیرهای خصوصی/ارتقای سن و نقش.
11 +3. شاخه `feat/child-device-safety` روی PR28: API آزمایشی ساخت کودک، دعوت دستگاه، سرپرست دوم، لغو و نمایش محدود دیدپذیری؛ آزمون روی app واقعی و اضافه‌شدن همین سناریو به آزمون نقش محدود در CI. PR و head نهایی در گزارش تحویل ثبت می‌شوند.
12 +
13 +همه تغییرات برای بررسی‌اند؛ هیچ merge،deploy،DNS،schema زنده یا SMS انجام نشده است. main هنگام بررسی همچنان `64b938dc9b0c3bb3620a7a12c22c690313d75bd7` بود. تغییرات ذخیره‌نشدهٔ worktreeهای قدیمی دست‌نخورده ماندند.
14 +
15 +## دامنه و مرز داده
16 +
17 +طبق [طرح sandbox](../decisions/2026-10-16-child-identity-sandbox.md)، تأیید ادامه فقط برای نمونه C-A/E-A/R-A تفسیر شد. `ENABLE_CHILD_IDENTITY_SANDBOX=true` همراه `NODE_ENV=test/development` لازم است؛ production همیشه503. این شرط مجوز واردکردن اطلاعات واقعی نیست.
18 +
19 +- والد ایجادکننده باید عضو فعال با نقش parent_guardian، مدیر و دارای DOB بالغ باشد. کودک جدید DOB معتبرِ زیر۱۸ و category مستقل از نقش خانواده دارد؛ بدون تماس یا رمز ساخته می‌شود. سن با تاریخ DB محاسبه می‌شود؛ احراز حقوقی سن نیست.
20 +- ثبت پروفایل، عضویت، سرپرست اولیه، نسخه/هش رضایت ساختگی و audit اتمیک است. متن `sandbox-child-consent-v1-not-legal` رضایت حقوقی نیست.
21 +- سرپرست دوم فقط با دعوت سازنده و پذیرش همان عضو بالغ اضافه می‌شود. endpoint قدیمی `/guardians` برای این کودکان رد می‌شود؛ سیاست legacy برای حساب‌های قدیمی هنوز اصلاح کامل نشده است.
22 +- دعوت دستگاه توکن تصادفی256بیتی/10دقیقه‌ای sandbox، digest و مصرف اتمیک دارد. صدور جایگزین ابتدا تمام نشست‌ها و دعوت‌های قبلی کودک را باطل می‌کند. حذف سرپرست دوم و لغو رضایت، اختیار/نشست‌های وابسته را قطع می‌کنند.
23 +- هر نشست صادرشده توسط والد، حتی اولین ورود، فقط `child_education` دارد؛ refresh به standard تبدیل نمی‌شود. وابستگی به سرپرست صادرکننده، رضایت، خانواده و عضویت در درخواست بعد دوباره بررسی می‌شود.
24 +- نام scope مجوز دسترسی به تمام داده آموزشی نیست: planner، جلسات خصوصی، هدف، سابقه آزمون، چت، سلامت و قاعدگی رد می‌شوند. فقط catalogue/locator/assessment منتشرشده، تقویم عمومی، پروفایل حداقلی بدون DOB/تماس، فهرست خانواده و API دیدپذیری مجازند. نمایش دیدپذیری فعلاً API است؛ صفحه Flutter نیست.
25 +
26 +از آنجا که والد می‌تواند دستگاه را صادر کند، دادن نشست کامل کودک مسیر ورود به فضای خصوصی او می‌شد. تا طراحی مسیرهای آموزشی با مجوز سطح رکورد، مسیرهای خصوصی قدیمی برای این نشست‌ها باز نمی‌شوند. این بسته سناریوی کامل تکلیف/تایمر/آزمون والد را پیاده نمی‌کند.
27 +
28 +## اجرای واقعی
29 +
30 +Node24.19.0، npm11.9.0 و PostgreSQL16.15. ظرف **جدید** `lifeguide-child-tests-20261016` با tmpfs و اتصال فقط loopback ساخته شد؛ سرویس‌های قبلی و Supabase استفاده/تغییر نشدند. داده‌ها و تماس‌ها همه ساختگی‌اند. احراز اتصال fixture از نوع trust محلی بود؛ آزمون نقش‌ها، مجوز SQL را می‌سنجد و گواه تنظیم احراز شبکه تولید نیست.
31 +
32 +|دستور|خروجی واقعی|
33 +|---|---|
34 +|`npm ci --no-fund`|111package نصب؛ exit0|
35 +|`npm run migrate` روی DB تازه و تکرار|23migration؛ تکرار بدون اعمال مجدد، exit0|
36 +|`node scripts/import-learning-catalog.js` و تکرار|217book/1373unit/1348video؛ تمام ویدیوها draft|
37 +|`node --test tests/managed_child_scope.test.js` پیش از اصلاح|3fail/2pass؛ نشست محدود به مسیرهای خصوصی می‌رسید|
38 +|`node --test tests/child_identity.test.js` پیش از وجود مسیر|9fail؛ مسیرهای جدید404|
39 +|`npm test -- --test-concurrency=1` اجرای نهایی بدون فیلتر|297test/297pass/0fail/0skip؛87.75s|
40 +|`node scripts/test-db-roles.js --synthetic-only`|30test/30pass با runtime مستقیم؛96test/96pass رگرسیون با fixture جدا|
41 +|چهار `*schema_test.sql` با `psql -v ON_ERROR_STOP=1`|چهار exit0؛ سه fixture rollback، فایل phase6 فقط assertion خواندنی|
42 +|`scripts/backup.sh` با نقش backup و `scripts/restore.sh` با migrator؛ `--verify-restored`|ledger23، مجوزها، داده ساختگی و study600seconds حفظ؛ exit0|
43 +|`npm run check`؛ `npm audit --audit-level=high`؛ `git diff --check`|82فایل syntax؛0vulnerability؛ diff پاک|
44 +|Gitleaks8.30.1 روی21فایل تغییرکردهٔ کد/schema/تست|0finding؛ archiveSHA با مرجع قبلی یکسان|
45 +|بازبین مستقل؛ چهار فایل scope/identity/server/bundle|29pass/0fail/0skip؛ یافته مهم حل‌نشده در همین دامنه محدود گزارش نشد|
46 +
47 +اجرای کامل نخست296pass/1fail بود: observer تست رقابت login/reset متن SQL قدیمی را عیناً می‌خواست؛ شرط جدید منع managed-child باعث شد قفل واقعی recovery را نشناسد. observer همچنان قفل واقعی account در `pg_stat_activity` را می‌بیند و اکنون فیلتر اضافی را مجاز می‌داند؛ اجرای نهایی297pass است. بازبین همچنین نام دارای NUL را با500 بازتولید کرد؛ validator و regression400 اضافه شد. wrapper گزارش SQL ابتدا به‌اشتباه برای assertion خواندنی phase6 انتظار ROLLBACK داشت؛ چهار اجرای psql از ابتدا exit0 بودند، طبقه‌بندی گزارش تصحیح شد.
48 +
49 +۲۱ migration قبلی، شامل0001–0020 و0023، و bundleهای تاریخی Supabase بایت‌به‌بایت حفظ شدند. generator جدید23فایل را برای **schema تازه** می‌سازد؛ migration افزایشی مناسب QA موجود یا گواه اعمال زنده نیست. از اجرای آن یا migrator عمومی روی Supabase موجود خودداری شود تا بسته انتقال جدا بررسی و تأیید شود.
50 +
51 +[رسید ماشین‌خوان و SHA لاگ‌ها](evidence/child-identity-sandbox-2026-10-16.json). لاگ‌های کامل ساختگی در بسته تحویل مستقل نگهداری می‌شوند؛ شماره/ایمیل واقعی، رمز، توکن یا داده واقعی کودک در این گزارش و receipt نیست.
52 +
53 +## اجرای مجدد
54 +
55 +روی شاخه نهایی، فقط PostgreSQL **تازه و محلیِ ساختگی** با نام `lifemate_ci` بسازید و `DATABASE_URL`/`JWT_SECRET` آزمایشی را در محیط قرار دهید؛ سپس در backend:
56 +
57 +```sh
58 +npm ci
59 +npm run migrate
60 +npm run migrate
61 +node scripts/import-learning-catalog.js
62 +npm test -- --test-concurrency=1
63 +npm run check
64 +```
65 +
66 +نصب UI جدید یا ارسال SMS لازم نیست. CI موجود نیز پس از PR همین migration/test و آزمون نقش/restore را اجرا می‌کند؛ وضعیت تازه هر PR باید از خروجی خودش خوانده شود. اجرای Flutter212 و ساخت APKdebug در CI قبلی PR24 تأیید شد، ولی ساخت این بسته یا نصب واقعی محسوب نمی‌شود.
67 +
68 +## UNVERIFIED و ادامه
69 +
70 +UI/QR، Android/iPhone/Safari و نصب/ارتقا؛ مسیر جدید مجازِ تکلیف/تایمر/آزمون، SMS واقعی و تأیید کاوه‌نگار؛ دسترسی ایران؛ سیستم آنلاین عمومی؛ رضایت حقوقی، نگهداری و زیرساخت تولید؛ اعمال0024/0025 روی Supabase و امضای release تأیید نشده‌اند. داده کودک واقعی یا تغییر میزبانی مجاز نشده است.
71 +
72 +P0های قبلیِ داده حساس در صورت بازکردن flag، سرپرستی حساب‌های legacy و سایر موارد ممیزی همچنان در برنامه‌اند. UI توضیح مجوزها، متن رضایت/اعتراض و مسیر بلوغ باید جدا تکمیل و بازبینی شوند. **فاز۲ شروع نشده است؛ فاز۱ کامل اعلام نمی‌شود.**
docs/audits/evidence/child-identity-sandbox-2026-10-16.json new
+225
@@ -0,0 +1,225 @@
1 +{
2 + "status": "VERIFIED_LOCAL_SYNTHETIC_ONLY",
3 + "date": "2026-10-16",
4 + "base": "ef1205417b6523e199ace4ac3d3667a8aaf9cab5",
5 + "schemaCommit": "6050a422598c3a575bf5a1f8a49fbfe262de843d",
6 + "boundaryCommit": "c72621fade774576ab9038f27e61670f5ba73335",
7 + "runtime": "Node24.19.0/npm11.9.0/PostgreSQL16.15",
8 + "commands": [
9 + {
10 + "command": "npm ci --no-fund",
11 + "output": "added 111 packages in 740ms",
12 + "exitCode": 0
13 + },
14 + {
15 + "command": "npm run migrate (fresh isolated local DB), repeat",
16 + "output": "23 migrations applied; repeat no migrations applied",
17 + "exitCode": 0
18 + },
19 + {
20 + "command": "node scripts/import-learning-catalog.js (twice)",
21 + "output": {
22 + "books": 217,
23 + "units": 1373,
24 + "videos": 1348,
25 + "publicationStatus": "draft"
26 + },
27 + "exitCode": 0
28 + },
29 + {
30 + "command": "npm test -- --test-concurrency=1",
31 + "output": {
32 + "tests": 297,
33 + "pass": 297,
34 + "fail": 0,
35 + "cancelled": 0,
36 + "skipped": 0,
37 + "duration_ms": 87745.639625
38 + },
39 + "exitCode": 0
40 + },
41 + {
42 + "command": "node scripts/test-db-roles.js --synthetic-only",
43 + "output": {
44 + "familyIdentityTests": 30,
45 + "familyIdentityPass": 30,
46 + "regressionTests": 96,
47 + "regressionPass": 96,
48 + "fail": 0
49 + },
50 + "exitCode": 0
51 + },
52 + {
53 + "command": "existing scripts/backup.sh -> scripts/restore.sh with independent backup/migrator roles; node scripts/test-db-roles.js --verify-restored",
54 + "output": "PASS restored checksum ledger entries, migrator ownership/repeat, runtime denial matrix, guardian/private policy and paused-study600seconds",
55 + "exitCode": 0
56 + },
57 + {
58 + "command": "npm run check",
59 + "output": "Syntax checked 82 source/script/test files.",
60 + "exitCode": 0
61 + },
62 + {
63 + "command": "npm audit --audit-level=high",
64 + "output": "found 0 vulnerabilities",
65 + "exitCode": 0
66 + },
67 + {
68 + "command": "git diff --check",
69 + "output": "",
70 + "exitCode": 0
71 + },
72 + {
73 + "command": "gitleaks8.30.1 dir <changed-source> --redact",
74 + "output": {
75 + "files": 21,
76 + "findings": 0
77 + },
78 + "exitCode": 0
79 + }
80 + ],
81 + "sqlMatrices": [
82 + {
83 + "file": "phase3_schema_test.sql",
84 + "exitCode": 0,
85 + "fixtureRollback": true,
86 + "readOnlyAssertions": false
87 + },
88 + {
89 + "file": "phase4_schema_test.sql",
90 + "exitCode": 0,
91 + "fixtureRollback": true,
92 + "readOnlyAssertions": false
93 + },
94 + {
95 + "file": "phase6_schema_test.sql",
96 + "exitCode": 0,
97 + "fixtureRollback": false,
98 + "readOnlyAssertions": true
99 + },
100 + {
101 + "file": "schema_test.sql",
102 + "exitCode": 0,
103 + "fixtureRollback": true,
104 + "readOnlyAssertions": false
105 + }
106 + ],
107 + "migrationManifest": [
108 + {
109 + "file": "0001_identity_family.sql",
110 + "sha256": "03339b58ceea571e9f9851153f039c7bba32b89eb8259c2171b5ec9934ab0443"
111 + },
112 + {
113 + "file": "0002_auth.sql",
114 + "sha256": "5a89eef261278ddc0caa49e5fff2ecbd800bcc86b62f3cbb6aef8681b9d201ad"
115 + },
116 + {
117 + "file": "0003_planner_school_family.sql",
118 + "sha256": "65989395542a6d103c4bec94f197f69f0d1f2598e8a7fd680ba0b9a2e8780b4a"
119 + },
120 + {
121 + "file": "0004_ai_learning_wellbeing.sql",
122 + "sha256": "d1c463276bbe48bc81f525f75b5542a65790f5e94629602533efa731cfad54c8"
123 + },
124 + {
125 + "file": "0005_iran_family_learning.sql",
126 + "sha256": "b54181ac5c8fd30e797ecf9eb65b2759549ec596b05cb96b36a7880b704f4ce2"
127 + },
128 + {
129 + "file": "0006_iran_calendar_1405_holidays.sql",
130 + "sha256": "431bfe20a4f4a94d77c92d9e3191eb932951ec1f3087e3fcfbdbf6803d36da54"
131 + },
132 + {
133 + "file": "0007_auth_contacts.sql",
134 + "sha256": "f8d20ecb8ded06c210125dd973670ead88cbbcb4a9ff2acf9c15e0e52059e392"
135 + },
136 + {
137 + "file": "0008_study_sessions.sql",
138 + "sha256": "546aa351dca8936fefd8cde9b2080b1a6e198b4174da643898657add135d7a7a"
139 + },
140 + {
141 + "file": "0009_authorization_privacy.sql",
142 + "sha256": "48c9423b303c1c00688326a21ac53e40e2183ded3ac8c9ea9bccdf0081f81fe3"
143 + },
144 + {
145 + "file": "0010_planner_sync.sql",
146 + "sha256": "a1994e6af0acb171f8c85195b18cb287c1d97a37147ae5edd9eadcecd5fbd7bf"
147 + },
148 + {
149 + "file": "0011_profile_category.sql",
150 + "sha256": "6ee7f5a00ecb9d2daf65d47e189a4850693d944a7dd36ef0521d911dd483c732"
151 + },
152 + {
153 + "file": "0012_school_archive.sql",
154 + "sha256": "e5e697a816a3d3b00dd2b0d1cf4dca43d130fb8478150419245ca36077ca3e84"
155 + },
156 + {
157 + "file": "0013_aparat_learning_library.sql",
158 + "sha256": "78add32ebd97bcb8a6a6cf6e65ad7aed26ce8fbf5e35d2f343d64878fdcac8c6"
159 + },
160 + {
161 + "file": "0014_learning_feedback.sql",
162 + "sha256": "8897b6d581644dc3c614573c0c21af2e2fd328413067bb9338ac0e42707856fd"
163 + },
164 + {
165 + "file": "0015_learning_assessment.sql",
166 + "sha256": "b62ac6551b5ef920740e8e1f7eb63f74a1bebd2f7b60243fa7269c5bca1c269a"
167 + },
168 + {
169 + "file": "0016_content_review.sql",
170 + "sha256": "2c390305940afb72fcfe92d180a08dc64cd9dc27d87a4ca9d2e8583ed2de147e"
171 + },
172 + {
173 + "file": "0017_learning_goal_mutations.sql",
174 + "sha256": "241578122d62c418c7d951607d15fc69c038d4ec678ca0c42f618042d9e8a930"
175 + },
176 + {
177 + "file": "0018_family_lifecycle.sql",
178 + "sha256": "711eb59781fd76d23440b9f55eae92489f365fdd0db1d32c8779ebd89818d09a"
179 + },
180 + {
181 + "file": "0019_school_lifecycle.sql",
182 + "sha256": "ed5bac695d4b0375e098a62d99b52fa8484b6318c16125339574974d3467c52a"
183 + },
184 + {
185 + "file": "0020_content_publication_audit.sql",
186 + "sha256": "84e8112f271eef5c3ee0860d3c3c94302ea9abd81d069147a10b52651b7d5fa3"
187 + },
188 + {
189 + "file": "0023_auth_ip_rate_limit.sql",
190 + "sha256": "805fc309af065c7f01f6255ecdf78f9cb32d24626c977b58612260a46650a77b"
191 + },
192 + {
193 + "file": "0024_child_device_safety.sql",
194 + "sha256": "c8853f59672e0eb3c291d81eebd299dd1107f5047aa5c00bbe0767b0809bfc86"
195 + },
196 + {
197 + "file": "0025_managed_guardian_authority.sql",
198 + "sha256": "ba04802b92ab498332c81f6e053569dc7e418b02c59eb2c02cb8823218edf49b"
199 + }
200 + ],
201 + "priorFailure": {
202 + "tests": 297,
203 + "pass": 296,
204 + "fail": 1,
205 + "cause": "Existing auth_delivery test looked for exact old SQL while observing a real recovery/login lock. Updated predicate still observes actual account-row lock waits; final unfiltered suite passed."
206 + },
207 + "review": "Independent focused29pass; NUL input500 reproduced then validator400 verified; no unresolved critical/important within bounded sandbox scope.",
208 + "unverified": [
209 + "New child UI and QR",
210 + "Android installation/upgrade and iOS Safari",
211 + "Actual SMS/template approval",
212 + "Iran network reachability",
213 + "Production consent and hosting",
214 + "Public online multi-user system",
215 + "New child planner/timer/quiz permitted data path",
216 + "Live Supabase application of0024/0025",
217 + "Fresh local Flutter/APK build for this package"
218 + ],
219 + "liveOperations": "No merge/deploy/DNS/live database or SMS operation",
220 + "evidenceSha256": {
221 + "final-full-suite.log": "6423d2a5f432a2709e5e84f89442148da612e31d5abc98be3fde069e7ea5fcbc",
222 + "runtime-role.log": "f1ae3141f835705136ff42a6b5277aab6d7b52b857c058ec3aee3f87698a829b",
223 + "restore-role.log": "81eb5dd942497df8f3ae64393079c5b2dd45c715b20514b98520a6f36755d1d6"
224 + }
225 +}
docs/decisions/2026-10-16-child-identity-sandbox.md
+2 -2
@@ -1,6 +1,6 @@
1 # هویت و سرپرستی کودک در محیط آزمایشی
2
3 -**وضعیت: EXPERIMENTAL — پیاده‌سازی و آزمون در جریان؛ نتایج این بسته UNVERIFIED تا ثبت خروجی اجرا.**
3 +**وضعیت: EXPERIMENTAL — Backend ساختگی محلی آزموده شد؛ تولید و رضایت حقوقی تأیید نشده‌اند.** [شواهد اجرا](../audits/2026-10-16-child-identity-sandbox.md).
4
5 دستور «ادامه بده» پس از پیشنهاد مشخص C-A/E-A/R-A، مجوز ادامهٔ نمونهٔ آزمایشی آن طرح تلقی می‌شود. این سند پذیرش متن حقوقی رضایت، تأیید هویت یا سن واقعی، مجوز استفاده از دادهٔ واقعی، انتخاب زیرساخت، merge یا deploy نیست. گزینه‌های AI، نگهداری داده و نشست وب همچنان تصمیم‌های مستقل و تأییدنشده‌اند.
6
@@ -47,4 +47,4 @@ allowlist باریک فقط برای خواندن پروفایل خود، فهر
47 5. رد همهٔ مسیرهای خصوصی و تغییر marker/DOB/scope از APIهای قدیمی؛ JWT جعلی با claim گسترده مجوز نمی‌آورد.
48 6. خواندن مستقل DB برای digest، scope و audit؛ عدم ذخیرهٔ خود توکن یا دادهٔ حساس در لاگ.
49
50 -**UNVERIFIED در این ADR:** نتایج آزمون این پیاده‌سازی، UI/QR، Android و Safari واقعی، SMS کاوه‌نگار، کارایی تولید، رضایت حقوقی، دسترسی ایران و اعمال migration زنده. هیچ‌یک از این موارد با سبزشدن تست‌های قبلی هویت تأیید نمی‌شود.
50 +**UNVERIFIED:** UI/QR، Android و Safari واقعی، SMS کاوه‌نگار، کارایی تولید، رضایت حقوقی، دسترسی ایران و اعمال migration زنده. نتایج محلی همین Backend در گزارش پیوندشده ثبت شده‌اند؛ موفقیت آن‌ها این محدودیت‌ها را رفع نمی‌کند.