سامانه صدور فاکتور و حسابداری
Mirrored from https://github.com/davoodmehraban89/Factor-easy.git
Synced Dec 3, 19:30 UTC
Compare simple and preflighted login health requests safely
davoodmehraban89 committed
Oct 26, 2026 at 08:47 UTC
2b06eb828861096eff3d4316606ab9857bf4855b
7 files changed
+252
-26
PROJECT_STATE.md
+4
@@ -141,3 +141,7 @@
141
- **Receipt documentation release VERIFIED:** main69e2da9b8573664e2a65b09ba2d960e14eba9e19, exact Quality40318656992 SUCCESS; Security40318656908 attempt2 SUCCESS after the independently verified runner retry; finalgate40319529150/job121560617861 and exactPages40319566777/job121560727485 SUCCESS. After deployment,12/12public runtime resource hashes match the prior verified application. Earlier cancelled gates40319100410/40319150057 and skipped Pages40319197865/40319541604 are not success evidence. Receipt delivery remains confirmed; owner-device connectivity remains OPEN/NOT FIXED with direct-health result pending. This investigation branch changes only continuity documentation; no speculative runtime/configuration fix was made.
142
- **Affected-PC direct request observed12:10UTC:** owner supplied a photo of the exact Supabase public health URL displaying gateway JSON No API key found. This is expected for a top-level request without apikey and demonstrates one completed direct response on that PC; it is NOT evidence that the app forgot its configured publishable key or proof that cross-origin/credentialed requests succeed. Total DNS/TLS/host outage is not established; continuous reachability, actual time-to-response and CORS/preflight/browser interference remain unknown. No production credential/configuration changes are justified by this response. Asked same-PC Incognito public app diagnostics without entering credentials; hotspot unavailable. Preserve Issue106 open until affected-site login is actually accepted.
143
- Read-only source review confirms current app explicitly supplies its publishable key, CSP permits the correct host, and no current production fetch override/service-worker registration is present. No defective key/CSP conclusion follows from the manual missing-key response. Incognito comparison preserves existing financial browser storage; do not recommend clearing site data, weakening CORS/CSP, no-cors authentication, blindly increasing waits or introducing a proxy without evidence/authorization. Direct health gateway response and fresh-context application diagnostics are different tests; actual affected-site login remains NOT VERIFIED.
144
+- **Affected-PC Incognito screenshot received12:23UTC:** Chrome Incognito marker visible, fields empty, form/actions-ready message; built-in diagnostic still SITE_JS_OK/MANIFEST_OK/AUTH_TIMEOUT/REST_TIMEOUT. This reproduces the stateless app diagnostic failure in a fresh browser context on that PC; old saved session alone is not its cause. It does not exclude extensions permitted in Incognito, OS/network filtering, valid-key gateway routing, CORS/preflight or latency. Stop treating cloud-only success or a direct keyless gateway401 as acceptance. Continue by distinguishing keyed/headered versus simple requests without account/password data or speculative production changes.
145
+- **Diagnostic implementation decision before runtime change:** extend the existing action with one simple same-project health GET, using only the already public sb_publishable key in its query and no custom headers/credentials, alongside the unchanged headered probes. This compares the project endpoint without OPTIONS; a bare401 only tests the gateway. Add safe UTC/id/per-probe durations and shared finora_diag query correlation; never expose key/URL/body/identity/token in the report. Other key formats skip the supplementary query. Existing failure states retain authority even if the simple request200s. This is diagnosis, not a proven login repair. Existing owner autonomous implementation/release authorization applies; no production Auth/DNS/RLS/schema change or new proxy is authorized. Design/plan are docs/superpowers/specs/2026-10-26-login-preflight-diagnostic-design.md and docs/superpowers/plans/2026-10-26-login-preflight-diagnostic.md. Meaningful RED is required before runtime edit.
146
+- **Diagnostic extension local checkpoint:** all5new meaningful regressions failed against the unchanged script (no setup failures), then the15-case focused suite passed on source and generated strict-CSP Pages; all51 existing static/behavioral/backup/server/release-safety commands passed, including45server tests and Golden. New diagnostic version20261026-preflight-compare-v5 changes only existing read-only diagnostic code/cache and reports; account Auth/REST transport is untouched. Full existing workflow suite182cases is running and independent review is in progress. No actual owner-side login or connectivity repair is claimed.
147
+- **Diagnostic extension final local evidence:**15/15source and15/15generated strict-CSP suite PASS; independent reviewer15/15source PASS with no blocking finding. Exact existing full workflow browser command **182/182 PASS (4.1m)**, all51static/behavioral/backup/server/release-safety PASS including45/45server andGolden, diff check PASS. Process-only cloud font configuration remains outside git; no dependency added. The only runtime change is read-only diagnostics plus cache tags; public-key-in-query is strictly supplementary/publishable-only, never actual Auth/REST transport. Publish the exact tested tree through PR183, verify its new head and merged main/gate/Pages, then check actualpublic5-probe/report/correlation behavior before requesting another owner result. Exact later SHA/run evidence belongs in PR183 description. Owner Incognito failure remains the current actual acceptance evidence; do not close106 or claim loginfixed. No new real mail/password/financial or productionconfiguration operation occurred.
docs/superpowers/plans/2026-10-26-login-preflight-diagnostic.md
new
+36
@@ -0,0 +1,36 @@
1
+# Login preflight comparison implementation plan
2
+
3
+> For agentic workers: use superpowers:executing-plans for the single implementation task; QA and final review may run independently. Steps use checkboxes for actual progress.
4
+
5
+**Goal:** Distinguish a successful simple project-health response from failed ordinary headered probes on the affected PC without changing login.
6
+
7
+**Architecture:** Extend checkAuthConnectivity in the existing small classic script. Use the same endpoint/public configuration, five concurrent bounded reads and a fixed privacy-safe report. Existing status branches retain authority.
8
+
9
+**Tech Stack:** Classic JavaScript, existing HTML/CSP build and Playwright; no dependencies.
10
+
11
+**Spec:** docs/superpowers/specs/2026-10-26-login-preflight-diagnostic-design.md
12
+
13
+## Global constraints
14
+
15
+No account/password/mail/financial operation, production SQL/Auth/DNS/RLS or dependency change. No authentication bypass or no-cors authentication. Separate12-second deadlines and existing duplicate guard remain. Supplementary success never proves ordinary login. Never expose configured keys, identities, bodies, tokens or raw errors in the report.
16
+
17
+## Review focus
18
+
19
+1. Supplementary200 with ordinary failure remains failed.
20
+2. Supplementary failure cannot break healthy ordinary probes.
21
+3. Query/error/input sentinels cannot enter the report.
22
+4. Offline/new checks cannot leave an old healthy report.
23
+5. Non-publishable keys cannot enter a supplementary query.
24
+
25
+## Task1 — diagnostic and delivery
26
+
27
+Files: js/login-connectivity.js; index.html cache tags; scripts/login-connectivity-check.mjs existing cache assertions; scripts/login-connectivity.spec.js; PROJECT_STATE.md and these two documents.
28
+
29
+- [x] Add five behavioral regressions for the review focus and query correlation; adjust only URL-routing patterns for new query strings.
30
+- [x] Execute the focused new tests against unchanged runtime; require meaningful RED, no actual network/account request.
31
+- [x] Extend checkAuthConnectivity with id/time/durations, five fixed probes, public-key-only simple request and sanitized report. Keep all real Auth/REST flows unchanged.
32
+- [x] Version diagnostic delivery and its self-probe; update existing cache checks.
33
+- [x] Run focused source and generated strict-CSP suites, existing full Quality command and51 checks including Golden/server/release safety. Inspect every result.
34
+- [x] Obtain independent whole-diff privacy/status review; correct demonstrated defects and rerun affected checks.
35
+- [ ] Update PR183 title/body around final scope, publish exact tested tree, verify exact-head CI, normal protected merge and exact-main/gated Pages, then actual public diagnostic readback.
36
+- [ ] Record NOT VERIFIED affected-PC result/actual login and keep Issue106 open; never infer connectivity repair from this diagnostic release.
docs/superpowers/specs/2026-10-26-login-preflight-diagnostic-design.md
new
+18
@@ -0,0 +1,18 @@
1
+# Login preflight comparison
2
+
3
+The affected PC reaches the keyless gateway directly but ordinary Auth and REST diagnostics time out in both normal and Incognito Chrome. The approximately matching server window contains OPTIONS200 without subsequent GETs. Cloud success does not reproduce that failure.
4
+
5
+The owner's existing instruction is to investigate and complete the login repair autonomously. This diagnostic is a reversible evidence-collection step within that scope; it does not establish a connectivity repair or authorize production configuration changes.
6
+
7
+## Approach
8
+
9
+Implementation choice: extend the existing diagnostic action with one concurrent simple CORS GET to the same health endpoint. It reuses only the existing explicitly publishable key in the query, omits credentials and sends no custom headers. Ordinary Auth/REST probes and actual authentication remain unchanged. A bare401 would test only the gateway; the simple keyed request tests the same project endpoint. A new proxy/custom domain needs separate evidence and authorization.
10
+
11
+- Only /^sb_publishable_[A-Za-z0-9_-]+$/ keys may enter the supplementary query. Other configured keys produce SIMPLE_SKIPPED; never place a secret/legacy JWT into this URL.
12
+- All five probes use the same fresh finora_diag query identifier for bounded log correlation, separate12-second deadlines, and header-only results. Never read a response body or call an account/table endpoint.
13
+- Preserve existing failure classification. SIMPLE_HTTP_200 cannot make failed ordinary Auth/REST healthy or establish login success.
14
+- Publish window.FinoraLoginConnectivityReport with only id, version, checkedAt, origin, durationMs and probes. Each fixed probe has only code and durationMs. No identity, key, token, header, body, raw exception or full URL.
15
+- Display UTC/id/per-probe durations in the existing output. Clear a previous report before a fresh/offline/failed check. Keep duplicate-click suppression.
16
+- Cache version20261026-preflight-compare-v5 applies only to the diagnostic script and its self-probe. No Auth transport, accounting, storage, CSP/RLS, DNS or server changes.
17
+
18
+Success here means an accurate privacy-safe comparison is deployed and usable. The affected-PC connection and actual login remain NOT VERIFIED until the owner-side result supports a repair and acceptance.
index.html
+2
-2
@@ -14,7 +14,7 @@
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=20261025-password-recovery-v1" />
17
-<link rel="preload" as="script" href="js/login-connectivity.js?v=20261024-independent-probes-v4" />
17
+<link rel="preload" as="script" href="js/login-connectivity.js?v=20261026-preflight-compare-v5" />
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" />
@@ -901,7 +901,7 @@ body{background:#f6f9fc}
901
902
<!-- The credential-free connectivity action must be loaded before core declares
903
login actions interactive. Hardened Pages binds static handlers just before core. -->
904
-<script src="js/login-connectivity.js?v=20261024-independent-probes-v4"></script>
904
+<script src="js/login-connectivity.js?v=20261026-preflight-compare-v5"></script>
905
<script src="js/password-recovery.js?v=20261026-recovery-cancel-v2"></script>
906
<script src="js/core.js?v=20261025-password-recovery-v1"></script>
907
<script src="js/admin.js?v=20261025-password-recovery-v1"></script>
js/login-connectivity.js
+40
-9
@@ -4,6 +4,7 @@ async function checkAuthConnectivity(){
4
const out=document.getElementById('auth-connectivity-result');
5
const button=document.getElementById('auth-connectivity-check');
6
if(!out||button?.disabled)return;
7
+ window.FinoraLoginConnectivityReport=null;
8
if(button)button.disabled=true;
9
out.textContent='در حال بررسی مستقل فایل برنامه و سرور ورود...';
10
out.dataset.status='checking';
@@ -13,27 +14,44 @@ async function checkAuthConnectivity(){
14
out.dataset.status='offline';
15
return;
16
}
16
- // Execute four independent GET checks. The REST root only returns
17
+ const started=performance.now();
18
+ const checkedAt=new Date().toISOString();
19
+ const id=window.crypto?.randomUUID?.()||Date.now().toString(36)+'-'+Math.random().toString(36).slice(2,12);
20
+ const identified=input=>{
21
+ const url=new URL(input,document.baseURI);
22
+ url.searchParams.set('finora_diag',id);
23
+ return url.href;
24
+ };
25
+ // The REST root only returns
26
// gateway/OpenAPI status: never call a table, use a user JWT or read records.
27
const finoraConnectivityProbe=async(input,init={})=>{
28
+ const probeStarted=performance.now();
29
const controller=new AbortController();
30
const timer=setTimeout(()=>controller.abort(),12000);
31
try{
32
const value=await fetch(input,{...init,cache:'no-store',signal:controller.signal});
33
// Only headers prove gateway reachability; do not download the body.
34
if(value.body)void value.body.cancel().catch(()=>{});
25
- return {status:'fulfilled',value};
35
+ return {status:'fulfilled',value,durationMs:Math.round(performance.now()-probeStarted)};
36
}catch{
27
- return {status:'rejected',timedOut:controller.signal.aborted};
37
+ return {status:'rejected',timedOut:controller.signal.aborted,durationMs:Math.round(performance.now()-probeStarted)};
38
}finally{clearTimeout(timer);}
39
};
40
+ let simpleRequest=Promise.resolve({status:'skipped',durationMs:0});
41
+ // Only an explicitly public key may enter this diagnostic-only URL.
42
+ if(/^sb_publishable_[A-Za-z0-9_-]+$/.test(String(SUPABASE_KEY))){
43
+ const simpleUrl=new URL(SUPABASE_URL+'/auth/v1/health');
44
+ simpleUrl.searchParams.set('apikey',SUPABASE_KEY);
45
+ simpleRequest=finoraConnectivityProbe(identified(simpleUrl.href),{method:'GET',credentials:'omit'});
46
+ }
47
const requests=[
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}})
48
+ finoraConnectivityProbe(identified(new URL('js/login-connectivity.js?v=20261026-preflight-compare-v5',document.baseURI).href)),
49
+ finoraConnectivityProbe(identified(new URL('manifest.json',document.baseURI).href)),
50
+ finoraConnectivityProbe(identified(SUPABASE_URL+'/auth/v1/health'),{method:'GET',headers:{apikey:SUPABASE_KEY}}),
51
+ finoraConnectivityProbe(identified(SUPABASE_URL+'/rest/v1/'),{method:'GET',headers:{apikey:SUPABASE_KEY}}),
52
+ simpleRequest
53
];
36
- const [script,manifest,auth,rest]=await Promise.all(requests);
54
+ const [script,manifest,auth,rest,simple]=await Promise.all(requests);
55
const describe=(r,name)=>{
56
if(r.status==='rejected')return name+(r.timedOut?'_TIMEOUT':'_NETWORK_ERROR');
57
return name+(r.value.ok?'_OK':'_HTTP_'+r.value.status);
@@ -49,7 +67,16 @@ async function checkAuthConnectivity(){
67
// It does NOT prove authenticated tenant reads or RLS authorization.
68
const restCode=rest.status==='rejected'?(rest.timedOut?'REST_TIMEOUT':'REST_UNREACHABLE'):'REST_HTTP_'+rest.value.status;
69
const restHealthy=rest.status==='fulfilled'&&rest.value.status<500;
52
- const codes=[siteCode,manifestCode,authCode,restCode].join(' | ');
70
+ const simpleCode=simple.status==='skipped'?'SIMPLE_SKIPPED':simple.status==='rejected'?(simple.timedOut?'SIMPLE_TIMEOUT':'SIMPLE_UNREACHABLE'):'SIMPLE_HTTP_'+simple.value.status;
71
+ const probes={
72
+ SITE_JS:{code:siteCode,durationMs:script.durationMs},
73
+ MANIFEST:{code:manifestCode,durationMs:manifest.durationMs},
74
+ AUTH:{code:authCode,durationMs:auth.durationMs},
75
+ REST:{code:restCode,durationMs:rest.durationMs},
76
+ SIMPLE:{code:simpleCode,durationMs:simple.durationMs}
77
+ };
78
+ window.FinoraLoginConnectivityReport={id,version:'20261026-preflight-compare-v5',checkedAt,origin:window.location.origin,durationMs:Math.round(performance.now()-started),probes};
79
+ const codes=[siteCode,manifestCode,authCode,restCode,simpleCode].join(' | ');
80
if(!scriptOk&&!manifestOk){
81
out.dataset.status='site-error';
82
out.textContent='دو فایل بررسیشده از این شبکه دریافت نشدند ('+codes+'). با اینترنت دیگری امتحان کنید؛ این آزمون علت قطعی مشکل ورود را مشخص نمیکند.';
@@ -69,6 +96,10 @@ async function checkAuthConnectivity(){
96
out.dataset.status='ok';
97
out.textContent='فایلهای سایت و درگاههای Auth و REST پاسخ دادهاند ('+codes+'). این نتیجه ورود موفق یا صحت مجوزها و دریافت اطلاعات شرکت را تأیید نمیکند.';
98
}
99
+ if(simple.status==='fulfilled'&&simple.value.status===200&&(!authOk||!restHealthy)){
100
+ out.textContent+=' درخواست سادهٔ همان سرور پاسخ داده، اما مسیر استاندارد برنامه موفق نبوده است؛ علت این تفاوت هنوز مشخص نیست.';
101
+ }
102
+ out.textContent+=' [UTC '+checkedAt+' | DIAG '+id+' | '+Object.entries(probes).map(([name,result])=>name+'='+result.durationMs+'ms').join(' | ')+']';
103
}catch{
104
out.textContent='بررسی مستقل اتصال کامل نشد (DIAGNOSTIC_FAILED). بدون ارسال رمز یا اطلاعات حساب دوباره امتحان کنید.';
105
out.dataset.status='error';
scripts/login-connectivity-check.mjs
+3
-3
@@ -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=20261024-independent-probes-v4'),'Missing versioned script');
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=20261024-independent-probes-v4"')<html.indexOf('<script src="js/core.js?v=20261025-password-recovery-v1"'),'Connectivity handler script must execute before core (not just preload)');
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)');
12
assert(html.includes('js/bootstrap.js?v=20261025-password-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=20261024-independent-probes-v4',document.baseURI)"),'Missing same-origin executable asset probe');
23
+assert(diagnostic.includes("new URL('js/login-connectivity.js?v=20261026-preflight-compare-v5',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
+149
-12
@@ -1,8 +1,11 @@
1
const { test, expect } = require('@playwright/test');
2
const base=process.env.FINORA_TEST_BASE||'http://127.0.0.1:4173/index.html';
3
+const healthRoot=/\/auth\/v1\/health(?:\?.*)?$/;
4
+const restRoot=/\/rest\/v1\/(?:\?.*)?$/;
5
test.beforeEach(async({page})=>{
6
+ await page.route('**/*',route=>new URL(route.request().url()).origin===new URL(base).origin?route.continue():route.abort());
7
// Gateway response confirms transport only; no private data or user token.
5
- await page.route('**/rest/v1/',route=>route.fulfill({
8
+ await page.route(restRoot,route=>route.fulfill({
9
status:200,
10
contentType:'application/json',
11
headers:{'access-control-allow-origin':'*'},
@@ -10,7 +13,7 @@ test.beforeEach(async({page})=>{
13
}));
14
});
15
test('Login diagnostics distinguish a reachable auth service from password errors', async ({page})=>{
13
- await page.route('**/auth/v1/health', route=>route.fulfill({
16
+ await page.route(healthRoot, route=>route.fulfill({
17
status:200, contentType:'application/json',
18
headers:{'access-control-allow-origin':'*'},
19
body:JSON.stringify({name:'GoTrue'})
@@ -23,7 +26,7 @@ test('Login diagnostics distinguish a reachable auth service from password error
26
await expect(page.locator('#auth-password')).toBeVisible();
27
});
28
test('Login diagnostics label upstream unreachable without exposing credentials', async ({page})=>{
26
- await page.route('**/auth/v1/health', route=>route.abort('failed'));
29
+ await page.route(healthRoot, route=>route.abort('failed'));
30
await page.goto(base,{waitUntil:'domcontentloaded'});
31
await page.locator('#auth-connectivity-check').click();
32
await expect(page.locator('#auth-connectivity-result')).toHaveAttribute('data-status','auth-unreachable',{timeout:15000});
@@ -31,7 +34,7 @@ test('Login diagnostics label upstream unreachable without exposing credentials'
34
expect(await page.locator('#auth-connectivity-result').textContent()).not.toContain('password');
35
});
36
test('Login diagnostics label HTTP server failures, not bad passwords', async ({page})=>{
34
- await page.route('**/auth/v1/health', route=>route.fulfill({status:503,headers:{'access-control-allow-origin':'*'},body:'unavailable'}));
37
+ await page.route(healthRoot, route=>route.fulfill({status:503,headers:{'access-control-allow-origin':'*'},body:'unavailable'}));
38
await page.goto(base,{waitUntil:'domcontentloaded'});
39
await page.locator('#auth-connectivity-check').click();
40
await expect(page.locator('#auth-connectivity-result')).toHaveAttribute('data-status','auth-http',{timeout:15000});
@@ -41,7 +44,7 @@ test('Login diagnostics label HTTP server failures, not bad passwords', async ({
44
test('A failing manifest cannot falsely classify working login JS and Auth as SITE_UNREACHABLE',async({page})=>{
45
await page.goto(base,{waitUntil:'domcontentloaded'});
46
await page.route('**/manifest.json*',route=>route.fulfill({status:404,body:'missing'}));
44
- await page.route('**/auth/v1/health',route=>route.fulfill({
47
+ await page.route(healthRoot,route=>route.fulfill({
48
status:200,contentType:'application/json',
49
headers:{'access-control-allow-origin':'*'},
50
body:'{"name":"GoTrue"}'
@@ -58,7 +61,7 @@ test('A failing manifest cannot falsely classify working login JS and Auth as SI
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'));
61
- await page.route('**/auth/v1/health',route=>route.fulfill({
64
+ await page.route(healthRoot,route=>route.fulfill({
65
status:200,contentType:'application/json',
66
headers:{'access-control-allow-origin':'*'},
67
body:'{"name":"GoTrue"}'
@@ -75,7 +78,7 @@ test('Both site resources and Auth unreachable: report independent failures with
78
await page.goto(base,{waitUntil:'domcontentloaded'});
79
await page.route('**/js/login-connectivity.js*',route=>route.abort('failed'));
80
await page.route('**/manifest.json*',route=>route.abort('failed'));
78
- await page.route('**/auth/v1/health',route=>route.abort('failed'));
81
+ await page.route(healthRoot,route=>route.abort('failed'));
82
await page.locator('#auth-connectivity-check').click();
83
const output=page.locator('#auth-connectivity-result');
84
await expect(output).toHaveAttribute('data-status','site-error',{timeout:15000});
@@ -85,9 +88,143 @@ test('Both site resources and Auth unreachable: report independent failures with
88
expect(await output.textContent()).not.toMatch(/Bearer |password|access_token|apiKey/i);
89
});
90
91
+test('Preflight comparison keeps standard Auth and REST failures when simple health responds',async({page})=>{
92
+ await page.goto(base,{waitUntil:'domcontentloaded'});
93
+ await page.clock.install();
94
+ await page.evaluate(()=>{
95
+ window.finoraTestProbeRequests=[];
96
+ window.fetch=(input,init={})=>{
97
+ const url=new URL(String(input));
98
+ window.finoraTestProbeRequests.push({
99
+ path:url.pathname,
100
+ diagnosticId:url.searchParams.get('finora_diag'),
101
+ simple:url.searchParams.has('apikey'),
102
+ publicKeyMatches:url.searchParams.get('apikey')===SUPABASE_KEY,
103
+ headerNames:[...new Headers(init.headers).keys()],
104
+ credentials:init.credentials,
105
+ method:init.method||'GET'
106
+ });
107
+ if(url.hostname.endsWith('.supabase.co')){
108
+ if(url.searchParams.has('apikey'))return Promise.resolve(new Response('{"name":"GoTrue"}',{status:200}));
109
+ return new Promise((resolve,reject)=>init.signal.addEventListener('abort',()=>reject(new DOMException('aborted','AbortError')),{once:true}));
110
+ }
111
+ return Promise.resolve(new Response('{}',{status:200}));
112
+ };
113
+ });
114
+ await page.locator('#auth-connectivity-check').click();
115
+ await page.clock.fastForward(12001);
116
+ const output=page.locator('#auth-connectivity-result');
117
+ await expect(output).toHaveAttribute('data-status','auth-unreachable');
118
+ await expect(output).toContainText('AUTH_TIMEOUT');
119
+ await expect(output).toContainText('REST_TIMEOUT');
120
+ await expect(output).toContainText('SIMPLE_HTTP_200');
121
+ await expect(output).toContainText('ساده');
122
+ await expect(output).not.toContainText(/(?:^|[ |(])AUTH_OK(?:[ |)]|$)/);
123
+ await expect(page.locator('#auth-connectivity-check')).toBeEnabled();
124
+ const {report,requests}=await page.evaluate(()=>({report:window.FinoraLoginConnectivityReport,requests:window.finoraTestProbeRequests}));
125
+ expect(report).toBeTruthy();
126
+ expect(report.probes.AUTH.code).toBe('AUTH_TIMEOUT');
127
+ expect(report.probes.REST.code).toBe('REST_TIMEOUT');
128
+ expect(report.probes.SIMPLE.code).toBe('SIMPLE_HTTP_200');
129
+ expect(report.durationMs).toBeGreaterThanOrEqual(12000);
130
+ expect(report.durationMs).toBeLessThanOrEqual(12050);
131
+ expect(requests).toHaveLength(5);
132
+ expect(requests.every(request=>request.diagnosticId===report.id&&request.method==='GET')).toBe(true);
133
+ const simple=requests.filter(request=>request.simple);
134
+ expect(simple).toHaveLength(1);
135
+ expect(simple[0]).toMatchObject({path:'/auth/v1/health',publicKeyMatches:true,headerNames:[],credentials:'omit'});
136
+});
137
+
138
+test('Preflight comparison supplemental failure cannot override healthy ordinary endpoints',async({page})=>{
139
+ await page.goto(base,{waitUntil:'domcontentloaded'});
140
+ await page.evaluate(()=>{
141
+ window.fetch=async(input)=>{
142
+ const url=new URL(String(input));
143
+ if(url.searchParams.has('apikey'))throw new TypeError('Failed to fetch');
144
+ return new Response('{}',{status:url.pathname==='/rest/v1/'?401:200});
145
+ };
146
+ });
147
+ await page.locator('#auth-connectivity-check').click();
148
+ const output=page.locator('#auth-connectivity-result');
149
+ await expect(output).toHaveAttribute('data-status','ok');
150
+ await expect(output).toContainText('AUTH_OK');
151
+ await expect(output).toContainText('REST_HTTP_401');
152
+ await expect(output).toContainText('SIMPLE_UNREACHABLE');
153
+ const report=await page.evaluate(()=>window.FinoraLoginConnectivityReport);
154
+ expect(report).toBeTruthy();
155
+ expect(report.probes.SIMPLE.code).toBe('SIMPLE_UNREACHABLE');
156
+});
157
+
158
+test('Preflight comparison report excludes credentials query values bodies and raw errors',async({page})=>{
159
+ await page.goto(base,{waitUntil:'domcontentloaded'});
160
+ await page.locator('#auth-email').fill('diagnostic-private@example.test');
161
+ await page.locator('#auth-password').fill('password-private-sentinel');
162
+ await page.evaluate(()=>{
163
+ history.replaceState({},'',location.pathname+'?access_token=location-private-sentinel');
164
+ window.fetch=async(input)=>{
165
+ if(new URL(String(input)).pathname==='/rest/v1/')throw new TypeError('raw-private-sentinel diagnostic-private@example.test password-private-sentinel');
166
+ return new Response('{"access_token":"body-private-sentinel"}',{status:200});
167
+ };
168
+ });
169
+ await page.locator('#auth-connectivity-check').click();
170
+ await expect(page.locator('#auth-connectivity-result')).toHaveAttribute('data-status','rest-unreachable');
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');
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);
178
+ expect(Object.keys(report.probes).sort()).toEqual(['AUTH','MANIFEST','REST','SIMPLE','SITE_JS']);
179
+ for(const probe of Object.values(report.probes)){
180
+ expect(Object.keys(probe).sort()).toEqual(['code','durationMs']);
181
+ expect(probe.durationMs).toBeGreaterThanOrEqual(0);
182
+ expect(Number.isFinite(probe.durationMs)).toBe(true);
183
+ }
184
+ expect(JSON.stringify(report)).not.toMatch(/diagnostic-private|password-private|location-private|body-private|raw-private|sb_publishable_|apikey|access_token|Bearer|headers/i);
185
+ expect(await page.locator('#auth-connectivity-result').textContent()).not.toMatch(/diagnostic-private|password-private|location-private|body-private|raw-private|sb_publishable_/i);
186
+});
187
+
188
+test('Preflight comparison clears an earlier report before an offline attempt',async({page})=>{
189
+ await page.route(healthRoot,route=>route.fulfill({status:200,body:'{}'}));
190
+ await page.goto(base,{waitUntil:'domcontentloaded'});
191
+ await page.locator('#auth-connectivity-check').click();
192
+ await expect(page.locator('#auth-connectivity-result')).toHaveAttribute('data-status','ok');
193
+ expect(await page.evaluate(()=>window.FinoraLoginConnectivityReport)).toBeTruthy();
194
+ await page.evaluate(()=>{
195
+ Object.defineProperty(navigator,'onLine',{configurable:true,get:()=>false});
196
+ window.finoraTestOfflineRequests=0;
197
+ window.fetch=()=>{window.finoraTestOfflineRequests++;return Promise.reject(new TypeError('Must not fetch offline'));};
198
+ });
199
+ await page.locator('#auth-connectivity-check').click();
200
+ await expect(page.locator('#auth-connectivity-result')).toHaveAttribute('data-status','offline');
201
+ expect(await page.evaluate(()=>window.FinoraLoginConnectivityReport)).toBeNull();
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');
223
+});
224
+
225
test('Auth and static files can work while Supabase PostgREST data endpoint is unreachable',async({page})=>{
89
- await page.route('**/rest/v1/',route=>route.abort('failed'));
90
- await page.route('**/auth/v1/health',route=>route.fulfill({
226
+ await page.route(restRoot,route=>route.abort('failed'));
227
+ await page.route(healthRoot,route=>route.fulfill({
228
status:200,contentType:'application/json',
229
headers:{'access-control-allow-origin':'*'},body:'{"name":"GoTrue"}'
230
}));
@@ -100,11 +237,11 @@ test('Auth and static files can work while Supabase PostgREST data endpoint is u
237
await expect(output).toContainText('REST_UNREACHABLE');
238
});
239
test('A 503 data gateway response remains distinct from good Auth service',async({page})=>{
103
- await page.route('**/rest/v1/',route=>route.fulfill({
240
+ await page.route(restRoot,route=>route.fulfill({
241
status:503,contentType:'application/json',
242
headers:{'access-control-allow-origin':'*'},body:'{}'
243
}));
107
- await page.route('**/auth/v1/health',route=>route.fulfill({
244
+ await page.route(healthRoot,route=>route.fulfill({
245
status:200,contentType:'application/json',
246
headers:{'access-control-allow-origin':'*'},body:'{"name":"GoTrue"}'
247
}));
@@ -121,7 +258,7 @@ for(const scenario of [
258
{failed:'/js/login-connectivity.js',stalled:'/auth/v1/health',expected:'SITE_JS_NETWORK_ERROR',timeout:'AUTH_TIMEOUT'}
259
])test('An immediate '+scenario.expected+' remains distinct when another probe times out',async({page})=>{
260
await page.route('https://cdn.jsdelivr.net/**',route=>route.abort());
124
- await page.route('**/auth/v1/health',route=>route.fulfill({status:200,body:'{}'}));
261
+ await page.route(healthRoot,route=>route.fulfill({status:200,body:'{}'}));
262
await page.goto(base,{waitUntil:'domcontentloaded'});
263
await page.clock.install();
264
await page.evaluate(({failed,stalled})=>{