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

fix(auth): bound complete responses and serialize cold login startup

davoodmehraban89 committed Oct 24, 2026 at 07:48 UTC 71d1ae1f09a4d0429068360b3292ae6cdb133143
11 files changed +504 -43
.github/workflows/quality.yml
+1 -1
@@ -123,7 +123,7 @@ jobs:
123 - name: Real DOM smoke
124 run: |
125 python3 -m http.server 4173 >/tmp/finora-http.log 2>&1 &
126 - npx playwright test scripts/phase0-startup-performance.spec.js 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/identity-wave5c.spec.js scripts/branding-login.spec.js scripts/login-connectivity.spec.js scripts/shell-scroll-ownership.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/chart-completeness.spec.js scripts/accounting-p0-journal.spec.js scripts/ux-hardening-r2.spec.js scripts/ux-keyboard-f2.spec.js scripts/phase0-dark-theme-contrast.spec.js scripts/phase0-selector-stress.spec.js scripts/phase0-invoice-persistence.spec.js scripts/phase0-modal-dashboard.spec.js scripts/accounting-document-workflow.spec.js scripts/admin-provisioning.spec.js scripts/pages-artifact.spec.js --reporter=line --workers=1
126 + npx playwright test scripts/login-auth-transport.spec.js scripts/login-startup-readiness.spec.js scripts/phase0-startup-performance.spec.js 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/identity-wave5c.spec.js scripts/branding-login.spec.js scripts/login-connectivity.spec.js scripts/shell-scroll-ownership.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/chart-completeness.spec.js scripts/accounting-p0-journal.spec.js scripts/ux-hardening-r2.spec.js scripts/ux-keyboard-f2.spec.js scripts/phase0-dark-theme-contrast.spec.js scripts/phase0-selector-stress.spec.js scripts/phase0-invoice-persistence.spec.js scripts/phase0-modal-dashboard.spec.js scripts/accounting-document-workflow.spec.js scripts/admin-provisioning.spec.js scripts/pages-artifact.spec.js --reporter=line --workers=1
127
128 identity-wave5a-database:
129 runs-on: ubuntu-latest
PROJECT_STATE.md
+10
@@ -38,3 +38,13 @@
38 ### 2026-10-16 Phase 0 post-merge Chromium intermittent fixture (QA-only follow-up; NOT application defect proven)
39 - **Original Phase 0 PR:** #160 merged exact-main `67be4fbfa6161156b10ce6279445266c989e97d3`. PR-head Quality `38867730181` 123/123 Chromium PASS, isolated DB and Security PASS. Protected main Quality `38868319174` attempt 1 **FAIL 122/123** at `scripts/phase0-invoice-persistence.spec.js:52`, `#auth-screen` remained visible for 5 seconds; all three DB jobs and Security `38868319200` succeeded. Same-SHA failed-job rerun attempt 2 was requested; result must be verified separately. Neither result proves actual production financial persistence or login failure.
40 - **Source-reproduced test harness race:** `authenticatedMockBrowser` waits only for `enterApp`, `commitSaveInvoice`, `pullAll` functions before installing a fake authenticated identity; asynchronously loaded `organization-rbac` wrapper can supersede the fake identity. Prior `scripts/accounting-document-workflow.spec.js:36–43` already fixes the identical fixture ordering issue by waiting for `FinoraStartupStatus.extensionsReady`, zero failed extensions, and `authChecked`. Apply the same pre-mock readiness condition **only in this synthetic invoice test**; preserve all UI, Supabase/Auth/RLS, financial accounting and live record behavior. Require Quality 123/123, Security and all three disposable DB on exact repair SHA; then controlled protected merge and same-main checks. Rollback is a test-only revert. All owner-ISP and real invoice E2E remain NOT VERIFIED.
41 +
42 +### 2026-10-24 — Owner-requested cold-login investigation and repair (in progress)
43 +- Owner reports repeated 1–2 minute cold-page waits and failed early sign-in on multiple PCs; requests full diagnosis, application/service log review, reproduction and repair. This new request authorizes scoped client login/startup corrections and read-only service-log inspection, separate from unmerged navigation #174 and settings #175. It does not authorize production configuration/Auth policies/schema/data writes, merge/deploy or Phase B.
44 +- Live main verified `bccd474433b4188e43aae345773498ea6fc65209`; isolated worktree `/workspace/Factor-easy-login`, branch `fix/login-startup-readiness-20261024`. Existing Issue #106 remains open; prior CI success is not owner-ISP acceptance.
45 +- Initial investigation: verify response-header vs body timeout lifetime using the actual bundled SDK; reproduce early sign-in while production parser-blocking bundles are delayed; inspect credential-free diagnostic classification. Service metadata reports ACTIVE_HEALTHY; read-only log stream (not production Postgres SQL) is accessible. No production sign-in attempt, token, customer/financial row or write is needed for reproduction.
46 +- Required evidence: failing synthetic regressions first, minimal fix, slow/failing startup and credential-error distinctions, full existing browser/static/Golden suite, Pages CSP artifact, exact-head remote CI and independent review. Real owner-ISP cold login and any historical attempt that cannot be correlated remain NOT VERIFIED.
47 +- **Verified cause and implementation:** [investigation report](docs/LOGIN_STARTUP_REPAIR_2026-10-24.md). Auth's timer previously stopped at response headers, leaving SDK body reads unbounded; it now lasts through the complete body. Generated Pages early-click tests proved asset downloads consumed the account-read deadline; assets now have a separate bounded stage, and the existing account/data deadline starts afterward. Initial session checking queues a manual click once; automatic restore owns `authBusy`. The unchanged SHA-pinned extension bundle preloads before later blocking groups finish, with original execution order. Diagnostic probes record independent timeout/network results. No financial engine, sync, organization access, posted data or frozen-module implementation changed.
48 +- **Executed local evidence:** expected RED observed for stalled Auth body/upstream body cancellation, early business/accounting downloads, competing restoration/password entry, pending initial session check, delayed extension dispatch, asset-stage expiry and mixed probe errors. Then **34/34 focused PASS (1.6m)** and full exact Quality browser command **138/138 PASS (2.9m)**: baseline 123 + 15 new cases, including generated strict-CSP Pages, existing A4/A5 printing and tenant/late-snapshot guards. All **50** existing static/behavioral/backup/release-safety commands PASS, including Golden Accounting; `git diff --check` PASS. Source blobs: core `ac9d45faa068fe748a038a219a7dd5fd8a33e3e8`, diagnostic `4dd327e398abc4928aef9ff4d6701e5f9d6b82f7`, build `9cb48ba5ad8516d1b5d57ea390990b12d03a487c`. Independent application/security whole-diff review has no remaining findings. The local cloud font workaround remained process-only; no font-related application change, weakened assertion or print-code edit was made.
49 +- **Service evidence:** management metadata ACTIVE_HEALTHY; read-only unified logs (24-hour window, not production Postgres SQL) showed five successful password responses and two HTTP400 `invalid_credentials`, with no basis to attribute the two failures to the friend's exact attempt. Pinned SDK source/controlled experiment confirms refresh initialization can delay session-token reads; its refresh commit guard preserved manual session identity. No WebLocks or SDK data-corruption claim is made. Issue #106 independently verified OPEN.
50 +- **Release/next work:** client fix is tested/reviewed and ready for a separate PR; exact remote SHA, tree and CI/job evidence will be maintained in that PR description. No merge/deploy or production write/configuration was performed. NOT VERIFIED: affected owner/friend ISP/browser, exact historical failed request identity, real OTP/Google delivery, physical printing, production two-user behavior. Do not close #106 on synthetic CI alone; release exact SHA and obtain affected-device acceptance. Navigation #174/settings #175 remain separate; Phase B is not authorized. Rollback is reverting this scoped login PR.
docs/LOGIN_STARTUP_REPAIR_2026-10-24.md new
+61
@@ -0,0 +1,61 @@
1 +# Cold login investigation — 2026-10-24
2 +
3 +Owner request: investigate the recurring slow login page, failed early password
4 +attempts and the screenshot `SITE_JS_OK | MANIFEST_OK | AUTH_TIMEOUT | REST_TIMEOUT`.
5 +Baseline: live protected main `bccd474433b4188e43aae345773498ea6fc65209`.
6 +This repair is independent of navigation PR #174 and settings PR #175.
7 +
8 +## Reproduced defects and corrections
9 +
10 +| Defect proved on the baseline | Correction | Regression evidence |
11 +| --- | --- | --- |
12 +| Auth fetch's 12-second timer ended when headers arrived. The actual bundled SDK could then wait indefinitely for an incomplete JSON body. | Keep the deadline and upstream cancellation active through a cloned response body; return the original unread Response. Non-Auth requests retain their original streaming semantics. | Real SDK password operation with immediate headers and stalled body fails with a retryable transport error; expired-session refresh recovers; complete invalid-credentials response remains distinct. |
13 +| An early successful password attempt spent the 25-second account-read deadline waiting for parser-blocking Pages bundles and the organization adapter. | Give workspace assets a separate bounded 45-second stage, then start the existing 25-second profile/company-read deadline. Keep the successful-auth progress message accurate. | Generated strict-CSP Pages with business/accounting downloads held for 26 simulated seconds remains pending, then opens once with the correct organization and lifetime entitlement. |
14 +| Cached-session hydration did not own `authBusy`; early manual login could run a competing hydration. Password authentication could also start while SDK initialization still held up session-token reads. | Claim busy ownership during automatic entry; queue one manual click behind the shared initial session check. | Restored-session/manual overlap and a held initial session check each produce one profile/records hydration, without a second click or writes. |
15 +| The 213 KB production extension bundle was only requested after DOMContentLoaded, after all blocking workspace groups. | Preload the identical content-hashed local bundle while those groups download; execution stays in the original dependency order. | Request observed before a held accounting bundle is released; exactly one request/execution and all 14 extensions complete. |
16 +| Diagnostic classification checked a shared abort signal after all probes settled. An immediate network rejection became a misleading TIMEOUT when another probe later timed out. | Each probe owns its deadline and records its own outcome. Cancel unused response bodies after header evidence. | Immediate Auth/site-JS network failures retain their original codes when a different probe stalls. |
17 +
18 +Failed or expired asset waits remain fail-closed: no partial financial workspace,
19 +no profile or company read before readiness, and no late automatic entry after
20 +expiry. After downloads recover, a fresh click succeeds. Missing required bundles
21 +still show `BOOT_APP_ASSETS_FAILED`.
22 +
23 +## Service observations and their limits
24 +
25 +Read-only Supabase management metadata reported `ACTIVE_HEALTHY`. Read-only log
26 +stream inspection covered the then-current 24-hour window; it did not query the
27 +production Postgres database or customer records. Five password `/token` responses
28 +were successful and two were HTTP 400 `invalid_credentials`. The failed responses
29 +were in the 2026-10-23 18:00 UTC hour, along with four successful password responses;
30 +one earlier successful response was in the 17:00 UTC hour.
31 +
32 +The server logs do not identify which browser-side stage the screenshot captured.
33 +They cannot establish that the two rejected attempts were the friend's attempts,
34 +or distinguish an unknown account from a wrong password. A request that never
35 +reaches the service cannot appear in its Auth logs. The screenshot is a transport
36 +diagnostic, not a password check. No claim is made that the user's network is now
37 +repaired or that waiting longer would make an invalid password succeed.
38 +
39 +No real sign-in, Auth configuration change, SQL, migration, role/grant, RLS,
40 +financial write, dependency change or production deployment was performed.
41 +
42 +## Verification and release gate
43 +
44 +The new failures were observed before their corresponding fixes. Local RED/GREEN
45 +logs are `/tmp/finora-login-auth-transport-{red,green}.log`,
46 +`/tmp/finora-login-diagnostic-{red,green}.log`,
47 +`/tmp/finora-login-readiness-red.log`,
48 +`/tmp/finora-login-assets-recovery-red.log`, and
49 +`/tmp/finora-login-initial-session-red.log`.
50 +
51 +Full-suite results and exact-head remote CI are recorded in `PROJECT_STATE.md`
52 +and the associated PR description. Two new browser suites are explicitly included
53 +in the existing Quality workflow; no existing assertion or accounting expectation
54 +was relaxed. Independent read-only application/security review found no remaining
55 +findings. Reverting this PR restores the previous client/build behavior.
56 +
57 +**NOT VERIFIED:** cold login on the owner's/friend's actual ISP and browser;
58 +the exact historical failed identity/request; real OTP/Google delivery;
59 +physical printing; authenticated production concurrency. Issue #106 remains open.
60 +Customer acceptance requires a released exact SHA and the affected-device check;
61 +green synthetic tests alone do not close it.
index.html
+4 -4
@@ -13,8 +13,8 @@
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=20261014-org-license-readiness-v1" />
17 -<link rel="preload" as="script" href="js/login-connectivity.js?v=20261012-data-probe-v3" />
16 +<link rel="preload" as="script" href="js/core.js?v=20261024-login-readiness-v1" />
17 +<link rel="preload" as="script" href="js/login-connectivity.js?v=20261024-independent-probes-v4" />
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>
20 <link id="finora-optional-font" rel="stylesheet" media="print" href="https://cdn.jsdelivr.net/gh/rastikerdar/vazirmatn@v33.003/misc/Farsi-Digits/Vazirmatn-FD-font-face.css" />
@@ -892,8 +892,8 @@ body{background:#f6f9fc}
892
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=20261014-org-license-readiness-v1"></script>
895 +<script src="js/login-connectivity.js?v=20261024-independent-probes-v4"></script>
896 +<script src="js/core.js?v=20261024-login-readiness-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>
js/core.js
+42 -23
@@ -34,8 +34,8 @@ const SUPABASE_URL='https://hcsixhqbyuhpshfwqpjx.supabase.co';
34 const SUPABASE_KEY='sb_publishable_2y8IsGdhqeLDPkEp7mBF4w_X4yji16D'; // publishable (public by design); access is enforced by RLS on the server
35 // Browser fetch otherwise may hang indefinitely on unstable ISPs. Bound only
36 // Auth transport requests; financial record requests keep their own semantics.
37 -// This abort releases the Auth SDK lock and permits a clear, retryable error.
38 -function finoraBoundedAuthFetch(input,init={},timeoutMs=12000){
37 +// This abort ends the pending transport read and permits a retryable error.
38 +async function finoraBoundedAuthFetch(input,init={},timeoutMs=12000){
39 const url=typeof input==='string'?input:String(input?.url||input||'');
40 if(!url.includes('/auth/v1/'))return fetch(input,init);
41 const controller=new AbortController();
@@ -44,10 +44,15 @@ function finoraBoundedAuthFetch(input,init={},timeoutMs=12000){
44 if(upstream?.aborted)controller.abort();
45 else if(upstream)upstream.addEventListener('abort',abortFromUpstream,{once:true});
46 const timeout=setTimeout(()=>controller.abort(),timeoutMs);
47 - return fetch(input,{...init,signal:controller.signal}).finally(()=>{
47 + try{
48 + const response=await fetch(input,{...init,signal:controller.signal});
49 + // Fetch resolves at headers; keep the deadline until the Auth body arrives.
50 + await response.clone().arrayBuffer();
51 + return response;
52 + }finally{
53 clearTimeout(timeout);
54 if(upstream)upstream.removeEventListener('abort',abortFromUpstream);
50 - });
55 + }
56 }
57 const sb=window.supabase.createClient(SUPABASE_URL,SUPABASE_KEY,{global:{fetch:finoraBoundedAuthFetch},auth:{persistSession:true,autoRefreshToken:true,detectSessionInUrl:true,flowType:'pkce'}});
58 const ID_RE=/^[A-Za-z0-9_-]{1,64}$/;
@@ -194,6 +199,7 @@ function reportOAuthReturnError(){
199 }catch(e){}
200 }
201 let finoraAuthInitStarted=false;
202 +let finoraInitialSessionCheck=Promise.resolve();
203 async function initAuthSystem(){
204 if(finoraAuthInitStarted)return;
205 finoraAuthInitStarted=true;
@@ -213,8 +219,13 @@ async function initAuthSystem(){
219 reportOAuthReturnError();
220 sb.auth.onAuthStateChange(ev=>{if(ev==='SIGNED_OUT'&&currentUser){window.location.reload();}});
221 try{
216 - const {data}=await sb.auth.getSession();
217 - if(data&&data.session&&!authBusy){await enterApp(data.session.user);return;}
222 + finoraInitialSessionCheck=sb.auth.getSession();
223 + const {data}=await finoraInitialSessionCheck;
224 + if(data&&data.session&&!authBusy){
225 + authBusy=true;
226 + try{await enterApp(data.session.user);}finally{authBusy=false;}
227 + return;
228 + }
229 }catch(e){console.error(e);}
230 finally{
231 window.FinoraStartupStatus.authSessionChecked=true;
@@ -231,12 +242,18 @@ async function handleLogin(){
242 if(!EMAIL_RE.test(email)){alert('آدرس ایمیل معتبر وارد کنید.');return;}
243 if(!pass){alert('رمز عبور را وارد کنید؛ یا «ادامه با کد ایمیل» را بزنید.');return;}
244 authBusy=true;
234 - setAuthLoginStatus('در حال بررسی اطلاعات ورود...','loading');
235 - const slowNotice=setTimeout(()=>setAuthLoginStatus('پاسخ سرور ورود طولانی شده است. اگر ادامه یافت از «بررسی اتصال به سرور ورود» استفاده کنید.','slow'),9000);
245 + setAuthLoginStatus('در حال بررسی نشست قبلی و اطلاعات ورود...','loading');
246 + let slowNotice;
247 try{
248 + // A restored SDK refresh can still hold up later authenticated reads.
249 + // Queue this click once, before starting the separate password request.
250 + await finoraInitialSessionCheck.catch(()=>{});
251 + setAuthLoginStatus('در حال بررسی اطلاعات ورود...','loading');
252 + slowNotice=setTimeout(()=>setAuthLoginStatus('پاسخ سرور ورود طولانی شده است. اگر ادامه یافت از «بررسی اتصال به سرور ورود» استفاده کنید.','slow'),9000);
253 const {data,error}=await sb.auth.signInWithPassword({email,password:pass});
254 if(error)throw error;
255 if(!data?.user)throw new Error('No authenticated user was returned');
256 + clearTimeout(slowNotice);
257 setAuthLoginStatus('ورود تأیید شد؛ در حال آماده‌سازی محیط و اطلاعات شرکت...','loading');
258 await enterApp(data.user);
259 }catch(err){
@@ -320,23 +337,24 @@ async function skipSetPassword(){
337 async function enterApp(authUser,{timeoutMs=25000}={}){
338 const controller=new AbortController();
339 let timeoutStageCodes=[];
323 - const timer=setTimeout(()=>{
340 + const abortLogin=()=>{
341 timeoutStageCodes=finoraPendingLoginStages(); // capture before aborted promises clear
342 controller.abort();
326 - },timeoutMs);
343 + };
344 + let timer=setTimeout(abortLogin,45000);
345 try{
328 - setAuthLoginStatus('در حال بازیابی نشست و آماده‌سازی محیط کار...','loading');
329 - // Waiting for ALL assets in parallel was not sufficient: the old account
330 - // lookup could resolve BEFORE organization-rbac.js installed its wrapper,
331 - // leaving a placeholder 'unavailable' license until the next login.
332 - const organizationAccount=window.FinoraOrganizationContextReady.then(()=>{
333 - if(controller.signal.aborted)throw new Error('FINORA_LOGIN_READ_TIMEOUT');
334 - return fetchCurrentUser(authUser,{signal:controller.signal});
335 - });
336 - const [profile]=await Promise.all([
337 - finoraTrackLoginRead('ACCOUNT_CONTEXT',finoraAbortableRead(organizationAccount,controller.signal)),
338 - finoraTrackLoginRead('APP_ASSETS',finoraAbortableRead(window.FinoraAppAssetsReady,controller.signal))
339 - ]);
346 + setAuthLoginStatus('در حال دریافت اجزای نرم‌افزار؛ درخواست ورود شما در حال انجام است...','loading');
347 + // Slow workspace downloads must not consume the server-read deadline or
348 + // hydrate a profile before the organization entitlement adapter exists.
349 + await finoraTrackLoginRead('APP_ASSETS',finoraAbortableRead(Promise.all([
350 + window.FinoraAppAssetsReady,window.FinoraOrganizationContextReady
351 + ]),controller.signal));
352 + clearTimeout(timer);
353 + if(controller.signal.aborted)throw new Error('FINORA_LOGIN_READ_TIMEOUT');
354 + timer=setTimeout(abortLogin,timeoutMs);
355 + setAuthLoginStatus('در حال دریافت مشخصات و دسترسی حساب...','loading');
356 + const organizationAccount=fetchCurrentUser(authUser,{signal:controller.signal});
357 + const profile=await finoraTrackLoginRead('ACCOUNT_CONTEXT',finoraAbortableRead(organizationAccount,controller.signal));
358 if(controller.signal.aborted)throw new Error('FINORA_LOGIN_READ_TIMEOUT');
359 currentUser=profile;
360 setAuthLoginStatus('در حال دریافت اطلاعات شرکت...','loading');
@@ -350,7 +368,8 @@ async function enterApp(authUser,{timeoutMs=25000}={}){
368 console.warn('Finora login read timed out (no identity or private data logged).');
369 const stages=timeoutStageCodes.length?timeoutStageCodes:finoraPendingLoginStages();
370 const safeCodes=stages.length?stages.join(','):'UNKNOWN';
353 - setAuthLoginStatus('دریافت اطلاعات حساب بیش از حد طول کشید. مرحله معطل: '+finoraLoginStageDescription(stages)+' (BOOT_'+safeCodes+'). اتصال را بررسی کنید و دوباره تلاش کنید.','error');
371 + const subject=stages.includes('APP_ASSETS')?'دریافت اجزای نرم‌افزار':'دریافت اطلاعات حساب';
372 + setAuthLoginStatus(subject+' بیش از حد طول کشید. مرحله معطل: '+finoraLoginStageDescription(stages)+' (BOOT_'+safeCodes+'). اتصال را بررسی کنید و دوباره تلاش کنید.','error');
373 }else if(err?.message==='FINORA_APP_ASSETS_UNAVAILABLE'){
374 setAuthLoginStatus('برخی اجزای نرم‌افزار از این شبکه دریافت نشدند (BOOT_APP_ASSETS_FAILED). برای جلوگیری از نمایش اطلاعات ناقص، محیط کار باز نشد. اتصال را تغییر دهید و صفحه را دوباره بارگذاری کنید.','error');
375 }else{
js/login-connectivity.js
+20 -11
@@ -7,8 +7,6 @@ async function checkAuthConnectivity(){
7 if(button)button.disabled=true;
8 out.textContent='در حال بررسی مستقل فایل برنامه و سرور ورود...';
9 out.dataset.status='checking';
10 - const controller=new AbortController();
11 - const timer=setTimeout(()=>controller.abort(),12000);
10 try{
11 if(navigator.onLine===false){
12 out.textContent='اتصال اینترنت دستگاه قطع است (OFFLINE). اتصال را برقرار کنید و دوباره بررسی کنید.';
@@ -17,15 +15,27 @@ async function checkAuthConnectivity(){
15 }
16 // Execute four independent GET checks. The REST root only returns
17 // gateway/OpenAPI status: never call a table, use a user JWT or read records.
18 + const finoraConnectivityProbe=async(input,init={})=>{
19 + const controller=new AbortController();
20 + const timer=setTimeout(()=>controller.abort(),12000);
21 + try{
22 + const value=await fetch(input,{...init,cache:'no-store',signal:controller.signal});
23 + // Only headers prove gateway reachability; do not download the body.
24 + if(value.body)void value.body.cancel().catch(()=>{});
25 + return {status:'fulfilled',value};
26 + }catch{
27 + return {status:'rejected',timedOut:controller.signal.aborted};
28 + }finally{clearTimeout(timer);}
29 + };
30 const requests=[
21 - fetch(new URL('js/login-connectivity.js?v=20261012-data-probe-v3',document.baseURI).href,{cache:'no-store',signal:controller.signal}),
22 - fetch(new URL('manifest.json',document.baseURI).href,{cache:'no-store',signal:controller.signal}),
23 - fetch(SUPABASE_URL+'/auth/v1/health',{method:'GET',headers:{apikey:SUPABASE_KEY},cache:'no-store',signal:controller.signal}),
24 - fetch(SUPABASE_URL+'/rest/v1/',{method:'GET',headers:{apikey:SUPABASE_KEY},cache:'no-store',signal:controller.signal})
31 + finoraConnectivityProbe(new URL('js/login-connectivity.js?v=20261024-independent-probes-v4',document.baseURI).href),
32 + finoraConnectivityProbe(new URL('manifest.json',document.baseURI).href),
33 + finoraConnectivityProbe(SUPABASE_URL+'/auth/v1/health',{method:'GET',headers:{apikey:SUPABASE_KEY}}),
34 + finoraConnectivityProbe(SUPABASE_URL+'/rest/v1/',{method:'GET',headers:{apikey:SUPABASE_KEY}})
35 ];
26 - const [script,manifest,auth,rest]=await Promise.allSettled(requests);
36 + const [script,manifest,auth,rest]=await Promise.all(requests);
37 const describe=(r,name)=>{
28 - if(r.status==='rejected')return name+(controller.signal.aborted?'_TIMEOUT':'_NETWORK_ERROR');
38 + if(r.status==='rejected')return name+(r.timedOut?'_TIMEOUT':'_NETWORK_ERROR');
39 return name+(r.value.ok?'_OK':'_HTTP_'+r.value.status);
40 };
41 const scriptOk=script.status==='fulfilled'&&script.value.ok;
@@ -33,11 +43,11 @@ async function checkAuthConnectivity(){
43 const authOk=auth.status==='fulfilled'&&auth.value.status===200;
44 const siteCode=describe(script,'SITE_JS');
45 const manifestCode=describe(manifest,'MANIFEST');
36 - const authCode=auth.status==='rejected'?(controller.signal.aborted?'AUTH_TIMEOUT':'AUTH_UNREACHABLE'):
46 + const authCode=auth.status==='rejected'?(auth.timedOut?'AUTH_TIMEOUT':'AUTH_UNREACHABLE'):
47 (auth.value.status===200?'AUTH_OK':'AUTH_HTTP_'+auth.value.status);
48 // A 401/403/404 from REST still proves the gateway responded; 5xx does not.
49 // It does NOT prove authenticated tenant reads or RLS authorization.
40 - const restCode=rest.status==='rejected'?(controller.signal.aborted?'REST_TIMEOUT':'REST_UNREACHABLE'):'REST_HTTP_'+rest.value.status;
50 + const restCode=rest.status==='rejected'?(rest.timedOut?'REST_TIMEOUT':'REST_UNREACHABLE'):'REST_HTTP_'+rest.value.status;
51 const restHealthy=rest.status==='fulfilled'&&rest.value.status<500;
52 const codes=[siteCode,manifestCode,authCode,restCode].join(' | ');
53 if(!scriptOk&&!manifestOk){
@@ -63,7 +73,6 @@ async function checkAuthConnectivity(){
73 out.textContent='بررسی مستقل اتصال کامل نشد (DIAGNOSTIC_FAILED). بدون ارسال رمز یا اطلاعات حساب دوباره امتحان کنید.';
74 out.dataset.status='error';
75 }finally{
66 - clearTimeout(timer);
76 if(button)button.disabled=false;
77 }
78 }
scripts/build-pages.mjs
+3
@@ -92,6 +92,9 @@ const bundle='// Bundled local Finora extensions, original dependency order.\n'+
92 new vm.Script(bundle,{filename:'finora-extension-bundle.js'});
93 const bundleHash=createHash('sha256').update(bundle).digest('hex').slice(0,16);
94 fs.writeFileSync(path.join(out,'js','finora-extension-bundle.js'),bundle);
95 +// Fetch while the parser loads core groups; bootstrap still executes the
96 +// extensions in dependency order after the workspace sources are available.
97 +html=html.replace('</head>','<link rel="preload" as="script" href="js/finora-extension-bundle.js?v='+bundleHash+'" />\n</head>');
98 const marker='const FINORA_EXTENSION_BUNDLE_URL=null;';
99 if(!originalBootstrap.includes(marker))throw new Error('Missing bundle loader feature flag');
100 fs.writeFileSync(bootstrapPath,originalBootstrap.replace(marker,
scripts/login-auth-transport.spec.js new
+123
@@ -0,0 +1,123 @@
1 +const {test,expect}=require('@playwright/test');
2 +const BASE=process.env.FINORA_TEST_BASE_URL||'http://127.0.0.1:4173/index.html';
3 +
4 +test.beforeEach(async({page})=>{
5 + await page.route('https://*.supabase.co/**',route=>route.abort());
6 + await page.goto(BASE,{waitUntil:'domcontentloaded'});
7 + await page.waitForFunction(()=>window.FinoraStartupStatus?.authChecked===true);
8 +});
9 +
10 +test('Auth timeout covers a stalled password response body after headers reach the real SDK',async({page})=>{
11 + const actual=await page.evaluate(async()=>{
12 + const originalFetch=window.fetch,originalAuthFetch=sb.auth.fetch;
13 + let streamController,signal;
14 + window.fetch=async(input,init)=>{
15 + signal=init.signal;
16 + return new Response(new ReadableStream({start(controller){
17 + streamController=controller;
18 + controller.enqueue(new TextEncoder().encode('{"access_token":'));
19 + signal.addEventListener('abort',()=>controller.error(new DOMException('Aborted','AbortError')),{once:true});
20 + }}),{status:200,headers:{'content-type':'application/json'}});
21 + };
22 + sb.auth.fetch=(input,init)=>finoraBoundedAuthFetch(input,init,60);
23 + try{
24 + const result=await Promise.race([
25 + sb.auth.signInWithPassword({email:'fixture@example.test',password:'synthetic-only'}).then(result=>({settled:true,failed:!!result.error,networkError:isAuthNetworkError(result.error)})),
26 + new Promise(resolve=>setTimeout(()=>resolve({settled:false}),500))
27 + ]);
28 + return {...result,aborted:signal.aborted};
29 + }finally{
30 + streamController.error(new DOMException('Fixture cleanup','AbortError'));
31 + window.fetch=originalFetch;sb.auth.fetch=originalAuthFetch;
32 + }
33 + });
34 + expect(actual).toEqual({settled:true,failed:true,networkError:true,aborted:true});
35 +});
36 +
37 +test('A complete Auth response preserves status, headers and an unread body',async({page})=>{
38 + const actual=await page.evaluate(async()=>{
39 + const originalFetch=window.fetch;
40 + const response=new Response('{"message":"fixture"}',{status:201,statusText:'Created',headers:{'content-type':'application/json','x-request-id':'fixture-request'}});
41 + window.fetch=async()=>response;
42 + try{
43 + const received=await finoraBoundedAuthFetch('https://fixture.invalid/auth/v1/token',{},200);
44 + const unread=!received.bodyUsed;
45 + return {sameResponse:received===response,status:received.status,statusText:received.statusText,requestId:received.headers.get('x-request-id'),unread,body:await received.json()};
46 + }finally{window.fetch=originalFetch;}
47 + });
48 + expect(actual).toEqual({sameResponse:true,status:201,statusText:'Created',requestId:'fixture-request',unread:true,body:{message:'fixture'}});
49 +});
50 +
51 +test('Real SDK keeps a completed invalid-password response distinct from a transport timeout',async({page})=>{
52 + const actual=await page.evaluate(async()=>{
53 + const originalFetch=window.fetch,originalAuthFetch=sb.auth.fetch;
54 + window.fetch=async()=>new Response(JSON.stringify({code:'invalid_credentials',message:'Invalid login credentials'}),{status:400,headers:{'content-type':'application/json','x-supabase-api-version':'2024-01-01'}});
55 + sb.auth.fetch=(input,init)=>finoraBoundedAuthFetch(input,init,200);
56 + try{
57 + const result=await sb.auth.signInWithPassword({email:'fixture@example.test',password:'synthetic-only'});
58 + return {code:result.error?.code,status:result.error?.status,networkError:isAuthNetworkError(result.error),message:authMsg(result.error)};
59 + }finally{window.fetch=originalFetch;sb.auth.fetch=originalAuthFetch;}
60 + });
61 + expect(actual).toMatchObject({code:'invalid_credentials',status:400,networkError:false});
62 + expect(actual.message).toContain('ایمیل یا رمز عبور اشتباه است');
63 +});
64 +
65 +test('Restoring an expired session retries a stalled Auth body and recovers through the real SDK',async({page})=>{
66 + const actual=await page.evaluate(async()=>{
67 + const originalFetch=window.fetch;
68 + const session={access_token:'synthetic-access',refresh_token:'synthetic-refresh',token_type:'bearer',expires_in:3600,expires_at:Math.floor(Date.now()/1000)+3600,user:{id:'synthetic-restored-user',aud:'authenticated',email:'fixture@example.test',app_metadata:{provider:'email',providers:['email']},user_metadata:{},created_at:'2026-01-01T00:00:00Z'}};
69 + const memory=new Map([['fixture-session',JSON.stringify({...session,expires_at:1})]]);
70 + let attempts=0,streamController;
71 + window.fetch=async(input,init)=>{
72 + attempts++;
73 + if(attempts>1)return new Response(JSON.stringify(session),{status:200,headers:{'content-type':'application/json'}});
74 + return new Response(new ReadableStream({start(controller){
75 + streamController=controller;
76 + controller.enqueue(new TextEncoder().encode('{"access_token":'));
77 + init.signal.addEventListener('abort',()=>controller.error(new DOMException('Aborted','AbortError')),{once:true});
78 + }}),{status:200,headers:{'content-type':'application/json'}});
79 + };
80 + const client=new window.supabase.AuthClient({url:'https://fixture.invalid/auth/v1',storageKey:'fixture-session',storage:{getItem:key=>memory.get(key)||null,setItem:(key,value)=>memory.set(key,value),removeItem:key=>memory.delete(key)},persistSession:true,autoRefreshToken:true,detectSessionInUrl:false,fetch:(input,init)=>finoraBoundedAuthFetch(input,init,60)});
81 + try{
82 + return await Promise.race([
83 + client.getSession().then(({data,error})=>({restored:!!data.session&&!error,userId:data.session?.user?.id})),
84 + new Promise(resolve=>setTimeout(()=>resolve({restored:false}),1500))
85 + ]);
86 + }finally{await client.stopAutoRefresh();streamController.error(new DOMException('Fixture cleanup','AbortError'));window.fetch=originalFetch;}
87 + });
88 + expect(actual).toEqual({restored:true,userId:'synthetic-restored-user'});
89 +});
90 +
91 +test('Upstream cancellation remains effective while an Auth body is still arriving',async({page})=>{
92 + const actual=await page.evaluate(async()=>{
93 + const originalFetch=window.fetch,upstream=new AbortController();
94 + let streamController;
95 + window.fetch=async(input,init)=>new Response(new ReadableStream({start(controller){
96 + streamController=controller;
97 + init.signal.addEventListener('abort',()=>controller.error(new DOMException('Aborted','AbortError')),{once:true});
98 + }}),{status:200});
99 + try{
100 + const request=finoraBoundedAuthFetch('https://fixture.invalid/auth/v1/token',{signal:upstream.signal},5000).then(response=>response.text());
101 + setTimeout(()=>upstream.abort(),20);
102 + return await Promise.race([
103 + request.then(()=>({cancelled:false}),err=>({cancelled:upstream.signal.aborted&&isAuthNetworkError(err)})),
104 + new Promise(resolve=>setTimeout(()=>resolve({cancelled:false}),400))
105 + ]);
106 + }finally{streamController.error(new DOMException('Fixture cleanup','AbortError'));window.fetch=originalFetch;}
107 + });
108 + expect(actual).toEqual({cancelled:true});
109 +});
110 +
111 +test('Non-Auth reads retain their streaming response and original cancellation signal',async({page})=>{
112 + const actual=await page.evaluate(async()=>{
113 + const originalFetch=window.fetch,upstream=new AbortController();
114 + let receivedSignal,controller;
115 + const response=new Response(new ReadableStream({start(value){controller=value;}}),{status:200});
116 + window.fetch=async(input,init)=>{receivedSignal=init.signal;return response;};
117 + try{
118 + const received=await finoraBoundedAuthFetch('https://fixture.invalid/rest/v1/records',{signal:upstream.signal},40);
119 + return {sameResponse:received===response,sameSignal:receivedSignal===upstream.signal,bodyStillUnread:!received.bodyUsed};
120 + }finally{controller.close();window.fetch=originalFetch;}
121 + });
122 + expect(actual).toEqual({sameResponse:true,sameSignal:true,bodyStillUnread:true});
123 +});
scripts/login-connectivity-check.mjs
+4 -4
@@ -6,9 +6,9 @@ const diagnostic=fs.readFileSync('js/login-connectivity.js','utf8');
6 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=20261014-org-license-readiness-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=20261014-org-license-readiness-v1"'),'Connectivity handler script must execute before core (not just preload)');
9 +assert(html.includes('js/login-connectivity.js?v=20261024-independent-probes-v4'),'Missing versioned script');
10 +assert(html.includes('js/core.js?v=20261024-login-readiness-v1'),'Production login controls must use new cache version');
11 +assert(html.indexOf('<script src="js/login-connectivity.js?v=20261024-independent-probes-v4"')<html.indexOf('<script src="js/core.js?v=20261024-login-readiness-v1"'),'Connectivity handler script must execute before core (not just preload)');
12 assert(html.includes('js/bootstrap.js?v=20261014-org-license-readiness-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');
@@ -20,7 +20,7 @@ assert(!core.includes('اتصال اینترنت/VPN را بررسی کنید'),
20 assert(diagnostic.includes("'/auth/v1/health'"),'Must test the real GoTrue health path');
21 assert(diagnostic.includes('apikey:SUPABASE_KEY'),'Health check requires public API key');
22 assert(diagnostic.includes("new URL('manifest.json',document.baseURI)"),'Missing same-origin site baseline');
23 -assert(diagnostic.includes("new URL('js/login-connectivity.js?v=20261012-data-probe-v3',document.baseURI)"),'Missing same-origin executable asset probe');
23 +assert(diagnostic.includes("new URL('js/login-connectivity.js?v=20261024-independent-probes-v4',document.baseURI)"),'Missing same-origin executable asset probe');
24 assert(diagnostic.includes("SITE_JS")&&diagnostic.includes("MANIFEST"),'Must diagnose executable asset and manifest independently');
25 assert(diagnostic.includes("'/rest/v1/'"),'PostgREST gateway probe required to distinguish data endpoint from Auth health');
26 assert(diagnostic.includes('REST_UNREACHABLE')&&diagnostic.includes('rest-unreachable'),'PostgREST network failure must surface separately');
scripts/login-connectivity.spec.js
+27
@@ -115,3 +115,30 @@ test('A 503 data gateway response remains distinct from good Auth service',async
115 await expect(output).toContainText('AUTH_OK');
116 await expect(output).toContainText('REST_HTTP_503');
117 });
118 +
119 +for(const scenario of [
120 + {failed:'/auth/v1/health',stalled:'/rest/v1/',expected:'AUTH_UNREACHABLE',timeout:'REST_TIMEOUT'},
121 + {failed:'/js/login-connectivity.js',stalled:'/auth/v1/health',expected:'SITE_JS_NETWORK_ERROR',timeout:'AUTH_TIMEOUT'}
122 +])test('An immediate '+scenario.expected+' remains distinct when another probe times out',async({page})=>{
123 + await page.route('https://cdn.jsdelivr.net/**',route=>route.abort());
124 + await page.route('**/auth/v1/health',route=>route.fulfill({status:200,body:'{}'}));
125 + await page.goto(base,{waitUntil:'domcontentloaded'});
126 + await page.clock.install();
127 + await page.evaluate(({failed,stalled})=>{
128 + window.fetch=(input,init={})=>{
129 + const url=String(input);
130 + if(url.includes(failed))return Promise.reject(new TypeError('Failed to fetch'));
131 + if(url.includes(stalled))return new Promise((resolve,reject)=>{
132 + init.signal.addEventListener('abort',()=>reject(new DOMException('aborted','AbortError')),{once:true});
133 + });
134 + return Promise.resolve(new Response('{}',{status:200}));
135 + };
136 + },scenario);
137 + await page.locator('#auth-connectivity-check').click();
138 + await page.clock.fastForward(12001);
139 + const output=page.locator('#auth-connectivity-result');
140 + await expect(output).toContainText(scenario.expected);
141 + await expect(output).toContainText(scenario.timeout);
142 + await expect(page.locator('#auth-connectivity-check')).toBeEnabled();
143 + expect(await output.textContent()).not.toMatch(/Bearer |password|access_token|apiKey/i);
144 +});
scripts/login-startup-readiness.spec.js new
+209
@@ -0,0 +1,209 @@
1 +const {test,expect}=require('@playwright/test');
2 +const BASE=process.env.FINORA_LOGIN_PAGES_BASE||'http://127.0.0.1:4173/_site/index.html';
3 +
4 +async function syntheticLogin(page,{restoreSession=false,holdSessionCheck=false}={}){
5 + // Patch transport before core.js calls createClient; initAuthSystem, the CSP
6 + // handlers, organization hydration and records loading remain the real code.
7 + await page.addInitScript(({restoreSession,holdSessionCheck})=>{
8 + const fixture=window.finoraLoginFixture={passwordCalls:0,profileReads:[],recordReads:0,writes:0};
9 + const sessionCheck=holdSessionCheck?new Promise(resolve=>{window.finoraReleaseSessionCheck=resolve;}):Promise.resolve();
10 + let sdk;
11 + Object.defineProperty(window,'supabase',{
12 + configurable:true,
13 + get(){return sdk;},
14 + set(value){
15 + sdk=value;
16 + const create=value.createClient;
17 + value.createClient=function(...args){
18 + const client=create.apply(this,args);
19 + client.auth.getSession=async()=>{
20 + await sessionCheck;
21 + return {data:{session:restoreSession?{user:{id:'fixture-restored'}}:null},error:null};
22 + };
23 + client.auth.signInWithPassword=async()=>{
24 + fixture.passwordCalls++;
25 + return {data:{user:{id:'fixture-password'}},error:null};
26 + };
27 + client.rpc=async()=>{fixture.writes++;throw new Error('Unexpected fixture write');};
28 + client.from=table=>{
29 + const filters={};
30 + let single=false;
31 + const query={
32 + select(){return this;},in(){return this;},order(){return this;},range(){return this;},abortSignal(){return this;},
33 + eq(key,value){filters[key]=value;return this;},
34 + single(){single=true;return this;},
35 + then(resolve){
36 + const uid=filters.id||filters.user_id||'fixture-password';
37 + let rows=[];
38 + if(table==='profiles'){
39 + fixture.profileReads.push(uid);
40 + rows=[{id:uid,email:'fixture@example.test',full_name:'Synthetic Login',role:'accountant'}];
41 + }else if(table==='organization_members'){
42 + rows=[{id:'fixture-membership',user_id:uid,organization_id:'fixture-org',status:'active',is_owner:true}];
43 + }else if(table==='organizations'){
44 + rows=[{id:'fixture-org',name:'Synthetic Company',status:'active'}];
45 + }else if(table==='licenses'){
46 + rows=[{organization_id:'fixture-org',plan:'lifetime',status:'active',starts_at:'2026-01-01',ends_at:'2099-01-01',modules:['full_suite'],max_companies:5,max_users:5}];
47 + }else if(table==='records')fixture.recordReads++;
48 + return Promise.resolve(resolve({data:single?rows[0]:rows,error:null}));
49 + }
50 + };
51 + return query;
52 + };
53 + return client;
54 + };
55 + }
56 + });
57 + },{restoreSession,holdSessionCheck});
58 + // Defense in depth: a fixture must never send credentials or read a real tenant.
59 + await page.route('https://*.supabase.co/**',route=>route.abort('blockedbyclient'));
60 + await page.route('https://cdn.jsdelivr.net/**',route=>route.abort('blockedbyclient'));
61 + await page.route('https://cdnjs.cloudflare.com/**',route=>route.abort('blockedbyclient'));
62 + page.on('dialog',dialog=>dialog.dismiss());
63 +}
64 +
65 +async function holdBundle(page,name){
66 + let release,arrived;
67 + const held=new Promise(resolve=>{release=resolve;});
68 + const requested=new Promise(resolve=>{arrived=resolve;});
69 + await page.route('**/js/finora-pages-'+name+'.js*',async route=>{
70 + arrived();
71 + await held;
72 + await route.continue();
73 + });
74 + return {release,requested};
75 +}
76 +
77 +async function submitPassword(page){
78 + await page.locator('#auth-email').fill('fixture@example.test');
79 + await page.locator('#auth-password').fill('synthetic-password-only');
80 + await page.locator('#auth-login-button').click({noWaitAfter:true});
81 +}
82 +
83 +for(const bundle of ['business','accounting']){
84 + test('early successful Pages login survives a slow '+bundle+' bundle before company-read timeout starts',async({page})=>{
85 + await syntheticLogin(page);
86 + await page.clock.install();
87 + const asset=await holdBundle(page,bundle);
88 + await page.goto(BASE,{waitUntil:'commit'});
89 + await asset.requested;
90 + await expect(page.locator('#auth-login-button')).toBeEnabled();
91 + expect(await page.evaluate(()=>document.readyState)).toBe('loading');
92 + await submitPassword(page);
93 + await expect(page.locator('#auth-login-status')).toHaveAttribute('data-state','loading');
94 + // The credentials have already succeeded. A slow local ERP download must
95 + // not consume the separate 25-second account/data-read deadline.
96 + await page.clock.fastForward(26000);
97 + expect(await page.evaluate(()=>({
98 + status:document.getElementById('auth-login-status').dataset.state,
99 + profileReads:window.finoraLoginFixture.profileReads,
100 + user:currentUser
101 + }))).toEqual({status:'loading',profileReads:[],user:null});
102 + await expect(page.locator('#auth-screen')).toBeVisible();
103 + asset.release();
104 + await expect(page.locator('#auth-screen')).toBeHidden({timeout:15000});
105 + expect(await page.evaluate(()=>({
106 + user:currentUser?.id,
107 + organization:currentUser?.organizationId,
108 + license:currentUser?.subscription?.type,
109 + ...window.finoraLoginFixture
110 + }))).toEqual({user:'fixture-password',organization:'fixture-org',license:'lifetime',passwordCalls:1,profileReads:['fixture-password'],recordReads:1,writes:0});
111 + });
112 +}
113 +
114 +test('stalled Pages assets expire visibly without late entry and a fresh click recovers after download',async({page})=>{
115 + await syntheticLogin(page);
116 + await page.clock.install();
117 + const asset=await holdBundle(page,'accounting');
118 + await page.goto(BASE,{waitUntil:'commit'});
119 + await asset.requested;
120 + await expect(page.locator('#auth-login-button')).toBeEnabled();
121 + await submitPassword(page);
122 + await page.clock.fastForward(46000);
123 + await expect(page.locator('#auth-login-status')).toHaveAttribute('data-state','error');
124 + await expect(page.locator('#auth-login-status')).toContainText('BOOT_APP_ASSETS');
125 + expect(await page.evaluate(()=>({user:currentUser,profileReads:window.finoraLoginFixture.profileReads})))
126 + .toEqual({user:null,profileReads:[]});
127 + asset.release();
128 + await expect.poll(()=>page.evaluate(()=>window.FinoraStartupStatus?.extensionsReady),{timeout:15000}).toBe(true);
129 + await expect(page.locator('#auth-screen')).toBeVisible();
130 + await expect(page.locator('#auth-login-status')).toHaveAttribute('data-state','error');
131 + expect(await page.evaluate(()=>window.finoraLoginFixture.profileReads)).toEqual([]);
132 + await submitPassword(page);
133 + await expect(page.locator('#auth-screen')).toBeHidden({timeout:15000});
134 + expect(await page.evaluate(()=>({user:currentUser?.id,...window.finoraLoginFixture})))
135 + .toEqual({user:'fixture-password',passwordCalls:2,profileReads:['fixture-password'],recordReads:1,writes:0});
136 +});
137 +
138 +test('cached-session restoration owns the login attempt while early password clicks are ignored',async({page})=>{
139 + await syntheticLogin(page,{restoreSession:true});
140 + const asset=await holdBundle(page,'accounting');
141 + await page.goto(BASE,{waitUntil:'commit'});
142 + await asset.requested;
143 + await expect(page.locator('#auth-login-button')).toBeEnabled();
144 + await expect(page.locator('#auth-login-status')).toHaveAttribute('data-state','loading');
145 + await submitPassword(page);
146 + expect(await page.evaluate(()=>window.finoraLoginFixture.passwordCalls)).toBe(0);
147 + await expect(page.locator('#auth-login-status')).toHaveAttribute('data-state','busy');
148 + asset.release();
149 + await expect(page.locator('#auth-screen')).toBeHidden({timeout:15000});
150 + expect(await page.evaluate(()=>({user:currentUser?.id,...window.finoraLoginFixture})))
151 + .toEqual({user:'fixture-restored',passwordCalls:0,profileReads:['fixture-restored'],recordReads:1,writes:0});
152 +});
153 +
154 +test('early password click waits for the pending initial session check then continues once without another click',async({page})=>{
155 + await syntheticLogin(page,{restoreSession:true,holdSessionCheck:true});
156 + await page.goto(BASE,{waitUntil:'domcontentloaded'});
157 + await expect(page.locator('#auth-login-button')).toBeEnabled();
158 + await submitPassword(page);
159 + expect(await page.evaluate(()=>window.finoraLoginFixture.passwordCalls)).toBe(0);
160 + await expect(page.locator('#auth-login-status')).toHaveAttribute('data-state','loading');
161 + expect(await page.evaluate(()=>({user:currentUser,profileReads:window.finoraLoginFixture.profileReads})))
162 + .toEqual({user:null,profileReads:[]});
163 + await page.evaluate(()=>window.finoraReleaseSessionCheck());
164 + await expect(page.locator('#auth-screen')).toBeHidden({timeout:15000});
165 + expect(await page.evaluate(()=>({user:currentUser?.id,...window.finoraLoginFixture})))
166 + .toEqual({user:'fixture-password',passwordCalls:1,profileReads:['fixture-password'],recordReads:1,writes:0});
167 +});
168 +
169 +test('Pages downloads its pinned extension bundle before slow accounting finishes and executes it once',async({page})=>{
170 + await syntheticLogin(page);
171 + const requested=[];
172 + page.on('request',request=>{
173 + if(new URL(request.url()).pathname.endsWith('/finora-extension-bundle.js'))requested.push(request.url());
174 + });
175 + await page.route('**/js/finora-extension-bundle.js*',async route=>{
176 + const response=await route.fetch();
177 + await route.fulfill({response,body:await response.text()+'\n;window.finoraFixtureBundleExecutions=(window.finoraFixtureBundleExecutions||0)+1;'});
178 + });
179 + const asset=await holdBundle(page,'accounting');
180 + await page.goto(BASE,{waitUntil:'commit'});
181 + await asset.requested;
182 + await expect(page.locator('#auth-login-button')).toBeEnabled();
183 + expect(await page.evaluate(()=>document.readyState)).toBe('loading');
184 + await expect.poll(()=>requested.length,{timeout:1500}).toBe(1);
185 + expect(requested[0]).toMatch(/finora-extension-bundle\.js\?v=[0-9a-f]{16}$/);
186 + expect(await page.evaluate(()=>window.finoraFixtureBundleExecutions||0)).toBe(0);
187 + asset.release();
188 + await expect.poll(()=>page.evaluate(()=>window.FinoraStartupStatus?.extensionsReady),{timeout:15000}).toBe(true);
189 + expect(await page.evaluate(()=>({
190 + executions:window.finoraFixtureBundleExecutions,
191 + failures:window.FinoraStartupStatus.failedExtensionCount,
192 + scripts:document.querySelectorAll('script[src*="finora-extension-bundle.js"]').length
193 + }))).toEqual({executions:1,failures:0,scripts:1});
194 + expect(requested).toHaveLength(1);
195 +});
196 +
197 +test('early successful credentials cannot open the workspace when a required Pages bundle fails',async({page})=>{
198 + await syntheticLogin(page);
199 + let release;
200 + const held=new Promise(resolve=>{release=resolve;});
201 + await page.route('**/js/finora-pages-accounting.js*',async route=>{await held;await route.abort('failed');});
202 + await page.goto(BASE,{waitUntil:'commit'});
203 + await expect(page.locator('#auth-login-button')).toBeEnabled();
204 + await submitPassword(page);
205 + release();
206 + await expect(page.locator('#auth-login-status')).toContainText('BOOT_APP_ASSETS_FAILED',{timeout:15000});
207 + await expect(page.locator('#auth-screen')).toBeVisible();
208 + expect(await page.evaluate(()=>({user:currentUser,writes:window.finoraLoginFixture.writes}))).toEqual({user:null,writes:0});
209 +});