@davoodmehraban89 / LifeMate / commits / f27afbd
Fork 0

LifeMate — Personal, Family & Learning Companion

feat(qa): deterministic private Supabase copy of all 20 original migrations

davoodmehraban89 committed Oct 15, 2026 at 01:20 UTC f27afbde14d30f5a2be36e687fc1bbd9dd200a5e
1 file changed +119
backend/scripts/build-supabase-qa-sql.js new
+119
@@ -0,0 +1,119 @@
1 +// Build a one-time, QA-only copy of the existing 20 LifeGuide PostgreSQL migrations.
2 +// This script outputs SQL, does NOT connect to a DB and cannot deploy by itself.
3 +// Crucially, original migration files / Compose role-provisioning stay unchanged.
4 +import { readdir, readFile } from 'node:fs/promises';
5 +import { createHash } from 'node:crypto';
6 +import { fileURLToPath } from 'node:url';
7 +
8 +const sourceRoot = new URL('../migrations/', import.meta.url);
9 +const targetSchema = 'lifeguide_qa';
10 +const digest = value => createHash('sha256').update(value, 'utf8').digest('hex');
11 +
12 +function normalizeMigration(filename, source) {
13 + let sql = source.trim();
14 + const wrapped = /^begin\s*;/i.test(sql) && /commit\s*;$/i.test(sql);
15 + if (/^begin\s*;/i.test(sql) !== /commit\s*;$/i.test(sql)) {
16 + throw new Error(`unbalanced_migration_transaction:${filename}`);
17 + }
18 + if (wrapped) sql = sql.replace(/^begin\s*;/i, '').replace(/commit\s*;$/i, '');
19 +
20 + // The host already provides pgcrypto; never change global extensions in QA.
21 + const extension = /create\s+extension\s+if\s+not\s+exists\s+pgcrypto\s*;/ig;
22 + const extCount = [...sql.matchAll(extension)].length;
23 + if ((filename.startsWith('0001_') ? 1 : 0) !== extCount) {
24 + throw new Error(`unexpected_pgcrypto_statement:${filename}`);
25 + }
26 + sql = sql.replace(extension, '-- pgcrypto already installed by Supabase (unchanged).');
27 +
28 + // Original school guard functions pin public as search_path. Keep their SQL
29 + // behaviour but make their QA copies refer exclusively to the private schema.
30 + const oldFunctionPath = /set\s+search_path\s*=\s*public\s*,\s*pg_catalog/ig;
31 + const n = [...sql.matchAll(oldFunctionPath)].length;
32 + if (n !== (filename.startsWith('0019_') ? 5 : 0)) throw new Error(`unexpected_function_search_path:${filename}`);
33 + sql = sql.replace(oldFunctionPath, `set search_path=${targetSchema},pg_catalog`);
34 +
35 + // Fail closed if a future source migration changes its privilege/schema rules.
36 + if (/\b(?:public|auth|storage|realtime)\s*\./i.test(sql) ||
37 + /\b(?:create|alter|drop)\s+(?:role|database|schema|extension)\b/i.test(sql) ||
38 + /\bsecurity\s+definer\b/i.test(sql) ||
39 + /\b(?:grant|revoke|truncate)\s+(?:all|select|insert|update|delete|usage|execute|on|table|schema|function)\b/i.test(sql)) {
40 + throw new Error(`source_migration_outside_private_qa:${filename}`);
41 + }
42 + return sql;
43 +}
44 +
45 +export async function buildSupabaseQaSql({ migrationsDir = sourceRoot } = {}) {
46 + const entries = (await readdir(migrationsDir)).filter(name => /^\d{4}_[a-z0-9_]+\.sql$/.test(name)).sort();
47 + if (entries.length !== 20 || entries[0].slice(0,4) !== '0001' || entries.at(-1).slice(0,4) !== '0020' ||
48 + entries.some((name, i) => name.slice(0,4) !== String(i+1).padStart(4, '0'))) {
49 + throw new Error('expected_exactly_20_original_migrations_in_order');
50 + }
51 +
52 + const parts = [`begin;
53 +set local lock_timeout='5s';
54 +set local statement_timeout='120s';
55 +set local search_path=lifeguide_qa,extensions,pg_catalog;
56 +do $qa_preflight$
57 +begin
58 + if current_database() <> 'postgres'
59 + or to_regnamespace('lifeguide_qa') is null
60 + or to_regclass('lifeguide_qa.setup_probe') is null
61 + or not exists (select 1 from pg_extension where extname='pgcrypto')
62 + or has_schema_privilege('anon','lifeguide_qa','USAGE')
63 + or has_schema_privilege('authenticated','lifeguide_qa','USAGE') then
64 + raise exception 'lifeguide_qa_preflight_denied';
65 + end if;
66 +end
67 +$qa_preflight$;
68 +
69 +create table if not exists lifeguide_qa.schema_migration (
70 + filename text primary key,
71 + sha256 text not null check (sha256 ~ '^[a-f0-9]{64}$'),
72 + applied_at timestamptz not null default now()
73 +);`];
74 + const manifest = [];
75 + for (const filename of entries) {
76 + const raw = await readFile(new URL(filename, migrationsDir), 'utf8');
77 + const source = normalizeMigration(filename, raw);
78 + const sha256 = digest(raw);
79 + manifest.push({ filename, sha256 });
80 + // The only interpolated source is the fixed, validated migration files.
81 + parts.push(`-- Original migration ${filename}; source sha256 ${sha256}
82 +${source}
83 +insert into lifeguide_qa.schema_migration(filename,sha256)
84 +values ('${filename}','${sha256}');`);
85 + }
86 +
87 + parts.push(`
88 +-- Supabase Data API and JWT roles have no direct access to these tables.
89 +revoke all on schema lifeguide_qa from public, anon, authenticated, service_role;
90 +revoke all on all tables in schema lifeguide_qa from public, anon, authenticated, service_role;
91 +revoke all on all sequences in schema lifeguide_qa from public, anon, authenticated, service_role;
92 +revoke all on all functions in schema lifeguide_qa from public, anon, authenticated, service_role;
93 +alter default privileges in schema lifeguide_qa revoke all on tables from public,anon,authenticated,service_role;
94 +alter default privileges in schema lifeguide_qa revoke all on sequences from public,anon,authenticated,service_role;
95 +alter default privileges in schema lifeguide_qa revoke execute on functions from public,anon,authenticated,service_role;
96 +do $qa_lockdown$
97 +declare obj record;
98 +begin
99 + for obj in select c.relname
100 + from pg_class c join pg_namespace n on n.oid=c.relnamespace
101 + where n.nspname='lifeguide_qa' and c.relkind in ('r','p')
102 + loop
103 + execute format('alter table %I.%I enable row level security','lifeguide_qa',obj.relname);
104 + execute format('alter table %I.%I force row level security','lifeguide_qa',obj.relname);
105 + end loop;
106 +end
107 +$qa_lockdown$;
108 +commit;`);
109 +
110 + return { sql: parts.join('\n'), manifest };
111 +}
112 +
113 +// Utility for local review only; stdout may contain DDL but never credentials.
114 +if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
115 + const result = await buildSupabaseQaSql();
116 + if (process.argv.includes('--manifest')) console.log(JSON.stringify(result.manifest,null,2));
117 + else if (process.argv.includes('--sql')) process.stdout.write(result.sql);
118 + else throw new Error('Specify --manifest or --sql; no database connection is ever made');
119 +}