سامانه صدور فاکتور و حسابداری
Mirrored from https://github.com/davoodmehraban89/Factor-easy.git
Synced Dec 3, 14:30 UTC
Fix login startup stall introduced by password recovery
davoodmehraban89 committed
Oct 28, 2026 at 09:16 UTC
bc6d9d885d32abecb695c4e49903592633870b86
4 files changed
+90
PROJECT_STATE.md
+7
@@ -145,3 +145,10 @@
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.
148
+
149
+### 2026-10-27 — Owner-requested before/after recovery startup regression investigation
150
+- Owner cannot perform the proposed Windows DNS change and reports that the severe startup issue began after Forgot Password was added; requests autonomous historical comparison and repair. Compare pre-recovery main ce32b0b52d974c2316b45b64a8166936f5a8d01e with recovery PR179 and current main. Fresh remote main49c4436cfec2005796e2bc77454dff9ca63e3db9 adds only Claude settings after PR183; no product divergence. Work continues in the existing isolated worktree on fix/recovery-login-startup-20261027. No owner-device settings change, real mail/password operation or production configuration/schema/data change is authorized by this investigation.
151
+- **Actual new regression reproduced before implementation:** generated strict-CSP Pages A/B with the same blocked external network and only the new password-recovery.js request held for3s: pre-recovery form enabled/core available; current form disabled/core undefined/document still loading. Releasing that request makes the current form ready in37ms. Independent core/security audit confirms SDK, endpoint, normal-session storage identity and Auth transport remain unchanged; recovery adds a blocking request before core/event binding. This is a proved new startup dependency, not proof that prior owner DNS/TLS failures share that cause.
152
+- Plan: first add a meaningful held-recovery-request browser regression, observe it fail against unchanged main, then package the exact recovery IIFE before core in the existing preloaded core request in the generated Pages artifact. Preserve static-handler-before-core order, recovery URL sanitization before SDK/session initialization and all recovery validation/tenant guards. Hash combined bytes for both preload and script so old core cannot pair with new HTML. Keep canonical source files, source execution order, account transport, stored data and production backend unchanged. Run targeted generated login/recovery suites, all existing checks/Golden/full browser suite, independent review and exact-head protected release checks. Actual affected-device login remains NOT VERIFIED and Issue106 stays open.
153
+- **Implemented and verified locally2026-10-28:** both new regressions failed against unchanged main for the intended reasons (disabled login while recovery download is held; stale core content version). Generated Pages now prepends the processed recovery IIFE to the existing preloaded core request, removes only its separate script tag and uses the complete-content SHA for both core references. No canonical runtime JavaScript or backend configuration changed. Full existing Quality browser command **184/184 PASS(3.8m)**, targeted startup plus full generated strict-CSP recovery **28/28 PASS(13.2s)**, all **51** existing static/behavioral/server/release-safety commands PASS including **45/45** server cases and Golden; diff check PASS. The initial input-driven attempt encountered the previously known local WOFF2/fontconfig issue, independently reproduced even on a standalone blank input; the final runs use only a process-local fontconfig exclusion, with no repository/CI/font/test-assertion change. Previous interrupted full-suite output was not counted; the complete rerun is persisted outside git.
154
+- **Independent application/security review:** no critical/important/minor findings; generated artifact order/hash verified and three additional synthetic SDK-boundary probes PASS (ordinary entry; valid recovery with another cached identity; invalid recovery Cancel preserving that identity). Concatenation's hoisted showAuthPanel is DOM-only and safe; URL sanitization and active guard still precede SDK initialization. Owner-network DNS/TLS/login acceptance, real password/email operations, physical printing and production two-user use remain NOT VERIFIED. Publish this scoped repair through its own protected PR; later exact PR/main SHA, CI/gate/Pages and public readback evidence belongs in the PR description, because those identifiers are created after this commit. No new real mail/account/password/financial write or Supabase production schema/Auth/DNS change occurred; rollback is reverting this build/test-only repair.
docs/superpowers/plans/2026-10-27-recovery-login-startup.md
new
+28
@@ -0,0 +1,28 @@
1
+# Recovery login startup repair implementation plan
2
+
3
+> **For agentic workers:** Use superpowers:executing-plans to execute the single repair and independent review before release.
4
+
5
+**Goal:** Remove the newly introduced standalone recovery download from the production login critical path.
6
+
7
+**Architecture:** In generated Pages only, prepend the existing processed recovery IIFE to the existing core asset and remove its separate script tag. Preserve recovery-before-core and CSP-handler-before-core execution. Derive both core script and preload version from the combined content hash.
8
+
9
+**Tech Stack:** Existing classic JavaScript, Node Pages builder, Playwright; no dependencies.
10
+
11
+**Spec:** PROJECT_STATE.md, 2026-10-27 owner-requested regression entry.
12
+
13
+## Constraints and review focus
14
+- No Auth transport, production backend/configuration, DNS, financial or source-script order changes.
15
+- Normal login must remain ready when the former standalone recovery URL cannot complete.
16
+- Valid recovery must sanitize callback fragments before the SDK reads them, including with another cached identity.
17
+- Invalid and marker-only callbacks must fail closed and allow Cancel.
18
+- Generated strict CSP event handlers must work before later ERP bundles finish.
19
+- Both preload and executing core URL must match the combined-content hash; recovery and core execute once.
20
+
21
+## Task: Remove the recovery download barrier
22
+- [x] Add a generated-Pages browser test holding the standalone recovery request; assert login controls and actual normal-login hydration work without releasing it.
23
+- [x] Build unchanged main and observe the assertion fail because core never executes.
24
+- [x] Modify only scripts/build-pages.mjs to combine processed recovery/core, verify syntax, remove the standalone tag and hash both core references.
25
+- [x] Run the new test plus existing startup, transport, recovery, admin and Pages suites; repeat full recovery suite against generated strict CSP.
26
+- [x] Run all existing Quality commands/Golden and the complete workflow browser suite; obtain independent application/security review.
27
+- [x] Record local results and actual limits in PROJECT_STATE.md:184/184full,28/28generated-focused,51checks/Golden/45server PASS; independent review has no findings.
28
+- Release gate: publish a separate PR, verify exact-head checks, protected merge and exact-main gated Pages/readback under existing owner release authorization. Record subsequent SHA/run/public evidence in the PR description. Never claim owner-network login acceptance from cloud tests alone.
scripts/build-pages.mjs
+11
@@ -56,6 +56,17 @@ html=html.replace(/script-src[^;]*/i,"script-src 'self' https://cdnjs.cloudflare
56
// frame-ancestors is ignored in meta-delivered CSP and generates a browser error;
57
// clickjacking protection must be supplied as an HTTP response header by the edge/host.
58
html=html.replace(/;\s*frame-ancestors 'none'/i,'');
59
+// Recovery must sanitize its callback before the SDK starts, without adding
60
+// another blocking download ahead of the preloaded login entrypoint.
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');
65
+new vm.Script(authSource,{filename:'core.js'});
66
+const authHash=createHash('sha256').update(authSource).digest('hex').slice(0,16);
67
+fs.writeFileSync(path.join(out,'js','core.js'),authSource);
68
+html=html.replace(recoveryEntrypoint,'');
69
+html=html.replace(/((?:href|src)="js\/core\.js\?v=)[^"]+/gi,(_,prefix)=>prefix+authHash);
70
// Login buttons are enabled by core.js *during HTML parsing*. Bind their
71
// CSP-safe static handlers first, not after dozens of blocking ERP modules.
72
const authEntrypoint=/<script src="js\/core\.js\?v=[^"]+"><\/script>/i;
scripts/login-startup-readiness.spec.js
+44
@@ -80,6 +80,50 @@ async function submitPassword(page){
80
await page.locator('#auth-login-button').click({noWaitAfter:true});
81
}
82
83
+test('Pages login does not wait for a separate recovery script download',async({page})=>{
84
+ await syntheticLogin(page);
85
+ let release;
86
+ const held=new Promise(resolve=>{release=resolve;});
87
+ const recoveryRequests=[];
88
+ await page.route('**/js/password-recovery.js*',async route=>{
89
+ recoveryRequests.push(route.request().url());
90
+ await held;
91
+ await route.continue().catch(()=>{});
92
+ });
93
+ try{
94
+ await page.goto(BASE,{waitUntil:'commit'});
95
+ await expect(page.locator('#auth-login-button')).toBeEnabled({timeout:2500});
96
+ expect(await page.evaluate(()=>({
97
+ bound:window.FinoraLoginActionsBound,
98
+ ready:window.FinoraStartupStatus?.authFormReady,
99
+ recovery:typeof window.finoraRequestPasswordRecovery,
100
+ active:window.FinoraPasswordRecovery?.active
101
+ }))).toEqual({bound:true,ready:true,recovery:'function',active:false});
102
+ await submitPassword(page);
103
+ await expect(page.locator('#auth-screen')).toBeHidden({timeout:15000});
104
+ expect(await page.evaluate(()=>({user:currentUser?.id,...window.finoraLoginFixture})))
105
+ .toEqual({user:'fixture-password',passwordCalls:1,profileReads:['fixture-password'],recordReads:1,writes:0});
106
+ expect(recoveryRequests).toEqual([]);
107
+ }finally{release();}
108
+});
109
+
110
+test('Pages preload and execute one core URL versioned from its complete auth content',async({page,request})=>{
111
+ await syntheticLogin(page);
112
+ const coreRequests=[];
113
+ page.on('request',req=>{if(new URL(req.url()).pathname.endsWith('/core.js'))coreRequests.push(req.url());});
114
+ await page.goto(BASE,{waitUntil:'domcontentloaded'});
115
+ const urls=await page.evaluate(()=>({
116
+ preload:document.querySelector('link[rel="preload"][href*="/core.js"]')?.href,
117
+ script:document.querySelector('script[src*="/core.js"]')?.src
118
+ }));
119
+ expect(urls.preload).toBe(urls.script);
120
+ const response=await request.get(urls.script);
121
+ expect(response.ok()).toBe(true);
122
+ const hash=require('node:crypto').createHash('sha256').update(await response.body()).digest('hex').slice(0,16);
123
+ expect(new URL(urls.script).searchParams.get('v')).toBe(hash);
124
+ expect(coreRequests).toEqual([urls.script]);
125
+});
126
+
127
for(const bundle of ['business','accounting']){
128
test('early successful Pages login survives a slow '+bundle+' bundle before company-read timeout starts',async({page})=>{
129
await syntheticLogin(page);