Files
WidgetWorkbench/hmi-frontend/tests/cheerpj-runner.mjs
2026-11-01 10:09:34 +00:00

148 lines
10 KiB
JavaScript

/** 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(/<resources\b([^>]*)>([\s\S]*?)<\/resources>/g)].map(m=>{
const html=m[2];
const jars=[...html.matchAll(/<jar\b([^>]*?)\s*\/>/g)].map(x=>fixtureNode('jar',x[1]));
const natives=[...html.matchAll(/<nativelib\b([^>]*?)\s*\/>/g)].map(x=>fixtureNode('nativelib',x[1]));
const java=[...html.matchAll(/<java\b([^>]*?)\s*\/>/g)].map(x=>fixtureNode('java',x[1]));
const properties=[...html.matchAll(/<property\b([^>]*?)\s*\/>/g)].map(x=>fixtureNode('property',x[1]));
return fixtureNode('resources',m[1],[...java,...jars,...natives,...properties]);
});
const args=[...xml.matchAll(/<argument>([^<]*)<\/argument>/g)].map(m=>fixtureNode('argument','',[],m[1]));
const appMatch=xml.match(/<application-desc\b([^>]*?)(?:\/>|>(?:[\s\S]*?)<\/application-desc>)/);
const app=appMatch?fixtureNode('application-desc',appMatch[1],args):null;
const rootMatch=xml.match(/<jnlp\b([^>]*)>/);
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={},testOptions={}){
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(opts)=>called.push(['init',opts]),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]);
if(cp==='')return {java:{nio:{file:{
Paths:{get:async path=>{called.push(['tempPath',path]);return {value:path}}},
Files:{
createDirectories:async (path,attributes)=>{
called.push(['tempMkdir',path.value,attributes]);
if(testOptions.failTemp)throw Error('Speicherplatz erschöpft');
return path;
},
isDirectory:async (path,options)=>{
called.push(['tempIsDir',path.value,options]);
return !testOptions.notDirectory;
},
createTempFile:async (path,prefix,suffix,attributes)=>{
called.push(['tempProbe',path.value,prefix,suffix,attributes]);
if(testOptions.readOnly)throw Error('Schreiben nicht erlaubt');
return {value:path.value+'/hmi-tmp-check-1.tmp'};
},
deleteIfExists:async path=>{called.push(['tempProbeRemove',path.value]);return true;}
}
}}}};
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=`<?xml version="1.0"?><jnlp codebase="${origin}/jar/"><resources><jar href="app.jar"/><jar href="lib.jar"/></resources><application-desc main-class="com.demo.Main"><argument>HELLO</argument></application-desc></jnlp>`;
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='<jnlp><resources><jar href="a.jar"/></resources><application-desc/></jnlp>';
result=await launch(origin+'/jnlp/demo.jnlp');
assert.equal(result.end?.state,'finished');
assert.equal(result.called.at(-1)[0],'runJar');
responseText='<!DOCTYPE jnlp [ <!ENTITY x SYSTEM "file:///etc/passwd"> ]><jnlp/>';
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"');
// The server rewrites the JNLP to include a verified MES JVM property.
responseText=responseText.replace('<resources>',
'<resources><property name="itac.artes.clusternodes" value="https://demo.example.org:8181/mes"/>');
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.deepEqual(Array.from(result.called.find(c=>Array.isArray(c)&&c[0]==='init')[1].javaProperties),
['itac.artes.clusternodes=https://demo.example.org:8181/mes',
'java.io.tmpdir=/files/itac-workplace/tmp']);
const initIndex=result.called.findIndex(c=>Array.isArray(c)&&c[0]==='init');
const mkdirIndex=result.called.findIndex(c=>Array.isArray(c)&&c[0]==='tempMkdir');
const runIndex=result.called.findIndex(c=>Array.isArray(c)&&c[0]==='runMain');
assert.ok(initIndex>=0&&mkdirIndex>initIndex&&runIndex>mkdirIndex,
'Java-Temp-Ordner muss vor dem Workplace-Start erzeugt werden.');
assert.equal(result.called[mkdirIndex][1],'/files/itac-workplace/tmp');
assert.ok(result.called.some(c=>Array.isArray(c)&&c[0]==='tempIsDir'&&c[1]==='/files/itac-workplace/tmp'));
assert.ok(result.called.some(c=>Array.isArray(c)&&c[0]==='tempProbe'&&c[1]==='/files/itac-workplace/tmp'));
assert.ok(result.called.some(c=>Array.isArray(c)&&c[0]==='tempProbeRemove'));
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',11,{workplace:true},{failTemp:true});
assert.equal(result.end?.state,'error');
assert.match(result.end.message,/Temp-Verzeichnis.*Speicherplatz erschöpft/);
assert.ok(!result.called.some(c=>Array.isArray(c)&&c[0]==='runMain'),
'Workplace darf nicht ohne benutzbaren Temp-Ordner starten.');
result=await launch(origin+'/backend/api/hmi/v1/cheerpj/workplace/manifest.jnlp',11,{workplace:true},{notDirectory:true});
assert.equal(result.end?.state,'error');
assert.match(result.end.message,/kein Verzeichnis/);
assert.ok(!result.called.some(c=>Array.isArray(c)&&c[0]==='runMain'));
result=await launch(origin+'/backend/api/hmi/v1/cheerpj/workplace/manifest.jnlp',11,{workplace:true},{readOnly:true});
assert.equal(result.end?.state,'error');
assert.match(result.end.message,/Schreiben nicht erlaubt/);
assert.ok(!result.called.some(c=>Array.isArray(c)&&c[0]==='runMain'));
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, iTAC 129 JARs, writable virtual temp directory and startup ordering validated.');