Initial Adaptive Music v0.5.0 release
This commit is contained in:
commit
14f0d8c26b
114 files changed
+6907
No files matched your search
@@ -0,0 +1,69 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { MAReadClient } from '../../gateway/ma-client.mjs';
|
||||
import { GatewayControl } from '../../gateway/control.mjs';
|
||||
import { SyntheticAudioGateway } from '../../gateway/synthetic-audio.mjs';
|
||||
const item=(id,provider='approved')=>({media_type:'playlist',is_playable:true,name:'Safe <name>',provider_mappings:[{provider_instance:provider,item_id:id,available:true}],uri:'private',metadata:{secret:'private'}});
|
||||
function client(fetchImpl,approvedProviders=['approved']) { return new MAReadClient({baseUrl:'http://localhost',token:'fixture',target:'dedicated',approvedProviders,fetchImpl}); }
|
||||
test('catalog paginates, strips private metadata and filters unapproved mappings',async()=>{
|
||||
const calls=[];
|
||||
const c=client(async(url,opts)=>{
|
||||
const {command,args}=JSON.parse(opts.body); calls.push({command,args});
|
||||
assert.deepEqual(args.provider,['approved']);
|
||||
return Response.json(command.includes('/radios/')?[]:args.offset===0?Array.from({length:100},(_,i)=>item(String(i))):[item('100'),item('bad','forbidden')]);
|
||||
});
|
||||
const result=await c.catalog(); assert.equal(result.length,101);
|
||||
assert.equal(calls.length,3);assert.equal(calls[1].args.offset,100);
|
||||
assert.deepEqual(Object.keys(result[0]).sort(),['id','kind','name','provider']);
|
||||
const again=await c.catalog();assert.equal(result[0].id,again[0].id);
|
||||
assert.ok(!JSON.stringify(result).includes('private'));
|
||||
});
|
||||
test('empty provider allowlist denies without I/O; malformed and endless pages fail',async()=>{
|
||||
let calls=0;const c=client(async()=>{calls++;},[]);
|
||||
await assert.rejects(c.catalog(),{code:'denied'});assert.equal(calls,0);
|
||||
await assert.rejects(client(async()=>Response.json({error:'private'})).catalog(),{code:'unavailable'});
|
||||
await assert.rejects(client(async()=>Response.json(Array.from({length:100},(_,i)=>item(String(i))))).catalog(),{code:'unavailable'});
|
||||
});
|
||||
test('target validation rejects group, changed identity and unavailable player',async()=>{
|
||||
const valid={player_id:'dedicated',provider:'sendspin',available:true,enabled:true,group_members:[],group_childs:[],static_group_members:[]};
|
||||
for(const patch of [{active_group:'other'},{synced_to:'other'},{group_members:['household']},{player_id:'wrong'},{available:false},{provider:'sonos'}]) {
|
||||
await assert.rejects(client(async()=>Response.json({...valid,...patch})).verifyTarget(),{code:'denied'});
|
||||
}
|
||||
});
|
||||
function audioFixture(){
|
||||
let now=0; const control=new GatewayControl({campaigns:{a:{},b:{}},origin:'https://example.test',now:()=>now});
|
||||
const audio=new SyntheticAudioGateway({control});for(const campaign of ['a','b'])audio.provision({campaign,session:'s'});
|
||||
const request={campaign:'a',session:'s',origin:'https://example.test',token:control.mint({campaign:'a',session:'s',role:'listener',ttlMs:1000})};
|
||||
const publish=(campaign,generation,value)=>audio.publish({campaign,session:'s',generation,pcm:new Uint8Array(1920).fill(value)});
|
||||
return {control,audio,request,publish,set now(value){now=value;}};
|
||||
}
|
||||
test('synthetic audio isolates simultaneous campaigns and copies every frame',()=>{
|
||||
const f=audioFixture(),a=f.audio.connect(f.request),b=f.audio.connect({...f.request,campaign:'b',token:f.control.mint({campaign:'b',session:'s',role:'listener'})});
|
||||
f.publish('a',1,11);f.publish('b',1,22);
|
||||
assert.equal(a.next().pcm[0],11);assert.equal(b.next().pcm[0],22);assert.equal(a.next(),null);
|
||||
f.publish('a',2,33);const frame=a.next();frame.pcm.fill(0);assert.equal(frame.sampleRate,24000);
|
||||
});
|
||||
test('audio denies forged origin/session/role, unknown fields and cross-campaign grants',()=>{
|
||||
const f=audioFixture();
|
||||
for(const patch of [{token:'forged'},{origin:'https://evil.test'},{session:'other'},{campaign:'b'},{command:'group'},{url:'http://localhost'},{token:f.control.mint({campaign:'a',session:'s',role:'controller'})}])assert.throws(()=>f.audio.connect({...f.request,...patch}),{code:'denied'});
|
||||
});
|
||||
test('active listener revocation/expiry and slow-client overflow close handles',()=>{
|
||||
const f=audioFixture(),a=f.audio.connect(f.request);f.control.revoke(f.request.token);f.audio.sweep();assert.equal(a.closed,true);
|
||||
const e=audioFixture(),b=e.audio.connect(e.request);e.now=1001;assert.throws(()=>b.next(),{code:'denied'});assert.equal(b.closed,true);
|
||||
const s=audioFixture(),c=s.audio.connect(s.request);for(let i=1;i<=11;i++)s.publish('a',i,0);
|
||||
assert.throws(()=>c.next(),{code:'stale'});assert.equal(c.closed,true);
|
||||
});
|
||||
test('synthetic source rejects stale sessions/generations, oversized frames; connections are bounded',()=>{
|
||||
const f=audioFixture();f.publish('a',1,0);assert.throws(()=>f.publish('a',1,0),{code:'stale'});
|
||||
assert.throws(()=>f.audio.publish({campaign:'a',session:'old',generation:2,pcm:new Uint8Array(1920)}),{code:'stale'});
|
||||
assert.throws(()=>f.audio.publish({campaign:'a',session:'s',generation:2,pcm:new Uint8Array(1921)}),{code:'denied'});
|
||||
for(let i=0;i<16;i++)f.audio.connect(f.request);assert.throws(()=>f.audio.connect(f.request),{code:'denied'});
|
||||
f.audio.purge('a');assert.throws(()=>f.audio.connect(f.request),{code:'denied'});
|
||||
});
|
||||
test('catalog authorization denies listener and injection before upstream',async()=>{
|
||||
let calls=0;const control=new GatewayControl({campaigns:{a:{client:{catalog:async()=>{calls++;return [];}}}},origin:'https://example.test'});
|
||||
const request={campaign:'a',session:'s',origin:'https://example.test',token:control.mint({campaign:'a',session:'s',role:'controller'}),generation:1};request.fence=control.acquire(request).fence;
|
||||
await assert.rejects(control.readCatalog({...request,provider:'forbidden'}),{code:'denied'});
|
||||
await assert.rejects(control.readCatalog({...request,token:control.mint({campaign:'a',session:'s',role:'listener'})}),{code:'denied'});assert.equal(calls,0);
|
||||
assert.deepEqual(await control.readCatalog(request),[]);assert.equal(calls,1);
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { savePlaylistConfiguration, mountPlaylistConfiguration, startConfigurationInterfaces } from '../../src/foundry/configuration.mjs';
|
||||
const choices=[{provider:'native',id:'owned',name:'Scene music'},{provider:'ma',id:'opaque',name:'Catalog music'}];
|
||||
function fixture(){
|
||||
let flag={boss:true,priority:7};const writes=[];
|
||||
const document={getFlag:()=>flag,async setFlag(ns,k,value){writes.push({ns,k,value});flag=value;}};
|
||||
return {document,writes,game:{user:{isGM:true}}};
|
||||
}
|
||||
test('scene/combat configuration preserves independent flags and stores only tagged references',async()=>{
|
||||
for(const choice of choices){const f=fixture();await savePlaylistConfiguration({...f,choices,selected:JSON.stringify([choice.provider,choice.id])});
|
||||
assert.deepEqual(f.writes,[{ns:'adaptive-music',k:'music',value:{boss:true,priority:7,playlist:{provider:choice.provider,id:choice.id}}}]);
|
||||
await savePlaylistConfiguration({...f,choices,selected:''});assert.equal(f.writes[1].value.playlist,null);
|
||||
}
|
||||
});
|
||||
test('role loss, stale selection and arbitrary URL/ID fail before document write',async()=>{
|
||||
const f=fixture();for(const selected of ['https://example.test/audio',JSON.stringify(['native','household']),JSON.stringify(['ma','stale'])])await assert.rejects(savePlaylistConfiguration({...f,choices,selected}),{code:'denied'});
|
||||
f.game.user.isGM=false;await assert.rejects(savePlaylistConfiguration({...f,choices,selected:''}),{code:'denied'});assert.equal(f.writes.length,0);
|
||||
});
|
||||
// Tiny DOM harness exercises event wiring/text sinks; it is not Foundry/browser evidence.
|
||||
class Element {
|
||||
constructor(tag,ownerDocument){this.tag=tag;this.ownerDocument=ownerDocument;this.children=[];this.dataset={};this.listeners={};}
|
||||
append(...children){this.children.push(...children);}
|
||||
querySelector(){return this.children.find(c=>c.dataset?.adaptiveMusic);}
|
||||
setAttribute(){}
|
||||
addEventListener(name,fn){this.listeners[name]=fn;}
|
||||
remove(){this.removed=true;}
|
||||
}
|
||||
function container(){const dom={createElement:tag=>new Element(tag,dom),createTextNode:text=>({textContent:text})};return new Element('div',dom);}
|
||||
test('editor uses text for catalog labels and rechecks GM on actual save event',async()=>{
|
||||
const f=fixture(),root=container();const panel=mountPlaylistConfiguration({...f,container:root,choices:[...choices,{provider:'ma',id:'x',name:'<img src=x onerror=attack()>'}]});
|
||||
assert.equal(mountPlaylistConfiguration({...f,container:root,choices}),null);
|
||||
const label=panel.children.find(c=>c.tag==='label'),select=label.children.find(c=>c.tag==='select');
|
||||
assert.ok(select.children.some(c=>c.textContent.includes('<img')));
|
||||
select.value=JSON.stringify(['native','owned']);const button=panel.children.find(c=>c.tag==='button');
|
||||
await button.listeners.click();assert.equal(f.writes.length,1);
|
||||
f.game.user.isGM=false;await button.listeners.click();assert.equal(f.writes.length,1);
|
||||
});
|
||||
test('configuration hook disposal prevents pending asynchronous render from mounting',async()=>{
|
||||
const f=fixture(),callbacks=new Map();let resolve;const off=[];
|
||||
const ui=startConfigurationInterfaces({...f,Hooks:{on(e,fn){callbacks.set(e,fn);return e;},off(...args){off.push(args);}},getChoices:()=>new Promise(r=>{resolve=r;})});
|
||||
const root=container();const pending=callbacks.get('renderSceneConfig')({document:f.document},root);ui.dispose();resolve(choices);await pending;assert.equal(root.children.length,0);assert.equal(off.length,2);
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
import {test} from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {createServer} from 'node:http';
|
||||
import {MAReadClient} from '../../gateway/ma-client.mjs';
|
||||
import {GatewayControl} from '../../gateway/control.mjs';
|
||||
import {DevelopmentService} from '../../gateway/development-service.mjs';
|
||||
import {startDevelopmentHTTP} from '../../gateway/development-http.mjs';
|
||||
import {GatewayClient} from '../../src/providers/ma/remote.mjs';
|
||||
import {SyntheticAudioGateway} from '../../gateway/synthetic-audio.mjs';
|
||||
import {MusicController} from '../../src/core/controller.mjs';
|
||||
const origin='https://foundry.example.test';
|
||||
async function fixture(){
|
||||
let items=[],state='idle',index=null,position=0;const writes=[],browserResponses=[];
|
||||
const track=id=>({queue_item_id:'occurrence-'+id,media_item:{media_type:'track',provider_mappings:[{provider_instance:'approved',item_id:id,available:true}]},duration:120});
|
||||
const queue=()=>({queue_id:'dev-only',active:true,available:true,items:items.length,state,current_index:index,current_item:items[index],elapsed_time:position,elapsed_time_last_updated:Date.now()/1000,repeat_mode:'off',shuffle_enabled:false,is_dynamic:false,autoplay_enabled:false,dont_stop_the_music_enabled:false,overlay_enabled:false,playback_speed:1,ended:false});
|
||||
let grouped=false;
|
||||
const ma=createServer(async(req,res)=>{
|
||||
assert.equal(req.headers.authorization,'Bearer MA-secret-fixture');let text='';for await(const chunk of req)text+=chunk;const {command,args}=JSON.parse(text);let result;
|
||||
if(command==='players/get')result={player_id:'dev-only',name:'Adaptive Music DEV',provider:'sendspin-fixture',available:true,enabled:true,group_members:grouped?['other']:[],group_childs:[],static_group_members:[]};
|
||||
else if(command==='player_queues/get'||command==='player_queues/get_active_queue')result=queue();
|
||||
else if(command==='player_queues/items')result=items.slice(args.offset,args.offset+args.limit);
|
||||
else if(command==='music/playlists/library_items')result=['ambient','combat'].map(id=>({name:'Fixture '+id,media_type:'playlist',is_playable:true,is_dynamic:false,provider_mappings:[{provider_instance:'approved',item_id:id,available:true}]}));
|
||||
else if(command==='music/radios/library_items')result=[];
|
||||
else if(command==='music/playlists/get')result={is_dynamic:false};
|
||||
else if(command==='music/playlists/playlist_tracks')result=[track(args.item_id+'-1').media_item,track(args.item_id+'-2').media_item];
|
||||
else{
|
||||
assert.equal(args.queue_id,'dev-only');writes.push(command);
|
||||
if(command==='player_queues/stop')state='idle';
|
||||
if(command==='player_queues/clear'){items=[];index=null;position=0;}
|
||||
if(command==='player_queues/play_media'){items=args.media.map(uri=>track(uri.split('/').at(-1)));index=0;position=0;if(args.option==='replace')state='playing';}
|
||||
if(command==='player_queues/play_index'){index=args.index;position=args.seek_position;state='playing';}
|
||||
if(command==='player_queues/pause')state='paused';result=null;
|
||||
}
|
||||
res.writeHead(200,{'Content-Type':'application/json'});res.end(JSON.stringify(result));
|
||||
});await new Promise(resolve=>ma.listen(0,'127.0.0.1',resolve));
|
||||
const client=new MAReadClient({baseUrl:`http://127.0.0.1:${ma.address().port}`,token:'MA-secret-fixture',target:'dev-only',approvedProviders:['approved'],catalogKey:Buffer.alloc(32,1),campaign:'server-c',expectedName:'Adaptive Music DEV',expectedProvider:'sendspin-fixture'});
|
||||
const choices=await client.catalog();
|
||||
let offset=0;const control=new GatewayControl({campaigns:{'server-c':{client}},origin,now:()=>Date.now()+offset});const grant=role=>({token:control.mint({campaign:'server-c',session:'server-s',role}),campaign:'server-c',session:'server-s'});
|
||||
const controller=grant('controller'),listener=grant('listener');
|
||||
const audio=new SyntheticAudioGateway({control});audio.provision({campaign:'server-c',session:'server-s'});
|
||||
const service=new DevelopmentService({control,campaign:'server-c',session:'server-s',client,snapshotKey:Buffer.alloc(32,2),allowedIds:choices.map(c=>c.id),playbackEnabled:true,audio});
|
||||
const http=await startDevelopmentHTTP({service,origin});
|
||||
const fetchImpl=async(path,options)=>{const response=await fetch(http.url+path.replace('/adaptive-music-gateway',''),{...options,headers:{...options.headers,Origin:origin}});browserResponses.push(await response.clone().text());return response;};
|
||||
const browser=new GatewayClient({origin,fetchImpl});
|
||||
return {browser,http,control,controller,listener,service,choices,writes,browserResponses,audio,client,expire(){offset=60001;},set grouped(value){grouped=value;},async close(){await browser.disconnect();await http.close();await new Promise(resolve=>ma.close(resolve));ma.closeAllConnections();}};
|
||||
}
|
||||
test('packaged browser client connects through real loopback companion/MA wire fixtures and restores combat queue',async()=>{
|
||||
const f=await fixture();try{
|
||||
const status=await f.browser.connect(f.controller);assert.equal(status.target,'verified');assert.equal(f.browser.catalog.length,2);
|
||||
const controller=new MusicController({campaign:'browser-world',session:'browser-session',providers:{ma:f.browser},authority:()=>true});
|
||||
const base={scene:{id:'scene',playlist:{provider:'ma',id:f.choices[0].id}},combats:[]};
|
||||
await controller.update(base);const combat={...base,combats:[{id:'combat',sceneId:'scene',active:true,started:true,playlist:{provider:'ma',id:f.choices[1].id}}]};
|
||||
await controller.update(combat);await controller.update(base);assert.equal(controller.current.playlist.id,f.choices[0].id);
|
||||
const before=f.writes.length;await Promise.allSettled([controller.update(combat),controller.update(base)]);assert.equal(f.writes.length,before);
|
||||
const wire=f.browserResponses.join('');assert.ok(!wire.includes('MA-secret-fixture'));assert.ok(!wire.includes('approved://'));assert.ok(!wire.includes('dev-only'));assert.ok(wire.includes('handle'));
|
||||
f.grouped=true;await assert.rejects(f.browser.stopOwned({generation:++controller.generation,check(){}}),{code:'denied'});assert.equal(f.writes.length,before);
|
||||
}finally{await f.close();}
|
||||
});
|
||||
test('companion denies listener control, wrong scope/Origin, upstream injection and unknown routes',async()=>{
|
||||
const f=await fixture();try{
|
||||
await assert.rejects(f.browser.connect(f.listener),{code:'denied'});
|
||||
const rpc=async(body,{grant=f.controller,requestOrigin=origin,path='/rpc'}={})=>fetch(f.http.url+path,{method:'POST',headers:{Origin:requestOrigin,Authorization:`Bearer ${grant.token}`,'Content-Type':'application/json'},body:JSON.stringify({...grant,token:undefined,...body})});
|
||||
for(const patch of [{campaign:'other',action:'catalog'},{action:'catalog',queue_id:'household'},{action:'transfer'}]){const res=await rpc(patch);assert.equal(res.status,403);}
|
||||
assert.equal((await rpc({action:'catalog'},{requestOrigin:'https://evil.test'})).status,403);
|
||||
assert.equal((await rpc({action:'catalog'},{path:'/api'})).status,403);assert.equal(f.writes.length,0);
|
||||
}finally{await f.close();}
|
||||
});
|
||||
test('browser accepts only relative same-origin paths and never persists a connection grant',()=>{
|
||||
for(const path of ['https://example.test','//evil.test','/../api','/api?token=x','/api#x'])assert.throws(()=>new GatewayClient({origin,path}),{code:'denied'});
|
||||
});
|
||||
test('companion operation replay is idempotent and same ID with changed payload is denied',async()=>{
|
||||
const f=await fixture();try{
|
||||
await f.browser.connect(f.controller);
|
||||
const body={action:'stop',campaign:f.controller.campaign,session:f.controller.session,fence:1,generation:1,operationId:'same-operation'};
|
||||
const send=patch=>fetch(f.http.url+'/rpc',{method:'POST',headers:{Origin:origin,Authorization:`Bearer ${f.controller.token}`,'Content-Type':'application/json'},body:JSON.stringify({...body,...patch})});
|
||||
assert.equal((await send()).status,200);assert.equal((await send()).status,200);assert.equal(f.writes.filter(c=>c==='player_queues/stop').length,1);
|
||||
assert.equal((await send({action:'snapshot'})).status,403);assert.equal((await send({generation:0,operationId:'stale'})).status,403);
|
||||
}finally{await f.close();}
|
||||
});
|
||||
test('companion listener stream rejects controller grant and closes on live revocation and expiry',async()=>{
|
||||
for(const mode of ['revoke','expire']){
|
||||
const f=await fixture();try{
|
||||
const open=grant=>fetch(f.http.url+'/audio',{method:'POST',headers:{Origin:origin,Authorization:`Bearer ${grant.token}`,'Content-Type':'application/json'},body:JSON.stringify({campaign:grant.campaign,session:grant.session})});
|
||||
const denied=await open(f.controller);assert.equal(denied.status,403);
|
||||
const response=await open(f.listener);assert.equal(response.status,200);const reader=response.body.getReader();
|
||||
f.audio.publish({campaign:'server-c',session:'server-s',generation:1,pcm:new Uint8Array(1920).fill(7)});assert.equal((await reader.read()).value[0],7);
|
||||
if(mode==='revoke')f.control.revoke(f.listener.token);else f.expire();
|
||||
let timer;try{await assert.rejects(Promise.race([reader.read(),new Promise((resolve,reject)=>{timer=setTimeout(()=>reject(Error('stream did not close promptly')),500);})]),{name:'TypeError'});}finally{clearTimeout(timer);}
|
||||
assert.equal(f.writes.length,0);
|
||||
}finally{await f.close();}
|
||||
}
|
||||
});
|
||||
|
||||
test('catalog revocation during upstream I/O suppresses the response at the companion boundary',async()=>{
|
||||
const f=await fixture();try{
|
||||
f.client.catalog=async()=>{f.control.revoke(f.controller.token);return [{name:'must never leave'}];};
|
||||
await assert.rejects(f.browser.connect(f.controller),{code:'denied'});
|
||||
assert.ok(!f.browserResponses.join('').includes('must never leave'));assert.equal(f.writes.length,0);
|
||||
}finally{await f.close();}
|
||||
});
|
||||
@@ -0,0 +1,128 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { MusicController, MusicError, candidates } from '../../src/core/controller.mjs';
|
||||
const ref = id => ({ provider: 'native', id });
|
||||
const scene = (id = 'A') => ({ id, playlist: ref(id) });
|
||||
const combat = (bosses = []) => ({ id: 'fight', active: true, started: true, sceneId: 'A', playlist: ref('combat'), bosses });
|
||||
const boss = (id = 'boss', priority = 1) => ({ id, priority, active: true, playlist: ref(id) });
|
||||
function fixture(options = {}) {
|
||||
const log = []; let playback = { items: ['duplicate','duplicate','third'], index: 1, offset: 42, paused: true };
|
||||
const provider = {
|
||||
async resolve(r,c) { log.push(['resolve',r.id]); return r; },
|
||||
async snapshot(c) { return { ...structuredClone(playback), campaign: c.campaign, session: c.session, generation: c.generation }; },
|
||||
async stopOwned(c) { c.check(); log.push(['stop']); },
|
||||
async apply(r,c) { c.check(); log.push(['apply',r.id]); playback = { items: [r.id], index: 0, offset: 0, paused: false }; },
|
||||
async restore(s,c) { c.check(); log.push(['restore',s]); playback = structuredClone(s); }
|
||||
};
|
||||
const controller = new MusicController({ campaign: 'campaign', session: 'session', providers: { native: provider, other: provider }, authority: () => true, ...options });
|
||||
return { controller, provider, log, get playback() { return playback; }, set playback(p) { playback=p; } };
|
||||
}
|
||||
test('policy precedence and explicit silence', () => {
|
||||
assert.equal(candidates({scene:scene(),combats:[combat([boss()])],overrides:[{id:'silence',playlist:null}]})[0].playlist,null);
|
||||
assert.equal(candidates({scene:scene(),combats:[combat([boss()])]})[0].playlist.id,'boss');
|
||||
assert.equal(candidates({scene:scene(),combats:[combat()]})[0].playlist.id,'combat');
|
||||
assert.equal(candidates({scene:scene()})[0].playlist.id,'A');
|
||||
assert.equal(candidates({defaultPlaylist:ref('world')})[0].playlist.id,'world');
|
||||
assert.equal(candidates({})[0].playlist,null);
|
||||
});
|
||||
test('inactive, unstarted and other scene combats ignored; boss ties stable', () => {
|
||||
for (const change of [{active:false},{started:false},{sceneId:'B'}]) {
|
||||
assert.equal(candidates({scene:scene(),combats:[{...combat([boss()]),...change}]})[0].playlist.id,'A');
|
||||
}
|
||||
assert.equal(candidates({scene:scene(),combats:[combat([boss('z',3),boss('a',3),boss('b',2)])]})[0].playlist.id,'a');
|
||||
});
|
||||
test('scene -> combat -> boss -> nested manual -> unwind restores offsets, duplicates and pause', async () => {
|
||||
const f=fixture(), c=f.controller;
|
||||
const base={scene:scene()}, fight={...base,combats:[combat()]}, big={...base,combats:[combat([boss()])]};
|
||||
await c.update(base); f.playback={items:['same','same','end'],index:1,offset:42,paused:true};
|
||||
await c.update(fight); await c.update(big);
|
||||
await c.update({...big,overrides:[{id:'one',playlist:ref('one')}]});
|
||||
await c.update({...big,overrides:[{id:'one',playlist:ref('one')},{id:'two',playlist:null}]});
|
||||
assert.equal((await c.update({...big,overrides:[{id:'one',playlist:ref('one')}]})).restored,true);
|
||||
assert.equal((await c.update(big)).restored,true);
|
||||
assert.equal((await c.update(fight)).restored,true);
|
||||
assert.equal((await c.update(base)).restored,true);
|
||||
assert.deepEqual(f.playback.items,['same','same','end']); assert.equal(f.playback.index,1);
|
||||
assert.equal(f.playback.offset,42); assert.equal(f.playback.paused,true);
|
||||
});
|
||||
test('scene change during manual never resurrects previous scene', async () => {
|
||||
const f=fixture(); const overrides=[{id:'manual',playlist:ref('manual')}];
|
||||
await f.controller.update({scene:scene()}); await f.controller.update({scene:scene(),overrides});
|
||||
await f.controller.update({scene:scene('B'),overrides}); await f.controller.update({scene:scene('B')});
|
||||
assert.equal(f.playback.items[0],'B'); assert.equal(f.controller.frames.length,0);
|
||||
});
|
||||
test('boss removed during manual and deleted combat cannot return', async () => {
|
||||
const f=fixture(); const base={scene:scene()}, big={...base,combats:[combat([boss()])]};
|
||||
await f.controller.update(base); await f.controller.update(big);
|
||||
await f.controller.update({...big,overrides:[{id:'m',playlist:ref('m')}]});
|
||||
await f.controller.update({...base,overrides:[{id:'m',playlist:ref('m')}]});
|
||||
await f.controller.update(base); assert.equal(f.playback.items[0],'A');
|
||||
assert.equal(f.controller.frames.length,0);
|
||||
});
|
||||
test('duplicate intent causes zero provider mutations', async () => {
|
||||
const f=fixture(); await f.controller.update({scene:scene()}); const before=f.log.length;
|
||||
assert.equal((await f.controller.update({scene:scene()})).unchanged,true); assert.equal(f.log.length,before);
|
||||
});
|
||||
test('prepare failure leaves current playback intact', async () => {
|
||||
const f=fixture(); await f.controller.update({scene:scene()});
|
||||
f.provider.resolve=async()=>{throw new MusicError('unavailable');};
|
||||
await assert.rejects(f.controller.update({scene:scene('B')}),{code:'unavailable'});
|
||||
assert.equal(f.playback.items[0],'A'); assert.equal(f.log.filter(x=>x[0]==='stop').length,0);
|
||||
});
|
||||
test('partial apply failure restores outgoing playback', async () => {
|
||||
const f=fixture(); await f.controller.update({scene:scene()});
|
||||
f.provider.apply=async()=>{throw new MusicError('unavailable');};
|
||||
await assert.rejects(f.controller.update({scene:scene('B')})); assert.equal(f.playback.items[0],'A');
|
||||
});
|
||||
test('obsolete async resolve is rejected before stop/apply', async () => {
|
||||
const f=fixture(); let resume, entered;
|
||||
const ready=new Promise(r=>entered=r), normal=f.provider.resolve;
|
||||
f.provider.resolve=async(r,c)=>{if(r.id==='A'){entered();await new Promise(r=>resume=r);} return normal(r,c);};
|
||||
const first=f.controller.update({scene:scene()}); await ready;
|
||||
const second=f.controller.update({scene:scene('B')}); resume();
|
||||
await assert.rejects(first,{code:'stale'}); await second;
|
||||
assert.deepEqual(f.log.filter(x=>x[0]==='apply'),[['apply','B']]);
|
||||
});
|
||||
test('lease loss during stop prevents apply and stale rollback', async () => {
|
||||
let active=true; const f=fixture({authority:()=>active}); await f.controller.update({scene:scene()});
|
||||
f.provider.stopOwned=async()=>{active=false;};
|
||||
await assert.rejects(f.controller.update({scene:scene(),combats:[combat()]}),{code:'stale'});
|
||||
assert.equal(f.log.filter(x=>x[0]==='restore').length,0);
|
||||
});
|
||||
test('provider switch and bounded nested stack', async () => {
|
||||
const f=fixture({maxFrames:2}); await f.controller.update({scene:scene()});
|
||||
await f.controller.update({scene:{id:'B',playlist:{provider:'other',id:'other'}}});
|
||||
assert.equal(f.playback.items[0],'other');
|
||||
for(let i=0;i<5;i++) await f.controller.update({scene:scene(),overrides:Array.from({length:i+1},(_,j)=>({id:String(j),playlist:ref(String(j))}))});
|
||||
assert.ok(f.controller.frames.length<=2);
|
||||
});
|
||||
test('no authority retains playback without provider access', async () => {
|
||||
const f=fixture({authority:()=>false}); await assert.rejects(f.controller.update({scene:scene()}),{code:'stale'}); assert.deepEqual(f.log,[]);
|
||||
});
|
||||
test('queued state is captured at submission rather than read after caller mutation',async()=>{
|
||||
const f=fixture(),state={scene:scene()};const pending=f.controller.update(state);state.scene.playlist=ref('mutated');
|
||||
await pending;assert.equal(f.playback.items[0],'A');
|
||||
});
|
||||
test('supersession after snapshot prevents mutations',async()=>{
|
||||
const f=fixture();await f.controller.update({scene:scene()});
|
||||
let resume,entered;const ready=new Promise(r=>entered=r),normal=f.provider.snapshot;
|
||||
f.provider.snapshot=async c=>{const s=await normal(c);entered();await new Promise(r=>resume=r);return s;};
|
||||
const first=f.controller.update({scene:scene(),combats:[combat()]});await ready;
|
||||
f.provider.snapshot=normal;const second=f.controller.update({scene:scene('B')});resume();
|
||||
await assert.rejects(first,{code:'stale'});await second;
|
||||
assert.equal(f.log.filter(x=>x[0]==='apply'&&x[1]==='combat').length,0);
|
||||
});
|
||||
test('failed cross-provider apply cleans new owned audio before outgoing restoration',async()=>{
|
||||
const f=fixture();await f.controller.update({scene:scene()});const effects=[];
|
||||
f.controller.providers.other={resolve:async r=>r,apply:async()=>{effects.push('partial');throw new Error('failed');},stopOwned:async()=>effects.push('cleanup')};
|
||||
await assert.rejects(f.controller.update({scene:{id:'B',playlist:{provider:'other',id:'B'}}}));
|
||||
assert.deepEqual(effects,['partial','cleanup']);assert.equal(f.playback.items[0],'A');
|
||||
});
|
||||
test('superseded cross-provider apply is reconciled by stopping partially touched target',async()=>{
|
||||
const f=fixture();await f.controller.update({scene:scene()});
|
||||
let resume,entered;const ready=new Promise(r=>entered=r);let cleanups=0;
|
||||
f.controller.providers.other={resolve:async r=>r,apply:async()=>{entered();await new Promise(r=>resume=r);},stopOwned:async()=>{cleanups++;}};
|
||||
const stale=f.controller.update({scene:{id:'B',playlist:{provider:'other',id:'B'}}});await ready;
|
||||
const newest=f.controller.update({scene:scene()});resume();await assert.rejects(stale,{code:'stale'});await newest;
|
||||
assert.equal(cleanups,1);assert.equal(f.playback.items[0],'A');
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
import {test} from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {mkdtemp,mkdir,writeFile,readFile,rm} from 'node:fs/promises';
|
||||
import {tmpdir} from 'node:os';
|
||||
import {join} from 'node:path';
|
||||
import {fileURLToPath} from 'node:url';
|
||||
import {spawn,spawnSync} from 'node:child_process';
|
||||
import {createServer} from 'node:http';
|
||||
test('extracted companion launches privately with fixture credentials, serves catalog diagnostics and listener PCM',async()=>{
|
||||
const folder=await mkdtemp(join(tmpdir(),'adaptive-companion-')),commands=[];
|
||||
const ma=createServer(async(req,res)=>{let text='';for await(const chunk of req)text+=chunk;const {command}=JSON.parse(text);commands.push(command);let result;
|
||||
if(command==='players/get')result={player_id:'dev-only',name:'Adaptive Music DEV',provider:'sendspin-fixture',enabled:true,available:true,group_members:[],group_childs:[],static_group_members:[]};
|
||||
else if(command.startsWith('player_queues/get'))result={queue_id:'dev-only',active:true,available:true};else result=[];
|
||||
res.writeHead(200,{'Content-Type':'application/json'});res.end(JSON.stringify(result));});
|
||||
await new Promise(resolve=>ma.listen(0,'127.0.0.1',resolve));let child;
|
||||
try{
|
||||
const source=fileURLToPath(new URL('../../scripts/package_module.py',import.meta.url));
|
||||
const script="import importlib.util,pathlib,sys,zipfile;s=importlib.util.spec_from_file_location('p',sys.argv[1]);m=importlib.util.module_from_spec(s);s.loader.exec_module(m);p=m.build_companion(pathlib.Path(sys.argv[2])/'companion.zip');zipfile.ZipFile(p).extractall(sys.argv[2])";
|
||||
const built=spawnSync('python3',['-c',script,source,folder],{encoding:'utf8'});assert.equal(built.status,0,built.stderr);
|
||||
const root=join(folder,'adaptive-music-companion'),local=join(root,'.local');await mkdir(local,{mode:0o700});
|
||||
const json=(name,value)=>writeFile(join(local,name),JSON.stringify(value),{mode:0o600});
|
||||
await writeFile(join(local,'ma-token'),'fixture-MA-secret',{mode:0o600});
|
||||
await json('environment.json',{ma_url:`http://127.0.0.1:${ma.address().port}`});await json('development-gateway.json',{foundryOrigin:'https://foundry.example.test',syntheticAudio:true});
|
||||
await json('ma-readonly-results.json',{me:{player_filter:['dev-only'],provider_filter:['approved']},player:{name:'Adaptive Music DEV',provider:'sendspin-fixture'}});
|
||||
child=spawn(process.execPath,['gateway/run-development.mjs'],{cwd:root,stdio:['ignore','pipe','pipe']});let output='';child.stdout.on('data',chunk=>{output+=chunk;});child.stderr.on('data',chunk=>{output+=chunk;});
|
||||
for(let attempt=0;attempt<200;attempt++){try{await readFile(join(local,'listener-bootstrap.json'));break;}catch{await new Promise(resolve=>setTimeout(resolve,10));}}
|
||||
const runtime=JSON.parse(await readFile(join(local,'development-gateway-runtime.json'),'utf8')),controller=JSON.parse(await readFile(join(local,'controller-bootstrap.json'),'utf8')),listener=JSON.parse(await readFile(join(local,'listener-bootstrap.json'),'utf8'));
|
||||
assert.ok(runtime.url.startsWith('http://127.0.0.1:'));assert.ok(!output.includes('fixture-MA-secret'));
|
||||
const rpc=async(action)=>fetch(runtime.url+'/rpc',{method:'POST',headers:{Origin:'https://foundry.example.test','Content-Type':'application/json',Authorization:`Bearer ${controller.token}`},body:JSON.stringify({action,campaign:controller.campaign,session:controller.session})});
|
||||
assert.equal((await rpc('connect')).status,200);const d=await (await rpc('diagnostics')).json();assert.equal(d.target,'verified');assert.equal(d.playbackEnabled,false);assert.deepEqual(await (await rpc('catalog')).json(),[]);
|
||||
const before=commands.length;
|
||||
const audio=await fetch(runtime.url+'/audio',{method:'POST',headers:{Origin:'https://foundry.example.test','Content-Type':'application/json',Authorization:`Bearer ${listener.token}`},body:JSON.stringify({campaign:listener.campaign,session:listener.session})});
|
||||
assert.equal(audio.status,200);const reader=audio.body.getReader();const frame=await reader.read();assert.ok(frame.value.length>=1920);await reader.cancel();assert.equal(commands.length,before);assert.ok(!commands.some(c=>['player_queues/play_media','player_queues/stop'].includes(c)));
|
||||
}finally{
|
||||
if(child&&child.exitCode===null){const exited=new Promise(resolve=>child.once('exit',resolve));child.kill('SIGTERM');await exited;}
|
||||
ma.closeAllConnections();await new Promise(resolve=>ma.close(resolve));await rm(folder,{recursive:true,force:true});
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,79 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { GatewayControl } from '../../gateway/control.mjs';
|
||||
import { MAReadClient } from '../../gateway/ma-client.mjs';
|
||||
function fixture() {
|
||||
let now=1000,calls=0;
|
||||
const g=new GatewayControl({campaigns:{a:{target:'dedicated-a',client:{async getOwnedQueue(id){assert.equal(id,'dedicated-a');calls++;return {state:'playing',items:3,secret:'must never leave'};}}},b:{target:'dedicated-b'}},origin:'https://example.test',now:()=>now});
|
||||
const token=g.mint({campaign:'a',session:'s',role:'controller'});
|
||||
const request={token,origin:'https://example.test',campaign:'a',session:'s',generation:1};
|
||||
request.fence=g.acquire(request).fence;
|
||||
return {g,request,get calls(){return calls;},set now(value){now=value;}};
|
||||
}
|
||||
test('gateway binds target server-side and sanitizes metadata',async()=>{
|
||||
const f=fixture();assert.deepEqual(await f.g.readQueue(f.request),{state:'playing',items:3});assert.equal(f.calls,1);
|
||||
});
|
||||
test('forged, wrong origin/campaign/session and unknown args deny before upstream',async()=>{
|
||||
const f=fixture();
|
||||
for(const patch of [{token:'forged'},{origin:'https://evil.test'},{campaign:'b'},{session:'other'},{queue_id:'household'},{command:'player_queues/transfer'},{uri:'http://example.test/'}])
|
||||
await assert.rejects(f.g.readQueue({...f.request,...patch}),{code:'denied'});
|
||||
assert.equal(f.calls,0);
|
||||
});
|
||||
test('listener cannot read queues or acquire controller lease',async()=>{
|
||||
const f=fixture(),token=f.g.mint({campaign:'a',session:'s',role:'listener'});
|
||||
await assert.rejects(f.g.readQueue({...f.request,token}),{code:'denied'});
|
||||
assert.throws(()=>f.g.acquire({...f.request,token}),{code:'denied'});assert.equal(f.calls,0);
|
||||
});
|
||||
test('expiry, revocation, stale fence and replay reject',async()=>{
|
||||
const f=fixture();await f.g.readQueue(f.request);
|
||||
await assert.rejects(f.g.readQueue(f.request),{code:'stale'});
|
||||
await assert.rejects(f.g.readQueue({...f.request,generation:2,fence:999}),{code:'stale'});
|
||||
f.now=40000;await assert.rejects(f.g.readQueue({...f.request,generation:2}),{code:'stale'});
|
||||
f.g.revoke(f.request.token);await assert.rejects(f.g.readQueue({...f.request,generation:2}),{code:'denied'});
|
||||
});
|
||||
test('lease cannot be stolen and increases fence after revoke',()=>{
|
||||
const f=fixture(),token=f.g.mint({campaign:'a',session:'s2',role:'controller'});
|
||||
assert.throws(()=>f.g.acquire({...f.request,token,session:'s2'}),{code:'denied'});
|
||||
f.g.revoke(f.request.token);const next=f.g.acquire({...f.request,token,session:'s2'});assert.equal(next.fence,2);
|
||||
});
|
||||
test('revocation during upstream I/O suppresses response',async()=>{
|
||||
const f=fixture();f.g.campaigns.get('a').client.getOwnedQueue=async()=>{f.g.revoke(f.request.token);return {state:'playing',items:1};};
|
||||
await assert.rejects(f.g.readQueue(f.request),{code:'denied'});
|
||||
});
|
||||
test('MA adapter uses pinned envelope, Bearer header, fixed path, no redirects and returns no metadata',async()=>{
|
||||
const client=new MAReadClient({baseUrl:'http://localhost:9999',token:'fixture-token',target:'owned',fetchImpl:async(url,options)=>{
|
||||
assert.equal(url,'http://localhost:9999/api');assert.equal(options.redirect,'error');
|
||||
assert.equal(options.headers.Authorization,'Bearer fixture-token');
|
||||
assert.deepEqual(JSON.parse(options.body),{message_id:'adaptive-music-read',command:'player_queues/get',args:{queue_id:'owned'}});
|
||||
return new Response(JSON.stringify({queue_id:'owned',active:true,state:'paused',items:2,uri:'secret'}));
|
||||
}});
|
||||
assert.deepEqual(await client.getOwnedQueue('owned'),{state:'paused',items:2});
|
||||
await assert.rejects(client.getOwnedQueue('household'),{code:'denied'});
|
||||
});
|
||||
test('MA mismatched queue, upstream failures and redirects fail with sanitized errors',async()=>{
|
||||
for(const fetchImpl of [async()=>new Response(JSON.stringify({queue_id:'household',active:true})), async()=>{throw new Error('private URL and secret');},async()=>new Response('failure',{status:403}),async()=>new Response('x'.repeat(1048577))]){
|
||||
const client=new MAReadClient({baseUrl:'http://localhost:9999',token:'fixture',target:'owned',fetchImpl});
|
||||
await assert.rejects(client.getOwnedQueue('owned'),e=>['denied','unavailable'].includes(e.message));
|
||||
}
|
||||
});
|
||||
test('MA rejects URL credentials, query/fragment, paths and non-HTTP configuration',()=>{
|
||||
for(const baseUrl of ['file:///etc/passwd','http://localhost/path','http://localhost/?token=x','http://localhost/#x','http://' + 'user:pass' + '@localhost/'])
|
||||
assert.throws(()=>new MAReadClient({baseUrl,token:'fixture',target:'owned'}));
|
||||
});
|
||||
test('MA read adapter performs real local HTTP POST against an isolated fixture',async()=>{
|
||||
const {createServer}=await import('node:http');
|
||||
const requests=[];
|
||||
const server=createServer(async(req,res)=>{
|
||||
let body='';for await(const chunk of req)body+=chunk;
|
||||
requests.push({method:req.method,path:req.url,auth:req.headers.authorization,body:JSON.parse(body)});
|
||||
res.writeHead(200,{'Content-Type':'application/json'});
|
||||
res.end(JSON.stringify({queue_id:'fixture-target',active:true,state:'paused',items:3}));
|
||||
});
|
||||
await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
|
||||
try {
|
||||
const client=new MAReadClient({baseUrl:`http://127.0.0.1:${server.address().port}`,token:'offline-fixture-only',target:'fixture-target'});
|
||||
assert.deepEqual(await client.getOwnedQueue('fixture-target'),{state:'paused',items:3});
|
||||
assert.equal(requests.length,1);assert.equal(requests[0].path,'/api');assert.equal(requests[0].method,'POST');
|
||||
assert.equal(requests[0].body.args.queue_id,'fixture-target');assert.equal(requests[0].auth,'Bearer offline-fixture-only');
|
||||
} finally { await new Promise(resolve=>server.close(resolve)); }
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
import {test} from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {SignalCodec,newAudioInvite} from '../../src/audio/signal-codec.mjs';
|
||||
import {PeerAudio,validateIceServers} from '../../src/audio/peer-audio.mjs';
|
||||
import {gmAccessPolicy,GMAudioHost} from '../../src/audio/gm-host.mjs';
|
||||
import {SendspinDecoder} from '../../vendor/sendspin-5.0.0.mjs';
|
||||
test('signaling is confidential, per-listener authenticated, scoped and replay resistant',async()=>{
|
||||
const invite=newAudioInvite({session:'s',userId:'player'}),gm=new SignalCodec(invite,'gm'),listener=new SignalCodec(invite,'listener');
|
||||
const secretSdp='v=0\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\na=sendonly\r\n';
|
||||
const frame=await gm.seal({type:'answer',sdp:secretSdp});assert.ok(!JSON.stringify(frame).includes('m=audio'));
|
||||
assert.deepEqual(await listener.open(frame),{type:'answer',sdp:secretSdp});await assert.rejects(listener.open(frame),{code:'denied'});
|
||||
const other=new SignalCodec(newAudioInvite({session:'s',userId:'other'}),'listener');await assert.rejects(other.open(frame),{code:'denied'});
|
||||
await assert.rejects(new SignalCodec(invite,'listener').open({...frame,seq:2}),{code:'denied'});
|
||||
await assert.rejects(gm.seal({type:'answer',sdp:secretSdp,token:'must not be sent'}),{code:'denied'});
|
||||
});
|
||||
test('signaling denies expired invitation, unknown/audio message types and unapproved TURN secrets',async()=>{
|
||||
assert.throws(()=>new SignalCodec({...newAudioInvite({session:'s',userId:'p'}),expires:0},'gm'),{code:'denied'});
|
||||
const codec=new SignalCodec(newAudioInvite({session:'s',userId:'p'}),'gm');await assert.rejects(codec.seal({type:'audio',pcm:[1,2]}),{code:'denied'});
|
||||
assert.deepEqual(validateIceServers([]),[]);
|
||||
assert.throws(()=>validateIceServers([{urls:'turn:relay.example.test',username:'static',credential:'secret'}]),{code:'denied'});
|
||||
assert.throws(()=>validateIceServers([{urls:'https://example.test'}]),{code:'denied'});
|
||||
assert.throws(()=>validateIceServers([{urls:'stun:user@relay.example.test'}]),{code:'denied'});
|
||||
});
|
||||
test('GM browser policy refuses mixed content and SDK identity mismatch before any MA connection',async()=>{
|
||||
assert.throws(()=>gmAccessPolicy('http://ma.example.test/','https://foundry.example.test/'),{code:'mixed-content'});
|
||||
assert.throws(()=>gmAccessPolicy('https://ma.example.test/?token=no','https://foundry.example.test/'),{code:'denied'});
|
||||
let sockets=0,closed=0;const host=new GMAudioHost({authority:()=>true,pageUrl:'https://foundry.example.test/',loadSDK:async()=>({loadSendspinClientIdentity:()=>({clientId:'wrong'})}),createSocket:()=>{sockets++;},createContext:()=>({state:'running',resume:async()=>{},createMediaStreamDestination:()=>({stream:{getTracks:()=>[]}}),close:async()=>{closed++;}})});
|
||||
await assert.rejects(host.readCatalog({}),{code:'auth-log-review-required'});assert.equal(sockets,0);
|
||||
await assert.rejects(host.start({maUrl:'https://ma.example.test/',target:'existing',targetName:'Adaptive Music DEV',expectedProvider:'sendspin-fixture',identityStorage:{'sendspin-identity-sk':'fixture'},approvedProviders:[],catalogKey:'fixture',namespace:'n'}),{code:'identity-mismatch'});assert.equal(sockets,0);assert.equal(closed,1);
|
||||
});
|
||||
test('official pinned SDK decodes real binary PCM frames and discards stale generations',async()=>{
|
||||
const chunks=[];let generation=1;const decoder=new SendspinDecoder(chunk=>chunks.push(chunk),()=>generation);
|
||||
const frame=new ArrayBuffer(9+8);const view=new DataView(frame);view.setUint8(0,4);view.setBigInt64(1,123456n,false);for(let i=0;i<4;i++)view.setInt16(9+i*2,16384,true);
|
||||
const format={codec:'pcm',channels:2,sample_rate:24000,bit_depth:16};await decoder.handleBinaryMessage(frame,format,1);assert.equal(chunks.length,1);assert.equal(chunks[0].samples[0][0],0.5);assert.equal(chunks[0].serverTimeUs,123456);
|
||||
generation=2;await decoder.handleBinaryMessage(frame,format,1);assert.equal(chunks.length,1);decoder.close();
|
||||
});
|
||||
test('parallel signaling replay cannot pass the asynchronous authentication check twice',async()=>{
|
||||
const invite=newAudioInvite({session:'parallel',userId:'p'}),sender=new SignalCodec(invite,'gm'),receiver=new SignalCodec(invite,'listener');
|
||||
const frame=await sender.seal({type:'bye'});const results=await Promise.allSettled([receiver.open(frame),receiver.open(frame)]);assert.equal(results.filter(r=>r.status==='fulfilled').length,1);
|
||||
});
|
||||
test('GM API WebSocket adapter authenticates privately, assembles partial results and refuses broad commands',async()=>{
|
||||
const {GMMAWebSocket}=await import('../../src/providers/ma/websocket.mjs');const sent=[];
|
||||
const bridge=new GMMAWebSocket({baseUrl:'https://ma.example.test',token:'GM-fixture-only',createSocket:url=>{
|
||||
assert.equal(url,'wss://ma.example.test/ws');
|
||||
const socket={send(text){const msg=JSON.parse(text);sent.push(msg);queueMicrotask(()=>{if(msg.command==='auth')socket.onmessage({data:JSON.stringify({message_id:msg.message_id,result:{authenticated:true}})});else{socket.onmessage({data:JSON.stringify({message_id:msg.message_id,partial:true,result:[{fixture:1}]})});socket.onmessage({data:JSON.stringify({message_id:msg.message_id,result:[{fixture:2}]})});}});},close(){this.onclose?.();}};
|
||||
queueMicrotask(()=>socket.onopen());return socket;
|
||||
}});
|
||||
try{
|
||||
const response=await bridge.fetch('https://ma.example.test/api',{method:'POST',redirect:'error',body:JSON.stringify({command:'music/playlists/library_items',args:{},message_id:'local'})});assert.deepEqual(await response.json(),[{fixture:1},{fixture:2}]);
|
||||
assert.equal(sent[0].command,'auth');assert.equal(sent[0].args.token,'GM-fixture-only');assert.ok(!JSON.stringify(sent[1]).includes('GM-fixture-only'));
|
||||
await assert.rejects(bridge.fetch('https://ma.example.test/api',{method:'POST',redirect:'error',body:JSON.stringify({command:'players/all'})}),{code:'denied'});
|
||||
}finally{bridge.close();}
|
||||
});
|
||||
|
||||
test('peer signaling bounds queued work and rejects expired invites before allocating a connection',async()=>{
|
||||
const handlers=new Map();let allocations=0;
|
||||
const socket={on:(name,fn)=>handlers.set(name,fn),off:name=>handlers.delete(name),emit(){}};
|
||||
const peer=new PeerAudio({socket,userId:'gm',isGM:()=>true,createPeer:()=>{allocations++;return {close(){}};}});
|
||||
try{
|
||||
peer.setSource({getAudioTracks:()=>[{}]});const invite=peer.invite('player');
|
||||
for(let i=0;i<1000;i++)handlers.get('module.adaptive-music')({peer:invite.peer,session:invite.session});
|
||||
await new Promise(resolve=>setTimeout(resolve,20));assert.equal(peer.diagnostics().rejectedSignals,1000);assert.equal(allocations,1);
|
||||
}finally{peer.close();}
|
||||
const listener=new PeerAudio({socket,userId:'player',isGM:()=>false,createPeer:()=>{allocations++;}});
|
||||
try{await assert.rejects(listener.listen({...newAudioInvite({session:'s',userId:'player'}),expires:0}),{code:'denied'});assert.equal(allocations,1);}finally{listener.close();}
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { request } from 'node:http';
|
||||
import { GatewayControl } from '../../gateway/control.mjs';
|
||||
import { SyntheticAudioGateway } from '../../gateway/synthetic-audio.mjs';
|
||||
import { startLoopbackAudio } from '../../gateway/loopback-audio.mjs';
|
||||
const origin='https://example.test';
|
||||
async function setup(){
|
||||
let now=0;const control=new GatewayControl({campaigns:{a:{},b:{}},origin,now:()=>now});
|
||||
const audio=new SyntheticAudioGateway({control});audio.provision({campaign:'a',session:'s'});
|
||||
const token=control.mint({campaign:'a',session:'s',role:'listener',ttlMs:1000});
|
||||
const transport=await startLoopbackAudio({audio,campaign:'a',session:'s'});
|
||||
return {control,audio,token,transport,set now(value){now=value;}};
|
||||
}
|
||||
function open(url,headers={}){
|
||||
return new Promise((resolve,reject)=>{const req=request(url,{headers},resolve);req.on('error',reject);req.setTimeout(2000,()=>req.destroy(new Error('fixture timeout')));req.end();});
|
||||
}
|
||||
test('loopback transport denies unauthenticated, cross-campaign, controller, query and wrong-origin requests',async()=>{
|
||||
const f=await setup();
|
||||
try {
|
||||
for(const [url,headers] of [[f.transport.url,{}],[f.transport.url,{origin,Authorization:'Bearer forged'}],
|
||||
[f.transport.url,{origin:'https://evil.test',Authorization:`Bearer ${f.token}`}],
|
||||
[f.transport.url+'?token=forbidden',{origin,Authorization:`Bearer ${f.token}`}],
|
||||
[f.transport.url,{origin,Authorization:`Bearer ${f.control.mint({campaign:'b',session:'s',role:'listener'})}`}],
|
||||
[f.transport.url,{origin,Authorization:`Bearer ${f.control.mint({campaign:'a',session:'s',role:'controller'})}`}],
|
||||
[f.transport.url,{origin,host:'evil.test',Authorization:`Bearer ${f.token}`}]] ) {
|
||||
const response=await open(url,headers);assert.equal(response.statusCode,403);let size=0;
|
||||
for await(const chunk of response)size+=chunk.length;assert.equal(size,0);
|
||||
}
|
||||
} finally {await f.transport.close();}
|
||||
});
|
||||
test('loopback streams synthetic PCM bytes and closes an active stream on revocation',async()=>{
|
||||
const f=await setup();
|
||||
try {
|
||||
const response=await open(f.transport.url,{origin,Authorization:`Bearer ${f.token}`});
|
||||
assert.equal(response.statusCode,200);assert.equal(response.headers['cache-control'],'no-store');
|
||||
const samples=new Int16Array(960);for(let i=0;i<480;i++)samples[i*2]=samples[i*2+1]=Math.round(Math.sin(i*2*Math.PI*440/24000)*1000);
|
||||
const pcm=new Uint8Array(samples.buffer);
|
||||
const received=new Promise((resolve,reject)=>{response.once('data',resolve);response.once('error',reject);});
|
||||
f.audio.publish({campaign:'a',session:'s',generation:1,pcm});
|
||||
assert.deepEqual(new Uint8Array(await received),pcm);
|
||||
const closed=new Promise(resolve=>response.once('close',resolve));
|
||||
// An aborted HTTP stream emits an expected error alongside close.
|
||||
response.on('error',()=>{});f.control.revoke(f.token);await closed;
|
||||
assert.equal(response.destroyed,true);
|
||||
} finally {await f.transport.close();}
|
||||
});
|
||||
test('loopback closes idle synthetic stream when its listener capability expires',async()=>{
|
||||
const f=await setup();
|
||||
try {
|
||||
const response=await open(f.transport.url,{origin,Authorization:`Bearer ${f.token}`});
|
||||
response.on('error',()=>{});const closed=new Promise(resolve=>response.once('close',resolve));
|
||||
f.now=1001;await closed;assert.equal(response.destroyed,true);
|
||||
} finally {await f.transport.close();}
|
||||
});
|
||||
@@ -0,0 +1,101 @@
|
||||
import {test} from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {MAPlaybackProvider} from '../../gateway/ma-provider.mjs';
|
||||
import {MAReadClient} from '../../gateway/ma-client.mjs';
|
||||
const key=Buffer.alloc(32,7);
|
||||
const track=(id)=>({queue_item_id:id,duration:120,media_item:{media_type:'track',provider_mappings:[{provider_instance:'approved',item_id:id,available:true}]}});
|
||||
function fixture(){
|
||||
let items=[track('a'),track('a'),track('b')],state={items:3,state:'paused',repeat_mode:'all',shuffle_enabled:false,current_index:1,elapsed_time:17,elapsed_time_last_updated:Date.now()/1000,playback_speed:1};
|
||||
const writes=[];let allowed=true;
|
||||
const client={verifyTarget:async()=>{},queueState:async()=>({...state,current_item:items[state.current_index]}),queueItems:async offset=>items.slice(offset,offset+100),mediaURI:i=>`approved://track/${i.media_item.provider_mappings[0].item_id}`,resolveCatalog:ref=> `approved://playlist/${ref.id}`,
|
||||
async mutate(action,args,ctx){ctx.check();writes.push({action,args});if(action==='stop')state.state='idle';if(action==='clear'){items=[];state.items=0;state.current_index=null;state.elapsed_time=0;}if(action==='play_media'){items=args.media.flatMap(uri=>uri.includes('://playlist/')?[track(uri.split('/').at(-1)+'1'),track(uri.split('/').at(-1)+'2')]:[track(uri.split('/').at(-1))]);state.items=items.length;state.current_index=0;state.elapsed_time=0;if(args.option==='replace')state.state='playing';}if(action==='play_index'){state.current_index=args.index;state.elapsed_time=args.seek_position;state.state='playing';}if(action==='pause')state.state='paused';}};
|
||||
const provider=new MAPlaybackProvider({client,campaign:'c',session:'s',fence:1,authority:()=>{if(!allowed)throw Object.assign(Error(),{code:'stale'});},snapshotKey:key});
|
||||
const ctx={campaign:'c',session:'s',generation:1,check(){}};
|
||||
return {provider,client,ctx,writes,state,set allowed(v){allowed=v;}};
|
||||
}
|
||||
test('MA snapshots ordered duplicate occurrences, pause and seek then reconstructs exact unshuffled order',async()=>{
|
||||
const f=fixture(),snapshot=await f.provider.snapshot(f.ctx);assert.equal(snapshot.value.items.length,3);assert.equal(snapshot.value.index,1);assert.equal(snapshot.value.position,17);
|
||||
await f.provider.restore(snapshot,{...f.ctx,generation:2});assert.deepEqual(f.writes.map(w=>w.action),['stop','clear','repeat','play_media','play_index','pause']);assert.equal(f.state.current_index,1);assert.equal(f.state.elapsed_time,17);assert.equal(f.state.state,'paused');
|
||||
});
|
||||
test('tampered, foreign/future snapshots and stale authority deny before MA mutations',async()=>{
|
||||
const f=fixture(),snapshot=await f.provider.snapshot(f.ctx);const bad=structuredClone(snapshot);bad.value.position=0;
|
||||
await assert.rejects(f.provider.restore(bad,f.ctx),{code:'stale'});
|
||||
await assert.rejects(f.provider.restore(snapshot,{...f.ctx,campaign:'other'}),{code:'stale'});
|
||||
f.allowed=false;await assert.rejects(f.provider.restore(snapshot,{...f.ctx,generation:2}),{code:'stale'});assert.equal(f.writes.length,0);
|
||||
});
|
||||
test('shuffled snapshot fails before interruption rather than promising exact restore',async()=>{
|
||||
const f=fixture();f.state.shuffle_enabled=true;await assert.rejects(f.provider.snapshot(f.ctx),{code:'unsupported'});assert.equal(f.writes.length,0);
|
||||
});
|
||||
test('prepared media cannot be forged and stale generations cannot issue controls',async()=>{
|
||||
const f=fixture();await assert.rejects(f.provider.apply({uri:'approved://playlist/forged'},f.ctx),{code:'denied'});
|
||||
await f.provider.control('pause',null,{...f.ctx,generation:4});await assert.rejects(f.provider.control('resume',null,{...f.ctx,generation:3}),{code:'stale'});
|
||||
});
|
||||
function wireFixture(){
|
||||
const commands=[];let grouped=false,expired=false;
|
||||
const player={player_id:'dev',name:'Adaptive Music DEV',provider:'sendspin-test',enabled:true,available:true,group_members:[],group_childs:[],static_group_members:[]};
|
||||
const client=new MAReadClient({baseUrl:'http://localhost',token:'fixture',target:'dev',approvedProviders:['approved'],expectedName:player.name,expectedProvider:player.provider,
|
||||
fetchImpl:async(url,options)=>{const body=JSON.parse(options.body);commands.push(body);if(body.command==='players/get')return Response.json({...player,active_group:grouped?'household':null});if(['player_queues/get','player_queues/get_active_queue'].includes(body.command)){expired=true;return Response.json({queue_id:'dev',active:true,available:true,is_dynamic:false,autoplay_enabled:false,dont_stop_the_music_enabled:false,overlay_enabled:false,playback_speed:1});}return new Response(null,{status:200});}});
|
||||
return {client,commands,set grouped(v){grouped=v;},get expired(){return expired;}};
|
||||
}
|
||||
test('every wire mutation revalidates exact identity/topology and uses fixed dedicated queue',async()=>{
|
||||
const f=wireFixture(),ctx={check(){}};await f.client.mutate('pause',{},ctx);await f.client.mutate('resume',{},ctx);
|
||||
assert.equal(f.commands.filter(c=>c.command==='players/get').length,2);
|
||||
assert.ok(f.commands.filter(c=>c.command.startsWith('player_queues/')).every(c=>c.args.queue_id==='dev'||c.command==='player_queues/get_active_queue'&&c.args.player_id==='dev'));
|
||||
f.grouped=true;await assert.rejects(f.client.mutate('stop',{},ctx),{code:'denied'});assert.equal(f.commands.filter(c=>c.command==='player_queues/stop').length,0);
|
||||
});
|
||||
test('queue injection, transfer, arbitrary media URL and authority loss deny without writes',async()=>{
|
||||
const f=wireFixture();for(const [action,args] of [['transfer',{}],['pause',{queue_id:'household'}],['play_media',{media:['approved://track/unregistered'],option:'replace',shuffle:false}],['play_media',{media:['https://example.test/secret'],option:'replace',shuffle:false}]])await assert.rejects(f.client.mutate(action,args,{check(){}}),{code:'denied'});
|
||||
await assert.rejects(f.client.mutate('pause',{}, {check(){if(f.expired)throw Object.assign(Error(),{code:'stale'});}}),{code:'stale'});
|
||||
assert.ok(!f.commands.some(c=>c.command==='player_queues/pause'));
|
||||
});
|
||||
test('catalog IDs survive independent adapter construction and differ across campaigns',async()=>{
|
||||
const make=campaign=>new MAReadClient({baseUrl:'http://localhost',token:'fixture',target:'dev',approvedProviders:['approved'],catalogKey:key,campaign,
|
||||
fetchImpl:async(url,opts)=>Response.json(JSON.parse(opts.body).command.includes('/radios/')?[]:[{name:'music',media_type:'playlist',is_playable:true,provider_mappings:[{provider_instance:'approved',item_id:'p',available:true}]}])});
|
||||
const a=await make('a').catalog(),again=await make('a').catalog(),b=await make('b').catalog();assert.equal(a[0].id,again[0].id);assert.notEqual(a[0].id,b[0].id);
|
||||
});
|
||||
test('same-generation duplicate controls and restores issue no duplicate mutations',async()=>{
|
||||
const f=fixture(),snapshot=await f.provider.snapshot(f.ctx);
|
||||
await Promise.all([f.provider.control('pause',null,f.ctx),f.provider.control('pause',null,f.ctx)]);assert.equal(f.writes.length,1);
|
||||
const context={...f.ctx,generation:2};await Promise.all([f.provider.restore(snapshot,context),f.provider.restore(snapshot,context)]);assert.equal(f.writes.length,7);
|
||||
});
|
||||
test('MA provider with mock MA client composes with controller for nested contexts and rapid supersession',async()=>{
|
||||
const {MusicController}=await import('../../src/core/controller.mjs');
|
||||
const f=fixture();
|
||||
const controller=new MusicController({campaign:'c',session:'s',providers:{ma:f.provider},authority:()=>true});
|
||||
const ref=id=>({provider:'ma',id});
|
||||
const base={scene:{id:'scene',playlist:ref('ambient')},combats:[]};
|
||||
const combat={id:'combat',sceneId:'scene',active:true,started:true,playlist:ref('combat'),bosses:[]};
|
||||
await controller.update(base);await controller.update({...base,combats:[combat]});
|
||||
await controller.update({...base,combats:[{...combat,bosses:[{id:'boss',active:true,priority:1,playlist:ref('boss')}]}]});
|
||||
await controller.update({...base,combats:[combat],overrides:[{id:'manual',playlist:ref('manual')}]});
|
||||
await controller.update({...base,combats:[combat]});await controller.update(base);
|
||||
const before=f.writes.length;const results=await Promise.allSettled([controller.update({...base,combats:[combat]}),controller.update({...base,overrides:[{id:'rapid',playlist:ref('manual')}]}),controller.update(base)]);
|
||||
assert.equal(f.writes.length,before);assert.equal(results.at(-1).status,'fulfilled');assert.equal(controller.current.playlist.id,'ambient');
|
||||
});
|
||||
test('ambiguous wire mutation failure latches closed instead of retrying or restoring blindly',async()=>{
|
||||
let effects=0;const client=new MAReadClient({baseUrl:'http://localhost',token:'fixture',target:'dev',approvedProviders:['approved'],expectedName:'Adaptive Music DEV',expectedProvider:'sendspin-test',fetchImpl:async(url,options)=>{
|
||||
const {command}=JSON.parse(options.body);
|
||||
if(command==='players/get')return Response.json({player_id:'dev',name:'Adaptive Music DEV',provider:'sendspin-test',enabled:true,available:true,group_members:[],group_childs:[],static_group_members:[]});
|
||||
if(command==='player_queues/get'||command==='player_queues/get_active_queue')return Response.json({queue_id:'dev',active:true,available:true,is_dynamic:false,autoplay_enabled:false,dont_stop_the_music_enabled:false,overlay_enabled:false,playback_speed:1});
|
||||
effects++;throw Error('lost response');
|
||||
}});
|
||||
await assert.rejects(client.mutate('pause',{}, {check(){}}),{code:'uncertain'});
|
||||
await assert.rejects(client.mutate('pause',{}, {check(){}}),{code:'uncertain'});assert.equal(effects,1);
|
||||
});
|
||||
test('listener cannot obtain a playback fence guard or renew a controller lease',async()=>{
|
||||
const {GatewayControl}=await import('../../gateway/control.mjs');
|
||||
const g=new GatewayControl({campaigns:{c:{}},origin:'https://example.test'});
|
||||
const request={campaign:'c',session:'s',origin:'https://example.test',token:g.mint({campaign:'c',session:'s',role:'listener'}),fence:1};
|
||||
assert.throws(()=>g.fenceGuard(request)(1),{code:'denied'});assert.throws(()=>g.renew(request),{code:'denied'});
|
||||
});
|
||||
test('playlist preparation expands approved ordered tracks before any playback mutation',async()=>{
|
||||
const commands=[];const client=new MAReadClient({baseUrl:'http://localhost',token:'fixture',target:'dev',approvedProviders:['approved'],fetchImpl:async(url,options)=>{
|
||||
const {command}=JSON.parse(options.body);commands.push(command);
|
||||
if(command==='music/playlists/library_items')return Response.json([{name:'Fixture catalog',is_playable:true,is_dynamic:false,media_type:'playlist',provider_mappings:[{provider_instance:'approved',item_id:'p',available:true}]}]);
|
||||
if(command==='music/radios/library_items')return Response.json([]);
|
||||
if(command==='music/playlists/get')return Response.json({is_dynamic:false});
|
||||
if(command==='music/playlists/playlist_tracks')return Response.json([track('a').media_item,track('a').media_item,track('b').media_item]);
|
||||
throw Error('unexpected command');
|
||||
}});
|
||||
const catalog=await client.catalog();assert.deepEqual(await client.prepareMedia(catalog[0]),['approved://track/a','approved://track/a','approved://track/b']);assert.ok(!commands.some(c=>c.startsWith('player_queues/')));
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
import {test} from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
test('installable development entry defaults automation off and imports no gateway',async()=>{
|
||||
const once=new Map(),settings=new Map(),module={};let registrations=0;
|
||||
globalThis.Hooks={once(e,fn){once.set(e,fn);},on(){registrations++;},off(){}};
|
||||
globalThis.game={user:{isGM:true},playlists:[],modules:{get:()=>module},settings:{register(ns,key,definition){settings.set(key,definition);},get(ns,key){return settings.get(key).default;}}};
|
||||
globalThis.ui={notifications:{warn(){}}};
|
||||
try{
|
||||
await import('../../src/foundry/module.mjs');once.get('init')();once.get('ready')();
|
||||
assert.equal(settings.get('enabled').default,false);assert.equal(settings.get('ownedPlaylistIds').default,'');
|
||||
assert.equal(registrations,2);assert.equal(typeof module.api.mountConfiguration,'function');assert.throws(()=>module.api.setOverrides([]));module.api.dispose();
|
||||
}finally{delete globalThis.game;delete globalThis.Hooks;delete globalThis.ui;}
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { NativeProvider } from '../../src/providers/native/provider.mjs';
|
||||
import { primaryGM, startNativeRuntime } from '../../src/foundry/runtime.mjs';
|
||||
const collection = items => { const m=new Map(items.map(x=>[x.id,x])); m[Symbol.iterator]=function*(){yield* this.values();}; return m; };
|
||||
function fixture() {
|
||||
const calls=[];
|
||||
const p={id:'owned',mode:0,sounds:collection([
|
||||
{id:'a',sort:0,playing:true,pausedTime:null,repeat:true,volume:0.4,sound:{currentTime:42,duration:100}},
|
||||
{id:'b',sort:1,playing:false,pausedTime:12,repeat:false,volume:0.7,sound:{duration:100}}
|
||||
]), async updateEmbeddedDocuments(type,updates){calls.push({type,updates}); for(const u of updates)Object.assign(this.sounds.get(u._id),u);} };
|
||||
const other={id:'household',sounds:collection([]),async updateEmbeddedDocuments(){assert.fail('unowned mutation');}};
|
||||
const provider=new NativeProvider({playlists:collection([p,other]),ownedPlaylistIds:['owned'],campaign:'c',session:'s'});
|
||||
const ctx={campaign:'c',session:'s',generation:4,check(){}};
|
||||
return {provider,p,ctx,calls};
|
||||
}
|
||||
test('native captures actual offset and paused state, stops per sound, restores repeat/volume',async()=>{
|
||||
const {provider,p,ctx,calls}=fixture(); const snap=await provider.snapshot(ctx);
|
||||
assert.equal(snap.playlists[0].sounds[0].pausedTime,42);
|
||||
await provider.stopOwned(ctx); assert.equal(calls[0].type,'PlaylistSound'); assert.equal(calls[0].updates.length,1);
|
||||
await provider.restore(snap,{...ctx,generation:5});
|
||||
assert.equal(p.sounds.get('a').pausedTime,42); assert.equal(p.sounds.get('a').repeat,true);
|
||||
assert.equal(p.sounds.get('b').playing,false); assert.equal(p.sounds.get('b').pausedTime,12);
|
||||
});
|
||||
test('native resolves sequential playlist and touches only owned documents',async()=>{
|
||||
const {provider,ctx,calls}=fixture(); const prepared=await provider.resolve({id:'owned'},ctx);
|
||||
await provider.apply(prepared,ctx); assert.equal(calls[0].updates[0]._id,'a');
|
||||
await assert.rejects(provider.resolve({id:'household'},ctx),{code:'denied'});
|
||||
await assert.rejects(provider.resolve({id:'owned'},{...ctx,campaign:'other'}),{code:'denied'});
|
||||
});
|
||||
test('native rejects unsupported shuffle and empty playlist',async()=>{
|
||||
const {provider,p,ctx}=fixture(); p.mode=1;
|
||||
await assert.rejects(provider.resolve({id:p.id},ctx),{code:'unsupported'});
|
||||
p.mode=0;p.sounds.clear();await assert.rejects(provider.resolve({id:p.id},ctx),{code:'unavailable'});
|
||||
});
|
||||
test('native rejects expired tracks, changed playlist membership and foreign/future snapshots before mutation',async()=>{
|
||||
const {provider,p,ctx,calls}=fixture();const snap=await provider.snapshot(ctx);
|
||||
for(const patch of [{campaign:'other'},{session:'other'},{generation:100}])await assert.rejects(provider.restore({...snap,...patch},ctx),{code:'stale'});
|
||||
p.sounds.delete('b'); await assert.rejects(provider.restore(snap,ctx),{code:'expired-media'});assert.equal(calls.length,0);
|
||||
});
|
||||
test('native reports nonseekable restoration and clamps near-end seek',async()=>{
|
||||
const {provider,p,ctx,calls}=fixture();const snap=await provider.snapshot(ctx);
|
||||
p.sounds.get('a').sound.duration=Infinity;
|
||||
await assert.rejects(provider.restore(snap,ctx),{code:'unsupported'});assert.equal(calls.length,0);
|
||||
p.sounds.get('a').sound.duration=40;await provider.restore(snap,ctx);assert.equal(p.sounds.get('a').pausedTime,39.99);
|
||||
});
|
||||
test('scene-linked playlist conflict and lost authority fail before mutation',async()=>{
|
||||
const {provider,ctx,calls}=fixture();provider.sceneConflict=()=>true;
|
||||
await assert.rejects(provider.resolve({id:'owned'},ctx),{code:'scene-conflict'});
|
||||
provider.sceneConflict=()=>false;
|
||||
await assert.rejects(provider.stopOwned({...ctx,check(){throw new Error('lost');}}));assert.equal(calls.length,0);
|
||||
});
|
||||
test('GM election deterministic and no GM means none',()=>{
|
||||
assert.equal(primaryGM([{id:'z',active:true,isGM:true},{id:'a',active:true,isGM:true},{id:'0',active:false,isGM:true}]),'a');
|
||||
assert.equal(primaryGM([]),undefined);
|
||||
});
|
||||
test('Foundry bootstrap registers local settings/hooks and disposes without ambient or actor access',async()=>{
|
||||
const callbacks=new Map();let index=0,registered=0;
|
||||
const Hooks={on(e,cb){callbacks.set(++index,cb);return index;},off(e,id){callbacks.delete(id);}};
|
||||
const game={ready:true,user:{id:'gm'},users:[{id:'gm',isGM:true,active:true}],playlists:collection([]),scenes:[],combats:[],
|
||||
settings:{register(){registered++;},get(){return null;}}};
|
||||
const runtime=startNativeRuntime({game,Hooks,campaign:'c',session:'s',ownedPlaylistIds:[]});
|
||||
await runtime.refresh();assert.equal(registered,1);assert.ok(callbacks.size>0);runtime.dispose();assert.equal(callbacks.size,0);
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
import {test} from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {pcmFixtureFrames} from '../../gateway/pcm-fixture.mjs';
|
||||
import {SyntheticAudioGateway} from '../../gateway/synthetic-audio.mjs';
|
||||
import {GatewayControl} from '../../gateway/control.mjs';
|
||||
function wav(){const data=Buffer.alloc(44+1920*2);data.write('RIFF');data.writeUInt32LE(data.length-8,4);data.write('WAVEfmt ',8);data.writeUInt32LE(16,16);data.writeUInt16LE(1,20);data.writeUInt16LE(2,22);data.writeUInt32LE(24000,24);data.writeUInt32LE(96000,28);data.writeUInt16LE(4,32);data.writeUInt16LE(16,34);data.write('data',36);data.writeUInt32LE(3840,40);data.fill(23,44);return data;}
|
||||
test('synthetic WAV termination emits fixed PCM frames through campaign listener authorization',()=>{
|
||||
const control=new GatewayControl({campaigns:{a:{}},origin:'https://example.test'});
|
||||
const audio=new SyntheticAudioGateway({control});audio.provision({campaign:'a',session:'s'});
|
||||
const listener=audio.connect({campaign:'a',session:'s',origin:'https://example.test',token:control.mint({campaign:'a',session:'s',role:'listener'})});
|
||||
let generation=0;for(const pcm of pcmFixtureFrames(wav())){audio.publish({campaign:'a',session:'s',generation:++generation,pcm});assert.equal(listener.next().pcm[0],23);}assert.equal(generation,2);listener.close();
|
||||
});
|
||||
test('malformed, truncated and incompatible WAV formats fail closed before PCM publication',()=>{
|
||||
const original=wav();const badRate=wav();badRate.writeUInt32LE(48000,24);
|
||||
const badCodec=wav();badCodec.writeUInt16LE(3,20);
|
||||
for(const input of [original.subarray(0,20),badRate,badCodec,Buffer.alloc(9000001)])assert.throws(()=>[...pcmFixtureFrames(input)],{code:'unsupported'});
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtemp, writeFile, chmod, rm, symlink } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { loadMAToken } from '../../gateway/private-config.mjs';
|
||||
test('credential loader rejects permissive modes, symlinks and malformed secrets',async()=>{
|
||||
const dir=await mkdtemp(join(tmpdir(),'adaptive-music-'));
|
||||
try {
|
||||
await chmod(dir,0o700);const path=join(dir,'ma-token');await writeFile(path,'fixture-only\n',{mode:0o600});
|
||||
assert.equal(await loadMAToken(dir),'fixture-only');
|
||||
await chmod(path,0o644);await assert.rejects(loadMAToken(dir),{code:'denied'});await chmod(path,0o600);
|
||||
await chmod(dir,0o755);await assert.rejects(loadMAToken(dir),{code:'denied'});await chmod(dir,0o700);
|
||||
await writeFile(path,'line1\nline2');await assert.rejects(loadMAToken(dir),{code:'denied'});
|
||||
await rm(path);await symlink('missing',path);await assert.rejects(loadMAToken(dir),{code:'denied'});
|
||||
} finally {await rm(dir,{recursive:true,force:true});}
|
||||
});
|
||||
test('private catalog identity key persists and unsafe key permissions fail',async()=>{
|
||||
const {loadCatalogKey}=await import('../../gateway/private-config.mjs');const dir=await mkdtemp(join(tmpdir(),'adaptive-music-key-'));
|
||||
try{await chmod(dir,0o700);await writeFile(join(dir,'ma-token'),'fixture',{mode:0o600});
|
||||
const first=await loadCatalogKey(dir),second=await loadCatalogKey(dir);assert.equal(first.length,32);assert.deepEqual(first,second);
|
||||
await chmod(join(dir,'catalog-key'),0o644);await assert.rejects(loadCatalogKey(dir),{code:'denied'});
|
||||
}finally{await rm(dir,{recursive:true,force:true});}
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import {test} from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {buildMusicState,referenceKey} from '../../src/core/scene-music.mjs';
|
||||
import {candidates} from '../../src/core/controller.mjs';
|
||||
import {saveMusicAssignments} from '../../src/foundry/music-editor.mjs';
|
||||
const native=id=>({provider:'native',id}),ma=id=>({provider:'ma',id});
|
||||
const choices=[{...native('fallback'),name:'Owned'},{...ma('ambient'),name:'Ambient'},{...ma('combat'),name:'Combat'},{...ma('boss'),name:'Boss'}];
|
||||
test('scene assignments persist independently and world defaults/boss priority resolve without actor schemas',async()=>{
|
||||
let flag={custom:'keep'},world={};const game={user:{isGM:true},settings:{get:()=>world,set:async(ns,k,v)=>{world=v;}}};
|
||||
const document={getFlag:()=>flag,setFlag:async(ns,k,v)=>{flag=v;}};
|
||||
await saveMusicAssignments({document,game,choices,values:{ambient:referenceKey(ma('ambient')),combat:referenceKey(ma('combat')),boss:referenceKey(ma('boss')),fallback:referenceKey(native('fallback'))}});
|
||||
assert.deepEqual(flag,{custom:'keep',ambient:ma('ambient'),combat:ma('combat'),boss:ma('boss'),fallback:native('fallback')});
|
||||
await saveMusicAssignments({game,choices,defaults:true,values:{combat:referenceKey(ma('combat'))}});assert.deepEqual(world.combat,ma('combat'));
|
||||
const state=buildMusicState({scene:{id:'s',music:flag},combats:[{id:'c',sceneId:'s',active:true,started:true,bosses:[{id:'b',active:true,priority:10}]}]});
|
||||
assert.equal(candidates(state)[0].playlist.id,'boss');assert.equal(candidates({...state,combats:state.combats.map(c=>({...c,bosses:[]}))})[0].playlist.id,'combat');assert.equal(candidates({...state,combats:[]})[0].playlist.id,'ambient');
|
||||
});
|
||||
test('native fallback is explicit, manual silence wins and legacy ambient does not resurrect after clearing',()=>{
|
||||
const state=buildMusicState({scene:{id:'s',music:{ambient:ma('offline'),combat:ma('blocked'),fallback:native('fallback')}},combats:[{id:'c',sceneId:'s',active:true,started:true}],choose:(ref,fallback)=>ref.provider==='ma'?fallback:ref,overrides:[{id:'silence',playlist:null}]});
|
||||
assert.equal(candidates(state)[0].playlist,null);assert.equal(state.scene.playlist.id,'fallback');assert.equal(state.combats[0].playlist.id,'fallback');
|
||||
assert.equal(buildMusicState({scene:{id:'s',music:{ambient:null,playlist:native('old')}}}).scene.playlist,null);
|
||||
});
|
||||
test('unavailable saved MA selections are preserved but new forged IDs/non-native fallback and role loss deny',async()=>{
|
||||
let flag={ambient:ma('old')};const document={getFlag:()=>flag,setFlag:async(ns,k,v)=>{flag=v;}};const game={user:{isGM:true}};
|
||||
await saveMusicAssignments({document,game,choices:[],values:{ambient:referenceKey(ma('old'))}});assert.equal(flag.ambient.id,'old');
|
||||
for(const values of [{ambient:referenceKey(ma('forged'))},{fallback:referenceKey(ma('ambient'))}])await assert.rejects(saveMusicAssignments({document,game,choices,values}),{code:'denied'});
|
||||
game.user.isGM=false;await assert.rejects(saveMusicAssignments({document,game,choices,values:{ambient:''}}),{code:'denied'});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import {test} from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {createSetupClass} from '../../src/foundry/setup.mjs';
|
||||
import {ListenerAudio} from '../../src/foundry/listener-audio.mjs';
|
||||
class Element{
|
||||
constructor(tag,dom){this.tag=tag;this.ownerDocument=dom;this.children=[];this.listeners={};this.dataset={};this.value='';}
|
||||
append(...children){this.children.push(...children);if(this.tag==='select'&&!this.value&&children[0]?.tag==='option')this.value=children[0].value;}
|
||||
replaceChildren(...children){this.children=[];this.append(...children);}
|
||||
setAttribute(){}
|
||||
addEventListener(name,fn){this.listeners[name]=fn;}
|
||||
}
|
||||
const descendants=node=>[node,...node.children.flatMap(descendants)];
|
||||
const collection=items=>{const map=new Map(items.map(i=>[i.id,i]));map[Symbol.iterator]=function*(){yield*map.values();};return map;};
|
||||
test('GM setup connects catalog into independent scene editors and never persists its connection code',async()=>{
|
||||
const dom={createElement:tag=>new Element(tag,dom)};globalThis.document=dom;
|
||||
let flag={},catalog=[];const settings={ownedPlaylistIds:'owned',musicDefaults:{},enabled:false},writes=[];
|
||||
const scene={id:'scene',name:'Scene',active:true,getFlag:()=>flag,setFlag:async(ns,k,value)=>{flag=value;}};
|
||||
const game={user:{isGM:true},playlists:collection([{id:'owned',name:'Owned'}]),scenes:collection([scene]),combats:[],settings:{get:(ns,k)=>settings[k],set:async(ns,k,value)=>{settings[k]=value;writes.push({k,value});}}};
|
||||
const gateway={status:null,async connect(code){assert.equal(code,'capability-fixture');catalog=[{provider:'ma',id:'opaque-ma',name:'MA fixture',kind:'playlist'}];this.status={target:'verified',playbackEnabled:false,audioSource:'none'};},refresh:async()=>{},disconnect:async()=>{}};
|
||||
try{
|
||||
const Setup=createSetupClass({game,gateway,audio:{},getChoices:async()=>[{provider:'native',id:'owned',name:'Owned'},...catalog],start(){},stop(){},setOverrides(){},onError:assert.fail,Base:class{}});
|
||||
const root=await new Setup()._renderHTML();const code=descendants(root).find(e=>e.tag==='input'&&e.type==='password');code.value='capability-fixture';
|
||||
await descendants(root).find(e=>e.tag==='button'&&e.textContent==='Connect and load MA catalog').listeners.click();assert.equal(code.value,'');
|
||||
const panel=descendants(root).find(e=>e.tag==='fieldset'&&e.children.some(c=>c.tag==='legend'&&c.textContent==='Scene music'));
|
||||
const selects=descendants(panel).filter(e=>e.tag==='select');assert.equal(selects.length,4);assert.ok(selects[0].children.some(o=>o.textContent.includes('MA fixture')));
|
||||
selects[0].value='["ma","opaque-ma"]';selects[1].value='["native","owned"]';selects[3].value='["native","owned"]';
|
||||
await descendants(panel).find(e=>e.tag==='button').listeners.click();assert.deepEqual(flag.ambient,{provider:'ma',id:'opaque-ma'});assert.deepEqual(flag.combat,{provider:'native',id:'owned'});assert.ok(!JSON.stringify({flag,writes}).includes('capability-fixture'));
|
||||
}finally{delete globalThis.document;}
|
||||
});
|
||||
test('browser PCM sink resumes from gesture, decodes stereo frames and closes its context on stream end',async()=>{
|
||||
const calls=[],buffers=[];const context={currentTime:0,destination:{},resume(){calls.push('resume');return Promise.resolve();},close(){calls.push('close');return Promise.resolve();},
|
||||
createBuffer(channels,length,rate){assert.equal(rate,24000);const channelsData=[new Float32Array(length),new Float32Array(length)];buffers.push(channelsData);return {getChannelData:i=>channelsData[i]};},
|
||||
createBufferSource(){return {connect(){},start(){calls.push('start');},stop(){calls.push('stop');}};}};
|
||||
const pcm=new Uint8Array(1920),view=new DataView(pcm.buffer);for(let i=0;i<960;i++)view.setInt16(i*2,16384,true);
|
||||
const audio=new ListenerAudio({createContext:()=>context,fetchImpl:async()=>{calls.push('fetch');return new Response(pcm,{headers:{'X-Audio-Format':'pcm16le;rate=24000;channels=2'}});}});
|
||||
const pending=audio.start({url:'/audio',options:{}});assert.equal(calls[0],'resume');await pending;assert.equal(buffers[0][0][0],0.5);assert.equal(buffers[0][1][0],0.5);assert.ok(calls.includes('close'));assert.ok(calls.indexOf('resume')<calls.indexOf('fetch'));
|
||||
});
|
||||
Reference in new issue
Block a user