Release v0.6.0 - Music Assistant wizard and automatic listener connections
Validate and generate manual release / package (push) Waiting to run

This commit is contained in:
Jason committed 2026-12-03 20:11:10 -05:00
1 parent 5319177c58
commit eb9536f903
26 files changed
+1553 -764

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
<!doctype html><meta charset="utf-8"><title>Adaptive Music setup fixture</title>
<link rel="stylesheet" href="/styles/adaptive-music.css">
<style>body{font:16px system-ui;background:#222;color:#eee;margin:2rem auto;max-width:640px}input,select,button{font:inherit;padding:.4rem;box-sizing:border-box}button{cursor:pointer}a{color:#9bd}</style>
<main id="app"></main>
<script type="module">
import {createSetupClass,createListenerClass} from '/src/foundry/setup.mjs';
let flag={},catalog=[];const settings={ownedPlaylistIds:'native',musicDefaults:{},enabled:false,advancedDevelopment:false};
const collection=items=>{const map=new Map(items.map(x=>[x.id,x]));map[Symbol.iterator]=function*(){yield*map.values()};return map};
const scene={id:'scene',name:'Moonlit forest',active:true,getFlag:()=>flag,setFlag:async(ns,k,v)=>{flag=v;window.saved=flag}};
const game={user:{isGM:true},settings:{get:(ns,k)=>settings[k],set:async(ns,k,v)=>{settings[k]=v}},playlists:collection([{id:'native',name:'Foundry fallback'}]),scenes:collection([scene]),combats:[]};
const connection={status:{state:'disconnected',catalog:0,audioContext:'closed'},test:async p=>{if(p.token!=='fixture-token')throw {code:'denied'};catalog=[{provider:'ma',id:'ambient',kind:'playlist',name:'Forest at night'},{provider:'ma',id:'combat',kind:'playlist',name:'Battle drums'}];connection.status={state:'catalog-ready',catalog:2,audioContext:'closed'};return {target:'dedicated',targetName:'Adaptive Music DEV'}},connect:async()=>{connection.status={state:'connected',catalog:2,audioContext:'running',catalogPlayback:true}},refresh:async()=>{},resume:async()=>{},disconnect:async()=>{}};
const Setup=createSetupClass({game,connection,getChoices:async()=>[{provider:'native',id:'native',name:'Foundry fallback'},...catalog],start(){},stop(){},setOverrides(){},onError(){},Base:class{}});
document.querySelector('#app').append(await new Setup()._renderHTML());window.ready=true;
window.listener=async()=>{const Listener=createListenerClass({game,audio:{stop(){}},resumeListener:()=>{window.activated=true},Base:class{}});document.querySelector('#app').replaceChildren(await new Listener()._renderHTML())};
</script>
+37
View File
@@ -0,0 +1,37 @@
import {test} from 'node:test';
import assert from 'node:assert/strict';
import {AutoListeners} from '../../src/audio/auto-listeners.mjs';
import {newAudioInvite} from '../../src/audio/signal-codec.mjs';
const user=(id,isGM=false)=>({id,isGM,active:true,async setFlag(ns,k,v){this.value=structuredClone(v);},getFlag(){return this.value;}});
async function fixture(){
const gm=user('gm',true),player=user('player'),other=user('other'),users=[gm,player,other],packets=[],received=[];
const socket={on(){},off(){},emit(channel,packet){packets.push(packet);}};
const host=new AutoListeners({game:{world:{id:'world'},user:gm,users,socket},isGM:()=>gm.active,onInvite:assert.fail});
const listener=new AutoListeners({game:{world:{id:'world'},user:player,users,socket},isGM:()=>false,onInvite:invite=>received.push(invite)});
await host.start();await listener.start();return {gm,player,other,users,host,listener,packets,received,close(){host.close();listener.close();}};
}
test('automatic invitations use document-bound ephemeral keys and never broadcast the capability',async()=>{
const f=await fixture();try{
const invite=newAudioInvite({session:'session',userId:'player'});await f.host.send(f.player,invite);
assert.ok(!JSON.stringify(f.packets).includes(invite.secret));assert.deepEqual(Object.keys(f.gm.value).sort(),['epoch','key','v']);
await f.listener.receive(f.packets[0]);assert.deepEqual(f.received,[invite]);await assert.rejects(f.listener.receive(f.packets[0]),{code:'denied'});
}finally{f.close();}
});
test('forged GM claims, recipient changes, tampering and rotated document keys fail closed',async()=>{
const f=await fixture();try{
await f.host.send(f.player,newAudioInvite({session:'session',userId:'player'}));const packet=f.packets[0];
await assert.rejects(f.listener.receive({...packet,from:'other'}),{code:'denied'});
await assert.rejects(f.listener.receive({...packet,cipher:packet.cipher.slice(0,-4)+'AAAA'}));
await f.listener.receive({...packet,to:'other'});assert.equal(f.received.length,0);
f.gm.value={...f.gm.value,epoch:crypto.randomUUID()};await assert.rejects(f.listener.receive(packet),{code:'denied'});assert.equal(f.received.length,0);
}finally{f.close();}
});
test('parallel bootstrap replay, multiple GMs, revoked roles and expired capabilities cannot connect',async()=>{
const f=await fixture();try{
await f.host.send(f.player,newAudioInvite({session:'session',userId:'player'}));
const attempts=await Promise.allSettled([f.listener.receive(f.packets[0]),f.listener.receive(f.packets[0])]);assert.equal(attempts.filter(r=>r.status==='fulfilled').length,1);assert.equal(f.received.length,1);
await f.host.send(f.player,newAudioInvite({session:'session',userId:'player'}));f.other.isGM=true;await assert.rejects(f.listener.receive(f.packets[1]),{code:'denied'});f.other.isGM=false;
f.gm.isGM=false;await assert.rejects(f.listener.receive(f.packets[1]),{code:'denied'});f.gm.isGM=true;
await f.host.send(f.player,{...newAudioInvite({session:'session',userId:'player'}),expires:Date.now()-1});await assert.rejects(f.listener.receive(f.packets[2]),{code:'denied'});
}finally{f.close();}
});
+35
View File
@@ -64,3 +64,38 @@ test('peer signaling bounds queued work and rejects expired invites before alloc
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();}
});
test('wizard inspects only the imported dedicated identity, loads stable catalog IDs and enables guarded playlist playback',async()=>{
const calls=[];let requested=0;const target='dedicated-fixture';
const player={player_id:target,name:'Campaign receiver',provider:'sendspin-fixture',enabled:true,available:true,volume_level:35,volume_muted:false,group_members:[],group_childs:[],static_group_members:[]};
const queue={queue_id:target,active:true,available:true,items:0,state:'idle',shuffle_enabled:false,is_dynamic:false,autoplay_enabled:false,dont_stop_the_music_enabled:false,overlay_enabled:false,playback_speed:1};
const createSocket=url=>{
requested++;const socket={send(text){const msg=JSON.parse(text);calls.push(msg);queueMicrotask(()=>{
if(url.endsWith('/sendspin')){socket.onmessage?.({data:JSON.stringify({type:'auth_ok'})});return;}
const result=msg.command==='auth'?{authenticated:true}:msg.command==='players/get'?player:msg.command==='providers'?[{instance_id:'approved',available:true}]:msg.command.includes('library_items')?(msg.command.includes('playlists')?[{name:'Ambient',media_type:'playlist',is_playable:true,is_dynamic:false,provider_mappings:[{provider_instance:'approved',item_id:'ambient',available:true}]}]:[]):queue;
socket.onmessage?.({data:JSON.stringify({message_id:msg.message_id,result})});
});},close(){this.onclose?.();}};queueMicrotask(()=>socket.onopen?.());return socket;
};
const context={state:'running',destination:{},resume(){return Promise.resolve();},createMediaStreamDestination:()=>({stream:{getTracks:()=>[]}}),createGain:()=>({connect(){}}),close:async()=>{}};
const sdk={loadSendspinClientIdentity:()=>({clientId:target}),SendspinCore:class{timeSyncInfo={synced:true};async connect(){}disconnect(){}}};
const originalNavigator=globalThis.navigator;
Object.defineProperty(globalThis,'navigator',{configurable:true,value:{locks:{request:async(name,opts,fn)=>fn({})}}});
const host=new GMAudioHost({authority:()=>true,pageUrl:'https://foundry.example.test',loadSDK:async()=>sdk,createContext:()=>context,createSocket});
try{
const supplied={maUrl:'https://ma.example.test',token:'private-fixture',identityStorage:{'sendspin-identity-sk':'A'.repeat(43)},campaign:'world',targetName:player.name,webSocketAuthLogSafe:true,allowCatalogPlayback:true};
const profile=await host.inspect(supplied);assert.equal(profile.target,target);assert.deepEqual(profile.approvedProviders,['approved']);
const catalog=await host.readCatalog(profile,{reconnecting:true});const again=await host.inspect(supplied);assert.equal(profile.catalogKey,again.catalogKey);
await host.start(profile);assert.equal(host.connected,true);assert.equal(host.supports(catalog[0]),true);assert.equal(host.supports({provider:'ma',id:'forged'}),false);
assert.ok(calls.filter(c=>c.command==='players/get').every(c=>c.args.player_id===target));assert.ok(!calls.some(c=>c.command==='players/all'||c.command==='player_queues/play_media'));assert.ok(requested>=3);
await host.close();assert.equal(host.supports(catalog[0]),false);
}finally{await host.close();Object.defineProperty(globalThis,'navigator',{configurable:true,value:originalNavigator});}
});
test('disconnect cancels pending GM startup before any authenticated receiver connection',async()=>{
let release,entered=0,sockets=0;const loaded=new Promise(resolve=>{release=resolve;});
const host=new GMAudioHost({authority:()=>true,pageUrl:'https://foundry.example.test',loadSDK:()=>{entered++;return loaded;},createSocket:()=>{sockets++;},createContext:()=>({state:'running',resume:async()=>{},createMediaStreamDestination:()=>({stream:{getTracks:()=>[]}}),close:async()=>{}})});
const profile={maUrl:'https://ma.example.test',target:'dedicated',targetName:'Campaign',expectedProvider:'sendspin-fixture',identityStorage:{'sendspin-identity-sk':'A'.repeat(43)},approvedProviders:['approved'],catalogKey:'fixture',namespace:'world'};
const pending=host.start(profile);assert.equal(entered,1);await assert.rejects(host.start(profile),{code:'denied'});await host.close();release({});await assert.rejects(pending,{code:'stale'});assert.equal(sockets,0);assert.equal(host.connected,false);
assert.throws(()=>gmAccessPolicy('http://localhost','https://foundry.example.test'),{code:'mixed-content'});
assert.throws(()=>gmAccessPolicy('https://ma.example.test','http://foundry.example.test'),{code:'insecure-context'});
});
+11 -6
View File
@@ -1,6 +1,6 @@
import {test} from 'node:test';
import assert from 'node:assert/strict';
import {createSetupClass} from '../../src/foundry/setup.mjs';
import {createSetupClass,createListenerClass} 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='';}
@@ -11,16 +11,16 @@ class Element{
}
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()=>{
test('GM setup connects catalog into independent scene editors and never persists private GM authentication',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()=>{}};
const connection={status:{state:'disconnected',catalog:0,audioContext:'closed'},async test(profile){assert.equal(profile.token,'capability-fixture');assert.equal(profile.maUrl,'https://ma.example.test');catalog=[{provider:'ma',id:'opaque-ma',name:'MA fixture',kind:'playlist'}];return {target:'dedicated',targetName:'Adaptive Music DEV'};},async connect(target){assert.equal(target,'dedicated');},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 Setup=createSetupClass({game,connection,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';descendants(root).find(e=>e.type==='url').value='https://ma.example.test';const checks=descendants(root).filter(e=>e.type==='checkbox');checks[0].checked=true;checks[1].checked=true;
await descendants(root).find(e=>e.tag==='button'&&e.textContent==='Test connection and load playlists').listeners.click();assert.equal(code.value,'');assert.ok(!descendants(root).some(e=>e.textContent==='Connect optional companion'));await descendants(root).find(e=>e.textContent==='Connect audio').listeners.click();
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"]';
@@ -35,3 +35,8 @@ test('browser PCM sink resumes from gesture, decodes stereo frames and closes it
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'));
});
test('normal listener has one activation action and no token or invitation entry',async()=>{
const dom={createElement:tag=>new Element(tag,dom)};globalThis.document=dom;let clicks=0;
try{const Listener=createListenerClass({game:{settings:{get:()=>false}},audio:{stop(){}},resumeListener:()=>{clicks++;},Base:class{}});const root=await new Listener()._renderHTML();assert.ok(!descendants(root).some(e=>e.tag==='input'));await descendants(root).find(e=>e.textContent==='Enable Audio').listeners.click();assert.equal(clicks,1);}finally{delete globalThis.document;}
});