Initial Adaptive Music v0.5.0 release
This commit is contained in:
commit
14f0d8c26b
114 files changed
+6907
No files matched your search
@@ -0,0 +1,84 @@
|
||||
> Optional experimental companion fallback. The standard module has no mandatory
|
||||
> companion or sandbox dependency. See ../ARCHITECTURE.md and ../INSTALL.md for
|
||||
> the 0.5.0 module-only experiment and remaining deployment gates. This guide
|
||||
> does not authorize host routing, service installation or production changes.
|
||||
|
||||
# Private companion — 0.4.0 development
|
||||
|
||||
The companion now connects the browser-safe provider/catalog interface to the
|
||||
existing MA client, fenced control and playback provider. It is a separate server
|
||||
artifact; no gateway code or MA credential is bundled into Foundry. Follow
|
||||
[SETUP.md](SETUP.md) for exact isolated-world setup and infrastructure gates.
|
||||
|
||||
`development-service.mjs` accepts only fixed controller phases: connect, diagnostics,
|
||||
catalog, renew, release, prepare, snapshot, apply, restore and stop. Server-bound
|
||||
campaign/session/target identity, controller role, lease/fence/generation and
|
||||
operation IDs constrain requests. Preparation and raw signed snapshots stay in
|
||||
server memory behind expiring opaque handles. Prepared handles bind their generation;
|
||||
restore handles bind fenced session and expiry. Same-ID changed payloads deny;
|
||||
replayed operations do not issue duplicate effects. Queue selectors, raw media,
|
||||
upstream commands/paths and proxy operations are not accepted from browsers.
|
||||
|
||||
`development-http.mjs` binds loopback only, with exact Host/Origin, header-only auth,
|
||||
fixed POST routes, bounded headers/body/responses/connections/request rate and queued
|
||||
work. The browser client uses same-origin relative `/adaptive-music-gateway` routes,
|
||||
credentials omitted and no redirects, with capability codes held in memory only.
|
||||
A private HTTPS route is still an operator infrastructure requirement. No public
|
||||
exposure, proxy/firewall change, CORS wildcard or MA Sendspin pass-through exists.
|
||||
This prototype still lacks permanent hosting, durable fencing/process locks and
|
||||
automatic Foundry login verification. Do not expose it publicly.
|
||||
|
||||
`run-development.mjs` loads protected ignored `.local/` config and pins the prior
|
||||
verified account's sole target, exact name Adaptive Music DEV and provider. It
|
||||
serves five minutes with separate controller/listener grants and starts no playback.
|
||||
Playback defaults off; explicit synthetic opt-in authorizes only generated sequence
|
||||
IDs. Real MA catalog entries remain selectable for configuration but unplayable
|
||||
under the current authorization. There is no automatic household discovery or
|
||||
selection, queue transfer, grouping or new receiver provisioning.
|
||||
|
||||
The browser package saves separate scene ambient/combat/boss/native-fallback refs,
|
||||
world defaults and explicit boss flags. Native fallback applies before preparation
|
||||
when MA is disconnected, expired or not authorized for that selection. It never
|
||||
bypasses an uncertain active MA target to start overlapping native audio. The
|
||||
controller still uses one base music layer interrupted by combat/boss/manual;
|
||||
concurrent ambient layers and crossfade are not implemented.
|
||||
|
||||
The existing `ma-provider.mjs` and `ma-client.mjs` retain fixed guarded commands:
|
||||
play_media, play_index, pause, resume, stop, seek, shuffle, repeat and clear. Every
|
||||
mutation rechecks supported queue modes, active queue identity and exact player/
|
||||
provider/topology, then authority immediately before dispatch. Registered approved
|
||||
media only; no arbitrary URI injection. Ambiguous responses latch the client closed
|
||||
with `uncertain`, without retries or blind restoration. The public MA API cannot
|
||||
atomically bind topology checks to a write; concurrent external changes and restart
|
||||
reconciliation remain development limitations.
|
||||
|
||||
Signed snapshots preserve ordered duplicate occurrences, index, whole-second
|
||||
position, state and repeat for supported unshuffled static queues. They expire in
|
||||
five minutes and bind campaign/session/fence/generation. Capture repeats bounded
|
||||
pagination; restore stages items, checks order, then seeks/plays and reapplies pause
|
||||
or idle. Shuffle/dynamic/autoplay/overlay/ended/nonstandard-speed restoration is
|
||||
unsupported. Volume is unchanged. Losing topology/authority can prevent recovery;
|
||||
report it rather than bypass guards. Durable recovery still needs further work.
|
||||
|
||||
Private `.local/catalog-key` and `.local/catalog-namespace.json` give opaque
|
||||
campaign-scoped catalog IDs persistence across companion restarts. Refresh the
|
||||
catalog to rebuild private mappings; back up those files. Secrets/config require
|
||||
0600 and directory 0700, owner checks and symlink refusal. MA tokens never enter
|
||||
browser assets/settings/flags/storage/URLs/logs. The upstream user role remains
|
||||
broader than read-only and queue reads lack player filtering in pinned source, so
|
||||
gateway boundaries remain essential even with account filters.
|
||||
|
||||
Separate listener POST /audio accepts listener capabilities only and streams quiet
|
||||
companion-generated PCM; joining causes no MA effects. Expiry/revocation/backpressure
|
||||
closes active sockets. The packaged Web Audio sink validates PCM and starts only
|
||||
on Enable Audio. This is a **synthetic test stream, not MA/Sendspin audio**. A
|
||||
supported public-interface dedicated receiver, private pairing, audited codecs and
|
||||
protocol/time tests are still needed; see `evidence/SENDSPIN-RECEIVER.md` in the repo.
|
||||
Crossfade remains explicitly unavailable in setup and diagnostics.
|
||||
|
||||
Actual connected live reading: verified DEV target, **11 playlists / 1 radio**, no
|
||||
MA token/endpoint/target ID in browser-facing responses, playback disabled and zero
|
||||
mutations. This exercised a local HTTP client/companion, not Foundry or TLS. New
|
||||
phase/queue restoration tests use an isolated fake MA HTTP server. Earlier live
|
||||
idle-queue controls/restoration and failed synthetic ingestion remain separately
|
||||
recorded; no new playback mutation occurred in this revision.
|
||||
@@ -0,0 +1,94 @@
|
||||
> Optional experimental companion fallback. The standard module has no mandatory
|
||||
> companion or sandbox dependency. See ../ARCHITECTURE.md and ../INSTALL.md for
|
||||
> the 0.5.0 module-only experiment and remaining deployment gates. This guide
|
||||
> does not authorize host routing, service installation or production changes.
|
||||
|
||||
# Private companion setup — 0.4.0-dev
|
||||
|
||||
This is a development companion, not a public deployment. It always binds an
|
||||
ephemeral **127.0.0.1** port, runs for five minutes, and starts no MA playback on
|
||||
launch. No firewall, reverse proxy, MA service or production Foundry configuration
|
||||
has been changed by this project. Node 24.23.0 or later; no npm install is needed.
|
||||
|
||||
The module and companion are separate artifacts. Extract the module into an isolated
|
||||
Foundry Data/modules directory. Extract `adaptive-music-companion-dev.zip` on the
|
||||
operator's private gateway host (or run the repository). All operator data stays in
|
||||
an owner-controlled `.local/` directory mode 0700, JSON/secret files mode 0600.
|
||||
The module ZIP contains only browser code; the companion ZIP contains server code
|
||||
and notices, never actual endpoint configuration or secrets.
|
||||
|
||||
For the existing authorized DEV target, provide private `.local/environment.json`
|
||||
with `ma_url`, `.local/ma-token`, and `.local/ma-readonly-results.json` generated by
|
||||
the existing approved read-only probe. The launcher pins that verified account's
|
||||
sole player, exact name Adaptive Music DEV and provider instance. It does not list
|
||||
or choose household players. Back up `.local/catalog-key` and
|
||||
`.local/catalog-namespace.json` to retain catalog IDs across restarts. Corrupt or
|
||||
unsafe existing namespace/key files fail rather than silently changing IDs.
|
||||
|
||||
Create `.local/development-gateway.json` with these operator values (placeholders):
|
||||
|
||||
```json
|
||||
{
|
||||
"foundryOrigin": "https://foundry.example.invalid",
|
||||
"proxyHost": true,
|
||||
"syntheticAudio": true,
|
||||
"enableSyntheticControl": false
|
||||
}
|
||||
```
|
||||
|
||||
Use the exact isolated Foundry origin, with no trailing slash/path. HTTPS is
|
||||
required except for localhost development. `proxyHost: true` requires the preserved
|
||||
Host header to match that origin. With `proxyHost: false`, only the ephemeral
|
||||
loopback Host is accepted (for local harnesses, not browser deployment). The process
|
||||
also requires an exact Origin and header-only grants; it rejects arbitrary paths,
|
||||
query strings, commands, target selectors, oversized bodies and excess requests.
|
||||
|
||||
Run `node gateway/run-development.mjs` from the companion/repository root. The
|
||||
loopback address is written to `.local/development-gateway-runtime.json`, never
|
||||
browser settings. The operator must already have, or separately approve and review,
|
||||
a **private same-origin HTTPS route** `/adaptive-music-gateway` from the isolated
|
||||
Foundry origin to this local companion, preserving Host, Origin and Authorization,
|
||||
streaming responses without buffering or token/header logging. Preserve every
|
||||
existing network restriction. No proxy template was applied, no route has been
|
||||
created and this build does not bypass mixed-content/private-network protections.
|
||||
A remote browser cannot reach the operator's loopback listener without that
|
||||
infrastructure. This ephemeral prototype is not suitable for permanent hosting.
|
||||
|
||||
Privately deliver `.local/controller-bootstrap.json` to the elected active GM.
|
||||
In Foundry settings → Configure Settings → Adaptive Music setup, paste the JSON
|
||||
into the password field and choose **Connect and load MA catalog**. The field is
|
||||
cleared and the capability stays in memory only. Do not paste an MA token. The
|
||||
module never receives one. Diagnostics show target availability, catalog contents,
|
||||
content authorization and the missing Sendspin/crossfade capabilities. Capabilities
|
||||
expire after five minutes; get a fresh bootstrap after restarting the companion.
|
||||
Only the elected active GM should connect; other GMs may configure native music.
|
||||
|
||||
Set owned native playlists using checkboxes, reload, then configure world defaults
|
||||
and each scene's ambient, combat, boss and native fallback choices. Boss combatants
|
||||
can override playlist, priority and inactive state in setup. Enable automation only
|
||||
after configuration. MA catalog assignments persist as opaque IDs, but real MA
|
||||
playlist playback remains disallowed under the current synthetic-only authorization.
|
||||
Unavailable/unapproved MA assignments choose the explicit scene/world native
|
||||
fallback or silence before preparing playback. A target with uncertain active MA
|
||||
playback cannot be bypassed by silently starting fallback audio.
|
||||
|
||||
`enableSyntheticControl: true` is an explicit operator opt-in for the **existing
|
||||
approved generated fixtures only**. It requires `.local/fixture-origin.json` and
|
||||
MA-readable synthetic files; it adds generated ambient/combat sequence choices.
|
||||
All real MA catalog IDs remain excluded from playback authorization. The earlier
|
||||
fixture ingestion attempt failed, so this is still an infrastructure gate. Do not
|
||||
modify existing playlists or select other MA players to work around it.
|
||||
|
||||
For browser audio, give listeners `.local/listener-bootstrap.json` privately. They
|
||||
open **Campaign audio (development)** and press Enable Audio. The separate listener
|
||||
grant cannot browse catalog, acquire a lease or control queues. This plays the
|
||||
companion's quiet synthetic PCM tone through Web Audio; it is independent of the
|
||||
DEV target and does **not** prove Sendspin/MA audio playback. Closing/stopping audio
|
||||
or capability expiry/revocation closes the stream. Browser rendering and autoplay
|
||||
still need actual Foundry/browser validation. Joining never changes any MA player.
|
||||
|
||||
For Sendspin audio, a separately approved gateway-owned public-interface receiver,
|
||||
private pairing/identity storage, codec review and termination are still needed.
|
||||
No direct MA Sendspin proxy is provided. Crossfade and concurrent ambient layers
|
||||
remain unimplemented, and the UI says so. See TESTING.md/PROGRESS.md in the repository
|
||||
for exact offline/live evidence. Do not expose this companion publicly.
|
||||
@@ -0,0 +1,78 @@
|
||||
// In-process, read-only security PoC. No HTTP/WSS listener or live credential bootstrap.
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { MusicError } from '../src/core/controller.mjs';
|
||||
export class GatewayControl {
|
||||
#grants = new Map(); #leases = new Map();
|
||||
constructor({ campaigns, origin, now = () => Date.now() }) {
|
||||
this.campaigns = new Map(Object.entries(campaigns)); this.origin = origin; this.now = now;
|
||||
}
|
||||
// Operator-only API. Never expose mint/revoke/acquire directly to unauthenticated browsers.
|
||||
mint({ campaign, session, role, ttlMs = 60000 }) {
|
||||
if (!this.campaigns.has(campaign) || !['controller','listener'].includes(role) ||
|
||||
!session || !(ttlMs > 0 && ttlMs <= 300000)) throw new MusicError('denied');
|
||||
const token = randomBytes(32).toString('base64url');
|
||||
this.#grants.set(token, { campaign, session, role, expires: this.now()+ttlMs }); return token;
|
||||
}
|
||||
revoke(token) { this.#grants.delete(token); }
|
||||
authorize(token, origin, campaign, session, role) {
|
||||
const grant = this.#grants.get(token);
|
||||
if (origin !== this.origin || !grant || grant.expires <= this.now() ||
|
||||
grant.campaign !== campaign || grant.session !== session || grant.role !== role) throw new MusicError('denied');
|
||||
return grant;
|
||||
}
|
||||
acquire(request) {
|
||||
const g = this.authorize(request.token, request.origin, request.campaign, request.session, 'controller');
|
||||
const previous = this.#leases.get(g.campaign);
|
||||
// No live takeover: new controller waits for expiry/revocation, then gets a greater fence.
|
||||
if (previous && previous.expires > this.now() && this.#grants.has(previous.token)) throw new MusicError('denied');
|
||||
const lease = { token: request.token, session: g.session, fence: (previous?.fence ?? 0)+1, generation: 0,
|
||||
expires: Math.min(g.expires, this.now()+30000) };
|
||||
this.#leases.set(g.campaign, lease); return { fence: lease.fence, expires: lease.expires };
|
||||
}
|
||||
// Server-only guard for a provider bound to this exact controller lease.
|
||||
fenceGuard(request) {
|
||||
const captured = {...request};
|
||||
return fence => {
|
||||
this.authorize(captured.token,captured.origin,captured.campaign,captured.session,'controller');
|
||||
const lease=this.#leases.get(captured.campaign);
|
||||
if (!lease || lease.token!==captured.token || lease.session!==captured.session ||
|
||||
lease.fence!==fence || fence!==captured.fence || lease.expires<=this.now()) throw new MusicError('stale');
|
||||
};
|
||||
}
|
||||
release(request) {this.fenceGuard(request)(request.fence);this.#leases.get(request.campaign).expires=this.now();}
|
||||
renew(request) {
|
||||
this.fenceGuard(request)(request.fence);
|
||||
const grant=this.authorize(request.token,request.origin,request.campaign,request.session,'controller');
|
||||
const lease=this.#leases.get(request.campaign);
|
||||
lease.expires=Math.min(grant.expires,this.now()+30000);
|
||||
return {fence:lease.fence,expires:lease.expires};
|
||||
}
|
||||
async #controllerRead(request, operation) {
|
||||
const allowed = new Set(['token','origin','campaign','session','fence','generation']);
|
||||
if (Object.keys(request).some(k => !allowed.has(k))) throw new MusicError('denied');
|
||||
const check = () => {
|
||||
this.authorize(request.token, request.origin, request.campaign, request.session, 'controller');
|
||||
const lease = this.#leases.get(request.campaign);
|
||||
if (!lease || lease.token !== request.token || lease.session !== request.session || lease.expires <= this.now() ||
|
||||
lease.fence !== request.fence || !Number.isSafeInteger(request.generation) ||
|
||||
request.generation <= lease.generation) throw new MusicError('stale');
|
||||
return lease;
|
||||
};
|
||||
const lease = check();
|
||||
// Consume generation before I/O so concurrent/replayed requests cannot both pass.
|
||||
lease.generation = request.generation;
|
||||
const result = await operation(this.campaigns.get(request.campaign));
|
||||
this.authorize(request.token, request.origin, request.campaign, request.session, 'controller');
|
||||
if (this.#leases.get(request.campaign) !== lease || lease.generation !== request.generation || lease.expires <= this.now()) throw new MusicError('stale');
|
||||
return result;
|
||||
}
|
||||
async readCatalog(request) {
|
||||
return this.#controllerRead(request, ({client}) => client.catalog());
|
||||
}
|
||||
async readQueue(request) {
|
||||
const queue = await this.#controllerRead(request, ({client,target}) => client.getOwnedQueue(target));
|
||||
// No URIs, names, upstream IDs, artwork or raw metadata leave the queue response.
|
||||
return { state: ['playing','paused','idle'].includes(queue.state) ? queue.state : 'unknown',
|
||||
items: Number.isSafeInteger(queue.items) && queue.items >= 0 ? queue.items : 0 };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import {createServer} from 'node:http';
|
||||
import {MusicError} from '../src/core/controller.mjs';
|
||||
// Development companion: fixed loopback binding. Public exposure is deliberately unavailable.
|
||||
export async function startDevelopmentHTTP({service,origin,prefix='/adaptive-music-gateway',expectedHost}){
|
||||
const streams=new Set(),rates=new Map();
|
||||
const server=createServer({maxHeaderSize:4096},async(req,res)=>{
|
||||
const respond=(status,data)=>{res.writeHead(status,{'Content-Type':'application/json','Cache-Control':'no-store','X-Content-Type-Options':'nosniff'});res.end(JSON.stringify(data));};
|
||||
let handle;
|
||||
try{
|
||||
if(req.method!=='POST'||![prefix+'/rpc',prefix+'/audio'].includes(req.url)||req.headers.host!==(expectedHost??`127.0.0.1:${server.address().port}`)||req.headers.origin!==origin||
|
||||
req.headers['content-type']!=='application/json'||typeof req.headers.authorization!=='string'||!req.headers.authorization.startsWith('Bearer '))throw new MusicError('denied');
|
||||
// Fixed peer count: this listener only accepts local peers, never arbitrary IP maps.
|
||||
const peer=req.socket.remoteAddress,now=Date.now(),rate=rates.get(peer);
|
||||
if(!rate||now-rate.start>60000)rates.set(peer,{start:now,count:1});else if(++rate.count>600)throw new MusicError('denied');
|
||||
const chunks=[];let size=0;
|
||||
for await(const chunk of req){size+=chunk.length;if(size>16384)throw new MusicError('denied');chunks.push(chunk);}
|
||||
let body;try{body=JSON.parse(Buffer.concat(chunks).toString('utf8'));}catch{throw new MusicError('denied');}
|
||||
if(!body||typeof body!=='object'||Array.isArray(body))throw new MusicError('denied');
|
||||
const token=req.headers.authorization.slice(7);
|
||||
if(req.url===prefix+'/rpc'){
|
||||
const value=await service.rpc(token,origin,body);service.authorize(token,origin,body);
|
||||
if(JSON.stringify(value).length>1048576)throw new MusicError('unavailable');respond(200,value);return;
|
||||
}
|
||||
if(Object.keys(body).sort().join(',')!=='campaign,session'||!service.audio)throw new MusicError('denied');
|
||||
service.authorize(token,origin,body,'listener');
|
||||
handle=service.audio.connect({token,origin,...body});
|
||||
res.writeHead(200,{'Content-Type':'application/octet-stream','Cache-Control':'no-store','X-Content-Type-Options':'nosniff','X-Audio-Format':'pcm16le;rate=24000;channels=2'});res.flushHeaders();
|
||||
const connection={res,handle,timer:setInterval(()=>{
|
||||
try{const frame=handle.next();if(frame&&!res.write(frame.pcm))res.destroy();}catch{res.destroy();}
|
||||
},20)};
|
||||
streams.add(connection);
|
||||
res.on('close',()=>{clearInterval(connection.timer);handle.close();streams.delete(connection);});
|
||||
}catch(error){handle?.close();if(res.headersSent)res.destroy();else respond(error.code==='denied'?403:409,{code:['denied','stale','unsupported','unavailable','uncertain','expired-media'].includes(error.code)?error.code:'unavailable'});}
|
||||
});
|
||||
server.maxHeadersCount=16;server.headersTimeout=2000;server.requestTimeout=5000;server.keepAliveTimeout=1000;server.maxConnections=32;
|
||||
await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(0,'127.0.0.1',resolve);});
|
||||
return {url:`http://127.0.0.1:${server.address().port}${prefix}`,async close(){for(const {res,handle,timer}of streams){clearInterval(timer);handle.close();res.destroy();}const done=new Promise(resolve=>server.close(resolve));server.closeAllConnections();await done;}};
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import {randomUUID} from 'node:crypto';
|
||||
import {MusicError} from '../src/core/controller.mjs';
|
||||
import {MAPlaybackProvider} from './ma-provider.mjs';
|
||||
// Server-only bridge. No upstream IDs, raw snapshots, arbitrary commands or URLs cross it.
|
||||
export class DevelopmentService {
|
||||
#control; #campaign; #session; #client; #key; #allowed; #provider; #binding; #latest=0; #tail=Promise.resolve(); #handles=new Map(); #cache=new Map(); #pending=0;
|
||||
constructor({control,campaign,session,client,snapshotKey,allowedIds=[],playbackEnabled=false,audio}){
|
||||
this.#control=control;this.#campaign=campaign;this.#session=session;this.#client=client;this.#key=snapshotKey;
|
||||
this.#allowed=new Set(allowedIds);this.playbackEnabled=playbackEnabled;this.audio=audio;
|
||||
}
|
||||
authorize(token,origin,body,role='controller'){
|
||||
this.#control.authorize(token,origin,body.campaign,body.session,role);
|
||||
if(body.campaign!==this.#campaign||body.session!==this.#session)throw new MusicError('denied');
|
||||
}
|
||||
async rpc(token,origin,body){
|
||||
this.authorize(token,origin,body);
|
||||
const base=['action','campaign','session'];
|
||||
const shape={connect:[],diagnostics:[],catalog:[],renew:['fence'],release:['fence'],prepare:['generation','operationId','fence','id'],snapshot:['generation','operationId','fence'],apply:['generation','operationId','fence','handle'],restore:['generation','operationId','fence','handle'],stop:['generation','operationId','fence']};
|
||||
if(!Object.hasOwn(shape,body.action)||Object.keys(body).some(k=>![...base,...shape[body.action]].includes(k)))throw new MusicError('denied');
|
||||
const request={token,origin,campaign:this.#campaign,session:this.#session,fence:body.fence};
|
||||
if(body.action==='connect'){
|
||||
const lease=this.#control.acquire(request);request.fence=lease.fence;
|
||||
this.#binding=request;this.#latest=0;this.#handles.clear();this.#cache.clear();
|
||||
this.#provider=new MAPlaybackProvider({client:this.#client,campaign:this.#campaign,session:this.#session,fence:lease.fence,authority:this.#control.fenceGuard(request),snapshotKey:this.#key});return lease;
|
||||
}
|
||||
if(body.action==='diagnostics'){
|
||||
let target='unavailable';try{await this.#client.verifyTarget();target='verified';}catch{}
|
||||
this.authorize(token,origin,body);
|
||||
return {target,catalog:true,playbackEnabled:this.playbackEnabled && target==='verified',allowedIds:[...this.#allowed],
|
||||
expiresAt:this.#control.authorize(token,origin,body.campaign,body.session,'controller').expires,audioSource:this.audio?'synthetic-pcm':'none',sendspin:false,crossfade:false,ambientLayers:1};
|
||||
}
|
||||
if(body.action==='catalog'){const items=await this.#client.catalog();this.authorize(token,origin,body);return [...items,...[...this.#allowed].filter(id=>id.startsWith('synthetic-')).map(id=>({provider:'ma',id,kind:'sequence',name:id==='synthetic-ambient'?'Generated ambient test sequence':'Generated combat test sequence'}))];}
|
||||
if(body.action==='renew')return this.#control.renew(request);
|
||||
if(body.action==='release'){this.#control.release(request);return {ok:true};}
|
||||
if(!this.playbackEnabled || !this.#provider || !Number.isSafeInteger(body.generation)||body.generation<1 || typeof body.operationId!=='string'||body.operationId.length>80 || !body.operationId ||
|
||||
this.#binding.token!==token || this.#binding.fence!==body.fence)throw new MusicError('denied');
|
||||
this.#control.fenceGuard(request)(body.fence);
|
||||
if(body.generation<this.#latest)throw new MusicError('stale');
|
||||
this.#latest=body.generation;
|
||||
const signature=JSON.stringify(body),cached=this.#cache.get(body.operationId);
|
||||
if(cached){if(cached.signature!==signature)throw new MusicError('denied');return cached.result;}
|
||||
const ctx={campaign:this.#campaign,session:this.#session,generation:body.generation,check:()=>{
|
||||
this.authorize(token,origin,body);this.#control.fenceGuard(request)(body.fence);if(body.generation!==this.#latest)throw new MusicError('stale');
|
||||
}};
|
||||
const put=(type,value)=>{
|
||||
ctx.check();
|
||||
for(const [id,entry]of this.#handles)if(entry.expires<=Date.now())this.#handles.delete(id);
|
||||
if(this.#handles.size>=64)throw new MusicError('unavailable');
|
||||
const handle=randomUUID(),expires=Date.now()+300000;this.#handles.set(handle,{type,value,expires,generation:body.generation});return {handle,expires};
|
||||
};
|
||||
const get=type=>{const entry=this.#handles.get(body.handle);if(!entry||entry.type!==type||entry.expires<=Date.now()||type==='prepared'&&entry.generation!==body.generation)throw new MusicError('expired-media');return entry.value;};
|
||||
for(const [id,entry]of this.#cache)if(entry.generation<body.generation)this.#cache.delete(id);
|
||||
if(this.#cache.size>=128||this.#pending>=16)throw new MusicError('unavailable');
|
||||
this.#pending++;
|
||||
const operation=this.#tail.catch(()=>{}).then(async()=>{
|
||||
ctx.check();
|
||||
switch(body.action){
|
||||
case 'prepare':if(!this.#allowed.has(body.id))throw new MusicError('denied');return put('prepared',await this.#provider.resolve({provider:'ma',id:body.id},ctx));
|
||||
case 'snapshot':return put('snapshot',await this.#provider.snapshot(ctx));
|
||||
case 'apply':await this.#provider.apply(get('prepared'),ctx);return {ok:true};
|
||||
case 'restore':await this.#provider.restore(get('snapshot'),ctx);return {ok:true};
|
||||
case 'stop':await this.#provider.stopOwned(ctx);return {ok:true};
|
||||
}
|
||||
}).finally(()=>{this.#pending--;});
|
||||
this.#tail=operation;
|
||||
this.#cache.set(body.operationId,{signature,result:operation,generation:body.generation});return operation;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { createServer } from 'node:http';
|
||||
// Local experiment only. No public binding, MA dependency, credential, control route or deployment entrypoint.
|
||||
// Wire format: raw signed stereo PCM16 little endian, 24 kHz, 20 ms per frame.
|
||||
export async function startLoopbackAudio({ audio, campaign, session }) {
|
||||
const active = new Set();
|
||||
const server = createServer({ maxHeaderSize: 4096 }, (req, res) => {
|
||||
let listener;
|
||||
try {
|
||||
if (req.method !== 'GET' || req.url !== '/audio' || req.headers.host !== `127.0.0.1:${server.address().port}` ||
|
||||
req.headers['content-length'] || req.headers['transfer-encoding'] ||
|
||||
typeof req.headers.authorization !== 'string' || !req.headers.authorization.startsWith('Bearer ')) throw Error();
|
||||
listener = audio.connect({ campaign, session, origin: req.headers.origin,
|
||||
token: req.headers.authorization.slice(7) });
|
||||
} catch { res.writeHead(403, { 'Cache-Control': 'no-store' }); res.end(); return; }
|
||||
res.writeHead(200, { 'Content-Type': 'application/octet-stream', 'Cache-Control': 'no-store',
|
||||
'X-Content-Type-Options': 'nosniff', 'X-Audio-Format': 'pcm16le;rate=24000;channels=2' });
|
||||
res.flushHeaders();
|
||||
const connection = { res, listener, timer: null };
|
||||
const close = () => { clearInterval(connection.timer); listener.close(); active.delete(connection); };
|
||||
res.on('close', close);
|
||||
connection.timer = setInterval(() => {
|
||||
try {
|
||||
const frame = listener.next();
|
||||
// Never queue an unbounded stream for a slow consumer.
|
||||
if (frame && !res.write(frame.pcm)) res.destroy();
|
||||
} catch { res.destroy(); }
|
||||
}, 20);
|
||||
active.add(connection);
|
||||
});
|
||||
server.maxHeadersCount = 16; server.headersTimeout = 1000;
|
||||
server.requestTimeout = 1000; server.keepAliveTimeout = 1000;
|
||||
server.maxConnections = 32;
|
||||
await new Promise((resolve,reject) => { server.once('error',reject); server.listen(0,'127.0.0.1',resolve); });
|
||||
return {
|
||||
url: `http://127.0.0.1:${server.address().port}/audio`,
|
||||
async close() {
|
||||
for (const {res,listener,timer} of active) { clearInterval(timer); listener.close(); res.destroy(); }
|
||||
active.clear();
|
||||
const closed = new Promise((resolve,reject) => server.close(error => error ? reject(error) : resolve()));
|
||||
server.closeAllConnections(); await closed;
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
// Compatibility export; validated transport is shared with the GM-local browser path.
|
||||
export {MAReadClient} from '../src/providers/ma/client.mjs';
|
||||
@@ -0,0 +1,2 @@
|
||||
// Compatibility export; the same provider now runs with browser Web Crypto.
|
||||
export {MAPlaybackProvider} from '../src/providers/ma/provider.mjs';
|
||||
@@ -0,0 +1,19 @@
|
||||
import { MusicError } from '../src/core/controller.mjs';
|
||||
// Strict local-fixture decoder only. No file/network fetch or third-party codec.
|
||||
export function* pcmFixtureFrames(input) {
|
||||
const data=Buffer.from(input);
|
||||
if(data.length<44 || data.length>9000000 || data.toString('ascii',0,4)!=='RIFF' || data.toString('ascii',8,12)!=='WAVE' || data.readUInt32LE(4)+8!==data.length)throw new MusicError('unsupported');
|
||||
let format=false,pcm;
|
||||
for(let offset=12;offset+8<=data.length;){
|
||||
const kind=data.toString('ascii',offset,offset+4),length=data.readUInt32LE(offset+4);offset+=8;
|
||||
if(offset+length>data.length)throw new MusicError('unsupported');
|
||||
if(kind==='fmt '){
|
||||
if(length<16 || data.readUInt16LE(offset)!==1 || data.readUInt16LE(offset+2)!==2 || data.readUInt32LE(offset+4)!==24000 || data.readUInt16LE(offset+12)!==4 || data.readUInt16LE(offset+14)!==16)throw new MusicError('unsupported');
|
||||
format=true;
|
||||
}
|
||||
if(kind==='data'){if(pcm)throw new MusicError('unsupported');pcm=data.subarray(offset,offset+length);}
|
||||
offset+=length+(length%2);
|
||||
}
|
||||
if(!format || !pcm?.length || pcm.length%1920!==0)throw new MusicError('unsupported');
|
||||
for(let offset=0;offset<pcm.length;offset+=1920)yield Uint8Array.from(pcm.subarray(offset,offset+1920));
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { lstat, open } from 'node:fs/promises';
|
||||
import { constants } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { MusicError } from '../src/core/controller.mjs';
|
||||
// Fixed private file only. No environment secret, URL parameter or browser input.
|
||||
export async function loadMAToken(directory) {
|
||||
try {
|
||||
const dir = await lstat(directory);
|
||||
if (!dir.isDirectory() || dir.isSymbolicLink() || (dir.mode & 0o777) !== 0o700 || dir.uid !== process.getuid()) throw Error();
|
||||
const file = await open(join(directory, 'ma-token'), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
||||
try {
|
||||
const info = await file.stat();
|
||||
if (!info.isFile() || (info.mode & 0o777) !== 0o600 || info.uid !== process.getuid() || info.size > 16384) throw Error();
|
||||
const token = (await file.readFile('utf8')).trim();
|
||||
if (!token || /[\r\n]/.test(token)) throw Error();
|
||||
return token;
|
||||
} finally { await file.close(); }
|
||||
} catch { throw new MusicError('denied'); }
|
||||
}
|
||||
|
||||
// Separate from the MA token. Back up this private key to preserve scene identifiers.
|
||||
export async function loadCatalogKey(directory) {
|
||||
const { randomBytes } = await import('node:crypto');
|
||||
const path = join(directory, 'catalog-key');
|
||||
// Reuse the directory/token owner-mode validation before creating private state.
|
||||
await loadMAToken(directory);
|
||||
try {
|
||||
const created = await open(path, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
|
||||
try { await created.writeFile(randomBytes(32)); await created.sync(); }
|
||||
finally { await created.close(); }
|
||||
} catch (error) { if (error.code !== 'EEXIST') throw new MusicError('denied'); }
|
||||
const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
||||
try {
|
||||
const info = await file.stat();
|
||||
if (!info.isFile() || info.uid !== process.getuid() || (info.mode & 0o777) !== 0o600 || info.size !== 32) throw new MusicError('denied');
|
||||
return await file.readFile();
|
||||
} finally { await file.close(); }
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
// Explicit private development companion. Never launched by the Foundry module.
|
||||
import {open} from 'node:fs/promises';
|
||||
import {constants} from 'node:fs';
|
||||
import {randomUUID} from 'node:crypto';
|
||||
import {MAReadClient} from './ma-client.mjs';
|
||||
import {loadMAToken,loadCatalogKey} from './private-config.mjs';
|
||||
import {GatewayControl} from './control.mjs';
|
||||
import {DevelopmentService} from './development-service.mjs';
|
||||
import {startDevelopmentHTTP} from './development-http.mjs';
|
||||
import {SyntheticAudioGateway} from './synthetic-audio.mjs';
|
||||
async function privateJSON(name,value){const file=await open(`.local/${name}`,constants.O_WRONLY|constants.O_CREAT|constants.O_NOFOLLOW,0o600);try{const info=await file.stat();if(!info.isFile()||(info.mode&0o777)!==0o600||info.uid!==process.getuid())throw Error();await file.truncate(0);await file.writeFile(JSON.stringify(value,null,2));}finally{await file.close();}}
|
||||
let activeServer,sourceTimer;
|
||||
async function readPrivate(name){const file=await open(`.local/${name}`,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const info=await file.stat();if(!info.isFile()||(info.mode&0o777)!==0o600||info.uid!==process.getuid()||info.size>1048576)throw Error();return JSON.parse(await file.readFile('utf8'));}finally{await file.close();}}
|
||||
try{
|
||||
await loadMAToken('.local');
|
||||
const config=await readPrivate('development-gateway.json');
|
||||
if(Object.keys(config).some(k=>!['foundryOrigin','proxyHost','syntheticAudio','enableSyntheticControl'].includes(k))||['proxyHost','syntheticAudio','enableSyntheticControl'].some(k=>config[k]!==undefined&&typeof config[k]!=='boolean'))throw Error();
|
||||
const environment=await readPrivate('environment.json');
|
||||
const verified=await readPrivate('ma-readonly-results.json');
|
||||
const origin=new URL(config.foundryOrigin);
|
||||
if(origin.origin!==config.foundryOrigin||origin.protocol!=='https:'&&!['localhost','127.0.0.1'].includes(origin.hostname)||verified.me.player_filter.length!==1||verified.player.name!=='Adaptive Music DEV')throw Error();
|
||||
const campaign=randomUUID(),session=randomUUID(),snapshotKey=await loadCatalogKey('.local');
|
||||
// Persist the opaque campaign namespace independently from ephemeral session/grants.
|
||||
let namespace;
|
||||
try{namespace=(await readPrivate('catalog-namespace.json')).campaign;}catch(error){if(error.code!=='ENOENT')throw error;namespace=randomUUID();await privateJSON('catalog-namespace.json',{campaign:namespace});}
|
||||
if(typeof namespace!=='string'||!namespace||namespace.length>256)throw Error();
|
||||
let sequences={};if(config.enableSyntheticControl){const fixture=await readPrivate('fixture-origin.json');sequences=Object.fromEntries(Object.entries(fixture.sequences).map(([kind,names])=>[`synthetic-${kind}`,names.map(name=>`builtin://track/${fixture.base_url}/${name}`)]));}
|
||||
const client=new MAReadClient({baseUrl:environment.ma_url,token:await loadMAToken('.local'),target:verified.me.player_filter[0],approvedProviders:verified.me.provider_filter,
|
||||
catalogKey:snapshotKey,campaign:namespace,expectedName:'Adaptive Music DEV',expectedProvider:verified.player.provider,syntheticSequences:sequences});
|
||||
const control=new GatewayControl({campaigns:{[campaign]:{client}},origin:origin.origin});
|
||||
const controller=control.mint({campaign,session,role:'controller',ttlMs:300000}),listener=control.mint({campaign,session,role:'listener',ttlMs:300000});
|
||||
let audio;if(config.syntheticAudio){audio=new SyntheticAudioGateway({control});audio.provision({campaign,session});}
|
||||
const service=new DevelopmentService({control,campaign,session,client,snapshotKey,allowedIds:Object.keys(sequences),playbackEnabled:config.enableSyntheticControl===true,audio});
|
||||
const server=await startDevelopmentHTTP({service,origin:origin.origin,expectedHost:config.proxyHost?origin.host:undefined});
|
||||
activeServer=server;
|
||||
await privateJSON('development-gateway-runtime.json',{url:server.url,expires:new Date(Date.now()+300000).toISOString()});
|
||||
await privateJSON('controller-bootstrap.json',{token:controller,campaign,session});
|
||||
await privateJSON('listener-bootstrap.json',{token:listener,campaign,session});
|
||||
let generation=0,sample=0;
|
||||
const timer=sourceTimer=audio&&setInterval(()=>{const pcm=new Uint8Array(1920),view=new DataView(pcm.buffer);for(let i=0;i<480;i++){const value=Math.round(500*Math.sin(2*Math.PI*220*sample++/24000));view.setInt16(i*4,value,true);view.setInt16(i*4+2,value,true);}audio.publish({campaign,session,generation:++generation,pcm});},20);
|
||||
let closing=false;
|
||||
const close=async()=>{if(closing)return;closing=true;clearInterval(timer);control.revoke(controller);control.revoke(listener);await server.close();process.exitCode=0;};
|
||||
process.once('SIGINT',close);process.once('SIGTERM',close);setTimeout(close,300000).unref();
|
||||
console.log('Private loopback companion ready for five minutes. Connection codes and address are in .local/; no MA playback starts on launch.');
|
||||
}catch{clearInterval(sourceTimer);await activeServer?.close();console.error('Companion startup failed; check protected .local configuration and origin. Details withheld.');process.exitCode=1;}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { MusicError } from '../src/core/controller.mjs';
|
||||
// In-process transport prototype; accepts only operator-generated 20 ms PCM fixtures.
|
||||
// No Sendspin socket, upstream URL, codec negotiation, network listener or MA connection.
|
||||
export class SyntheticAudioGateway {
|
||||
#control; #streams = new Map(); #connections = new Set();
|
||||
constructor({ control }) { this.#control = control; }
|
||||
// Operator-only session bootstrap; rotate on gateway restart. Never a browser route.
|
||||
provision({ campaign, session }) {
|
||||
if (!this.#control.campaigns.has(campaign) || !session || this.#streams.has(campaign)) throw new MusicError('denied');
|
||||
this.#streams.set(campaign, { session, generation: 0, frames: [] });
|
||||
}
|
||||
// Operator-only synthetic source. Real sources must acquire/check the authority fence.
|
||||
publish({ campaign, session, generation, pcm }) {
|
||||
const stream = this.#streams.get(campaign);
|
||||
if (!stream || stream.session !== session || !Number.isSafeInteger(generation) || generation !== stream.generation + 1) throw new MusicError('stale');
|
||||
if (!(pcm instanceof Uint8Array) || pcm.byteLength !== 1920) throw new MusicError('denied');
|
||||
stream.generation = generation;
|
||||
stream.frames.push({ generation, pcm: Uint8Array.from(pcm) });
|
||||
// At most 200 ms of stereo PCM16 at 24 kHz per campaign, no disk cache.
|
||||
if (stream.frames.length > 10) stream.frames.shift();
|
||||
}
|
||||
#check(request) {
|
||||
if (!request || Object.keys(request).sort().join(',') !== 'campaign,origin,session,token') throw new MusicError('denied');
|
||||
this.#control.authorize(request.token, request.origin, request.campaign, request.session, 'listener');
|
||||
const stream = this.#streams.get(request.campaign);
|
||||
if (!stream || stream.session !== request.session) throw new MusicError('denied');
|
||||
return stream;
|
||||
}
|
||||
connect(request) {
|
||||
const stream = this.#check(request);
|
||||
this.sweep();
|
||||
if ([...this.#connections].filter(c => c.request.campaign === request.campaign).length >= 16) throw new MusicError('denied');
|
||||
const connection = { request: { ...request }, cursor: stream.generation, closed: false };
|
||||
this.#connections.add(connection);
|
||||
const close = () => { connection.closed = true; this.#connections.delete(connection); };
|
||||
return {
|
||||
close,
|
||||
get closed() { return connection.closed; },
|
||||
next: () => {
|
||||
try {
|
||||
if (connection.closed) throw new MusicError('denied');
|
||||
const current = this.#check(connection.request);
|
||||
const frame = current.frames.find(f => f.generation > connection.cursor);
|
||||
// Fail closed for listeners that fell behind the bounded ring.
|
||||
if (current.frames.length && connection.cursor < current.frames[0].generation - 1) throw new MusicError('stale');
|
||||
if (!frame) return null;
|
||||
connection.cursor = frame.generation;
|
||||
return { generation: frame.generation, pcm: Uint8Array.from(frame.pcm), sampleRate: 24000, channels: 2 };
|
||||
} catch (error) { close(); throw error; }
|
||||
}
|
||||
};
|
||||
}
|
||||
// A future transport must schedule this and close its socket when a handle closes.
|
||||
sweep() {
|
||||
for (const connection of this.#connections) {
|
||||
try { this.#check(connection.request); }
|
||||
catch { connection.closed = true; this.#connections.delete(connection); }
|
||||
}
|
||||
}
|
||||
purge(campaign) {
|
||||
this.#streams.delete(campaign); this.sweep();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user