LifeMate — Personal, Family & Learning Companion

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