@davoodmehraban89 / Factor-easy-2 Mirror · read-only / commits / 23c5f54
Fork 0

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

Mirrored from https://github.com/davoodmehraban89/Factor-easy.git

Synced Dec 3, 19:30 UTC

fix(phase0): wire production login handlers and bound tenant session restore (#107)

* docs(state): record owner-reproduced login handler race and read-only hang before fix * fix(pages): install CSP-safe login handlers before enabling login during parsing * fix(login): initialize connectivity helper before enabling interactive login buttons * fix(login): never advertise unwired CSP actions, bound read-only session restore * fix(sync): abort stale login hydration reads before atomic datastore commit * test(login): enforce early production handlers and safe stalled-session fallback * test(pages): reproduce original inert CSP login clicks under a stalled ERP script * test(auth): bounded restored session and no late partial financial record snapshot * test(auth): read lexical currentUser from isolated Chromium fixture * test(login): compare execution tags rather than early resource preload tags * test(pages): correctly handle mocked cross-origin GoTrue health preflight * test(auth): deterministic immediate abort and specific no-partial-data assertions * test(auth): expose individual atomic-read cancellation invariant results * fix(cache): force new versioned sync reader for bounded login hydration * test(auth): assert actual loaded pullAll includes timeout invariant at runtime * fix(tenant): propagate login abort through actual organization and scoped records readers * fix(cache): invalidate organization scoped reader after cancellation fix * test(tenant): prove scoped read keeps org filter and rejects delayed cancelled snapshot

davoodmehraban89 committed Oct 12, 2026 at 20:56 UTC 23c5f5426bc2f8ad48c6323f1d43b7cf5b556875
10 files changed +219 -29
PROJECT_STATE.md
+7
@@ -47,6 +47,13 @@ The latest user message is the sole source of new instructions. Read AGENTS.md t
47 - **Live deployed asset readback on authorized remote Windows device:** unauthenticated read-only GET of `https://factoreasy.ir/?phase0_login_release=20261012` returned HTML containing `js/core.js?v=20261012-login-ready-v2`, `js/bootstrap.js?v=20261012-login-ready-v2`, and `auth-login-status`. Independent GET of live versioned `js/core.js` contained `finoraBoundedAuthFetch` and `FinoraAppAssetsReady` strings. No password, local cookie, login session, customer records or financial writes accessed.
48 - **Acceptance:** FIX_RELEASED + CI_CONTROLLED_QA_PASSED. Owner's affected ISP/device real sign-in/response timing, two-user RLS, full post-login `pullAll()` latency, live company/accounting and physical printer are **NOT VERIFIED**. F0-01 and Phase 0 remain **OPEN**. No Auth server/RLS/role/schema or stored finance data mutated. Next safest step is authenticated owner-device F0-01 test (without sharing any credential) and targeted read-only timings for login to workspace; only if latency persists consider a separately tested data-hydration change. Rollback: revert merged #104 and gated redeploy, no DB rollback.
49
50 +### 2026-10-12 P0 owner photo: inert login connectivity button / lingering session hydration (OPEN FIX)
51 +- **User evidence:** Owner's photographed latest production login shows `در حال آماده‌سازی محیط کار...` although no fresh credentials are visible, and clicking `بررسی اتصال به سرور ورود` reportedly has no visible response. This is **owner-reported real UI failure**, not evidence of an actual failed Auth HTTP request. Related [issue #106](https://github.com/davoodmehraban89/Factor-easy/issues/106).
52 +- **Confirmed source-level root cause for inert buttons under production CSP:** the Pages builder externalizes static `onclick` handlers into `js/generated-event-handlers.js` and appends that script only at the bottom of the HTML **after dozens of parser-blocking ERP scripts**, whereas `js/core.js` enables all login buttons and declares them ready early. Thus the user can click apparently enabled controls before their production event listeners are installed. Local (unbuilt) Chromium tests retain raw inline handlers, so existing coverage did not detect the gap.
53 +- **Separate suspected hang:** restored Supabase session calls `enterApp()` before a manual login and awaits `FinoraAppAssetsReady`, profile and sequential `pullAll()` without a bounded read timeout. The screenshot matches a pending restore but does not identify the precise stalled request.
54 +- **Implementation authority and safety:** change only Pages event-binding ordering and bounded READ-ONLY hydration with visible retry/error; ensure diagnostic handler is loaded before buttons enable; add realistic built Pages Chromium test with artificially stalled unrelated JS and a synthetic restored-session read. Preserve the legacy ERP script execution order and tenant-safe, atomic datastore replacement; no modification to Supabase Auth/RLS/roles/schema, stored financial records or real customer users.
55 +- **Acceptance:** demonstrate diagnostic click starts changing UI before intentionally delayed ERP script completes in built CSP artifact; synthetic stuck read must time out and return operable login without prematurely entering app; complete Golden/92+ Chromium/3 DB/Security checks and gated release; actual affected owner ISP acceptance still OPEN. Rollback narrow PR; no DB rollback.
56 +
57 ## Current change ledger
58 | 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. |
59
index.html
+5 -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-login-ready-v2" />
16 +<link rel="preload" as="script" href="js/core.js?v=20261012-login-wiring-v3" />
17 <link rel="preload" as="script" href="js/login-connectivity.js?v=20261011-login-triage-v1" />
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>
@@ -890,10 +890,12 @@ body{background:#f6f9fc}
890 <div class="dock-tab" data-view="view-settings" onclick="switchView('view-settings')"><span>⚙️</span><span>تنظیمات</span></div>
891 </nav>
892
893 -<script src="js/core.js?v=20261012-login-ready-v2"></script>
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=20261011-login-triage-v1"></script>
896 +<script src="js/core.js?v=20261012-login-wiring-v3"></script>
897 <script src="js/admin.js?v=20261012-provision-error-v1"></script>
896 -<script src="js/sync.js?v=20260928-data-v4"></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>
900 <script src="js/invoices.js?v=20261011-doc-draft-v1"></script>
901 <script src="js/print.js?v=20261012-clean-invoice-print-v1"></script>
js/bootstrap.js
+1 -1
@@ -3,7 +3,7 @@
3 // browsers may download in parallel but preserve script execution/dependencies.
4 // Auth starts only once all extensions have finished loading or failed.
5 const FINORA_EXTENSION_SCRIPTS=[
6 - "js/organization-rbac.js?v=20260930-slice-b-v1",
6 + "js/organization-rbac.js?v=20261012-login-scoped-read-v1",
7 "js/organization-invitations.js?v=20260930-eli3-v1",
8 "js/organization-enterprise-ux.js?v=20260930-eli4-v1",
9 "js/platform-modules.js?v=20261001-platform-c6-v1",
js/core.js
+47 -12
@@ -67,6 +67,20 @@ function setAuthLoginStatus(message,state){
67 const el=document.getElementById('auth-login-status');
68 if(el){el.textContent=message;el.dataset.state=state||'ready';}
69 }
70 +// Abort a stuck read or optional startup barrier without claiming a half-loaded
71 +// financial workspace is usable. Only the login hydration path uses this.
72 +function finoraAbortableRead(promise,signal){
73 + if(!signal)return Promise.resolve(promise);
74 + if(signal.aborted)return Promise.reject(new Error('FINORA_LOGIN_READ_TIMEOUT'));
75 + return new Promise((resolve,reject)=>{
76 + const abort=()=>{signal.removeEventListener('abort',abort);reject(new Error('FINORA_LOGIN_READ_TIMEOUT'));};
77 + signal.addEventListener('abort',abort,{once:true});
78 + Promise.resolve(promise).then(
79 + value=>{signal.removeEventListener('abort',abort);if(signal.aborted)reject(new Error('FINORA_LOGIN_READ_TIMEOUT'));else resolve(value);},
80 + err=>{signal.removeEventListener('abort',abort);reject(err);}
81 + );
82 + });
83 +}
84
85
86 const EMAIL_RE=/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
@@ -84,8 +98,10 @@ function buildUserFromRows(profile,lic){
98 const sub=hasLicense?{type:lic.plan,startDate:lic.starts_at,endDate:lic.ends_at,status:lic.status}:{type:'none',startDate:null,endDate:null,status:'unavailable'};
99 return {id:profile.id,email:profile.email||'',fullName:profile.full_name||'',username:profile.username||profile.email||'',role:profile.role,maxCompanies:hasLicense?Math.max(1,Number(lic.max_companies||1)):1,licenseCapacityServerReady:hasLicense&&Object.prototype.hasOwnProperty.call(lic,'max_companies'),subscription:sub,subscriptionType:sub.type,subscriptionStart:sub.startDate,subscriptionEnd:sub.endDate,licenseStatus:sub.status};
100 }
87 -async function fetchCurrentUser(authUser){
88 - const p=await sb.from('profiles').select('id,email,username,full_name,role').eq('id',authUser.id).single();
101 +async function fetchCurrentUser(authUser,{signal}={}){
102 + let query=sb.from('profiles').select('id,email,username,full_name,role').eq('id',authUser.id);
103 + if(signal&&typeof query.abortSignal==='function')query=query.abortSignal(signal);
104 + const p=await finoraAbortableRead(query.single(),signal);
105 if(p.error)throw p.error;
106 return buildUserFromRows(p.data,null);
107 }
@@ -138,9 +154,13 @@ async function initAuthSystem(){
154 const screen=document.getElementById('auth-screen');
155 if(screen)screen.style.display='flex';
156 showAuthPanel('main');
141 - if(screen)screen.querySelectorAll('button').forEach(button=>{button.disabled=false;});
142 - window.FinoraStartupStatus.authFormReady=true;
143 - setAuthLoginStatus('فرم ورود آماده است.','ready');
157 + // Production externalizes onclick attributes under strict CSP. Do not mark
158 + // the controls ready until those actual click listeners are registered.
159 + const builtHandlers=!!screen?.querySelector('[data-finora-handler-0]');
160 + const canUseActions=typeof checkAuthConnectivity==='function'&&(!builtHandlers||window.FinoraLoginActionsBound===true);
161 + if(canUseActions&&screen)screen.querySelectorAll('button').forEach(button=>{button.disabled=false;});
162 + window.FinoraStartupStatus.authFormReady=canUseActions;
163 + setAuthLoginStatus(canUseActions?'فرم ورود و دکمه‌ها آماده هستند.':'عملکرد دکمه‌های ورود بارگذاری نشده است؛ صفحه را دوباره بارگذاری کنید.',canUseActions?'ready':'error');
164 // Remove the legacy plaintext user database that older versions kept in this browser.
165 try{localStorage.removeItem(AUTH_KEY);}catch(e){}
166 try{sessionStorage.removeItem('easy_factor_session_v4_7');}catch(e){}
@@ -251,22 +271,37 @@ async function skipSetPassword(){
271 authBusy=true;
272 try{await enterApp(u);}finally{authBusy=false;}
273 }
254 -async function enterApp(authUser){
274 +async function enterApp(authUser,{timeoutMs=25000}={}){
275 + const controller=new AbortController();
276 + const timer=setTimeout(()=>controller.abort(),timeoutMs);
277 try{
256 - setAuthLoginStatus('در حال آماده‌سازی محیط کار...','loading');
257 - const [profile]=await Promise.all([fetchCurrentUser(authUser),window.FinoraAppAssetsReady]);
278 + setAuthLoginStatus('در حال بازیابی نشست و آماده‌سازی محیط کار...','loading');
279 + const [profile]=await Promise.all([
280 + fetchCurrentUser(authUser,{signal:controller.signal}),
281 + finoraAbortableRead(window.FinoraAppAssetsReady,controller.signal)
282 + ]);
283 + if(controller.signal.aborted)throw new Error('FINORA_LOGIN_READ_TIMEOUT');
284 currentUser=profile;
285 setAuthLoginStatus('در حال دریافت اطلاعات شرکت...','loading');
260 - await pullAll();
286 + await finoraAbortableRead(pullAll({signal:controller.signal}),controller.signal);
287 + if(controller.signal.aborted)throw new Error('FINORA_LOGIN_READ_TIMEOUT');
288 const prefs=typeof getMySettings==='function'?getMySettings():null;if(prefs?.user_display_name&&!currentUser.fullName)currentUser.fullName=prefs.user_display_name;if(prefs?.professional_role)currentUser.professionalRole=prefs.professional_role;
289 }catch(err){
263 - console.error(err);
290 currentUser=null;
265 - setAuthLoginStatus('دریافت اطلاعات حساب ناموفق بود؛ اتصال را بررسی و دوباره تلاش کنید.','error');
266 - alert('خطا در بارگذاری اطلاعات حساب. اتصال اینترنت را بررسی کنید و دوباره وارد شوید.');
291 + const timedOut=controller.signal.aborted||err?.message==='FINORA_LOGIN_READ_TIMEOUT';
292 + if(timedOut){
293 + console.warn('Finora login read timed out (no identity or private data logged).');
294 + setAuthLoginStatus('دریافت اطلاعات حساب بیش از حد طول کشید. اتصال سرور را بررسی کنید و ورود را دوباره انجام دهید.','error');
295 + }else{
296 + console.error('Finora account hydration failed',err);
297 + setAuthLoginStatus('دریافت اطلاعات حساب ناموفق بود؛ اتصال را بررسی و دوباره تلاش کنید.','error');
298 + alert('خطا در بارگذاری اطلاعات حساب. اتصال اینترنت را بررسی کنید و دوباره وارد شوید.');
299 + }
300 document.getElementById('auth-screen').style.display='flex';
301 showAuthPanel('main');
302 return;
303 + }finally{
304 + clearTimeout(timer);
305 }
306 // Post-login UI. Every step is null-safe / isolated so that one missing element or one failing
307 // render can never abort the rest and leave the app empty (previous bug: #menu-admin-panel).
js/organization-rbac.js
+21 -8
@@ -1,8 +1,15 @@
1 /* Finora Slice B organization context + member capabilities. Server RLS remains authoritative. */
2 (function(){
3 const baseFetchCurrentUser=fetchCurrentUser;
4 -async function loadOrganizationContext(user){
5 - const {data:members,error:memberError}=await sb.from('organization_members').select('id,organization_id,unit_id,position_title,status,is_owner').eq('user_id',user.id).eq('status','active');
4 +// Forward read-only timeout through the actual membership/license lookups.
5 +async function finoraOrganizationRead(query,signal){
6 + if(signal&&typeof query.abortSignal==='function')query=query.abortSignal(signal);
7 + const result=await finoraAbortableRead(query,signal);
8 + if(signal?.aborted)throw new Error('FINORA_LOGIN_READ_TIMEOUT');
9 + return result;
10 +}
11 +async function loadOrganizationContext(user,{signal}={}){
12 + const {data:members,error:memberError}=await finoraOrganizationRead(sb.from('organization_members').select('id,organization_id,unit_id,position_title,status,is_owner').eq('user_id',user.id).eq('status','active'),signal);
13 if(memberError)throw memberError;
14 const orgIds=(members||[]).map(x=>x.organization_id);
15 if(!orgIds.length)throw new Error('عضویت سازمانی برای این کاربر تعریف نشده است.');
@@ -14,7 +21,8 @@ async function loadOrganizationContext(user){
21 sb.from('organization_roles').select('id,organization_id,role_key,title,active,is_system').in('organization_id',orgIds).eq('active',true),
22 sb.from('organization_role_permissions').select('id,organization_id,role_id,module_key,capabilities,scope_type,scope_id,confidentiality_level').in('organization_id',orgIds),
23 sb.from('organization_member_roles').select('id,organization_id,member_id,role_id,active').in('organization_id',orgIds).eq('active',true)
17 - ]);
24 + ].map(query=>finoraOrganizationRead(query,signal)));
25 + if(signal?.aborted)throw new Error('FINORA_LOGIN_READ_TIMEOUT');
26 if(orgError)throw orgError;if(permError)throw permError;if(licenseError)throw licenseError;if(seatError)throw seatError;if(roleError)throw roleError;if(rolePermError)throw rolePermError;if(memberRoleError)throw memberRoleError;
27 const contexts=(members||[]).map(m=>{
28 const assignments=(memberRoles||[]).filter(x=>x.member_id===m.id&&x.organization_id===m.organization_id);
@@ -47,7 +55,7 @@ async function loadOrganizationContext(user){
55 user.subscription=sub;user.subscriptionType=sub.type;user.subscriptionStart=sub.startDate;user.subscriptionEnd=sub.endDate;user.licenseStatus=sub.status;
56 return user;
57 }
50 -fetchCurrentUser=async function(authUser){return loadOrganizationContext(await baseFetchCurrentUser(authUser))};
58 +fetchCurrentUser=async function(authUser,options={}){return loadOrganizationContext(await baseFetchCurrentUser(authUser,options),options)};
59 let finoraMembershipRevalidationBusy=false;
60 function clearFinoraTenantMemory(userId){
61 clearTimeout(syncTimer);syncPending=false;syncAgain=false;syncFailCount=0;syncSnap.clear();
@@ -94,16 +102,21 @@ window.hasFinoraCapability=function(moduleKey,capability='read'){
102 return (currentUser.modulePermissions||[]).some(p=>(p.module_key===moduleKey||p.module_key==='full_suite')&&Array.isArray(p.capabilities)&&p.capabilities.includes(capability));
103 };
104 const legacyPullAll=pullAll;
97 -pullAll=async function(){
98 - if(!currentUser?.organizationId)return legacyPullAll();
99 - const uid=currentUser.id,fresh={};COLLS.forEach(k=>fresh[k]=[]);
105 +pullAll=async function(options={}){
106 + const signal=options?.signal;
107 + if(!currentUser?.organizationId)return legacyPullAll(options);
108 + const uid=currentUser.id,orgId=currentUser.organizationId,fresh={};COLLS.forEach(k=>fresh[k]=[]);
109 const snap=new Map(),page=1000;let from=0;
110 for(;;){
102 - const {data,error}=await sb.from('records').select('collection,id,data,owner_id,organization_id').eq('organization_id',currentUser.organizationId).order('collection').order('id').range(from,from+page-1);
111 + const request=sb.from('records').select('collection,id,data,owner_id,organization_id').eq('organization_id',orgId).order('collection').order('id').range(from,from+page-1);
112 + const {data,error}=await finoraOrganizationRead(request,signal);
113 if(error)throw error;
114 (data||[]).forEach(r=>{if(!fresh[r.collection])return;const obj=(r.data&&typeof r.data==='object'&&!Array.isArray(r.data))?r.data:{};obj.id=r.id;snap.set(r.collection+'|'+r.id,JSON.stringify(stripOwner(obj)));obj.ownerUserId=uid;fresh[r.collection].push(obj)});
115 if(!data||data.length<page)break;from+=page;
116 }
117 + // Never apply an aborted/stale company snapshot to the active tenant.
118 + if(signal?.aborted)throw new Error('FINORA_LOGIN_READ_TIMEOUT');
119 + if(currentUser?.id!==uid||currentUser.organizationId!==orgId)throw new Error('FINORA_ORGANIZATION_CONTEXT_CHANGED');
120 datastore=fresh;syncSnap.clear();snap.forEach((v,k)=>syncSnap.set(k,v));
121 };
122 runSync=async function(){
js/sync.js
+8 -2
@@ -30,13 +30,16 @@ function setSyncBadge(state){
30 clearTimeout(setSyncBadge._t);
31 if(state==='saved')setSyncBadge._t=setTimeout(()=>{el.style.display='none';},2000);
32 }
33 -async function pullAll(){
33 +async function pullAll({signal}={}){
34 const uid=currentUser.id;
35 const fresh={};COLLS.forEach(k=>{fresh[k]=[];});
36 const snap=new Map();
37 const page=1000;let from=0;
38 for(;;){
39 - const {data,error}=await sb.from('records').select('collection,id,data').order('collection').order('id').range(from,from+page-1);
39 + let request=sb.from('records').select('collection,id,data').order('collection').order('id').range(from,from+page-1);
40 + if(signal&&typeof request.abortSignal==='function')request=request.abortSignal(signal);
41 + const {data,error}=await finoraAbortableRead(request,signal);
42 + if(signal?.aborted)throw new Error('FINORA_LOGIN_READ_TIMEOUT');
43 if(error)throw error;
44 (data||[]).forEach(r=>{
45 if(!fresh[r.collection])return;
@@ -49,6 +52,9 @@ async function pullAll(){
52 if(!data||data.length<page)break;
53 from+=page;
54 }
55 + // A timed-out restore must never replace current local data from a late
56 + // response or publish a partial snapshot; writes still use existing guards.
57 + if(signal?.aborted)throw new Error('FINORA_LOGIN_READ_TIMEOUT');
58 datastore=fresh;
59 syncSnap.clear();snap.forEach((v,k)=>syncSnap.set(k,v));
60 }
scripts/build-pages.mjs
+7 -2
@@ -53,9 +53,14 @@ html=html.replace(/script-src[^;]*/i,"script-src 'self' https://cdnjs.cloudflare
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>');
56 +// Login buttons are enabled by core.js *during HTML parsing*. Bind their
57 +// CSP-safe static handlers first, not after dozens of blocking ERP modules.
58 +const authEntrypoint=/<script src="js\/core\.js\?v=[^"]+"><\/script>/i;
59 +if(!authEntrypoint.test(html))throw new Error('Missing auth entrypoint for early event binding');
60 +html=html.replace(authEntrypoint,tag=>'<script src="js/generated-event-handlers.js"></script>\n'+tag);
61 +html=html.replace('</body>','<script src="js/generated-dynamic-handlers.js"></script>\n</body>');
62
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`;
63 +const generated=`// Generated at build time from legacy static inline event attributes.\n(function(){\nwindow.FinoraLoginActionsBound=false;\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')}\nwindow.FinoraLoginActionsBound=true;\n})();\n`;
64
65 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`;
66
scripts/login-connectivity-check.mjs
+4 -1
@@ -7,10 +7,13 @@ 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=20261011-login-triage-v1'),'Missing versioned script');
10 -assert(html.includes('js/core.js?v=20261012-login-ready-v2'),'New login core must have a distinct production cache version');
10 +assert(html.includes('js/core.js?v=20261012-login-wiring-v3'),'Production login controls must use new cache version');
11 +assert(html.indexOf('<script src="js/login-connectivity.js?v=20261011-login-triage-v1"')<html.indexOf('<script src="js/core.js?v=20261012-login-wiring-v3"'),'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');
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');
16 +assert(core.includes('FINORA_LOGIN_READ_TIMEOUT'),'Restored-session reads must have bounded wait and visible fallback');
17 assert(core.includes('isAuthNetworkError(err)'),'Network error diagnostic not wired');
18 assert(!core.includes('اتصال اینترنت/VPN را بررسی کنید'),'Misleading VPN-only error text remains');
19 assert(diagnostic.includes("'/auth/v1/health'"),'Must test the real GoTrue health path');
scripts/pages-artifact.spec.js
+30
@@ -25,3 +25,33 @@ test('hardened Pages artifact loads without script/CSP console errors',async({pa
25 expect(diag.status()).toBe(404);
26 expect(errors).toEqual([]);
27 });
28 +
29 +
30 +test('Production CSP login and connectivity actions work while later ERP JS is still downloading',async({page})=>{
31 + let delayedModuleFinished=false;
32 + await page.route('**/js/phase6-reporting.js*',async route=>{
33 + await new Promise(resolve=>setTimeout(resolve,5000));
34 + delayedModuleFinished=true;
35 + await route.continue();
36 + });
37 + await page.route('**/auth/v1/health',route=>route.fulfill({
38 + status:200,
39 + contentType:'application/json',
40 + headers:{'access-control-allow-origin':'*','access-control-allow-headers':'apikey, authorization, content-type, x-client-info','access-control-allow-methods':'GET, OPTIONS'},
41 + body:'{"status":"ok"}'
42 + }));
43 + // The actual hardened Pages output removes inline onclick attributes.
44 + await page.goto(base,{waitUntil:'commit'});
45 + await expect(page.locator('#auth-connectivity-check')).toBeEnabled({timeout:4000});
46 + expect(await page.evaluate(()=>window.FinoraLoginActionsBound)).toBe(true);
47 + expect(delayedModuleFinished,'Login actions must be wired before slow ERP scripts').toBe(false);
48 + await page.locator('#auth-connectivity-check').click();
49 + await expect(page.locator('#auth-connectivity-result')).toContainText('AUTH_OK',{timeout:2500});
50 + expect(delayedModuleFinished,'Connectivity check must not await unrelated modules').toBe(false);
51 + const alertHandled=page.waitForEvent('dialog').then(async d=>{
52 + expect(d.message()).toContain('ایمیل');
53 + await d.dismiss();
54 + });
55 + await Promise.all([page.locator('#auth-login-button').click(),alertHandled]);
56 + expect(delayedModuleFinished).toBe(false);
57 +});
scripts/phase0-startup-performance.spec.js
+89
@@ -110,3 +110,92 @@ test('F0 auth transport times out stalled requests without affecting other Supab
110 {url:'https://example.test/rest/v1/records',signal:false}
111 ]);
112 });
113 +
114 +
115 +test('F0 restored session with stalled company data returns actionable error instead of endless loading',async({page})=>{
116 + await page.goto(BASE,{waitUntil:'domcontentloaded'});
117 + await expect.poll(()=>page.evaluate(()=>window.FinoraStartupStatus?.authChecked),{timeout:15000}).toBe(true);
118 + const actual=await page.evaluate(async()=>{
119 + window.fetchCurrentUser=async()=>({id:'synthetic-restore',email:'fixture@example.test',role:'accountant'});
120 + window.pullAll=async()=>new Promise(()=>{}); // Intentionally unresolved read only, no account/database write.
121 + await enterApp({id:'synthetic-restore'},{timeoutMs:60});
122 + return {
123 + state:document.getElementById('auth-login-status').dataset.state,
124 + message:document.getElementById('auth-login-status').textContent,
125 + visible:getComputedStyle(document.getElementById('auth-screen')).display,
126 + currentUser:currentUser
127 + };
128 + });
129 + expect(actual.state).toBe('error');
130 + expect(actual.message).toContain('بیش از حد');
131 + expect(actual.visible).toBe('flex');
132 + expect(actual.currentUser).toBe(null);
133 + await expect(page.locator('#auth-connectivity-check')).toBeEnabled();
134 +});
135 +
136 +test('F0 cancelled company records read cannot apply a late partial datastore snapshot',async({page})=>{
137 + await page.goto(BASE,{waitUntil:'domcontentloaded'});
138 + await expect.poll(()=>page.evaluate(()=>window.FinoraStartupStatus?.authChecked),{timeout:15000}).toBe(true);
139 + const unchanged=await page.evaluate(async()=>{
140 + const originalFrom=sb.from;
141 + const originalUser=currentUser;
142 + currentUser={id:'fixture-read-only'};
143 + const before=datastore;
144 + const controller=new AbortController();
145 + sb.from=()=>({
146 + select(){return this;},order(){return this;},range(){return this;},
147 + abortSignal(){return this;},
148 + then(resolve){setTimeout(()=>resolve({data:[{collection:'products',id:'dummy',data:{name:'should-not-commit'}}],error:null}),75);}
149 + });
150 + try{
151 + const pending=pullAll({signal:controller.signal}).catch(()=>{});
152 + // Abort synchronously, before the deliberately late thenable resolves.
153 + // A tiny delayed abort introduces unrelated CI scheduling variability.
154 + controller.abort();
155 + await pending;
156 + await new Promise(resolve=>setTimeout(resolve,110));
157 + return {
158 + sameSnapshot:datastore===before,
159 + noDummyRecord:!(datastore.products||[]).some(p=>p.id==='dummy'),
160 + noDummySnapshot:!syncSnap.has('products|dummy'),
161 + aborted:controller.signal.aborted,
162 + runtimeHasCancelGuard:String(pullAll).includes('FINORA_LOGIN_READ_TIMEOUT')
163 +
164 + };
165 + }finally{
166 + sb.from=originalFrom;currentUser=originalUser;
167 + }
168 + });
169 + expect(unchanged).toEqual({sameSnapshot:true,noDummyRecord:true,noDummySnapshot:true,aborted:true,runtimeHasCancelGuard:true});
170 +});
171 +
172 +
173 +test('F0 organization-scoped record hydration respects abort and tenant boundary',async({page})=>{
174 + await page.goto(BASE,{waitUntil:'domcontentloaded'});
175 + await expect.poll(()=>page.evaluate(()=>window.FinoraStartupStatus?.authChecked),{timeout:15000}).toBe(true);
176 + const observed=await page.evaluate(async()=>{
177 + const originalFrom=sb.from,oldUser=currentUser,previous=datastore;
178 + let requestedOrganization='';
179 + currentUser={id:'fixture-user',organizationId:'org-fixture'};
180 + const controller=new AbortController();
181 + sb.from=()=>({
182 + select(){return this;},order(){return this;},range(){return this;},
183 + eq(field,value){if(field==='organization_id')requestedOrganization=value;return this;},
184 + abortSignal(){return this;},
185 + then(resolve){setTimeout(()=>resolve({data:[{collection:'products',id:'never-commit',data:{name:'fixture'}}],error:null}),80);}
186 + });
187 + try{
188 + const task=pullAll({signal:controller.signal}).catch(()=>{});
189 + controller.abort();
190 + await task;
191 + await new Promise(resolve=>setTimeout(resolve,120));
192 + return {
193 + selectedTenant:requestedOrganization,
194 + preserved:datastore===previous,
195 + noLeakedDummy:!(datastore.products||[]).some(x=>x.id==='never-commit'),
196 + noStaleSnapshot:!syncSnap.has('products|never-commit')
197 + };
198 + }finally{sb.from=originalFrom;currentUser=oldUser;}
199 + });
200 + expect(observed).toEqual({selectedTenant:'org-fixture',preserved:true,noLeakedDummy:true,noStaleSnapshot:true});
201 +});