Initial Adaptive Music v0.5.0 release

This commit is contained in:
Jason committed 2026-12-03 16:11:47 -05:00
commit 14f0d8c26b
114 files changed
+6907

No files matched your search

+182
View File
@@ -0,0 +1,182 @@
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;
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 ||
url.search || url.hash || url.pathname !== '/' || typeof token !== 'string' || !token ||
/[\r\n]/.test(token) || typeof target !== 'string' || !target ||
!Array.isArray(approvedProviders) || approvedProviders.some(p => typeof p !== 'string' || !p)) throw new MusicError('denied');
this.#base = url.origin; this.#token = token; this.#target = target; this.#fetch = fetchImpl;
if (!(catalogKey instanceof Uint8Array) || catalogKey.length !== 32 || !campaign) throw new MusicError('denied');
this.#providers = [...new Set(approvedProviders)];
this.#catalogKey = Uint8Array.from(catalogKey); this.#campaign = campaign;
if(!syntheticSequences || typeof syntheticSequences!=='object' || Object.values(syntheticSequences).some(v=>!Array.isArray(v)||!v.length||v.length>5000||v.some(uri=>typeof uri!=='string'||!uri.startsWith('builtin://track/http://'))))throw new MusicError('denied');
this.#synthetic = structuredClone(syntheticSequences);
for(const uri of Object.values(this.#synthetic).flat())this.#authorizedMedia.add(uri);
this.#expectedName = expectedName; this.#expectedProvider = expectedProvider;
}
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' },
body: JSON.stringify({ message_id: messageId, command, args }) });
if (!response.ok) throw new MusicError(response.status === 403 ? 'denied' : 'unavailable');
const reader = response.body?.getReader();
if (!reader) return null;
const chunks = []; let size = 0;
try {
while (true) {
const { value, done } = await reader.read(); if (done) break;
size += value.byteLength;
if (size > 1048576) { await reader.cancel(); throw new MusicError('unavailable'); }
chunks.push(value);
}
} finally { reader.releaseLock(); }
const bytes=new Uint8Array(size);let offset=0;for(const chunk of chunks){bytes.set(chunk,offset);offset+=chunk.length;}
const body = new TextDecoder().decode(bytes);
return body ? JSON.parse(body) : null;
} catch (error) {
throw new MusicError(error instanceof MusicError ? error.code : 'unavailable');
}
}
async getOwnedQueue(target) {
if (target !== this.#target) throw new MusicError('denied');
const queue = await this.#read('player_queues/get', { queue_id: this.#target });
if (queue?.queue_id !== this.#target || queue.active !== true) throw new MusicError('denied');
return { state: queue.state, items: queue.items };
}
async verifyTarget({allowUnavailable=false}={}) {
if(!allowUnavailable && this.#expectedName && this.#expectedProvider){
await this.getOwnedQueue(this.#target);
const active=await this.#read('player_queues/get_active_queue',{player_id:this.#target});
if(active?.queue_id!==this.#target)throw new MusicError('denied');
}
const player = await this.#read('players/get', { player_id: this.#target });
if (player?.player_id !== this.#target || !allowUnavailable&&player.available !== true || player.enabled !== true ||
(this.#expectedName && player.name !== this.#expectedName) ||
(this.#expectedProvider && player.provider !== this.#expectedProvider) ||
!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.#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 };
}
targetVolumeState(){if(!this.#targetVolume)throw new MusicError('unsupported');return {...this.#targetVolume};}
async catalog() {
if (!this.#providers.length) throw new MusicError('denied');
const next = new Map(); const choices = [];
// Bounded all-or-nothing pagination; a full final page fails rather than truncating silently.
for (const [kind, type] of [['playlists','playlist'],['radios','radio']]) {
let complete = false;
for (let offset = 0; offset < 5000; offset += 100) {
const page = await this.#read(`music/${kind}/library_items`, {
provider: this.#providers, limit: 100, offset, order_by: 'name', summary: false });
if (!Array.isArray(page) || page.length > 100) throw new MusicError('unavailable');
for (const item of page) {
const mapping = Array.isArray(item?.provider_mappings) && [...item.provider_mappings].sort((a,b) => String(a?.provider_instance).localeCompare(String(b?.provider_instance))).find(m => m && this.#providers.includes(m.provider_instance) && m.available === true);
if (!mapping || item.media_type !== type || item.is_playable !== true ||
typeof item.name !== 'string' || typeof mapping.item_id !== 'string') continue;
// Keyed campaign-scoped identity survives restart with the same private key.
const key = JSON.stringify([type, mapping.provider_instance, mapping.item_id]);
if (next.has(key)) continue;
const id = base64url(await hmac(this.#catalogKey,JSON.stringify([this.#campaign,key])));
next.set(key, { id, type, provider: mapping.provider_instance, itemId: mapping.item_id, dynamic: item.is_dynamic === true });
choices.push({ provider: 'ma', id, kind: type, name: item.name.replace(/[\x00-\x1f\x7f]/g,'').slice(0,160) });
}
if (page.length < 100) { complete = true; break; }
}
if (!complete) throw new MusicError('unavailable');
}
this.#catalog = next;
return choices;
}
resolveCatalog(ref) {
if (ref?.provider !== 'ma') throw new MusicError('denied');
const entry = [...this.#catalog.values()].find(e => e.id === ref.id);
if (!entry) throw new MusicError('expired-media');
if(entry.dynamic)throw new MusicError('unsupported');
const uri=`${entry.provider}://${entry.type}/${entry.itemId}`;this.#authorizedMedia.add(uri);return uri;
}
resolveMedia(ref) {
if (ref?.provider === 'ma' && Object.hasOwn(this.#synthetic,ref.id)) return [...this.#synthetic[ref.id]];
return [this.resolveCatalog(ref)];
}
async prepareMedia(ref) {
const media=this.resolveMedia(ref);
if(Object.hasOwn(this.#synthetic,ref.id)) {
await this.inspectSynthetic(media);
return media;
}
const entry=[...this.#catalog.values()].find(e=>e.id===ref.id);
if(entry.type==='radio')return media;
const playlist=await this.#read('music/playlists/get',{item_id:entry.itemId,provider_instance_id_or_domain:entry.provider,allow_update_metadata:false});
if(playlist?.is_dynamic!==false)throw new MusicError('unsupported');
const tracks=await this.#read('music/playlists/playlist_tracks',{item_id:entry.itemId,provider_instance_id_or_domain:entry.provider,allow_dynamic_tracks:false});
if(!Array.isArray(tracks) || !tracks.length || tracks.length>5000)throw new MusicError('unavailable');
return tracks.map(track=>this.mediaURI({media_item:track}));
}
async inspectSynthetic(selected) {
const approved=Object.values(this.#synthetic).flat();
const uris=selected??approved;
if(!Array.isArray(uris) || uris.some(uri=>!approved.includes(uri)))throw new MusicError('denied');
if(!this.#providers.includes('builtin') || !uris.length)throw new MusicError('denied');
const result=[];
for(const uri of uris){
if(typeof uri!=='string' || !uri.startsWith('builtin://track/http://'))throw new MusicError('denied');
const track=await this.#read('music/tracks/get',{item_id:uri.slice('builtin://track/'.length),provider_instance_id_or_domain:'builtin',allow_update_metadata:false});
if(!(track?.duration>=60))throw new MusicError('unavailable');
result.push({duration:track.duration});
}
return result;
}
async queueState({allowUnavailable=false}={}) {
const queue = await this.#read('player_queues/get', {queue_id:this.#target});
if (queue?.queue_id !== this.#target || !allowUnavailable&&(queue.active !== true || queue.available !== true)) throw new MusicError('denied');
return queue;
}
async queueItems(offset = 0) {
if (!Number.isSafeInteger(offset) || offset < 0 || offset >= 5000) throw new MusicError('denied');
const items = await this.#read('player_queues/items', {queue_id:this.#target,limit:100,offset});
if (!Array.isArray(items) || items.length > 100) throw new MusicError('unavailable');
return items;
}
mediaURI(item) {
const media = item?.media_item;
const mapping = Array.isArray(media?.provider_mappings) && media.provider_mappings.find(m => m && this.#providers.includes(m.provider_instance) && m.available === true);
if (!mapping || !['track','radio'].includes(media.media_type) || typeof mapping.item_id !== 'string') throw new MusicError('unsupported');
const uri=`${mapping.provider_instance}://${media.media_type}/${mapping.item_id}`;this.#authorizedMedia.add(uri);return uri;
}
// Server-only fixed command surface, never a browser route. Target is not an argument.
async mutate(action, args, ctx) {
const fields = {stop:[],pause:[],resume:[],clear:[],seek:['position'],shuffle:['shuffle_enabled'],repeat:['repeat_mode'],
play_index:['index','seek_position'],play_media:['media','option','shuffle']};
if (!Object.hasOwn(fields,action) || !args || Object.keys(args).some(k => !fields[action].includes(k)) ||
!this.#expectedName || !this.#expectedProvider || !ctx?.check) throw new MusicError('denied');
if (action === 'seek' && (!Number.isSafeInteger(args.position) || args.position < 0)) throw new MusicError('denied');
if (action === 'shuffle' && typeof args.shuffle_enabled !== 'boolean') throw new MusicError('denied');
if (action === 'repeat' && !['off','one','all'].includes(args.repeat_mode)) throw new MusicError('denied');
if (action === 'play_index' && (!Number.isSafeInteger(args.index) || args.index < 0 || !Number.isSafeInteger(args.seek_position) || args.seek_position < 0)) throw new MusicError('denied');
if (action === 'play_media') {
if (!['replace','add'].includes(args.option) || typeof args.shuffle !== 'boolean' || !Array.isArray(args.media) || !args.media.length || args.media.length > 5000 ||
args.media.some(uri => typeof uri !== 'string' || !this.#authorizedMedia.has(uri) || !this.#providers.some(p => uri.startsWith(`${p}://track/`) || uri.startsWith(`${p}://playlist/`) || uri.startsWith(`${p}://radio/`)))) throw new MusicError('denied');
}
const captured = structuredClone(args);
const operation = this.#writes.catch(() => {}).then(async () => {
ctx.check();
if(this.#uncertain)throw new MusicError('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');}
ctx.check();
});
this.#writes = operation;
return operation;
}
}
+84
View File
@@ -0,0 +1,84 @@
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;
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);
}
capabilities() { return {seek:true,exactOrderRestore:false,exactUnshuffledRestore:true,concurrentLayers:false,volume:false}; }
#check(ctx) {
if (ctx?.campaign !== this.#campaign || ctx?.session !== this.#session || !Number.isSafeInteger(ctx.generation) || ctx.generation < this.#generation || ctx.generation < 1) throw new MusicError('stale');
ctx.check(); this.#authority(this.#fence); this.#generation=ctx.generation;
}
#context(ctx) { return {check:()=>this.#check(ctx)}; }
#once(ctx,label,operation) {
this.#check(ctx);
const key=`${ctx.generation}:${label}`;
if(this.#operations.has(key))return this.#operations.get(key);
for(const previous of this.#operations.keys())if(!previous.startsWith(`${ctx.generation}:`))this.#operations.delete(previous);
const result=operation();this.#operations.set(key,result);return result;
}
async resolve(ref,ctx) {
this.#check(ctx); const media=this.#client.prepareMedia ? await this.#client.prepareMedia(ref) : this.#client.resolveMedia ? this.#client.resolveMedia(ref) : [this.#client.resolveCatalog(ref)]; this.#check(ctx);const prepared=Object.freeze({});this.#prepared.set(prepared,Object.freeze([...media]));return prepared;
}
async #capture(ctx) {
this.#check(ctx);await this.#client.verifyTarget();
const before=await this.#client.queueState();
if (before.shuffle_enabled || before.is_dynamic || before.autoplay_enabled || before.dont_stop_the_music_enabled || before.overlay_enabled || before.playback_speed !== 1 || before.ended) throw new MusicError('unsupported');
const items=[];
for(let offset=0;offset<5000;offset+=100){this.#check(ctx);const page=await this.#client.queueItems(offset);items.push(...page);if(page.length<100)break;if(offset===4900)throw new MusicError('unsupported');}
const after=await this.#client.queueState();
const again=[];for(let offset=0;offset<items.length;offset+=100)again.push(...await this.#client.queueItems(offset));
const stable=q=>JSON.stringify([q.items,q.current_index,q.current_item?.queue_item_id,q.state,q.shuffle_enabled,q.repeat_mode,q.is_dynamic,q.autoplay_enabled,q.dont_stop_the_music_enabled,q.overlay_enabled,q.playback_speed,q.ended]);
if (before.items!==items.length || stable(before)!==stable(after) || identity(items)!==identity(again)) throw new MusicError('stale');
if (!['idle','playing','paused'].includes(after.state) || !['off','one','all'].includes(after.repeat_mode) ||
(items.length && (!Number.isSafeInteger(after.current_index) || after.current_index<0 || after.current_index>=items.length))) throw new MusicError('unsupported');
const elapsed=after.state==='playing' ? after.elapsed_time+Math.max(0,Date.now()/1000-after.elapsed_time_last_updated) : after.elapsed_time;
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,
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}))};
}
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)}; }
async apply(prepared,ctx) {
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++;
});
}
async stopOwned(ctx) { return this.#once(ctx,`stop:${this.#epoch}`,()=>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++;});
}
async restore(snapshot,ctx) {
this.#check(ctx);
try{snapshot=structuredClone(snapshot);}catch{throw new MusicError('stale');}
const value=snapshot?.value;
if(!value || typeof snapshot.signature!=='string' || !/^[a-f0-9]{64}$/.test(snapshot.signature) ||
!await verifyHmac(this.#key,'snapshot-v1\0'+JSON.stringify(value),snapshot.signature) ||
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',{});
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==='idle')await write('stop',{});
}
});
}
}
+58
View File
@@ -0,0 +1,58 @@
import { MusicError } from '../../core/controller.mjs';
// Browser-safe client. Only same-origin relative application routes and campaign grants.
export class GatewayClient {
#fetch; #path; #origin; #grant; #fence; #catalog=[]; #status=null;
constructor({path='/adaptive-music-gateway',origin=globalThis.location?.origin,fetchImpl=globalThis.fetch}={}) {
if(typeof path!=='string' || !/^\/[a-zA-Z0-9/_-]+$/.test(path) || path.includes('//') || !origin)throw new MusicError('denied');
this.#path=path.replace(/\/$/,'');this.#origin=origin;this.#fetch=fetchImpl;
}
get connected(){return !!this.#grant&&(!this.#status||this.#status.expiresAt>Date.now());}
get status(){return this.#status&&{...structuredClone(this.#status),playbackEnabled:this.canControl};}
get catalog(){return structuredClone(this.#catalog);}
get canControl(){return this.connected && this.#status?.playbackEnabled===true && this.#status.expiresAt>Date.now();}
supports(ref){return this.canControl && this.#status.allowedIds?.includes(ref.id);}
async #request(action,args={},ctx) {
if(!this.#grant)throw new MusicError('unavailable');ctx?.check();
const grant=this.#grant;
try{
const response=await this.#fetch(this.#path+'/rpc',{method:'POST',redirect:'error',credentials:'omit',cache:'no-store',
signal:AbortSignal.timeout(8000),headers:{'Content-Type':'application/json',Authorization:`Bearer ${grant.token}`},
body:JSON.stringify({action,...args,campaign:grant.campaign,session:grant.session,...(ctx?{generation:ctx.generation,operationId:globalThis.crypto.randomUUID(),fence:this.#fence}:{})})});
const reader=response.body?.getReader();if(!reader)throw new MusicError('unavailable');
const chunks=[];let size=0;
try{while(true){const {value,done}=await reader.read();if(done)break;size+=value.length;if(size>1048576){await reader.cancel();throw new MusicError('unavailable');}chunks.push(value);}}finally{reader.releaseLock();}
const bytes=new Uint8Array(size);let offset=0;for(const chunk of chunks){bytes.set(chunk,offset);offset+=chunk.length;}const text=new TextDecoder().decode(bytes);
const data=JSON.parse(text);
if(!response.ok)throw new MusicError(['denied','stale','unsupported','unavailable','uncertain','expired-media'].includes(data.code)?data.code:'unavailable');
if(this.#grant!==grant)throw new MusicError('stale');ctx?.check();return data;
}catch(error){if(this.#status)this.#status.playbackEnabled=false;throw new MusicError(error instanceof MusicError?error.code:'unavailable');}
}
async connect(code) {
await this.disconnect();
let grant;try{grant=typeof code==='string'?JSON.parse(code):structuredClone(code);}catch{throw new MusicError('denied');}
if(!grant || Object.keys(grant).sort().join(',')!=='campaign,session,token' || ['token','campaign','session'].some(k=>typeof grant[k]!=='string'||!grant[k]||grant[k].length>512))throw new MusicError('denied');
this.#grant=grant;
try{const lease=await this.#request('connect');this.#fence=lease.fence;return await this.refresh();}
catch(error){await this.disconnect();throw error;}
}
async refresh(){
const status=await this.#request('diagnostics');
if(!status||!['verified','unavailable'].includes(status.target)||typeof status.playbackEnabled!=='boolean'||!Number.isFinite(status.expiresAt)||!Array.isArray(status.allowedIds)||status.allowedIds.some(id=>typeof id!=='string'||id.length>256)||!['none','synthetic-pcm'].includes(status.audioSource))throw new MusicError('unavailable');
this.#status={target:status.target,playbackEnabled:status.playbackEnabled,expiresAt:status.expiresAt,allowedIds:[...status.allowedIds],audioSource:status.audioSource,sendspin:false,crossfade:false,ambientLayers:1};const catalog=await this.#request('catalog');
if(!Array.isArray(catalog)||catalog.length>10000||catalog.some(c=>c?.provider!=='ma'||typeof c.id!=='string'||c.id.length>256||typeof c.name!=='string'||c.name.length>160||!['playlist','radio','sequence'].includes(c.kind)))throw new MusicError('unavailable');
this.#catalog=catalog.map(({provider,id,name,kind})=>({provider,id,name,kind}));return this.status;
}
async renew(){return this.#request('renew',{fence:this.#fence});}
async disconnect(){try{if(this.#grant&&this.#fence)await this.#request('release',{fence:this.#fence});}catch{}finally{this.#grant=null;this.#catalog=[];this.#status=null;this.#fence=null;}}
async resolve(ref,ctx){if(!this.supports(ref))throw new MusicError('unsupported');return this.#request('prepare',{id:ref.id},ctx);}
snapshot(ctx){return this.#request('snapshot',{},ctx);}
apply(prepared,ctx){return this.#request('apply',{handle:prepared.handle},ctx);}
restore(snapshot,ctx){return this.#request('restore',{handle:snapshot.handle},ctx);}
stopOwned(ctx){return this.#request('stop',{},ctx);}
// Listener access is supplied separately, never derived from or shared with the GM grant.
audioRequest(code){
if(!code || Object.keys(code).sort().join(',')!=='campaign,session,token' || ['token','campaign','session'].some(k=>typeof code[k]!=='string'||!code[k]||code[k].length>512))throw new MusicError('denied');
return {url:this.#path+'/audio',options:{method:'POST',redirect:'error',credentials:'omit',cache:'no-store',
headers:{'Content-Type':'application/json',Authorization:`Bearer ${code.token}`},body:JSON.stringify({campaign:code.campaign,session:code.session})}};
}
}
+13
View File
@@ -0,0 +1,13 @@
// Shared Web Crypto implementation: runs in a secure browser and Node 24.
export const randomKey=()=>globalThis.crypto.getRandomValues(new Uint8Array(32));
export const hex=bytes=>[...bytes].map(n=>n.toString(16).padStart(2,'0')).join('');
export async function hmac(key,text){
const imported=await crypto.subtle.importKey('raw',key,{name:'HMAC',hash:'SHA-256'},false,['sign']);
return new Uint8Array(await crypto.subtle.sign('HMAC',imported,new TextEncoder().encode(text)));
}
export async function verifyHmac(key,text,signature){
const imported=await crypto.subtle.importKey('raw',key,{name:'HMAC',hash:'SHA-256'},false,['verify']);
const bytes=Uint8Array.from(signature.match(/../g)??[],s=>parseInt(s,16));
return crypto.subtle.verify('HMAC',imported,bytes,new TextEncoder().encode(text));
}
export const base64url=bytes=>btoa(String.fromCharCode(...bytes)).replace(/\+/g,'-').replace(/\//g,'_').replace(/=+$/,'');
+42
View File
@@ -0,0 +1,42 @@
import {MusicError} from '../../core/controller.mjs';
const commands=new Set(['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;}
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}}));
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;}
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;}
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'));};
});return this.#connect;
}
fetch=async(url,options)=>{
if(url!==this.#base+'/api'||options.method!=='POST'||options.redirect!=='error')throw new MusicError('denied');
let request;try{request=JSON.parse(options.body);}catch{throw new MusicError('denied');}
if(!commands.has(request.command))throw new MusicError('denied');await this.connect();
if(options.signal?.aborted||this.#pending.size>=16)throw new MusicError('unavailable');
return new Promise((resolve,reject)=>{
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});
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;}
}
+71
View File
@@ -0,0 +1,71 @@
// Per-sound stop and pausedTime approach adapted from VGM (MIT), release-1.4.5.
// Copyright (c) 2025 3 Death Saves. Full notice: licenses/VGM-MIT.txt.
import { MusicError } from '../../core/controller.mjs';
export class NativeProvider {
constructor({ playlists, ownedPlaylistIds, campaign, session, sceneConflict = () => false }) {
Object.assign(this, { playlists, campaign, session, sceneConflict });
this.owned = new Set(ownedPlaylistIds);
}
capabilities() { return { seek: true, exactOrderRestore: false, concurrentLayers: false, volume: true }; }
playlist(id, ctx) {
ctx.check();
if (ctx.campaign !== this.campaign || ctx.session !== this.session || !this.owned.has(id)) throw new MusicError('denied');
const p = this.playlists.get(id);
if (!p) throw new MusicError('unavailable');
if (this.sceneConflict(id)) throw new MusicError('scene-conflict');
return p;
}
async resolve(ref, ctx) {
const p = this.playlist(ref.id, ctx);
// Sequential single-track start only; automatic shuffled order is not an exact restore API.
if (p.mode !== 0) throw new MusicError('unsupported');
const sound = [...p.sounds].sort((a,b) => a.sort-b.sort || a.id.localeCompare(b.id))[0];
if (!sound) throw new MusicError('unavailable');
return { id: p.id, soundId: sound.id };
}
async snapshot(ctx) {
const playlists = [...this.owned].map(id => {
const p = this.playlist(id, ctx);
return { id, mode: p.mode, sounds: [...p.sounds].map(s => ({
id: s.id, playing: s.playing, pausedTime: s.playing ? (s.sound?.currentTime ?? 0) : s.pausedTime,
repeat: s.repeat, volume: s.volume
})) };
});
return { version: 1, campaign: ctx.campaign, session: ctx.session, generation: ctx.generation, playlists };
}
async stopOwned(ctx) {
for (const id of this.owned) {
const p = this.playlist(id, ctx);
const updates = [...p.sounds].filter(s => s.playing).map(s => ({ _id: s.id, playing: false, pausedTime: null }));
if (updates.length) { ctx.check(); await p.updateEmbeddedDocuments('PlaylistSound', updates); }
}
}
async apply(prepared, ctx) {
const p = this.playlist(prepared.id, ctx);
if (p.mode !== 0) throw new MusicError('unsupported');
if (!p.sounds.get(prepared.soundId)) throw new MusicError('unavailable');
ctx.check(); await p.updateEmbeddedDocuments('PlaylistSound', [{ _id: prepared.soundId, playing: true, pausedTime: 0 }]);
}
async restore(snapshot, ctx) {
ctx.check();
if (snapshot.version !== 1 || snapshot.campaign !== ctx.campaign || snapshot.session !== ctx.session ||
snapshot.generation > ctx.generation) throw new MusicError('stale');
// Validate the entire restore before any mutation; never silently restart nonseekable audio.
const plans = snapshot.playlists.map(saved => {
const p = this.playlist(saved.id, ctx);
if (p.mode !== saved.mode || p.mode !== 0) throw new MusicError('unsupported');
if (p.sounds.size !== saved.sounds.length) throw new MusicError('expired-media');
const updates = saved.sounds.map(s => {
const live = p.sounds.get(s.id);
if (!live) throw new MusicError('expired-media');
const offset = s.pausedTime;
const duration = live.sound?.duration;
if (offset != null && (!Number.isFinite(offset) || offset < 0 ||
(offset > 0 && !(Number.isFinite(duration) && duration > 0)))) throw new MusicError('unsupported');
return { _id: s.id, playing: s.playing, pausedTime: offset == null ? null : Math.min(offset, Math.max(0, (duration ?? 0)-0.01)), repeat: s.repeat, volume: s.volume };
});
return { p, updates };
});
for (const { p, updates } of plans) { ctx.check(); await p.updateEmbeddedDocuments('PlaylistSound', updates); }
}
}