LifeMate — Personal, Family & Learning Companion

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