LifeMate — Personal, Family & Learning Companion

fix/personal-jalali-dates
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 82 lines 4.61 KB
Raw
1 // No remote/live permission changes: this packet supports explicitly named,
2 // local synthetic fixtures only. No default admin, family role or HTTP grant.
3 import crypto from 'node:crypto';
4 import pg from 'pg';
5 import { fileURLToPath } from 'node:url';
6 import path from 'node:path';
7
8 const scopes=new Set(['feedback.read','feedback.review','brief.prepare']);
9 const uuid=value=>typeof value==='string'&&/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(value);
10
11 export function normalizeCapabilityOperation(args) {
12 const [action,userId,permission,expiresAt,...extra]=args;
13 if(!['grant','revoke'].includes(action)||!uuid(userId)||!scopes.has(permission)||extra.length||
14 (action==='revoke'&&expiresAt!==undefined)) return null;
15 if(action==='grant') {
16 if(typeof expiresAt!=='string'||!/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{3})?Z$/.test(expiresAt)||
17 !Number.isFinite(Date.parse(expiresAt))||Date.parse(expiresAt)<=Date.now()) return null;
18 }
19 return {action,userId:userId.toLowerCase(),permission,expiresAt:expiresAt??null};
20 }
21
22 export function localSyntheticConnection(env) {
23 if(!env.CONTENT_CAPABILITY_DATABASE_URL||env.CONTENT_CAPABILITY_SYNTHETIC_ONLY!=='true') {
24 throw new Error('Set separate CONTENT_CAPABILITY_DATABASE_URL and CONTENT_CAPABILITY_SYNTHETIC_ONLY=true');
25 }
26 let location;
27 try { location=new URL(env.CONTENT_CAPABILITY_DATABASE_URL); } catch { throw new Error('Invalid operator database configuration'); }
28 if(!['postgres:','postgresql:'].includes(location.protocol)||
29 !['localhost','127.0.0.1','[::1]','::1'].includes(location.hostname)||
30 !(location.pathname.includes('test')||location.pathname==='/lifemate_ci'||
31 /^\/lifeguide_roles_(?:source|target)_[a-f0-9]{16}$/.test(location.pathname))) {
32 throw new Error('Capability operator refuses a nonlocal or non-test database');
33 }
34 return location.toString();
35 }
36
37 export async function manageCapability(client,operation) {
38 await client.query('begin');
39 try {
40 const role=(await client.query(`select current_user,
41 has_table_privilege(current_user,'content_capability_grant','INSERT') can_grant,
42 has_table_privilege(current_user,'content_capability_grant','UPDATE') can_revoke`)).rows[0];
43 if(['lifeguide_api','lifeguide_backup'].includes(role.current_user)||!role.can_grant||!role.can_revoke) {
44 throw new Error('Use separate operator/migrator credentials, never runtime/backup credentials');
45 }
46 const actor=await client.query('select id from app_user where id=$1 and disabled_at is null for update',[operation.userId]);
47 if(!actor.rowCount) throw new Error('Active synthetic account not found');
48 if(operation.action==='grant') {
49 if(Date.parse(operation.expiresAt)<=Date.now()) throw new Error('Grant expiry must be in the future');
50 await client.query(`insert into content_capability_grant(user_id,permission,expires_at)
51 values($1,$2,$3) on conflict(user_id,permission) do update set
52 granted_at=statement_timestamp(),expires_at=excluded.expires_at,revoked_at=null`,
53 [operation.userId,operation.permission,operation.expiresAt]);
54 } else {
55 await client.query(`update content_capability_grant set revoked_at=coalesce(revoked_at,statement_timestamp())
56 where user_id=$1 and permission=$2`,[operation.userId,operation.permission]);
57 }
58 await client.query(`insert into content_capability_audit(id,target_user_id,permission,action,expires_at)
59 values($1,$2,$3,$4,$5)`,[crypto.randomUUID(),operation.userId,operation.permission,operation.action,operation.expiresAt]);
60 await client.query('commit');
61 return {action:operation.action,permission:operation.permission,expiresAt:operation.expiresAt};
62 } catch(error) { await client.query('rollback').catch(()=>{}); throw error; }
63 }
64
65 if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url)) {
66 const operation=normalizeCapabilityOperation(process.argv.slice(2));
67 if(!operation) {
68 console.error('Usage: node scripts/manage-content-capabilities.js grant USER_UUID SCOPE ISO_UTC_EXPIRY | revoke USER_UUID SCOPE');
69 process.exitCode=1;
70 } else {
71 let client;
72 try {
73 client=new pg.Client({connectionString:localSyntheticConnection(process.env)});
74 await client.connect();
75 console.log(JSON.stringify({type:'synthetic_content_capability',...(await manageCapability(client,operation))}));
76 } catch {
77 // Database URLs, account IDs, passwords and raw driver errors stay private.
78 console.error('Capability operation rejected; check explicit synthetic configuration and separate operator privileges.');
79 process.exitCode=1;
80 } finally { if(client) await client.end().catch(()=>{}); }
81 }
82 }