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

fix(phase0): bundle ordered ERP modules and safely gate workspace on asset errors (#116)

* docs(state): record owner BOOT_APP_ASSETS and exact bounded single-bundle remedial scope * fix(startup): introduce production extension bundle mode and load deadline * fix(startup): bound each extension download with a hard deadline * fix(startup): load production bundle as one ordered request * fix(startup): reject readiness when a module is unavailable instead of exposing partial ERP * fix(auth): prepare explicit blocked asset readiness state * fix(auth): support rejectable workspace module readiness * fix(auth): surface missing extension failure without exposing workspace * fix(auth UX): clearly identify failed app modules instead of generic profile error * build(pages): enable hashed single-request ERP extension compilation * build(pages): compile and syntax-check 14 ordered extensions into hashed same-origin JS bundle * fix(cache): load bundled Pages bootstrap and fail-closed authentication barrier * test(startup): require fresh auth and bundle loader asset versions * test(pages): verify one bundled request and fail-closed unavailable financial workspace

davoodmehraban89 committed Oct 13, 2026 at 01:09 UTC c72a83981860ca38a68b6f4a7b9900dd664c64f7
7 files changed +113 -17
PROJECT_STATE.md
+6
@@ -109,6 +109,12 @@ The latest user message is the sole source of new instructions. Read AGENTS.md t
109 - **Protected-main release:** merged runtime **`bead02fbc48f04e12de8b1565d99d2a3c4af761d`**, exact SHA [Quality `38303068200`](https://github.com/davoodmehraban89/Factor-easy/actions/runs/38303068200) SUCCESS (103/103), [Security `38303068209`](https://github.com/davoodmehraban89/Factor-easy/actions/runs/38303068209) SUCCESS, [Release Gate `38303361728`](https://github.com/davoodmehraban89/Factor-easy/actions/runs/38303361728) SUCCESS and [Deploy gated Pages `38303407938`](https://github.com/davoodmehraban89/Factor-easy/actions/runs/38303407938) SUCCESS; duplicate `38303255014` Release CANCELLED and `38303388240` Pages SKIPPED excluded.
110 - **Acceptance still NOT verified:** no direct live `factoreasy.ir` GET or owner-ISP runtime trace after this release; Desktop Commander was ONLINE but latest remote command attempt returned MONTHLY QUOTA EXCEEDED; no bypass/reconnect attempted. No actual authenticated owner sign-in, company data loading or delay root cause yet. User to hard-refresh, run built-in diagnostic, report only `REST_*` code, then attempt sign-in privately, report `BOOT_*` code on a repeated timeout; compare a different ISP if useful. The fixed outer wait prevents indefinite hanging but is **not proof full login latency has been cured**. [Issue #106](https://github.com/davoodmehraban89/Factor-easy/issues/106), F0-01 and Phase 0 remain OPEN. No server Auth/RLS/schema/roles, user identity, financial data or customer payload modifications. Rollback via #114 revert and gated redeploy, no database rollback.
111
112 +### 2026-10-13 Owner affected-ISP evidence pinpoints BOOT_APP_ASSETS / slow local files — REMEDIATION IN PROGRESS
113 +- **Actual photographed owner browser after #114:** `BOOT_APP_ASSETS` when attempting authenticated workspace entry; connectivity check `SITE_JS_TIMEOUT | MANIFEST_TIMEOUT | AUTH_OK | REST_HTTP_401`. The later screenshot shows cleared email/password fields, but earlier supplied login contains private email: **never reproduce identifiers**. `AUTH_OK` means GoTrue health only; `REST_HTTP_401` for unauthenticated REST root is not proof PostgREST is offline and must not be treated as the login root cause. Two same-origin no-store diagnostics timed out under owner ISP, a strong signal of unstable own-domain asset delivery, not definitive server infrastructure fault.
114 +- **Code-proven wait:** `js/bootstrap.js` currently dispatches 14 separate extension script downloads, `Promise.allSettled` has no per-resource deadline and sets `FinoraAppAssetsReady` only after **all 14** finish/fail; `enterApp()` refuses full app until that promise resolves. This exactly matches `BOOT_APP_ASSETS`, whereas the owner code did not name a specific file. The existing flow even resolves this readiness promise if any extension fails, risking partially usable financial software.
115 +- **Safe fix scope:** build a same-origin, deterministic **single production extension JS bundle** from the exact 14 source modules in dependency order (all IIFEs, preserve CSP and source); retain existing unbundled source/dev loader; bound the extension load (including missing network) and on any failure explicitly reject workspace readiness, leave login responsive and show actionable asset-failure status, NEVER render incomplete ERP. Cache-bust built script. Add real Playwright built Pages/browser tests for one-request delivery, missing bundle fail-closed, and original parallel development behavior. No network-unapproved external CDNs, no Auth/RLS/schema/users/posting/tenant data modifications. Rollback #PR via protected Pages; no DB rollback.
116 +- **Required acceptance:** full 103+ Chromium/Golden/disposable 3 PostgreSQL/Security and exact SHA Pages gate; actual affected-ISP sign-in **remains OPEN** until owner real network retest. Desktop Commander quota previously explicitly exhausted; no retry/bypass. Keep F0-01 and Phase 0 OPEN.
117 +
118 ## Current change ledger
119 | 2026-10-07 | Owner requested accounting/product usability refinement from live screenshots: automatic non-user-entered floating-detail codes, contextual in-product guides (especially accounting/chart/dimensions), remove duplicate product internal tax ID and use product code as internal item ID, strengthen in-control product/person search, introduce hierarchical product group/subgroup coding with deterministic 6-digit product codes, and keep sale/purchase commercial-document workspace layout stable while only semantic fields change. | **IMPLEMENTED / LOCAL VERIFICATION PASSED / CI PENDING** | Baseline main = `7e58c75f7d754f378d94ca3f356c1ae580aa7ee3`. Automatic dimension type/value codes, contextual guides, product-code-as-internal-ID, normalized multi-token search, and additive six-digit product coding implemented. Existing historical codes preserved. Commercial sale/purchase workspaces now share a stable `صدور سند تجاری` header/actions layout; duplicate purchase sidebar injection removed; the public selector is the single document-type selector and the legacy internal invoice-kind control is hidden. Local syntax/static/commerce/UX/accounting phases 2–6/Golden checks passed; protected-branch CI remains pending. |
120
index.html
+3 -3
@@ -13,7 +13,7 @@
13 <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; font-src 'self' https://cdn.jsdelivr.net data:; img-src 'self' data: blob:; connect-src 'self' https://hcsixhqbyuhpshfwqpjx.supabase.co; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'; upgrade-insecure-requests" />
14 <meta name="apple-mobile-web-app-capable" content="yes" />
15 <meta name="theme-color" content="#071a48" />
16 -<link rel="preload" as="script" href="js/core.js?v=20261012-bootstrap-stages-v4" />
16 +<link rel="preload" as="script" href="js/core.js?v=20261013-asset-failclosed-v1" />
17 <link rel="preload" as="script" href="js/login-connectivity.js?v=20261012-data-probe-v3" />
18 <script src="vendor/supabase.js"></script>
19 <script async src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
@@ -893,7 +893,7 @@ body{background:#f6f9fc}
893 <!-- The credential-free connectivity action must be loaded before core declares
894 login actions interactive. Hardened Pages binds static handlers just before core. -->
895 <script src="js/login-connectivity.js?v=20261012-data-probe-v3"></script>
896 -<script src="js/core.js?v=20261012-bootstrap-stages-v4"></script>
896 +<script src="js/core.js?v=20261013-asset-failclosed-v1"></script>
897 <script src="js/admin.js?v=20261012-provision-error-v1"></script>
898 <script src="js/sync.js?v=20261012-login-read-cancel-v1"></script>
899 <script src="js/ui.js?v=20261002-shell-scroll-ownership-v2"></script>
@@ -906,7 +906,7 @@ body{background:#f6f9fc}
906 <script src="js/companies.js?v=20260928-integrity-v4"></script>
907 <script src="js/backup.js?v=20260928-data-v3"></script>
908 <script src="js/words.js"></script>
909 -<script src="js/bootstrap.js?v=20261012-login-ready-v2"></script>
909 +<script src="js/bootstrap.js?v=20261013-ordered-bundle-v1"></script>
910
911 <style>
912 .form-control, textarea, select { direction: rtl; }
js/bootstrap.js
+25 -9
@@ -18,13 +18,24 @@ const FINORA_EXTENSION_SCRIPTS=[
18 "js/organization-shell.js?v=20260930-eli4-v1",
19 "js/taxpayer-print.js?v=20261003-reference-v2"
20 ];
21 +const FINORA_EXTENSION_BUNDLE_URL=null;
22 +const FINORA_EXTENSION_WAIT_MS=18000;
23 function finoraLoadScript(src){
24 return new Promise((resolve,reject)=>{
25 const script=document.createElement('script');
26 script.async=false;
27 script.src=src;
26 - script.onload=()=>resolve(src);
27 - script.onerror=()=>reject(new Error('Failed to load '+src));
28 + let complete=false;
29 + const finish=(error)=>{
30 + if(complete)return;
31 + complete=true;clearTimeout(timeout);
32 + script.onload=null;script.onerror=null;
33 + if(error){script.remove();reject(new Error('FINORA_EXTENSION_LOAD_FAILED'));}
34 + else resolve(src);
35 + };
36 + const timeout=setTimeout(()=>finish(true),FINORA_EXTENSION_WAIT_MS);
37 + script.onload=()=>finish(false);
38 + script.onerror=()=>finish(true);
39 document.head.appendChild(script);
40 });
41 }
@@ -39,17 +50,22 @@ if(finoraFontLink){
50 }
51 window.addEventListener('DOMContentLoaded',async()=>{
52 const started=performance.now();
42 - const results=await Promise.allSettled(FINORA_EXTENSION_SCRIPTS.map(finoraLoadScript));
43 - const failed=results.flatMap((r,i)=>r.status==='rejected'?[FINORA_EXTENSION_SCRIPTS[i]]:[]);
53 + const sources=FINORA_EXTENSION_BUNDLE_URL?[FINORA_EXTENSION_BUNDLE_URL]:FINORA_EXTENSION_SCRIPTS;
54 + const results=await Promise.allSettled(sources.map(finoraLoadScript));
55 + const failed=results.flatMap((r,i)=>r.status==='rejected'?[sources[i]]:[]);
56 Object.assign(window.FinoraStartupStatus,{
57 extensionCount:FINORA_EXTENSION_SCRIPTS.length,
46 - failedExtensionCount:failed.length,
58 + failedExtensionCount:FINORA_EXTENSION_BUNDLE_URL&&failed.length?FINORA_EXTENSION_SCRIPTS.length:failed.length,
59 + extensionBundle:!!FINORA_EXTENSION_BUNDLE_URL,
60 extensionLoadMs:Math.round(performance.now()-started),
61 extensionsReady:true
62 });
50 - if(failed.length)console.error('Finora platform extension assets unavailable:',failed);
51 - // A successful sign-in/restored session must wait for these modules, but
52 - // rendering the interactive email/password form never waits for them.
53 - window.finoraMarkAppAssetsReady();
63 + if(failed.length){
64 + console.warn('Finora workspace assets unavailable; partial ERP is blocked.');
65 + window.finoraMarkAppAssetsFailed();
66 + }else{
67 + window.finoraMarkAppAssetsReady();
68 + }
69 + // Login controls remain usable even when workspace modules fail.
70 if(window.FinoraStartupStatus.authSessionChecked)window.FinoraStartupStatus.authChecked=true;
71 });
js/core.js
+6 -2
@@ -59,9 +59,11 @@ function todayISO(){return new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Tehra
59 let currentUser=null;
60 let authBusy=false;
61 // Authentication starts independently of the optional ERP modules.
62 -let finoraAppAssetsResolve;
63 -window.FinoraAppAssetsReady=new Promise(resolve=>{finoraAppAssetsResolve=resolve;});
62 +let finoraAppAssetsResolve,finoraAppAssetsReject;
63 +window.FinoraAppAssetsReady=new Promise((resolve,reject)=>{finoraAppAssetsResolve=resolve;finoraAppAssetsReject=reject;});
64 +window.FinoraAppAssetsReady.catch(()=>{});
65 window.finoraMarkAppAssetsReady=()=>finoraAppAssetsResolve();
66 +window.finoraMarkAppAssetsFailed=()=>finoraAppAssetsReject(new Error('FINORA_APP_ASSETS_UNAVAILABLE'));
67 window.FinoraStartupStatus={authFormReady:false,authSessionChecked:false,authChecked:false,extensionsReady:false};
68 function setAuthLoginStatus(message,state){
69 const el=document.getElementById('auth-login-status');
@@ -327,6 +329,8 @@ async function enterApp(authUser,{timeoutMs=25000}={}){
329 const stages=timeoutStageCodes.length?timeoutStageCodes:finoraPendingLoginStages();
330 const safeCodes=stages.length?stages.join(','):'UNKNOWN';
331 setAuthLoginStatus('دریافت اطلاعات حساب بیش از حد طول کشید. مرحله معطل: '+finoraLoginStageDescription(stages)+' (BOOT_'+safeCodes+'). اتصال را بررسی کنید و دوباره تلاش کنید.','error');
332 + }else if(err?.message==='FINORA_APP_ASSETS_UNAVAILABLE'){
333 + setAuthLoginStatus('برخی اجزای نرم‌افزار از این شبکه دریافت نشدند (BOOT_APP_ASSETS_FAILED). برای جلوگیری از نمایش اطلاعات ناقص، محیط کار باز نشد. اتصال را تغییر دهید و صفحه را دوباره بارگذاری کنید.','error');
334 }else{
335 console.error('Finora account hydration failed',err);
336 setAuthLoginStatus('دریافت اطلاعات حساب ناموفق بود؛ اتصال را بررسی و دوباره تلاش کنید.','error');
scripts/build-pages.mjs
+26
@@ -1,5 +1,7 @@
1 import fs from 'node:fs';
2 import path from 'node:path';
3 +import {createHash} from 'node:crypto';
4 +import vm from 'node:vm';
5
6 const root=process.cwd();
7 const out=path.join(root,'_site');
@@ -70,6 +72,30 @@ if(/script-src[^;]*'unsafe-inline'/i.test(html))throw new Error('Built page stil
72 const externalScripts=[...html.matchAll(/<script[^>]+src="https:\/\/[^\"]+"[^>]*>/gi)].map(m=>m[0]);
73 for(const tag of externalScripts)if(!/integrity=/i.test(tag))throw new Error('Built page contains external script without SRI: '+tag);
74
75 +// Build one self-hosted production request from the 14 dependency-ordered IIFEs.
76 +// Both the list and all individual sources remain canonical in git.
77 +const bootstrapPath=path.join(out,'js','bootstrap.js');
78 +const originalBootstrap=fs.readFileSync(bootstrapPath,'utf8');
79 +const manifestMatch=originalBootstrap.match(/const FINORA_EXTENSION_SCRIPTS=\[([\s\S]*?)\];/);
80 +if(!manifestMatch)throw new Error('Missing canonical module list for bundle build');
81 +const extensionFiles=JSON.parse('['+manifestMatch[1]+']');
82 +if(extensionFiles.length!==14||new Set(extensionFiles.map(s=>s.split('?')[0])).size!==14)
83 + throw new Error('Unexpected module list or duplicate extension');
84 +const bundleParts=extensionFiles.map(src=>{
85 + if(!/^js\/[a-z0-9-]+\.js\?v=[a-z0-9-]+$/i.test(src))throw new Error('Invalid extension source');
86 + const sourcePath=path.join(out,src.split('?')[0]);
87 + if(!fs.existsSync(sourcePath))throw new Error('Missing extension: '+src);
88 + return '\n;\n'+fs.readFileSync(sourcePath,'utf8')+'\n;\n';
89 +});
90 +const bundle='// Bundled local Finora extensions, original dependency order.\n'+bundleParts.join('');
91 +new vm.Script(bundle,{filename:'finora-extension-bundle.js'});
92 +const bundleHash=createHash('sha256').update(bundle).digest('hex').slice(0,16);
93 +fs.writeFileSync(path.join(out,'js','finora-extension-bundle.js'),bundle);
94 +const marker='const FINORA_EXTENSION_BUNDLE_URL=null;';
95 +if(!originalBootstrap.includes(marker))throw new Error('Missing bundle loader feature flag');
96 +fs.writeFileSync(bootstrapPath,originalBootstrap.replace(marker,
97 + 'const FINORA_EXTENSION_BUNDLE_URL="js/finora-extension-bundle.js?v='+bundleHash+'";'));
98 +
99 fs.writeFileSync(path.join(out,'index.html'),html);
100 fs.writeFileSync(path.join(out,'js','generated-event-handlers.js'),generated);
101 fs.writeFileSync(path.join(out,'js','generated-dynamic-handlers.js'),dynamic);
scripts/login-connectivity-check.mjs
+3 -3
@@ -7,9 +7,9 @@ assert(html.includes('id="auth-connectivity-check"'),'Missing diagnostic action'
7 assert(html.includes('id="auth-connectivity-result"'),'Missing accessible result');
8 assert(html.includes('id="auth-connectivity-result" aria-live="polite"'),'Diagnostic must announce updates without adding a conflicting global role=status');
9 assert(html.includes('js/login-connectivity.js?v=20261012-data-probe-v3'),'Missing versioned script');
10 -assert(html.includes('js/core.js?v=20261012-bootstrap-stages-v4'),'Production login controls must use new cache version');
11 -assert(html.indexOf('<script src="js/login-connectivity.js?v=20261012-data-probe-v3"')<html.indexOf('<script src="js/core.js?v=20261012-bootstrap-stages-v4"'),'Connectivity handler script must execute before core (not just preload)');
12 -assert(html.includes('js/bootstrap.js?v=20261012-login-ready-v2'),'Parallel bootstrap must also be cache-busted');
10 +assert(html.includes('js/core.js?v=20261013-asset-failclosed-v1'),'Production login controls must use new cache version');
11 +assert(html.indexOf('<script src="js/login-connectivity.js?v=20261012-data-probe-v3"')<html.indexOf('<script src="js/core.js?v=20261013-asset-failclosed-v1"'),'Connectivity handler script must execute before core (not just preload)');
12 +assert(html.includes('js/bootstrap.js?v=20261013-ordered-bundle-v1'),'Parallel bootstrap must also be cache-busted');
13 assert(html.includes('id="auth-login-button"')&&html.includes('id="auth-login-status"'),'Login control requires real readiness/progress feedback');
14 assert(core.includes('window.FinoraAppAssetsReady'),'Authenticated workspace must remain gated until all module scripts settle');
15 assert(core.includes('FinoraLoginActionsBound'),'Production CSP action readiness must require installed event listeners');
scripts/pages-artifact.spec.js
+44
@@ -55,3 +55,47 @@ test('Production CSP login and connectivity actions work while later ERP JS is s
55 await Promise.all([page.locator('#auth-login-button').click(),alertHandled]);
56 expect(delayedModuleFinished).toBe(false);
57 });
58 +
59 +test('Built Pages uses exactly one SHA-pinned local bundle for all 14 ERP extensions',async({page})=>{
60 + const requested=[];
61 + page.on('request',req=>{
62 + const path=new URL(req.url()).pathname;
63 + if(path.includes('finora-extension-bundle.js')||/\/(organization-rbac|request-workflow-d2|office-workflow|taxpayer-print)\.js$/.test(path))
64 + requested.push(path);
65 + });
66 + await page.goto(base,{waitUntil:'domcontentloaded'});
67 + await expect.poll(()=>page.evaluate(()=>window.FinoraStartupStatus?.extensionsReady),{timeout:15000}).toBe(true);
68 + const state=await page.evaluate(()=>({
69 + ...window.FinoraStartupStatus,
70 + bundle:document.querySelector('script[src*="finora-extension-bundle.js"]')?.src||'',
71 + loaded:typeof window.FINORA_OFFICE_WORKFLOW_C8_UI_VERSION
72 + }));
73 + expect(state.extensionBundle).toBe(true);
74 + expect(state.extensionCount).toBe(14);
75 + expect(state.failedExtensionCount).toBe(0);
76 + expect(state.bundle).toMatch(/finora-extension-bundle\.js\?v=[0-9a-f]{16}$/);
77 + expect(state.loaded).toBe('string');
78 + expect(requested.filter(x=>x.endsWith('/finora-extension-bundle.js')).length).toBe(1);
79 + expect(requested.filter(x=>/\/(organization-rbac|request-workflow-d2|office-workflow|taxpayer-print)\.js$/.test(x))).toEqual([]);
80 +});
81 +
82 +test('A blocked production bundle fails closed and never exposes a partial financial workspace',async({page})=>{
83 + await page.route('**/js/finora-extension-bundle.js*',route=>route.abort('failed'));
84 + await page.goto(base,{waitUntil:'domcontentloaded'});
85 + await expect.poll(()=>page.evaluate(()=>window.FinoraStartupStatus?.extensionsReady),{timeout:15000}).toBe(true);
86 + const output=await page.evaluate(async()=>{
87 + window.fetchCurrentUser=async()=>({id:'fixture-no-account',role:'accountant'});
88 + await enterApp({id:'fixture-no-account'}, {timeoutMs:500});
89 + return {
90 + status:document.getElementById('auth-login-status').textContent,
91 + loginVisible:getComputedStyle(document.getElementById('auth-screen')).display!=='none',
92 + currentUser:currentUser,
93 + failures:window.FinoraStartupStatus.failedExtensionCount
94 + };
95 + });
96 + expect(output.failures).toBe(14);
97 + expect(output.status).toContain('BOOT_APP_ASSETS_FAILED');
98 + expect(output.status).not.toContain('fixture-no-account');
99 + expect(output.loginVisible).toBe(true);
100 + expect(output.currentUser).toBe(null);
101 +});