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

+29
View File
@@ -0,0 +1,29 @@
name: Validate and generate manual release
on:
push:
tags: ['v*']
workflow_dispatch:
jobs:
package:
# Map this existing runner label to a host/shell executor, not a Docker image.
runs-on: [self-hosted, linux, adaptive-music-release]
steps:
- uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
with:
persist-credentials: false
- name: Validate and generate offline artifacts
env:
RELEASE_REPOSITORY: ${{ vars.RELEASE_REPOSITORY }}
run: |
node --version
node --test tests/js/*.test.mjs
python3 -m unittest discover -s tests -v
python3 scripts/audit_repository.py
python3 scripts/ci_release.py
# Gitea's artifact protocol varies by instance version; this pinned v3 action
# is for compatible existing instances. Manual local generation needs no CI.
- uses: https://github.com/actions/upload-artifact@c6a366c94c3e0affe28c06c8df20a878f24da3cf
with:
name: adaptive-music-manual-release
path: dist/releases/
if-no-files-found: error
+29
View File
@@ -0,0 +1,29 @@
name: Validate and generate manual release
on:
push:
tags: ['v*']
workflow_dispatch:
permissions:
contents: read
jobs:
package:
# Existing shell runner only; this workflow provisions no VM/container/service.
runs-on: [self-hosted, linux, adaptive-music-release]
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
with:
persist-credentials: false
- name: Validate and generate offline artifacts
env:
RELEASE_REPOSITORY: ${{ vars.RELEASE_REPOSITORY }}
run: |
node --version
node --test tests/js/*.test.mjs
python3 -m unittest discover -s tests -v
python3 scripts/audit_repository.py
python3 scripts/ci_release.py
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
with:
name: adaptive-music-manual-release
path: dist/releases/
if-no-files-found: error
+12
View File
@@ -0,0 +1,12 @@
.local/
.env
.env.*
!.env.example
node_modules/
dist/
coverage/
__pycache__/
*.pyc
*.pem
*.key
*.log
+31
View File
@@ -0,0 +1,31 @@
# Adaptive Music contributor instructions
Adaptive Music is an independent open-source project by CheddahBoxMB targeting
Foundry VTT v14.371 and Music Assistant (MA) 2.10.6. It is system-independent.
- Read ARCHITECTURE.md, SECURITY.md, TESTING.md and PROGRESS.md before changes.
- Milestone 1 is research and repository scaffolding. No installable module or
working gateway exists yet. Never label design, source inspection, mocks or
offline checks as verified live integration.
- Require no other Foundry modules. Do not import ATLAS, system-specific actor
schemas, proprietary source, subscription services or telemetry.
- Do not alter production Foundry, MA, Sonos, Nginx, firewall or service versions.
Ask before credential use or production changes. Never request unrestricted root.
- Keep endpoints, credentials, campaign/player mappings and deployment files under
ignored .local/ (directory mode 0700, secret files 0600). Never place MA tokens in
Foundry settings, browser bundles, flags, URLs or logs. Examples use placeholders.
- MA access belongs on the gateway; browsers receive campaign-scoped capabilities.
Never implement an unrestricted MA HTTP/WebSocket/Sendspin proxy.
- Only a campaign-owned dedicated audio target is eligible for control. Do not
discover-and-select household players, transfer queues, group speakers or issue
global stops. Native sound effects and AmbientSound documents are out of scope.
- Serialize transitions under a fenced authority lease; snapshots and commands
carry campaign, session and generation. Reject stale events and restores.
- Preserve upstream notices for reused source. Record exact versions, commits,
licenses and dependencies before adding code. Do not run upstream install hooks
merely to inspect source. Lock and audit dependencies before distribution.
- Run `python3 -m unittest discover -s tests -v` and
`python3 scripts/audit_repository.py` before a commit. Run
`python3 scripts/verify_upstream.py` when local research checkouts are available.
- Update evidence and verification status with every meaningful implementation.
Do not invent Gitea remotes, release URLs, Foundry verification or test results.
+193
View File
@@ -0,0 +1,193 @@
# Adaptive Music architecture — 0.5.0 local release candidate
Independent project by **CheddahBoxMB**, system-independent, targeting Foundry
**v14.371** and MA **2.10.6**. Standard distribution is **one Foundry module ZIP**
with a stable Git-hosted manifest and immutable version-specific download URL.
No mandatory Foundry modules, containers, VMs/LXCs, sandbox runtime, core patches,
OS-service installer, subscription or telemetry. Planned Gitea URLs are configured
but the host/repository has not been contacted or confirmed to exist.
## Decision after reevaluation
The 0.4.0 companion is **not a mandatory architecture**. Native playback and all
scene/world/combat/boss/manual rules remain entirely module-local. The preferred
MA experiment is a trusted GM-browser host using the official Sendspin browser
SDK, Web Audio and WebRTC audio tracks. Its feasibility is conditional on secure
private MA reachability, an authorized existing receiver identity, GM availability,
participant capabilities and a working ICE path. It cannot yet be represented as
reliable module-only remote MA audio for arbitrary networks.
The validated companion remains under `gateway/` and local branch
`experimental/companion-0.4.0`; provider/catalog/restoration code is preserved.
Shared Web Crypto transport/provider implementations now serve both GM and optional
companion, with compatibility exports at the original gateway paths. All original
regressions remain. If the browser gates cannot be met, propose one manually run,
restricted process **co-located on the existing Foundry host**. No new machine,
container or automatic service is proposed or deployed. Placement/routing and any
manual service registration require explicit approval after concrete review.
```mermaid
flowchart LR
F[Foundry scene and combat policy] --> C[Existing serialized controller]
C --> N[Owned native playlist provider]
C --> M[Shared guarded MA provider in trusted GM browser]
M -->|private authenticated API WebSocket| A[Private MA 2.10.6]
A -->|authenticated Sendspin to pinned existing identity| S[Official SDK in GM browser]
S --> W[Web Audio MediaStream]
W -->|DTLS SRTP media tracks| P[Authorized player browsers]
G[Foundry module socket] <-->|bounded encrypted SDP only| S
G <-->|bounded encrypted SDP only| P
```
No raw audio or MA token uses the ordinary module socket. No MA HTTP/WS/Sendspin
proxy is exposed to players. No microphone is requested and no RTC control data
channel is accepted. A GM's credentials are **not hidden from that GM/browser user**;
all code executing in that browser origin must be trusted. Other player browsers
never receive the MA credential, SDK identity, private queue snapshots or endpoint.
## What is measured
`evidence/browser-audio.json`: actual Chromium **143.0.7499.4**, two independent
listener browser contexts, original 440 Hz synthetic PCM encoded in Sendspin binary
frames and decoded by the pinned official SDK, Web Audio -> WebRTC -> HTMLAudio /
listener analyser. Both listeners had signal after **1,757 ms**, FFT peak **445.3125
Hz** (bin resolution around the 440 Hz source), RMS about **0.054**, aggregate GM RTP
payload **42.3 kbps** over **4.766 seconds**. Four encrypted signaling messages,
maximum **2,078 bytes**; no audio on the signaling channel. Localhost, no TURN, no
MA/Noise handshake, no real Foundry socket, no hardware audibility claim, no WAN,
interlistener skew or long-run drift measurement. These are synthetic path results,
not MA playlist playback or synchronization verification.
Live dedicated target/queue reads still verify the existing DEV identity and an
empty idle queue. `module-only-prerequisites.json`: the configured MA origin is
HTTP, the HTTPS-host access policy rejects it as mixed content, and no authorized
DEV private SDK identity is available locally. **Zero new Sendspin connections,
identities or playback mutations.** Earlier read-only catalogs and bounded idle
controls remain separate evidence; synthetic ingestion previously failed.
## Browser access and GM-local authentication
`GMAudioHost` uses a private, memory-only profile supplied by the GM, with canonical
MA origin, dedicated target ID/name/provider, approved provider filter, catalog key/
namespace and existing SDK identity/pairing storage. Nothing is saved into Foundry
settings, flags, browser localStorage, module socket or a release. Catalog IDs remain
HMAC-derived and stable when the operator retains the same private key/namespace.
The official public `/ws` control API avoids dependence on cross-origin HTTP `/api`
preflight, which is not configured for that route in the inspected MA pin. The same
fixed client command allowlist, response bounds, timeout, redirect policy, target
checks and registered-media rules are preserved through the WebSocket adapter.
Its initial auth command carries the GM's token in a private connection, never a
URL; unsolicited events are discarded. The Sendspin `/sendspin` connection uses
the official frontend's first-message auth pattern, then the official SDK's Noise
transport. The SDK's fixed roles include controller/metadata; it runs only in the
trusted GM host, never as a supposedly restricted player listener.
A source-derived privacy gate matters: pinned MA `websocket_client.py` logs raw
received frames at VERBOSE, including auth. The GM profile requires an explicit
operator `webSocketAuthLogSafe` acknowledgment after ensuring such payload logging
is disabled. This has **not** been verified live or changed by the agent. No live
WebSocket token test was attempted. The module logs no credential and does not
modify MA logging/core. An adapter cannot redact the remote server's own logs.
HTTPS Foundry -> plain HTTP/ws private MA is not a generally portable browser path,
even with encrypted Sendspin payloads. CSP, browser local-network access rules,
Origin policy, TLS trust and private routing still apply. Current policy refuses
that deployment rather than disabling browser protections. Local-network exceptions
in particular browsers are not a cross-browser guarantee. A private trusted HTTPS/
WSS MA endpoint reachable by the GM, or the approved co-located restricted worker,
is required. Players do not need MA network access.
SDK identity is derived from an X25519 private key. A player name or ID alone cannot
reconstruct it. The code checks the supplied identity matches **Adaptive Music DEV**
before any receiver connection; no random replacement, discovery-and-select, pairing
or internal virtual-player provisioning occurs. Operator-controlled handover from
the original web player is needed. Read-only identity/topology checks may inspect
the known unavailable target during handover; every mutation still requires full
availability, exact name/provider, own active queue and standalone topology.
## WebRTC signaling, authorization and transport
Foundry's supported `game.socket`/module channel is a relay, not an authenticated
claim of sender identity. We do **not** trust a payload `userId`/`isGM` or assume
that broadcast destinations enforce confidentiality. The GM explicitly issues a
unique short-lived 256-bit per-listener invitation, delivered over an authenticated
private channel outside the module broadcast. Possession authorizes only that peer;
it does not prove a Foundry login cryptographically, and a recipient can forward
its own capability/audio. No automatically broadcast bootstrap exists.
`SignalCodec` authenticates/encrypts SDP (including ICE addresses/DTLS fingerprints)
with AES-GCM, session/peer/direction/sequence binding, nonce, expiry, size/type limits
and replay checks rechecked after asynchronous decryption. A listener can affect
only its own peer; another peer has another key. `PeerAudio` permits one recvonly
listener offer and audio-only answer, rejects video/data/outbound listener audio,
bounds peers, drops unknown frames, permits at most two explicit ICE restarts, and
revokes on expiry, disconnect or authorization reconciliation. Continuous media is
browser-managed DTLS-SRTP, never JSON PCM over Foundry sockets.
Default ICE servers are **empty**: no silent external STUN/TURN or telemetry.
Operator-provided STUN/TURN configuration is explicit. TURN credentials must be
short-lived; relay-only mode requires TURN and avoids direct peer candidates.
Authorized peers can inspect their own ICE/network details and credentials. Direct
P2P may disclose GM/peer network addresses to the authorized peer; encryption hides
SDP from other world clients, not its intended recipient. No secrets are protected
from the browser's own user. Existing public-interface references:
[Foundry Game/socket](https://foundryvtt.com/api/v14/classes/foundry.Game.html),
[WebRTC connectivity](https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Connectivity),
[mixed content](https://developer.mozilla.org/en-US/docs/Web/Security/Defenses/Mixed_content).
Symmetric NAT, CGNAT, UDP filtering and restrictive corporate networks can need TURN;
STUN alone cannot guarantee connectivity. A relay must already exist or be separately
approved, not installed as another container/VM by this module. One GM peer connection
per listener means approximately linear GM upload/encoding cost. The 42.3 kbps local
measurement is two listeners and short synthetic content, not a capacity promise.
Browser jitter buffers, suspend/background policy and output devices introduce
independent playout delay: Sendspin's upstream timestamps do not create synchronized
WebRTC outputs automatically. Measure WAN jitter/skew and 30-minute drift before any
sync guarantee. Crossfade and concurrent ambient layers remain unimplemented.
## Authority, lifecycle and restoration
Policy remains manual (including silence) > explicit eligible boss > started active
combat for the scene > scene ambient > world default > silence. Bosses use module
flags/priority, no actor HP/schema. Scene/world assignments, explicit native fallback,
legacy flag migration, snapshots, interrupted paused offsets and duplicate ordered
occurrences are preserved. Ambient is currently the single interrupted base queue;
AmbientSound and effects remain untouched. Optional companion control retains its
expiring fenced lease; native document ownership stays explicitly opted in.
GM-local control shares the same serialized, generation-checked provider and target
checks. A Web Lock excludes duplicate GM tabs on the same origin; startup requires
one active GM and a known empty idle target. This is **not a distributed server fence**
and cannot prevent a malicious/stale independent GM client with its own MA token.
The module refuses automatic split-brain handover and invalidates authority on
Foundry disconnect. Permanent strict multi-writer fencing needs the approved worker.
No browser-only design can manufacture an MA server-side compare-and-swap lease.
GM loss stops WebRTC forwarding and automated writes; it cannot guarantee immediate
restoration after a crashed/offline browser, and already delivered audio cannot be
revoked from a recipient. SDK-adopted sockets do not auto-reconnect. Explicit reconnect
requires target reconciliation, same identity, secure access, new peer invitations
and role checks. Native fallback cannot silently bypass an uncertain active MA target.
The preserved MA snapshots are signed, scoped to campaign/session/fence/generation,
expire after five minutes and carry ordered occurrences, index, whole-second offset,
pause/state and repeat. Capture repeats pagination; restore stages ordered items,
checks them and seeks. Shuffled/dynamic/autoplay/overlay/ended/nonstandard speed
states are unsupported. Remote ambiguity latches closed rather than retrying blindly.
Restart/crash durability, shuffled restoration and true cross-client fencing remain
acceptance gates. The bounded live harness still captures/restores original state;
closing an experimental GM tab is not claimed to restore MA automatically.
## Optional minimal co-located fallback
If secure private browser reachability, network traversal or GM uptime is unacceptable,
review a single non-root worker on the **existing Foundry host**, using existing host
runtime/network capacity and protected state. It would terminate only the dedicated
MA receiver, hold credentials server-side, enforce controller/listener authorization
and expose restricted campaign audio/control through the existing TLS origin. It
must never forward arbitrary MA API/WS/Sendspin messages. Existing `gateway/` code is
a validated starting point, but actual Sendspin termination, durability and production
security remain work. No system service is installed automatically, no host is
provisioned and no Foundry/MA core is changed. Any real route/placement/deployment
must be proposed concretely and approved first; nothing is deployed here.
+33
View File
@@ -0,0 +1,33 @@
# Changelog
## 0.5.0 — local release candidate
- Prepare one standard Foundry module ZIP and offline manual-upload release bundle
for the planned Gitea destination, with configurable GitHub/Gitea URL generation,
stable update manifest, immutable versioned download and SHA256 checksums.
- Preserve validated native playback, scene/world assignments, combat/boss/manual
policy, catalog, guarded MA transport and queue restoration. Share the same
transport/provider implementation between the optional companion and trusted GM
browser using Web Crypto.
- Add pinned official Sendspin JS 5.0.0 PCM-only bundle with dependency lock, audit,
full notices and recorded modification (optional Opus fallback omitted).
- Add experimental GM-local SDK decoding/Web Audio and encrypted, per-listener
capability-signaled WebRTC audio. Module sockets carry no continuous raw audio.
- Keep the companion as an optional, undeployed co-located fallback; no container,
VM/LXC, OS-service installer, core patch or sandbox runtime dependency.
- Remote MA audio is not yet verified: existing DEV private identity, secure browser
reachability, synthetic ingestion and real NAT/browser/Foundry gates remain.
Crossfade, simultaneous ambient layers and seamless GM handover remain unsupported.
## 0.4.0-dev
- Connected GM setup, scene ambient/combat/boss defaults and native fallback with the
private companion and MA catalog. Measured connected read-only MA catalog locally;
added synthetic PCM browser sink and loopback integration tests.
## 0.3.0-dev
- Added guarded MA playback provider, durable catalog identifiers, signed ordered
queue snapshots/restoration and isolated native Foundry development package.
- Live idle queue control tests restored original state. Synthetic ingestion failed;
no nonempty MA queue or real playlist playback was verified.
+150
View File
@@ -0,0 +1,150 @@
# Adaptive Music 0.5.0 — manual release and installation
Module ID **adaptive-music**, author **CheddahBoxMB**, Foundry generation **14**;
system-independent, no mandatory Foundry modules. Native operation needs only this
module ZIP. No container, VM/LXC, Ubuntu sandbox, core patch or automatically installed
OS service is required. GM-local MA/WebRTC audio remains experimental; limitations
and measured results are in ARCHITECTURE.md and evidence/browser-audio.json.
## Build offline without Git credentials or a remote
From this repository (Python 3 standard library; local Git metadata is optional):
```
python3 scripts/release.py
python3 scripts/release.py --validate dist/releases/v0.5.0/adaptive-music.zip
```
This creates `dist/releases/v0.5.0/adaptive-music-release-v0.5.0.zip`. It contains:
`adaptive-music.zip`, standalone `module.json`, `adaptive-music-source.zip`, README,
this INSTALL guide, CHANGELOG, LICENSE, THIRD-PARTY-NOTICES, all vendor license
texts, `release.json` and `SHA256SUMS`. The SDK bundle is committed, so packaging
needs no npm installation, browser download, network, Git token or Git-host access.
The builder never verifies, contacts, creates or pushes a remote repository.
For another host, for example your own public GitHub repository:
```
python3 scripts/release.py --repository https://github.com/OWNER/adaptive-music --output dist/github-release
```
Use a real destination under your control. The generated manifest's `url`, stable
`manifest` and version-specific `download` are changed together. The builder does
not write to the Git host or alter the root manifest. It validates identity, v14
compatibility, import/assets closure, SDK hash, licenses, private-file exclusion and
public HTTPS URL shape locally. This cannot prove that a planned URL exists.
## Upload to the planned Gitea destination manually
Planned repository (existence/access **not checked**):
`https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music`
1. On your own initiative, use Gitea's web UI to create/confirm that repository and
enable public read access to the source manifest and release attachments. Foundry
must be able to fetch them without Git credentials. This exposes release files,
not MA. This agent has not accessed or authenticated with your Gitea server.
2. Unpack the **source archive**, not the outer release bundle, into the repository
using your normal Git/web upload workflow. Preserve directory structure, notices,
scripts and the generated root `module.json`. Exclude `.local/`, node_modules,
private deployment files and credentials. Do not upload an outer bundle as the
module contents. If web upload cannot preserve folders, use your own local Git
client; no credential is needed by the release builder itself.
3. Create tag/release **v0.5.0** for this version. Keep that tag immutable. Paste the
CHANGELOG entry into the release notes. Do not mark this unverified development
release as Foundry-verified or production-ready.
4. Upload **adaptive-music.zip** and **module.json** as release attachments with
those exact names. Upload source/archive, SHA256SUMS, docs/notices or the full
outer bundle as additional review artifacts. Never use the source ZIP or outer
bundle as the module download attachment.
5. After publishing, manually verify anonymous downloads and checksums. The module
ZIP should resolve at:
`https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/releases/download/v0.5.0/adaptive-music.zip`
6. Ensure `main/module.json` is the generated standalone manifest. The stable
installation/update URL is:
`https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/raw/branch/main/module.json`
This URL is deliberately stable across releases. Do not give Foundry a tag-specific
manifest URL if you expect automatic version discovery.
No URL above was requested by the build/validation process. Uploading/publishing is
manual; no token, remote connection, automatic push or release publication is used.
## Install and update through Foundry
Once the public manifest and release attachments actually exist:
1. In isolated Foundry v14 Setup → Add-on Modules → Install Module, paste the stable
manifest URL above and install. Enable Adaptive Music in the isolated world.
2. Configure Settings → Adaptive Music setup: select dedicated native music playlists,
save ownership/reload, set world/scene ambient/combat/boss/native fallback choices,
then enable automation. Sound effects/AmbientSound are excluded. Automation
defaults off. Test real v14.371 behavior before considering production use.
3. For later versions, preserve the module ID and stable manifest URL. Bump semantic
version in module.json/package.json/lockfile, update CHANGELOG and build a new
immutable tag-specific release. The versioned ZIP URL must change with version.
4. Publish new attachments **before promoting the new standalone manifest to main**.
Prepare on a release branch/tag if needed, leaving the previous main manifest
untouched until assets are available. Never overwrite a previous version's ZIP.
5. Foundry Setup → Update Modules should discover the newer manifest version and
download its new ZIP while keeping world/document settings. This is the standard
update contract and is validated structurally, not measured against your server.
GitHub uses the same ZIP and upload process, with a stable generated manifest at
`https://raw.githubusercontent.com/OWNER/adaptive-music/main/module.json` and ZIP at
`https://github.com/OWNER/adaptive-music/releases/download/v0.5.0/adaptive-music.zip`.
Optional pinned GitHub/Gitea CI workflows only test/build artifacts for manual
publication on an already provisioned runner. They install no runner/service or
runtime infrastructure. CI/host execution has not been validated on your Gitea.
## GM-local MA and WebRTC experiment
The intended module-only path is: private MA → official Sendspin JS SDK in the GM
browser → Web Audio → encrypted WebRTC audio tracks → authorized player browsers.
Foundry module sockets carry only encrypted bounded SDP/control, never continuous
raw audio or an MA token. No STUN/TURN service is silently selected. Per-listener
invitations must be delivered privately, not posted to a module socket/public flag.
The GM must be able to reach MA privately over a browser-allowed secure connection.
An HTTPS Foundry page cannot be assumed to access plain HTTP/ws MA just because the
Sendspin payload is encrypted. CSP, local-network permissions and server Origin policy also apply. The GM-local control adapter uses the official /ws API because HTTP /api CORS preflight is not enabled in the inspected MA pin.
No mixed-content bypass or public MA route is provided. Browser-local MA credentials
are visible to that GM/user and any compromised code running in their browser;
this design does not claim otherwise. Players never receive those credentials.
Developer API (explicit operator actions; no automatic playback on module enable):
- `api = game.modules.get('adaptive-music').api`
- `api.readGMCatalog(profile)` reads through GM-local authentication.
- `api.startGMHost(profile)` must be invoked directly by a user gesture with automation
stopped and the optional companion disconnected. `profile` stays in GM memory.
- `api.inviteListener(userId, {iceServers: []})` creates a unique expiring invitation.
Deliver it over a private authenticated channel to that participant.
- Player gesture: `api.listenWebRTC(invitation)`. No microphone/control channel.
- `api.peerStats()` returns sanitized bandwidth/jitter statistics.
- `api.closeGMHost()` tears down the local host. MA state recovery still requires
the existing guarded bounded test procedure; do not assume tab closure restores MA.
The private profile requires MA origin/token, pinned existing DEV ID/name/provider,
approved providers, a base64 32-byte catalogKey and namespace retained privately,
plus the **existing DEV Sendspin identity and pairing storage**, and `webSocketAuthLogSafe: true` only after verifying that MA raw WebSocket payload logging at VERBOSE is disabled. The pinned server would otherwise log the auth frame/token; no logging configuration was changed or verified here. No real profile is bundled or
stored in world settings/flags/localStorage. `campaign` is supplied by the module.
Use only previously approved generated synthetic sequences and explicit synthetic
playback opt-in; real library playlist playback is a separate authorization gate.
The current sandbox has **no existing DEV private identity**. The module refuses to
register a random replacement or hijack a name-matching player. The GM must privately
supply an authorized export of the existing web player's identity, or separately
approve a new dedicated identity and update the target/account binding. No such
provisioning has occurred. Synthetic files also still need to be reachable by MA.
WebRTC without a configured relay cannot guarantee remote connections behind all
NAT/firewall combinations. TURN, if required, must be an explicitly approved existing
service with short-lived credentials; no new container/VM or service is installed.
The GM's upload scales with listener count and their browser must stay running.
Startup also requires one active GM, a browser Web Lock and a reconciled empty idle test target. Read-only identity checks can inspect the known unavailable target during operator handover; every mutation still rechecks full availability/topology. GM loss stops forwarding, invalidates automation authority and requires explicit
reconciliation/reconnection; no seamless handover or distributed MA fence is claimed.
If browser access/NAT/GM-availability gates cannot be satisfied, an optional minimal
co-located worker on the **existing Foundry host** is the fallback design. Its source
is retained in gateway/ and branch experimental/companion-0.4.0. It is not installed,
started or required by the module. Any host placement, TLS route or manual service
registration needs separate approval; MA remains private. No core modifications.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 CheddahBoxMB
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+104
View File
@@ -0,0 +1,104 @@
# Adaptive Music progress — 0.5.0
Continued from `50c3a7c`; the complete 0.4.0 companion implementation is preserved
at local branch `experimental/companion-0.4.0` as well as in `gateway/`. The original
0.3.0 ZIP gap audit remains `evidence/package-objective-audit.json`; it describes
that historical package, not the current release. No validated code was discarded.
## Implemented
The standard release is one module ZIP, ID `adaptive-music`, author CheddahBoxMB,
Foundry generation 14, no mandatory modules or system dependency. Python's offline
builder produces a complete manual upload bundle, stable manifest/versioned download,
source archive, docs/licenses and checksums. Gitea/GitHub repository base is configurable.
The default destination is the user's **planned, unconfirmed** Gitea repository.
It was not contacted, authenticated with, created or pushed to. Git remotes and
credentials are not required. CI artifact workflows are prepared but unexecuted;
no runner or OS service is installed. Publication and hosted updates are unverified.
Native playback and scene/world/combat/boss/manual configuration are preserved.
Persistent ambient/combat/boss/native fallback references, world defaults, legacy
migration, explicit combatant flags and native ownership remain connected to the
existing controller. The shared guarded MA client/provider now use Web Crypto,
retaining the optional companion import paths and stable catalog IDs/signatures.
The new experimental GM host uses the official pinned Sendspin 5.0.0 SDK, a
reproducible PCM-only browser bundle with audited notices, Web Audio termination
and WebRTC audio tracks. GM-local MA authentication uses the public `/ws` API;
no raw unrestricted proxy, browser player credential or external CDN is introduced.
The existing DEV private identity must match before a receiver connection; no new
identity/target/pairing or internal provisioning was attempted. Only approved
synthetic sequences can be controlled by this path. Real catalog selections are
available through the developer connection API and existing assignment UI; actual
playlist playback is still separately gated. GM setup for MA remains developer-API
based; there is no claim of a finished one-click connection wizard.
Listener capabilities are separate from controller access. Foundry module sockets
carry per-peer encrypted bounded SDP/control; WebRTC transports continuous audio.
No microphone, video, data channel, automatic STUN/TURN or raw PCM socket transport.
Expiry, revocation, role changes and disconnect tear down peers; there are bounded
explicit ICE restarts. Same-origin GM Web Locks and a single-active-GM check reject
obvious conflicts, but do not constitute a distributed MA fence. Memory-only secret
handling cannot hide secrets from the GM browser's own user.
## Actual observations
- **85 JS / 15 Python tests pass**; repository privacy/attribution and recorded
upstream hashes pass. Online npm advisory audit reports zero vulnerabilities.
The SDK and dependencies are pinned; no installation hooks ran. Exact command
evidence is retained in `evidence/development-checks.txt`.
- An actual Chromium decoder → Web Audio → WebRTC experiment delivered original
synthetic PCM to two listeners: signal at 1.757 s, RMS approximately 0.054,
aggregate GM RTP payload approximately 42.3 kbit/s. Four encrypted control messages.
This was a loopback socket shim, not actual Foundry, MA, WAN or a sync measurement.
See `evidence/browser-audio.json`.
- Fresh live MA read-only checks verified the dedicated DEV identity/topology and
empty idle queue. Configured MA is HTTP; HTTPS Foundry would fail mixed-content
policy. No existing DEV private identity is present in the GM profile. No receiver
connection, new identity or playback mutation was made in this revision.
- Pinned MA source logs received WebSocket frames at VERBOSE. Before token-bearing
WS auth the module requires explicit operator acknowledgment that payload logging
is disabled. This was neither checked nor changed live. No WS auth test occurred.
- Previous restricted catalog and idle-state live controls are retained. Prior
bounded runs restored their original empty idle state. Synthetic ingestion failed
previously (timeout/HTTP 400). No actual MA music audio, nonempty live restore,
combat/boss interruption with audible MA content or real playlist acceptance.
## Testable inside isolated Foundry
Without infrastructure: install/enable the module, GM native ownership/setup,
world and scene assignments surviving reload, boss flags/priority, manual overrides,
active combat policy, native playback/restoration and explicit native fallback.
These behaviors are unit/fixture tested; real Foundry v14.371 testing remains pending.
With separately supplied secure private MA access, existing DEV identity/pairing,
log review and synthetic ingestion: developer GM connection/catalog and synthetic
control, then listener WebRTC invitations and audio. Test actual Foundry socket
relay with distinct logged-in users before assuming the loopback benchmark applies.
See INSTALL.md and TESTING.md for precise steps/acceptance boundaries.
## Remaining blockers and next infrastructure decision
1. Supply a licensed isolated Foundry v14.371 world/browser session for actual install,
native playback, socket, document and reconnect acceptance; production is excluded.
2. Operator must provide private trusted HTTPS/WSS MA access reachable by the GM,
the existing DEV identity/pairing, and authentication-log review. No public MA
endpoint or network configuration weakening is acceptable. New identity/target
binding would require separate explicit authorization.
3. Make the generated synthetic tracks readable through an approved existing MA
provider/private range-capable source. Do not modify existing playlists. This
minimum ingestion change is still unimplemented/unverified, not silently waived.
4. WAN peers may require an explicitly approved existing TURN relay with short-lived
credentials. Measure NAT reachability, latency, bandwidth, skew and reconnect.
5. Browser-only GM loss/crash cannot guarantee automatic restore or continuity;
durable distributed fencing and crash recovery need the optional minimal worker
on the existing Foundry host. Actual Sendspin termination in that worker remains
work. Deployment/routing/service changes need a concrete proposal and approval;
nothing has been deployed. No additional machine/container is proposed.
6. Crossfade, independent concurrent ambient layers, shuffled exact restoration and
actual MA playlist playback remain unsupported/unaccepted. No production readiness.
The manual release can be uploaded without any of those runtime prerequisites;
they gate MA audio acceptance, not native module packaging. Next authorization, if
browser gates cannot be met, is review of a concrete restricted co-located worker
and existing-host TLS route. This release does not authorize deploying that fallback.
+61
View File
@@ -0,0 +1,61 @@
# Adaptive Music — 0.5.0 development
Independent open-source project by **CheddahBoxMB**, targeting Foundry VTT **v14.371**
and Music Assistant **2.10.6**, independent of game system and other modules.
This is a development release; it has not been exercised inside an actual Foundry
world. No production installation or external service is changed by building it.
Install `adaptive-music.zip` through Foundry's normal module manifest mechanism.
[INSTALL.md](INSTALL.md) covers manual Gitea publication, installation, updates and
isolated testing. The configured repository is **planned, not confirmed**. No
connection to it was made. An uploaded, anonymously readable manifest and release
asset are required before Foundry installation by URL can work.
The standard module includes native playlist playback, persistent separate scene
ambient/combat/boss/native fallback assignments, global defaults, manual overrides,
combat automation and the existing snapshot/restore controller. The GM setup menu
configures native ownership and assignments. Automation defaults off. Only
explicitly owned native music playlists are eligible; sound effects are out of scope.
The new **experimental GM browser host** shares the validated MA provider/catalog
code, uses the bundled official Sendspin SDK's PCM decoder and Web Audio, and
sends audio to invited listeners with WebRTC. Supported Foundry module sockets carry
only encrypted bounded signaling, never continuous audio. GM credentials remain in
GM memory and are visible to that browser's user; players receive individual
expiring audio capabilities. No Docker, VM, LXC, external module, permanent sandbox,
core patch, OS service or public MA endpoint is required by the module.
This path is a developer API experiment, not a completed one-click MA setup.
The existing DEV receiver's private identity/pairing, private browser-reachable TLS,
authentication-log review and MA ingestion of the approved synthetic sequences are
still prerequisites. Real catalog entries can be displayed/assigned, but only the
authorized synthetic sequences are enabled for experimental MA playback. The
companion implementation remains optional experimental source and is preserved at
local branch `experimental/companion-0.4.0`; it is not needed for native playback.
Measured in Chromium: the official decoder and WebRTC delivered synthetic 440 Hz
PCM to **two** listener contexts, with first signal at **1.757 s** and approximately
**42.3 kbit/s** aggregate GM RTP payload. This used a loopback signaling shim, not
Foundry or MA. WAN/NAT/TURN, inter-listener synchronization, audible MA output and
nonempty live queue restoration remain unverified. Crossfade and simultaneous
ambient layers are not implemented. GM loss ends forwarding; seamless failover or
crash restoration is not promised.
Build a complete manual release bundle locally, without Git credentials or a remote:
```sh
python3 scripts/release.py
# To prepare the same release for GitHub instead:
python3 scripts/release.py --repository https://github.com/OWNER/REPOSITORY --output dist/github
```
Output: `dist/releases/v0.5.0/adaptive-music-release-v0.5.0.zip`, containing the
installable module, standalone manifest, source archive, documentation, licenses
and SHA256 checksums. The manifest uses a stable branch URL and a version-specific
release download. Build automation validates both but does not publish anything.
Prebuilt browser assets are included; end users do not need Node/npm or Python.
For contributor commands and evidence see [TESTING.md](TESTING.md),
[PROGRESS.md](PROGRESS.md), [ARCHITECTURE.md](ARCHITECTURE.md) and
[SECURITY.md](SECURITY.md). MIT project license; upstream MIT/Apache notices and
full dependency licenses are retained in `THIRD-PARTY-NOTICES` and `licenses/`.
+133
View File
@@ -0,0 +1,133 @@
# Security — standalone module and optional host fallback
The module installs through the normal Foundry manifest/ZIP mechanism. No runtime
Docker/VM/LXC, sandbox host, third-party Foundry module, core modification, service
installer or public MA endpoint is required or created. The optional companion is
retained as experimental source/branch, not a mandatory backend. Co-located host
placement/routing/manual service setup is a proposal requiring separate approval.
## Trust boundaries
Only an elected single active GM may initiate GM-local MA access. The GM explicitly
supplies a memory-only private profile; that GM/browser user can inspect its token,
identity and private data. JavaScript private fields are not a secret store against
the browser owner, debugger, compromised same-origin code or server administrator.
No contrary claim is made. Trust all code served into the GM origin. A player never
receives the GM's MA token/profile, SDK private key, upstream URL or queue payload.
Profiles/tokens are not persisted in Foundry settings, flags, localStorage, sockets,
logs, release files or URLs. Operator private backups belong outside the module's
public files; existing development secrets stay under ignored `.local/` (0700,
regular owner-matching files 0600, symlinks refused). Catalog references are opaque
HMAC identifiers, stable only with retained operator key/namespace. Configured native
ownership and scene/world references are public world data, never MA credentials.
GM control uses the official private MA `/ws` API, with fixed command allowlists,
correlated bounded responses and discarded unsolicited events, behind the preserved
MA target/media/provider checks. The MA account's role still grants broader writes;
filtering is defense in depth, not the sole boundary. No endpoint selector, queue
transfer, grouping, unrestricted HTTP/WS/Sendspin proxy or household discovery is
available to players. No new identity is registered: supplied X25519 SDK identity
must match the already verified DEV target before connecting; reconnecting an existing
known unavailable target never relaxes mutation guards. SDK auth is first-message,
not a token URL. Only original synthetic test sequences may be enabled for playback.
A precise upstream logging limitation: MA 2.10.6's WebSocket handler logs raw frames
at VERBOSE, including auth payloads. No live token WebSocket test was attempted and
no upstream log configuration was read/changed. The GM profile requires explicit
`webSocketAuthLogSafe` operator review of disabled raw-frame logging before use.
The module's own logs omit credentials; it cannot redact MA's logs without changing
that upstream behavior. Do not assume default logging or ignore this gate.
## Browser network/security policy
Private network access from an HTTPS Foundry page still needs permitted routing,
trusted TLS/WSS, CSP and server/browser Origin/local-network policies. Sendspin Noise
does not waive mixed-content restrictions. Current module policy refuses HTTPS ->
non-loopback HTTP/ws MA; modern per-browser local-network exceptions are not a
portable supported deployment. HTTP `/api` CORS is also insufficient in the inspected
pin; GM control instead uses the public authenticated WebSocket API, not a CORS
bypass proxy. No private API is exposed publicly to fix browser access.
No public third-party STUN/TURN is silently used. Default ICE servers are empty;
relay configuration is explicit and TURN credentials must be short-lived. Browser
users necessarily see their own relay credentials and decrypted peer signaling.
Direct P2P can reveal network addresses to the authorized peer; relay-only mode can
reduce that exposure if an approved relay already exists. It cannot guarantee WAN
connectivity without appropriate infrastructure. No service/container is provisioned.
## Signaling and players
Ordinary Foundry module sockets carry only bounded encrypted SDP/control envelopes,
never continuous PCM/audio chunks, MA commands, media URLs, tokens or invitation
secrets. Claimed sender IDs/GM flags are not trusted as authentication. The GM issues
a unique expiring 256-bit per-listener capability out of band over a private
authenticated channel. Possession authorizes that one peer, not a proven login.
A recipient can share its own capability/record received audio; this cannot be
prevented by browser JavaScript. Do not distribute a controller/MA secret as an invite.
AES-GCM covers SDP/ICE/DTLS fingerprints with session/peer/direction/sequence binding,
nonce/expiry, strict fields/types/size limits and asynchronous replay rechecks. A
listener may negotiate one recvonly audio m-line; video, outbound listener audio and
RTC data/control channels are rejected. Keys are per listener, so one recipient
cannot forge another listener's authorized exchange. Invalid broadcast frames are
dropped; world-server/socket flooding is still a server-side availability concern,
not solved by client encryption. Explicit peer/expiry/restart bounds limit our work.
Media uses browser DTLS-SRTP WebRTC audio tracks. No microphone is requested. GM
revocation stops new media, but cannot erase audio already delivered or force a
malicious recipient to discard buffered/recorded content. Real Foundry identity,
packet validation, WAN/NAT and browsers still need live acceptance.
## Authority, failure and original state
Target identity/provider, own active queue, standalone topology and current authority
are rechecked immediately before each mutation. Snapshot and prepared data remain
scoped, generation-checked and serialized. Signed snapshots preserve ordered duplicates,
index/offset/state/repeat for static unshuffled supported queues; expiry, foreign,
tampered or future state denies. Ambiguous remote writes latch closed with no blind
retry. Unsupported shuffle/dynamic/autoplay/overlay/ended/speed states fail closed.
Only the campaign-owned target is eligible; volume/mute state is read before SDK
handover instead of assuming maximum output. Native effects/AmbientSound stay unowned.
The optional companion retains its process-local fenced lease checks. GM-local control
has one-GM checks and a same-origin Web Lock, **not a distributed MA server fence**.
It cannot protect against a malicious/stale independent GM with MA credentials.
Multiple-GM automation/hard fencing remains a readiness blocker. No automatic GM
handover, queue ownership transfer or speaker grouping exists. Foundry disconnect
stops forwarding and future writes; an offline/crashed GM cannot guarantee restoration.
Native fallback never skips reconciliation of an uncertain active MA target.
Existing bounded live harnesses still capture original state and report restoration
success/failure explicitly. No new playback mutation or Sendspin pairing was attempted
in this revision; the read-only check observed an empty idle dedicated queue. The browser measurement
used original synthetic PCM, not real MA or licensed-service content. Existing
synthetic ingestion failure and identity/TLS/logging gates remain. Crossfade,
simultaneous layers, durable recovery and deployment security are not claimed complete.
## Release and supply-chain safeguards
The release builder runs offline, uses no Git credential/remote API and never contacts
the planned Gitea server. It validates public HTTPS URL shape, stable manifest and
versioned ZIP consistency, module ID/author/v14 compatibility, no false `verified`
claim, no mandatory systems/modules, import closure, notices, SDK hash and privacy
patterns. It rejects private/symlinked package files. Exact private token/endpoint/target
scans of history and artifacts supplement these guardrails; they are not a
comprehensive secret scanner or proof of uncontacted server availability.
Official SDK 5.0.0 and noble dependencies are pinned/audited and bundled locally;
there is no runtime CDN or installer. Full Apache/MIT texts accompany releases.
Optional Opus fallback imports are explicitly disabled in the PCM-only SDK build;
libopus/speex/opus-encdec binaries are not distributed. WebRTC's browser codec is not
bundled by this project. Install hooks were disabled. Developer-only Playwright/
esbuild tools and local Chromium are not shipped or a runtime dependency.
CI workflows use pinned action commits on an existing shell runner, build artifacts
for manual publication, and install no services or infrastructure. No Git host was
accessed/authenticated/created/pushed on the user's behalf. Public release files
contain no private MA addresses/credentials/deployment data. A source archive is not
an installable Foundry ZIP; documentation distinguishes both.
Peer signaling also bounds each peer to four queued control frames and 64 received
control attempts per invitation, limiting asynchronous decrypt/SDP backlog. Socket
flooding of the Foundry server remains a server/operator availability concern.
+1
View File
@@ -0,0 +1 @@
1ccdd229e40e1e02f0fa76d8fc553877c66c9494
+102
View File
@@ -0,0 +1,102 @@
# Adaptive Music verification — 0.5.0
## Regression and offline release validation
The current suite has **85 JavaScript tests** and **15 Python tests**. Tests cover
controller transitions, signed snapshots, target/topology guards, durable catalog
IDs, native restore behavior, scene/default/combat interfaces, optional companion
scope/replay protection, GM access policy, official PCM decoder, encrypted WebRTC
signaling/replay checks, public MA WebSocket correlation and offline release contracts.
These are fixtures and source checks, not live Foundry/MA playback tests.
```sh
PATH="$HOME/.nvm/versions/node/v24.23.0/bin:$PATH" npm test
python3 -m unittest discover -s tests -v
python3 scripts/audit_repository.py
python3 scripts/verify_upstream.py
python3 scripts/release.py
python3 scripts/release.py --validate dist/releases/v0.5.0/adaptive-music.zip
```
Python uses the standard library. Upstream verification requires ignored pinned
research copies; it does not fetch/install them. Browser assets are prebuilt and
SHA256 verified. Optional rebuilding uses Node 24.23.0, `npm ci --ignore-scripts`
and `node scripts/build_sendspin.mjs`. No install hooks were run. The online npm
advisory audit of the pinned dependency tree reported **zero vulnerabilities**;
this is an advisory observation, not a safety guarantee or an offline audit.
Release tests exercise repeatable ZIP generation, embedded/standalone manifest
identity, missing import/asset rejection, URL versioning, GitHub configuration,
checksums, attribution, private-content exclusion and rebuilding from a source
archive without Git metadata. Neither the builder nor these tests contact Gitea.
CI workflows generate artifacts only on an already provisioned shell runner.
They have not run on GitHub or Gitea; Gitea Actions/artifact compatibility is untested.
## Measured browser audio experiment
`evidence/browser-audio.json` records an actual Chromium 143.0.7499.4 experiment:
official Sendspin 5.0.0 decoder → Web Audio → WebRTC → two listener browser contexts.
The original 440 Hz synthetic tone produced RMS 0.05391/0.05396 and FFT peaks
445.3125 Hz (nearest frequency bin). All listeners had signal at 1.757 s; during
4.766 s observation, the GM sent 25,198 RTP payload bytes, approximately 42.3 kbit/s
aggregate. Four encrypted signaling messages (maximum 2,078 bytes), no raw audio
on signaling. AudioContexts/HTMLAudioElements were unlocked by actual page clicks.
Optional reproduction after a separate Playwright Chromium download:
```sh
PLAYWRIGHT_BROWSERS_PATH=.local/browsers node scripts/measure_browser_audio.mjs
```
The harness starts a temporary loopback static server and a socket shim, uses
headless Chromium with `--no-sandbox` only for the development experiment and
closes them afterwards. This is not a real Foundry socket integration, live MA
Sendspin handshake, WAN/NAT/TURN test, perceptual quality test or synchronization
measurement. Browser dependencies/binaries do not ship with the module.
## Live MA evidence and limits
`ma-readonly.json` records prior authenticated restricted account checks, dedicated
target/provider restrictions and catalog reads. `ma-adapter.json` records eleven
playlists/one radio and stable opaque identifiers across adapter reconstruction.
`ma-live-history.json` and `ma-playback.json` record prior bounded idle-queue runs:
shuffle/repeat/stop and exact restoration to empty/idle/unshuffled/repeat-off/zero.
They verify neither audible music nor restoration of a nonempty queue.
`module-only-prerequisites.json` adds fresh authenticated **read-only HTTP**
verification of the fixed DEV identity/topology and empty idle queue. The configured
MA endpoint is HTTP; an HTTPS Foundry page fails the module mixed-content gate.
The existing receiver private identity is absent from the GM profile. No receiver
was created, no Sendspin connection attempted and no playback command issued in
this revision. MA 2.10.6 source logs received WebSocket frames at VERBOSE: operator
log review is required before token-bearing `/ws` authentication. No live WS auth
was attempted. Route behavior and authentication protocol are source-derived.
Prior synthetic URI ingestion timed out/returned HTTP 400; approved six-track
ambient/combat WAV sequences are not established as ingestible. Actual MA playlist
playback remains a separate content-approval acceptance test. Synthetic browser
PCM does not satisfy it. Household devices, grouping, queue transfers, production
Foundry and network/service configuration remain untouched.
## Remaining acceptance tests
In an isolated Foundry v14.371 world: install/enable ZIP, test native ownership,
scene ambient/combat/boss and world defaults, explicit combatant flags, manual
silence/clear, rapid transitions and native fallback. Validate supported socket
signaling using two logged-in users; private invite delivery and revocation, user
role changes, disconnects and automation shutdown need real-world confirmation.
Before live MA audio: operator supplies the existing DEV identity/pairing without
registering a new target; makes private secure MA browser access available without
public exposure; confirms token-bearing WS frames cannot enter logs; supplies
approved synthetic ingestion. Recheck exact target/group/queue before every write.
Capture and restore original state with a bounded harness. Then test seeking,
interrupt/restore, rapid/nested contexts and stereo/format handling with listeners.
Do not treat mocked nonempty restoration as live evidence. Real playlists require
separate approved content. Record an explicit restoration failure if it occurs.
Remote WAN trials must measure ICE/TURN reachability, expiry/reconnect, throughput,
latency and listener skew; none is inferred from the loopback result. GM restart,
durable nonempty live restore, distributed fencing, crossfade, background tab
behavior and service fallback termination remain unsupported or unverified as
specified in ARCHITECTURE.md. No production readiness claim.
+51
View File
@@ -0,0 +1,51 @@
Adaptive Music — independent open-source project by CheddahBoxMB.
Not an official Foundry VTT, Music Assistant, Sendspin or VGM product.
Milestone 1 records research; the subsequent source prototype adapts VGM per-sound
stop and pausedTime restoration in src/providers/native/provider.mjs. The controller
and Foundry bootstrap are new implementations informed by the audited VGM behavior.
The browser SDK and cryptographic dependencies listed below are now bundled.
Preserve this attribution and the full licenses supplied alongside the module.
Video Game Music (VGM)
https://github.com/Sayshal/vgmusic
Release release-1.4.5; commit eba07a08c9925f31b9c8adb72faf95de11ae705c
Authors named by manifest: Furyspark and Tyler (Sayshal).
Copyright (c) 2025 3 Death Saves
MIT License. Full copyright, grant and disclaimer: licenses/VGM-MIT.txt.
The notice and permission text must accompany copies/substantial portions.
Music Assistant server
https://github.com/music-assistant/server
2.10.6; commit c24866405bd2068c25a60e1014e5ef8c3f6445bb
Music Assistant frontend
https://github.com/music-assistant/frontend
2.17.297; commit e779b9d359e47cd210c2801f16a0ce6263571903
Sendspin JS — Sendspin Protocol Authors / Open Home Foundation
https://github.com/Sendspin/sendspin-js
5.0.0; commit 7d103075138dda5c8909045647bb42b33c2d44fc
6.1.0; commit 7ee7ca35ac29ae3ef5f2eeeeaac1e24751a8790b (comparison)
aiosendspin — Sendspin Protocol Authors
https://pypi.org/project/aiosendspin/9.1.1/
These inspected sources declare Apache-2.0. Full license: licenses/Apache-2.0.txt.
Bundled browser runtime (vendor/sendspin-5.0.0.mjs):
- @sendspin/sendspin-js 5.0.0, Apache-2.0; licenses/vendor/-sendspin-sendspin-js.txt.
- @noble/ciphers 1.3.0, MIT; licenses/vendor/-noble-ciphers.txt.
- @noble/curves 1.9.7, MIT; licenses/vendor/-noble-curves.txt.
- @noble/hashes 1.8.0, MIT; licenses/vendor/-noble-hashes.txt.
Exact registry integrity hashes, build inputs and bundle SHA256 are recorded in
vendor/provenance.json and evidence/sdk-adoption.json. Modified distribution:
bundled/minified exports, PCM-only; optional Opus decoder imports are replaced by
explicit unsupported-codec stubs. No Opus/WASM decoder or codec binaries ship.
No upstream NOTICE file was present in the inspected SDK package. Full upstream
copyright/license texts accompany this modified distribution. No runtime CDN.
Build/test dependencies (not required by the installed module): esbuild 0.27.1
(MIT), Playwright 1.57.0 (Apache-2.0), exact transitive pins in package-lock.json.
Their installed source/binaries are not included. opus-encdec 0.1.1 is installed
as an SDK dependency for reproducible inspection but excluded from the browser
bundle; its MIT and embedded libopus/Speex BSD licenses were reviewed. See
evidence/sdk-adoption.json for the distribution boundary and audit results.
Foundry VTT public documentation is a reference only. Foundry software is not
redistributed. No third-party music assets are included; browser tests generate original tones. No upstream source has been relicensed.
+30
View File
@@ -0,0 +1,30 @@
# Sendspin provisioning research — 2026-12-03
Evidence class: source inspection only. MA 2.10.6, commit
`c24866405bd2068c25a60e1014e5ef8c3f6445bb`; new inspected file hashes recorded in
`upstream.json`. No upstream code copied, dependency installed or provisioning run.
`providers/sendspin/provider.py:656` defines `create_virtual_player(owner_instance_id,
display_name, player_id=None)`. This is an in-server Python provider API, not a
registered external HTTP command. It requires a loaded provider owner, checks
ownership/collisions, prefixes stable IDs, registers the client and queue, and
persists the owner marker. Removal deletes configuration; unloading the owner
removes its targets. Restart requires the owner to recreate the anchor. See the
same directory's README, “Virtual Players”, and `_register_virtual_player_client`.
This anchor discards its own audio. Its documented delivery mechanism attaches
member players through standard grouping. That mechanism does not meet Adaptive
Music's no-grouping boundary and is not an adopted gateway audio source. Creating
an anchor alone would not terminate audio at the gateway.
`player.py:_refresh_client_info` recognizes web/app clients from device information
and makes them standalone/private. A future isolated gateway Sendspin client with
an operator-assigned stable identity could be researched as a dedicated receiver,
but needs protocol/Noise/codec and reconnect tests, licensing/dependency review,
explicit target creation approval, and an operator update of the nonempty account
player filter. An arbitrary new identity must never be automatically selected.
No public automatic provisioning path suitable for the current external gateway
was established. Existing Adaptive Music DEV remains the only authorized target.
Decision: retain the manually provisioned development target. Do not add an MA
plugin, use grouping, create resources, or change production settings in this milestone.
+46
View File
@@ -0,0 +1,46 @@
# Dedicated gateway receiver — public-interface investigation
Checked 2026-12-03. Evidence class: official public protocol/SDK documentation and
pinned source inspection, not a running receiver or a live MA handshake.
Official references:
- [Client implementation guide](https://www.sendspin-audio.com/build/guide/client/)
- [Protocol specification](https://www.sendspin-audio.com/build/spec/)
- [aiosendspin SDK](https://github.com/Sendspin/aiosendspin)
A separate player-role client is the supported public interface. Persist its X25519
identity and pairing records privately; advertise only player capability, use Noise
transport, pin the intended server identity, and never advertise controller/source
roles or forward MA traffic. The public protocol supports client-initiated discovery
and connection as well as server-initiated connections. Prefer an operator-configured
private MA peer with no broad household discovery. Read the exact pinned SDK
behavior rather than assuming today's mutable specification matches every field.
Inspected aiosendspin 9.1.1 source distribution (already recorded archive SHA256):
`client/client.py:SendspinClient` takes identity, pairing store, roles and player
support; `connect(url, expected_server_id=...)` supplies a public connection path;
`add_audio_chunk_listener` exposes decoded PCM, negotiated format and server
presentation timestamps. Its time mapping methods convert presentation time.
These methods avoid MA provider internals and virtual-player provisioning.
This makes a gateway-owned receiver feasible as a source-derived design. A worker
can terminate Noise/codec state locally, validate PCM format/timestamps, and feed a
campaign-specific bounded ring. Neither upstream control frames, pairing messages,
MA credentials nor client-selected identities may reach listeners. The new strict
WAV-to-PCM fixture pipeline exercises only local PCM validation/distribution, not
that handshake or time mapping.
No SDK dependency has been installed, copied, adopted or bundled. The distribution
is Apache-2.0 and its declared client dependencies include aiohttp, cpace,
cryptography, mashumaro, noiseprotocol, orjson and zeroconf; a locked transitive and
codec review is still required before adoption. The SDK's own README calls its
client a test/reference client. No compatibility claim follows from API inspection.
Infrastructure needed for a live receiver experiment: isolated non-root worker,
private writable identity/trust storage (0700/0600), operator-approved persistent
receiver identity, explicit pairing to the pinned MA server, and an operator update
to the account's nonempty player filter/target binding after verifying the new
identity. The current authorization covers only Adaptive Music DEV, so no additional
receiver identity was registered or selected. No mDNS advertisement, MA source edit,
internal virtual-player API, grouping or production configuration was used.
+127
View File
@@ -0,0 +1,127 @@
# Upstream source audit
Inspected 2026-12-03 using GitHub release metadata, shallow tagged Git checkouts and
PyPI source distribution. Full commits and selected file SHA-256 values are in
[upstream.json](upstream.json). Checkouts are ignored under .local/upstream; no
install hooks or upstream application code executed. Hashes establish reproducibility,
not signature verification or a security audit. Release selection excludes drafts
and prereleases; package version placeholders are not reliable release identifiers.
| Component | Inspected release | Role | License |
| --- | --- | --- | --- |
| Sayshal/vgmusic | release-1.4.5 | Latest stable observed; behavioral reference | MIT |
| music-assistant/server | 2.10.6 | Deployment target source | Apache-2.0 |
| music-assistant/frontend | 2.17.297 | Exact server dependency | Apache-2.0 |
| sendspin/sendspin-js | 5.0.0 | Exact pinned frontend dependency | Apache-2.0 |
| sendspin/sendspin-js | 6.1.0 | Latest stable observed; comparison only | Apache-2.0 |
| aiosendspin | 9.1.1 | Exact server Sendspin dependency; PyPI sdist | Apache-2.0 |
Latest frontend release observed was 2.17.388 at commit
e19509049634795d69abd4dec417f1281201deb8, pinning Sendspin JS 6.1.0. It was inspected
for comparison before checking out the server-pinned frontend. Latest MA stable
observed was 2.10.15. Neither is a recommendation to upgrade production.
## VGM findings
[Release source](https://github.com/Sayshal/vgmusic/tree/eba07a08c9925f31b9c8adb72faf95de11ae705c)
contains module.json declaring Foundry minimum/verified 14 and **requires 3ds-atlas**.
`package.json` has no runtime npm dependencies; development dependencies include
Rollup, Terser, ESLint/JSDoc, Prettier, Stylelint, lint-staged, copy and PostCSS
plugins. Its package-lock has 396 non-root package entries. At the initial source audit, no npm vulnerability
scan or install was run because Node/npm were absent. The later prototype uses no
third-party packages and has not installed or audited VGM development dependencies. This is an inventory, not a
finding that dependencies are safe. Manifest version/download are build placeholders
and package.json says 1.0.0; GitHub stable release tag is the version evidence.
`scripts/music-controller.mjs` uses ATLAS primary-GM arbitration/logging, resolves
scene/combat/token/actor contexts, pauses/restores track offsets via document flags,
and stops per-playlist sounds to avoid reseeding shuffle. `scripts/hooks.mjs` listens
to core combat, scene, token and actor hooks; other source includes optional
Calendaria and Minstrel interaction. These integrations are not required by this
project. Snapshot concept is useful, but no MA provider, secure gateway, campaign
isolation or demonstrated full queue restoration was found. MIT permits reuse with
the copyright and permission notice; see THIRD-PARTY-NOTICES.
## Music Assistant API findings (2.10.6 source)
All paths below are within
[the pinned server](https://github.com/music-assistant/server/tree/c24866405bd2068c25a60e1014e5ef8c3f6445bb).
- `music_assistant/controllers/webserver/controller.py`: GET `/info`, GET `/ws`,
POST `/api`, generated `/api-docs/commands.json`, schemas and OpenAPI routes.
Source identifies these routes; only `/` and `/info` were probed live: initially timed out, now both HTTP 200
with `/info` reporting 2.10.6. No authenticated API command has been sent.
- `websocket_client.py`: server info on connect, command envelopes parsed as
CommandMessage (`message_id`, `command`, `args` as used by frontend), special
`auth` command with token; authenticated event subscriptions. Not a generic
arbitrary JSON-RPC-over-WebSocket assumption. HTTP API has separate JSON-RPC handler.
- `auth.py` and `helpers/auth_middleware.py`: built-in credential and token paths,
`auth/login`, `auth/token/create`, `auth/token/revoke`, scopes, player/provider
filters and Bearer-header support. No credentials used, account created or token
minted. Effective least-privilege scopes must be checked in an authorized test.
- `player_queues/controller.py`: `all/get/items` (items default limit 500 and offset),
`play_media`, `play_index`, `seek`, `pause/resume`, `shuffle/repeat`, `transfer`.
`play_media` accepts queue_id, media, option, start_item and shuffle among others.
Seek rejects no-duration or out-of-range media. Queue read/control scopes are
declared, but do not assume all handlers enforce identical resource filters.
`_check_player_permission` permits an own-client exception and tests a *nonempty*
player filter; empty filters are not restrictive. Gateway must independently
validate all resources, methods, arguments and returned metadata.
- No public atomic full queue snapshot/restore pair found in the inspected controller.
Rebuilding requires ordered items, duplicate occurrence/index, position, mode and
state; shuffled future order and dynamic playlists remain PoC questions.
- `providers/sendspin/manifest.json`: builtin beta-stage provider;
`aiosendspin[server]==9.1.1`, `av==16.1.0`. Server pyproject requires Python >=3.14
and frontend==2.17.297; sandbox Python 3.12 cannot run this MA server version.
## Sendspin findings
[Pinned frontend](https://github.com/music-assistant/frontend/tree/e779b9d359e47cd210c2801f16a0ce6263571903)
`package.json` pins Sendspin JS **5.0.0**. `src/plugins/sendspin-connection.ts` wraps
WebSocket authentication `{type:"auth", token, client_id}` and provides alternate
remote DataChannel handling. We will not enable MA remote mode.
MA `controllers/webserver/sendspin_proxy.py` authenticates the first message then
forwards bidirectionally, optionally registering the chosen client ID with that
session. Authentication is not demonstrated campaign-level authorization. No claim
that forwarding this socket safely restricts listeners is justified.
[Sendspin JS 5.0.0 source](https://github.com/Sendspin/sendspin-js/tree/7d103075138dda5c8909045647bb42b33c2d44fc)
uses Noise transport and advertises `player@v1`, `controller@v1`, `metadata@v1` in
`src/core/protocol-handler.ts`. Codec type includes PCM, FLAC and Opus; browser code
uses AudioContext/WebCodecs and an opus-encdec fallback. Comments identify Firefox
Opus limitations; those are upstream claims, not tested here. Both inspected JS
versions depend on @noble/ciphers, @noble/curves, @noble/hashes and opus-encdec.
5.0.0 and 6.1.0 package version fields are 0.1.0 build placeholders. Both require
Node >=20.19.0. Pin release tags/commits and verify published package before adoption.
aiosendspin 9.1.1 sdist SHA-256 matches PyPI metadata. It requires Python >=3.12 and
has client/server implementations with protocol version 1, Noise, legacy transport
handling, pairing and role machinery. Runtime dependencies: aiohttp, cpace,
cryptography, mashumaro, noiseprotocol, orjson, zeroconf; optional server adds av,
numpy and pillow. Source was extracted safely and inspected, not installed or run.
It is a plausible gateway-worker candidate, not a verified compatible solution.
All transitive licenses (especially bundled codec/WASM assets), distribution NOTICE
files and vulnerability results must be reviewed before packaging dependencies.
No runtime dependency has been adopted by Adaptive Music at this milestone.
## Foundry public API evidence
Official [v14 Playlist API](https://foundryvtt.com/api/classes/foundry.documents.Playlist.html)
and [PlaylistSound API](https://foundryvtt.com/api/classes/foundry.documents.PlaylistSound.html)
were inspected. Public Playlist playback and document update APIs are the native
adapter boundary. A v14 API reference and VGM's v14 manifest do not verify behavior
on build 14.371. No Foundry binaries or proprietary source were obtained.
## Implementation follow-through — 2026-12-03
Selected pins and hashes still pass `verify_upstream.py`. The native prototype
adapts the VGM per-sound update/pausedTime pattern with its 2025 3 Death Saves MIT
notice. Core policy and local GM/settings/hooks are new code; ATLAS and optional
integrations were not copied. No upstream runtime dependency was installed.
The official v14 Playlist/PlaylistSound public API pages were rechecked; they remain
API references, not build 14.371 playback evidence. Native document tests are mocks.
MA PoC uses the source-inspected HTTP envelope (raw response, not a JSON-RPC result
wrapper). Account-role/token limitations are recorded in gateway/README.md.
+31
View File
@@ -0,0 +1,31 @@
{
"checked_at": "2026-12-03T20:37:24.512Z",
"evidence_class": "real Chromium localhost SDK PCM decoder/WebAudio/WebRTC; synthetic input; socket relay shim, not Foundry or MA",
"browser": "143.0.7499.4",
"listeners": 2,
"first_all_listeners_signal_ms": 1757,
"observation_seconds": 4.766,
"sdk_decoded_frames": 255,
"listeners_measured": [
{
"rms": 0.05391,
"peak_hz": 445.3125
},
{
"rms": 0.05396,
"peak_hz": 445.3125
}
],
"gm_rtp_bytes_sent": 25198,
"aggregate_media_kbps": 42.3,
"signaling_messages": 4,
"max_signal_bytes": 2078,
"socket_payloads_are_encrypted_control_only": true,
"turn_used": false,
"public_network_test": false,
"ma_handshake_test": false,
"ma_audio_playback": false,
"interlistener_skew_measured": false,
"autoplay_gesture": "actual page click",
"sandbox_note": "headless browser only used --no-sandbox; not a deployment setting"
}
+22
View File
@@ -0,0 +1,22 @@
{
"checked_at": "2026-12-03T20:42:10.993912+00:00",
"source": "official GitHub Git-ref API; no planned Gitea access",
"actions": [
{
"repository": "actions/checkout",
"version": "v4.2.2",
"commit": "11bd71901bbe5b1630ceea73d27597364c9af683"
},
{
"repository": "actions/upload-artifact",
"version": "v4.6.2",
"commit": "ea165f8d65b6e75b540449e92b4886f43607fa02"
},
{
"repository": "actions/upload-artifact",
"version": "v3.2.2",
"commit": "c6a366c94c3e0affe28c06c8df20a878f24da3cf"
}
],
"execution": "not run on either hosting platform; Gitea artifact protocol needs instance compatibility check"
}
+12
View File
@@ -0,0 +1,12 @@
{
"checked_at": "2026-12-03T19:56:36.693Z",
"evidence_class": "live MA reads through local companion and browser-safe client; no real Foundry browser",
"target": "verified",
"playlists": 11,
"radios": 1,
"browser_payloads_private": true,
"playback_enabled": false,
"mutations_sent": 0,
"foundry_verified": false,
"tls_verified": false
}
+21
View File
@@ -0,0 +1,21 @@
{
"checked_at": "2026-12-03T16:17:30.410831+00:00",
"authenticated": false,
"results": [
{
"path": "/",
"status": 200,
"content_type": "text/html",
"bytes": 31252,
"elapsed_seconds": 0.0
},
{
"path": "/info",
"status": 200,
"content_type": "application/json; charset=utf-8",
"bytes": 386,
"elapsed_seconds": 0.0
}
],
"server_version": "2.10.6"
}
+405
View File
@@ -0,0 +1,405 @@
UTC 2026-12-03T20:59:41.184630+00:00
Evidence: offline regressions/source/package checks. Separate actual synthetic browser and live read-only MA results are in browser-audio.json and module-only-prerequisites.json. No live MA audio/Foundry/WAN verification.
$ node --version
v24.23.0
exit=0
$ npm --version
11.21.3
exit=0
$ python3 --version
Python 3.12.3
exit=0
$ npm test
> adaptive-music@0.5.0 test
> node --test tests/js/*.test.mjs
✔ catalog paginates, strips private metadata and filters unapproved mappings (38.46361ms)
✔ empty provider allowlist denies without I/O; malformed and endless pages fail (20.827361ms)
✔ target validation rejects group, changed identity and unavailable player (1.374042ms)
✔ synthetic audio isolates simultaneous campaigns and copies every frame (0.435995ms)
✔ audio denies forged origin/session/role, unknown fields and cross-campaign grants (0.222736ms)
✔ active listener revocation/expiry and slow-client overflow close handles (0.404296ms)
✔ synthetic source rejects stale sessions/generations, oversized frames; connections are bounded (0.35765ms)
✔ catalog authorization denies listener and injection before upstream (0.360554ms)
✔ scene/combat configuration preserves independent flags and stores only tagged references (1.270817ms)
✔ role loss, stale selection and arbitrary URL/ID fail before document write (0.329095ms)
✔ editor uses text for catalog labels and rechecks GM on actual save event (0.360413ms)
✔ configuration hook disposal prevents pending asynchronous render from mounting (0.195415ms)
✔ packaged browser client connects through real loopback companion/MA wire fixtures and restores combat queue (96.38079ms)
✔ companion denies listener control, wrong scope/Origin, upstream injection and unknown routes (9.391963ms)
✔ browser accepts only relative same-origin paths and never persists a connection grant (0.171381ms)
✔ companion operation replay is idempotent and same ID with changed payload is denied (12.023186ms)
✔ companion listener stream rejects controller grant and closes on live revocation and expiry (90.295314ms)
✔ catalog revocation during upstream I/O suppresses the response at the companion boundary (6.811085ms)
✔ policy precedence and explicit silence (1.288631ms)
✔ inactive, unstarted and other scene combats ignored; boss ties stable (3.916738ms)
✔ scene -> combat -> boss -> nested manual -> unwind restores offsets, duplicates and pause (1.549288ms)
✔ scene change during manual never resurrects previous scene (0.270146ms)
✔ boss removed during manual and deleted combat cannot return (0.290985ms)
✔ duplicate intent causes zero provider mutations (0.138488ms)
✔ prepare failure leaves current playback intact (0.445754ms)
✔ partial apply failure restores outgoing playback (0.220112ms)
✔ obsolete async resolve is rejected before stop/apply (0.243806ms)
✔ lease loss during stop prevents apply and stale rollback (0.231364ms)
✔ provider switch and bounded nested stack (0.299902ms)
✔ no authority retains playback without provider access (0.105036ms)
✔ queued state is captured at submission rather than read after caller mutation (0.06934ms)
✔ supersession after snapshot prevents mutations (0.16576ms)
✔ failed cross-provider apply cleans new owned audio before outgoing restoration (0.147205ms)
✔ superseded cross-provider apply is reconciled by stopping partially touched target (0.166159ms)
✔ extracted companion launches privately with fixture credentials, serves catalog diagnostics and listener PCM (193.762492ms)
✔ gateway binds target server-side and sanitizes metadata (1.054182ms)
✔ forged, wrong origin/campaign/session and unknown args deny before upstream (0.367508ms)
✔ listener cannot read queues or acquire controller lease (0.162183ms)
✔ expiry, revocation, stale fence and replay reject (0.269445ms)
✔ lease cannot be stolen and increases fence after revoke (0.138238ms)
✔ revocation during upstream I/O suppresses response (0.705801ms)
✔ MA adapter uses pinned envelope, Bearer header, fixed path, no redirects and returns no metadata (12.7784ms)
✔ MA mismatched queue, upstream failures and redirects fail with sanitized errors (1.87536ms)
✔ MA rejects URL credentials, query/fragment, paths and non-HTTP configuration (0.214121ms)
✔ MA read adapter performs real local HTTP POST against an isolated fixture (16.7976ms)
✔ signaling is confidential, per-listener authenticated, scoped and replay resistant (6.537352ms)
✔ signaling denies expired invitation, unknown/audio message types and unapproved TURN secrets (0.630831ms)
✔ GM browser policy refuses mixed content and SDK identity mismatch before any MA connection (0.568644ms)
✔ official pinned SDK decodes real binary PCM frames and discards stale generations (0.309118ms)
✔ parallel signaling replay cannot pass the asynchronous authentication check twice (1.495718ms)
✔ GM API WebSocket adapter authenticates privately, assembles partial results and refuses broad commands (14.752335ms)
✔ loopback transport denies unauthenticated, cross-campaign, controller, query and wrong-origin requests (14.358346ms)
✔ loopback streams synthetic PCM bytes and closes an active stream on revocation (41.212213ms)
✔ loopback closes idle synthetic stream when its listener capability expires (21.925676ms)
✔ MA snapshots ordered duplicate occurrences, pause and seek then reconstructs exact unshuffled order (7.914799ms)
✔ tampered, foreign/future snapshots and stale authority deny before MA mutations (1.351109ms)
✔ shuffled snapshot fails before interruption rather than promising exact restore (0.158526ms)
✔ prepared media cannot be forged and stale generations cannot issue controls (0.190847ms)
✔ every wire mutation revalidates exact identity/topology and uses fixed dedicated queue (14.987794ms)
✔ queue injection, transfer, arbitrary media URL and authority loss deny without writes (0.548456ms)
✔ catalog IDs survive independent adapter construction and differ across campaigns (2.585898ms)
✔ same-generation duplicate controls and restores issue no duplicate mutations (0.707344ms)
✔ MA provider with mock MA client composes with controller for nested contexts and rapid supersession (3.595579ms)
✔ ambiguous wire mutation failure latches closed instead of retrying or restoring blindly (0.911135ms)
✔ listener cannot obtain a playback fence guard or renew a controller lease (0.765943ms)
✔ playlist preparation expands approved ordered tracks before any playback mutation (0.954477ms)
✔ installable development entry defaults automation off and imports no gateway (7.147644ms)
✔ native captures actual offset and paused state, stops per sound, restores repeat/volume (1.230282ms)
✔ native resolves sequential playlist and touches only owned documents (0.396662ms)
✔ native rejects unsupported shuffle and empty playlist (0.118061ms)
✔ native rejects expired tracks, changed playlist membership and foreign/future snapshots before mutation (0.157575ms)
✔ native reports nonseekable restoration and clamps near-end seek (0.142567ms)
✔ scene-linked playlist conflict and lost authority fail before mutation (0.18704ms)
✔ GM election deterministic and no GM means none (4.923312ms)
✔ Foundry bootstrap registers local settings/hooks and disposes without ambient or actor access (0.768578ms)
✔ synthetic WAV termination emits fixed PCM frames through campaign listener authorization (0.871321ms)
✔ malformed, truncated and incompatible WAV formats fail closed before PCM publication (6.066001ms)
✔ credential loader rejects permissive modes, symlinks and malformed secrets (4.9003ms)
✔ private catalog identity key persists and unsafe key permissions fail (53.152506ms)
✔ scene assignments persist independently and world defaults/boss priority resolve without actor schemas (1.187302ms)
✔ native fallback is explicit, manual silence wins and legacy ambient does not resurrect after clearing (0.690973ms)
✔ unavailable saved MA selections are preserved but new forged IDs/non-native fallback and role loss deny (0.380373ms)
✔ GM setup connects catalog into independent scene editors and never persists its connection code (1.961399ms)
✔ browser PCM sink resumes from gesture, decodes stereo frames and closes its context on stream end (16.382984ms)
ℹ tests 84
ℹ suites 0
ℹ pass 84
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 1326.873707
exit=0
$ python3 -m unittest discover -s tests -v
test_companion_is_separate_complete_and_excludes_private_configuration (test_package.DevelopmentPackageTests.test_companion_is_separate_complete_and_excludes_private_configuration) ... ok
test_package_excludes_gateway_private_state_and_false_verification (test_package.DevelopmentPackageTests.test_package_excludes_gateway_private_state_and_false_verification) ... ok
test_complete_offline_bundle_is_repeatable_and_checksums_match (test_release.ReleaseTests.test_complete_offline_bundle_is_repeatable_and_checksums_match) ... ok
test_gitea_github_stable_manifest_and_immutable_download_contract (test_release.ReleaseTests.test_gitea_github_stable_manifest_and_immutable_download_contract) ... ok
test_source_archive_rebuild_does_not_need_a_git_remote_or_metadata (test_release.ReleaseTests.test_source_archive_rebuild_does_not_need_a_git_remote_or_metadata) ... ok
test_tampered_manifest_or_missing_asset_is_rejected (test_release.ReleaseTests.test_tampered_manifest_or_missing_asset_is_rejected) ... ok
test_documentation_versions_are_not_private_addresses (test_repository.RepositorySafetyTests.test_documentation_versions_are_not_private_addresses) ... ok
test_embedded_url_credentials_rejected (test_repository.RepositorySafetyTests.test_embedded_url_credentials_rejected) ... ok
test_key_material_rejected (test_repository.RepositorySafetyTests.test_key_material_rejected) ... ok
test_network_evidence_is_unauthenticated (test_repository.RepositorySafetyTests.test_network_evidence_is_unauthenticated) ... ok
test_private_addresses_rejected (test_repository.RepositorySafetyTests.test_private_addresses_rejected) ... ok
test_private_config_rejected_even_when_forced_into_git (test_repository.RepositorySafetyTests.test_private_config_rejected_even_when_forced_into_git) ... ok
test_private_paths_are_ignored (test_repository.RepositorySafetyTests.test_private_paths_are_ignored) ... ok
test_provenance_pins_have_hashes (test_repository.RepositorySafetyTests.test_provenance_pins_have_hashes) ... ok
test_repository_guardrails (test_repository.RepositorySafetyTests.test_repository_guardrails) ... ok
----------------------------------------------------------------------
Ran 15 tests in 0.209s
OK
exit=0
$ python3 scripts/audit_repository.py
PASS: repository privacy/attribution guardrails
exit=0
$ python3 scripts/verify_upstream.py
PASS: all recorded Git heads, source and distribution file hashes
exit=0
$ git diff --check
exit=0
Final after peer signaling bound/tests:
$ npm test
> adaptive-music@0.5.0 test
> node --test tests/js/*.test.mjs
✔ catalog paginates, strips private metadata and filters unapproved mappings (34.489068ms)
✔ empty provider allowlist denies without I/O; malformed and endless pages fail (19.785397ms)
✔ target validation rejects group, changed identity and unavailable player (0.905344ms)
✔ synthetic audio isolates simultaneous campaigns and copies every frame (0.447057ms)
✔ audio denies forged origin/session/role, unknown fields and cross-campaign grants (0.209794ms)
✔ active listener revocation/expiry and slow-client overflow close handles (0.258885ms)
✔ synthetic source rejects stale sessions/generations, oversized frames; connections are bounded (0.312956ms)
✔ catalog authorization denies listener and injection before upstream (0.324718ms)
✔ scene/combat configuration preserves independent flags and stores only tagged references (1.271449ms)
✔ role loss, stale selection and arbitrary URL/ID fail before document write (0.321131ms)
✔ editor uses text for catalog labels and rechecks GM on actual save event (0.353852ms)
✔ configuration hook disposal prevents pending asynchronous render from mounting (0.188401ms)
✔ packaged browser client connects through real loopback companion/MA wire fixtures and restores combat queue (96.734315ms)
✔ companion denies listener control, wrong scope/Origin, upstream injection and unknown routes (8.058096ms)
✔ browser accepts only relative same-origin paths and never persists a connection grant (0.173145ms)
✔ companion operation replay is idempotent and same ID with changed payload is denied (11.338403ms)
✔ companion listener stream rejects controller grant and closes on live revocation and expiry (91.136521ms)
✔ catalog revocation during upstream I/O suppresses the response at the companion boundary (7.375589ms)
✔ policy precedence and explicit silence (1.319699ms)
✔ inactive, unstarted and other scene combats ignored; boss ties stable (4.027014ms)
✔ scene -> combat -> boss -> nested manual -> unwind restores offsets, duplicates and pause (1.273683ms)
✔ scene change during manual never resurrects previous scene (0.207358ms)
✔ boss removed during manual and deleted combat cannot return (0.249657ms)
✔ duplicate intent causes zero provider mutations (0.114244ms)
✔ prepare failure leaves current playback intact (0.378869ms)
✔ partial apply failure restores outgoing playback (0.232705ms)
✔ obsolete async resolve is rejected before stop/apply (0.222235ms)
✔ lease loss during stop prevents apply and stale rollback (4.212221ms)
✔ provider switch and bounded nested stack (0.292198ms)
✔ no authority retains playback without provider access (0.105488ms)
✔ queued state is captured at submission rather than read after caller mutation (0.09027ms)
✔ supersession after snapshot prevents mutations (0.166812ms)
✔ failed cross-provider apply cleans new owned audio before outgoing restoration (0.16018ms)
✔ superseded cross-provider apply is reconciled by stopping partially touched target (0.177582ms)
✔ extracted companion launches privately with fixture credentials, serves catalog diagnostics and listener PCM (201.412951ms)
✔ gateway binds target server-side and sanitizes metadata (1.013095ms)
✔ forged, wrong origin/campaign/session and unknown args deny before upstream (0.391262ms)
✔ listener cannot read queues or acquire controller lease (0.179616ms)
✔ expiry, revocation, stale fence and replay reject (0.201757ms)
✔ lease cannot be stolen and increases fence after revoke (0.129522ms)
✔ revocation during upstream I/O suppresses response (0.134181ms)
✔ MA adapter uses pinned envelope, Bearer header, fixed path, no redirects and returns no metadata (16.0455ms)
✔ MA mismatched queue, upstream failures and redirects fail with sanitized errors (1.798383ms)
✔ MA rejects URL credentials, query/fragment, paths and non-HTTP configuration (0.211004ms)
✔ MA read adapter performs real local HTTP POST against an isolated fixture (16.105082ms)
✔ signaling is confidential, per-listener authenticated, scoped and replay resistant (6.635415ms)
✔ signaling denies expired invitation, unknown/audio message types and unapproved TURN secrets (0.54029ms)
✔ GM browser policy refuses mixed content and SDK identity mismatch before any MA connection (0.715168ms)
✔ official pinned SDK decodes real binary PCM frames and discards stale generations (0.248766ms)
✔ parallel signaling replay cannot pass the asynchronous authentication check twice (1.826007ms)
✔ GM API WebSocket adapter authenticates privately, assembles partial results and refuses broad commands (12.583653ms)
✔ peer signaling bounds queued work and rejects expired invites before allocating a connection (25.202933ms)
✔ loopback transport denies unauthenticated, cross-campaign, controller, query and wrong-origin requests (12.953336ms)
✔ loopback streams synthetic PCM bytes and closes an active stream on revocation (43.258833ms)
✔ loopback closes idle synthetic stream when its listener capability expires (22.15983ms)
✔ MA snapshots ordered duplicate occurrences, pause and seek then reconstructs exact unshuffled order (7.12461ms)
✔ tampered, foreign/future snapshots and stale authority deny before MA mutations (0.866281ms)
✔ shuffled snapshot fails before interruption rather than promising exact restore (0.122439ms)
✔ prepared media cannot be forged and stale generations cannot issue controls (0.207959ms)
✔ every wire mutation revalidates exact identity/topology and uses fixed dedicated queue (15.898154ms)
✔ queue injection, transfer, arbitrary media URL and authority loss deny without writes (0.583201ms)
✔ catalog IDs survive independent adapter construction and differ across campaigns (1.436568ms)
✔ same-generation duplicate controls and restores issue no duplicate mutations (0.550701ms)
✔ MA provider with mock MA client composes with controller for nested contexts and rapid supersession (3.584397ms)
✔ ambiguous wire mutation failure latches closed instead of retrying or restoring blindly (0.947353ms)
✔ listener cannot obtain a playback fence guard or renew a controller lease (0.867032ms)
✔ playlist preparation expands approved ordered tracks before any playback mutation (1.429755ms)
✔ installable development entry defaults automation off and imports no gateway (7.558522ms)
✔ native captures actual offset and paused state, stops per sound, restores repeat/volume (1.465481ms)
✔ native resolves sequential playlist and touches only owned documents (0.502239ms)
✔ native rejects unsupported shuffle and empty playlist (0.147065ms)
✔ native rejects expired tracks, changed playlist membership and foreign/future snapshots before mutation (0.194464ms)
✔ native reports nonseekable restoration and clamps near-end seek (0.177542ms)
✔ scene-linked playlist conflict and lost authority fail before mutation (0.220453ms)
✔ GM election deterministic and no GM means none (4.613983ms)
✔ Foundry bootstrap registers local settings/hooks and disposes without ambient or actor access (0.664022ms)
✔ synthetic WAV termination emits fixed PCM frames through campaign listener authorization (0.875678ms)
✔ malformed, truncated and incompatible WAV formats fail closed before PCM publication (5.881385ms)
✔ credential loader rejects permissive modes, symlinks and malformed secrets (5.428296ms)
✔ private catalog identity key persists and unsafe key permissions fail (41.697223ms)
✔ scene assignments persist independently and world defaults/boss priority resolve without actor schemas (1.144961ms)
✔ native fallback is explicit, manual silence wins and legacy ambient does not resurrect after clearing (1.34135ms)
✔ unavailable saved MA selections are preserved but new forged IDs/non-native fallback and role loss deny (0.431697ms)
✔ GM setup connects catalog into independent scene editors and never persists its connection code (2.344586ms)
✔ browser PCM sink resumes from gesture, decodes stereo frames and closes its context on stream end (17.582896ms)
ℹ tests 85
ℹ suites 0
ℹ pass 85
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 1347.229561
$ python3 -m unittest discover -s tests -v
test_companion_is_separate_complete_and_excludes_private_configuration (test_package.DevelopmentPackageTests.test_companion_is_separate_complete_and_excludes_private_configuration) ... ok
test_package_excludes_gateway_private_state_and_false_verification (test_package.DevelopmentPackageTests.test_package_excludes_gateway_private_state_and_false_verification) ... ok
test_complete_offline_bundle_is_repeatable_and_checksums_match (test_release.ReleaseTests.test_complete_offline_bundle_is_repeatable_and_checksums_match) ... ok
test_gitea_github_stable_manifest_and_immutable_download_contract (test_release.ReleaseTests.test_gitea_github_stable_manifest_and_immutable_download_contract) ... ok
test_source_archive_rebuild_does_not_need_a_git_remote_or_metadata (test_release.ReleaseTests.test_source_archive_rebuild_does_not_need_a_git_remote_or_metadata) ... ok
test_tampered_manifest_or_missing_asset_is_rejected (test_release.ReleaseTests.test_tampered_manifest_or_missing_asset_is_rejected) ... ok
test_documentation_versions_are_not_private_addresses (test_repository.RepositorySafetyTests.test_documentation_versions_are_not_private_addresses) ... ok
test_embedded_url_credentials_rejected (test_repository.RepositorySafetyTests.test_embedded_url_credentials_rejected) ... ok
test_key_material_rejected (test_repository.RepositorySafetyTests.test_key_material_rejected) ... ok
test_network_evidence_is_unauthenticated (test_repository.RepositorySafetyTests.test_network_evidence_is_unauthenticated) ... ok
test_private_addresses_rejected (test_repository.RepositorySafetyTests.test_private_addresses_rejected) ... ok
test_private_config_rejected_even_when_forced_into_git (test_repository.RepositorySafetyTests.test_private_config_rejected_even_when_forced_into_git) ... ok
test_private_paths_are_ignored (test_repository.RepositorySafetyTests.test_private_paths_are_ignored) ... ok
test_provenance_pins_have_hashes (test_repository.RepositorySafetyTests.test_provenance_pins_have_hashes) ... ok
test_repository_guardrails (test_repository.RepositorySafetyTests.test_repository_guardrails) ... ok
----------------------------------------------------------------------
Ran 15 tests in 0.193s
OK
Final backend mutual-exclusion check:
$ npm test
> adaptive-music@0.5.0 test
> node --test tests/js/*.test.mjs
✔ catalog paginates, strips private metadata and filters unapproved mappings (34.696629ms)
✔ empty provider allowlist denies without I/O; malformed and endless pages fail (20.325816ms)
✔ target validation rejects group, changed identity and unavailable player (1.810717ms)
✔ synthetic audio isolates simultaneous campaigns and copies every frame (0.554908ms)
✔ audio denies forged origin/session/role, unknown fields and cross-campaign grants (0.381735ms)
✔ active listener revocation/expiry and slow-client overflow close handles (0.470911ms)
✔ synthetic source rejects stale sessions/generations, oversized frames; connections are bounded (0.358902ms)
✔ catalog authorization denies listener and injection before upstream (0.314629ms)
✔ scene/combat configuration preserves independent flags and stores only tagged references (1.750965ms)
✔ role loss, stale selection and arbitrary URL/ID fail before document write (0.331429ms)
✔ editor uses text for catalog labels and rechecks GM on actual save event (0.414065ms)
✔ configuration hook disposal prevents pending asynchronous render from mounting (0.190486ms)
✔ packaged browser client connects through real loopback companion/MA wire fixtures and restores combat queue (100.68071ms)
✔ companion denies listener control, wrong scope/Origin, upstream injection and unknown routes (8.076499ms)
✔ browser accepts only relative same-origin paths and never persists a connection grant (0.16008ms)
✔ companion operation replay is idempotent and same ID with changed payload is denied (11.60538ms)
✔ companion listener stream rejects controller grant and closes on live revocation and expiry (90.26337ms)
✔ catalog revocation during upstream I/O suppresses the response at the companion boundary (6.482046ms)
✔ policy precedence and explicit silence (1.518581ms)
✔ inactive, unstarted and other scene combats ignored; boss ties stable (4.045799ms)
✔ scene -> combat -> boss -> nested manual -> unwind restores offsets, duplicates and pause (1.253274ms)
✔ scene change during manual never resurrects previous scene (0.222587ms)
✔ boss removed during manual and deleted combat cannot return (0.291025ms)
✔ duplicate intent causes zero provider mutations (0.125034ms)
✔ prepare failure leaves current playback intact (0.343953ms)
✔ partial apply failure restores outgoing playback (0.183673ms)
✔ obsolete async resolve is rejected before stop/apply (0.309378ms)
✔ lease loss during stop prevents apply and stale rollback (0.230632ms)
✔ provider switch and bounded nested stack (1.168335ms)
✔ no authority retains playback without provider access (0.107982ms)
✔ queued state is captured at submission rather than read after caller mutation (0.068407ms)
✔ supersession after snapshot prevents mutations (0.16593ms)
✔ failed cross-provider apply cleans new owned audio before outgoing restoration (0.168415ms)
✔ superseded cross-provider apply is reconciled by stopping partially touched target (0.173114ms)
✔ extracted companion launches privately with fixture credentials, serves catalog diagnostics and listener PCM (196.285252ms)
✔ gateway binds target server-side and sanitizes metadata (0.985664ms)
✔ forged, wrong origin/campaign/session and unknown args deny before upstream (0.376113ms)
✔ listener cannot read queues or acquire controller lease (0.188895ms)
✔ expiry, revocation, stale fence and replay reject (0.190857ms)
✔ lease cannot be stolen and increases fence after revoke (0.121416ms)
✔ revocation during upstream I/O suppresses response (0.738723ms)
✔ MA adapter uses pinned envelope, Bearer header, fixed path, no redirects and returns no metadata (13.573212ms)
✔ MA mismatched queue, upstream failures and redirects fail with sanitized errors (1.742879ms)
✔ MA rejects URL credentials, query/fragment, paths and non-HTTP configuration (0.191988ms)
✔ MA read adapter performs real local HTTP POST against an isolated fixture (15.582672ms)
✔ signaling is confidential, per-listener authenticated, scoped and replay resistant (6.879711ms)
✔ signaling denies expired invitation, unknown/audio message types and unapproved TURN secrets (0.633104ms)
✔ GM browser policy refuses mixed content and SDK identity mismatch before any MA connection (0.540021ms)
✔ official pinned SDK decodes real binary PCM frames and discards stale generations (0.258925ms)
✔ parallel signaling replay cannot pass the asynchronous authentication check twice (1.449151ms)
✔ GM API WebSocket adapter authenticates privately, assembles partial results and refuses broad commands (12.419294ms)
✔ peer signaling bounds queued work and rejects expired invites before allocating a connection (24.838497ms)
✔ loopback transport denies unauthenticated, cross-campaign, controller, query and wrong-origin requests (13.373719ms)
✔ loopback streams synthetic PCM bytes and closes an active stream on revocation (42.631304ms)
✔ loopback closes idle synthetic stream when its listener capability expires (21.663446ms)
✔ MA snapshots ordered duplicate occurrences, pause and seek then reconstructs exact unshuffled order (8.238082ms)
✔ tampered, foreign/future snapshots and stale authority deny before MA mutations (1.022132ms)
✔ shuffled snapshot fails before interruption rather than promising exact restore (0.140523ms)
✔ prepared media cannot be forged and stale generations cannot issue controls (0.198481ms)
✔ every wire mutation revalidates exact identity/topology and uses fixed dedicated queue (15.718245ms)
✔ queue injection, transfer, arbitrary media URL and authority loss deny without writes (0.588681ms)
✔ catalog IDs survive independent adapter construction and differ across campaigns (2.752148ms)
✔ same-generation duplicate controls and restores issue no duplicate mutations (0.661507ms)
✔ MA provider with mock MA client composes with controller for nested contexts and rapid supersession (3.769762ms)
✔ ambiguous wire mutation failure latches closed instead of retrying or restoring blindly (0.612365ms)
✔ listener cannot obtain a playback fence guard or renew a controller lease (0.730557ms)
✔ playlist preparation expands approved ordered tracks before any playback mutation (2.677008ms)
✔ installable development entry defaults automation off and imports no gateway (9.722018ms)
✔ native captures actual offset and paused state, stops per sound, restores repeat/volume (4.196049ms)
✔ native resolves sequential playlist and touches only owned documents (0.489666ms)
✔ native rejects unsupported shuffle and empty playlist (0.149099ms)
✔ native rejects expired tracks, changed playlist membership and foreign/future snapshots before mutation (0.263082ms)
✔ native reports nonseekable restoration and clamps near-end seek (0.168274ms)
✔ scene-linked playlist conflict and lost authority fail before mutation (0.185315ms)
✔ GM election deterministic and no GM means none (3.762779ms)
✔ Foundry bootstrap registers local settings/hooks and disposes without ambient or actor access (0.648934ms)
✔ synthetic WAV termination emits fixed PCM frames through campaign listener authorization (0.819092ms)
✔ malformed, truncated and incompatible WAV formats fail closed before PCM publication (6.152892ms)
✔ credential loader rejects permissive modes, symlinks and malformed secrets (6.562927ms)
✔ private catalog identity key persists and unsafe key permissions fail (34.527232ms)
✔ scene assignments persist independently and world defaults/boss priority resolve without actor schemas (1.210996ms)
✔ native fallback is explicit, manual silence wins and legacy ambient does not resurrect after clearing (0.620279ms)
✔ unavailable saved MA selections are preserved but new forged IDs/non-native fallback and role loss deny (0.43879ms)
✔ GM setup connects catalog into independent scene editors and never persists its connection code (1.952823ms)
✔ browser PCM sink resumes from gesture, decodes stereo frames and closes its context on stream end (14.895866ms)
ℹ tests 85
ℹ suites 0
ℹ pass 85
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 1347.263856
$ python3 -m unittest discover -s tests -v
test_companion_is_separate_complete_and_excludes_private_configuration (test_package.DevelopmentPackageTests.test_companion_is_separate_complete_and_excludes_private_configuration) ... ok
test_package_excludes_gateway_private_state_and_false_verification (test_package.DevelopmentPackageTests.test_package_excludes_gateway_private_state_and_false_verification) ... ok
test_complete_offline_bundle_is_repeatable_and_checksums_match (test_release.ReleaseTests.test_complete_offline_bundle_is_repeatable_and_checksums_match) ... ok
test_gitea_github_stable_manifest_and_immutable_download_contract (test_release.ReleaseTests.test_gitea_github_stable_manifest_and_immutable_download_contract) ... ok
test_source_archive_rebuild_does_not_need_a_git_remote_or_metadata (test_release.ReleaseTests.test_source_archive_rebuild_does_not_need_a_git_remote_or_metadata) ... ok
test_tampered_manifest_or_missing_asset_is_rejected (test_release.ReleaseTests.test_tampered_manifest_or_missing_asset_is_rejected) ... ok
test_documentation_versions_are_not_private_addresses (test_repository.RepositorySafetyTests.test_documentation_versions_are_not_private_addresses) ... ok
test_embedded_url_credentials_rejected (test_repository.RepositorySafetyTests.test_embedded_url_credentials_rejected) ... ok
test_key_material_rejected (test_repository.RepositorySafetyTests.test_key_material_rejected) ... ok
test_network_evidence_is_unauthenticated (test_repository.RepositorySafetyTests.test_network_evidence_is_unauthenticated) ... ok
test_private_addresses_rejected (test_repository.RepositorySafetyTests.test_private_addresses_rejected) ... ok
test_private_config_rejected_even_when_forced_into_git (test_repository.RepositorySafetyTests.test_private_config_rejected_even_when_forced_into_git) ... ok
test_private_paths_are_ignored (test_repository.RepositorySafetyTests.test_private_paths_are_ignored) ... ok
test_provenance_pins_have_hashes (test_repository.RepositorySafetyTests.test_provenance_pins_have_hashes) ... ok
test_repository_guardrails (test_repository.RepositorySafetyTests.test_repository_guardrails) ... ok
----------------------------------------------------------------------
Ran 15 tests in 0.184s
OK
$ python3 scripts/audit_repository.py
PASS: repository privacy/attribution guardrails
$ python3 scripts/verify_upstream.py
PASS: all recorded Git heads, source and distribution file hashes
+12
View File
@@ -0,0 +1,12 @@
{
"checked_at": "2026-12-03T17:24:19.084Z",
"target": {
"dedicated": true,
"available": true,
"standalone": true
},
"playlists": 11,
"radios": 1,
"sanitized": true,
"independent_adapter_ids_match": true
}
+12
View File
@@ -0,0 +1,12 @@
{
"evidence_class": "live dedicated MA control tests; no content playback",
"runs": [
{"checked_at":"2026-12-03T17:16:04.878Z","successful_mutations":9,"original_state":"empty idle queue","restored":true},
{"checked_at":"2026-12-03T17:24:18.937Z","successful_mutations":0,"result":"session mismatch denied before mutations; harness corrected"},
{"checked_at":"2026-12-03T17:24:30.986Z","successful_mutations":9,"original_state":"empty idle queue","restored":true}
],
"total_successful_mutations":18,
"content_playback_mutations":0,
"synthetic_ingestion": "five-second metadata request failed; longer diagnostic returned HTTP 400; no queue mutation",
"limitations": "No pause/resume/seek with content, ordered nonempty restore, live combat/boss/manual or actual MA playlist playback verified"
}
+50
View File
@@ -0,0 +1,50 @@
{
"checked_at": "2026-12-03T17:24:30.986Z",
"evidence_class": "live dedicated MA",
"mutations": 9,
"checks": [
{
"action": "shuffle",
"value": true,
"result": "pass",
"scope": "idle queue controls"
},
{
"action": "shuffle",
"value": false,
"result": "pass",
"scope": "idle queue controls"
},
{
"action": "repeat",
"value": "one",
"result": "pass",
"scope": "idle queue controls"
},
{
"action": "repeat",
"value": "all",
"result": "pass",
"scope": "idle queue controls"
},
{
"action": "repeat",
"value": "off",
"result": "pass",
"scope": "idle queue controls"
},
{
"action": "stop",
"value": null,
"result": "pass",
"scope": "idle queue controls"
}
],
"restored": true,
"isolation_verified": true,
"original": {
"state": "idle",
"items": 0,
"position": 0
}
}
+40
View File
@@ -0,0 +1,40 @@
{
"checked_at": "2026-12-03T16:58:07.948228+00:00",
"credential": {
"directory_mode": "0700",
"token_mode": "0600",
"git_ignored": true,
"token_absent_reachable_history": true,
"token_absent_tracked_files": true
},
"authentication": true,
"role": "user",
"player_filter_count": 1,
"provider_filter_count": 7,
"dedicated_name_matches": true,
"player_available": true,
"sendspin_provider": true,
"standalone_topology": true,
"queue_id_matches_player": true,
"queue_active": true,
"synthetic_target_denial_status": 403,
"synthetic_provider_denial_status": 403,
"role_scopes": [
"config.core.read",
"config.players.read",
"config.providers.read",
"library.read",
"library.write",
"players.control",
"players.read",
"providers.read",
"queues.control",
"queues.read",
"system.read",
"users.invite"
],
"playlists_count": 11,
"playlists_approved_mappings": true,
"radios_count": 1,
"radios_approved_mappings": true
}
+16
View File
@@ -0,0 +1,16 @@
test_documentation_versions_are_not_private_addresses (test_repository.RepositorySafetyTests.test_documentation_versions_are_not_private_addresses) ... ok
test_embedded_url_credentials_rejected (test_repository.RepositorySafetyTests.test_embedded_url_credentials_rejected) ... ok
test_key_material_rejected (test_repository.RepositorySafetyTests.test_key_material_rejected) ... ok
test_network_evidence_is_unauthenticated (test_repository.RepositorySafetyTests.test_network_evidence_is_unauthenticated) ... ok
test_private_addresses_rejected (test_repository.RepositorySafetyTests.test_private_addresses_rejected) ... ok
test_private_config_rejected_even_when_forced_into_git (test_repository.RepositorySafetyTests.test_private_config_rejected_even_when_forced_into_git) ... ok
test_private_paths_are_ignored (test_repository.RepositorySafetyTests.test_private_paths_are_ignored) ... ok
test_provenance_pins_have_hashes (test_repository.RepositorySafetyTests.test_provenance_pins_have_hashes) ... ok
test_repository_guardrails (test_repository.RepositorySafetyTests.test_repository_guardrails) ... ok
----------------------------------------------------------------------
Ran 9 tests in 0.010s
OK
PASS: repository privacy/attribution guardrails
PASS: all recorded Git heads and source file hashes
+17
View File
@@ -0,0 +1,17 @@
{
"checked_at": "2026-12-03T20:42:10.945Z",
"evidence_class": "live MA target/queue reads plus browser-policy/source checks; no live browser-to-MA connection",
"target_verified": true,
"queue_state": "idle",
"queue_items": 0,
"target_identity_format_compatible": true,
"configured_ma_scheme": "http:",
"https_foundry_origin_policy": "mixed-content",
"gm_identity_profile_present": false,
"sendspin_connections": 0,
"identities_created": 0,
"mutations_sent": 0,
"actual_ma_audio": "blocked pending existing DEV private identity, secure private browser access and approved synthetic ingestion",
"websocket_auth_log_safety": "not verified live; source logs raw inbound auth at VERBOSE, explicit operator review required",
"live_websocket_auth_attempts": 0
}
+44
View File
@@ -0,0 +1,44 @@
{
"checked_at": "2026-12-03T21:01:48.898612+00:00",
"version": "0.5.0",
"artifacts": [
{
"artifact": "dist/adaptive-music-dev.zip",
"sha256": "ec45c0a3e4f8eae2593c7ae9cf1bdc3d724b5c6e6e9afd199ff6a506db71163f",
"bytes": 115735,
"files": 36
},
{
"artifact": "dist/releases/v0.5.0/adaptive-music.zip",
"sha256": "a9f904cb9e0844fe9b6a5c3a19f24358dfa6a0c4ca995aea9b1a3f81b301d584",
"bytes": 115735,
"files": 36
}
],
"foundry_live_verified": false,
"browser_zip_has_server_code": false,
"automation_default": false,
"history": [
{
"checked_at": "2026-12-03T20:07:10.575810+00:00",
"version": "0.4.0-dev",
"artifacts": [
{
"artifact": "dist/adaptive-music-dev.zip",
"sha256": "28637fd0a4b9754d591893a8224d059fc71a9371f6a978bfb5b935088e0956c2",
"bytes": 27681,
"files": 17
},
{
"artifact": "dist/adaptive-music-companion-dev.zip",
"sha256": "05427fc4998d8bef6d3d5ccb61d68931cd98fae2e28f6b777b9468d993c5558e",
"bytes": 33191,
"files": 19
}
],
"foundry_live_verified": false,
"browser_zip_has_server_code": false,
"automation_default": false
}
]
}
+53
View File
@@ -0,0 +1,53 @@
{
"checked_at": "2026-12-03T19:50:32.141285+00:00",
"audited_version": "0.3.0-dev",
"sha256": "2e0d5370a64e854b4bbdbea12d6969e6467b3eef9f5846361886d45058d3e801",
"files": [
"adaptive-music/module.json",
"adaptive-music/LICENSE",
"adaptive-music/THIRD-PARTY-NOTICES",
"adaptive-music/README.md",
"adaptive-music/src/core/controller.mjs",
"adaptive-music/src/foundry/configuration.mjs",
"adaptive-music/src/foundry/module.mjs",
"adaptive-music/src/foundry/runtime.mjs",
"adaptive-music/src/providers/native/provider.mjs",
"adaptive-music/licenses/Apache-2.0.txt",
"adaptive-music/licenses/VGM-MIT.txt"
],
"findings": {
"ma_connection_setup": false,
"browser_gateway_client": false,
"ma_catalog_in_configuration": false,
"separate_scene_ambient_combat": false,
"sendspin_browser_playback": false,
"crossfade": false
},
"assessment": "Native-only development package; server-side components were not connected to its browser entrypoint.",
"rebuilt_assessment": {
"version": "0.4.0-dev",
"ma_connection_setup": "operator capability + private same-origin companion route",
"browser_gateway_client": true,
"ma_catalog_in_configuration": true,
"separate_scene_ambient_combat": true,
"world_defaults_boss_native_fallback": true,
"synthetic_pcm_browser_sink": true,
"sendspin_browser_playback": false,
"crossfade": false,
"foundry_live_verified": false,
"artifacts": [
{
"artifact": "dist/adaptive-music-dev.zip",
"sha256": "28637fd0a4b9754d591893a8224d059fc71a9371f6a978bfb5b935088e0956c2",
"bytes": 27681,
"files": 17
},
{
"artifact": "dist/adaptive-music-companion-dev.zip",
"sha256": "05427fc4998d8bef6d3d5ccb61d68931cd98fae2e28f6b777b9468d993c5558e",
"bytes": 33191,
"files": 19
}
]
}
}
+12
View File
@@ -0,0 +1,12 @@
{
"checked_at": "2026-12-03T20:59:20.741930+00:00",
"local_directory_mode": "0700",
"token_file_mode": "0600",
"token_ignored": true,
"local_files_tracked": false,
"git_history_blob_count": 136,
"credential_in_git_history": false,
"generated_module_and_source_private_value_scan": "pass",
"gitea_contacted": false,
"limitations": "exact credential and configured private endpoint/target scan supplements repository heuristics; not a comprehensive secret detector"
}
+24
View File
@@ -0,0 +1,24 @@
{
"version": "0.5.0",
"scope": "offline package audit; actual browser synthetic experiment separate from MA/Foundry acceptance",
"connection_configuration": "GM-local in-memory developer API; optional companion setup retained; no one-click GM MA wizard",
"catalog_and_assignments": "shared MA catalog connected to existing GM choices and persistent scene ambient/combat/boss/native fallback + world defaults; real MA playback gated",
"audio": "official SDK PCM and WebRTC implemented experimentally; measured synthetic loopback browser audio, no live MA receiver connection",
"crossfade": "unimplemented",
"companion": "optional source and experimental/companion-0.4.0 branch; no deployment",
"distribution": "one module ZIP; configurable Git-hosted stable manifest + versioned download; offline bundle/checksums/tests pass; no hosted install/update verification",
"ma_mutations_this_revision": 0,
"regression": {
"javascript": 85,
"python": 15
},
"blocking_infrastructure": [
"isolated Foundry v14.371 world",
"existing DEV private identity/pairing",
"secure private browser MA access",
"operator WebSocket auth log review",
"approved synthetic MA ingestion",
"explicit existing TURN relay if required by NAT"
],
"gitea_contacted": false
}
+32
View File
@@ -0,0 +1,32 @@
{
"sdk": "@sendspin/sendspin-js",
"version": "5.0.0",
"git_commit": "7d103075138dda5c8909045647bb42b33c2d44fc",
"license": "Apache-2.0",
"integrity": "sha512-yRRjPsz6TyR1GzRYO7ur7oAzwZ11tELK1PEp6Ci7fscXOI0JdtP6BbwPhw+/CR0TWQxu/VwtVPtXT9SH/xhzFw==",
"inspected_before_install": true,
"install_hooks": false,
"dependency_pins": {
"@noble/ciphers": "1.3.0",
"@noble/curves": "1.9.7",
"@noble/hashes": "1.8.0",
"opus-encdec": "0.1.1"
},
"tool_pins": {
"esbuild": "0.27.1",
"playwright": "1.57.0"
},
"distribution_gate": "Pinned bundle hash, all notices and release validator required; no install hooks executed",
"license_review": "Reviewed Apache-2.0 SDK and full MIT noble license texts copied to licenses/vendor; optional opus-encdec fallback disabled, not distributed",
"lockfile": "package-lock.json",
"audit_checked_at": "2026-12-03T20:42:10.993687+00:00",
"vulnerabilities": {
"info": 0,
"low": 0,
"moderate": 0,
"high": 0,
"critical": 0,
"total": 0
},
"bundle_sha256": "b3a7c91e87c0a45e4bdb5a3bd3f323a12ffde9b54babd5ba38351d5dfd4d8556"
}
+42
View File
@@ -0,0 +1,42 @@
{
"license": "MIT; original mathematically generated tones",
"sample_rate": 24000,
"channels": 2,
"duration_seconds": 90,
"sequences": {
"ambient": [
{
"file": "ambient-1.wav",
"frequency_hz": 110,
"sha256": "12ec19bfe12e8a8e3d0f29e79de31812127f1f7e360ac4a2175026e5f210211e"
},
{
"file": "ambient-2.wav",
"frequency_hz": 165,
"sha256": "b12e11c31154dae190c9e448165577decd932d53af5f1969eaa8869db4ea690f"
},
{
"file": "ambient-3.wav",
"frequency_hz": 220,
"sha256": "c9bf2501ba41d16f0c1055b8b383db05f7de714206af35446eb0aad82476376b"
}
],
"combat": [
{
"file": "combat-1.wav",
"frequency_hz": 440,
"sha256": "4e6ba740d0fba4115e6117a118faec5eb74d5d171b1d4051602f86e004b9ee2e"
},
{
"file": "combat-2.wav",
"frequency_hz": 660,
"sha256": "95e8758c279780d4687011a755f7d79528e359e1b9221fb9739602eade7c5b08"
},
{
"file": "combat-3.wav",
"frequency_hz": 880,
"sha256": "cb83457277efdaa44e181697eadc7b8542fe60d00199bb10d547a5c21c29d4e9"
}
]
}
}
+6
View File
@@ -0,0 +1,6 @@
{
"checked_at": "2026-12-03T17:18:24.860Z",
"synthetic_ingestion": false,
"error": "unavailable",
"playback_mutations": 0
}
+8
View File
@@ -0,0 +1,8 @@
{
"checked_at": "2026-12-03T17:25:16.043Z",
"evidence_class": "local generated audio decoding",
"tracks": 6,
"frames": 27000,
"duration_seconds": 540,
"hashes_match": true
}
+131
View File
@@ -0,0 +1,131 @@
{
"checked_at": "2026-12-03",
"git_sources": [
{
"repository": "https://github.com/Sayshal/vgmusic",
"tag": "release-1.4.5",
"commit": "eba07a08c9925f31b9c8adb72faf95de11ae705c",
"local_directory": "vgmusic",
"files": {
"LICENSE": "8da4373e2f64fdd0289d5aba0ad81856f39742582dfa8caf49b22eece53e62d0",
"module.json": "2a50f7dfaaf91e953f6ffde97c8d58f5c88ab3cf2499863cf873d8f264539357",
"package.json": "6e607c8234023df368935e22fd7463d15ac6ab357e604899999c8a78ee1747fa",
"package-lock.json": "245c2723ddfc25a549e600630a324603e9cb234553dc392c8c5c92cc6da896f2",
"scripts/music-controller.mjs": "fc51195eda3c9cb8e04b9fc90ab9a4bd91c99ce6735a54929cf2bf3fa7404ccf",
"scripts/hooks.mjs": "069f1ede780ef1d55c51d65ff17322606f2d89f83d7d02284d2b1149a44898a0",
"scripts/playlist-context.mjs": "5126fbdef6b8129e6a8050da098a6fd904b02684565db014b9afe53d00bd2c0f"
}
},
{
"repository": "https://github.com/music-assistant/server",
"tag": "2.10.6",
"commit": "c24866405bd2068c25a60e1014e5ef8c3f6445bb",
"local_directory": "server",
"files": {
"LICENSE": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4",
"pyproject.toml": "39e6e2cd3962b081b6b8d2b905846d1e79a3ebc21f330d8003bf748f6913c84c",
"requirements_all.txt": "bf97bece2eaca5c0a9beead3a9a2f4e9cf66228c891e6580cb074219c1b2a141",
"music_assistant/controllers/webserver/controller.py": "93a3784d2c2070be512ed2f4619a6ea32088cb91aaa13879ab2fc2a7725a2f06",
"music_assistant/controllers/webserver/auth.py": "462717a6b2486c692d18f3917b26cf12eb036d1bb31ab1a4d0281a9ab505b116",
"music_assistant/controllers/webserver/websocket_client.py": "7ad62ba1f015914cdea6f99c8cac384a4c10ee33fb5b03ab0b6049cce729ecfd",
"music_assistant/controllers/webserver/sendspin_proxy.py": "0b2a25363786e8ef13a460b18c43e1a4a9d0ba30d816349a61f8db7421b85e7e",
"music_assistant/controllers/player_queues/controller.py": "3d610ee9b643a5a338104fbf13d67d2b680b7d4570bc7dfe2364e4d9712b4588",
"music_assistant/providers/sendspin/manifest.json": "cb99a3715f32c573a5120b960e5c3a31c6823bfc269f4963b8d72910132e38ea",
"music_assistant/controllers/webserver/helpers/auth_middleware.py": "f1c45cc4927c9a5e71193b13ff9d4300daaa65dc7b849d255c924fa495fb24a5",
"music_assistant/controllers/players/controller.py": "fd4a66cfe2b28ab7859f46990b3c45f58778d9fbb8dfb196346bed516a012c99",
"music_assistant/controllers/music/media/base.py": "a47aa23c9ed1039e303db1e4da1903c84d2122ed7c66c2b66ad8edd2d7341d45",
"music_assistant/providers/sendspin/provider.py": "9ba7235cd48723255a1d7e4af28f8f90f0e7448f4b234228571e219fa92ccb14",
"music_assistant/providers/sendspin/player.py": "306251735f52295cce3293549ca7f226fe37cab4d454966e8fb657aca7c535c6",
"music_assistant/providers/sendspin/README.md": "ee43c336550a7f4b8cac188f77e6d4e0b580d47d94321f392738d93da9e2c890",
"music_assistant/controllers/player_queues/queue_loader.py": "ead02948ca4450d3651d0c90683df16a16e8b6e23a040bf16b3eb877756e7a0e",
"music_assistant/helpers/uri.py": "c97c43f28db833910635bc89268dd44cb2487b3c26005737f55eb6c1f55521ca",
"music_assistant/providers/builtin/__init__.py": "54349ff427defa5a8c6664ccbcaf47c6564e1eb1606def5b8572c6d57e77df91",
"music_assistant/controllers/music/media/playlists.py": "7dbc38f93688a2b4f6fcd0501607a22942af55766d40f81795beef0dc037eb3e",
"music_assistant/controllers/player_queues/helpers.py": "0206927895599dae0b1dd4842a37d11d5d8e0de539e8f710b07684572de25529"
}
},
{
"repository": "https://github.com/music-assistant/frontend",
"tag": "2.17.297",
"commit": "e779b9d359e47cd210c2801f16a0ce6263571903",
"local_directory": "frontend",
"files": {
"LICENSE": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4",
"package.json": "83c66acc4371e0f10119ee50ee3d6940e3126fbf36898de02875331a590847c6",
"pnpm-lock.yaml": "129e7a8526a2e96c37f53bcc1895292cb56a73443c373198974ac7aa90b40093",
"src/plugins/sendspin-connection.ts": "780f52ad85fa38b1789267a50f03c744d59b59fa3dca3599ae0f742b150173ee"
}
},
{
"repository": "https://github.com/sendspin/sendspin-js",
"tag": "5.0.0",
"commit": "7d103075138dda5c8909045647bb42b33c2d44fc",
"local_directory": "sendspin-js-5",
"files": {
"LICENSE": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4",
"package.json": "6e1a04d4cf82ddae3e09ac7964952c718395b22a6de260f2e092d9848235aa88",
"src/core/protocol-handler.ts": "b3108d57fbaf974dd7aaf2b8bf0102817928fa1de501b0806b52bdd50a5d9436",
"src/core/transport.ts": "0d855eab42e1f94ef94e5aa324244eadd0e6fe99cb8be8e528199ab07cedb6b2",
"src/audio/clock-source.ts": "bd1c7321702211db42e3bedac746c0fa490a1e12215c3e34ec6b372a2c48a0e6",
"src/audio/decoder.ts": "0abefd87c26079cde9e2f87ad4c8d77a19818818d4ae745002e22930afac1e6a",
"src/audio/output-latency-tracker.ts": "1f5f6492fbb8ee7c1b2dc15c0299c7bbb62aa7dd356c8845c6c4e4178017d7c7",
"src/audio/platform-output-latency.ts": "ad916a598042e1a28578e9568668cdf2c3f880950f9232c438eebbdb34a1519a",
"src/audio/recorrection-monitor.ts": "075660439b7d1ae4140979c20d92a4b15d0842adf4d66f2ad32be031d2116858",
"src/audio/scheduler.ts": "d6d5b134d83d06c0d93b3da49aa70503e38da2fe5800f5029f299b233dd38b9a",
"src/client-identity.ts": "27b645e35d7967577c3a63246128b26350989e4a6ec8cfd66687682c048c4726",
"src/core/activate-authorization.ts": "e2a23dec97ef03829baafee8a4c83075e29c4c265d281926b2ce921d0ec1ccab",
"src/core/codec-support.ts": "fe160adfa40d2c5e0a3b3edd255ea94a283bf98e77431846ae3a0048e6cc50ce",
"src/core/core.ts": "44ce239896faca0887dbf33b5d5b7de924a3ee94c8babfe4e631ef6a82c2c5db",
"src/core/noise/base64url.ts": "0a8fc8f065de1b79497cd166cdfd02f0b1a8558d371bd641c0f8ab6f13cb9a16",
"src/core/noise/cipher-state.ts": "f31000531f6c5aecdbab4cb7ea3d2bfe3911fb58136b72c9e9a58cd0c386cd5d",
"src/core/noise/constants.ts": "bde591118b52136f90cd7e41f6901494c4a1cfae61cb0edaea26b599337829de",
"src/core/noise/handshake.ts": "40caa0df0098d1121a50547614b3564837241945d136fd2faab9202d8228ee3a",
"src/core/noise/identity.ts": "9f23c76b71aa7558aed9a6d416a5c9e75c69798cd74748454d96e96b9791022e",
"src/core/noise/index.ts": "0facbc17a2621f2e9ebf86dd1fadf5efece71028a495eb7165c62c8fe68c8218",
"src/core/noise/pairing-token.ts": "dfbc2e88478bbf9b7e4559c6597206b2262de431007143f8b3d099000980b762",
"src/core/noise/psk.ts": "7c5028446c85ff15e61f1afbee8fa6cc95628afb670018a107f0bd33622acafd",
"src/core/noise/session.ts": "fc1c6747c3d556920e5ac21726f1baa401c575ff6efe9546c8aa6687ebc95c50",
"src/core/noise/suites.ts": "59ba4f407a462c82afbd15568af682de823b012e5e831e67b368a2506d696abc",
"src/core/noise/symmetric-state.ts": "c498ce9caaf89af44076fa89dbd1fc8919289c6ca1b6de2a9670f4b99496a5f9",
"src/core/pairing.ts": "59c0994b3cd422035b98812268e2e87a87b99554786e8da46936af751cbcdc34",
"src/core/pake/cpace.ts": "fed37dbc91bb0f7711492a8481598982c887f14e244c0d1ef1ec0d59a103a2ec",
"src/core/pake/pin.ts": "5852b68967caa92626636f9cb48be3fd527ebee6911ddd54228740674efb71e4",
"src/core/state-manager.ts": "827fff0bbbb6153d807f21456a952f73b61b3aa81fa7bcd5b7aad7362ad122f9",
"src/core/static-delay-store.ts": "265dddae81afe28a8d1b376560e70cbe8c8c26f996ace0bf0bd1be84079d8f29",
"src/core/time-filter.ts": "0d562c167deb3cbdc2b7a23e5baa6f2dc70f214e5307b89903762f01dd6000f7",
"src/core/time-sync-manager.ts": "d64b7b648422333f68bafa878b2b3e2c084bd91d00f980b88c51c4ad8b07f913",
"src/core/websocket-manager.ts": "4acada3e75f19f63f2f7e6d367c545e2dc37a8735fdb32a40e100d94e6bb96db",
"src/index.ts": "e4ba034a7ab604ab80786ca255c73821cd4951ffc4a80c1bf24c4db3fb8d173b",
"src/internal-types.ts": "26e818c95bf831a7123788ca79cba104fc05c887e654c5e67bae06b9669cc2e2",
"src/opus-encdec.d.ts": "e05ec654daf12453bfe44d81b0ec8bc5162d1cd47a12df4502d0e879ca6be40a",
"src/sync-delay.ts": "8bdc54745a7b75da3d2dc78133e82601241323f9e33ee381f9c657d58c58916f",
"src/types.ts": "939c8df601891ad7b483fafa49df2b837e834881685f7e2278eb9e2ffd5dea15"
}
},
{
"repository": "https://github.com/sendspin/sendspin-js",
"tag": "6.1.0",
"commit": "7ee7ca35ac29ae3ef5f2eeeeaac1e24751a8790b",
"local_directory": "sendspin-js",
"files": {
"LICENSE": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4",
"package.json": "b6cae2c9836e467941bb7baab35bde2ead29f3171ce8be18fdb23b758d6b30e9"
}
}
],
"pypi_sources": [
{
"version": "9.1.1",
"url": "https://files.pythonhosted.org/packages/73/f0/03f798813a0e09f4e1565691d2e5138f0750c98b36d93f522d06c44efe66/aiosendspin-9.1.1.tar.gz",
"sha256": "1e9a33ec5b6dcbc16b4f03c07586195beaa80eb2e5ba4254b97979ae0e0ec4b7",
"inspected_files": {
"LICENSE": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4",
"README.md": "c7f2aaeb734b6628edf06ea9b4a5b425f25a5949a606a3d7f1f3dfb2268c749d",
"pyproject.toml": "940b19e327b155d56ca4935a6d62b946a28b60b734e4f35f61c49bd7b194798c",
"aiosendspin/client/client.py": "1fb7911997417fc97b85221de84935a0c4ae6cfc71d6dc29ca2e2aef5e4b4a08",
"aiosendspin/noise/trust_store.py": "b5a8dbd3f5d6692dca9ccdd4e9eba8eb9b706fa1ced69ef91bb8dcccb0d3f37f"
},
"local_directory": "aiosendspin/aiosendspin-9.1.1"
}
]
}
+84
View File
@@ -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.
+94
View File
@@ -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.
+78
View File
@@ -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 };
}
}
+38
View File
@@ -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;}};
}
+68
View File
@@ -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;
}
}
+43
View File
@@ -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;
}
};
}
+2
View File
@@ -0,0 +1,2 @@
// Compatibility export; validated transport is shared with the GM-local browser path.
export {MAReadClient} from '../src/providers/ma/client.mjs';
+2
View File
@@ -0,0 +1,2 @@
// Compatibility export; the same provider now runs with browser Web Crypto.
export {MAPlaybackProvider} from '../src/providers/ma/provider.mjs';
+19
View File
@@ -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));
}
+38
View File
@@ -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(); }
}
+45
View File
@@ -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;}
+63
View File
@@ -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();
}
}
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2025 3 Death Saves
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+22
View File
@@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2022 Paul Miller (https://paulmillr.com)
Copyright (c) 2016 Thomas Pornin <pornin@bolet.org>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2022 Paul Miller (https://paulmillr.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2022 Paul Miller (https://paulmillr.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+28
View File
@@ -0,0 +1,28 @@
{
"id": "adaptive-music",
"title": "Adaptive Music \u2014 Development",
"description": "Independent scene/combat music automation and experimental GM-local Sendspin/WebRTC audio. Native playback works without a companion; remote MA audio requires validated browser/network access.",
"version": "0.5.0",
"authors": [
{
"name": "CheddahBoxMB"
}
],
"compatibility": {
"minimum": "14",
"maximum": "14"
},
"esmodules": [
"src/foundry/module.mjs"
],
"relationships": {
"requires": []
},
"styles": [
"styles/adaptive-music.css"
],
"socket": true,
"url": "https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music",
"manifest": "https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/raw/branch/main/module.json",
"download": "https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/releases/download/v0.5.0/adaptive-music.zip"
}
+614
View File
@@ -0,0 +1,614 @@
{
"name": "adaptive-music",
"version": "0.5.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "adaptive-music",
"version": "0.5.0",
"license": "MIT",
"dependencies": {
"@sendspin/sendspin-js": "5.0.0"
},
"devDependencies": {
"esbuild": "0.27.1",
"playwright": "1.57.0"
},
"engines": {
"node": ">=24.23.0"
}
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.1.tgz",
"integrity": "sha512-HHB50pdsBX6k47S4u5g/CaLjqS3qwaOVE5ILsq64jyzgMhLuCuZ8rGzM9yhsAjfjkbgUPMzZEPa7DAp7yz6vuA==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"aix"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.1.tgz",
"integrity": "sha512-kFqa6/UcaTbGm/NncN9kzVOODjhZW8e+FRdSeypWe6j33gzclHtwlANs26JrupOntlcWmB0u8+8HZo8s7thHvg==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm64": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.1.tgz",
"integrity": "sha512-45fuKmAJpxnQWixOGCrS+ro4Uvb4Re9+UTieUY2f8AEc+t7d4AaZ6eUJ3Hva7dtrxAAWHtlEFsXFMAgNnGU9uQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-x64": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.1.tgz",
"integrity": "sha512-LBEpOz0BsgMEeHgenf5aqmn/lLNTFXVfoWMUox8CtWWYK9X4jmQzWjoGoNb8lmAYml/tQ/Ysvm8q7szu7BoxRQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-arm64": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.1.tgz",
"integrity": "sha512-veg7fL8eMSCVKL7IW4pxb54QERtedFDfY/ASrumK/SbFsXnRazxY4YykN/THYqFnFwJ0aVjiUrVG2PwcdAEqQQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-x64": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.1.tgz",
"integrity": "sha512-+3ELd+nTzhfWb07Vol7EZ+5PTbJ/u74nC6iv4/lwIU99Ip5uuY6QoIf0Hn4m2HoV0qcnRivN3KSqc+FyCHjoVQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-arm64": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.1.tgz",
"integrity": "sha512-/8Rfgns4XD9XOSXlzUDepG8PX+AVWHliYlUkFI3K3GB6tqbdjYqdhcb4BKRd7C0BhZSoaCxhv8kTcBrcZWP+xg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-x64": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.1.tgz",
"integrity": "sha512-GITpD8dK9C+r+5yRT/UKVT36h/DQLOHdwGVwwoHidlnA168oD3uxA878XloXebK4Ul3gDBBIvEdL7go9gCUFzQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.1.tgz",
"integrity": "sha512-ieMID0JRZY/ZeCrsFQ3Y3NlHNCqIhTprJfDgSB3/lv5jJZ8FX3hqPyXWhe+gvS5ARMBJ242PM+VNz/ctNj//eA==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm64": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.1.tgz",
"integrity": "sha512-W9//kCrh/6in9rWIBdKaMtuTTzNj6jSeG/haWBADqLLa9P8O5YSRDzgD5y9QBok4AYlzS6ARHifAb75V6G670Q==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ia32": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.1.tgz",
"integrity": "sha512-VIUV4z8GD8rtSVMfAj1aXFahsi/+tcoXXNYmXgzISL+KB381vbSTNdeZHHHIYqFyXcoEhu9n5cT+05tRv13rlw==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-loong64": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.1.tgz",
"integrity": "sha512-l4rfiiJRN7sTNI//ff65zJ9z8U+k6zcCg0LALU5iEWzY+a1mVZ8iWC1k5EsNKThZ7XCQ6YWtsZ8EWYm7r1UEsg==",
"cpu": [
"loong64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-mips64el": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.1.tgz",
"integrity": "sha512-U0bEuAOLvO/DWFdygTHWY8C067FXz+UbzKgxYhXC0fDieFa0kDIra1FAhsAARRJbvEyso8aAqvPdNxzWuStBnA==",
"cpu": [
"mips64el"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ppc64": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.1.tgz",
"integrity": "sha512-NzdQ/Xwu6vPSf/GkdmRNsOfIeSGnh7muundsWItmBsVpMoNPVpM61qNzAVY3pZ1glzzAxLR40UyYM23eaDDbYQ==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-riscv64": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.1.tgz",
"integrity": "sha512-7zlw8p3IApcsN7mFw0O1Z1PyEk6PlKMu18roImfl3iQHTnr/yAfYv6s4hXPidbDoI2Q0pW+5xeoM4eTCC0UdrQ==",
"cpu": [
"riscv64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-s390x": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.1.tgz",
"integrity": "sha512-cGj5wli+G+nkVQdZo3+7FDKC25Uh4ZVwOAK6A06Hsvgr8WqBBuOy/1s+PUEd/6Je+vjfm6stX0kmib5b/O2Ykw==",
"cpu": [
"s390x"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-x64": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.1.tgz",
"integrity": "sha512-z3H/HYI9MM0HTv3hQZ81f+AKb+yEoCRlUby1F80vbQ5XdzEMyY/9iNlAmhqiBKw4MJXwfgsh7ERGEOhrM1niMA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-arm64": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.1.tgz",
"integrity": "sha512-wzC24DxAvk8Em01YmVXyjl96Mr+ecTPyOuADAvjGg+fyBpGmxmcr2E5ttf7Im8D0sXZihpxzO1isus8MdjMCXQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-x64": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.1.tgz",
"integrity": "sha512-1YQ8ybGi2yIXswu6eNzJsrYIGFpnlzEWRl6iR5gMgmsrR0FcNoV1m9k9sc3PuP5rUBLshOZylc9nqSgymI+TYg==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-arm64": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.1.tgz",
"integrity": "sha512-5Z+DzLCrq5wmU7RDaMDe2DVXMRm2tTDvX2KU14JJVBN2CT/qov7XVix85QoJqHltpvAOZUAc3ndU56HSMWrv8g==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-x64": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.1.tgz",
"integrity": "sha512-Q73ENzIdPF5jap4wqLtsfh8YbYSZ8Q0wnxplOlZUOyZy7B4ZKW8DXGWgTCZmF8VWD7Tciwv5F4NsRf6vYlZtqg==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openharmony-arm64": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.1.tgz",
"integrity": "sha512-ajbHrGM/XiK+sXM0JzEbJAen+0E+JMQZ2l4RR4VFwvV9JEERx+oxtgkpoKv1SevhjavK2z2ReHk32pjzktWbGg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openharmony"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/sunos-x64": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.1.tgz",
"integrity": "sha512-IPUW+y4VIjuDVn+OMzHc5FV4GubIwPnsz6ubkvN8cuhEqH81NovB53IUlrlBkPMEPxvNnf79MGBoz8rZ2iW8HA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"sunos"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-arm64": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.1.tgz",
"integrity": "sha512-RIVRWiljWA6CdVu8zkWcRmGP7iRRIIwvhDKem8UMBjPql2TXM5PkDVvvrzMtj1V+WFPB4K7zkIGM7VzRtFkjdg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-ia32": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.1.tgz",
"integrity": "sha512-2BR5M8CPbptC1AK5JbJT1fWrHLvejwZidKx3UMSF0ecHMa+smhi16drIrCEggkgviBwLYd5nwrFLSl5Kho96RQ==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-x64": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.1.tgz",
"integrity": "sha512-d5X6RMYv6taIymSk8JBP+nxv8DQAMY6A51GPgusqLdK9wBz5wWIXy1KjTck6HnjE9hqJzJRdk+1p/t5soSbCtw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@noble/ciphers": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-1.3.0.tgz",
"integrity": "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==",
"license": "MIT",
"engines": {
"node": "^14.21.3 || >=16"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@noble/curves": {
"version": "1.9.7",
"resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.7.tgz",
"integrity": "sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw==",
"license": "MIT",
"dependencies": {
"@noble/hashes": "1.8.0"
},
"engines": {
"node": "^14.21.3 || >=16"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@noble/hashes": {
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz",
"integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==",
"license": "MIT",
"engines": {
"node": "^14.21.3 || >=16"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@sendspin/sendspin-js": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/@sendspin/sendspin-js/-/sendspin-js-5.0.0.tgz",
"integrity": "sha512-yRRjPsz6TyR1GzRYO7ur7oAzwZ11tELK1PEp6Ci7fscXOI0JdtP6BbwPhw+/CR0TWQxu/VwtVPtXT9SH/xhzFw==",
"license": "Apache-2.0",
"dependencies": {
"@noble/ciphers": "^1.2.1",
"@noble/curves": "^1.8.1",
"@noble/hashes": "^1.7.1",
"opus-encdec": "^0.1.1"
},
"engines": {
"node": ">=16.0.0"
}
},
"node_modules/esbuild": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.1.tgz",
"integrity": "sha512-yY35KZckJJuVVPXpvjgxiCuVEJT67F6zDeVTv4rizyPrfGBUpZQsvmxnN+C371c2esD/hNMjj4tpBhuueLN7aA==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"bin": {
"esbuild": "bin/esbuild"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"@esbuild/aix-ppc64": "0.27.1",
"@esbuild/android-arm": "0.27.1",
"@esbuild/android-arm64": "0.27.1",
"@esbuild/android-x64": "0.27.1",
"@esbuild/darwin-arm64": "0.27.1",
"@esbuild/darwin-x64": "0.27.1",
"@esbuild/freebsd-arm64": "0.27.1",
"@esbuild/freebsd-x64": "0.27.1",
"@esbuild/linux-arm": "0.27.1",
"@esbuild/linux-arm64": "0.27.1",
"@esbuild/linux-ia32": "0.27.1",
"@esbuild/linux-loong64": "0.27.1",
"@esbuild/linux-mips64el": "0.27.1",
"@esbuild/linux-ppc64": "0.27.1",
"@esbuild/linux-riscv64": "0.27.1",
"@esbuild/linux-s390x": "0.27.1",
"@esbuild/linux-x64": "0.27.1",
"@esbuild/netbsd-arm64": "0.27.1",
"@esbuild/netbsd-x64": "0.27.1",
"@esbuild/openbsd-arm64": "0.27.1",
"@esbuild/openbsd-x64": "0.27.1",
"@esbuild/openharmony-arm64": "0.27.1",
"@esbuild/sunos-x64": "0.27.1",
"@esbuild/win32-arm64": "0.27.1",
"@esbuild/win32-ia32": "0.27.1",
"@esbuild/win32-x64": "0.27.1"
}
},
"node_modules/fsevents": {
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/opus-encdec": {
"version": "0.1.1",
"resolved": "https://registry.npmjs.org/opus-encdec/-/opus-encdec-0.1.1.tgz",
"integrity": "sha512-TDzyGqYqrwn5UEUNaLsfLGu8Ma+HRNrgLYj7Vx5wfTnafAA21G6Bnm/qTIa3orQi/yZPZYmkdpO/gez4nfA1Rw==",
"license": "MIT"
},
"node_modules/playwright": {
"version": "1.57.0",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.57.0.tgz",
"integrity": "sha512-ilYQj1s8sr2ppEJ2YVadYBN0Mb3mdo9J0wQ+UuDhzYqURwSoW4n1Xs5vs7ORwgDGmyEh33tRMeS8KhdkMoLXQw==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright-core": "1.57.0"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"fsevents": "2.3.2"
}
},
"node_modules/playwright-core": {
"version": "1.57.0",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.57.0.tgz",
"integrity": "sha512-agTcKlMw/mjBWOnD6kFZttAAGHgi/Nw0CZ2o6JqWSbMlI219lAFLZZCyqByTsvVAJq5XA5H8cA6PrvBRpBWEuQ==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
},
"engines": {
"node": ">=18"
}
}
}
}
+31
View File
@@ -0,0 +1,31 @@
{
"name": "adaptive-music",
"version": "0.5.0",
"private": true,
"type": "module",
"license": "MIT",
"engines": {
"node": ">=24.23.0"
},
"scripts": {
"test": "node --test tests/js/*.test.mjs",
"package:module": "python3 scripts/package_module.py",
"gateway:dev": "node gateway/run-development.mjs",
"build:vendor": "node scripts/build_sendspin.mjs",
"release": "python3 scripts/release.py",
"test:browser-audio": "node scripts/measure_browser_audio.mjs"
},
"dependencies": {
"@sendspin/sendspin-js": "5.0.0"
},
"devDependencies": {
"esbuild": "0.27.1",
"playwright": "1.57.0"
},
"overrides": {
"@noble/ciphers": "1.3.0",
"@noble/curves": "1.9.7",
"@noble/hashes": "1.8.0",
"opus-encdec": "0.1.1"
}
}
+52
View File
@@ -0,0 +1,52 @@
"""Offline tracked/unignored-file guardrails; not a complete secret scanner."""
from __future__ import annotations
import ipaddress
from pathlib import Path
import re
import subprocess
ROOT = Path(__file__).resolve().parents[1]
REQUIRED = ('AGENTS.md', 'ARCHITECTURE.md', 'PROGRESS.md', 'TESTING.md',
'SECURITY.md', 'THIRD-PARTY-NOTICES', '.gitignore')
def findings(name: str, data: str) -> list[str]:
issues = []
if name.startswith('.local/') or Path(name).name.startswith('.env'):
issues.append('private configuration file included')
for candidate in re.findall(r'(?<![\w.])(?:\d{1,3}\.){3}\d{1,3}(?![\w.])', data):
try:
address = ipaddress.ip_address(candidate)
except ValueError:
continue
if address.is_private and not address.is_loopback:
issues.append('private IP address included')
if re.search(r'-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----', data):
issues.append('private key material included')
if re.search(r'https?://[^\s/@]+:[^\s/@]+@', data):
issues.append('URL credentials included')
return sorted(set(issues))
def audit() -> list[str]:
errors = [f'missing {name}' for name in REQUIRED if not (ROOT / name).is_file()]
paths = subprocess.check_output(
['git', 'ls-files', '-z', '--cached', '--others', '--exclude-standard'],
cwd=ROOT).decode().split('\0')
for name in sorted(set(filter(None, paths))):
path = ROOT / name
if path.is_file():
errors.extend(f'{name}: {reason}' for reason in findings(
name, path.read_text(errors='replace')))
notices = (ROOT / 'THIRD-PARTY-NOTICES').read_text()
for credit in ('CheddahBoxMB', '3 Death Saves', 'Furyspark', 'Tyler', 'Apache-2.0'):
if credit not in notices:
errors.append(f'missing attribution: {credit}')
return errors
if __name__ == '__main__':
problems = audit()
print('\n'.join(problems) if problems else 'PASS: repository privacy/attribution guardrails')
raise SystemExit(bool(problems))
+16
View File
@@ -0,0 +1,16 @@
// Rebuild only with npm ci --ignore-scripts from the audited lock. Releases use committed output.
import {build} from 'esbuild';
import {readFile,writeFile,copyFile,mkdir} from 'node:fs/promises';
import {createHash} from 'node:crypto';
await mkdir('vendor',{recursive:true});await mkdir('licenses/vendor',{recursive:true});
const result=await build({stdin:{contents:"export {SendspinCore,SendspinDecoder,loadSendspinClientIdentity} from '@sendspin/sendspin-js';",resolveDir:process.cwd()},bundle:true,format:'esm',platform:'browser',target:'es2022',minify:true,legalComments:'eof',write:false,metafile:true,
plugins:[{name:'pcm-only-no-optional-codec',setup(builder){builder.onResolve({filter:/^opus-encdec\//},()=>({path:'disabled-codec',namespace:'pcm-only'}));builder.onLoad({filter:/.*/,namespace:'pcm-only'},()=>({contents:"throw new Error('Optional Opus fallback is not distributed; negotiate PCM'); export default undefined;",loader:'js'}));}}]});
const banner='// @sendspin/sendspin-js 5.0.0 (Apache-2.0), bundled with audited noble MIT dependencies.\n// Modification: optional opus-encdec decoder imports disabled; this build negotiates PCM only.\n// See licenses/vendor and THIRD-PARTY-NOTICES. No source maps or remote imports.\n';
const bytes=banner+result.outputFiles[0].text;await writeFile('vendor/sendspin-5.0.0.mjs',bytes);
const licenses=[['@sendspin/sendspin-js','LICENSE'],['@noble/ciphers','LICENSE'],['@noble/curves','LICENSE'],['@noble/hashes','LICENSE']];
for(const [name,file]of licenses)await copyFile(`node_modules/${name}/${file}`,`licenses/vendor/${name.replace(/[@/]/g,'-')}.txt`);
const lock=JSON.parse(await readFile('package-lock.json','utf8'));
const provenance={sdk:'@sendspin/sendspin-js',version:'5.0.0',sha256:createHash('sha256').update(bytes).digest('hex'),build:'scripts/build_sendspin.mjs',pcm_only:true,optional_opus_fallback_distributed:false,
packages:licenses.map(([name])=>({name,version:lock.packages['node_modules/'+name].version,integrity:lock.packages['node_modules/'+name].integrity})),input_files:Object.keys(result.metafile.inputs).filter(p=>p.startsWith('node_modules/'))};
await writeFile('vendor/provenance.json',JSON.stringify(provenance,null,2)+'\n');
console.log('Built pinned PCM-only official SDK bundle and copied notices.');
+26
View File
@@ -0,0 +1,26 @@
// Authorized reads only: browser-safe client -> loopback companion -> dedicated live MA.
import {readFile,writeFile} from 'node:fs/promises';
import {liveClient} from './live_ma_preflight.mjs';
import {GatewayControl} from '../gateway/control.mjs';
import {DevelopmentService} from '../gateway/development-service.mjs';
import {startDevelopmentHTTP} from '../gateway/development-http.mjs';
import {GatewayClient} from '../src/providers/ma/remote.mjs';
const origin='https://foundry.example.test';let server,browser;
try{
const {client,catalogKey}=await liveClient();
const campaign='read-only-local',session='read-only-session';
const control=new GatewayControl({campaigns:{[campaign]:{client}},origin});
const token=control.mint({campaign,session,role:'controller'});
const service=new DevelopmentService({control,campaign,session,client,snapshotKey:catalogKey,playbackEnabled:false});
server=await startDevelopmentHTTP({service,origin});const wire=[];
browser=new GatewayClient({origin,fetchImpl:async(path,options)=>{const response=await fetch(server.url+path.replace('/adaptive-music-gateway',''),{...options,headers:{...options.headers,Origin:origin}});wire.push(await response.clone().text());return response;}});
const status=await browser.connect({token,campaign,session});
const maToken=(await readFile('.local/ma-token','utf8')).trim(),environment=JSON.parse(await readFile('.local/environment.json','utf8')),prior=JSON.parse(await readFile('.local/ma-readonly-results.json','utf8'));
const report={checked_at:new Date().toISOString(),evidence_class:'live MA reads through local companion and browser-safe client; no real Foundry browser',target:status.target,
playlists:browser.catalog.filter(c=>c.kind==='playlist').length,radios:browser.catalog.filter(c=>c.kind==='radio').length,
browser_payloads_private:!wire.join('').includes(maToken)&&!wire.join('').includes(environment.ma_url)&&!wire.join('').includes(prior.me.player_filter[0]),
playback_enabled:status.playbackEnabled,mutations_sent:0,foundry_verified:false,tls_verified:false};
await writeFile('evidence/connected-ma-readonly.json',JSON.stringify(report,null,2)+'\n');console.log(JSON.stringify(report,null,2));
if(report.target!=='verified'||!report.browser_payloads_private)process.exitCode=1;
}catch(error){console.error('Connected catalog check failed:',error.code??'unavailable');process.exitCode=1;}
finally{await browser?.disconnect();await server?.close();}
+13
View File
@@ -0,0 +1,13 @@
// Authorized target/catalog reads only; compare two independent adapters for restart identity.
import { writeFile } from 'node:fs/promises';
import { liveClient } from './live_ma_preflight.mjs';
try {
const {client}=await liveClient();const target=await client.verifyTarget();const catalog=await client.catalog();
const restarted=await liveClient();const after=await restarted.client.catalog();
const ids=items=>items.map(c=>c.id).sort().join(',');
const report={checked_at:new Date().toISOString(),target,playlists:catalog.filter(c=>c.kind==='playlist').length,
radios:catalog.filter(c=>c.kind==='radio').length,sanitized:catalog.every(c=>Object.keys(c).sort().join(',')==='id,kind,name,provider'),
independent_adapter_ids_match:ids(catalog)===ids(after)};
await writeFile('evidence/ma-adapter.json',JSON.stringify(report,null,2)+'\n');console.log(JSON.stringify(report,null,2));
if(!report.independent_adapter_ids_match)process.exitCode=1;
}catch{console.error('MA adapter verification failed (details withheld)');process.exitCode=1;}
@@ -0,0 +1,15 @@
// Authorized live read-only preflight. No Sendspin connection, pairing, new identity or playback.
import {readFile,writeFile,access} from 'node:fs/promises';
import {liveClient} from './live_ma_preflight.mjs';
import {gmAccessPolicy} from '../src/audio/gm-host.mjs';
const environment=JSON.parse(await readFile('.local/environment.json','utf8'));
const previous=JSON.parse(await readFile('.local/ma-readonly-results.json','utf8'));
const {client}=await liveClient();await client.verifyTarget();const queue=await client.queueState();
let policy='allowed';try{gmAccessPolicy(environment.ma_url,'https://foundry.example.test/');}catch(error){policy=error.code??'denied';}
let identityProfilePresent=false;try{await access('.local/gm-profile.json');identityProfilePresent=true;}catch{}
const result={checked_at:new Date().toISOString(),evidence_class:'live MA target/queue reads plus browser-policy/source checks; no live browser-to-MA connection',
target_verified:true,queue_state:queue.state,queue_items:queue.items,target_identity_format_compatible:/^[A-Za-z0-9_-]{43}$/.test(previous.player.player_id),
configured_ma_scheme:new URL(environment.ma_url).protocol,https_foundry_origin_policy:policy,gm_identity_profile_present:identityProfilePresent,sendspin_connections:0,identities_created:0,mutations_sent:0,
websocket_auth_log_safety:'not verified live; source logs raw inbound auth at VERBOSE, explicit operator review required',live_websocket_auth_attempts:0,
actual_ma_audio:'blocked pending existing DEV private identity, secure private browser access and approved synthetic ingestion'};
await writeFile('evidence/module-only-prerequisites.json',JSON.stringify(result,null,2)+'\n');console.log(JSON.stringify(result,null,2));
+15
View File
@@ -0,0 +1,15 @@
import {readFile,writeFile} from 'node:fs/promises';
import {liveClient} from './live_ma_preflight.mjs';
export async function syntheticSequences(){
const source=JSON.parse(await readFile('.local/fixture-origin.json','utf8'));
return Object.fromEntries(Object.entries(source.sequences).map(([kind,files])=>[`synthetic-${kind}`,files.map(name=>`builtin://track/${source.base_url}/${name}`)]));
}
try{
const {client}=await liveClient(await syntheticSequences());await client.verifyTarget();
const tracks=await client.inspectSynthetic();
const report={checked_at:new Date().toISOString(),synthetic_ingestion:true,tracks:tracks.length,durations:tracks.map(t=>t.duration),playback_mutations:0};
await writeFile('evidence/synthetic-ingestion.json',JSON.stringify(report,null,2)+'\n');console.log(JSON.stringify(report));
}catch(error){
const report={checked_at:new Date().toISOString(),synthetic_ingestion:false,error:error.code??'unavailable',playback_mutations:0};
await writeFile('evidence/synthetic-ingestion.json',JSON.stringify(report,null,2)+'\n');console.log(JSON.stringify(report));process.exitCode=1;
}
+12
View File
@@ -0,0 +1,12 @@
import {readFile,writeFile} from 'node:fs/promises';
import {createHash} from 'node:crypto';
import {pcmFixtureFrames} from '../gateway/pcm-fixture.mjs';
const manifest=JSON.parse(await readFile('.local/synthetic-audio/manifest.json','utf8'));
const result={checked_at:new Date().toISOString(),evidence_class:'local generated audio decoding',tracks:0,frames:0,duration_seconds:0,hashes_match:true};
for(const tracks of Object.values(manifest.sequences))for(const track of tracks){
const bytes=await readFile(`.local/synthetic-audio/${track.file}`);
if(createHash('sha256').update(bytes).digest('hex')!==track.sha256)throw Error('fixture mismatch');
let frames=0;for(const frame of pcmFixtureFrames(bytes)){if(frame.length!==1920)throw Error('frame mismatch');frames++;}
if(frames!==4500)throw Error('duration mismatch');result.tracks++;result.frames+=frames;result.duration_seconds+=frames*.02;
}
await writeFile('evidence/synthetic-pipeline.json',JSON.stringify(result,null,2)+'\n');console.log(JSON.stringify(result));
+12
View File
@@ -0,0 +1,12 @@
"""Runner-neutral artifact generation; no publish/upload/git-host API calls."""
import os
from pathlib import Path
import json
from release import ROOT,DEFAULT_REPOSITORY,build_release
manifest=json.loads((ROOT/'module.json').read_text())
ref=os.environ.get('GITHUB_REF_NAME') or os.environ.get('GITEA_REF_NAME','')
if ref.startswith('v') and ref!='v'+manifest['version']:raise SystemExit('tag/manifest version mismatch')
repository=os.environ.get('RELEASE_REPOSITORY')
if not repository and os.environ.get('GITHUB_SERVER_URL')=='https://github.com' and os.environ.get('GITHUB_REPOSITORY'):repository='https://github.com/'+os.environ['GITHUB_REPOSITORY']
repository=repository or DEFAULT_REPOSITORY
print(build_release(repository))
+83
View File
@@ -0,0 +1,83 @@
// Explicit bounded DEV-only experiment. No browser or network control endpoint.
import { randomUUID } from 'node:crypto';
import { readFile,writeFile } from 'node:fs/promises';
import { liveClient,savePrivate } from './live_ma_preflight.mjs';
import { MAPlaybackProvider } from '../gateway/ma-provider.mjs';
import { GatewayControl } from '../gateway/control.mjs';
import { MusicController } from '../src/core/controller.mjs';
const report={checked_at:new Date().toISOString(),evidence_class:'live dedicated MA',mutations:0,checks:[],restored:false};
let provider,original,client,gateway,request,timer,controller,generation=0;
const session=randomUUID();
const ctx=()=>({campaign:'development',session,generation:(generation=Math.max(generation,controller?.generation??0)+1),check(){if(generation>10000)throw Error('stale');}});
const delay=ms=>new Promise(resolve=>setTimeout(resolve,ms));
try {
if(!process.argv.includes('--controls-only') && !process.argv.includes('--synthetic'))throw Object.assign(Error(),{code:'mode-required'});
let sequences;
if(process.argv.includes('--synthetic')) {
const source=JSON.parse(await readFile('.local/fixture-origin.json','utf8'));
sequences=Object.fromEntries(Object.entries(source.sequences).map(([kind,files])=>[`synthetic-${kind}`,files.map(name=>`builtin://track/${source.base_url}/${name}`)]));
}
const loaded=await liveClient(sequences);client=loaded.client;
if(sequences){await client.inspectSynthetic();report.content='original synthetic sequences; not MA playlists';}
await client.verifyTarget();report.isolation_verified=true;
gateway=new GatewayControl({campaigns:{development:{client}},origin:'https://example.test'});
request={campaign:'development',session,origin:'https://example.test',token:gateway.mint({campaign:'development',session,role:'controller',ttlMs:300000})};request.fence=gateway.acquire(request).fence;
timer=setInterval(()=>{try{gateway.renew(request);}catch{clearInterval(timer);}},10000);
const mutate=client.mutate.bind(client);client.mutate=async(...args)=>{await mutate(...args);report.mutations++;};
provider=new MAPlaybackProvider({client,campaign:request.campaign,session:request.session,fence:request.fence,authority:gateway.fenceGuard(request),snapshotKey:loaded.catalogKey});
original=await provider.snapshot(ctx());await savePrivate('ma-original-snapshot.json',original);
report.original={state:original.value.state,items:original.value.items.length,position:original.value.position};
// Abort instead of interrupting unexpected existing playback in a controls-only run.
if(process.argv.includes('--controls-only')){
if(original.value.items.length || original.value.state!=='idle')throw Object.assign(Error(),{code:'unsupported'});
for(const [action,value] of [['shuffle',true],['shuffle',false],['repeat','one'],['repeat','all'],['repeat','off'],['stop',null]]){
await provider.control(action,value,ctx());const q=await client.queueState();
if(action==='shuffle' && q.shuffle_enabled!==value || action==='repeat' && q.repeat_mode!==value)throw Error();
report.checks.push({action,value,result:'pass',scope:'idle queue controls'});
}
}else{
// Original generated fixtures only; actual MA playlist playback needs separate acceptance.
const refs=['synthetic-ambient','synthetic-combat'].map(id=>({provider:'ma',id}));
await provider.apply(await provider.resolve(refs[0],ctx()),ctx());await delay(1500);
for(const [action,value] of [['pause',null],['resume',null],['seek',3],['shuffle',true],['shuffle',false],['repeat','one'],['repeat','all'],['repeat','off']]){
await provider.control(action,value,ctx());await delay(250);report.checks.push({action,result:'command accepted'});
}
// Park the ambient fixture for exact offset comparisons through nested contexts.
await provider.control('pause',null,ctx());await delay(250);
const ambient=await provider.snapshot(ctx());
controller=new MusicController({campaign:request.campaign,session:request.session,providers:{ma:provider},authority:()=>true});
controller.generation=generation;
const base={scene:{id:'fixture',playlist:refs[0]},combats:[]};
// Adopt the existing fixture as current rather than restarting it.
const {candidates}=await import('../src/core/controller.mjs');controller.current=candidates(base)[0];
const combat={id:'fixture-combat',sceneId:'fixture',active:true,started:true,playlist:refs[1],bosses:[]};
await controller.update({...base,combats:[combat]});await delay(500);
const bossState={...base,combats:[{...combat,bosses:[{id:'boss',active:true,priority:1,playlist:refs[0]}]}]};
await controller.update(bossState);
await controller.update({...bossState,overrides:[{id:'manual',playlist:refs[1]}]});
await controller.update(bossState);
await controller.update({...base,combats:[combat]});await controller.update(base);
generation=controller.generation;const restored=await provider.snapshot(ctx());
if(JSON.stringify(restored.value.items)!==JSON.stringify(ambient.value.items) || restored.value.index!==ambient.value.index || Math.abs(restored.value.position-ambient.value.position)>1 || restored.value.state!==ambient.value.state)throw Object.assign(Error(),{code:'restore-mismatch'});
report.checks.push({action:'nested combat/boss/manual unwind',result:'pass'});
controller.generation=generation;
const mutationsBefore=report.mutations;
const results=await Promise.allSettled([controller.update({...base,combats:[combat]}),controller.update({...base,overrides:[{id:'rapid',playlist:refs[1]}]}),controller.update(base)]);
generation=controller.generation;report.checks.push({action:'rapid contexts',settled:results.map(r=>r.status),result:'completed',mutations:report.mutations-mutationsBefore});
if(report.mutations!==mutationsBefore)throw Object.assign(Error(),{code:'duplicate-mutation'});
}
}catch(error){report.error=error.code??'unavailable';}
finally{
if(original && provider){
try{
await provider.restore(original,ctx());await delay(250);const after=await provider.snapshot(ctx());
const fields=v=>JSON.stringify([v.state,v.items,v.index,v.repeat,v.shuffle,v.position]);
report.restored=fields(after.value)===fields(original.value);
if(!report.restored)report.restore_error='state mismatch';
}catch(error){report.restore_error=error.code??'unavailable';}
}
if(!original && report.mutations===0){report.original_unchanged=true;report.restored=null;}
clearInterval(timer);if(gateway&&request)gateway.revoke(request.token);
await writeFile(process.argv.includes('--synthetic')?'evidence/ma-synthetic-playback.json':'evidence/ma-playback.json',JSON.stringify(report,null,2)+'\n');console.log(JSON.stringify(report,null,2));
if(report.error || !report.restored)process.exitCode=1;
}
+23
View File
@@ -0,0 +1,23 @@
// Read-only; original state and identifiers remain in private storage.
import { constants } from 'node:fs';
import { readFile, open } from 'node:fs/promises';
import { MAReadClient } from '../gateway/ma-client.mjs';
import { loadMAToken,loadCatalogKey } from '../gateway/private-config.mjs';
export async function liveClient(syntheticSequences = {}) {
const config=JSON.parse(await readFile('.local/environment.json','utf8'));
const prior=JSON.parse(await readFile('.local/ma-readonly-results.json','utf8'));
if(prior.me.player_filter.length!==1 || prior.player.name!=='Adaptive Music DEV')throw Error('denied');
const catalogKey=await loadCatalogKey('.local');
const client=new MAReadClient({baseUrl:config.ma_url,token:await loadMAToken('.local'),target:prior.me.player_filter[0],
approvedProviders:prior.me.provider_filter,syntheticSequences,catalogKey,campaign:'development',expectedName:'Adaptive Music DEV',expectedProvider:prior.player.provider});
return {client,catalogKey};
}
export async function savePrivate(name,data) {
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.uid!==process.getuid() || (info.mode&0o777)!==0o600)throw Error('denied');await file.truncate(0);await file.writeFile(JSON.stringify(data,null,2)+'\n');await file.sync();}finally{await file.close();}
}
if(process.argv[1]?.endsWith('live_ma_preflight.mjs')) {
try {const {client}=await liveClient();await client.verifyTarget();const q=await client.queueState();const choices=await client.catalog();
console.log(JSON.stringify({isolation_verified:true,state:q.state,items:q.items,shuffle:q.shuffle_enabled,playlists:choices.filter(c=>c.kind==='playlist').length}));
} catch(error){console.log(JSON.stringify({isolation_verified:false,error:error.code??'unavailable',mutations_sent:0}));process.exitCode=1;}
}
+31
View File
@@ -0,0 +1,31 @@
// Local synthetic media benchmark. No real MA account, endpoint, SDK identity or Git host is accessed.
import {chromium} from 'playwright';
import {createServer} from 'node:http';
import {readFile,writeFile} from 'node:fs/promises';
import {resolve,extname} from 'node:path';
const root=process.cwd();const http=createServer(async(req,res)=>{
try{const path=req.url==='/'?'/tests/browser/audio.html':req.url;if(!/^\/(src|vendor|tests\/browser)\//.test(path)||path.includes('..')||path.includes('?'))throw Error();const file=resolve(root,'.'+path);const bytes=await readFile(file);res.writeHead(200,{'Content-Type':extname(file)==='.html'?'text/html':'text/javascript','Cache-Control':'no-store'});res.end(bytes);}catch{res.writeHead(404);res.end();}
});await new Promise(resolve=>http.listen(0,'127.0.0.1',resolve));
let browser;const pages=[],signals=[];
try{
browser=await chromium.launch({headless:true,args:['--no-sandbox']});
for(const [role,id]of [['gm','gm'],['listener','player-a'],['listener','player-b']]){
const context=await browser.newContext();const page=await context.newPage();pages.push(page);
await page.exposeFunction('relay',async(name,frame)=>{signals.push({name,bytes:JSON.stringify(frame).length,keys:Object.keys(frame)});await Promise.all(pages.filter(p=>p!==page).map(p=>p.evaluate(({name,frame})=>window.deliver?.(name,frame),{name,frame})));});
await page.goto(`http://127.0.0.1:${http.address().port}/`);await page.waitForFunction(()=>window.ready);await page.evaluate(({role,id})=>window.configure({role,id}),{role,id});await page.click('#enable');await page.waitForFunction(()=>window.unlocked);
}
const started=Date.now();
for(let i=1;i<pages.length;i++){const invite=await pages[0].evaluate(id=>window.makeInvite(id),i===1?'player-a':'player-b');await pages[i].evaluate(invite=>window.join(invite),invite);}
for(const page of pages.slice(1))await page.waitForFunction(()=>window.measure()?.rms>0.01,{},{timeout:15000});
const firstAudioMs=Date.now()-started;await new Promise(resolve=>setTimeout(resolve,3000));
const measurements=await Promise.all(pages.slice(1).map(p=>p.evaluate(()=>window.measure()))),stats=await pages[0].evaluate(()=>window.stats());
const source=await pages[0].evaluate(()=>({frames:window.decodedFrames,started:window.sourceStarted}));
const seconds=(Date.now()-started)/1000,bytesSent=stats.filter(s=>s.type==='outbound-rtp').reduce((sum,s)=>sum+(s.bytesSent??0),0);
const report={checked_at:new Date().toISOString(),evidence_class:'real Chromium localhost SDK PCM decoder/WebAudio/WebRTC; synthetic input; socket relay shim, not Foundry or MA',browser:await browser.version(),listeners:2,
first_all_listeners_signal_ms:firstAudioMs,observation_seconds:seconds,sdk_decoded_frames:source.frames,listeners_measured:measurements.map(m=>({rms:Number(m.rms.toFixed(5)),peak_hz:m.peakHz})),
gm_rtp_bytes_sent:bytesSent,aggregate_media_kbps:Number((bytesSent*8/seconds/1000).toFixed(2)),signaling_messages:signals.length,max_signal_bytes:Math.max(...signals.map(s=>s.bytes)),
socket_payloads_are_encrypted_control_only:signals.every(s=>s.name==='module.adaptive-music'&&s.keys.sort().join(',')==='cipher,from,iv,peer,seq,session,v'),
turn_used:false,public_network_test:false,ma_handshake_test:false,ma_audio_playback:false,interlistener_skew_measured:false,autoplay_gesture:'actual page click',sandbox_note:'headless browser only used --no-sandbox; not a deployment setting'};
if(measurements.some(m=>m.rms<0.01||Math.abs(m.peakHz-440)>30)||!report.socket_payloads_are_encrypted_control_only)throw Error('audio acceptance failed');
await writeFile('evidence/browser-audio.json',JSON.stringify(report,null,2)+'\n');console.log(JSON.stringify(report,null,2));
}catch(error){for(const page of pages)console.log(JSON.stringify(await page.evaluate(async()=>({diagnostics:await window.diagnostics?.(),decoded:window.decodedFrames,measurement:window.measure?.(),sample:Array.from(window.sampleValue??[]),error:window.lastError,playError:window.lastPlayError})).catch(()=>({}))));throw error;}finally{for(const page of pages)await page.evaluate(()=>window.finish?.()).catch(()=>{});await browser?.close();await new Promise(resolve=>http.close(resolve));}
+49
View File
@@ -0,0 +1,49 @@
"""Build a local development ZIP from an explicit public browser-source allowlist."""
import json
from pathlib import Path
import zipfile
ROOT = Path(__file__).resolve().parents[1]
def build(destination=None):
destination = destination or ROOT / 'dist/adaptive-music-dev.zip'
destination.parent.mkdir(parents=True,exist_ok=True)
names = ['module.json','LICENSE','THIRD-PARTY-NOTICES','README.md','INSTALL.md','CHANGELOG.md','ARCHITECTURE.md','SECURITY.md','TESTING.md','PROGRESS.md']
names += [str(p.relative_to(ROOT)) for p in sorted((ROOT/'src').rglob('*.mjs'))]
names += [str(p.relative_to(ROOT)) for p in sorted((ROOT/'licenses').rglob('*.txt'))]
names += [str(p.relative_to(ROOT)) for p in sorted((ROOT/'styles').glob('*.css'))]
names += [str(p.relative_to(ROOT)) for p in sorted((ROOT/'vendor').glob('*')) if p.is_file()]
manifest=json.loads((ROOT/'module.json').read_text())
if manifest['id']!='adaptive-music' or 'verified' in manifest['compatibility']:
raise ValueError('invalid development manifest')
with zipfile.ZipFile(destination,'w',zipfile.ZIP_DEFLATED) as archive:
for name in names:
path=ROOT/name
if path.is_symlink(): raise ValueError('symlink refused')
data=path.read_bytes()
if name.endswith('.mjs') and (b'node:' in data or b'gateway/' in data):
raise ValueError('server source in browser package')
entry=zipfile.ZipInfo('adaptive-music/'+name,date_time=(2026,12,3,0,0,0))
entry.compress_type=zipfile.ZIP_DEFLATED
entry.external_attr=0o100644<<16
archive.writestr(entry,data)
return destination
def build_companion(destination=None):
destination=destination or ROOT/'dist/adaptive-music-companion-dev.zip'
destination.parent.mkdir(parents=True,exist_ok=True)
names=['LICENSE','THIRD-PARTY-NOTICES','package.json','package-lock.json','src/core/controller.mjs','src/providers/ma/client.mjs','src/providers/ma/provider.mjs','src/providers/ma/webcrypto.mjs']
names += [str(p.relative_to(ROOT)) for p in sorted((ROOT/'gateway').glob('*.mjs'))]
names += ['gateway/README.md','gateway/SETUP.md']
names += [str(p.relative_to(ROOT)) for p in sorted((ROOT/'licenses').rglob('*.txt'))]
with zipfile.ZipFile(destination,'w',zipfile.ZIP_DEFLATED) as archive:
for name in names:
path=ROOT/name
if path.is_symlink(): raise ValueError('symlink refused')
entry=zipfile.ZipInfo('adaptive-music-companion/'+name,date_time=(2026,12,3,0,0,0))
entry.compress_type=zipfile.ZIP_DEFLATED;entry.external_attr=0o100644<<16
archive.writestr(entry,path.read_bytes())
return destination
if __name__=='__main__':
print(build().relative_to(ROOT))
# The optional companion remains source/experimental fallback, not a required release artifact.
+42
View File
@@ -0,0 +1,42 @@
"""Explicitly invoked, read-only unauthenticated diagnostics; raw data stays private."""
import json
from pathlib import Path
import time
import urllib.error
import urllib.request
ROOT = Path(__file__).resolve().parents[1]
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
def probe(base_url: str) -> list[dict]:
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect())
results = []
for path in ('/', '/info'):
start = time.monotonic()
result = {'path': path}
try:
req = urllib.request.Request(base_url.rstrip('/') + path, method='GET')
with opener.open(req, timeout=5) as response:
body = response.read(65536)
result.update(status=response.status,
content_type=response.headers.get('content-type'),
bytes=len(body))
# Deliberately do not log bodies, Location headers, URLs or exception text.
except urllib.error.HTTPError as exc:
result['status'] = exc.code
except (OSError, urllib.error.URLError) as exc:
result.update(error_type=type(exc).__name__,
reason_type=type(getattr(exc, 'reason', None)).__name__)
result['elapsed_seconds'] = round(time.monotonic() - start, 2)
results.append(result)
return results
if __name__ == '__main__':
config = json.loads((ROOT / '.local/environment.json').read_text())
print(json.dumps(probe(config['ma_url']), indent=2))
+160
View File
@@ -0,0 +1,160 @@
"""Offline Foundry/Gitea/GitHub release generation. Never contacts a Git host."""
from __future__ import annotations
import argparse
import hashlib
import ipaddress
import json
from pathlib import Path
import re
import subprocess
import sys
import urllib.parse
import zipfile
ROOT=Path(__file__).resolve().parents[1]
DEFAULT_REPOSITORY='https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music'
ZIP_TIME=(2000,1,1,0,0,0)
if str(ROOT/'scripts') not in sys.path:sys.path.insert(0,str(ROOT/'scripts'))
def public_url(value):
parsed=urllib.parse.urlsplit(value)
if parsed.scheme!='https' or not parsed.hostname or parsed.username or parsed.password or parsed.query or parsed.fragment:
raise ValueError('public HTTPS URL required')
try:
address=ipaddress.ip_address(parsed.hostname)
except ValueError:
if parsed.hostname in ('localhost',) or parsed.hostname.endswith(('.local','.invalid')):raise ValueError('placeholder/local release URL')
else:
if not address.is_global:raise ValueError('private release address')
return value.rstrip('/')
def urls(repository,version,branch='main'):
repository=public_url(repository)
parsed=urllib.parse.urlsplit(repository)
if repository.endswith('.git'):repository=repository[:-4]
if not re.fullmatch(r'[A-Za-z0-9._-]+',branch):raise ValueError('invalid branch')
if not re.fullmatch(r'\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?',version):raise ValueError('invalid release version')
if parsed.hostname=='github.com':
parts=urllib.parse.urlsplit(repository).path.strip('/').split('/')
if len(parts)!=2:raise ValueError('GitHub owner/repo required')
manifest=f'https://raw.githubusercontent.com/{parts[0]}/{parts[1]}/{branch}/module.json'
else:manifest=f'{repository}/raw/branch/{branch}/module.json'
return {'url':repository,'manifest':manifest,'download':f'{repository}/releases/download/v{version}/adaptive-music.zip'}
def release_manifest(repository=DEFAULT_REPOSITORY,version=None,branch='main'):
manifest=json.loads((ROOT/'module.json').read_text())
if version is not None and version!=manifest['version']:raise ValueError('tag/version must match source module.json')
manifest['version']=version or manifest['version'];manifest.update(urls(repository,manifest['version'],branch))
validate_manifest(manifest);return manifest
def validate_manifest(manifest):
if not isinstance(manifest,dict) or any(k not in manifest for k in ('id','authors','compatibility','version','url','manifest','download','esmodules')):raise ValueError('incomplete manifest')
if manifest.get('id')!='adaptive-music' or manifest.get('authors')!=[{'name':'CheddahBoxMB'}]:raise ValueError('module identity mismatch')
if manifest.get('compatibility',{}).get('minimum')!='14' or manifest['compatibility'].get('maximum')!='14' or 'verified' in manifest['compatibility']:raise ValueError('unsupported compatibility claim')
if manifest.get('relationships',{}).get('requires',[]) or manifest.get('systems'):raise ValueError('mandatory system/module dependency')
expected=urls(manifest['url'],manifest['version'])
for key in ('manifest','download'):
public_url(manifest[key])
if manifest[key]!=expected[key]:raise ValueError('manifest/update URL mismatch')
if 'v'+manifest['version'] not in manifest['download']:raise ValueError('unversioned download')
def module_files():
names=['module.json','README.md','INSTALL.md','CHANGELOG.md','ARCHITECTURE.md','SECURITY.md','TESTING.md','PROGRESS.md','LICENSE','THIRD-PARTY-NOTICES']
for directory,pattern in [('src','*.mjs'),('styles','*.css'),('licenses','*'),('vendor','*')]:
names.extend(str(p.relative_to(ROOT)) for p in sorted((ROOT/directory).rglob(pattern)) if p.is_file())
return names
def write_zip(path,entries):
path.parent.mkdir(parents=True,exist_ok=True)
with zipfile.ZipFile(path,'w',zipfile.ZIP_DEFLATED) as archive:
for name,data in sorted(entries.items()):
info=zipfile.ZipInfo(name,ZIP_TIME);info.compress_type=zipfile.ZIP_DEFLATED;info.external_attr=0o100644<<16
archive.writestr(info,data)
def module_entries(manifest):
result={}
for name in module_files():
path=ROOT/name
if path.is_symlink():raise ValueError('package symlink refused')
data=(json.dumps(manifest,indent=2)+'\n').encode() if name=='module.json' else path.read_bytes()
if name.endswith('.mjs') and (b'node:' in data or b"from '../../gateway/" in data):raise ValueError('server code in browser package')
result['adaptive-music/'+name]=data
return result
def validate_package(path,manifest=None):
from audit_repository import findings
with zipfile.ZipFile(path) as archive:
names=archive.namelist()
if len(names)!=len(set(names)) or any(not n.startswith('adaptive-music/') or '..' in Path(n).parts or '/.local/' in n or '/node_modules/' in n or '/gateway/' in n for n in names):raise ValueError('unsafe package inventory')
actual=json.loads(archive.read('adaptive-music/module.json'));validate_manifest(actual)
if manifest and actual!=manifest:raise ValueError('embedded and standalone manifest mismatch')
for name in names:
data=archive.read(name);problems=findings(name,data.decode(errors='replace'))
if problems:raise ValueError('private content in release: '+name)
if name.endswith('.mjs'):
text=data.decode();relative_imports=re.findall(r"(?:from\s*|import\s*\()['\"](\.[^'\"]+)['\"]",text)
import posixpath
for relative in relative_imports:
resolved=posixpath.normpath(posixpath.join(posixpath.dirname(name),relative))
if resolved not in names:raise ValueError('missing browser import: '+resolved)
for asset in actual['esmodules']+actual.get('styles',[]):
if 'adaptive-music/'+asset not in names:raise ValueError('missing manifest asset')
provenance=json.loads(archive.read('adaptive-music/vendor/provenance.json'))
if hashlib.sha256(archive.read('adaptive-music/vendor/sendspin-5.0.0.mjs')).hexdigest()!=provenance['sha256']:raise ValueError('SDK bundle hash mismatch')
required=['licenses/VGM-MIT.txt','licenses/Apache-2.0.txt','licenses/vendor/-sendspin-sendspin-js.txt','licenses/vendor/-noble-ciphers.txt','licenses/vendor/-noble-curves.txt','licenses/vendor/-noble-hashes.txt']
if any('adaptive-music/'+name not in names for name in required):raise ValueError('missing license')
return actual
def local_revision():
try:return subprocess.check_output(['git','rev-parse','HEAD'],cwd=ROOT,text=True,stderr=subprocess.DEVNULL).strip()
except (subprocess.CalledProcessError,FileNotFoundError):
file=ROOT/'SOURCE_REVISION.txt'
return file.read_text().strip() if file.is_file() else 'unknown (source archive without Git metadata)'
def source_entries(manifest):
from audit_repository import findings
try:names=subprocess.check_output(['git','ls-files','-z','--cached','--others','--exclude-standard'],cwd=ROOT,stderr=subprocess.DEVNULL).decode().split('\0')
except (subprocess.CalledProcessError,FileNotFoundError):
names=[p.name for p in ROOT.iterdir() if p.is_file() and p.name in {'.gitignore','AGENTS.md','ARCHITECTURE.md','SECURITY.md','TESTING.md','PROGRESS.md','module.json','package.json','package-lock.json','README.md','INSTALL.md','CHANGELOG.md','ARCHITECTURE.md','SECURITY.md','TESTING.md','PROGRESS.md','LICENSE','THIRD-PARTY-NOTICES','SOURCE_REVISION.txt'}]
for directory in ('src','styles','licenses','vendor','gateway','scripts','tests','evidence','.github','.gitea'):
names.extend(str(p.relative_to(ROOT)) for p in (ROOT/directory).rglob('*') if p.is_file() and '__pycache__' not in p.parts and p.suffix!='.pyc')
entries={}
for name in sorted(set(filter(None,names))):
path=ROOT/name
if name.startswith(('.local/','dist/','node_modules/','.git/')) or path.is_symlink():raise ValueError('private/unsafe source path')
if path.is_file():
data=path.read_bytes()
if findings(name,data.decode(errors='replace')):raise ValueError('private material in source: '+name)
entries['adaptive-music-source/'+name]=data
entries['adaptive-music-source/module.json']=(json.dumps(manifest,indent=2)+'\n').encode()
entries['adaptive-music-source/SOURCE_REVISION.txt']=(local_revision()+'\n').encode()
return entries
def build_release(repository=DEFAULT_REPOSITORY,version=None,output=None):
manifest=release_manifest(repository,version);version=manifest['version'];output=output or ROOT/'dist/releases'/('v'+version)
output=Path(output).resolve()
if output.is_relative_to(ROOT) and not output.is_relative_to(ROOT/'dist'):raise ValueError('in-repository output must be under ignored dist/')
output.mkdir(parents=True,exist_ok=True)
allowed={'adaptive-music.zip','module.json','adaptive-music-source.zip','README.md','INSTALL.md','CHANGELOG.md','ARCHITECTURE.md','SECURITY.md','TESTING.md','PROGRESS.md','LICENSE','THIRD-PARTY-NOTICES','release.json','SHA256SUMS',f'adaptive-music-release-v{version}.zip',f'adaptive-music-release-v{version}.zip.sha256'}
allowed.update(str(p.relative_to(ROOT)) for p in (ROOT/'licenses').rglob('*') if p.is_file())
for file in output.rglob('*'):
if file.is_symlink() or file.is_file() and str(file.relative_to(output)) not in allowed:raise ValueError('unmanaged file in release output')
write_zip(output/'adaptive-music.zip',module_entries(manifest));validate_package(output/'adaptive-music.zip',manifest)
(output/'module.json').write_text(json.dumps(manifest,indent=2)+'\n')
write_zip(output/'adaptive-music-source.zip',source_entries(manifest))
for name in ('README.md','INSTALL.md','CHANGELOG.md','ARCHITECTURE.md','SECURITY.md','TESTING.md','PROGRESS.md','LICENSE','THIRD-PARTY-NOTICES'):(output/name).write_bytes((ROOT/name).read_bytes())
for path in (ROOT/'licenses').rglob('*'):
if path.is_file():target=output/path.relative_to(ROOT);target.parent.mkdir(parents=True,exist_ok=True);target.write_bytes(path.read_bytes())
metadata={'version':version,'repository':manifest['url'],'manifest':manifest['manifest'],'download':manifest['download'],
'sourceCommit':local_revision(),'destinationStatus':'planned; never contacted by this builder','foundryLiveVerified':False,'networkAccessRequired':False}
(output/'release.json').write_text(json.dumps(metadata,indent=2)+'\n')
files={str(p.relative_to(output)):p.read_bytes() for p in output.rglob('*') if p.is_file() and p.name not in ('SHA256SUMS',) and not p.name.startswith('adaptive-music-release-')}
(output/'SHA256SUMS').write_text(''.join(f'{hashlib.sha256(data).hexdigest()} {name}\n' for name,data in sorted(files.items())))
files['SHA256SUMS']=(output/'SHA256SUMS').read_bytes();bundle=output/f'adaptive-music-release-v{version}.zip';write_zip(bundle,files)
(output/(bundle.name+'.sha256')).write_text(hashlib.sha256(bundle.read_bytes()).hexdigest()+' '+bundle.name+'\n')
return bundle
if __name__=='__main__':
parser=argparse.ArgumentParser();parser.add_argument('--repository',default=DEFAULT_REPOSITORY);parser.add_argument('--version');parser.add_argument('--output',type=Path);parser.add_argument('--validate',type=Path);args=parser.parse_args()
if args.validate:validate_package(args.validate);print('PASS: standalone Foundry package, imports, manifest/update URLs, privacy and licenses')
else:print(build_release(args.repository,args.version,args.output))
+92
View File
@@ -0,0 +1,92 @@
"""Generate original quiet tones and optionally serve only them on a private interface.
No MA library, playlist, provider configuration or firewall changes are performed.
"""
from array import array
import argparse
import hashlib
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import ipaddress
import json
import math
import os
from pathlib import Path
import socket
import threading
import wave
from urllib.parse import urlsplit
ROOT=Path(__file__).resolve().parents[1]
FOLDER=ROOT/'.local/synthetic-audio'
def generate():
FOLDER.mkdir(mode=0o700,parents=True,exist_ok=True)
manifest={'license':'MIT; original mathematically generated tones','sample_rate':24000,'channels':2,'duration_seconds':90,'sequences':{}}
for kind,frequencies in [('ambient',[110,165,220]),('combat',[440,660,880])]:
manifest['sequences'][kind]=[]
for number,frequency in enumerate(frequencies,1):
name=f'{kind}-{number}.wav'; path=FOLDER/name
# Gentle fades and low amplitude; no borrowed recordings or samples.
samples=array('h')
for frame in range(24000*90):
envelope=min(1,frame/2400,(24000*90-frame)/2400)
value=round(700*envelope*math.sin(2*math.pi*frequency*frame/24000))
samples.extend((value,value))
import sys
if sys.byteorder!='little': samples.byteswap()
with wave.open(str(path),'wb') as audio:
audio.setparams((2,2,24000,0,'NONE','not compressed'));audio.writeframes(samples.tobytes())
path.chmod(0o600)
manifest['sequences'][kind].append({'file':name,'frequency_hz':frequency,'sha256':hashlib.sha256(path.read_bytes()).hexdigest()})
path=FOLDER/'manifest.json';path.write_text(json.dumps(manifest,indent=2)+'\n');path.chmod(0o600)
return manifest
def serve():
manifest=json.loads((FOLDER/'manifest.json').read_text())
remote=socket.gethostbyname(urlsplit(json.loads((ROOT/'.local/environment.json').read_text())['ma_url']).hostname)
with socket.socket(socket.AF_INET,socket.SOCK_DGRAM) as route:
route.connect((remote,9));address=route.getsockname()[0]
if not ipaddress.ip_address(address).is_private or not ipaddress.ip_address(remote).is_private:
raise ValueError('private interface required')
names={row['file'] for rows in manifest['sequences'].values() for row in rows}
class Handler(BaseHTTPRequestHandler):
def log_message(self,*args): pass
def do_HEAD(self): self.respond(False)
def do_GET(self): self.respond(True)
def respond(self,body):
name=self.path.removeprefix('/')
if self.client_address[0] not in (remote,address) or name not in names:
self.send_error(403);return
path=FOLDER/name;size=path.stat().st_size;start=0;end=size-1
if request_range:=self.headers.get('Range'):
import re
match=re.fullmatch(r'bytes=(\d+)-(\d*)',request_range)
if not match: self.send_error(416);return
start=int(match[1]);end=min(size-1,int(match[2])) if match[2] else size-1
if start>end: self.send_error(416);return
self.send_response(206 if request_range else 200)
self.send_header('Content-Type','audio/wav');self.send_header('Accept-Ranges','bytes')
self.send_header('Content-Length',str(end-start+1));self.send_header('Cache-Control','no-store')
if request_range:self.send_header('Content-Range',f'bytes {start}-{end}/{size}')
self.end_headers()
if body:
try:
with path.open('rb') as audio:
audio.seek(start);remaining=end-start+1
while remaining:
data=audio.read(min(65536,remaining))
if not data: break
self.wfile.write(data);remaining-=len(data)
except (BrokenPipeError,ConnectionResetError): pass
server=ThreadingHTTPServer((address,0),Handler);server.daemon_threads=True
configuration={'base_url':f'http://{address}:{server.server_port}','sequences':{kind:[row['file'] for row in rows] for kind,rows in manifest['sequences'].items()}}
path=ROOT/'.local/fixture-origin.json';path.write_text(json.dumps(configuration));path.chmod(0o600)
timer=threading.Timer(300,server.shutdown);timer.daemon=True;timer.start()
print('Private synthetic fixture origin ready; MA-source IP allowlist; five-minute lifetime.',flush=True)
try:server.serve_forever()
finally:timer.cancel();server.server_close()
if __name__=='__main__':
parser=argparse.ArgumentParser();parser.add_argument('--serve',action='store_true');args=parser.parse_args()
if args.serve:serve()
else:
manifest=generate();print('Generated six original 90-second stereo fixtures in private storage.')
(ROOT/'evidence/synthetic-fixtures.json').write_text(json.dumps(manifest,indent=2)+'\n')
+114
View File
@@ -0,0 +1,114 @@
"""Authorized read-only MA probe. Never print raw responses, secrets or private IDs."""
import datetime
import json
import os
from pathlib import Path
import stat
import subprocess
import urllib.error
import urllib.request
from probe_ma import NoRedirect
ROOT = Path(__file__).resolve().parents[1]
def credential_check():
directory = ROOT / '.local'
path = directory / 'ma-token'
if directory.is_symlink() or path.is_symlink():
raise ValueError('credential symlink refused')
if stat.S_IMODE(directory.stat().st_mode) != 0o700 or stat.S_IMODE(path.stat().st_mode) != 0o600:
raise ValueError('private permissions required')
if path.stat().st_uid != os.getuid() or not path.is_file():
raise ValueError('credential owner/type refused')
token = path.read_bytes().strip()
if not token or b'\n' in token or b'\r' in token:
raise ValueError('invalid credential format')
ignored = subprocess.run(['git','check-ignore','-q','.local/ma-token'], cwd=ROOT).returncode == 0
# Inspect file paths and blob contents across all reachable refs, without logging matches.
objects = subprocess.check_output(['git','rev-list','--objects','--all'], cwd=ROOT).splitlines()
for entry in objects:
oid, _, name = entry.partition(b' ')
if name.startswith(b'.local/'):
raise ValueError('private path in history')
if subprocess.check_output(['git','cat-file','-t',oid], cwd=ROOT).strip() == b'blob':
if token in subprocess.check_output(['git','cat-file','blob',oid], cwd=ROOT):
raise ValueError('credential in history')
for name in subprocess.check_output(['git','ls-files','-z'],cwd=ROOT).split(b'\0'):
if name and token in (ROOT / os.fsdecode(name)).read_bytes():
raise ValueError('credential in tracked working tree')
if not ignored:
raise ValueError('credential not ignored')
return token.decode(), {'directory_mode':'0700','token_mode':'0600','git_ignored':True,
'token_absent_reachable_history':True,'token_absent_tracked_files':True}
def main():
token, safety = credential_check()
base = json.loads((ROOT / '.local/environment.json').read_text())['ma_url']
from urllib.parse import urlsplit
url = urlsplit(base)
if url.scheme not in ('http','https') or url.username or url.password or url.query or url.fragment or url.path not in ('','/'):
raise ValueError('invalid upstream')
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect())
allowed = {'auth/me','auth/scopes','players/get','player_queues/get','music/playlists/library_items','music/radios/library_items'}
def call(command, args=None):
if command not in allowed:
raise ValueError('command refused')
request = urllib.request.Request(base.rstrip('/')+'/api',data=json.dumps({
'message_id':'adaptive-music-read','command':command,'args':args or {}}).encode(),
headers={'Authorization':'Bearer '+token,'Content-Type':'application/json'},method='POST')
try:
with opener.open(request,timeout=10) as response:
data=response.read(1048577)
if len(data)>1048576:
raise ValueError('response limit')
return json.loads(data)
except urllib.error.HTTPError as exc:
return {'probe_http_status':exc.code}
me=call('auth/me')
report={'checked_at':datetime.datetime.now(datetime.timezone.utc).isoformat(), 'credential':safety,
'authentication':me.get('username') == 'adaptive-music' and me.get('enabled') is True}
raw={'me':me}
if report['authentication']:
raw['scopes']=call('auth/scopes')
filters=me.get('player_filter',[]); providers=me.get('provider_filter',[])
report.update(role=me.get('role'), player_filter_count=len(filters),provider_filter_count=len(providers))
if len(filters)==1:
player=call('players/get',{'player_id':filters[0]}); raw['player']=player
report['dedicated_name_matches']=player.get('name')=='Adaptive Music DEV'
report['player_available']=player.get('available')
report['sendspin_provider']=str(player.get('provider','')).startswith('sendspin')
report['standalone_topology']=not any(player.get(k) for k in ('active_group','synced_to','group_members','group_childs','static_group_members'))
if report['dedicated_name_matches']:
queue=call('player_queues/get',{'queue_id':filters[0]}); raw['queue']=queue
report['queue_id_matches_player']=queue.get('queue_id')==filters[0]
report['queue_active']=queue.get('active')
# Negative read uses a nonexistent synthetic ID, never a household player.
negative=call('players/get',{'player_id':'adaptive-music-forbidden-synthetic'})
report['synthetic_target_denial_status']=negative.get('probe_http_status')
if providers:
negative_provider=call('music/playlists/library_items',{'provider':['adaptive-music-forbidden-synthetic'],'limit':1})
report['synthetic_provider_denial_status']=negative_provider.get('probe_http_status') if isinstance(negative_provider,dict) else None
report['role_scopes']=raw['scopes'].get(me.get('role'),[])
for kind in ('playlists','radios'):
items=[]
for offset in range(0,5000,100):
page=call(f'music/{kind}/library_items',{'provider':providers,'limit':100,'offset':offset,'order_by':'name','summary':False})
if not isinstance(page,list):
report[kind+'_error']=True; break
items.extend(page)
if len(page)<100: break
raw[kind]=items; report[kind+'_count']=len(items)
report[kind+'_approved_mappings']=all(any(m.get('provider_instance') in providers and m.get('available') is True for m in i.get('provider_mappings',[])) for i in items)
else:
report['catalog_blocker']='No explicit approved provider filter; catalog reads skipped'
private=ROOT/'.local/ma-readonly-results.json'
fd=os.open(private,os.O_WRONLY|os.O_CREAT|os.O_TRUNC|os.O_NOFOLLOW,0o600)
with os.fdopen(fd,'w') as output: json.dump(raw,output)
(ROOT/'evidence/ma-readonly.json').write_text(json.dumps(report,indent=2)+'\n')
print(json.dumps(report,indent=2))
if __name__=='__main__':
try: main()
except Exception as exc:
print('Read-only probe failed:',type(exc).__name__)
raise SystemExit(1)
+41
View File
@@ -0,0 +1,41 @@
"""Validate local research copies against recorded pins. No network or installation."""
import hashlib
import json
from pathlib import Path
import subprocess
ROOT = Path(__file__).resolve().parents[1]
def verify() -> list[str]:
evidence = json.loads((ROOT / 'evidence/upstream.json').read_text())
errors = []
for source in evidence['git_sources']:
path = ROOT / '.local/upstream' / source['local_directory']
label = source['tag'] + ':' + source['local_directory']
if not (path / '.git').is_dir():
errors.append(f'{label}: missing checkout')
continue
head = subprocess.check_output(['git', '-C', str(path), 'rev-parse', 'HEAD'],
text=True).strip()
if head != source['commit']:
errors.append(f'{label}: commit mismatch')
for name, expected in source['files'].items():
file = path / name
if not file.is_file() or hashlib.sha256(file.read_bytes()).hexdigest() != expected:
errors.append(f'{label}: file mismatch: {name}')
for source in evidence.get('pypi_sources', []):
if not source.get('inspected_files'):
continue
directory = ROOT / '.local/upstream' / source['local_directory']
for name, expected in source['inspected_files'].items():
file = directory / name
if not file.is_file() or hashlib.sha256(file.read_bytes()).hexdigest() != expected:
errors.append(f"{source['version']}: distribution file mismatch: {name}")
return errors
if __name__ == '__main__':
problems = verify()
print('\n'.join(problems) if problems else 'PASS: all recorded Git heads, source and distribution file hashes')
raise SystemExit(bool(problems))
+90
View File
@@ -0,0 +1,90 @@
import {MusicError} from '../core/controller.mjs';
import {MAReadClient} from '../providers/ma/client.mjs';
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);
if(target.username||target.password||target.search||target.hash||target.pathname!=='/'||!['http:','https:'].includes(target.protocol))throw new MusicError('denied');
if(page.protocol==='https:'&&target.protocol!=='https:'&&!['localhost','127.0.0.1','[::1]'].includes(target.hostname))throw new MusicError('mixed-content');
return target;
}
function memoryStorage(values){const map=new Map(Object.entries(values));return {getItem:k=>map.get(k)??null,setItem:(k,v)=>map.set(k,v),removeItem:k=>map.delete(k)};}
export class GMAudioHost{
#authority;#sdk;#core;#context;#destination;#nodes=new Set();#client;#provider;#catalog=[];#session;#live=false;#socket;#generation=-1; #allowed=new Set(); #apiTransport; #gain; #releaseLock;
constructor({authority,pageUrl=globalThis.location?.href,loadSDK=()=>import('../../vendor/sendspin-5.0.0.mjs'),createContext=()=>new AudioContext(),createSocket=url=>new WebSocket(url)}){this.#authority=authority;this.pageUrl=pageUrl;this.loadSDK=loadSDK;this.createContext=createContext;this.createSocket=createSocket;}
get catalog(){return structuredClone(this.#catalog);}
get session(){return this.#session;}
get stream(){return this.#destination?.stream;}
get connected(){return this.#live;}
supports(ref){return this.#live&&this.#allowed.has(ref.id);}
async readCatalog(profile,{reconnecting=false}={}){
if(!this.#authority()||this.#live)throw new MusicError('denied');if(profile.webSocketAuthLogSafe!==true)throw new MusicError('auth-log-review-required');const base=gmAccessPolicy(profile.maUrl,this.pageUrl);
const key=Uint8Array.from(atob(profile.catalogKey),c=>c.charCodeAt(0));if(key.length!==32||profile.targetName!=='Adaptive Music DEV')throw new MusicError('denied');
this.#apiTransport?.close();this.#apiTransport=new GMMAWebSocket({baseUrl:base.origin,token:profile.token,createSocket:this.createSocket});
this.#client=new MAReadClient({baseUrl:base.origin,token:profile.token,target:profile.target,expectedName:profile.targetName,expectedProvider:profile.expectedProvider,approvedProviders:profile.approvedProviders,catalogKey:key,campaign:profile.namespace,syntheticSequences:profile.syntheticSequences??{},fetchImpl:this.#apiTransport.fetch});
await this.#client.verifyTarget({allowUnavailable:reconnecting});this.#catalog=await this.#client.catalog();return this.catalog;
}
async start(profile){
if(!this.#authority()||this.#live)throw new MusicError('denied');
const base=gmAccessPolicy(profile.maUrl,this.pageUrl);
if(profile.targetName!=='Adaptive Music DEV'||typeof profile.target!=='string'||!profile.expectedProvider?.startsWith('sendspin')||!profile.identityStorage?.['sendspin-identity-sk']||!Array.isArray(profile.approvedProviders)||!profile.catalogKey||!profile.namespace)throw new MusicError('profile-required');
// Unlock synchronously in the caller's gesture before SDK/network work.
this.#context=this.createContext();const unlocked=this.#context.resume();this.#destination=this.#context.createMediaStreamDestination();
try{
this.#sdk=await this.loadSDK();await unlocked;
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});
const original=await this.#client.queueState({allowUnavailable:true});
if(original.items!==0||original.state!=='idle')throw new MusicError('reconcile-required');
if(profile.allowSyntheticPlayback===true){
for(const id of Object.keys(profile.syntheticSequences??{})){if(!['synthetic-ambient','synthetic-combat'].includes(id))throw new MusicError('denied');this.#allowed.add(id);}
this.#catalog.push(...[...this.#allowed].map(id=>({provider:'ma',id,kind:'sequence',name:'Generated '+id.slice(10)+' sequence'})));
}
let volumeState=this.#client.targetVolumeState();
this.#socket=await this.#authenticatedSocket(base,profile.token,identity.clientId);
this.#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.#core.onVolumeUpdate=()=>this.#gain.gain.setTargetAtTime(this.#core.muted?0:Math.pow(Math.min(100,Math.max(0,this.#core.volume))/100,1.5),this.#context.currentTime,0.015);
this.#core.onAudioData=chunk=>this.#schedule(chunk);
this.#core.onConnectionClose=()=>{this.#live=false;this.#clear();for(const track of this.#destination?.stream.getTracks()??[])track.stop();};
this.#core.onStreamClear=()=>this.#clear();this.#core.onStreamEnd=()=>this.#clear();
this.#session=crypto.randomUUID();this.#live=true;
this.#provider=new MAPlaybackProvider({client:this.#client,campaign:profile.campaign,session:this.#session,fence:1,snapshotKey:randomKey(),authority:()=>{if(!this.#live||!this.#authority())throw new MusicError('stale');}});
await this.#core.connect();const deadline=Date.now()+10000;while(this.#live&&!this.#core.timeSyncInfo.synced&&Date.now()<deadline)await new Promise(resolve=>setTimeout(resolve,50));if(!this.#live||!this.#core.timeSyncInfo.synced)throw new MusicError('unavailable');await this.#client.verifyTarget();return {clientIdVerified:true,catalog:this.#catalog.length,codecs:['pcm'],remoteAudio:'webrtc',audioMeasured:false,distributedFencing:false};
}catch(error){await this.close();throw new MusicError(error instanceof MusicError?error.code:'unavailable');}
}
#authenticatedSocket(base,token,clientId){
const url=new URL('/sendspin',base);url.protocol=base.protocol==='https:'?'wss:':'ws:';
return new Promise((resolve,reject)=>{const socket=this.createSocket(url.href);socket.binaryType='arraybuffer';const timer=setTimeout(()=>{socket.close();reject(new MusicError('unavailable'));},8000);
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();}};
});
}
#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;}
const lead=(chunk.serverTimeUs-this.#core.getCurrentServerTimeUs())/1000000;
if(!Number.isFinite(lead)||lead>2||lead+frames/chunk.sampleRate<0||this.#nodes.size>=128)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));
}
#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);}
stopOwned(ctx){return this.#ready().stopOwned(ctx);}
async close(){this.#live=false;this.#releaseLock?.();this.#releaseLock=null;this.#clear();this.#core?.disconnect('user_request');this.#socket?.close();this.#core=null;this.#socket=null;this.#provider=null;this.#apiTransport?.close();this.#apiTransport=null;this.#client=null;this.#catalog=[];this.#allowed.clear();for(const track of this.#destination?.stream.getTracks()??[])track.stop();this.#destination=null;const context=this.#context;this.#context=null;if(context&&context.state!=='closed')await context.close();}
}
+79
View File
@@ -0,0 +1,79 @@
import {MusicError} from '../core/controller.mjs';
import {SignalCodec,newAudioInvite} from './signal-codec.mjs';
export function validateIceServers(servers){
if(!Array.isArray(servers)||servers.length>4)throw new MusicError('denied');
for(const server of servers){
const urls=Array.isArray(server.urls)?server.urls:[server.urls];
if(!urls.length||urls.length>4||urls.some(u=>typeof u!=='string'||!/^(stun|stuns|turn|turns):[^\s@]+$/.test(u)))throw new MusicError('denied');
if(urls.some(u=>/^turns?:/.test(u))&&(!server.username||!server.credential||!Number.isFinite(server.expires)||server.expires<=Date.now()||server.expires>Date.now()+3600000))throw new MusicError('denied');
}
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');
}
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;
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();
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;}
invite(userId,{iceServers=[],ttlMs=300000,relayOnly=false}={}){
if(!this.#isGM()||!this.authorized(userId)||!this.#stream||this.#peers.size>=8)throw new MusicError('denied');validateIceServers(iceServers);
const invite=newAudioInvite({session:this.#session,userId,iceServers,ttlMs,relayOnly});this.#entry(invite,'gm');return invite;
}
async listen(invite){
if(this.#isGM()||invite.userId!==this.#userId||this.#peers.size)throw new MusicError('denied');
const entry=this.#entry(invite,'listener');
// Listener sends only a recvonly offer. No microphone or control/data channel.
entry.pc.addTransceiver('audio',{direction:'recvonly'});
await entry.pc.setLocalDescription(await entry.pc.createOffer());await gathered(entry.pc);
await this.#send(entry,{type:'offer',sdp:entry.pc.localDescription.sdp});
}
#entry(invite,role){
const iceServers=validateIceServers(invite.iceServers??[]);
if(invite.relayOnly&&!iceServers.some(s=>(Array.isArray(s.urls)?s.urls:[s.urls]).some(url=>/^turns?:/.test(url))))throw new MusicError('denied');
const codec=new SignalCodec(invite,role); // Validate before allocating a browser connection.
const pc=this.#create({iceServers,iceTransportPolicy:invite.relayOnly?'relay':'all'}),entry={invite:structuredClone(invite),role,pc,codec,tail:Promise.resolve(),restarts:0,pending:0,signals:0};
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);}};
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);}
async #receive(frame){
const entry=this.#peers.get(frame?.peer);if(!entry||frame.session!==entry.invite.session)return;
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);
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');
if(!entry.started){entry.pc.addTrack(this.#stream.getAudioTracks()[0],this.#stream);entry.started=true;}
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});
}else if(entry.role==='listener'&&payload.type==='answer'){
audioOnly(payload.sdp,'offer');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();}
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}))};}
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;}
}
+33
View File
@@ -0,0 +1,33 @@
import {MusicError} from '../core/controller.mjs';
const encode=bytes=>btoa(String.fromCharCode(...bytes)).replace(/\+/g,'-').replace(/\//g,'_').replace(/=+$/,'');
const decode=value=>{if(typeof value!=='string'||!/^[A-Za-z0-9_-]+$/.test(value))throw new MusicError('denied');return Uint8Array.from(atob(value.replace(/-/g,'+').replace(/_/g,'/')),c=>c.charCodeAt(0));};
export function newAudioInvite({session,userId,ttlMs=300000,iceServers=[],relayOnly=false}){
if(!session||!userId||!(ttlMs>0&&ttlMs<=1800000))throw new MusicError('denied');
return {transport:'webrtc-v1',session,peer:crypto.randomUUID(),userId,secret:encode(crypto.getRandomValues(new Uint8Array(32))),expires:Date.now()+ttlMs,relayOnly,iceServers:structuredClone(iceServers)};
}
// Module sockets carry only encrypted SDP/ICE control envelopes, never audio or MA credentials.
export class SignalCodec{
#invite;#key;#sent=0;#received=0;#role;
constructor(invite,role){
if(!invite||invite.transport!=='webrtc-v1'||!['gm','listener'].includes(role)||typeof invite.session!=='string'||typeof invite.peer!=='string'||!Number.isFinite(invite.expires)||invite.expires<=Date.now()||invite.expires>Date.now()+1800000||decode(invite.secret).length!==32)throw new MusicError('denied');
this.#invite=structuredClone(invite);this.#role=role;this.#key=crypto.subtle.importKey('raw',decode(invite.secret),'AES-GCM',false,['encrypt','decrypt']);
}
async seal(payload){
if(Date.now()>=this.#invite.expires||this.#sent>=1000||!['offer','answer','bye'].includes(payload?.type)||Object.keys(payload).some(k=>!['type','sdp'].includes(k))||payload.type!=='bye'&&(typeof payload.sdp!=='string'||payload.sdp.length>65536))throw new MusicError('denied');
const frame={v:1,session:this.#invite.session,peer:this.#invite.peer,from:this.#role,seq:++this.#sent};
const plain=new TextEncoder().encode(JSON.stringify(payload));if(plain.length>65536)throw new MusicError('denied');
const iv=crypto.getRandomValues(new Uint8Array(12)),cipher=await crypto.subtle.encrypt({name:'AES-GCM',iv,additionalData:new TextEncoder().encode(JSON.stringify(frame))},await this.#key,plain);
return {...frame,iv:encode(iv),cipher:encode(new Uint8Array(cipher))};
}
async open(frame){
if(!frame||Object.keys(frame).sort().join(',')!=='cipher,from,iv,peer,seq,session,v'||frame.v!==1||frame.session!==this.#invite.session||frame.peer!==this.#invite.peer||frame.from==this.#role||!['gm','listener'].includes(frame.from)||!Number.isSafeInteger(frame.seq)||frame.seq<=this.#received||frame.seq>1000||typeof frame.cipher!=='string'||frame.cipher.length>88000||Date.now()>=this.#invite.expires)throw new MusicError('denied');
try{
const {iv,cipher,...header}=frame;const nonce=decode(iv);if(nonce.length!==12)throw Error();
const bytes=await crypto.subtle.decrypt({name:'AES-GCM',iv:nonce,additionalData:new TextEncoder().encode(JSON.stringify(header))},await this.#key,decode(cipher));
const payload=JSON.parse(new TextDecoder().decode(bytes));
if(!['offer','answer','bye'].includes(payload?.type)||Object.keys(payload).some(k=>!['type','sdp'].includes(k))||payload.type!=='bye'&&(typeof payload.sdp!=='string'||payload.sdp.length>65536))throw Error();
if(Date.now()>=this.#invite.expires||frame.seq<=this.#received)throw Error();
this.#received=frame.seq;return payload;
}catch{throw new MusicError('denied');}
}
}
+82
View File
@@ -0,0 +1,82 @@
// Independent implementation informed by VGM release-1.4.5; see THIRD-PARTY-NOTICES.
export class MusicError extends Error {
constructor(code) { super(code); this.code = code; }
}
export function candidates(state) {
const scene = state.scene;
const combats = (state.combats ?? []).filter(c => c.active && c.started && c.sceneId === scene?.id);
const bosses = combats.flatMap(c => c.bosses ?? []).filter(b => b.active && b.playlist)
.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0) || a.id.localeCompare(b.id));
const make = (key, playlist) => ({ key, playlist: playlist ?? null });
return [
...(state.overrides ?? []).slice().reverse().map(o => make(`manual:${o.id}`, o.playlist)),
...bosses.map(b => make(`boss:${scene.id}:${b.id}`, b.playlist)),
...combats.filter(c => c.playlist).sort((a,b) => a.id.localeCompare(b.id))
.map(c => make(`combat:${scene.id}:${c.id}`, c.playlist)),
...(scene?.playlist ? [make(`scene:${scene.id}`, scene.playlist)] : []),
make('default', state.defaultPlaylist)
].map(i => ({ ...i, key: `${i.key}:${JSON.stringify(i.playlist)}` }));
}
export class MusicController {
constructor({ campaign, session, providers, authority, maxFrames = 16 }) {
Object.assign(this, { campaign, session, providers, authority, maxFrames });
this.dirty = new Set();
this.generation = 0; this.frames = []; this.current = null; this.tail = Promise.resolve();
}
update(state) {
const input = structuredClone(state);
const generation = ++this.generation;
this.abort?.abort(); this.abort = new AbortController();
const context = { campaign: this.campaign, session: this.session, generation,
signal: this.abort.signal, check: () => {
if (generation !== this.generation || !this.authority()) throw new MusicError('stale');
} };
const task = this.tail.catch(() => {}).then(() => this.transition(input, context));
this.tail = task; return task;
}
async transition(state, ctx) {
ctx.check();
const choices = candidates(state), next = choices[0];
const valid = new Set(choices.map(i => i.key));
this.frames = this.frames.filter(f => valid.has(f.intent.key));
if (this.current?.key === next.key) return { unchanged: true };
const provider = next.playlist && this.providers[next.playlist.provider];
if (next.playlist && !provider) throw new MusicError('unsupported');
const prepared = provider ? await provider.resolve(next.playlist, ctx) : null;
ctx.check();
const old = this.current, outgoing = old?.playlist && this.providers[old.playlist.provider];
const snapshot = outgoing ? await outgoing.snapshot(ctx) : null;
ctx.check();
const frame = this.frames.findLast(f => f.intent.key === next.key);
if (old && snapshot && valid.has(old.key)) {
this.frames = this.frames.filter(f => f.intent.key !== old.key);
this.frames.push({ intent: old, snapshot });
this.frames = this.frames.slice(-this.maxFrames);
}
const cleanup = new Set([...this.dirty, outgoing].filter(Boolean));
for (const p of [outgoing, provider]) if (p) this.dirty.add(p);
try {
for (const p of cleanup) { ctx.check(); await p.stopOwned(ctx); }
ctx.check();
if (provider) {
if (frame) await provider.restore(frame.snapshot, ctx);
else await provider.apply(prepared, ctx);
}
ctx.check();
} catch (error) {
// Never restore an obsolete transition. Reconciliation is explicit after stale writes.
this.current = null;
if (error.code !== 'stale') {
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; }
this.dirty.clear();
}
throw error;
}
this.frames = this.frames.filter(f => f.intent.key !== next.key).slice(-this.maxFrames);
this.dirty.clear();
this.current = next;
return { intent: next, restored: Boolean(frame) };
}
}
+21
View File
@@ -0,0 +1,21 @@
import { MusicError } from './controller.mjs';
export const musicFields = ['ambient','combat','boss','fallback'];
export const referenceKey = ref => ref ? JSON.stringify([ref.provider,ref.id]) : '';
export function selection(value, choices, {nativeOnly=false}={}) {
if(value==='')return null;
const choice=choices.find(c=>referenceKey(c)===value && ['native','ma'].includes(c.provider) && typeof c.id==='string' && c.id.length<=256);
if(!choice || nativeOnly && choice.provider!=='native')throw new MusicError('denied');
return {provider:choice.provider,id:choice.id};
}
// Single music layer: ambient is the base queue interrupted by combat/boss/manual.
// These assignments do not address Foundry AmbientSound or sound effects.
export function buildMusicState({scene,combats=[],defaults={},overrides=[],choose=ref=>ref}) {
const config=scene?.music??{};
const ambient=(Object.hasOwn(config,'ambient')?config.ambient:config.playlist)??defaults.ambient??null;
const fallback=config.fallback??defaults.fallback??null;
const selected=ref=>ref ? choose(ref,fallback) : null;
return {scene:scene && {id:scene.id,playlist:selected(ambient)},defaultPlaylist:scene ? null : selected(defaults.ambient),
overrides:overrides.map(o=>({...o,playlist:selected(o.playlist)})),
combats:combats.map(c=>({...c,playlist:selected(c.playlist??config.combat??defaults.combat),
bosses:(c.bosses??[]).map(b=>({...b,playlist:selected(b.playlist??config.boss??defaults.boss)}))}))};
}
+67
View File
@@ -0,0 +1,67 @@
import {mountMusicAssignments} from './music-editor.mjs';
import { MusicError } from '../core/controller.mjs';
const namespace = 'adaptive-music';
const key = ref => JSON.stringify([ref?.provider, ref?.id]);
function validChoice(choice) {
return choice && ['native','ma'].includes(choice.provider) && typeof choice.id === 'string' &&
choice.id.length > 0 && choice.id.length <= 256 && typeof choice.name === 'string';
}
// Pass only owned native playlists and controller-authorized MA catalog choices.
// No gateway credential, endpoint or upstream URI belongs in this interface.
export async function savePlaylistConfiguration({ document, game, choices, selected }) {
if (!game.user?.isGM) throw new MusicError('denied');
const choice = selected === '' ? null : choices.find(c => validChoice(c) && key(c) === selected);
if (selected !== '' && !choice) throw new MusicError('denied');
const previous = document.getFlag(namespace, 'music') ?? {};
await document.setFlag(namespace, 'music', { ...previous,
playlist: choice ? { provider: choice.provider, id: choice.id } : null });
}
export function mountPlaylistConfiguration({ document, game, container, choices, onError = () => {} }) {
if (!game.user?.isGM || container.querySelector('[data-adaptive-music]')) return null;
if(document.documentName==='Scene')return mountMusicAssignments({document,game,container,choices,onError});
const dom = container.ownerDocument;
const panel = dom.createElement('fieldset'); panel.dataset.adaptiveMusic = 'configuration';
const legend = dom.createElement('legend'); legend.textContent = 'Adaptive Music'; panel.append(legend);
const label = dom.createElement('label'); label.append(dom.createTextNode('Music playlist '));
const select = dom.createElement('select'); label.append(select); panel.append(label);
const available = choices.filter(validChoice).map(c => ({provider:c.provider,id:c.id,name:c.name}));
const add = (value, text) => { const option = dom.createElement('option'); option.value = value; option.textContent = text; select.append(option); };
add('', 'Use the next applicable music rule');
for (const choice of available) add(key(choice), `${choice.provider === 'ma' ? 'Music Assistant' : 'Foundry'}: ${choice.name}`);
const current = document.getFlag(namespace, 'music')?.playlist;
if (current && !available.some(c => key(c) === key(current))) add(key(current), 'Previously selected playlist is unavailable');
select.value = current ? key(current) : '';
const note = dom.createElement('p'); note.textContent = 'Music Assistant playback requires a separately configured gateway; this development module uses Foundry playlists.'; panel.append(note);
const status = dom.createElement('p'); status.setAttribute('role','status'); panel.append(status);
const save = dom.createElement('button'); save.type = 'button'; save.textContent = 'Save music playlist'; panel.append(save);
let saving = false;
save.addEventListener('click', async () => {
if (saving) return;
saving = true; save.disabled = true;
try {
await savePlaylistConfiguration({document,game,choices:available,selected:select.value});
status.textContent = 'Music playlist saved.';
} catch (error) { status.textContent = 'Music playlist could not be saved.'; onError(new MusicError(error instanceof MusicError ? error.code : 'unavailable')); }
finally { saving = false; save.disabled = false; }
});
container.append(panel); return panel;
}
// Explicit development-only UI bootstrap. Importing this file registers nothing.
export function startConfigurationInterfaces({ game, Hooks, getChoices, onError = () => {} }) {
let disposed = false;
const panels = new Set();
const render = async (app, html) => {
if (!game.user?.isGM) return;
const container = html?.querySelector ? html : html?.[0];
const document = app.document;
if (!document || !container) return;
try {
const choices = await getChoices();
if (disposed) return;
const panel = mountPlaylistConfiguration({document,game,container,choices,onError});
if (panel) panels.add(panel);
} catch { onError(new MusicError('unavailable')); }
};
const hooks = ['renderSceneConfig','renderCombatConfig'].map(event => [event,Hooks.on(event, render)]);
return { dispose() { disposed = true; for (const [event,id] of hooks) Hooks.off(event,id); for (const panel of panels) panel.remove(); panels.clear(); } };
}
+34
View File
@@ -0,0 +1,34 @@
import {MusicError} from '../core/controller.mjs';
// Gateway-terminated PCM test transport, NOT a Sendspin pass-through client.
export class ListenerAudio {
#context; #abort; #nodes=new Set(); #fetch;
constructor({fetchImpl=globalThis.fetch,createContext=()=>new AudioContext()}={}){this.#fetch=fetchImpl;this.createContext=createContext;}
async start(request){
const stopped=this.stop();const context=this.createContext();this.#context=context;
// Called directly from Enable Audio; retain the autoplay gesture before network work.
const resumed=context.resume();await stopped;await resumed;if(this.#context!==context)throw new MusicError('stale');const abort=new AbortController();this.#abort=abort;
try{
const response=await this.#fetch(request.url,{...request.options,signal:abort.signal});
if(!response.ok||response.headers.get('X-Audio-Format')!=='pcm16le;rate=24000;channels=2')throw new MusicError('denied');
const reader=response.body.getReader();let pending=new Uint8Array(),next=context.currentTime+0.06;
try{
while(true){const {value,done}=await reader.read();if(done)break;
if(value.length>65536)throw new MusicError('unavailable');
const bytes=new Uint8Array(pending.length+value.length);bytes.set(pending);bytes.set(value,pending.length);let offset=0;
while(offset+1920<=bytes.length){
if(this.#abort!==abort)throw new MusicError('stale');
if(next<context.currentTime)next=context.currentTime+0.02;
if(next-context.currentTime>0.25)throw new MusicError('unavailable');
const buffer=context.createBuffer(2,480,24000),view=new DataView(bytes.buffer,bytes.byteOffset+offset,1920);
for(let sample=0;sample<480;sample++)for(let channel=0;channel<2;channel++)buffer.getChannelData(channel)[sample]=view.getInt16((sample*2+channel)*2,true)/32768;
const node=context.createBufferSource();node.buffer=buffer;node.connect(context.destination);this.#nodes.add(node);node.onended=()=>this.#nodes.delete(node);node.start(next);next+=0.02;offset+=1920;
}
pending=bytes.slice(offset);
}
if(pending.length)throw new MusicError('unavailable');
}finally{await reader.cancel().catch(()=>{});reader.releaseLock();}
}catch(error){if(!abort.signal.aborted)throw new MusicError(error instanceof MusicError?error.code:'unavailable');}
finally{if(this.#abort===abort)await this.stop();}
}
async stop(){this.#abort?.abort();this.#abort=null;for(const node of this.#nodes){try{node.stop();}catch{}}this.#nodes.clear();const context=this.#context;this.#context=null;if(context)await context.close();}
}
+61
View File
@@ -0,0 +1,61 @@
import {startNativeRuntime,primaryGM} from './runtime.mjs';
import {startConfigurationInterfaces,mountPlaylistConfiguration} from './configuration.mjs';
import {GatewayClient} from '../providers/ma/remote.mjs';
import {GMAudioHost} from '../audio/gm-host.mjs';
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=[];
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:gateway?.catalog??[])];
const onError=()=>ui.notifications.warn('Adaptive Music could not complete the operation. Open Adaptive Music setup for connection diagnostics and ownership checks.');
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});
runtime.refresh().catch(onError);
}
function stop(){runtime?.dispose();runtime=null;}
function setOverrides(value){if(!runtime)throw Error('Automation is disabled');return runtime.setOverrides(value);}
function listenWebRTC(invite){
if(game.user.isGM||!peers)throw Error('Listener only');
if(!remoteAudio){remoteAudio=document.createElement('audio');document.body.append(remoteAudio);}
remoteAudio.play().catch(()=>{});return peers.listen(invite);
}
function stopWebRTC(){peers?.reset();remoteAudio?.pause();if(remoteAudio)remoteAudio.srcObject=null;}
Hooks.once('init',()=>{
game.settings.register(id,'enabled',{name:'Enable music automation',hint:'Configure through Adaptive Music setup. Defaults off.',scope:'world',config:false,type:Boolean,default:false});
game.settings.register(id,'ownedPlaylistIds',{scope:'world',config:false,type:String,default:'',requiresReload:true});
game.settings.register(id,'musicDefaults',{scope:'world',config:false,type:Object,default:{}});
if(game.settings.registerMenu){
// The factory reads live module state when the settings menu is rendered.
const Setup=createSetupClass({game,gateway:{get status(){return gateway?.status;},connect:async code=>{if(gmHost?.connected)throw Error('Disconnect GM host first');const result=await gateway.connect(code);await runtime?.refresh();return result;},refresh:()=>gateway.refresh(),disconnect:()=>gateway.disconnect(),audioRequest:code=>gateway.audioRequest(code)},
audio:{start:request=>audio.start(request),stop:()=>audio.stop()},getChoices:choices,start,stop,setOverrides,onError,canConnect:()=>!gmHost?.connected&&primaryGM(game.users)===game.user.id});
const Listener=createListenerClass({game,gateway:{audioRequest:code=>gateway.audioRequest(code)},audio:{start:request=>audio.start(request),stop:()=>audio.stop()},listenWebRTC,stopWebRTC,onError});
game.settings.registerMenu(id,'listen',{name:'Campaign audio (development)',label:'Enable Audio',hint:'Private WebRTC invitation, or optional companion synthetic test.',icon:'fas fa-headphones',type:Listener,restricted:false});
game.settings.registerMenu(id,'setup',{name:'Adaptive Music setup',label:'Configure music',hint:'Native ownership, world/scene assignments, boss overrides, gateway and audio diagnostics.',icon:'fas fa-music',type:Setup,restricted:true});
}
});
Hooks.once('ready',()=>{
gmHost=new GMAudioHost({authority:gmAuthority});
if(game.socket){peers=new PeerAudio({socket:game.socket,userId:game.user.id,isGM:gmAuthority,isAuthorizedUser:id=>{const user=game.users.get(id);return user?.active&&!user.isGM&&!user.isBanned;},onError,onStream:stream=>{if(!remoteAudio){remoteAudio=document.createElement('audio');remoteAudio.autoplay=true;document.body.append(remoteAudio);}remoteAudio.srcObject=stream;remoteAudio.play().catch(onError);}});game.socket.on('disconnect',()=>{stop();gmHost.close();peers.reset();remoteAudio?.pause();});}
if(game.socket)authorityHooks=['updateUser','deleteUser'].map(event=>[event,Hooks.on(event,()=>{peers.reconcile();if(gmHost.connected&&!gmAuthority()){stop();gmHost.close();peers.reset();remoteAudio?.pause();}})]);
gateway=new GatewayClient({origin:globalThis.location?.origin??'http://localhost'});audio=new ListenerAudio();
if(game.user.isGM){interfaces=startConfigurationInterfaces({game,Hooks,getChoices:choices,onError});renewTimer=setInterval(()=>{if(gateway.connected&&primaryGM(game.users)===game.user.id)gateway.renew().catch(onError);},10000);}
game.modules.get(id).api={
startDevelopment:start,stopDevelopment:stop,setOverrides,
async connectGateway(code){if(!game.user.isGM||primaryGM(game.users)!==game.user.id||gmHost?.connected)throw Error('Controller unavailable');const result=await gateway.connect(code);await runtime?.refresh();return result;},
gatewayDiagnostics:()=>gateway.status,
async readGMCatalog(profile){if(runtime||gateway.connected)throw Error('Stop automation and disconnect optional companion first');return gmHost.readCatalog({...profile,campaign:game.world.id});},
async startGMHost(profile){if(runtime||gateway.connected)throw Error('Stop automation and disconnect optional companion first');const result=await gmHost.start({...profile,campaign:game.world.id});peers.setSource(gmHost.stream);return result;},
inviteListener:(userId,options)=>peers.invite(userId,options),
listenWebRTC,
peerStats:()=>peers.stats(),
async closeGMHost(){stop();peers?.reset();await gmHost.close();},
async mountConfiguration(document,container){return mountPlaylistConfiguration({document,container,game,choices:await choices(),onError});},
enableAudio(code){return audio.start(gateway.audioRequest(code));},stopAudio:()=>audio.stop(),
dispose(){stop();for(const [event,hook]of authorityHooks)Hooks.off(event,hook);authorityHooks=[];interfaces?.dispose();clearInterval(renewTimer);gateway.disconnect();audio.stop();gmHost?.close();peers?.close();remoteAudio?.pause();remoteAudio?.remove();interfaces=null;}
};
if(game.settings.get(id,'enabled'))start();
});
+48
View File
@@ -0,0 +1,48 @@
import {MusicError} from '../core/controller.mjs';
import {musicFields,referenceKey,selection} from '../core/scene-music.mjs';
const namespace='adaptive-music';
export async function saveMusicAssignments({document,game,choices,values,defaults=false}){
if(!game.user?.isGM||Object.keys(values).some(k=>!musicFields.includes(k)))throw new MusicError('denied');
const previous=defaults?game.settings.get(namespace,'musicDefaults')??{}:document.getFlag(namespace,'music')??{};
const result={...previous};
for(const field of musicFields){
if(!Object.hasOwn(values,field))continue;
// Keep an unchanged offline catalog selection; never permit a forged new one.
if(values[field]===referenceKey(previous[field]) && previous[field]){if(field==='fallback'&&previous[field].provider!=='native')throw new MusicError('denied');result[field]={provider:previous[field].provider,id:previous[field].id};continue;}
result[field]=selection(values[field],choices,{nativeOnly:field==='fallback'});
}
if(defaults)await game.settings.set(namespace,'musicDefaults',result);else await document.setFlag(namespace,'music',result);
}
export function musicSelect(dom,choices,current,{nativeOnly=false,empty='Use world default / silence'}={}){
const select=dom.createElement('select');
const add=(value,text)=>{const option=dom.createElement('option');option.value=value;option.textContent=text;select.append(option);};
add('',empty);
for(const c of choices.filter(c=>!nativeOnly||c.provider==='native'))add(referenceKey(c),`${c.provider==='ma'?'MA':'Foundry'}: ${c.name}`);
if(current&&!choices.some(c=>referenceKey(c)===referenceKey(current)))add(referenceKey(current),'Saved selection (catalog unavailable)');
select.value=referenceKey(current);return select;
}
export function mountMusicAssignments({document,game,container,choices,defaults=false,onError=()=>{}}){
if(!game.user?.isGM)return null;
const dom=container.ownerDocument,panel=dom.createElement('fieldset');panel.dataset.adaptiveMusic='assignments';
const legend=dom.createElement('legend');legend.textContent=defaults?'World music defaults':'Scene music';panel.append(legend);
const previous=defaults?game.settings.get(namespace,'musicDefaults')??{}:document.getFlag(namespace,'music')??{};
const labels={ambient:'Ambient music (base queue)',combat:'Combat music',boss:'Default boss music',fallback:'Native fallback when MA is unavailable'};
const controls={};
for(const field of musicFields){const label=dom.createElement('label');label.textContent=labels[field]+' ';const current=previous[field]??(field==='ambient'?previous.playlist:null);controls[field]=musicSelect(dom,choices,current,{nativeOnly:field==='fallback',empty:defaults?(field==='fallback'?'No native fallback':'No world default'):'Use world default / silence'});label.append(controls[field]);panel.append(label);}
const note=dom.createElement('p');note.textContent='One music layer: combat interrupts ambient music. Concurrent ambient layers and crossfade are not implemented. Native AmbientSound and effects remain separate.';panel.append(note);
const status=dom.createElement('p');status.setAttribute('role','status');panel.append(status);
const button=dom.createElement('button');button.type='button';button.textContent='Save assignments';panel.append(button);
button.addEventListener('click',async()=>{button.disabled=true;try{await saveMusicAssignments({document,game,choices,defaults,values:Object.fromEntries(musicFields.map(k=>[k,controls[k].value]))});status.textContent='Assignments saved.';}catch{status.textContent='Assignments could not be saved.';onError(new MusicError('denied'));}finally{button.disabled=false;}});
container.append(panel);return panel;
}
export function mountBossEditor({document,game,container,choices,onError=()=>{}}){
if(!game.user?.isGM)return null;
const dom=container.ownerDocument,panel=dom.createElement('fieldset'),flag=document.getFlag(namespace,'music')??{};
const label=dom.createElement('label');label.textContent='Boss override ';const enabled=dom.createElement('input');enabled.type='checkbox';enabled.checked=flag.boss===true;label.append(enabled);panel.append(label);
const priority=dom.createElement('input');priority.type='number';priority.value=String(flag.priority??0);priority.setAttribute('aria-label','Boss priority');panel.append(priority);
const inactive=dom.createElement('input');inactive.type='checkbox';inactive.checked=flag.inactive===true;const inactiveLabel=dom.createElement('label');inactiveLabel.textContent='Boss inactive ';inactiveLabel.append(inactive);panel.append(inactiveLabel);
const select=musicSelect(dom,choices,flag.playlist,{empty:'Use scene / world boss music'});select.setAttribute('aria-label','Boss playlist');panel.append(select);
const save=dom.createElement('button');save.type='button';save.textContent='Save boss override';panel.append(save);
save.addEventListener('click',async()=>{try{if(!game.user.isGM||!Number.isFinite(Number(priority.value)))throw new MusicError('denied');const previous=document.getFlag(namespace,'music')??{};const playlist=select.value===referenceKey(previous.playlist)?previous.playlist??null:selection(select.value,choices);await document.setFlag(namespace,'music',{...previous,boss:enabled.checked,inactive:inactive.checked,priority:Number(priority.value),playlist});}catch{onError(new MusicError('denied'));}});
container.append(panel);return panel;
}
+35
View File
@@ -0,0 +1,35 @@
import { MusicController } from '../core/controller.mjs';
import { buildMusicState } from '../core/scene-music.mjs';
import { NativeProvider } from '../providers/native/provider.mjs';
export const primaryGM = users => [...users].filter(u => u.active && u.isGM)
.sort((a,b) => a.id.localeCompare(b.id))[0]?.id;
// Explicit development bootstrap. No hooks or document mutations occur on import.
// All music configuration uses module-owned flags; no actor/system schema access.
export function startNativeRuntime({ game, Hooks, campaign, session, ownedPlaylistIds, maProvider, onError = () => {} }) {
const flag = d => d?.getFlag('adaptive-music', 'music');
const provider = new NativeProvider({ playlists: game.playlists, ownedPlaylistIds, campaign, session,
sceneConflict: id => [...game.scenes].some(s => s.active && (s.playlist?.id ?? s.playlist) === id) });
const controller = new MusicController({ campaign, session, providers: { native: provider,...(maProvider?{ma:maProvider}:{}) },
authority: () => game.ready && primaryGM(game.users) === game.user.id });
let overrides = [];
const refresh = () => {
if (!game.ready || primaryGM(game.users) !== game.user.id) return Promise.resolve();
const scene = [...game.scenes].find(s => s.active);
const defaults=game.settings.get('adaptive-music','musicDefaults')??{};
const choose=(ref,fallback)=>ref?.provider==='ma'&&!maProvider?.supports(ref)?fallback??null:ref;
const state=buildMusicState({scene:scene&&{id:scene.id,music:flag(scene)},
defaults:{...defaults,ambient:Object.hasOwn(defaults,'ambient')?defaults.ambient:game.settings.get('adaptive-music','defaultPlaylist')},overrides,choose,
combats:[...game.combats].map(c=>({id:c.id,sceneId:c.scene?.id??c.scene,active:c.active,started:c.started,playlist:flag(c)?.playlist,
bosses:[...c.combatants].map(b=>{const f=flag(b)??flag(b.token)??{};return {id:b.id,active:f.boss===true&&f.inactive!==true,priority:Number.isFinite(f.priority)?f.priority:0,playlist:f.playlist};})}))});
return controller.update(state);
};
if(!game.settings.settings?.has('adaptive-music.defaultPlaylist'))game.settings.register('adaptive-music', 'defaultPlaylist', { scope: 'world', config: false, type: Object, default: null });
const events = ['updateScene', 'createCombat', 'updateCombat', 'deleteCombat', 'createCombatant',
'updateCombatant', 'deleteCombatant', 'updateToken', 'updateSetting', 'updateUser', 'deletePlaylist', 'deletePlaylistSound'];
const subscriptions = events.map(event => [event, Hooks.on(event, () => refresh().catch(onError))]);
return { controller, refresh,
setOverrides: value => { overrides = structuredClone(value); return refresh(); },
dispose: () => { for (const [event,id] of subscriptions) Hooks.off(event,id); controller.generation++; controller.abort?.abort(); }
};
}
+66
View File
@@ -0,0 +1,66 @@
import {MusicError} from '../core/controller.mjs';
import {selection} from '../core/scene-music.mjs';
import {mountMusicAssignments,mountBossEditor,musicSelect} from './music-editor.mjs';
export function createSetupClass({game,gateway,audio,getChoices,start,stop,setOverrides,onError,canConnect=()=>true,Base=globalThis.foundry.applications.api.ApplicationV2}){
return class AdaptiveMusicSetup extends Base {
static DEFAULT_OPTIONS={id:'adaptive-music-setup',window:{title:'Adaptive Music setup'},position:{width:640,height:'auto'}};
async _renderHTML(){
if(!game.user.isGM)throw new MusicError('denied');
const dom=globalThis.document,root=dom.createElement('div');root.className='adaptive-music-setup';
const text=value=>{const p=dom.createElement('p');p.textContent=value;root.append(p);return p;};
const status=text('Automation is opt-in. Configure dedicated music playlists and assignments before enabling it.');status.setAttribute('role','status');
const button=(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 new MusicError('denied');await action();}catch(e){status.textContent=e?.code==='denied'?'Connection or selection denied. Check capability role/expiry, active GM, and native ownership.':e?.code==='stale'?'Controller lease changed. Reconnect with a fresh connection code.':'Gateway unavailable. Check the private same-origin route, TLS, companion process and target diagnostics. Native configuration can be used offline.';onError(e);}finally{b.disabled=false;}});root.append(b);return b;};
const owned=new Set(game.settings.get('adaptive-music','ownedPlaylistIds').split(',').filter(Boolean));
const boxes=[];const ownedPanel=dom.createElement('fieldset');const legend=dom.createElement('legend');legend.textContent='Dedicated native music playlists';ownedPanel.append(legend);
for(const playlist of game.playlists){const label=dom.createElement('label'),input=dom.createElement('input');input.type='checkbox';input.checked=owned.has(playlist.id);label.textContent=playlist.name+' ';label.append(input);ownedPanel.append(label);boxes.push({id:playlist.id,input});}root.append(ownedPanel);
text('Opt in only dedicated music playlists. Do not select AmbientSound, effects or shared playlists. Saving ownership disables automation and requires a reload.');
button('Save native ownership',async()=>{stop();await game.settings.set('adaptive-music','enabled',false);await game.settings.set('adaptive-music','ownedPlaylistIds',boxes.filter(b=>b.input.checked).map(b=>b.id).join(','));status.textContent='Ownership saved. Reload this world before enabling automation.';});
const codeLabel=dom.createElement('label');codeLabel.textContent='Optional companion controller code (memory only; never an MA token) ';const code=dom.createElement('input');code.type='password';code.autocomplete='off';codeLabel.append(code);root.append(codeLabel);
text('Native playback requires no companion. The optional companion uses a private same-origin route. The module-only GM-host API uses private GM-local authentication; see INSTALL.md. Never share MA credentials with listeners.');
const diagnostics=text('Gateway disconnected. Owned native playlists work without it.');
const assignmentRoot=dom.createElement('div');
const show=()=>{const d=gateway.status;diagnostics.textContent=d?`Target: ${d.target}. Playback authorization: ${d.playbackEnabled?'enabled for approved test IDs':'disabled'}. Audio: ${d.audioSource} (test transport only). Sendspin receiver: unavailable. Crossfade: unavailable.`:'Gateway disconnected. Owned native fallback is available.';};
button('Connect and load MA catalog',async()=>{if(!canConnect())throw new MusicError('denied');const value=code.value;code.value='';await gateway.connect(value);show();await renderAssignments();});
button('Refresh connection diagnostics',async()=>{await gateway.refresh();show();await renderAssignments();});
button('Disconnect gateway',async()=>{await gateway.disconnect();show();status.textContent='Gateway disconnected. Existing MA playback, if any, is retained; automatic fallback cannot bypass an unreachable owned target.';});
const renderAssignments=async()=>{
assignmentRoot.replaceChildren();const choices=await getChoices();
mountMusicAssignments({game,container:assignmentRoot,choices,defaults:true,onError});
const sceneLabel=dom.createElement('label');sceneLabel.textContent='Scene ';const scenes=dom.createElement('select');
for(const scene of game.scenes){const option=dom.createElement('option');option.value=scene.id;option.textContent=scene.name;scenes.append(option);}sceneLabel.append(scenes);assignmentRoot.append(sceneLabel);
const scenePanel=dom.createElement('div');assignmentRoot.append(scenePanel);
const showScene=()=>{scenePanel.replaceChildren();const scene=game.scenes.get(scenes.value);if(scene)mountMusicAssignments({document:scene,game,container:scenePanel,choices,onError});};
const active=[...game.scenes].find(s=>s.active);if(active)scenes.value=active.id;scenes.addEventListener('change',showScene);showScene();
const bossLabel=dom.createElement('label');bossLabel.textContent='Boss combatant ';const bosses=dom.createElement('select'),documents=new Map();
for(const combat of game.combats)for(const combatant of combat.combatants){const option=dom.createElement('option');option.value=combat.id+':'+combatant.id;option.textContent=combatant.name??combatant.id;documents.set(option.value,combatant);bosses.append(option);}bossLabel.append(bosses);assignmentRoot.append(bossLabel);
const bossPanel=dom.createElement('div');assignmentRoot.append(bossPanel);const showBoss=()=>{bossPanel.replaceChildren();const document=documents.get(bosses.value);if(document)mountBossEditor({document,game,container:bossPanel,choices,onError});};bosses.addEventListener('change',showBoss);showBoss();
const manual=musicSelect(dom,choices,null,{empty:'Silence'});manual.setAttribute('aria-label','Manual music override');assignmentRoot.append(manual);
for(const [label,action]of [['Apply manual override',()=>setOverrides([{id:'gm-manual',playlist:selection(manual.value,choices)}])],['Clear manual override',()=>setOverrides([])]]){const b=dom.createElement('button');b.type='button';b.textContent=label;b.addEventListener('click',()=>Promise.resolve().then(action).catch(onError));assignmentRoot.append(b);}
};
await renderAssignments();root.append(assignmentRoot);
const enabledLabel=dom.createElement('label');enabledLabel.textContent='Enable music automation ';const enabled=dom.createElement('input');enabled.type='checkbox';enabled.checked=game.settings.get('adaptive-music','enabled');enabledLabel.append(enabled);root.append(enabledLabel);
button('Apply automation setting',async()=>{await game.settings.set('adaptive-music','enabled',enabled.checked);if(enabled.checked)start();else stop();status.textContent=enabled.checked?'Automation enabled. MA assignments require authorized content; otherwise the configured native fallback is selected.':'Automation disabled; current playback is retained.';});
const listenerLabel=dom.createElement('label');listenerLabel.textContent='Separate listener connection code (memory only) ';const listener=dom.createElement('input');listener.type='password';listener.autocomplete='off';listenerLabel.append(listener);root.append(listenerLabel);
text('Enable Audio plays only the companion synthetic PCM test tone. It does not relay the MA DEV player or Sendspin audio. Crossfade is not available.');
// Start directly in the click task so AudioContext.resume retains user activation.
const enable=dom.createElement('button');enable.type='button';enable.textContent='Enable synthetic test audio';enable.addEventListener('click',()=>{try{const value=JSON.parse(listener.value);listener.value='';audio.start(gateway.audioRequest(value)).catch(onError);}catch{onError(new MusicError('denied'));}});root.append(enable);
button('Stop test audio',()=>audio.stop());show();return root;
}
_replaceHTML(result,content){content.replaceChildren(result);}
};
}
export function createListenerClass({game,gateway,audio,listenWebRTC,stopWebRTC=()=>{},onError,Base=globalThis.foundry.applications.api.ApplicationV2}){
return class AdaptiveMusicListener extends Base {
static DEFAULT_OPTIONS={id:'adaptive-music-listener',window:{title:'Campaign audio (development)'},position:{width:480}};
async _renderHTML(){
const dom=globalThis.document,root=dom.createElement('div');root.className='adaptive-music-setup';
const note=dom.createElement('p');note.textContent='Use a private GM WebRTC invitation, or an optional companion test code. No microphone or MA credentials are sent by players. GM-local MA audio remains experimental; never paste an MA token here.';root.append(note);
const label=dom.createElement('label');label.textContent='Listener connection code ';const input=dom.createElement('input');input.type='password';input.autocomplete='off';label.append(input);root.append(label);
const status=dom.createElement('p');status.setAttribute('role','status');root.append(status);
const enable=dom.createElement('button');enable.type='button';enable.textContent='Enable Audio';enable.addEventListener('click',()=>{try{const code=JSON.parse(input.value);input.value='';status.textContent='Connecting to campaign audio…';const task=code.transport==='webrtc-v1'?listenWebRTC(code):audio.start(gateway.audioRequest(code));Promise.resolve(task).then(()=>{status.textContent=code.transport==='webrtc-v1'?'Peer negotiation sent; waiting for GM media.':'Audio stopped.';}).catch(()=>{status.textContent='Audio unavailable. Check the private route, listener code and expiry.';onError(new MusicError('unavailable'));});}catch{status.textContent='Invalid listener code.';}});root.append(enable);
const stop=dom.createElement('button');stop.type='button';stop.textContent='Stop Audio';stop.addEventListener('click',()=>{stopWebRTC();audio.stop();});root.append(stop);return root;
}
_replaceHTML(result,content){content.replaceChildren(result);}
};
}
+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); }
}
}
+7
View File
@@ -0,0 +1,7 @@
.adaptive-music-setup {display:grid;gap:0.7rem;max-height:75vh;overflow:auto;padding:0.5rem;}
.adaptive-music-setup fieldset,[data-adaptive-music="assignments"] {display:grid;gap:0.5rem;padding:0.75rem;}
.adaptive-music-setup fieldset:first-of-type {max-height:18rem;overflow:auto;}
.adaptive-music-setup label,[data-adaptive-music="assignments"] label {display:grid;gap:0.3rem;}
.adaptive-music-setup select,[data-adaptive-music="assignments"] select {width:100%;min-width:0;}
.adaptive-music-setup input[type="checkbox"] {justify-self:start;}
.adaptive-music-setup [role="status"] {font-weight:600;}
+29
View File
@@ -0,0 +1,29 @@
<!doctype html><meta charset="utf-8"><title>Adaptive Music local audio experiment</title>
<button id="enable">Enable test audio</button>
<script type="module">
import {PeerAudio} from '/src/audio/peer-audio.mjs';
import {SendspinDecoder} from '/vendor/sendspin-5.0.0.mjs';
let listeners=new Map(),audio,context,destination,decoder,timer,analyser,sample=0,next=0;
const socket={on(name,fn){if(!listeners.has(name))listeners.set(name,new Set());listeners.get(name).add(fn);},off(name,fn){listeners.get(name)?.delete(fn);},emit(name,frame){window.relay(name,frame);}};
window.deliver=(name,frame)=>{for(const fn of listeners.get(name)??[])fn(frame);};
window.configure=({role,id})=>{audio=new PeerAudio({socket,userId:id,isGM:()=>role==='gm',isAuthorizedUser:()=>true,onError:e=>{window.lastError=e.code;},onStream:stream=>{const element=document.createElement('audio');element.autoplay=true;element.volume=0.01;element.srcObject=stream;document.body.append(element);element.play().catch(e=>{window.lastPlayError=e.name;});window.receivedAudio=element;const source=context.createMediaStreamSource(stream);analyser=context.createAnalyser();analyser.fftSize=4096;source.connect(analyser);const gain=context.createGain();gain.gain.value=0.01;analyser.connect(gain);gain.connect(context.destination);window.receivedNodes={source,analyser,gain,stream};window.receivedAt=Date.now();}});window.role=role;};
document.querySelector('#enable').onclick=async()=>{
context=new AudioContext({sampleRate:48000});await context.resume();
if(window.role==='gm'){
destination=context.createMediaStreamDestination();audio.setSource(destination.stream);next=context.currentTime+0.06;
decoder=new SendspinDecoder(chunk=>{window.sampleValue=chunk.samples[0].slice(0,10);const buffer=context.createBuffer(chunk.samples.length,chunk.samples[0].length,chunk.sampleRate);chunk.samples.forEach((samples,i)=>buffer.getChannelData(i).set(samples));const source=context.createBufferSource();source.buffer=buffer;source.connect(destination);next=Math.max(next,context.currentTime+0.02);source.start(next);next+=buffer.duration;window.decodedFrames=(window.decodedFrames??0)+1;},()=>1);
timer=setInterval(()=>{const frame=new ArrayBuffer(9+960*4),view=new DataView(frame);view.setUint8(0,4);view.setBigInt64(1,BigInt(Math.floor(context.currentTime*1000000)),false);for(let i=0;i<960;i++){const v=Math.round(2500*Math.sin(2*Math.PI*440*sample++/48000));view.setInt16(9+i*4,v,true);view.setInt16(11+i*4,v,true);}window.sourceStarted??=Date.now();decoder.handleBinaryMessage(frame,{codec:'pcm',sample_rate:48000,channels:2,bit_depth:16},1);},20);
}
window.unlocked=true;
};
window.makeInvite=id=>audio.invite(id);
window.join=invite=>audio.listen(invite);
window.measure=()=>{
if(!analyser)return null;const samples=new Float32Array(analyser.fftSize);analyser.getFloatTimeDomainData(samples);const rms=Math.sqrt(samples.reduce((sum,v)=>sum+v*v,0)/samples.length);
const bins=new Float32Array(analyser.frequencyBinCount);analyser.getFloatFrequencyData(bins);let peak=0;for(let i=1;i<bins.length;i++)if(bins[i]>bins[peak])peak=i;
return {rms,peakHz:peak*context.sampleRate/analyser.fftSize,receivedAt:window.receivedAt,stats:null};
};
window.stats=()=>audio.stats();window.diagnostics=async()=>({...audio.diagnostics(),stats:await audio.stats(),contextState:context?.state,currentTime:context?.currentTime});
window.finish=async()=>{clearInterval(timer);audio.close();for(const t of destination?.stream.getTracks()??[])t.stop();decoder?.close();await context?.close();};
window.ready=true;
</script>
+69
View File
@@ -0,0 +1,69 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { MAReadClient } from '../../gateway/ma-client.mjs';
import { GatewayControl } from '../../gateway/control.mjs';
import { SyntheticAudioGateway } from '../../gateway/synthetic-audio.mjs';
const item=(id,provider='approved')=>({media_type:'playlist',is_playable:true,name:'Safe <name>',provider_mappings:[{provider_instance:provider,item_id:id,available:true}],uri:'private',metadata:{secret:'private'}});
function client(fetchImpl,approvedProviders=['approved']) { return new MAReadClient({baseUrl:'http://localhost',token:'fixture',target:'dedicated',approvedProviders,fetchImpl}); }
test('catalog paginates, strips private metadata and filters unapproved mappings',async()=>{
const calls=[];
const c=client(async(url,opts)=>{
const {command,args}=JSON.parse(opts.body); calls.push({command,args});
assert.deepEqual(args.provider,['approved']);
return Response.json(command.includes('/radios/')?[]:args.offset===0?Array.from({length:100},(_,i)=>item(String(i))):[item('100'),item('bad','forbidden')]);
});
const result=await c.catalog(); assert.equal(result.length,101);
assert.equal(calls.length,3);assert.equal(calls[1].args.offset,100);
assert.deepEqual(Object.keys(result[0]).sort(),['id','kind','name','provider']);
const again=await c.catalog();assert.equal(result[0].id,again[0].id);
assert.ok(!JSON.stringify(result).includes('private'));
});
test('empty provider allowlist denies without I/O; malformed and endless pages fail',async()=>{
let calls=0;const c=client(async()=>{calls++;},[]);
await assert.rejects(c.catalog(),{code:'denied'});assert.equal(calls,0);
await assert.rejects(client(async()=>Response.json({error:'private'})).catalog(),{code:'unavailable'});
await assert.rejects(client(async()=>Response.json(Array.from({length:100},(_,i)=>item(String(i))))).catalog(),{code:'unavailable'});
});
test('target validation rejects group, changed identity and unavailable player',async()=>{
const valid={player_id:'dedicated',provider:'sendspin',available:true,enabled:true,group_members:[],group_childs:[],static_group_members:[]};
for(const patch of [{active_group:'other'},{synced_to:'other'},{group_members:['household']},{player_id:'wrong'},{available:false},{provider:'sonos'}]) {
await assert.rejects(client(async()=>Response.json({...valid,...patch})).verifyTarget(),{code:'denied'});
}
});
function audioFixture(){
let now=0; const control=new GatewayControl({campaigns:{a:{},b:{}},origin:'https://example.test',now:()=>now});
const audio=new SyntheticAudioGateway({control});for(const campaign of ['a','b'])audio.provision({campaign,session:'s'});
const request={campaign:'a',session:'s',origin:'https://example.test',token:control.mint({campaign:'a',session:'s',role:'listener',ttlMs:1000})};
const publish=(campaign,generation,value)=>audio.publish({campaign,session:'s',generation,pcm:new Uint8Array(1920).fill(value)});
return {control,audio,request,publish,set now(value){now=value;}};
}
test('synthetic audio isolates simultaneous campaigns and copies every frame',()=>{
const f=audioFixture(),a=f.audio.connect(f.request),b=f.audio.connect({...f.request,campaign:'b',token:f.control.mint({campaign:'b',session:'s',role:'listener'})});
f.publish('a',1,11);f.publish('b',1,22);
assert.equal(a.next().pcm[0],11);assert.equal(b.next().pcm[0],22);assert.equal(a.next(),null);
f.publish('a',2,33);const frame=a.next();frame.pcm.fill(0);assert.equal(frame.sampleRate,24000);
});
test('audio denies forged origin/session/role, unknown fields and cross-campaign grants',()=>{
const f=audioFixture();
for(const patch of [{token:'forged'},{origin:'https://evil.test'},{session:'other'},{campaign:'b'},{command:'group'},{url:'http://localhost'},{token:f.control.mint({campaign:'a',session:'s',role:'controller'})}])assert.throws(()=>f.audio.connect({...f.request,...patch}),{code:'denied'});
});
test('active listener revocation/expiry and slow-client overflow close handles',()=>{
const f=audioFixture(),a=f.audio.connect(f.request);f.control.revoke(f.request.token);f.audio.sweep();assert.equal(a.closed,true);
const e=audioFixture(),b=e.audio.connect(e.request);e.now=1001;assert.throws(()=>b.next(),{code:'denied'});assert.equal(b.closed,true);
const s=audioFixture(),c=s.audio.connect(s.request);for(let i=1;i<=11;i++)s.publish('a',i,0);
assert.throws(()=>c.next(),{code:'stale'});assert.equal(c.closed,true);
});
test('synthetic source rejects stale sessions/generations, oversized frames; connections are bounded',()=>{
const f=audioFixture();f.publish('a',1,0);assert.throws(()=>f.publish('a',1,0),{code:'stale'});
assert.throws(()=>f.audio.publish({campaign:'a',session:'old',generation:2,pcm:new Uint8Array(1920)}),{code:'stale'});
assert.throws(()=>f.audio.publish({campaign:'a',session:'s',generation:2,pcm:new Uint8Array(1921)}),{code:'denied'});
for(let i=0;i<16;i++)f.audio.connect(f.request);assert.throws(()=>f.audio.connect(f.request),{code:'denied'});
f.audio.purge('a');assert.throws(()=>f.audio.connect(f.request),{code:'denied'});
});
test('catalog authorization denies listener and injection before upstream',async()=>{
let calls=0;const control=new GatewayControl({campaigns:{a:{client:{catalog:async()=>{calls++;return [];}}}},origin:'https://example.test'});
const request={campaign:'a',session:'s',origin:'https://example.test',token:control.mint({campaign:'a',session:'s',role:'controller'}),generation:1};request.fence=control.acquire(request).fence;
await assert.rejects(control.readCatalog({...request,provider:'forbidden'}),{code:'denied'});
await assert.rejects(control.readCatalog({...request,token:control.mint({campaign:'a',session:'s',role:'listener'})}),{code:'denied'});assert.equal(calls,0);
assert.deepEqual(await control.readCatalog(request),[]);assert.equal(calls,1);
});
+43
View File
@@ -0,0 +1,43 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { savePlaylistConfiguration, mountPlaylistConfiguration, startConfigurationInterfaces } from '../../src/foundry/configuration.mjs';
const choices=[{provider:'native',id:'owned',name:'Scene music'},{provider:'ma',id:'opaque',name:'Catalog music'}];
function fixture(){
let flag={boss:true,priority:7};const writes=[];
const document={getFlag:()=>flag,async setFlag(ns,k,value){writes.push({ns,k,value});flag=value;}};
return {document,writes,game:{user:{isGM:true}}};
}
test('scene/combat configuration preserves independent flags and stores only tagged references',async()=>{
for(const choice of choices){const f=fixture();await savePlaylistConfiguration({...f,choices,selected:JSON.stringify([choice.provider,choice.id])});
assert.deepEqual(f.writes,[{ns:'adaptive-music',k:'music',value:{boss:true,priority:7,playlist:{provider:choice.provider,id:choice.id}}}]);
await savePlaylistConfiguration({...f,choices,selected:''});assert.equal(f.writes[1].value.playlist,null);
}
});
test('role loss, stale selection and arbitrary URL/ID fail before document write',async()=>{
const f=fixture();for(const selected of ['https://example.test/audio',JSON.stringify(['native','household']),JSON.stringify(['ma','stale'])])await assert.rejects(savePlaylistConfiguration({...f,choices,selected}),{code:'denied'});
f.game.user.isGM=false;await assert.rejects(savePlaylistConfiguration({...f,choices,selected:''}),{code:'denied'});assert.equal(f.writes.length,0);
});
// Tiny DOM harness exercises event wiring/text sinks; it is not Foundry/browser evidence.
class Element {
constructor(tag,ownerDocument){this.tag=tag;this.ownerDocument=ownerDocument;this.children=[];this.dataset={};this.listeners={};}
append(...children){this.children.push(...children);}
querySelector(){return this.children.find(c=>c.dataset?.adaptiveMusic);}
setAttribute(){}
addEventListener(name,fn){this.listeners[name]=fn;}
remove(){this.removed=true;}
}
function container(){const dom={createElement:tag=>new Element(tag,dom),createTextNode:text=>({textContent:text})};return new Element('div',dom);}
test('editor uses text for catalog labels and rechecks GM on actual save event',async()=>{
const f=fixture(),root=container();const panel=mountPlaylistConfiguration({...f,container:root,choices:[...choices,{provider:'ma',id:'x',name:'<img src=x onerror=attack()>'}]});
assert.equal(mountPlaylistConfiguration({...f,container:root,choices}),null);
const label=panel.children.find(c=>c.tag==='label'),select=label.children.find(c=>c.tag==='select');
assert.ok(select.children.some(c=>c.textContent.includes('<img')));
select.value=JSON.stringify(['native','owned']);const button=panel.children.find(c=>c.tag==='button');
await button.listeners.click();assert.equal(f.writes.length,1);
f.game.user.isGM=false;await button.listeners.click();assert.equal(f.writes.length,1);
});
test('configuration hook disposal prevents pending asynchronous render from mounting',async()=>{
const f=fixture(),callbacks=new Map();let resolve;const off=[];
const ui=startConfigurationInterfaces({...f,Hooks:{on(e,fn){callbacks.set(e,fn);return e;},off(...args){off.push(args);}},getChoices:()=>new Promise(r=>{resolve=r;})});
const root=container();const pending=callbacks.get('renderSceneConfig')({document:f.document},root);ui.dispose();resolve(choices);await pending;assert.equal(root.children.length,0);assert.equal(off.length,2);
});
+100
View File
@@ -0,0 +1,100 @@
import {test} from 'node:test';
import assert from 'node:assert/strict';
import {createServer} from 'node:http';
import {MAReadClient} from '../../gateway/ma-client.mjs';
import {GatewayControl} from '../../gateway/control.mjs';
import {DevelopmentService} from '../../gateway/development-service.mjs';
import {startDevelopmentHTTP} from '../../gateway/development-http.mjs';
import {GatewayClient} from '../../src/providers/ma/remote.mjs';
import {SyntheticAudioGateway} from '../../gateway/synthetic-audio.mjs';
import {MusicController} from '../../src/core/controller.mjs';
const origin='https://foundry.example.test';
async function fixture(){
let items=[],state='idle',index=null,position=0;const writes=[],browserResponses=[];
const track=id=>({queue_item_id:'occurrence-'+id,media_item:{media_type:'track',provider_mappings:[{provider_instance:'approved',item_id:id,available:true}]},duration:120});
const queue=()=>({queue_id:'dev-only',active:true,available:true,items:items.length,state,current_index:index,current_item:items[index],elapsed_time:position,elapsed_time_last_updated:Date.now()/1000,repeat_mode:'off',shuffle_enabled:false,is_dynamic:false,autoplay_enabled:false,dont_stop_the_music_enabled:false,overlay_enabled:false,playback_speed:1,ended:false});
let grouped=false;
const ma=createServer(async(req,res)=>{
assert.equal(req.headers.authorization,'Bearer MA-secret-fixture');let text='';for await(const chunk of req)text+=chunk;const {command,args}=JSON.parse(text);let result;
if(command==='players/get')result={player_id:'dev-only',name:'Adaptive Music DEV',provider:'sendspin-fixture',available:true,enabled:true,group_members:grouped?['other']:[],group_childs:[],static_group_members:[]};
else if(command==='player_queues/get'||command==='player_queues/get_active_queue')result=queue();
else if(command==='player_queues/items')result=items.slice(args.offset,args.offset+args.limit);
else if(command==='music/playlists/library_items')result=['ambient','combat'].map(id=>({name:'Fixture '+id,media_type:'playlist',is_playable:true,is_dynamic:false,provider_mappings:[{provider_instance:'approved',item_id:id,available:true}]}));
else if(command==='music/radios/library_items')result=[];
else if(command==='music/playlists/get')result={is_dynamic:false};
else if(command==='music/playlists/playlist_tracks')result=[track(args.item_id+'-1').media_item,track(args.item_id+'-2').media_item];
else{
assert.equal(args.queue_id,'dev-only');writes.push(command);
if(command==='player_queues/stop')state='idle';
if(command==='player_queues/clear'){items=[];index=null;position=0;}
if(command==='player_queues/play_media'){items=args.media.map(uri=>track(uri.split('/').at(-1)));index=0;position=0;if(args.option==='replace')state='playing';}
if(command==='player_queues/play_index'){index=args.index;position=args.seek_position;state='playing';}
if(command==='player_queues/pause')state='paused';result=null;
}
res.writeHead(200,{'Content-Type':'application/json'});res.end(JSON.stringify(result));
});await new Promise(resolve=>ma.listen(0,'127.0.0.1',resolve));
const client=new MAReadClient({baseUrl:`http://127.0.0.1:${ma.address().port}`,token:'MA-secret-fixture',target:'dev-only',approvedProviders:['approved'],catalogKey:Buffer.alloc(32,1),campaign:'server-c',expectedName:'Adaptive Music DEV',expectedProvider:'sendspin-fixture'});
const choices=await client.catalog();
let offset=0;const control=new GatewayControl({campaigns:{'server-c':{client}},origin,now:()=>Date.now()+offset});const grant=role=>({token:control.mint({campaign:'server-c',session:'server-s',role}),campaign:'server-c',session:'server-s'});
const controller=grant('controller'),listener=grant('listener');
const audio=new SyntheticAudioGateway({control});audio.provision({campaign:'server-c',session:'server-s'});
const service=new DevelopmentService({control,campaign:'server-c',session:'server-s',client,snapshotKey:Buffer.alloc(32,2),allowedIds:choices.map(c=>c.id),playbackEnabled:true,audio});
const http=await startDevelopmentHTTP({service,origin});
const fetchImpl=async(path,options)=>{const response=await fetch(http.url+path.replace('/adaptive-music-gateway',''),{...options,headers:{...options.headers,Origin:origin}});browserResponses.push(await response.clone().text());return response;};
const browser=new GatewayClient({origin,fetchImpl});
return {browser,http,control,controller,listener,service,choices,writes,browserResponses,audio,client,expire(){offset=60001;},set grouped(value){grouped=value;},async close(){await browser.disconnect();await http.close();await new Promise(resolve=>ma.close(resolve));ma.closeAllConnections();}};
}
test('packaged browser client connects through real loopback companion/MA wire fixtures and restores combat queue',async()=>{
const f=await fixture();try{
const status=await f.browser.connect(f.controller);assert.equal(status.target,'verified');assert.equal(f.browser.catalog.length,2);
const controller=new MusicController({campaign:'browser-world',session:'browser-session',providers:{ma:f.browser},authority:()=>true});
const base={scene:{id:'scene',playlist:{provider:'ma',id:f.choices[0].id}},combats:[]};
await controller.update(base);const combat={...base,combats:[{id:'combat',sceneId:'scene',active:true,started:true,playlist:{provider:'ma',id:f.choices[1].id}}]};
await controller.update(combat);await controller.update(base);assert.equal(controller.current.playlist.id,f.choices[0].id);
const before=f.writes.length;await Promise.allSettled([controller.update(combat),controller.update(base)]);assert.equal(f.writes.length,before);
const wire=f.browserResponses.join('');assert.ok(!wire.includes('MA-secret-fixture'));assert.ok(!wire.includes('approved://'));assert.ok(!wire.includes('dev-only'));assert.ok(wire.includes('handle'));
f.grouped=true;await assert.rejects(f.browser.stopOwned({generation:++controller.generation,check(){}}),{code:'denied'});assert.equal(f.writes.length,before);
}finally{await f.close();}
});
test('companion denies listener control, wrong scope/Origin, upstream injection and unknown routes',async()=>{
const f=await fixture();try{
await assert.rejects(f.browser.connect(f.listener),{code:'denied'});
const rpc=async(body,{grant=f.controller,requestOrigin=origin,path='/rpc'}={})=>fetch(f.http.url+path,{method:'POST',headers:{Origin:requestOrigin,Authorization:`Bearer ${grant.token}`,'Content-Type':'application/json'},body:JSON.stringify({...grant,token:undefined,...body})});
for(const patch of [{campaign:'other',action:'catalog'},{action:'catalog',queue_id:'household'},{action:'transfer'}]){const res=await rpc(patch);assert.equal(res.status,403);}
assert.equal((await rpc({action:'catalog'},{requestOrigin:'https://evil.test'})).status,403);
assert.equal((await rpc({action:'catalog'},{path:'/api'})).status,403);assert.equal(f.writes.length,0);
}finally{await f.close();}
});
test('browser accepts only relative same-origin paths and never persists a connection grant',()=>{
for(const path of ['https://example.test','//evil.test','/../api','/api?token=x','/api#x'])assert.throws(()=>new GatewayClient({origin,path}),{code:'denied'});
});
test('companion operation replay is idempotent and same ID with changed payload is denied',async()=>{
const f=await fixture();try{
await f.browser.connect(f.controller);
const body={action:'stop',campaign:f.controller.campaign,session:f.controller.session,fence:1,generation:1,operationId:'same-operation'};
const send=patch=>fetch(f.http.url+'/rpc',{method:'POST',headers:{Origin:origin,Authorization:`Bearer ${f.controller.token}`,'Content-Type':'application/json'},body:JSON.stringify({...body,...patch})});
assert.equal((await send()).status,200);assert.equal((await send()).status,200);assert.equal(f.writes.filter(c=>c==='player_queues/stop').length,1);
assert.equal((await send({action:'snapshot'})).status,403);assert.equal((await send({generation:0,operationId:'stale'})).status,403);
}finally{await f.close();}
});
test('companion listener stream rejects controller grant and closes on live revocation and expiry',async()=>{
for(const mode of ['revoke','expire']){
const f=await fixture();try{
const open=grant=>fetch(f.http.url+'/audio',{method:'POST',headers:{Origin:origin,Authorization:`Bearer ${grant.token}`,'Content-Type':'application/json'},body:JSON.stringify({campaign:grant.campaign,session:grant.session})});
const denied=await open(f.controller);assert.equal(denied.status,403);
const response=await open(f.listener);assert.equal(response.status,200);const reader=response.body.getReader();
f.audio.publish({campaign:'server-c',session:'server-s',generation:1,pcm:new Uint8Array(1920).fill(7)});assert.equal((await reader.read()).value[0],7);
if(mode==='revoke')f.control.revoke(f.listener.token);else f.expire();
let timer;try{await assert.rejects(Promise.race([reader.read(),new Promise((resolve,reject)=>{timer=setTimeout(()=>reject(Error('stream did not close promptly')),500);})]),{name:'TypeError'});}finally{clearTimeout(timer);}
assert.equal(f.writes.length,0);
}finally{await f.close();}
}
});
test('catalog revocation during upstream I/O suppresses the response at the companion boundary',async()=>{
const f=await fixture();try{
f.client.catalog=async()=>{f.control.revoke(f.controller.token);return [{name:'must never leave'}];};
await assert.rejects(f.browser.connect(f.controller),{code:'denied'});
assert.ok(!f.browserResponses.join('').includes('must never leave'));assert.equal(f.writes.length,0);
}finally{await f.close();}
});
+128
View File
@@ -0,0 +1,128 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { MusicController, MusicError, candidates } from '../../src/core/controller.mjs';
const ref = id => ({ provider: 'native', id });
const scene = (id = 'A') => ({ id, playlist: ref(id) });
const combat = (bosses = []) => ({ id: 'fight', active: true, started: true, sceneId: 'A', playlist: ref('combat'), bosses });
const boss = (id = 'boss', priority = 1) => ({ id, priority, active: true, playlist: ref(id) });
function fixture(options = {}) {
const log = []; let playback = { items: ['duplicate','duplicate','third'], index: 1, offset: 42, paused: true };
const provider = {
async resolve(r,c) { log.push(['resolve',r.id]); return r; },
async snapshot(c) { return { ...structuredClone(playback), campaign: c.campaign, session: c.session, generation: c.generation }; },
async stopOwned(c) { c.check(); log.push(['stop']); },
async apply(r,c) { c.check(); log.push(['apply',r.id]); playback = { items: [r.id], index: 0, offset: 0, paused: false }; },
async restore(s,c) { c.check(); log.push(['restore',s]); playback = structuredClone(s); }
};
const controller = new MusicController({ campaign: 'campaign', session: 'session', providers: { native: provider, other: provider }, authority: () => true, ...options });
return { controller, provider, log, get playback() { return playback; }, set playback(p) { playback=p; } };
}
test('policy precedence and explicit silence', () => {
assert.equal(candidates({scene:scene(),combats:[combat([boss()])],overrides:[{id:'silence',playlist:null}]})[0].playlist,null);
assert.equal(candidates({scene:scene(),combats:[combat([boss()])]})[0].playlist.id,'boss');
assert.equal(candidates({scene:scene(),combats:[combat()]})[0].playlist.id,'combat');
assert.equal(candidates({scene:scene()})[0].playlist.id,'A');
assert.equal(candidates({defaultPlaylist:ref('world')})[0].playlist.id,'world');
assert.equal(candidates({})[0].playlist,null);
});
test('inactive, unstarted and other scene combats ignored; boss ties stable', () => {
for (const change of [{active:false},{started:false},{sceneId:'B'}]) {
assert.equal(candidates({scene:scene(),combats:[{...combat([boss()]),...change}]})[0].playlist.id,'A');
}
assert.equal(candidates({scene:scene(),combats:[combat([boss('z',3),boss('a',3),boss('b',2)])]})[0].playlist.id,'a');
});
test('scene -> combat -> boss -> nested manual -> unwind restores offsets, duplicates and pause', async () => {
const f=fixture(), c=f.controller;
const base={scene:scene()}, fight={...base,combats:[combat()]}, big={...base,combats:[combat([boss()])]};
await c.update(base); f.playback={items:['same','same','end'],index:1,offset:42,paused:true};
await c.update(fight); await c.update(big);
await c.update({...big,overrides:[{id:'one',playlist:ref('one')}]});
await c.update({...big,overrides:[{id:'one',playlist:ref('one')},{id:'two',playlist:null}]});
assert.equal((await c.update({...big,overrides:[{id:'one',playlist:ref('one')}]})).restored,true);
assert.equal((await c.update(big)).restored,true);
assert.equal((await c.update(fight)).restored,true);
assert.equal((await c.update(base)).restored,true);
assert.deepEqual(f.playback.items,['same','same','end']); assert.equal(f.playback.index,1);
assert.equal(f.playback.offset,42); assert.equal(f.playback.paused,true);
});
test('scene change during manual never resurrects previous scene', async () => {
const f=fixture(); const overrides=[{id:'manual',playlist:ref('manual')}];
await f.controller.update({scene:scene()}); await f.controller.update({scene:scene(),overrides});
await f.controller.update({scene:scene('B'),overrides}); await f.controller.update({scene:scene('B')});
assert.equal(f.playback.items[0],'B'); assert.equal(f.controller.frames.length,0);
});
test('boss removed during manual and deleted combat cannot return', async () => {
const f=fixture(); const base={scene:scene()}, big={...base,combats:[combat([boss()])]};
await f.controller.update(base); await f.controller.update(big);
await f.controller.update({...big,overrides:[{id:'m',playlist:ref('m')}]});
await f.controller.update({...base,overrides:[{id:'m',playlist:ref('m')}]});
await f.controller.update(base); assert.equal(f.playback.items[0],'A');
assert.equal(f.controller.frames.length,0);
});
test('duplicate intent causes zero provider mutations', async () => {
const f=fixture(); await f.controller.update({scene:scene()}); const before=f.log.length;
assert.equal((await f.controller.update({scene:scene()})).unchanged,true); assert.equal(f.log.length,before);
});
test('prepare failure leaves current playback intact', async () => {
const f=fixture(); await f.controller.update({scene:scene()});
f.provider.resolve=async()=>{throw new MusicError('unavailable');};
await assert.rejects(f.controller.update({scene:scene('B')}),{code:'unavailable'});
assert.equal(f.playback.items[0],'A'); assert.equal(f.log.filter(x=>x[0]==='stop').length,0);
});
test('partial apply failure restores outgoing playback', async () => {
const f=fixture(); await f.controller.update({scene:scene()});
f.provider.apply=async()=>{throw new MusicError('unavailable');};
await assert.rejects(f.controller.update({scene:scene('B')})); assert.equal(f.playback.items[0],'A');
});
test('obsolete async resolve is rejected before stop/apply', async () => {
const f=fixture(); let resume, entered;
const ready=new Promise(r=>entered=r), normal=f.provider.resolve;
f.provider.resolve=async(r,c)=>{if(r.id==='A'){entered();await new Promise(r=>resume=r);} return normal(r,c);};
const first=f.controller.update({scene:scene()}); await ready;
const second=f.controller.update({scene:scene('B')}); resume();
await assert.rejects(first,{code:'stale'}); await second;
assert.deepEqual(f.log.filter(x=>x[0]==='apply'),[['apply','B']]);
});
test('lease loss during stop prevents apply and stale rollback', async () => {
let active=true; const f=fixture({authority:()=>active}); await f.controller.update({scene:scene()});
f.provider.stopOwned=async()=>{active=false;};
await assert.rejects(f.controller.update({scene:scene(),combats:[combat()]}),{code:'stale'});
assert.equal(f.log.filter(x=>x[0]==='restore').length,0);
});
test('provider switch and bounded nested stack', async () => {
const f=fixture({maxFrames:2}); await f.controller.update({scene:scene()});
await f.controller.update({scene:{id:'B',playlist:{provider:'other',id:'other'}}});
assert.equal(f.playback.items[0],'other');
for(let i=0;i<5;i++) await f.controller.update({scene:scene(),overrides:Array.from({length:i+1},(_,j)=>({id:String(j),playlist:ref(String(j))}))});
assert.ok(f.controller.frames.length<=2);
});
test('no authority retains playback without provider access', async () => {
const f=fixture({authority:()=>false}); await assert.rejects(f.controller.update({scene:scene()}),{code:'stale'}); assert.deepEqual(f.log,[]);
});
test('queued state is captured at submission rather than read after caller mutation',async()=>{
const f=fixture(),state={scene:scene()};const pending=f.controller.update(state);state.scene.playlist=ref('mutated');
await pending;assert.equal(f.playback.items[0],'A');
});
test('supersession after snapshot prevents mutations',async()=>{
const f=fixture();await f.controller.update({scene:scene()});
let resume,entered;const ready=new Promise(r=>entered=r),normal=f.provider.snapshot;
f.provider.snapshot=async c=>{const s=await normal(c);entered();await new Promise(r=>resume=r);return s;};
const first=f.controller.update({scene:scene(),combats:[combat()]});await ready;
f.provider.snapshot=normal;const second=f.controller.update({scene:scene('B')});resume();
await assert.rejects(first,{code:'stale'});await second;
assert.equal(f.log.filter(x=>x[0]==='apply'&&x[1]==='combat').length,0);
});
test('failed cross-provider apply cleans new owned audio before outgoing restoration',async()=>{
const f=fixture();await f.controller.update({scene:scene()});const effects=[];
f.controller.providers.other={resolve:async r=>r,apply:async()=>{effects.push('partial');throw new Error('failed');},stopOwned:async()=>effects.push('cleanup')};
await assert.rejects(f.controller.update({scene:{id:'B',playlist:{provider:'other',id:'B'}}}));
assert.deepEqual(effects,['partial','cleanup']);assert.equal(f.playback.items[0],'A');
});
test('superseded cross-provider apply is reconciled by stopping partially touched target',async()=>{
const f=fixture();await f.controller.update({scene:scene()});
let resume,entered;const ready=new Promise(r=>entered=r);let cleanups=0;
f.controller.providers.other={resolve:async r=>r,apply:async()=>{entered();await new Promise(r=>resume=r);},stopOwned:async()=>{cleanups++;}};
const stale=f.controller.update({scene:{id:'B',playlist:{provider:'other',id:'B'}}});await ready;
const newest=f.controller.update({scene:scene()});resume();await assert.rejects(stale,{code:'stale'});await newest;
assert.equal(cleanups,1);assert.equal(f.playback.items[0],'A');
});
+38
View File
@@ -0,0 +1,38 @@
import {test} from 'node:test';
import assert from 'node:assert/strict';
import {mkdtemp,mkdir,writeFile,readFile,rm} from 'node:fs/promises';
import {tmpdir} from 'node:os';
import {join} from 'node:path';
import {fileURLToPath} from 'node:url';
import {spawn,spawnSync} from 'node:child_process';
import {createServer} from 'node:http';
test('extracted companion launches privately with fixture credentials, serves catalog diagnostics and listener PCM',async()=>{
const folder=await mkdtemp(join(tmpdir(),'adaptive-companion-')),commands=[];
const ma=createServer(async(req,res)=>{let text='';for await(const chunk of req)text+=chunk;const {command}=JSON.parse(text);commands.push(command);let result;
if(command==='players/get')result={player_id:'dev-only',name:'Adaptive Music DEV',provider:'sendspin-fixture',enabled:true,available:true,group_members:[],group_childs:[],static_group_members:[]};
else if(command.startsWith('player_queues/get'))result={queue_id:'dev-only',active:true,available:true};else result=[];
res.writeHead(200,{'Content-Type':'application/json'});res.end(JSON.stringify(result));});
await new Promise(resolve=>ma.listen(0,'127.0.0.1',resolve));let child;
try{
const source=fileURLToPath(new URL('../../scripts/package_module.py',import.meta.url));
const script="import importlib.util,pathlib,sys,zipfile;s=importlib.util.spec_from_file_location('p',sys.argv[1]);m=importlib.util.module_from_spec(s);s.loader.exec_module(m);p=m.build_companion(pathlib.Path(sys.argv[2])/'companion.zip');zipfile.ZipFile(p).extractall(sys.argv[2])";
const built=spawnSync('python3',['-c',script,source,folder],{encoding:'utf8'});assert.equal(built.status,0,built.stderr);
const root=join(folder,'adaptive-music-companion'),local=join(root,'.local');await mkdir(local,{mode:0o700});
const json=(name,value)=>writeFile(join(local,name),JSON.stringify(value),{mode:0o600});
await writeFile(join(local,'ma-token'),'fixture-MA-secret',{mode:0o600});
await json('environment.json',{ma_url:`http://127.0.0.1:${ma.address().port}`});await json('development-gateway.json',{foundryOrigin:'https://foundry.example.test',syntheticAudio:true});
await json('ma-readonly-results.json',{me:{player_filter:['dev-only'],provider_filter:['approved']},player:{name:'Adaptive Music DEV',provider:'sendspin-fixture'}});
child=spawn(process.execPath,['gateway/run-development.mjs'],{cwd:root,stdio:['ignore','pipe','pipe']});let output='';child.stdout.on('data',chunk=>{output+=chunk;});child.stderr.on('data',chunk=>{output+=chunk;});
for(let attempt=0;attempt<200;attempt++){try{await readFile(join(local,'listener-bootstrap.json'));break;}catch{await new Promise(resolve=>setTimeout(resolve,10));}}
const runtime=JSON.parse(await readFile(join(local,'development-gateway-runtime.json'),'utf8')),controller=JSON.parse(await readFile(join(local,'controller-bootstrap.json'),'utf8')),listener=JSON.parse(await readFile(join(local,'listener-bootstrap.json'),'utf8'));
assert.ok(runtime.url.startsWith('http://127.0.0.1:'));assert.ok(!output.includes('fixture-MA-secret'));
const rpc=async(action)=>fetch(runtime.url+'/rpc',{method:'POST',headers:{Origin:'https://foundry.example.test','Content-Type':'application/json',Authorization:`Bearer ${controller.token}`},body:JSON.stringify({action,campaign:controller.campaign,session:controller.session})});
assert.equal((await rpc('connect')).status,200);const d=await (await rpc('diagnostics')).json();assert.equal(d.target,'verified');assert.equal(d.playbackEnabled,false);assert.deepEqual(await (await rpc('catalog')).json(),[]);
const before=commands.length;
const audio=await fetch(runtime.url+'/audio',{method:'POST',headers:{Origin:'https://foundry.example.test','Content-Type':'application/json',Authorization:`Bearer ${listener.token}`},body:JSON.stringify({campaign:listener.campaign,session:listener.session})});
assert.equal(audio.status,200);const reader=audio.body.getReader();const frame=await reader.read();assert.ok(frame.value.length>=1920);await reader.cancel();assert.equal(commands.length,before);assert.ok(!commands.some(c=>['player_queues/play_media','player_queues/stop'].includes(c)));
}finally{
if(child&&child.exitCode===null){const exited=new Promise(resolve=>child.once('exit',resolve));child.kill('SIGTERM');await exited;}
ma.closeAllConnections();await new Promise(resolve=>ma.close(resolve));await rm(folder,{recursive:true,force:true});
}
});
+79
View File
@@ -0,0 +1,79 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { GatewayControl } from '../../gateway/control.mjs';
import { MAReadClient } from '../../gateway/ma-client.mjs';
function fixture() {
let now=1000,calls=0;
const g=new GatewayControl({campaigns:{a:{target:'dedicated-a',client:{async getOwnedQueue(id){assert.equal(id,'dedicated-a');calls++;return {state:'playing',items:3,secret:'must never leave'};}}},b:{target:'dedicated-b'}},origin:'https://example.test',now:()=>now});
const token=g.mint({campaign:'a',session:'s',role:'controller'});
const request={token,origin:'https://example.test',campaign:'a',session:'s',generation:1};
request.fence=g.acquire(request).fence;
return {g,request,get calls(){return calls;},set now(value){now=value;}};
}
test('gateway binds target server-side and sanitizes metadata',async()=>{
const f=fixture();assert.deepEqual(await f.g.readQueue(f.request),{state:'playing',items:3});assert.equal(f.calls,1);
});
test('forged, wrong origin/campaign/session and unknown args deny before upstream',async()=>{
const f=fixture();
for(const patch of [{token:'forged'},{origin:'https://evil.test'},{campaign:'b'},{session:'other'},{queue_id:'household'},{command:'player_queues/transfer'},{uri:'http://example.test/'}])
await assert.rejects(f.g.readQueue({...f.request,...patch}),{code:'denied'});
assert.equal(f.calls,0);
});
test('listener cannot read queues or acquire controller lease',async()=>{
const f=fixture(),token=f.g.mint({campaign:'a',session:'s',role:'listener'});
await assert.rejects(f.g.readQueue({...f.request,token}),{code:'denied'});
assert.throws(()=>f.g.acquire({...f.request,token}),{code:'denied'});assert.equal(f.calls,0);
});
test('expiry, revocation, stale fence and replay reject',async()=>{
const f=fixture();await f.g.readQueue(f.request);
await assert.rejects(f.g.readQueue(f.request),{code:'stale'});
await assert.rejects(f.g.readQueue({...f.request,generation:2,fence:999}),{code:'stale'});
f.now=40000;await assert.rejects(f.g.readQueue({...f.request,generation:2}),{code:'stale'});
f.g.revoke(f.request.token);await assert.rejects(f.g.readQueue({...f.request,generation:2}),{code:'denied'});
});
test('lease cannot be stolen and increases fence after revoke',()=>{
const f=fixture(),token=f.g.mint({campaign:'a',session:'s2',role:'controller'});
assert.throws(()=>f.g.acquire({...f.request,token,session:'s2'}),{code:'denied'});
f.g.revoke(f.request.token);const next=f.g.acquire({...f.request,token,session:'s2'});assert.equal(next.fence,2);
});
test('revocation during upstream I/O suppresses response',async()=>{
const f=fixture();f.g.campaigns.get('a').client.getOwnedQueue=async()=>{f.g.revoke(f.request.token);return {state:'playing',items:1};};
await assert.rejects(f.g.readQueue(f.request),{code:'denied'});
});
test('MA adapter uses pinned envelope, Bearer header, fixed path, no redirects and returns no metadata',async()=>{
const client=new MAReadClient({baseUrl:'http://localhost:9999',token:'fixture-token',target:'owned',fetchImpl:async(url,options)=>{
assert.equal(url,'http://localhost:9999/api');assert.equal(options.redirect,'error');
assert.equal(options.headers.Authorization,'Bearer fixture-token');
assert.deepEqual(JSON.parse(options.body),{message_id:'adaptive-music-read',command:'player_queues/get',args:{queue_id:'owned'}});
return new Response(JSON.stringify({queue_id:'owned',active:true,state:'paused',items:2,uri:'secret'}));
}});
assert.deepEqual(await client.getOwnedQueue('owned'),{state:'paused',items:2});
await assert.rejects(client.getOwnedQueue('household'),{code:'denied'});
});
test('MA mismatched queue, upstream failures and redirects fail with sanitized errors',async()=>{
for(const fetchImpl of [async()=>new Response(JSON.stringify({queue_id:'household',active:true})), async()=>{throw new Error('private URL and secret');},async()=>new Response('failure',{status:403}),async()=>new Response('x'.repeat(1048577))]){
const client=new MAReadClient({baseUrl:'http://localhost:9999',token:'fixture',target:'owned',fetchImpl});
await assert.rejects(client.getOwnedQueue('owned'),e=>['denied','unavailable'].includes(e.message));
}
});
test('MA rejects URL credentials, query/fragment, paths and non-HTTP configuration',()=>{
for(const baseUrl of ['file:///etc/passwd','http://localhost/path','http://localhost/?token=x','http://localhost/#x','http://' + 'user:pass' + '@localhost/'])
assert.throws(()=>new MAReadClient({baseUrl,token:'fixture',target:'owned'}));
});
test('MA read adapter performs real local HTTP POST against an isolated fixture',async()=>{
const {createServer}=await import('node:http');
const requests=[];
const server=createServer(async(req,res)=>{
let body='';for await(const chunk of req)body+=chunk;
requests.push({method:req.method,path:req.url,auth:req.headers.authorization,body:JSON.parse(body)});
res.writeHead(200,{'Content-Type':'application/json'});
res.end(JSON.stringify({queue_id:'fixture-target',active:true,state:'paused',items:3}));
});
await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
try {
const client=new MAReadClient({baseUrl:`http://127.0.0.1:${server.address().port}`,token:'offline-fixture-only',target:'fixture-target'});
assert.deepEqual(await client.getOwnedQueue('fixture-target'),{state:'paused',items:3});
assert.equal(requests.length,1);assert.equal(requests[0].path,'/api');assert.equal(requests[0].method,'POST');
assert.equal(requests[0].body.args.queue_id,'fixture-target');assert.equal(requests[0].auth,'Bearer offline-fixture-only');
} finally { await new Promise(resolve=>server.close(resolve)); }
});
Loaded 100 of 114 files, more files were not shown because too many files have changed in this diff. Show more