LifeMate — Personal, Family & Learning Companion

design/mobile-navigation-review
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 135 lines 6.74 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
48 // Fail closed if a future source migration changes its privilege/schema rules.
49 if (/\b(?:public|auth|storage|realtime)\s*\./i.test(sql) ||
50 /\b(?:create|alter|drop)\s+(?:role|database|schema|extension)\b/i.test(sql) ||
51 /\bsecurity\s+definer\b/i.test(sql) ||
52 /\b(?:grant|revoke|truncate)\s+(?:all|select|insert|update|delete|usage|execute|on|table|schema|function)\b/i.test(sql)) {
53 throw new Error(`source_migration_outside_private_qa:${filename}`);
54 }
55 return sql;
56 }
57
58 export async function buildSupabaseQaSql({ migrationsDir = sourceRoot } = {}) {
59 const entries = (await readdir(migrationsDir)).filter(name => /^\d{4}_[a-z0-9_]+\.sql$/.test(name)).sort();
60 const expected = [...Array.from({length:20}, (_,i) => String(i+1).padStart(4,'0')), '0023', '0024', '0025'];
61 if (entries.length !== expected.length ||
62 entries.some((name, i) => name.slice(0,4) !== expected[i]) ||
63 entries[20] !== '0023_auth_ip_rate_limit.sql' || entries[21] !== '0024_child_device_safety.sql' ||
64 entries[22] !== '0025_managed_guardian_authority.sql') {
65 throw new Error('expected_baseline_and_auth_migrations_in_order');
66 }
67
68 const parts = [`begin;
69 set local lock_timeout='5s';
70 set local statement_timeout='120s';
71 set local search_path=lifeguide_qa,extensions,pg_catalog;
72 do $qa_preflight$
73 begin
74 if current_database() <> 'postgres'
75 or to_regnamespace('lifeguide_qa') is null
76 or to_regclass('lifeguide_qa.setup_probe') is null
77 or not exists (select 1 from pg_extension where extname='pgcrypto')
78 or has_schema_privilege('anon','lifeguide_qa','USAGE')
79 or has_schema_privilege('authenticated','lifeguide_qa','USAGE') then
80 raise exception 'lifeguide_qa_preflight_denied';
81 end if;
82 end
83 $qa_preflight$;
84
85 create table if not exists lifeguide_qa.schema_migration (
86 filename text primary key,
87 sha256 text not null check (sha256 ~ '^[a-f0-9]{64}$'),
88 applied_at timestamptz not null default now()
89 );`];
90 const manifest = [];
91 for (const filename of entries) {
92 const raw = await readFile(new URL(filename, migrationsDir), 'utf8');
93 const source = normalizeMigration(filename, raw);
94 const sha256 = digest(raw);
95 manifest.push({ filename, sha256 });
96 // The only interpolated source is the fixed, validated migration files.
97 parts.push(`-- Original migration ${filename}; source sha256 ${sha256}
98 ${source}
99 insert into lifeguide_qa.schema_migration(filename,sha256)
100 values ('${filename}','${sha256}');`);
101 }
102
103 parts.push(`
104 -- Supabase Data API and JWT roles have no direct access to these tables.
105 revoke all on schema lifeguide_qa from public, anon, authenticated, service_role;
106 revoke all on all tables in schema lifeguide_qa from public, anon, authenticated, service_role;
107 revoke all on all sequences in schema lifeguide_qa from public, anon, authenticated, service_role;
108 revoke all on all functions in schema lifeguide_qa from public, anon, authenticated, service_role;
109 alter default privileges in schema lifeguide_qa revoke all on tables from public,anon,authenticated,service_role;
110 alter default privileges in schema lifeguide_qa revoke all on sequences from public,anon,authenticated,service_role;
111 alter default privileges in schema lifeguide_qa revoke execute on functions from public,anon,authenticated,service_role;
112 do $qa_lockdown$
113 declare obj record;
114 begin
115 for obj in select c.relname
116 from pg_class c join pg_namespace n on n.oid=c.relnamespace
117 where n.nspname='lifeguide_qa' and c.relkind in ('r','p')
118 loop
119 execute format('alter table %I.%I enable row level security','lifeguide_qa',obj.relname);
120 execute format('alter table %I.%I force row level security','lifeguide_qa',obj.relname);
121 end loop;
122 end
123 $qa_lockdown$;
124 commit;`);
125
126 return { sql: parts.join('\n'), manifest };
127 }
128
129 // Utility for local review only; stdout may contain DDL but never credentials.
130 if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
131 const result = await buildSupabaseQaSql();
132 if (process.argv.includes('--manifest')) console.log(JSON.stringify(result.manifest,null,2));
133 else if (process.argv.includes('--sql')) process.stdout.write(result.sql);
134 else throw new Error('Specify --manifest or --sql; no database connection is ever made');
135 }