سامانه صدور فاکتور و حسابداری
Fix inert login controls after incomplete script loading (#196)
* fix(auth): recover login controls after incomplete bootstrap * ci: pin browser job to supported Ubuntu 24.04 --------- Co-authored-by: JVK <lanxniew246@gmail.com>
davoodmehraban89 committed
Nov 10, 2026 at 15:57 UTC
4382e83a73bc3636d53273f07f0eaaa4911b5879
12 files changed
+239
-37
.github/workflows/quality.yml
+2
-1
@@ -11,7 +11,8 @@ permissions:
11
contents: read
12
jobs:
13
static-quality:
14
- runs-on: ubuntu-latest
14
+ # Playwright 1.55 supports Ubuntu 24.04; latest now resolves to 26.04.
15
+ runs-on: ubuntu-24.04
16
steps:
17
- uses: actions/checkout@v7
18
- uses: actions/setup-node@v7
PROJECT_STATE.md
+9
@@ -227,3 +227,12 @@ Owner requests layer-by-layer click/functional testing of all controls and compa
227
- Two commerce regressions observed RED→GREEN; focused commerce+existing invoice persistence7/7 PASS. Generated combined new scenarios8/8 PASS. First generated run failed because local HTTP server ended after steered user turn (connection refused); excluded, rerun with server lifetime bound to test succeeded. Static contracts updated to follow centralized existing authorization guard, not remove it; all pre-browser commands plus release-safety now PASS, including49server/Golden. Full211browser run ongoing. Independent reviewer agent unavailable due provider usage limit; root reviewing diff directly, no independent-review success claimed.
228
- Full local browser211 completed:210PASS, sole failure was shell-scroll-ownership hardcoded old ui.js cache URL. Updated expected URL to actual new version; no layout assertions changed. Exact d12da87 CI likewise failed Quality, Security and3DB passed. Follow-up final CI must pass before merge; do not treat previous failure as release acceptance. Root reviewed final diff and generated screenshots (synthetic only); accepted captures under docs/audits/2026-10-31/recovery.
229
- Release evidence location: PR191 description is the live ledger for final PR-head/full-browser outcome, protected merge SHA, exact-main CI/gate/Pages and public asset readback, because merge identifiers exist only after commit. Current local docs preserve findings/remaining real-account gaps rather than invent future IDs. Remaining About placeholders, broad control audit and subsequent phases remain open in docs/EXECUTION_STATUS.md.
230
+
231
+### 2026-11-10 — Owner reports inert login and diagnostics buttons
232
+- Owner prioritizes a new live login blocker: email/password entered, password login and connectivity buttons appear inert, initial preparing-login message persists after page load. Diagnose this first, then resume the unfinished navigation utility placement and WP1. Screenshot was mentioned but no new attachment is visible in this message; proceed with actual code/live evidence without requesting credentials.
233
+- Remote main remains4416794. LiveHTML has disabled login/diagnostic controls and initial preparation text by design; readiness JS must activate them. PR193 remainsopen and concerns hydration/member errors, not proof of fixing this early bootstrap failure. Investigate missing/failing criticalSDK/core/handler resources and execution exceptions, reproduce before changing behavior, preserve recovery/PKCE/session authority. Separatebranchfrommain, no productionAuth/schema/data changes.
234
+- Navigation fix branch has only its recorded plan so far; module launcher stillaboveLogout and accessbelow inliveUI. Do not mark it fixed. WP1readgraph61092e4 is separatelypublishedcandidate; no financialreleaseauthorizedbythisincident.
235
+- Repair checkpoint: generated Pages now ships the existing SDK/recovery/core atomically; standalone diagnostics binds without core/static handlers, provides bounded bootstrap feedback and a reload action. Independent initial review found3P2 issues (hidden CSS, recovery fragment loss, early versioned probing); all fixed and covered. Re-review agent was quota-blocked; no independent final approval claimed.
236
+- Focused62/62 browser scenarios PASS, all51 existing pre-browser/server/static/release commands PASS; final syntax/diagnostic/quality/release checks rerun PASS. Full220-browser run is in progress at this commit; exact-head CI and production release still pending. See docs/LOGIN_BOOTSTRAP_INCIDENT_2026-11-10.md. Public baseline visit works from this environment; exact owner-network cause/account acceptance remains NOT VERIFIED. TinyFish connected but profile metadata lists no factoreasy.ir session.
237
+- Autonomous protected frontend release is covered by the owner's continuing authorization; preserve all exact-SHA checks and publish/read back before claiming live. No production Auth/schema/data change. Navigation relocation resumes separately; WP1 candidate61092e4 verified all three remote workflows SUCCESS (Quality41957583573,Security41957583565,WP141957583675), still not merged/deployed.
238
+- CI infrastructure finding: PR196 Quality42814653548 completed all static/server checks but could not install Chromium: GitHub's ubuntu-latest moved to26.04, unsupported by the pinned Playwright1.55.0. Pin only the browser/static job to supported ubuntu-24.04; retain browser version, assertions and all release gates. Local full run is invalid because its prior-turn HTTP server ended (connection refused); restart with server lifetime tied to the test process, not classify as product failures or a passing run.
docs/EXECUTION_STATUS.md
+4
-1
@@ -1,6 +1,6 @@
1
# وضعیت اجرای فینورا
2
3
-آخرین بهروزرسانی: ۲۰۲۶-۱۰-۳۱. مرجع تاریخچه و اختیار اجرا: [PROJECT_STATE](../PROJECT_STATE.md).
3
+آخرین بهروزرسانی: ۲۰۲۶-۱۱-۱۰. مرجع تاریخچه و اختیار اجرا: [PROJECT_STATE](../PROJECT_STATE.md).
4
5
## هدف جاری
6
@@ -8,6 +8,9 @@
8
9
|کار|وضعیت|شواهد / اقدام بعدی|
10
|---|---|---|
11
+|ورود با دکمههای غیرفعال|اصلاح و تست متمرکز ۶۲/۶۲ قبول؛ انتشار در انتظار بررسی کامل|[گزارش رخداد](LOGIN_BOOTSTRAP_INCIDENT_2026-11-10.md)؛ پذیرش حساب و اینترنت مالک هنوز تأیید نشده|
12
+|جابهجایی ماژولها و دسترسیها کنار خروج|برنامه ثبت شده؛ بعد از رفع ورود|انتقال انتخابگر به نوار بالا و مدیریت دسترسی به تنظیمات؛ هنوز منتشر نشده|
13
+|WP1 سختسازی مالی|کاندیدای جداگانه؛ روی سایت فعال نشده|PR195، نسخه61092e4: Quality41957583573 / Security41957583565 / WP141957583675 موفق؛ اتصال امن کلاینت و گیتهای انتشار باقی است|
14
|تفکیک نوع سند خرید/فروش|پیادهسازی؛ تست جدید source/Pages قبول|فروش: فروش/پیشفاکتور/صورتوضعیت؛ خرید: خرید؛ ۲۱۰/۲۱۱ اجرای کامل؛ یک انتظار کش قدیمی اصلاح شد؛ اجرای نهایی در PR191|
15
|سازمان، درخواستها و مدیریت اعضا|پیادهسازی؛ تست Pages قبول|ورودی تنظیمات، سازمان در انتخابگر، دعوت/ظرفیت موجود؛ شواهد زنده انتشار و SHA در PR191|
16
|اصلاح شرکت|منتشر؛ بازکردن/انصراف واقعی قبول|ذخیرهٔ تغییر شرکت در حساب واقعی از این پذیرش نتیجه نمیشود|
docs/LOGIN_BOOTSTRAP_INCIDENT_2026-11-10.md
new
+36
@@ -0,0 +1,36 @@
1
+# Login bootstrap incident — 2026-11-10
2
+
3
+## Goal and observed boundary
4
+
5
+Owner reports password login and connectivity buttons inert after HTML finishes loading, with the initial preparing-form message still displayed. The immediate task is to recover this path before returning to navigation utility placement and WP1. No new login screenshot was attached to this report.
6
+
7
+Baseline remote main: `4416794682d29a17976c901d866d182627f63c29`. A fresh public Chromium visit from the execution environment completed bootstrap, enabled both buttons and recorded no JS error or failed resource. This does **not** reproduce the owner's network, authenticate their account or establish a service-wide outage.
8
+
9
+The reproducible defect is dependency coupling: initial HTML deliberately disables controls; failure of the separate SDK or core/handler scripts prevents initialization. Diagnostics previously depended on core configuration and generated click handlers, so the recovery control could be inert at the same time.
10
+
11
+## Repair
12
+
13
+- Generated Pages carries the existing vendored SDK, recovery sanitizer and core in one content-versioned entrypoint. SDK client creation still follows recovery URL sanitization. No new dependency or provider configuration.
14
+- Diagnostics binds independently before core/static handlers and reads only public publishable configuration. Unknown/private configuration fails before any request. It probes the actual content-versioned core (including its preload when the parser has not reached the script tag).
15
+- Missing/execution-failed core and failed handlers produce fixed, credential-free error codes. A six-second incomplete-bootstrap message explains delay without pretending login succeeded. Late successful readiness clears the recovery action and retains typed input.
16
+- A separately bound reload button calls `location.reload()`: no copied callback credentials, and pending recovery fragments survive until the sanitizer can consume them. A core fallback binds reload if the diagnostic script itself is unavailable.
17
+- No automatic reload, password logging, Auth configuration change, customer record mutation, migration or financial behavior change.
18
+
19
+## Verification ledger
20
+
21
+- Three new failure scenarios initially failed against the old implementation: separate SDK unavailable, core unavailable, generated handlers unavailable.
22
+- Focused generated/source browser run: **62/62 PASS**, including recovery ownership, reload, network timeouts, exactly-once synthetic password submission, healthy mobile/tall/short desktop hiding, recovery callback preservation and early versioned diagnostic probing.
23
+- All 51 existing pre-browser/static/server/release commands passed before final review; syntax, diagnostic, static quality and release safety were rerun successfully after review corrections.
24
+- Independent initial review found three P2 defects in the candidate (hidden CSS media scope, callback fragment loss, unversioned early probe). All three corrected and covered by browser assertions. Follow-up independent review could not run because its provider quota was exhausted; no independent final approval claimed.
25
+- Earlier focused failures remain accounted for: fixed retained handler failure classification; updated fixture expectations for report version/probed core; replaced VM fixture with browser fail-closed private-key check. A Pages diagnostic fixture matched only a query-free Auth URL and left REST live; both endpoints are now explicitly mocked while retaining the 2.5-second limit and early-login assertions.
26
+- Full canonical browser suite and exact-head remote CI/release: pending at this documentation checkpoint. Deployment identifiers and public artifact comparison belong in the linked release PR after they actually exist.
27
+
28
+CI infrastructure: run42814653548 passed all pre-browser checks but failed installing the pinned Playwright1.55 on the newly migrated ubuntu-latest (26.04). The browser/static job now pins supported Ubuntu24.04; no test/gate removed. The initial full local run lost its prior-turn HTTP server and is excluded (connection refused); rerun owns its HTTP server lifetime.
29
+
30
+## Remaining work and rollback
31
+
32
+Owner-device/ISP and real-account acceptance remain unverified. TinyFish is connected, but its profile listing currently records no signed-in factoreasy.ir session. Do not collect passwords in chat or infer authenticated acceptance from public/bootstrap tests.
33
+
34
+After urgent release: move the module launcher above Logout into the topbar, and access administration below Logout into a discoverable authorized Settings entry. That navigation task is still planned, not implemented. Resume the separate WP1 graph-to-client adapter afterward, preserving financial release gates. PR193 addresses different account-hydration errors and remains separate.
35
+
36
+Rollback: revert this frontend/build PR through normal protected release. No database rollback is involved.
index.html
+10
-5
@@ -9,12 +9,14 @@
9
<link rel="apple-touch-icon" sizes="180x180" href="assets/finora-icon-180.png?v=20261002-brand-v1" />
10
<meta name="application-name" content="نرمافزار ERP سازمانی فینورا" />
11
<meta name="description" content="نرمافزار ERP سازمانی فینورا؛ مدیریت یکپارچه مالی، بازرگانی، خزانه، انبار، پیمان و عملیات سازمانی" />
12
+<meta name="finora-auth-url" content="https://hcsixhqbyuhpshfwqpjx.supabase.co" />
13
+<meta name="finora-auth-publishable-key" content="sb_publishable_2y8IsGdhqeLDPkEp7mBF4w_X4yji16D" />
14
<meta name="referrer" content="strict-origin-when-cross-origin" />
15
<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" />
16
<meta name="apple-mobile-web-app-capable" content="yes" />
17
<meta name="theme-color" content="#071a48" />
16
-<link rel="preload" as="script" href="js/core.js?v=20261025-password-recovery-v1" />
17
-<link rel="preload" as="script" href="js/login-connectivity.js?v=20261026-preflight-compare-v5" />
18
+<link rel="preload" as="script" href="js/core.js?v=20261110-login-bootstrap-v2" />
19
+<link rel="preload" as="script" href="js/login-connectivity.js?v=20261110-login-bootstrap-v6" />
20
<script src="vendor/supabase.js"></script>
21
<script async src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
22
<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" />
@@ -42,6 +44,7 @@ body{background-color:var(--bg);color:var(--text);font-size:14px}
44
.auth-google{min-height:44px;margin-bottom:4px}.auth-divider{margin:4px 0 6px}.auth-actions{margin-top:6px}.auth-actions .btn{min-height:44px}.auth-note{margin-top:8px;line-height:1.5}#auth-connectivity-result:empty{display:none}
45
.auth-visual{padding:28px}.auth-hero-logo{width:72px;height:72px;margin-bottom:12px}.auth-hero h2{font-size:42px}.auth-hero .tagline{margin-top:16px}.auth-dashboard-art{height:180px;margin-top:20px}
46
}
47
+#auth-reload-page[hidden]{display:none}
48
.app-root{display:flex;min-height:100vh;width:100%;max-width:100%;overflow-x:hidden}
49
.sidebar{width:var(--sidebar-w);background:var(--card-bg);border-left:1px solid var(--border);display:flex;flex-direction:column;position:fixed;top:0;bottom:0;right:0;z-index:100}
50
.brand-box{padding:20px;display:flex;align-items:center;gap:12px;border-bottom:1px solid var(--border)}
@@ -232,6 +235,7 @@ body{background:#f6f9fc}
235
<div id="auth-screen">
236
<div class="auth-shell">
237
<div class="auth-card">
238
+<noscript><p style="padding:16px;text-align:center">برای کارکرد دکمههای ورود، JavaScript باید در مرورگر فعال باشد.</p></noscript>
239
<div class="auth-brand">
240
<img class="auth-brand-logo" src="assets/finora-icon-180.png?v=20261002-brand-v1" alt="نشان فینورا" />
241
<div><h1>نرمافزار ERP سازمانی فینورا</h1><p>ورود یا ثبتنام امن در محیط سازمانی</p></div>
@@ -246,8 +250,9 @@ body{background:#f6f9fc}
250
<button disabled class="btn btn-secondary" onclick="startEmailOtp(false,false)">ورود با کد ایمیل</button>
251
</div>
252
<button disabled type="button" id="auth-forgot-password" class="btn btn-secondary" style="width:100%;margin-top:10px" onclick="finoraRequestPasswordRecovery()">فراموشی رمز عبور</button>
253
+ <button type="button" id="auth-reload-page" class="btn btn-secondary" hidden style="margin-top:10px">بارگذاری دوباره صفحه</button>
254
<p id="auth-login-status" aria-live="polite" data-state="loading" style="font-size:12px;line-height:1.9;margin-top:8px;min-height:24px;color:#475569">در حال آمادهسازی فرم ورود...</p>
250
- <button disabled type="button" id="auth-connectivity-check" class="btn btn-secondary" style="width:100%;margin-top:10px" onclick="checkAuthConnectivity()">بررسی اتصال به سرور ورود</button>
255
+ <button disabled type="button" id="auth-connectivity-check" class="btn btn-secondary" style="width:100%;margin-top:10px">بررسی اتصال به سرور ورود</button>
256
<p id="auth-connectivity-result" aria-live="polite" style="font-size:12px;line-height:1.9;margin-top:8px;overflow-wrap:anywhere"></p>
257
<button disabled class="btn auth-signup" onclick="startEmailOtp(false,true)">ثبتنام با کد ایمیل</button>
258
<p class="auth-note">ورود با کد ایمیل برای حساب موجود است. ایجاد حساب جدید فقط از مسیر «ثبتنام با کد ایمیل» انجام میشود.</p>
@@ -920,9 +925,9 @@ body{background:#f6f9fc}
925
926
<!-- The credential-free connectivity action must be loaded before core declares
927
login actions interactive. Hardened Pages binds static handlers just before core. -->
923
-<script src="js/login-connectivity.js?v=20261026-preflight-compare-v5"></script>
928
+<script src="js/login-connectivity.js?v=20261110-login-bootstrap-v6"></script>
929
<script src="js/password-recovery.js?v=20261026-recovery-cancel-v2"></script>
925
-<script src="js/core.js?v=20261025-password-recovery-v1"></script>
930
+<script src="js/core.js?v=20261110-login-bootstrap-v2"></script>
931
<script src="js/admin.js?v=20261028-central-password-reset-v1"></script>
932
<script src="js/sync.js?v=20261012-login-read-cancel-v1"></script>
933
<script src="js/ui.js?v=20261031-workspace-recovery-v1"></script>
js/core.js
+10
@@ -215,7 +215,17 @@ async function initAuthSystem(){
215
if(canUseActions&&screen)screen.querySelectorAll('button').forEach(button=>{button.disabled=false;});
216
window.FinoraPasswordRecovery?.render();
217
window.FinoraStartupStatus.authFormReady=canUseActions;
218
+ if(canUseActions)window.finoraMarkLoginBootstrapReady?.();
219
+ const reload=document.getElementById('auth-reload-page');
220
+ if(reload){
221
+ reload.hidden=canUseActions;
222
+ if(!reload.dataset.finoraReloadBound){
223
+ reload.addEventListener('click',()=>window.location.reload());
224
+ reload.dataset.finoraReloadBound='true';
225
+ }
226
+ }
227
setAuthLoginStatus(canUseActions?'فرم ورود و دکمهها آماده هستند.':'عملکرد دکمههای ورود بارگذاری نشده است؛ صفحه را دوباره بارگذاری کنید.',canUseActions?'ready':'error');
228
+ if(!canUseActions)window.finoraReportLoginBootstrapFailure?.();
229
// Remove the legacy plaintext user database that older versions kept in this browser.
230
try{localStorage.removeItem(AUTH_KEY);}catch(e){}
231
try{sessionStorage.removeItem('easy_factor_session_v4_7');}catch(e){}
js/login-connectivity.js
+42
-2
@@ -9,6 +9,10 @@ async function checkAuthConnectivity(){
9
out.textContent='در حال بررسی مستقل فایل برنامه و سرور ورود...';
10
out.dataset.status='checking';
11
try{
12
+ // Public configuration is available even if core.js never loaded.
13
+ const SUPABASE_URL=document.querySelector('meta[name="finora-auth-url"]')?.content||'';
14
+ const SUPABASE_KEY=document.querySelector('meta[name="finora-auth-publishable-key"]')?.content||'';
15
+ if(!/^https:\/\/[a-z0-9-]+\.supabase\.co$/.test(SUPABASE_URL)||!/^sb_publishable_[A-Za-z0-9_-]+$/.test(SUPABASE_KEY))throw new Error('DIAGNOSTIC_CONFIGURATION_UNAVAILABLE');
16
if(navigator.onLine===false){
17
out.textContent='اتصال اینترنت دستگاه قطع است (OFFLINE). اتصال را برقرار کنید و دوباره بررسی کنید.';
18
out.dataset.status='offline';
@@ -45,7 +49,7 @@ async function checkAuthConnectivity(){
49
simpleRequest=finoraConnectivityProbe(identified(simpleUrl.href),{method:'GET',credentials:'omit'});
50
}
51
const requests=[
48
- finoraConnectivityProbe(identified(new URL('js/login-connectivity.js?v=20261026-preflight-compare-v5',document.baseURI).href)),
52
+ finoraConnectivityProbe(identified(document.querySelector('script[src*="js/core.js"]')?.src||document.querySelector('link[rel="preload"][href*="js/core.js"]')?.href||new URL('js/core.js',document.baseURI).href)),
53
finoraConnectivityProbe(identified(new URL('manifest.json',document.baseURI).href)),
54
finoraConnectivityProbe(identified(SUPABASE_URL+'/auth/v1/health'),{method:'GET',headers:{apikey:SUPABASE_KEY}}),
55
finoraConnectivityProbe(identified(SUPABASE_URL+'/rest/v1/'),{method:'GET',headers:{apikey:SUPABASE_KEY}}),
@@ -75,7 +79,7 @@ async function checkAuthConnectivity(){
79
REST:{code:restCode,durationMs:rest.durationMs},
80
SIMPLE:{code:simpleCode,durationMs:simple.durationMs}
81
};
78
- window.FinoraLoginConnectivityReport={id,version:'20261026-preflight-compare-v5',checkedAt,origin:window.location.origin,durationMs:Math.round(performance.now()-started),probes};
82
+ window.FinoraLoginConnectivityReport={id,version:'20261110-login-bootstrap-v6',checkedAt,origin:window.location.origin,durationMs:Math.round(performance.now()-started),probes};
83
const codes=[siteCode,manifestCode,authCode,restCode,simpleCode].join(' | ');
84
if(!scriptOk&&!manifestOk){
85
out.dataset.status='site-error';
@@ -111,3 +115,39 @@ function isAuthNetworkError(error){
115
if(error?.code==='invalid_credentials'||error?.status===400||error?.status===401)return false;
116
return /fetch|network|load failed|timeout|abort/i.test(String(error?.message||''));
117
}
118
+
119
+
120
+// This file runs before core and the generated handlers. Diagnostics must stay
121
+// usable when either critical script fails; never read or store form values.
122
+(function(){
123
+ const button=document.getElementById('auth-connectivity-check');
124
+ if(button&&!button.dataset.finoraDiagnosticBound){
125
+ button.addEventListener('click',checkAuthConnectivity);
126
+ button.dataset.finoraDiagnosticBound='true';button.disabled=false;
127
+ }
128
+ const ready=()=>window.FinoraStartupStatus?.authFormReady===true;
129
+ const reload=document.getElementById('auth-reload-page');
130
+ if(reload&&!reload.dataset.finoraReloadBound){
131
+ reload.addEventListener('click',()=>window.location.reload());
132
+ reload.dataset.finoraReloadBound='true';
133
+ }
134
+ let failureCode=null;
135
+ function unavailable(code){
136
+ failureCode=code;
137
+ if(ready())return;
138
+ const status=document.getElementById('auth-login-status');
139
+ if(status){status.dataset.state='error';status.textContent='آمادهسازی دکمههای ورود کامل نشد ('+code+'). اتصال را بررسی کنید و سپس صفحه را دوباره بارگذاری کنید.';}
140
+ if(reload)reload.hidden=false;
141
+ }
142
+ const deadline=setTimeout(()=>unavailable(failureCode||'LOGIN_BOOTSTRAP_TIMEOUT'),6000);
143
+ window.finoraReportLoginBootstrapFailure=()=>unavailable(failureCode||'LOGIN_ACTIONS_LOAD_FAILED');
144
+ window.finoraMarkLoginBootstrapReady=()=>{clearTimeout(deadline);if(reload)reload.hidden=true;};
145
+ window.addEventListener('error',event=>{
146
+ if(ready())return;
147
+ const script=event.target?.tagName==='SCRIPT';
148
+ const source=String(script?event.target.src:event.filename||'');
149
+ let name='';try{name=new URL(source,document.baseURI).pathname.split('/').pop();}catch{return;}
150
+ if(name==='core.js')unavailable(script?'LOGIN_CORE_LOAD_FAILED':'LOGIN_CORE_EXECUTION_FAILED');
151
+ else if(name==='generated-event-handlers.js')unavailable('LOGIN_ACTIONS_LOAD_FAILED');
152
+ },true);
153
+})();
scripts/build-pages.mjs
+5
-1
@@ -61,7 +61,11 @@ html=html.replace(/;\s*frame-ancestors 'none'/i,'');
61
const recoveryEntrypoint=/<script src="js\/password-recovery\.js\?v=[^"]+"><\/script>\s*/i;
62
const recoveryThenCore=/<script src="js\/password-recovery\.js\?v=[^"]+"><\/script>\s*<script src="js\/core\.js\?v=[^"]+"><\/script>/i;
63
if(!recoveryThenCore.test(html))throw new Error('Missing ordered recovery/login entrypoints');
64
-const authSource=['password-recovery','core'].map(name=>fs.readFileSync(path.join(out,'js',name+'.js'),'utf8')).join('\n;\n');
64
+// Ship the vendored SDK and its consumers atomically: a failed separate SDK
65
+// request must not leave core.js throwing before login readiness is initialized.
66
+const authSource=[fs.readFileSync(path.join(out,'vendor','supabase.js'),'utf8'),...['password-recovery','core'].map(name=>fs.readFileSync(path.join(out,'js',name+'.js'),'utf8'))].join('\n;\n');
67
+if(!html.includes('<script src="vendor/supabase.js"></script>'))throw new Error('Missing canonical self-hosted Auth SDK');
68
+html=html.replace('<script src="vendor/supabase.js"></script>','');
69
new vm.Script(authSource,{filename:'core.js'});
70
const authHash=createHash('sha256').update(authSource).digest('hex').slice(0,16);
71
fs.writeFileSync(path.join(out,'js','core.js'),authSource);
scripts/login-connectivity-check.mjs
+6
-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=20261026-preflight-compare-v5'),'Missing versioned script');
10
-assert(html.includes('js/core.js?v=20261025-password-recovery-v1'),'Production login controls must use new cache version');
11
-assert(html.indexOf('<script src="js/login-connectivity.js?v=20261026-preflight-compare-v5"')<html.indexOf('<script src="js/core.js?v=20261025-password-recovery-v1"'),'Connectivity handler script must execute before core (not just preload)');
9
+assert(html.includes('js/login-connectivity.js?v=20261110-login-bootstrap-v6'),'Missing versioned script');
10
+assert(html.includes('js/core.js?v=20261110-login-bootstrap-v2'),'Production login controls must use new cache version');
11
+assert(html.indexOf('<script src="js/login-connectivity.js?v=20261110-login-bootstrap-v6"')<html.indexOf('<script src="js/core.js?v=20261110-login-bootstrap-v2"'),'Connectivity handler script must execute before core (not just preload)');
12
assert(html.includes('js/bootstrap.js?v=20261031-workspace-recovery-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=20261026-preflight-compare-v5',document.baseURI)"),'Missing same-origin executable asset probe');
23
+assert(diagnostic.includes('script[src*="js/core.js"]'),'Probe the actual versioned Auth entrypoint, independently of SDK execution');
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');
@@ -30,3 +30,5 @@ assert(!diagnostic.includes("if(!siteOk)"),'Legacy manifest-only SITE_UNREACHABL
30
assert(!diagnostic.includes('signInWithPassword')&&!diagnostic.includes('auth-password'),'Diagnostic must not touch credentials');
31
assert(diagnostic.includes('new AbortController()'),'Probe timeout must be bounded');
32
console.log('PASS: login connectivity diagnostics are read-only, cache-versioned and credential-free');
33
+
34
+for(const [name,constant] of [['finora-auth-url','SUPABASE_URL'],['finora-auth-publishable-key','SUPABASE_KEY']]){const value=core.match(new RegExp("const "+constant+"='([^']+)'"))?.[1];assert(value&&html.includes('name="'+name+'" content="'+value+'"'),'Standalone diagnostic public configuration must match Auth client');}
scripts/login-connectivity.spec.js
+16
-22
@@ -60,7 +60,7 @@ test('A failing manifest cannot falsely classify working login JS and Auth as SI
60
61
test('Critical JS read fails but manifest and Auth are healthy: report failed asset precisely',async({page})=>{
62
await page.goto(base,{waitUntil:'domcontentloaded'});
63
- await page.route('**/js/login-connectivity.js*',route=>route.abort('failed'));
63
+ await page.route('**/js/core.js*',route=>route.abort('failed'));
64
await page.route(healthRoot,route=>route.fulfill({
65
status:200,contentType:'application/json',
66
headers:{'access-control-allow-origin':'*'},
@@ -76,7 +76,7 @@ test('Critical JS read fails but manifest and Auth are healthy: report failed as
76
77
test('Both site resources and Auth unreachable: report independent failures without exposing user data',async({page})=>{
78
await page.goto(base,{waitUntil:'domcontentloaded'});
79
- await page.route('**/js/login-connectivity.js*',route=>route.abort('failed'));
79
+ await page.route('**/js/core.js*',route=>route.abort('failed'));
80
await page.route('**/manifest.json*',route=>route.abort('failed'));
81
await page.route(healthRoot,route=>route.abort('failed'));
82
await page.locator('#auth-connectivity-check').click();
@@ -171,7 +171,7 @@ test('Preflight comparison report excludes credentials query values bodies and r
171
const report=await page.evaluate(()=>window.FinoraLoginConnectivityReport);
172
expect(report).toBeTruthy();
173
expect(Object.keys(report).sort()).toEqual(['checkedAt','durationMs','id','origin','probes','version']);
174
- expect(report.version).toBe('20261026-preflight-compare-v5');
174
+ expect(report.version).toBe('20261110-login-bootstrap-v6');
175
expect(report.checkedAt).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/);
176
expect(report.id).toMatch(/^[A-Za-z0-9_-]{8,100}$/);
177
expect(report.origin).toBe(new URL(base).origin);
@@ -202,24 +202,18 @@ test('Preflight comparison clears an earlier report before an offline attempt',a
202
expect(await page.evaluate(()=>window.finoraTestOfflineRequests)).toBe(0);
203
});
204
205
-test('Preflight comparison never puts a non-publishable key into a query',async()=>{
206
- const fs=require('node:fs'),vm=require('node:vm');
207
- const out={textContent:'',dataset:{}},button={disabled:false},requests=[];
208
- const crypto=require('node:crypto');
209
- const window={location:{origin:'https://diagnostic.example.test'},crypto};
210
- const context=vm.createContext({
211
- window,crypto,
212
- document:{baseURI:'https://diagnostic.example.test/index.html',getElementById:id=>id==='auth-connectivity-result'?out:button},
213
- navigator:{onLine:true},
214
- SUPABASE_URL:'https://diagnostic-supabase.example.test',SUPABASE_KEY:'sb_secret_private_fixture',
215
- URL,Headers,AbortController,performance,setTimeout,clearTimeout,
216
- fetch:async(input)=>{requests.push(String(input));return new Response('{}',{status:200});}
217
- });
218
- await vm.runInContext(fs.readFileSync(require('node:path').resolve('js/login-connectivity.js'),'utf8')+'\ncheckAuthConnectivity();',context);
219
- expect(requests.some(url=>new URL(url).searchParams.has('apikey'))).toBe(false);
220
- expect(context.window.FinoraLoginConnectivityReport?.probes?.SIMPLE?.code).toBe('SIMPLE_SKIPPED');
221
- expect(JSON.stringify(context.window.FinoraLoginConnectivityReport)).not.toContain('sb_secret_private_fixture');
222
- expect(out.dataset.status).toBe('ok');
205
+test('Standalone diagnostics reject non-publishable configuration without any request',async({page})=>{
206
+ await page.goto(base,{waitUntil:'domcontentloaded'});
207
+ await page.evaluate(()=>{
208
+ document.querySelector('meta[name="finora-auth-publishable-key"]').content='sb_secret_private_fixture';
209
+ window.__diagnosticRequests=[];
210
+ window.fetch=async(input)=>{window.__diagnosticRequests.push(String(input));return new Response('{}',{status:200});};
211
+ });
212
+ await page.locator('#auth-connectivity-check').click();
213
+ await expect(page.locator('#auth-connectivity-result')).toHaveAttribute('data-status','error');
214
+ expect(await page.evaluate(()=>window.__diagnosticRequests)).toEqual([]);
215
+ expect(await page.evaluate(()=>window.FinoraLoginConnectivityReport)).toBeNull();
216
+ expect(await page.locator('#auth-connectivity-result').textContent()).not.toContain('sb_secret_private_fixture');
217
});
218
219
test('Auth and static files can work while Supabase PostgREST data endpoint is unreachable',async({page})=>{
@@ -255,7 +249,7 @@ test('A 503 data gateway response remains distinct from good Auth service',async
249
250
for(const scenario of [
251
{failed:'/auth/v1/health',stalled:'/rest/v1/',expected:'AUTH_UNREACHABLE',timeout:'REST_TIMEOUT'},
258
- {failed:'/js/login-connectivity.js',stalled:'/auth/v1/health',expected:'SITE_JS_NETWORK_ERROR',timeout:'AUTH_TIMEOUT'}
252
+ {failed:'/js/core.js',stalled:'/auth/v1/health',expected:'SITE_JS_NETWORK_ERROR',timeout:'AUTH_TIMEOUT'}
253
])test('An immediate '+scenario.expected+' remains distinct when another probe times out',async({page})=>{
254
await page.route('https://cdn.jsdelivr.net/**',route=>route.abort());
255
await page.route(healthRoot,route=>route.fulfill({status:200,body:'{}'}));
scripts/login-startup-readiness.spec.js
+97
@@ -264,3 +264,100 @@ test('early successful credentials cannot open the workspace when a required Pag
264
await expect(page.locator('#auth-screen')).toBeVisible();
265
expect(await page.evaluate(()=>({user:currentUser,writes:window.finoraLoginFixture.writes}))).toEqual({user:null,writes:0});
266
});
267
+
268
+test('Pages login survives an unavailable standalone SDK asset',async({page})=>{
269
+ await syntheticLogin(page);
270
+ await page.route('**/vendor/supabase.js*',r=>r.abort('failed'));
271
+ await page.goto(BASE,{waitUntil:'domcontentloaded'});
272
+ await expect(page.locator('#auth-login-button')).toBeEnabled({timeout:2500});
273
+ await expect(page.locator('#auth-reload-page')).toBeHidden();
274
+ await submitPassword(page);
275
+ await expect(page.locator('#auth-screen')).toBeHidden({timeout:15000});
276
+ expect(await page.evaluate(()=>window.finoraLoginFixture.passwordCalls)).toBe(1);
277
+});
278
+for(const asset of ['core','generated-event-handlers'])test('Pages '+asset+' failure leaves independent diagnostics and a truthful recovery action',async({page})=>{
279
+ await syntheticLogin(page);
280
+ await page.route('**/js/'+asset+'.js*',r=>r.abort('failed'));
281
+ await page.goto(BASE,{waitUntil:'domcontentloaded'});
282
+ await expect(page.locator('#auth-login-status')).toHaveAttribute('data-state','error',{timeout:8000});
283
+ await expect(page.locator('#auth-login-status')).toContainText(/LOGIN_.*(?:FAILED|TIMEOUT)/);
284
+ await expect(page.locator('#auth-login-button')).toBeDisabled();
285
+ await expect(page.locator('#auth-connectivity-check')).toBeEnabled();
286
+ await expect(page.locator('#auth-reload-page')).toBeVisible();
287
+ await page.locator('#auth-connectivity-check').click();
288
+ await expect(page.locator('#auth-connectivity-result')).toHaveAttribute('data-status',asset==='core'?'site-error':'auth-unreachable',{timeout:15000});
289
+ expect(await page.evaluate(()=>window.finoraLoginFixture.passwordCalls)).toBe(0);
290
+ await page.unroute('**/js/'+asset+'.js*');
291
+ await Promise.all([page.waitForNavigation({waitUntil:'domcontentloaded'}),page.locator('#auth-reload-page').click()]);
292
+ await expect(page.locator('#auth-login-button')).toBeEnabled();
293
+ await expect(page.locator('#auth-reload-page')).toBeHidden();
294
+ await expect(page.locator('#auth-login-status')).toHaveAttribute('data-state','ready');
295
+});
296
+
297
+test('delayed Auth bundle gives bounded feedback and recovers without losing typed input',async({page})=>{
298
+ await syntheticLogin(page);
299
+ let release;const held=new Promise(resolve=>{release=resolve});
300
+ await page.route('**/js/core.js*',async route=>{await held;await route.continue().catch(()=>{})});
301
+ try{
302
+ await page.goto(BASE,{waitUntil:'commit'});
303
+ await page.locator('#auth-email').fill('fixture@example.test');
304
+ await page.locator('#auth-password').fill('synthetic-password-only');
305
+ await expect(page.locator('#auth-login-status')).toContainText('LOGIN_BOOTSTRAP_TIMEOUT',{timeout:9000});
306
+ await expect(page.locator('#auth-connectivity-check')).toBeEnabled();
307
+ await expect(page.locator('#auth-login-button')).toBeDisabled();
308
+ release();
309
+ await expect(page.locator('#auth-login-button')).toBeEnabled();
310
+ await expect(page.locator('#auth-reload-page')).toBeHidden();
311
+ await expect(page.locator('#auth-email')).toHaveValue('fixture@example.test');
312
+ await expect(page.locator('#auth-password')).toHaveValue('synthetic-password-only');
313
+ await page.locator('#auth-login-button').click();
314
+ await expect(page.locator('#auth-screen')).toBeHidden({timeout:15000});
315
+ expect(await page.evaluate(()=>window.finoraLoginFixture.passwordCalls)).toBe(1);
316
+ }finally{release()}
317
+});
318
+
319
+for(const viewport of [{width:390,height:844},{width:1440,height:900},{width:1280,height:720}]){
320
+ test('healthy login hides recovery action at '+viewport.width+'x'+viewport.height,async({page})=>{
321
+ await page.setViewportSize(viewport);
322
+ await syntheticLogin(page);
323
+ await page.goto(BASE,{waitUntil:'domcontentloaded'});
324
+ await expect(page.locator('#auth-login-button')).toBeEnabled();
325
+ await expect(page.locator('#auth-reload-page')).toBeHidden();
326
+ });
327
+}
328
+
329
+test('bootstrap reload preserves recovery callback until recovery code can consume it',async({page})=>{
330
+ await syntheticLogin(page);
331
+ await page.addInitScript(()=>{window.finoraInitialCallback={hash:location.hash,search:location.search};});
332
+ await page.route('**/js/core.js*',r=>r.abort('failed'));
333
+ const url=new URL(BASE);
334
+ url.search='?finora_recovery=1';
335
+ url.hash='type=recovery&access_token=SYNTHETIC_ONLY&refresh_token=SYNTHETIC_ONLY';
336
+ await page.goto(url.href,{waitUntil:'domcontentloaded'});
337
+ await expect(page.locator('#auth-reload-page')).toBeVisible();
338
+ await page.unroute('**/js/core.js*');
339
+ await Promise.all([page.waitForNavigation({waitUntil:'domcontentloaded'}),page.locator('#auth-reload-page').click()]);
340
+ expect(await page.evaluate(()=>window.finoraInitialCallback)).toEqual({hash:url.hash,search:url.search});
341
+ // The independently loaded recovery sanitizer still removes credentials.
342
+ expect(new URL(page.url()).hash).toBe('');
343
+ expect(await page.evaluate(()=>window.finoraLoginFixture.passwordCalls)).toBe(0);
344
+});
345
+
346
+test('diagnostics use the versioned core preload while button handlers are pending',async({page})=>{
347
+ await syntheticLogin(page);
348
+ let release;const held=new Promise(resolve=>{release=resolve;});
349
+ await page.route('**/js/generated-event-handlers.js*',async route=>{await held;await route.continue().catch(()=>{});});
350
+ const probes=[];
351
+ page.on('request',req=>{const u=new URL(req.url());if(u.pathname.endsWith('/core.js')&&u.searchParams.has('finora_diag'))probes.push(u);});
352
+ try{
353
+ await page.goto(BASE,{waitUntil:'commit'});
354
+ await expect(page.locator('#auth-connectivity-check')).toBeEnabled();
355
+ expect(await page.locator('script[src*="js/core.js"]').count()).toBe(0);
356
+ const preload=new URL(await page.locator('link[rel="preload"][href*="js/core.js"]').getAttribute('href'),BASE);
357
+ await page.locator('#auth-connectivity-check').click();
358
+ await expect(page.locator('#auth-connectivity-result')).toHaveAttribute('data-status','auth-unreachable');
359
+ expect(probes).toHaveLength(1);
360
+ expect(probes[0].searchParams.get('v')).toBe(preload.searchParams.get('v'));
361
+ expect(preload.searchParams.get('v')).toMatch(/^[a-f0-9]{16}$/);
362
+ }finally{release();}
363
+});
scripts/pages-artifact.spec.js
+2
-1
@@ -34,12 +34,13 @@ test('Production CSP login and connectivity actions work while later ERP JS is s
34
delayedModuleFinished=true;
35
await route.continue();
36
});
37
- await page.route('**/auth/v1/health',route=>route.fulfill({
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
+ await page.route(/\/rest\/v1\/(?:\?|$)/,route=>route.fulfill({status:200,contentType:'application/json',body:'{}'}));
44
// The actual hardened Pages output removes inline onclick attributes.
45
await page.goto(base,{waitUntil:'commit'});
46
await expect(page.locator('#auth-connectivity-check')).toBeEnabled({timeout:4000});