@davoodmehraban89 / Factor-easy / commits / 74f6521
Fork 0

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

Wave 0/1: gated Pages, public QA hardening, legacy request guard

Verified PR checks: Quality run 36931616093 (static-quality, C8 DB, D1/Wave1 DB all success; Real DOM 35/35) and Security run 36931616057 required jobs success (Release/QA invariants + CodeQL). Dependency review remains separately blocked by disabled Dependency graph.

davoodmehraban89 committed Oct 2, 2026 at 01:25 UTC 74f6521fe53da145706feeeb15dca7036e992feb
11 files changed +400 -53
.github/workflows/pages.yml new
+56
@@ -0,0 +1,56 @@
1 +name: Deploy gated Pages
2 +
3 +on:
4 + workflow_run:
5 + workflows: ["Release gate"]
6 + types: [completed]
7 +
8 +permissions:
9 + contents: read
10 + pages: write
11 + id-token: write
12 + actions: read
13 +
14 +concurrency:
15 + group: pages-production
16 + cancel-in-progress: false
17 +
18 +jobs:
19 + deploy:
20 + name: Deploy exact gated SHA
21 + if: >-
22 + github.event.workflow_run.conclusion == 'success' &&
23 + github.event.workflow_run.head_branch == 'main'
24 + runs-on: ubuntu-latest
25 + environment:
26 + name: github-pages
27 + url: ${{ steps.deployment.outputs.page_url }}
28 + steps:
29 + - name: Checkout exact gated SHA
30 + uses: actions/checkout@v7
31 + with:
32 + ref: ${{ github.event.workflow_run.head_sha }}
33 + persist-credentials: false
34 + - name: Reconfirm exact release-gate job
35 + env:
36 + GH_TOKEN: ${{ github.token }}
37 + REPO: ${{ github.repository }}
38 + RUN_ID: ${{ github.event.workflow_run.id }}
39 + HEAD_SHA: ${{ github.event.workflow_run.head_sha }}
40 + run: |
41 + set -euo pipefail
42 + run_sha="$(gh api "repos/$REPO/actions/runs/$RUN_ID" --jq '.head_sha')"
43 + test "$run_sha" = "$HEAD_SHA" || { echo '::error::Release-gate SHA mismatch'; exit 1; }
44 + conclusion="$(gh api "repos/$REPO/actions/runs/$RUN_ID/jobs?per_page=100" --jq '[.jobs[] | select(.name == "Exact SHA promotion gate")] | last | .conclusion // empty')"
45 + test "$conclusion" = success || { echo '::error::Exact SHA promotion gate is not successful'; exit 1; }
46 + - name: Build bounded hardened site
47 + run: node scripts/build-pages.mjs
48 + - name: Configure Pages
49 + uses: actions/configure-pages@v5
50 + - name: Upload Pages artifact
51 + uses: actions/upload-pages-artifact@v4
52 + with:
53 + path: _site
54 + - name: Deploy to GitHub Pages
55 + id: deployment
56 + uses: actions/deploy-pages@v4
.github/workflows/quality.yml
+6 -2
@@ -85,7 +85,7 @@ jobs:
85 - name: Real DOM smoke
86 run: |
87 python3 -m http.server 4173 >/tmp/finora-http.log 2>&1 &
88 - npx playwright test scripts/dom-smoke.spec.js scripts/platform-office.spec.js scripts/enterprise-license.spec.js scripts/enterprise-role.spec.js scripts/enterprise-invitation.spec.js scripts/enterprise-org-ux.spec.js scripts/office-slice-c1.spec.js scripts/office-slice-c2.spec.js scripts/office-slice-c3.spec.js scripts/office-slice-c4.spec.js scripts/office-slice-c5.spec.js scripts/office-slice-c6.spec.js scripts/office-slice-c7.spec.js scripts/office-slice-c8.spec.js scripts/office-slice-c8-runtime.spec.js scripts/request-workflow-d2.spec.js scripts/request-workflow-d3b.spec.js scripts/request-workflow-d3c.spec.js scripts/taxpayer-print.spec.js --reporter=line --workers=1
88 + npx playwright test scripts/dom-smoke.spec.js scripts/platform-office.spec.js scripts/enterprise-license.spec.js scripts/enterprise-role.spec.js scripts/enterprise-invitation.spec.js scripts/enterprise-org-ux.spec.js scripts/office-slice-c1.spec.js scripts/office-slice-c2.spec.js scripts/office-slice-c3.spec.js scripts/office-slice-c4.spec.js scripts/office-slice-c5.spec.js scripts/office-slice-c6.spec.js scripts/office-slice-c7.spec.js scripts/office-slice-c8.spec.js scripts/office-slice-c8-runtime.spec.js scripts/request-workflow-d2.spec.js scripts/request-workflow-d3b.spec.js scripts/request-workflow-d3c.spec.js scripts/taxpayer-print.spec.js scripts/pages-artifact.spec.js --reporter=line --workers=1
89
90 c8-policy-database:
91 runs-on: ubuntu-latest
@@ -180,6 +180,10 @@ jobs:
180 run: psql -v ON_ERROR_STOP=1 -f supabase/migrations/20261001230000_request_workflow_d3a_step_runtime.sql
181 - name: Execute D3a sequential and parallel workflow assertions
182 run: psql -v ON_ERROR_STOP=1 -f supabase/tests/request_d3a_workflow_behavior.sql
183 + - name: Apply Wave 1 legacy transition guard
184 + run: psql -v ON_ERROR_STOP=1 -f supabase/migrations/20261002010000_request_wave1_legacy_transition_guard.sql
185 + - name: Execute Wave 1 adversarial legacy transition assertions
186 + run: psql -v ON_ERROR_STOP=1 -f supabase/tests/request_wave1_legacy_transition_security.sql
187 - name: Apply D3b conditions and timeline
188 run: psql -v ON_ERROR_STOP=1 -f supabase/migrations/20261001233000_request_workflow_d3b_conditions_timeline.sql
189 - name: Execute D3b condition and timeline assertions
@@ -189,4 +193,4 @@ jobs:
193 - name: Apply D3c escalation idempotency fix
194 run: psql -v ON_ERROR_STOP=1 -f supabase/migrations/20261002000500_request_workflow_d3c_escalation_conflict_fix.sql
195 - name: Execute D3c operational assertions
192 - run: psql -v ON_ERROR_STOP=1 -f supabase/tests/request_d3c_operations.sql
196 + run: psql -v ON_ERROR_STOP=1 -f supabase/tests/request_d3c_operations.sql
\ No newline at end of file
PROJECT_STATE.md
+1
@@ -14,6 +14,7 @@ This is high-assurance accounting/ERP software. Posted financial history, tenant
14 ## Current change ledger
15 | Date | Request / decision | Status | Evidence / next action |
16 |---|---|---|---|
17 +| 2026-10-02 | Owner completed the GitHub `Protect main` ruleset and directed autonomous continuation to fully remediate the audited defects. | **IN PROGRESS — REMEDIATION CONTINUATION** | Live ruleset `24334764` verified ACTIVE on the default branch with deletion + non-fast-forward protection, PR-only updates, strict required checks `static-quality`, `Release and QA safety invariants`, and `CodeQL JavaScript`; bypass list empty. First bounded slice: reconcile/fix public Live QA findings and close remaining Wave 0 deployment gate evidence, then Wave 1 F-409/F-410. |
18 | 2026-10-01 | Owner authorized starting the canonical remediation pack after external full-system audit. | **WAVE 0 CODE-SIDE VERIFIED / ADMIN DEPLOY GATE OPEN** | F-406/F-423/F-424 code contracts hardened; dependency review fail-open removed; exact-SHA Quality+Security+DB promotion evidence added. F-402/F-403/F-407 remain OPEN because Pages still deploys from unprotected main before CI and repository-admin mutation is unavailable in the connected GitHub tool. |
19 | 2026-10-01 | Owner said «ادامه بده» after D3a handoff. | **D3B + D3C VERIFIED** | D3b visual editor/conditions/timeline and D3c SLA/delegation/outbox are production + disposable-DB + real-DOM verified. Remediation audit supersedes roadmap ordering: Wave 0 then Wave 1 before D4. |
20 | 2026-10-01 | Slice D3c — SLA/escalation, delegation/substitution, transactional outbox. | **IMPLEMENTED / PRODUCTION + DISPOSABLE-DB + REAL-DOM + CI VERIFIED** | `js/request-workflow-d3c.js`; migrations `20261001235500`, `20261002000500`, `20261002001000`; Quality run `36917772952` all three jobs SUCCESS. Evidence: `docs/REQUEST_WORKFLOW_D3C_VERIFICATION.md`. |
diag.html deleted
-47
@@ -1,47 +0,0 @@
1 -<!DOCTYPE html>
2 -<html lang="fa" dir="rtl"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
3 -<title>تشخیص اتصال فینورا</title>
4 -<style>body{font-family:system-ui,Tahoma,sans-serif;padding:16px;max-width:680px;margin:auto;line-height:1.9}
5 -.ok{color:#059669;font-weight:bold}.bad{color:#dc2626;font-weight:bold}.box{border:1px solid #cbd5e1;border-radius:10px;padding:10px;margin:10px 0}
6 -pre{background:#f1f5f9;padding:10px;border-radius:8px;white-space:pre-wrap;direction:ltr;text-align:left;font-size:12px}
7 -button{padding:12px 18px;font-size:16px;border-radius:10px;border:0;background:#2563eb;color:#fff}</style></head>
8 -<body>
9 -<h2>تشخیص اتصال به سرور فینورا</h2>
10 -<p>این صفحه فقط ۳ درخواست بی‌خطر می‌فرستد و هیچ داده‌ای نمی‌سازد. VPN را روشن کن و دکمه را بزن.</p>
11 -<button id="go">شروع آزمایش</button>
12 -<div id="out"></div>
13 -<pre id="rep"></pre>
14 -<script>
15 -const U='https://hcsixhqbyuhpshfwqpjx.supabase.co';
16 -const K='sb_publishable_2y8IsGdhqeLDPkEp7mBF4w_X4yji16D';
17 -const out=document.getElementById('out'),rep=document.getElementById('rep');
18 -let lines=[];
19 -function row(title,ok,detail){
20 - out.insertAdjacentHTML('beforeend','<div class="box"><span class="'+(ok?'ok':'bad')+'">'+(ok?'✔ ':'✘ ')+title+'</span></div>');
21 - lines.push((ok?'OK ':'FAIL ')+title+' :: '+detail);rep.textContent=lines.join('\n');
22 -}
23 -async function t(name,fn){
24 - const s=performance.now();
25 - try{const d=await fn();row(name,true,d+' ('+Math.round(performance.now()-s)+'ms)');return true;}
26 - catch(e){row(name,false,(e&&e.name)+': '+(e&&e.message)+' ('+Math.round(performance.now()-s)+'ms)');return false;}
27 -}
28 -document.getElementById('go').onclick=async()=>{
29 - out.innerHTML='';lines=[];
30 - lines.push('UA: '+navigator.userAgent);lines.push('online: '+navigator.onLine);lines.push('time: '+new Date().toISOString());rep.textContent=lines.join('\n');
31 - const a=await t('۱) رسیدن به سرور (TCP/TLS)',async()=>{await fetch(U+'/auth/v1/health',{mode:'no-cors',cache:'no-store'});return 'reachable';});
32 - const b=await t('۲) درخواست مرورگری با کلید (CORS)',async()=>{
33 - const r=await fetch(U+'/auth/v1/settings',{headers:{apikey:K},cache:'no-store'});const j=await r.json();
34 - return 'status '+r.status+' disable_signup='+j.disable_signup+' mailer_autoconfirm='+j.mailer_autoconfirm+' email_provider='+(j.external&&j.external.email);});
35 - const c=await t('۳) درخواست POST مثل ثبت‌نام (بدون ساخت کاربر)',async()=>{
36 - const r=await fetch(U+'/auth/v1/signup',{method:'POST',headers:{apikey:K,'Content-Type':'application/json'},body:'{}'});
37 - const x=await r.text();return 'status '+r.status+' body='+x.slice(0,160);});
38 - let msg='';
39 - if(!a)msg='به خود سرور نمی‌رسد: مشکل شبکه/VPN/فیلترینگ است، نه کد فینورا.';
40 - else if(!b)msg='سرور در دسترس است ولی درخواست مرورگری با کلید مسدود می‌شود (VPN، افزونه/مسدودکننده یا شبکه).';
41 - else if(!c)msg='خواندن کار می‌کند ولی POST مسدود می‌شود؛ احتمالاً فیلتر شبکه یا VPN.';
42 - else msg='شبکه سالم است. مشکل در کد یا تنظیمات است؛ متن گزارش زیر را برای من بفرست.';
43 - out.insertAdjacentHTML('beforeend','<div class="box"><b>نتیجه:</b> '+msg+'</div>');
44 - lines.push('VERDICT: '+msg);rep.textContent=lines.join('\n');
45 -};
46 -</script></body></html>
47 -
js/money-format.js
+8 -4
@@ -1,12 +1,16 @@
1 // ============== فرمت سه رقمی اعداد هنگام تایپ (قیمت‌ها و مبالغ) ==============
2 function toEnglishDigitsMoney(str){
3 if(str===null||str===undefined)return '';
4 - const map={'۰':'0','۱':'1','۲':'2','۳':'3','۴':'4','۵':'5','۶':'6','۷':'7','۸':'8','۹':'9'};
5 - return String(str).replace(/[۰-۹]/g,d=>map[d]);
4 + const fa={'۰':'0','۱':'1','۲':'2','۳':'3','۴':'4','۵':'5','۶':'6','۷':'7','۸':'8','۹':'9'};
5 + const ar={'٠':'0','١':'1','٢':'2','٣':'3','٤':'4','٥':'5','٦':'6','٧':'7','٨':'8','٩':'9'};
6 + return String(str).replace(/[۰-۹]/g,d=>fa[d]).replace(/[٠-٩]/g,d=>ar[d]);
7 }
8 function parseFormattedNumber(v){
9 if(v===null||v===undefined||v==='')return 0;
9 - const cleaned=toEnglishDigitsMoney(String(v)).replace(/[^0-9.\-]/g,'');
10 + const normalized=toEnglishDigitsMoney(String(v))
11 + .replace(/[٬،,\u00A0\u202F\s]/g,'')
12 + .replace(/[٫]/g,'.');
13 + const cleaned=normalized.replace(/[^0-9.\-]/g,'');
14 const n=parseFloat(cleaned);
15 return isNaN(n)?0:n;
16 }
@@ -14,7 +18,7 @@ function handleMoneyInput(el){
18 if(!el)return;
19 const caretFromEnd=el.value.length-(el.selectionStart||el.value.length);
20 const raw=parseFormattedNumber(el.value);
17 - const hasDigit=/[0-9۰-۹]/.test(el.value);
21 + const hasDigit=/[0-9۰-۹٠-٩]/.test(el.value);
22 const formatted=(!hasDigit)?'':raw.toLocaleString('en-US');
23 el.value=formatted;
24 const pos=Math.max(0,el.value.length-caretFromEnd);
scripts/build-pages.mjs new
+71
@@ -0,0 +1,71 @@
1 +import fs from 'node:fs';
2 +import path from 'node:path';
3 +
4 +const root=process.cwd();
5 +const out=path.join(root,'_site');
6 +fs.rmSync(out,{recursive:true,force:true});
7 +fs.mkdirSync(out,{recursive:true});
8 +
9 +for(const name of ['manifest.json','CNAME']){
10 + const src=path.join(root,name);
11 + if(fs.existsSync(src))fs.copyFileSync(src,path.join(out,name));
12 +}
13 +for(const dir of ['js','vendor'])fs.cpSync(path.join(root,dir),path.join(out,dir),{recursive:true});
14 +
15 +const simpleCall=/^\s*(?:return\s+)?(?:window\.)?[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*\s*\([^;]*\)\s*;?\s*$/;
16 +const builderExpression=/^'\+[A-Za-z_$][\w$]*\+'$/;
17 +const assignmentBuilder=/^[A-Za-z_$][\w$]*\['\+[A-Za-z_$][\w$]*\+'\]\.[A-Za-z_$][\w$]*=this\.(?:value|checked)$/;
18 +const simpleSequence=text=>text.split(';').map(x=>x.trim()).filter(Boolean).every(x=>simpleCall.test(x)||/^return\s+(?:false|true)$/.test(x));
19 +let dynamicHandlers=0;
20 +for(const name of fs.readdirSync(path.join(out,'js'))){
21 + if(!name.endsWith('.js'))continue;
22 + const file=path.join(out,'js',name);
23 + let source=fs.readFileSync(file,'utf8');
24 + source=source.replace(/\s(on[a-z]+)="([^"]*)"/gi,(_,attr,body)=>{
25 + const event=attr.slice(2).toLowerCase();
26 + const decoded=body.replace(/&quot;/g,'"').replace(/&#39;|&apos;/g,"'").replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&amp;/g,'&');
27 + if(!simpleSequence(decoded)&&!builderExpression.test(decoded)&&!assignmentBuilder.test(decoded))throw new Error(`Unsupported dynamic inline handler in ${name}: ${decoded}`);
28 + dynamicHandlers++;
29 + return ` data-finora-dynamic-${event}="${body}"`;
30 + });
31 + source=source
32 + .replace(/getAttribute\((['"])onclick\1\)/g,"getAttribute('data-finora-dynamic-click')")
33 + .replace(/\[onclick\^=/g,'[data-finora-dynamic-click^=')
34 + .replace(/\[onclick\*=/g,'[data-finora-dynamic-click*=');
35 + fs.writeFileSync(file,source);
36 +}
37 +
38 +let html=fs.readFileSync(path.join(root,'index.html'),'utf8');
39 +const handlers=[];
40 +html=html.replace(/\s(on[a-z]+)="([^"]*)"/gi,(_,attr,body)=>{
41 + const event=attr.slice(2).toLowerCase();
42 + const id=handlers.length;
43 + const decoded=body.replace(/&quot;/g,'"').replace(/&#39;|&apos;/g,"'").replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&amp;/g,'&');
44 + handlers.push({id,event,body:decoded});
45 + return ` data-finora-handler-${id}="${event}"`;
46 +});
47 +
48 +html=html.replace(
49 + /<script\s+src="https:\/\/cdn\.jsdelivr\.net\/npm\/xlsx@0\.18\.5\/dist\/xlsx\.full\.min\.js"><\/script>/i,
50 + '<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js" integrity="sha512-r22gChDnGvBylk90+2e/ycr3RVrDi8DIOkIGNhJlKfuyQM4tIRAI062MaV8sfjQKYVGjOBaZBOA87z+IhZE9DA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>'
51 +);
52 +html=html.replace(/script-src[^;]*/i,"script-src 'self' https://cdnjs.cloudflare.com");
53 +// frame-ancestors is ignored in meta-delivered CSP and generates a browser error;
54 +// clickjacking protection must be supplied as an HTTP response header by the edge/host.
55 +html=html.replace(/;\s*frame-ancestors 'none'/i,'');
56 +html=html.replace('</body>','<script src="js/generated-event-handlers.js"></script>\n<script src="js/generated-dynamic-handlers.js"></script>\n</body>');
57 +
58 +const generated=`// Generated at build time from legacy static inline event attributes.\n(function(){\n${handlers.map(({id,event,body})=>` {\n const el=document.querySelector('[data-finora-handler-${id}]');\n if(el)el.addEventListener(${JSON.stringify(event)},function(event){\n const result=(function(event){${body}}).call(this,event);\n if(result===false){event.preventDefault();event.stopPropagation();}\n });\n }`).join('\n')}\n})();\n`;
59 +
60 +const dynamic=`// CSP-safe dispatcher for simple handlers emitted by runtime renderers.\n(function(){\n const events=['click','change','input','submit','blur','focus','keydown','keyup'];\n function split(text,separator){\n const out=[];let cur='',quote='',escape=false;\n for(const ch of text){\n if(escape){cur+=ch;escape=false;continue;}\n if(ch==='\\\\'){cur+=ch;escape=true;continue;}\n if(quote){cur+=ch;if(ch===quote)quote='';continue;}\n if(ch==='\\"'||ch==="'"){quote=ch;cur+=ch;continue;}\n if(ch===separator){if(cur.trim())out.push(cur.trim());cur='';continue;}\n cur+=ch;\n }\n if(cur.trim())out.push(cur.trim());\n return out;\n }\n function arg(token,el,event){\n if(token==='')return undefined;\n if((token[0]==="'"&&token.at(-1)==="'")||(token[0]==='\\"'&&token.at(-1)==='\\"'))return token.slice(1,-1).replace(/\\\\(['\\"\\\\])/g,'$1');\n if(token==='this')return el;if(token==='event')return event;if(token==='this.value')return el.value;if(token==='this.checked')return el.checked;if(token==='event.target.value')return event.target?.value;\n if(token==='true')return true;if(token==='false')return false;if(token==='null')return null;if(token==='undefined')return undefined;\n if(/^-?\\d+(?:\\.\\d+)?$/.test(token))return Number(token);\n throw new Error('Unsupported CSP-safe handler argument: '+token);\n }\n function invokeOne(statement,el,event){\n const raw=String(statement||'').trim();if(raw==='return false')return false;if(raw==='return true')return true;\n const text=raw.replace(/^return\\s+/,'');\n const assign=text.match(/^([A-Za-z_$][\\w$]*)\\[(\\d+)\\]\\.([A-Za-z_$][\\w$]*)=(this\\.(?:value|checked))$/);\n if(assign){const target=window[assign[1]]?.[Number(assign[2])];if(!target)throw new Error('Missing CSP-safe assignment target: '+assign[1]+'['+assign[2]+']');target[assign[3]]=assign[4]==='this.checked'?el.checked:el.value;return target[assign[3]];}\n const m=text.match(/^((?:window\\.)?[A-Za-z_$][\\w$]*(?:\\.[A-Za-z_$][\\w$]*)*)\\s*\\((.*)\\)$/);\n if(!m)throw new Error('Unsupported CSP-safe handler: '+text);\n const parts=m[1].replace(/^window\\./,'').split('.');let owner=window;\n for(let i=0;i<parts.length-1;i++)owner=owner?.[parts[i]];\n const fn=owner?.[parts.at(-1)];if(typeof fn!=='function')throw new Error('Missing CSP-safe handler function: '+m[1]);\n return fn.apply(el,split(m[2],',').map(x=>arg(x,el,event)));\n }\n function invoke(expression,el,event){let result;for(const statement of split(String(expression||''),';')){result=invokeOne(statement,el,event);if(result===false)break;}return result;}\n for(const type of events){\n document.addEventListener(type,function(event){\n const el=event.target?.closest?.('[data-finora-dynamic-'+type+']');if(!el)return;\n const result=invoke(el.getAttribute('data-finora-dynamic-'+type),el,event);\n if(result===false){event.preventDefault();event.stopPropagation();}\n },type==='blur'||type==='focus');\n }\n})();\n`;
61 +
62 +if(/<script(?![^>]*\ssrc=)[^>]*>/i.test(html))throw new Error('Built page still contains inline script blocks');
63 +if(/\son[a-z]+=/i.test(html))throw new Error('Built page still contains inline event handlers');
64 +if(/script-src[^;]*'unsafe-inline'/i.test(html))throw new Error('Built page still permits unsafe-inline scripts');
65 +const externalScripts=[...html.matchAll(/<script[^>]+src="https:\/\/[^\"]+"[^>]*>/gi)].map(m=>m[0]);
66 +for(const tag of externalScripts)if(!/integrity=/i.test(tag))throw new Error('Built page contains external script without SRI: '+tag);
67 +
68 +fs.writeFileSync(path.join(out,'index.html'),html);
69 +fs.writeFileSync(path.join(out,'js','generated-event-handlers.js'),generated);
70 +fs.writeFileSync(path.join(out,'js','generated-dynamic-handlers.js'),dynamic);
71 +console.log(`Pages artifact built: ${handlers.length} static + ${dynamicHandlers} runtime inline handlers externalized; diag.html intentionally excluded.`);
scripts/pages-artifact.spec.js new
+27
@@ -0,0 +1,27 @@
1 +const {test,expect}=require('@playwright/test');
2 +const {execFileSync}=require('node:child_process');
3 +
4 +const base='http://127.0.0.1:4173/_site/';
5 +
6 +test.beforeAll(()=>{
7 + execFileSync(process.execPath,['scripts/build-pages.mjs'],{stdio:'inherit'});
8 +});
9 +
10 +test('hardened Pages artifact loads without script/CSP console errors',async({page,request})=>{
11 + const errors=[];
12 + page.on('pageerror',e=>errors.push('pageerror: '+e.message));
13 + page.on('console',m=>{if(m.type()==='error')errors.push('console: '+m.text());});
14 + await page.goto(base,{waitUntil:'networkidle'});
15 + await expect(page.locator('#view-dashboard')).toHaveCount(1);
16 + await expect.poll(()=>page.evaluate(()=>window.FinoraHealth?.version||null)).toBe('1.0');
17 + expect(await page.evaluate(()=>window.parseFormattedNumber('۱٬۲۳۴٫۵۶'))).toBe(1234.56);
18 + expect(await page.evaluate(()=>window.parseFormattedNumber('١٢٫٥'))).toBe(12.5);
19 + const csp=await page.locator('meta[http-equiv="Content-Security-Policy"]').getAttribute('content');
20 + expect(csp||'').not.toMatch(/script-src[^;]*'unsafe-inline'/i);
21 + const inline=await page.locator('[onclick],[onchange],[oninput],[onsubmit],[onblur],[onfocus]').evaluateAll(nodes=>nodes.map(el=>({tag:el.tagName,id:el.id||'',attrs:[...el.attributes].filter(a=>/^on/i.test(a.name)).map(a=>[a.name,a.value])})));
22 + if(inline.length)console.log('REMAINING_INLINE_HANDLERS='+JSON.stringify(inline));
23 + expect(inline).toEqual([]);
24 + const diag=await request.get(base+'diag.html');
25 + expect(diag.status()).toBe(404);
26 + expect(errors).toEqual([]);
27 +});
scripts/public-qa-regression-check.mjs new
+28
@@ -0,0 +1,28 @@
1 +import fs from 'node:fs';
2 +import vm from 'node:vm';
3 +import {spawnSync} from 'node:child_process';
4 +import './build-pages.mjs';
5 +
6 +function must(condition,message){if(!condition)throw new Error('Public QA regression: '+message);}
7 +
8 +const money=fs.readFileSync('js/money-format.js','utf8');
9 +const sandbox={};
10 +vm.runInNewContext(money+'\n;globalThis.__parseFormattedNumber=parseFormattedNumber;',sandbox,{filename:'js/money-format.js'});
11 +for(const [input,expected] of [['۱۲٫۵',12.5],['۱٬۲۳۴٫۵۶',1234.56],['١٢٫٥',12.5],['12.5',12.5],['1,234.56',1234.56]]){
12 + const actual=sandbox.__parseFormattedNumber(input);
13 + must(Object.is(actual,expected),`parseFormattedNumber(${JSON.stringify(input)}) expected ${expected}, got ${actual}`);
14 +}
15 +
16 +const built=fs.readFileSync('_site/index.html','utf8');
17 +must(!fs.existsSync('_site/diag.html'),'diag.html must never be present in the deployable artifact');
18 +must(!/script-src[^;]*'unsafe-inline'/i.test(built),'deployable CSP must not allow unsafe-inline scripts');
19 +must(!/\son[a-z]+=/i.test(built),'deployable HTML must not contain inline event handlers');
20 +must(!/<script(?![^>]*\ssrc=)[^>]*>/i.test(built),'deployable HTML must not contain inline script blocks');
21 +for(const tag of [...built.matchAll(/<script[^>]+src="https:\/\/[^\"]+"[^>]*>/gi)].map(m=>m[0]))must(/integrity=/i.test(tag),'external scripts must carry SRI');
22 +for(const file of ['_site/js/generated-event-handlers.js','_site/js/generated-dynamic-handlers.js']){
23 + const check=spawnSync(process.execPath,['--check',file],{encoding:'utf8'});
24 + must(check.status===0,`${file} must parse: `+(check.stderr||check.stdout));
25 +}
26 +const selfcheck=fs.readFileSync('js/selfcheck.js','utf8');
27 +must(/version:'1\.0'/.test(selfcheck)&&/\{version:'1\.0',run\}/.test(selfcheck),'FinoraHealth version must remain 1.0');
28 +console.log('Public QA regression invariants: PASS');
scripts/release-safety-check.mjs
+10
@@ -1,10 +1,14 @@
1 import fs from 'node:fs';
2 +import './public-qa-regression-check.mjs';
3
4 const qa = fs.readFileSync('.github/workflows/qa.yml', 'utf8');
5 const security = fs.readFileSync('.github/workflows/security.yml', 'utf8');
6 const gate = fs.existsSync('.github/workflows/release-gate.yml')
7 ? fs.readFileSync('.github/workflows/release-gate.yml', 'utf8')
8 : '';
9 +const pages = fs.existsSync('.github/workflows/pages.yml')
10 + ? fs.readFileSync('.github/workflows/pages.yml', 'utf8')
11 + : '';
12
13 function must(condition, message) {
14 if (!condition) throw new Error(`Release safety invariant failed: ${message}`);
@@ -29,4 +33,10 @@ must(/head_sha/.test(gate), 'promotion gate must bind evidence to the exact test
33 must(/d1-request-database/.test(gate) && /c8-policy-database/.test(gate), 'promotion gate must verify database jobs, not only top-level workflow conclusion');
34 must(/Security checks/.test(gate) && /Quality checks/.test(gate), 'promotion gate must require both Quality and Security');
35
36 +must(pages.length > 0, 'gated Pages deployment workflow must exist');
37 +must(/workflows:\s*\["Release gate"\]/.test(pages), 'Pages deployment must be downstream of Release gate');
38 +must(/github\.event\.workflow_run\.conclusion == 'success'/.test(pages), 'Pages deployment must reject failed release gates');
39 +must(/github\.event\.workflow_run\.head_sha/.test(pages), 'Pages deployment must checkout the exact gated SHA');
40 +must(/scripts\/build-pages\.mjs/.test(pages), 'Pages deployment must use the hardened bounded artifact builder');
41 +
42 console.log('Release/QA safety invariants: PASS');
supabase/migrations/20261002010000_request_wave1_legacy_transition_guard.sql new
+79
@@ -0,0 +1,79 @@
1 +-- Wave 1 / F-409 + F-410
2 +-- Re-authorize every legacy transition replay and prohibit the legacy transition API
3 +-- from mutating requests that have D3 step-runtime state.
4 +
5 +create or replace function private.request_transition_instance(
6 + p_request_instance_id uuid,
7 + p_action text,
8 + p_expected_revision bigint,
9 + p_idempotency_key text,
10 + p_note text default null
11 +) returns table(request_instance_id uuid,status text,revision bigint)
12 +language plpgsql security definer set search_path=''
13 +as $$
14 +declare
15 + v_row public.request_instances%rowtype;
16 + v_next text;
17 + v_from text;
18 + v_action text;
19 + v_event public.request_instance_events%rowtype;
20 +begin
21 + if auth.uid() is null then raise exception 'authentication required' using errcode='28000'; end if;
22 + if char_length(trim(coalesce(p_idempotency_key,'')))<8 then raise exception 'idempotency_key is required'; end if;
23 +
24 + -- Lock and authorize the current caller before consulting replay evidence.
25 + select * into v_row from public.request_instances r where r.id=p_request_instance_id for update;
26 + if not found then raise exception 'request instance not found'; end if;
27 + if v_row.organization_id not in (select private.current_organization_ids()) then raise exception 'organization access denied' using errcode='42501'; end if;
28 + if not private.organization_has_module_entitlement(v_row.organization_id,'requests_workflow',true) then raise exception 'active requests_workflow entitlement required' using errcode='42501'; end if;
29 + if not (private.has_org_capability(v_row.organization_id,'requests_workflow','approve') or private.has_org_capability(v_row.organization_id,'requests_workflow','edit')) then raise exception 'requests_workflow approve or edit capability required' using errcode='42501'; end if;
30 +
31 + -- D3 requests are exclusively mutated through request_step_decide. The legacy
32 + -- endpoint must never collapse quorum/step semantics into a direct status change.
33 + if exists(select 1 from private.request_step_instances s where s.request_instance_id=v_row.id) then
34 + raise exception 'D3 workflow requires request_step_decide' using errcode='55000';
35 + end if;
36 +
37 + v_action:=lower(trim(coalesce(p_action,'')));
38 + if v_action not in ('approve','reject','return','submit','cancel') then raise exception 'unsupported transition action'; end if;
39 +
40 + select e.* into v_event
41 + from public.request_instance_events e
42 + where e.request_instance_id=v_row.id
43 + and e.organization_id=v_row.organization_id
44 + and e.idempotency_key=p_idempotency_key;
45 + if found then
46 + if v_event.actor_user_id<>auth.uid() or v_event.action<>v_action then
47 + raise exception 'idempotency key already used by another actor or action' using errcode='42501';
48 + end if;
49 + return query select v_row.id,v_event.to_status,v_event.revision;
50 + return;
51 + end if;
52 +
53 + if p_expected_revision is null or p_expected_revision<>v_row.revision then raise exception 'stale revision'; end if;
54 + v_from:=v_row.status;
55 + v_next:=case v_action
56 + when 'approve' then 'approved'
57 + when 'reject' then 'rejected'
58 + when 'return' then 'returned'
59 + when 'submit' then 'submitted'
60 + when 'cancel' then 'cancelled'
61 + else null end;
62 + if v_next is null then raise exception 'unsupported transition action'; end if;
63 + if v_from in ('approved','rejected','cancelled') then raise exception 'terminal request cannot transition'; end if;
64 +
65 + update public.request_instances as ri
66 + set status=v_next,revision=ri.revision+1,updated_at=now()
67 + where ri.id=v_row.id
68 + returning ri.* into v_row;
69 +
70 + insert into public.request_instance_events(
71 + organization_id,request_instance_id,actor_user_id,action,from_status,to_status,revision,note,idempotency_key
72 + ) values(
73 + v_row.organization_id,v_row.id,auth.uid(),v_action,v_from,v_next,v_row.revision,p_note,p_idempotency_key
74 + );
75 + return query select v_row.id,v_next,v_row.revision;
76 +end $$;
77 +
78 +revoke all on function private.request_transition_instance(uuid,text,bigint,text,text) from public,anon;
79 +grant execute on function private.request_transition_instance(uuid,text,bigint,text,text) to authenticated;
supabase/tests/request_wave1_legacy_transition_security.sql new
+114
@@ -0,0 +1,114 @@
1 +\set ON_ERROR_STOP on
2 +
3 +set role authenticated;
4 +select set_config('request.jwt.claim.sub','11111111-1111-1111-1111-111111111111',false);
5 +select set_config('request.jwt.claim.org','aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',false);
6 +select set_config('request.jwt.claim.member_active','true',false);
7 +select set_config('request.jwt.claim.entitled','true',false);
8 +select set_config('request.jwt.claim.write','true',false);
9 +select set_config('request.jwt.claim.capabilities','read,configure,create,edit,approve',false);
10 +
11 +create temporary table wave1_ids(k text primary key,v uuid);
12 +insert into wave1_ids
13 +select 'legacy_type',request_type_version_id from public.request_publish_type_version(
14 + 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa','W1_LEGACY','Legacy security',null,
15 + '{"schemaVersion":1,"fields":[]}'::jsonb,
16 + '{"schemaVersion":1}'::jsonb,
17 + 0
18 +);
19 +insert into wave1_ids values(
20 + 'legacy_instance',
21 + public.request_create_instance(
22 + 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
23 + (select v from wave1_ids where k='legacy_type'),
24 + '{}'::jsonb,
25 + 'wave1-create-legacy-0001'
26 + )
27 +);
28 +select * from public.request_transition_instance(
29 + (select v from wave1_ids where k='legacy_instance'),
30 + 'approve',1,'wave1-transition-legacy-0001','first authorized transition'
31 +);
32 +-- Authorized same-actor/same-action replay remains stable even though expected revision is stale.
33 +select * from public.request_transition_instance(
34 + (select v from wave1_ids where k='legacy_instance'),
35 + 'approve',1,'wave1-transition-legacy-0001','authorized retry'
36 +);
37 +
38 +-- F-409: a caller who no longer has transition capability must not learn/replay
39 +-- a prior successful idempotency result.
40 +select set_config('request.jwt.claim.sub','22222222-2222-2222-2222-222222222222',false);
41 +select set_config('request.jwt.claim.capabilities','read',false);
42 +do $$
43 +begin
44 + begin
45 + perform * from public.request_transition_instance(
46 + (select v from wave1_ids where k='legacy_instance'),
47 + 'approve',1,'wave1-transition-legacy-0001','unauthorized replay'
48 + );
49 + raise exception 'F-409: unauthorized idempotent replay unexpectedly succeeded';
50 + exception when insufficient_privilege then null;
51 + end;
52 +end $$;
53 +
54 +-- Possessing approval capability is still insufficient to replay another actor's
55 +-- idempotency evidence. The replay identity itself is part of the authorization contract.
56 +select set_config('request.jwt.claim.capabilities','read,approve',false);
57 +do $$
58 +begin
59 + begin
60 + perform * from public.request_transition_instance(
61 + (select v from wave1_ids where k='legacy_instance'),
62 + 'approve',1,'wave1-transition-legacy-0001','cross-actor replay'
63 + );
64 + raise exception 'F-409: cross-actor idempotent replay unexpectedly succeeded';
65 + exception when insufficient_privilege then null;
66 + end;
67 +end $$;
68 +
69 +-- F-410: even a fully-authorized approver cannot bypass D3 step/quorum state
70 +-- through the legacy transition endpoint.
71 +select set_config('request.jwt.claim.sub','11111111-1111-1111-1111-111111111111',false);
72 +select set_config('request.jwt.claim.capabilities','read,configure,create,edit,approve',false);
73 +insert into wave1_ids
74 +select 'd3_type',request_type_version_id from public.request_publish_type_version(
75 + 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa','W1_D3','D3 bypass guard',null,
76 + '{"schemaVersion":1,"fields":[]}'::jsonb,
77 + '{"schemaVersion":2,"steps":[{"key":"manager","title":"Manager","mode":"sequential","requiredApprovals":1,"requiredCapability":"approve"}]}'::jsonb,
78 + 0
79 +);
80 +insert into wave1_ids values(
81 + 'd3_instance',
82 + public.request_create_instance(
83 + 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
84 + (select v from wave1_ids where k='d3_type'),
85 + '{}'::jsonb,
86 + 'wave1-create-d3-0000001'
87 + )
88 +);
89 +do $$
90 +begin
91 + begin
92 + perform * from public.request_transition_instance(
93 + (select v from wave1_ids where k='d3_instance'),
94 + 'approve',1,'wave1-legacy-bypass-0001','must fail'
95 + );
96 + raise exception 'F-410: D3 request bypassed step runtime through legacy transition';
97 + exception when object_not_in_prerequisite_state then
98 + if position('D3 workflow requires request_step_decide' in sqlerrm)=0 then raise; end if;
99 + end;
100 +end $$;
101 +
102 +reset role;
103 +do $$
104 +declare legacy_id uuid; d3_id uuid;
105 +begin
106 + legacy_id=(select v from wave1_ids where k='legacy_instance');
107 + d3_id=(select v from wave1_ids where k='d3_instance');
108 + if (select status from public.request_instances where id=legacy_id)<>'approved' then raise exception 'legacy transition status drifted'; end if;
109 + if (select revision from public.request_instances where id=legacy_id)<>2 then raise exception 'legacy replay mutated revision'; end if;
110 + if (select count(*) from public.request_instance_events where request_instance_id=legacy_id and idempotency_key='wave1-transition-legacy-0001')<>1 then raise exception 'legacy replay duplicated evidence'; end if;
111 + if (select status from public.request_instances where id=d3_id)<>'submitted' then raise exception 'D3 bypass attempt mutated request status'; end if;
112 + if (select revision from public.request_instances where id=d3_id)<>1 then raise exception 'D3 bypass attempt mutated revision'; end if;
113 + if not exists(select 1 from private.request_step_instances where request_instance_id=d3_id and state='active') then raise exception 'D3 active step missing after bypass attempt'; end if;
114 +end $$;