Release v0.6.0 - Music Assistant wizard and automatic listener connections

This commit is contained in:
Jason committed 2026-12-03 20:11:10 -05:00
1 parent 5319177c58
commit c2c2d1314d
26 files changed
+1553 -764

No files matched your search

+98 -176
View File
@@ -1,193 +1,115 @@
# Adaptive Music architecture — 0.5.0 local release candidate
# 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**
with a stable Git-hosted manifest and immutable version-specific download URL.
No mandatory Foundry modules, containers, VMs/LXCs, sandbox runtime, core patches,
OS-service installer, subscription or telemetry. Planned Gitea URLs are configured
but the host/repository has not been contacted or confirmed to exist.
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.
## Decision after reevaluation
## Connection and catalog
The 0.4.0 companion is **not a mandatory architecture**. Native playback and all
scene/world/combat/boss/manual rules remain entirely module-local. The preferred
MA experiment is a trusted GM-browser host using the official Sendspin browser
SDK, Web Audio and WebRTC audio tracks. Its feasibility is conditional on secure
private MA reachability, an authorized existing receiver identity, GM availability,
participant capabilities and a working ICE path. It cannot yet be represented as
reliable module-only remote MA audio for arbitrary networks.
`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 validated companion remains under `gateway/` and local branch
`experimental/companion-0.4.0`; provider/catalog/restoration code is preserved.
Shared Web Crypto transport/provider implementations now serve both GM and optional
companion, with compatibility exports at the original gateway paths. All original
regressions remain. If the browser gates cannot be met, propose one manually run,
restricted process **co-located on the existing Foundry host**. No new machine,
container or automatic service is proposed or deployed. Placement/routing and any
manual service registration require explicit approval after concrete review.
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
F[Foundry scene and combat policy] --> C[Existing serialized controller]
C --> N[Owned native playlist provider]
C --> M[Shared guarded MA provider in trusted GM browser]
M -->|private authenticated API WebSocket| A[Private MA 2.10.6]
A -->|authenticated Sendspin to pinned existing identity| S[Official SDK in GM browser]
S --> W[Web Audio MediaStream]
W -->|DTLS SRTP media tracks| P[Authorized player browsers]
G[Foundry module socket] <-->|bounded encrypted SDP only| S
G <-->|bounded encrypted SDP only| P
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
```
No raw audio or MA token uses the ordinary module socket. No MA HTTP/WS/Sendspin
proxy is exposed to players. No microphone is requested and no RTC control data
channel is accepted. A GM's credentials are **not hidden from that GM/browser user**;
all code executing in that browser origin must be trusted. Other player browsers
never receive the MA credential, SDK identity, private queue snapshots or endpoint.
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.
## What is measured
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.
`evidence/browser-audio.json`: actual Chromium **143.0.7499.4**, two independent
listener browser contexts, original 440 Hz synthetic PCM encoded in Sendspin binary
frames and decoded by the pinned official SDK, Web Audio -> WebRTC -> HTMLAudio /
listener analyser. Both listeners had signal after **1,757 ms**, FFT peak **445.3125
Hz** (bin resolution around the 440 Hz source), RMS about **0.054**, aggregate GM RTP
payload **42.3 kbps** over **4.766 seconds**. Four encrypted signaling messages,
maximum **2,078 bytes**; no audio on the signaling channel. Localhost, no TURN, no
MA/Noise handshake, no real Foundry socket, no hardware audibility claim, no WAN,
interlistener skew or long-run drift measurement. These are synthetic path results,
not MA playlist playback or synchronization verification.
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.
Live dedicated target/queue reads still verify the existing DEV identity and an
empty idle queue. `module-only-prerequisites.json`: the configured MA origin is
HTTP, the HTTPS-host access policy rejects it as mixed content, and no authorized
DEV private SDK identity is available locally. **Zero new Sendspin connections,
identities or playback mutations.** Earlier read-only catalogs and bounded idle
controls remain separate evidence; synthetic ingestion previously failed.
## Policy, authority and fallback
## Browser access and GM-local authentication
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.
`GMAudioHost` uses a private, memory-only profile supplied by the GM, with canonical
MA origin, dedicated target ID/name/provider, approved provider filter, catalog key/
namespace and existing SDK identity/pairing storage. Nothing is saved into Foundry
settings, flags, browser localStorage, module socket or a release. Catalog IDs remain
HMAC-derived and stable when the operator retains the same private key/namespace.
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.
The official public `/ws` control API avoids dependence on cross-origin HTTP `/api`
preflight, which is not configured for that route in the inspected MA pin. The same
fixed client command allowlist, response bounds, timeout, redirect policy, target
checks and registered-media rules are preserved through the WebSocket adapter.
Its initial auth command carries the GM's token in a private connection, never a
URL; unsolicited events are discarded. The Sendspin `/sendspin` connection uses
the official frontend's first-message auth pattern, then the official SDK's Noise
transport. The SDK's fixed roles include controller/metadata; it runs only in the
trusted GM host, never as a supposedly restricted player listener.
A 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.
A source-derived privacy gate matters: pinned MA `websocket_client.py` logs raw
received frames at VERBOSE, including auth. The GM profile requires an explicit
operator `webSocketAuthLogSafe` acknowledgment after ensuring such payload logging
is disabled. This has **not** been verified live or changed by the agent. No live
WebSocket token test was attempted. The module logs no credential and does not
modify MA logging/core. An adapter cannot redact the remote server's own logs.
## Evidence
HTTPS Foundry -> plain HTTP/ws private MA is not a generally portable browser path,
even with encrypted Sendspin payloads. CSP, browser local-network access rules,
Origin policy, TLS trust and private routing still apply. Current policy refuses
that deployment rather than disabling browser protections. Local-network exceptions
in particular browsers are not a cross-browser guarantee. A private trusted HTTPS/
WSS MA endpoint reachable by the GM, or the approved co-located restricted worker,
is required. Players do not need MA network access.
SDK identity is derived from an X25519 private key. A player name or ID alone cannot
reconstruct it. The code checks the supplied identity matches **Adaptive Music DEV**
before any receiver connection; no random replacement, discovery-and-select, pairing
or internal virtual-player provisioning occurs. Operator-controlled handover from
the original web player is needed. Read-only identity/topology checks may inspect
the known unavailable target during handover; every mutation still requires full
availability, exact name/provider, own active queue and standalone topology.
## WebRTC signaling, authorization and transport
Foundry's supported `game.socket`/module channel is a relay, not an authenticated
claim of sender identity. We do **not** trust a payload `userId`/`isGM` or assume
that broadcast destinations enforce confidentiality. The GM explicitly issues a
unique short-lived 256-bit per-listener invitation, delivered over an authenticated
private channel outside the module broadcast. Possession authorizes only that peer;
it does not prove a Foundry login cryptographically, and a recipient can forward
its own capability/audio. No automatically broadcast bootstrap exists.
`SignalCodec` authenticates/encrypts SDP (including ICE addresses/DTLS fingerprints)
with AES-GCM, session/peer/direction/sequence binding, nonce, expiry, size/type limits
and replay checks rechecked after asynchronous decryption. A listener can affect
only its own peer; another peer has another key. `PeerAudio` permits one recvonly
listener offer and audio-only answer, rejects video/data/outbound listener audio,
bounds peers, drops unknown frames, permits at most two explicit ICE restarts, and
revokes on expiry, disconnect or authorization reconciliation. Continuous media is
browser-managed DTLS-SRTP, never JSON PCM over Foundry sockets.
Default ICE servers are **empty**: no silent external STUN/TURN or telemetry.
Operator-provided STUN/TURN configuration is explicit. TURN credentials must be
short-lived; relay-only mode requires TURN and avoids direct peer candidates.
Authorized peers can inspect their own ICE/network details and credentials. Direct
P2P may disclose GM/peer network addresses to the authorized peer; encryption hides
SDP from other world clients, not its intended recipient. No secrets are protected
from the browser's own user. Existing public-interface references:
[Foundry Game/socket](https://foundryvtt.com/api/v14/classes/foundry.Game.html),
[WebRTC connectivity](https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Connectivity),
[mixed content](https://developer.mozilla.org/en-US/docs/Web/Security/Defenses/Mixed_content).
Symmetric NAT, CGNAT, UDP filtering and restrictive corporate networks can need TURN;
STUN alone cannot guarantee connectivity. A relay must already exist or be separately
approved, not installed as another container/VM by this module. One GM peer connection
per listener means approximately linear GM upload/encoding cost. The 42.3 kbps local
measurement is two listeners and short synthetic content, not a capacity promise.
Browser jitter buffers, suspend/background policy and output devices introduce
independent playout delay: Sendspin's upstream timestamps do not create synchronized
WebRTC outputs automatically. Measure WAN jitter/skew and 30-minute drift before any
sync guarantee. Crossfade and concurrent ambient layers remain unimplemented.
## Authority, lifecycle and restoration
Policy remains manual (including silence) > explicit eligible boss > started active
combat for the scene > scene ambient > world default > silence. Bosses use module
flags/priority, no actor HP/schema. Scene/world assignments, explicit native fallback,
legacy flag migration, snapshots, interrupted paused offsets and duplicate ordered
occurrences are preserved. Ambient is currently the single interrupted base queue;
AmbientSound and effects remain untouched. Optional companion control retains its
expiring fenced lease; native document ownership stays explicitly opted in.
GM-local control shares the same serialized, generation-checked provider and target
checks. A Web Lock excludes duplicate GM tabs on the same origin; startup requires
one active GM and a known empty idle target. This is **not a distributed server fence**
and cannot prevent a malicious/stale independent GM client with its own MA token.
The module refuses automatic split-brain handover and invalidates authority on
Foundry disconnect. Permanent strict multi-writer fencing needs the approved worker.
No browser-only design can manufacture an MA server-side compare-and-swap lease.
GM loss stops WebRTC forwarding and automated writes; it cannot guarantee immediate
restoration after a crashed/offline browser, and already delivered audio cannot be
revoked from a recipient. SDK-adopted sockets do not auto-reconnect. Explicit reconnect
requires target reconciliation, same identity, secure access, new peer invitations
and role checks. Native fallback cannot silently bypass an uncertain active MA target.
The preserved MA snapshots are signed, scoped to campaign/session/fence/generation,
expire after five minutes and carry ordered occurrences, index, whole-second offset,
pause/state and repeat. Capture repeats pagination; restore stages ordered items,
checks them and seeks. Shuffled/dynamic/autoplay/overlay/ended/nonstandard speed
states are unsupported. Remote ambiguity latches closed rather than retrying blindly.
Restart/crash durability, shuffled restoration and true cross-client fencing remain
acceptance gates. The bounded live harness still captures/restores original state;
closing an experimental GM tab is not claimed to restore MA automatically.
## Optional minimal co-located fallback
If secure private browser reachability, network traversal or GM uptime is unacceptable,
review a single non-root worker on the **existing Foundry host**, using existing host
runtime/network capacity and protected state. It would terminate only the dedicated
MA receiver, hold credentials server-side, enforce controller/listener authorization
and expose restricted campaign audio/control through the existing TLS origin. It
must never forward arbitrary MA API/WS/Sendspin messages. Existing `gateway/` code is
a validated starting point, but actual Sendspin termination, durability and production
security remain work. No system service is installed automatically, no host is
provisioned and no Foundry/MA core is changed. Any real route/placement/deployment
must be proposed concretely and approved first; nothing is deployed here.
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.
+17
View File
@@ -1,5 +1,22 @@
# 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
+174 -140
View File
@@ -1,150 +1,184 @@
# Adaptive Music 0.5.0 — manual release and installation
# Adaptive Music 0.6.0 — setup and manual publication
Module ID **adaptive-music**, author **CheddahBoxMB**, Foundry generation **14**;
system-independent, no mandatory Foundry modules. Native operation needs only this
module ZIP. No container, VM/LXC, Ubuntu sandbox, core patch or automatically installed
OS service is required. GM-local MA/WebRTC audio remains experimental; limitations
and measured results are in ARCHITECTURE.md and evidence/browser-audio.json.
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.
## Build offline without Git credentials or a remote
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.
From this repository (Python 3 standard library; local Git metadata is optional):
## 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.5.0/adaptive-music.zip
python3 scripts/release.py --validate dist/releases/v0.6.0/adaptive-music.zip
```
This creates `dist/releases/v0.5.0/adaptive-music-release-v0.5.0.zip`. It contains:
`adaptive-music.zip`, standalone `module.json`, `adaptive-music-source.zip`, README,
this INSTALL guide, CHANGELOG, LICENSE, THIRD-PARTY-NOTICES, all vendor license
texts, `release.json` and `SHA256SUMS`. The SDK bundle is committed, so packaging
needs no npm installation, browser download, network, Git token or Git-host access.
The builder never verifies, contacts, creates or pushes a remote repository.
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.
For another host, for example your own public GitHub repository:
```
python3 scripts/release.py --repository https://github.com/OWNER/adaptive-music --output dist/github-release
```
Use a real destination under your control. The generated manifest's `url`, stable
`manifest` and version-specific `download` are changed together. The builder does
not write to the Git host or alter the root manifest. It validates identity, v14
compatibility, import/assets closure, SDK hash, licenses, private-file exclusion and
public HTTPS URL shape locally. This cannot prove that a planned URL exists.
## Upload to the planned Gitea destination manually
Planned repository (existence/access **not checked**):
`https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music`
1. On your own initiative, use Gitea's web UI to create/confirm that repository and
enable public read access to the source manifest and release attachments. Foundry
must be able to fetch them without Git credentials. This exposes release files,
not MA. This agent has not accessed or authenticated with your Gitea server.
2. Unpack the **source archive**, not the outer release bundle, into the repository
using your normal Git/web upload workflow. Preserve directory structure, notices,
scripts and the generated root `module.json`. Exclude `.local/`, node_modules,
private deployment files and credentials. Do not upload an outer bundle as the
module contents. If web upload cannot preserve folders, use your own local Git
client; no credential is needed by the release builder itself.
3. Create tag/release **v0.5.0** for this version. Keep that tag immutable. Paste the
CHANGELOG entry into the release notes. Do not mark this unverified development
release as Foundry-verified or production-ready.
4. Upload **adaptive-music.zip** and **module.json** as release attachments with
those exact names. Upload source/archive, SHA256SUMS, docs/notices or the full
outer bundle as additional review artifacts. Never use the source ZIP or outer
bundle as the module download attachment.
5. After publishing, manually verify anonymous downloads and checksums. The module
ZIP should resolve at:
`https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/releases/download/v0.5.0/adaptive-music.zip`
6. Ensure `main/module.json` is the generated standalone manifest. The stable
installation/update URL is:
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`
This URL is deliberately stable across releases. Do not give Foundry a tag-specific
manifest URL if you expect automatic version discovery.
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.
No URL above was requested by the build/validation process. Uploading/publishing is
manual; no token, remote connection, automatic push or release publication is used.
## Install and update through Foundry
Once the public manifest and release attachments actually exist:
1. In isolated Foundry v14 Setup → Add-on Modules → Install Module, paste the stable
manifest URL above and install. Enable Adaptive Music in the isolated world.
2. Configure Settings → Adaptive Music setup: select dedicated native music playlists,
save ownership/reload, set world/scene ambient/combat/boss/native fallback choices,
then enable automation. Sound effects/AmbientSound are excluded. Automation
defaults off. Test real v14.371 behavior before considering production use.
3. For later versions, preserve the module ID and stable manifest URL. Bump semantic
version in module.json/package.json/lockfile, update CHANGELOG and build a new
immutable tag-specific release. The versioned ZIP URL must change with version.
4. Publish new attachments **before promoting the new standalone manifest to main**.
Prepare on a release branch/tag if needed, leaving the previous main manifest
untouched until assets are available. Never overwrite a previous version's ZIP.
5. Foundry Setup → Update Modules should discover the newer manifest version and
download its new ZIP while keeping world/document settings. This is the standard
update contract and is validated structurally, not measured against your server.
GitHub uses the same ZIP and upload process, with a stable generated manifest at
`https://raw.githubusercontent.com/OWNER/adaptive-music/main/module.json` and ZIP at
`https://github.com/OWNER/adaptive-music/releases/download/v0.5.0/adaptive-music.zip`.
Optional pinned GitHub/Gitea CI workflows only test/build artifacts for manual
publication on an already provisioned runner. They install no runner/service or
runtime infrastructure. CI/host execution has not been validated on your Gitea.
## GM-local MA and WebRTC experiment
The intended module-only path is: private MA → official Sendspin JS SDK in the GM
browser → Web Audio → encrypted WebRTC audio tracks → authorized player browsers.
Foundry module sockets carry only encrypted bounded SDP/control, never continuous
raw audio or an MA token. No STUN/TURN service is silently selected. Per-listener
invitations must be delivered privately, not posted to a module socket/public flag.
The GM must be able to reach MA privately over a browser-allowed secure connection.
An HTTPS Foundry page cannot be assumed to access plain HTTP/ws MA just because the
Sendspin payload is encrypted. CSP, local-network permissions and server Origin policy also apply. The GM-local control adapter uses the official /ws API because HTTP /api CORS preflight is not enabled in the inspected MA pin.
No mixed-content bypass or public MA route is provided. Browser-local MA credentials
are visible to that GM/user and any compromised code running in their browser;
this design does not claim otherwise. Players never receive those credentials.
Developer API (explicit operator actions; no automatic playback on module enable):
- `api = game.modules.get('adaptive-music').api`
- `api.readGMCatalog(profile)` reads through GM-local authentication.
- `api.startGMHost(profile)` must be invoked directly by a user gesture with automation
stopped and the optional companion disconnected. `profile` stays in GM memory.
- `api.inviteListener(userId, {iceServers: []})` creates a unique expiring invitation.
Deliver it over a private authenticated channel to that participant.
- Player gesture: `api.listenWebRTC(invitation)`. No microphone/control channel.
- `api.peerStats()` returns sanitized bandwidth/jitter statistics.
- `api.closeGMHost()` tears down the local host. MA state recovery still requires
the existing guarded bounded test procedure; do not assume tab closure restores MA.
The private profile requires MA origin/token, pinned existing DEV ID/name/provider,
approved providers, a base64 32-byte catalogKey and namespace retained privately,
plus the **existing DEV Sendspin identity and pairing storage**, and `webSocketAuthLogSafe: true` only after verifying that MA raw WebSocket payload logging at VERBOSE is disabled. The pinned server would otherwise log the auth frame/token; no logging configuration was changed or verified here. No real profile is bundled or
stored in world settings/flags/localStorage. `campaign` is supplied by the module.
Use only previously approved generated synthetic sequences and explicit synthetic
playback opt-in; real library playlist playback is a separate authorization gate.
The current sandbox has **no existing DEV private identity**. The module refuses to
register a random replacement or hijack a name-matching player. The GM must privately
supply an authorized export of the existing web player's identity, or separately
approve a new dedicated identity and update the target/account binding. No such
provisioning has occurred. Synthetic files also still need to be reachable by MA.
WebRTC without a configured relay cannot guarantee remote connections behind all
NAT/firewall combinations. TURN, if required, must be an explicitly approved existing
service with short-lived credentials; no new container/VM or service is installed.
The GM's upload scales with listener count and their browser must stay running.
Startup also requires one active GM, a browser Web Lock and a reconciled empty idle test target. Read-only identity checks can inspect the known unavailable target during operator handover; every mutation still rechecks full availability/topology. GM loss stops forwarding, invalidates automation authority and requires explicit
reconciliation/reconnection; no seamless handover or distributed MA fence is claimed.
If browser access/NAT/GM-availability gates cannot be satisfied, an optional minimal
co-located worker on the **existing Foundry host** is the fallback design. Its source
is retained in gateway/ and branch experimental/companion-0.4.0. It is not installed,
started or required by the module. Any host placement, TLS route or manual service
registration needs separate approval; MA remains private. No core modifications.
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.
+51 -96
View File
@@ -1,104 +1,59 @@
# Adaptive Music progress — 0.5.0
# Adaptive Music progress — 0.6.0
Continued from `50c3a7c`; the complete 0.4.0 companion implementation is preserved
at local branch `experimental/companion-0.4.0` as well as in `gateway/`. The original
0.3.0 ZIP gap audit remains `evidence/package-objective-audit.json`; it describes
that historical package, not the current release. No validated code was discarded.
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
## Implemented for v0.6.0
The standard release is one module ZIP, ID `adaptive-music`, author CheddahBoxMB,
Foundry generation 14, no mandatory modules or system dependency. Python's offline
builder produces a complete manual upload bundle, stable manifest/versioned download,
source archive, docs/licenses and checksums. Gitea/GitHub repository base is configurable.
The default destination is the user's **planned, unconfirmed** Gitea repository.
It was not contacted, authenticated with, created or pushed to. Git remotes and
credentials are not required. CI artifact workflows are prepared but unexecuted;
no runner or OS service is installed. Publication and hosted updates are unverified.
- 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.
Native playback and scene/world/combat/boss/manual configuration are preserved.
Persistent ambient/combat/boss/native fallback references, world defaults, legacy
migration, explicit combatant flags and native ownership remain connected to the
existing controller. The shared guarded MA client/provider now use Web Crypto,
retaining the optional companion import paths and stable catalog IDs/signatures.
## Verification and unresolved prerequisites
The new experimental GM host uses the official pinned Sendspin 5.0.0 SDK, a
reproducible PCM-only browser bundle with audited notices, Web Audio termination
and WebRTC audio tracks. GM-local MA authentication uses the public `/ws` API;
no raw unrestricted proxy, browser player credential or external CDN is introduced.
The existing DEV private identity must match before a receiver connection; no new
identity/target/pairing or internal provisioning was attempted. Only approved
synthetic sequences can be controlled by this path. Real catalog selections are
available through the developer connection API and existing assignment UI; actual
playlist playback is still separately gated. GM setup for MA remains developer-API
based; there is no claim of a finished one-click connection wizard.
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.
Listener capabilities are separate from controller access. Foundry module sockets
carry per-peer encrypted bounded SDP/control; WebRTC transports continuous audio.
No microphone, video, data channel, automatic STUN/TURN or raw PCM socket transport.
Expiry, revocation, role changes and disconnect tear down peers; there are bounded
explicit ICE restarts. Same-origin GM Web Locks and a single-active-GM check reject
obvious conflicts, but do not constitute a distributed MA fence. Memory-only secret
handling cannot hide secrets from the GM browser's own user.
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.
## Actual observations
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.
- **85 JS / 15 Python tests pass**; repository privacy/attribution and recorded
upstream hashes pass. Online npm advisory audit reports zero vulnerabilities.
The SDK and dependencies are pinned; no installation hooks ran. Exact command
evidence is retained in `evidence/development-checks.txt`.
- An actual Chromium decoder → Web Audio → WebRTC experiment delivered original
synthetic PCM to two listeners: signal at 1.757 s, RMS approximately 0.054,
aggregate GM RTP payload approximately 42.3 kbit/s. Four encrypted control messages.
This was a loopback socket shim, not actual Foundry, MA, WAN or a sync measurement.
See `evidence/browser-audio.json`.
- Fresh live MA read-only checks verified the dedicated DEV identity/topology and
empty idle queue. Configured MA is HTTP; HTTPS Foundry would fail mixed-content
policy. No existing DEV private identity is present in the GM profile. No receiver
connection, new identity or playback mutation was made in this revision.
- Pinned MA source logs received WebSocket frames at VERBOSE. Before token-bearing
WS auth the module requires explicit operator acknowledgment that payload logging
is disabled. This was neither checked nor changed live. No WS auth test occurred.
- Previous restricted catalog and idle-state live controls are retained. Prior
bounded runs restored their original empty idle state. Synthetic ingestion failed
previously (timeout/HTTP 400). No actual MA music audio, nonempty live restore,
combat/boss interruption with audible MA content or real playlist acceptance.
## Testable inside isolated Foundry
Without infrastructure: install/enable the module, GM native ownership/setup,
world and scene assignments surviving reload, boss flags/priority, manual overrides,
active combat policy, native playback/restoration and explicit native fallback.
These behaviors are unit/fixture tested; real Foundry v14.371 testing remains pending.
With separately supplied secure private MA access, existing DEV identity/pairing,
log review and synthetic ingestion: developer GM connection/catalog and synthetic
control, then listener WebRTC invitations and audio. Test actual Foundry socket
relay with distinct logged-in users before assuming the loopback benchmark applies.
See INSTALL.md and TESTING.md for precise steps/acceptance boundaries.
## Remaining blockers and next infrastructure decision
1. Supply a licensed isolated Foundry v14.371 world/browser session for actual install,
native playback, socket, document and reconnect acceptance; production is excluded.
2. Operator must provide private trusted HTTPS/WSS MA access reachable by the GM,
the existing DEV identity/pairing, and authentication-log review. No public MA
endpoint or network configuration weakening is acceptable. New identity/target
binding would require separate explicit authorization.
3. Make the generated synthetic tracks readable through an approved existing MA
provider/private range-capable source. Do not modify existing playlists. This
minimum ingestion change is still unimplemented/unverified, not silently waived.
4. WAN peers may require an explicitly approved existing TURN relay with short-lived
credentials. Measure NAT reachability, latency, bandwidth, skew and reconnect.
5. Browser-only GM loss/crash cannot guarantee automatic restore or continuity;
durable distributed fencing and crash recovery need the optional minimal worker
on the existing Foundry host. Actual Sendspin termination in that worker remains
work. Deployment/routing/service changes need a concrete proposal and approval;
nothing has been deployed. No additional machine/container is proposed.
6. Crossfade, independent concurrent ambient layers, shuffled exact restoration and
actual MA playlist playback remain unsupported/unaccepted. No production readiness.
The manual release can be uploaded without any of those runtime prerequisites;
they gate MA audio acceptance, not native module packaging. Next authorization, if
browser gates cannot be met, is review of a concrete restricted co-located worker
and existing-host TLS route. This release does not authorize deploying that fallback.
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.
+34 -49
View File
@@ -1,61 +1,46 @@
# Adaptive Music — 0.5.0 development
# Adaptive Music — 0.6.0
Independent open-source project by **CheddahBoxMB**, targeting Foundry VTT **v14.371**
and Music Assistant **2.10.6**, independent of game system and other modules.
This is a development release; it has not been exercised inside an actual Foundry
world. No production installation or external service is changed by building it.
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.
Install `adaptive-music.zip` through Foundry's normal module manifest mechanism.
[INSTALL.md](INSTALL.md) covers manual Gitea publication, installation, updates and
isolated testing. The configured repository is **planned, not confirmed**. No
connection to it was made. An uploaded, anonymously readable manifest and release
asset are required before Foundry installation by URL can work.
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 standard module includes native playlist playback, persistent separate scene
ambient/combat/boss/native fallback assignments, global defaults, manual overrides,
combat automation and the existing snapshot/restore controller. The GM setup menu
configures native ownership and assignments. Automation defaults off. Only
explicitly owned native music playlists are eligible; sound effects are out of scope.
The 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.
The new **experimental GM browser host** shares the validated MA provider/catalog
code, uses the bundled official Sendspin SDK's PCM decoder and Web Audio, and
sends audio to invited listeners with WebRTC. Supported Foundry module sockets carry
only encrypted bounded signaling, never continuous audio. GM credentials remain in
GM memory and are visible to that browser's user; players receive individual
expiring audio capabilities. No Docker, VM, LXC, external module, permanent sandbox,
core patch, OS service or public MA endpoint is required by the module.
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).
This path is a developer API experiment, not a completed one-click MA setup.
The existing DEV receiver's private identity/pairing, private browser-reachable TLS,
authentication-log review and MA ingestion of the approved synthetic sequences are
still prerequisites. Real catalog entries can be displayed/assigned, but only the
authorized synthetic sequences are enabled for experimental MA playback. The
companion implementation remains optional experimental source and is preserved at
local branch `experimental/companion-0.4.0`; it is not needed for native playback.
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.
Measured in Chromium: the official decoder and WebRTC delivered synthetic 440 Hz
PCM to **two** listener contexts, with first signal at **1.757 s** and approximately
**42.3 kbit/s** aggregate GM RTP payload. This used a loopback signaling shim, not
Foundry or MA. WAN/NAT/TURN, inter-listener synchronization, audible MA output and
nonempty live queue restoration remain unverified. Crossfade and simultaneous
ambient layers are not implemented. GM loss ends forwarding; seamless failover or
crash restoration is not promised.
Build a complete manual release bundle locally, without Git credentials or a remote:
Build without contacting a Git server:
```sh
python3 scripts/release.py
# To prepare the same release for GitHub instead:
python3 scripts/release.py --repository https://github.com/OWNER/REPOSITORY --output dist/github
python3 scripts/release.py --validate dist/releases/v0.6.0/adaptive-music.zip
```
Output: `dist/releases/v0.5.0/adaptive-music-release-v0.5.0.zip`, containing the
installable module, standalone manifest, source archive, documentation, licenses
and SHA256 checksums. The manifest uses a stable branch URL and a version-specific
release download. Build automation validates both but does not publish anything.
Prebuilt browser assets are included; end users do not need Node/npm or Python.
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.
For contributor commands and evidence see [TESTING.md](TESTING.md),
[PROGRESS.md](PROGRESS.md), [ARCHITECTURE.md](ARCHITECTURE.md) and
[SECURITY.md](SECURITY.md). MIT project license; upstream MIT/Apache notices and
full dependency licenses are retained in `THIRD-PARTY-NOTICES` and `licenses/`.
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).
+71 -119
View File
@@ -1,133 +1,85 @@
# Security — standalone module and optional host fallback
# Adaptive Music security — 0.6.0
The module installs through the normal Foundry manifest/ZIP mechanism. No runtime
Docker/VM/LXC, sandbox host, third-party Foundry module, core modification, service
installer or public MA endpoint is required or created. The optional companion is
retained as experimental source/branch, not a mandatory backend. Co-located host
placement/routing/manual service setup is a proposal requiring separate approval.
## Private GM connection
## Trust boundaries
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.
Only an elected single active GM may initiate GM-local MA access. The GM explicitly
supplies a memory-only private profile; that GM/browser user can inspect its token,
identity and private data. JavaScript private fields are not a secret store against
the browser owner, debugger, compromised same-origin code or server administrator.
No contrary claim is made. Trust all code served into the GM origin. A player never
receives the GM's MA token/profile, SDK private key, upstream URL or queue payload.
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.
Profiles/tokens are not persisted in Foundry settings, flags, localStorage, sockets,
logs, release files or URLs. Operator private backups belong outside the module's
public files; existing development secrets stay under ignored `.local/` (0700,
regular owner-matching files 0600, symlinks refused). Catalog references are opaque
HMAC identifiers, stable only with retained operator key/namespace. Configured native
ownership and scene/world references are public world data, never MA credentials.
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.
GM control uses the official private MA `/ws` API, with fixed command allowlists,
correlated bounded responses and discarded unsolicited events, behind the preserved
MA target/media/provider checks. The MA account's role still grants broader writes;
filtering is defense in depth, not the sole boundary. No endpoint selector, queue
transfer, grouping, unrestricted HTTP/WS/Sendspin proxy or household discovery is
available to players. No new identity is registered: supplied X25519 SDK identity
must match the already verified DEV target before connecting; reconnecting an existing
known unavailable target never relaxes mutation guards. SDK auth is first-message,
not a token URL. Only original synthetic test sequences may be enabled for playback.
## Transport and authorization
A precise upstream logging limitation: MA 2.10.6's WebSocket handler logs raw frames
at VERBOSE, including auth payloads. No live token WebSocket test was attempted and
no upstream log configuration was read/changed. The GM profile requires explicit
`webSocketAuthLogSafe` operator review of disabled raw-frame logging before use.
The module's own logs omit credentials; it cannot redact MA's logs without changing
that upstream behavior. Do not assume default logging or ignore this gate.
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.
## Browser network/security policy
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.
Private network access from an HTTPS Foundry page still needs permitted routing,
trusted TLS/WSS, CSP and server/browser Origin/local-network policies. Sendspin Noise
does not waive mixed-content restrictions. Current module policy refuses HTTPS ->
non-loopback HTTP/ws MA; modern per-browser local-network exceptions are not a
portable supported deployment. HTTP `/api` CORS is also insufficient in the inspected
pin; GM control instead uses the public authenticated WebSocket API, not a CORS
bypass proxy. No private API is exposed publicly to fix browser access.
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.
No public third-party STUN/TURN is silently used. Default ICE servers are empty;
relay configuration is explicit and TURN credentials must be short-lived. Browser
users necessarily see their own relay credentials and decrypted peer signaling.
Direct P2P can reveal network addresses to the authorized peer; relay-only mode can
reduce that exposure if an approved relay already exists. It cannot guarantee WAN
connectivity without appropriate infrastructure. No service/container is provisioned.
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.
## Signaling and players
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.
Ordinary Foundry module sockets carry only bounded encrypted SDP/control envelopes,
never continuous PCM/audio chunks, MA commands, media URLs, tokens or invitation
secrets. Claimed sender IDs/GM flags are not trusted as authentication. The GM issues
a unique expiring 256-bit per-listener capability out of band over a private
authenticated channel. Possession authorizes that one peer, not a proven login.
A recipient can share its own capability/record received audio; this cannot be
prevented by browser JavaScript. Do not distribute a controller/MA secret as an invite.
## Authority, recovery and distribution
AES-GCM covers SDP/ICE/DTLS fingerprints with session/peer/direction/sequence binding,
nonce/expiry, strict fields/types/size limits and asynchronous replay rechecks. A
listener may negotiate one recvonly audio m-line; video, outbound listener audio and
RTC data/control channels are rejected. Keys are per listener, so one recipient
cannot forge another listener's authorized exchange. Invalid broadcast frames are
dropped; world-server/socket flooding is still a server-side availability concern,
not solved by client encryption. Explicit peer/expiry/restart bounds limit our work.
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.
Media uses browser DTLS-SRTP WebRTC audio tracks. No microphone is requested. GM
revocation stops new media, but cannot erase audio already delivered or force a
malicious recipient to discard buffered/recorded content. Real Foundry identity,
packet validation, WAN/NAT and browsers still need live acceptance.
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.
## Authority, failure and original state
Target identity/provider, own active queue, standalone topology and current authority
are rechecked immediately before each mutation. Snapshot and prepared data remain
scoped, generation-checked and serialized. Signed snapshots preserve ordered duplicates,
index/offset/state/repeat for static unshuffled supported queues; expiry, foreign,
tampered or future state denies. Ambiguous remote writes latch closed with no blind
retry. Unsupported shuffle/dynamic/autoplay/overlay/ended/speed states fail closed.
Only the campaign-owned target is eligible; volume/mute state is read before SDK
handover instead of assuming maximum output. Native effects/AmbientSound stay unowned.
The optional companion retains its process-local fenced lease checks. GM-local control
has one-GM checks and a same-origin Web Lock, **not a distributed MA server fence**.
It cannot protect against a malicious/stale independent GM with MA credentials.
Multiple-GM automation/hard fencing remains a readiness blocker. No automatic GM
handover, queue ownership transfer or speaker grouping exists. Foundry disconnect
stops forwarding and future writes; an offline/crashed GM cannot guarantee restoration.
Native fallback never skips reconciliation of an uncertain active MA target.
Existing bounded live harnesses still capture original state and report restoration
success/failure explicitly. No new playback mutation or Sendspin pairing was attempted
in this revision; the read-only check observed an empty idle dedicated queue. The browser measurement
used original synthetic PCM, not real MA or licensed-service content. Existing
synthetic ingestion failure and identity/TLS/logging gates remain. Crossfade,
simultaneous layers, durable recovery and deployment security are not claimed complete.
## Release and supply-chain safeguards
The release builder runs offline, uses no Git credential/remote API and never contacts
the planned Gitea server. It validates public HTTPS URL shape, stable manifest and
versioned ZIP consistency, module ID/author/v14 compatibility, no false `verified`
claim, no mandatory systems/modules, import closure, notices, SDK hash and privacy
patterns. It rejects private/symlinked package files. Exact private token/endpoint/target
scans of history and artifacts supplement these guardrails; they are not a
comprehensive secret scanner or proof of uncontacted server availability.
Official SDK 5.0.0 and noble dependencies are pinned/audited and bundled locally;
there is no runtime CDN or installer. Full Apache/MIT texts accompany releases.
Optional Opus fallback imports are explicitly disabled in the PCM-only SDK build;
libopus/speex/opus-encdec binaries are not distributed. WebRTC's browser codec is not
bundled by this project. Install hooks were disabled. Developer-only Playwright/
esbuild tools and local Chromium are not shipped or a runtime dependency.
CI workflows use pinned action commits on an existing shell runner, build artifacts
for manual publication, and install no services or infrastructure. No Git host was
accessed/authenticated/created/pushed on the user's behalf. Public release files
contain no private MA addresses/credentials/deployment data. A source archive is not
an installable Foundry ZIP; documentation distinguishes both.
Peer signaling also bounds each peer to four queued control frames and 64 received
control attempts per invitation, limiting asynchronous decrypt/SDP backlog. Socket
flooding of the Foundry server remains a server/operator availability concern.
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.
+76 -82
View File
@@ -1,102 +1,96 @@
# Adaptive Music verification — 0.5.0
# Adaptive Music verification — 0.6.0
## Regression and offline release validation
## Offline regression and packaging
The current suite has **85 JavaScript tests** and **15 Python tests**. Tests cover
controller transitions, signed snapshots, target/topology guards, durable catalog
IDs, native restore behavior, scene/default/combat interfaces, optional companion
scope/replay protection, GM access policy, official PCM decoder, encrypted WebRTC
signaling/replay checks, public MA WebSocket correlation and offline release contracts.
These are fixtures and source checks, not live Foundry/MA playback tests.
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.5.0/adaptive-music.zip
python3 scripts/release.py --validate dist/releases/v0.6.0/adaptive-music.zip
```
Python uses the standard library. Upstream verification requires ignored pinned
research copies; it does not fetch/install them. Browser assets are prebuilt and
SHA256 verified. Optional rebuilding uses Node 24.23.0, `npm ci --ignore-scripts`
and `node scripts/build_sendspin.mjs`. No install hooks were run. The online npm
advisory audit of the pinned dependency tree reported **zero vulnerabilities**;
this is an advisory observation, not a safety guarantee or an offline audit.
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.
Release tests exercise repeatable ZIP generation, embedded/standalone manifest
identity, missing import/asset rejection, URL versioning, GitHub configuration,
checksums, attribution, private-content exclusion and rebuilding from a source
archive without Git metadata. Neither the builder nor these tests contact Gitea.
CI workflows generate artifacts only on an already provisioned shell runner.
They have not run on GitHub or Gitea; Gitea Actions/artifact compatibility is untested.
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.
## Measured browser audio experiment
`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.
`evidence/browser-audio.json` records an actual Chromium 143.0.7499.4 experiment:
official Sendspin 5.0.0 decoder → Web Audio → WebRTC → two listener browser contexts.
The original 440 Hz synthetic tone produced RMS 0.05391/0.05396 and FFT peaks
445.3125 Hz (nearest frequency bin). All listeners had signal at 1.757 s; during
4.766 s observation, the GM sent 25,198 RTP payload bytes, approximately 42.3 kbit/s
aggregate. Four encrypted signaling messages (maximum 2,078 bytes), no raw audio
on signaling. AudioContexts/HTMLAudioElements were unlocked by actual page clicks.
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.
Optional reproduction after a separate Playwright Chromium download:
## User report and historical evidence
```sh
PLAYWRIGHT_BROWSERS_PATH=.local/browsers node scripts/measure_browser_audio.mjs
```
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.
The harness starts a temporary loopback static server and a socket shim, uses
headless Chromium with `--no-sandbox` only for the development experiment and
closes them afterwards. This is not a real Foundry socket integration, live MA
Sendspin handshake, WAN/NAT/TURN test, perceptual quality test or synchronization
measurement. Browser dependencies/binaries do not ship with the module.
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.
## Live MA evidence and limits
## Remaining isolated live acceptance
`ma-readonly.json` records prior authenticated restricted account checks, dedicated
target/provider restrictions and catalog reads. `ma-adapter.json` records eleven
playlists/one radio and stable opaque identifiers across adapter reconstruction.
`ma-live-history.json` and `ma-playback.json` record prior bounded idle-queue runs:
shuffle/repeat/stop and exact restoration to empty/idle/unshuffled/repeat-off/zero.
They verify neither audible music nor restoration of a nonempty queue.
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.
`module-only-prerequisites.json` adds fresh authenticated **read-only HTTP**
verification of the fixed DEV identity/topology and empty idle queue. The configured
MA endpoint is HTTP; an HTTPS Foundry page fails the module mixed-content gate.
The existing receiver private identity is absent from the GM profile. No receiver
was created, no Sendspin connection attempted and no playback command issued in
this revision. MA 2.10.6 source logs received WebSocket frames at VERBOSE: operator
log review is required before token-bearing `/ws` authentication. No live WS auth
was attempted. Route behavior and authentication protocol are source-derived.
Prior synthetic URI ingestion timed out/returned HTTP 400; approved six-track
ambient/combat WAV sequences are not established as ingestible. Actual MA playlist
playback remains a separate content-approval acceptance test. Synthetic browser
PCM does not satisfy it. Household devices, grouping, queue transfers, production
Foundry and network/service configuration remain untouched.
## Remaining acceptance tests
In an isolated Foundry v14.371 world: install/enable ZIP, test native ownership,
scene ambient/combat/boss and world defaults, explicit combatant flags, manual
silence/clear, rapid transitions and native fallback. Validate supported socket
signaling using two logged-in users; private invite delivery and revocation, user
role changes, disconnects and automation shutdown need real-world confirmation.
Before live MA audio: operator supplies the existing DEV identity/pairing without
registering a new target; makes private secure MA browser access available without
public exposure; confirms token-bearing WS frames cannot enter logs; supplies
approved synthetic ingestion. Recheck exact target/group/queue before every write.
Capture and restore original state with a bounded harness. Then test seeking,
interrupt/restore, rapid/nested contexts and stereo/format handling with listeners.
Do not treat mocked nonempty restoration as live evidence. Real playlists require
separate approved content. Record an explicit restoration failure if it occurs.
Remote WAN trials must measure ICE/TURN reachability, expiry/reconnect, throughput,
latency and listener skew; none is inferred from the loopback result. GM restart,
durable nonempty live restore, distributed fencing, crossfade, background tab
behavior and service fallback termination remain unsupported or unverified as
specified in ARCHITECTURE.md. No production readiness claim.
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.
+67 -19
View File
@@ -1,24 +1,72 @@
{
"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,
"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": 85,
"python": 15
"javascript": 91,
"python": 15,
"passed": true
},
"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"
"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"
],
"gitea_contacted": false
"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
}
]
}
+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
+4 -4
View File
@@ -1,8 +1,8 @@
{
"id": "adaptive-music",
"title": "Adaptive Music \u2014 Development",
"description": "Independent scene/combat music automation and experimental GM-local Sendspin/WebRTC audio. Native playback works without a companion; remote MA audio requires validated browser/network access.",
"version": "0.5.0",
"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"
@@ -24,5 +24,5 @@
"socket": true,
"url": "https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music",
"manifest": "https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/raw/branch/main/module.json",
"download": "https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/releases/download/v0.5.0/adaptive-music.zip"
"download": "https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/releases/download/v0.6.0/adaptive-music.zip"
}
+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));}
+1 -1
View File
@@ -146,7 +146,7 @@ def build_release(repository=DEFAULT_REPOSITORY,version=None,output=None):
for path in (ROOT/'licenses').rglob('*'):
if path.is_file():target=output/path.relative_to(ROOT);target.parent.mkdir(parents=True,exist_ok=True);target.write_bytes(path.read_bytes())
metadata={'version':version,'repository':manifest['url'],'manifest':manifest['manifest'],'download':manifest['download'],
'sourceCommit':local_revision(),'destinationStatus':'planned; never contacted by this builder','foundryLiveVerified':False,'networkAccessRequired':False}
'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())))
+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;}
}
+47 -19
View File
@@ -6,33 +6,61 @@ import {randomKey} from '../providers/ma/webcrypto.mjs';
export function gmAccessPolicy(baseUrl,pageUrl){
const target=new URL(baseUrl),page=new URL(pageUrl);
if(target.username||target.password||target.search||target.hash||target.pathname!=='/'||!['http:','https:'].includes(target.protocol))throw new MusicError('denied');
if(page.protocol==='https:'&&target.protocol!=='https:'&&!['localhost','127.0.0.1','[::1]'].includes(target.hostname))throw new MusicError('mixed-content');
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;
constructor({authority,pageUrl=globalThis.location?.href,loadSDK=()=>import('../../vendor/sendspin-5.0.0.mjs'),createContext=()=>new AudioContext(),createSocket=url=>new WebSocket(url)}){this.#authority=authority;this.pageUrl=pageUrl;this.loadSDK=loadSDK;this.createContext=createContext;this.createSocket=createSocket;}
#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 this.#live&&this.#allowed.has(ref.id);}
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!=='Adaptive Music DEV')throw new MusicError('denied');
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});
await this.#client.verifyTarget({allowUnavailable:reconnecting});this.#catalog=await this.#client.catalog();return this.catalog;
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;}
}
async start(profile){
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!=='Adaptive Music DEV'||typeof profile.target!=='string'||!profile.expectedProvider?.startsWith('sendspin')||!profile.identityStorage?.['sendspin-identity-sk']||!Array.isArray(profile.approvedProviders)||!profile.catalogKey||!profile.namespace)throw new MusicError('profile-required');
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;
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');
@@ -41,29 +69,29 @@ export class GMAudioHost{
const lockName='adaptive-music-'+Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',new TextEncoder().encode(base.origin+profile.target))),n=>n.toString(16).padStart(2,'0')).join('');
const released=new Promise(resolve=>{this.#releaseLock=resolve;});
await new Promise((resolve,reject)=>{navigator.locks.request(lockName,{ifAvailable:true},async lock=>{if(!lock){reject(new MusicError('denied'));return;}resolve();await released;}).catch(()=>reject(new MusicError('unavailable')));});
await this.readCatalog(profile,{reconnecting:true});
const original=await this.#client.queueState({allowUnavailable:true});
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);
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=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=()=>{this.#live=false;this.#clear();for(const track of this.#destination?.stream.getTracks()??[])track.stop();};
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.#live=true;
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();const deadline=Date.now()+10000;while(this.#live&&!this.#core.timeSyncInfo.synced&&Date.now()<deadline)await new Promise(resolve=>setTimeout(resolve,50));if(!this.#live||!this.#core.timeSyncInfo.synced)throw new MusicError('unavailable');await this.#client.verifyTarget();return {clientIdVerified:true,catalog:this.#catalog.length,codecs:['pcm'],remoteAudio:'webrtc',audioMeasured:false,distributedFencing:false};
}catch(error){await this.close();throw new MusicError(error instanceof MusicError?error.code:'unavailable');}
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);socket.binaryType='arraybuffer';const timer=setTimeout(()=>{socket.close();reject(new MusicError('unavailable'));},8000);
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();}};
@@ -86,5 +114,5 @@ export class GMAudioHost{
apply(prepared,ctx){return this.#ready().apply(prepared,ctx);}
restore(snapshot,ctx){return this.#ready().restore(snapshot,ctx);}
stopOwned(ctx){return this.#ready().stopOwned(ctx);}
async close(){this.#live=false;this.#releaseLock?.();this.#releaseLock=null;this.#clear();this.#core?.disconnect('user_request');this.#socket?.close();this.#core=null;this.#socket=null;this.#provider=null;this.#apiTransport?.close();this.#apiTransport=null;this.#client=null;this.#catalog=[];this.#allowed.clear();for(const track of this.#destination?.stream.getTracks()??[])track.stop();this.#destination=null;const context=this.#context;this.#context=null;if(context&&context.state!=='closed')await context.close();}
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();}
}
+3 -2
View File
@@ -26,9 +26,10 @@ export class PeerAudio{
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||this.#peers.size>=8)throw new MusicError('denied');validateIceServers(iceServers);
const invite=newAudioInvite({session:this.#session,userId,iceServers,ttlMs,relayOnly});this.#entry(invite,'gm');return invite;
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');
+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;
}
+36 -14
View File
@@ -2,14 +2,15 @@ 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 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:gateway?.catalog??[])];
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;
@@ -18,29 +19,50 @@ function start(){
}
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');
if(!remoteAudio){remoteAudio=document.createElement('audio');document.body.append(remoteAudio);}
remoteAudio.play().catch(()=>{});return peers.listen(invite);
ensureRemoteAudio().play().catch(()=>{});listenerState='Connecting to GM audio…';return peers.listen(invite);
}
function stopWebRTC(){peers?.reset();remoteAudio?.pause();if(remoteAudio)remoteAudio.srcObject=null;}
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});
const Listener=createListenerClass({game,gateway:{audioRequest:code=>gateway.audioRequest(code)},audio:{start:request=>audio.start(request),stop:()=>audio.stop()},listenWebRTC,stopWebRTC,onError});
game.settings.registerMenu(id,'listen',{name:'Campaign audio (development)',label:'Enable Audio',hint:'Private WebRTC invitation, or optional companion synthetic test.',icon:'fas fa-headphones',type:Listener,restricted:false});
game.settings.registerMenu(id,'setup',{name:'Adaptive Music setup',label:'Configure music',hint:'Native ownership, world/scene assignments, boss overrides, gateway and audio diagnostics.',icon:'fas fa-music',type:Setup,restricted:true});
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});
if(game.socket){peers=new PeerAudio({socket:game.socket,userId:game.user.id,isGM:gmAuthority,isAuthorizedUser:id=>{const user=game.users.get(id);return user?.active&&!user.isGM&&!user.isBanned;},onError,onStream:stream=>{if(!remoteAudio){remoteAudio=document.createElement('audio');remoteAudio.autoplay=true;document.body.append(remoteAudio);}remoteAudio.srcObject=stream;remoteAudio.play().catch(onError);}});game.socket.on('disconnect',()=>{stop();gmHost.close();peers.reset();remoteAudio?.pause();});}
if(game.socket)authorityHooks=['updateUser','deleteUser'].map(event=>[event,Hooks.on(event,()=>{peers.reconcile();if(gmHost.connected&&!gmAuthority()){stop();gmHost.close();peers.reset();remoteAudio?.pause();}})]);
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={
@@ -52,10 +74,10 @@ Hooks.once('ready',()=>{
inviteListener:(userId,options)=>peers.invite(userId,options),
listenWebRTC,
peerStats:()=>peers.stats(),
async closeGMHost(){stop();peers?.reset();await gmHost.close();},
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();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;}
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();
});
+2 -2
View File
@@ -17,7 +17,7 @@ export function musicSelect(dom,choices,current,{nativeOnly=false,empty='Use wor
const select=dom.createElement('select');
const add=(value,text)=>{const option=dom.createElement('option');option.value=value;option.textContent=text;select.append(option);};
add('',empty);
for(const c of choices.filter(c=>!nativeOnly||c.provider==='native'))add(referenceKey(c),`${c.provider==='ma'?'MA':'Foundry'}: ${c.name}`);
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;
}
@@ -26,7 +26,7 @@ export function mountMusicAssignments({document,game,container,choices,defaults=
const dom=container.ownerDocument,panel=dom.createElement('fieldset');panel.dataset.adaptiveMusic='assignments';
const legend=dom.createElement('legend');legend.textContent=defaults?'World music defaults':'Scene music';panel.append(legend);
const previous=defaults?game.settings.get(namespace,'musicDefaults')??{}:document.getFlag(namespace,'music')??{};
const labels={ambient:'Ambient music (base queue)',combat:'Combat music',boss:'Default boss music',fallback:'Native fallback when MA is unavailable'};
const 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);
+35 -28
View File
@@ -1,7 +1,8 @@
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,Base=globalThis.foundry.applications.api.ApplicationV2}){
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(){
@@ -9,57 +10,63 @@ export function createSetupClass({game,gateway,audio,getChoices,start,stop,setOv
const dom=globalThis.document,root=dom.createElement('div');root.className='adaptive-music-setup';
const text=value=>{const p=dom.createElement('p');p.textContent=value;root.append(p);return p;};
const status=text('Automation is opt-in. Configure dedicated music playlists and assignments before enabling it.');status.setAttribute('role','status');
const button=(label,action)=>{const b=dom.createElement('button');b.type='button';b.textContent=label;b.addEventListener('click',async()=>{b.disabled=true;try{if(!game.user.isGM)throw new MusicError('denied');await action();}catch(e){status.textContent=e?.code==='denied'?'Connection or selection denied. Check capability role/expiry, active GM, and native ownership.':e?.code==='stale'?'Controller lease changed. Reconnect with a fresh connection code.':'Gateway unavailable. Check the private same-origin route, TLS, companion process and target diagnostics. Native configuration can be used offline.';onError(e);}finally{b.disabled=false;}});root.append(b);return b;};
const 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='Dedicated native music playlists';ownedPanel.append(legend);
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 codeLabel=dom.createElement('label');codeLabel.textContent='Optional companion controller code (memory only; never an MA token) ';const code=dom.createElement('input');code.type='password';code.autocomplete='off';codeLabel.append(code);root.append(codeLabel);
text('Native playback requires no companion. The optional companion uses a private same-origin route. The module-only GM-host API uses private GM-local authentication; see INSTALL.md. Never share MA credentials with listeners.');
const diagnostics=text('Gateway disconnected. Owned native playlists work without it.');
const assignmentRoot=dom.createElement('div');
const show=()=>{const d=gateway.status;diagnostics.textContent=d?`Target: ${d.target}. Playback authorization: ${d.playbackEnabled?'enabled for approved test IDs':'disabled'}. Audio: ${d.audioSource} (test transport only). Sendspin receiver: unavailable. Crossfade: unavailable.`:'Gateway disconnected. Owned native fallback is available.';};
button('Connect and load MA catalog',async()=>{if(!canConnect())throw new MusicError('denied');const value=code.value;code.value='';await gateway.connect(value);show();await renderAssignments();});
button('Refresh connection diagnostics',async()=>{await gateway.refresh();show();await renderAssignments();});
button('Disconnect gateway',async()=>{await gateway.disconnect();show();status.textContent='Gateway disconnected. Existing MA playback, if any, is retained; automatic fallback cannot bypass an unreachable owned target.';});
const 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();
mountMusicAssignments({game,container:assignmentRoot,choices,defaults:true,onError});
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);assignmentRoot.append(bossLabel);
const bossPanel=dom.createElement('div');assignmentRoot.append(bossPanel);const showBoss=()=>{bossPanel.replaceChildren();const document=documents.get(bosses.value);if(document)mountBossEditor({document,game,container:bossPanel,choices,onError});};bosses.addEventListener('change',showBoss);showBoss();
const manual=musicSelect(dom,choices,null,{empty:'Silence'});manual.setAttribute('aria-label','Manual music override');assignmentRoot.append(manual);
for(const [label,action]of [['Apply manual override',()=>setOverrides([{id:'gm-manual',playlist:selection(manual.value,choices)}])],['Clear manual override',()=>setOverrides([])]]){const b=dom.createElement('button');b.type='button';b.textContent=label;b.addEventListener('click',()=>Promise.resolve().then(action).catch(onError));assignmentRoot.append(b);}
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.';});
const listenerLabel=dom.createElement('label');listenerLabel.textContent='Separate listener connection code (memory only) ';const listener=dom.createElement('input');listener.type='password';listener.autocomplete='off';listenerLabel.append(listener);root.append(listenerLabel);
text('Enable Audio plays only the companion synthetic PCM test tone. It does not relay the MA DEV player or Sendspin audio. Crossfade is not available.');
// Start directly in the click task so AudioContext.resume retains user activation.
const enable=dom.createElement('button');enable.type='button';enable.textContent='Enable synthetic test audio';enable.addEventListener('click',()=>{try{const value=JSON.parse(listener.value);listener.value='';audio.start(gateway.audioRequest(value)).catch(onError);}catch{onError(new MusicError('denied'));}});root.append(enable);
button('Stop test audio',()=>audio.stop());show();return root;
return root;
}
_replaceHTML(result,content){content.replaceChildren(result);}
};
}
export function createListenerClass({game,gateway,audio,listenWebRTC,stopWebRTC=()=>{},onError,Base=globalThis.foundry.applications.api.ApplicationV2}){
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 (development)'},position:{width:480}};
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='Use a private GM WebRTC invitation, or an optional companion test code. No microphone or MA credentials are sent by players. GM-local MA audio remains experimental; never paste an MA token here.';root.append(note);
const label=dom.createElement('label');label.textContent='Listener connection code ';const input=dom.createElement('input');input.type='password';input.autocomplete='off';label.append(input);root.append(label);
const status=dom.createElement('p');status.setAttribute('role','status');root.append(status);
const enable=dom.createElement('button');enable.type='button';enable.textContent='Enable Audio';enable.addEventListener('click',()=>{try{const code=JSON.parse(input.value);input.value='';status.textContent='Connecting to campaign audio…';const task=code.transport==='webrtc-v1'?listenWebRTC(code):audio.start(gateway.audioRequest(code));Promise.resolve(task).then(()=>{status.textContent=code.transport==='webrtc-v1'?'Peer negotiation sent; waiting for GM media.':'Audio stopped.';}).catch(()=>{status.textContent='Audio unavailable. Check the private route, listener code and expiry.';onError(new MusicError('unavailable'));});}catch{status.textContent='Invalid listener code.';}});root.append(enable);
const stop=dom.createElement('button');stop.type='button';stop.textContent='Stop Audio';stop.addEventListener('click',()=>{stopWebRTC();audio.stop();});root.append(stop);return root;
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);}
};
+1 -1
View File
@@ -1,5 +1,5 @@
import {MusicError} from '../../core/controller.mjs';
const commands=new Set(['players/get','player_queues/get','player_queues/get_active_queue','player_queues/items','music/playlists/library_items','music/radios/library_items','music/playlists/get','music/playlists/playlist_tracks','music/tracks/get',...['play_media','play_index','pause','resume','stop','seek','shuffle','repeat','clear'].map(a=>'player_queues/'+a)]);
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;
+13 -6
View File
@@ -1,7 +1,14 @@
.adaptive-music-setup {display:grid;gap:0.7rem;max-height:75vh;overflow:auto;padding:0.5rem;}
.adaptive-music-setup fieldset,[data-adaptive-music="assignments"] {display:grid;gap:0.5rem;padding:0.75rem;}
.adaptive-music-setup fieldset:first-of-type {max-height:18rem;overflow:auto;}
.adaptive-music-setup label,[data-adaptive-music="assignments"] label {display:grid;gap:0.3rem;}
.adaptive-music-setup select,[data-adaptive-music="assignments"] select {width:100%;min-width:0;}
.adaptive-music-setup {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;}
.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;}
+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>
+37
View File
@@ -0,0 +1,37 @@
import {test} from 'node:test';
import assert from 'node:assert/strict';
import {AutoListeners} from '../../src/audio/auto-listeners.mjs';
import {newAudioInvite} from '../../src/audio/signal-codec.mjs';
const user=(id,isGM=false)=>({id,isGM,active:true,async setFlag(ns,k,v){this.value=structuredClone(v);},getFlag(){return this.value;}});
async function fixture(){
const gm=user('gm',true),player=user('player'),other=user('other'),users=[gm,player,other],packets=[],received=[];
const socket={on(){},off(){},emit(channel,packet){packets.push(packet);}};
const host=new AutoListeners({game:{world:{id:'world'},user:gm,users,socket},isGM:()=>gm.active,onInvite:assert.fail});
const listener=new AutoListeners({game:{world:{id:'world'},user:player,users,socket},isGM:()=>false,onInvite:invite=>received.push(invite)});
await host.start();await listener.start();return {gm,player,other,users,host,listener,packets,received,close(){host.close();listener.close();}};
}
test('automatic invitations use document-bound ephemeral keys and never broadcast the capability',async()=>{
const f=await fixture();try{
const invite=newAudioInvite({session:'session',userId:'player'});await f.host.send(f.player,invite);
assert.ok(!JSON.stringify(f.packets).includes(invite.secret));assert.deepEqual(Object.keys(f.gm.value).sort(),['epoch','key','v']);
await f.listener.receive(f.packets[0]);assert.deepEqual(f.received,[invite]);await assert.rejects(f.listener.receive(f.packets[0]),{code:'denied'});
}finally{f.close();}
});
test('forged GM claims, recipient changes, tampering and rotated document keys fail closed',async()=>{
const f=await fixture();try{
await f.host.send(f.player,newAudioInvite({session:'session',userId:'player'}));const packet=f.packets[0];
await assert.rejects(f.listener.receive({...packet,from:'other'}),{code:'denied'});
await assert.rejects(f.listener.receive({...packet,cipher:packet.cipher.slice(0,-4)+'AAAA'}));
await f.listener.receive({...packet,to:'other'});assert.equal(f.received.length,0);
f.gm.value={...f.gm.value,epoch:crypto.randomUUID()};await assert.rejects(f.listener.receive(packet),{code:'denied'});assert.equal(f.received.length,0);
}finally{f.close();}
});
test('parallel bootstrap replay, multiple GMs, revoked roles and expired capabilities cannot connect',async()=>{
const f=await fixture();try{
await f.host.send(f.player,newAudioInvite({session:'session',userId:'player'}));
const attempts=await Promise.allSettled([f.listener.receive(f.packets[0]),f.listener.receive(f.packets[0])]);assert.equal(attempts.filter(r=>r.status==='fulfilled').length,1);assert.equal(f.received.length,1);
await f.host.send(f.player,newAudioInvite({session:'session',userId:'player'}));f.other.isGM=true;await assert.rejects(f.listener.receive(f.packets[1]),{code:'denied'});f.other.isGM=false;
f.gm.isGM=false;await assert.rejects(f.listener.receive(f.packets[1]),{code:'denied'});f.gm.isGM=true;
await f.host.send(f.player,{...newAudioInvite({session:'session',userId:'player'}),expires:Date.now()-1});await assert.rejects(f.listener.receive(f.packets[2]),{code:'denied'});
}finally{f.close();}
});
+35
View File
@@ -64,3 +64,38 @@ test('peer signaling bounds queued work and rejects expired invites before alloc
const listener=new PeerAudio({socket,userId:'player',isGM:()=>false,createPeer:()=>{allocations++;}});
try{await assert.rejects(listener.listen({...newAudioInvite({session:'s',userId:'player'}),expires:0}),{code:'denied'});assert.equal(allocations,1);}finally{listener.close();}
});
test('wizard inspects only the imported dedicated identity, loads stable catalog IDs and enables guarded playlist playback',async()=>{
const calls=[];let requested=0;const target='dedicated-fixture';
const player={player_id:target,name:'Campaign receiver',provider:'sendspin-fixture',enabled:true,available:true,volume_level:35,volume_muted:false,group_members:[],group_childs:[],static_group_members:[]};
const queue={queue_id:target,active:true,available:true,items:0,state:'idle',shuffle_enabled:false,is_dynamic:false,autoplay_enabled:false,dont_stop_the_music_enabled:false,overlay_enabled:false,playback_speed:1};
const createSocket=url=>{
requested++;const socket={send(text){const msg=JSON.parse(text);calls.push(msg);queueMicrotask(()=>{
if(url.endsWith('/sendspin')){socket.onmessage?.({data:JSON.stringify({type:'auth_ok'})});return;}
const result=msg.command==='auth'?{authenticated:true}:msg.command==='players/get'?player:msg.command==='providers'?[{instance_id:'approved',available:true}]:msg.command.includes('library_items')?(msg.command.includes('playlists')?[{name:'Ambient',media_type:'playlist',is_playable:true,is_dynamic:false,provider_mappings:[{provider_instance:'approved',item_id:'ambient',available:true}]}]:[]):queue;
socket.onmessage?.({data:JSON.stringify({message_id:msg.message_id,result})});
});},close(){this.onclose?.();}};queueMicrotask(()=>socket.onopen?.());return socket;
};
const context={state:'running',destination:{},resume(){return Promise.resolve();},createMediaStreamDestination:()=>({stream:{getTracks:()=>[]}}),createGain:()=>({connect(){}}),close:async()=>{}};
const sdk={loadSendspinClientIdentity:()=>({clientId:target}),SendspinCore:class{timeSyncInfo={synced:true};async connect(){}disconnect(){}}};
const originalNavigator=globalThis.navigator;
Object.defineProperty(globalThis,'navigator',{configurable:true,value:{locks:{request:async(name,opts,fn)=>fn({})}}});
const host=new GMAudioHost({authority:()=>true,pageUrl:'https://foundry.example.test',loadSDK:async()=>sdk,createContext:()=>context,createSocket});
try{
const supplied={maUrl:'https://ma.example.test',token:'private-fixture',identityStorage:{'sendspin-identity-sk':'A'.repeat(43)},campaign:'world',targetName:player.name,webSocketAuthLogSafe:true,allowCatalogPlayback:true};
const profile=await host.inspect(supplied);assert.equal(profile.target,target);assert.deepEqual(profile.approvedProviders,['approved']);
const catalog=await host.readCatalog(profile,{reconnecting:true});const again=await host.inspect(supplied);assert.equal(profile.catalogKey,again.catalogKey);
await host.start(profile);assert.equal(host.connected,true);assert.equal(host.supports(catalog[0]),true);assert.equal(host.supports({provider:'ma',id:'forged'}),false);
assert.ok(calls.filter(c=>c.command==='players/get').every(c=>c.args.player_id===target));assert.ok(!calls.some(c=>c.command==='players/all'||c.command==='player_queues/play_media'));assert.ok(requested>=3);
await host.close();assert.equal(host.supports(catalog[0]),false);
}finally{await host.close();Object.defineProperty(globalThis,'navigator',{configurable:true,value:originalNavigator});}
});
test('disconnect cancels pending GM startup before any authenticated receiver connection',async()=>{
let release,entered=0,sockets=0;const loaded=new Promise(resolve=>{release=resolve;});
const host=new GMAudioHost({authority:()=>true,pageUrl:'https://foundry.example.test',loadSDK:()=>{entered++;return loaded;},createSocket:()=>{sockets++;},createContext:()=>({state:'running',resume:async()=>{},createMediaStreamDestination:()=>({stream:{getTracks:()=>[]}}),close:async()=>{}})});
const profile={maUrl:'https://ma.example.test',target:'dedicated',targetName:'Campaign',expectedProvider:'sendspin-fixture',identityStorage:{'sendspin-identity-sk':'A'.repeat(43)},approvedProviders:['approved'],catalogKey:'fixture',namespace:'world'};
const pending=host.start(profile);assert.equal(entered,1);await assert.rejects(host.start(profile),{code:'denied'});await host.close();release({});await assert.rejects(pending,{code:'stale'});assert.equal(sockets,0);assert.equal(host.connected,false);
assert.throws(()=>gmAccessPolicy('http://localhost','https://foundry.example.test'),{code:'mixed-content'});
assert.throws(()=>gmAccessPolicy('https://ma.example.test','http://foundry.example.test'),{code:'insecure-context'});
});
+11 -6
View File
@@ -1,6 +1,6 @@
import {test} from 'node:test';
import assert from 'node:assert/strict';
import {createSetupClass} from '../../src/foundry/setup.mjs';
import {createSetupClass,createListenerClass} from '../../src/foundry/setup.mjs';
import {ListenerAudio} from '../../src/foundry/listener-audio.mjs';
class Element{
constructor(tag,dom){this.tag=tag;this.ownerDocument=dom;this.children=[];this.listeners={};this.dataset={};this.value='';}
@@ -11,16 +11,16 @@ class Element{
}
const descendants=node=>[node,...node.children.flatMap(descendants)];
const collection=items=>{const map=new Map(items.map(i=>[i.id,i]));map[Symbol.iterator]=function*(){yield*map.values();};return map;};
test('GM setup connects catalog into independent scene editors and never persists its connection code',async()=>{
test('GM setup connects catalog into independent scene editors and never persists private GM authentication',async()=>{
const dom={createElement:tag=>new Element(tag,dom)};globalThis.document=dom;
let flag={},catalog=[];const settings={ownedPlaylistIds:'owned',musicDefaults:{},enabled:false},writes=[];
const scene={id:'scene',name:'Scene',active:true,getFlag:()=>flag,setFlag:async(ns,k,value)=>{flag=value;}};
const game={user:{isGM:true},playlists:collection([{id:'owned',name:'Owned'}]),scenes:collection([scene]),combats:[],settings:{get:(ns,k)=>settings[k],set:async(ns,k,value)=>{settings[k]=value;writes.push({k,value});}}};
const gateway={status:null,async connect(code){assert.equal(code,'capability-fixture');catalog=[{provider:'ma',id:'opaque-ma',name:'MA fixture',kind:'playlist'}];this.status={target:'verified',playbackEnabled:false,audioSource:'none'};},refresh:async()=>{},disconnect:async()=>{}};
const connection={status:{state:'disconnected',catalog:0,audioContext:'closed'},async test(profile){assert.equal(profile.token,'capability-fixture');assert.equal(profile.maUrl,'https://ma.example.test');catalog=[{provider:'ma',id:'opaque-ma',name:'MA fixture',kind:'playlist'}];return {target:'dedicated',targetName:'Adaptive Music DEV'};},async connect(target){assert.equal(target,'dedicated');},refresh:async()=>{},disconnect:async()=>{}};
try{
const Setup=createSetupClass({game,gateway,audio:{},getChoices:async()=>[{provider:'native',id:'owned',name:'Owned'},...catalog],start(){},stop(){},setOverrides(){},onError:assert.fail,Base:class{}});
const root=await new Setup()._renderHTML();const code=descendants(root).find(e=>e.tag==='input'&&e.type==='password');code.value='capability-fixture';
await descendants(root).find(e=>e.tag==='button'&&e.textContent==='Connect and load MA catalog').listeners.click();assert.equal(code.value,'');
const Setup=createSetupClass({game,connection,audio:{},getChoices:async()=>[{provider:'native',id:'owned',name:'Owned'},...catalog],start(){},stop(){},setOverrides(){},onError:assert.fail,Base:class{}});
const root=await new Setup()._renderHTML();const code=descendants(root).find(e=>e.tag==='input'&&e.type==='password');code.value='capability-fixture';descendants(root).find(e=>e.type==='url').value='https://ma.example.test';const checks=descendants(root).filter(e=>e.type==='checkbox');checks[0].checked=true;checks[1].checked=true;
await descendants(root).find(e=>e.tag==='button'&&e.textContent==='Test connection and load playlists').listeners.click();assert.equal(code.value,'');assert.ok(!descendants(root).some(e=>e.textContent==='Connect optional companion'));await descendants(root).find(e=>e.textContent==='Connect audio').listeners.click();
const panel=descendants(root).find(e=>e.tag==='fieldset'&&e.children.some(c=>c.tag==='legend'&&c.textContent==='Scene music'));
const selects=descendants(panel).filter(e=>e.tag==='select');assert.equal(selects.length,4);assert.ok(selects[0].children.some(o=>o.textContent.includes('MA fixture')));
selects[0].value='["ma","opaque-ma"]';selects[1].value='["native","owned"]';selects[3].value='["native","owned"]';
@@ -35,3 +35,8 @@ test('browser PCM sink resumes from gesture, decodes stereo frames and closes it
const audio=new ListenerAudio({createContext:()=>context,fetchImpl:async()=>{calls.push('fetch');return new Response(pcm,{headers:{'X-Audio-Format':'pcm16le;rate=24000;channels=2'}});}});
const pending=audio.start({url:'/audio',options:{}});assert.equal(calls[0],'resume');await pending;assert.equal(buffers[0][0][0],0.5);assert.equal(buffers[0][1][0],0.5);assert.ok(calls.includes('close'));assert.ok(calls.indexOf('resume')<calls.indexOf('fetch'));
});
test('normal listener has one activation action and no token or invitation entry',async()=>{
const dom={createElement:tag=>new Element(tag,dom)};globalThis.document=dom;let clicks=0;
try{const Listener=createListenerClass({game:{settings:{get:()=>false}},audio:{stop(){}},resumeListener:()=>{clicks++;},Base:class{}});const root=await new Listener()._renderHTML();assert.ok(!descendants(root).some(e=>e.tag==='input'));await descendants(root).find(e=>e.textContent==='Enable Audio').listeners.click();assert.equal(clicks,1);}finally{delete globalThis.document;}
});