@davoodmehraban89 / Factor-easy / commits / 3670153
Fork 0

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

fix: externalize runtime-generated inline event handlers

davoodmehraban89 committed Oct 2, 2026 at 01:18 UTC 36701539acaa3601bc957d0876b1d25a3c81199e
1 file changed +26 -3
scripts/build-pages.mjs
+26 -3
@@ -12,6 +12,26 @@ for(const name of ['manifest.json','CNAME']){
12 }
13 for(const dir of ['js','vendor'])fs.cpSync(path.join(root,dir),path.join(out,dir),{recursive:true});
14
15 +const simpleCall=/^\s*(?:return\s+)?(?:window\.)?[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*\s*\([^;]*\)\s*;?\s*$/;
16 +let dynamicHandlers=0;
17 +for(const name of fs.readdirSync(path.join(out,'js'))){
18 + if(!name.endsWith('.js'))continue;
19 + const file=path.join(out,'js',name);
20 + let source=fs.readFileSync(file,'utf8');
21 + source=source.replace(/\s(on[a-z]+)="([^"]*)"/gi,(_,attr,body)=>{
22 + const event=attr.slice(2).toLowerCase();
23 + const decoded=body.replace(/&quot;/g,'"').replace(/&#39;|&apos;/g,"'").replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&amp;/g,'&');
24 + if(!simpleCall.test(decoded))throw new Error(`Unsupported dynamic inline handler in ${name}: ${decoded}`);
25 + dynamicHandlers++;
26 + return ` data-finora-dynamic-${event}="${body}"`;
27 + });
28 + source=source
29 + .replace(/getAttribute\((['"])onclick\1\)/g,"getAttribute('data-finora-dynamic-click')")
30 + .replace(/\[onclick\^=/g,'[data-finora-dynamic-click^=')
31 + .replace(/\[onclick\*=/g,'[data-finora-dynamic-click*=');
32 + fs.writeFileSync(file,source);
33 +}
34 +
35 let html=fs.readFileSync(path.join(root,'index.html'),'utf8');
36 const handlers=[];
37 html=html.replace(/\s(on[a-z]+)="([^"]*)"/gi,(_,attr,body)=>{
@@ -30,9 +50,11 @@ html=html.replace(/script-src[^;]*/i,"script-src 'self' https://cdnjs.cloudflare
50 // frame-ancestors is ignored in meta-delivered CSP and generates a browser error;
51 // clickjacking protection must be supplied as an HTTP response header by the edge/host.
52 html=html.replace(/;\s*frame-ancestors 'none'/i,'');
33 -html=html.replace('</body>','<script src="js/generated-event-handlers.js"></script>\n</body>');
53 +html=html.replace('</body>','<script src="js/generated-event-handlers.js"></script>\n<script src="js/generated-dynamic-handlers.js"></script>\n</body>');
54 +
55 +const generated=`// Generated at build time from legacy static inline event attributes.\n(function(){\n${handlers.map(({id,event,body})=>` {\n const el=document.querySelector('[data-finora-handler-${id}]');\n if(el)el.addEventListener(${JSON.stringify(event)},function(event){\n const result=(function(event){${body}}).call(this,event);\n if(result===false){event.preventDefault();event.stopPropagation();}\n });\n }`).join('\n')}\n})();\n`;
56
35 -const generated=`// Generated at build time from legacy inline event attributes.\n(function(){\n${handlers.map(({id,event,body})=>` {\n const el=document.querySelector('[data-finora-handler-${id}]');\n if(el)el.addEventListener(${JSON.stringify(event)},function(event){\n const result=(function(event){${body}}).call(this,event);\n if(result===false){event.preventDefault();event.stopPropagation();}\n });\n }`).join('\n')}\n})();\n`;
57 +const dynamic=`// CSP-safe dispatcher for simple handlers emitted by runtime renderers.\n(function(){\n const events=['click','change','input','submit','blur','focus','keydown','keyup'];\n function splitArgs(text){\n const out=[];let cur='',quote='',escape=false;\n for(const ch of text){\n if(escape){cur+=ch;escape=false;continue;}\n if(ch==='\\\\'){cur+=ch;escape=true;continue;}\n if(quote){cur+=ch;if(ch===quote)quote='';continue;}\n if(ch==='\\"'||ch==="'"){quote=ch;cur+=ch;continue;}\n if(ch===','){out.push(cur.trim());cur='';continue;}\n cur+=ch;\n }\n if(cur.trim()||text.trim())out.push(cur.trim());\n return out;\n }\n function arg(token,el,event){\n if(token==='')return undefined;\n if((token[0]==="'"&&token.at(-1)==="'")||(token[0]==='\\"'&&token.at(-1)==='\\"'))return token.slice(1,-1).replace(/\\\\(['\\"\\\\])/g,'$1');\n if(token==='this')return el;if(token==='event')return event;if(token==='this.value')return el.value;if(token==='this.checked')return el.checked;if(token==='event.target.value')return event.target?.value;\n if(token==='true')return true;if(token==='false')return false;if(token==='null')return null;if(token==='undefined')return undefined;\n if(/^-?\\d+(?:\\.\\d+)?$/.test(token))return Number(token);\n throw new Error('Unsupported CSP-safe handler argument: '+token);\n }\n function invoke(expression,el,event){\n const text=String(expression||'').trim().replace(/^return\\s+/,'').replace(/;$/,'');\n const m=text.match(/^((?:window\\.)?[A-Za-z_$][\\w$]*(?:\\.[A-Za-z_$][\\w$]*)*)\\s*\\((.*)\\)$/);\n if(!m)throw new Error('Unsupported CSP-safe handler: '+text);\n const parts=m[1].replace(/^window\\./,'').split('.');let owner=window;\n for(let i=0;i<parts.length-1;i++)owner=owner?.[parts[i]];\n const fn=owner?.[parts.at(-1)];if(typeof fn!=='function')throw new Error('Missing CSP-safe handler function: '+m[1]);\n return fn.apply(el,splitArgs(m[2]).map(x=>arg(x,el,event)));\n }\n for(const type of events){\n document.addEventListener(type,function(event){\n const el=event.target?.closest?.('[data-finora-dynamic-'+type+']');if(!el)return;\n const result=invoke(el.getAttribute('data-finora-dynamic-'+type),el,event);\n if(result===false){event.preventDefault();event.stopPropagation();}\n },type==='blur'||type==='focus');\n }\n})();\n`;
58
59 if(/<script(?![^>]*\ssrc=)[^>]*>/i.test(html))throw new Error('Built page still contains inline script blocks');
60 if(/\son[a-z]+=/i.test(html))throw new Error('Built page still contains inline event handlers');
@@ -42,4 +64,5 @@ for(const tag of externalScripts)if(!/integrity=/i.test(tag))throw new Error('Bu
64
65 fs.writeFileSync(path.join(out,'index.html'),html);
66 fs.writeFileSync(path.join(out,'js','generated-event-handlers.js'),generated);
45 -console.log(`Pages artifact built: ${handlers.length} inline handlers externalized; diag.html intentionally excluded.`);
67 +fs.writeFileSync(path.join(out,'js','generated-dynamic-handlers.js'),dynamic);
68 +console.log(`Pages artifact built: ${handlers.length} static + ${dynamicHandlers} runtime inline handlers externalized; diag.html intentionally excluded.`);