/** CheerpJ Core contract tests, including the customer-provided iTAC Workplace JNLP. No proprietary JAR execution. */ import assert from 'node:assert/strict'; import fs from 'node:fs'; import vm from 'node:vm'; function fixtureNode(name,attributes='',children=[],content='') { const getAttribute=k=>attributes.match(new RegExp('(?:^|\\s)'+k+'="([^"]*)"'))?.[1]??null; const all=tag=>children.flatMap(c=>[...(c.localName===tag?[c]:[]),...(c.getElementsByTagName?.(tag)||[])]); return {localName:name,nodeType:1,childNodes:children,textContent:content,getAttribute,hasAttribute:k=>getAttribute(k)!==null,getElementsByTagName:all}; } class DOMParser { parseFromString(xml){ const groups=[...xml.matchAll(/]*)>([\s\S]*?)<\/resources>/g)].map(m=>{ const html=m[2]; const jars=[...html.matchAll(/]*?)\s*\/>/g)].map(x=>fixtureNode('jar',x[1])); const natives=[...html.matchAll(/]*?)\s*\/>/g)].map(x=>fixtureNode('nativelib',x[1])); const java=[...html.matchAll(/]*?)\s*\/>/g)].map(x=>fixtureNode('java',x[1])); return fixtureNode('resources',m[1],[...java,...jars,...natives]); }); const args=[...xml.matchAll(/([^<]*)<\/argument>/g)].map(m=>fixtureNode('argument','',[],m[1])); const appMatch=xml.match(/]*?)(?:\/>|>(?:[\s\S]*?)<\/application-desc>)/); const app=appMatch?fixtureNode('application-desc',appMatch[1],args):null; const rootMatch=xml.match(/]*)>/); const root=fixtureNode(rootMatch?'jnlp':'error',rootMatch?.[1]||'',[...groups,...(app?[app]:[])]); return {documentElement:root,getElementsByTagName:tag=>tag==='parsererror'?[]:root.getElementsByTagName(tag)}; } } const source=fs.readFileSync(new URL('../public/cheerpj-runner.js',import.meta.url),'utf8'); let responseText=''; const origin='https://demo.example.org:8181'; async function launch(path,version=11,opts={}){ const sent=[],called=[]; const context={URL,DOMParser, location:{href:origin+'/backend/hmi/cheerpj-runner.html',origin,hostname:'demo.example.org'}, document:{body:{classList:{add:()=>{}}},getElementById:()=>({textContent:'',className:'',getBoundingClientRect:()=>({width:960,height:640})})}, window:{parent:{postMessage:m=>sent.push(m)},addEventListener:(type,fn)=>{if(type==='message')context._handler=fn}, cheerpjInit:async()=>called.push('init'),cheerpjCreateDisplay:(w,h)=>{assert.equal(w,-1);assert.equal(h,-1);called.push('display')}, cheerpjRunMain:async (...args)=>{called.push(['runMain',...args]);return 0}, cheerpjRunJar:async (...args)=>{called.push(['runJar',...args]);return 0}, cheerpjRunLibrary:async cp=>{called.push(['library',cp]);return {com:{widgetworkbench:{cheerpj:{WorkplaceResizeBridge:{resize:async (w,h)=>{called.push(['resize',w,h]);return 1}}}}}}}}, parent:{postMessage:m=>sent.push(m)}, fetch:async u=>({ok:true,status:200,url:u,text:async()=>responseText}), setInterval,clearInterval,Error,Promise,ResizeObserver:class { observe(){} disconnect(){} }, }; vm.createContext(context);vm.runInContext('(function(){\n'+source+'\n})()',context); context._handler({source:context.window.parent,origin,data:{type:'hmi-cheerpj-launch',requestId:'test-1',jnlpUrl:path,javaVersion:version,...opts}}); for(let i=0;i<60&&!sent.some(s=>s.state==='finished'||s.state==='error');i++) await new Promise(r=>setTimeout(r,8)); return {end:sent.at(-1),called,sent}; } responseText=`HELLO`; let result=await launch(origin+'/jnlp/start.jnlp'); assert.equal(result.end?.state,'finished',JSON.stringify(result.end)); assert.equal(result.called.at(-1)[1],'com.demo.Main'); assert.equal(result.called.at(-1)[2],'/app/jar/app.jar:/app/jar/lib.jar'); assert.equal(result.called.at(-1)[3],'HELLO'); result=await launch('https://other.example.org/evil.jnlp'); assert.equal(result.end?.state,'error'); responseText=''; result=await launch(origin+'/jnlp/demo.jnlp'); assert.equal(result.end?.state,'finished'); assert.equal(result.called.at(-1)[0],'runJar'); responseText=' ]>'; result=await launch(origin+'/jnlp/demo.jnlp'); assert.equal(result.end?.state,'error'); // The provided iTAC Workplace file: codebase rewritten to fixed authenticated local bridge. responseText=fs.readFileSync(new URL('../../backend/src/main/resources/hmi/Workplace.jnlp',import.meta.url),'utf8') .replace('codebase="https://partner.itacsoftware.com:8181/mes/webstart/clients"', 'codebase="/backend/api/hmi/v1/cheerpj/workplace/jars"'); result=await launch(origin+'/backend/api/hmi/v1/cheerpj/workplace/manifest.jnlp',11,{workplace:true,displayMode:'fit'}); assert.equal(result.end?.state,'finished',JSON.stringify(result.end)); assert.ok(result.called.some(c=>Array.isArray(c)&&c[0]==='library'&&c[1].endsWith('workplace-resize-bridge-v2.jar'))); assert.ok(result.called.some(c=>Array.isArray(c)&&c[0]==='runMain'&&c[2].endsWith('workplace-resize-bridge-v2.jar'))); const workplaceCall=result.called.find(c=>Array.isArray(c)&&c[0]==='runMain'); assert.equal(workplaceCall[1],'com.itac.mes.suite.presentation.MesSuiteFrameWebstartLauncher'); assert.equal(workplaceCall[3],'itac.appid=Workplace'); assert.equal(workplaceCall[2].split(':').length,130); assert.match(result.sent.find(s=>s.state==='running')?.message||'',/RXTX/); result=await launch(origin+'/backend/api/hmi/v1/cheerpj/workplace/manifest.jnlp',8); assert.equal(result.end?.state,'error'); assert.match(result.end?.message||'',/Java 11/); // An HTTP host is supported when the JNLP and browser have exactly the same origin. const httpUrl='http://mes.internal:8181'; const httpContext={ URL,location:{href:httpUrl+'/backend/hmi/cheerpj-runner.html',origin:httpUrl,hostname:'mes.internal'} }; const m=source.match(/const trusted=([\s\S]*?);\nfunction readManifest/); assert.ok(m,'trusted URL helper present'); const resolveTrusted=vm.runInNewContext('('+m[1]+')',httpContext); assert.equal(resolveTrusted('/backend/api/hmi/v1/cheerpj/workplace/manifest.jnlp').protocol,'http:'); assert.throws(()=>resolveTrusted('http://evil.example.com/x.jnlp'),/Origin/); assert.throws(()=>resolveTrusted('https://mes.internal:8181/mes/x.jnlp'),/Origin/); const backend=fs.readFileSync(new URL('../../backend/src/main/java/com/workbenchclassic/hmi/HmiWorkplaceProxyResource.java',import.meta.url),'utf8'); assert.match(backend,/HmiImsapiGateway\.targetOrigin\(request\)/); assert.doesNotMatch(backend,/private static final String BASE = "https:\/\/partner/); assert.ok(fs.statSync(new URL('../public/cheerpj/workplace-resize-bridge-v2.jar',import.meta.url)).size>1000); console.log('CheerpJ contracts: JNLP, HTTP same-origin, no cross-origin, iTAC 129 JARs, Bridge classpath validated.');