@davoodmehraban89 / Factor-easy / commits / e9831e4
Fork 0

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

Identity: fail closed on membership revocation

davoodmehraban89 committed Oct 2, 2026 at 11:38 UTC e9831e4d23fceae3a30359fe2eca8743087bb6b5
6 files changed +70 -2
.github/workflows/quality.yml
+3 -1
@@ -52,6 +52,8 @@ jobs:
52 run: node scripts/enterprise-org-ux-check.mjs
53 - name: Wave 5a identity/bootstrap invariants
54 run: node scripts/identity-wave5a-check.mjs
55 + - name: Wave 5b offboarding/revocation invariants
56 + run: node scripts/identity-wave5b-check.mjs
57 - name: Office Slice C1 invariants
58 run: node scripts/office-slice-c1-check.mjs
59 - name: Office Slice C2 invariants
@@ -89,7 +91,7 @@ jobs:
91 - name: Real DOM smoke
92 run: |
93 python3 -m http.server 4173 >/tmp/finora-http.log 2>&1 &
92 - 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/identity-wave5a.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/request-workflow-d4a.spec.js scripts/taxpayer-print.spec.js scripts/pages-artifact.spec.js --reporter=line --workers=1
94 + 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/identity-wave5a.spec.js scripts/identity-wave5b.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/request-workflow-d4a.spec.js scripts/taxpayer-print.spec.js scripts/pages-artifact.spec.js --reporter=line --workers=1
95
96 identity-wave5a-database:
97 runs-on: ubuntu-latest
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 | Wave 5b offboarding/revocation client fail-closed remediation from Round 29. | **IMPLEMENTED ON BRANCH / CI PENDING** | Added 30s + visibility membership revalidation, known-revocation tenant-memory/cache purge, stale `currentUser` removal, sensitive-view lock, alternate-org recovery path, no-membership sign-out, and fresh server membership gate before bulk export. Static + Real-DOM regression gates added. Persistent two-real-user production E2E and capability-specific privileged export authorization remain NOT VERIFIED. |
18 | 2026-10-02 | Permanent project constraint: user operates from Iran and cannot use paid infrastructure, paid APIs, international-card billing, or services that require a later paid upgrade for essential operation. Railway is excluded from Finora runtime/deployment. | **ACTIVE ARCHITECTURE CONSTRAINT** | Use only genuinely no-cost capabilities for required operation; do not create paid resources or make Finora depend on a service whose essential path later requires billing. GitHub + Supabase remain current sources of truth; any future infrastructure choice must pass this zero-cost/no-billing constraint first. |
19 | 2026-10-02 | Gmail/GitHub failure review: latest Wave 5a Quality run failed only because the disposable PostgreSQL harness lacked Supabase roles `anon`/`authenticated`; Security latest run is green. | **TEST HARNESS VERIFIED** | Added the two no-login Supabase compatibility roles to the disposable identity DB bootstrap. Wave 5a identity DB gate passed on PR head and main Quality `36980655736`; the earlier failure was harness-only. |
20 | 2026-10-02 | Second CI retest showed the safety-check regex itself was over-escaped. | **REGEX FIX VERIFIED** | Normalized regex literals to match the workflow labels/variable gate exactly; main Security `36980655725` passed Release/QA safety + CodeQL. |
js/backup.js
+2 -1
@@ -1,4 +1,5 @@
1 -function exportDataBlob(){
1 +async function exportDataBlob(){
2 + if(typeof window.requireFreshFinoraMembership==='function'&&!await window.requireFreshFinoraMembership()){alert('خروجی‌گیری متوقف شد؛ عضویت سازمانی باید دوباره از سرور تأیید شود.');return;}
3 const userExport={user:currentUser?.username,exportedAt:new Date().toISOString(),companies:getMyCompanies(),contacts:getMyContacts(),products:getMyProducts(),invoices:getMyInvoices(),purchases:getMyPurchases(),cheques:getMyCheques(),expenses:getMyExpenses(),payments:getMyPayments(),fiscalYears:getMyFiscalYears(),accounts:getMyAccounts(),dimensionTypes:getMyDimensionTypes(),dimensionValues:getMyDimensionValues(),accountDimensionRules:getMyAccountDimensionRules(),branches:getMyBranches(),projects:getMyGlobalProjects(),projectLinks:afOwned('projectLinks'),postingProfiles:getMyPostingProfiles(),journalVouchers:getMyJournalVouchers(),journalLines:getMyJournalLines(),journalLineDimensions:getMyJournalLineDimensions(),contracts:getMyContracts(),contractAmendments:getMyContractAmendments(),contractParties:getMyContractParties(),contractDeductions:getMyContractDeductions(),guarantees:getMyGuarantees(),guaranteeEvents:getMyGuaranteeEvents(),contractStatements:getMyContractStatements(),phase4Audit:getMyPhase4Audit(),warehouses:getMyWarehouses(),stockMovements:getMyStockMovements(),inventoryCounts:getMyInventoryCounts(),fixedAssets:getMyFixedAssets(),assetDepreciations:getMyAssetDepreciations(),currencies:getMyCurrencies(),exchangeRates:getMyExchangeRates(),costCenters:getMyCostCenters(),importBatches:getMyImportBatches(),integrationConnections:getMyIntegrationConnections(),integrationOutbox:getMyIntegrationOutbox(),phase5Audit:getMyPhase5Audit(),settings:getMySettings()};
4 const blobString="data:text/json;charset=utf-8,"+encodeURIComponent(JSON.stringify(userExport,null,2));
5 const anchor=document.createElement('a');
js/organization-rbac.js
+37
@@ -48,6 +48,43 @@ async function loadOrganizationContext(user){
48 return user;
49 }
50 fetchCurrentUser=async function(authUser){return loadOrganizationContext(await baseFetchCurrentUser(authUser))};
51 +let finoraMembershipRevalidationBusy=false;
52 +function clearFinoraTenantMemory(userId){
53 + clearTimeout(syncTimer);syncPending=false;syncAgain=false;syncFailCount=0;syncSnap.clear();
54 + const fresh={};COLLS.forEach(k=>fresh[k]=[]);datastore=fresh;
55 + try{localStorage.removeItem('finora_active_org_'+userId);localStorage.removeItem(STORAGE_KEY);}catch(e){}
56 + document.querySelectorAll('.modal-backdrop.active').forEach(el=>el.classList.remove('active'));
57 +}
58 +function showFinoraMembershipLock(hasAlternative){
59 + let el=document.getElementById('finora-membership-lock');
60 + if(!el){el=document.createElement('div');el.id='finora-membership-lock';el.className='modal-backdrop active';document.body.appendChild(el)}
61 + el.innerHTML='<div class="modal-card" style="max-width:520px"><h3>دسترسی سازمانی متوقف شده است</h3><p class="af-hint">عضویت شما در سازمان فعال تعلیق یا حذف شده است. داده‌های این سازمان از حافظه این نشست پاک شد و همگام‌سازی، خروجی و عملیات حساس تا احراز مجدد متوقف هستند.</p>'+(hasAlternative?'<button class="btn btn-primary" onclick="resumeFinoraAuthorizedOrganization()">ورود به سازمان مجاز دیگر</button>':'<p class="af-hint">عضویت فعال دیگری برای این حساب در دسترس نیست؛ نشست بسته می‌شود.</p>')+'</div>';
62 + el.classList.add('active');
63 +}
64 +window.resumeFinoraAuthorizedOrganization=async function(){
65 + const {data,error}=await sb.auth.getUser();if(error||!data?.user)return false;
66 + try{currentUser=await fetchCurrentUser(data.user);await pullAll();document.getElementById('finora-membership-lock')?.remove();refreshAllSurfaces();if(typeof showModuleLauncher==='function')showModuleLauncher(true);return true}
67 + catch(e){console.error('authorized organization rebuild failed',e);currentUser=null;return false}
68 +};
69 +window.revalidateFinoraMembership=async function(options){
70 + const sensitive=!!options?.sensitive;
71 + if(!currentUser?.id||!currentUser?.organizationId)return false;
72 + if(finoraMembershipRevalidationBusy)return false;
73 + finoraMembershipRevalidationBusy=true;
74 + const uid=currentUser.id,orgId=currentUser.organizationId;
75 + try{
76 + const {data,error}=await sb.from('organization_members').select('id,organization_id,status').eq('user_id',uid).eq('status','active');
77 + if(error){if(sensitive)return false;throw error}
78 + const active=data||[];
79 + if(active.some(m=>m.organization_id===orgId))return true;
80 + clearFinoraTenantMemory(uid);currentUser=null;showFinoraMembershipLock(active.length>0);
81 + if(!active.length){try{await sb.auth.signOut()}catch(e){console.error('revoked-session signout failed',e)}}
82 + return false;
83 + }finally{finoraMembershipRevalidationBusy=false}
84 +};
85 +window.requireFreshFinoraMembership=async function(){return window.revalidateFinoraMembership({sensitive:true})};
86 +setInterval(()=>{if(currentUser)window.revalidateFinoraMembership({sensitive:false}).catch(e=>console.error('membership revalidation failed',e))},30000);
87 +document.addEventListener('visibilitychange',()=>{if(document.visibilityState==='visible'&&currentUser)window.revalidateFinoraMembership({sensitive:false}).catch(e=>console.error('membership revalidation failed',e))});
88 window.hasFinoraCapability=function(moduleKey,capability='read'){
89 if(!currentUser)return false;
90 if(moduleKey==='core'&&capability==='read')return true;
scripts/identity-wave5b-check.mjs new
+8
@@ -0,0 +1,8 @@
1 +import fs from 'node:fs';import assert from 'node:assert/strict';
2 +const org=fs.readFileSync('js/organization-rbac.js','utf8'),backup=fs.readFileSync('js/backup.js','utf8');
3 +for(const s of ['revalidateFinoraMembership','clearFinoraTenantMemory','finora-membership-lock','setInterval','visibilitychange'])assert(org.includes(s),s+' missing');
4 +assert(org.includes("localStorage.removeItem(STORAGE_KEY)"),'legacy local cache must be purged on known revocation');
5 +assert(org.includes("currentUser=null;showFinoraMembershipLock"),'stale currentUser must not survive known revocation');
6 +assert(org.includes("await sb.auth.signOut()"),'no-membership path must close auth session');
7 +assert(backup.includes("await window.requireFreshFinoraMembership()"),'bulk export must require fresh membership');
8 +console.log('Wave 5b offboarding/revocation invariants passed');
scripts/identity-wave5b.spec.js new
+19
@@ -0,0 +1,19 @@
1 +const {test,expect}=require('@playwright/test');
2 +test('Wave 5b export fails closed when fresh membership is denied',async({page})=>{
3 + await page.goto('http://127.0.0.1:4173/index.html',{waitUntil:'domcontentloaded'});
4 + await page.waitForFunction(()=>typeof exportDataBlob==='function');
5 + const result=await page.evaluate(async()=>{let clicks=0,alerts=[];const oldCreate=document.createElement.bind(document),oldAlert=window.alert;window.alert=m=>alerts.push(String(m));window.requireFreshFinoraMembership=async()=>false;document.createElement=(tag)=>{const el=oldCreate(tag);if(tag==='a')el.click=()=>{clicks++};return el};try{await exportDataBlob()}finally{document.createElement=oldCreate;window.alert=oldAlert}return {clicks,alerts}});
6 + expect(result.clicks).toBe(0);expect(result.alerts.join(' ')).toContain('عضویت سازمانی');
7 +});
8 +test('Wave 5b known revocation clears tenant memory and stale user',async({page})=>{
9 + await page.goto('http://127.0.0.1:4173/index.html',{waitUntil:'domcontentloaded'});
10 + await page.waitForFunction(()=>typeof revalidateFinoraMembership==='function');
11 + const result=await page.evaluate(async()=>{
12 + currentUser={id:'u1',organizationId:'org-revoked',username:'seat'};datastore.products=[{id:'p1',ownerUserId:'u1'}];syncSnap.set('products|p1','x');localStorage.setItem(STORAGE_KEY,'secret-cache');
13 + const oldFrom=sb.from,oldSignOut=sb.auth.signOut;let signedOut=0;
14 + sb.from=()=>({select(){return this},eq(){return this},then(resolve){resolve({data:[],error:null})}});
15 + sb.auth.signOut=async()=>{signedOut++;return {error:null}};
16 + try{const ok=await revalidateFinoraMembership({sensitive:true});return {ok,signedOut,user:currentUser,products:datastore.products.length,snap:syncSnap.size,legacy:localStorage.getItem(STORAGE_KEY),lock:!!document.getElementById('finora-membership-lock')}}finally{sb.from=oldFrom;sb.auth.signOut=oldSignOut}
17 + });
18 + expect(result).toEqual({ok:false,signedOut:1,user:null,products:0,snap:0,legacy:null,lock:true});
19 +});