@davoodmehraban89 / Factor-easy / commits / 79f0476
Fork 0

سامانه صدور فاکتور و حسابداری

ci(security): block mass posted-to-draft SQL rewrites before financial migration review

davoodmehraban89 committed Nov 22, 2026 at 12:41 UTC 79f0476ffa01abbb9217d07972f1385ff84997a5
4 files changed +158
.github/workflows/quality.yml
+2
@@ -21,6 +21,8 @@ jobs:
21 package-manager-cache: false
22 - name: JavaScript syntax
23 run: node scripts/syntax-check.mjs
24 + - name: Block unsafe history-downgrade SQL migrations (synthetic diff tests)
25 + run: node --test scripts/accounting-history-migration-guard.test.mjs
26 - name: Draft conversion graph preflight (read-only)
27 run: node --test scripts/draft-conversion-plan.test.mjs
28 - name: Draft conversion inventory on isolated PostgreSQL
.github/workflows/security.yml
+5
@@ -19,12 +19,17 @@ jobs:
19 - uses: actions/checkout@v7
20 with:
21 persist-credentials: false
22 + fetch-depth: 0
23 - uses: actions/setup-node@v7
24 with:
25 node-version: '22'
26 package-manager-cache: false
27 - name: Verify release safety contracts
28 run: node scripts/release-safety-check.mjs
29 + - name: Block historical posted-to-draft SQL migration rewrites
30 + env:
31 + FINORA_MIGRATION_BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.before }}
32 + run: node scripts/accounting-history-migration-guard.mjs
33 codeql:
34 name: CodeQL JavaScript
35 runs-on: ubuntu-latest
scripts/accounting-history-migration-guard.mjs new
+71
@@ -0,0 +1,71 @@
1 +// Security/QA stop-merge tripwire for one destructive accounting migration pattern.
2 +// Diff-only and source-only; NEVER connects to a database or mutates records.
3 +// This heuristic does not replace SQL migration review or historical parity E2E.
4 +import {spawnSync} from 'node:child_process';
5 +import {pathToFileURL} from 'node:url';
6 +
7 +function withoutComments(sql) {
8 + return sql
9 + .replace(/\/\*[\s\S]*?\*\//g, m=>m.replace(/[^\r\n]/g,' '))
10 + .replace(/--[^\r\n]*/g, m=>' '.repeat(m.length));
11 +}
12 +
13 +export function findPostedToDraftRewrites(sql) {
14 + const text=withoutComments(sql);
15 + const results=[];
16 + // SQL storage is public.records JSONB. INSERT of a new draft is allowed;
17 + // rewriting existing records to draft requires a dedicated safety review.
18 + const updates=/\bUPDATE\s+(?:public\s*\.\s*)?records\b(?:\s+(?:AS\s+)?[a-z_][a-z_0-9]*)?\s+SET\b/gi;
19 + for(const match of text.matchAll(updates)){
20 + const tail=text.slice(match.index);
21 + const statement=tail.slice(0,tail.indexOf(';')===-1?tail.length:tail.indexOf(';'));
22 + const assignments=[
23 + /\b(?:status|documentStatus|accountingStatus)\s*=\s*'draft'/i,
24 + /['"](?:status|documentStatus|accountingStatus)['"]\s*,\s*['"]draft['"]/i,
25 + /'\{\s*(?:status|documentStatus|accountingStatus)\s*\}'\s*,\s*'(?:"draft"|draft)'/i
26 + ];
27 + if(assignments.some(p=>p.test(statement))){
28 + const line=1+text.slice(0,match.index).split('\n').length-1;
29 + results.push({line,reason:'UPDATE of existing public.records assigns accounting lifecycle draft; historical posted/reversed rows must be preserved'});
30 + }
31 + }
32 + return results;
33 +}
34 +
35 +function git(args,cwd=process.cwd()){
36 + const r=spawnSync('git',args,{cwd,encoding:'utf8',timeout:30000,maxBuffer:8*1024*1024});
37 + if(r.error||r.status!==0)throw Error('Git migration diff unavailable: '+(r.stderr||r.error?.message||'git exit '+r.status).trim());
38 + return r.stdout;
39 +}
40 +
41 +export function auditMigrationDiff({base='HEAD^',head='HEAD',cwd=process.cwd()}={}){
42 + const refs=/^(?:[a-fA-F0-9]{40}|HEAD(?:\^|~1)?)$/;
43 + if(!refs.test(base)||!refs.test(head))throw Error('Invalid migration compare SHA');
44 + const names=git(['diff','--no-renames','--name-only','--diff-filter=AM',base,head,'--','supabase/migrations'],cwd);
45 + const violations=[];
46 + let inspected=0;
47 + for(const path of names.split('\n').filter(Boolean)){
48 + if(!/^supabase\/migrations\/[a-zA-Z0-9_.-]+\.sql$/.test(path))
49 + throw Error('Unexpected migration path from Git diff');
50 + const sql=git(['show',head+':'+path],cwd);
51 + inspected++;
52 + for(const finding of findPostedToDraftRewrites(sql))violations.push({file:path,...finding});
53 + }
54 + return {inspected,violations};
55 +}
56 +
57 +if(process.argv[1]&&import.meta.url===pathToFileURL(process.argv[1]).href){
58 + try{
59 + const input=process.env.FINORA_MIGRATION_BASE_SHA||'';
60 + const base=input&&!/^0+$/.test(input)?input:'HEAD^';
61 + const report=auditMigrationDiff({base});
62 + if(report.violations.length){
63 + for(const v of report.violations)
64 + console.error('FINORA_POSTED_HISTORY_DOWNGRADE_BLOCKED '+v.file+':'+v.line+' '+v.reason);
65 + console.error('STOP MERGE: preserve historical posted/reversed records and reversal links; use owner-approved non-destructive migration and isolated historic parity tests.');
66 + process.exitCode=1;
67 + }else{
68 + console.log('FINORA_POSTED_HISTORY_MIGRATION_TRIPWIRE_PASS: '+report.inspected+' changed migration file(s) scanned; heuristic only, SQL review required.');
69 + }
70 + }catch(error){console.error('FINORA_MIGRATION_GUARD_UNVERIFIED: '+error.message);process.exitCode=1;}
71 +}
scripts/accounting-history-migration-guard.test.mjs new
+80
@@ -0,0 +1,80 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import {mkdtempSync,mkdirSync,writeFileSync,rmSync} from 'node:fs';
4 +import {tmpdir} from 'node:os';
5 +import {join} from 'node:path';
6 +import {fileURLToPath} from 'node:url';
7 +import {spawnSync} from 'node:child_process';
8 +import {findPostedToDraftRewrites,auditMigrationDiff} from './accounting-history-migration-guard.mjs';
9 +
10 +const dangerous219=String.raw`
11 +DO $$
12 +BEGIN
13 + UPDATE public.records
14 + SET data=(data-'postedAt'-'postedBy'-'reversalVoucherId'-'reversedAt')
15 + ||jsonb_build_object('status','draft','documentStatus','draft','accountingStatus','draft'),
16 + version=version+1
17 + WHERE organization_id=r.organization_id AND collection='journalVouchers' AND id=r.id;
18 +END $$;
19 +`;
20 +const dangerous217=String.raw`
21 +UPDATE public.records
22 + SET data=CASE WHEN collection='journalVouchers' THEN
23 + (data||jsonb_build_object('status','draft','lifecycleMigrationOriginalStatus',v_status)
24 + -'postedAt'-'postedBy') ELSE
25 + (data||jsonb_build_object('documentStatus','draft','accountingStatus','draft')) END
26 + WHERE organization_id=r.organization_id AND collection=r.collection AND id=r.id;
27 +`;
28 +
29 +test('rejects PR217/219-shaped blanket historical posted → draft rewrites',()=>{
30 + assert.equal(findPostedToDraftRewrites(dangerous219).length,1);
31 + assert.equal(findPostedToDraftRewrites(dangerous217).length,1);
32 + assert.equal(findPostedToDraftRewrites("UPDATE public.records SET data=jsonb_set(data,'{documentStatus}','\"draft\"') WHERE id='X';").length,1);
33 +});
34 +
35 +test('does not block new draft INSERT, unrelated updates or commented example SQL',()=>{
36 + const source=[
37 + "-- UPDATE public.records SET data=jsonb_build_object('status','draft');",
38 + "/* UPDATE public.records SET data=jsonb_build_object('status','draft'); */",
39 + "INSERT INTO public.records(organization_id,collection,id,data) VALUES ('o','journalVouchers','v',jsonb_build_object('status','draft'));",
40 + "UPDATE public.records SET data=jsonb_set(data,'{updatedAt}',to_jsonb(now())) WHERE id='DRAFT';"
41 + ].join('\n');
42 + assert.deepEqual(findPostedToDraftRewrites(source),[]);
43 +});
44 +
45 +test('only scans added/modified SQL migrations in base-to-head commit diff; blocks unsafe new SQL',()=>{
46 + const dir=mkdtempSync(join(tmpdir(),'finora-migration-tripwire-'));
47 + const run=(args,env={})=>{
48 + const r=spawnSync('git',args,{cwd:dir,encoding:'utf8',timeout:15000,env:{...process.env,...env}});
49 + assert.equal(r.status,0,r.stderr||r.error?.message);
50 + return r.stdout.trim();
51 + };
52 + const cli=fileURLToPath(new URL('./accounting-history-migration-guard.mjs',import.meta.url));
53 + try{
54 + mkdirSync(join(dir,'supabase','migrations'),{recursive:true});
55 + run(['init','-q']);
56 + run(['config','user.email','qa@example.invalid']);
57 + run(['config','user.name','Finora QA']);
58 + writeFileSync(join(dir,'supabase','migrations','000_safe.sql'),"INSERT INTO public.records(collection,id,data) VALUES ('journalVouchers','J',jsonb_build_object('status','draft'));");
59 + run(['add','.']);run(['commit','-qm','safe base']);
60 + const base=run(['rev-parse','HEAD']);
61 + writeFileSync(join(dir,'supabase','migrations','001_bad.sql'),dangerous219);
62 + run(['add','.']);run(['commit','-qm','dangerous migration']);
63 + let x=auditMigrationDiff({base,cwd:dir});
64 + assert.equal(x.inspected,1);assert.equal(x.violations.length,1);
65 + assert.equal(x.violations[0].file,'supabase/migrations/001_bad.sql');
66 + const rejected=spawnSync(process.execPath,[cli],{cwd:dir,encoding:'utf8',
67 + env:{...process.env,FINORA_MIGRATION_BASE_SHA:base}});
68 + assert.equal(rejected.status,1);
69 + assert.match(rejected.stderr,/FINORA_POSTED_HISTORY_DOWNGRADE_BLOCKED/);
70 + writeFileSync(join(dir,'supabase','migrations','001_bad.sql'),
71 + "UPDATE public.records SET updated_at=now() WHERE collection='journalVouchers';");
72 + run(['add','.']);run(['commit','-qm','remove unsafe mutation']);
73 + x=auditMigrationDiff({base,cwd:dir});
74 + assert.equal(x.inspected,1);assert.equal(x.violations.length,0);
75 + const accepted=spawnSync(process.execPath,[cli],{cwd:dir,encoding:'utf8',
76 + env:{...process.env,FINORA_MIGRATION_BASE_SHA:base}});
77 + assert.equal(accepted.status,0,accepted.stderr);
78 + assert.match(accepted.stdout,/FINORA_POSTED_HISTORY_MIGRATION_TRIPWIRE_PASS/);
79 + }finally{rmSync(dir,{recursive:true,force:true});}
80 +});