36 lines
2.1 KiB
JavaScript
36 lines
2.1 KiB
JavaScript
import {readFileSync} from 'node:fs';
|
|
import vm from 'node:vm';
|
|
import test from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
const source = readFileSync(new URL('../../public/customer-service/widget.mjs', import.meta.url), 'utf8');
|
|
function page(config, protocol='http:') {
|
|
if(config?.base_url)config={enabled:true,...config};
|
|
const scripts=[], calls=[];
|
|
const context = {URL, MutationObserver:class{observe(){}}, location:{protocol,origin:'http://xb.loc'}, console, window:{addEventListener(){},
|
|
xbCustomerService:config, chatwootSDK:{run:args=>calls.push(args)},
|
|
// An XB session exists; the widget must never forward it.
|
|
fucSettings:{auth_data:'PRIVATE-XB-SESSION',email:'[email protected]'},
|
|
}, document:{body:{},getElementById:()=>null,createElement:()=>({events:{},addEventListener(name,fn){this.events[name]=fn;}}),
|
|
head:{append:script=>scripts.push(script)}}};
|
|
return {context,scripts,calls,run(){vm.runInNewContext(`(()=>{${source}\n})()`,context);}};
|
|
}
|
|
test('unconfigured instances and unsafe origins make no SDK request',()=>{
|
|
for(const config of [undefined,{}, {base_url:'javascript:alert(1)',website_token:'public'},
|
|
{base_url:'http://user:[email protected]:8596',website_token:'public'},
|
|
{base_url:'http://xb.loc:8596/redirect?secret=x',website_token:'public'}]){
|
|
const p=page(config);p.run();assert.equal(p.scripts.length,0);
|
|
}
|
|
const secure=page({base_url:'http://xb.loc:8596',website_token:'public'},'https:');
|
|
secure.run();assert.equal(secure.scripts.length,0);
|
|
});
|
|
test('SDK initializes once and receives only public widget configuration',()=>{
|
|
const p=page({base_url:'http://xb.loc:8596',website_token:'public'});
|
|
p.run();assert.equal(p.scripts.length,1);assert.equal(p.scripts[0].src,'http://xb.loc:8596/packs/js/sdk.js');
|
|
assert.deepEqual(JSON.parse(JSON.stringify(p.context.window.chatwootSettings)), {
|
|
locale: 'zh_CN', type: 'expanded_bubble', launcherTitle: '联系客服',
|
|
});
|
|
p.scripts[0].events.load();
|
|
assert.deepEqual(JSON.parse(JSON.stringify(p.calls)),[{websiteToken:'public',baseUrl:'http://xb.loc:8596'}]);
|
|
p.run();assert.equal(p.scripts.length,1);
|
|
});
|