LifeMate — Personal, Family & Learning Companion

feat/aparat-learning-library
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 222 lines 17 KB
Raw
1 // Operations-only policy. Keep application object names stable; these are not
2 // product labels. No REASSIGN OWNED, catalog writes or broad ownership transfer.
3 import crypto from 'node:crypto';
4 import fs from 'node:fs/promises';
5
6 export const applicationTables = [
7 'academic_term', 'academic_year', 'access_audit', 'activity_state_event',
8 'ai_guide_message', 'ai_guide_session', 'ai_plan_proposal', 'app_user',
9 'auth_credential', 'auth_delivery_attempt', 'auth_phone_challenge', 'auth_session',
10 'auth_token', 'class_session', 'curriculum_subject', 'education_profile',
11 'family_invitation', 'family_membership', 'family_workspace', 'guardian_relationship',
12 'iran_calendar_event', 'learning_checkin', 'learning_goal', 'life_context',
13 'learning_unit', 'learning_video_resource', 'learning_progress', 'learning_progress_mutation',
14 'learning_content_feedback',
15 'learning_assessment', 'learning_assessment_attempt', 'learning_review_schedule',
16 'menstrual_cycle_entry', 'notification_outbox', 'notification_preference',
17 'plan_item', 'profile', 'reminder', 'schema_migration', 'sharing_grant',
18 'study_interval', 'study_mutation', 'study_session', 'subject', 'sync_mutation',
19 'textbook_catalog', 'wellbeing_checkin', 'wellbeing_safety_event',
20 ];
21 export const applicationTypes = ['member_role', 'invitation_status', 'visibility_scope',
22 'auth_token_kind', 'life_context_kind', 'plan_item_kind', 'plan_item_status',
23 'plan_priority', 'sharing_scope', 'reminder_status'];
24 export const applicationSequences = ['access_audit_id_seq', 'notification_outbox_id_seq',
25 'study_interval_id_seq', 'activity_state_event_id_seq'];
26 export const applicationFunctions = [
27 'is_active_family_member(uuid, uuid)', 'is_family_admin(uuid, uuid)',
28 'is_active_guardian(uuid, uuid, uuid)', 'can_view_student_academic(uuid, uuid)',
29 'can_view_plan_item(uuid, uuid)', 'recompute_reminder_schedule(uuid)',
30 'plan_item_revision()', 'revoke_changed_plan_item_grants()',
31 'validate_learning_publication()',
32 'validate_learning_assessment_publication()',
33 'revoke_ended_membership_grants()', 'plan_item_legacy_activity()',
34 ];
35 export const roleNames = Object.freeze({ api: 'lifeguide_api', migrator: 'lifeguide_migrator', backup: 'lifeguide_backup' });
36 // Only the separate migrator/importer can change reviewed teaching material.
37 export const readOnlyCatalogTables = new Set(['curriculum_subject', 'textbook_catalog',
38 'learning_unit', 'learning_video_resource', 'learning_assessment']);
39 const ident = (value) => `"${String(value).replaceAll('"', '""')}"`;
40 export function validateRoles(env) {
41 const configured = { api: env.API_DB_USER ?? roleNames.api, migrator: env.MIGRATOR_DB_USER ?? roleNames.migrator, backup: env.BACKUP_DB_USER ?? roleNames.backup };
42 for (const kind of Object.keys(roleNames)) {
43 if (configured[kind] !== roleNames[kind]) throw new Error('Use the three canonical, distinct application role names');
44 }
45 return configured;
46 }
47
48 async function grantUuidDefault(client,roles) {
49 // Existing table DEFAULT expressions bind to pgcrypto's public UUID function,
50 // even when the runtime search_path prefers the equivalent pg_catalog one.
51 // Allow only this value-generating extension function, never backup execution.
52 const uuid = await client.query(`SELECT 1 FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace
53 JOIN pg_depend d ON d.classid='pg_proc'::regclass AND d.objid=p.oid AND d.deptype='e'
54 JOIN pg_extension e ON e.oid=d.refobjid
55 WHERE n.nspname='public' AND p.proname='gen_random_uuid' AND p.pronargs=0 AND e.extname='pgcrypto'`);
56 if(uuid.rowCount) await client.query(`GRANT EXECUTE ON FUNCTION public.gen_random_uuid() TO ${ident(roles.api)},${ident(roles.migrator)}`);
57 }
58
59 async function inventory(client) {
60 const tables = await client.query(`SELECT c.relname name,c.relkind kind,pg_get_userbyid(c.relowner) owner
61 FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace
62 WHERE n.nspname='public' AND c.relkind IN ('r','p','S','v','m','f')
63 AND NOT EXISTS(SELECT 1 FROM pg_depend d WHERE d.classid='pg_class'::regclass AND d.objid=c.oid AND d.deptype='e')`);
64 const types = await client.query(`SELECT t.typname name,pg_get_userbyid(t.typowner) owner FROM pg_type t
65 JOIN pg_namespace n ON n.oid=t.typnamespace WHERE n.nspname='public' AND t.typtype IN ('e','d')
66 AND NOT EXISTS(SELECT 1 FROM pg_depend d WHERE d.classid='pg_type'::regclass AND d.objid=t.oid AND d.deptype='e')`);
67 const functions = await client.query(`SELECT p.proname||'('||oidvectortypes(p.proargtypes)||')' name,
68 pg_get_userbyid(p.proowner) owner,p.prosecdef security_definer FROM pg_proc p
69 JOIN pg_namespace n ON n.oid=p.pronamespace WHERE n.nspname='public'
70 AND NOT EXISTS(SELECT 1 FROM pg_depend d WHERE d.classid='pg_proc'::regclass AND d.objid=p.oid AND d.deptype='e')`);
71 return { tables: tables.rows, types: types.rows, functions: functions.rows };
72 }
73
74 function isKnown(object, category) {
75 if (category === 'tables') return (object.kind === 'S' ? applicationSequences : applicationTables).includes(object.name);
76 if (category === 'types') return applicationTypes.includes(object.name);
77 return applicationFunctions.includes(object.name);
78 }
79
80 export async function prepareRoles(client, { env = process.env, adoptOwner, backupFile } = {}) {
81 const roles = validateRoles(env);
82 const passwords = { api: env.API_DB_PASSWORD, migrator: env.MIGRATOR_DB_PASSWORD, backup: env.BACKUP_DB_PASSWORD };
83 const values = Object.values(passwords);
84 if (values.some((v) => typeof v !== 'string' || v.length < 32 || v.startsWith('CHANGE_ME')) || new Set(values).size !== 3 || values.includes(env.PGPASSWORD)) {
85 throw new Error('Three independent non-placeholder role passwords of at least32 characters are required');
86 }
87 let backupDigest;
88 let backupManifest;
89 if (adoptOwner) {
90 if (!/^[a-z_][a-z0-9_]{0,62}$/.test(adoptOwner) || Object.values(roles).includes(adoptOwner)) throw new Error('Invalid expected previous owner');
91 if (!backupFile) throw new Error('Existing ownership adoption requires an explicit verified backup file');
92 const content = await fs.readFile(backupFile);
93 if (content.length < 6 || content.subarray(0,5).toString() !== 'PGDMP') throw new Error('Adoption backup must be a PostgreSQL custom-format archive');
94 backupDigest = crypto.createHash('sha256').update(content).digest('hex');
95 backupManifest=JSON.parse(await fs.readFile(`${backupFile}.validated.json`,'utf8'));
96 if(backupManifest.format!=='LifeGuide-adoption-backup-v1' || backupManifest.sha256!==backupDigest || backupManifest.pgRestoreList!==true ||
97 !Number.isFinite(Date.parse(backupManifest.validatedAt)) || Date.now()-Date.parse(backupManifest.validatedAt)>15*60*1000 || Date.parse(backupManifest.validatedAt)>Date.now()+60000) {
98 throw new Error('Run the local adoption helper to validate this exact backup first');
99 }
100 }
101 await client.query('BEGIN');
102 try {
103 await client.query("SELECT pg_advisory_xact_lock(hashtextextended('lifeguide_role_provision',0))");
104 await client.query("SET LOCAL lock_timeout='5s'");
105 const session = (await client.query(`SELECT current_user, current_database() database,
106 (SELECT rolsuper FROM pg_roles WHERE rolname=current_user) superuser`)).rows[0];
107 if (!session.superuser || Object.values(roles).includes(session.current_user)) throw new Error('Provisioning requires the separate bootstrap administrator');
108 if(backupManifest && backupManifest.database!==session.database) throw new Error('Adoption backup belongs to another database');
109 const restricted=[roles.api,roles.backup];
110 const databaseOwnership=await client.query(`SELECT EXISTS(SELECT 1 FROM pg_database
111 WHERE datdba IN (SELECT oid FROM pg_roles WHERE rolname=ANY($1::text[]))) owned`,[Object.values(roles)]);
112 if(databaseOwnership.rows[0].owned) throw new Error('Application roles must not own any database; operator must resolve unexpected ownership explicitly');
113 const unexpectedOwnership=await client.query(`SELECT EXISTS(
114 SELECT 1 FROM pg_namespace WHERE nspowner IN (SELECT oid FROM pg_roles WHERE rolname=ANY($1::text[]))
115 UNION ALL SELECT 1 FROM pg_class WHERE relowner IN (SELECT oid FROM pg_roles WHERE rolname=ANY($1::text[]))
116 UNION ALL SELECT 1 FROM pg_proc WHERE proowner IN (SELECT oid FROM pg_roles WHERE rolname=ANY($1::text[]))
117 UNION ALL SELECT 1 FROM pg_type WHERE typowner IN (SELECT oid FROM pg_roles WHERE rolname=ANY($1::text[]))
118 UNION ALL SELECT 1 FROM pg_extension WHERE extowner IN (SELECT oid FROM pg_roles WHERE rolname=ANY($1::text[]))) owned`,[restricted]);
119 if(unexpectedOwnership.rows[0].owned) throw new Error('Runtime/backup ownership outside granted application data access is forbidden; operator must resolve it explicitly');
120 const unknownSchema=await client.query(`SELECT EXISTS(SELECT 1 FROM pg_namespace
121 WHERE nspname<>'public' AND nspname<>'information_schema' AND nspname !~ '^pg_') present`);
122 // A dedicated app DB has only public plus PostgreSQL system schemas.
123 // Refuse auxiliary namespaces: inherited CREATE, TRIGGER or executable
124 // SECURITY DEFINER there could undo this policy. Never rewrite their ACLs.
125 if(unknownSchema.rows[0].present) throw new Error('Unknown non-system schema in dedicated application DB; operator must isolate or explicitly resolve it');
126 const objects = await inventory(client);
127 for (const [category, list] of Object.entries(objects)) for (const object of list) {
128 if (object.security_definer) throw new Error('Application SECURITY DEFINER is outside the approved role policy');
129 if (object.owner !== roles.migrator && (!adoptOwner || object.owner !== adoptOwner || !isKnown(object, category))) {
130 throw new Error('Existing ownership differs. Stop writers, verify backup, then explicitly adopt the known application owner');
131 }
132 }
133 for (const [kind, name] of Object.entries(roles)) {
134 const existing = (await client.query(`SELECT rolsuper,rolcreatedb,rolcreaterole,rolreplication,rolbypassrls,rolinherit,
135 EXISTS(SELECT 1 FROM pg_auth_members WHERE member=pg_roles.oid) memberships
136 FROM pg_roles WHERE rolname=$1`, [name])).rows[0];
137 if (existing && Object.values(existing).some(Boolean)) throw new Error('Existing application role has unexpected privileges or memberships; refusing to change it');
138 // Parameterized session settings keep password values out of SQL text and
139 // error statements. The exception handler deliberately removes context
140 // containing the dynamically constructed CREATE/ALTER ROLE password.
141 await client.query("SELECT set_config('lifeguide_provision.role_name',$1,true),set_config('lifeguide_provision.role_password',$2,true)", [name,passwords[kind]]);
142 await client.query(`DO $$ BEGIN
143 IF NOT EXISTS(SELECT 1 FROM pg_roles WHERE rolname=current_setting('lifeguide_provision.role_name')) THEN
144 EXECUTE format('CREATE ROLE %I LOGIN NOINHERIT NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS',current_setting('lifeguide_provision.role_name'));
145 END IF;
146 EXECUTE format('ALTER ROLE %I PASSWORD %L',current_setting('lifeguide_provision.role_name'),current_setting('lifeguide_provision.role_password'));
147 EXCEPTION WHEN OTHERS THEN RAISE EXCEPTION 'Role credential provisioning failed' USING ERRCODE='P0001'; END $$`);
148 }
149 const db = ident(session.database);
150 await client.query(`REVOKE ALL ON DATABASE ${db} FROM PUBLIC`);
151 for (const name of Object.values(roles)) await client.query(`REVOKE ALL ON DATABASE ${db} FROM ${ident(name)}`);
152 await client.query(`GRANT CONNECT ON DATABASE ${db} TO ${Object.values(roles).map(ident).join(',')}`);
153 // pgcrypto is a trusted PG16 extension. CREATE applies only to this DB,
154 // never CREATEDB/CREATEROLE. Migrator owns the extension on a fresh restore.
155 await client.query(`GRANT CREATE ON DATABASE ${db} TO ${ident(roles.migrator)}`);
156 await client.query(`ALTER SCHEMA public OWNER TO ${ident(roles.migrator)}`);
157 await client.query('REVOKE ALL ON SCHEMA public FROM PUBLIC');
158 await client.query(`REVOKE ALL ON SCHEMA public FROM ${ident(roles.api)},${ident(roles.backup)}`);
159 await client.query(`GRANT USAGE ON SCHEMA public TO ${ident(roles.api)},${ident(roles.backup)}`);
160 for (const object of objects.tables) if (object.kind !== 'S' && object.owner !== roles.migrator) {
161 // ALTER TABLE also transfers its identity/serial sequences. PostgreSQL
162 // rejects independent OWNER changes on those linked sequences.
163 await client.query(`ALTER TABLE public.${ident(object.name)} OWNER TO ${ident(roles.migrator)}`);
164 }
165 for(const object of objects.tables) if(object.kind==='S') {
166 const current=(await client.query("SELECT pg_get_userbyid(relowner) owner FROM pg_class WHERE oid=$1::regclass",[`public.${object.name}`])).rows[0];
167 if(current.owner!==roles.migrator) throw new Error('Sequence ownership did not follow its application table; refusing automatic repair');
168 }
169 for (const object of objects.types) if (object.owner !== roles.migrator) await client.query(`ALTER TYPE public.${ident(object.name)} OWNER TO ${ident(roles.migrator)}`);
170 for (const object of objects.functions) if (object.owner !== roles.migrator) await client.query(`ALTER FUNCTION public.${object.name} OWNER TO ${ident(roles.migrator)}`);
171 await client.query(`ALTER ROLE ${ident(roles.api)} IN DATABASE ${db} SET search_path=pg_catalog,public,pg_temp`);
172 await client.query(`ALTER ROLE ${ident(roles.backup)} IN DATABASE ${db} SET search_path=pg_catalog,public,pg_temp`);
173 await client.query(`ALTER ROLE ${ident(roles.migrator)} IN DATABASE ${db} SET search_path=public,pg_catalog,pg_temp`);
174 // Global per-creator revocation removes PostgreSQL's default PUBLIC EXECUTE;
175 // a per-schema REVOKE alone cannot override that global default.
176 await client.query(`ALTER DEFAULT PRIVILEGES FOR ROLE ${ident(roles.migrator)} REVOKE EXECUTE ON FUNCTIONS FROM PUBLIC`);
177 await client.query(`ALTER DEFAULT PRIVILEGES FOR ROLE ${ident(roles.migrator)} IN SCHEMA public REVOKE INSERT,UPDATE,DELETE ON TABLES FROM ${ident(roles.api)}`);
178 await client.query(`ALTER DEFAULT PRIVILEGES FOR ROLE ${ident(roles.migrator)} IN SCHEMA public GRANT SELECT ON TABLES TO ${ident(roles.api)}`);
179 await client.query(`ALTER DEFAULT PRIVILEGES FOR ROLE ${ident(roles.migrator)} IN SCHEMA public GRANT SELECT ON TABLES TO ${ident(roles.backup)}`);
180 await client.query(`ALTER DEFAULT PRIVILEGES FOR ROLE ${ident(roles.migrator)} IN SCHEMA public GRANT USAGE,SELECT ON SEQUENCES TO ${ident(roles.api)}`);
181 await client.query(`ALTER DEFAULT PRIVILEGES FOR ROLE ${ident(roles.migrator)} IN SCHEMA public GRANT SELECT ON SEQUENCES TO ${ident(roles.backup)}`);
182 await grantUuidDefault(client,roles);
183 await client.query('COMMIT');
184 return { database: session.database, adopted: Boolean(adoptOwner), backupDigest };
185 } catch (error) { await client.query('ROLLBACK'); throw error; }
186 }
187
188 export async function reconcileGrants(client, env = process.env) {
189 const roles = validateRoles(env);
190 await client.query('BEGIN');
191 try {
192 await client.query("SELECT pg_advisory_xact_lock(hashtextextended('lifeguide_role_provision',0))");
193 const objects = await inventory(client);
194 if (Object.values(objects).flat().some((object) => object.owner !== roles.migrator || object.security_definer)) throw new Error('Grant reconciliation refuses non-migrator application ownership');
195 // Bootstrap runs this short-lived step so legacy pgcrypto PUBLIC grants are
196 // revoked as well, without modifying extension ownership or member objects.
197 await client.query('REVOKE ALL ON ALL TABLES IN SCHEMA public FROM PUBLIC');
198 await client.query('REVOKE ALL ON ALL SEQUENCES IN SCHEMA public FROM PUBLIC');
199 await client.query('REVOKE ALL ON ALL FUNCTIONS IN SCHEMA public FROM PUBLIC');
200 for (const role of [roles.api,roles.backup]) {
201 await client.query(`REVOKE ALL ON ALL TABLES IN SCHEMA public FROM ${ident(role)}`);
202 await client.query(`REVOKE ALL ON ALL SEQUENCES IN SCHEMA public FROM ${ident(role)}`);
203 await client.query(`REVOKE ALL ON ALL FUNCTIONS IN SCHEMA public FROM ${ident(role)}`);
204 }
205 for (const object of objects.tables) {
206 const relation = `public.${ident(object.name)}`;
207 if (object.kind === 'S') {
208 await client.query(`GRANT USAGE,SELECT ON SEQUENCE ${relation} TO ${ident(roles.api)}`);
209 await client.query(`GRANT SELECT ON SEQUENCE ${relation} TO ${ident(roles.backup)}`);
210 } else {
211 if (object.name !== 'schema_migration') {
212 const privileges = readOnlyCatalogTables.has(object.name) || !applicationTables.includes(object.name) ? 'SELECT' : 'SELECT,INSERT,UPDATE,DELETE';
213 await client.query(`GRANT ${privileges} ON TABLE ${relation} TO ${ident(roles.api)}`);
214 }
215 await client.query(`GRANT SELECT ON TABLE ${relation} TO ${ident(roles.backup)}`);
216 }
217 }
218 for (const object of objects.functions) if (applicationFunctions.includes(object.name)) await client.query(`GRANT EXECUTE ON FUNCTION public.${object.name} TO ${ident(roles.api)}`);
219 await grantUuidDefault(client,roles);
220 await client.query('COMMIT');
221 } catch (error) { await client.query('ROLLBACK'); throw error; }
222 }