4 Commits
Author SHA1 Message Date
Jason eb9536f903 Release v0.6.0 - Music Assistant wizard and automatic listener connections
Validate and generate manual release / package (push) Waiting to run
2026-12-03 20:11:10 -05:00
CheddahBoxMB 5319177c58 Upload files to "/" 2026-12-03 16:20:06 -05:00
Jason f9f891d779 Merge remote-tracking branch 'origin/main'
Validate and generate manual release / package (push) Canceled after 0s
2026-12-03 16:15:54 -05:00
Jason 14f0d8c26b Initial Adaptive Music v0.5.0 release 2026-12-03 16:11:47 -05:00
121 changed files with 7695 additions and 1 deletions

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.
+115
View File
@@ -0,0 +1,115 @@
# Adaptive Music architecture — 0.6.0
Independent project by CheddahBoxMB, system-independent, targeting Foundry v14.371
and MA 2.10.6. Standard distribution is one Foundry module ZIP. No additional module,
container, VM/LXC, OS service, subscription, telemetry or core patch is required.
The user reports successful v0.5.0 publication/install/activation and window rendering;
this revision's live MA/Foundry audio is not verified.
## Connection and catalog
`connection-wizard.mjs` mounts into the GM ApplicationV2 setup. It collects the MA
origin, private access token, exact dedicated receiver name, existing private
identity/pairing backup and ownership/logging/playback acknowledgments. There are
no credential-bearing world settings, localStorage entries, URLs or logs. The private
connection profile lives in module closure memory until disconnect/reload. A trusted
GM can inspect their own browser memory; all same-origin code must be trusted.
The pinned SDK derives the one known receiver ID from the imported X25519 private
identity. The wizard queries only `players/get` for that ID, checks the exact name
and Sendspin provider, then validates standalone topology with the shared MA client.
It never enumerates household players or registers a new receiver. The selector
contains only this verified imported receiver; import a different authorized backup
to select a different dedicated receiver. Selection alone grants no household control.
Read-only setup allows the existing receiver to be unavailable during handover; writes
still require an available/enabled standalone target with its own active queue.
A fixed `providers` read filtered to music supplies account-authorized provider IDs.
The existing bounded catalog reader paginates library playlists/radios, validates
provider mappings and returns opaque HMAC references and display names. Normal
selectors show playlists; radio and synthetic transport remain outside normal setup.
Catalog keys derive from the private identity and world ID, so reconnecting with the
same identity/world preserves selections. A full legacy profile can retain its
catalogKey/namespace. Saved references never contain upstream URIs or credentials.
The `/ws` API uses first-message token authentication and bounded correlated responses;
`/sendspin` uses first-message authentication followed by official SDK Noise transport.
No HTTP CORS dependency or arbitrary MA proxy is introduced. The SDK/dependency
versions, hashes and licenses remain unchanged from v0.5.0. No upstream install hooks.
## Audio and automatic listeners
```mermaid
flowchart LR
C[Scene and combat controller] --> N[Owned Foundry playlists]
C --> G[Guarded provider in GM browser]
G -->|Private authenticated WSS| MA[Music Assistant]
MA -->|Authenticated Sendspin| S[GM SDK and Web Audio]
S -->|DTLS SRTP audio| P[Active player browsers]
U[Permission controlled User public keys] --> E[Encrypted invitation bootstrap]
E --> P
S <-->|Encrypted bounded SDP via Foundry module socket| P
```
At ready each client generates a memory-only non-extractable P-256 private key and
publishes only its public key and random epoch to its own User document flag.
Foundry's server-enforced User update permissions are the authentication boundary;
socket `from`/`isGM` claims alone are never trusted. The single active GM derives an
AES-GCM key by ECDH with the intended active non-GM's current document public key.
Only an encrypted expiring audio invitation is broadcast, bound to world, sender,
recipient and both epochs. Players authenticate against the current active GM's
User public key. Tampering, unknown fields, replay, wrong world/recipient/epoch,
expired capability and role changes fail closed. Document permission behavior must
also be checked with distinct users in real Foundry before live acceptance.
The invitation contains a unique per-peer 256-bit capability, never MA credentials,
SDK keys or endpoint. The existing SignalCodec then encrypts/authenticates bounded
SDP/ICE/DTLS signaling with session/peer/direction/sequence/expiry binding. Audio uses
WebRTC audio tracks, never PCM over Foundry sockets. No microphone, video or data
channel. Up to eight peers; fresh invites replace each user's prior peer. Invitations
last 30 minutes and renew after 20 minutes; failed peers are retried on the 15-second
reconciliation timer. New logins/key epochs trigger delivery. Default ICE servers
are empty. Optional private backup `listenerNetwork` holds explicit ICE settings.
The listener automatically negotiates and attempts playback. If autoplay is denied,
Campaign audio → Enable Audio uses a direct click. Stop Audio opts out until Enable
Audio. The same HTMLAudioElement survives normal renewals. Latest tab publishing a
User key receives subsequent invitations; use one audio tab per account. Reloads,
network failures, browser suspends and relay expiry can require reconnecting.
The GM also hears decoded audio and can resume their AudioContext through the UI.
## Policy, authority and fallback
Manual override/silence > explicit eligible boss > started scene combat > scene
ambient > world default > silence. Scene/world flags and module settings persist
ambient/combat/boss/native fallback references. Legacy assignments and native ownership
remain supported. Effects and AmbientSound documents are outside the owned music set.
Bosses use explicit module flags, not system actor schemas. Boss/manual controls are
in a disclosure; companion/synthetic/manual capability tools require advanced development.
Explicit catalog playback opt-in enables registered static catalog playlists through
the existing serialized guarded provider. Dynamic/shuffled/autoplay/overlay/ended or
nonstandard speed states remain unsupported. Every mutation checks campaign/session/
generation, current authority, exact target/name/provider, standalone topology and own
active queue. Startup requires an empty idle queue. Signed five-minute snapshots retain
ordered duplicates, index, whole-second position, pause/state and repeat. Ambiguous
writes latch closed; no blind retry or arbitrary queue transfer/group/global stop.
Native fallback uses only explicitly owned Foundry playlists and does not reconcile
an uncertain active MA target automatically.
A single active GM plus same-origin Web Lock excludes common duplicate GM tabs.
This is not a distributed MA server-side fence. Foundry disconnect/GM role loss ends
forwarding and writes; it does not guarantee crash restoration. No seamless GM
handover, long-run drift/synchronization guarantee, crossfade or simultaneous layers.
The optional companion remains in gateway/ as development source. No host worker or
TLS route is installed; any production change requires separate authorization.
## Evidence
Offline tests and a Chromium DOM fixture cover this revision. Historical
`evidence/browser-audio.json` measured two local synthetic listeners using the official
PCM decoder, Web Audio and WebRTC: signal at 1.757 s, about 42.3 kbit/s aggregate RTP.
It was not Foundry, real MA, WAN, audibility or synchronization verification. Prior
read-only catalog/target checks and idle queue controls remain separate evidence.
No new credential use, receiver registration, production connection or playback
mutation was performed for v0.6.0. See TESTING.md for remaining acceptance gates.
+50
View File
@@ -0,0 +1,50 @@
# Changelog
## 0.6.0 — GM connection interface
- Add a GM Music Assistant connection wizard: private server/token entry, existing
receiver backup import, dedicated target verification, catalog loading, audio
connection and actionable diagnostics. Credentials remain in GM tab memory.
- Enable explicitly authorized catalog playlist playback through the existing guarded
provider. Keep native ownership, ambient/combat/boss assignments and fallback.
- Automatically deliver encrypted listener invitations using ephemeral ECDH keys
bound to Foundry User documents; players normally need only Enable Audio.
- Hide optional companion and synthetic/manual test controls behind a client-scoped
advanced development setting. Simplify the primary setup and listener windows.
- Document trusted HTTPS/WSS, logging, identity/pairing, browser activation and ICE
requirements without bypasses or additional mandatory infrastructure.
- User reports v0.5.0 published/installed/activated on Foundry v14.371 and D&D 5e
6.1.2 with both windows rendering. v0.6.0 live Foundry/MA audio remains unverified.
## 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.
+184
View File
@@ -0,0 +1,184 @@
# Adaptive Music 0.6.0 — setup and manual publication
One Foundry module ZIP, ID **adaptive-music**, author **CheddahBoxMB**, targeting
Foundry v14.371 and MA 2.10.6. No other Foundry modules, Docker containers, VMs/LXCs
or mandatory services. Native music can be configured without Music Assistant.
The user reports v0.5.0 installed/activated with D&D 5e 6.1.2 and both windows
rendering. v0.6.0 has offline/fixture validation; live MA audio remains to be tested.
## GM setup
Open Settings → Adaptive Music setup → Configure music.
1. Enter the **Music Assistant server address**, using a trusted private HTTPS origin
such as `https://ma.example.test` (placeholder). Use the server origin without a
subpath, query, username or password. The browser uses `wss://…/ws` for control
and `wss://…/sendspin` for receiver audio. It does not use cross-origin HTTP `/api`.
2. Enter a **private GM access token** from an MA account authorized for the dedicated
campaign receiver and music providers. Never give this token to players. It remains
only in this GM tab's memory and is cleared from the input after testing.
3. Import the **existing dedicated receiver's private identity/pairing backup** as JSON
and enter its exact MA player name (default: Adaptive Music DEV). A flat Sendspin
storage map or an existing full private GM profile containing `identityStorage`
is accepted, up to 64 KiB. The map must include `sendspin-identity-sk` and the
associated `sendspin-*` pairing/trust records from that receiver's SDK storage.
Keep the complete backup private; never put it in Foundry settings, module files,
chat or a release. Development backups belong in ignored `.local/`, mode 0600.
4. Confirm dedicated campaign ownership and that MA **VERBOSE raw WebSocket frame
logging is disabled**. The pinned MA source can log token-bearing auth frames
at that level. Review this before connecting; the wizard cannot check remote logs.
5. Optionally allow **catalog playlist playback**. Test connection and load playlists
performs read-only authentication/target/provider/catalog checks, with no queue
mutations. The player selector contains only the receiver verified from the
imported private identity. To select another owned receiver, import its matching
backup and name. Household speakers are never enumerated or selected.
6. Stop the original web receiver before handover. Reconcile the dedicated queue to
**empty and idle** in MA. Select **Connect audio** to start the GM SDK receiver.
If time sync/Noise pairing cannot complete, the operation fails closed. Keep one
active GM and one GM host tab. The GM hears receiver audio; Enable GM audio resumes
the context if the browser suspends it.
7. Select dedicated **Foundry music and fallback** playlists, save ownership and reload
if ownership changed. Reconnect MA after reload. Choose world defaults and a scene's
**ambient playlist**, **combat playlist** and optional Foundry fallback. Save assignments.
Boss and manual controls are in their disclosure. Enable music automation when ready.
The module cannot reconstruct a receiver identity from a player name/ID or MA token.
It deliberately does not create/register a new receiver. If you have no matching
private SDK backup, MA audio cannot start; native playback still works. Obtain an
authorized backup from the existing dedicated web receiver's operator. The backup
must come from the SDK/browser instance that owns that receiver, not a server API
player export. No generic export feature or production provisioning is assumed.
Malformed/mismatched identities fail before a receiver connection. Existing pairing
trust must match the MA server; this wizard does not silently enable unpaired access.
Profiles from v0.5.0 may include catalogKey/namespace to preserve legacy opaque IDs.
Otherwise IDs derive consistently from the imported private identity and world ID.
Scene assignments persist across reconnect/reload and display a saved unavailable
choice while offline. Re-enter GM authentication/import the same backup after reload.
Disconnect clears the private profile, stops automation/forwarding and leaves MA queue
state for review; it does not promise automatic restoration after a crash or disconnect.
## Players
Players need no MA login, address, receiver identity or pasted invitation. Active
non-GM accounts publish only an ephemeral public key through their own Foundry User
document. The connected GM automatically sends individually encrypted expiring audio
invitations, then WebRTC negotiates audio. If sound is blocked by autoplay, open
Settings → Campaign audio → **Enable Audio** once. Stop Audio opts out until enabled
again. No microphone permission is requested. Use one listening tab per account.
Native Foundry playback uses Foundry's existing browser audio controls.
Invitation renewal and new player logins are automatic while the GM stays online.
The default supports up to eight listeners and uses no external STUN/TURN. A network
failure, suspended browser or expired relay credential may need reconnecting. GM loss
stops forwarding; seamless failover, crash restore and exact listener synchronization
are not promised. Client key/permission/socket behavior still needs live v14 acceptance.
## HTTPS/WSS requirements and diagnostics
| Path | Requirement |
| --- | --- |
| Remote browser → Foundry | Trusted HTTPS and working Foundry socket. Web Crypto/Web Locks need a secure context. |
| GM browser → MA control | Trusted private HTTPS origin with WSS upgrade on `/ws`; first-message token auth. |
| GM browser → receiver | Same origin's WSS `/sendspin` route, first-message auth and SDK pairing/trust. |
| Player → MA | No route or credential required. Players talk only to Foundry and the GM's WebRTC peer. |
| GM ↔ player media | A viable WebRTC ICE path; restrictive NAT/firewalls may require an existing approved TURN relay. |
HTTPS Foundry cannot use plain HTTP/ws MA in the supported configuration, even if
Sendspin encrypts its payload. The module rejects this, including loopback downgrade.
Remote plain HTTP Foundry is also rejected for GM MA connections. Loopback HTTP is
reserved for offline development, not a remote deployment solution. Browser exceptions
are not a supported workaround. Do not enable insecure content, disable certificate
checks or Web security, or expose an unrestricted MA proxy publicly.
A valid solution uses an **existing private trusted TLS endpoint** reachable from the
GM browser: MA's supported TLS endpoint if already available, or an operator-approved
TLS virtual host on existing infrastructure forwarding the authenticated `/ws` and
`/sendspin` WebSocket routes to the private MA service. Preserve upgrade headers,
Origin and MA authentication; use browser-trusted certificates and private access
control. Both routes must work, not just the MA homepage. The origin is dedicated
because the current client resolves routes from `/`; subpath deployments are unsupported.
No route, certificate, Nginx, firewall or service configuration was changed here.
The user's actual HTTP MA endpoint remains blocked until this TLS prerequisite is
satisfied. There is no release-only JavaScript fix for an unreachable/insecure endpoint.
Foundry CSP `connect-src` must permit that private WSS origin. MA/reverse proxy must
accept the Foundry browser Origin without stripping authentication. Browser local-network
permission, private DNS/VPN/routing and certificate trust are separate checks; enabling
CORS on `/api` alone does not solve WSS. Browser WebSocket errors intentionally reveal
little. Diagnostics describe likely causes without logging raw upstream responses/tokens.
Inspect browser network status privately if required; never share token-bearing frames.
For WAN ICE, a full private backup may include `listenerNetwork` with `iceServers`
and optional `relayOnly: true`. Use only an existing approved STUN/TURN endpoint and
short-lived TURN username/credential/`expires` (Unix milliseconds, at most one hour).
No silent public relay is configured. Relay-only needs TURN. Renew expired relay
credentials by disconnecting and importing an updated private profile. No additional
service, container, VM or machine is installed. Without a viable ICE path, automatic
setup cannot make audio reach a remote browser.
| Diagnostic | Action |
| --- | --- |
| Mixed content / insecure context | Supply trusted HTTPS/WSS; do not bypass browser protections. |
| Identity required / mismatch | Import the matching dedicated SDK identity and pairing backup. |
| Dedicated target denied | Check exact name, account target permission and standalone topology. |
| Reconciliation required | Empty/idle the dedicated queue and stop its other web receiver before handover. |
| No catalog providers/items | Check account provider scopes, library contents and provider availability. |
| WSS unavailable | Check TLS trust, both upgrade routes, Origin/CSP, token and private connectivity. |
| Connected but silent | Check MA playback, mute/volume, GM context, player Enable Audio and ICE connectivity. |
| Authority changed | Use one active GM; stop automation and explicitly reconnect. |
Reference: [MDN mixed content](https://developer.mozilla.org/en-US/docs/Web/Security/Defenses/Mixed_content),
[Web Audio practices](https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API/Best_practices),
[WebRTC connectivity](https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Connectivity),
[Foundry v14 User documents](https://foundryvtt.com/api/v14/classes/foundry.documents.User.html).
Pinned MA/SDK source provenance is in `evidence/upstream.json` and `vendor/provenance.json`.
The network arrangement above is a deployment requirement, not verified connectivity
or authorization to change production. Any such change needs separate concrete review.
## Advanced development
Settings → Show advanced development controls (client setting, defaults off) reveals
optional companion controller/synthetic test controls and manual listener capability
entry. These are not required for normal operation. Companion source remains in
`gateway/`; no companion or co-located worker is installed or started by the module.
## Build and publish manually to the existing Gitea
The repository and v0.5.0 publication are user-reported. This work did not access,
authenticate to, push to or verify the Git server. Existing manifest URL is preserved.
```sh
python3 scripts/release.py
python3 scripts/release.py --validate dist/releases/v0.6.0/adaptive-music.zip
```
Output `dist/releases/v0.6.0/adaptive-music-release-v0.6.0.zip` contains installable
`adaptive-music.zip`, standalone `module.json`, complete `adaptive-music-source.zip`,
docs, notices/licenses, release metadata and SHA256SUMS. An adjacent `.sha256` checks
the outer bundle. Source metadata identifies the base commit; the included source
archive and its digest identify the actual release sources, including current edits.
Packaging is offline, requires no credentials and never contacts the Git server.
1. Back up the world and existing module. Review CHANGELOG and remaining acceptance
limits. Unpack the outer bundle locally; check SHA256SUMS.
2. Import the **source archive contents** through your normal Gitea/local Git workflow,
preserving directories/notices. Do not upload `.local/`, credentials, node_modules
or deployment files. Prepare on a release branch; keep the old main manifest until
the new versioned asset is available.
3. Create immutable tag/release **v0.6.0** in your existing repository. Upload
**adaptive-music.zip** and **module.json** with those exact attachment names.
The source archive, checksums and outer bundle can be extra review artifacts.
4. Confirm the ZIP is anonymously downloadable with the expected checksum at:
`https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/releases/download/v0.6.0/adaptive-music.zip`
5. Promote the generated standalone manifest to **main/module.json** only after the
attachment exists. Preserve the existing stable install/update URL:
`https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/raw/branch/main/module.json`
6. Use Foundry Setup → Update Modules, then activate in an isolated v14.371 world
and follow TESTING.md. Do not use the source/outer ZIP as Foundry's module download.
No `compatibility.verified` claim is added based on offline checks or v0.5.0 rendering.
Repository base can be changed offline with `--repository https://github.com/OWNER/REPOSITORY`
and a separate `--output dist/alternate-release`. No URL in this guide was contacted
by this build. No automatic publication or production deployment is performed.
+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.
+59
View File
@@ -0,0 +1,59 @@
# Adaptive Music progress — 0.6.0
The user reports v0.5.0 published to their existing Gitea, installed through the manifest,
activated on Foundry v14.371 with D&D 5e 6.1.2, and configuration/listener windows rendering.
That supersedes the previous unknown publication/install status for v0.5.0 only. This
work did not access the Git server, use MA credentials or change production services.
## Implemented for v0.6.0
- Three-step GM connection wizard: private server/token, dedicated existing receiver
backup/name and ownership/logging/playback acknowledgments, read-only target/catalog
check, verified receiver selection, Connect audio, resume/disconnect and diagnostics.
- Existing official Sendspin/Web Audio/WebRTC host integrated with the UI. GM hears
receiver audio; explicitly authorized static catalog playlists are eligible through
the existing guarded serialized provider, rather than only synthetic sequences.
- Automatic encrypted listener bootstrap with memory-only P-256 private keys, public
keys on permission-controlled User documents, AES-GCM invitation delivery bound to
world/account/epochs, and existing per-peer encrypted SDP. No credential/address/SDK
identity goes to players. Default eight peers, 30-minute invites renewed after 20
minutes, retries/reconciliation every 15 seconds while GM host is online.
- Player interface normally needs only Enable Audio when browser activation is required.
No pasted code or MA login. Native playback/fallback, persistent scene ambient/combat/
boss references, world defaults and explicit playlist ownership remain intact.
- Companion/synthetic/manual capability controls hidden behind a client-scoped advanced
development setting. World defaults and boss/manual controls use disclosures.
- Offline manual release v0.6.0: one installable ZIP, stable existing manifest URL,
immutable version-specific download, complete source, docs/licenses and checksums.
No new dependencies, mandatory services/containers, core patches or browser bypass.
## Verification and unresolved prerequisites
91 JavaScript and 15 Python regressions, privacy/attribution audit and pinned upstream
verification are recorded in `evidence/v0.6.0-checks.txt`. A Chromium 143.0.7499.4 DOM
fixture verifies the wizard, catalog selection/save, private field clearing, hidden
advanced controls and listener activation. These are offline fixtures, not live
Foundry/MA playback or network verification. Historical decoder/WebRTC synthetic
measurements and live idle/read-only MA evidence remain separately identified.
The actual private MA deployment still needs browser-trusted HTTPS/WSS for both `/ws`
and `/sendspin`; the previous HTTP endpoint is unsupported from HTTPS Foundry. INSTALL.md
now explains TLS, private routing, Origin/CSP and ICE requirements. No JavaScript-only
workaround can replace a secure reachable endpoint. No route, logging or certificate
configuration was inspected or changed. A matching existing SDK identity/pairing backup
is also required; no receiver was registered or commandeered. GM authentication is
memory-only and must be entered after reload. A private legacy catalog key/namespace
can be imported to preserve old IDs.
Remaining live acceptance includes v0.6.0 ApplicationV2/SceneConfig behavior, Foundry
User document permission enforcement/socket signaling with distinct users, MA pairing/
time sync and audible real playlist playback, nonempty interruption/restore, normal
one-click audio activation across browsers, renewal/reconnect and WAN/NAT/TURN paths.
The user must separately authorize credentials/production changes. No such action
was taken. TESTING.md gives isolated acceptance steps and exact limits.
Browser-only authority still uses a single active GM and same-origin Web Lock, not a
distributed server fence. GM loss/crash cannot guarantee restoration or continuity.
Crossfade, independent simultaneous layers and synchronization/drift guarantees remain
unimplemented/unverified. Optional companion source is preserved in gateway/ and the
historical experimental branch; no infrastructure is deployed or mandatory.
+45 -1
View File
@@ -1,2 +1,46 @@
# adaptive-music # Adaptive Music — 0.6.0
Independent open-source project by **CheddahBoxMB**, targeting Foundry VTT
**v14.371** and Music Assistant **2.10.6**. System-independent; no other modules,
containers, VMs/LXCs or mandatory services. Install the single Foundry module ZIP.
GM setup now includes a Music Assistant connection wizard, private GM authentication,
existing dedicated receiver selection by identity backup, catalog-backed playlist
selectors, audio connection and diagnostics. World defaults and separate scene
ambient/combat/boss/Foundry fallback selections persist in Foundry. Native effects
and AmbientSound documents remain untouched. Automation defaults off.
The GM browser hosts the bundled official Sendspin SDK, decodes PCM with Web Audio,
and sends audio to authorized active players over WebRTC. Players connect automatically
and may need one **Enable Audio** click. Neither MA credentials nor its address are
sent to players. Private credentials and receiver identity stay in GM tab memory;
reloading the GM tab requires reconnecting. All code running in the GM browser origin
must be trusted. Optional companion controls are hidden under advanced development.
MA needs trusted private HTTPS/WSS reachable by the GM, an existing dedicated receiver
identity/pairing backup, account permissions and authentication-log review. This release
does not create a receiver or change any service/network configuration. WAN audio may
need an already available approved TURN relay. No browser bypasses, public MA proxy,
new service or guaranteed synchronization is provided. See [INSTALL.md](INSTALL.md).
The user reports v0.5.0 published to their existing Gitea, installed/activated in
Foundry v14.371 with D&D 5e 6.1.2, and both windows rendering. This is user-supplied
installation evidence, not a claim of MA playback. v0.6.0 is checked with offline
regressions and a Chromium UI fixture; live Foundry/MA audio and WAN acceptance remain
pending. Earlier synthetic browser measurements are recorded separately.
Build without contacting a Git server:
```sh
python3 scripts/release.py
python3 scripts/release.py --validate dist/releases/v0.6.0/adaptive-music.zip
```
Manual upload bundle: `dist/releases/v0.6.0/adaptive-music-release-v0.6.0.zip`.
It includes the installable module, standalone manifest, complete source archive,
documentation, licenses and checksums. [INSTALL.md](INSTALL.md) explains manual
publication to the existing Gitea. No Git server was accessed by this work.
MIT project license. Upstream MIT/Apache notices and licenses remain in
`THIRD-PARTY-NOTICES` and `licenses/`. See [TESTING.md](TESTING.md),
[PROGRESS.md](PROGRESS.md), [ARCHITECTURE.md](ARCHITECTURE.md) and [SECURITY.md](SECURITY.md).
+85
View File
@@ -0,0 +1,85 @@
# Adaptive Music security — 0.6.0
## Private GM connection
MA endpoint, access token, receiver private identity, pairing records and provider
configuration stay in the GM tab's closure memory. They are never registered as
Foundry settings, saved to document flags/localStorage, sent in module sockets,
embedded in URLs, logged or shipped. Closing/reloading requires private re-entry.
The user supplies a local identity backup; development/private copies belong under
ignored `.local/` (directory 0700, regular secret files 0600). No private configuration
or deployment files are included in releases. No credential was used in this work.
GM browser users, debuggers and code executing in that origin can inspect the GM's
secrets. Trust Foundry and every enabled module. This architecture cannot hide tokens
from the GM, same-origin compromise or the host administrator. Players receive only
scoped encrypted audio invitations, never an MA credential, endpoint or SDK identity.
Use a restricted MA account scoped to the dedicated target and authorized music
providers; application-side filtering is defense in depth, not an account restriction.
MA 2.10.6's inspected WebSocket handler logs received raw frames at VERBOSE, including
authentication. Before token-bearing connections the GM must confirm raw-frame
logging is disabled. The wizard cannot verify or redact remote logs and does not
change logging configuration. No live WebSocket token test was performed here.
## Transport and authorization
Use trusted HTTPS for remote Foundry and trusted HTTPS/WSS for private GM-to-MA
access. HTTPS → HTTP/ws is rejected, including loopback downgrade. Plain remote
Foundry HTTP is rejected for GM MA access. CORS exceptions, encrypted Sendspin payloads
and browser local-network permissions do not replace TLS, CSP or Origin policy.
Never disable mixed-content protection, certificate validation, Web security or MA
authentication. No public/unrestricted MA HTTP/WS/Sendspin proxy is provided.
Private imported X25519 identity determines one existing receiver ID. Exact name,
Sendspin provider, enabled/available state, standalone topology and own active queue
are rechecked before each write. There is no household discovery/select list, queue
transfer, speaker grouping, global stop or automatic receiver registration. Setup
reads can inspect that known target while unavailable during handover; mutation
guards are not relaxed. Catalog playback requires explicit GM opt-in and uses only
registered static playlist media from approved music providers.
Automatic listeners use public ephemeral P-256 keys in User flags and private keys
in memory. User document permissions, enforced by Foundry's server, bind public keys
to accounts. Server/admin/GM and own-browser trust remain necessary. No MA secrets
or listener capabilities are stored in those flags. A fixed encrypted invitation
bootstrap authenticates both document keys, binds world/epochs/recipient and limits
size/concurrent decrypts/replay. Only one active GM and active non-GM participants
are eligible. Server User permission enforcement is a real-Foundry acceptance gate,
not proven by fixtures. Do not use this scheme with a modified server that permits
players to edit another account's User flags or GM role.
Capabilities are individual and expire after at most 30 minutes. SDP/ICE is protected
by the existing AES-GCM SignalCodec with session/peer/sequence/direction binding.
No raw continuous audio, token, upstream URL or queue data goes over module sockets.
Audio uses DTLS-SRTP. No microphone/video/control data channel. Role loss, disconnect,
revocation and expiry tear down peers. A recipient can forward its own capability
or record received audio; browser code cannot prevent that. Authorized direct peers
may learn each other's network addresses. Relay-only mode reduces direct candidate
exposure when a suitable existing TURN service is configured.
No silent public STUN/TURN. TURN credentials must expire within an hour; expired
credentials require renewed operator configuration. No service is provisioned.
Foundry socket flooding remains an availability concern even though bounded queues,
strict envelopes and decrypt limits prevent unbounded application work.
## Authority, recovery and distribution
Transitions remain serialized and generation checked with signed, campaign/session/
fence-scoped snapshots. Uncertain writes latch closed. Browser Web Locks and a
single active GM are not a server-side distributed fence. Crashes/offline browsers
cannot guarantee MA restore; no automatic split-brain handover or durable recovery.
Native fallback cannot silently resolve an uncertain active remote queue. Effects
and AmbientSound remain unowned. No production service/network version is changed.
The optional companion source and manual test transports remain advanced development
features. No additional service/container is mandatory or installed. Production routes,
logging changes or credential use require separate explicit authorization.
Release generation is offline and checks browser import closure, manifests, SDK hash,
notices/licenses, deterministic packaging and private-file patterns. Included source
archive represents this revision, including uncommitted edits; metadata names the base
Git revision and source archive digest. These checks supplement, rather than replace,
secret review. Official SDK 5.0.0, noble dependencies and notices remain pinned; no
new dependencies, runtime CDN, upstream install hooks or telemetry. PCM-only vendor
build omits optional Opus fallback binaries. No Git server was contacted or published to.
+1
View File
@@ -0,0 +1 @@
1ccdd229e40e1e02f0fa76d8fc553877c66c9494
+96
View File
@@ -0,0 +1,96 @@
# Adaptive Music verification — 0.6.0
## Offline regression and packaging
Use pinned Node 24.23.0 and Python standard library:
```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
PLAYWRIGHT_BROWSERS_PATH=.local/browsers node scripts/check_setup_browser.mjs
python3 scripts/release.py
python3 scripts/release.py --validate dist/releases/v0.6.0/adaptive-music.zip
```
The v0.6.0 suite contains 91 JavaScript tests and 15 Python tests. See
`evidence/v0.6.0-checks.txt` for executed results. Loopback fixture servers and headless
Chromium need permission to bind/launch in restricted environments. No production
endpoint, credential or Git server is needed. Upstream verification reads ignored
pinned local research copies; it does not fetch/install them.
New regressions cover private wizard input clearing, catalog-to-scene ambient/combat
persistence, normal listener activation without token/code fields, identity-bound
player lookup, stable catalog IDs, explicitly enabled playlist support, canceled
startup, and encrypted bootstrap tampering/replay/rotation/role/expiry rejection.
Existing controller, native restoration/fallback, signed snapshots, queue/topology,
companion, WebSocket correlation and distribution regressions remain.
`check_setup_browser.mjs` actually renders the setup/listener DOM in Chromium
143.0.7499.4 using fake Foundry documents and a fake connection. It clicks the wizard,
connects the fixture, loads/chooses/saves ambient and combat choices, confirms the
private input clears, advanced controls are absent, and player activation works.
A preview is written under ignored `dist/previews/`. This is an offline UI check,
not an actual Foundry ApplicationV2 host or an MA connection/audio test. The development
browser runs with `--no-sandbox` for the local test environment only; the module never
sets browser flags or requires users to bypass browser security.
Python tests check repeatable complete ZIPs, manifest/import/assets closure, attribution,
privacy patterns, checksums and rebuilding source without Git metadata. Builder
validation does not prove URL availability. No additional dependency was introduced;
SDK/browser assets remain prebuilt/pinned. Rebuilding them, when needed, uses
`npm ci --ignore-scripts` and `node scripts/build_sendspin.mjs`. The earlier zero-advisory
audit is historical, not a new online audit or a security guarantee for this revision.
## User report and historical evidence
The user reports v0.5.0 successfully published to existing Gitea, installed through
the manifest, activated on Foundry v14.371 with D&D 5e 6.1.2, and both windows rendering.
This is explicitly user-supplied evidence for that version. No v0.6.0 live install,
MA authentication, receiver handshake or playlist playback was performed here.
Historical `evidence/browser-audio.json`: actual Chromium official Sendspin decoder
→ Web Audio → WebRTC → two listeners, original synthetic 440 Hz PCM, signal at 1.757 s,
RMS about 0.054, 42.3 kbit/s aggregate RTP over 4.766 s. Localhost socket shim, no
real Foundry or MA/Noise handshake, no WAN, skew/drift or hardware audibility result.
Historical MA read-only catalogs/target checks and bounded idle controls are retained;
those live controls restored an empty idle queue. Synthetic URI ingestion previously
failed; no real MA music audio or nonempty live queue restore is established.
## Remaining isolated live acceptance
1. Install/update the v0.6.0 ZIP in an isolated Foundry v14.371 world. Test the actual
ApplicationV2 windows and SceneConfig hooks. Save world/scene ambient and combat,
reload, reconnect with the same identity, verify references remain selected. Test
native ownership, boss/manual rules, rapid transitions, native snapshot/restoration,
fallback, and confirm AmbientSound/effects are untouched. No system dependency.
2. With separate explicit credential authorization, supply trusted private MA HTTPS/WSS,
an existing matching dedicated SDK identity/pairing backup and remote log review.
Check read-only target/catalog diagnostics first; confirm no household enumeration
or unintended target selection. Confirm token/endpoint/SDK secrets never appear in
player settings/documents/socket/network/logs or release artifacts.
3. Test server-enforced User flags with two distinct logged-in players: each can update
only its own key, cannot change another player's or GM's key/role, and forged socket
sender IDs do not authorize audio. Test banned/inactive/promoted users, multiple GMs,
key rotation/new login, renewal, revoke, disconnect and latest-tab behavior. Fixtures
validate cryptography, not production Foundry server permissions.
4. Before writes, capture dedicated target state, arrange an empty idle handover and
approved test content. Opt in catalog playback, connect SDK and verify pairing/time
sync and audible GM/player output. Exercise ambient → combat → boss → restore,
offsets, duplicate occurrences and pause/repeat. Capture original state and report
restoration failures explicitly. Real playlists need operator-approved content;
packaging authorization is not approval to play production content in this session.
5. Test automatic listener delivery and one Enable Audio click in supported Chrome,
Firefox and Safari configurations; background/suspend/reload behavior may vary.
Check audio after renewal, Stop/Enable and disconnect. Only Chromium DOM fixtures
ran here. GM audio/stream drift and true synchronization are unmeasured.
6. Test real remote networks with an explicitly approved existing relay if necessary.
Measure ICE success, RTT/jitter/loss, upload, latency/skew and 30-minute drift. Default
ICE has no public relay. Expired TURN credentials need operator renewal. Do not infer
WAN acceptance from loopback synthetic audio.
No production route, logging, Nginx/firewall/service version or Foundry/MA installation
was changed. Browser-only distributed fencing, durable crash restore, seamless GM
handover, crossfade and concurrent layers remain unsupported. Live acceptance is
pending; neither fixture tests nor the user's v0.5.0 rendering report waive it.
+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"
}
+72
View File
@@ -0,0 +1,72 @@
{
"version": "0.6.0",
"scope": "offline regressions, actual Chromium DOM fixture, pinned-source and package checks; no v0.6.0 live Foundry/MA verification",
"connection_configuration": "three-step GM wizard; memory-only endpoint/token/identity; imported existing dedicated receiver only",
"catalog_and_assignments": "connected catalog playlists, explicit playback opt-in and persistent scene ambient/combat/boss/native fallback and world defaults",
"audio": "existing official Sendspin GM host integrated; automatic individually encrypted WebRTC listener invitations; browser activation when required",
"bootstrap": "ephemeral ECDH P-256 keys bound to permission-controlled Foundry User documents; AES-GCM encrypted capabilities; live server permissions remain an acceptance gate",
"companion": "hidden by default; client-scoped advanced development setting; no mandatory service",
"https_wss": "trusted private MA origin with /ws and /sendspin WSS required from HTTPS Foundry; no mixed-content or certificate bypass; deployment untouched",
"distribution": "one installable module ZIP plus complete offline manual publication bundle, sources, docs, licenses and checksums",
"regression": {
"javascript": 91,
"python": 15,
"passed": true
},
"browser_ui": {
"browser": "Chromium 143.0.7499.4",
"passed": true,
"scope": "fake Foundry documents and fake connection; no MA or actual Foundry",
"pageErrors": []
},
"user_report": {
"version": "0.5.0",
"giteaPublished": true,
"manifestInstalled": true,
"foundry": "14.371",
"system": "D&D 5e 6.1.2",
"activated": true,
"configurationAndListenerWindowsRender": true,
"source": "user report; not independently accessed"
},
"ma_mutations_this_revision": 0,
"credential_use_this_revision": false,
"gitea_contacted": false,
"production_changes": false,
"v060_live_audio_verified": false,
"remaining_acceptance": [
"real Foundry v14.371 ApplicationV2 and User permissions",
"trusted private MA HTTPS/WSS",
"matching dedicated Sendspin identity/pairing backup",
"authentication logging review",
"authorized audible catalog playback and nonempty restore",
"autoplay/renewal/reconnect across browsers",
"WAN ICE/TURN and drift"
],
"history": [
{
"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"
}
]
}
+29
View File
@@ -0,0 +1,29 @@
Adaptive Music v0.6.0 validation — 2026-12-03
/home/ubuntu/.nvm/versions/node/v24.23.0/bin/node --test --test-reporter=tap tests/js/*.test.mjs
PASS: 91 tests, 0 failed, 0 skipped. Full output: v0.6.0-js-tests.txt.
Temporary loopback fixture servers required execution outside the restricted sandbox.
python3 -m unittest discover -s tests -v
PASS: 15 tests, 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.
Read local pinned research checkouts; did not fetch or install dependencies.
git diff --check
PASS: no whitespace errors.
PLAYWRIGHT_BROWSERS_PATH=.local/browsers node scripts/check_setup_browser.mjs
PASS: Chromium 143.0.7499.4 actual DOM fixture; wizard render/steps,
private field clearing, catalog selectors, scene ambient/combat save,
hidden advanced controls, listener activation; no page errors.
Temporary loopback HTTP and headless browser; fixture documents/connection only.
No v0.6.0 live Foundry or MA connection/playback, no production credential use,
no Git server access, and no production service/network changes.
User-reported v0.5.0 publication/install/window rendering is recorded separately.
Release import/manifest/license/privacy/checksum validation is performed by release.py.
+556
View File
@@ -0,0 +1,556 @@
TAP version 13
# Subtest: automatic invitations use document-bound ephemeral keys and never broadcast the capability
ok 1 - automatic invitations use document-bound ephemeral keys and never broadcast the capability
---
duration_ms: 11.117677
type: 'test'
...
# Subtest: forged GM claims, recipient changes, tampering and rotated document keys fail closed
ok 2 - forged GM claims, recipient changes, tampering and rotated document keys fail closed
---
duration_ms: 2.082811
type: 'test'
...
# Subtest: parallel bootstrap replay, multiple GMs, revoked roles and expired capabilities cannot connect
ok 3 - parallel bootstrap replay, multiple GMs, revoked roles and expired capabilities cannot connect
---
duration_ms: 2.475986
type: 'test'
...
# Subtest: catalog paginates, strips private metadata and filters unapproved mappings
ok 4 - catalog paginates, strips private metadata and filters unapproved mappings
---
duration_ms: 32.850148
type: 'test'
...
# Subtest: empty provider allowlist denies without I/O; malformed and endless pages fail
ok 5 - empty provider allowlist denies without I/O; malformed and endless pages fail
---
duration_ms: 18.296825
type: 'test'
...
# Subtest: target validation rejects group, changed identity and unavailable player
ok 6 - target validation rejects group, changed identity and unavailable player
---
duration_ms: 1.442234
type: 'test'
...
# Subtest: synthetic audio isolates simultaneous campaigns and copies every frame
ok 7 - synthetic audio isolates simultaneous campaigns and copies every frame
---
duration_ms: 0.485778
type: 'test'
...
# Subtest: audio denies forged origin/session/role, unknown fields and cross-campaign grants
ok 8 - audio denies forged origin/session/role, unknown fields and cross-campaign grants
---
duration_ms: 0.315819
type: 'test'
...
# Subtest: active listener revocation/expiry and slow-client overflow close handles
ok 9 - active listener revocation/expiry and slow-client overflow close handles
---
duration_ms: 0.506526
type: 'test'
...
# Subtest: synthetic source rejects stale sessions/generations, oversized frames; connections are bounded
ok 10 - synthetic source rejects stale sessions/generations, oversized frames; connections are bounded
---
duration_ms: 0.400789
type: 'test'
...
# Subtest: catalog authorization denies listener and injection before upstream
ok 11 - catalog authorization denies listener and injection before upstream
---
duration_ms: 0.376122
type: 'test'
...
# Subtest: scene/combat configuration preserves independent flags and stores only tagged references
ok 12 - scene/combat configuration preserves independent flags and stores only tagged references
---
duration_ms: 4.695721
type: 'test'
...
# Subtest: role loss, stale selection and arbitrary URL/ID fail before document write
ok 13 - role loss, stale selection and arbitrary URL/ID fail before document write
---
duration_ms: 0.347479
type: 'test'
...
# Subtest: editor uses text for catalog labels and rechecks GM on actual save event
ok 14 - editor uses text for catalog labels and rechecks GM on actual save event
---
duration_ms: 0.372166
type: 'test'
...
# Subtest: configuration hook disposal prevents pending asynchronous render from mounting
ok 15 - configuration hook disposal prevents pending asynchronous render from mounting
---
duration_ms: 0.222887
type: 'test'
...
# Subtest: packaged browser client connects through real loopback companion/MA wire fixtures and restores combat queue
ok 16 - packaged browser client connects through real loopback companion/MA wire fixtures and restores combat queue
---
duration_ms: 94.0349
type: 'test'
...
# Subtest: companion denies listener control, wrong scope/Origin, upstream injection and unknown routes
ok 17 - companion denies listener control, wrong scope/Origin, upstream injection and unknown routes
---
duration_ms: 11.775335
type: 'test'
...
# Subtest: browser accepts only relative same-origin paths and never persists a connection grant
ok 18 - browser accepts only relative same-origin paths and never persists a connection grant
---
duration_ms: 0.275675
type: 'test'
...
# Subtest: companion operation replay is idempotent and same ID with changed payload is denied
ok 19 - companion operation replay is idempotent and same ID with changed payload is denied
---
duration_ms: 12.942194
type: 'test'
...
# Subtest: companion listener stream rejects controller grant and closes on live revocation and expiry
ok 20 - companion listener stream rejects controller grant and closes on live revocation and expiry
---
duration_ms: 92.342037
type: 'test'
...
# Subtest: catalog revocation during upstream I/O suppresses the response at the companion boundary
ok 21 - catalog revocation during upstream I/O suppresses the response at the companion boundary
---
duration_ms: 8.904953
type: 'test'
...
# Subtest: policy precedence and explicit silence
ok 22 - policy precedence and explicit silence
---
duration_ms: 1.199009
type: 'test'
...
# Subtest: inactive, unstarted and other scene combats ignored; boss ties stable
ok 23 - inactive, unstarted and other scene combats ignored; boss ties stable
---
duration_ms: 3.984422
type: 'test'
...
# Subtest: scene -> combat -> boss -> nested manual -> unwind restores offsets, duplicates and pause
ok 24 - scene -> combat -> boss -> nested manual -> unwind restores offsets, duplicates and pause
---
duration_ms: 1.248452
type: 'test'
...
# Subtest: scene change during manual never resurrects previous scene
ok 25 - scene change during manual never resurrects previous scene
---
duration_ms: 0.257202
type: 'test'
...
# Subtest: boss removed during manual and deleted combat cannot return
ok 26 - boss removed during manual and deleted combat cannot return
---
duration_ms: 0.309818
type: 'test'
...
# Subtest: duplicate intent causes zero provider mutations
ok 27 - duplicate intent causes zero provider mutations
---
duration_ms: 0.115966
type: 'test'
...
# Subtest: prepare failure leaves current playback intact
ok 28 - prepare failure leaves current playback intact
---
duration_ms: 0.348671
type: 'test'
...
# Subtest: partial apply failure restores outgoing playback
ok 29 - partial apply failure restores outgoing playback
---
duration_ms: 3.387266
type: 'test'
...
# Subtest: obsolete async resolve is rejected before stop/apply
ok 30 - obsolete async resolve is rejected before stop/apply
---
duration_ms: 0.246049
type: 'test'
...
# Subtest: lease loss during stop prevents apply and stale rollback
ok 31 - lease loss during stop prevents apply and stale rollback
---
duration_ms: 0.785727
type: 'test'
...
# Subtest: provider switch and bounded nested stack
ok 32 - provider switch and bounded nested stack
---
duration_ms: 0.299308
type: 'test'
...
# Subtest: no authority retains playback without provider access
ok 33 - no authority retains playback without provider access
---
duration_ms: 0.104495
type: 'test'
...
# Subtest: queued state is captured at submission rather than read after caller mutation
ok 34 - queued state is captured at submission rather than read after caller mutation
---
duration_ms: 0.070922
type: 'test'
...
# Subtest: supersession after snapshot prevents mutations
ok 35 - supersession after snapshot prevents mutations
---
duration_ms: 0.179354
type: 'test'
...
# Subtest: failed cross-provider apply cleans new owned audio before outgoing restoration
ok 36 - failed cross-provider apply cleans new owned audio before outgoing restoration
---
duration_ms: 0.158736
type: 'test'
...
# Subtest: superseded cross-provider apply is reconciled by stopping partially touched target
ok 37 - superseded cross-provider apply is reconciled by stopping partially touched target
---
duration_ms: 0.161141
type: 'test'
...
# Subtest: extracted companion launches privately with fixture credentials, serves catalog diagnostics and listener PCM
ok 38 - extracted companion launches privately with fixture credentials, serves catalog diagnostics and listener PCM
---
duration_ms: 202.3378
type: 'test'
...
# Subtest: gateway binds target server-side and sanitizes metadata
ok 39 - gateway binds target server-side and sanitizes metadata
---
duration_ms: 1.026207
type: 'test'
...
# Subtest: forged, wrong origin/campaign/session and unknown args deny before upstream
ok 40 - forged, wrong origin/campaign/session and unknown args deny before upstream
---
duration_ms: 0.381642
type: 'test'
...
# Subtest: listener cannot read queues or acquire controller lease
ok 41 - listener cannot read queues or acquire controller lease
---
duration_ms: 0.165018
type: 'test'
...
# Subtest: expiry, revocation, stale fence and replay reject
ok 42 - expiry, revocation, stale fence and replay reject
---
duration_ms: 0.216595
type: 'test'
...
# Subtest: lease cannot be stolen and increases fence after revoke
ok 43 - lease cannot be stolen and increases fence after revoke
---
duration_ms: 0.125214
type: 'test'
...
# Subtest: revocation during upstream I/O suppresses response
ok 44 - revocation during upstream I/O suppresses response
---
duration_ms: 0.132218
type: 'test'
...
# Subtest: MA adapter uses pinned envelope, Bearer header, fixed path, no redirects and returns no metadata
ok 45 - MA adapter uses pinned envelope, Bearer header, fixed path, no redirects and returns no metadata
---
duration_ms: 13.038734
type: 'test'
...
# Subtest: MA mismatched queue, upstream failures and redirects fail with sanitized errors
ok 46 - MA mismatched queue, upstream failures and redirects fail with sanitized errors
---
duration_ms: 1.733057
type: 'test'
...
# Subtest: MA rejects URL credentials, query/fragment, paths and non-HTTP configuration
ok 47 - MA rejects URL credentials, query/fragment, paths and non-HTTP configuration
---
duration_ms: 0.276196
type: 'test'
...
# Subtest: MA read adapter performs real local HTTP POST against an isolated fixture
ok 48 - MA read adapter performs real local HTTP POST against an isolated fixture
---
duration_ms: 16.08324
type: 'test'
...
# Subtest: signaling is confidential, per-listener authenticated, scoped and replay resistant
ok 49 - signaling is confidential, per-listener authenticated, scoped and replay resistant
---
duration_ms: 6.13541
type: 'test'
...
# Subtest: signaling denies expired invitation, unknown/audio message types and unapproved TURN secrets
ok 50 - signaling denies expired invitation, unknown/audio message types and unapproved TURN secrets
---
duration_ms: 3.598632
type: 'test'
...
# Subtest: GM browser policy refuses mixed content and SDK identity mismatch before any MA connection
ok 51 - GM browser policy refuses mixed content and SDK identity mismatch before any MA connection
---
duration_ms: 0.721157
type: 'test'
...
# Subtest: official pinned SDK decodes real binary PCM frames and discards stale generations
ok 52 - official pinned SDK decodes real binary PCM frames and discards stale generations
---
duration_ms: 0.249546
type: 'test'
...
# Subtest: parallel signaling replay cannot pass the asynchronous authentication check twice
ok 53 - parallel signaling replay cannot pass the asynchronous authentication check twice
---
duration_ms: 1.522783
type: 'test'
...
# Subtest: GM API WebSocket adapter authenticates privately, assembles partial results and refuses broad commands
ok 54 - GM API WebSocket adapter authenticates privately, assembles partial results and refuses broad commands
---
duration_ms: 12.304332
type: 'test'
...
# Subtest: peer signaling bounds queued work and rejects expired invites before allocating a connection
ok 55 - peer signaling bounds queued work and rejects expired invites before allocating a connection
---
duration_ms: 23.16561
type: 'test'
...
# Subtest: wizard inspects only the imported dedicated identity, loads stable catalog IDs and enables guarded playlist playback
ok 56 - wizard inspects only the imported dedicated identity, loads stable catalog IDs and enables guarded playlist playback
---
duration_ms: 6.110794
type: 'test'
...
# Subtest: disconnect cancels pending GM startup before any authenticated receiver connection
ok 57 - disconnect cancels pending GM startup before any authenticated receiver connection
---
duration_ms: 0.285383
type: 'test'
...
# Subtest: loopback transport denies unauthenticated, cross-campaign, controller, query and wrong-origin requests
ok 58 - loopback transport denies unauthenticated, cross-campaign, controller, query and wrong-origin requests
---
duration_ms: 15.412999
type: 'test'
...
# Subtest: loopback streams synthetic PCM bytes and closes an active stream on revocation
ok 59 - loopback streams synthetic PCM bytes and closes an active stream on revocation
---
duration_ms: 42.102941
type: 'test'
...
# Subtest: loopback closes idle synthetic stream when its listener capability expires
ok 60 - loopback closes idle synthetic stream when its listener capability expires
---
duration_ms: 22.434864
type: 'test'
...
# Subtest: MA snapshots ordered duplicate occurrences, pause and seek then reconstructs exact unshuffled order
ok 61 - MA snapshots ordered duplicate occurrences, pause and seek then reconstructs exact unshuffled order
---
duration_ms: 7.970949
type: 'test'
...
# Subtest: tampered, foreign/future snapshots and stale authority deny before MA mutations
ok 62 - tampered, foreign/future snapshots and stale authority deny before MA mutations
---
duration_ms: 0.994428
type: 'test'
...
# Subtest: shuffled snapshot fails before interruption rather than promising exact restore
ok 63 - shuffled snapshot fails before interruption rather than promising exact restore
---
duration_ms: 0.12279
type: 'test'
...
# Subtest: prepared media cannot be forged and stale generations cannot issue controls
ok 64 - prepared media cannot be forged and stale generations cannot issue controls
---
duration_ms: 0.197099
type: 'test'
...
# Subtest: every wire mutation revalidates exact identity/topology and uses fixed dedicated queue
ok 65 - every wire mutation revalidates exact identity/topology and uses fixed dedicated queue
---
duration_ms: 16.659427
type: 'test'
...
# Subtest: queue injection, transfer, arbitrary media URL and authority loss deny without writes
ok 66 - queue injection, transfer, arbitrary media URL and authority loss deny without writes
---
duration_ms: 0.561489
type: 'test'
...
# Subtest: catalog IDs survive independent adapter construction and differ across campaigns
ok 67 - catalog IDs survive independent adapter construction and differ across campaigns
---
duration_ms: 2.228873
type: 'test'
...
# Subtest: same-generation duplicate controls and restores issue no duplicate mutations
ok 68 - same-generation duplicate controls and restores issue no duplicate mutations
---
duration_ms: 0.864215
type: 'test'
...
# Subtest: MA provider with mock MA client composes with controller for nested contexts and rapid supersession
ok 69 - MA provider with mock MA client composes with controller for nested contexts and rapid supersession
---
duration_ms: 2.850994
type: 'test'
...
# Subtest: ambiguous wire mutation failure latches closed instead of retrying or restoring blindly
ok 70 - ambiguous wire mutation failure latches closed instead of retrying or restoring blindly
---
duration_ms: 0.537284
type: 'test'
...
# Subtest: listener cannot obtain a playback fence guard or renew a controller lease
ok 71 - listener cannot obtain a playback fence guard or renew a controller lease
---
duration_ms: 0.734622
type: 'test'
...
# Subtest: playlist preparation expands approved ordered tracks before any playback mutation
ok 72 - playlist preparation expands approved ordered tracks before any playback mutation
---
duration_ms: 0.80827
type: 'test'
...
# Subtest: installable development entry defaults automation off and imports no gateway
ok 73 - installable development entry defaults automation off and imports no gateway
---
duration_ms: 7.235745
type: 'test'
...
# Subtest: native captures actual offset and paused state, stops per sound, restores repeat/volume
ok 74 - native captures actual offset and paused state, stops per sound, restores repeat/volume
---
duration_ms: 1.289138
type: 'test'
...
# Subtest: native resolves sequential playlist and touches only owned documents
ok 75 - native resolves sequential playlist and touches only owned documents
---
duration_ms: 0.389277
type: 'test'
...
# Subtest: native rejects unsupported shuffle and empty playlist
ok 76 - native rejects unsupported shuffle and empty playlist
---
duration_ms: 0.136165
type: 'test'
...
# Subtest: native rejects expired tracks, changed playlist membership and foreign/future snapshots before mutation
ok 77 - native rejects expired tracks, changed playlist membership and foreign/future snapshots before mutation
---
duration_ms: 0.153157
type: 'test'
...
# Subtest: native reports nonseekable restoration and clamps near-end seek
ok 78 - native reports nonseekable restoration and clamps near-end seek
---
duration_ms: 0.166301
type: 'test'
...
# Subtest: scene-linked playlist conflict and lost authority fail before mutation
ok 79 - scene-linked playlist conflict and lost authority fail before mutation
---
duration_ms: 0.16035
type: 'test'
...
# Subtest: GM election deterministic and no GM means none
ok 80 - GM election deterministic and no GM means none
---
duration_ms: 3.895297
type: 'test'
...
# Subtest: Foundry bootstrap registers local settings/hooks and disposes without ambient or actor access
ok 81 - Foundry bootstrap registers local settings/hooks and disposes without ambient or actor access
---
duration_ms: 0.706259
type: 'test'
...
# Subtest: synthetic WAV termination emits fixed PCM frames through campaign listener authorization
ok 82 - synthetic WAV termination emits fixed PCM frames through campaign listener authorization
---
duration_ms: 0.897347
type: 'test'
...
# Subtest: malformed, truncated and incompatible WAV formats fail closed before PCM publication
ok 83 - malformed, truncated and incompatible WAV formats fail closed before PCM publication
---
duration_ms: 5.927141
type: 'test'
...
# Subtest: credential loader rejects permissive modes, symlinks and malformed secrets
ok 84 - credential loader rejects permissive modes, symlinks and malformed secrets
---
duration_ms: 5.456782
type: 'test'
...
# Subtest: private catalog identity key persists and unsafe key permissions fail
ok 85 - private catalog identity key persists and unsafe key permissions fail
---
duration_ms: 52.916147
type: 'test'
...
# Subtest: scene assignments persist independently and world defaults/boss priority resolve without actor schemas
ok 86 - scene assignments persist independently and world defaults/boss priority resolve without actor schemas
---
duration_ms: 1.092932
type: 'test'
...
# Subtest: native fallback is explicit, manual silence wins and legacy ambient does not resurrect after clearing
ok 87 - native fallback is explicit, manual silence wins and legacy ambient does not resurrect after clearing
---
duration_ms: 0.897637
type: 'test'
...
# Subtest: unavailable saved MA selections are preserved but new forged IDs/non-native fallback and role loss deny
ok 88 - unavailable saved MA selections are preserved but new forged IDs/non-native fallback and role loss deny
---
duration_ms: 0.389588
type: 'test'
...
# Subtest: GM setup connects catalog into independent scene editors and never persists private GM authentication
ok 89 - GM setup connects catalog into independent scene editors and never persists private GM authentication
---
duration_ms: 3.130998
type: 'test'
...
# Subtest: browser PCM sink resumes from gesture, decodes stereo frames and closes its context on stream end
ok 90 - browser PCM sink resumes from gesture, decodes stereo frames and closes its context on stream end
---
duration_ms: 15.104151
type: 'test'
...
# Subtest: normal listener has one activation action and no token or invitation entry
ok 91 - normal listener has one activation action and no token or invitation entry
---
duration_ms: 0.236251
type: 'test'
...
1..91
# tests 91
# suites 0
# pass 91
# fail 0
# cancelled 0
# skipped 0
# todo 0
# duration_ms 1421.813847
+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",
"description": "Scene and combat playlist automation with native Foundry fallback, private GM Music Assistant setup and Sendspin/WebRTC campaign audio.",
"version": "0.6.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.6.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));
+25
View File
@@ -0,0 +1,25 @@
// Offline Chromium UI fixture. No Foundry, MA, Git host, token or production access.
import {createServer} from 'node:http';
import {readFile,mkdir} from 'node:fs/promises';
import {resolve,extname} from 'node:path';
import {chromium} from 'playwright';
import assert from 'node:assert/strict';
const root=resolve(import.meta.dirname,'..');
const server=createServer(async(req,res)=>{try{const path=resolve(root,'.'+new URL(req.url,'http://localhost').pathname);if(!path.startsWith(root+'/'))throw Error();const data=await readFile(path);res.setHeader('Content-Type',extname(path)==='.mjs'?'text/javascript':extname(path)==='.css'?'text/css':'text/html');res.end(data);}catch{res.writeHead(404);res.end();}});
await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));let browser;
try{
browser=await chromium.launch({headless:true,args:['--no-sandbox']});const page=await browser.newPage({viewport:{width:1000,height:1000}}),errors=[];page.on('pageerror',e=>errors.push(e.message));
await page.goto(`http://127.0.0.1:${server.address().port}/tests/browser/setup.html`);await page.waitForFunction(()=>window.ready);
assert.equal(await page.getByText('Connect optional companion',{exact:true}).count(),0);
await page.getByLabel('Music Assistant server address').fill('https://ma.example.test');await page.getByLabel('Private GM access token').fill('fixture-token');
await page.getByLabel('I checked MA logging: raw WebSocket frames at VERBOSE are disabled').check();await page.getByRole('button',{name:'Next: dedicated receiver'}).click();await page.getByLabel('I own this dedicated campaign receiver').check();
await page.getByRole('button',{name:'Test connection and load playlists',exact:true}).click();await page.getByText('Authenticated; dedicated player and catalog verified.',{exact:false}).waitFor();
assert.equal(await page.getByLabel('Private GM access token').inputValue(),'');
await page.getByRole('button',{name:'Connect audio',exact:true}).click();await page.getByText('GM audio connected.',{exact:false}).waitFor();
const panel=page.locator('fieldset').filter({has:page.locator('legend',{hasText:'Scene music'})});
await panel.locator('select').nth(0).selectOption('["ma","ambient"]');await panel.locator('select').nth(1).selectOption('["ma","combat"]');await panel.getByRole('button',{name:'Save assignments'}).click();
assert.deepEqual(await page.evaluate(()=>window.saved.ambient),{provider:'ma',id:'ambient'});assert.deepEqual(await page.evaluate(()=>window.saved.combat),{provider:'ma',id:'combat'});
await mkdir(resolve(root,'dist/previews'),{recursive:true});await page.locator('.adaptive-music-setup').evaluate(el=>el.scrollTop=0);await page.screenshot({path:resolve(root,'dist/previews/v0.6.0-setup.png'),fullPage:true});
await page.evaluate(()=>window.listener());assert.equal(await page.locator('input').count(),0);await page.getByRole('button',{name:'Enable Audio'}).click();assert.equal(await page.evaluate(()=>window.activated),true);assert.deepEqual(errors,[]);
console.log(JSON.stringify({status:'pass',browser:browser.version(),scope:'offline DOM fixture; no live Foundry or MA',checks:['wizard render','private field clearing','catalog selectors','ambient/combat save','advanced controls hidden','listener activation'],pageErrors:errors},null,2));
}finally{await browser?.close();await new Promise(resolve=>server.close(resolve));}
+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(),'sourceRevisionStatus':'base revision; included source archive is authoritative','sourceArchiveSHA256':hashlib.sha256((output/'adaptive-music-source.zip').read_bytes()).hexdigest(),'destinationStatus':'user-reported existing Gitea; 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))
+52
View File
@@ -0,0 +1,52 @@
import {MusicError} from '../core/controller.mjs';
const ns='adaptive-music',flag='audioPublicKey',channel='module.adaptive-music';
const encode=a=>btoa(String.fromCharCode(...a));
const decode=s=>Uint8Array.from(atob(s),c=>c.charCodeAt(0));
const valid=p=>p?.v===1&&typeof p.epoch==='string'&&p.epoch.length===36&&typeof p.key==='string'&&p.key.length===88;
// Only PUBLIC ephemeral keys are stored in User flags. The authenticated Foundry
// document permission boundary binds those keys to accounts; socket sender IDs do not.
export class AutoListeners {
#game;#socket;#keys;#public;#onInvite;#isGM;#received=new Set();#pending=0;#closed=false;#starting;
constructor({game,isGM,onInvite}){this.#game=game;this.#socket=game.socket;this.#isGM=isGM;this.#onInvite=onInvite;this.handler=packet=>{this.receive(packet).catch(()=>{});};}
async start(){if(this.#starting)return this.#starting;this.#starting=this.#rotate();try{return await this.#starting;}finally{this.#starting=null;}}
async #rotate(){
this.#socket.off(channel,this.handler);this.#received.clear();
this.#keys=await crypto.subtle.generateKey({name:'ECDH',namedCurve:'P-256'},false,['deriveKey']);
this.#public={v:1,epoch:crypto.randomUUID(),key:encode(new Uint8Array(await crypto.subtle.exportKey('raw',this.#keys.publicKey)))};
if(this.#closed)return;
this.#socket.on(channel,this.handler);
await this.#game.user.setFlag(ns,flag,this.#public);
}
async #key(remote,usage){
if(!valid(remote))throw new MusicError('denied');
const publicKey=await crypto.subtle.importKey('raw',decode(remote.key),{name:'ECDH',namedCurve:'P-256'},false,[]);
return crypto.subtle.deriveKey({name:'ECDH',public:publicKey},this.#keys.privateKey,{name:'AES-GCM',length:256},false,[usage]);
}
recipientKey(user){const value=user?.getFlag(ns,flag);return valid(value)?value:null;}
async send(user,invite){
if(!this.#isGM()||!this.#public||!user.active||user.isGM||user.isBanned||invite.userId!==user.id)throw new MusicError('denied');
const recipient=this.recipientKey(user);if(!recipient)throw new MusicError('unavailable');
const header={type:'audio-invite-v1',campaign:this.#game.world.id,from:this.#game.user.id,to:user.id,sender:this.#public.epoch,recipient:recipient.epoch,id:crypto.randomUUID()};
const iv=crypto.getRandomValues(new Uint8Array(12)),key=await this.#key(recipient,'encrypt');
const cipher=await crypto.subtle.encrypt({name:'AES-GCM',iv,additionalData:new TextEncoder().encode(JSON.stringify(header))},key,new TextEncoder().encode(JSON.stringify(invite)));
if(this.#closed||!this.#isGM()||this.recipientKey(user)?.epoch!==recipient.epoch)throw new MusicError('stale');
this.#socket.emit(channel,{...header,iv:encode(iv),cipher:encode(new Uint8Array(cipher))});
}
async receive(packet){
if(this.#closed||!this.#keys||this.#game.user.isGM||packet?.type!=='audio-invite-v1'||packet.to!==this.#game.user.id||packet.campaign!==this.#game.world.id||packet.recipient!==this.#public.epoch)return;
if(Object.keys(packet).sort().join(',')!=='campaign,cipher,from,id,iv,recipient,sender,to,type'||typeof packet.id!=='string'||packet.id.length!==36||typeof packet.cipher!=='string'||packet.cipher.length>16384||typeof packet.iv!=='string'||packet.iv.length!==16||this.#pending>=2||this.#received.has(packet.id)||this.#received.size>=256)throw new MusicError('denied');
const gms=[...this.#game.users].filter(u=>u.active&&u.isGM),gm=gms[0];
if(gms.length!==1||gm.id!==packet.from||gm.isBanned)throw new MusicError('denied');
const remote=this.recipientKey(gm);if(remote?.epoch!==packet.sender)throw new MusicError('denied');
const localEpoch=this.#public.epoch;this.#pending++;
try{
const {iv,cipher,...header}=packet;
const plain=await crypto.subtle.decrypt({name:'AES-GCM',iv:decode(iv),additionalData:new TextEncoder().encode(JSON.stringify(header))},await this.#key(remote,'decrypt'),decode(cipher));
if(this.#closed||this.#public.epoch!==localEpoch||this.#received.has(packet.id)||this.recipientKey(gm)?.epoch!==remote.epoch||!gm.active||!gm.isGM||[...this.#game.users].filter(u=>u.active&&u.isGM).length!==1)throw new MusicError('stale');
const invite=JSON.parse(new TextDecoder().decode(plain));
if(invite.transport!=='webrtc-v1'||invite.userId!==this.#game.user.id||invite.expires<=Date.now()||invite.expires>Date.now()+1800000)throw new MusicError('denied');
this.#received.add(packet.id);await this.#onInvite(invite);
}finally{this.#pending--;}
}
close(){this.#closed=true;this.#socket.off(channel,this.handler);this.#keys=null;}
}
+118
View File
@@ -0,0 +1,118 @@
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:')throw new MusicError('mixed-content');
if(page.protocol!=='https:'&&!['localhost','127.0.0.1','[::1]'].includes(page.hostname))throw new MusicError('insecure-context');
return target;
}
function memoryStorage(values){const map=new Map(Object.entries(values));return {getItem:k=>map.get(k)??null,setItem:(k,v)=>map.set(k,v),removeItem:k=>map.delete(k)};}
export class GMAudioHost{
#authority;#sdk;#core;#context;#destination;#nodes=new Set();#client;#provider;#catalog=[];#session;#live=false;#socket;#generation=-1; #allowed=new Set(); #apiTransport; #gain; #releaseLock; #catalogPlayback=false; #status='disconnected'; #starting=false; #epoch=0;
constructor({authority,onDisconnect=()=>{},pageUrl=globalThis.location?.href,loadSDK=()=>import('../../vendor/sendspin-5.0.0.mjs'),createContext=()=>new AudioContext(),createSocket=url=>new WebSocket(url)}){this.#authority=authority;this.onDisconnect=onDisconnect;this.pageUrl=pageUrl;this.loadSDK=loadSDK;this.createContext=createContext;this.createSocket=createSocket;}
get status(){return {state:this.#live?'connected':this.#starting?'connecting':this.#status,catalog:this.#catalog.length,audioContext:this.#context?.state??'closed',catalogPlayback:this.#catalogPlayback};}
get catalog(){return structuredClone(this.#catalog);}
get session(){return this.#session;}
get stream(){return this.#destination?.stream;}
get connected(){return this.#live;}
supports(ref){return ref?.provider==='ma'&&this.#live&&(this.#allowed.has(ref.id)||this.#catalogPlayback&&this.#catalog.some(c=>c.id===ref.id&&c.kind==='playlist')); }
async inspect(profile){
if(!this.#authority()||this.#live)throw new MusicError('denied');
if(profile.webSocketAuthLogSafe!==true)throw new MusicError('auth-log-review-required');
const base=gmAccessPolicy(profile.maUrl,this.pageUrl);
const sk=profile.identityStorage?.['sendspin-identity-sk'];
if(typeof sk!=='string'||!/^[A-Za-z0-9_-]{43}$/.test(sk))throw new MusicError('identity-required');
const sdk=await this.loadSDK(),identity=sdk.loadSendspinClientIdentity(memoryStorage(profile.identityStorage));
if(profile.target&&profile.target!==identity.clientId)throw new MusicError('identity-mismatch');
const transport=new GMMAWebSocket({baseUrl:base.origin,token:profile.token,createSocket:this.createSocket});
const read=async(command,args)=>{
const response=await transport.fetch(base.origin+'/api',{method:'POST',redirect:'error',body:JSON.stringify({command,args})});return response.json();
};
try{
const player=await read('players/get',{player_id:identity.clientId});
if(player?.player_id!==identity.clientId||player.name!==profile.targetName||!player.provider?.startsWith('sendspin'))throw new MusicError('dedicated-target-required');
const providers=await read('providers',{provider_type:'music'});
const approvedProviders=providers.filter(p=>p.available===true&&typeof p.instance_id==='string').map(p=>p.instance_id);
if(!approvedProviders.length)throw new MusicError('catalog-empty');
const catalogKey=profile.catalogKey??btoa(String.fromCharCode(...new Uint8Array(await crypto.subtle.digest('SHA-256',new TextEncoder().encode('adaptive-music-catalog-v1:'+profile.campaign+':'+sk)))));
return {...profile,maUrl:base.origin,target:identity.clientId,expectedProvider:player.provider,approvedProviders,catalogKey,namespace:profile.namespace??profile.campaign};
}finally{transport.close();}
}
async refreshCatalog(){if(!this.#client||!this.#authority())throw new MusicError('denied');await this.#client.verifyTarget({allowUnavailable:!this.#live});this.#catalog=await this.#client.catalog();return this.catalog;}
resumeAudio(){return this.#context?.resume();}
async readCatalog(profile,{reconnecting=false}={}){
if(!this.#authority()||this.#live)throw new MusicError('denied');if(profile.webSocketAuthLogSafe!==true)throw new MusicError('auth-log-review-required');const base=gmAccessPolicy(profile.maUrl,this.pageUrl);
const key=Uint8Array.from(atob(profile.catalogKey),c=>c.charCodeAt(0));if(key.length!==32||!profile.targetName)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});
try{await this.#client.verifyTarget({allowUnavailable:reconnecting});this.#catalog=await this.#client.catalog();this.#status='catalog-ready';return this.catalog;}catch(error){await this.close();throw error;}
}
start(profile){if(this.#starting)return Promise.reject(new MusicError('denied'));this.#starting=true;return this.#start(profile).finally(()=>{this.#starting=false;});}
async #start(profile){
if(!this.#authority()||this.#live)throw new MusicError('denied');
const base=gmAccessPolicy(profile.maUrl,this.pageUrl);
if(!profile.targetName||typeof profile.target!=='string'||!profile.expectedProvider?.startsWith('sendspin')||!profile.identityStorage?.['sendspin-identity-sk']||!Array.isArray(profile.approvedProviders)||!profile.catalogKey||!profile.namespace)throw new MusicError('profile-required');
const epoch=this.#epoch,check=()=>{if(epoch!==this.#epoch||!this.#authority())throw new MusicError('stale');};
// Unlock synchronously in the caller's gesture before SDK/network work.
this.#context=this.createContext();const unlocked=this.#context.resume();this.#destination=this.#context.createMediaStreamDestination();
try{
this.#sdk=await this.loadSDK();await unlocked;check();
const storage=memoryStorage(profile.identityStorage),identity=this.#sdk.loadSendspinClientIdentity(storage);
// Never register a fresh identity or silently select a new/household player.
if(identity.clientId!==profile.target)throw new MusicError('identity-mismatch');
const key=Uint8Array.from(atob(profile.catalogKey),c=>c.charCodeAt(0));if(key.length!==32)throw new MusicError('denied');
if(!globalThis.navigator?.locks)throw new MusicError('unsupported');
const lockName='adaptive-music-'+Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',new TextEncoder().encode(base.origin+profile.target))),n=>n.toString(16).padStart(2,'0')).join('');
const released=new Promise(resolve=>{this.#releaseLock=resolve;});
await new Promise((resolve,reject)=>{navigator.locks.request(lockName,{ifAvailable:true},async lock=>{if(!lock){reject(new MusicError('denied'));return;}resolve();await released;}).catch(()=>reject(new MusicError('unavailable')));});
await this.readCatalog(profile,{reconnecting:true});check();
const original=await this.#client.queueState({allowUnavailable:true});check();
if(original.items!==0||original.state!=='idle')throw new MusicError('reconcile-required');
if(profile.allowSyntheticPlayback===true){
for(const id of Object.keys(profile.syntheticSequences??{})){if(!['synthetic-ambient','synthetic-combat'].includes(id))throw new MusicError('denied');this.#allowed.add(id);}
this.#catalog.push(...[...this.#allowed].map(id=>({provider:'ma',id,kind:'sequence',name:'Generated '+id.slice(10)+' sequence'})));
}
let volumeState=this.#client.targetVolumeState();
this.#socket=await this.#authenticatedSocket(base,profile.token,identity.clientId);check();
this.#core=new this.#sdk.SendspinCore({webSocket:this.#socket,storage,clientName:profile.targetName,productName:'Web Browser',codecs:['pcm'],bufferCapacity:768000,requiredLeadTimeMs:250,minBufferMs:250,useHardwareVolume:true,getExternalVolume:()=>volumeState,onVolumeCommand:(volume,muted)=>{volumeState={volume,muted};},unpairedAccess:false,reconnect:{enabled:false}});
this.#gain=this.#context.createGain();this.#gain.connect(this.#destination);this.#gain.connect(this.#context.destination);
this.#core.onVolumeUpdate=()=>this.#gain.gain.setTargetAtTime(this.#core.muted?0:Math.pow(Math.min(100,Math.max(0,this.#core.volume))/100,1.5),this.#context.currentTime,0.015);
this.#core.onAudioData=chunk=>this.#schedule(chunk);
this.#core.onConnectionClose=()=>{const wasLive=this.#live;this.#status='connection-lost';this.#live=false;if(wasLive)this.onDisconnect();this.#clear();for(const track of this.#destination?.stream.getTracks()??[])track.stop();};
this.#core.onStreamClear=()=>this.#clear();this.#core.onStreamEnd=()=>this.#clear();
this.#session=crypto.randomUUID();this.#catalogPlayback=profile.allowCatalogPlayback===true;this.#live=true;
this.#provider=new MAPlaybackProvider({client:this.#client,campaign:profile.campaign,session:this.#session,fence:1,snapshotKey:randomKey(),authority:()=>{if(!this.#live||!this.#authority())throw new MusicError('stale');}});
await this.#core.connect();check();const deadline=Date.now()+10000;while(this.#live&&!this.#core.timeSyncInfo.synced&&Date.now()<deadline)await new Promise(resolve=>setTimeout(resolve,50));if(!this.#live||!this.#core.timeSyncInfo.synced)throw new MusicError('unavailable');await this.#client.verifyTarget();check();return {clientIdVerified:true,catalog:this.#catalog.length,codecs:['pcm'],remoteAudio:'webrtc',audioMeasured:false,distributedFencing:false};
}catch(error){if(epoch===this.#epoch)await this.close();throw new MusicError(error instanceof MusicError?error.code:'unavailable');}
}
#authenticatedSocket(base,token,clientId){
const url=new URL('/sendspin',base);url.protocol=base.protocol==='https:'?'wss:':'ws:';
return new Promise((resolve,reject)=>{const socket=this.createSocket(url.href);this.#socket=socket;socket.binaryType='arraybuffer';const timer=setTimeout(()=>{socket.close();reject(new MusicError('unavailable'));},8000);
const fail=()=>{clearTimeout(timer);socket.close();reject(new MusicError('unavailable'));};socket.onerror=fail;socket.onclose=fail;
socket.onopen=()=>socket.send(JSON.stringify({type:'auth',token,client_id:clientId}));
socket.onmessage=event=>{try{if(JSON.parse(event.data).type!=='auth_ok')throw Error();clearTimeout(timer);socket.onerror=null;socket.onclose=null;socket.onmessage=null;resolve(socket);}catch{fail();}};
});
}
#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.#epoch++;this.#status='disconnected';this.#catalogPlayback=false;this.#live=false;this.#releaseLock?.();this.#releaseLock=null;this.#clear();this.#core?.disconnect('user_request');this.#socket?.close();this.#core=null;this.#socket=null;this.#provider=null;this.#apiTransport?.close();this.#apiTransport=null;this.#client=null;this.#catalog=[];this.#allowed.clear();for(const track of this.#destination?.stream.getTracks()??[])track.stop();this.#destination=null;const context=this.#context;this.#context=null;if(context&&context.state!=='closed')await context.close();}
}
+80
View File
@@ -0,0 +1,80 @@
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;}
hasListener(userId){return [...this.#peers.values()].some(e=>e.invite.userId===userId);}
invite(userId,{iceServers=[],ttlMs=300000,relayOnly=false}={}){
if(!this.#isGM()||!this.authorized(userId)||!this.#stream)throw new MusicError('denied');validateIceServers(iceServers);
const invite=newAudioInvite({session:this.#session,userId,iceServers,ttlMs,relayOnly});for(const [id,entry]of this.#peers)if(entry.invite.userId===userId)this.revoke(id);if(this.#peers.size>=8)throw new MusicError('denied');this.#entry(invite,'gm');return invite;
}
async listen(invite){
if(this.#isGM()||invite.userId!==this.#userId||this.#peers.size)throw new MusicError('denied');
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(); } };
}
+63
View File
@@ -0,0 +1,63 @@
const messages={
'insecure-context':'Open Foundry over trusted HTTPS. Remote plain HTTP cannot provide the secure browser APIs required for GM audio.',
'mixed-content':'This Foundry page uses HTTPS. Use a trusted HTTPS Music Assistant address (WSS for /ws and /sendspin). HTTP/ws is blocked.',
'auth-log-review-required':'Confirm that MA raw WebSocket frame logging at VERBOSE is disabled before sending a token.',
'identity-required':'Import the private backup for your existing dedicated Sendspin receiver. Its sendspin-identity-sk is required.',
'identity-mismatch':'The private receiver identity does not match the selected player. Import the matching backup.',
'dedicated-target-required':'The imported identity and dedicated player name do not match a Sendspin target. Check the name and backup; no other player was selected.',
'reconcile-required':'The dedicated queue must be empty and idle before handover. Reconcile it in Music Assistant, then reconnect.',
'catalog-empty':'No authorized music providers were found. Check the MA account’s provider permissions.',
'unsupported':'This browser or queue mode is unsupported. Use HTTPS, Web Locks, Web Audio and WebRTC; disable shuffle, dynamic queues and autoplay.',
'profile-required':'Check the server, authentication and dedicated receiver backup.',
'denied':'Connection denied. Check the private MA token, dedicated target, single active GM and account permissions.',
'stale':'Authority changed. Keep one active GM, stop automation and reconnect.',
'unavailable':'Cannot reach Music Assistant. Check trusted TLS, /ws and /sendspin upgrades, Origin/CSP permissions, private routing and the MA token.'
};
export const connectionMessage=error=>messages[error?.code]??messages.unavailable;
export function mountConnectionWizard({game,container,connection,onCatalog=()=>{},onError=()=>{}}){
const dom=container.ownerDocument,panel=dom.createElement('fieldset');
const legend=dom.createElement('legend');legend.textContent='1. Connect Music Assistant';panel.append(legend);
const note=dom.createElement('p');note.textContent='Optional. Authentication stays in this GM tab’s memory; reconnect after reload. Trust every module running in this browser.';panel.append(note);
const heading=dom.createElement('p');heading.setAttribute('role','status');panel.append(heading);
const steps=Array.from({length:3},()=>{const step=dom.createElement('div');step.className='adaptive-music-step';panel.append(step);return step;});
const go=index=>{steps.forEach((step,i)=>{step.hidden=i!==index;});heading.textContent=['Step 1 of 3: Server and private authentication','Step 2 of 3: Dedicated receiver','Step 3 of 3: Connect campaign audio'][index];};
const status=dom.createElement('p');status.setAttribute('role','status');panel.append(status);
const field=(parent,label,type='text')=>{const l=dom.createElement('label');l.textContent=label;const input=dom.createElement('input');input.type=type;input.autocomplete='off';input.spellcheck=false;l.append(input);parent.append(l);return input;};
const button=(parent,label,action)=>{const b=dom.createElement('button');b.type='button';b.textContent=label;b.addEventListener('click',async()=>{b.disabled=true;try{if(!game.user.isGM)throw {code:'denied'};await action();}catch(error){status.textContent=connectionMessage(error);onError();}finally{b.disabled=false;show();}});parent.append(b);return b;};
const address=field(steps[0],'Music Assistant server address','url');address.placeholder='https://ma.example.test';
const token=field(steps[0],'Private GM access token','password');
const logs=field(steps[0],'I checked MA logging: raw WebSocket frames at VERBOSE are disabled','checkbox');
const logNote=dom.createElement('p');logNote.textContent='Review server logging before sending a token. See connection requirements below. Native music works without Music Assistant.';steps[0].append(logNote);
button(steps[0],'Next: dedicated receiver',()=>{if(!address.value.trim()||!logs.checked)throw {code:'profile-required'};go(1);status.textContent='Import the existing dedicated receiver backup, then test the connection.';});
const name=field(steps[1],'Dedicated receiver name');name.value='Adaptive Music DEV';
const backup=field(steps[1],'Private receiver backup (.json)','file');backup.accept='.json,application/json';
const backupNote=dom.createElement('p');backupNote.textContent='Import the existing Sendspin identity and pairing backup. Only that receiver is eligible; no new receiver is registered. Keep this file private.';steps[1].append(backupNote);
const owned=field(steps[1],'I own this dedicated campaign receiver','checkbox');
const playback=field(steps[1],'Allow scene automation to play my catalog playlists on this receiver','checkbox');
button(steps[1],'Back: server',()=>go(0));
button(steps[1],'Test connection and load playlists',async()=>{
connect.disabled=true;
if(!owned.checked||!logs.checked)throw {code:'denied'};
let imported={};
try{const file=backup.files?.[0];if(file){if(file.size>65536)throw Error();imported=JSON.parse(await file.text());}}catch{throw {code:'identity-required'};}
const profile={...imported,maUrl:address.value.trim(),token:token.value,identityStorage:imported.identityStorage??imported,targetName:name.value.trim(),webSocketAuthLogSafe:true,allowCatalogPlayback:playback.checked};
token.value='';backup.value='';
const result=await connection.test(profile);setTarget(result.target,result.targetName);
connect.disabled=false;go(2);status.textContent='Authenticated; dedicated player and catalog verified. Select Connect audio to start the GM receiver.';await onCatalog();
});
const target=dom.createElement('select'),targetLabel=dom.createElement('label');targetLabel.textContent='Dedicated player';target.disabled=true;targetLabel.append(target);steps[2].append(targetLabel);
const setTarget=(id,name)=>{target.replaceChildren();const option=dom.createElement('option');option.value=id;option.textContent=name;target.append(option);target.value=id;target.disabled=false;};
const diagnostics=dom.createElement('p');diagnostics.setAttribute('role','status');steps[2].append(diagnostics);
const show=()=>{const d=connection.status;if(d.state==='connected')connect.disabled=true;diagnostics.textContent=`Connection: ${d.state}. Catalog: ${d.catalog} items. GM audio: ${d.audioContext}. ${d.catalogPlayback?'Catalog playback enabled.':'Catalog playback disabled.'} ${d.peers??0} listener connections.`;};
const connect=button(steps[2],'Connect audio',async()=>{
// Call before the first await to retain the browser activation gesture.
const pending=connection.connect(target.value);await pending;status.textContent='GM audio connected. Active players connect automatically; a browser may ask them to Enable Audio once.';await onCatalog();
});connect.disabled=true;
button(steps[2],'Refresh catalog and diagnostics',async()=>{await connection.refresh();await onCatalog();status.textContent='Catalog and target checks refreshed.';});
button(steps[2],'Enable GM audio',()=>connection.resume());
button(steps[2],'Back: receiver',()=>go(1));
button(steps[2],'Disconnect Music Assistant',async()=>{await connection.disconnect();token.value='';backup.value='';target.replaceChildren();connect.disabled=true;go(0);status.textContent='Disconnected. Automation is stopped; existing remote queue state is retained for review.';await onCatalog();});
const help=dom.createElement('a');help.href='modules/adaptive-music/INSTALL.md';help.target='_blank';help.rel='noopener';help.textContent='Connection requirements and troubleshooting';panel.append(help);
const d=connection.status;if(d.selectedTarget){setTarget(d.selectedTarget,d.selectedName);connect.disabled=d.state==='connected';go(2);}else go(0);
show();container.append(panel);return panel;
}
+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();}
}
+83
View File
@@ -0,0 +1,83 @@
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 {AutoListeners} from '../audio/auto-listeners.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=[];let bootstrap,privateProfile,inviteTimer,latestInvite,listenerStopped=false,listenerState='Waiting for GM audio.',inviteTail=Promise.resolve();const sentInvites=new Map();let connectionGeneration=0;let listenerContext,listenerSource;
const gmAuthority=()=>game.ready&&game.user.isGM&&primaryGM(game.users)===game.user.id&&[...game.users].filter(u=>u.active&&u.isGM).length===1&&game.socket?.connected===true;
const owned=()=>game.settings.get(id,'ownedPlaylistIds').split(',').map(s=>s.trim()).filter(Boolean);
const choices=async()=>[...[...game.playlists].filter(p=>owned().includes(p.id)).map(p=>({provider:'native',id:p.id,name:p.name})),...(gmHost?.catalog.length?gmHost.catalog.filter(c=>c.kind==='playlist'||c.kind==='sequence'):gateway?.catalog??[])];
const onError=()=>ui.notifications.warn('Adaptive Music could not complete the operation. Open Adaptive Music setup for connection diagnostics and ownership checks.');
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 ensureRemoteAudio(){if(!remoteAudio){remoteAudio=document.createElement('audio');remoteAudio.autoplay=true;document.body.append(remoteAudio);}return remoteAudio;}
function attachListenerSource(stream){listenerSource?.disconnect();if(listenerContext){listenerSource=listenerContext.createMediaStreamSource(stream);listenerSource.connect(listenerContext.destination);remoteAudio.muted=true;}}
function resumeListener(){if(game.user.isGM)return gmHost.resumeAudio();listenerStopped=false;const element=ensureRemoteAudio();let resumed=Promise.resolve();if(globalThis.AudioContext){listenerContext??=new AudioContext();resumed=listenerContext.resume();if(element.srcObject)attachListenerSource(element.srcObject);}const play=element.play();play.catch(()=>{});if(!peers.diagnostics().peers.length)bootstrap?.start().catch(onError);return resumed.then(()=>{listenerState=element.srcObject?'Campaign audio enabled.':'Audio enabled. Waiting for GM audio.';});}
function sendInvites(){
inviteTail=inviteTail.catch(()=>{}).then(async()=>{
if(!bootstrap||!gmHost?.connected||!gmAuthority())return;
for(const user of game.users){
if(!user.active||user.isGM||user.isBanned)continue;const key=bootstrap.recipientKey(user);if(!key)continue;
const previous=sentInvites.get(user.id);if(previous?.epoch===key.epoch&&previous.until>Date.now()&&peers.hasListener(user.id))continue;
try{const invite=peers.invite(user.id,{ttlMs:1800000,...(privateProfile?.listenerNetwork??{})});await bootstrap.send(user,invite);sentInvites.set(user.id,{epoch:key.epoch,until:Date.now()+1200000});}catch{onError();}
}
});return inviteTail;
}
const connection={
get status(){return {...(gmHost?.status??{state:'disconnected',catalog:0,audioContext:'closed'}),selectedTarget:privateProfile?.target,selectedName:privateProfile?.targetName,peers:peers?.diagnostics().peers.filter(p=>p.connection==='connected').length??0};},
async test(profile){if(gmHost.connected||gmHost.status.state==='connecting'||gateway.connected)throw {code:'denied'};stop();const generation=++connectionGeneration;const old=privateProfile;privateProfile=null;await gmHost.close();const candidate={...old,...profile,token:profile.token||old?.token,identityStorage:profile.identityStorage?.['sendspin-identity-sk']?profile.identityStorage:old?.identityStorage,campaign:game.world.id};const result=await gmHost.inspect(candidate);await gmHost.readCatalog(result,{reconnecting:true});if(generation!==connectionGeneration)throw {code:'stale'};privateProfile=result;return {target:result.target,targetName:result.targetName};},
async connect(target){if(!privateProfile||target!==privateProfile.target||gateway.connected)throw {code:'denied'};stop();const pending=gmHost.start(privateProfile);await pending;peers.setSource(gmHost.stream);sentInvites.clear();await sendInvites();if(game.settings.get(id,'enabled'))start();},
refresh:()=>gmHost.refreshCatalog(),resume:()=>gmHost.resumeAudio(),
async disconnect(){connectionGeneration++;stop();peers?.reset();sentInvites.clear();privateProfile=null;await gmHost.close();}
};
function listenWebRTC(invite){
if(game.user.isGM||!peers)throw Error('Listener only');
ensureRemoteAudio().play().catch(()=>{});listenerState='Connecting to GM audio…';return peers.listen(invite);
}
function stopWebRTC(){listenerStopped=true;listenerState='Audio stopped.';listenerSource?.disconnect();listenerSource=null;listenerContext?.suspend();peers?.reset();remoteAudio?.pause();if(remoteAudio)remoteAudio.srcObject=null;}
Hooks.once('init',()=>{
game.settings.register(id,'advancedDevelopment',{name:'Show advanced development controls',hint:'Optional companion and manual test capabilities. Not needed for normal music setup.',scope:'client',config:true,type:Boolean,default:false});
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,connection});
const Listener=createListenerClass({game,gateway:{audioRequest:code=>gateway.audioRequest(code)},audio:{start:request=>audio.start(request),stop:()=>audio.stop()},listenWebRTC,stopWebRTC,onError,resumeListener,listenerStatus:()=>listenerState});
game.settings.registerMenu(id,'listen',{name:'Campaign audio',label:'Enable Audio',hint:'Connects automatically to GM audio. Enable sound if your browser asks.',icon:'fas fa-headphones',type:Listener,restricted:false});
game.settings.registerMenu(id,'setup',{name:'Adaptive Music setup',label:'Configure music',hint:'Music Assistant connection, scene music and Foundry fallback.',icon:'fas fa-music',type:Setup,restricted:true});
}
});
Hooks.once('ready',()=>{
gmHost=new GMAudioHost({authority:gmAuthority,onDisconnect:()=>{stop();peers?.reset();sentInvites.clear();onError();}});
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=>{ensureRemoteAudio().srcObject=stream;attachListenerSource(stream);(listenerContext?.state==='running'?Promise.resolve():remoteAudio.play()).then(()=>{listenerState='Campaign audio connected.';}).catch(()=>{listenerState='GM audio connected. Select Enable Audio to allow sound.';ui.notifications.info('Adaptive Music: open Campaign audio and select Enable Audio to allow sound.');});}});game.socket.on('disconnect',()=>{stop();privateProfile=null;gmHost.close();peers.reset();sentInvites.clear();latestInvite=null;listenerState='Foundry disconnected. Waiting for the GM to reconnect.';remoteAudio?.pause();});}
if(game.socket)authorityHooks=['updateUser','deleteUser'].map(event=>[event,Hooks.on(event,()=>{peers.reconcile();if(!game.user.isGM&&[...game.users].filter(u=>u.active&&u.isGM).length!==1){peers.reset();remoteAudio?.pause();latestInvite=null;listenerState='Waiting for one active GM.';}sendInvites();if(gmHost.connected&&!gmAuthority()){stop();gmHost.close();peers.reset();remoteAudio?.pause();}})]);
if(game.socket&&game.user.setFlag){bootstrap=new AutoListeners({game,isGM:gmAuthority,onInvite:async invite=>{latestInvite=invite;if(listenerStopped)return;peers.reset();await listenWebRTC(invite);}});bootstrap.start().then(sendInvites).catch(onError);inviteTimer=setInterval(()=>{sendInvites();if(game.user.isGM&&runtime&&!gmHost.connected&&privateProfile){stop();peers.reset();sentInvites.clear();onError();}},15000);}
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(){await connection.disconnect();},
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();listenerSource?.disconnect();listenerContext?.close();privateProfile=null;bootstrap?.close();clearInterval(inviteTimer);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'?'Music Assistant':'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 playlist',combat:'Combat playlist',boss:'Default boss music',fallback:'Foundry fallback playlist'};
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(); }
};
}
+73
View File
@@ -0,0 +1,73 @@
import {mountConnectionWizard} from './connection-wizard.mjs';
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,connection,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='Could not apply this change. Check ownership, active GM authority and connection diagnostics.';onError(e);}finally{b.disabled=false;}});root.append(b);return b;};
const assignmentRoot=dom.createElement('div');
if(connection)mountConnectionWizard({game,container:root,connection,onCatalog:()=>renderAssignments(),onError});
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='2. Foundry music and fallback';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 advanced=game.settings.get('adaptive-music','advancedDevelopment')===true;
if(advanced){
const dev=dom.createElement('details'),title=dom.createElement('summary');title.textContent='Advanced development: optional companion';dev.append(title);root.append(dev);
const label=dom.createElement('label');label.textContent='Companion controller code';const code=dom.createElement('input');code.type='password';code.autocomplete='off';label.append(code);dev.append(label);
const connect=button('Connect optional companion',async()=>{if(!canConnect())throw new MusicError('denied');const value=code.value;code.value='';await gateway.connect(value);await renderAssignments();});dev.append(connect);
const disconnect=button('Disconnect optional companion',()=>gateway.disconnect());dev.append(disconnect);
const listen=dom.createElement('input');listen.type='password';listen.setAttribute('aria-label','Companion test capability');dev.append(listen);
const enable=button('Enable synthetic test audio',()=>{const value=JSON.parse(listen.value);listen.value='';return audio.start(gateway.audioRequest(value));});dev.append(enable);
const disable=button('Stop test audio',()=>audio.stop());dev.append(disable);
}
const renderAssignments=async()=>{
assignmentRoot.replaceChildren();const choices=await getChoices();
const defaults=dom.createElement('details'),defaultsTitle=dom.createElement('summary');defaultsTitle.textContent='World music defaults';defaults.append(defaultsTitle);mountMusicAssignments({game,container:defaults,choices,defaults:true,onError});assignmentRoot.append(defaults);
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 more=dom.createElement('details'),moreTitle=dom.createElement('summary');moreTitle.textContent='Boss music and manual controls';more.append(moreTitle);assignmentRoot.append(more);
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);more.append(bossLabel);
const bossPanel=dom.createElement('div');more.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');more.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));more.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.';});
return root;
}
_replaceHTML(result,content){content.replaceChildren(result);}
};
}
export function createListenerClass({game,gateway,audio,listenWebRTC,stopWebRTC=()=>{},onError,listenerStatus=()=>'Waiting for the GM to connect Music Assistant.',resumeListener=()=>{},Base=globalThis.foundry.applications.api.ApplicationV2}){
return class AdaptiveMusicListener extends Base {
static DEFAULT_OPTIONS={id:'adaptive-music-listener',window:{title:'Campaign audio'},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='Campaign audio connects automatically while the GM receiver is online. Your browser may require one audio activation click. No microphone or Music Assistant login is needed.';root.append(note);
const status=dom.createElement('p');status.setAttribute('role','status');status.textContent=listenerStatus();root.append(status);
const enable=dom.createElement('button');enable.type='button';enable.textContent='Enable Audio';enable.addEventListener('click',()=>{Promise.resolve(resumeListener()).then(()=>{status.textContent=listenerStatus();}).catch(()=>{status.textContent='Audio is waiting. Keep this tab open; check with the GM if it does not connect.';});});root.append(enable);
const stop=dom.createElement('button');stop.type='button';stop.textContent='Stop Audio';stop.addEventListener('click',()=>{stopWebRTC();audio.stop();status.textContent='Audio stopped. Select Enable Audio to reconnect.';});root.append(stop);
if(game.settings.get('adaptive-music','advancedDevelopment')===true){
const dev=dom.createElement('details'),summary=dom.createElement('summary');summary.textContent='Advanced development';dev.append(summary);
const input=dom.createElement('input');input.type='password';input.setAttribute('aria-label','Manual listener capability');dev.append(input);
const manual=dom.createElement('button');manual.type='button';manual.textContent='Use manual invitation';manual.addEventListener('click',()=>{try{const code=JSON.parse(input.value);input.value='';Promise.resolve(code.transport==='webrtc-v1'?listenWebRTC(code):audio.start(gateway.audioRequest(code))).catch(onError);}catch{onError(new MusicError('denied'));}});dev.append(manual);root.append(dev);
}
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(['providers','players/get','player_queues/get','player_queues/get_active_queue','player_queues/items','music/playlists/library_items','music/radios/library_items','music/playlists/get','music/playlists/playlist_tracks','music/tracks/get',...['play_media','play_index','pause','resume','stop','seek','shuffle','repeat','clear'].map(a=>'player_queues/'+a)]);
// GM-local adapter for MA's public /ws API. No HTTP CORS dependency or server proxy.
export class GMMAWebSocket{
#base;#token;#socket;#connect;#pending=new Map();#factory;#closed=false;
constructor({baseUrl,token,createSocket=url=>new WebSocket(url)}){this.#base=new URL(baseUrl).origin;this.#token=token;this.#factory=createSocket;}
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); }
}
}
+14
View File
@@ -0,0 +1,14 @@
.adaptive-music-setup {display:grid;gap:0.85rem;max-height:75vh;overflow:auto;padding:0.75rem;}
.adaptive-music-setup fieldset,[data-adaptive-music="assignments"] {display:grid;gap:0.65rem;padding:0.85rem;border:1px solid var(--color-border-light-primary,#777);border-radius:6px;min-width:0;}
.adaptive-music-setup legend {font-weight:700;padding:0 0.4rem;}
.adaptive-music-setup label,[data-adaptive-music="assignments"] label {display:grid;gap:0.35rem;}
.adaptive-music-setup select,.adaptive-music-setup input:not([type="checkbox"]),[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;overflow-wrap:anywhere;}
.adaptive-music-setup p {margin:0.2rem 0;line-height:1.4;}
.adaptive-music-setup button {height:auto;min-height:2rem;white-space:normal;}
.adaptive-music-setup details {padding:0.6rem;border:1px solid var(--color-border-light-primary,#777);border-radius:6px;}
.adaptive-music-setup details[open] {display:grid;gap:0.65rem;}
.adaptive-music-setup summary {cursor:pointer;font-weight:600;}
.adaptive-music-step {display:grid;gap:0.65rem;}
.adaptive-music-step[hidden] {display:none;}
+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>
+15
View File
@@ -0,0 +1,15 @@
<!doctype html><meta charset="utf-8"><title>Adaptive Music setup fixture</title>
<link rel="stylesheet" href="/styles/adaptive-music.css">
<style>body{font:16px system-ui;background:#222;color:#eee;margin:2rem auto;max-width:640px}input,select,button{font:inherit;padding:.4rem;box-sizing:border-box}button{cursor:pointer}a{color:#9bd}</style>
<main id="app"></main>
<script type="module">
import {createSetupClass,createListenerClass} from '/src/foundry/setup.mjs';
let flag={},catalog=[];const settings={ownedPlaylistIds:'native',musicDefaults:{},enabled:false,advancedDevelopment:false};
const collection=items=>{const map=new Map(items.map(x=>[x.id,x]));map[Symbol.iterator]=function*(){yield*map.values()};return map};
const scene={id:'scene',name:'Moonlit forest',active:true,getFlag:()=>flag,setFlag:async(ns,k,v)=>{flag=v;window.saved=flag}};
const game={user:{isGM:true},settings:{get:(ns,k)=>settings[k],set:async(ns,k,v)=>{settings[k]=v}},playlists:collection([{id:'native',name:'Foundry fallback'}]),scenes:collection([scene]),combats:[]};
const connection={status:{state:'disconnected',catalog:0,audioContext:'closed'},test:async p=>{if(p.token!=='fixture-token')throw {code:'denied'};catalog=[{provider:'ma',id:'ambient',kind:'playlist',name:'Forest at night'},{provider:'ma',id:'combat',kind:'playlist',name:'Battle drums'}];connection.status={state:'catalog-ready',catalog:2,audioContext:'closed'};return {target:'dedicated',targetName:'Adaptive Music DEV'}},connect:async()=>{connection.status={state:'connected',catalog:2,audioContext:'running',catalogPlayback:true}},refresh:async()=>{},resume:async()=>{},disconnect:async()=>{}};
const Setup=createSetupClass({game,connection,getChoices:async()=>[{provider:'native',id:'native',name:'Foundry fallback'},...catalog],start(){},stop(){},setOverrides(){},onError(){},Base:class{}});
document.querySelector('#app').append(await new Setup()._renderHTML());window.ready=true;
window.listener=async()=>{const Listener=createListenerClass({game,audio:{stop(){}},resumeListener:()=>{window.activated=true},Base:class{}});document.querySelector('#app').replaceChildren(await new Listener()._renderHTML())};
</script>
Loaded 100 of 121 files, more files were not shown because too many files have changed in this diff. Show more