LifeMate — Personal, Family & Learning Companion

fix/personal-upgrade-delivery-guard
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 139 lines 7 KB
Raw
1 // Build a one-time, QA-only copy of the baseline plus reviewed additive DDL.
2 // Existing provider-applied 0001..0020 bundles remain historical and unchanged.
3 // This script outputs SQL, does NOT connect to a DB and cannot deploy by itself.
4 // Crucially, original migration files / Compose role-provisioning stay unchanged.
5 import { readdir, readFile } from 'node:fs/promises';
6 import { createHash } from 'node:crypto';
7 import { fileURLToPath } from 'node:url';
8
9 const sourceRoot = new URL('../migrations/', import.meta.url);
10 const targetSchema = 'lifeguide_qa';
11 const digest = value => createHash('sha256').update(value, 'utf8').digest('hex');
12
13 function normalizeMigration(filename, source) {
14 let sql = source.trim();
15 const wrapped = /^begin\s*;/i.test(sql) && /commit\s*;$/i.test(sql);
16 if (/^begin\s*;/i.test(sql) !== /commit\s*;$/i.test(sql)) {
17 throw new Error(`unbalanced_migration_transaction:${filename}`);
18 }
19 if (wrapped) sql = sql.replace(/^begin\s*;/i, '').replace(/commit\s*;$/i, '');
20
21 // The host already provides pgcrypto; never change global extensions in QA.
22 const extension = /create\s+extension\s+if\s+not\s+exists\s+pgcrypto\s*;/ig;
23 const extCount = [...sql.matchAll(extension)].length;
24 if ((filename.startsWith('0001_') ? 1 : 0) !== extCount) {
25 throw new Error(`unexpected_pgcrypto_statement:${filename}`);
26 }
27 sql = sql.replace(extension, '-- pgcrypto already installed by Supabase (unchanged).');
28
29 // Original school guard functions pin public as search_path. Keep their SQL
30 // behaviour but make their QA copies refer exclusively to the private schema.
31 const oldFunctionPath = /set\s+search_path\s*=\s*public\s*,\s*pg_catalog/ig;
32 const n = [...sql.matchAll(oldFunctionPath)].length;
33 if (n !== (filename.startsWith('0019_') ? 5 : 0)) throw new Error(`unexpected_function_search_path:${filename}`);
34 sql = sql.replace(oldFunctionPath, `set search_path=${targetSchema},pg_catalog`);
35
36 // The additive auth migration removes PUBLIC access to its one metadata
37 // table. The QA wrapper below already revokes ALL tables for every client
38 // role. Allow only this exact restriction; arbitrary GRANT/REVOKE still fails.
39 if (filename === '0023_auth_ip_rate_limit.sql') {
40 sql = sql.replace(/^revoke all on auth_ip_rate_limit from public;$/m,
41 '-- Auth metadata is included in the QA wrapper table-wide lockdown.');
42 }
43 if (filename === '0024_child_device_safety.sql') {
44 sql = sql.replace(/^revoke all on managed_child,child_consent,child_device_invitation,guardian_invitation from public;$/m,
45 '-- Child identity tables are included in the QA wrapper lockdown.');
46 }
47 if (filename === '0026_personal_planner_series.sql') {
48 sql = sql.replace(/^revoke all on planner_series from public;$/m,
49 '-- Private planner series are included in the QA wrapper lockdown.');
50 }
51
52 // Fail closed if a future source migration changes its privilege/schema rules.
53 if (/\b(?:public|auth|storage|realtime)\s*\./i.test(sql) ||
54 /\b(?:create|alter|drop)\s+(?:role|database|schema|extension)\b/i.test(sql) ||
55 /\bsecurity\s+definer\b/i.test(sql) ||
56 /\b(?:grant|revoke|truncate)\s+(?:all|select|insert|update|delete|usage|execute|on|table|schema|function)\b/i.test(sql)) {
57 throw new Error(`source_migration_outside_private_qa:${filename}`);
58 }
59 return sql;
60 }
61
62 export async function buildSupabaseQaSql({ migrationsDir = sourceRoot } = {}) {
63 const entries = (await readdir(migrationsDir)).filter(name => /^\d{4}_[a-z0-9_]+\.sql$/.test(name)).sort();
64 const expected = [...Array.from({length:20}, (_,i) => String(i+1).padStart(4,'0')), '0023', '0024', '0025', '0026'];
65 if (entries.length !== expected.length ||
66 entries.some((name, i) => name.slice(0,4) !== expected[i]) ||
67 entries[20] !== '0023_auth_ip_rate_limit.sql' || entries[21] !== '0024_child_device_safety.sql' ||
68 entries[22] !== '0025_managed_guardian_authority.sql' || entries[23] !== '0026_personal_planner_series.sql') {
69 throw new Error('expected_baseline_and_auth_migrations_in_order');
70 }
71
72 const parts = [`begin;
73 set local lock_timeout='5s';
74 set local statement_timeout='120s';
75 set local search_path=lifeguide_qa,extensions,pg_catalog;
76 do $qa_preflight$
77 begin
78 if current_database() <> 'postgres'
79 or to_regnamespace('lifeguide_qa') is null
80 or to_regclass('lifeguide_qa.setup_probe') is null
81 or not exists (select 1 from pg_extension where extname='pgcrypto')
82 or has_schema_privilege('anon','lifeguide_qa','USAGE')
83 or has_schema_privilege('authenticated','lifeguide_qa','USAGE') then
84 raise exception 'lifeguide_qa_preflight_denied';
85 end if;
86 end
87 $qa_preflight$;
88
89 create table if not exists lifeguide_qa.schema_migration (
90 filename text primary key,
91 sha256 text not null check (sha256 ~ '^[a-f0-9]{64}$'),
92 applied_at timestamptz not null default now()
93 );`];
94 const manifest = [];
95 for (const filename of entries) {
96 const raw = await readFile(new URL(filename, migrationsDir), 'utf8');
97 const source = normalizeMigration(filename, raw);
98 const sha256 = digest(raw);
99 manifest.push({ filename, sha256 });
100 // The only interpolated source is the fixed, validated migration files.
101 parts.push(`-- Original migration ${filename}; source sha256 ${sha256}
102 ${source}
103 insert into lifeguide_qa.schema_migration(filename,sha256)
104 values ('${filename}','${sha256}');`);
105 }
106
107 parts.push(`
108 -- Supabase Data API and JWT roles have no direct access to these tables.
109 revoke all on schema lifeguide_qa from public, anon, authenticated, service_role;
110 revoke all on all tables in schema lifeguide_qa from public, anon, authenticated, service_role;
111 revoke all on all sequences in schema lifeguide_qa from public, anon, authenticated, service_role;
112 revoke all on all functions in schema lifeguide_qa from public, anon, authenticated, service_role;
113 alter default privileges in schema lifeguide_qa revoke all on tables from public,anon,authenticated,service_role;
114 alter default privileges in schema lifeguide_qa revoke all on sequences from public,anon,authenticated,service_role;
115 alter default privileges in schema lifeguide_qa revoke execute on functions from public,anon,authenticated,service_role;
116 do $qa_lockdown$
117 declare obj record;
118 begin
119 for obj in select c.relname
120 from pg_class c join pg_namespace n on n.oid=c.relnamespace
121 where n.nspname='lifeguide_qa' and c.relkind in ('r','p')
122 loop
123 execute format('alter table %I.%I enable row level security','lifeguide_qa',obj.relname);
124 execute format('alter table %I.%I force row level security','lifeguide_qa',obj.relname);
125 end loop;
126 end
127 $qa_lockdown$;
128 commit;`);
129
130 return { sql: parts.join('\n'), manifest };
131 }
132
133 // Utility for local review only; stdout may contain DDL but never credentials.
134 if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
135 const result = await buildSupabaseQaSql();
136 if (process.argv.includes('--manifest')) console.log(JSON.stringify(result.manifest,null,2));
137 else if (process.argv.includes('--sql')) process.stdout.write(result.sql);
138 else throw new Error('Specify --manifest or --sql; no database connection is ever made');
139 }