Release v0.7.0 - Automatic pairing and validated MA audio playback
Validate and generate manual release / package (push) Waiting to run

This commit is contained in:
Jason committed 2026-12-04 08:58:47 -05:00
1 parent 83d168f5a1
commit 1ed30567fb
48 files changed
+2717 -742

No files matched your search

+88 -40
View File
@@ -4,23 +4,39 @@ import {MAPlaybackProvider} from '../providers/ma/provider.mjs';
import {GMMAWebSocket} from '../providers/ma/websocket.mjs';
import {randomKey} from '../providers/ma/webcrypto.mjs';
export function gmAccessPolicy(baseUrl,pageUrl){
const target=new URL(baseUrl),page=new URL(pageUrl);
let target,page;try{target=new URL(baseUrl);page=new URL(pageUrl);}catch{throw new MusicError('address-invalid');}
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:')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)};}
function memoryStorage(values){return {getItem:k=>values[k]??null,setItem:(k,v)=>{values[k]=v;},removeItem:k=>{delete values[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; #catalogPlayback=false; #status='disconnected'; #starting=false; #epoch=0;
#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; #phase='idle'; #frames=0; #samples=0; #energy=0; #lastAudio=0; #attachedQueue=false; #lastError; #scheduled=0; #late=0; #ahead=0; #lastLead=0; #bufferedBytes=0; #meter;
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 status(){let outputRMS=0;if(this.#meter){const data=new Float32Array(this.#meter.fftSize);this.#meter.getFloatTimeDomainData(data);outputRMS=Math.sqrt(data.reduce((sum,v)=>sum+v*v,0)/data.length);}return {state:this.#live?'connected':this.#starting?'connecting':this.#status,catalog:this.#catalog.length,audioContext:this.#context?.state??'closed',catalogPlayback:this.#catalogPlayback,stage:this.#phase,decodedFrames:this.#frames,lastAudioAt:this.#lastAudio,outputRMS,rms:this.#samples?Math.sqrt(this.#energy/this.#samples):0,attachedExistingQueue:this.#attachedQueue,volume:this.#core?.volume??100,muted:this.#core?.muted??false,pauseMode:this.#client?.supportsNativePause()===false?'emulated':'native',scheduledFrames:this.#scheduled,droppedLate:this.#late,droppedAhead:this.#ahead,lastLeadSeconds:this.#lastLead,audioTime:this.#context?.currentTime,lastError:this.#lastError};}
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 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){
async prepare(profile){
if(!this.#authority()||this.#live)throw new MusicError('denied');
const base=gmAccessPolicy(profile.maUrl,this.pageUrl);this.#phase='API authentication';
const transport=new GMMAWebSocket({baseUrl:base.origin,token:profile.token,createSocket:this.createSocket});
try{
const response=await transport.fetch(base.origin+'/api',{method:'POST',redirect:'error',body:JSON.stringify({command:'providers',args:{provider_type:'music'}})});
const providers=await response.json();
if(!Array.isArray(providers))throw new MusicError('catalog-empty');
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 sdk=await this.loadSDK(),identityStorage=profile.identityStorage??{},identity=sdk.loadSendspinClientIdentity(memoryStorage(identityStorage));
const catalogKey=profile.catalogKey??btoa(String.fromCharCode(...new Uint8Array(await crypto.subtle.digest('SHA-256',new TextEncoder().encode('adaptive-music-catalog-v1:'+profile.campaign+':'+identityStorage['sendspin-identity-sk'])))));
this.#phase='authenticated';
return {...profile,maUrl:base.origin,identityStorage,target:identity.clientId,targetName:profile.targetName||'Adaptive Music campaign',approvedProviders,catalogKey,namespace:profile.namespace??profile.campaign,autoProvision:true,campaignOwned:true,webSocketAuthLogSafe:true};
}finally{transport.close();}
}
async inspect(profile,{transport:existingTransport}={}){
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);
@@ -28,7 +44,7 @@ export class GMAudioHost{
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 transport=existingTransport??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();
};
@@ -40,79 +56,111 @@ export class GMAudioHost{
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();}
}finally{if(!existingTransport)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}={}){
async readCatalog(profile,{reconnecting=false,preserveTransport=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)throw new MusicError('denied');
this.#apiTransport?.close();this.#apiTransport=new GMMAWebSocket({baseUrl:base.origin,token:profile.token,createSocket:this.createSocket});
if(!preserveTransport){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});
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;}
}
start(profile){if(this.#starting)return Promise.reject(new MusicError('denied'));this.#starting=true;return this.#start(profile).finally(()=>{this.#starting=false;});}
#connectionLost(epoch,stage){
if(epoch!==this.#epoch||!this.#live)return;
void this.close();
this.#status='connection-lost';this.#phase=stage;
this.onDisconnect();
}
async #start(profile){
if(!this.#authority()||this.#live)throw new MusicError('denied');
const base=gmAccessPolicy(profile.maUrl,this.pageUrl);
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');
if(!profile.targetName||typeof profile.target!=='string'||!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();
this.#lastError=undefined;this.#attachedQueue=false;this.#context=this.createContext();const unlocked=this.#context.resume();this.#destination=this.#context.createMediaStreamDestination();this.#frames=this.#samples=this.#energy=this.#lastAudio=this.#scheduled=this.#late=this.#ahead=0;
try{
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');
const key=Uint8Array.from(atob(profile.catalogKey),c=>c.charCodeAt(0));if(key.length!==32)throw new MusicError('denied');
if(!globalThis.navigator?.locks)throw new MusicError('unsupported');
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});check();
const original=await this.#client.queueState({allowUnavailable:true});check();
if(original.items!==0||original.state!=='idle')throw new MusicError('reconcile-required');
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')));});check();
this.#apiTransport?.close();this.#apiTransport=new GMMAWebSocket({baseUrl:base.origin,token:profile.token,createSocket:this.createSocket,onDisconnect:()=>this.#connectionLost(epoch,'API connection lost')});
await this.#apiTransport.connect();check();
this.#phase='Sendspin authentication';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:false,unpairedAccess:false,reconnect:{enabled:false}});
this.#gain=this.#context.createGain();this.#meter=this.#context.createAnalyser?.();if(this.#meter){this.#gain.connect(this.#meter);this.#meter.connect(this.#destination);this.#meter.connect(this.#context.destination);}else{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.#connectionLost(epoch,'Sendspin connection lost');
this.#core.onStreamStart=(format,isFormatUpdate)=>{if(!isFormatUpdate)this.#clear();};this.#core.onStreamClear=timestamp=>this.#clear(timestamp);this.#core.onStreamEnd=()=>this.#clear();
this.#phase='Noise handshake';await this.#core.connect();check();
if(profile.autoProvision){
this.#phase='receiver pairing';
await this.#apiTransport.fetch(base.origin+'/api',{method:'POST',redirect:'error',body:JSON.stringify({command:'sendspin/pair_web_player',args:{pairing_token:this.#core.pairingToken}})});
}
this.#phase='clock synchronization';const deadline=Date.now()+15000;
while(!this.#core.timeSyncInfo.synced&&Date.now()<deadline){check();await new Promise(resolve=>setTimeout(resolve,50));}
if(!this.#core.timeSyncInfo.synced)throw new MusicError('sendspin-sync-failed');check();
if(profile.autoProvision){this.#phase='dedicated receiver verification';Object.assign(profile,await this.inspect(profile,{transport:this.#apiTransport}));check();}
await this.readCatalog(profile,{reconnecting:true,preserveTransport:true});check();
this.#phase='dedicated queue verification';
await this.#client.verifyTarget({checkRegistration:check});
const original=await this.#client.queueState();check();
this.#attachedQueue=original.items!==0||original.state!=='idle';
if(this.#attachedQueue&&!profile.campaignOwned)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);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.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=()=>{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.#catalogPlayback=profile.allowCatalogPlayback===true;this.#live=true;
this.#session=crypto.randomUUID();this.#catalogPlayback=profile.allowCatalogPlayback===true;this.#live=true;this.#phase='ready';
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();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');}
return {clientIdVerified:true,catalog:this.#catalog.length,codecs:['pcm'],remoteAudio:'webrtc',audioMeasured:false,distributedFencing:false,attachedExistingQueue:this.#attachedQueue};
}catch(error){this.#lastError={code:error instanceof MusicError?error.code:'unavailable',stage:this.#phase,command:error.command,upstreamCode:error.upstreamCode,translationKey:error.translationKey};if(epoch===this.#epoch)await this.close();throw new MusicError(this.#lastError.code);}
}
#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);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();}};
return new Promise((resolve,reject)=>{
let socket,opened=false,settled=false;
const fail=code=>{if(settled)return;settled=true;clearTimeout(timer);if(socket){socket.onopen=socket.onmessage=socket.onerror=socket.onclose=null;socket.close();}reject(new MusicError(code));};
const timer=setTimeout(()=>fail(opened?'sendspin-auth-failed':'ws-upgrade-failed'),8000);
try{socket=this.createSocket(url.href);this.#socket=socket;}catch{fail('ws-upgrade-failed');return;}
socket.binaryType='arraybuffer';
socket.onerror=()=>fail(opened?'sendspin-auth-failed':'ws-upgrade-failed');socket.onclose=()=>fail(opened?'sendspin-auth-failed':'ws-upgrade-failed');
socket.onopen=()=>{opened=true;try{socket.send(JSON.stringify({type:'auth',token,client_id:clientId}));}catch{fail('sendspin-auth-failed');}};
socket.onmessage=event=>{try{if(typeof event.data!=='string'||event.data.length>65536||JSON.parse(event.data).type!=='auth_ok')throw Error();clearTimeout(timer);settled=true;socket.onopen=socket.onerror=socket.onclose=socket.onmessage=null;resolve(socket);}catch{fail('sendspin-auth-failed');}};
});
}
#schedule(chunk){
if(!this.#live||!this.#authority()){this.#clear();return;}
if(!this.#core.timeSyncInfo.synced||!Array.isArray(chunk.samples)||chunk.samples.length>2||!chunk.samples.length||!Number.isFinite(chunk.sampleRate)||chunk.sampleRate<8000||chunk.sampleRate>96000)return;
const frames=chunk.samples[0].length;if(frames<1||frames>chunk.sampleRate/4||chunk.samples.some(c=>c.length!==frames))return;
if(chunk.generation!==this.#generation){this.#clear();this.#generation=chunk.generation;}
this.#frames++;this.#lastAudio=Date.now();for(const channel of chunk.samples)for(const sample of channel){this.#samples++;this.#energy+=sample*sample;}
const lead=(chunk.serverTimeUs-this.#core.getCurrentServerTimeUs())/1000000;
if(!Number.isFinite(lead)||lead>2||lead+frames/chunk.sampleRate<0||this.#nodes.size>=128)return;
this.#lastLead=lead;if(!Number.isFinite(lead)||this.#nodes.size>=512||this.#bufferedBytes+frames*chunk.samples.length*4>2097152)return;
if(lead>6){this.#ahead++;return;}if(lead+frames/chunk.sampleRate<0){this.#late++;return;}
const buffer=this.#context.createBuffer(chunk.samples.length,frames,chunk.sampleRate);chunk.samples.forEach((samples,i)=>buffer.getChannelData(i).set(samples));
const node=this.#context.createBufferSource();node.buffer=buffer;node.connect(this.#gain);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);node.onended=()=>this.#nodes.delete(node);this.#nodes.add(node);node.start(Math.max(this.#context.currentTime+0.01,this.#context.currentTime+lead));
const node=this.#context.createBufferSource();node.buffer=buffer;node.connect(this.#gain);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);node.adaptiveBytes=frames*chunk.samples.length*4;node.adaptiveServerStart=chunk.serverTimeUs;node.adaptiveServerEnd=chunk.serverTimeUs+frames/chunk.sampleRate*1000000;node.onended=()=>{if(this.#nodes.delete(node))this.#bufferedBytes-=node.adaptiveBytes;};this.#nodes.add(node);this.#bufferedBytes+=node.adaptiveBytes;node.start(Math.max(this.#context.currentTime+0.01,this.#context.currentTime+lead));this.#scheduled++;
}
#clear(fromTimestampUs){
if(Number.isFinite(fromTimestampUs)){
const when=Math.max(this.#context.currentTime,this.#context.currentTime+(fromTimestampUs-this.#core.getCurrentServerTimeUs())/1000000);
for(const node of this.#nodes)if(node.adaptiveServerEnd>fromTimestampUs){try{node.stop(node.adaptiveServerStart>=fromTimestampUs?0:when);}catch{}}
return;
}
for(const node of this.#nodes){try{node.stop();}catch{}}this.#nodes.clear();this.#bufferedBytes=0;
}
#clear(){for(const node of this.#nodes){try{node.stop();}catch{}}this.#nodes.clear();}
#ready(){if(!this.#live||!this.#authority()||!this.#provider)throw new MusicError('stale');return this.#provider;}
resolve(ref,ctx){if(!this.supports(ref))throw new MusicError('denied');return this.#ready().resolve(ref,ctx);}
snapshot(ctx){return this.#ready().snapshot(ctx);}
apply(prepared,ctx){return this.#ready().apply(prepared,ctx);}
restore(snapshot,ctx){return this.#ready().restore(snapshot,ctx);}
async #observe(operation){try{return await operation();}catch(error){this.#lastError={code:error.code??'unavailable',stage:this.#phase,command:error.command,upstreamCode:error.upstreamCode,translationKey:error.translationKey};if(error.code==='uncertain')this.#phase='queue reconciliation required';throw error;}}
apply(prepared,ctx){return this.#observe(()=>this.#ready().apply(prepared,ctx));}
restore(snapshot,ctx){return this.#observe(()=>this.#ready().restore(snapshot,ctx));}
stopOwned(ctx){return this.#ready().stopOwned(ctx);}
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();}
control(action,value,ctx){return this.#observe(()=>this.#ready().control(action,value,ctx));}
setVolume(value){this.#ready();if(!Number.isFinite(value)||value<0||value>100)throw new MusicError('denied');this.#core.setVolume(Math.round(value));}
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;this.#meter=null;const context=this.#context;this.#context=null;if(context&&context.state!=='closed')await context.close();}
}
+30 -14
View File
@@ -9,20 +9,30 @@ export function validateIceServers(servers){
}
return servers.map(({urls,username,credential})=>({urls,...(username?{username,credential}:{})}));
}
function audioOnly(sdp,remote){
if(typeof sdp!=='string'||sdp.length>65536)throw new MusicError('denied');
const media=sdp.split(/\r?\n/).filter(line=>line.startsWith('m='));
if(media.length!==1||!media[0].startsWith('m=audio ')||/a=sendrecv|a=sendonly/.test(sdp)&&remote==='answer')throw new MusicError('denied');
export function validateAudioSDP(sdp,remote){
if(typeof sdp!=='string'||sdp.length>65536||!['offer','answer'].includes(remote))throw new MusicError('denied');
const sections=[[]];
for(const line of sdp.split(/\r?\n/)){if(line.startsWith('m='))sections.push([]);sections.at(-1).push(line);}
if(sections.length!==2||!sections[1][0].startsWith('m=audio '))throw new MusicError('denied');
const directions=lines=>lines.filter(line=>/^a=(sendrecv|sendonly|recvonly|inactive)$/.test(line));
const session=directions(sections[0]),media=directions(sections[1]);
if(session.length>1||media.length>1)throw new MusicError('denied');
// SDP media attributes override session defaults. Firefox inserts session-level
// sendrecv after ICE gathering even when the sole audio media is recvonly.
const effective=media[0]??session[0]??'a=sendrecv';
const expected=remote==='offer'?'a=recvonly':'a=sendonly';
if(effective!==expected&&effective!=='a=inactive')throw new MusicError('denied');
}
async function gathered(pc){
if(pc.iceGatheringState==='complete')return;
await new Promise((resolve,reject)=>{const timer=setTimeout(()=>{pc.removeEventListener('icegatheringstatechange',check);reject(new MusicError('unavailable'));},5000);const check=()=>{if(pc.iceGatheringState==='complete'){clearTimeout(timer);pc.removeEventListener('icegatheringstatechange',check);resolve();}};pc.addEventListener('icegatheringstatechange',check);check();});
}
export class PeerAudio{
#socket;#userId;#isGM;#peers=new Map();#session=crypto.randomUUID();#stream;#handler;#disconnect;#create;#onStream;#onError; #rejected=0;
#socket;#userId;#isGM;#peers=new Map();#session=crypto.randomUUID();#stream;#handler;#disconnect;#create;#onStream;#onError; #rejected=0; #lastSignalError;
constructor({socket,userId,isGM,isAuthorizedUser=()=>true,onStream=()=>{},onError=()=>{},createPeer=config=>new RTCPeerConnection(config)}){
this.#socket=socket;this.#userId=userId;this.#isGM=isGM;this.authorized=isAuthorizedUser;this.#create=createPeer;this.#onStream=onStream;this.#onError=onError;
this.#handler=frame=>{this.#receive(frame).catch(()=>{this.#rejected++;});};this.#disconnect=()=>this.reset();
this.#handler=frame=>{this.#receive(frame).catch(error=>{this.#rejected++;this.#lastSignalError={code:['denied','stale','unavailable'].includes(error.code)?error.code:'browser-error',name:/^[A-Za-z]{1,40}$/.test(error.name??'')?error.name:undefined,stage:this.#peers.get(frame?.peer)?.stage};});};this.#disconnect=()=>this.reset();
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;}
@@ -47,7 +57,13 @@ export class PeerAudio{
entry.timer=setTimeout(()=>this.revoke(invite.peer),Math.max(1,invite.expires-Date.now()));
pc.ontrack=event=>{if(role!=='listener'||event.track.kind!=='audio'){event.track.stop();return;}this.#onStream(event.streams[0]??new MediaStream([event.track]));};
pc.ondatachannel=event=>event.channel.close();
pc.onconnectionstatechange=()=>{if(['failed','closed'].includes(pc.connectionState)){this.#onError(new MusicError('unavailable'));this.revoke(invite.peer);}};
pc.onconnectionstatechange=()=>{
clearTimeout(entry.disconnectTimer);
if(pc.connectionState==='connected')clearTimeout(entry.handshakeTimer);
if(['failed','closed'].includes(pc.connectionState)){this.#onError(new MusicError('unavailable'));this.revoke(invite.peer);}
else if(pc.connectionState==='disconnected')entry.disconnectTimer=setTimeout(()=>{if(pc.connectionState!=='connected'){this.#onError(new MusicError('unavailable'));this.revoke(invite.peer);}},10000);
};
entry.handshakeTimer=setTimeout(()=>{if(pc.connectionState!=='connected'){this.#onError(new MusicError('unavailable'));this.revoke(invite.peer);}},20000);
this.#peers.set(invite.peer,entry);return entry;
}
async #send(entry,payload){if(this.#peers.get(entry.invite.peer)!==entry)return;const frame=await entry.codec.seal(payload);if(this.#peers.get(entry.invite.peer)!==entry||entry.invite.expires<=Date.now())return;this.#socket.emit('module.adaptive-music',frame);}
@@ -56,25 +72,25 @@ export class PeerAudio{
if(entry.pending>=4||++entry.signals>64)throw new MusicError('denied');entry.pending++;
entry.tail=entry.tail.catch(()=>{}).then(async()=>{
if(entry.role==='gm'&&(!this.#isGM()||!this.authorized(entry.invite.userId)))throw new MusicError('denied');
const payload=await entry.codec.open(frame);
entry.stage='decrypt signal';const payload=await entry.codec.open(frame);entry.stage='validate SDP';
if(payload.type==='bye'){this.revoke(frame.peer);return;}
if(entry.role==='gm'&&payload.type==='offer'){
// The listener's SDP is recvonly: reject video, data, injected outbound audio.
audioOnly(payload.sdp,'answer');
validateAudioSDP(payload.sdp,'offer');
if(!entry.started){entry.pc.addTrack(this.#stream.getAudioTracks()[0],this.#stream);entry.started=true;}
await entry.pc.setRemoteDescription({type:'offer',sdp:payload.sdp});
entry.stage='apply offer';await entry.pc.setRemoteDescription({type:'offer',sdp:payload.sdp});
await entry.pc.setLocalDescription(await entry.pc.createAnswer());await gathered(entry.pc);
await this.#send(entry,{type:'answer',sdp:entry.pc.localDescription.sdp});
entry.stage='send answer';await this.#send(entry,{type:'answer',sdp:entry.pc.localDescription.sdp});
}else if(entry.role==='listener'&&payload.type==='answer'){
audioOnly(payload.sdp,'offer');await entry.pc.setRemoteDescription({type:'answer',sdp:payload.sdp});
validateAudioSDP(payload.sdp,'answer');await entry.pc.setRemoteDescription({type:'answer',sdp:payload.sdp});
}else throw new MusicError('denied');
});return entry.tail.finally(()=>{entry.pending--;});
}
async restart(peer){const entry=this.#peers.get(peer);if(!entry||entry.role!=='listener'||++entry.restarts>2)throw new MusicError('denied');await entry.pc.setLocalDescription(await entry.pc.createOffer({iceRestart:true}));await gathered(entry.pc);await this.#send(entry,{type:'offer',sdp:entry.pc.localDescription.sdp});}
revoke(peer){const entry=this.#peers.get(peer);if(!entry)return;clearTimeout(entry.timer);this.#peers.delete(peer);entry.pc.onconnectionstatechange=null;entry.pc.ontrack=null;entry.pc.close();}
revoke(peer){const entry=this.#peers.get(peer);if(!entry)return;clearTimeout(entry.timer);clearTimeout(entry.handshakeTimer);clearTimeout(entry.disconnectTimer);this.#peers.delete(peer);entry.pc.onconnectionstatechange=null;entry.pc.ontrack=null;entry.pc.close();}
reset(){for(const peer of [...this.#peers.keys()])this.revoke(peer);this.#stream=null;this.#session=crypto.randomUUID();}
close(){this.reset();this.#socket.off('module.adaptive-music',this.#handler);this.#socket.off('disconnect',this.#disconnect);}
reconcile(){for(const [peer,entry]of this.#peers)if(entry.role==='gm'&&(!this.#isGM()||!this.authorized(entry.invite.userId)))this.revoke(peer);}
diagnostics(){return {rejectedSignals:this.#rejected,peers:[...this.#peers.values()].map(e=>({role:e.role,connection:e.pc.connectionState,ice:e.pc.iceConnectionState,signaling:e.pc.signalingState}))};}
diagnostics(){return {rejectedSignals:this.#rejected,lastSignalError:this.#lastSignalError,peers:[...this.#peers.values()].map(e=>({role:e.role,connection:e.pc.connectionState,ice:e.pc.iceConnectionState,signaling:e.pc.signalingState,stage:e.stage}))};}
async stats(){const results=[];for(const entry of this.#peers.values()){const stats=await entry.pc.getStats();for(const item of stats.values())if(['inbound-rtp','outbound-rtp','candidate-pair'].includes(item.type))results.push({type:item.type,bytesSent:item.bytesSent,bytesReceived:item.bytesReceived,jitter:item.jitter,packetsLost:item.packetsLost,audioLevel:item.audioLevel,totalAudioEnergy:item.totalAudioEnergy,totalSamplesReceived:item.totalSamplesReceived,currentRoundTripTime:item.currentRoundTripTime});}return results;}
}
+2 -2
View File
@@ -64,9 +64,9 @@ export class MusicController {
}
ctx.check();
} catch (error) {
// Never restore an obsolete transition. Reconciliation is explicit after stale writes.
// Stale or uncertain writes require explicit reconciliation.
this.current = null;
if (error.code !== 'stale') {
if (error.code !== 'stale' && error.code !== 'uncertain') {
ctx.check();
for (const p of this.dirty) { ctx.check(); await p.stopOwned(ctx); }
if (snapshot) { ctx.check(); await outgoing.restore(snapshot, ctx); this.current = old; }
+7
View File
@@ -0,0 +1,7 @@
// Secrets stay in closure memory across failed attempts and window rerenders.
// Never carry a token to a changed server, including a scheme/port change.
export function connectionDraft(previous,profile,campaign){
let same=false;try{same=new URL(previous?.maUrl).origin===new URL(profile.maUrl).origin;}catch{}
const old=same?previous:{};
return {...old,...profile,token:profile.token||old?.token,identityStorage:profile.identityStorage?.['sendspin-identity-sk']?profile.identityStorage:old?.identityStorage,campaign};
}
+82 -55
View File
@@ -1,63 +1,90 @@
import {validateIceServers} from '../audio/peer-audio.mjs';
import {probeWebSockets,diagnosticMessage} from '../providers/ma/diagnostics.mjs';
const messages={
'insecure-context':'Open Foundry over trusted HTTPS. Remote plain HTTP cannot provide the secure browser APIs required for GM audio.',
'mixed-content':'This Foundry page uses HTTPS. Use a trusted HTTPS Music Assistant address (WSS for /ws and /sendspin). HTTP/ws is blocked.',
'auth-log-review-required':'Confirm that MA raw WebSocket frame logging at VERBOSE is disabled before sending a token.',
'identity-required':'Import the private backup for your existing dedicated Sendspin receiver. Its sendspin-identity-sk is required.',
'identity-mismatch':'The private receiver identity does not match the selected player. Import the matching backup.',
'dedicated-target-required':'The imported identity and dedicated player name do not match a Sendspin target. Check the name and backup; no other player was selected.',
'reconcile-required':'The dedicated queue must be empty and idle before handover. Reconcile it in Music Assistant, then reconnect.',
'catalog-empty':'No authorized music providers were found. Check the MA account’s provider permissions.',
'unsupported':'This browser or queue mode is unsupported. Use HTTPS, Web Locks, Web Audio and WebRTC; disable shuffle, dynamic queues and autoplay.',
'profile-required':'Check the server, authentication and dedicated receiver backup.',
'denied':'Connection denied. Check the private MA token, dedicated target, single active GM and account permissions.',
'stale':'Authority changed. Keep one active GM, stop automation and reconnect.',
'unavailable':'Cannot reach Music Assistant. Check trusted TLS, /ws and /sendspin upgrades, Origin/CSP permissions, private routing and the MA token.'
'ice-config-invalid':'Enter a valid existing STUN/TURN URL. TURN also needs a username, credential and UTC expiry within one hour. No network setting was applied.',
'address-invalid':'Enter the MA server origin, such as https://ma.example.test, without a path or query.',
'ws-upgrade-failed':'The browser could not open the API WebSocket. Run Check browser connection below. If it works from MA’s page only, compare this browser’s local-network permission, private DNS and site restrictions.',
'ws-auth-timeout':'The API socket opened, but authentication did not finish. Check that /ws reaches MA rather than a login portal.',
'ws-auth-denied':'MA rejected the token. Enter a replacement and Authenticate again; the receiver is remembered.',
'ws-disconnected':'The API socket closed. Your private inputs remain in this tab. Retry after checking the private route.',
'ws-command-timeout':'MA did not answer a command before its deadline. Catalog reads have a 10-second limit; stream startup has a 60-second limit. Unconfirmed queue writes stop automation for review.',
'ws-command-failed':'MA rejected a command. The account needs music-provider access and permission to control and pair its dedicated web receiver.',
'sendspin-auth-failed':'The receiver socket opened, but Sendspin authentication failed. Verify the authenticated /sendspin route, separate from /ws.',
'sendspin-sync-failed':'Sendspin did not complete pairing and clock synchronization. Retry the remembered receiver; transport HTTP 101 alone does not prove a working audio receiver.',
'insecure-context':'Open Foundry over trusted HTTPS to use secure browser audio APIs.',
'mixed-content':'HTTPS Foundry requires a trusted HTTPS MA address. Browser security cannot permit an HTTP/ws downgrade.',
'reconcile-required':'This dedicated receiver has an existing queue. Playback was left untouched. Resume the remembered receiver after reviewing its queue in MA, or use a new dedicated receiver.',
'catalog-empty':'No available music providers were returned. Check the dedicated MA account’s music-provider access.',
'unsupported':'This queue or browser feature is unsupported. Use a standalone receiver with a static queue, shuffle and autoplay off, and a browser with Web Locks, Web Audio and WebRTC.',
'private-storage-unavailable':'This browser denied private receiver storage. Allow site storage for Foundry, then retry. No MA token is stored there.',
'private-storage-corrupt':'The remembered receiver could not be decrypted. Use Forget remembered receiver below to create a replacement. Existing MA queues are left untouched.',
'identity-mismatch':'The remembered receiver identity does not match this connection. Forget that receiver to create a new campaign receiver.',
'dedicated-target-required':'The receiver did not match the identity and name created for this campaign. No unrelated player was selected.',
'receiver-queue-unavailable':'MA did not make this receiver’s queue available after connection. Retry connecting the remembered receiver.',
'denied':'The dedicated receiver, account permission or active GM check failed. Keep one active GM and verify that this account can control its campaign receiver.',
'stale':'GM authority or the connection changed during setup. Keep one active GM, then retry.',
'uncertain':'MA did not confirm a queue write. Automation stopped to avoid duplicate playback. Review this dedicated queue before reconnecting.',
'unavailable':'The operation failed. Your private inputs are retained. Run the browser connection check to separate transport failures from receiver and audio setup.'
};
export const connectionMessage=error=>messages[error?.code]??messages.unavailable;
export const connectionMessage=error=>error?.upstreamCode===2&&['player_queues/play_media','player_queues/play_index'].includes(error.command)?'MA could not find playable media for this playlist (MA error 2). Check its content/provider in MA or choose another playlist. Automation stopped; an unconfirmed queue write is never retried.':messages[error?.code]??messages.unavailable;
export function mountConnectionWizard({game,container,connection,onCatalog=()=>{},onError=()=>{}}){
const dom=container.ownerDocument,panel=dom.createElement('fieldset');
const legend=dom.createElement('legend');legend.textContent='1. Connect Music Assistant';panel.append(legend);
const note=dom.createElement('p');note.textContent='Optional. Authentication stays in this GM tab’s memory; reconnect after reload. Trust every module running in this browser.';panel.append(note);
const heading=dom.createElement('p');heading.setAttribute('role','status');panel.append(heading);
const steps=Array.from({length:3},()=>{const step=dom.createElement('div');step.className='adaptive-music-step';panel.append(step);return step;});
const go=index=>{steps.forEach((step,i)=>{step.hidden=i!==index;});heading.textContent=['Step 1 of 3: Server and private authentication','Step 2 of 3: Dedicated receiver','Step 3 of 3: Connect campaign audio'][index];};
const dom=container.ownerDocument,panel=dom.createElement('fieldset'),legend=dom.createElement('legend');legend.textContent='1. Music Assistant';panel.append(legend);
const note=dom.createElement('p');note.textContent='Enter your server and access token. A dedicated campaign receiver is created and paired automatically. The token stays in this GM tab; its receiver identity is remembered privately in this browser.';panel.append(note);
const status=dom.createElement('p');status.setAttribute('role','status');panel.append(status);
const steps=Array.from({length:2},()=>{const step=dom.createElement('div');step.className='adaptive-music-step';panel.append(step);return step;});
const go=index=>steps.forEach((step,i)=>{step.hidden=i!==index;});
const field=(parent,label,type='text')=>{const l=dom.createElement('label');l.textContent=label;const input=dom.createElement('input');input.type=type;input.autocomplete='off';input.spellcheck=false;l.append(input);parent.append(l);return input;};
const button=(parent,label,action)=>{const b=dom.createElement('button');b.type='button';b.textContent=label;b.addEventListener('click',async()=>{b.disabled=true;try{if(!game.user.isGM)throw {code:'denied'};await action();}catch(error){status.textContent=connectionMessage(error);onError();}finally{b.disabled=false;show();}});parent.append(b);return b;};
const address=field(steps[0],'Music Assistant server address','url');address.placeholder='https://ma.example.test';
const button=(parent,label,action)=>{const b=dom.createElement('button');b.type='button';b.textContent=label;b.addEventListener('click',async()=>{b.disabled=true;try{if(!game.user.isGM)throw {code:'denied'};await action();}catch(error){status.textContent=connectionMessage(error);onError(error);}finally{b.disabled=false;show();}});parent.append(b);return b;};
const draft=connection.draftFields??{},address=field(steps[0],'Music Assistant server address','url');address.placeholder='https://ma.example.test';address.value=draft.maUrl??'';
const token=field(steps[0],'Private GM access token','password');
const logs=field(steps[0],'I checked MA logging: raw WebSocket frames at VERBOSE are disabled','checkbox');
const logNote=dom.createElement('p');logNote.textContent='Review server logging before sending a token. See connection requirements below. Native music works without Music Assistant.';steps[0].append(logNote);
button(steps[0],'Next: dedicated receiver',()=>{if(!address.value.trim()||!logs.checked)throw {code:'profile-required'};go(1);status.textContent='Import the existing dedicated receiver backup, then test the connection.';});
const name=field(steps[1],'Dedicated receiver name');name.value='Adaptive Music DEV';
const backup=field(steps[1],'Private receiver backup (.json)','file');backup.accept='.json,application/json';
const backupNote=dom.createElement('p');backupNote.textContent='Import the existing Sendspin identity and pairing backup. Only that receiver is eligible; no new receiver is registered. Keep this file private.';steps[1].append(backupNote);
const owned=field(steps[1],'I own this dedicated campaign receiver','checkbox');
const playback=field(steps[1],'Allow scene automation to play my catalog playlists on this receiver','checkbox');
button(steps[1],'Back: server',()=>go(0));
button(steps[1],'Test connection and load playlists',async()=>{
connect.disabled=true;
if(!owned.checked||!logs.checked)throw {code:'denied'};
let imported={};
try{const file=backup.files?.[0];if(file){if(file.size>65536)throw Error();imported=JSON.parse(await file.text());}}catch{throw {code:'identity-required'};}
const profile={...imported,maUrl:address.value.trim(),token:token.value,identityStorage:imported.identityStorage??imported,targetName:name.value.trim(),webSocketAuthLogSafe:true,allowCatalogPlayback:playback.checked};
token.value='';backup.value='';
const result=await connection.test(profile);setTarget(result.target,result.targetName);
connect.disabled=false;go(2);status.textContent='Authenticated; dedicated player and catalog verified. Select Connect audio to start the GM receiver.';await onCatalog();
const advanced=dom.createElement('details'),summary=dom.createElement('summary');summary.textContent='Receiver options';advanced.append(summary);steps[0].append(advanced);
const name=field(advanced,'Dedicated receiver name');name.value=draft.targetName??'Adaptive Music '+(game.world?.title??'campaign');
const iceURL=field(advanced,'Existing ICE server URL (optional)');iceURL.placeholder='stun:stun.example.test:3478';
const iceUsername=field(advanced,'TURN username (if required)'),iceCredential=field(advanced,'Short-lived TURN credential','password'),iceExpiry=field(advanced,'TURN credential expiry (UTC)','datetime-local');
const networkNote=dom.createElement('p');networkNote.textContent='Direct connections use no external ICE service. For remote players, you may supply an existing STUN/TURN service. TURN credentials must expire within one hour; no service is installed.';advanced.append(networkNote);
const logging=dom.createElement('p');logging.textContent='Keep MA raw-frame VERBOSE logging disabled: it can record authentication frames. No server logging settings are changed by this module.';advanced.append(logging);
button(steps[0],'Authenticate',async()=>{
if(!address.value.trim())throw {code:'address-invalid'};status.textContent='Authenticating with Music Assistant…';
const network={};
if(iceURL.value.trim()){
const server={urls:iceURL.value.trim()};
if(/^turns?:/.test(server.urls)){server.username=iceUsername.value.trim();server.credential=iceCredential.value;server.expires=Date.parse(iceExpiry.value+'Z');}
try{validateIceServers([server]);}catch{throw {code:'ice-config-invalid'};}network.listenerNetwork={iceServers:[server]};
}
let result;try{result=await connection.test({maUrl:address.value.trim(),token:token.value,targetName:name.value.trim(),allowCatalogPlayback:true,webSocketAuthLogSafe:true,...network});}
finally{if(connection.status.hasPrivateDraft){token.value='';}}
token.value='';setTarget(result.target,result.targetName);go(1);connect.disabled=false;
status.textContent='Authenticated. Connect this dedicated campaign receiver to pair it and load your playlists.';
});
const target=dom.createElement('select'),targetLabel=dom.createElement('label');targetLabel.textContent='Dedicated player';target.disabled=true;targetLabel.append(target);steps[2].append(targetLabel);
const setTarget=(id,name)=>{target.replaceChildren();const option=dom.createElement('option');option.value=id;option.textContent=name;target.append(option);target.value=id;target.disabled=false;};
const diagnostics=dom.createElement('p');diagnostics.setAttribute('role','status');steps[2].append(diagnostics);
const show=()=>{const d=connection.status;if(d.state==='connected')connect.disabled=true;diagnostics.textContent=`Connection: ${d.state}. Catalog: ${d.catalog} items. GM audio: ${d.audioContext}. ${d.catalogPlayback?'Catalog playback enabled.':'Catalog playback disabled.'} ${d.peers??0} listener connections.`;};
const connect=button(steps[2],'Connect audio',async()=>{
// Call before the first await to retain the browser activation gesture.
const pending=connection.connect(target.value);await pending;status.textContent='GM audio connected. Active players connect automatically; a browser may ask them to Enable Audio once.';await onCatalog();
});connect.disabled=true;
button(steps[2],'Refresh catalog and diagnostics',async()=>{await connection.refresh();await onCatalog();status.textContent='Catalog and target checks refreshed.';});
button(steps[2],'Enable GM audio',()=>connection.resume());
button(steps[2],'Back: receiver',()=>go(1));
button(steps[2],'Disconnect Music Assistant',async()=>{await connection.disconnect();token.value='';backup.value='';target.replaceChildren();connect.disabled=true;go(0);status.textContent='Disconnected. Automation is stopped; existing remote queue state is retained for review.';await onCatalog();});
const help=dom.createElement('a');help.href='modules/adaptive-music/INSTALL.md';help.target='_blank';help.rel='noopener';help.textContent='Connection requirements and troubleshooting';panel.append(help);
const d=connection.status;if(d.selectedTarget){setTarget(d.selectedTarget,d.selectedName);connect.disabled=d.state==='connected';go(2);}else go(0);
show();container.append(panel);return panel;
const target=dom.createElement('select'),label=dom.createElement('label');label.textContent='Dedicated campaign receiver';label.append(target);steps[1].append(label);
const setTarget=(id,name)=>{target.replaceChildren();const option=dom.createElement('option');option.value=id;option.textContent=name;target.append(option);target.value=id;};
const connect=button(steps[1],'Connect audio',async()=>{
status.textContent='Connecting and pairing the dedicated receiver…';
const result=await connection.connect(target.value);await onCatalog();status.textContent=result?.attachedExistingQueue?'Campaign audio reconnected. The existing queue was preserved. Apply the automation setting below when ready to resume scene control.':'Campaign audio connected. Assign ambient and combat playlists below, then enable automation. Players connect automatically.';
});
button(steps[1],'Enable GM audio',()=>connection.resume());
const volume=field(steps[1],'Campaign volume','range');volume.min='0';volume.max='100';volume.value=String(connection.status.volume??100);volume.addEventListener('change',()=>{try{connection.setVolume?.(Number(volume.value));}catch(error){status.textContent=connectionMessage(error);onError(error);}});
button(steps[1],'Refresh playlists',async()=>{await connection.refresh();await onCatalog();status.textContent='Playlists refreshed.';});
button(steps[1],'Back to authentication',()=>go(0));
const diagnostics=dom.createElement('p');diagnostics.setAttribute('role','status');panel.append(diagnostics);
const report=dom.createElement('div');report.setAttribute('aria-live','polite');panel.append(report);let transportResults=[];
button(panel,'Check browser connection (no MA token)',async()=>{
report.replaceChildren();status.textContent='Checking both WebSocket routes from this Foundry page…';
try{transportResults=await probeWebSockets(address.value.trim());}catch(error){throw error?.code?error:{code:'address-invalid'};}
for(const result of transportResults){const line=dom.createElement('p');line.textContent=result.path+': '+diagnosticMessage(result);report.append(line);}
status.textContent='Browser checks complete. No MA token was sent. An open socket still needs authentication, pairing and clock synchronization.';
});
button(panel,'Copy connection diagnostics',async()=>{
const d=connection.status;const text=JSON.stringify({state:d.state,stage:d.stage,catalog:d.catalog,audioContext:d.audioContext,decodedFrames:d.decodedFrames,scheduledFrames:d.scheduledFrames,droppedLate:d.droppedLate,droppedAhead:d.droppedAhead,muted:d.muted,pauseMode:d.pauseMode,signalRMS:d.rms,listenerConnections:d.peers??0,lastError:d.lastError,listenerDiagnostics:d.listenerDiagnostics,transport:transportResults,secureContext:globalThis.isSecureContext},null,2);
await navigator.clipboard.writeText(text);status.textContent='Diagnostics copied. The report excludes the address, token, receiver identity and catalog titles.';
});
button(panel,'Disconnect Music Assistant',async()=>{await connection.disconnect();token.value='';iceCredential.value='';target.replaceChildren();go(0);status.textContent='Disconnected. The token was forgotten; this browser remembers its campaign receiver.';await onCatalog();});
const recovery=dom.createElement('details'),recoveryTitle=dom.createElement('summary');recoveryTitle.textContent='Connection recovery';recovery.append(recoveryTitle);panel.append(recovery);
button(recovery,'Reconnect remembered receiver',async()=>{await connection.reconnect();await onCatalog();status.textContent='Receiver reconnected using retained private inputs. The queue was preserved and automation is paused. Review it, then Apply automation setting when ready.';});
button(recovery,'Forget remembered receiver',async()=>{await (connection.forgetReceiver?.()??connection.disconnect());token.value='';iceCredential.value='';target.replaceChildren();go(0);status.textContent='Local receiver identity forgotten. Reauthenticate to provision a new receiver. Existing MA queues were left untouched.';await onCatalog();});
const show=()=>{const d=connection.status;volume.disabled=d.state!=='connected';if(d.hasPrivateDraft)token.placeholder='Retained in this tab; leave blank to retry';connect.disabled=d.state==='connected'||d.state==='connecting';diagnostics.textContent=`${d.state}. ${d.stage??''} Playlists: ${d.catalog??0}. GM audio: ${d.audioContext??'closed'}. Decoded frames: ${d.decodedFrames??0}. Connected listeners: ${d.peers??0}.`;};
const d=connection.status;if(d.selectedTarget){setTarget(d.selectedTarget,d.selectedName);go(1);}else go(0);show();container.append(panel);
// Refresh while the actual ApplicationV2 window is mounted; no secret-bearing events.
if(globalThis.document===dom&&typeof panel.isConnected==='boolean'){const timer=setInterval(()=>{if(!panel.isConnected){clearInterval(timer);return;}show();},1000);}
return panel;
}
+28 -7
View File
@@ -1,3 +1,6 @@
import {connectionMessage} from './connection-wizard.mjs';
import {ReceiverVault} from './receiver-vault.mjs';
import {connectionDraft} from './connection-draft.mjs';
import {startNativeRuntime,primaryGM} from './runtime.mjs';
import {startConfigurationInterfaces,mountPlaylistConfiguration} from './configuration.mjs';
import {GatewayClient} from '../providers/ma/remote.mjs';
@@ -7,11 +10,13 @@ import {PeerAudio} from '../audio/peer-audio.mjs';
import {ListenerAudio} from './listener-audio.mjs';
import {createSetupClass,createListenerClass} from './setup.mjs';
const id='adaptive-music';
let runtime,interfaces,gateway,audio,renewTimer,gmHost,peers,remoteAudio;let authorityHooks=[];let bootstrap,privateProfile,inviteTimer,latestInvite,listenerStopped=false,listenerState='Waiting for GM audio.',inviteTail=Promise.resolve();const sentInvites=new Map();let connectionGeneration=0;let listenerContext,listenerSource;
const receiverVault=new ReceiverVault();
const receiverScope=profile=>({campaign:game.world.id,userId:game.user.id,maUrl:profile.maUrl});
let runtime,interfaces,gateway,audio,renewTimer,gmHost,peers,remoteAudio;let authorityHooks=[];let bootstrap,privateProfile,privateDraft,inviteTimer,latestInvite,listenerStopped=false,listenerState='Waiting for GM audio.',inviteTail=Promise.resolve();const sentInvites=new Map();let connectionGeneration=0,connectionTesting=false;let listenerContext,listenerSource;
const gmAuthority=()=>game.ready&&game.user.isGM&&primaryGM(game.users)===game.user.id&&[...game.users].filter(u=>u.active&&u.isGM).length===1&&game.socket?.connected===true;
const owned=()=>game.settings.get(id,'ownedPlaylistIds').split(',').map(s=>s.trim()).filter(Boolean);
const choices=async()=>[...[...game.playlists].filter(p=>owned().includes(p.id)).map(p=>({provider:'native',id:p.id,name:p.name})),...(gmHost?.catalog.length?gmHost.catalog.filter(c=>c.kind==='playlist'||c.kind==='sequence'):gateway?.catalog??[])];
const onError=()=>ui.notifications.warn('Adaptive Music could not complete the operation. Open Adaptive Music setup for connection diagnostics and ownership checks.');
const onError=error=>{if(error?.code==='uncertain')stop();ui.notifications.warn('Adaptive Music: '+connectionMessage(error));};
function start(){
if(!game.user.isGM||runtime)return;
runtime=startNativeRuntime({game,Hooks,campaign:game.world.id,session:gmHost?.connected?gmHost.session:globalThis.crypto.randomUUID(),ownedPlaylistIds:owned(),maProvider:gmHost?.connected?gmHost:gateway,onError});
@@ -33,11 +38,27 @@ function sendInvites(){
});return inviteTail;
}
const connection={
get status(){return {...(gmHost?.status??{state:'disconnected',catalog:0,audioContext:'closed'}),selectedTarget:privateProfile?.target,selectedName:privateProfile?.targetName,peers:peers?.diagnostics().peers.filter(p=>p.connection==='connected').length??0};},
async test(profile){if(gmHost.connected||gmHost.status.state==='connecting'||gateway.connected)throw {code:'denied'};stop();const generation=++connectionGeneration;const old=privateProfile;privateProfile=null;await gmHost.close();const candidate={...old,...profile,token:profile.token||old?.token,identityStorage:profile.identityStorage?.['sendspin-identity-sk']?profile.identityStorage:old?.identityStorage,campaign:game.world.id};const result=await gmHost.inspect(candidate);await gmHost.readCatalog(result,{reconnecting:true});if(generation!==connectionGeneration)throw {code:'stale'};privateProfile=result;return {target:result.target,targetName:result.targetName};},
async connect(target){if(!privateProfile||target!==privateProfile.target||gateway.connected)throw {code:'denied'};stop();const pending=gmHost.start(privateProfile);await pending;peers.setSource(gmHost.stream);sentInvites.clear();await sendInvites();if(game.settings.get(id,'enabled'))start();},
refresh:()=>gmHost.refreshCatalog(),resume:()=>gmHost.resumeAudio(),
async disconnect(){connectionGeneration++;stop();peers?.reset();sentInvites.clear();privateProfile=null;await gmHost.close();}
get draftFields(){return privateDraft?{maUrl:privateDraft.maUrl,targetName:privateDraft.targetName,webSocketAuthLogSafe:privateDraft.webSocketAuthLogSafe,allowCatalogPlayback:privateDraft.allowCatalogPlayback}:{};},
get status(){return {...(gmHost?.status??{state:'disconnected',catalog:0,audioContext:'closed'}),hasPrivateDraft:!!privateDraft,selectedTarget:privateProfile?.target,selectedName:privateProfile?.targetName,listenerDiagnostics:peers?.diagnostics(),peers:peers?.diagnostics().peers.filter(p=>p.connection==='connected').length??0};},
async test(profile){
if(connectionTesting||gmHost.connected||gmHost.status.state==='connecting'||gateway.connected)throw {code:'denied'};
connectionTesting=true;stop();const generation=++connectionGeneration;privateProfile=null;
const check=()=>{if(generation!==connectionGeneration)throw {code:'stale'};};
try{
await gmHost.close();check();
const candidate=connectionDraft(privateDraft,profile,game.world.id);privateDraft=candidate;
if(!candidate.identityStorage?.['sendspin-identity-sk'])Object.assign(candidate,await receiverVault.load(receiverScope(candidate))??{});check();
candidate.targetName??='Adaptive Music '+game.world.title;candidate.allowCatalogPlayback=true;
const result=await gmHost.prepare(candidate);check();
await receiverVault.save(receiverScope(result),result);check();
privateProfile=result;privateDraft=result;return {target:result.target,targetName:result.targetName};
}finally{connectionTesting=false;}
},
async connect(target,{resumeAutomation=true}={}){if(!privateProfile||target!==privateProfile.target||gateway.connected)throw {code:'denied'};stop();const pending=gmHost.start(privateProfile);let result;try{result=await pending;}finally{if(privateProfile)await receiverVault.save(receiverScope(privateProfile),privateProfile);}peers.setSource(gmHost.stream);sentInvites.clear();await sendInvites();if(resumeAutomation&&game.settings.get(id,'enabled')&&!result.attachedExistingQueue)start();return result;},
async reconnect(){if(!privateProfile||!gmAuthority())throw {code:'denied'};const generation=++connectionGeneration;stop();peers?.reset();sentInvites.clear();await gmHost.close();if(generation!==connectionGeneration)throw {code:'stale'};return connection.connect(privateProfile.target,{resumeAutomation:false});},
refresh:()=>gmHost.refreshCatalog(),resume:()=>gmHost.resumeAudio(),setVolume:value=>gmHost.setVolume(value),
async forgetReceiver(){if(privateDraft){const scope=receiverScope(privateDraft);await connection.disconnect();await receiverVault.forget(scope);}},
async disconnect(){connectionGeneration++;stop();peers?.reset();sentInvites.clear();privateProfile=null;privateDraft=null;await gmHost.close();}
};
function listenWebRTC(invite){
if(game.user.isGM||!peers)throw Error('Listener only');
+42
View File
@@ -0,0 +1,42 @@
import {MusicError} from '../core/controller.mjs';
// GM browser profile only. A non-extractable key protects the stored receiver
// material; same-origin scripts and the browser profile owner remain trusted.
// MA access tokens are intentionally excluded from the serialization surface.
export class ReceiverVault{
#database;#tail=Promise.resolve();
async #db(){
if(!globalThis.indexedDB)throw new MusicError('private-storage-unavailable');
this.#database??=new Promise((resolve,reject)=>{const request=indexedDB.open('adaptive-music-private-receivers',1);request.onupgradeneeded=()=>request.result.createObjectStore('records');request.onsuccess=()=>resolve(request.result);request.onerror=()=>reject(new MusicError('private-storage-unavailable'));request.onblocked=()=>reject(new MusicError('private-storage-unavailable'));});
return this.#database;
}
async #scope({campaign,userId,maUrl}){
if(!campaign||!userId)throw new MusicError('denied');
return Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',new TextEncoder().encode(JSON.stringify([campaign,userId,new URL(maUrl).origin])))),n=>n.toString(16).padStart(2,'0')).join('');
}
async #transaction(key,value,remove=false){
const db=await this.#db();return new Promise((resolve,reject)=>{
const tx=db.transaction('records',value!==undefined||remove?'readwrite':'readonly'),store=tx.objectStore('records');
const request=remove?store.delete(key):value!==undefined?store.put(value,key):store.get(key);
tx.oncomplete=()=>resolve(request.result);tx.onerror=tx.onabort=()=>reject(new MusicError('private-storage-unavailable'));
});
}
async load(scope){
const id=await this.#scope(scope),record=await this.#transaction(id);if(!record)return null;
try{
const bytes=await crypto.subtle.decrypt({name:'AES-GCM',iv:record.iv,additionalData:new TextEncoder().encode(id)},record.key,record.data);
const value=JSON.parse(new TextDecoder().decode(bytes));
if(value.version!==1||typeof value.identityStorage?.['sendspin-identity-sk']!=='string')throw Error();return value;
}catch{throw new MusicError('private-storage-corrupt');}
}
save(scope,profile){
const op=this.#tail.catch(()=>{}).then(async()=>{
const id=await this.#scope(scope),old=await this.#transaction(id);
const key=old?.key??await crypto.subtle.generateKey({name:'AES-GCM',length:256},false,['encrypt','decrypt']);
const value={version:1,identityStorage:profile.identityStorage,targetName:profile.targetName,catalogKey:profile.catalogKey,namespace:profile.namespace};
const bytes=new TextEncoder().encode(JSON.stringify(value));if(bytes.length>65536||!value.identityStorage?.['sendspin-identity-sk'])throw new MusicError('denied');
const iv=crypto.getRandomValues(new Uint8Array(12)),data=await crypto.subtle.encrypt({name:'AES-GCM',iv,additionalData:new TextEncoder().encode(id)},key,bytes);
await this.#transaction(id,{key,iv,data});
});this.#tail=op;return op;
}
async forget(scope){await this.#tail.catch(()=>{});await this.#transaction(await this.#scope(scope),undefined,true);}
}
+28 -10
View File
@@ -2,7 +2,7 @@ import {randomKey,hmac,base64url} from './webcrypto.mjs';
import { MusicError } from '../../core/controller.mjs';
// Shared trusted-GM/optional-companion transport. Never construct with MA credentials on a player client.
export class MAReadClient {
#base; #token; #target; #fetch; #providers; #catalog = new Map(); #catalogKey; #campaign; #expectedName; #expectedProvider; #writes = Promise.resolve(); #synthetic; #uncertain = false; #authorizedMedia = new Set(); #targetVolume;
#base; #token; #target; #fetch; #providers; #catalog = new Map(); #catalogKey; #campaign; #expectedName; #expectedProvider; #writes = Promise.resolve(); #synthetic; #uncertain; #authorizedMedia = new Set(); #targetVolume; #nativePause;
constructor({ baseUrl, token, target, approvedProviders = [], catalogKey = randomKey(), campaign = 'default', expectedName, expectedProvider, syntheticSequences = {}, fetchImpl = fetch }) {
const url = new URL(baseUrl);
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password ||
@@ -21,7 +21,7 @@ export class MAReadClient {
async #read(command, args, messageId = 'adaptive-music-read') {
try {
const response = await this.#fetch(`${this.#base}/api`, { method: 'POST', redirect: 'error',
signal: AbortSignal.timeout(5000), headers: { Authorization: `Bearer ${this.#token}`, 'Content-Type': 'application/json' },
signal: AbortSignal.timeout(['player_queues/play_media','player_queues/play_index'].includes(command)?60000:10000), headers: { Authorization: `Bearer ${this.#token}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ message_id: messageId, command, args }) });
if (!response.ok) throw new MusicError(response.status === 403 ? 'denied' : 'unavailable');
const reader = response.body?.getReader();
@@ -39,18 +39,29 @@ export class MAReadClient {
const body = new TextDecoder().decode(bytes);
return body ? JSON.parse(body) : null;
} catch (error) {
throw new MusicError(error instanceof MusicError ? error.code : 'unavailable');
if(error instanceof MusicError)throw error;throw new MusicError('unavailable');
}
}
async getOwnedQueue(target) {
async getOwnedQueue(target, {checkRegistration} = {}) {
if (target !== this.#target) throw new MusicError('denied');
const queue = await this.#read('player_queues/get', { queue_id: this.#target });
const args = {queue_id: this.#target};
let queue = await this.#read('player_queues/get', args);
if (checkRegistration && queue === null) {
// MA publishes the player before its saved queue finishes loading.
const deadline = performance.now() + 5000;
while (queue === null && performance.now() < deadline) {
await new Promise(resolve => setTimeout(resolve, 250));
checkRegistration();
queue = await this.#read('player_queues/get', args);
}
if (queue === null) throw new MusicError('receiver-queue-unavailable');
}
if (queue?.queue_id !== this.#target || queue.active !== true) throw new MusicError('denied');
return { state: queue.state, items: queue.items };
}
async verifyTarget({allowUnavailable=false}={}) {
async verifyTarget({allowUnavailable=false,checkRegistration}={}) {
if(!allowUnavailable && this.#expectedName && this.#expectedProvider){
await this.getOwnedQueue(this.#target);
await this.getOwnedQueue(this.#target,{checkRegistration});
const active=await this.#read('player_queues/get_active_queue',{player_id:this.#target});
if(active?.queue_id!==this.#target)throw new MusicError('denied');
}
@@ -61,9 +72,11 @@ export class MAReadClient {
!player.provider?.startsWith('sendspin') || player.active_group || player.synced_to ||
['group_members','group_childs','static_group_members'].some(k => !Array.isArray(player[k]) || player[k].some(id => id !== this.#target))) throw new MusicError('denied');
if(!allowUnavailable&&(!this.#expectedName || !this.#expectedProvider))await this.getOwnedQueue(this.#target);
this.#nativePause=Array.isArray(player.supported_features)?player.supported_features.includes('pause'):undefined;
this.#targetVolume=Number.isFinite(player.volume_level)&&typeof player.volume_muted==='boolean'?{volume:Math.min(100,Math.max(0,player.volume_level)),muted:player.volume_muted}:null;
return { dedicated: true, available: player.available===true, standalone: true };
}
supportsNativePause(){return this.#nativePause;}
targetVolumeState(){if(!this.#targetVolume)throw new MusicError('unsupported');return {...this.#targetVolume};}
async catalog() {
if (!this.#providers.length) throw new MusicError('denied');
@@ -166,13 +179,18 @@ export class MAReadClient {
const captured = structuredClone(args);
const operation = this.#writes.catch(() => {}).then(async () => {
ctx.check();
if(this.#uncertain)throw new MusicError('uncertain');
if(this.#uncertain)throw this.#uncertain;
const queue = await this.queueState();
if (queue.is_dynamic !== false || queue.autoplay_enabled !== false || queue.dont_stop_the_music_enabled !== false || queue.overlay_enabled !== false || queue.playback_speed !== 1) throw new MusicError('unsupported');
await this.verifyTarget();
ctx.check(); // Recheck authority after all reads, immediately before dispatch.
try{await this.#read(`player_queues/${action}`, {...captured,queue_id:this.#target},`adaptive-music-write-${crypto.randomUUID()}`);}
catch{this.#uncertain=true;throw new MusicError('uncertain');}
const command = `player_queues/${action}`;
try{await this.#read(command, {...captured,queue_id:this.#target},`adaptive-music-write-${crypto.randomUUID()}`);}
catch(error){
const failure=new MusicError('uncertain');
failure.command=command;failure.upstreamCode=error.upstreamCode;failure.translationKey=error.translationKey;
this.#uncertain=failure;throw failure;
}
ctx.check();
});
this.#writes = operation;
+27
View File
@@ -0,0 +1,27 @@
// Token-free transport checks. Browser WebSocket APIs intentionally hide HTTP/TLS
// failure details; never turn an opaque failure into a claimed root cause.
export async function probeWebSockets(baseUrl,{createSocket=url=>new WebSocket(url),events=globalThis.document,timeoutMs=5000}={}){
const base=new URL(baseUrl);
if(base.username||base.password||base.search||base.hash||base.pathname!=='/'||!['https:','http:'].includes(base.protocol))throw {code:'address-invalid'};
if(globalThis.location?.protocol==='https:'&&base.protocol!=='https:')throw {code:'mixed-content'};
const results=[];
// Sequential, bounded and deliberately unauthenticated. No player or queue commands.
for(const path of ['/ws','/sendspin']){
const url=new URL(path,base);url.protocol=base.protocol==='https:'?'wss:':'ws:';
results.push(await new Promise(resolve=>{
let socket,timer,done=false,csp=false;
const finish=code=>{if(done)return;done=true;clearTimeout(timer);events?.removeEventListener('securitypolicyviolation',policy);if(socket){socket.onopen=socket.onerror=socket.onclose=null;socket.close();}resolve({path,code});};
const policy=event=>{if(event.disposition==='enforce'&&['connect-src','default-src'].includes(event.effectiveDirective)&&event.blockedURI===url.href){csp=true;finish('csp-blocked');}};
events?.addEventListener('securitypolicyviolation',policy);
timer=setTimeout(()=>finish(csp?'csp-blocked':'upgrade-timeout'),timeoutMs);
try{socket=createSocket(url.href);socket.onopen=()=>finish('upgrade-ok');socket.onerror=()=>setTimeout(()=>finish(csp?'csp-blocked':'upgrade-failed'),25);socket.onclose=()=>setTimeout(()=>finish(csp?'csp-blocked':'upgrade-failed'),25);}catch{setTimeout(()=>finish(csp?'csp-blocked':'upgrade-failed'),50);}
}));
}
return results;
}
export const diagnosticMessage=result=>({
'upgrade-ok':'WebSocket upgrade succeeded from this page. Authentication, receiver pairing and audio are still untested.',
'csp-blocked':'This page’s enforced Content Security Policy blocked the connection. Ask the Foundry host administrator to allow the exact trusted MA WSS origin in connect-src; retain existing policy restrictions.',
'upgrade-timeout':'No WebSocket upgrade within 5 seconds. Check the private route and compare from the MA page. Browser APIs cannot identify DNS, TLS or firewall causes.',
'upgrade-failed':'The browser did not expose a successful upgrade. Compare the same check from the MA origin. Check the exact Origin at the reverse proxy and page policy. HTTP status and TLS errors are hidden by browsers; 101 from another client does not prove this path works.'
}[result.code]??'Diagnostic unavailable.');
+20 -8
View File
@@ -2,7 +2,7 @@ import {hmac,hex,verifyHmac} from './webcrypto.mjs';
import { MusicError } from '../../core/controller.mjs';
const identity = items => JSON.stringify(items.map(i => i.queue_item_id));
export class MAPlaybackProvider {
#client; #campaign; #session; #fence; #authority; #key; #generation = 0; #prepared = new WeakMap(); #operations = new Map(); #epoch = 0;
#client; #campaign; #session; #fence; #authority; #key; #generation = 0; #prepared = new WeakMap(); #operations = new Map(); #epoch = 0; #paused;
constructor({ client, campaign, session, fence, authority, snapshotKey }) {
if (!campaign || !session || !Number.isSafeInteger(fence) || fence < 1 || typeof authority !== 'function' || snapshotKey?.length !== 32) throw new MusicError('denied');
this.#client=client; this.#campaign=campaign; this.#session=session; this.#fence=fence; this.#authority=authority; this.#key=Uint8Array.from(snapshotKey);
@@ -39,9 +39,11 @@ export class MAPlaybackProvider {
const position=Math.floor(elapsed ?? 0);
if (!Number.isSafeInteger(position) || position<0 || (position>0 && !(items[after.current_index]?.duration>position))) throw new MusicError('unsupported');
this.#check(ctx);
return {version:1,campaign:this.#campaign,session:this.#session,fence:this.#fence,generation:ctx.generation,expires:Date.now()+300000,
const value={version:1,campaign:this.#campaign,session:this.#session,fence:this.#fence,generation:ctx.generation,expires:Date.now()+43200000,
state:after.state,repeat:after.repeat_mode,shuffle:false,index:after.current_index,position,
items:items.map(item=>({uri:this.#client.mediaURI(item),duration:item.duration ?? 0}))};
if(this.#paused){if(value.state!=='idle'||JSON.stringify(value.items)!==JSON.stringify(this.#paused.items))throw new MusicError('stale');return {...value,state:'paused',index:this.#paused.index,position:this.#paused.position};}
return value;
}
async #sign(value) { return hex(await hmac(this.#key,'snapshot-v1\0'+JSON.stringify(value))); }
async snapshot(ctx) { const value=await this.#capture(ctx);return {value,signature:await this.#sign(value)}; }
@@ -49,15 +51,25 @@ export class MAPlaybackProvider {
this.#check(ctx);if(!this.#prepared.has(prepared))throw new MusicError('denied');
const media=this.#prepared.get(prepared);
return this.#once(ctx,`apply:${JSON.stringify(media)}`,async()=>{
await this.#client.mutate('play_media',{media,option:'replace',shuffle:false},this.#context(ctx));this.#epoch++;
this.#paused=undefined;await this.#client.mutate('play_media',{media,option:'replace',shuffle:false},this.#context(ctx));this.#epoch++;
});
}
async stopOwned(ctx) { return this.#once(ctx,`stop:${this.#epoch}`,()=>this.#client.mutate('stop',{},this.#context(ctx))); }
async stopOwned(ctx) { return this.#once(ctx,`stop:${this.#epoch}`,()=>{this.#paused=undefined;return this.#client.mutate('stop',{},this.#context(ctx));}); }
async control(action,value,ctx) {
this.#check(ctx);
const args={pause:{},resume:{},stop:{},seek:{position:value},shuffle:{shuffle_enabled:value},repeat:{repeat_mode:value}};
if(!Object.hasOwn(args,action))throw new MusicError('denied');
return this.#once(ctx,`control:${action}:${JSON.stringify(value)}`,async()=>{await this.#client.mutate(action,args[action],this.#context(ctx));this.#epoch++;});
return this.#once(ctx,`control:${action}:${JSON.stringify(value)}`,async()=>{
if(action==='pause'&&this.#client.supportsNativePause?.()===false){
const captured=await this.#capture(ctx);if(!captured.items.length)return;
await this.#client.mutate('stop',{},this.#context(ctx));this.#paused=captured;
}else if(action==='resume'&&this.#paused){
const captured=await this.#capture(ctx);await this.#client.mutate('play_index',{index:captured.index,seek_position:captured.position},this.#context(ctx));this.#paused=undefined;
}else if(action==='seek'&&this.#paused){
const captured=await this.#capture(ctx);if(!Number.isSafeInteger(value)||value<0||!(captured.items[captured.index]?.duration>value))throw new MusicError('unsupported');this.#paused={...captured,position:value};
}else{if(action==='stop')this.#paused=undefined;await this.#client.mutate(action,args[action],this.#context(ctx));}
this.#epoch++;
});
}
async restore(snapshot,ctx) {
this.#check(ctx);
@@ -68,15 +80,15 @@ export class MAPlaybackProvider {
value.expires<=Date.now() || value.version!==1 || value.campaign!==this.#campaign || value.session!==this.#session || value.fence!==this.#fence || value.generation>ctx.generation)throw new MusicError('stale');
return this.#once(ctx,`restore:${snapshot.signature}`,async()=>{
const write=async(action,args)=>{await this.#client.mutate(action,args,this.#context(ctx));this.#epoch++;};
await write('stop',{});await write('clear',{});
this.#paused=undefined;await write('stop',{});await write('clear',{});
await write('repeat',{repeat_mode:value.repeat});
if(value.items.length){
await write('play_media',{media:value.items.map(i=>i.uri),option:'add',shuffle:false});
// Validate complete ordered occurrences before starting any rebuilt item.
const rebuilt=[];for(let offset=0;offset<value.items.length;offset+=100)rebuilt.push(...await this.#client.queueItems(offset));
if(JSON.stringify(rebuilt.map(i=>this.#client.mediaURI(i)))!==JSON.stringify(value.items.map(i=>i.uri)))throw new MusicError('unsupported');
await write('play_index',{index:value.index,seek_position:value.position});
if(value.state==='paused')await write('pause',{});
if(value.state==='paused'&&this.#client.supportsNativePause?.()===false)this.#paused=structuredClone(value);
else{await write('play_index',{index:value.index,seek_position:value.position});if(value.state==='paused')await write('pause',{});}
if(value.state==='idle')await write('stop',{});
}
});
+14 -13
View File
@@ -1,27 +1,28 @@
import {MusicError} from '../../core/controller.mjs';
const commands=new Set(['providers','players/get','player_queues/get','player_queues/get_active_queue','player_queues/items','music/playlists/library_items','music/radios/library_items','music/playlists/get','music/playlists/playlist_tracks','music/tracks/get',...['play_media','play_index','pause','resume','stop','seek','shuffle','repeat','clear'].map(a=>'player_queues/'+a)]);
const commands=new Set(['sendspin/pair_web_player','providers','players/get','player_queues/get','player_queues/get_active_queue','player_queues/items','music/playlists/library_items','music/radios/library_items','music/playlists/get','music/playlists/playlist_tracks','music/tracks/get',...['play_media','play_index','pause','resume','stop','seek','shuffle','repeat','clear'].map(a=>'player_queues/'+a)]);
// GM-local adapter for MA's public /ws API. No HTTP CORS dependency or server proxy.
export class GMMAWebSocket{
#base;#token;#socket;#connect;#pending=new Map();#factory;#closed=false;
constructor({baseUrl,token,createSocket=url=>new WebSocket(url)}){this.#base=new URL(baseUrl).origin;this.#token=token;this.#factory=createSocket;}
#base;#token;#socket;#connect;#pending=new Map();#factory;#closed=false;#authenticated=false;#onDisconnect;
constructor({baseUrl,token,createSocket=url=>new WebSocket(url),onDisconnect=()=>{}}){this.#onDisconnect=onDisconnect;this.#base=new URL(baseUrl).origin;this.#token=token;this.#factory=createSocket;}
async connect(){
if(this.#closed)throw new MusicError('unavailable');if(this.#connect)return this.#connect;
this.#connect=new Promise((resolve,reject)=>{
const url=new URL('/ws',this.#base);url.protocol=url.protocol==='https:'?'wss:':'ws:';const socket=this.#socket=this.#factory(url.href);
const id='auth-'+crypto.randomUUID(),timer=setTimeout(()=>{reject(new MusicError('unavailable'));this.close();},8000);
socket.onopen=()=>socket.send(JSON.stringify({message_id:id,command:'auth',args:{token:this.#token}}));
const url=new URL('/ws',this.#base);url.protocol=url.protocol==='https:'?'wss:':'ws:';let socket;try{socket=this.#socket=this.#factory(url.href);}catch{reject(new MusicError('ws-upgrade-failed'));return;}
let opened=false;
const id='auth-'+crypto.randomUUID(),timer=setTimeout(()=>{reject(new MusicError(opened?'ws-auth-timeout':'ws-upgrade-failed'));this.close();},8000);
socket.onopen=()=>{opened=true;socket.send(JSON.stringify({message_id:id,command:'auth',args:{token:this.#token}}));};
socket.onmessage=event=>{
if(typeof event.data!=='string'||event.data.length>1048576){this.close();return;}
let msg;try{msg=JSON.parse(event.data);}catch{this.close();return;}
if(msg.message_id===id){clearTimeout(timer);if(msg.result?.authenticated===true)resolve();else{reject(new MusicError('denied'));this.close();}return;}
if(msg.message_id===id){clearTimeout(timer);if(msg.result?.authenticated===true){this.#authenticated=true;resolve();}else{reject(new MusicError('ws-auth-denied'));this.close();}return;}
const pending=this.#pending.get(msg.message_id);if(!pending)return; // Drop unsolicited metadata/events.
if(Object.hasOwn(msg,'error_code')){pending.fail(new MusicError('unavailable'));return;}
if(Object.hasOwn(msg,'error_code')){const error=new MusicError('ws-command-failed');error.command=pending.command;error.upstreamCode=Number.isSafeInteger(msg.error_code)?msg.error_code:null;error.translationKey=typeof msg.translation_key==='string'&&/^[a-z0-9_.-]{1,100}$/.test(msg.translation_key)?msg.translation_key:null;pending.fail(error);return;}
pending.bytes+=event.data.length;if(pending.bytes>1048576){pending.fail(new MusicError('unavailable'));return;}
if(msg.partial===true){if(!Array.isArray(msg.result)||pending.parts.length+msg.result.length>5000){pending.fail(new MusicError('unavailable'));return;}pending.parts.push(...msg.result);return;}
pending.finish(pending.parts.length?[...pending.parts,...(Array.isArray(msg.result)?msg.result:[])]:msg.result);
};
socket.onerror=()=>{clearTimeout(timer);reject(new MusicError('unavailable'));this.close();};
socket.onclose=()=>{clearTimeout(timer);reject(new MusicError('unavailable'));this.#closed=true;for(const p of [...this.#pending.values()])p.fail(new MusicError('unavailable'));};
socket.onerror=()=>{const notify=this.#authenticated&&!this.#closed;clearTimeout(timer);reject(new MusicError(opened?'ws-disconnected':'ws-upgrade-failed'));this.close();if(notify)this.#onDisconnect();};
socket.onclose=()=>{const notify=this.#authenticated&&!this.#closed;clearTimeout(timer);reject(new MusicError(opened?'ws-disconnected':'ws-upgrade-failed'));this.#closed=true;this.#token=null;for(const p of [...this.#pending.values()])p.fail(new MusicError('unavailable'));if(notify)this.#onDisconnect();};
});return this.#connect;
}
fetch=async(url,options)=>{
@@ -33,10 +34,10 @@ export class GMMAWebSocket{
const id=crypto.randomUUID();let pending;
const cleanup=()=>{clearTimeout(timer);options.signal?.removeEventListener('abort',abort);this.#pending.delete(id);};
const finish=value=>{cleanup();const body=JSON.stringify(value??null);if(body.length>1048576){reject(new MusicError('unavailable'));return;}resolve(new Response(body,{headers:{'Content-Type':'application/json'}}));};
const fail=error=>{cleanup();reject(error);};const abort=()=>fail(new MusicError('unavailable'));const timer=setTimeout(abort,5000);
pending={parts:[],bytes:0,finish,fail};this.#pending.set(id,pending);options.signal?.addEventListener('abort',abort,{once:true});
const fail=error=>{if(!error.command)error.command=request.command;cleanup();reject(error);};const abort=()=>fail(new MusicError('ws-command-timeout'));const timer=setTimeout(abort,request.command==='sendspin/pair_web_player'?25000:['player_queues/play_media','player_queues/play_index'].includes(request.command)?60000:10000);
pending={command:request.command,parts:[],bytes:0,finish,fail};this.#pending.set(id,pending);options.signal?.addEventListener('abort',abort,{once:true});
try{this.#socket.send(JSON.stringify({...request,message_id:id}));}catch{fail(new MusicError('unavailable'));}
});
};
close(){if(this.#closed)return;this.#closed=true;for(const p of [...this.#pending.values()])p.fail(new MusicError('unavailable'));this.#socket?.close();this.#token=null;}
close(){if(this.#closed)return;this.#closed=true;this.#token=null;for(const p of [...this.#pending.values()])p.fail(new MusicError('unavailable'));this.#socket?.close();this.#token=null;}
}