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

+52
View File
@@ -0,0 +1,52 @@
import {MusicError} from '../core/controller.mjs';
const ns='adaptive-music',flag='audioPublicKey',channel='module.adaptive-music';
const encode=a=>btoa(String.fromCharCode(...a));
const decode=s=>Uint8Array.from(atob(s),c=>c.charCodeAt(0));
const valid=p=>p?.v===1&&typeof p.epoch==='string'&&p.epoch.length===36&&typeof p.key==='string'&&p.key.length===88;
// Only PUBLIC ephemeral keys are stored in User flags. The authenticated Foundry
// document permission boundary binds those keys to accounts; socket sender IDs do not.
export class AutoListeners {
#game;#socket;#keys;#public;#onInvite;#isGM;#received=new Set();#pending=0;#closed=false;#starting;
constructor({game,isGM,onInvite}){this.#game=game;this.#socket=game.socket;this.#isGM=isGM;this.#onInvite=onInvite;this.handler=packet=>{this.receive(packet).catch(()=>{});};}
async start(){if(this.#starting)return this.#starting;this.#starting=this.#rotate();try{return await this.#starting;}finally{this.#starting=null;}}
async #rotate(){
this.#socket.off(channel,this.handler);this.#received.clear();
this.#keys=await crypto.subtle.generateKey({name:'ECDH',namedCurve:'P-256'},false,['deriveKey']);
this.#public={v:1,epoch:crypto.randomUUID(),key:encode(new Uint8Array(await crypto.subtle.exportKey('raw',this.#keys.publicKey)))};
if(this.#closed)return;
this.#socket.on(channel,this.handler);
await this.#game.user.setFlag(ns,flag,this.#public);
}
async #key(remote,usage){
if(!valid(remote))throw new MusicError('denied');
const publicKey=await crypto.subtle.importKey('raw',decode(remote.key),{name:'ECDH',namedCurve:'P-256'},false,[]);
return crypto.subtle.deriveKey({name:'ECDH',public:publicKey},this.#keys.privateKey,{name:'AES-GCM',length:256},false,[usage]);
}
recipientKey(user){const value=user?.getFlag(ns,flag);return valid(value)?value:null;}
async send(user,invite){
if(!this.#isGM()||!this.#public||!user.active||user.isGM||user.isBanned||invite.userId!==user.id)throw new MusicError('denied');
const recipient=this.recipientKey(user);if(!recipient)throw new MusicError('unavailable');
const header={type:'audio-invite-v1',campaign:this.#game.world.id,from:this.#game.user.id,to:user.id,sender:this.#public.epoch,recipient:recipient.epoch,id:crypto.randomUUID()};
const iv=crypto.getRandomValues(new Uint8Array(12)),key=await this.#key(recipient,'encrypt');
const cipher=await crypto.subtle.encrypt({name:'AES-GCM',iv,additionalData:new TextEncoder().encode(JSON.stringify(header))},key,new TextEncoder().encode(JSON.stringify(invite)));
if(this.#closed||!this.#isGM()||this.recipientKey(user)?.epoch!==recipient.epoch)throw new MusicError('stale');
this.#socket.emit(channel,{...header,iv:encode(iv),cipher:encode(new Uint8Array(cipher))});
}
async receive(packet){
if(this.#closed||!this.#keys||this.#game.user.isGM||packet?.type!=='audio-invite-v1'||packet.to!==this.#game.user.id||packet.campaign!==this.#game.world.id||packet.recipient!==this.#public.epoch)return;
if(Object.keys(packet).sort().join(',')!=='campaign,cipher,from,id,iv,recipient,sender,to,type'||typeof packet.id!=='string'||packet.id.length!==36||typeof packet.cipher!=='string'||packet.cipher.length>16384||typeof packet.iv!=='string'||packet.iv.length!==16||this.#pending>=2||this.#received.has(packet.id)||this.#received.size>=256)throw new MusicError('denied');
const gms=[...this.#game.users].filter(u=>u.active&&u.isGM),gm=gms[0];
if(gms.length!==1||gm.id!==packet.from||gm.isBanned)throw new MusicError('denied');
const remote=this.recipientKey(gm);if(remote?.epoch!==packet.sender)throw new MusicError('denied');
const localEpoch=this.#public.epoch;this.#pending++;
try{
const {iv,cipher,...header}=packet;
const plain=await crypto.subtle.decrypt({name:'AES-GCM',iv:decode(iv),additionalData:new TextEncoder().encode(JSON.stringify(header))},await this.#key(remote,'decrypt'),decode(cipher));
if(this.#closed||this.#public.epoch!==localEpoch||this.#received.has(packet.id)||this.recipientKey(gm)?.epoch!==remote.epoch||!gm.active||!gm.isGM||[...this.#game.users].filter(u=>u.active&&u.isGM).length!==1)throw new MusicError('stale');
const invite=JSON.parse(new TextDecoder().decode(plain));
if(invite.transport!=='webrtc-v1'||invite.userId!==this.#game.user.id||invite.expires<=Date.now()||invite.expires>Date.now()+1800000)throw new MusicError('denied');
this.#received.add(packet.id);await this.#onInvite(invite);
}finally{this.#pending--;}
}
close(){this.#closed=true;this.#socket.off(channel,this.handler);this.#keys=null;}
}
+47 -19
View File
@@ -6,33 +6,61 @@ import {randomKey} from '../providers/ma/webcrypto.mjs';
export function gmAccessPolicy(baseUrl,pageUrl){
const target=new URL(baseUrl),page=new URL(pageUrl);
if(target.username||target.password||target.search||target.hash||target.pathname!=='/'||!['http:','https:'].includes(target.protocol))throw new MusicError('denied');
if(page.protocol==='https:'&&target.protocol!=='https:'&&!['localhost','127.0.0.1','[::1]'].includes(target.hostname))throw new MusicError('mixed-content');
if(page.protocol==='https:'&&target.protocol!=='https:')throw new MusicError('mixed-content');
if(page.protocol!=='https:'&&!['localhost','127.0.0.1','[::1]'].includes(page.hostname))throw new MusicError('insecure-context');
return target;
}
function memoryStorage(values){const map=new Map(Object.entries(values));return {getItem:k=>map.get(k)??null,setItem:(k,v)=>map.set(k,v),removeItem:k=>map.delete(k)};}
export class GMAudioHost{
#authority;#sdk;#core;#context;#destination;#nodes=new Set();#client;#provider;#catalog=[];#session;#live=false;#socket;#generation=-1; #allowed=new Set(); #apiTransport; #gain; #releaseLock;
constructor({authority,pageUrl=globalThis.location?.href,loadSDK=()=>import('../../vendor/sendspin-5.0.0.mjs'),createContext=()=>new AudioContext(),createSocket=url=>new WebSocket(url)}){this.#authority=authority;this.pageUrl=pageUrl;this.loadSDK=loadSDK;this.createContext=createContext;this.createSocket=createSocket;}
#authority;#sdk;#core;#context;#destination;#nodes=new Set();#client;#provider;#catalog=[];#session;#live=false;#socket;#generation=-1; #allowed=new Set(); #apiTransport; #gain; #releaseLock; #catalogPlayback=false; #status='disconnected'; #starting=false; #epoch=0;
constructor({authority,onDisconnect=()=>{},pageUrl=globalThis.location?.href,loadSDK=()=>import('../../vendor/sendspin-5.0.0.mjs'),createContext=()=>new AudioContext(),createSocket=url=>new WebSocket(url)}){this.#authority=authority;this.onDisconnect=onDisconnect;this.pageUrl=pageUrl;this.loadSDK=loadSDK;this.createContext=createContext;this.createSocket=createSocket;}
get status(){return {state:this.#live?'connected':this.#starting?'connecting':this.#status,catalog:this.#catalog.length,audioContext:this.#context?.state??'closed',catalogPlayback:this.#catalogPlayback};}
get catalog(){return structuredClone(this.#catalog);}
get session(){return this.#session;}
get stream(){return this.#destination?.stream;}
get connected(){return this.#live;}
supports(ref){return this.#live&&this.#allowed.has(ref.id);}
supports(ref){return ref?.provider==='ma'&&this.#live&&(this.#allowed.has(ref.id)||this.#catalogPlayback&&this.#catalog.some(c=>c.id===ref.id&&c.kind==='playlist')); }
async inspect(profile){
if(!this.#authority()||this.#live)throw new MusicError('denied');
if(profile.webSocketAuthLogSafe!==true)throw new MusicError('auth-log-review-required');
const base=gmAccessPolicy(profile.maUrl,this.pageUrl);
const sk=profile.identityStorage?.['sendspin-identity-sk'];
if(typeof sk!=='string'||!/^[A-Za-z0-9_-]{43}$/.test(sk))throw new MusicError('identity-required');
const sdk=await this.loadSDK(),identity=sdk.loadSendspinClientIdentity(memoryStorage(profile.identityStorage));
if(profile.target&&profile.target!==identity.clientId)throw new MusicError('identity-mismatch');
const transport=new GMMAWebSocket({baseUrl:base.origin,token:profile.token,createSocket:this.createSocket});
const read=async(command,args)=>{
const response=await transport.fetch(base.origin+'/api',{method:'POST',redirect:'error',body:JSON.stringify({command,args})});return response.json();
};
try{
const player=await read('players/get',{player_id:identity.clientId});
if(player?.player_id!==identity.clientId||player.name!==profile.targetName||!player.provider?.startsWith('sendspin'))throw new MusicError('dedicated-target-required');
const providers=await read('providers',{provider_type:'music'});
const approvedProviders=providers.filter(p=>p.available===true&&typeof p.instance_id==='string').map(p=>p.instance_id);
if(!approvedProviders.length)throw new MusicError('catalog-empty');
const catalogKey=profile.catalogKey??btoa(String.fromCharCode(...new Uint8Array(await crypto.subtle.digest('SHA-256',new TextEncoder().encode('adaptive-music-catalog-v1:'+profile.campaign+':'+sk)))));
return {...profile,maUrl:base.origin,target:identity.clientId,expectedProvider:player.provider,approvedProviders,catalogKey,namespace:profile.namespace??profile.campaign};
}finally{transport.close();}
}
async refreshCatalog(){if(!this.#client||!this.#authority())throw new MusicError('denied');await this.#client.verifyTarget({allowUnavailable:!this.#live});this.#catalog=await this.#client.catalog();return this.catalog;}
resumeAudio(){return this.#context?.resume();}
async readCatalog(profile,{reconnecting=false}={}){
if(!this.#authority()||this.#live)throw new MusicError('denied');if(profile.webSocketAuthLogSafe!==true)throw new MusicError('auth-log-review-required');const base=gmAccessPolicy(profile.maUrl,this.pageUrl);
const key=Uint8Array.from(atob(profile.catalogKey),c=>c.charCodeAt(0));if(key.length!==32||profile.targetName!=='Adaptive Music DEV')throw new MusicError('denied');
const key=Uint8Array.from(atob(profile.catalogKey),c=>c.charCodeAt(0));if(key.length!==32||!profile.targetName)throw new MusicError('denied');
this.#apiTransport?.close();this.#apiTransport=new GMMAWebSocket({baseUrl:base.origin,token:profile.token,createSocket:this.createSocket});
this.#client=new MAReadClient({baseUrl:base.origin,token:profile.token,target:profile.target,expectedName:profile.targetName,expectedProvider:profile.expectedProvider,approvedProviders:profile.approvedProviders,catalogKey:key,campaign:profile.namespace,syntheticSequences:profile.syntheticSequences??{},fetchImpl:this.#apiTransport.fetch});
await this.#client.verifyTarget({allowUnavailable:reconnecting});this.#catalog=await this.#client.catalog();return this.catalog;
try{await this.#client.verifyTarget({allowUnavailable:reconnecting});this.#catalog=await this.#client.catalog();this.#status='catalog-ready';return this.catalog;}catch(error){await this.close();throw error;}
}
async start(profile){
start(profile){if(this.#starting)return Promise.reject(new MusicError('denied'));this.#starting=true;return this.#start(profile).finally(()=>{this.#starting=false;});}
async #start(profile){
if(!this.#authority()||this.#live)throw new MusicError('denied');
const base=gmAccessPolicy(profile.maUrl,this.pageUrl);
if(profile.targetName!=='Adaptive Music DEV'||typeof profile.target!=='string'||!profile.expectedProvider?.startsWith('sendspin')||!profile.identityStorage?.['sendspin-identity-sk']||!Array.isArray(profile.approvedProviders)||!profile.catalogKey||!profile.namespace)throw new MusicError('profile-required');
if(!profile.targetName||typeof profile.target!=='string'||!profile.expectedProvider?.startsWith('sendspin')||!profile.identityStorage?.['sendspin-identity-sk']||!Array.isArray(profile.approvedProviders)||!profile.catalogKey||!profile.namespace)throw new MusicError('profile-required');
const epoch=this.#epoch,check=()=>{if(epoch!==this.#epoch||!this.#authority())throw new MusicError('stale');};
// Unlock synchronously in the caller's gesture before SDK/network work.
this.#context=this.createContext();const unlocked=this.#context.resume();this.#destination=this.#context.createMediaStreamDestination();
try{
this.#sdk=await this.loadSDK();await unlocked;
this.#sdk=await this.loadSDK();await unlocked;check();
const storage=memoryStorage(profile.identityStorage),identity=this.#sdk.loadSendspinClientIdentity(storage);
// Never register a fresh identity or silently select a new/household player.
if(identity.clientId!==profile.target)throw new MusicError('identity-mismatch');
@@ -41,29 +69,29 @@ export class GMAudioHost{
const lockName='adaptive-music-'+Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',new TextEncoder().encode(base.origin+profile.target))),n=>n.toString(16).padStart(2,'0')).join('');
const released=new Promise(resolve=>{this.#releaseLock=resolve;});
await new Promise((resolve,reject)=>{navigator.locks.request(lockName,{ifAvailable:true},async lock=>{if(!lock){reject(new MusicError('denied'));return;}resolve();await released;}).catch(()=>reject(new MusicError('unavailable')));});
await this.readCatalog(profile,{reconnecting:true});
const original=await this.#client.queueState({allowUnavailable:true});
await this.readCatalog(profile,{reconnecting:true});check();
const original=await this.#client.queueState({allowUnavailable:true});check();
if(original.items!==0||original.state!=='idle')throw new MusicError('reconcile-required');
if(profile.allowSyntheticPlayback===true){
for(const id of Object.keys(profile.syntheticSequences??{})){if(!['synthetic-ambient','synthetic-combat'].includes(id))throw new MusicError('denied');this.#allowed.add(id);}
this.#catalog.push(...[...this.#allowed].map(id=>({provider:'ma',id,kind:'sequence',name:'Generated '+id.slice(10)+' sequence'})));
}
let volumeState=this.#client.targetVolumeState();
this.#socket=await this.#authenticatedSocket(base,profile.token,identity.clientId);
this.#socket=await this.#authenticatedSocket(base,profile.token,identity.clientId);check();
this.#core=new this.#sdk.SendspinCore({webSocket:this.#socket,storage,clientName:profile.targetName,productName:'Web Browser',codecs:['pcm'],bufferCapacity:768000,requiredLeadTimeMs:250,minBufferMs:250,useHardwareVolume:true,getExternalVolume:()=>volumeState,onVolumeCommand:(volume,muted)=>{volumeState={volume,muted};},unpairedAccess:false,reconnect:{enabled:false}});
this.#gain=this.#context.createGain();this.#gain.connect(this.#destination);
this.#gain=this.#context.createGain();this.#gain.connect(this.#destination);this.#gain.connect(this.#context.destination);
this.#core.onVolumeUpdate=()=>this.#gain.gain.setTargetAtTime(this.#core.muted?0:Math.pow(Math.min(100,Math.max(0,this.#core.volume))/100,1.5),this.#context.currentTime,0.015);
this.#core.onAudioData=chunk=>this.#schedule(chunk);
this.#core.onConnectionClose=()=>{this.#live=false;this.#clear();for(const track of this.#destination?.stream.getTracks()??[])track.stop();};
this.#core.onConnectionClose=()=>{const wasLive=this.#live;this.#status='connection-lost';this.#live=false;if(wasLive)this.onDisconnect();this.#clear();for(const track of this.#destination?.stream.getTracks()??[])track.stop();};
this.#core.onStreamClear=()=>this.#clear();this.#core.onStreamEnd=()=>this.#clear();
this.#session=crypto.randomUUID();this.#live=true;
this.#session=crypto.randomUUID();this.#catalogPlayback=profile.allowCatalogPlayback===true;this.#live=true;
this.#provider=new MAPlaybackProvider({client:this.#client,campaign:profile.campaign,session:this.#session,fence:1,snapshotKey:randomKey(),authority:()=>{if(!this.#live||!this.#authority())throw new MusicError('stale');}});
await this.#core.connect();const deadline=Date.now()+10000;while(this.#live&&!this.#core.timeSyncInfo.synced&&Date.now()<deadline)await new Promise(resolve=>setTimeout(resolve,50));if(!this.#live||!this.#core.timeSyncInfo.synced)throw new MusicError('unavailable');await this.#client.verifyTarget();return {clientIdVerified:true,catalog:this.#catalog.length,codecs:['pcm'],remoteAudio:'webrtc',audioMeasured:false,distributedFencing:false};
}catch(error){await this.close();throw new MusicError(error instanceof MusicError?error.code:'unavailable');}
await this.#core.connect();check();const deadline=Date.now()+10000;while(this.#live&&!this.#core.timeSyncInfo.synced&&Date.now()<deadline)await new Promise(resolve=>setTimeout(resolve,50));if(!this.#live||!this.#core.timeSyncInfo.synced)throw new MusicError('unavailable');await this.#client.verifyTarget();check();return {clientIdVerified:true,catalog:this.#catalog.length,codecs:['pcm'],remoteAudio:'webrtc',audioMeasured:false,distributedFencing:false};
}catch(error){if(epoch===this.#epoch)await this.close();throw new MusicError(error instanceof MusicError?error.code:'unavailable');}
}
#authenticatedSocket(base,token,clientId){
const url=new URL('/sendspin',base);url.protocol=base.protocol==='https:'?'wss:':'ws:';
return new Promise((resolve,reject)=>{const socket=this.createSocket(url.href);socket.binaryType='arraybuffer';const timer=setTimeout(()=>{socket.close();reject(new MusicError('unavailable'));},8000);
return new Promise((resolve,reject)=>{const socket=this.createSocket(url.href);this.#socket=socket;socket.binaryType='arraybuffer';const timer=setTimeout(()=>{socket.close();reject(new MusicError('unavailable'));},8000);
const fail=()=>{clearTimeout(timer);socket.close();reject(new MusicError('unavailable'));};socket.onerror=fail;socket.onclose=fail;
socket.onopen=()=>socket.send(JSON.stringify({type:'auth',token,client_id:clientId}));
socket.onmessage=event=>{try{if(JSON.parse(event.data).type!=='auth_ok')throw Error();clearTimeout(timer);socket.onerror=null;socket.onclose=null;socket.onmessage=null;resolve(socket);}catch{fail();}};
@@ -86,5 +114,5 @@ export class GMAudioHost{
apply(prepared,ctx){return this.#ready().apply(prepared,ctx);}
restore(snapshot,ctx){return this.#ready().restore(snapshot,ctx);}
stopOwned(ctx){return this.#ready().stopOwned(ctx);}
async close(){this.#live=false;this.#releaseLock?.();this.#releaseLock=null;this.#clear();this.#core?.disconnect('user_request');this.#socket?.close();this.#core=null;this.#socket=null;this.#provider=null;this.#apiTransport?.close();this.#apiTransport=null;this.#client=null;this.#catalog=[];this.#allowed.clear();for(const track of this.#destination?.stream.getTracks()??[])track.stop();this.#destination=null;const context=this.#context;this.#context=null;if(context&&context.state!=='closed')await context.close();}
async close(){this.#epoch++;this.#status='disconnected';this.#catalogPlayback=false;this.#live=false;this.#releaseLock?.();this.#releaseLock=null;this.#clear();this.#core?.disconnect('user_request');this.#socket?.close();this.#core=null;this.#socket=null;this.#provider=null;this.#apiTransport?.close();this.#apiTransport=null;this.#client=null;this.#catalog=[];this.#allowed.clear();for(const track of this.#destination?.stream.getTracks()??[])track.stop();this.#destination=null;const context=this.#context;this.#context=null;if(context&&context.state!=='closed')await context.close();}
}
+3 -2
View File
@@ -26,9 +26,10 @@ export class PeerAudio{
socket.on('module.adaptive-music',this.#handler);socket.on('disconnect',this.#disconnect);
}
setSource(stream){if(!this.#isGM()||stream.getAudioTracks().length!==1)throw new MusicError('denied');this.#stream=stream;}
hasListener(userId){return [...this.#peers.values()].some(e=>e.invite.userId===userId);}
invite(userId,{iceServers=[],ttlMs=300000,relayOnly=false}={}){
if(!this.#isGM()||!this.authorized(userId)||!this.#stream||this.#peers.size>=8)throw new MusicError('denied');validateIceServers(iceServers);
const invite=newAudioInvite({session:this.#session,userId,iceServers,ttlMs,relayOnly});this.#entry(invite,'gm');return invite;
if(!this.#isGM()||!this.authorized(userId)||!this.#stream)throw new MusicError('denied');validateIceServers(iceServers);
const invite=newAudioInvite({session:this.#session,userId,iceServers,ttlMs,relayOnly});for(const [id,entry]of this.#peers)if(entry.invite.userId===userId)this.revoke(id);if(this.#peers.size>=8)throw new MusicError('denied');this.#entry(invite,'gm');return invite;
}
async listen(invite){
if(this.#isGM()||invite.userId!==this.#userId||this.#peers.size)throw new MusicError('denied');