LifeMate — Personal, Family & Learning Companion

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