Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
398749210a | ||
|
|
1d894f59fb | ||
|
|
0b1607cd20 | ||
|
|
1ed30567fb | ||
|
|
83d168f5a1 | ||
|
|
eb9536f903 | ||
|
|
5319177c58 |
No files matched your search
+90
-176
@@ -1,193 +1,107 @@
|
|||||||
# Adaptive Music architecture — 0.5.0 local release candidate
|
# Adaptive Music architecture — 0.7.2
|
||||||
|
|
||||||
Independent project by **CheddahBoxMB**, system-independent, targeting Foundry
|
Adaptive Music is an independent project by CheddahBoxMB for Foundry v14.371 and
|
||||||
**v14.371** and MA **2.10.6**. Standard distribution is **one Foundry module ZIP**
|
MA 2.10.6, with no system dependency or additional required process. The expanded
|
||||||
with a stable Git-hosted manifest and immutable version-specific download URL.
|
operator authorization selects direct trusted-GM browser access and GM-local
|
||||||
No mandatory Foundry modules, containers, VMs/LXCs, sandbox runtime, core patches,
|
credential handling for the standalone module; it supersedes the older gateway-only
|
||||||
OS-service installer, subscription or telemetry. Planned Gitea URLs are configured
|
scaffolding rule. Optional historical gateway source is not required or deployed.
|
||||||
but the host/repository has not been contacted or confirmed to exist.
|
|
||||||
|
|
||||||
## Decision after reevaluation
|
## Setup and receiver ownership
|
||||||
|
|
||||||
The 0.4.0 companion is **not a mandatory architecture**. Native playback and all
|
The Connection tab validates the server, token and optional Advanced network fields
|
||||||
scene/world/combat/boss/manual rules remain entirely module-local. The preferred
|
before authentication. The Connect gesture starts the GM audio context before
|
||||||
MA experiment is a trusted GM-browser host using the official Sendspin browser
|
authentication, receiver provisioning and catalog loading. Playback reads the
|
||||||
SDK, Web Audio and WebRTC audio tracks. Its feasibility is conditional on secure
|
dedicated MA queue and submits controls on the same controller as scene transitions.
|
||||||
private MA reachability, an authorized existing receiver identity, GM availability,
|
|
||||||
participant capabilities and a working ICE path. It cannot yet be represented as
|
|
||||||
reliable module-only remote MA audio for arbitrary networks.
|
|
||||||
|
|
||||||
The validated companion remains under `gateway/` and local branch
|
The GM supplies the private trusted HTTPS MA origin and access token. Authentication
|
||||||
`experimental/companion-0.4.0`; provider/catalog/restoration code is preserved.
|
reads account-authorized music providers. The official pinned Sendspin SDK generates
|
||||||
Shared Web Crypto transport/provider implementations now serve both GM and optional
|
one X25519 identity for the campaign, GM user and MA origin. Its identity, pairing
|
||||||
companion, with compatibility exports at the original gateway paths. All original
|
storage, catalog key and name are encrypted in local IndexedDB with a non-extractable
|
||||||
regressions remain. If the browser gates cannot be met, propose one manually run,
|
AES-GCM key. The key is stored in the same browser; this does not protect against
|
||||||
restricted process **co-located on the existing Foundry host**. No new machine,
|
trusted-origin scripts or theft of the complete browser profile. The token is never
|
||||||
container or automatic service is proposed or deployed. Placement/routing and any
|
persisted. Failed attempts retain private inputs in tab memory; changing the MA
|
||||||
manual service registration require explicit approval after concrete review.
|
origin never reuses its token or identity.
|
||||||
|
|
||||||
```mermaid
|
The logged-in GM account can retain an AES-GCM envelope containing the last
|
||||||
flowchart LR
|
successfully connected MA address and receiver name in a Foundry User Setting.
|
||||||
F[Foundry scene and combat policy] --> C[Existing serialized controller]
|
The MA token supplied for a connection unlocks the envelope. Its key is derived
|
||||||
C --> N[Owned native playlist provider]
|
with a separate purpose label and bound to the Foundry origin, world and user.
|
||||||
C --> M[Shared guarded MA provider in trusted GM browser]
|
Foundry persists the encrypted record across devices and server restarts.
|
||||||
M -->|private authenticated API WebSocket| A[Private MA 2.10.6]
|
|
||||||
A -->|authenticated Sendspin to pinned existing identity| S[Official SDK in GM browser]
|
|
||||||
S --> W[Web Audio MediaStream]
|
|
||||||
W -->|DTLS SRTP media tracks| P[Authorized player browsers]
|
|
||||||
G[Foundry module socket] <-->|bounded encrypted SDP only| S
|
|
||||||
G <-->|bounded encrypted SDP only| P
|
|
||||||
```
|
|
||||||
|
|
||||||
No raw audio or MA token uses the ordinary module socket. No MA HTTP/WS/Sendspin
|
Connect audio first authenticates the `/ws` API session, then authenticates
|
||||||
proxy is exposed to players. No microphone is requested and no RTC control data
|
`/sendspin` using that token and the SDK-generated client ID. MA 2.10.6 associates
|
||||||
channel is accepted. A GM's credentials are **not hidden from that GM/browser user**;
|
this new web receiver with already-authenticated API sessions for the token. The
|
||||||
all code executing in that browser origin must be trusted. Other player browsers
|
same API session must therefore survive pairing, catalog reads and playback.
|
||||||
never receive the MA credential, SDK identity, private queue snapshots or endpoint.
|
`sendspin/pair_web_player` pairs only this identity to the calling account. Noise
|
||||||
|
activation and clock synchronization precede exact ID/name/provider/topology checks.
|
||||||
|
During startup, a successful null queue lookup is retried briefly on the same
|
||||||
|
authenticated API session because MA can expose the player before registering its
|
||||||
|
queue. Playback requires the receiver’s own active queue.
|
||||||
|
There is no household player list or arbitrary target selector.
|
||||||
|
|
||||||
## What is measured
|
The receiver uses SDK software volume. Fresh receivers do not report volume before
|
||||||
|
capabilities are advertised, so volume cannot be a preconnection requirement. Static
|
||||||
|
account-authorized playlist tracks become opaque HMAC references bound to the stored
|
||||||
|
catalog key and campaign. New references use a separate key derived from the MA
|
||||||
|
token, MA origin and campaign so the same authorized catalog resolves on another
|
||||||
|
browser. A browser with its original receiver vault still resolves legacy IDs.
|
||||||
|
Saving that scene again writes the new reference. Scene/world flags hold opaque
|
||||||
|
references. Live connections still depend on the active GM browser and its audio
|
||||||
|
context. Disconnect stops the session and clears the in-memory token.
|
||||||
|
|
||||||
`evidence/browser-audio.json`: actual Chromium **143.0.7499.4**, two independent
|
## Audio and listeners
|
||||||
listener browser contexts, original 440 Hz synthetic PCM encoded in Sendspin binary
|
|
||||||
frames and decoded by the pinned official SDK, Web Audio -> WebRTC -> HTMLAudio /
|
|
||||||
listener analyser. Both listeners had signal after **1,757 ms**, FFT peak **445.3125
|
|
||||||
Hz** (bin resolution around the 440 Hz source), RMS about **0.054**, aggregate GM RTP
|
|
||||||
payload **42.3 kbps** over **4.766 seconds**. Four encrypted signaling messages,
|
|
||||||
maximum **2,078 bytes**; no audio on the signaling channel. Localhost, no TURN, no
|
|
||||||
MA/Noise handshake, no real Foundry socket, no hardware audibility claim, no WAN,
|
|
||||||
interlistener skew or long-run drift measurement. These are synthetic path results,
|
|
||||||
not MA playlist playback or synchronization verification.
|
|
||||||
|
|
||||||
Live dedicated target/queue reads still verify the existing DEV identity and an
|
The pinned official SDK negotiates PCM, performs Noise and time synchronization,
|
||||||
empty idle queue. `module-only-prerequisites.json`: the configured MA origin is
|
and decodes audio. A bounded Web Audio scheduler accepts the normal approximately
|
||||||
HTTP, the HTTPS-host access policy rejects it as mixed content, and no authorized
|
four-second stream-ahead window (six-second ceiling, 512 nodes and 2 MiB of decoded
|
||||||
DEV private SDK identity is available locally. **Zero new Sendspin connections,
|
buffers). Timestamped partial clears trim only affected audio. Full clears and ends
|
||||||
identities or playback mutations.** Earlier read-only catalogs and bounded idle
|
stop the stream. A software gain and output meter feed the GM speakers and a single
|
||||||
controls remain separate evidence; synthetic ingestion previously failed.
|
MediaStreamDestination track for listener distribution.
|
||||||
|
|
||||||
## Browser access and GM-local authentication
|
User document public keys authenticate ephemeral ECDH/AES-GCM invitation delivery.
|
||||||
|
Private keys stay in memory. Invitations are bound to world, sender, recipient,
|
||||||
|
epochs and expiry. Each player receives only its own WebRTC capability. Bounded
|
||||||
|
AES-GCM envelopes carry SDP over Foundry’s module socket; audio uses DTLS-SRTP,
|
||||||
|
never PCM over that socket. Firefox’s session-level SDP direction default is
|
||||||
|
correctly overridden by the sole audio media direction. Offers remain recvonly;
|
||||||
|
answers remain sendonly. Video, data and injected sender media are rejected.
|
||||||
|
|
||||||
`GMAudioHost` uses a private, memory-only profile supplied by the GM, with canonical
|
Up to eight listeners negotiate automatically. Invitations renew after 20 minutes
|
||||||
MA origin, dedicated target ID/name/provider, approved provider filter, catalog key/
|
and expire after 30. Failed negotiation times out after 20 seconds; disconnected
|
||||||
namespace and existing SDK identity/pairing storage. Nothing is saved into Foundry
|
peers are revoked after 10 seconds and the 15-second reconciliation loop can issue
|
||||||
settings, flags, browser localStorage, module socket or a release. Catalog IDs remain
|
fresh invitations. One user gesture unlocks browser audio when required. A stable
|
||||||
HMAC-derived and stable when the operator retains the same private key/namespace.
|
HTMLAudioElement pumps the incoming remote track; Web Audio provides an optional
|
||||||
|
activated playback path. Default ICE has no public STUN/TURN service. WAN delivery
|
||||||
|
requires a viable existing ICE route and is not inferred from local tests.
|
||||||
|
|
||||||
The official public `/ws` control API avoids dependence on cross-origin HTTP `/api`
|
## Transitions and recovery
|
||||||
preflight, which is not configured for that route in the inspected MA pin. The same
|
|
||||||
fixed client command allowlist, response bounds, timeout, redirect policy, target
|
|
||||||
checks and registered-media rules are preserved through the WebSocket adapter.
|
|
||||||
Its initial auth command carries the GM's token in a private connection, never a
|
|
||||||
URL; unsolicited events are discarded. The Sendspin `/sendspin` connection uses
|
|
||||||
the official frontend's first-message auth pattern, then the official SDK's Noise
|
|
||||||
transport. The SDK's fixed roles include controller/metadata; it runs only in the
|
|
||||||
trusted GM host, never as a supposedly restricted player listener.
|
|
||||||
|
|
||||||
A source-derived privacy gate matters: pinned MA `websocket_client.py` logs raw
|
Manual override/silence > explicit boss > started combat in the active scene >
|
||||||
received frames at VERBOSE, including auth. The GM profile requires an explicit
|
ambient > world default > silence. No system actor schemas are used. The existing
|
||||||
operator `webSocketAuthLogSafe` acknowledgment after ensuring such payload logging
|
serialized controller checks campaign/session/generation and current authority.
|
||||||
is disabled. This has **not** been verified live or changed by the agent. No live
|
A single active GM plus a Web Lock excludes common duplicate tabs; this is not a
|
||||||
WebSocket token test was attempted. The module logs no credential and does not
|
server-side distributed fence or seamless handover protocol.
|
||||||
modify MA logging/core. An adapter cannot redact the remote server's own logs.
|
|
||||||
|
|
||||||
HTTPS Foundry -> plain HTTP/ws private MA is not a generally portable browser path,
|
Every queue mutation verifies the exact dedicated target, standalone topology and
|
||||||
even with encrypted Sendspin payloads. CSP, browser local-network access rules,
|
its own active queue. Signed snapshots retain ordered duplicates, index, repeat,
|
||||||
Origin policy, TLS trust and private routing still apply. Current policy refuses
|
whole-second position and state, scoped to campaign/session/fence/generation for up
|
||||||
that deployment rather than disabling browser protections. Local-network exceptions
|
to 12 hours. Ambiguous writes latch closed and stop automation; they are not retried.
|
||||||
in particular browsers are not a cross-browser guarantee. A private trusted HTTPS/
|
MA Sendspin lacks native pause in 2.10.6, so pause retains a logical stopped-queue
|
||||||
WSS MA endpoint reachable by the GM, or the approved co-located restricted worker,
|
snapshot and resume explicitly seeks its item. A paused restore rebuilds without
|
||||||
is required. Players do not need MA network access.
|
briefly playing. This logical pause state is memory-only.
|
||||||
|
|
||||||
SDK identity is derived from an X25519 private key. A player name or ID alone cannot
|
Reconnecting to a remembered owned receiver can attach to its existing queue
|
||||||
reconstruct it. The code checks the supplied identity matches **Adaptive Music DEV**
|
without replacing it. Automation remains paused for explicit resumption when that
|
||||||
before any receiver connection; no random replacement, discovery-and-select, pairing
|
queue is nonempty. Crash/reload cannot guarantee restoration of an interrupted
|
||||||
or internal virtual-player provisioning occurs. Operator-controlled handover from
|
ambient stack or logical pause position. No crossfade or independent simultaneous
|
||||||
the original web player is needed. Read-only identity/topology checks may inspect
|
layers is implemented with the single upstream queue. Native playback uses only
|
||||||
the known unavailable target during handover; every mutation still requires full
|
explicitly owned playlists; effects and AmbientSound remain untouched.
|
||||||
availability, exact name/provider, own active queue and standalone topology.
|
|
||||||
|
|
||||||
## WebRTC signaling, authorization and transport
|
## Verification boundary
|
||||||
|
|
||||||
Foundry's supported `game.socket`/module channel is a relay, not an authenticated
|
The installed v0.7.0 module was tested in a logged-in Foundry v14.371 development
|
||||||
claim of sender identity. We do **not** trust a payload `userId`/`isGM` or assume
|
world through the private Nginx route. The GM connected to MA and two players
|
||||||
that broadcast destinations enforce confidentiality. The GM explicitly issues a
|
received audio using Foundry’s module socket for signaling. The test also exercised
|
||||||
unique short-lived 256-bit per-listener invitation, delivered over an authenticated
|
real combat hooks, ordered ambient restoration, and User document permissions.
|
||||||
private channel outside the module broadcast. Possession authorizes only that peer;
|
Earlier browser tests used a Playwright source overlay. The original Mac path,
|
||||||
it does not prove a Foundry login cryptographically, and a recipient can forward
|
physical-device audibility, invitation renewal and WAN behavior remain unverified.
|
||||||
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.
|
|
||||||
@@ -1,5 +1,58 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## 0.7.2 — account-scoped connection setup
|
||||||
|
|
||||||
|
- Remember the Music Assistant address and receiver name in an encrypted Foundry User Setting. Enter the MA token to unlock the saved address and connect in a new browser session.
|
||||||
|
- Make newly saved catalog assignments readable across browsers that use the same MA token, server and Foundry world. Preserve legacy reference resolution in the browser that created it.
|
||||||
|
|
||||||
|
## 0.7.1 — AM-006 setup usability
|
||||||
|
|
||||||
|
- Give the resizable GM window three tabs for Connection, Scene Music and Playback.
|
||||||
|
- Connect with one action that validates the inputs, authenticates, provisions the
|
||||||
|
dedicated receiver and loads playlists. Keep listener networking under Advanced.
|
||||||
|
- Show the current track, position, volume, automation state and connected listener
|
||||||
|
count. Queue pause, resume, seek and stop through the existing playback authority.
|
||||||
|
|
||||||
|
## 0.7.0 — integrated campaign receiver
|
||||||
|
|
||||||
|
- Replace receiver JSON import with authenticated automatic dedicated web-receiver
|
||||||
|
provisioning and account-bound pairing. Remember the receiver privately in the
|
||||||
|
GM browser; retain the MA token only in tab memory.
|
||||||
|
- Keep one authenticated API session established before Sendspin so restricted MA
|
||||||
|
accounts retain the receiver’s session permissions. Wait briefly for MA to
|
||||||
|
register the dedicated queue during setup. Use SDK software volume.
|
||||||
|
- Fix Firefox SDP direction inheritance, PCM stream-ahead scheduling and timestamped
|
||||||
|
partial clears. Add transport, authentication, pairing, clock, audio and listener
|
||||||
|
diagnostics in the interface. Fix narrow ApplicationV2 layout.
|
||||||
|
- Preserve inputs across failures, retain receiver identity across reloads, and allow
|
||||||
|
reconnection to the owned queue without replacing it. Pause automation on uncertain
|
||||||
|
writes; do not retry queue mutations blindly. Bound failed listener negotiation.
|
||||||
|
- Emulate pause for MA 2.10.6 Sendspin using stopped queue plus saved index/position;
|
||||||
|
restore paused queues without briefly playing them. Keep active-session interruption
|
||||||
|
snapshots for up to 12 hours rather than five minutes.
|
||||||
|
- Exercise actual MA catalog audio, two browser listeners, combat transitions and queue
|
||||||
|
restoration in Firefox and Chromium. Preserve the failing queue command in
|
||||||
|
diagnostics and skip rollback on uncertain writes.
|
||||||
|
- Preserve existing Gitea manifest/update URLs and manual publication bundles.
|
||||||
|
Crossfade and durable crash restoration remain unsupported.
|
||||||
|
|
||||||
|
## 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
|
## 0.5.0 — local release candidate
|
||||||
|
|
||||||
- Prepare one standard Foundry module ZIP and offline manual-upload release bundle
|
- Prepare one standard Foundry module ZIP and offline manual-upload release bundle
|
||||||
|
|||||||
+68
-136
@@ -1,150 +1,82 @@
|
|||||||
# Adaptive Music 0.5.0 — manual release and installation
|
# Install and connect — 0.7.2
|
||||||
|
|
||||||
Module ID **adaptive-music**, author **CheddahBoxMB**, Foundry generation **14**;
|
## Normal setup
|
||||||
system-independent, no mandatory Foundry modules. Native operation needs only this
|
|
||||||
module ZIP. No container, VM/LXC, Ubuntu sandbox, core patch or automatically installed
|
|
||||||
OS service is required. GM-local MA/WebRTC audio remains experimental; limitations
|
|
||||||
and measured results are in ARCHITECTURE.md and evidence/browser-audio.json.
|
|
||||||
|
|
||||||
## Build offline without Git credentials or a remote
|
1. Install or update **Adaptive Music** using the existing Foundry manifest URL.
|
||||||
|
For the staged acceptance build, extract `adaptive-music.zip` into the existing
|
||||||
|
Foundry user-data `Data/modules/` directory and reload the isolated test world.
|
||||||
|
The ZIP contains one `adaptive-music/` directory. Do not install the outer release
|
||||||
|
bundle or source archive as the module.
|
||||||
|
2. As the single active GM, open Settings → Adaptive Music setup. In **Connection**,
|
||||||
|
enter the private **HTTPS Music Assistant server address** and the dedicated
|
||||||
|
account’s access token. Use the server origin and select **Connect** to create or
|
||||||
|
reconnect the campaign receiver, pair it, and load playlists.
|
||||||
|
3. Select **Choose scene music**. In **Scene Music**, choose the scene and save its
|
||||||
|
ambient, combat, boss and native fallback assignments. You can also set world
|
||||||
|
defaults and individual boss overrides.
|
||||||
|
4. Open **Playback** to enable automation, see the current track and listeners, or
|
||||||
|
adjust campaign volume and control the dedicated MA queue.
|
||||||
|
5. Players connect automatically. If a browser requires activation, open Campaign
|
||||||
|
audio and select **Enable Audio** once. Keep one audio tab per account.
|
||||||
|
|
||||||
From this repository (Python 3 standard library; local Git metadata is optional):
|
After a successful connection, the GM’s Foundry account remembers the encrypted
|
||||||
|
server address and receiver name. On another computer or after reload, enter the
|
||||||
|
same MA token and select **Connect** to unlock the saved address. Reload and
|
||||||
|
**Disconnect** clear the in-memory token. If the token changes, enter the server
|
||||||
|
address with the replacement token. **Advanced → Forget saved connection** clears
|
||||||
|
the account record. The receiver identity remains encrypted in its browser vault.
|
||||||
|
|
||||||
```
|
New MA playlist assignments resolve across browsers using the same MA token and
|
||||||
python3 scripts/release.py
|
origin. To update a legacy assignment, connect from the browser that originally
|
||||||
python3 scripts/release.py --validate dist/releases/v0.5.0/adaptive-music.zip
|
saved it and save the scene again. From a different browser, reselect its playlists.
|
||||||
```
|
Keep the active GM browser open for live MA playback and listener forwarding.
|
||||||
|
|
||||||
This creates `dist/releases/v0.5.0/adaptive-music-release-v0.5.0.zip`. It contains:
|
Reconnecting to an owned nonempty queue preserves it. Enable automation in Playback
|
||||||
`adaptive-music.zip`, standalone `module.json`, `adaptive-music-source.zip`, README,
|
when ready to resume scene control. Unknown mutation outcomes stop automation and
|
||||||
this INSTALL guide, CHANGELOG, LICENSE, THIRD-PARTY-NOTICES, all vendor license
|
require review. Pause preserves a stopped queue’s index and position for the active
|
||||||
texts, `release.json` and `SHA256SUMS`. The SDK bundle is committed, so packaging
|
GM session.
|
||||||
needs no npm installation, browser download, network, Git token or Git-host access.
|
|
||||||
The builder never verifies, contacts, creates or pushes a remote repository.
|
|
||||||
|
|
||||||
For another host, for example your own public GitHub repository:
|
## Connection diagnostics
|
||||||
|
|
||||||
```
|
Connection shows authentication, receiver setup and catalog progress. **Check browser
|
||||||
python3 scripts/release.py --repository https://github.com/OWNER/adaptive-music --output dist/github-release
|
connection** tests both WebSocket routes from the actual Foundry page without sending
|
||||||
```
|
an MA authentication frame. Normal browser cookies can accompany the handshake.
|
||||||
|
**Copy connection diagnostics** supplies a report without address, token, receiver
|
||||||
|
keys or playlist titles. No browser developer console is required.
|
||||||
|
|
||||||
Use a real destination under your control. The generated manifest's `url`, stable
|
| Result | Action |
|
||||||
`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
|
| Enforced CSP block | Have the host administrator review an exact trusted WSS-origin allowance in the existing connect-src policy. Do not remove CSP or allow all origins. |
|
||||||
compatibility, import/assets closure, SDK hash, licenses, private-file exclusion and
|
| Socket fails before opening | Compare this browser’s MA page, private DNS/routing and local-network site permission. Browser APIs conceal the precise HTTP/TLS failure. |
|
||||||
public HTTPS URL shape locally. This cannot prove that a planned URL exists.
|
| API auth denied | Enter a valid token; the remembered receiver is retained. |
|
||||||
|
| Sendspin auth/pair/sync fails | Check the separate authenticated /sendspin route and the account’s web-player control permission. |
|
||||||
|
| Dedicated queue unavailable after pairing | Retry connecting the remembered receiver after MA has registered its queue. |
|
||||||
|
| Frames arrive but audio is suspended | Select Enable GM audio or the player’s Enable Audio once. |
|
||||||
|
| Listener fails negotiation | Check its diagnostics and existing network/ICE route. It is automatically retried after timeout. |
|
||||||
|
| MA error 2 on playlist startup | MA could not find playable media even if catalog metadata exists. Check that content/provider in MA; this is separate from a WebSocket upgrade failure. |
|
||||||
|
| Unknown queue write | Review the dedicated queue, then deliberately reconnect; no blind retry occurs. |
|
||||||
|
|
||||||
## Upload to the planned Gitea destination manually
|
Use trusted HTTPS for Foundry and private HTTPS/WSS for both MA `/ws` and `/sendspin`.
|
||||||
|
Keep Nginx access restrictions, Origin, certificate validation and browser protections.
|
||||||
|
Keep MA raw-frame VERBOSE logging disabled. No public API/proxy, core modification,
|
||||||
|
additional container, service, VM or LXC is required by this module. A direct HTTP MA
|
||||||
|
address cannot be used from HTTPS Foundry. Default ICE does not use a public relay;
|
||||||
|
remote players still need a viable existing WebRTC path.
|
||||||
|
|
||||||
Planned repository (existence/access **not checked**):
|
See TESTING.md for private-route evidence and the outstanding installed, Mac and WAN checks.
|
||||||
`https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music`
|
|
||||||
|
|
||||||
1. On your own initiative, use Gitea's web UI to create/confirm that repository and
|
## Manual Gitea publication
|
||||||
enable public read access to the source manifest and release attachments. Foundry
|
|
||||||
must be able to fetch them without Git credentials. This exposes release files,
|
|
||||||
not MA. This agent has not accessed or authenticated with your Gitea server.
|
|
||||||
2. Unpack the **source archive**, not the outer release bundle, into the repository
|
|
||||||
using your normal Git/web upload workflow. Preserve directory structure, notices,
|
|
||||||
scripts and the generated root `module.json`. Exclude `.local/`, node_modules,
|
|
||||||
private deployment files and credentials. Do not upload an outer bundle as the
|
|
||||||
module contents. If web upload cannot preserve folders, use your own local Git
|
|
||||||
client; no credential is needed by the release builder itself.
|
|
||||||
3. Create tag/release **v0.5.0** for this version. Keep that tag immutable. Paste the
|
|
||||||
CHANGELOG entry into the release notes. Do not mark this unverified development
|
|
||||||
release as Foundry-verified or production-ready.
|
|
||||||
4. Upload **adaptive-music.zip** and **module.json** as release attachments with
|
|
||||||
those exact names. Upload source/archive, SHA256SUMS, docs/notices or the full
|
|
||||||
outer bundle as additional review artifacts. Never use the source ZIP or outer
|
|
||||||
bundle as the module download attachment.
|
|
||||||
5. After publishing, manually verify anonymous downloads and checksums. The module
|
|
||||||
ZIP should resolve at:
|
|
||||||
`https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/releases/download/v0.5.0/adaptive-music.zip`
|
|
||||||
6. Ensure `main/module.json` is the generated standalone manifest. The stable
|
|
||||||
installation/update URL is:
|
|
||||||
`https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/raw/branch/main/module.json`
|
|
||||||
This URL is deliberately stable across releases. Do not give Foundry a tag-specific
|
|
||||||
manifest URL if you expect automatic version discovery.
|
|
||||||
|
|
||||||
No URL above was requested by the build/validation process. Uploading/publishing is
|
The existing stable manifest and versioned download mechanism is preserved:
|
||||||
manual; no token, remote connection, automatic push or release publication is used.
|
|
||||||
|
|
||||||
## Install and update through Foundry
|
- Manifest: `https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/raw/branch/main/module.json`
|
||||||
|
- v0.7.2 asset: `https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/releases/download/v0.7.2/adaptive-music.zip`
|
||||||
|
|
||||||
Once the public manifest and release attachments actually exist:
|
These are the established repository’s URLs; this work never contacted Gitea or
|
||||||
|
verified public asset availability. After acceptance, manually publish the included
|
||||||
1. In isolated Foundry v14 Setup → Add-on Modules → Install Module, paste the stable
|
source to your existing repository, create tag/release `v0.7.2`, attach
|
||||||
manifest URL above and install. Enable Adaptive Music in the isolated world.
|
`adaptive-music.zip` and the included manifest/checksums, and update the branch
|
||||||
2. Configure Settings → Adaptive Music setup: select dedicated native music playlists,
|
manifest only after its versioned asset exists. The outer bundle includes full
|
||||||
save ownership/reload, set world/scene ambient/combat/boss/native fallback choices,
|
source, docs, licenses, metadata and SHA256SUMS. Keep the previous immutable release
|
||||||
then enable automation. Sound effects/AmbientSound are excluded. Automation
|
assets for rollback. To roll back, restore the prior branch manifest/module ZIP;
|
||||||
defaults off. Test real v14.371 behavior before considering production use.
|
MA queues and remembered browser identities are not automatically deleted.
|
||||||
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.
|
|
||||||
+49
-97
@@ -1,104 +1,56 @@
|
|||||||
# Adaptive Music progress — 0.5.0
|
# Adaptive Music progress — 0.7.2 staged acceptance
|
||||||
|
|
||||||
Continued from `50c3a7c`; the complete 0.4.0 companion implementation is preserved
|
Standalone module work now includes automatic campaign receiver provisioning and
|
||||||
at local branch `experimental/companion-0.4.0` as well as in `gateway/`. The original
|
account-bound pairing, remembered encrypted browser-local identity, memory-only token
|
||||||
0.3.0 ZIP gap audit remains `evidence/package-objective-audit.json`; it describes
|
retention/retry, scene assignments, listener bootstrap, guarded transitions and queue
|
||||||
that historical package, not the current release. No validated code was discarded.
|
restoration. Existing Gitea URLs/manual release mechanism are preserved. No Git host
|
||||||
|
was accessed and no production infrastructure/core versions were changed.
|
||||||
|
|
||||||
## Implemented
|
## Defects
|
||||||
|
|
||||||
The standard release is one module ZIP, ID `adaptive-music`, author CheddahBoxMB,
|
| Defect | Implemented and tested | Remaining acceptance |
|
||||||
Foundry generation 14, no mandatory modules or system dependency. Python's offline
|
| --- | --- | --- |
|
||||||
builder produces a complete manual upload bundle, stable manifest/versioned download,
|
| AM-001 layout | Actual Foundry v14.371 ApplicationV2 at 380/640px; Chromium fixture at 380/640/1000px | Operator’s logged-in-world theme |
|
||||||
source archive, docs/licenses and checksums. Gitea/GitHub repository base is configurable.
|
| AM-002 provisioning | SDK-created identity, authenticated dedicated web-receiver pairing, no normal JSON import; real MA tests | Normal installed-world flow on Mac |
|
||||||
The default destination is the user's **planned, unconfirmed** Gitea repository.
|
| AM-003 diagnostics | Per-route upgrade/CSP checks, staged auth/pair/sync errors, output counters and copyable secret-free listener report | Original Mac failure report if it persists |
|
||||||
It was not contacted, authenticated with, created or pushed to. Git remotes and
|
| AM-004 retry retention | Tab-private draft; encrypted receiver vault; token/identity origin binding; Firefox and Chromium reattached after transport loss and reload without replacing the queue | Mac reload/retry/network lifecycle |
|
||||||
credentials are not required. CI artifact workflows are prepared but unexecuted;
|
| AM-005 cross-origin | Both WSS routes open through private Nginx in Ubuntu Chromium and Firefox. Chromium authenticated and paired in the installed Foundry world. The MA front end’s unauthenticated Sendspin interceptor explains the failing control probe. | Original Mac-specific pre-upgrade failure remains unresolved |
|
||||||
no runner or OS service is installed. Publication and hosted updates are unverified.
|
| AM-006 setup usability | The v0.7.1 browser preview passed layout at 380 and 760 pixels, one-click connection, scene assignment and real playback controls in the development world. | Retry the same workflow with v0.7.1 installed on the server |
|
||||||
|
| Account persistence | The v0.7.2 preview saved an encrypted connection record in the Foundry GM account and connected from a fresh browser with the token alone. New scene references are portable across browsers using that token. | v0.7.2 server installation and Mac acceptance |
|
||||||
|
| MA catalog playback | The installed module delivered audio to two real Foundry players during ambient, combat and restoration to a seven-second offset. Stop/Enable and reload were exercised. | Physical devices, invitation renewal and WAN acceptance |
|
||||||
|
|
||||||
Native playback and scene/world/combat/boss/manual configuration are preserved.
|
## Technical findings
|
||||||
Persistent ambient/combat/boss/native fallback references, world defaults, legacy
|
|
||||||
migration, explicit combatant flags and native ownership remain connected to the
|
|
||||||
existing controller. The shared guarded MA client/provider now use Web Crypto,
|
|
||||||
retaining the optional companion import paths and stable catalog IDs/signatures.
|
|
||||||
|
|
||||||
The new experimental GM host uses the official pinned Sendspin 5.0.0 SDK, a
|
- The operator’s scoped firewall exception enabled TCP 443 and trusted TLS to the
|
||||||
reproducible PCM-only browser bundle with audited notices, Web Audio termination
|
private Nginx proxy. The test verified the proxy peer before signing in on the
|
||||||
and WebRTC audio tracks. GM-local MA authentication uses the public `/ws` API;
|
normal Foundry hostname. The signed-in page had no enforced CSP header or meta
|
||||||
no raw unrestricted proxy, browser player credential or external CDN is introduced.
|
policy and both MA WebSocket upgrades returned HTTP 101.
|
||||||
The existing DEV private identity must match before a receiver connection; no new
|
- Browser playback analysers measured audio on both real Foundry listeners even
|
||||||
identity/target/pairing or internal provisioning was attempted. Only approved
|
while Chromium’s inbound RTP energy statistic reported zero. The integration
|
||||||
synthetic sequences can be controlled by this path. Real catalog selections are
|
test uses the rendered playback signal. No module runtime change was required.
|
||||||
available through the developer connection API and existing assignment UI; actual
|
- MA grants a new browser receiver access through API sessions authenticated before
|
||||||
playlist playback is still separately gated. GM setup for MA remains developer-API
|
Sendspin auth. Replacing the API socket breaks a restricted account’s access.
|
||||||
based; there is no claim of a finished one-click connection wizard.
|
- Firefox reached an available paired receiver before MA returned its queue. Setup
|
||||||
|
now waits briefly for a missing queue on the same session. The regression fixture
|
||||||
|
exercises the delayed reply; the live follow-up received the queue immediately.
|
||||||
|
- A new receiver’s volume is initially null. SDK software volume avoids that startup
|
||||||
|
dependency and provides campaign volume without controlling unrelated players.
|
||||||
|
- Firefox adds a session sendrecv default after ICE gathering. Correct SDP validation
|
||||||
|
honors the audio media recvonly override and still rejects sender/video/data offers.
|
||||||
|
- MA sends PCM roughly four seconds ahead. The old two-second scheduler cutoff dropped
|
||||||
|
most real audio; bounded six-second scheduling and timestamped clears address it.
|
||||||
|
- MA 2.10.6 Sendspin has no native pause. Logical stop-plus-position pause is implemented
|
||||||
|
and tested, including paused restoration without briefly playing.
|
||||||
|
- Five-minute snapshot expiry was too short for combat. Signed active-session snapshots
|
||||||
|
now last up to 12 hours and remain campaign/session/fence/generation-bound.
|
||||||
|
|
||||||
Listener capabilities are separate from controller access. Foundry module sockets
|
The live follow-up records real PCM and two listener signals, emulated pause, seek,
|
||||||
carry per-peer encrypted bounded SDP/control; WebRTC transports continuous audio.
|
resume, volume, and queue restoration in Firefox and Chromium. Earlier catalog
|
||||||
No microphone, video, data channel, automatic STUN/TURN or raw PCM socket transport.
|
startup failed with MA `MediaNotFoundError` in both engines. The cause of those
|
||||||
Expiry, revocation, role changes and disconnect tear down peers; there are bounded
|
failures remains unconfirmed. The controller preserves the failed command and skips
|
||||||
explicit ICE restarts. Same-origin GM Web Locks and a single-active-GM check reject
|
rollback after an uncertain write. See `evidence/v0.7.0-live-follow-up.json`.
|
||||||
obvious conflicts, but do not constitute a distributed MA fence. Memory-only secret
|
|
||||||
handling cannot hide secrets from the GM browser's own user.
|
|
||||||
|
|
||||||
## Actual observations
|
The installed-world evidence is in `evidence/v0.7.0-foundry-private.json`. Publication
|
||||||
|
remains pending Mac, physical-device, WAN and invitation-renewal checks in TESTING.md.
|
||||||
- **85 JS / 15 Python tests pass**; repository privacy/attribution and recorded
|
Crossfade, durable crash restoration, seamless handover and WAN synchronization
|
||||||
upstream hashes pass. Online npm advisory audit reports zero vulnerabilities.
|
remain unsupported.
|
||||||
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.
|
|
||||||
@@ -1,61 +1,29 @@
|
|||||||
# Adaptive Music — 0.5.0 development
|
# Adaptive Music — 0.7.2
|
||||||
|
|
||||||
Independent open-source project by **CheddahBoxMB**, targeting Foundry VTT **v14.371**
|
Independent open-source Foundry VTT music automation by **CheddahBoxMB**, targeting
|
||||||
and Music Assistant **2.10.6**, independent of game system and other modules.
|
Foundry v14.371 and Music Assistant 2.10.6. System-independent; one Foundry module
|
||||||
This is a development release; it has not been exercised inside an actual Foundry
|
ZIP, no other required module, container, VM/LXC or companion service.
|
||||||
world. No production installation or external service is changed by building it.
|
|
||||||
|
|
||||||
Install `adaptive-music.zip` through Foundry's normal module manifest mechanism.
|
Enter your private HTTPS MA address and token in **Connection**, then select
|
||||||
[INSTALL.md](INSTALL.md) covers manual Gitea publication, installation, updates and
|
**Connect**. Assign playlists in **Scene Music** and enable automation in
|
||||||
isolated testing. The configured repository is **planned, not confirmed**. No
|
**Playback**. Players receive WebRTC audio
|
||||||
connection to it was made. An uploaded, anonymously readable manifest and release
|
automatically, with one Enable Audio click if their browser requires it. No receiver
|
||||||
asset are required before Foundry installation by URL can work.
|
identity export or JSON import is part of setup.
|
||||||
|
|
||||||
The standard module includes native playlist playback, persistent separate scene
|
The signed-in GM account remembers the encrypted Music Assistant address. Enter the
|
||||||
ambient/combat/boss/native fallback assignments, global defaults, manual overrides,
|
MA token and select **Connect** to unlock it in a new browser session. MA tokens
|
||||||
combat automation and the existing snapshot/restore controller. The GM setup menu
|
stay in the GM tab’s memory. A campaign/GM/origin-scoped receiver identity
|
||||||
configures native ownership and assignments. Automation defaults off. Only
|
is encrypted in that browser’s IndexedDB so reconnecting does not create another
|
||||||
explicitly owned native music playlists are eligible; sound effects are out of scope.
|
receiver. Players receive individually encrypted invitations, not MA credentials.
|
||||||
|
Only that dedicated receiver and explicitly owned Foundry music playlists are
|
||||||
|
controlled. Household speakers, grouping, queue transfers, sound effects and
|
||||||
|
AmbientSound documents are outside the control surface.
|
||||||
|
|
||||||
The new **experimental GM browser host** shares the validated MA provider/catalog
|
The v0.7.1 browser preview passed the new graphical setup and playback workflow
|
||||||
code, uses the bundled official Sendspin SDK's PCM decoder and Web Audio, and
|
in a real Foundry v14.371 development world with two listeners. See TESTING.md
|
||||||
sends audio to invited listeners with WebRTC. Supported Foundry module sockets carry
|
for the test scope and remaining installed-build checks.
|
||||||
only encrypted bounded signaling, never continuous audio. GM credentials remain in
|
|
||||||
GM memory and are visible to that browser's user; players receive individual
|
|
||||||
expiring audio capabilities. No Docker, VM, LXC, external module, permanent sandbox,
|
|
||||||
core patch, OS service or public MA endpoint is required by the module.
|
|
||||||
|
|
||||||
This path is a developer API experiment, not a completed one-click MA setup.
|
See INSTALL.md for setup/manual publication, TESTING.md for the consolidated Mac
|
||||||
The existing DEV receiver's private identity/pairing, private browser-reachable TLS,
|
acceptance sequence, SECURITY.md for trust boundaries and PROGRESS.md for status.
|
||||||
authentication-log review and MA ingestion of the approved synthetic sequences are
|
Crossfade, seamless GM handover, durable crash restore and WAN synchronization
|
||||||
still prerequisites. Real catalog entries can be displayed/assigned, but only the
|
claims are not implemented. Attribution and licenses remain in THIRD-PARTY-NOTICES.
|
||||||
authorized synthetic sequences are enabled for experimental MA playback. The
|
|
||||||
companion implementation remains optional experimental source and is preserved at
|
|
||||||
local branch `experimental/companion-0.4.0`; it is not needed for native playback.
|
|
||||||
|
|
||||||
Measured in Chromium: the official decoder and WebRTC delivered synthetic 440 Hz
|
|
||||||
PCM to **two** listener contexts, with first signal at **1.757 s** and approximately
|
|
||||||
**42.3 kbit/s** aggregate GM RTP payload. This used a loopback signaling shim, not
|
|
||||||
Foundry or MA. WAN/NAT/TURN, inter-listener synchronization, audible MA output and
|
|
||||||
nonempty live queue restoration remain unverified. Crossfade and simultaneous
|
|
||||||
ambient layers are not implemented. GM loss ends forwarding; seamless failover or
|
|
||||||
crash restoration is not promised.
|
|
||||||
|
|
||||||
Build a complete manual release bundle locally, without Git credentials or a remote:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
python3 scripts/release.py
|
|
||||||
# To prepare the same release for GitHub instead:
|
|
||||||
python3 scripts/release.py --repository https://github.com/OWNER/REPOSITORY --output dist/github
|
|
||||||
```
|
|
||||||
|
|
||||||
Output: `dist/releases/v0.5.0/adaptive-music-release-v0.5.0.zip`, containing the
|
|
||||||
installable module, standalone manifest, source archive, documentation, licenses
|
|
||||||
and SHA256 checksums. The manifest uses a stable branch URL and a version-specific
|
|
||||||
release download. Build automation validates both but does not publish anything.
|
|
||||||
Prebuilt browser assets are included; end users do not need Node/npm or Python.
|
|
||||||
|
|
||||||
For contributor commands and evidence see [TESTING.md](TESTING.md),
|
|
||||||
[PROGRESS.md](PROGRESS.md), [ARCHITECTURE.md](ARCHITECTURE.md) and
|
|
||||||
[SECURITY.md](SECURITY.md). MIT project license; upstream MIT/Apache notices and
|
|
||||||
full dependency licenses are retained in `THIRD-PARTY-NOTICES` and `licenses/`.
|
|
||||||
+58
-121
@@ -1,133 +1,70 @@
|
|||||||
# Security — standalone module and optional host fallback
|
# Adaptive Music security — 0.7.2
|
||||||
|
|
||||||
The module installs through the normal Foundry manifest/ZIP mechanism. No runtime
|
## Credentials and browser trust
|
||||||
Docker/VM/LXC, sandbox host, third-party Foundry module, core modification, service
|
|
||||||
installer or public MA endpoint is required or created. The optional companion is
|
|
||||||
retained as experimental source/branch, not a mandatory backend. Co-located host
|
|
||||||
placement/routing/manual service setup is a proposal requiring separate approval.
|
|
||||||
|
|
||||||
## Trust boundaries
|
The MA access token remains in the trusted GM tab’s closure memory. It is excluded
|
||||||
|
from Foundry settings, flags, sockets, URLs, console logging, IndexedDB serialization
|
||||||
|
and release archives. Setup failures retain it in this tab; disconnect or reload
|
||||||
|
forgets it. Tokens are never reused after an origin change. Use a restricted MA
|
||||||
|
account with only the intended music providers and dedicated receiver permissions.
|
||||||
|
|
||||||
Only an elected single active GM may initiate GM-local MA access. The GM explicitly
|
The Foundry User Setting stores only a version, random nonce and encrypted MA
|
||||||
supplies a memory-only private profile; that GM/browser user can inspect its token,
|
address and receiver name. The encryption key is derived from the user-entered MA
|
||||||
identity and private data. JavaScript private fields are not a secret store against
|
token for this account and world. Use a generated, high-entropy MA token. The
|
||||||
the browser owner, debugger, compromised same-origin code or server administrator.
|
envelope cannot be unlocked after rotating that token. Connect with the explicit
|
||||||
No contrary claim is made. Trust all code served into the GM origin. A player never
|
address and new token to replace it. Forget saved connection removes the envelope.
|
||||||
receives the GM's MA token/profile, SDK private key, upstream URL or queue payload.
|
|
||||||
|
|
||||||
Profiles/tokens are not persisted in Foundry settings, flags, localStorage, sockets,
|
Receiver private identity and pairing material are encrypted in the GM browser’s
|
||||||
logs, release files or URLs. Operator private backups belong outside the module's
|
IndexedDB under a campaign/user/origin-derived scope. Encryption uses AES-GCM and
|
||||||
public files; existing development secrets stay under ignored `.local/` (0700,
|
a non-extractable key stored in the same browser. It avoids plaintext receiver
|
||||||
regular owner-matching files 0600, symlinks refused). Catalog references are opaque
|
storage; it cannot protect against same-origin scripts, a compromised enabled
|
||||||
HMAC identifiers, stable only with retained operator key/namespace. Configured native
|
module, the local profile owner or theft of a complete browser profile. Use separate
|
||||||
ownership and scene/world references are public world data, never MA credentials.
|
browser profiles for trusted GM and untrusted accounts. Forget remembered receiver
|
||||||
|
removes the local record only; it does not delete MA resources or touch queues.
|
||||||
|
|
||||||
GM control uses the official private MA `/ws` API, with fixed command allowlists,
|
Private development endpoints, tokens, identities, account/catalog results and
|
||||||
correlated bounded responses and discarded unsolicited events, behind the preserved
|
snapshots remain under ignored .local/ (0700; secret files 0600). MA raw WebSocket
|
||||||
MA target/media/provider checks. The MA account's role still grants broader writes;
|
frames can include credentials at VERBOSE logging. Keep raw-frame logging disabled;
|
||||||
filtering is defense in depth, not the sole boundary. No endpoint selector, queue
|
the module does not change production log settings. Expanded operator authorization
|
||||||
transfer, grouping, unrestricted HTTP/WS/Sendspin proxy or household discovery is
|
covers the dedicated live development tests; no production infrastructure was changed.
|
||||||
available to players. No new identity is registered: supplied X25519 SDK identity
|
|
||||||
must match the already verified DEV target before connecting; reconnecting an existing
|
|
||||||
known unavailable target never relaxes mutation guards. SDK auth is first-message,
|
|
||||||
not a token URL. Only original synthetic test sequences may be enabled for playback.
|
|
||||||
|
|
||||||
A precise upstream logging limitation: MA 2.10.6's WebSocket handler logs raw frames
|
## Network and authority
|
||||||
at VERBOSE, including auth payloads. No live token WebSocket test was attempted and
|
|
||||||
no upstream log configuration was read/changed. The GM profile requires explicit
|
|
||||||
`webSocketAuthLogSafe` operator review of disabled raw-frame logging before use.
|
|
||||||
The module's own logs omit credentials; it cannot redact MA's logs without changing
|
|
||||||
that upstream behavior. Do not assume default logging or ignore this gate.
|
|
||||||
|
|
||||||
## Browser network/security policy
|
Trusted HTTPS Foundry and private HTTPS/WSS MA are required. TLS validation, browser
|
||||||
|
security, Origin and private access controls remain enabled. No public MA endpoint,
|
||||||
|
Origin forgery, CORS wildcard change or unrestricted proxy is introduced. Both `/ws`
|
||||||
|
and `/sendspin` must reach their authenticated MA routes. Token-free diagnostics
|
||||||
|
send no explicit MA auth frame; browsers may still send their normal ambient cookies.
|
||||||
|
Browser APIs do not expose arbitrary HTTP/TLS errors and diagnostics do not invent
|
||||||
|
those causes.
|
||||||
|
|
||||||
Private network access from an HTTPS Foundry page still needs permitted routing,
|
Only the SDK-generated and locally remembered campaign receiver is paired or
|
||||||
trusted TLS/WSS, CSP and server/browser Origin/local-network policies. Sendspin Noise
|
controlled. The account-bound pairing API is used after the API session is bound
|
||||||
does not waive mixed-content restrictions. Current module policy refuses HTTPS ->
|
by Sendspin authentication. Exact identity/name/provider, enabled/available state,
|
||||||
non-loopback HTTP/ws MA; modern per-browser local-network exceptions are not a
|
standalone topology and own active queue are checked before writes. No household
|
||||||
portable supported deployment. HTTP `/api` CORS is also insufficient in the inspected
|
selection, grouping, transfer or global stop is offered. Unknown writes latch closed.
|
||||||
pin; GM control instead uses the public authenticated WebSocket API, not a CORS
|
Queue snapshots are signed and campaign/session/fence/generation-bound; later
|
||||||
bypass proxy. No private API is exposed publicly to fix browser access.
|
sessions reject them. Browser authority cannot replace a distributed server fence.
|
||||||
|
|
||||||
No public third-party STUN/TURN is silently used. Default ICE servers are empty;
|
Players receive scoped expiring encrypted capabilities, not MA secrets or addresses.
|
||||||
relay configuration is explicit and TURN credentials must be short-lived. Browser
|
Public ephemeral keys on permission-controlled User documents authenticate invitation
|
||||||
users necessarily see their own relay credentials and decrypted peer signaling.
|
delivery. Both ordinary test players were denied a write to the GM’s User flags in
|
||||||
Direct P2P can reveal network addresses to the authorized peer; relay-only mode can
|
the installed development world. SDP is encrypted, bounded and
|
||||||
reduce that exposure if an approved relay already exists. It cannot guarantee WAN
|
replay protected, and validated for one audio direction with media-level SDP
|
||||||
connectivity without appropriate infrastructure. No service/container is provisioned.
|
inheritance. No microphone, video or data channel is requested. Audio uses DTLS-SRTP.
|
||||||
|
Recipients can record audio or disclose their own capability. Direct peers can
|
||||||
|
learn network addresses. No public STUN/TURN is silently configured. Optional existing ICE URLs and short-lived TURN credentials are entered in the GM interface, kept in tab memory, and delivered only inside the encrypted per-player invitation.
|
||||||
|
|
||||||
## Signaling and players
|
## Recovery and distribution
|
||||||
|
|
||||||
Ordinary Foundry module sockets carry only bounded encrypted SDP/control envelopes,
|
API/Sendspin loss stops automation and listener forwarding. Retained tab inputs
|
||||||
never continuous PCM/audio chunks, MA commands, media URLs, tokens or invitation
|
support a deliberate reconnect; the owned queue is not replaced during reattachment.
|
||||||
secrets. Claimed sender IDs/GM flags are not trusted as authentication. The GM issues
|
No blind mutation retry or automatic crash restoration is promised. Logical pause
|
||||||
a unique expiring 256-bit per-listener capability out of band over a private
|
and interruption snapshots do not survive a reload. Native fallback cannot silently
|
||||||
authenticated channel. Possession authorizes that one peer, not a proven login.
|
resolve an uncertain remote queue.
|
||||||
A recipient can share its own capability/record received audio; this cannot be
|
|
||||||
prevented by browser JavaScript. Do not distribute a controller/MA secret as an invite.
|
|
||||||
|
|
||||||
AES-GCM covers SDP/ICE/DTLS fingerprints with session/peer/direction/sequence binding,
|
The release builder is offline, preserves the existing Gitea update mechanism,
|
||||||
nonce/expiry, strict fields/types/size limits and asynchronous replay rechecks. A
|
checks import/assets closure, SDK hash, licenses, privacy patterns and checksums,
|
||||||
listener may negotiate one recvonly audio m-line; video, outbound listener audio and
|
and includes complete source. No new distributed dependency, runtime CDN, upstream
|
||||||
RTC data/control channels are rejected. Keys are per listener, so one recipient
|
install hook, telemetry, core patch or mandatory companion service was added. The
|
||||||
cannot forge another listener's authorized exchange. Invalid broadcast frames are
|
pinned SDK and noble notices remain intact. No Git host was contacted.
|
||||||
dropped; world-server/socket flooding is still a server-side availability concern,
|
|
||||||
not solved by client encryption. Explicit peer/expiry/restart bounds limit our work.
|
|
||||||
|
|
||||||
Media uses browser DTLS-SRTP WebRTC audio tracks. No microphone is requested. GM
|
|
||||||
revocation stops new media, but cannot erase audio already delivered or force a
|
|
||||||
malicious recipient to discard buffered/recorded content. Real Foundry identity,
|
|
||||||
packet validation, WAN/NAT and browsers still need live acceptance.
|
|
||||||
|
|
||||||
## Authority, failure and original state
|
|
||||||
|
|
||||||
Target identity/provider, own active queue, standalone topology and current authority
|
|
||||||
are rechecked immediately before each mutation. Snapshot and prepared data remain
|
|
||||||
scoped, generation-checked and serialized. Signed snapshots preserve ordered duplicates,
|
|
||||||
index/offset/state/repeat for static unshuffled supported queues; expiry, foreign,
|
|
||||||
tampered or future state denies. Ambiguous remote writes latch closed with no blind
|
|
||||||
retry. Unsupported shuffle/dynamic/autoplay/overlay/ended/speed states fail closed.
|
|
||||||
Only the campaign-owned target is eligible; volume/mute state is read before SDK
|
|
||||||
handover instead of assuming maximum output. Native effects/AmbientSound stay unowned.
|
|
||||||
|
|
||||||
The optional companion retains its process-local fenced lease checks. GM-local control
|
|
||||||
has one-GM checks and a same-origin Web Lock, **not a distributed MA server fence**.
|
|
||||||
It cannot protect against a malicious/stale independent GM with MA credentials.
|
|
||||||
Multiple-GM automation/hard fencing remains a readiness blocker. No automatic GM
|
|
||||||
handover, queue ownership transfer or speaker grouping exists. Foundry disconnect
|
|
||||||
stops forwarding and future writes; an offline/crashed GM cannot guarantee restoration.
|
|
||||||
Native fallback never skips reconciliation of an uncertain active MA target.
|
|
||||||
|
|
||||||
Existing bounded live harnesses still capture original state and report restoration
|
|
||||||
success/failure explicitly. No new playback mutation or Sendspin pairing was attempted
|
|
||||||
in this revision; the read-only check observed an empty idle dedicated queue. The browser measurement
|
|
||||||
used original synthetic PCM, not real MA or licensed-service content. Existing
|
|
||||||
synthetic ingestion failure and identity/TLS/logging gates remain. Crossfade,
|
|
||||||
simultaneous layers, durable recovery and deployment security are not claimed complete.
|
|
||||||
|
|
||||||
## Release and supply-chain safeguards
|
|
||||||
|
|
||||||
The release builder runs offline, uses no Git credential/remote API and never contacts
|
|
||||||
the planned Gitea server. It validates public HTTPS URL shape, stable manifest and
|
|
||||||
versioned ZIP consistency, module ID/author/v14 compatibility, no false `verified`
|
|
||||||
claim, no mandatory systems/modules, import closure, notices, SDK hash and privacy
|
|
||||||
patterns. It rejects private/symlinked package files. Exact private token/endpoint/target
|
|
||||||
scans of history and artifacts supplement these guardrails; they are not a
|
|
||||||
comprehensive secret scanner or proof of uncontacted server availability.
|
|
||||||
|
|
||||||
Official SDK 5.0.0 and noble dependencies are pinned/audited and bundled locally;
|
|
||||||
there is no runtime CDN or installer. Full Apache/MIT texts accompany releases.
|
|
||||||
Optional Opus fallback imports are explicitly disabled in the PCM-only SDK build;
|
|
||||||
libopus/speex/opus-encdec binaries are not distributed. WebRTC's browser codec is not
|
|
||||||
bundled by this project. Install hooks were disabled. Developer-only Playwright/
|
|
||||||
esbuild tools and local Chromium are not shipped or a runtime dependency.
|
|
||||||
|
|
||||||
CI workflows use pinned action commits on an existing shell runner, build artifacts
|
|
||||||
for manual publication, and install no services or infrastructure. No Git host was
|
|
||||||
accessed/authenticated/created/pushed on the user's behalf. Public release files
|
|
||||||
contain no private MA addresses/credentials/deployment data. A source archive is not
|
|
||||||
an installable Foundry ZIP; documentation distinguishes both.
|
|
||||||
|
|
||||||
Peer signaling also bounds each peer to four queued control frames and 64 received
|
|
||||||
control attempts per invitation, limiting asynchronous decrypt/SDP backlog. Socket
|
|
||||||
flooding of the Foundry server remains a server/operator availability concern.
|
|
||||||
+163
-90
@@ -1,102 +1,175 @@
|
|||||||
# Adaptive Music verification — 0.5.0
|
# Adaptive Music verification — 0.7.2
|
||||||
|
|
||||||
## Regression and offline release validation
|
## Executed evidence
|
||||||
|
|
||||||
The current suite has **85 JavaScript tests** and **15 Python tests**. Tests cover
|
The source archive includes sanitized evidence separately from private .local inputs.
|
||||||
controller transitions, signed snapshots, target/topology guards, durable catalog
|
|
||||||
IDs, native restore behavior, scene/default/combat interfaces, optional companion
|
### Account persistence and v0.7.0 GUI review
|
||||||
scope/replay protection, GM access policy, official PCM decoder, encrypted WebRTC
|
|
||||||
signaling/replay checks, public MA WebSocket correlation and offline release contracts.
|
The installed v0.7.0 was exercised again through Foundry’s Settings and Adaptive
|
||||||
These are fixtures and source checks, not live Foundry/MA playback tests.
|
Music menus. Playwright filled the server address and access token and pressed
|
||||||
|
Authenticate and Connect audio. The run used the private proxy route with normal
|
||||||
|
TLS validation and did not replace module assets. The GM saved ambient and combat
|
||||||
|
assignments on a review scene and confirmed the GM decoder received live audio.
|
||||||
|
The scene was left in the development world. In the same world, a browser-supplied
|
||||||
|
v0.7.2 candidate saved an encrypted Foundry User Setting. A new browser session
|
||||||
|
logged into the same GM account and connected with the token alone. The server
|
||||||
|
continued serving v0.7.0 during both tests. Closing the GM audio tab ends the
|
||||||
|
browser-hosted connection. See `evidence/v0.7.2-live.json`.
|
||||||
|
|
||||||
|
### AM-006 live graphical workflow
|
||||||
|
|
||||||
|
The v0.7.1 interface ran inside the actual Foundry v14.371 development world with
|
||||||
|
module assets supplied to the test browser by Playwright. The graphical window
|
||||||
|
passed sizing, horizontal fit, scroll containment, keyboard navigation, Advanced
|
||||||
|
visibility and input validation at 380 and 760 pixels. Through the private route,
|
||||||
|
one Connect action authenticated, provisioned the receiver and loaded the catalog.
|
||||||
|
The GM saved scene assignments and enabled automation through the tabs. Both
|
||||||
|
listeners measured audio during real combat and ambient restoration to eight seconds.
|
||||||
|
The Playback tab showed the track and both listeners. Volume, pause, resume and stop
|
||||||
|
worked through the graphical controls. Listener Stop/Enable and reload also passed.
|
||||||
|
The earlier private-route timeout and an ambient startup attempt without a queue
|
||||||
|
write are recorded alongside the passing rerun in `evidence/v0.7.1-live.json`.
|
||||||
|
Verification of the v0.7.1 ZIP installed on the server is pending.
|
||||||
|
|
||||||
|
### Installed development world over private Nginx
|
||||||
|
|
||||||
|
- Chromium 159 signed into Foundry v14.371 as the GM and both players. The installed
|
||||||
|
v0.7.0 module authenticated to MA and paired a dedicated Sendspin receiver. Both
|
||||||
|
WebSocket routes returned HTTP 101 from the signed-in page, which exposed no
|
||||||
|
enforced CSP header or meta policy.
|
||||||
|
- Both players received encrypted invitations through the real Foundry module socket.
|
||||||
|
Foundry denied both ordinary players’ attempts to update a flag on the GM’s User
|
||||||
|
document. Both players measured signal in their actual playback graphs during
|
||||||
|
ambient, combat and restored ambient. The original queue order and seven-second
|
||||||
|
offset were restored. Audio also returned after Stop/Enable and a player reload.
|
||||||
|
Chromium’s inbound RTP energy counter stayed at zero while the playback graphs
|
||||||
|
showed audio, so the test uses the playback signal.
|
||||||
|
- The MA control page replaces `window.WebSocket` and intercepts Sendspin. Its
|
||||||
|
unauthenticated interceptor failed the bare `/sendspin` probe. The native browser
|
||||||
|
constructor opened the same URL from the same page in Chromium and Firefox.
|
||||||
|
The original Mac-specific AM-005 failure did not reproduce on this Ubuntu route.
|
||||||
|
The Ubuntu Firefox build completed transport checks. Its Foundry join UI failed
|
||||||
|
to render in this environment, which could not create a WebGL context.
|
||||||
|
|
||||||
|
See `evidence/v0.7.0-foundry-private.json` for the installed-world results.
|
||||||
|
|
||||||
|
### Earlier browser and source-overlay checks
|
||||||
|
|
||||||
|
- Ubuntu Firefox 159.0 and Chromium 159.0.8154.6
|
||||||
|
authenticated from Foundry’s origin and MA’s origin and retrieved seven providers.
|
||||||
|
The unauthenticated Foundry page returned no enforced CSP header or meta policy.
|
||||||
|
- Both browsers paired a dedicated MA web receiver, completed Noise and clock sync,
|
||||||
|
and loaded eleven catalog playlists.
|
||||||
|
- Firefox 159 and Chromium 159 delivered real MA audio to two WebRTC listeners
|
||||||
|
after one activation click each. Both listeners measured audio during ambient,
|
||||||
|
combat and restored ambient. The runs exercised emulated pause, seek, resume,
|
||||||
|
volume, ordered track/offset restoration and final queue restoration.
|
||||||
|
- Both browsers reconnected the same receiver after an induced Sendspin disconnect
|
||||||
|
and browser reload. Reattachment preserved the idle nonempty queue without
|
||||||
|
writes, retained the identity without the token and rejected a stale snapshot.
|
||||||
|
- One Firefox startup received an available player but no queue. Startup now waits
|
||||||
|
briefly for that queue to register. The delayed reply is covered by a regression
|
||||||
|
fixture. The passing live playback follow-up received the queue on the first read.
|
||||||
|
- The browser source assets were supplied locally by Playwright under the deployed
|
||||||
|
Foundry origin. Controller inputs were explicit scene/combat states and signaling
|
||||||
|
used an encrypted-envelope relay through the test runner. This was not an installed,
|
||||||
|
logged-in Foundry world or real Foundry socket/user-permission test.
|
||||||
|
- Actual deployed Foundry v14.371 ApplicationV2 rendered the setup at 380/640px with
|
||||||
|
in-memory sample documents. Real IndexedDB receiver vault reopen, user isolation,
|
||||||
|
token exclusion and forgetting passed. No world documents were changed.
|
||||||
|
- Real browser signaling exposed Firefox’s session-default SDP inheritance; its fix
|
||||||
|
was retested in Firefox 144.0.2 and Chromium 143.0.7499.4.
|
||||||
|
Trusted local-CA HTTPS/WSS policy tests cover
|
||||||
|
allowed cross-origin, enforced/report-only CSP and server Origin rejection.
|
||||||
|
|
||||||
|
See `evidence/v0.7.0-live-follow-up.json`, `evidence/v0.7.0-live.json`,
|
||||||
|
`evidence/foundry-application-v070.json` and `evidence/v0.7.0-checks.txt` in the source
|
||||||
|
archive. Earlier Firefox and Chromium runs received MA `MediaNotFoundError` (code 2)
|
||||||
|
during playlist startup despite playable track metadata. Its cause remains
|
||||||
|
unconfirmed. Those failures are retained alongside the passing follow-up. The live
|
||||||
|
runs used dedicated MA development receivers exclusively.
|
||||||
|
|
||||||
|
## One consolidated Mac / logged-in-world acceptance
|
||||||
|
|
||||||
|
Run this in an isolated test world with the actual Foundry v14.371 host and existing
|
||||||
|
private HTTPS MA endpoint. It needs no developer console or diagnostic shell commands.
|
||||||
|
|
||||||
|
1. Install the staged module ZIP, reload, and log in as the sole active GM from your
|
||||||
|
Mac. Open setup at normal and narrow window sizes. Enter the HTTPS MA address and
|
||||||
|
dedicated token, then select **Connect**. The receiver should be provisioned
|
||||||
|
and playlists should load without a backup file. If MA reports media error 2 after connection, verify the same content in MA’s own dedicated web player before treating it as a browser transport failure. If connection fails, select Check
|
||||||
|
browser connection and Copy connection diagnostics once, and report that single
|
||||||
|
report with browser/version and whether MA’s own page works in that same browser.
|
||||||
|
2. In **Scene Music**, choose two authorized static playlists for an active scene’s
|
||||||
|
ambient/combat music and save. In **Playback**, enable automation. Check the GM
|
||||||
|
hears ambient and decoded frames increase.
|
||||||
|
Only the campaign receiver may be controlled. Native fallback remains optional.
|
||||||
|
3. Log in as two ordinary players using separate browser profiles/devices. They should
|
||||||
|
receive audio automatically, needing at most one Enable Audio click. Check late login,
|
||||||
|
Stop/Enable and one player reload. An unrelated user must not receive another user’s
|
||||||
|
invitation; verify Foundry still prevents players from editing other User keys/roles.
|
||||||
|
4. Note the ambient track/offset in MA. Start an actual Foundry combat in this scene,
|
||||||
|
then end/delete it. Both players should hear combat then ambient at the saved offset,
|
||||||
|
rather than restarting ambient. Repeat a rapid start/end and confirm no duplicate queue.
|
||||||
|
5. Close/reopen setup and retry one failed login with a replacement token. The private
|
||||||
|
draft/receiver should remain; after a browser reload only the token needs reentry.
|
||||||
|
Reconnect the same owned receiver and confirm its queue is not replaced. Apply the
|
||||||
|
automation setting explicitly if a nonempty queue was retained.
|
||||||
|
6. Continue listening for at least 30 minutes across invitation renewal. Exercise one
|
||||||
|
brief network interruption, reconnect, and one background/suspend cycle. Report
|
||||||
|
failures with Copy connection diagnostics. Repeat on the actual WAN player route;
|
||||||
|
loopback/LAN signal does not establish NAT/TURN reachability or synchronization.
|
||||||
|
|
||||||
|
The installed-world run covered real Foundry hooks, socket delivery and User
|
||||||
|
permissions. Public release acceptance still requires audibility on the actual
|
||||||
|
Mac/player devices, the original Mac connection, invitation renewal and WAN checks.
|
||||||
|
If AM-005 reproduces on the Mac, correlate its browser connection stage and timestamp
|
||||||
|
with the private proxy’s request and upstream status or TCP counters. The procedure
|
||||||
|
and temporary VM-to-proxy access rollback are in ignored .local/PRIVATE-ROUTE-REQUEST.md.
|
||||||
|
|
||||||
|
## Reproduce development checks
|
||||||
|
|
||||||
|
Use the existing pinned Node 24.23.0, Python standard library and Playwright 1.57.0.
|
||||||
|
No upstream installation hook is required.
|
||||||
|
|
||||||
|
For private-route diagnostics, run `node scripts/check_foundry_private_route.mjs`
|
||||||
|
with the existing browser path settings. The probe verifies the HTTPS peer address
|
||||||
|
for both origins and compares WSS upgrades from Foundry and Music Assistant. It
|
||||||
|
captures handshake status and browser policy metadata. Add `--logged-in` after the
|
||||||
|
private route is reachable and the dedicated development world is active. That
|
||||||
|
mode verifies the installed module version, signs in with the three configured
|
||||||
|
test accounts in separate browser contexts, and adds the authenticated Foundry
|
||||||
|
page as a comparison. `--playback` also exercises actual MA audio, Foundry combat,
|
||||||
|
listener recovery, and cleanup with temporary development-world documents and a
|
||||||
|
dedicated integration receiver. Configuration and results remain under ignored
|
||||||
|
`.local/`.
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
PATH="$HOME/.nvm/versions/node/v24.23.0/bin:$PATH" npm test
|
npm test
|
||||||
python3 -m unittest discover -s tests -v
|
python3 -m unittest discover -s tests -v
|
||||||
python3 scripts/audit_repository.py
|
python3 scripts/audit_repository.py
|
||||||
python3 scripts/verify_upstream.py
|
python3 scripts/verify_upstream.py
|
||||||
|
PLAYWRIGHT_BROWSERS_PATH=.local/browsers node scripts/check_setup_browser.mjs
|
||||||
|
PLAYWRIGHT_BROWSERS_PATH=.local/browsers node scripts/check_foundry_application.mjs
|
||||||
|
PLAYWRIGHT_BROWSERS_PATH=.local/browsers node scripts/check_browser_signaling.mjs
|
||||||
|
PLAYWRIGHT_BROWSERS_PATH=.local/browsers node scripts/live_browser_preflight.mjs
|
||||||
|
PLAYWRIGHT_BROWSERS_PATH=.local/browsers node scripts/live_receiver_browser.mjs
|
||||||
|
PLAYWRIGHT_BROWSERS_PATH=.local/browsers node scripts/live_receiver_browser.mjs --chromium
|
||||||
python3 scripts/release.py
|
python3 scripts/release.py
|
||||||
python3 scripts/release.py --validate dist/releases/v0.5.0/adaptive-music.zip
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Python uses the standard library. Upstream verification requires ignored pinned
|
Live scripts require authorized private configuration/token in ignored .local/ and
|
||||||
research copies; it does not fetch/install them. Browser assets are prebuilt and
|
must only operate on their generated `Adaptive Music integration …` receivers.
|
||||||
SHA256 verified. Optional rebuilding uses Node 24.23.0, `npm ci --ignore-scripts`
|
`--fresh` exercises module provisioning directly and keeps the generated receiver
|
||||||
and `node scripts/build_sendspin.mjs`. No install hooks were run. The online npm
|
identity and reports in a separate private directory under .local/.
|
||||||
advisory audit of the pinned dependency tree reported **zero vulnerabilities**;
|
Browser transport evidence includes no TLS bypass. Headless Chromium’s local test
|
||||||
this is an advisory observation, not a safety guarantee or an offline audit.
|
launcher uses --no-sandbox for this development environment; the shipped module sets
|
||||||
|
no browser flags. No new distributed dependency was introduced. Supplemental Playwright 1.65.2 and Chromium/Firefox 159 builds are isolated under .local/dev-browser-tools; AM_PLAYWRIGHT_MODULE selects that pinned development package. Its provenance is in evidence/v0.7.0-browser-tools.json. The repository dependency lock remains unchanged apart from the application version.
|
||||||
|
|
||||||
Release tests exercise repeatable ZIP generation, embedded/standalone manifest
|
## Limits
|
||||||
identity, missing import/asset rejection, URL versioning, GitHub configuration,
|
|
||||||
checksums, attribution, private-content exclusion and rebuilding from a source
|
|
||||||
archive without Git metadata. Neither the builder nor these tests contact Gitea.
|
|
||||||
CI workflows generate artifacts only on an already provisioned shell runner.
|
|
||||||
They have not run on GitHub or Gitea; Gitea Actions/artifact compatibility is untested.
|
|
||||||
|
|
||||||
## Measured browser audio experiment
|
Mac/Safari behavior, physical audibility, WAN relay, long-run skew/drift, seamless
|
||||||
|
GM handover, crash restore and crossfade remain unverified or unsupported. The
|
||||||
`evidence/browser-audio.json` records an actual Chromium 143.0.7499.4 experiment:
|
upstream single queue provides one playback stream. Pause is emulated and its
|
||||||
official Sendspin 5.0.0 decoder → Web Audio → WebRTC → two listener browser contexts.
|
saved position lasts for the active GM session.
|
||||||
The original 440 Hz synthetic tone produced RMS 0.05391/0.05396 and FFT peaks
|
|
||||||
445.3125 Hz (nearest frequency bin). All listeners had signal at 1.757 s; during
|
|
||||||
4.766 s observation, the GM sent 25,198 RTP payload bytes, approximately 42.3 kbit/s
|
|
||||||
aggregate. Four encrypted signaling messages (maximum 2,078 bytes), no raw audio
|
|
||||||
on signaling. AudioContexts/HTMLAudioElements were unlocked by actual page clicks.
|
|
||||||
|
|
||||||
Optional reproduction after a separate Playwright Chromium download:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
PLAYWRIGHT_BROWSERS_PATH=.local/browsers node scripts/measure_browser_audio.mjs
|
|
||||||
```
|
|
||||||
|
|
||||||
The harness starts a temporary loopback static server and a socket shim, uses
|
|
||||||
headless Chromium with `--no-sandbox` only for the development experiment and
|
|
||||||
closes them afterwards. This is not a real Foundry socket integration, live MA
|
|
||||||
Sendspin handshake, WAN/NAT/TURN test, perceptual quality test or synchronization
|
|
||||||
measurement. Browser dependencies/binaries do not ship with the module.
|
|
||||||
|
|
||||||
## Live MA evidence and limits
|
|
||||||
|
|
||||||
`ma-readonly.json` records prior authenticated restricted account checks, dedicated
|
|
||||||
target/provider restrictions and catalog reads. `ma-adapter.json` records eleven
|
|
||||||
playlists/one radio and stable opaque identifiers across adapter reconstruction.
|
|
||||||
`ma-live-history.json` and `ma-playback.json` record prior bounded idle-queue runs:
|
|
||||||
shuffle/repeat/stop and exact restoration to empty/idle/unshuffled/repeat-off/zero.
|
|
||||||
They verify neither audible music nor restoration of a nonempty queue.
|
|
||||||
|
|
||||||
`module-only-prerequisites.json` adds fresh authenticated **read-only HTTP**
|
|
||||||
verification of the fixed DEV identity/topology and empty idle queue. The configured
|
|
||||||
MA endpoint is HTTP; an HTTPS Foundry page fails the module mixed-content gate.
|
|
||||||
The existing receiver private identity is absent from the GM profile. No receiver
|
|
||||||
was created, no Sendspin connection attempted and no playback command issued in
|
|
||||||
this revision. MA 2.10.6 source logs received WebSocket frames at VERBOSE: operator
|
|
||||||
log review is required before token-bearing `/ws` authentication. No live WS auth
|
|
||||||
was attempted. Route behavior and authentication protocol are source-derived.
|
|
||||||
|
|
||||||
Prior synthetic URI ingestion timed out/returned HTTP 400; approved six-track
|
|
||||||
ambient/combat WAV sequences are not established as ingestible. Actual MA playlist
|
|
||||||
playback remains a separate content-approval acceptance test. Synthetic browser
|
|
||||||
PCM does not satisfy it. Household devices, grouping, queue transfers, production
|
|
||||||
Foundry and network/service configuration remain untouched.
|
|
||||||
|
|
||||||
## Remaining acceptance tests
|
|
||||||
|
|
||||||
In an isolated Foundry v14.371 world: install/enable ZIP, test native ownership,
|
|
||||||
scene ambient/combat/boss and world defaults, explicit combatant flags, manual
|
|
||||||
silence/clear, rapid transitions and native fallback. Validate supported socket
|
|
||||||
signaling using two logged-in users; private invite delivery and revocation, user
|
|
||||||
role changes, disconnects and automation shutdown need real-world confirmation.
|
|
||||||
|
|
||||||
Before live MA audio: operator supplies the existing DEV identity/pairing without
|
|
||||||
registering a new target; makes private secure MA browser access available without
|
|
||||||
public exposure; confirms token-bearing WS frames cannot enter logs; supplies
|
|
||||||
approved synthetic ingestion. Recheck exact target/group/queue before every write.
|
|
||||||
Capture and restore original state with a bounded harness. Then test seeking,
|
|
||||||
interrupt/restore, rapid/nested contexts and stereo/format handling with listeners.
|
|
||||||
Do not treat mocked nonempty restoration as live evidence. Real playlists require
|
|
||||||
separate approved content. Record an explicit restoration failure if it occurs.
|
|
||||||
|
|
||||||
Remote WAN trials must measure ICE/TURN reachability, expiry/reconnect, throughput,
|
|
||||||
latency and listener skew; none is inferred from the loopback result. GM restart,
|
|
||||||
durable nonempty live restore, distributed fencing, crossfade, background tab
|
|
||||||
behavior and service fallback termination remain unsupported or unverified as
|
|
||||||
specified in ARCHITECTURE.md. No production readiness claim.
|
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
# v0.6.0 connection investigation — 2026-12-03
|
||||||
|
|
||||||
|
Historical report. The expanded authorization and v0.7.0 implementation supersede
|
||||||
|
its pending-credential and provisioning status. See v0.7.0-live.json and current
|
||||||
|
PROGRESS.md for the actual live results and unresolved private-route/MA-media checks.
|
||||||
|
|
||||||
|
Status: working-tree remediation; **not a release and not live acceptance**.
|
||||||
|
No production credentials, services, routes, players or queues were used/changed.
|
||||||
|
The pre-existing uncommitted v0.6.0 work has been preserved.
|
||||||
|
|
||||||
|
## Reported deployment evidence
|
||||||
|
|
||||||
|
The operator reports trusted Let's Encrypt HTTPS, Nginx WebSocket HTTP 101,
|
||||||
|
responding MA 2.10.6, functioning private access restrictions, and Firefox success
|
||||||
|
from MA's origin but failure from Foundry's origin. VPN removal, DNS clearing and
|
||||||
|
local-network permission did not resolve it. This supersedes the old assumption
|
||||||
|
that missing TLS is the remaining infrastructure problem. These facts are operator
|
||||||
|
reports, not independently observed request/response captures.
|
||||||
|
|
||||||
|
## What is established
|
||||||
|
|
||||||
|
Pinned MA 2.10.6 commit c24866405bd2068c25a60e1014e5ef8c3f6445bb has no explicit
|
||||||
|
Origin allowlist in its inspected API WebSocket and authenticated Sendspin proxy
|
||||||
|
handlers. The API authenticates a correlated `auth` command after upgrade; the
|
||||||
|
Sendspin proxy authenticates a first text frame, then Noise/Sendspin follows.
|
||||||
|
Neither a homepage response nor a separate client's HTTP 101 establishes that the
|
||||||
|
Foundry-origin browser reaches either authenticated stage. HTTP CORS headers are
|
||||||
|
not a WebSocket Origin authorization fix.
|
||||||
|
|
||||||
|
Real Firefox 144.0.2 exercised two distinct HTTPS origins (localhost and 127.0.0.1,
|
||||||
|
separate ports) and WSS, with a local CA trusted only in an isolated browser profile.
|
||||||
|
No ignore-certificate setting, security-disabled flag or production endpoint was
|
||||||
|
used. `cross-origin-browser.json` records the six passing scenarios:
|
||||||
|
|
||||||
|
| Scenario | Browser observation |
|
||||||
|
| --- | --- |
|
||||||
|
| Trusted cross-origin WSS, policy allows target | Both routes open |
|
||||||
|
| Enforced connect-src self | Both blocked; no server upgrade |
|
||||||
|
| MA same-origin control | Both open |
|
||||||
|
| Report-only connect-src self | Both open |
|
||||||
|
| Server rejects the Foundry Origin | Both fail opaquely |
|
||||||
|
| Same-origin under that Origin restriction | Both open |
|
||||||
|
|
||||||
|
The local server implements a real RFC 6455 upgrade and close, **not MA's API,
|
||||||
|
Noise or audio**. This is evidence about browser enforcement and diagnostics, not
|
||||||
|
MA/Foundry integration. It exposed a synchronous SecurityError/asynchronous CSP
|
||||||
|
event ordering issue that mocks missed; diagnostics now allow time for that event.
|
||||||
|
Browser WebSocket APIs conceal HTTP status, TLS errors and arbitrary close causes.
|
||||||
|
An opaque failure cannot be truthfully labeled an Origin rejection or TLS problem.
|
||||||
|
|
||||||
|
## Defect status
|
||||||
|
|
||||||
|
| Defect | Change/evidence | Still required |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| AM-001 | Scoped ApplicationV2 label/input/button sizing, narrow-window overflow and hidden-step checks at 380/640/1000px | Actual Foundry v14 theme/window verification |
|
||||||
|
| AM-002 | Corrected research: public `sendspin/pair_web_player` exists and binds pairing to an account | Implement and validate dedicated creation/pairing; backup import remains required |
|
||||||
|
| AM-003 | Credential-free in-interface checks for each route; enforced CSP identification; separate API upgrade/auth denial/auth timeout/disconnect/command and Sendspin auth/sync messages | Deployed failures and Noise errors must be observed; opaque transport errors stay explicitly uncertain |
|
||||||
|
| AM-004 | Draft persists in closure memory across failed tests and setup rerenders; retry regression; explicit forget; no token reuse across origin changes; concurrent tests rejected | Actual Foundry window lifecycle check; reload intentionally clears secrets |
|
||||||
|
| AM-005 | Real HTTPS Firefox reproductions and actionable stage diagnostics | Exact deployed root cause, correction and live regression are **unresolved** |
|
||||||
|
|
||||||
|
## Provisioning correction and blockers
|
||||||
|
|
||||||
|
The earlier SENDSPIN-PROVISIONING research considered virtual players but missed
|
||||||
|
`providers/sendspin/provider.py:894` and command registration at :1048.
|
||||||
|
`sendspin/pair_web_player(pairing_token)` requires PLAYERS_CONTROL, waits for the
|
||||||
|
connected registered browser client, checks `is_web_player`, and pairs using the
|
||||||
|
calling account as owner. The SDK exposes `pairingToken` and generates a stable
|
||||||
|
identity with its supplied storage. This offers a source-supported route to
|
||||||
|
integrated provisioning without grouping, household enumeration or another service.
|
||||||
|
|
||||||
|
It is not implemented here. A correct flow must explicitly create only a new
|
||||||
|
campaign-owned identity, connect the Sendspin transport before target lookup,
|
||||||
|
submit only that identity's pairing token, await completed Noise activation and
|
||||||
|
clock sync, verify exact identity/name/provider/standalone topology, retain the
|
||||||
|
updated SDK storage in memory, and offer a private backup export. Disconnect,
|
||||||
|
failed pairing, receiver persistence and restart semantics need real MA testing.
|
||||||
|
The current flow instead looks up an existing identity before connecting it.
|
||||||
|
Merely removing the backup requirement would fail or create an unpaired target.
|
||||||
|
No broad players list or queue control should be added to solve this.
|
||||||
|
|
||||||
|
AGENTS.md also places MA access on a gateway, while the inherited v0.6.0 browser
|
||||||
|
host puts credentials in the GM tab. This existing architectural conflict is not
|
||||||
|
resolved by a WebSocket patch. Adding an unrestricted same-origin MA reverse proxy
|
||||||
|
would violate the stated boundary and is not an adopted solution. An actual
|
||||||
|
server-side gateway cannot be installed by Foundry's browser-only module API.
|
||||||
|
No new mandatory service is proposed.
|
||||||
|
|
||||||
|
## Next acceptance decision
|
||||||
|
|
||||||
|
Obtain the current Foundry and trusted MA origins and explicit read-only credential
|
||||||
|
permission (requested in chat; not received during these checks). Inspect the
|
||||||
|
actual page's enforced response/meta CSP and test both routes from that page in
|
||||||
|
Firefox. Compare the same browser's MA-origin result, not curl or a synthetic page.
|
||||||
|
If CSP is confirmed, prepare an exact-origin connect-src amendment to the existing
|
||||||
|
policy for operator review. If the handshake reaches the proxy and is rejected,
|
||||||
|
inspect the exact Origin against private route policy. Never strip/forge Origin,
|
||||||
|
allow every origin, disable browser security or expose an unrestricted MA proxy.
|
||||||
|
Any production configuration amendment requires separate approval before applying.
|
||||||
|
|
||||||
|
Only after the observed blocker is corrected should authentication, owned receiver
|
||||||
|
creation/pairing, catalog load, interrupted retry and approved audio/restore testing
|
||||||
|
be accepted. Credential approval for read-only tests does not authorize provisioning
|
||||||
|
or playback. The existing Gitea URL/update mechanism is unchanged. Do not publish a
|
||||||
|
new version or replace the existing v0.6.0 immutable artifact on this evidence.
|
||||||
@@ -28,3 +28,10 @@ was established. Existing Adaptive Music DEV remains the only authorized target.
|
|||||||
|
|
||||||
Decision: retain the manually provisioned development target. Do not add an MA
|
Decision: retain the manually provisioned development target. Do not add an MA
|
||||||
plugin, use grouping, create resources, or change production settings in this milestone.
|
plugin, use grouping, create resources, or change production settings in this milestone.
|
||||||
|
|
||||||
|
## Follow-up correction
|
||||||
|
|
||||||
|
The virtual-player conclusion above does not rule out browser receiver provisioning.
|
||||||
|
Pinned MA 2.10.6 registers `sendspin/pair_web_player` with account-bound pairing.
|
||||||
|
See [the later investigation](CROSS-ORIGIN-INVESTIGATION.md) for the exact path,
|
||||||
|
required handshake sequence and unverified implementation/acceptance gates.
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
2026-12-03, unreleased working-tree follow-up
|
||||||
|
|
||||||
|
Node v24.23.0: npm test — 96 passed, 0 failed.
|
||||||
|
python3 -m unittest discover -s tests -v — 15 passed.
|
||||||
|
python3 scripts/audit_repository.py — PASS.
|
||||||
|
python3 scripts/verify_upstream.py — PASS.
|
||||||
|
Chromium 143.0.7499.4 setup DOM fixture — PASS, no page errors;
|
||||||
|
layout 380/640/1000px, hidden steps, catalog and scene persistence, listener UI.
|
||||||
|
Firefox 144.0.2 isolated trusted HTTPS/WSS cross-origin matrix — PASS, six cases.
|
||||||
|
Full results: evidence/cross-origin-browser.json.
|
||||||
|
Local CA confined to disposable profile; no TLS bypass.
|
||||||
|
|
||||||
|
No actual Foundry server, real MA authentication/Noise/pairing/audio, production
|
||||||
|
credential use, production configuration change or new release. Python release
|
||||||
|
regressions built disposable test archives; no new publication artifact is approved.
|
||||||
|
AM-002 and AM-005 remain open; see CROSS-ORIGIN-INVESTIGATION.md.
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
{
|
||||||
|
"scope": "isolated real Firefox HTTPS/WSS policy tests; local transport server, no MA, no Foundry, no credentials or audio",
|
||||||
|
"browser": "144.0.2",
|
||||||
|
"tls": "local CA trusted in disposable Firefox profile; no certificate bypass",
|
||||||
|
"checks": [
|
||||||
|
{
|
||||||
|
"name": "Trusted HTTPS cross-origin WSS allowed",
|
||||||
|
"results": [
|
||||||
|
{
|
||||||
|
"path": "/ws",
|
||||||
|
"code": "upgrade-ok"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "/sendspin",
|
||||||
|
"code": "upgrade-ok"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Enforced CSP blocks cross-origin before upgrade",
|
||||||
|
"results": [
|
||||||
|
{
|
||||||
|
"path": "/ws",
|
||||||
|
"code": "csp-blocked"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "/sendspin",
|
||||||
|
"code": "csp-blocked"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Same MA origin control",
|
||||||
|
"results": [
|
||||||
|
{
|
||||||
|
"path": "/ws",
|
||||||
|
"code": "upgrade-ok"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "/sendspin",
|
||||||
|
"code": "upgrade-ok"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Report-only CSP does not block",
|
||||||
|
"results": [
|
||||||
|
{
|
||||||
|
"path": "/ws",
|
||||||
|
"code": "upgrade-ok"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "/sendspin",
|
||||||
|
"code": "upgrade-ok"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Server Origin rejection stays opaque",
|
||||||
|
"results": [
|
||||||
|
{
|
||||||
|
"path": "/ws",
|
||||||
|
"code": "upgrade-failed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "/sendspin",
|
||||||
|
"code": "upgrade-failed"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Same origin still succeeds under Origin restriction",
|
||||||
|
"results": [
|
||||||
|
{
|
||||||
|
"path": "/ws",
|
||||||
|
"code": "upgrade-ok"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "/sendspin",
|
||||||
|
"code": "upgrade-ok"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"passed": true
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
{
|
||||||
|
"at": "2026-12-04T03:16:41.371Z",
|
||||||
|
"scope": "actual deployed Foundry ApplicationV2 before login, in-memory sample documents; no world writes or MA connection",
|
||||||
|
"browser": "159.0.8154.6",
|
||||||
|
"applicationV2": true,
|
||||||
|
"version": "14.371",
|
||||||
|
"receiverVault": {
|
||||||
|
"reopened": true,
|
||||||
|
"tokenExcluded": true,
|
||||||
|
"userIsolation": true,
|
||||||
|
"forgotten": true
|
||||||
|
},
|
||||||
|
"sizes": [
|
||||||
|
{
|
||||||
|
"width": 380,
|
||||||
|
"fits": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"width": 640,
|
||||||
|
"fits": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"passed": true
|
||||||
|
}
|
||||||
@@ -1,24 +1,259 @@
|
|||||||
{
|
{
|
||||||
"version": "0.5.0",
|
"version": "0.7.0",
|
||||||
"scope": "offline package audit; actual browser synthetic experiment separate from MA/Foundry acceptance",
|
"publicationReady": false,
|
||||||
"connection_configuration": "GM-local in-memory developer API; optional companion setup retained; no one-click GM MA wizard",
|
"completedCoreRunPassed": true,
|
||||||
"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",
|
"macPrivateRouteVerified": false,
|
||||||
"audio": "official SDK PCM and WebRTC implemented experimentally; measured synthetic loopback browser audio, no live MA receiver connection",
|
"foundryLoggedInWorldVerified": true,
|
||||||
"crossfade": "unimplemented",
|
"actualMAAuthentication": true,
|
||||||
"companion": "optional source and experimental/companion-0.4.0 branch; no deployment",
|
"actualMACatalogPlaylists": 11,
|
||||||
"distribution": "one module ZIP; configurable Git-hosted stable manifest + versioned download; offline bundle/checksums/tests pass; no hosted install/update verification",
|
"actualMADedicatedProvisioning": true,
|
||||||
"ma_mutations_this_revision": 0,
|
"actualMAAudioAndTwoListeners": true,
|
||||||
"regression": {
|
"actualAmbientCombatRestore": true,
|
||||||
"javascript": 85,
|
"actualNativePause": false,
|
||||||
"python": 15
|
"logicalPauseEmulation": true,
|
||||||
|
"browserAudioHardwareAudibilityVerified": false,
|
||||||
|
"crossfade": false,
|
||||||
|
"coreSuccessEvidence": "evidence/v0.7.0-live-chromium.json",
|
||||||
|
"browserAuthentication": {
|
||||||
|
"at": "2026-12-04T03:13:45.898Z",
|
||||||
|
"scope": "actual origins, read-only API authentication; Ubuntu browsers, not Mac",
|
||||||
|
"browsers": [
|
||||||
|
{
|
||||||
|
"browser": "firefox",
|
||||||
|
"version": "159.0",
|
||||||
|
"origin": "foundry",
|
||||||
|
"maRoute": "normal resolver",
|
||||||
|
"httpStatus": 200,
|
||||||
|
"csp": null,
|
||||||
|
"result": {
|
||||||
|
"stage": "authenticated",
|
||||||
|
"providerCount": 7,
|
||||||
|
"commandError": null,
|
||||||
|
"metaCSP": [],
|
||||||
|
"blocked": [],
|
||||||
|
"secureContext": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"browser": "firefox",
|
||||||
|
"version": "159.0",
|
||||||
|
"origin": "ma",
|
||||||
|
"maRoute": "normal resolver",
|
||||||
|
"httpStatus": 200,
|
||||||
|
"csp": null,
|
||||||
|
"result": {
|
||||||
|
"stage": "authenticated",
|
||||||
|
"providerCount": 7,
|
||||||
|
"commandError": null,
|
||||||
|
"metaCSP": [],
|
||||||
|
"blocked": [],
|
||||||
|
"secureContext": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"browser": "chromium",
|
||||||
|
"version": "159.0.8154.6",
|
||||||
|
"origin": "foundry",
|
||||||
|
"maRoute": "normal resolver",
|
||||||
|
"httpStatus": 200,
|
||||||
|
"csp": null,
|
||||||
|
"result": {
|
||||||
|
"stage": "authenticated",
|
||||||
|
"providerCount": 7,
|
||||||
|
"commandError": null,
|
||||||
|
"metaCSP": [],
|
||||||
|
"blocked": [],
|
||||||
|
"secureContext": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"browser": "chromium",
|
||||||
|
"version": "159.0.8154.6",
|
||||||
|
"origin": "ma",
|
||||||
|
"maRoute": "normal resolver",
|
||||||
|
"httpStatus": 200,
|
||||||
|
"csp": null,
|
||||||
|
"result": {
|
||||||
|
"stage": "authenticated",
|
||||||
|
"providerCount": 7,
|
||||||
|
"commandError": null,
|
||||||
|
"metaCSP": [],
|
||||||
|
"blocked": [],
|
||||||
|
"secureContext": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
},
|
},
|
||||||
"blocking_infrastructure": [
|
"networkBoundary": {
|
||||||
"isolated Foundry v14.371 world",
|
"sandboxNormalDNS": "public addresses",
|
||||||
"existing DEV private identity/pairing",
|
"operatorMacMAResolution": "private proxy mapping",
|
||||||
"secure private browser MA access",
|
"temporaryAccessRequestPrepared": true,
|
||||||
"operator WebSocket auth log review",
|
"initialUbuntuPrivateProxyTCP443": "timeout before TLS",
|
||||||
"approved synthetic MA ingestion",
|
"followUpUbuntuPrivateProxyTCP443": "verified TLS and installed Foundry browser through operator-scoped firewall access",
|
||||||
"explicit existing TURN relay if required by NAT"
|
"infrastructureChangedByTestAgent": false
|
||||||
|
},
|
||||||
|
"remaining": [
|
||||||
|
"original Mac connection and AM-005 reproduction if the symptom persists",
|
||||||
|
"WAN/30-minute behavior and hardware audibility"
|
||||||
],
|
],
|
||||||
"gitea_contacted": false
|
"credentialUseAuthorized": true,
|
||||||
|
"dedicatedReceiverMutationsPerformed": true,
|
||||||
|
"latestCatalogReplayPassed": true,
|
||||||
|
"freshProvisioningObserved": {
|
||||||
|
"browser": "Firefox 144.0.2",
|
||||||
|
"at": "2026-12-04T03:10:40.566Z",
|
||||||
|
"path": "module creates a fresh identity; no manual protocol pre-provisioning",
|
||||||
|
"pairing": true,
|
||||||
|
"audioTwoListeners": true,
|
||||||
|
"ambientOrderAndOffsetRestored": true,
|
||||||
|
"finalQueueRestored": true,
|
||||||
|
"source": "observed live driver output; private driver reports were subsequently superseded by current-browser reruns"
|
||||||
|
},
|
||||||
|
"productionDependencyAudit": {
|
||||||
|
"info": 0,
|
||||||
|
"low": 0,
|
||||||
|
"moderate": 0,
|
||||||
|
"high": 0,
|
||||||
|
"critical": 0,
|
||||||
|
"total": 0
|
||||||
|
},
|
||||||
|
"history": [
|
||||||
|
{
|
||||||
|
"version": "0.7.0",
|
||||||
|
"scope": "Local acceptance package with isolated browser checks, deployed Foundry ApplicationV2 rendering and dedicated MA receiver tests",
|
||||||
|
"publicationReady": false,
|
||||||
|
"foundryInstalledWorldVerified": true,
|
||||||
|
"originalMacConnectionVerified": false,
|
||||||
|
"deployedOriginAuthentication": "Ubuntu Chromium and Firefox",
|
||||||
|
"maReceiver": {
|
||||||
|
"chromiumPlaybackPassed": true,
|
||||||
|
"firefoxFreshProvisioningPassed": true,
|
||||||
|
"firefoxPlaybackPassed": true,
|
||||||
|
"priorFirefoxPlaybackError": "MA MediaNotFoundError on the first ambient play_media command"
|
||||||
|
},
|
||||||
|
"evidence": [
|
||||||
|
"evidence/v0.7.0-live.json",
|
||||||
|
"evidence/v0.7.0-live-follow-up.json",
|
||||||
|
"evidence/foundry-application-v070.json",
|
||||||
|
"evidence/v0.7.0-checks.txt",
|
||||||
|
"evidence/v0.7.0-foundry-private.json"
|
||||||
|
],
|
||||||
|
"regression": {
|
||||||
|
"javascript": 101,
|
||||||
|
"python": 15
|
||||||
|
},
|
||||||
|
"giteaContacted": false,
|
||||||
|
"productionInfrastructureChanged": false,
|
||||||
|
"remainingAcceptance": [
|
||||||
|
"Mac private MA route",
|
||||||
|
"listener renewal, actual player devices and WAN route"
|
||||||
|
],
|
||||||
|
"history": [
|
||||||
|
{
|
||||||
|
"version": "0.6.0",
|
||||||
|
"scope": "offline regressions, actual Chromium DOM fixture, pinned-source and package checks; no v0.6.0 live Foundry/MA verification",
|
||||||
|
"connection_configuration": "three-step GM wizard; memory-only endpoint/token/identity; imported existing dedicated receiver only",
|
||||||
|
"catalog_and_assignments": "connected catalog playlists, explicit playback opt-in and persistent scene ambient/combat/boss/native fallback and world defaults",
|
||||||
|
"audio": "existing official Sendspin GM host integrated; automatic individually encrypted WebRTC listener invitations; browser activation when required",
|
||||||
|
"bootstrap": "ephemeral ECDH P-256 keys bound to permission-controlled Foundry User documents; AES-GCM encrypted capabilities; live server permissions remain an acceptance gate",
|
||||||
|
"companion": "hidden by default; client-scoped advanced development setting; no mandatory service",
|
||||||
|
"https_wss": "trusted private MA origin with /ws and /sendspin WSS required from HTTPS Foundry; no mixed-content or certificate bypass; deployment untouched",
|
||||||
|
"distribution": "one installable module ZIP plus complete offline manual publication bundle, sources, docs, licenses and checksums",
|
||||||
|
"regression": {
|
||||||
|
"javascript": 91,
|
||||||
|
"python": 15,
|
||||||
|
"passed": true
|
||||||
|
},
|
||||||
|
"browser_ui": {
|
||||||
|
"browser": "Chromium 143.0.7499.4",
|
||||||
|
"passed": true,
|
||||||
|
"scope": "fake Foundry documents and fake connection; no MA or actual Foundry",
|
||||||
|
"pageErrors": []
|
||||||
|
},
|
||||||
|
"user_report": {
|
||||||
|
"version": "0.5.0",
|
||||||
|
"giteaPublished": true,
|
||||||
|
"manifestInstalled": true,
|
||||||
|
"foundry": "14.371",
|
||||||
|
"system": "D&D 5e 6.1.2",
|
||||||
|
"activated": true,
|
||||||
|
"configurationAndListenerWindowsRender": true,
|
||||||
|
"source": "user report; not independently accessed"
|
||||||
|
},
|
||||||
|
"ma_mutations_this_revision": 0,
|
||||||
|
"credential_use_this_revision": false,
|
||||||
|
"gitea_contacted": false,
|
||||||
|
"production_changes": false,
|
||||||
|
"v060_live_audio_verified": false,
|
||||||
|
"remaining_acceptance": [
|
||||||
|
"real Foundry v14.371 ApplicationV2 and User permissions",
|
||||||
|
"trusted private MA HTTPS/WSS",
|
||||||
|
"matching dedicated Sendspin identity/pairing backup",
|
||||||
|
"authentication logging review",
|
||||||
|
"authorized audible catalog playback and nonempty restore",
|
||||||
|
"autoplay/renewal/reconnect across browsers",
|
||||||
|
"WAN ICE/TURN and drift"
|
||||||
|
],
|
||||||
|
"unreleased_follow_up": {
|
||||||
|
"publication_ready": false,
|
||||||
|
"deployed_root_cause_confirmed": false,
|
||||||
|
"integrated_provisioning": false,
|
||||||
|
"production_credentials_used": false,
|
||||||
|
"production_changes": false,
|
||||||
|
"javascript_tests": 96,
|
||||||
|
"browser_policy_evidence": "evidence/cross-origin-browser.json",
|
||||||
|
"details": "evidence/CROSS-ORIGIN-INVESTIGATION.md",
|
||||||
|
"pending": [
|
||||||
|
"current trusted Foundry and MA origins",
|
||||||
|
"explicit read-only credential approval",
|
||||||
|
"deployed diagnosis and accepted correction",
|
||||||
|
"dedicated receiver provisioning and audio acceptance"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"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
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"priorFirefoxFailureEvidence": "evidence/v0.7.0-live-firefox-latest.json",
|
||||||
|
"priorChromiumFailureEvidence": "evidence/v0.7.0-live-chromium-latest.json",
|
||||||
|
"latestFirefoxEvidence": "evidence/v0.7.0-live-follow-up.json",
|
||||||
|
"latestChromiumEvidence": "evidence/v0.7.0-live-follow-up.json",
|
||||||
|
"priorMAError": {
|
||||||
|
"code": 2,
|
||||||
|
"meaning": "MediaNotFound",
|
||||||
|
"phase": "player_queues/play_media",
|
||||||
|
"bothBrowserEngines": true,
|
||||||
|
"catalogMetadataStillPlayable": true,
|
||||||
|
"exactUpstreamResolutionCause": "unconfirmed",
|
||||||
|
"automaticMutationRetries": false
|
||||||
|
},
|
||||||
|
"dedicatedReceiverReconnectPassed": true,
|
||||||
|
"privateNginxRouteVerifiedFromUbuntu": true,
|
||||||
|
"installedFoundryEvidence": "evidence/v0.7.0-foundry-private.json",
|
||||||
|
"priorBrowserEvidenceScope": "deployed Foundry origin with local source overlay; actual MA, PCM, Web Audio and WebRTC; test-runner signaling, not installed world",
|
||||||
|
"evidenceScope": "Installed Foundry and actual MA over the private Nginx HTTPS route. Two real player accounts used Foundry module signaling and browser-measured WebRTC playback."
|
||||||
}
|
}
|
||||||
+21
-2
@@ -41,7 +41,8 @@
|
|||||||
"music_assistant/helpers/uri.py": "c97c43f28db833910635bc89268dd44cb2487b3c26005737f55eb6c1f55521ca",
|
"music_assistant/helpers/uri.py": "c97c43f28db833910635bc89268dd44cb2487b3c26005737f55eb6c1f55521ca",
|
||||||
"music_assistant/providers/builtin/__init__.py": "54349ff427defa5a8c6664ccbcaf47c6564e1eb1606def5b8572c6d57e77df91",
|
"music_assistant/providers/builtin/__init__.py": "54349ff427defa5a8c6664ccbcaf47c6564e1eb1606def5b8572c6d57e77df91",
|
||||||
"music_assistant/controllers/music/media/playlists.py": "7dbc38f93688a2b4f6fcd0501607a22942af55766d40f81795beef0dc037eb3e",
|
"music_assistant/controllers/music/media/playlists.py": "7dbc38f93688a2b4f6fcd0501607a22942af55766d40f81795beef0dc037eb3e",
|
||||||
"music_assistant/controllers/player_queues/helpers.py": "0206927895599dae0b1dd4842a37d11d5d8e0de539e8f710b07684572de25529"
|
"music_assistant/controllers/player_queues/helpers.py": "0206927895599dae0b1dd4842a37d11d5d8e0de539e8f710b07684572de25529",
|
||||||
|
"music_assistant/controllers/config/core.py": "4703113e383c70edd4d2e2b997fb3c0d6cbd86209cb076eb21e723991e49c634"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -109,7 +110,14 @@
|
|||||||
"local_directory": "sendspin-js",
|
"local_directory": "sendspin-js",
|
||||||
"files": {
|
"files": {
|
||||||
"LICENSE": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4",
|
"LICENSE": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4",
|
||||||
"package.json": "b6cae2c9836e467941bb7baab35bde2ead29f3171ce8be18fdb23b758d6b30e9"
|
"package.json": "b6cae2c9836e467941bb7baab35bde2ead29f3171ce8be18fdb23b758d6b30e9",
|
||||||
|
"src/core/core.ts": "54a122bada7d50890336af583b38b4f84d1dc2b343867fbadf2b1fe315862a07",
|
||||||
|
"src/core/transport.ts": "f3b275b436bc008c64f8f8b7d97530a7fb0a4611a8541585e047157d4d9d172c",
|
||||||
|
"src/core/websocket-manager.ts": "f302d00e67815b4052b4ca68029152ed0c28d36de074730f257a68e6f73e3315",
|
||||||
|
"src/core/noise/identity.ts": "bce6e2a4382702a89f690337a752a36a989318234af407aec0f7cc97ae233d6c",
|
||||||
|
"src/index.ts": "3099bac414aa077cd2d816fd75a38e129cdc3f84f15808e19a7fde57318744a5",
|
||||||
|
"src/core/state-manager.ts": "74a053e6315b5e5915ff42fea8ca4f7d7fc8f3e970050b3e2a8511b54c3aaf9f",
|
||||||
|
"src/core/protocol-handler.ts": "75fdafd6c19906385f4c53699080494d0141f77d0cb9c45301853db0462b75f3"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
@@ -126,6 +134,17 @@
|
|||||||
"aiosendspin/noise/trust_store.py": "b5a8dbd3f5d6692dca9ccdd4e9eba8eb9b706fa1ced69ef91bb8dcccb0d3f37f"
|
"aiosendspin/noise/trust_store.py": "b5a8dbd3f5d6692dca9ccdd4e9eba8eb9b706fa1ced69ef91bb8dcccb0d3f37f"
|
||||||
},
|
},
|
||||||
"local_directory": "aiosendspin/aiosendspin-9.1.1"
|
"local_directory": "aiosendspin/aiosendspin-9.1.1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "music-assistant-models",
|
||||||
|
"version": "1.1.205",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"url": "https://files.pythonhosted.org/packages/93/f3/2d9bad4aabf98a12353f9cade2b37fb460b8dd61ad190aab230a17e6abdd/music_assistant_models-1.1.205-py3-none-any.whl",
|
||||||
|
"sha256": "9a7a7f72d2eaeaa5ab12a5f32b15000605d6ee9053f72934e06aae3d1535ae4f",
|
||||||
|
"inspected_files": {
|
||||||
|
"music_assistant_models/errors.py": "6257aafd11910b27c228d7bfbff2240024363e6eb64c2ae6c1a0a07e1cea0ed4"
|
||||||
|
},
|
||||||
|
"local_directory": "music-assistant-models-1.1.205"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -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.
|
||||||
@@ -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
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
{
|
||||||
|
"scope": "isolated development tools only, not distributed dependencies",
|
||||||
|
"packages": [
|
||||||
|
{
|
||||||
|
"name": "playwright",
|
||||||
|
"version": "1.65.2",
|
||||||
|
"integrity": "sha512-Bfg9lfUnqknFzjWrvz2GMckl656TWYwDHiR+T8MQK1V+Sp1D+ODuxpcsnMQ31BYH+LBiKs6kXRMInesqO8F41w==",
|
||||||
|
"license": "Apache-2.0"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "playwright-core",
|
||||||
|
"version": "1.65.2",
|
||||||
|
"integrity": "sha512-aHu9F46Mx5ha9iiB+VLZMUUtex3PBw4am9MHptc0IXaJhz++6YXsH96eEyThwCwMkIUiB8TdZcwXqnb3xKDzmA==",
|
||||||
|
"license": "Apache-2.0"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"installHooksExecuted": false,
|
||||||
|
"browserVersionsFromLiveReports": true
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
v0.7.0 staged acceptance — updated 2026-12-04
|
||||||
|
|
||||||
|
Node 24.23.0 JavaScript suite: 101 passed, 0 failed.
|
||||||
|
Python repository/release suite: 15 passed.
|
||||||
|
Repository privacy/attribution audit: PASS.
|
||||||
|
Pinned upstream Git heads and file hashes: PASS.
|
||||||
|
Production dependency npm audit: 0 reported advisories (not a security guarantee).
|
||||||
|
Chromium DOM fixture: PASS, 380/640/1000px, no page errors.
|
||||||
|
Actual Foundry 14.371 ApplicationV2 / browser IndexedDB: PASS at 380/640px.
|
||||||
|
Browser signaling: Firefox/Chromium real negotiation PASS after SDP fix.
|
||||||
|
Trusted local-CA HTTPS/WSS policy matrix: six scenarios PASS.
|
||||||
|
|
||||||
|
Actual deployed-origin authentication: Firefox 159 and Chromium 159 PASS through
|
||||||
|
normal sandbox DNS (public addresses); seven providers.
|
||||||
|
Actual MA catalog/audio + two browser listeners + emulated pause/seek/resume/volume
|
||||||
|
+ combat interruption and ordered/position restoration: complete passing live runs
|
||||||
|
recorded separately, including Chromium 159 and a fresh module-created receiver in
|
||||||
|
Firefox 144. The listener relay is in the test runner, not Foundry's module socket.
|
||||||
|
|
||||||
|
Earlier Firefox and Chromium 159 runs received MA error 2 / MediaNotFound on catalog
|
||||||
|
startup. The cause remains unconfirmed. Both engines subsequently passed full live
|
||||||
|
playback with two listeners, ambient/combat/ambient, pause, seek, volume and starting
|
||||||
|
queue restoration. Both engines also passed dedicated receiver reconnect after
|
||||||
|
transport loss and page reload. See v0.7.0-live-follow-up.json.
|
||||||
|
|
||||||
|
A Firefox startup attempt reached an available paired receiver before MA returned
|
||||||
|
its queue. Startup now retries a null queue read briefly on the bound API session.
|
||||||
|
The offline regression exercises the waiting path. In the passing live reruns both
|
||||||
|
browsers received the queue on the first read.
|
||||||
|
|
||||||
|
The initial VM-to-proxy TCP probe timed out before TLS. After the operator enabled
|
||||||
|
the scoped firewall exception, private Nginx TLS and Chromium GM/player login passed.
|
||||||
|
Real Foundry signaling, Player User flag denial, dedicated MA playback for both
|
||||||
|
listeners, combat/ambient restore to seven seconds, and listener Stop/Enable and
|
||||||
|
reload passed. See v0.7.0-foundry-private.json. The original Mac issue did not
|
||||||
|
reproduce on Ubuntu. Mac, WAN, renewal and physical audibility remain unverified.
|
||||||
|
Publication readiness remains false.
|
||||||
@@ -0,0 +1,612 @@
|
|||||||
|
{
|
||||||
|
"scope": "Foundry and Music Assistant through the operator private Nginx HTTPS route, with trusted TLS and a verified proxy peer",
|
||||||
|
"foundryVersion": "14.371",
|
||||||
|
"installedModuleVersion": "0.7.0",
|
||||||
|
"privateRouteVerified": true,
|
||||||
|
"transport": [
|
||||||
|
{
|
||||||
|
"engine": "chromium",
|
||||||
|
"version": "159.0.8154.6",
|
||||||
|
"at": "2026-12-04T15:00:10.335Z",
|
||||||
|
"checks": {
|
||||||
|
"foundryAnonymous": {
|
||||||
|
"pageStatus": 200,
|
||||||
|
"privatePeerVerified": true,
|
||||||
|
"cspHeaderPresent": false,
|
||||||
|
"reportOnlyCspHeaderPresent": false,
|
||||||
|
"cspMetaPresent": false,
|
||||||
|
"secureContext": true,
|
||||||
|
"pageReplacesWebSocket": false,
|
||||||
|
"upgrades": [
|
||||||
|
{
|
||||||
|
"path": "/ws",
|
||||||
|
"code": "upgrade-ok"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "/sendspin",
|
||||||
|
"code": "upgrade-ok"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"handshakeReplies": [
|
||||||
|
{
|
||||||
|
"path": "/ws",
|
||||||
|
"httpStatus": 101
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "/sendspin",
|
||||||
|
"httpStatus": 101
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"failedRequests": [],
|
||||||
|
"policyIssues": []
|
||||||
|
},
|
||||||
|
"maSameOrigin": {
|
||||||
|
"pageStatus": 200,
|
||||||
|
"privatePeerVerified": true,
|
||||||
|
"cspHeaderPresent": false,
|
||||||
|
"reportOnlyCspHeaderPresent": false,
|
||||||
|
"cspMetaPresent": false,
|
||||||
|
"secureContext": true,
|
||||||
|
"pageReplacesWebSocket": true,
|
||||||
|
"upgrades": [
|
||||||
|
{
|
||||||
|
"path": "/ws",
|
||||||
|
"code": "upgrade-ok"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "/sendspin",
|
||||||
|
"code": "upgrade-failed"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"handshakeReplies": [
|
||||||
|
{
|
||||||
|
"path": "/ws",
|
||||||
|
"httpStatus": 101
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "/ws",
|
||||||
|
"httpStatus": 101
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "/ws",
|
||||||
|
"httpStatus": 101
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "/sendspin",
|
||||||
|
"httpStatus": 101
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"failedRequests": [],
|
||||||
|
"policyIssues": [],
|
||||||
|
"nativeSendspinUpgrade": "upgrade-ok"
|
||||||
|
},
|
||||||
|
"foundryLoggedIn": {
|
||||||
|
"pageStatus": 200,
|
||||||
|
"privatePeerVerified": true,
|
||||||
|
"cspHeaderPresent": false,
|
||||||
|
"reportOnlyCspHeaderPresent": false,
|
||||||
|
"cspMetaPresent": false,
|
||||||
|
"secureContext": true,
|
||||||
|
"pageReplacesWebSocket": false,
|
||||||
|
"upgrades": [
|
||||||
|
{
|
||||||
|
"path": "/ws",
|
||||||
|
"code": "upgrade-ok"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "/sendspin",
|
||||||
|
"code": "upgrade-ok"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"handshakeReplies": [
|
||||||
|
{
|
||||||
|
"path": "/ws",
|
||||||
|
"httpStatus": 101
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "/sendspin",
|
||||||
|
"httpStatus": 101
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"failedRequests": [],
|
||||||
|
"policyIssues": []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"engine": "firefox",
|
||||||
|
"version": "159.0",
|
||||||
|
"at": "2026-12-04T14:51:41.129Z",
|
||||||
|
"checks": {
|
||||||
|
"foundryAnonymous": {
|
||||||
|
"pageStatus": 200,
|
||||||
|
"privatePeerVerified": true,
|
||||||
|
"cspHeaderPresent": false,
|
||||||
|
"reportOnlyCspHeaderPresent": false,
|
||||||
|
"cspMetaPresent": false,
|
||||||
|
"secureContext": true,
|
||||||
|
"pageReplacesWebSocket": false,
|
||||||
|
"upgrades": [
|
||||||
|
{
|
||||||
|
"path": "/ws",
|
||||||
|
"code": "upgrade-ok"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "/sendspin",
|
||||||
|
"code": "upgrade-ok"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"handshakeReplies": [],
|
||||||
|
"failedRequests": [],
|
||||||
|
"policyIssues": []
|
||||||
|
},
|
||||||
|
"maSameOrigin": {
|
||||||
|
"pageStatus": 200,
|
||||||
|
"privatePeerVerified": true,
|
||||||
|
"cspHeaderPresent": false,
|
||||||
|
"reportOnlyCspHeaderPresent": false,
|
||||||
|
"cspMetaPresent": false,
|
||||||
|
"secureContext": true,
|
||||||
|
"pageReplacesWebSocket": true,
|
||||||
|
"upgrades": [
|
||||||
|
{
|
||||||
|
"path": "/ws",
|
||||||
|
"code": "upgrade-ok"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "/sendspin",
|
||||||
|
"code": "upgrade-failed"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"handshakeReplies": [],
|
||||||
|
"failedRequests": [],
|
||||||
|
"policyIssues": [],
|
||||||
|
"nativeSendspinUpgrade": "upgrade-ok"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"signedInPlayers": [
|
||||||
|
{
|
||||||
|
"worldVerified": true,
|
||||||
|
"foundry": "14.371",
|
||||||
|
"moduleVersion": "0.7.0",
|
||||||
|
"foreignWriteDenied": true,
|
||||||
|
"gmActive": true,
|
||||||
|
"apiReady": true,
|
||||||
|
"publicKeyPublished": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"worldVerified": true,
|
||||||
|
"foundry": "14.371",
|
||||||
|
"moduleVersion": "0.7.0",
|
||||||
|
"foreignWriteDenied": true,
|
||||||
|
"gmActive": true,
|
||||||
|
"apiReady": true,
|
||||||
|
"publicKeyPublished": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"gmVerified": true,
|
||||||
|
"maControlPageFinding": "The Music Assistant frontend replaces window.WebSocket and intercepts Sendspin. The intercepted call failed on its unauthenticated page. The same page opened Sendspin with the native constructor retained before frontend scripts.",
|
||||||
|
"originalMacAM005Reproduced": false,
|
||||||
|
"originalMacAM005RootCauseConfirmed": false,
|
||||||
|
"threeAccountsVerifiedTogether": true,
|
||||||
|
"installedWorldPlaybackBaseline": {
|
||||||
|
"at": "2026-12-04T15:00:10.335Z",
|
||||||
|
"engine": "chromium",
|
||||||
|
"playback": {
|
||||||
|
"stage": "ambient",
|
||||||
|
"publicKeys": [
|
||||||
|
true,
|
||||||
|
true,
|
||||||
|
true
|
||||||
|
],
|
||||||
|
"playerCannotWriteGMFlag": true,
|
||||||
|
"maAPIAuthenticated": true,
|
||||||
|
"sendspinAuthenticated": true,
|
||||||
|
"accountPairingPassed": true,
|
||||||
|
"catalogChoices": 11,
|
||||||
|
"listenerStatsAtFailure": [
|
||||||
|
{
|
||||||
|
"bytes": 125468,
|
||||||
|
"energy": 0,
|
||||||
|
"samples": 1560000
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"bytes": 125468,
|
||||||
|
"energy": 0,
|
||||||
|
"samples": 1560480
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"queueWrites": [
|
||||||
|
{
|
||||||
|
"command": "player_queues/play_media",
|
||||||
|
"reply": true,
|
||||||
|
"error": null
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"gmAudioDiagnostics": {
|
||||||
|
"stage": "ready",
|
||||||
|
"state": "connected",
|
||||||
|
"audioContext": "running",
|
||||||
|
"decoded": 1367,
|
||||||
|
"scheduled": 1367,
|
||||||
|
"droppedLate": 0,
|
||||||
|
"droppedAhead": 0,
|
||||||
|
"signalRMS": 0.1258655905070254,
|
||||||
|
"muted": false,
|
||||||
|
"listenerConnections": 2,
|
||||||
|
"volume": 100
|
||||||
|
},
|
||||||
|
"browserAudio": [
|
||||||
|
{
|
||||||
|
"decodedFrames": 1367,
|
||||||
|
"signaling": {
|
||||||
|
"invitationsForMe": 0,
|
||||||
|
"invitationEvents": 0,
|
||||||
|
"offers": 2,
|
||||||
|
"answers": 0,
|
||||||
|
"sentInvitations": 2,
|
||||||
|
"sentSignals": 2
|
||||||
|
},
|
||||||
|
"browsers": [
|
||||||
|
{
|
||||||
|
"connection": "connected",
|
||||||
|
"ice": "connected",
|
||||||
|
"signaling": "stable"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"connection": "connected",
|
||||||
|
"ice": "connected",
|
||||||
|
"signaling": "stable"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"decodedFrames": null,
|
||||||
|
"signaling": {
|
||||||
|
"invitationsForMe": 1,
|
||||||
|
"invitationEvents": 2,
|
||||||
|
"offers": 1,
|
||||||
|
"answers": 2,
|
||||||
|
"sentInvitations": 0,
|
||||||
|
"sentSignals": 1
|
||||||
|
},
|
||||||
|
"browsers": [
|
||||||
|
{
|
||||||
|
"connection": "connected",
|
||||||
|
"ice": "connected",
|
||||||
|
"signaling": "stable"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"decodedFrames": null,
|
||||||
|
"signaling": {
|
||||||
|
"invitationsForMe": 1,
|
||||||
|
"invitationEvents": 2,
|
||||||
|
"offers": 1,
|
||||||
|
"answers": 2,
|
||||||
|
"sentInvitations": 0,
|
||||||
|
"sentSignals": 1
|
||||||
|
},
|
||||||
|
"browsers": [
|
||||||
|
{
|
||||||
|
"connection": "connected",
|
||||||
|
"ice": "connected",
|
||||||
|
"signaling": "stable"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"temporaryWorldChangesRestored": true
|
||||||
|
},
|
||||||
|
"failure": {
|
||||||
|
"stage": "installed-world-playback",
|
||||||
|
"code": "listener-audio-energy-did-not-increase"
|
||||||
|
},
|
||||||
|
"interpretation": "Chromium reported zero inbound RTP energy although later direct Web Audio playback measurements in the installed world were positive with the same module files."
|
||||||
|
},
|
||||||
|
"diagnosticBeforePlaybackMeters": {
|
||||||
|
"inboundStats": [
|
||||||
|
{
|
||||||
|
"bytes": 124880,
|
||||||
|
"energy": 0,
|
||||||
|
"samples": 1558080
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"bytes": 124937,
|
||||||
|
"energy": 0,
|
||||||
|
"samples": 1558080
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"senderEnergy": [
|
||||||
|
4.082235420083857,
|
||||||
|
4.082235420083857
|
||||||
|
],
|
||||||
|
"gmAnalyserRMS": [
|
||||||
|
0.1651397004235531
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"installedWorldPlaybackPass": {
|
||||||
|
"at": "2026-12-04T15:05:54.779Z",
|
||||||
|
"engine": "chromium",
|
||||||
|
"browser": "159.0.8154.6",
|
||||||
|
"accounts": {
|
||||||
|
"gm-login": {
|
||||||
|
"worldMatches": true,
|
||||||
|
"accountMatches": true,
|
||||||
|
"gm": true,
|
||||||
|
"foundryVersion": "14.371",
|
||||||
|
"system": "dnd5e",
|
||||||
|
"otherActiveGMs": 0,
|
||||||
|
"adaptiveMusicActive": true,
|
||||||
|
"adaptiveMusicVersion": "0.7.0",
|
||||||
|
"canvasTickerPaused": true
|
||||||
|
},
|
||||||
|
"player-1-login": {
|
||||||
|
"worldMatches": true,
|
||||||
|
"accountMatches": true,
|
||||||
|
"gm": false,
|
||||||
|
"foundryVersion": "14.371",
|
||||||
|
"system": "dnd5e",
|
||||||
|
"otherActiveGMs": 1,
|
||||||
|
"adaptiveMusicActive": true,
|
||||||
|
"adaptiveMusicVersion": "0.7.0",
|
||||||
|
"canvasTickerPaused": true
|
||||||
|
},
|
||||||
|
"player-2-login": {
|
||||||
|
"worldMatches": true,
|
||||||
|
"accountMatches": true,
|
||||||
|
"gm": false,
|
||||||
|
"foundryVersion": "14.371",
|
||||||
|
"system": "dnd5e",
|
||||||
|
"otherActiveGMs": 1,
|
||||||
|
"adaptiveMusicActive": true,
|
||||||
|
"adaptiveMusicVersion": "0.7.0",
|
||||||
|
"canvasTickerPaused": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"playback": {
|
||||||
|
"stage": "passed",
|
||||||
|
"publicKeys": [
|
||||||
|
true,
|
||||||
|
true,
|
||||||
|
true
|
||||||
|
],
|
||||||
|
"playerCannotWriteGMFlag": true,
|
||||||
|
"maAPIAuthenticated": true,
|
||||||
|
"sendspinAuthenticated": true,
|
||||||
|
"accountPairingPassed": true,
|
||||||
|
"catalogChoices": 11,
|
||||||
|
"ambient": [
|
||||||
|
{
|
||||||
|
"bytesIncreased": true,
|
||||||
|
"energyIncrease": 0,
|
||||||
|
"playbackRMS": 0.004791336274277526,
|
||||||
|
"samplesIncreased": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"bytesIncreased": true,
|
||||||
|
"energyIncrease": 0,
|
||||||
|
"playbackRMS": 0.004743247823567246,
|
||||||
|
"samplesIncreased": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"combat": [
|
||||||
|
{
|
||||||
|
"bytesIncreased": true,
|
||||||
|
"energyIncrease": 0,
|
||||||
|
"playbackRMS": 0.12556049134588929,
|
||||||
|
"samplesIncreased": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"bytesIncreased": true,
|
||||||
|
"energyIncrease": 0,
|
||||||
|
"playbackRMS": 0.1205585037803511,
|
||||||
|
"samplesIncreased": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"ambientOrderRestored": true,
|
||||||
|
"ambientRestoreOffset": {
|
||||||
|
"index": 0,
|
||||||
|
"seconds": 7
|
||||||
|
},
|
||||||
|
"ambientIndexAndOffsetRestored": true,
|
||||||
|
"restoredAmbient": [
|
||||||
|
{
|
||||||
|
"bytesIncreased": true,
|
||||||
|
"energyIncrease": 0,
|
||||||
|
"playbackRMS": 0.0457946358080247,
|
||||||
|
"samplesIncreased": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"bytesIncreased": true,
|
||||||
|
"energyIncrease": 0,
|
||||||
|
"playbackRMS": 0.04364745631856095,
|
||||||
|
"samplesIncreased": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"onlyDedicatedQueueWritten": true,
|
||||||
|
"afterListenerResume": [
|
||||||
|
{
|
||||||
|
"bytesIncreased": true,
|
||||||
|
"energyIncrease": 0,
|
||||||
|
"playbackRMS": 0.04998535387418037,
|
||||||
|
"samplesIncreased": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"bytesIncreased": true,
|
||||||
|
"energyIncrease": 0,
|
||||||
|
"playbackRMS": 0.051046648244698796,
|
||||||
|
"samplesIncreased": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"afterListenerReload": [
|
||||||
|
{
|
||||||
|
"bytesIncreased": true,
|
||||||
|
"energyIncrease": 0,
|
||||||
|
"playbackRMS": 0.1276089199898213,
|
||||||
|
"samplesIncreased": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"bytesIncreased": true,
|
||||||
|
"energyIncrease": 0,
|
||||||
|
"playbackRMS": 0.09472793662374407,
|
||||||
|
"samplesIncreased": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"queueWrites": [
|
||||||
|
{
|
||||||
|
"command": "player_queues/play_media",
|
||||||
|
"reply": true,
|
||||||
|
"error": null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "player_queues/stop",
|
||||||
|
"reply": true,
|
||||||
|
"error": null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "player_queues/play_media",
|
||||||
|
"reply": true,
|
||||||
|
"error": null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "player_queues/stop",
|
||||||
|
"reply": true,
|
||||||
|
"error": null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "player_queues/stop",
|
||||||
|
"reply": true,
|
||||||
|
"error": null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "player_queues/clear",
|
||||||
|
"reply": true,
|
||||||
|
"error": null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "player_queues/repeat",
|
||||||
|
"reply": true,
|
||||||
|
"error": null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "player_queues/play_media",
|
||||||
|
"reply": true,
|
||||||
|
"error": null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "player_queues/play_index",
|
||||||
|
"reply": true,
|
||||||
|
"error": null
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"gmAudioDiagnostics": {
|
||||||
|
"stage": "ready",
|
||||||
|
"state": "connected",
|
||||||
|
"audioContext": "running",
|
||||||
|
"decoded": 1608,
|
||||||
|
"scheduled": 1608,
|
||||||
|
"droppedLate": 0,
|
||||||
|
"droppedAhead": 0,
|
||||||
|
"signalRMS": 0.13149861108647076,
|
||||||
|
"muted": false,
|
||||||
|
"listenerConnections": 2,
|
||||||
|
"volume": 100
|
||||||
|
},
|
||||||
|
"browserAudio": [
|
||||||
|
{
|
||||||
|
"decodedFrames": 1608,
|
||||||
|
"signaling": {
|
||||||
|
"invitationsForMe": 0,
|
||||||
|
"invitationEvents": 0,
|
||||||
|
"offers": 4,
|
||||||
|
"answers": 0,
|
||||||
|
"sentInvitations": 5,
|
||||||
|
"sentSignals": 4
|
||||||
|
},
|
||||||
|
"contexts": [
|
||||||
|
{
|
||||||
|
"state": "running",
|
||||||
|
"time": 35.735510204081635,
|
||||||
|
"track": "live"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"analyserRMS": [
|
||||||
|
0.2428510186200088
|
||||||
|
],
|
||||||
|
"browsers": [
|
||||||
|
{
|
||||||
|
"connection": "closed",
|
||||||
|
"ice": "closed",
|
||||||
|
"signaling": "closed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"connection": "closed",
|
||||||
|
"ice": "closed",
|
||||||
|
"signaling": "closed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"connection": "connected",
|
||||||
|
"ice": "connected",
|
||||||
|
"signaling": "stable",
|
||||||
|
"outgoingEnergy": 4.711130388295272
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"connection": "closed",
|
||||||
|
"ice": "closed",
|
||||||
|
"signaling": "closed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"connection": "connected",
|
||||||
|
"ice": "connected",
|
||||||
|
"signaling": "stable",
|
||||||
|
"outgoingEnergy": 0.2959549249485192
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"decodedFrames": null,
|
||||||
|
"signaling": {
|
||||||
|
"invitationsForMe": 2,
|
||||||
|
"invitationEvents": 5,
|
||||||
|
"offers": 2,
|
||||||
|
"answers": 4,
|
||||||
|
"sentInvitations": 0,
|
||||||
|
"sentSignals": 2
|
||||||
|
},
|
||||||
|
"contexts": [],
|
||||||
|
"analyserRMS": [],
|
||||||
|
"browsers": [
|
||||||
|
{
|
||||||
|
"connection": "closed",
|
||||||
|
"ice": "closed",
|
||||||
|
"signaling": "closed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"connection": "connected",
|
||||||
|
"ice": "connected",
|
||||||
|
"signaling": "stable"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"decodedFrames": null,
|
||||||
|
"contexts": [],
|
||||||
|
"analyserRMS": [],
|
||||||
|
"browsers": [
|
||||||
|
{
|
||||||
|
"connection": "connected",
|
||||||
|
"ice": "connected",
|
||||||
|
"signaling": "stable"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"temporaryWorldChangesRestored": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"firefoxInstalledWorldBlocker": "The Firefox build completed WSS probes, but the Foundry join form did not render on this headless or Xvfb host. A WebGL 2 context was unavailable."
|
||||||
|
}
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
{
|
||||||
|
"at": "2026-12-04T03:24:28.333Z",
|
||||||
|
"scope": "real MA dedicated receiver from deployed Foundry origin; local source overlay and test-runner signaling, not an installed world",
|
||||||
|
"browser": "Chromium",
|
||||||
|
"browserVersion": "159.0.8154.6",
|
||||||
|
"steps": [
|
||||||
|
{
|
||||||
|
"path": "raw protocol preflight on remembered test identity",
|
||||||
|
"provisioned": true,
|
||||||
|
"queueItems": 4,
|
||||||
|
"available": true,
|
||||||
|
"standalone": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"host": {
|
||||||
|
"ok": true
|
||||||
|
},
|
||||||
|
"pipeline": {
|
||||||
|
"catalogCount": 11,
|
||||||
|
"candidates": [
|
||||||
|
"usable",
|
||||||
|
"usable"
|
||||||
|
],
|
||||||
|
"restored": false,
|
||||||
|
"phase": "ambient",
|
||||||
|
"error": "uncertain",
|
||||||
|
"command": "player_queues/play_media",
|
||||||
|
"upstreamCode": 2,
|
||||||
|
"translationKey": null,
|
||||||
|
"failureStatus": {
|
||||||
|
"state": "connected",
|
||||||
|
"catalog": 12,
|
||||||
|
"audioContext": "running",
|
||||||
|
"catalogPlayback": true,
|
||||||
|
"stage": "queue reconciliation required",
|
||||||
|
"decodedFrames": 0,
|
||||||
|
"lastAudioAt": 0,
|
||||||
|
"outputRMS": 0,
|
||||||
|
"rms": 0,
|
||||||
|
"attachedExistingQueue": false,
|
||||||
|
"volume": 100,
|
||||||
|
"muted": false,
|
||||||
|
"pauseMode": "emulated",
|
||||||
|
"scheduledFrames": 0,
|
||||||
|
"droppedLate": 0,
|
||||||
|
"droppedAhead": 0,
|
||||||
|
"lastLeadSeconds": 0,
|
||||||
|
"audioTime": 5.3986394557823125,
|
||||||
|
"lastError": {
|
||||||
|
"code": "uncertain",
|
||||||
|
"stage": "ready",
|
||||||
|
"command": "player_queues/play_media",
|
||||||
|
"upstreamCode": 2,
|
||||||
|
"translationKey": null
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"restoreSkipped": "queue reconciliation required"
|
||||||
|
},
|
||||||
|
"relay": {
|
||||||
|
"gm": 2,
|
||||||
|
"listener": 2,
|
||||||
|
"failures": 0
|
||||||
|
},
|
||||||
|
"gmPeers": {
|
||||||
|
"rejectedSignals": 0,
|
||||||
|
"peers": [
|
||||||
|
{
|
||||||
|
"role": "gm",
|
||||||
|
"connection": "connected",
|
||||||
|
"ice": "connected",
|
||||||
|
"signaling": "stable",
|
||||||
|
"stage": "send answer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"role": "gm",
|
||||||
|
"connection": "connected",
|
||||||
|
"ice": "connected",
|
||||||
|
"signaling": "stable",
|
||||||
|
"stage": "send answer"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"mediaStats": [
|
||||||
|
{
|
||||||
|
"type": "candidate-pair",
|
||||||
|
"bytesSent": 21875,
|
||||||
|
"bytesReceived": 5477,
|
||||||
|
"currentRoundTripTime": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "outbound-rtp",
|
||||||
|
"bytesSent": 9411
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "candidate-pair",
|
||||||
|
"bytesSent": 21874,
|
||||||
|
"bytesReceived": 5444,
|
||||||
|
"currentRoundTripTime": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "outbound-rtp",
|
||||||
|
"bytesSent": 9411
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"browserWarnings": [
|
||||||
|
"Foundry Virtual Tabletop requires a screen resolution of 1366px by 768px or greater. Your display has a resolution of 1280px by 720px. You must increase your resolution or use a di"
|
||||||
|
],
|
||||||
|
"passed": false
|
||||||
|
}
|
||||||
@@ -0,0 +1,253 @@
|
|||||||
|
{
|
||||||
|
"at": "2026-12-04T03:14:46.888Z",
|
||||||
|
"scope": "real MA dedicated receiver from deployed Foundry origin; local source overlay and test-runner signaling, not an installed world",
|
||||||
|
"browser": "Chromium",
|
||||||
|
"browserVersion": "159.0.8154.6",
|
||||||
|
"steps": [
|
||||||
|
{
|
||||||
|
"path": "raw protocol preflight on remembered test identity",
|
||||||
|
"provisioned": true,
|
||||||
|
"queueItems": 4,
|
||||||
|
"available": true,
|
||||||
|
"standalone": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"host": {
|
||||||
|
"ok": true
|
||||||
|
},
|
||||||
|
"pipeline": {
|
||||||
|
"catalogCount": 11,
|
||||||
|
"candidates": [
|
||||||
|
"usable",
|
||||||
|
"usable"
|
||||||
|
],
|
||||||
|
"restored": true,
|
||||||
|
"gmPeerDiagnostics": {
|
||||||
|
"rejectedSignals": 0,
|
||||||
|
"peers": [
|
||||||
|
{
|
||||||
|
"role": "gm",
|
||||||
|
"connection": "connected",
|
||||||
|
"ice": "connected",
|
||||||
|
"signaling": "stable",
|
||||||
|
"stage": "send answer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"role": "gm",
|
||||||
|
"connection": "connected",
|
||||||
|
"ice": "connected",
|
||||||
|
"signaling": "stable",
|
||||||
|
"stage": "send answer"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"ambient": {
|
||||||
|
"state": "connected",
|
||||||
|
"catalog": 12,
|
||||||
|
"audioContext": "running",
|
||||||
|
"catalogPlayback": true,
|
||||||
|
"stage": "ready",
|
||||||
|
"decodedFrames": 549,
|
||||||
|
"lastAudioAt": 1796354102931,
|
||||||
|
"outputRMS": 0.04921308464995044,
|
||||||
|
"rms": 0.0671612288164562,
|
||||||
|
"attachedExistingQueue": false,
|
||||||
|
"volume": 100,
|
||||||
|
"muted": false,
|
||||||
|
"pauseMode": "emulated",
|
||||||
|
"scheduledFrames": 549,
|
||||||
|
"droppedLate": 0,
|
||||||
|
"droppedAhead": 0,
|
||||||
|
"lastLeadSeconds": 3.973421,
|
||||||
|
"audioTime": 13.397913832199546
|
||||||
|
},
|
||||||
|
"ambientListeners": [
|
||||||
|
{
|
||||||
|
"currentRMS": 0.030545943832978314,
|
||||||
|
"maximumRMS": 0.058502134399453995,
|
||||||
|
"measurements": 143,
|
||||||
|
"peers": [
|
||||||
|
{
|
||||||
|
"role": "listener",
|
||||||
|
"connection": "connected",
|
||||||
|
"ice": "connected",
|
||||||
|
"signaling": "stable",
|
||||||
|
"stage": "validate SDP"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"currentRMS": 0.033752629068495146,
|
||||||
|
"maximumRMS": 0.054916530670132836,
|
||||||
|
"measurements": 131,
|
||||||
|
"peers": [
|
||||||
|
{
|
||||||
|
"role": "listener",
|
||||||
|
"connection": "connected",
|
||||||
|
"ice": "connected",
|
||||||
|
"signaling": "stable",
|
||||||
|
"stage": "validate SDP"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"controls": {
|
||||||
|
"paused": true,
|
||||||
|
"seekPosition": 3,
|
||||||
|
"resumed": true,
|
||||||
|
"volume": true
|
||||||
|
},
|
||||||
|
"combat": {
|
||||||
|
"state": "connected",
|
||||||
|
"catalog": 12,
|
||||||
|
"audioContext": "running",
|
||||||
|
"catalogPlayback": true,
|
||||||
|
"stage": "ready",
|
||||||
|
"decodedFrames": 1210,
|
||||||
|
"lastAudioAt": 1796354115182,
|
||||||
|
"outputRMS": 0.12068391176023772,
|
||||||
|
"rms": 0.09744877113552601,
|
||||||
|
"attachedExistingQueue": false,
|
||||||
|
"volume": 100,
|
||||||
|
"muted": false,
|
||||||
|
"pauseMode": "emulated",
|
||||||
|
"scheduledFrames": 1210,
|
||||||
|
"droppedLate": 0,
|
||||||
|
"droppedAhead": 0,
|
||||||
|
"lastLeadSeconds": 3.972349,
|
||||||
|
"audioTime": 25.658049886621317
|
||||||
|
},
|
||||||
|
"combatListeners": [
|
||||||
|
{
|
||||||
|
"currentRMS": 0.11736051792312625,
|
||||||
|
"maximumRMS": 0.3094812285235373,
|
||||||
|
"measurements": 265,
|
||||||
|
"peers": [
|
||||||
|
{
|
||||||
|
"role": "listener",
|
||||||
|
"connection": "connected",
|
||||||
|
"ice": "connected",
|
||||||
|
"signaling": "stable",
|
||||||
|
"stage": "validate SDP"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"currentRMS": 0.10247671612159892,
|
||||||
|
"maximumRMS": 0.2766517889229327,
|
||||||
|
"measurements": 253,
|
||||||
|
"peers": [
|
||||||
|
{
|
||||||
|
"role": "listener",
|
||||||
|
"connection": "connected",
|
||||||
|
"ice": "connected",
|
||||||
|
"signaling": "stable",
|
||||||
|
"stage": "validate SDP"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"ambientOrderRestored": true,
|
||||||
|
"ambientPositionBefore": 4,
|
||||||
|
"ambientPositionRestored": 4,
|
||||||
|
"ambientStateRestored": "playing",
|
||||||
|
"returnedAmbient": {
|
||||||
|
"state": "connected",
|
||||||
|
"catalog": 12,
|
||||||
|
"audioContext": "running",
|
||||||
|
"catalogPlayback": true,
|
||||||
|
"stage": "ready",
|
||||||
|
"decodedFrames": 1605,
|
||||||
|
"lastAudioAt": 1796354123750,
|
||||||
|
"outputRMS": 0.06371873072766408,
|
||||||
|
"rms": 0.09363425367488697,
|
||||||
|
"attachedExistingQueue": false,
|
||||||
|
"volume": 100,
|
||||||
|
"muted": false,
|
||||||
|
"pauseMode": "emulated",
|
||||||
|
"scheduledFrames": 1605,
|
||||||
|
"droppedLate": 0,
|
||||||
|
"droppedAhead": 0,
|
||||||
|
"lastLeadSeconds": 3.972924,
|
||||||
|
"audioTime": 34.2378231292517
|
||||||
|
},
|
||||||
|
"restoredListeners": [
|
||||||
|
{
|
||||||
|
"currentRMS": 0.04320093615787444,
|
||||||
|
"maximumRMS": 0.26127431126808276,
|
||||||
|
"measurements": 351,
|
||||||
|
"peers": [
|
||||||
|
{
|
||||||
|
"role": "listener",
|
||||||
|
"connection": "connected",
|
||||||
|
"ice": "connected",
|
||||||
|
"signaling": "stable",
|
||||||
|
"stage": "validate SDP"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"currentRMS": 0.039217057552145614,
|
||||||
|
"maximumRMS": 0.18129978959096216,
|
||||||
|
"measurements": 339,
|
||||||
|
"peers": [
|
||||||
|
{
|
||||||
|
"role": "listener",
|
||||||
|
"connection": "connected",
|
||||||
|
"ice": "connected",
|
||||||
|
"signaling": "stable",
|
||||||
|
"stage": "validate SDP"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"transitionsCompleted": true
|
||||||
|
},
|
||||||
|
"relay": {
|
||||||
|
"gm": 2,
|
||||||
|
"listener": 2,
|
||||||
|
"failures": 0
|
||||||
|
},
|
||||||
|
"gmPeers": {
|
||||||
|
"rejectedSignals": 0,
|
||||||
|
"peers": [
|
||||||
|
{
|
||||||
|
"role": "gm",
|
||||||
|
"connection": "connected",
|
||||||
|
"ice": "connected",
|
||||||
|
"signaling": "stable",
|
||||||
|
"stage": "send answer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"role": "gm",
|
||||||
|
"connection": "connected",
|
||||||
|
"ice": "connected",
|
||||||
|
"signaling": "stable",
|
||||||
|
"stage": "send answer"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"mediaStats": [
|
||||||
|
{
|
||||||
|
"type": "candidate-pair",
|
||||||
|
"bytesSent": 165647,
|
||||||
|
"bytesReceived": 25203,
|
||||||
|
"currentRoundTripTime": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "outbound-rtp",
|
||||||
|
"bytesSent": 96584
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "candidate-pair",
|
||||||
|
"bytesSent": 160475,
|
||||||
|
"bytesReceived": 24905,
|
||||||
|
"currentRoundTripTime": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "outbound-rtp",
|
||||||
|
"bytesSent": 92001
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"passed": true
|
||||||
|
}
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
{
|
||||||
|
"at": "2026-12-04T03:26:05.240Z",
|
||||||
|
"scope": "real MA dedicated receiver from deployed Foundry origin; local source overlay and test-runner signaling, not an installed world",
|
||||||
|
"browser": "Firefox",
|
||||||
|
"browserVersion": "159.0",
|
||||||
|
"steps": [
|
||||||
|
{
|
||||||
|
"path": "raw protocol preflight on remembered test identity",
|
||||||
|
"provisioned": true,
|
||||||
|
"queueItems": 4,
|
||||||
|
"available": true,
|
||||||
|
"standalone": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"host": {
|
||||||
|
"ok": true
|
||||||
|
},
|
||||||
|
"pipeline": {
|
||||||
|
"playlistOffset": 2,
|
||||||
|
"catalogCount": 9,
|
||||||
|
"candidates": [
|
||||||
|
"unsupported",
|
||||||
|
"unsupported",
|
||||||
|
"unavailable",
|
||||||
|
"usable",
|
||||||
|
"usable"
|
||||||
|
],
|
||||||
|
"restored": false,
|
||||||
|
"phase": "ambient",
|
||||||
|
"error": "uncertain",
|
||||||
|
"command": "player_queues/play_media",
|
||||||
|
"upstreamCode": 2,
|
||||||
|
"translationKey": null,
|
||||||
|
"failureStatus": {
|
||||||
|
"state": "connected",
|
||||||
|
"catalog": 12,
|
||||||
|
"audioContext": "running",
|
||||||
|
"catalogPlayback": true,
|
||||||
|
"stage": "queue reconciliation required",
|
||||||
|
"decodedFrames": 0,
|
||||||
|
"lastAudioAt": 0,
|
||||||
|
"outputRMS": 0,
|
||||||
|
"rms": 0,
|
||||||
|
"attachedExistingQueue": false,
|
||||||
|
"volume": 100,
|
||||||
|
"muted": false,
|
||||||
|
"pauseMode": "emulated",
|
||||||
|
"scheduledFrames": 0,
|
||||||
|
"droppedLate": 0,
|
||||||
|
"droppedAhead": 0,
|
||||||
|
"lastLeadSeconds": 0,
|
||||||
|
"audioTime": 19.086802721088436,
|
||||||
|
"lastError": {
|
||||||
|
"code": "uncertain",
|
||||||
|
"stage": "ready",
|
||||||
|
"command": "player_queues/play_media",
|
||||||
|
"upstreamCode": 2,
|
||||||
|
"translationKey": null
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"restoreSkipped": "queue reconciliation required"
|
||||||
|
},
|
||||||
|
"relay": {
|
||||||
|
"gm": 2,
|
||||||
|
"listener": 2,
|
||||||
|
"failures": 0
|
||||||
|
},
|
||||||
|
"gmPeers": {
|
||||||
|
"rejectedSignals": 0,
|
||||||
|
"peers": [
|
||||||
|
{
|
||||||
|
"role": "gm",
|
||||||
|
"connection": "connected",
|
||||||
|
"ice": "connected",
|
||||||
|
"signaling": "stable",
|
||||||
|
"stage": "send answer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"role": "gm",
|
||||||
|
"connection": "connected",
|
||||||
|
"ice": "connected",
|
||||||
|
"signaling": "stable",
|
||||||
|
"stage": "send answer"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"mediaStats": [
|
||||||
|
{
|
||||||
|
"type": "outbound-rtp",
|
||||||
|
"bytesSent": 2697
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "candidate-pair",
|
||||||
|
"bytesSent": 39868,
|
||||||
|
"bytesReceived": 17569,
|
||||||
|
"currentRoundTripTime": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "outbound-rtp",
|
||||||
|
"bytesSent": 2586
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "candidate-pair",
|
||||||
|
"bytesSent": 38176,
|
||||||
|
"bytesReceived": 17026,
|
||||||
|
"currentRoundTripTime": 0
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"browserWarnings": [
|
||||||
|
"[JavaScript Warning: \"downloadable font: glyf: Glyph bbox was incorrect; adjusting (glyph 59) (font-family: \"Modesto Condensed\" style:normal weight:700 width:100 src index:0) sourc",
|
||||||
|
"[JavaScript Warning: \"unreachable code after return statement\" {file: \"[address] line: 2}]",
|
||||||
|
"[JavaScript Warning: \"unreachable code after return statement\" {file: \"[address] line: 2}]",
|
||||||
|
"[JavaScript Warning: \"unreachable code after return statement\" {file: \"[address] line: 54}]",
|
||||||
|
"[JavaScript Warning: \"unreachable code after return statement\" {file: \"[address] line: 54}]",
|
||||||
|
"[JavaScript Warning: \"unreachable code after return statement\" {file: \"[address] line: 54}]",
|
||||||
|
"[JavaScript Warning: \"Failed to create WebGL context: WebGL creation failed: \n* WebglAllowWindowsNativeGl:false restricts context creation on this system. ()\n* Exhausted GL driver "
|
||||||
|
],
|
||||||
|
"passed": false
|
||||||
|
}
|
||||||
@@ -0,0 +1,178 @@
|
|||||||
|
{
|
||||||
|
"scope": "Ubuntu browsers with real MA and the deployed Foundry origin, local source overlay and test-runner signaling. Audio measured in-browser, without a logged-in world or physical listener devices.",
|
||||||
|
"playback": [
|
||||||
|
{
|
||||||
|
"at": "2026-12-04T13:50:56.500Z",
|
||||||
|
"browser": "Firefox",
|
||||||
|
"browserVersion": "159.0",
|
||||||
|
"passed": true,
|
||||||
|
"queueBefore": {
|
||||||
|
"state": "idle",
|
||||||
|
"items": 0,
|
||||||
|
"index": null,
|
||||||
|
"repeat": "off"
|
||||||
|
},
|
||||||
|
"audio": {
|
||||||
|
"ambient": {
|
||||||
|
"gmDecodedFramesCumulative": 549,
|
||||||
|
"listenerPeakRMS": [
|
||||||
|
0.112356,
|
||||||
|
0.151159
|
||||||
|
],
|
||||||
|
"listenersConnected": true
|
||||||
|
},
|
||||||
|
"combat": {
|
||||||
|
"gmDecodedFramesCumulative": 1211,
|
||||||
|
"listenerPeakRMS": [
|
||||||
|
0.281149,
|
||||||
|
0.208914
|
||||||
|
],
|
||||||
|
"listenersConnected": true
|
||||||
|
},
|
||||||
|
"restored": {
|
||||||
|
"gmDecodedFramesCumulative": 1601,
|
||||||
|
"listenerPeakRMS": [
|
||||||
|
0.233427,
|
||||||
|
0.220558
|
||||||
|
],
|
||||||
|
"listenersConnected": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"controls": {
|
||||||
|
"paused": true,
|
||||||
|
"seekPosition": 3,
|
||||||
|
"resumed": true,
|
||||||
|
"volume": true
|
||||||
|
},
|
||||||
|
"ambientOrderRestored": true,
|
||||||
|
"ambientPositionBefore": 4,
|
||||||
|
"ambientPositionRestored": 4,
|
||||||
|
"ambientStateRestored": "playing",
|
||||||
|
"transitionsCompleted": true,
|
||||||
|
"ambientIndexRestored": true,
|
||||||
|
"startingQueueRestored": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"at": "2026-12-04T13:52:15.173Z",
|
||||||
|
"browser": "Chromium",
|
||||||
|
"browserVersion": "159.0.8154.6",
|
||||||
|
"passed": true,
|
||||||
|
"queueBefore": {
|
||||||
|
"state": "idle",
|
||||||
|
"items": 0,
|
||||||
|
"index": null,
|
||||||
|
"repeat": "off"
|
||||||
|
},
|
||||||
|
"audio": {
|
||||||
|
"ambient": {
|
||||||
|
"gmDecodedFramesCumulative": 549,
|
||||||
|
"listenerPeakRMS": [
|
||||||
|
0.117859,
|
||||||
|
0.118074
|
||||||
|
],
|
||||||
|
"listenersConnected": true
|
||||||
|
},
|
||||||
|
"combat": {
|
||||||
|
"gmDecodedFramesCumulative": 1210,
|
||||||
|
"listenerPeakRMS": [
|
||||||
|
0.207405,
|
||||||
|
0.278865
|
||||||
|
],
|
||||||
|
"listenersConnected": true
|
||||||
|
},
|
||||||
|
"restored": {
|
||||||
|
"gmDecodedFramesCumulative": 1604,
|
||||||
|
"listenerPeakRMS": [
|
||||||
|
0.142352,
|
||||||
|
0.230279
|
||||||
|
],
|
||||||
|
"listenersConnected": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"controls": {
|
||||||
|
"paused": true,
|
||||||
|
"seekPosition": 3,
|
||||||
|
"resumed": true,
|
||||||
|
"volume": true
|
||||||
|
},
|
||||||
|
"ambientOrderRestored": true,
|
||||||
|
"ambientIndexRestored": true,
|
||||||
|
"ambientPositionBefore": 4,
|
||||||
|
"ambientPositionRestored": 4,
|
||||||
|
"ambientStateRestored": "playing",
|
||||||
|
"transitionsCompleted": true,
|
||||||
|
"startingQueueRestored": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"reconnect": [
|
||||||
|
{
|
||||||
|
"at": "2026-12-04T03:32:42.269Z",
|
||||||
|
"browser": "Firefox",
|
||||||
|
"browserVersion": "159.0",
|
||||||
|
"passed": true,
|
||||||
|
"transportLossDetected": true,
|
||||||
|
"reconnectedAfterLoss": true,
|
||||||
|
"reconnectedAfterReload": true,
|
||||||
|
"sameReceiver": true,
|
||||||
|
"rememberedIdentityWithoutToken": true,
|
||||||
|
"oldSnapshotRejected": true,
|
||||||
|
"emptyBaselineRestored": true,
|
||||||
|
"queueAfter": {
|
||||||
|
"state": "idle",
|
||||||
|
"items": 0,
|
||||||
|
"index": null,
|
||||||
|
"position": 0,
|
||||||
|
"repeat": "off"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"at": "2026-12-04T03:33:13.440Z",
|
||||||
|
"browser": "Chromium",
|
||||||
|
"browserVersion": "159.0.8154.6",
|
||||||
|
"passed": true,
|
||||||
|
"transportLossDetected": true,
|
||||||
|
"reconnectedAfterLoss": true,
|
||||||
|
"reconnectedAfterReload": true,
|
||||||
|
"sameReceiver": true,
|
||||||
|
"rememberedIdentityWithoutToken": true,
|
||||||
|
"oldSnapshotRejected": true,
|
||||||
|
"emptyBaselineRestored": true,
|
||||||
|
"queueAfter": {
|
||||||
|
"state": "idle",
|
||||||
|
"items": 0,
|
||||||
|
"index": null,
|
||||||
|
"position": 0,
|
||||||
|
"repeat": "off"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"queueRegistration": {
|
||||||
|
"beforeFix": {
|
||||||
|
"at": "2026-12-04T13:49:26.827Z",
|
||||||
|
"browser": "Firefox",
|
||||||
|
"browserVersion": "159.0",
|
||||||
|
"passed": false,
|
||||||
|
"authenticated": true,
|
||||||
|
"dedicatedPlayerAvailable": true,
|
||||||
|
"successfulLookupReturnedNoQueue": true,
|
||||||
|
"queueWritesSent": false
|
||||||
|
},
|
||||||
|
"afterFixFirefoxFirstLookupReturnedActiveQueue": true,
|
||||||
|
"delayedQueueResponseCoveredByRegressionFixture": true,
|
||||||
|
"afterFix": [
|
||||||
|
{
|
||||||
|
"at": "2026-12-04T13:50:56.500Z",
|
||||||
|
"browser": "Firefox",
|
||||||
|
"queueAvailableOnFirstRead": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"at": "2026-12-04T13:52:15.173Z",
|
||||||
|
"browser": "Chromium",
|
||||||
|
"queueAvailableOnFirstRead": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"offlineRegression": "First queue read returns null, a later read succeeds on the same authenticated API session, and startup issues no queue writes."
|
||||||
|
},
|
||||||
|
"priorMediaNotFoundCauseConfirmed": false,
|
||||||
|
"publicationReady": false
|
||||||
|
}
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
{
|
||||||
|
"version": "0.7.0",
|
||||||
|
"publicationReady": false,
|
||||||
|
"completedCoreRunPassed": true,
|
||||||
|
"macPrivateRouteVerified": false,
|
||||||
|
"foundryLoggedInWorldVerified": true,
|
||||||
|
"actualMAAuthentication": true,
|
||||||
|
"actualMACatalogPlaylists": 11,
|
||||||
|
"actualMADedicatedProvisioning": true,
|
||||||
|
"actualMAAudioAndTwoListeners": true,
|
||||||
|
"actualAmbientCombatRestore": true,
|
||||||
|
"actualNativePause": false,
|
||||||
|
"logicalPauseEmulation": true,
|
||||||
|
"browserAudioHardwareAudibilityVerified": false,
|
||||||
|
"crossfade": false,
|
||||||
|
"coreSuccessEvidence": "evidence/v0.7.0-live-chromium.json",
|
||||||
|
"browserAuthentication": {
|
||||||
|
"at": "2026-12-04T03:13:45.898Z",
|
||||||
|
"scope": "actual origins, read-only API authentication; Ubuntu browsers, not Mac",
|
||||||
|
"browsers": [
|
||||||
|
{
|
||||||
|
"browser": "firefox",
|
||||||
|
"version": "159.0",
|
||||||
|
"origin": "foundry",
|
||||||
|
"maRoute": "normal resolver",
|
||||||
|
"httpStatus": 200,
|
||||||
|
"csp": null,
|
||||||
|
"result": {
|
||||||
|
"stage": "authenticated",
|
||||||
|
"providerCount": 7,
|
||||||
|
"commandError": null,
|
||||||
|
"metaCSP": [],
|
||||||
|
"blocked": [],
|
||||||
|
"secureContext": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"browser": "firefox",
|
||||||
|
"version": "159.0",
|
||||||
|
"origin": "ma",
|
||||||
|
"maRoute": "normal resolver",
|
||||||
|
"httpStatus": 200,
|
||||||
|
"csp": null,
|
||||||
|
"result": {
|
||||||
|
"stage": "authenticated",
|
||||||
|
"providerCount": 7,
|
||||||
|
"commandError": null,
|
||||||
|
"metaCSP": [],
|
||||||
|
"blocked": [],
|
||||||
|
"secureContext": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"browser": "chromium",
|
||||||
|
"version": "159.0.8154.6",
|
||||||
|
"origin": "foundry",
|
||||||
|
"maRoute": "normal resolver",
|
||||||
|
"httpStatus": 200,
|
||||||
|
"csp": null,
|
||||||
|
"result": {
|
||||||
|
"stage": "authenticated",
|
||||||
|
"providerCount": 7,
|
||||||
|
"commandError": null,
|
||||||
|
"metaCSP": [],
|
||||||
|
"blocked": [],
|
||||||
|
"secureContext": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"browser": "chromium",
|
||||||
|
"version": "159.0.8154.6",
|
||||||
|
"origin": "ma",
|
||||||
|
"maRoute": "normal resolver",
|
||||||
|
"httpStatus": 200,
|
||||||
|
"csp": null,
|
||||||
|
"result": {
|
||||||
|
"stage": "authenticated",
|
||||||
|
"providerCount": 7,
|
||||||
|
"commandError": null,
|
||||||
|
"metaCSP": [],
|
||||||
|
"blocked": [],
|
||||||
|
"secureContext": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"networkBoundary": {
|
||||||
|
"sandboxNormalDNS": "public addresses",
|
||||||
|
"operatorMacMAResolution": "private proxy mapping",
|
||||||
|
"temporaryAccessRequestPrepared": true,
|
||||||
|
"initialUbuntuPrivateProxyTCP443": "timeout before TLS",
|
||||||
|
"followUpUbuntuPrivateProxyTCP443": "verified TLS and installed Foundry browser through operator-scoped firewall access",
|
||||||
|
"infrastructureChangedByTestAgent": false
|
||||||
|
},
|
||||||
|
"remaining": [
|
||||||
|
"original Mac connection and AM-005 reproduction if the symptom persists",
|
||||||
|
"WAN/30-minute behavior and hardware audibility"
|
||||||
|
],
|
||||||
|
"credentialUseAuthorized": true,
|
||||||
|
"dedicatedReceiverMutationsPerformed": true,
|
||||||
|
"latestCatalogReplayPassed": true,
|
||||||
|
"freshProvisioningObserved": {
|
||||||
|
"browser": "Firefox 144.0.2",
|
||||||
|
"at": "2026-12-04T03:10:40.566Z",
|
||||||
|
"path": "module creates a fresh identity; no manual protocol pre-provisioning",
|
||||||
|
"pairing": true,
|
||||||
|
"audioTwoListeners": true,
|
||||||
|
"ambientOrderAndOffsetRestored": true,
|
||||||
|
"finalQueueRestored": true,
|
||||||
|
"source": "observed live driver output; private driver reports were subsequently superseded by current-browser reruns"
|
||||||
|
},
|
||||||
|
"productionDependencyAudit": {
|
||||||
|
"info": 0,
|
||||||
|
"low": 0,
|
||||||
|
"moderate": 0,
|
||||||
|
"high": 0,
|
||||||
|
"critical": 0,
|
||||||
|
"total": 0
|
||||||
|
},
|
||||||
|
"priorFirefoxFailureEvidence": "evidence/v0.7.0-live-firefox-latest.json",
|
||||||
|
"priorChromiumFailureEvidence": "evidence/v0.7.0-live-chromium-latest.json",
|
||||||
|
"latestFirefoxEvidence": "evidence/v0.7.0-live-follow-up.json",
|
||||||
|
"latestChromiumEvidence": "evidence/v0.7.0-live-follow-up.json",
|
||||||
|
"priorMAError": {
|
||||||
|
"code": 2,
|
||||||
|
"meaning": "MediaNotFound",
|
||||||
|
"phase": "player_queues/play_media",
|
||||||
|
"bothBrowserEngines": true,
|
||||||
|
"catalogMetadataStillPlayable": true,
|
||||||
|
"exactUpstreamResolutionCause": "unconfirmed",
|
||||||
|
"automaticMutationRetries": false
|
||||||
|
},
|
||||||
|
"dedicatedReceiverReconnectPassed": true,
|
||||||
|
"privateNginxRouteVerifiedFromUbuntu": true,
|
||||||
|
"installedFoundryEvidence": "evidence/v0.7.0-foundry-private.json",
|
||||||
|
"priorBrowserEvidenceScope": "deployed Foundry origin with local source overlay; actual MA, PCM, Web Audio and WebRTC; test-runner signaling, not installed world",
|
||||||
|
"evidenceScope": "Installed Foundry and actual MA over the private Nginx HTTPS route. Two real player accounts used Foundry module signaling and browser-measured WebRTC playback."
|
||||||
|
}
|
||||||
@@ -0,0 +1,536 @@
|
|||||||
|
{
|
||||||
|
"version": "0.7.1",
|
||||||
|
"defect": "AM-006",
|
||||||
|
"publicationReady": false,
|
||||||
|
"completedCoreRunPassed": true,
|
||||||
|
"macPrivateRouteVerified": false,
|
||||||
|
"foundryLoggedInWorldVerified": false,
|
||||||
|
"verifiedGraphicalPreview": {
|
||||||
|
"at": "2026-12-04T15:29:05.529Z",
|
||||||
|
"scope": "private Nginx HTTPS route",
|
||||||
|
"checks": {},
|
||||||
|
"engine": "chromium",
|
||||||
|
"browser": "159.0.8154.6",
|
||||||
|
"moduleAssets": "workspace module assets in the test browser",
|
||||||
|
"accounts": {
|
||||||
|
"gm-login": {
|
||||||
|
"worldMatches": true,
|
||||||
|
"accountMatches": true,
|
||||||
|
"gm": true,
|
||||||
|
"foundryVersion": "14.371",
|
||||||
|
"system": "dnd5e",
|
||||||
|
"otherActiveGMs": 0,
|
||||||
|
"adaptiveMusicActive": true,
|
||||||
|
"adaptiveMusicVersion": "0.7.0",
|
||||||
|
"canvasTickerPaused": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"layout": {
|
||||||
|
"resizable": true,
|
||||||
|
"layout": [
|
||||||
|
{
|
||||||
|
"width": 760,
|
||||||
|
"tab": "Connection",
|
||||||
|
"horizontalFit": true,
|
||||||
|
"nestedScroll": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"width": 760,
|
||||||
|
"tab": "Scene Music",
|
||||||
|
"horizontalFit": true,
|
||||||
|
"nestedScroll": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"width": 760,
|
||||||
|
"tab": "Playback",
|
||||||
|
"horizontalFit": true,
|
||||||
|
"nestedScroll": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"width": 380,
|
||||||
|
"tab": "Connection",
|
||||||
|
"horizontalFit": true,
|
||||||
|
"nestedScroll": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"width": 380,
|
||||||
|
"tab": "Scene Music",
|
||||||
|
"horizontalFit": true,
|
||||||
|
"nestedScroll": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"width": 380,
|
||||||
|
"tab": "Playback",
|
||||||
|
"horizontalFit": true,
|
||||||
|
"nestedScroll": false
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"keyboardTabs": true,
|
||||||
|
"advancedCollapsed": true,
|
||||||
|
"invalidAddressRejected": true,
|
||||||
|
"missingTokenRejected": true,
|
||||||
|
"routeDiagnostics": [
|
||||||
|
{
|
||||||
|
"path": "/ws",
|
||||||
|
"opened": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "/sendspin",
|
||||||
|
"opened": true
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"completed": true
|
||||||
|
},
|
||||||
|
"regression": {
|
||||||
|
"javascript": 102,
|
||||||
|
"python": 15,
|
||||||
|
"offlineBrowserControls": [
|
||||||
|
"connect",
|
||||||
|
"tabs",
|
||||||
|
"save assignments",
|
||||||
|
"current track",
|
||||||
|
"pause",
|
||||||
|
"resume",
|
||||||
|
"seek",
|
||||||
|
"volume",
|
||||||
|
"stop"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"remaining": [
|
||||||
|
"verify the packaged candidate after a server-side installation in the development environment",
|
||||||
|
"Mac and WAN acceptance"
|
||||||
|
],
|
||||||
|
"previousInstalledWorldEvidence": "evidence/v0.7.0-foundry-private.json",
|
||||||
|
"verifiedLiveWorkflowPreview": {
|
||||||
|
"at": "2026-12-04T15:32:01.859Z",
|
||||||
|
"scope": "private Nginx HTTPS route",
|
||||||
|
"checks": {
|
||||||
|
"foundryAnonymous": {
|
||||||
|
"pageStatus": 200,
|
||||||
|
"privatePeerVerified": true,
|
||||||
|
"cspHeaderPresent": false,
|
||||||
|
"reportOnlyCspHeaderPresent": false,
|
||||||
|
"cspMetaPresent": false,
|
||||||
|
"secureContext": true,
|
||||||
|
"pageReplacesWebSocket": false,
|
||||||
|
"upgrades": [
|
||||||
|
{
|
||||||
|
"path": "/ws",
|
||||||
|
"code": "upgrade-ok"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "/sendspin",
|
||||||
|
"code": "upgrade-ok"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"handshakeReplies": [
|
||||||
|
{
|
||||||
|
"path": "/ws",
|
||||||
|
"httpStatus": 101
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "/sendspin",
|
||||||
|
"httpStatus": 101
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"failedRequests": [],
|
||||||
|
"policyIssues": []
|
||||||
|
},
|
||||||
|
"maSameOrigin": {
|
||||||
|
"pageStatus": 200,
|
||||||
|
"privatePeerVerified": true,
|
||||||
|
"cspHeaderPresent": false,
|
||||||
|
"reportOnlyCspHeaderPresent": false,
|
||||||
|
"cspMetaPresent": false,
|
||||||
|
"secureContext": true,
|
||||||
|
"pageReplacesWebSocket": true,
|
||||||
|
"upgrades": [
|
||||||
|
{
|
||||||
|
"path": "/ws",
|
||||||
|
"code": "upgrade-ok"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "/sendspin",
|
||||||
|
"code": "upgrade-failed"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"handshakeReplies": [
|
||||||
|
{
|
||||||
|
"path": "/ws",
|
||||||
|
"httpStatus": 101
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "/ws",
|
||||||
|
"httpStatus": 101
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "/sendspin",
|
||||||
|
"httpStatus": 101
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"failedRequests": [],
|
||||||
|
"policyIssues": [],
|
||||||
|
"nativeSendspinUpgrade": "upgrade-ok"
|
||||||
|
},
|
||||||
|
"foundryLoggedIn": {
|
||||||
|
"pageStatus": 200,
|
||||||
|
"privatePeerVerified": true,
|
||||||
|
"cspHeaderPresent": false,
|
||||||
|
"reportOnlyCspHeaderPresent": false,
|
||||||
|
"cspMetaPresent": false,
|
||||||
|
"secureContext": true,
|
||||||
|
"pageReplacesWebSocket": false,
|
||||||
|
"upgrades": [
|
||||||
|
{
|
||||||
|
"path": "/ws",
|
||||||
|
"code": "upgrade-ok"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "/sendspin",
|
||||||
|
"code": "upgrade-ok"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"handshakeReplies": [
|
||||||
|
{
|
||||||
|
"path": "/ws",
|
||||||
|
"httpStatus": 101
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "/sendspin",
|
||||||
|
"httpStatus": 101
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"failedRequests": [],
|
||||||
|
"policyIssues": []
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"engine": "chromium",
|
||||||
|
"browser": "159.0.8154.6",
|
||||||
|
"moduleAssets": "workspace module assets in the test browser",
|
||||||
|
"accounts": {
|
||||||
|
"gm-login": {
|
||||||
|
"worldMatches": true,
|
||||||
|
"accountMatches": true,
|
||||||
|
"gm": true,
|
||||||
|
"foundryVersion": "14.371",
|
||||||
|
"system": "dnd5e",
|
||||||
|
"otherActiveGMs": 0,
|
||||||
|
"adaptiveMusicActive": true,
|
||||||
|
"adaptiveMusicVersion": "0.7.0",
|
||||||
|
"canvasTickerPaused": true
|
||||||
|
},
|
||||||
|
"player-1-login": {
|
||||||
|
"worldMatches": true,
|
||||||
|
"accountMatches": true,
|
||||||
|
"gm": false,
|
||||||
|
"foundryVersion": "14.371",
|
||||||
|
"system": "dnd5e",
|
||||||
|
"otherActiveGMs": 1,
|
||||||
|
"adaptiveMusicActive": true,
|
||||||
|
"adaptiveMusicVersion": "0.7.0",
|
||||||
|
"canvasTickerPaused": true
|
||||||
|
},
|
||||||
|
"player-2-login": {
|
||||||
|
"worldMatches": true,
|
||||||
|
"accountMatches": true,
|
||||||
|
"gm": false,
|
||||||
|
"foundryVersion": "14.371",
|
||||||
|
"system": "dnd5e",
|
||||||
|
"otherActiveGMs": 1,
|
||||||
|
"adaptiveMusicActive": true,
|
||||||
|
"adaptiveMusicVersion": "0.7.0",
|
||||||
|
"canvasTickerPaused": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"playback": {
|
||||||
|
"stage": "passed",
|
||||||
|
"publicKeys": [
|
||||||
|
true,
|
||||||
|
true,
|
||||||
|
true
|
||||||
|
],
|
||||||
|
"playerCannotWriteGMFlag": true,
|
||||||
|
"advancedInitiallyCollapsed": true,
|
||||||
|
"formRejectedMissingTokenWithoutNetwork": true,
|
||||||
|
"oneClickConnection": true,
|
||||||
|
"maAPIAuthenticated": true,
|
||||||
|
"sendspinAuthenticated": true,
|
||||||
|
"accountPairingPassed": true,
|
||||||
|
"catalogChoices": 11,
|
||||||
|
"sceneAssignmentVerified": true,
|
||||||
|
"ambient": [
|
||||||
|
{
|
||||||
|
"bytesIncreased": true,
|
||||||
|
"energyIncrease": 0,
|
||||||
|
"playbackRMS": 0.008014325143255013,
|
||||||
|
"samplesIncreased": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"bytesIncreased": true,
|
||||||
|
"energyIncrease": 0,
|
||||||
|
"playbackRMS": 0.007670743474125928,
|
||||||
|
"samplesIncreased": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"combat": [
|
||||||
|
{
|
||||||
|
"bytesIncreased": true,
|
||||||
|
"energyIncrease": 0,
|
||||||
|
"playbackRMS": 0.12679305568945426,
|
||||||
|
"samplesIncreased": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"bytesIncreased": true,
|
||||||
|
"energyIncrease": 0,
|
||||||
|
"playbackRMS": 0.12893801659879386,
|
||||||
|
"samplesIncreased": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"ambientOrderRestored": true,
|
||||||
|
"ambientRestoreOffset": {
|
||||||
|
"index": 0,
|
||||||
|
"seconds": 8
|
||||||
|
},
|
||||||
|
"ambientIndexAndOffsetRestored": true,
|
||||||
|
"restoredAmbient": [
|
||||||
|
{
|
||||||
|
"bytesIncreased": true,
|
||||||
|
"energyIncrease": 0,
|
||||||
|
"playbackRMS": 0.09003888968411675,
|
||||||
|
"samplesIncreased": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"bytesIncreased": true,
|
||||||
|
"energyIncrease": 0,
|
||||||
|
"playbackRMS": 0.09750464413094424,
|
||||||
|
"samplesIncreased": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"onlyDedicatedQueueWritten": true,
|
||||||
|
"afterListenerResume": [
|
||||||
|
{
|
||||||
|
"bytesIncreased": true,
|
||||||
|
"energyIncrease": 0,
|
||||||
|
"playbackRMS": 0.0868827545622943,
|
||||||
|
"samplesIncreased": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"bytesIncreased": true,
|
||||||
|
"energyIncrease": 0,
|
||||||
|
"playbackRMS": 0.09662535253515621,
|
||||||
|
"samplesIncreased": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"afterListenerReload": [
|
||||||
|
{
|
||||||
|
"bytesIncreased": true,
|
||||||
|
"energyIncrease": 0,
|
||||||
|
"playbackRMS": 0.08775154314156451,
|
||||||
|
"samplesIncreased": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"bytesIncreased": true,
|
||||||
|
"energyIncrease": 0,
|
||||||
|
"playbackRMS": 0.08398555055737364,
|
||||||
|
"samplesIncreased": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"afterPlaybackResume": [
|
||||||
|
{
|
||||||
|
"bytesIncreased": true,
|
||||||
|
"energyIncrease": 0,
|
||||||
|
"playbackRMS": 0.10693401545725446,
|
||||||
|
"samplesIncreased": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"bytesIncreased": true,
|
||||||
|
"energyIncrease": 0,
|
||||||
|
"playbackRMS": 0.14311589172943934,
|
||||||
|
"samplesIncreased": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"playbackTabControls": true,
|
||||||
|
"queueWrites": [
|
||||||
|
{
|
||||||
|
"command": "player_queues/play_media",
|
||||||
|
"reply": true,
|
||||||
|
"error": null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "player_queues/stop",
|
||||||
|
"reply": true,
|
||||||
|
"error": null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "player_queues/play_media",
|
||||||
|
"reply": true,
|
||||||
|
"error": null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "player_queues/stop",
|
||||||
|
"reply": true,
|
||||||
|
"error": null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "player_queues/stop",
|
||||||
|
"reply": true,
|
||||||
|
"error": null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "player_queues/clear",
|
||||||
|
"reply": true,
|
||||||
|
"error": null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "player_queues/repeat",
|
||||||
|
"reply": true,
|
||||||
|
"error": null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "player_queues/play_media",
|
||||||
|
"reply": true,
|
||||||
|
"error": null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "player_queues/play_index",
|
||||||
|
"reply": true,
|
||||||
|
"error": null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "player_queues/stop",
|
||||||
|
"reply": true,
|
||||||
|
"error": null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "player_queues/play_index",
|
||||||
|
"reply": true,
|
||||||
|
"error": null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "player_queues/stop",
|
||||||
|
"reply": true,
|
||||||
|
"error": null
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"gmAudioDiagnostics": {
|
||||||
|
"stage": "ready",
|
||||||
|
"state": "connected",
|
||||||
|
"audioContext": "running",
|
||||||
|
"decoded": 1829,
|
||||||
|
"scheduled": 1829,
|
||||||
|
"droppedLate": 0,
|
||||||
|
"droppedAhead": 0,
|
||||||
|
"signalRMS": 0.12175643489717901,
|
||||||
|
"muted": false,
|
||||||
|
"listenerConnections": 2,
|
||||||
|
"volume": 99
|
||||||
|
},
|
||||||
|
"browserAudio": [
|
||||||
|
{
|
||||||
|
"decodedFrames": null,
|
||||||
|
"signaling": {
|
||||||
|
"invitationsForMe": 0,
|
||||||
|
"invitationEvents": 0,
|
||||||
|
"offers": 4,
|
||||||
|
"answers": 0,
|
||||||
|
"sentInvitations": 4,
|
||||||
|
"sentSignals": 4
|
||||||
|
},
|
||||||
|
"contexts": [
|
||||||
|
{
|
||||||
|
"state": "running",
|
||||||
|
"time": 101.05324263038548,
|
||||||
|
"track": "live"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"analyserRMS": [
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"browsers": [
|
||||||
|
{
|
||||||
|
"connection": "closed",
|
||||||
|
"ice": "closed",
|
||||||
|
"signaling": "closed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"connection": "closed",
|
||||||
|
"ice": "closed",
|
||||||
|
"signaling": "closed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"connection": "connected",
|
||||||
|
"ice": "connected",
|
||||||
|
"signaling": "stable",
|
||||||
|
"outgoingEnergy": 2.5731208355109527
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"connection": "connected",
|
||||||
|
"ice": "connected",
|
||||||
|
"signaling": "stable",
|
||||||
|
"outgoingEnergy": 0.4176949028255943
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"decodedFrames": null,
|
||||||
|
"signaling": {
|
||||||
|
"invitationsForMe": 2,
|
||||||
|
"invitationEvents": 4,
|
||||||
|
"offers": 2,
|
||||||
|
"answers": 4,
|
||||||
|
"sentInvitations": 0,
|
||||||
|
"sentSignals": 2
|
||||||
|
},
|
||||||
|
"contexts": [],
|
||||||
|
"analyserRMS": [],
|
||||||
|
"browsers": [
|
||||||
|
{
|
||||||
|
"connection": "closed",
|
||||||
|
"ice": "closed",
|
||||||
|
"signaling": "closed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"connection": "connected",
|
||||||
|
"ice": "connected",
|
||||||
|
"signaling": "stable"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"decodedFrames": null,
|
||||||
|
"contexts": [],
|
||||||
|
"analyserRMS": [],
|
||||||
|
"browsers": [
|
||||||
|
{
|
||||||
|
"connection": "connected",
|
||||||
|
"ice": "connected",
|
||||||
|
"signaling": "stable"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"temporaryWorldChangesRestored": true
|
||||||
|
},
|
||||||
|
"completed": true
|
||||||
|
},
|
||||||
|
"earlierAttempts": [
|
||||||
|
"The private Foundry vhost served the logged-in application. The Music Assistant vhost completed trusted TLS and supplied no HTTP response before the deadline. The in-window token-free checks opened neither WebSocket.",
|
||||||
|
{
|
||||||
|
"at": "2026-12-04T15:29:22.993Z",
|
||||||
|
"failure": {
|
||||||
|
"stage": "installed-world-playback",
|
||||||
|
"code": "ma-play-media-not-observed"
|
||||||
|
},
|
||||||
|
"restoredWorld": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"productionDependencyAudit": {
|
||||||
|
"info": 0,
|
||||||
|
"low": 0,
|
||||||
|
"moderate": 0,
|
||||||
|
"high": 0,
|
||||||
|
"critical": 0,
|
||||||
|
"total": 0
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
{
|
||||||
|
"version": "0.7.2",
|
||||||
|
"publicationReady": false,
|
||||||
|
"completedCoreRunPassed": false,
|
||||||
|
"foundryLoggedInWorldVerified": false,
|
||||||
|
"installedV070GuiReview": {
|
||||||
|
"at": "2026-12-04T15:55:39.842Z",
|
||||||
|
"moduleVersion": "0.7.0",
|
||||||
|
"assetOverrides": false,
|
||||||
|
"injectedRuntimeScripts": false,
|
||||||
|
"manualGuiControls": true,
|
||||||
|
"authenticatedAndConnected": true,
|
||||||
|
"catalogCount": 12,
|
||||||
|
"savedScene": true,
|
||||||
|
"decodedFrames": 299,
|
||||||
|
"passed": true,
|
||||||
|
"reviewScene": "Adaptive Music \u2014 GM review"
|
||||||
|
},
|
||||||
|
"accountPersistence": "Encrypted address and name in a Foundry User Setting. The MA token is required for each new browser session. The server does not host the browser audio relay.",
|
||||||
|
"regression": {
|
||||||
|
"javascript": 104,
|
||||||
|
"python": 15
|
||||||
|
},
|
||||||
|
"candidateAccountSettingVerified": {
|
||||||
|
"scope": "Actual development world, v0.7.2 candidate assets supplied in Playwright only",
|
||||||
|
"firstSession": {
|
||||||
|
"settingScope": "user",
|
||||||
|
"hasEnvelope": true,
|
||||||
|
"connected": true,
|
||||||
|
"manualAddressEntry": true,
|
||||||
|
"addressRestored": true
|
||||||
|
},
|
||||||
|
"newBrowserSession": {
|
||||||
|
"settingScope": "user",
|
||||||
|
"hasEnvelope": true,
|
||||||
|
"connected": true,
|
||||||
|
"manualAddressEntry": false,
|
||||||
|
"addressRestored": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"productionDependencyAudit": {
|
||||||
|
"info": 0,
|
||||||
|
"low": 0,
|
||||||
|
"moderate": 0,
|
||||||
|
"high": 0,
|
||||||
|
"critical": 0,
|
||||||
|
"total": 0
|
||||||
|
}
|
||||||
|
}
|
||||||
+4
-4
@@ -1,8 +1,8 @@
|
|||||||
{
|
{
|
||||||
"id": "adaptive-music",
|
"id": "adaptive-music",
|
||||||
"title": "Adaptive Music \u2014 Development",
|
"title": "Adaptive Music",
|
||||||
"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.",
|
"description": "Scene and combat playlist automation with native Foundry fallback, private GM Music Assistant setup and Sendspin/WebRTC campaign audio.",
|
||||||
"version": "0.5.0",
|
"version": "0.7.2",
|
||||||
"authors": [
|
"authors": [
|
||||||
{
|
{
|
||||||
"name": "CheddahBoxMB"
|
"name": "CheddahBoxMB"
|
||||||
@@ -24,5 +24,5 @@
|
|||||||
"socket": true,
|
"socket": true,
|
||||||
"url": "https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music",
|
"url": "https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music",
|
||||||
"manifest": "https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/raw/branch/main/module.json",
|
"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.7.2/adaptive-music.zip"
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
// Browser interoperability checks for encrypted signaling and audio-only SDP.
|
||||||
|
import {createServer} from 'node:http';
|
||||||
|
import {readFile,writeFile} from 'node:fs/promises';
|
||||||
|
import {resolve} from 'node:path';
|
||||||
|
const {firefox,chromium}=await import(process.env.AM_PLAYWRIGHT_MODULE??'playwright');
|
||||||
|
const root=resolve(import.meta.dirname,'..');
|
||||||
|
const server=createServer(async(req,res)=>{if(req.url==='/'){res.end('<!doctype html><title>Signal check</title>');return;}const path=resolve(root,'.'+new URL(req.url,'http://localhost').pathname);if(!path.startsWith(root+'/src/')){res.writeHead(404);res.end();return;}try{res.setHeader('Content-Type','text/javascript');res.end(await readFile(path));}catch{res.writeHead(404);res.end();}});
|
||||||
|
await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));const reports=[];
|
||||||
|
try{
|
||||||
|
for(const [name,type]of [['firefox',firefox],['chromium',chromium]]){
|
||||||
|
const browser=await type.launch({headless:true,...(name==='chromium'?{args:['--no-sandbox']}: {})});
|
||||||
|
try{
|
||||||
|
const context=await browser.newContext(),pages=[await context.newPage(),await context.newPage()];
|
||||||
|
for(const page of pages)await page.goto('http://127.0.0.1:'+server.address().port);
|
||||||
|
const invite=await pages[0].evaluate(async()=>{const {newAudioInvite,SignalCodec}=await import('/src/audio/signal-codec.mjs');const invite=newAudioInvite({session:'browser-test',userId:'test-listener'});window.codec=new SignalCodec(invite,'gm');return invite;});
|
||||||
|
await pages[1].evaluate(async invite=>{const {SignalCodec}=await import('/src/audio/signal-codec.mjs');window.codec=new SignalCodec(invite,'listener');},invite);
|
||||||
|
const frame=await pages[1].evaluate(()=>window.codec.seal({type:'offer',sdp:'fixture'}));
|
||||||
|
const cryptoResult=await pages[0].evaluate(async frame=>{try{await window.codec.open(frame);return 'pass';}catch(e){return e.code;}},frame);
|
||||||
|
const sdp=await pages[1].evaluate(async()=>{const pc=new RTCPeerConnection({iceServers:[]});pc.addTransceiver('audio',{direction:'recvonly'});const offer=await pc.createOffer();pc.close();return {media:offer.sdp.split(/\r?\n/).filter(l=>l.startsWith('m=')),directionLines:offer.sdp.split(/\r?\n/).filter(l=>/^a=(send|recv|inactive)/.test(l)),unsafe:/a=sendrecv|a=sendonly/.test(offer.sdp)};});
|
||||||
|
for(let i=0;i<pages.length;i++){
|
||||||
|
await pages[i].exposeFunction('signal',async frame=>pages[1-i].evaluate(frame=>window.receiveSignal?.(frame),frame));
|
||||||
|
await pages[i].evaluate(async isGM=>{const {PeerAudio}=await import('/src/audio/peer-audio.mjs');const handlers=new Map();const socket={on:(event,fn)=>handlers.set(event,fn),off:event=>handlers.delete(event),emit:(event,frame)=>window.signal(frame)};window.receiveSignal=frame=>handlers.get('module.adaptive-music')?.(frame);window.peer=new PeerAudio({socket,userId:isGM?'gm':'test-listener',isGM:()=>isGM,createPeer:config=>{window.createdPC=new RTCPeerConnection(config);return window.createdPC;}});if(isGM){window.ctx=new AudioContext();window.peer.setSource(window.ctx.createMediaStreamDestination().stream);}},i===0);
|
||||||
|
}
|
||||||
|
const peerInvite=await pages[0].evaluate(()=>window.peer.invite('test-listener'));await pages[1].evaluate(invite=>window.peer.listen(invite),peerInvite);
|
||||||
|
await pages[0].waitForFunction(()=>window.peer.diagnostics().peers[0]?.connection==='connected',{},{timeout:8000}).catch(()=>{});
|
||||||
|
const finalSDP=await pages[1].evaluate(()=>({media:window.createdPC.localDescription.sdp.split(/\r?\n/).filter(l=>l.startsWith('m=')),directions:window.createdPC.localDescription.sdp.split(/\r?\n/).filter(l=>/^a=(send|recv|inactive)/.test(l)),sessionHeader:window.createdPC.localDescription.sdp.split('m=')[0].split(/\r?\n/).filter(l=>/^a=(send|recv|inactive)/.test(l))}));
|
||||||
|
const peers=await Promise.all(pages.map(page=>page.evaluate(()=>window.peer.diagnostics())));
|
||||||
|
reports.push({browser:name,cryptoResult,frameKeys:Object.keys(frame),sdp,finalSDP,peers});
|
||||||
|
}finally{await browser.close();}
|
||||||
|
}
|
||||||
|
console.log(JSON.stringify(reports,null,2));await writeFile('.local/browser-signaling.json',JSON.stringify(reports,null,2),{mode:0o600});
|
||||||
|
}finally{await new Promise(resolve=>server.close(resolve));}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
// Real browser policy/transport reproduction, NOT MA/Foundry acceptance.
|
||||||
|
// Local CA is trusted only by the disposable Firefox profile. No TLS bypass.
|
||||||
|
import {createServer} from 'node:https';
|
||||||
|
import {readFile,mkdir,writeFile,chmod} from 'node:fs/promises';
|
||||||
|
import {execFileSync} from 'node:child_process';
|
||||||
|
import {createHash} from 'node:crypto';
|
||||||
|
import {resolve} from 'node:path';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import {firefox} from 'playwright';
|
||||||
|
const root=resolve(import.meta.dirname,'..'),dir=resolve(root,'.local/browser-policy'),profile=resolve(dir,'firefox-profile');
|
||||||
|
await mkdir(profile,{recursive:true,mode:0o700});await chmod(dir,0o700);
|
||||||
|
const run=(binary,args)=>execFileSync(binary,args,{cwd:dir,stdio:'pipe'});
|
||||||
|
run('openssl',['req','-x509','-newkey','rsa:2048','-nodes','-keyout','ca.key','-out','ca.pem','-days','2','-subj','/CN=Adaptive Music isolated test CA','-addext','basicConstraints=critical,CA:TRUE']);
|
||||||
|
run('openssl',['req','-newkey','rsa:2048','-nodes','-keyout','server.key','-out','server.csr','-subj','/CN=localhost']);
|
||||||
|
await writeFile(resolve(dir,'extensions.cnf'),'subjectAltName=DNS:localhost,IP:127.0.0.1\nbasicConstraints=CA:FALSE\nextendedKeyUsage=serverAuth\n',{mode:0o600});
|
||||||
|
run('openssl',['x509','-req','-in','server.csr','-CA','ca.pem','-CAkey','ca.key','-CAcreateserial','-out','server.pem','-days','2','-extfile','extensions.cnf']);
|
||||||
|
for(const name of ['ca.key','server.key'])await chmod(resolve(dir,name),0o600);
|
||||||
|
const certutil=process.env.AM_CERTUTIL??resolve(dir,'nss/usr/bin/certutil');
|
||||||
|
try{run(certutil,['-N','--empty-password','-d','sql:'+profile]);}catch{}
|
||||||
|
try{run(certutil,['-D','-n','am-isolated-ca','-d','sql:'+profile]);}catch{}
|
||||||
|
run(certutil,['-A','-n','am-isolated-ca','-t','C,,','-i',resolve(dir,'ca.pem'),'-d','sql:'+profile]);
|
||||||
|
const tls={key:await readFile(resolve(dir,'server.key')),cert:await readFile(resolve(dir,'server.pem'))};
|
||||||
|
let mode='allow',maOrigin,foundryOrigin,upgrades=0;const seenOrigins=new Set(),sockets=new Set();
|
||||||
|
const handler=async(req,res)=>{
|
||||||
|
if(req.url==='/src/providers/ma/diagnostics.mjs'){res.setHeader('Content-Type','text/javascript');res.end(await readFile(resolve(root,'src/providers/ma/diagnostics.mjs')));return;}
|
||||||
|
const policy=`default-src 'self'; script-src 'self'; connect-src 'self'${mode==='allow'||mode==='reject-origin'?' '+maOrigin.replace('https:','wss:'):''}`;
|
||||||
|
res.setHeader(mode==='report-only'?'Content-Security-Policy-Report-Only':'Content-Security-Policy',policy);
|
||||||
|
res.end('<!doctype html><title>Isolated browser policy test</title>');
|
||||||
|
};
|
||||||
|
const ma=createServer(tls,handler),foundry=createServer(tls,handler);
|
||||||
|
for(const server of [ma,foundry]){
|
||||||
|
server.on('upgrade',(req,socket)=>{
|
||||||
|
sockets.add(socket);socket.on('error',()=>{});socket.on('close',()=>sockets.delete(socket));seenOrigins.add(req.headers.origin);
|
||||||
|
if(mode==='reject-origin'&&req.headers.origin!==maOrigin){socket.end('HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n');return;}
|
||||||
|
upgrades++;const accept=createHash('sha1').update(req.headers['sec-websocket-key']+'258EAFA5-E914-47DA-95CA-C5AB0DC85B11').digest('base64');
|
||||||
|
socket.write('HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: '+accept+'\r\n\r\n');
|
||||||
|
socket.on('data',()=>socket.end(Buffer.from([0x88,0]))); // No authentication, protocol emulation or commands.
|
||||||
|
});
|
||||||
|
await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
|
||||||
|
}
|
||||||
|
maOrigin=`https://127.0.0.1:${ma.address().port}`;foundryOrigin=`https://localhost:${foundry.address().port}`;
|
||||||
|
let context;const checks=[];
|
||||||
|
try{
|
||||||
|
context=await firefox.launchPersistentContext(profile,{headless:true});const page=await context.newPage();
|
||||||
|
const check=async(name,origin,expected)=>{
|
||||||
|
await page.goto(origin);assert.equal(await page.evaluate(()=>isSecureContext),true);
|
||||||
|
const results=await page.evaluate(async base=>{const {probeWebSockets}=await import('/src/providers/ma/diagnostics.mjs');return probeWebSockets(base);},maOrigin);
|
||||||
|
assert.deepEqual(results.map(r=>r.code),[expected,expected]);checks.push({name,results});
|
||||||
|
};
|
||||||
|
await check('Trusted HTTPS cross-origin WSS allowed',foundryOrigin,'upgrade-ok');
|
||||||
|
mode='csp';const before=upgrades;await check('Enforced CSP blocks cross-origin before upgrade',foundryOrigin,'csp-blocked');assert.equal(upgrades,before);
|
||||||
|
// Explicit WSS self is necessary across browser interpretations of HTTPS self.
|
||||||
|
mode='allow';await check('Same MA origin control',maOrigin,'upgrade-ok');
|
||||||
|
mode='report-only';await check('Report-only CSP does not block',foundryOrigin,'upgrade-ok');
|
||||||
|
mode='reject-origin';await check('Server Origin rejection stays opaque',foundryOrigin,'upgrade-failed');await check('Same origin still succeeds under Origin restriction',maOrigin,'upgrade-ok');
|
||||||
|
assert.ok(seenOrigins.has(foundryOrigin));assert.ok(seenOrigins.has(maOrigin));
|
||||||
|
const result={scope:'isolated real Firefox HTTPS/WSS policy tests; local transport server, no MA, no Foundry, no credentials or audio',browser:context.browser().version(),tls:'local CA trusted in disposable Firefox profile; no certificate bypass',checks,passed:true};
|
||||||
|
await mkdir(resolve(root,'evidence'),{recursive:true});await writeFile(resolve(root,'evidence/cross-origin-browser.json'),JSON.stringify(result,null,2)+'\n');console.log(JSON.stringify(result,null,2));
|
||||||
|
}finally{await context?.close();for(const socket of sockets)socket.destroy();await Promise.all([ma,foundry].map(server=>new Promise(resolve=>server.close(resolve))));}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
// Uses the deployed Foundry ApplicationV2 renderer, with in-memory sample documents.
|
||||||
|
// Does not log in, install anything, update a world or connect to MA.
|
||||||
|
import {readFile,writeFile,mkdir} from 'node:fs/promises';
|
||||||
|
import {resolve} from 'node:path';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
const {chromium}=await import(process.env.AM_PLAYWRIGHT_MODULE??'playwright');
|
||||||
|
const root=resolve(import.meta.dirname,'..'),config=JSON.parse(await readFile('.local/live-environment.json','utf8'));
|
||||||
|
const browser=await chromium.launch({headless:true,args:['--no-sandbox']});const page=await browser.newPage({viewport:{width:1440,height:1000}});
|
||||||
|
try{
|
||||||
|
await page.route(config.foundry+'/adaptive-music-development/**',async route=>{const rel=new URL(route.request().url()).pathname.slice('/adaptive-music-development/'.length),file=resolve(root,rel);if(!file.startsWith(root+'/src/'))return route.abort();try{await route.fulfill({contentType:'text/javascript',body:await readFile(file)});}catch{await route.abort();}});
|
||||||
|
await page.goto(config.foundry,{waitUntil:'domcontentloaded'});await page.waitForFunction(()=>globalThis.foundry?.applications?.api?.ApplicationV2);
|
||||||
|
await page.addStyleTag({content:await readFile('styles/adaptive-music.css','utf8')});
|
||||||
|
const details=await page.evaluate(async()=>{
|
||||||
|
const {createSetupClass}=await import('/adaptive-music-development/src/foundry/setup.mjs');
|
||||||
|
const {ReceiverVault}=await import('/adaptive-music-development/src/foundry/receiver-vault.mjs');
|
||||||
|
const collection=items=>{const m=new Map(items.map(i=>[i.id,i]));m[Symbol.iterator]=function*(){yield*m.values();};return m;};
|
||||||
|
const fixtureGame={world:{id:'ui-test',title:'UI test'},user:{isGM:true},settings:{get:(ns,key)=>({ownedPlaylistIds:'',musicDefaults:{},enabled:false})[key]},playlists:collection([]),scenes:collection([]),combats:[]};
|
||||||
|
const connection={status:{state:'disconnected',catalog:0,audioContext:'closed'},test:async()=>{},connect:async()=>{},refresh:async()=>{},resume:async()=>{},disconnect:async()=>{}};
|
||||||
|
const Setup=createSetupClass({game:fixtureGame,connection,getChoices:async()=>[],start(){},stop(){},setOverrides(){},onError(){}});window.testApplication=new Setup();await window.testApplication.render({force:true});
|
||||||
|
const scope={campaign:'isolated-ui-test',userId:'isolated-test-gm',maUrl:'https://ma.example.test'};
|
||||||
|
const vault=new ReceiverVault();await vault.save(scope,{identityStorage:{'sendspin-identity-sk':'A'.repeat(43)},targetName:'Test receiver',catalogKey:'fixture-key',namespace:'test',token:'must-never-be-stored'});
|
||||||
|
const record=await new ReceiverVault().load(scope);const other=await vault.load({...scope,userId:'other-gm'});await vault.forget(scope);
|
||||||
|
return {applicationV2:true,version:game.version,receiverVault:{reopened:record.identityStorage['sendspin-identity-sk']==='A'.repeat(43),tokenExcluded:!Object.hasOwn(record,'token'),userIsolation:other===null,forgotten:await vault.load(scope)===null}};
|
||||||
|
});
|
||||||
|
assert.ok(Object.values(details.receiverVault).every(Boolean));const sizes=[];
|
||||||
|
for(const width of [380,640]){await page.evaluate(width=>window.testApplication.setPosition({width}),width);await page.waitForTimeout(100);const fits=await page.locator('#adaptive-music-setup .adaptive-music-setup').evaluate(el=>el.scrollWidth<=el.clientWidth+1);assert.equal(fits,true);sizes.push({width,fits});}
|
||||||
|
await mkdir('dist/previews',{recursive:true});await page.screenshot({path:'dist/previews/foundry-v14-setup.png'});
|
||||||
|
const report={at:new Date().toISOString(),scope:'actual deployed Foundry ApplicationV2 before login, in-memory sample documents; no world writes or MA connection',browser:browser.version(),...details,sizes,passed:true};
|
||||||
|
await writeFile('evidence/foundry-application-v070.json',JSON.stringify(report,null,2)+'\n');console.log(JSON.stringify(report,null,2));
|
||||||
|
}finally{await browser.close();}
|
||||||
@@ -0,0 +1,288 @@
|
|||||||
|
// Browser diagnostics on the actual private HTTPS hosts. Records metadata only.
|
||||||
|
import {readFile, stat, writeFile} from 'node:fs/promises';
|
||||||
|
import {lookup} from 'node:dns/promises';
|
||||||
|
import {isIP} from 'node:net';
|
||||||
|
import {resolve} from 'node:path';
|
||||||
|
import {probeWebSockets} from '../src/providers/ma/diagnostics.mjs';
|
||||||
|
|
||||||
|
const report = {at: new Date().toISOString(), scope: 'private Nginx HTTPS route', checks: {}};
|
||||||
|
const playback = process.argv.includes('--playback');
|
||||||
|
const layoutOnly = process.argv.includes('--layout-only');
|
||||||
|
const loggedIn = playback || layoutOnly || process.argv.includes('--logged-in');
|
||||||
|
const engine = process.argv.includes('--firefox') ? 'firefox' : 'chromium';
|
||||||
|
const previewModule = process.argv.includes('--preview-module');
|
||||||
|
const expect = (ok, code) => { if (!ok) throw new Error(code); };
|
||||||
|
|
||||||
|
async function privateJSON(name) {
|
||||||
|
const file = `.local/${name}.json`;
|
||||||
|
expect(((await stat(file)).mode & 0o777) === 0o600, 'private-file-mode');
|
||||||
|
return JSON.parse(await readFile(file, 'utf8'));
|
||||||
|
}
|
||||||
|
|
||||||
|
function httpsOrigin(value) {
|
||||||
|
const url = new URL(value);
|
||||||
|
expect(url.protocol === 'https:' && !url.username && !url.password && url.pathname === '/' &&
|
||||||
|
!url.search && !url.hash && (!url.port || url.port === '443') &&
|
||||||
|
/^[a-z0-9.-]+$/i.test(url.hostname) && !isIP(url.hostname), 'invalid-https-origin');
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function verifyPrivateResponse(response, origin, proxyIP) {
|
||||||
|
expect(response && new URL(response.url()).origin === origin, 'unexpected-navigation-origin');
|
||||||
|
expect((await response.serverAddr())?.ipAddress === proxyIP, 'unexpected-server-address');
|
||||||
|
expect(await response.securityDetails(), 'missing-tls-details');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function openPrivatePage(page, url, proxyIP) {
|
||||||
|
const response = await page.goto(url.href, {waitUntil: 'domcontentloaded', timeout: 30000});
|
||||||
|
await verifyPrivateResponse(response, url.origin, proxyIP);
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function retainBrowserWebSocket(page) {
|
||||||
|
await page.addInitScript(() => {
|
||||||
|
Object.defineProperty(window, '__adaptiveMusicProbeNativeSocket', {value: window.WebSocket});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function collectTransport(page, response, ma) {
|
||||||
|
const headers = await response.allHeaders();
|
||||||
|
const session = engine === 'chromium' ? await page.context().newCDPSession(page) : null;
|
||||||
|
const requests = new Map();
|
||||||
|
const socketResults = [];
|
||||||
|
const failedRequests = [];
|
||||||
|
const policyIssues = [];
|
||||||
|
session?.on('Network.webSocketCreated', ({requestId, url}) => {
|
||||||
|
for (const path of ['/ws', '/sendspin']) {
|
||||||
|
if (url === `wss://${ma.host}${path}`) requests.set(requestId, path);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
session?.on('Network.webSocketHandshakeResponseReceived', ({requestId, response}) => {
|
||||||
|
if (requests.has(requestId)) socketResults.push({path: requests.get(requestId), httpStatus: response.status});
|
||||||
|
});
|
||||||
|
session?.on('Network.loadingFailed', ({requestId, errorText, blockedReason}) => {
|
||||||
|
if (!requests.has(requestId)) return;
|
||||||
|
const error = /^net::ERR_[A-Z0-9_]+$/.test(errorText) ? errorText : null;
|
||||||
|
failedRequests.push({path: requests.get(requestId), error, blockedReason: blockedReason ?? null});
|
||||||
|
});
|
||||||
|
session?.on('Network.webSocketFrameError', ({requestId, errorMessage}) => {
|
||||||
|
if (!requests.has(requestId)) return;
|
||||||
|
const status = errorMessage?.match(/Unexpected response code: (\d{3})/);
|
||||||
|
const error = errorMessage?.match(/\bnet::ERR_[A-Z0-9_]+\b/);
|
||||||
|
if (status || error) failedRequests.push({path: requests.get(requestId), httpStatus: status ? Number(status[1]) : null, error: error?.[0] ?? null});
|
||||||
|
});
|
||||||
|
session?.on('Audits.issueAdded', ({issue}) => {
|
||||||
|
const detail = issue.details?.corsIssueDetails ?? issue.details?.contentSecurityPolicyIssueDetails;
|
||||||
|
const url = detail?.request?.url ?? detail?.blockedURL;
|
||||||
|
if (!URL.canParse(url) || ![ma.origin, `wss://${ma.host}`].includes(new URL(url).origin)) return;
|
||||||
|
policyIssues.push({code: issue.code, reason: detail.corsErrorStatus?.corsError ?? detail.contentSecurityPolicyViolationType});
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
await session?.send('Network.enable');
|
||||||
|
await session?.send('Audits.enable');
|
||||||
|
const details = {
|
||||||
|
pageStatus: response.status(),
|
||||||
|
privatePeerVerified: true,
|
||||||
|
cspHeaderPresent: Boolean(headers['content-security-policy']),
|
||||||
|
reportOnlyCspHeaderPresent: Boolean(headers['content-security-policy-report-only']),
|
||||||
|
cspMetaPresent: await page.locator('meta[http-equiv="Content-Security-Policy" i]').count() > 0,
|
||||||
|
secureContext: await page.evaluate(() => globalThis.isSecureContext),
|
||||||
|
pageReplacesWebSocket: await page.evaluate(() => window.WebSocket !== window.__adaptiveMusicProbeNativeSocket),
|
||||||
|
upgrades: await page.evaluate(probeWebSockets, ma.origin),
|
||||||
|
handshakeReplies: socketResults,
|
||||||
|
failedRequests,
|
||||||
|
policyIssues,
|
||||||
|
};
|
||||||
|
if (details.pageReplacesWebSocket) {
|
||||||
|
details.nativeSendspinUpgrade = await page.evaluate(host => new Promise(resolve => {
|
||||||
|
const socket = new window.__adaptiveMusicProbeNativeSocket(`wss://${host}/sendspin`);
|
||||||
|
const timer = setTimeout(() => finish('upgrade-timeout'), 5000);
|
||||||
|
function finish(code) {
|
||||||
|
clearTimeout(timer);
|
||||||
|
socket.onopen = socket.onerror = socket.onclose = null;
|
||||||
|
socket.close();
|
||||||
|
resolve(code);
|
||||||
|
}
|
||||||
|
socket.onopen = () => finish('upgrade-ok');
|
||||||
|
socket.onerror = socket.onclose = () => finish('upgrade-failed');
|
||||||
|
}), ma.host);
|
||||||
|
}
|
||||||
|
return details;
|
||||||
|
} finally {
|
||||||
|
await session?.detach();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function joinWorld(browser, foundry, proxyIP, world, {name, gm, password}, progress) {
|
||||||
|
expect(typeof name === 'string' && name && typeof password === 'string' && typeof gm === 'boolean', 'invalid-test-account');
|
||||||
|
const page = await browser.newPage({viewport: {width: 1440, height: 1000}, screen: {width: 1440, height: 1000}});
|
||||||
|
if (previewModule) {
|
||||||
|
const prefix='/modules/adaptive-music/';
|
||||||
|
const root=resolve(import.meta.dirname,'..');
|
||||||
|
await page.context().route(`${foundry.origin}${prefix}**`,async route=>{
|
||||||
|
const file=new URL(route.request().url()).pathname.slice(prefix.length);
|
||||||
|
if(!/^(src\/.+\.mjs|styles\/.+\.css|vendor\/.+\.mjs)$/.test(file)||file.split('/').includes('..'))return route.continue();
|
||||||
|
await route.fulfill({path:resolve(root,file),contentType:file.endsWith('.css')?'text/css':'text/javascript'});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
page.setDefaultTimeout(20000);
|
||||||
|
await retainBrowserWebSocket(page);
|
||||||
|
if (playback) await page.addInitScript(() => {
|
||||||
|
const peers = [];
|
||||||
|
const contexts = [];
|
||||||
|
const analysers = [];
|
||||||
|
const listenerAnalysers = [];
|
||||||
|
window.__adaptiveMusicTestAudio = {contexts, analysers, listenerAnalysers};
|
||||||
|
const createStream = AudioContext.prototype.createMediaStreamDestination;
|
||||||
|
AudioContext.prototype.createMediaStreamDestination = function () {
|
||||||
|
const destination = createStream.call(this);
|
||||||
|
contexts.push({context: this, destination});
|
||||||
|
return destination;
|
||||||
|
};
|
||||||
|
const createAnalyser = AudioContext.prototype.createAnalyser;
|
||||||
|
AudioContext.prototype.createAnalyser = function () {
|
||||||
|
const analyser = createAnalyser.call(this);
|
||||||
|
analysers.push(analyser);
|
||||||
|
return analyser;
|
||||||
|
};
|
||||||
|
const createSource = AudioContext.prototype.createMediaStreamSource;
|
||||||
|
AudioContext.prototype.createMediaStreamSource = function (stream) {
|
||||||
|
const source = createSource.call(this, stream);
|
||||||
|
const analyser = createAnalyser.call(this);
|
||||||
|
source.connect(analyser);
|
||||||
|
listenerAnalysers.push({context: this, stream, analyser});
|
||||||
|
return source;
|
||||||
|
};
|
||||||
|
window.__adaptiveMusicTestPeers = peers;
|
||||||
|
window.RTCPeerConnection = new Proxy(window.RTCPeerConnection, {
|
||||||
|
construct(target, args, newTarget) {
|
||||||
|
const peer = Reflect.construct(target, args, newTarget);
|
||||||
|
peers.push(peer);
|
||||||
|
return peer;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
const url = new URL('/join', foundry);
|
||||||
|
progress('join-page');
|
||||||
|
await openPrivatePage(page, url, proxyIP);
|
||||||
|
await page.getByText(world.title, {exact: true}).first().waitFor({timeout: 30000});
|
||||||
|
expect(new URL(page.url()).pathname === '/join', 'unexpected-join-path');
|
||||||
|
|
||||||
|
progress('select-account');
|
||||||
|
const form = page.locator('#join-game-form');
|
||||||
|
const users = form.locator('select[name="userId"]');
|
||||||
|
await users.waitFor({state: 'visible'});
|
||||||
|
const option = await users.evaluate((select, name) => {
|
||||||
|
const user = [...select.options].find(option => option.label === name);
|
||||||
|
return user ? {value: user.value, disabled: user.disabled} : null;
|
||||||
|
}, name);
|
||||||
|
expect(option?.value, 'development-account-not-found');
|
||||||
|
expect(!option.disabled, 'development-account-unavailable');
|
||||||
|
await users.selectOption({value: option.value});
|
||||||
|
await form.locator('input[type="password"]').fill(password);
|
||||||
|
progress('submit-join');
|
||||||
|
const navigation = page.waitForResponse(response => response.request().isNavigationRequest() &&
|
||||||
|
response.request().frame() === page.mainFrame() && new URL(response.url()).pathname === '/game');
|
||||||
|
const [response] = await Promise.all([navigation, form.locator('[type="submit"]').click()]);
|
||||||
|
await verifyPrivateResponse(response, foundry.origin, proxyIP);
|
||||||
|
progress('wait-for-game-ready');
|
||||||
|
await page.bringToFront();
|
||||||
|
await page.waitForFunction(() => globalThis.game?.ready && game.socket?.connected, undefined, {polling: 250, timeout: 55000});
|
||||||
|
const state = await page.evaluate(({id, title, account}) => ({
|
||||||
|
worldMatches: game.world.id === id && game.world.title === title,
|
||||||
|
accountMatches: game.user.name === account,
|
||||||
|
gm: game.user.isGM,
|
||||||
|
foundryVersion: game.version,
|
||||||
|
system: game.system.id,
|
||||||
|
otherActiveGMs: game.users.filter(user => user.id !== game.user.id && user.active && user.isGM).length,
|
||||||
|
adaptiveMusicActive: game.modules.get('adaptive-music')?.active === true,
|
||||||
|
adaptiveMusicVersion: game.modules.get('adaptive-music')?.version ?? null,
|
||||||
|
}), {id: world.id, title: world.title, account: name});
|
||||||
|
expect(state.worldMatches && state.accountMatches && state.gm === gm, 'unexpected-world-account-or-role');
|
||||||
|
expect(state.foundryVersion === '14.371' && state.system === 'dnd5e', 'unexpected-foundry-or-system');
|
||||||
|
expect(state.otherActiveGMs === (state.gm ? 0 : 1), 'unexpected-active-gm-count');
|
||||||
|
expect(state.adaptiveMusicActive, 'adaptive-music-inactive');
|
||||||
|
// Keep the unattended canvases from saturating the shared headless renderer.
|
||||||
|
state.canvasTickerPaused = await page.evaluate(() => {
|
||||||
|
const ticker = globalThis.canvas?.app?.ticker;
|
||||||
|
if (!ticker?.started) return false;
|
||||||
|
ticker.stop();
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
return {page, response, state};
|
||||||
|
}
|
||||||
|
|
||||||
|
let browser, stage = 'configuration';
|
||||||
|
try {
|
||||||
|
const config = await privateJSON('live-environment');
|
||||||
|
const foundry = httpsOrigin(config.foundry), ma = httpsOrigin(config.ma);
|
||||||
|
const proxyIP = config.proxy_ip;
|
||||||
|
expect(isIP(proxyIP) === 4 && foundry.host !== ma.host, 'invalid-private-route');
|
||||||
|
const playwright = await import(process.env.AM_PLAYWRIGHT_MODULE ?? 'playwright');
|
||||||
|
stage = 'browser-launch';
|
||||||
|
if (engine === 'firefox') {
|
||||||
|
for (const host of [foundry.hostname, ma.hostname]) {
|
||||||
|
const answers = await lookup(host, {all: true});
|
||||||
|
expect(answers.length && answers.every(answer => answer.address === proxyIP), 'private-hostname-resolution-required');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
browser = await playwright[engine].launch(engine === 'chromium' ? {args: ['--no-sandbox', '--no-proxy-server',
|
||||||
|
`--host-resolver-rules=MAP ${foundry.hostname} ${proxyIP}, MAP ${ma.hostname} ${proxyIP}`]} :
|
||||||
|
{firefoxUserPrefs: {'network.trr.mode': 5, 'network.proxy.type': 0}});
|
||||||
|
report.engine = engine;
|
||||||
|
report.browser = browser.version();
|
||||||
|
report.moduleAssets = previewModule ? 'workspace module assets in the test browser' : 'installed module assets';
|
||||||
|
|
||||||
|
for (const [name, origin] of (layoutOnly ? [] : [['foundryAnonymous', foundry], ['maSameOrigin', ma]])) {
|
||||||
|
stage = name;
|
||||||
|
const page = await browser.newPage();
|
||||||
|
await retainBrowserWebSocket(page);
|
||||||
|
const response = await openPrivatePage(page, origin, proxyIP);
|
||||||
|
report.checks[name] = await collectTransport(page, response, ma);
|
||||||
|
await page.context().close();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (loggedIn) {
|
||||||
|
stage = 'development-world-configuration';
|
||||||
|
const {world, accounts} = await privateJSON('foundry-development');
|
||||||
|
expect(typeof world?.id === 'string' && world.id && typeof world.title === 'string' && world.title &&
|
||||||
|
Array.isArray(accounts) && accounts.length === 3 && accounts.every((account, index) => account?.gm === (index === 0)) &&
|
||||||
|
new Set(accounts.map(account => account.name)).size === 3, 'invalid-development-world-configuration');
|
||||||
|
report.accounts = {};
|
||||||
|
const pages = [];
|
||||||
|
for (const [index, account] of (layoutOnly ? accounts.slice(0,1) : accounts).entries()) {
|
||||||
|
const login = index === 0 ? 'gm-login' : `player-${index}-login`;
|
||||||
|
const {page, response, state} = await joinWorld(browser, foundry, proxyIP, world, account, step => {
|
||||||
|
stage = `${login}-${step}`;
|
||||||
|
console.error(`Development world authentication stage: ${stage}`);
|
||||||
|
});
|
||||||
|
report.accounts[login] = state;
|
||||||
|
pages.push(page);
|
||||||
|
if (index === 0 && !layoutOnly) {
|
||||||
|
stage = 'foundryLoggedIn';
|
||||||
|
report.checks[stage] = await collectTransport(page, response, ma);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if(layoutOnly){
|
||||||
|
stage='foundry-graphical-layout';
|
||||||
|
const {checkFoundryLayout}=await import('./live_foundry_playback.mjs');
|
||||||
|
report.layout=await checkFoundryLayout(pages[0],ma);
|
||||||
|
}
|
||||||
|
if (playback) {
|
||||||
|
stage = 'installed-world-playback';
|
||||||
|
const {checkFoundryPlayback} = await import('./live_foundry_playback.mjs');
|
||||||
|
report.playback = {};
|
||||||
|
await checkFoundryPlayback({pages, ma, world, report: report.playback});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
report.completed = true;
|
||||||
|
} catch (error) {
|
||||||
|
report.completed = false;
|
||||||
|
report.failure = {stage, code: /^[a-z][a-z-]+$/.test(error.message) ? error.message : error.code ?? error.name};
|
||||||
|
process.exitCode = 1;
|
||||||
|
} finally {
|
||||||
|
await browser?.close();
|
||||||
|
const resultName=previewModule?`foundry-am006-preview-${engine}`:`foundry-private-route-${engine}`;
|
||||||
|
await writeFile(`.local/${resultName}.json`, JSON.stringify(report, null, 2) + '\n', {mode: 0o600});
|
||||||
|
console.log(JSON.stringify(report, null, 2));
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
// 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);
|
||||||
|
for(const width of [380,640,1000]){
|
||||||
|
await page.setViewportSize({width,height:1000});
|
||||||
|
assert.equal(await page.locator('.adaptive-music-setup').evaluate(el=>el.scrollWidth<=el.clientWidth+1),true,'setup must fit narrow window');
|
||||||
|
assert.equal(await page.getByLabel('ICE server URL').isVisible(),false,'advanced fields must remain hidden');
|
||||||
|
}
|
||||||
|
await page.getByLabel('Music Assistant server address').fill('https://ma.example.test');await page.getByLabel('Private GM access token').fill('fixture-token');
|
||||||
|
await page.getByRole('button',{name:'Connect',exact:true}).click();await page.getByText('Campaign audio connected.',{exact:false}).waitFor();
|
||||||
|
assert.equal(await page.getByLabel('Private GM access token').inputValue(),'');
|
||||||
|
await page.getByRole('button',{name:'Choose scene music',exact:true}).click();
|
||||||
|
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 page.getByRole('button',{name:'Go to Playback',exact:true}).click();await page.getByRole('heading',{name:'Forest at night'}).waitFor();
|
||||||
|
await page.getByText('2 connected listeners',{exact:true}).waitFor();
|
||||||
|
await page.getByRole('button',{name:'Pause',exact:true}).click();await page.getByRole('button',{name:'Resume',exact:true}).click();
|
||||||
|
await page.getByLabel('Playback position').press('ArrowRight');await page.getByText('0:13 / 1:30',{exact:true}).waitFor();
|
||||||
|
await page.getByLabel('Campaign volume').press('ArrowLeft');
|
||||||
|
assert.equal(await page.getByLabel('Campaign volume').inputValue(),'99');
|
||||||
|
await page.getByRole('button',{name:'Stop playback',exact:true}).click();await page.getByText('Stopped',{exact:true}).waitFor();
|
||||||
|
assert.deepEqual(await page.evaluate(()=>window.controlActions),['pause','resume','seek','stop']);
|
||||||
|
await mkdir(resolve(root,'dist/previews'),{recursive:true});await page.screenshot({path:resolve(root,'dist/previews/am006-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:['380/640/1000px layout','three setup tabs','private field clearing','catalog selectors','ambient/combat save','advanced controls hidden','track and listeners','pause/resume/seek/volume/stop','listener activation'],pageErrors:errors},null,2));
|
||||||
|
}finally{await browser?.close();await new Promise(resolve=>server.close(resolve));}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
// Read-only comparison of browser-prepared media. Raw identifiers remain private.
|
||||||
|
import {readFile,writeFile} from 'node:fs/promises';
|
||||||
|
import {resolve} from 'node:path';
|
||||||
|
import {createHash} from 'node:crypto';
|
||||||
|
import {loadMAToken} from '../gateway/private-config.mjs';
|
||||||
|
const {chromium,firefox}=await import(process.env.AM_PLAYWRIGHT_MODULE??'playwright');
|
||||||
|
const cfg=JSON.parse(await readFile('.local/live-environment.json','utf8')),token=await loadMAToken('.local'),root=resolve(import.meta.dirname,'..');
|
||||||
|
const result=[];
|
||||||
|
for(const [name,type]of [['firefox',firefox],['chromium',chromium]]){
|
||||||
|
const browser=await type.launch({headless:true,...(name==='chromium'?{args:['--no-sandbox']}: {})});
|
||||||
|
try{const page=await browser.newPage();await page.route(cfg.foundry+'/adaptive-music-development/**',async route=>{const rel=new URL(route.request().url()).pathname.slice('/adaptive-music-development/'.length),file=resolve(root,rel);if(!file.startsWith(root+'/src/')&&!file.startsWith(root+'/vendor/'))return route.abort();await route.fulfill({contentType:'text/javascript',body:await readFile(file)});});await page.goto(cfg.foundry,{waitUntil:'domcontentloaded'});
|
||||||
|
const data=await page.evaluate(async({base,token})=>{
|
||||||
|
const {GMMAWebSocket}=await import('/adaptive-music-development/src/providers/ma/websocket.mjs');const {MAReadClient}=await import('/adaptive-music-development/src/providers/ma/client.mjs');const transport=new GMMAWebSocket({baseUrl:base,token});
|
||||||
|
try{const providers=await (await transport.fetch(base+'/api',{method:'POST',redirect:'error',body:JSON.stringify({command:'providers',args:{provider_type:'music'}})})).json();const client=new MAReadClient({baseUrl:base,token,target:'read-only-unused-target',approvedProviders:providers.filter(p=>p.available).map(p=>p.instance_id),fetchImpl:transport.fetch});const choices=await client.catalog();const prepared=[];for(const choice of choices.filter(c=>c.kind==='playlist').slice(0,2))prepared.push(await client.prepareMedia({provider:'ma',id:choice.id}));return prepared;}finally{transport.close();}
|
||||||
|
},{base:cfg.ma,token});await writeFile('.local/catalog-prepared-'+name+'.json',JSON.stringify(data),{mode:0o600});result.push({browser:name,version:browser.version(),tracks:data.map(p=>p.length),digest:createHash('sha256').update(JSON.stringify(data)).digest('hex')});
|
||||||
|
}finally{await browser.close();}
|
||||||
|
}
|
||||||
|
console.log(JSON.stringify({results:result,identical:result[0].digest===result[1].digest},null,2));
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
// Authorized read-only real-origin browser check. Private inputs/results stay .local.
|
||||||
|
import {readFile,writeFile,chmod} from 'node:fs/promises';
|
||||||
|
const {chromium,firefox}=await import(process.env.AM_PLAYWRIGHT_MODULE??'playwright');
|
||||||
|
import {loadMAToken} from '../gateway/private-config.mjs';
|
||||||
|
const config=JSON.parse(await readFile('.local/live-environment.json','utf8')),token=await loadMAToken('.local');
|
||||||
|
const report={at:new Date().toISOString(),scope:'actual origins, read-only API authentication; Ubuntu browsers, not Mac',browsers:[]};
|
||||||
|
for(const [name,type]of (process.env.AM_PRIVATE_ROUTE==='1'?[['chromium',chromium]]:[['firefox',firefox],['chromium',chromium]])){
|
||||||
|
const browser=await type.launch({headless:true,...(name==='chromium'?{args:['--no-sandbox',...(process.env.AM_PRIVATE_ROUTE==='1'?['--host-resolver-rules=MAP '+new URL(config.ma).hostname+' '+config.proxy_ip]:[])]}: {})});
|
||||||
|
try{
|
||||||
|
for(const origin of ['foundry','ma']){
|
||||||
|
const page=await browser.newPage();const entry={browser:name,version:browser.version(),origin,maRoute:process.env.AM_PRIVATE_ROUTE==='1'&&name==='chromium'?'sandbox DNS override to private proxy; TLS validation unchanged':'normal resolver'};
|
||||||
|
try{
|
||||||
|
const response=await page.goto(config[origin],{waitUntil:'domcontentloaded',timeout:20000});const headers=await response.allHeaders();
|
||||||
|
entry.httpStatus=response.status();entry.csp=headers['content-security-policy']??null;
|
||||||
|
entry.result=await page.evaluate(async({base,token})=>{
|
||||||
|
const meta=[...document.querySelectorAll('meta[http-equiv]')].filter(e=>e.httpEquiv.toLowerCase()==='content-security-policy').map(e=>e.content);
|
||||||
|
const blocked=[];const policy=e=>blocked.push({directive:e.effectiveDirective,disposition:e.disposition});document.addEventListener('securitypolicyviolation',policy);
|
||||||
|
const result=await new Promise(resolve=>{
|
||||||
|
const url=new URL('/ws',base);url.protocol='wss:';let opened=false,settled=false,socket;
|
||||||
|
const finish=result=>{if(settled)return;settled=true;clearTimeout(timer);if(socket){socket.onmessage=socket.onerror=socket.onclose=null;socket.close();}resolve(result);};
|
||||||
|
const timer=setTimeout(()=>finish({stage:opened?'auth-timeout':'upgrade-timeout'}),10000);
|
||||||
|
try{socket=new WebSocket(url);socket.onopen=()=>{opened=true;socket.send(JSON.stringify({message_id:'am-preflight-auth',command:'auth',args:{token}}));};
|
||||||
|
socket.onmessage=e=>{let msg;try{msg=JSON.parse(e.data);}catch{return;}
|
||||||
|
if(msg.message_id==='am-preflight-auth'){
|
||||||
|
if(msg.result?.authenticated!==true){finish({stage:'auth-rejected'});return;}
|
||||||
|
socket.send(JSON.stringify({message_id:'am-preflight-providers',command:'providers',args:{provider_type:'music'}}));
|
||||||
|
}
|
||||||
|
if(msg.message_id==='am-preflight-providers')finish({stage:'authenticated',providerCount:Array.isArray(msg.result)?msg.result.length:null,commandError:msg.error_code??null});
|
||||||
|
};socket.onerror=()=>setTimeout(()=>finish({stage:opened?'socket-error':'upgrade-error'}),100);socket.onclose=e=>finish({stage:opened?'closed-after-open':'closed-before-open',code:e.code});
|
||||||
|
}catch{setTimeout(()=>finish({stage:'constructor-error'}),100);}
|
||||||
|
});document.removeEventListener('securitypolicyviolation',policy);return {...result,metaCSP:meta,blocked,secureContext:isSecureContext};
|
||||||
|
},{base:config.ma,token});
|
||||||
|
}catch{entry.result={stage:'navigation-failed'};}
|
||||||
|
report.browsers.push(entry);await page.close();
|
||||||
|
}
|
||||||
|
}finally{await browser.close();}
|
||||||
|
}
|
||||||
|
await writeFile(process.env.AM_PRIVATE_ROUTE==='1'?'.local/live-browser-private-preflight.json':'.local/live-browser-preflight.json',JSON.stringify(report,null,2)+'\n',{mode:0o600});await chmod('.local/live-browser-preflight.json',0o600);
|
||||||
|
console.log(JSON.stringify(report,null,2));
|
||||||
@@ -0,0 +1,458 @@
|
|||||||
|
// Exercises the installed module through the authorized development world.
|
||||||
|
import {randomUUID} from 'node:crypto';
|
||||||
|
import {setTimeout as delay} from 'node:timers/promises';
|
||||||
|
import {loadMAToken} from '../gateway/private-config.mjs';
|
||||||
|
|
||||||
|
const moduleId = 'adaptive-music';
|
||||||
|
const check = (value, code) => { if (!value) throw new Error(code); };
|
||||||
|
|
||||||
|
async function until(read, accept, code, timeout = 25000) {
|
||||||
|
const end = Date.now() + timeout;
|
||||||
|
do {
|
||||||
|
const result = await read();
|
||||||
|
if (accept(result)) return result;
|
||||||
|
await delay(300);
|
||||||
|
} while (Date.now() < end);
|
||||||
|
throw new Error(code);
|
||||||
|
}
|
||||||
|
|
||||||
|
function observeMA(page, ma) {
|
||||||
|
const commands = [];
|
||||||
|
let sendspinAuthenticated = false;
|
||||||
|
const json = event => {
|
||||||
|
if (typeof event.payload !== 'string') return null;
|
||||||
|
try { return JSON.parse(event.payload); } catch { return null; }
|
||||||
|
};
|
||||||
|
page.on('websocket', socket => {
|
||||||
|
if (socket.url() === `wss://${ma.host}/sendspin`) {
|
||||||
|
socket.on('framereceived', event => {
|
||||||
|
if (json(event)?.type === 'auth_ok') sendspinAuthenticated = true;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (socket.url() !== `wss://${ma.host}/ws`) return;
|
||||||
|
const pending = new Map();
|
||||||
|
socket.on('framesent', event => {
|
||||||
|
const frame = json(event);
|
||||||
|
if (!frame?.message_id || typeof frame.command !== 'string') return;
|
||||||
|
const entry = {command: frame.command, args: frame.command.startsWith('player_queues/') ? frame.args : null};
|
||||||
|
commands.push(entry);
|
||||||
|
pending.set(frame.message_id, entry);
|
||||||
|
});
|
||||||
|
socket.on('framereceived', event => {
|
||||||
|
const frame = json(event);
|
||||||
|
const entry = pending.get(frame?.message_id);
|
||||||
|
if (!entry || frame.partial) return;
|
||||||
|
pending.delete(frame.message_id);
|
||||||
|
entry.reply = true;
|
||||||
|
entry.error = frame.error_code ?? null;
|
||||||
|
if (entry.command === 'auth') entry.authenticated = frame.result?.authenticated === true;
|
||||||
|
if (entry.command === 'players/get' && frame.result) entry.player = {id:frame.result.player_id,name:frame.result.name};
|
||||||
|
if (entry.command === 'player_queues/get' && frame.result) {
|
||||||
|
const {state, current_index, elapsed_time} = frame.result;
|
||||||
|
entry.queue = {state, index: current_index, position: elapsed_time};
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
return {commands, sendspinAuthenticated: () => sendspinAuthenticated};
|
||||||
|
}
|
||||||
|
|
||||||
|
function safeStats(page) {
|
||||||
|
return page.evaluate(async moduleId => {
|
||||||
|
const stats = await game.modules.get(moduleId).api.peerStats();
|
||||||
|
const streams = [...document.querySelectorAll('audio')].map(element => element.srcObject).filter(Boolean);
|
||||||
|
const rms = (window.__adaptiveMusicTestAudio?.listenerAnalysers ?? []).filter(sensor => streams.includes(sensor.stream))
|
||||||
|
.reduce((max, {analyser}) => {
|
||||||
|
const samples = new Float32Array(analyser.fftSize);
|
||||||
|
analyser.getFloatTimeDomainData(samples);
|
||||||
|
return Math.max(max, Math.sqrt(samples.reduce((sum, sample) => sum + sample ** 2, 0) / samples.length));
|
||||||
|
}, 0);
|
||||||
|
return stats.filter(row => row.type === 'inbound-rtp').reduce((result, row) => ({
|
||||||
|
rms,
|
||||||
|
bytes: result.bytes + (row.bytesReceived ?? 0),
|
||||||
|
energy: result.energy + (row.totalAudioEnergy ?? 0),
|
||||||
|
samples: result.samples + (row.totalSamplesReceived ?? 0),
|
||||||
|
}), {rms, bytes: 0, energy: 0, samples: 0});
|
||||||
|
}, moduleId);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function gmAudioDiagnostics(page, setup) {
|
||||||
|
await page.evaluate(() => {
|
||||||
|
Object.defineProperty(navigator.clipboard, 'writeText', {
|
||||||
|
configurable: true,
|
||||||
|
value: async text => { window.__adaptiveMusicTestDiagnostics = JSON.parse(text); },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
await setup.getByRole('button', {name: 'Copy connection diagnostics', exact: true}).click({timeout: 3000});
|
||||||
|
return page.evaluate(() => {
|
||||||
|
const d = window.__adaptiveMusicTestDiagnostics;
|
||||||
|
if (!d) return null;
|
||||||
|
return {
|
||||||
|
stage: d.stage, state: d.state, audioContext: d.audioContext, decoded: d.decodedFrames,
|
||||||
|
scheduled: d.scheduledFrames, droppedLate: d.droppedLate, droppedAhead: d.droppedAhead,
|
||||||
|
signalRMS: d.signalRMS, muted: d.muted, listenerConnections: d.listenerConnections,
|
||||||
|
volume: Number([...document.querySelectorAll('#adaptive-music-setup input[type="range"]')][0]?.value),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function openMenu(page, name) {
|
||||||
|
await page.evaluate(async key => {
|
||||||
|
const type = game.settings.menus.get(key)?.type;
|
||||||
|
if (!type) throw Error('missing-installed-module-menu');
|
||||||
|
const app=new type();
|
||||||
|
await app.render({force: true});
|
||||||
|
window.__adaptiveTestWindow=app;
|
||||||
|
}, `${moduleId}.${name}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const writes = new Set(['stop', 'clear', 'play_media', 'play_index', 'repeat'].map(action => 'player_queues/' + action));
|
||||||
|
|
||||||
|
export async function checkFoundryLayout(page,ma){
|
||||||
|
await openMenu(page,'setup');
|
||||||
|
const setup=page.locator('#adaptive-music-setup');
|
||||||
|
const tabs=setup.getByRole('tab');
|
||||||
|
check(await tabs.count()===3,'three-foundry-tabs-required');
|
||||||
|
const resizable=await page.evaluate(()=>window.__adaptiveTestWindow.options.window.resizable);
|
||||||
|
check(resizable===true,'foundry-window-not-resizable');
|
||||||
|
const originalWidth=Math.round((await setup.boundingBox()).width);
|
||||||
|
const layout=[];
|
||||||
|
for(const width of [originalWidth,380]){
|
||||||
|
await page.evaluate(width=>window.__adaptiveTestWindow.setPosition({width,height:490}),width);
|
||||||
|
for(const label of ['Connection','Scene Music','Playback']){
|
||||||
|
await setup.getByRole('tab',{name:label,exact:true}).click();
|
||||||
|
const panel=setup.getByRole('tabpanel');
|
||||||
|
await panel.waitFor({state:'visible'});
|
||||||
|
const measurements=await panel.evaluate(el=>{
|
||||||
|
const content=el.closest('.window-content');
|
||||||
|
const horizontalFit=el.scrollWidth<=el.clientWidth+1&&content.scrollWidth<=content.clientWidth+1;
|
||||||
|
const nestedScroll=[...content.querySelectorAll('div,section,details,fieldset')].some(node=>['auto','scroll'].includes(getComputedStyle(node).overflowY));
|
||||||
|
return {horizontalFit,nestedScroll};
|
||||||
|
});
|
||||||
|
check(measurements.horizontalFit&&!measurements.nestedScroll,'foundry-layout-overflow');
|
||||||
|
layout.push({width,tab:label,...measurements});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await setup.getByRole('tab',{name:'Connection',exact:true}).press('ArrowRight');
|
||||||
|
check(await setup.getByRole('tabpanel',{name:'Scene Music'}).isVisible(),'tab-keyboard-navigation-failed');
|
||||||
|
await setup.getByRole('tab',{name:'Connection',exact:true}).click();
|
||||||
|
const advanced=setup.getByText('Advanced',{exact:true});
|
||||||
|
check(!await setup.getByLabel('ICE server URL').isVisible(),'advanced-visible-by-default');
|
||||||
|
await advanced.click();
|
||||||
|
check(await setup.getByLabel('ICE server URL').isVisible(),'advanced-controls-unreachable');
|
||||||
|
await advanced.click();
|
||||||
|
await setup.getByLabel('Music Assistant server address').fill('https://ma.example.test/path');
|
||||||
|
await setup.getByRole('button',{name:'Connect',exact:true}).click();
|
||||||
|
await setup.getByRole('alert').filter({hasText:'Enter the MA server origin'}).waitFor();
|
||||||
|
await setup.getByLabel('Music Assistant server address').fill(ma.origin);
|
||||||
|
await setup.getByRole('button',{name:'Connect',exact:true}).click();
|
||||||
|
await setup.getByRole('alert').filter({hasText:'Enter a Music Assistant access token'}).waitFor();
|
||||||
|
await setup.getByRole('button',{name:'Check browser connection',exact:true}).click();
|
||||||
|
await setup.getByText('Browser checks complete.',{exact:true}).waitFor();
|
||||||
|
const routeDiagnostics=await setup.locator('[aria-live="polite"] p').evaluateAll(lines=>lines.map(line=>({
|
||||||
|
path:line.textContent.startsWith('/ws')?'/ws':'/sendspin',opened:line.textContent.includes('upgrade succeeded'),
|
||||||
|
})));
|
||||||
|
check(routeDiagnostics.length===2,'missing-graphical-route-diagnostics');
|
||||||
|
return {resizable,layout,keyboardTabs:true,advancedCollapsed:true,invalidAddressRejected:true,missingTokenRejected:true,routeDiagnostics};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function checkFoundryPlayback({pages, ma, world, report}) {
|
||||||
|
const [gm, ...players] = pages;
|
||||||
|
const run = randomUUID().slice(0, 8);
|
||||||
|
const receiverName = `Adaptive Music integration ${run}`;
|
||||||
|
const fixtureName = `Adaptive Music verification ${run}`;
|
||||||
|
const setup = gm.locator('#adaptive-music-setup');
|
||||||
|
const wire = observeMA(gm, ma);
|
||||||
|
const stage = name => {
|
||||||
|
report.stage = name;
|
||||||
|
console.error(`Installed-world playback stage: ${name}`);
|
||||||
|
};
|
||||||
|
let baseline, sceneId, combatId, receiver;
|
||||||
|
|
||||||
|
const fixture = data => gm.evaluate(async ({world, moduleId, ...data}) => {
|
||||||
|
if (!game.ready || game.world.id !== world || !game.user.isGM || !game.socket?.connected) throw Error('wrong-development-world');
|
||||||
|
if (data.action === 'scene') {
|
||||||
|
const scene = await CONFIG.Scene.documentClass.create({name: data.fixtureName, width: 1200, height: 1000, navigation: false, tokenVision: false});
|
||||||
|
return scene.id;
|
||||||
|
}
|
||||||
|
if (data.action === 'combat') {
|
||||||
|
const combat = await CONFIG.Combat.documentClass.create({scene: data.sceneId, active: true});
|
||||||
|
await combat.createEmbeddedDocuments('Combatant', [{name: data.fixtureName, initiative: 12}]);
|
||||||
|
return combat.id;
|
||||||
|
}
|
||||||
|
if (data.action === 'start-combat') {
|
||||||
|
const combat = game.combats.get(data.combatId);
|
||||||
|
await combat.startCombat();
|
||||||
|
return Boolean(combat.started && combat.active);
|
||||||
|
}
|
||||||
|
if (data.action === 'delete-combat') return game.combats.get(data.combatId)?.delete().then(() => true);
|
||||||
|
if (data.action === 'activate-scene') return game.scenes.get(data.sceneId)?.activate().then(() => true);
|
||||||
|
if (data.action === 'baseline') {
|
||||||
|
const enabled = game.settings.get(moduleId, 'enabled');
|
||||||
|
const scene = game.scenes.active?.id ?? null;
|
||||||
|
if (enabled) {
|
||||||
|
game.modules.get(moduleId).api.stopDevelopment();
|
||||||
|
await game.settings.set(moduleId, 'enabled', false);
|
||||||
|
}
|
||||||
|
return {enabled, scene};
|
||||||
|
}
|
||||||
|
if (data.action === 'cleanup') {
|
||||||
|
const api = game.modules.get(moduleId).api;
|
||||||
|
api.stopDevelopment();
|
||||||
|
await api.closeGMHost();
|
||||||
|
if (data.combatId) await game.combats.get(data.combatId)?.delete();
|
||||||
|
if (data.baseline.scene && game.scenes.active?.id !== data.baseline.scene) await game.scenes.get(data.baseline.scene)?.activate();
|
||||||
|
if (data.sceneId) await game.scenes.get(data.sceneId)?.delete();
|
||||||
|
if (game.settings.get(moduleId, 'enabled') !== data.baseline.enabled) await game.settings.set(moduleId, 'enabled', data.baseline.enabled);
|
||||||
|
return (!data.sceneId || !game.scenes.has(data.sceneId)) && (!data.combatId || !game.combats.has(data.combatId)) &&
|
||||||
|
game.settings.get(moduleId, 'enabled') === data.baseline.enabled;
|
||||||
|
}
|
||||||
|
throw Error('unknown-fixture-operation');
|
||||||
|
}, {world: world.id, moduleId, ...data});
|
||||||
|
|
||||||
|
const command = (from, name, predicate = () => true) => until(
|
||||||
|
() => wire.commands.slice(from).find(entry => entry.command === `player_queues/${name}` && entry.reply && predicate(entry.args)),
|
||||||
|
Boolean, `ma-${name.replaceAll('_', '-')}-not-observed`, 70000).then(entry => {
|
||||||
|
if (entry.error !== null) report.upstreamError = {command: entry.command, code: entry.error};
|
||||||
|
check(entry.error === null, 'ma-queue-command-failed');
|
||||||
|
return entry;
|
||||||
|
});
|
||||||
|
|
||||||
|
const audio = async () => {
|
||||||
|
const before = await Promise.all(players.map(safeStats));
|
||||||
|
try {
|
||||||
|
return await Promise.all(players.map(async (page, index) => {
|
||||||
|
const after = await until(() => safeStats(page), value => value.bytes > before[index].bytes &&
|
||||||
|
(value.energy - before[index].energy > 1e-6 || value.rms > 0.001),
|
||||||
|
'listener-audio-energy-did-not-increase', 30000);
|
||||||
|
return {bytesIncreased: true, energyIncrease: after.energy - before[index].energy, playbackRMS: after.rms,
|
||||||
|
samplesIncreased: after.samples > before[index].samples};
|
||||||
|
}));
|
||||||
|
} catch (error) {
|
||||||
|
report.listenerStatsAtFailure = await Promise.all(players.map(page => safeStats(page).catch(() => null)));
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
stage('world-readiness');
|
||||||
|
await gm.waitForFunction(({moduleId, count}) => game.modules.get(moduleId)?.api &&
|
||||||
|
[...game.users].filter(user => user.active && !user.isGM).length >= count &&
|
||||||
|
[...game.users].filter(user => user.active && user.isGM).length === 1, {moduleId, count: players.length});
|
||||||
|
report.publicKeys = await Promise.all(pages.map(page => page.waitForFunction(moduleId => Boolean(game.user.getFlag(moduleId, 'audioPublicKey')?.key), moduleId, {timeout: 8000}).then(() => true, () => false)));
|
||||||
|
await Promise.all(pages.map(page => page.evaluate(() => {
|
||||||
|
const tally = {invitationsForMe: 0, invitationEvents: 0, offers: 0, answers: 0, sentInvitations: 0, sentSignals: 0};
|
||||||
|
window.__adaptiveMusicTestSignaling = tally;
|
||||||
|
game.socket.on('module.adaptive-music', frame => {
|
||||||
|
if (frame?.type === 'audio-invite-v1') {
|
||||||
|
tally.invitationEvents++;
|
||||||
|
if (frame.to === game.user.id) tally.invitationsForMe++;
|
||||||
|
}
|
||||||
|
if (frame?.v === 1 && frame.from === 'listener') tally.offers++;
|
||||||
|
if (frame?.v === 1 && frame.from === 'gm') tally.answers++;
|
||||||
|
});
|
||||||
|
game.socket.onAnyOutgoing?.((event, frame) => {
|
||||||
|
if (event !== 'module.adaptive-music') return;
|
||||||
|
if (frame?.type === 'audio-invite-v1') tally.sentInvitations++;
|
||||||
|
if (frame?.v === 1 && typeof frame.cipher === 'string') tally.sentSignals++;
|
||||||
|
});
|
||||||
|
})));
|
||||||
|
|
||||||
|
stage('user-document-permissions');
|
||||||
|
const gmId = await gm.evaluate(() => game.user.id);
|
||||||
|
const probeFlag = `integrationProbe${run}`;
|
||||||
|
report.playerCannotWriteGMFlag = await players[0].evaluate(async ({gmId, moduleId, probeFlag}) => {
|
||||||
|
try { await game.users.get(gmId).setFlag(moduleId, probeFlag, true); return false; }
|
||||||
|
catch { return true; }
|
||||||
|
}, {gmId, moduleId, probeFlag});
|
||||||
|
if (!report.playerCannotWriteGMFlag) await gm.evaluate(({moduleId, probeFlag}) => game.user.unsetFlag(moduleId, probeFlag), {moduleId, probeFlag});
|
||||||
|
|
||||||
|
stage('create-test-scene');
|
||||||
|
baseline = await fixture({action: 'baseline'});
|
||||||
|
sceneId = await fixture({action: 'scene', fixtureName});
|
||||||
|
await fixture({action: 'activate-scene', sceneId});
|
||||||
|
await openMenu(gm, 'setup');
|
||||||
|
await gm.evaluate(()=>{
|
||||||
|
window.__adaptiveTestNotifications=[];
|
||||||
|
const observer=new MutationObserver(()=>{
|
||||||
|
for(const node of document.querySelectorAll('#notifications .notification')){
|
||||||
|
const text=node.textContent.trim();
|
||||||
|
if(text.startsWith('Adaptive Music: ')&&!window.__adaptiveTestNotifications.includes(text))window.__adaptiveTestNotifications.push(text);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
observer.observe(document.body,{childList:true,subtree:true});
|
||||||
|
});
|
||||||
|
|
||||||
|
stage('ma-authentication');
|
||||||
|
const tabbed=await setup.getByRole('tab',{name:'Connection',exact:true}).count()>0;
|
||||||
|
await setup.getByLabel('Music Assistant server address').fill(ma.origin);
|
||||||
|
if(tabbed){
|
||||||
|
const before=wire.commands.length;
|
||||||
|
report.advancedInitiallyCollapsed=!await setup.getByLabel('ICE server URL').isVisible();
|
||||||
|
await setup.getByRole('button',{name:'Connect',exact:true}).click();
|
||||||
|
await setup.getByRole('alert').filter({hasText:'Enter a Music Assistant access token'}).waitFor();
|
||||||
|
report.formRejectedMissingTokenWithoutNetwork=wire.commands.length===before;
|
||||||
|
check(report.formRejectedMissingTokenWithoutNetwork&&report.advancedInitiallyCollapsed,'connection-form-validation-failed');
|
||||||
|
await setup.getByText('Advanced',{exact:true}).click();
|
||||||
|
await setup.getByLabel('Dedicated receiver name').fill(receiverName);
|
||||||
|
await setup.getByText('Advanced',{exact:true}).click();
|
||||||
|
await setup.getByLabel('Private GM access token').fill(await loadMAToken('.local'));
|
||||||
|
await setup.getByRole('button',{name:'Connect',exact:true}).click();
|
||||||
|
await setup.getByText(/^Campaign audio connected\./).waitFor({timeout:50000});
|
||||||
|
receiver=wire.commands.findLast(entry=>entry.player?.name===receiverName)?.player.id;
|
||||||
|
check(receiver,'receiver-identity-not-verified');
|
||||||
|
report.oneClickConnection=true;
|
||||||
|
await setup.getByRole('button',{name:'Choose scene music'}).click();
|
||||||
|
}else{
|
||||||
|
await setup.getByLabel('Private GM access token').fill(await loadMAToken('.local'));
|
||||||
|
await setup.getByText('Receiver options',{exact:true}).click();
|
||||||
|
await setup.getByLabel('Dedicated receiver name').fill(receiverName);
|
||||||
|
await setup.getByRole('button',{name:'Authenticate',exact:true}).click();
|
||||||
|
const selector=setup.getByLabel('Dedicated campaign receiver');
|
||||||
|
await selector.locator('option').filter({hasText:receiverName}).waitFor({state:'attached',timeout:25000});
|
||||||
|
receiver=await selector.inputValue();
|
||||||
|
await setup.getByRole('button',{name:'Connect audio',exact:true}).click();
|
||||||
|
}
|
||||||
|
report.maAPIAuthenticated = wire.commands.some(entry => entry.authenticated);
|
||||||
|
check(receiver && report.maAPIAuthenticated, 'receiver-identity-not-verified');
|
||||||
|
|
||||||
|
stage('dedicated-sendspin-connection');
|
||||||
|
if(!tabbed)await setup.getByText(/^Campaign audio connected\./).waitFor({timeout: 50000});
|
||||||
|
report.sendspinAuthenticated = wire.sendspinAuthenticated();
|
||||||
|
report.accountPairingPassed = wire.commands.some(entry => entry.command === 'sendspin/pair_web_player' && entry.reply && entry.error === null);
|
||||||
|
check(report.sendspinAuthenticated && report.accountPairingPassed, 'sendspin-pairing-not-observed');
|
||||||
|
|
||||||
|
stage('scene-assignments');
|
||||||
|
const assignments = setup.locator('fieldset[data-adaptive-music="assignments"]').filter({has: gm.locator('legend', {hasText: /^Scene music$/})});
|
||||||
|
const ambient = assignments.getByLabel('Ambient playlist');
|
||||||
|
const references = await ambient.locator('option').evaluateAll(options => options.map(option => option.value).filter(value => value.startsWith('["ma",')));
|
||||||
|
report.catalogChoices = references.length;
|
||||||
|
check(references.length >= 2, 'insufficient-ma-catalog-choices');
|
||||||
|
await ambient.selectOption(references[0]);
|
||||||
|
await assignments.getByLabel('Combat playlist').selectOption(references[1]);
|
||||||
|
if(tabbed)await assignments.getByLabel('Default boss music').selectOption(references[1]);
|
||||||
|
await assignments.getByRole('button', {name: 'Save assignments', exact: true}).click();
|
||||||
|
await assignments.getByText('Assignments saved.', {exact: true}).waitFor();
|
||||||
|
report.sceneAssignmentVerified=await gm.evaluate(({sceneId,ambient})=>{
|
||||||
|
const scene=game.scenes.get(sceneId);
|
||||||
|
return scene?.active===true&&JSON.stringify(['ma',scene.getFlag('adaptive-music','music')?.ambient?.id])===ambient;
|
||||||
|
},{sceneId,ambient:references[0]});
|
||||||
|
check(report.sceneAssignmentVerified,'assignment-not-saved-to-active-scene');
|
||||||
|
|
||||||
|
stage('activate-listener-audio');
|
||||||
|
await Promise.all(players.map(async page => {
|
||||||
|
await openMenu(page, 'listen');
|
||||||
|
await page.locator('#adaptive-music-listener').getByRole('button', {name: 'Enable Audio', exact: true}).click();
|
||||||
|
}));
|
||||||
|
|
||||||
|
stage('ambient');
|
||||||
|
const start = wire.commands.length;
|
||||||
|
if(tabbed){
|
||||||
|
await setup.getByRole('button',{name:'Go to Playback'}).click();
|
||||||
|
await setup.getByRole('button',{name:'Enable automation'}).click();
|
||||||
|
await setup.getByText('Automation active',{exact:true}).waitFor({timeout:10000});
|
||||||
|
}else{
|
||||||
|
await setup.getByLabel('Enable music automation').check();
|
||||||
|
await setup.getByRole('button',{name:'Apply automation setting',exact:true}).click();
|
||||||
|
}
|
||||||
|
const ambientPlay = await command(start, 'play_media', args => args.option === 'replace');
|
||||||
|
report.ambient = await audio();
|
||||||
|
await delay(6500);
|
||||||
|
|
||||||
|
stage('actual-combat');
|
||||||
|
combatId = await fixture({action: 'combat', sceneId, fixtureName});
|
||||||
|
const interrupt = wire.commands.length;
|
||||||
|
check(await fixture({action: 'start-combat', combatId}), 'foundry-combat-did-not-start');
|
||||||
|
const combatPlay = await command(interrupt, 'play_media', args => args.option === 'replace');
|
||||||
|
check(JSON.stringify(combatPlay.args.media) !== JSON.stringify(ambientPlay.args.media), 'combat-playlist-was-not-distinct');
|
||||||
|
await delay(4500);
|
||||||
|
report.combat = await audio();
|
||||||
|
|
||||||
|
stage('ambient-restoration');
|
||||||
|
const restore = wire.commands.length;
|
||||||
|
check(await fixture({action: 'delete-combat', combatId}), 'foundry-combat-delete-not-observed');
|
||||||
|
const restored = await command(restore, 'play_media', args => args.option === 'add');
|
||||||
|
const seek = await command(restore, 'play_index');
|
||||||
|
report.ambientOrderRestored = JSON.stringify(restored.args.media) === JSON.stringify(ambientPlay.args.media);
|
||||||
|
const snapshot = wire.commands.slice(interrupt, wire.commands.indexOf(combatPlay)).findLast(entry => entry.queue?.state === 'playing')?.queue;
|
||||||
|
report.ambientRestoreOffset = {index: seek.args.index, seconds: seek.args.seek_position};
|
||||||
|
report.ambientIndexAndOffsetRestored = Boolean(snapshot && seek.args.seek_position > 0 &&
|
||||||
|
snapshot.index === seek.args.index && Math.abs(snapshot.position - seek.args.seek_position) <= 2);
|
||||||
|
await delay(4500);
|
||||||
|
report.restoredAmbient = await audio();
|
||||||
|
report.onlyDedicatedQueueWritten = wire.commands.filter(entry => writes.has(entry.command)).every(entry => entry.args?.queue_id === receiver);
|
||||||
|
check(report.ambientOrderRestored && report.ambientIndexAndOffsetRestored && report.onlyDedicatedQueueWritten, 'queue-restore-or-ownership-mismatch');
|
||||||
|
|
||||||
|
stage('listener-stop-and-resume');
|
||||||
|
const listener = players[0].locator('#adaptive-music-listener');
|
||||||
|
await listener.getByRole('button', {name: 'Stop Audio', exact: true}).click();
|
||||||
|
await until(() => safeStats(players[0]), stats => stats.bytes === 0, 'listener-stop-did-not-close-peer');
|
||||||
|
await listener.getByRole('button', {name: 'Enable Audio', exact: true}).click();
|
||||||
|
report.afterListenerResume = await audio();
|
||||||
|
|
||||||
|
stage('listener-reload');
|
||||||
|
const reloaded = players[1];
|
||||||
|
await reloaded.reload({waitUntil: 'domcontentloaded', timeout: 30000});
|
||||||
|
await reloaded.waitForFunction(id => game.ready && game.world.id === id && !game.user.isGM && game.socket?.connected,
|
||||||
|
world.id, {polling: 250, timeout: 45000});
|
||||||
|
await openMenu(reloaded, 'listen');
|
||||||
|
await reloaded.locator('#adaptive-music-listener').getByRole('button', {name: 'Enable Audio', exact: true}).click();
|
||||||
|
report.afterListenerReload = await audio();
|
||||||
|
if(tabbed){
|
||||||
|
stage('playback-tab-controls');
|
||||||
|
await setup.getByText('2 connected listeners',{exact:true}).waitFor();
|
||||||
|
await setup.locator('.adaptive-now h3').filter({hasText:/^(?!Nothing playing).+/}).waitFor();
|
||||||
|
const slider=setup.getByLabel('Campaign volume');
|
||||||
|
await slider.press('ArrowLeft');
|
||||||
|
await setup.getByRole('button',{name:'Pause',exact:true}).click();
|
||||||
|
await setup.getByRole('button',{name:'Resume',exact:true}).click();
|
||||||
|
report.afterPlaybackResume=await audio();
|
||||||
|
await setup.getByRole('button',{name:'Stop playback',exact:true}).click();
|
||||||
|
await setup.getByText('Stopped',{exact:true}).waitFor();
|
||||||
|
report.playbackTabControls=true;
|
||||||
|
}
|
||||||
|
stage('passed');
|
||||||
|
} finally {
|
||||||
|
report.maAPIAuthenticated = wire.commands.some(entry => entry.authenticated);
|
||||||
|
report.sendspinAuthenticated = wire.sendspinAuthenticated();
|
||||||
|
report.accountPairingPassed = wire.commands.some(entry => entry.command === 'sendspin/pair_web_player' && entry.reply && entry.error === null);
|
||||||
|
report.queueWrites = wire.commands.filter(entry => writes.has(entry.command)).map(({command, reply, error}) => ({command, reply: reply === true, error}));
|
||||||
|
if(report.stage!=='passed')report.playbackFailureDetails={
|
||||||
|
notifications:await gm.evaluate(()=>window.__adaptiveTestNotifications??[]).catch(()=>[]),
|
||||||
|
recentMACommands:wire.commands.slice(-20).map(({command,reply,error})=>({command,reply:reply===true,error})),
|
||||||
|
};
|
||||||
|
if (receiver) {
|
||||||
|
if(await setup.getByRole('tab',{name:'Connection',exact:true}).count())await setup.getByRole('tab',{name:'Connection',exact:true}).click().catch(()=>{});
|
||||||
|
report.gmAudioDiagnostics = await gmAudioDiagnostics(gm, setup).catch(() => null);
|
||||||
|
}
|
||||||
|
report.browserAudio = await Promise.all(pages.map(page => page.evaluate(async () => {
|
||||||
|
const diagnostic = [...document.querySelectorAll('#adaptive-music-setup [role="status"]')].map(node => node.textContent).find(text => text.includes('Decoded frames:'));
|
||||||
|
const {contexts = [], analysers = []} = window.__adaptiveMusicTestAudio ?? {};
|
||||||
|
return {
|
||||||
|
decodedFrames: diagnostic ? Number(diagnostic.match(/Decoded frames: (\d+)/)?.[1] ?? 0) : null,
|
||||||
|
signaling: window.__adaptiveMusicTestSignaling,
|
||||||
|
contexts: contexts.map(({context, destination}) => ({state: context.state, time: context.currentTime, track: destination.stream.getAudioTracks()[0]?.readyState})),
|
||||||
|
analyserRMS: analysers.map(analyser => {
|
||||||
|
const samples = new Float32Array(analyser.fftSize);
|
||||||
|
analyser.getFloatTimeDomainData(samples);
|
||||||
|
return Math.sqrt(samples.reduce((sum, sample) => sum + sample ** 2, 0) / samples.length);
|
||||||
|
}),
|
||||||
|
browsers: await Promise.all((window.__adaptiveMusicTestPeers ?? []).map(async peer => {
|
||||||
|
const stats = peer.connectionState === 'connected' ? [...(await peer.getStats()).values()] : [];
|
||||||
|
return {connection: peer.connectionState, ice: peer.iceConnectionState, signaling: peer.signalingState,
|
||||||
|
outgoingEnergy: stats.find(row => row.type === 'media-source' && row.kind === 'audio')?.totalAudioEnergy};
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}).catch(() => null)));
|
||||||
|
if (!report.upstreamError) {
|
||||||
|
const lastError = wire.commands.findLast(entry => entry.reply && entry.error !== null);
|
||||||
|
if (lastError) report.upstreamError = {command: lastError.command, code: lastError.error};
|
||||||
|
}
|
||||||
|
if (baseline) {
|
||||||
|
try {
|
||||||
|
if (report.stage === 'passed') await gm.evaluate(moduleId => game.modules.get(moduleId).api.setOverrides([{id: 'integration-cleanup', playlist: null}]), moduleId);
|
||||||
|
} finally {
|
||||||
|
report.temporaryWorldChangesRestored = await fixture({action: 'cleanup', sceneId, combatId, baseline}).catch(() => false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,271 @@
|
|||||||
|
// Dedicated-only authorized real MA experiment. No Foundry install/config changes.
|
||||||
|
import {readFile,writeFile,mkdtemp} from 'node:fs/promises';
|
||||||
|
import {resolve} from 'node:path';
|
||||||
|
const {firefox,chromium}=await import(process.env.AM_PLAYWRIGHT_MODULE??'playwright');
|
||||||
|
import {loadMAToken} from '../gateway/private-config.mjs';
|
||||||
|
const root=resolve(import.meta.dirname,'..'),config=JSON.parse(await readFile('.local/live-environment.json','utf8')),token=await loadMAToken('.local');
|
||||||
|
const fresh=process.argv.includes('--fresh');
|
||||||
|
const useChromium=process.argv.includes('--chromium');
|
||||||
|
const reconcile=process.argv.includes('--reconcile-empty');
|
||||||
|
const inspectOnly=process.argv.includes('--inspect');
|
||||||
|
const recovery=process.argv.includes('--recovery');
|
||||||
|
const selection=process.argv.find(arg=>arg.startsWith('--select='))?.slice(9).split(',').map(Number)??[0,1];
|
||||||
|
if(selection.length!==2||new Set(selection).size!==2||selection.some(index=>!Number.isSafeInteger(index)||index<0)||fresh&&(reconcile||inspectOnly||recovery)||[reconcile,inspectOnly,recovery].filter(Boolean).length>1)throw Error('invalid test mode or playlist selection');
|
||||||
|
const savedDir=process.argv.find(arg=>arg.startsWith('--receiver='))?.slice(11)??'.local';
|
||||||
|
if(!/^\.local(?:\/live-receiver-fresh-[A-Za-z0-9]+)?$/.test(savedDir))throw Error('invalid receiver directory');
|
||||||
|
const artifactDir=await mkdtemp(fresh?'.local/live-receiver-fresh-':'.local/live-receiver-run-');
|
||||||
|
const identityPath=resolve(fresh?artifactDir:savedDir,'integration-receiver.json');
|
||||||
|
const identity=fresh?{name:'Adaptive Music integration '+crypto.randomUUID().slice(0,8),storage:{}}:JSON.parse(await readFile(identityPath,'utf8'));
|
||||||
|
if(!/^Adaptive Music integration [A-Za-z0-9-]+$/.test(identity.name)||!fresh&&(!identity.id||!identity.storage?.['sendspin-identity-sk']))throw Error('recorded dedicated integration receiver required');
|
||||||
|
const save=(name,value)=>writeFile(resolve(artifactDir,name),JSON.stringify(value,null,2)+'\n',{mode:0o600});
|
||||||
|
const browser=await (useChromium?chromium:firefox).launch({headless:true,...(useChromium?{args:['--no-sandbox']}: {})});
|
||||||
|
const context=await browser.newContext();
|
||||||
|
const page=await context.newPage();
|
||||||
|
await context.route(config.foundry+'/adaptive-music-development/**',async route=>{
|
||||||
|
const relative=new URL(route.request().url()).pathname.slice('/adaptive-music-development/'.length);
|
||||||
|
if(!/^(src|vendor)\/[a-z0-9/.-]+\.mjs$/i.test(relative)||relative.split('/').includes('..'))return route.abort();
|
||||||
|
try{await route.fulfill({contentType:'text/javascript',body:await readFile(resolve(root,relative))});}catch{await route.abort();}
|
||||||
|
});
|
||||||
|
const listeners=[],signalPages=[page],relayCounts={gm:0,listener:0,failures:0};
|
||||||
|
await context.exposeBinding('adaptiveSignal',async(source,frame)=>{relayCounts[frame.from]=(relayCounts[frame.from]??0)+1;try{await Promise.all(signalPages.filter(p=>p!==source.page&&!p.isClosed()).map(p=>p.evaluate(f=>window.receiveAdaptiveSignal?.(f),frame)));}catch{relayCounts.failures++;}});
|
||||||
|
await page.exposeBinding('sampleListeners',async()=>Promise.all(listeners.map(p=>p.evaluate(()=>window.listenerMetrics()))));
|
||||||
|
const report={at:new Date().toISOString(),scope:'real MA dedicated receiver from deployed Foundry origin; local source overlay and test-runner signaling',browser:useChromium?'Chromium':'Firefox',browserVersion:browser.version(),fresh,selection};
|
||||||
|
const mountHost=async(initialIdentity,recoverFromVault=false)=>{
|
||||||
|
await page.evaluate(async({base,token,identity,recoverFromVault})=>{
|
||||||
|
const {GMAudioHost}=await import('/adaptive-music-development/src/audio/gm-host.mjs');
|
||||||
|
const {ReceiverVault}=await import('/adaptive-music-development/src/foundry/receiver-vault.mjs');
|
||||||
|
const {MAReadClient}=await import('/adaptive-music-development/src/providers/ma/client.mjs');
|
||||||
|
const campaign='integration-test',scope={campaign,userId:'integration-gm',maUrl:base},vault=new ReceiverVault();
|
||||||
|
const remembered=recoverFromVault?await vault.load(scope):null;
|
||||||
|
if(recoverFromVault&&(!remembered||Object.hasOwn(remembered,'token')))throw Error('receiver-vault');
|
||||||
|
const trace=[],apiSockets=[],sendspinSockets=[];
|
||||||
|
const observe=new Set(['auth','sendspin/pair_web_player','providers','players/get','player_queues/get','player_queues/get_active_queue','music/playlists/library_items','music/playlists/get','music/playlists/playlist_tracks','music/tracks/get','player_queues/play_media','player_queues/play_index','player_queues/stop','player_queues/clear','player_queues/repeat']);
|
||||||
|
const createSocket=url=>{
|
||||||
|
const socket=new WebSocket(url);
|
||||||
|
if(new URL(url).pathname!=='/ws'){sendspinSockets.push(socket);return socket;}
|
||||||
|
const session=apiSockets.push(socket),pending=new Map(),send=socket.send.bind(socket);
|
||||||
|
socket.send=value=>{
|
||||||
|
const {message_id,command,args}=JSON.parse(value);
|
||||||
|
if(observe.has(command)){
|
||||||
|
const entry={session,command,...(!['auth','sendspin/pair_web_player'].includes(command)&&{args})};
|
||||||
|
trace.push(entry);pending.set(message_id,entry);
|
||||||
|
}
|
||||||
|
send(value);
|
||||||
|
};
|
||||||
|
socket.addEventListener('message',event=>{
|
||||||
|
const {message_id,result,error_code,details,partial}=JSON.parse(event.data);
|
||||||
|
const entry=pending.get(message_id);if(!entry)return;
|
||||||
|
entry.errorCode=error_code??null;
|
||||||
|
if(error_code===2)entry.mediaNotFound=details==='The requested media item could not be found.';
|
||||||
|
if(entry.command==='auth')entry.authenticated=result?.authenticated===true;
|
||||||
|
if(entry.command==='providers'&&Array.isArray(result))entry.providers=result.map(p=>({instance:p.instance_id,domain:p.domain,available:p.available}));
|
||||||
|
if(entry.command==='players/get'&&result)entry.player={id:result.player_id,provider:result.provider,enabled:result.enabled,available:result.available,activeGroup:result.active_group,syncedTo:result.synced_to};
|
||||||
|
if(entry.command.startsWith('player_queues/get')&&result)entry.queue={id:result.queue_id,state:result.state,items:result.items,active:result.active,available:result.available};
|
||||||
|
if(['music/playlists/library_items','music/playlists/playlist_tracks','music/tracks/get'].includes(entry.command)&&result){
|
||||||
|
const items=Array.isArray(result)?result:[result];
|
||||||
|
(entry.result??=[]).push(...items.map(item=>({id:item.item_id,provider:item.provider,available:item.available,mappings:item.provider_mappings})));
|
||||||
|
}
|
||||||
|
if(!partial)pending.delete(message_id);
|
||||||
|
});
|
||||||
|
return socket;
|
||||||
|
};
|
||||||
|
let losses=0;
|
||||||
|
const host=new GMAudioHost({authority:()=>true,createSocket,onDisconnect:()=>{losses++;}});
|
||||||
|
const profile=await host.prepare({maUrl:base,token,campaign,targetName:remembered?.targetName??identity.name,identityStorage:remembered?.identityStorage??identity.storage,catalogKey:remembered?.catalogKey,allowCatalogPlayback:true});
|
||||||
|
if(identity.id&&profile.target!==identity.id)throw Error('receiver-identity-changed');
|
||||||
|
await vault.save(scope,profile);
|
||||||
|
const request=(command,args)=>new Promise((resolve,reject)=>{
|
||||||
|
const socket=apiSockets.at(-1),id=crypto.randomUUID();
|
||||||
|
if(socket.readyState!==WebSocket.OPEN){reject(Error('diagnostic-disconnected'));return;}
|
||||||
|
const finish=()=>{clearTimeout(timer);socket.removeEventListener('message',reply);};
|
||||||
|
const timer=setTimeout(()=>{finish();reject(Error('diagnostic-timeout'));},10000);
|
||||||
|
const reply=event=>{const msg=JSON.parse(event.data);if(msg.message_id!==id)return;finish();if(msg.error_code!==undefined)reject(Object.assign(Error('diagnostic-rejected'),{upstreamCode:msg.error_code}));else resolve(msg.result);};
|
||||||
|
socket.addEventListener('message',reply);socket.send(JSON.stringify({command,args,message_id:id}));
|
||||||
|
});
|
||||||
|
const verifiedClient=()=>new MAReadClient({baseUrl:base,token,target:profile.target,expectedName:profile.targetName,expectedProvider:profile.expectedProvider,approvedProviders:profile.approvedProviders,fetchImpl:async(_url,options)=>{const {command,args}=JSON.parse(options.body);return Response.json((await request(command,args))??null);}});
|
||||||
|
window.pipeline={host,profile,trace,request,verifiedClient,losses:()=>losses,disconnectSendspin:()=>sendspinSockets.at(-1).close(),reopened:!!remembered};
|
||||||
|
document.querySelector('#adaptive-integration-start')?.remove();
|
||||||
|
const button=document.createElement('button');button.id='adaptive-integration-start';button.textContent='Start dedicated integration receiver';
|
||||||
|
button.onclick=()=>{window.pipeline.started=host.start(profile).then(async result=>{await vault.save(scope,profile);return {ok:true,attached:result.attachedExistingQueue};}).catch(e=>({ok:false,error:e.code??'unavailable'}));};document.body.append(button);
|
||||||
|
},{base:config.ma,token,identity:initialIdentity,recoverFromVault});
|
||||||
|
if(fresh)await writeFile(identityPath,JSON.stringify(await knownIdentity(),null,2)+'\n',{mode:0o600});
|
||||||
|
await page.locator('#adaptive-integration-start').click();
|
||||||
|
return page.evaluate(()=>window.pipeline.started);
|
||||||
|
};
|
||||||
|
const knownIdentity=()=>page.evaluate(()=>({storage:window.pipeline.profile.identityStorage,name:window.pipeline.profile.targetName,id:window.pipeline.profile.target}));
|
||||||
|
const catalogReferences=()=>page.evaluate(()=>window.pipeline.host.catalog.map(({id,kind})=>({id,kind})));
|
||||||
|
const snapshot=()=>page.evaluate(async()=>{
|
||||||
|
const {host,profile}=window.pipeline;
|
||||||
|
return (await host.snapshot({campaign:profile.campaign,session:host.session,generation:1,check(){}})).value;
|
||||||
|
});
|
||||||
|
const queueSummary=value=>({state:value.state,items:value.items.length,index:value.index,position:value.position,repeat:value.repeat});
|
||||||
|
const empty=value=>value.state==='idle'&&value.items.length===0&&value.index===null&&value.position===0&&value.repeat==='off';
|
||||||
|
const noRecoveryWrites=(from=0)=>page.evaluate(from=>window.pipeline.trace.slice(from).every(entry=>!/^player_queues\/(play_media|play_index|stop|clear|repeat)$/.test(entry.command)),from);
|
||||||
|
const clearIdle=()=>page.evaluate(async()=>{
|
||||||
|
const {verifiedClient,host,profile}=window.pipeline,client=verifiedClient(),session=host.session;
|
||||||
|
const ctx={check(){if(!host.connected||host.session!==session)throw Error('receiver-session-changed');}};
|
||||||
|
await client.verifyTarget();
|
||||||
|
const existing=await client.queueState();
|
||||||
|
if(existing.state!=='idle'||existing.repeat_mode!=='off'||existing.shuffle_enabled!==false)throw Error('test-queue-not-idle');
|
||||||
|
if(existing.items){
|
||||||
|
await client.mutate('clear',{},ctx);
|
||||||
|
// MA debounces its queue cache for five seconds and cancels the save on receiver removal.
|
||||||
|
await new Promise(resolve=>setTimeout(resolve,6500));
|
||||||
|
}
|
||||||
|
return (await host.snapshot({...ctx,campaign:profile.campaign,session,generation:10})).value;
|
||||||
|
});
|
||||||
|
try{
|
||||||
|
await page.goto(config.foundry,{waitUntil:'domcontentloaded'});
|
||||||
|
report.host=await mountHost(identity);
|
||||||
|
const draft=await knownIdentity();
|
||||||
|
if(report.host.ok||fresh)await writeFile(identityPath,JSON.stringify(draft,null,2)+'\n',{mode:0o600});
|
||||||
|
if(report.host.ok){
|
||||||
|
const refs=await catalogReferences();
|
||||||
|
await save('catalog-references.json',refs);
|
||||||
|
const raw=await page.evaluate(async()=>{const client=window.pipeline.verifiedClient();await client.verifyTarget();return client.queueState();});
|
||||||
|
report.queueBefore={state:raw.state,items:raw.items,index:raw.current_index,repeat:raw.repeat_mode};
|
||||||
|
if(!reconcile&&!inspectOnly){const original=await snapshot();await save('queue-before.json',original);}
|
||||||
|
if(reconcile){
|
||||||
|
const value=await clearIdle();
|
||||||
|
report.queueAfter=queueSummary(value);
|
||||||
|
report.reconciled=empty(value);
|
||||||
|
}
|
||||||
|
if(recovery){
|
||||||
|
if(!empty(await snapshot()))throw Error('test-queue-not-empty');
|
||||||
|
const baseline=await page.evaluate(async selected=>{
|
||||||
|
const {host,profile}=window.pipeline;
|
||||||
|
const choices=[];
|
||||||
|
for(const item of host.catalog.filter(item=>item.kind==='playlist')){
|
||||||
|
try{const ref={provider:'ma',id:item.id}; await host.resolve(ref,{campaign:profile.campaign,session:host.session,generation:1,check(){}});choices.push(ref);}catch{}
|
||||||
|
}
|
||||||
|
if(!choices[selected])throw Error('selected-static-playlist-unavailable');
|
||||||
|
const ctx={campaign:profile.campaign,session:host.session,generation:2,check(){}};
|
||||||
|
await host.apply(await host.resolve(choices[selected],ctx),ctx);
|
||||||
|
await host.stopOwned({...ctx,generation:3});
|
||||||
|
await new Promise(resolve=>setTimeout(resolve,6500));
|
||||||
|
return host.snapshot({...ctx,generation:4});
|
||||||
|
},selection[0]);
|
||||||
|
report.recovery={};
|
||||||
|
await save('queued-before-recovery.json',baseline.value);
|
||||||
|
const sameQueue=value=>value.state==='idle'&&value.repeat===baseline.value.repeat&&JSON.stringify(value.items)===JSON.stringify(baseline.value.items)&&value.index===baseline.value.index;
|
||||||
|
try{
|
||||||
|
await page.evaluate(()=>{
|
||||||
|
const {host,disconnectSendspin}=window.pipeline;
|
||||||
|
window.previousTrack=host.stream.getAudioTracks()[0];disconnectSendspin();
|
||||||
|
});
|
||||||
|
await page.waitForFunction(()=>window.pipeline.losses()===1&&!window.pipeline.host.connected&&window.previousTrack.readyState==='ended');
|
||||||
|
report.recovery.transportLossDetected=true;
|
||||||
|
const traceBeforeReconnect=await page.evaluate(()=>window.pipeline.trace.length);
|
||||||
|
await page.locator('#adaptive-integration-start').click();
|
||||||
|
const afterLoss=await page.evaluate(()=>window.pipeline.started);
|
||||||
|
report.recovery.reconnectedAfterLoss=afterLoss.ok&&afterLoss.attached&&sameQueue(await snapshot())&&await noRecoveryWrites(traceBeforeReconnect);
|
||||||
|
await save('wire-after-loss.json',await page.evaluate(()=>window.pipeline.trace));
|
||||||
|
await page.reload({waitUntil:'domcontentloaded'});
|
||||||
|
const afterReload=await mountHost({id:draft.id},true);
|
||||||
|
if(!afterReload.ok)throw Error('reload-reconnect-failed');
|
||||||
|
report.recovery.reconnectedAfterReload=afterReload.attached&&sameQueue(await snapshot())&&await noRecoveryWrites()&&JSON.stringify(refs)===JSON.stringify(await catalogReferences());
|
||||||
|
report.recovery.sameReceiver=(await knownIdentity()).id===draft.id;
|
||||||
|
report.recovery.rememberedIdentityWithoutToken=await page.evaluate(()=>window.pipeline.reopened);
|
||||||
|
report.recovery.oldSnapshotRejected=await page.evaluate(async old=>{
|
||||||
|
const {host,profile}=window.pipeline;
|
||||||
|
try{await host.restore(old,{campaign:profile.campaign,session:host.session,generation:2,check(){}});return false;}
|
||||||
|
catch(error){return error.code==='stale';}
|
||||||
|
},baseline);
|
||||||
|
}finally{
|
||||||
|
const value=await clearIdle();report.queueAfter=queueSummary(value);report.recovery.emptyBaselineRestored=empty(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if(inspectOnly){
|
||||||
|
report.inspected=await page.evaluate(async()=>{
|
||||||
|
const {host,profile,trace,request}=window.pipeline;
|
||||||
|
const ctx={campaign:profile.campaign,session:host.session,generation:1,check(){}};
|
||||||
|
const entries=[];
|
||||||
|
for(const choice of host.catalog.filter(item=>item.kind==='playlist')){
|
||||||
|
const start=trace.length;
|
||||||
|
try{await host.resolve({provider:'ma',id:choice.id},ctx);}catch{continue;}
|
||||||
|
const listed=trace.slice(start).find(entry=>entry.command==='music/playlists/playlist_tracks');
|
||||||
|
const tracks=[];
|
||||||
|
for(const item of (listed?.result??[]).slice(0,8)){
|
||||||
|
const mapping=item.mappings?.find(value=>value.available===true&&profile.approvedProviders.includes(value.provider_instance));
|
||||||
|
if(!mapping)continue;
|
||||||
|
const args={item_id:mapping.item_id,provider_instance_id_or_domain:mapping.provider_instance,allow_update_metadata:false};
|
||||||
|
let status;try{const track=await request('music/tracks/get',args);status=track?.item_id?'resolved':'unknown';}catch(error){status=error.upstreamCode??'lookup-failed';}
|
||||||
|
tracks.push(status);
|
||||||
|
}
|
||||||
|
entries.push({reference:choice.id,tracks});
|
||||||
|
}
|
||||||
|
window.comparedCatalog=entries;
|
||||||
|
return {candidates:entries.length,trackLookups:entries.map(entry=>entry.tracks)};
|
||||||
|
});
|
||||||
|
await save('compared-catalog.json',await page.evaluate(()=>window.comparedCatalog));
|
||||||
|
}
|
||||||
|
if(!reconcile&&!inspectOnly&&!recovery){
|
||||||
|
await page.evaluate(async()=>{
|
||||||
|
const {PeerAudio}=await import('/adaptive-music-development/src/audio/peer-audio.mjs');const handlers=new Map();
|
||||||
|
const socket={on:(event,fn)=>handlers.set(event,fn),off:event=>handlers.delete(event),emit:(event,frame)=>window.adaptiveSignal(frame)};
|
||||||
|
window.receiveAdaptiveSignal=frame=>handlers.get('module.adaptive-music')?.(frame);
|
||||||
|
window.integrationPeers=new PeerAudio({socket,userId:'integration-gm',isGM:()=>true,isAuthorizedUser:id=>['integration-listener-0','integration-listener-1'].includes(id)});window.integrationPeers.setSource(window.pipeline.host.stream);
|
||||||
|
});
|
||||||
|
for(let index=0;index<2;index++){
|
||||||
|
const listener=await context.newPage();listeners.push(listener);signalPages.push(listener);await listener.goto(config.foundry,{waitUntil:'domcontentloaded'});
|
||||||
|
const userId='integration-listener-'+index,invite=await page.evaluate(id=>window.integrationPeers.invite(id),userId);
|
||||||
|
await listener.evaluate(async({invite,userId})=>{
|
||||||
|
const {PeerAudio}=await import('/adaptive-music-development/src/audio/peer-audio.mjs');const handlers=new Map();let analyser,audioContext,source,maximum=0,current=0,measurements=0;
|
||||||
|
const socket={on:(event,fn)=>handlers.set(event,fn),off:event=>handlers.delete(event),emit:(event,frame)=>window.adaptiveSignal(frame)};window.receiveAdaptiveSignal=frame=>handlers.get('module.adaptive-music')?.(frame);
|
||||||
|
const peer=new PeerAudio({socket,userId,isGM:()=>false,onStream:stream=>{const element=document.createElement('audio');element.autoplay=true;element.muted=true;element.srcObject=stream;document.body.append(element);element.play().catch(()=>{});source=audioContext.createMediaStreamSource(stream);analyser=audioContext.createAnalyser();source.connect(analyser);analyser.connect(audioContext.destination);}});
|
||||||
|
const button=document.createElement('button');button.id='adaptive-integration-listen';button.textContent='Enable Audio';button.onclick=()=>{audioContext=new AudioContext();audioContext.resume();window.listenerStarted=peer.listen(invite);};document.body.append(button);
|
||||||
|
const timer=setInterval(()=>{if(!analyser)return;const data=new Float32Array(analyser.fftSize);analyser.getFloatTimeDomainData(data);current=Math.sqrt(data.reduce((sum,v)=>sum+v*v,0)/data.length);maximum=Math.max(maximum,current);measurements++;},100);
|
||||||
|
window.listenerMetrics=()=>{const result={currentRMS:current,maximumRMS:maximum,measurements,peers:peer.diagnostics().peers};maximum=0;return result;};window.closeIntegrationListener=()=>{clearInterval(timer);peer.close();source?.disconnect();audioContext?.close();};
|
||||||
|
},{invite,userId});await listener.locator('#adaptive-integration-listen').click();await listener.evaluate(()=>window.listenerStarted);
|
||||||
|
}
|
||||||
|
report.pipeline=await page.evaluate(async selection=>{
|
||||||
|
const {host,profile}=window.pipeline;const {MusicController}=await import('/adaptive-music-development/src/core/controller.mjs');
|
||||||
|
const choices=host.catalog.filter(c=>c.kind==='playlist');const usable=[];let generation=1;
|
||||||
|
const ctx=()=>({campaign:profile.campaign,session:host.session,generation:generation++,check(){}});
|
||||||
|
const original=await host.snapshot(ctx());let controller,phase='resolve catalog';
|
||||||
|
const out={catalogCount:choices.length,candidates:[],restored:false};
|
||||||
|
try{
|
||||||
|
for(const choice of choices){try{const ref={provider:'ma',id:choice.id};await host.resolve(ref,ctx());usable.push(ref);out.candidates.push('usable');}catch(e){out.candidates.push(e.code??'unavailable');}}
|
||||||
|
if(selection.some(index=>!usable[index]))throw {code:'selected-static-playlist-unavailable'};
|
||||||
|
controller=new MusicController({campaign:profile.campaign,session:host.session,providers:{ma:host},authority:()=>true});controller.generation=generation;
|
||||||
|
const base={scene:{id:'integration-scene',playlist:usable[selection[0]]},combats:[]};
|
||||||
|
phase='ambient';await controller.update(base);await new Promise(r=>setTimeout(r,10000));out.gmPeerDiagnostics=window.integrationPeers.diagnostics();out.ambient=host.status;out.ambientListeners=await window.sampleListeners();
|
||||||
|
phase='playback controls';
|
||||||
|
generation=Math.max(generation,controller.generation)+1;await host.control('pause',null,ctx());let paused;const pauseDeadline=Date.now()+4000;do{await new Promise(r=>setTimeout(r,200));paused=await host.snapshot(ctx());}while(paused.value.state!=='paused'&&Date.now()<pauseDeadline);await host.control('seek',3,ctx());const sought=await host.snapshot(ctx());await host.control('resume',null,ctx());await new Promise(r=>setTimeout(r,1000));out.controls={paused:paused.value.state==='paused',seekPosition:sought.value.position,resumed:(await host.snapshot(ctx())).value.state==='playing'};host.setVolume(35);const volumeSet=host.status.volume===35;host.setVolume(100);out.controls.volume=volumeSet&&host.status.volume===100;const ambient=await host.snapshot(ctx());controller.generation=generation;
|
||||||
|
phase='combat';await controller.update({...base,combats:[{id:'integration-combat',sceneId:'integration-scene',active:true,started:true,playlist:usable[selection[1]],bosses:[]}]});
|
||||||
|
await new Promise(r=>setTimeout(r,8000));out.combat=host.status;out.combatListeners=await window.sampleListeners();
|
||||||
|
phase='restore ambient';await controller.update(base);generation=Math.max(generation,controller.generation)+1;const restoredAmbient=await host.snapshot(ctx());out.ambientOrderRestored=JSON.stringify(ambient.value.items)===JSON.stringify(restoredAmbient.value.items);out.ambientIndexRestored=ambient.value.index===restoredAmbient.value.index;out.ambientPositionBefore=ambient.value.position;out.ambientPositionRestored=restoredAmbient.value.position;out.ambientStateRestored=restoredAmbient.value.state;await new Promise(r=>setTimeout(r,6000));out.returnedAmbient=host.status;out.restoredListeners=await window.sampleListeners();
|
||||||
|
out.transitionsCompleted=true;
|
||||||
|
}catch(e){out.phase=phase;out.error=e.code??'unavailable';out.command=e.command;out.upstreamCode=e.upstreamCode;out.translationKey=e.translationKey;out.failureStatus=host.status;}
|
||||||
|
finally{
|
||||||
|
generation=Math.max(generation,controller?.generation??0)+1;
|
||||||
|
if (out.error === 'uncertain') {
|
||||||
|
out.restoreSkipped = 'queue reconciliation required';
|
||||||
|
} else {
|
||||||
|
try{await host.restore(original,ctx());await new Promise(r=>setTimeout(r,6500));const after=await host.snapshot(ctx());out.restored=JSON.stringify([after.value.state,after.value.items,after.value.index,after.value.repeat,after.value.position])===JSON.stringify([original.value.state,original.value.items,original.value.index,original.value.repeat,original.value.position]);}catch(e){out.restoreError=e.code??'unavailable';}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
},selection);
|
||||||
|
}
|
||||||
|
await save('wire.json',await page.evaluate(()=>window.pipeline.trace));
|
||||||
|
report.relay=relayCounts;report.gmPeers=await page.evaluate(()=>window.integrationPeers?.diagnostics());report.mediaStats=await page.evaluate(()=>window.integrationPeers?.stats());
|
||||||
|
for(const listener of listeners)await listener.evaluate(()=>window.closeIntegrationListener());
|
||||||
|
const retained=await page.evaluate(()=>({storage:window.pipeline.profile.identityStorage,name:window.pipeline.profile.targetName,id:window.pipeline.profile.target}));await writeFile(identityPath,JSON.stringify(retained,null,2),{mode:0o600});
|
||||||
|
await page.evaluate(()=>{window.integrationPeers?.close();return window.pipeline.host.close();});
|
||||||
|
}
|
||||||
|
}catch(error){report.error=/^[a-z][a-z-]{1,60}$/.test(error.message)?error.message:'browser-experiment-failed';}
|
||||||
|
finally{
|
||||||
|
const trace=await page.evaluate(()=>window.pipeline?.trace).catch(()=>null);
|
||||||
|
if(trace)await save('wire.json',trace);
|
||||||
|
await browser.close();
|
||||||
|
const pipeline=report.pipeline;
|
||||||
|
const listenerGroups=[pipeline?.ambientListeners,pipeline?.combatListeners,pipeline?.restoredListeners];
|
||||||
|
const listenerAudio=listenerGroups.every(group=>group?.length===2&&group.every(listener=>listener.maximumRMS>0.001&&listener.peers[0]?.connection==='connected'));
|
||||||
|
const playbackPassed=pipeline?.restored&&pipeline.transitionsCompleted&&pipeline.ambientOrderRestored&&pipeline.ambientIndexRestored&&pipeline.ambientStateRestored==='playing'&&pipeline.ambientPositionBefore===pipeline.ambientPositionRestored&&pipeline.controls?.paused&&pipeline.controls?.resumed&&pipeline.controls?.seekPosition===3&&pipeline.controls?.volume&&listenerAudio;
|
||||||
|
const recoveryPassed=Object.keys(report.recovery??{}).length===7&&Object.values(report.recovery).every(Boolean);
|
||||||
|
report.passed=!!(report.host?.ok&&(reconcile?report.reconciled:inspectOnly?report.inspected?.candidates>0:recovery?recoveryPassed:playbackPassed));
|
||||||
|
if(!report.passed)process.exitCode=1;
|
||||||
|
await save('report.json',report);
|
||||||
|
console.log(JSON.stringify({...report,artifactDir},null,2));
|
||||||
|
}
|
||||||
+14
-2
@@ -136,17 +136,29 @@ def build_release(repository=DEFAULT_REPOSITORY,version=None,output=None):
|
|||||||
if output.is_relative_to(ROOT) and not output.is_relative_to(ROOT/'dist'):raise ValueError('in-repository output must be under ignored dist/')
|
if output.is_relative_to(ROOT) and not output.is_relative_to(ROOT/'dist'):raise ValueError('in-repository output must be under ignored dist/')
|
||||||
output.mkdir(parents=True,exist_ok=True)
|
output.mkdir(parents=True,exist_ok=True)
|
||||||
allowed={'adaptive-music.zip','module.json','adaptive-music-source.zip','README.md','INSTALL.md','CHANGELOG.md','ARCHITECTURE.md','SECURITY.md','TESTING.md','PROGRESS.md','LICENSE','THIRD-PARTY-NOTICES','release.json','SHA256SUMS',f'adaptive-music-release-v{version}.zip',f'adaptive-music-release-v{version}.zip.sha256'}
|
allowed={'adaptive-music.zip','module.json','adaptive-music-source.zip','README.md','INSTALL.md','CHANGELOG.md','ARCHITECTURE.md','SECURITY.md','TESTING.md','PROGRESS.md','LICENSE','THIRD-PARTY-NOTICES','release.json','SHA256SUMS',f'adaptive-music-release-v{version}.zip',f'adaptive-music-release-v{version}.zip.sha256'}
|
||||||
|
evidence_name=f'evidence/v{version}-live.json'
|
||||||
|
if (ROOT/evidence_name).is_file():allowed.add(evidence_name)
|
||||||
allowed.update(str(p.relative_to(ROOT)) for p in (ROOT/'licenses').rglob('*') if p.is_file())
|
allowed.update(str(p.relative_to(ROOT)) for p in (ROOT/'licenses').rglob('*') if p.is_file())
|
||||||
for file in output.rglob('*'):
|
for file in output.rglob('*'):
|
||||||
if file.is_symlink() or file.is_file() and str(file.relative_to(output)) not in allowed:raise ValueError('unmanaged file in release output')
|
if file.is_symlink() or file.is_file() and str(file.relative_to(output)) not in allowed:raise ValueError('unmanaged file in release output')
|
||||||
write_zip(output/'adaptive-music.zip',module_entries(manifest));validate_package(output/'adaptive-music.zip',manifest)
|
write_zip(output/'adaptive-music.zip',module_entries(manifest));validate_package(output/'adaptive-music.zip',manifest)
|
||||||
(output/'module.json').write_text(json.dumps(manifest,indent=2)+'\n')
|
(output/'module.json').write_text(json.dumps(manifest,indent=2)+'\n')
|
||||||
write_zip(output/'adaptive-music-source.zip',source_entries(manifest))
|
source=source_entries(manifest)
|
||||||
|
write_zip(output/'adaptive-music-source.zip',source)
|
||||||
|
evidence=source.get(f'adaptive-music-source/{evidence_name}')
|
||||||
|
if evidence is not None:
|
||||||
|
(output/evidence_name).parent.mkdir(parents=True,exist_ok=True)
|
||||||
|
(output/evidence_name).write_bytes(evidence)
|
||||||
for name in ('README.md','INSTALL.md','CHANGELOG.md','ARCHITECTURE.md','SECURITY.md','TESTING.md','PROGRESS.md','LICENSE','THIRD-PARTY-NOTICES'):(output/name).write_bytes((ROOT/name).read_bytes())
|
for name in ('README.md','INSTALL.md','CHANGELOG.md','ARCHITECTURE.md','SECURITY.md','TESTING.md','PROGRESS.md','LICENSE','THIRD-PARTY-NOTICES'):(output/name).write_bytes((ROOT/name).read_bytes())
|
||||||
for path in (ROOT/'licenses').rglob('*'):
|
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())
|
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'],
|
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}
|
||||||
|
acceptance=json.loads(evidence) if evidence is not None else {}
|
||||||
|
metadata['publicationReady']=acceptance.get('publicationReady') is True
|
||||||
|
metadata['maCoreFlowDemonstrated']=acceptance.get('completedCoreRunPassed') is True
|
||||||
|
metadata['macPrivateRouteVerified']=acceptance.get('macPrivateRouteVerified') is True
|
||||||
|
metadata['acceptanceStatus']='staged; operator Mac and logged-in-world acceptance required' if not metadata['publicationReady'] else 'operator acceptance recorded'
|
||||||
(output/'release.json').write_text(json.dumps(metadata,indent=2)+'\n')
|
(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-')}
|
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())))
|
(output/'SHA256SUMS').write_text(''.join(f'{hashlib.sha256(data).hexdigest()} {name}\n' for name,data in sorted(files.items())))
|
||||||
|
|||||||
@@ -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;}
|
||||||
|
}
|
||||||
+126
-46
@@ -2,89 +2,169 @@ import {MusicError} from '../core/controller.mjs';
|
|||||||
import {MAReadClient} from '../providers/ma/client.mjs';
|
import {MAReadClient} from '../providers/ma/client.mjs';
|
||||||
import {MAPlaybackProvider} from '../providers/ma/provider.mjs';
|
import {MAPlaybackProvider} from '../providers/ma/provider.mjs';
|
||||||
import {GMMAWebSocket} from '../providers/ma/websocket.mjs';
|
import {GMMAWebSocket} from '../providers/ma/websocket.mjs';
|
||||||
import {randomKey} from '../providers/ma/webcrypto.mjs';
|
import {hmac,randomKey} from '../providers/ma/webcrypto.mjs';
|
||||||
export function gmAccessPolicy(baseUrl,pageUrl){
|
export function gmAccessPolicy(baseUrl,pageUrl){
|
||||||
const target=new URL(baseUrl),page=new URL(pageUrl);
|
let target,page;try{target=new URL(baseUrl);page=new URL(pageUrl);}catch{throw new MusicError('address-invalid');}
|
||||||
if(target.username||target.password||target.search||target.hash||target.pathname!=='/'||!['http:','https:'].includes(target.protocol))throw new MusicError('denied');
|
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;
|
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)};}
|
function memoryStorage(values){return {getItem:k=>values[k]??null,setItem:(k,v)=>{values[k]=v;},removeItem:k=>{delete values[k];}};}
|
||||||
export class GMAudioHost{
|
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;
|
#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; #phase='idle'; #frames=0; #samples=0; #energy=0; #lastAudio=0; #attachedQueue=false; #lastError; #scheduled=0; #late=0; #ahead=0; #lastLead=0; #bufferedBytes=0; #meter;
|
||||||
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;}
|
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(){let outputRMS=0;if(this.#meter){const data=new Float32Array(this.#meter.fftSize);this.#meter.getFloatTimeDomainData(data);outputRMS=Math.sqrt(data.reduce((sum,v)=>sum+v*v,0)/data.length);}return {state:this.#live?'connected':this.#starting?'connecting':this.#status,catalog:this.#catalog.length,audioContext:this.#context?.state??'closed',catalogPlayback:this.#catalogPlayback,stage:this.#phase,decodedFrames:this.#frames,lastAudioAt:this.#lastAudio,outputRMS,rms:this.#samples?Math.sqrt(this.#energy/this.#samples):0,attachedExistingQueue:this.#attachedQueue,volume:this.#core?.volume??100,muted:this.#core?.muted??false,pauseMode:this.#client?.supportsNativePause()===false?'emulated':'native',scheduledFrames:this.#scheduled,droppedLate:this.#late,droppedAhead:this.#ahead,lastLeadSeconds:this.#lastLead,audioTime:this.#context?.currentTime,lastError:this.#lastError};}
|
||||||
get catalog(){return structuredClone(this.#catalog);}
|
get catalog(){return structuredClone(this.#catalog);}
|
||||||
get session(){return this.#session;}
|
get session(){return this.#session;}
|
||||||
get stream(){return this.#destination?.stream;}
|
get stream(){return this.#destination?.stream;}
|
||||||
get connected(){return this.#live;}
|
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.legacyId&&c.legacyId===ref.id)&&c.kind==='playlist')); }
|
||||||
async readCatalog(profile,{reconnecting=false}={}){
|
async prepare(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);
|
if(!this.#authority()||this.#live)throw new MusicError('denied');
|
||||||
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 base=gmAccessPolicy(profile.maUrl,this.pageUrl);this.#phase='API authentication';
|
||||||
this.#apiTransport?.close();this.#apiTransport=new GMMAWebSocket({baseUrl:base.origin,token:profile.token,createSocket:this.createSocket});
|
const transport=new GMMAWebSocket({baseUrl:base.origin,token:profile.token,createSocket:this.createSocket});
|
||||||
this.#client=new MAReadClient({baseUrl:base.origin,token:profile.token,target:profile.target,expectedName:profile.targetName,expectedProvider:profile.expectedProvider,approvedProviders:profile.approvedProviders,catalogKey:key,campaign:profile.namespace,syntheticSequences:profile.syntheticSequences??{},fetchImpl:this.#apiTransport.fetch});
|
try{
|
||||||
await this.#client.verifyTarget({allowUnavailable:reconnecting});this.#catalog=await this.#client.catalog();return this.catalog;
|
const response=await transport.fetch(base.origin+'/api',{method:'POST',redirect:'error',body:JSON.stringify({command:'providers',args:{provider_type:'music'}})});
|
||||||
|
const providers=await response.json();
|
||||||
|
if(!Array.isArray(providers))throw new MusicError('catalog-empty');
|
||||||
|
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 sdk=await this.loadSDK(),identityStorage=profile.identityStorage??{},identity=sdk.loadSendspinClientIdentity(memoryStorage(identityStorage));
|
||||||
|
const catalogKey=profile.catalogKey??btoa(String.fromCharCode(...new Uint8Array(await crypto.subtle.digest('SHA-256',new TextEncoder().encode('adaptive-music-catalog-v1:'+profile.campaign+':'+identityStorage['sendspin-identity-sk'])))));
|
||||||
|
this.#phase='authenticated';
|
||||||
|
return {...profile,maUrl:base.origin,identityStorage,target:identity.clientId,targetName:profile.targetName||'Adaptive Music campaign',approvedProviders,catalogKey,namespace:profile.namespace??profile.campaign,autoProvision:true,campaignOwned:true,webSocketAuthLogSafe:true};
|
||||||
|
}finally{transport.close();}
|
||||||
}
|
}
|
||||||
async start(profile){
|
async inspect(profile,{transport:existingTransport}={}){
|
||||||
|
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=existingTransport??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{if(!existingTransport)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,preserveTransport=false}={}){
|
||||||
|
if(!this.#authority()||this.#live)throw new MusicError('denied');if(profile.webSocketAuthLogSafe!==true)throw new MusicError('auth-log-review-required');const base=gmAccessPolicy(profile.maUrl,this.pageUrl);
|
||||||
|
const key=Uint8Array.from(atob(profile.catalogKey),c=>c.charCodeAt(0));if(key.length!==32||!profile.targetName)throw new MusicError('denied');
|
||||||
|
if(!preserveTransport){this.#apiTransport?.close();this.#apiTransport=new GMMAWebSocket({baseUrl:base.origin,token:profile.token,createSocket:this.createSocket});}
|
||||||
|
// The same authorized token, world and MA origin can resolve new assignments on another GM device.
|
||||||
|
const portable=profile.portableCatalog&&await hmac(new TextEncoder().encode(profile.token),'adaptive-music portable catalog\0'+JSON.stringify([base.origin,profile.namespace]));
|
||||||
|
this.#client=new MAReadClient({baseUrl:base.origin,token:profile.token,target:profile.target,expectedName:profile.targetName,expectedProvider:profile.expectedProvider,approvedProviders:profile.approvedProviders,catalogKey:portable||key,legacyCatalogKey:portable?key:undefined,campaign:profile.namespace,syntheticSequences:profile.syntheticSequences??{},fetchImpl:this.#apiTransport.fetch});
|
||||||
|
try{await this.#client.verifyTarget({allowUnavailable:reconnecting});this.#catalog=await this.#client.catalog();this.#status='catalog-ready';return this.catalog;}catch(error){await this.close();throw error;}
|
||||||
|
}
|
||||||
|
start(profile,{audioContext}={}){if(this.#starting)return Promise.reject(new MusicError('denied'));this.#starting=true;return this.#start(profile,audioContext).finally(()=>{this.#starting=false;});}
|
||||||
|
#connectionLost(epoch,stage){
|
||||||
|
if(epoch!==this.#epoch||!this.#live)return;
|
||||||
|
void this.close();
|
||||||
|
this.#status='connection-lost';this.#phase=stage;
|
||||||
|
this.onDisconnect();
|
||||||
|
}
|
||||||
|
async #start(profile,audioContext){
|
||||||
if(!this.#authority()||this.#live)throw new MusicError('denied');
|
if(!this.#authority()||this.#live)throw new MusicError('denied');
|
||||||
const base=gmAccessPolicy(profile.maUrl,this.pageUrl);
|
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.identityStorage?.['sendspin-identity-sk']||!Array.isArray(profile.approvedProviders)||!profile.catalogKey||!profile.namespace)throw new MusicError('profile-required');
|
||||||
// Unlock synchronously in the caller's gesture before SDK/network work.
|
const epoch=this.#epoch,check=()=>{if(epoch!==this.#epoch||!this.#authority())throw new MusicError('stale');};
|
||||||
this.#context=this.createContext();const unlocked=this.#context.resume();this.#destination=this.#context.createMediaStreamDestination();
|
this.#lastError=undefined;this.#attachedQueue=false;this.#context=audioContext??this.createContext();const unlocked=audioContext?null:this.#context.resume();this.#destination=this.#context.createMediaStreamDestination();this.#frames=this.#samples=this.#energy=this.#lastAudio=this.#scheduled=this.#late=this.#ahead=0;
|
||||||
try{
|
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);
|
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');
|
if(identity.clientId!==profile.target)throw new MusicError('identity-mismatch');
|
||||||
const key=Uint8Array.from(atob(profile.catalogKey),c=>c.charCodeAt(0));if(key.length!==32)throw new MusicError('denied');
|
|
||||||
if(!globalThis.navigator?.locks)throw new MusicError('unsupported');
|
if(!globalThis.navigator?.locks)throw new MusicError('unsupported');
|
||||||
const lockName='adaptive-music-'+Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',new TextEncoder().encode(base.origin+profile.target))),n=>n.toString(16).padStart(2,'0')).join('');
|
const 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;});
|
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 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')));});check();
|
||||||
await this.readCatalog(profile,{reconnecting:true});
|
this.#apiTransport?.close();this.#apiTransport=new GMMAWebSocket({baseUrl:base.origin,token:profile.token,createSocket:this.createSocket,onDisconnect:()=>this.#connectionLost(epoch,'API connection lost')});
|
||||||
const original=await this.#client.queueState({allowUnavailable:true});
|
await this.#apiTransport.connect();check();
|
||||||
if(original.items!==0||original.state!=='idle')throw new MusicError('reconcile-required');
|
this.#phase='Sendspin authentication';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:false,unpairedAccess:false,reconnect:{enabled:false}});
|
||||||
|
this.#gain=this.#context.createGain();this.#meter=this.#context.createAnalyser?.();if(this.#meter){this.#gain.connect(this.#meter);this.#meter.connect(this.#destination);this.#meter.connect(this.#context.destination);}else{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.#connectionLost(epoch,'Sendspin connection lost');
|
||||||
|
this.#core.onStreamStart=(format,isFormatUpdate)=>{if(!isFormatUpdate)this.#clear();};this.#core.onStreamClear=timestamp=>this.#clear(timestamp);this.#core.onStreamEnd=()=>this.#clear();
|
||||||
|
this.#phase='Noise handshake';await this.#core.connect();check();
|
||||||
|
if(profile.autoProvision){
|
||||||
|
this.#phase='receiver pairing';
|
||||||
|
await this.#apiTransport.fetch(base.origin+'/api',{method:'POST',redirect:'error',body:JSON.stringify({command:'sendspin/pair_web_player',args:{pairing_token:this.#core.pairingToken}})});
|
||||||
|
}
|
||||||
|
this.#phase='clock synchronization';const deadline=Date.now()+15000;
|
||||||
|
while(!this.#core.timeSyncInfo.synced&&Date.now()<deadline){check();await new Promise(resolve=>setTimeout(resolve,50));}
|
||||||
|
if(!this.#core.timeSyncInfo.synced)throw new MusicError('sendspin-sync-failed');check();
|
||||||
|
if(profile.autoProvision){this.#phase='dedicated receiver verification';Object.assign(profile,await this.inspect(profile,{transport:this.#apiTransport}));check();}
|
||||||
|
this.#phase='catalog retrieval';
|
||||||
|
await this.readCatalog(profile,{reconnecting:true,preserveTransport:true});check();
|
||||||
|
this.#phase='dedicated queue verification';
|
||||||
|
await this.#client.verifyTarget({checkRegistration:check});
|
||||||
|
const original=await this.#client.queueState();check();
|
||||||
|
this.#attachedQueue=original.items!==0||original.state!=='idle';
|
||||||
|
if(this.#attachedQueue&&!profile.campaignOwned)throw new MusicError('reconcile-required');
|
||||||
if(profile.allowSyntheticPlayback===true){
|
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);}
|
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'})));
|
this.#catalog.push(...[...this.#allowed].map(id=>({provider:'ma',id,kind:'sequence',name:'Generated '+id.slice(10)+' sequence'})));
|
||||||
}
|
}
|
||||||
let volumeState=this.#client.targetVolumeState();
|
this.#session=crypto.randomUUID();this.#catalogPlayback=profile.allowCatalogPlayback===true;this.#live=true;this.#phase='ready';
|
||||||
this.#socket=await this.#authenticatedSocket(base,profile.token,identity.clientId);
|
|
||||||
this.#core=new this.#sdk.SendspinCore({webSocket:this.#socket,storage,clientName:profile.targetName,productName:'Web Browser',codecs:['pcm'],bufferCapacity:768000,requiredLeadTimeMs:250,minBufferMs:250,useHardwareVolume:true,getExternalVolume:()=>volumeState,onVolumeCommand:(volume,muted)=>{volumeState={volume,muted};},unpairedAccess:false,reconnect:{enabled:false}});
|
|
||||||
this.#gain=this.#context.createGain();this.#gain.connect(this.#destination);
|
|
||||||
this.#core.onVolumeUpdate=()=>this.#gain.gain.setTargetAtTime(this.#core.muted?0:Math.pow(Math.min(100,Math.max(0,this.#core.volume))/100,1.5),this.#context.currentTime,0.015);
|
|
||||||
this.#core.onAudioData=chunk=>this.#schedule(chunk);
|
|
||||||
this.#core.onConnectionClose=()=>{this.#live=false;this.#clear();for(const track of this.#destination?.stream.getTracks()??[])track.stop();};
|
|
||||||
this.#core.onStreamClear=()=>this.#clear();this.#core.onStreamEnd=()=>this.#clear();
|
|
||||||
this.#session=crypto.randomUUID();this.#live=true;
|
|
||||||
this.#provider=new MAPlaybackProvider({client:this.#client,campaign:profile.campaign,session:this.#session,fence:1,snapshotKey:randomKey(),authority:()=>{if(!this.#live||!this.#authority())throw new MusicError('stale');}});
|
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};
|
return {clientIdVerified:true,catalog:this.#catalog.length,codecs:['pcm'],remoteAudio:'webrtc',audioMeasured:false,distributedFencing:false,attachedExistingQueue:this.#attachedQueue};
|
||||||
}catch(error){await this.close();throw new MusicError(error instanceof MusicError?error.code:'unavailable');}
|
}catch(error){this.#lastError={code:error instanceof MusicError?error.code:'unavailable',stage:this.#phase,command:error.command,upstreamCode:error.upstreamCode,translationKey:error.translationKey};if(epoch===this.#epoch)await this.close();throw Object.assign(new MusicError(this.#lastError.code),this.#lastError);}
|
||||||
}
|
}
|
||||||
#authenticatedSocket(base,token,clientId){
|
#authenticatedSocket(base,token,clientId){
|
||||||
const url=new URL('/sendspin',base);url.protocol=base.protocol==='https:'?'wss:':'ws:';
|
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 fail=()=>{clearTimeout(timer);socket.close();reject(new MusicError('unavailable'));};socket.onerror=fail;socket.onclose=fail;
|
let socket,opened=false,settled=false;
|
||||||
socket.onopen=()=>socket.send(JSON.stringify({type:'auth',token,client_id:clientId}));
|
const fail=code=>{if(settled)return;settled=true;clearTimeout(timer);if(socket){socket.onopen=socket.onmessage=socket.onerror=socket.onclose=null;socket.close();}reject(new MusicError(code));};
|
||||||
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();}};
|
const timer=setTimeout(()=>fail(opened?'sendspin-auth-failed':'ws-upgrade-failed'),8000);
|
||||||
|
try{socket=this.createSocket(url.href);this.#socket=socket;}catch{fail('ws-upgrade-failed');return;}
|
||||||
|
socket.binaryType='arraybuffer';
|
||||||
|
socket.onerror=()=>fail(opened?'sendspin-auth-failed':'ws-upgrade-failed');socket.onclose=()=>fail(opened?'sendspin-auth-failed':'ws-upgrade-failed');
|
||||||
|
socket.onopen=()=>{opened=true;try{socket.send(JSON.stringify({type:'auth',token,client_id:clientId}));}catch{fail('sendspin-auth-failed');}};
|
||||||
|
socket.onmessage=event=>{try{if(typeof event.data!=='string'||event.data.length>65536||JSON.parse(event.data).type!=='auth_ok')throw Error();clearTimeout(timer);settled=true;socket.onopen=socket.onerror=socket.onclose=socket.onmessage=null;resolve(socket);}catch{fail('sendspin-auth-failed');}};
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
#schedule(chunk){
|
#schedule(chunk){
|
||||||
if(!this.#live||!this.#authority()){this.#clear();return;}
|
if(!this.#live||!this.#authority()){this.#clear();return;}
|
||||||
if(!this.#core.timeSyncInfo.synced||!Array.isArray(chunk.samples)||chunk.samples.length>2||!chunk.samples.length||!Number.isFinite(chunk.sampleRate)||chunk.sampleRate<8000||chunk.sampleRate>96000)return;
|
if(!this.#core.timeSyncInfo.synced||!Array.isArray(chunk.samples)||chunk.samples.length>2||!chunk.samples.length||!Number.isFinite(chunk.sampleRate)||chunk.sampleRate<8000||chunk.sampleRate>96000)return;
|
||||||
const frames=chunk.samples[0].length;if(frames<1||frames>chunk.sampleRate/4||chunk.samples.some(c=>c.length!==frames))return;
|
const frames=chunk.samples[0].length;if(frames<1||frames>chunk.sampleRate/4||chunk.samples.some(c=>c.length!==frames))return;
|
||||||
if(chunk.generation!==this.#generation){this.#clear();this.#generation=chunk.generation;}
|
this.#frames++;this.#lastAudio=Date.now();for(const channel of chunk.samples)for(const sample of channel){this.#samples++;this.#energy+=sample*sample;}
|
||||||
const lead=(chunk.serverTimeUs-this.#core.getCurrentServerTimeUs())/1000000;
|
const lead=(chunk.serverTimeUs-this.#core.getCurrentServerTimeUs())/1000000;
|
||||||
if(!Number.isFinite(lead)||lead>2||lead+frames/chunk.sampleRate<0||this.#nodes.size>=128)return;
|
this.#lastLead=lead;if(!Number.isFinite(lead)||this.#nodes.size>=512||this.#bufferedBytes+frames*chunk.samples.length*4>2097152)return;
|
||||||
|
if(lead>6){this.#ahead++;return;}if(lead+frames/chunk.sampleRate<0){this.#late++;return;}
|
||||||
const buffer=this.#context.createBuffer(chunk.samples.length,frames,chunk.sampleRate);chunk.samples.forEach((samples,i)=>buffer.getChannelData(i).set(samples));
|
const buffer=this.#context.createBuffer(chunk.samples.length,frames,chunk.sampleRate);chunk.samples.forEach((samples,i)=>buffer.getChannelData(i).set(samples));
|
||||||
const node=this.#context.createBufferSource();node.buffer=buffer;node.connect(this.#gain);this.#gain.gain.setTargetAtTime(this.#core.muted?0:Math.pow(Math.min(100,Math.max(0,this.#core.volume))/100,1.5),this.#context.currentTime,0.015);node.onended=()=>this.#nodes.delete(node);this.#nodes.add(node);node.start(Math.max(this.#context.currentTime+0.01,this.#context.currentTime+lead));
|
const node=this.#context.createBufferSource();node.buffer=buffer;node.connect(this.#gain);this.#gain.gain.setTargetAtTime(this.#core.muted?0:Math.pow(Math.min(100,Math.max(0,this.#core.volume))/100,1.5),this.#context.currentTime,0.015);node.adaptiveBytes=frames*chunk.samples.length*4;node.adaptiveServerStart=chunk.serverTimeUs;node.adaptiveServerEnd=chunk.serverTimeUs+frames/chunk.sampleRate*1000000;node.onended=()=>{if(this.#nodes.delete(node))this.#bufferedBytes-=node.adaptiveBytes;};this.#nodes.add(node);this.#bufferedBytes+=node.adaptiveBytes;node.start(Math.max(this.#context.currentTime+0.01,this.#context.currentTime+lead));this.#scheduled++;
|
||||||
|
}
|
||||||
|
#clear(fromTimestampUs){
|
||||||
|
if(Number.isFinite(fromTimestampUs)){
|
||||||
|
const when=Math.max(this.#context.currentTime,this.#context.currentTime+(fromTimestampUs-this.#core.getCurrentServerTimeUs())/1000000);
|
||||||
|
for(const node of this.#nodes)if(node.adaptiveServerEnd>fromTimestampUs){try{node.stop(node.adaptiveServerStart>=fromTimestampUs?0:when);}catch{}}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for(const node of this.#nodes){try{node.stop();}catch{}}this.#nodes.clear();this.#bufferedBytes=0;
|
||||||
}
|
}
|
||||||
#clear(){for(const node of this.#nodes){try{node.stop();}catch{}}this.#nodes.clear();}
|
|
||||||
#ready(){if(!this.#live||!this.#authority()||!this.#provider)throw new MusicError('stale');return this.#provider;}
|
#ready(){if(!this.#live||!this.#authority()||!this.#provider)throw new MusicError('stale');return this.#provider;}
|
||||||
resolve(ref,ctx){if(!this.supports(ref))throw new MusicError('denied');return this.#ready().resolve(ref,ctx);}
|
resolve(ref,ctx){if(!this.supports(ref))throw new MusicError('denied');return this.#ready().resolve(ref,ctx);}
|
||||||
snapshot(ctx){return this.#ready().snapshot(ctx);}
|
snapshot(ctx){return this.#ready().snapshot(ctx);}
|
||||||
apply(prepared,ctx){return this.#ready().apply(prepared,ctx);}
|
async #observe(operation){try{return await operation();}catch(error){this.#lastError={code:error.code??'unavailable',stage:this.#phase,command:error.command,upstreamCode:error.upstreamCode,translationKey:error.translationKey};if(error.code==='uncertain')this.#phase='queue reconciliation required';throw error;}}
|
||||||
restore(snapshot,ctx){return this.#ready().restore(snapshot,ctx);}
|
apply(prepared,ctx){return this.#observe(()=>this.#ready().apply(prepared,ctx));}
|
||||||
|
restore(snapshot,ctx){return this.#observe(()=>this.#ready().restore(snapshot,ctx));}
|
||||||
stopOwned(ctx){return this.#ready().stopOwned(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();}
|
control(action,value,ctx){return this.#observe(()=>this.#ready().control(action,value,ctx));}
|
||||||
|
playbackStatus(){return this.#ready().playbackStatus();}
|
||||||
|
setVolume(value){this.#ready();if(!Number.isFinite(value)||value<0||value>100)throw new MusicError('denied');this.#core.setVolume(Math.round(value));}
|
||||||
|
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;this.#meter=null;const context=this.#context;this.#context=null;if(context&&context.state!=='closed')await context.close();}
|
||||||
}
|
}
|
||||||
+33
-16
@@ -9,26 +9,37 @@ export function validateIceServers(servers){
|
|||||||
}
|
}
|
||||||
return servers.map(({urls,username,credential})=>({urls,...(username?{username,credential}:{})}));
|
return servers.map(({urls,username,credential})=>({urls,...(username?{username,credential}:{})}));
|
||||||
}
|
}
|
||||||
function audioOnly(sdp,remote){
|
export function validateAudioSDP(sdp,remote){
|
||||||
if(typeof sdp!=='string'||sdp.length>65536)throw new MusicError('denied');
|
if(typeof sdp!=='string'||sdp.length>65536||!['offer','answer'].includes(remote))throw new MusicError('denied');
|
||||||
const media=sdp.split(/\r?\n/).filter(line=>line.startsWith('m='));
|
const sections=[[]];
|
||||||
if(media.length!==1||!media[0].startsWith('m=audio ')||/a=sendrecv|a=sendonly/.test(sdp)&&remote==='answer')throw new MusicError('denied');
|
for(const line of sdp.split(/\r?\n/)){if(line.startsWith('m='))sections.push([]);sections.at(-1).push(line);}
|
||||||
|
if(sections.length!==2||!sections[1][0].startsWith('m=audio '))throw new MusicError('denied');
|
||||||
|
const directions=lines=>lines.filter(line=>/^a=(sendrecv|sendonly|recvonly|inactive)$/.test(line));
|
||||||
|
const session=directions(sections[0]),media=directions(sections[1]);
|
||||||
|
if(session.length>1||media.length>1)throw new MusicError('denied');
|
||||||
|
// SDP media attributes override session defaults. Firefox inserts session-level
|
||||||
|
// sendrecv after ICE gathering even when the sole audio media is recvonly.
|
||||||
|
const effective=media[0]??session[0]??'a=sendrecv';
|
||||||
|
const expected=remote==='offer'?'a=recvonly':'a=sendonly';
|
||||||
|
if(effective!==expected&&effective!=='a=inactive')throw new MusicError('denied');
|
||||||
}
|
}
|
||||||
|
|
||||||
async function gathered(pc){
|
async function gathered(pc){
|
||||||
if(pc.iceGatheringState==='complete')return;
|
if(pc.iceGatheringState==='complete')return;
|
||||||
await new Promise((resolve,reject)=>{const timer=setTimeout(()=>{pc.removeEventListener('icegatheringstatechange',check);reject(new MusicError('unavailable'));},5000);const check=()=>{if(pc.iceGatheringState==='complete'){clearTimeout(timer);pc.removeEventListener('icegatheringstatechange',check);resolve();}};pc.addEventListener('icegatheringstatechange',check);check();});
|
await new Promise((resolve,reject)=>{const timer=setTimeout(()=>{pc.removeEventListener('icegatheringstatechange',check);reject(new MusicError('unavailable'));},5000);const check=()=>{if(pc.iceGatheringState==='complete'){clearTimeout(timer);pc.removeEventListener('icegatheringstatechange',check);resolve();}};pc.addEventListener('icegatheringstatechange',check);check();});
|
||||||
}
|
}
|
||||||
export class PeerAudio{
|
export class PeerAudio{
|
||||||
#socket;#userId;#isGM;#peers=new Map();#session=crypto.randomUUID();#stream;#handler;#disconnect;#create;#onStream;#onError; #rejected=0;
|
#socket;#userId;#isGM;#peers=new Map();#session=crypto.randomUUID();#stream;#handler;#disconnect;#create;#onStream;#onError; #rejected=0; #lastSignalError;
|
||||||
constructor({socket,userId,isGM,isAuthorizedUser=()=>true,onStream=()=>{},onError=()=>{},createPeer=config=>new RTCPeerConnection(config)}){
|
constructor({socket,userId,isGM,isAuthorizedUser=()=>true,onStream=()=>{},onError=()=>{},createPeer=config=>new RTCPeerConnection(config)}){
|
||||||
this.#socket=socket;this.#userId=userId;this.#isGM=isGM;this.authorized=isAuthorizedUser;this.#create=createPeer;this.#onStream=onStream;this.#onError=onError;
|
this.#socket=socket;this.#userId=userId;this.#isGM=isGM;this.authorized=isAuthorizedUser;this.#create=createPeer;this.#onStream=onStream;this.#onError=onError;
|
||||||
this.#handler=frame=>{this.#receive(frame).catch(()=>{this.#rejected++;});};this.#disconnect=()=>this.reset();
|
this.#handler=frame=>{this.#receive(frame).catch(error=>{this.#rejected++;this.#lastSignalError={code:['denied','stale','unavailable'].includes(error.code)?error.code:'browser-error',name:/^[A-Za-z]{1,40}$/.test(error.name??'')?error.name:undefined,stage:this.#peers.get(frame?.peer)?.stage};});};this.#disconnect=()=>this.reset();
|
||||||
socket.on('module.adaptive-music',this.#handler);socket.on('disconnect',this.#disconnect);
|
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;}
|
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}={}){
|
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);
|
if(!this.#isGM()||!this.authorized(userId)||!this.#stream)throw new MusicError('denied');validateIceServers(iceServers);
|
||||||
const invite=newAudioInvite({session:this.#session,userId,iceServers,ttlMs,relayOnly});this.#entry(invite,'gm');return invite;
|
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){
|
async listen(invite){
|
||||||
if(this.#isGM()||invite.userId!==this.#userId||this.#peers.size)throw new MusicError('denied');
|
if(this.#isGM()||invite.userId!==this.#userId||this.#peers.size)throw new MusicError('denied');
|
||||||
@@ -46,7 +57,13 @@ export class PeerAudio{
|
|||||||
entry.timer=setTimeout(()=>this.revoke(invite.peer),Math.max(1,invite.expires-Date.now()));
|
entry.timer=setTimeout(()=>this.revoke(invite.peer),Math.max(1,invite.expires-Date.now()));
|
||||||
pc.ontrack=event=>{if(role!=='listener'||event.track.kind!=='audio'){event.track.stop();return;}this.#onStream(event.streams[0]??new MediaStream([event.track]));};
|
pc.ontrack=event=>{if(role!=='listener'||event.track.kind!=='audio'){event.track.stop();return;}this.#onStream(event.streams[0]??new MediaStream([event.track]));};
|
||||||
pc.ondatachannel=event=>event.channel.close();
|
pc.ondatachannel=event=>event.channel.close();
|
||||||
pc.onconnectionstatechange=()=>{if(['failed','closed'].includes(pc.connectionState)){this.#onError(new MusicError('unavailable'));this.revoke(invite.peer);}};
|
pc.onconnectionstatechange=()=>{
|
||||||
|
clearTimeout(entry.disconnectTimer);
|
||||||
|
if(pc.connectionState==='connected')clearTimeout(entry.handshakeTimer);
|
||||||
|
if(['failed','closed'].includes(pc.connectionState)){this.#onError(new MusicError('unavailable'));this.revoke(invite.peer);}
|
||||||
|
else if(pc.connectionState==='disconnected')entry.disconnectTimer=setTimeout(()=>{if(pc.connectionState!=='connected'){this.#onError(new MusicError('unavailable'));this.revoke(invite.peer);}},10000);
|
||||||
|
};
|
||||||
|
entry.handshakeTimer=setTimeout(()=>{if(pc.connectionState!=='connected'){this.#onError(new MusicError('unavailable'));this.revoke(invite.peer);}},20000);
|
||||||
this.#peers.set(invite.peer,entry);return entry;
|
this.#peers.set(invite.peer,entry);return entry;
|
||||||
}
|
}
|
||||||
async #send(entry,payload){if(this.#peers.get(entry.invite.peer)!==entry)return;const frame=await entry.codec.seal(payload);if(this.#peers.get(entry.invite.peer)!==entry||entry.invite.expires<=Date.now())return;this.#socket.emit('module.adaptive-music',frame);}
|
async #send(entry,payload){if(this.#peers.get(entry.invite.peer)!==entry)return;const frame=await entry.codec.seal(payload);if(this.#peers.get(entry.invite.peer)!==entry||entry.invite.expires<=Date.now())return;this.#socket.emit('module.adaptive-music',frame);}
|
||||||
@@ -55,25 +72,25 @@ export class PeerAudio{
|
|||||||
if(entry.pending>=4||++entry.signals>64)throw new MusicError('denied');entry.pending++;
|
if(entry.pending>=4||++entry.signals>64)throw new MusicError('denied');entry.pending++;
|
||||||
entry.tail=entry.tail.catch(()=>{}).then(async()=>{
|
entry.tail=entry.tail.catch(()=>{}).then(async()=>{
|
||||||
if(entry.role==='gm'&&(!this.#isGM()||!this.authorized(entry.invite.userId)))throw new MusicError('denied');
|
if(entry.role==='gm'&&(!this.#isGM()||!this.authorized(entry.invite.userId)))throw new MusicError('denied');
|
||||||
const payload=await entry.codec.open(frame);
|
entry.stage='decrypt signal';const payload=await entry.codec.open(frame);entry.stage='validate SDP';
|
||||||
if(payload.type==='bye'){this.revoke(frame.peer);return;}
|
if(payload.type==='bye'){this.revoke(frame.peer);return;}
|
||||||
if(entry.role==='gm'&&payload.type==='offer'){
|
if(entry.role==='gm'&&payload.type==='offer'){
|
||||||
// The listener's SDP is recvonly: reject video, data, injected outbound audio.
|
// The listener's SDP is recvonly: reject video, data, injected outbound audio.
|
||||||
audioOnly(payload.sdp,'answer');
|
validateAudioSDP(payload.sdp,'offer');
|
||||||
if(!entry.started){entry.pc.addTrack(this.#stream.getAudioTracks()[0],this.#stream);entry.started=true;}
|
if(!entry.started){entry.pc.addTrack(this.#stream.getAudioTracks()[0],this.#stream);entry.started=true;}
|
||||||
await entry.pc.setRemoteDescription({type:'offer',sdp:payload.sdp});
|
entry.stage='apply offer';await entry.pc.setRemoteDescription({type:'offer',sdp:payload.sdp});
|
||||||
await entry.pc.setLocalDescription(await entry.pc.createAnswer());await gathered(entry.pc);
|
await entry.pc.setLocalDescription(await entry.pc.createAnswer());await gathered(entry.pc);
|
||||||
await this.#send(entry,{type:'answer',sdp:entry.pc.localDescription.sdp});
|
entry.stage='send answer';await this.#send(entry,{type:'answer',sdp:entry.pc.localDescription.sdp});
|
||||||
}else if(entry.role==='listener'&&payload.type==='answer'){
|
}else if(entry.role==='listener'&&payload.type==='answer'){
|
||||||
audioOnly(payload.sdp,'offer');await entry.pc.setRemoteDescription({type:'answer',sdp:payload.sdp});
|
validateAudioSDP(payload.sdp,'answer');await entry.pc.setRemoteDescription({type:'answer',sdp:payload.sdp});
|
||||||
}else throw new MusicError('denied');
|
}else throw new MusicError('denied');
|
||||||
});return entry.tail.finally(()=>{entry.pending--;});
|
});return entry.tail.finally(()=>{entry.pending--;});
|
||||||
}
|
}
|
||||||
async restart(peer){const entry=this.#peers.get(peer);if(!entry||entry.role!=='listener'||++entry.restarts>2)throw new MusicError('denied');await entry.pc.setLocalDescription(await entry.pc.createOffer({iceRestart:true}));await gathered(entry.pc);await this.#send(entry,{type:'offer',sdp:entry.pc.localDescription.sdp});}
|
async restart(peer){const entry=this.#peers.get(peer);if(!entry||entry.role!=='listener'||++entry.restarts>2)throw new MusicError('denied');await entry.pc.setLocalDescription(await entry.pc.createOffer({iceRestart:true}));await gathered(entry.pc);await this.#send(entry,{type:'offer',sdp:entry.pc.localDescription.sdp});}
|
||||||
revoke(peer){const entry=this.#peers.get(peer);if(!entry)return;clearTimeout(entry.timer);this.#peers.delete(peer);entry.pc.onconnectionstatechange=null;entry.pc.ontrack=null;entry.pc.close();}
|
revoke(peer){const entry=this.#peers.get(peer);if(!entry)return;clearTimeout(entry.timer);clearTimeout(entry.handshakeTimer);clearTimeout(entry.disconnectTimer);this.#peers.delete(peer);entry.pc.onconnectionstatechange=null;entry.pc.ontrack=null;entry.pc.close();}
|
||||||
reset(){for(const peer of [...this.#peers.keys()])this.revoke(peer);this.#stream=null;this.#session=crypto.randomUUID();}
|
reset(){for(const peer of [...this.#peers.keys()])this.revoke(peer);this.#stream=null;this.#session=crypto.randomUUID();}
|
||||||
close(){this.reset();this.#socket.off('module.adaptive-music',this.#handler);this.#socket.off('disconnect',this.#disconnect);}
|
close(){this.reset();this.#socket.off('module.adaptive-music',this.#handler);this.#socket.off('disconnect',this.#disconnect);}
|
||||||
reconcile(){for(const [peer,entry]of this.#peers)if(entry.role==='gm'&&(!this.#isGM()||!this.authorized(entry.invite.userId)))this.revoke(peer);}
|
reconcile(){for(const [peer,entry]of this.#peers)if(entry.role==='gm'&&(!this.#isGM()||!this.authorized(entry.invite.userId)))this.revoke(peer);}
|
||||||
diagnostics(){return {rejectedSignals:this.#rejected,peers:[...this.#peers.values()].map(e=>({role:e.role,connection:e.pc.connectionState,ice:e.pc.iceConnectionState,signaling:e.pc.signalingState}))};}
|
diagnostics(){return {rejectedSignals:this.#rejected,lastSignalError:this.#lastSignalError,peers:[...this.#peers.values()].map(e=>({role:e.role,connection:e.pc.connectionState,ice:e.pc.iceConnectionState,signaling:e.pc.signalingState,stage:e.stage}))};}
|
||||||
async stats(){const results=[];for(const entry of this.#peers.values()){const stats=await entry.pc.getStats();for(const item of stats.values())if(['inbound-rtp','outbound-rtp','candidate-pair'].includes(item.type))results.push({type:item.type,bytesSent:item.bytesSent,bytesReceived:item.bytesReceived,jitter:item.jitter,packetsLost:item.packetsLost,audioLevel:item.audioLevel,totalAudioEnergy:item.totalAudioEnergy,totalSamplesReceived:item.totalSamplesReceived,currentRoundTripTime:item.currentRoundTripTime});}return results;}
|
async stats(){const results=[];for(const entry of this.#peers.values()){const stats=await entry.pc.getStats();for(const item of stats.values())if(['inbound-rtp','outbound-rtp','candidate-pair'].includes(item.type))results.push({type:item.type,bytesSent:item.bytesSent,bytesReceived:item.bytesReceived,jitter:item.jitter,packetsLost:item.packetsLost,audioLevel:item.audioLevel,totalAudioEnergy:item.totalAudioEnergy,totalSamplesReceived:item.totalSamplesReceived,currentRoundTripTime:item.currentRoundTripTime});}return results;}
|
||||||
}
|
}
|
||||||
+26
-4
@@ -25,13 +25,35 @@ export class MusicController {
|
|||||||
}
|
}
|
||||||
update(state) {
|
update(state) {
|
||||||
const input = structuredClone(state);
|
const input = structuredClone(state);
|
||||||
|
const context = this.#nextContext();
|
||||||
|
return this.#enqueue(() => this.transition(input, context));
|
||||||
|
}
|
||||||
|
control(action, value) {
|
||||||
|
if (!['pause', 'resume', 'stop', 'seek'].includes(action) || !this.providers.ma?.control) {
|
||||||
|
return Promise.reject(new MusicError('unsupported'));
|
||||||
|
}
|
||||||
|
const expected = this.generation;
|
||||||
|
return this.#enqueue(() => {
|
||||||
|
if (expected !== this.generation) throw new MusicError('stale');
|
||||||
|
const context = this.#nextContext();
|
||||||
|
context.check();
|
||||||
|
return this.providers.ma.control(action, value, context);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
cancel() {
|
||||||
|
this.generation++;
|
||||||
|
this.abort?.abort();
|
||||||
|
}
|
||||||
|
#nextContext() {
|
||||||
const generation = ++this.generation;
|
const generation = ++this.generation;
|
||||||
this.abort?.abort(); this.abort = new AbortController();
|
this.abort?.abort(); this.abort = new AbortController();
|
||||||
const context = { campaign: this.campaign, session: this.session, generation,
|
return { campaign: this.campaign, session: this.session, generation,
|
||||||
signal: this.abort.signal, check: () => {
|
signal: this.abort.signal, check: () => {
|
||||||
if (generation !== this.generation || !this.authority()) throw new MusicError('stale');
|
if (generation !== this.generation || !this.authority()) throw new MusicError('stale');
|
||||||
} };
|
} };
|
||||||
const task = this.tail.catch(() => {}).then(() => this.transition(input, context));
|
}
|
||||||
|
#enqueue(operation) {
|
||||||
|
const task = this.tail.catch(() => {}).then(operation);
|
||||||
this.tail = task; return task;
|
this.tail = task; return task;
|
||||||
}
|
}
|
||||||
async transition(state, ctx) {
|
async transition(state, ctx) {
|
||||||
@@ -64,9 +86,9 @@ export class MusicController {
|
|||||||
}
|
}
|
||||||
ctx.check();
|
ctx.check();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Never restore an obsolete transition. Reconciliation is explicit after stale writes.
|
// Stale or uncertain writes require explicit reconciliation.
|
||||||
this.current = null;
|
this.current = null;
|
||||||
if (error.code !== 'stale') {
|
if (error.code !== 'stale' && error.code !== 'uncertain') {
|
||||||
ctx.check();
|
ctx.check();
|
||||||
for (const p of this.dirty) { ctx.check(); await p.stopOwned(ctx); }
|
for (const p of this.dirty) { ctx.check(); await p.stopOwned(ctx); }
|
||||||
if (snapshot) { ctx.check(); await outgoing.restore(snapshot, ctx); this.current = old; }
|
if (snapshot) { ctx.check(); await outgoing.restore(snapshot, ctx); this.current = old; }
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import {MusicError} from '../core/controller.mjs';
|
||||||
|
import {base64url,hmac} from '../providers/ma/webcrypto.mjs';
|
||||||
|
|
||||||
|
const bytes=new TextEncoder();
|
||||||
|
|
||||||
|
async function key(token,scope){
|
||||||
|
const material=await hmac(bytes.encode(token),'adaptive-music saved connection\0'+scope);
|
||||||
|
return crypto.subtle.importKey('raw',material,'AES-GCM',false,['encrypt','decrypt']);
|
||||||
|
}
|
||||||
|
|
||||||
|
function decode(value){
|
||||||
|
if(typeof value!=='string'||!/^[A-Za-z0-9_-]+$/.test(value))throw new MusicError('saved-connection-unavailable');
|
||||||
|
return Uint8Array.from(atob(value.replace(/-/g,'+').replace(/_/g,'/')),char=>char.charCodeAt(0));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function sealAccountConnection({maUrl,targetName},token,scope){
|
||||||
|
const iv=crypto.getRandomValues(new Uint8Array(12));
|
||||||
|
const content=bytes.encode(JSON.stringify({maUrl,targetName}));
|
||||||
|
if(content.length>2048)throw new MusicError('saved-connection-too-large');
|
||||||
|
const cipher=await crypto.subtle.encrypt({name:'AES-GCM',iv,additionalData:bytes.encode(scope)},await key(token,scope),content);
|
||||||
|
return {version:1,iv:base64url(iv),cipher:base64url(new Uint8Array(cipher))};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function openAccountConnection(saved,token,scope){
|
||||||
|
try{
|
||||||
|
if(saved?.version!==1||saved.iv?.length!==16||!saved.cipher||saved.cipher.length>2800)throw Error();
|
||||||
|
const content=await crypto.subtle.decrypt({name:'AES-GCM',iv:decode(saved.iv),additionalData:bytes.encode(scope)},await key(token,scope),decode(saved.cipher));
|
||||||
|
const {maUrl,targetName}=JSON.parse(new TextDecoder().decode(content));
|
||||||
|
if(typeof maUrl!=='string'||typeof targetName!=='string')throw Error();
|
||||||
|
return {maUrl,targetName};
|
||||||
|
}catch{throw new MusicError('saved-connection-unavailable');}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
// Secrets stay in closure memory across failed attempts and window rerenders.
|
||||||
|
// Never carry a token to a changed server, including a scheme/port change.
|
||||||
|
export function connectionDraft(previous,profile,campaign){
|
||||||
|
let same=false;try{same=new URL(previous?.maUrl).origin===new URL(profile.maUrl).origin;}catch{}
|
||||||
|
const old=same?previous:{};
|
||||||
|
return {...old,...profile,token:profile.token||old?.token,identityStorage:profile.identityStorage?.['sendspin-identity-sk']?profile.identityStorage:old?.identityStorage,campaign};
|
||||||
|
}
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
import {gmAccessPolicy} from '../audio/gm-host.mjs';
|
||||||
|
import {validateIceServers} from '../audio/peer-audio.mjs';
|
||||||
|
import {probeWebSockets,diagnosticMessage} from '../providers/ma/diagnostics.mjs';
|
||||||
|
const messages={
|
||||||
|
'saved-connection-unavailable':'This token could not unlock the saved connection. Enter the server address and a valid token to save a new connection.',
|
||||||
|
'saved-connection-write-failed':'Connected, but Foundry could not save the connection for this account.',
|
||||||
|
'ice-config-invalid':'Enter a valid existing STUN/TURN URL. TURN also needs a username, credential and UTC expiry within one hour. No network setting was applied.',
|
||||||
|
'token-required':'Enter a Music Assistant access token for this server.',
|
||||||
|
'token-invalid':'Remove line breaks from the access token and try again.',
|
||||||
|
'receiver-name-invalid':'Use at most 120 characters for the receiver name, without line breaks.',
|
||||||
|
'automation-disabled':'Enable automation before applying a manual playlist override.',
|
||||||
|
'address-invalid':'Enter the MA server origin, such as https://ma.example.test, without a path or query.',
|
||||||
|
'ws-upgrade-failed':'The browser could not open the API WebSocket. Run Check browser connection below. If it works from MA’s page only, compare this browser’s local-network permission, private DNS and site restrictions.',
|
||||||
|
'ws-auth-timeout':'The API socket opened, but authentication did not finish. Check that /ws reaches MA rather than a login portal.',
|
||||||
|
'ws-auth-denied':'MA rejected the token. Enter a replacement and select Connect again; the receiver is remembered.',
|
||||||
|
'ws-disconnected':'The API socket closed. Your private inputs remain in this tab. Retry after checking the private route.',
|
||||||
|
'ws-command-timeout':'MA did not answer a command before its deadline. Catalog reads have a 10-second limit; stream startup has a 60-second limit. Unconfirmed queue writes stop automation for review.',
|
||||||
|
'ws-command-failed':'MA rejected a command. The account needs music-provider access and permission to control and pair its dedicated web receiver.',
|
||||||
|
'sendspin-auth-failed':'The receiver socket opened, but Sendspin authentication failed. Verify the authenticated /sendspin route, separate from /ws.',
|
||||||
|
'sendspin-sync-failed':'Sendspin did not complete pairing and clock synchronization. Retry the remembered receiver; transport HTTP 101 alone does not prove a working audio receiver.',
|
||||||
|
'insecure-context':'Open Foundry over trusted HTTPS to use secure browser audio APIs.',
|
||||||
|
'mixed-content':'HTTPS Foundry requires a trusted HTTPS MA address. Browser security cannot permit an HTTP/ws downgrade.',
|
||||||
|
'reconcile-required':'This dedicated receiver has an existing queue. Playback was left untouched. Resume the remembered receiver after reviewing its queue in MA, or use a new dedicated receiver.',
|
||||||
|
'catalog-empty':'No available music providers were returned. Check the dedicated MA account’s music-provider access.',
|
||||||
|
'unsupported':'This queue or browser feature is unsupported. Use a standalone receiver with a static queue, shuffle and autoplay off, and a browser with Web Locks, Web Audio and WebRTC.',
|
||||||
|
'private-storage-unavailable':'This browser denied private receiver storage. Allow site storage for Foundry, then retry. No MA token is stored there.',
|
||||||
|
'private-storage-corrupt':'The remembered receiver could not be decrypted. Use Forget remembered receiver below to create a replacement. Existing MA queues are left untouched.',
|
||||||
|
'identity-mismatch':'The remembered receiver identity does not match this connection. Forget that receiver to create a new campaign receiver.',
|
||||||
|
'dedicated-target-required':'The receiver did not match the identity and name created for this campaign. No unrelated player was selected.',
|
||||||
|
'receiver-queue-unavailable':'MA did not make this receiver’s queue available after connection. Retry connecting the remembered receiver.',
|
||||||
|
'denied':'The dedicated receiver, account permission or active GM check failed. Keep one active GM and verify that this account can control its campaign receiver.',
|
||||||
|
'stale':'GM authority or the connection changed during setup. Keep one active GM, then retry.',
|
||||||
|
'uncertain':'MA did not confirm a queue write. Automation stopped to avoid duplicate playback. Review this dedicated queue before reconnecting.',
|
||||||
|
'unavailable':'The operation failed. Your private inputs are retained. Run the browser connection check to separate transport failures from receiver and audio setup.'
|
||||||
|
};
|
||||||
|
export const connectionMessage=error=>error?.upstreamCode===2&&['player_queues/play_media','player_queues/play_index'].includes(error.command)?'MA could not find playable media for this playlist (MA error 2). Check its content/provider in MA or choose another playlist. Automation stopped; an unconfirmed queue write is never retried.':messages[error?.code]??messages.unavailable;
|
||||||
|
|
||||||
|
function failureStage(error) {
|
||||||
|
if (['ws-upgrade-failed', 'ws-disconnected', 'mixed-content', 'insecure-context'].includes(error?.code)) return 'Connection failed';
|
||||||
|
if (['ws-auth-denied', 'ws-auth-timeout'].includes(error?.code) || error?.stage === 'API authentication') return 'Authentication failed';
|
||||||
|
if (['receiver pairing','dedicated receiver verification','dedicated queue verification','Noise handshake'].includes(error?.stage) || error?.code === 'sendspin-sync-failed') return 'Receiver setup failed';
|
||||||
|
if (error?.stage === 'Sendspin authentication' || error?.code === 'sendspin-auth-failed') return 'Receiver connection failed';
|
||||||
|
if (error?.stage === 'catalog retrieval' || error?.code === 'catalog-empty') return 'Playlist catalog unavailable';
|
||||||
|
return 'Setup failed';
|
||||||
|
}
|
||||||
|
|
||||||
|
function iceConfiguration(fields) {
|
||||||
|
const {url, username, credential, expires} = fields;
|
||||||
|
if (!url && !username && !credential && !expires) return undefined;
|
||||||
|
const scheme = url.match(/^(stun|stuns|turn|turns):/i)?.[1].toLowerCase();
|
||||||
|
const target = scheme && URL.canParse(`https://${url.slice(scheme.length + 1)}`) && new URL(`https://${url.slice(scheme.length + 1)}`);
|
||||||
|
const turn = scheme?.startsWith('turn');
|
||||||
|
if (!target || !target.hostname || target.username || target.password || target.pathname !== '/' || target.hash ||
|
||||||
|
/[\s/]/.test(url) || (target.search && !(turn && /^\?transport=(udp|tcp)$/.test(target.search))) ||
|
||||||
|
(!turn && (username || credential || expires))) throw {code:'ice-config-invalid'};
|
||||||
|
const server = {urls:url, ...(turn ? {username, credential, expires:Date.parse(expires + 'Z')} : {})};
|
||||||
|
try{validateIceServers([server]);}
|
||||||
|
catch{throw {code:'ice-config-invalid'};}
|
||||||
|
return {iceServers:[server]};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mountConnectionWizard({game,container,connection,onCatalog=()=>{},onError=()=>{},next,advancedContent}) {
|
||||||
|
const dom=container.ownerDocument;
|
||||||
|
const make=(tag,text,parent=container)=>{
|
||||||
|
const node=dom.createElement(tag);
|
||||||
|
if(text)node.textContent=text;
|
||||||
|
parent.append(node);
|
||||||
|
return node;
|
||||||
|
};
|
||||||
|
const input=(parent,label,type='text')=>{
|
||||||
|
const wrapper=make('label',label,parent),field=make('input',null,wrapper);
|
||||||
|
field.type=type;field.autocomplete='off';field.spellcheck=false;
|
||||||
|
return field;
|
||||||
|
};
|
||||||
|
const initial=connection.draftFields??{};
|
||||||
|
make('h2','Connect Music Assistant');
|
||||||
|
make('p','Enter your Music Assistant address and access token. Adaptive Music creates or reconnects your campaign receiver and loads your playlists.');
|
||||||
|
if(initial.savedConnection)make('p','This Foundry account has a saved connection. Enter its access token to unlock the address, or enter a different address to replace it.');
|
||||||
|
const fields=make('div');fields.className='adaptive-fields';
|
||||||
|
const address=input(fields,'Music Assistant server address','url');address.placeholder='https://ma.example.test';address.value=initial.maUrl??'';
|
||||||
|
const token=input(fields,'Private GM access token','password');
|
||||||
|
const retainError=make('p');retainError.setAttribute('role','alert');retainError.hidden=true;
|
||||||
|
const actions=make('div');actions.className='adaptive-actions';
|
||||||
|
const state=make('p');state.className='adaptive-state';
|
||||||
|
const status=make('p');status.setAttribute('role','status');
|
||||||
|
const advanced=make('details');make('summary','Advanced',advanced);
|
||||||
|
const advancedFields=make('div',null,advanced);advancedFields.className='adaptive-fields';
|
||||||
|
const name=input(advancedFields,'Dedicated receiver name');name.value=initial.targetName??'';name.placeholder='Adaptive Music '+(game.world?.title??'campaign');
|
||||||
|
const iceURL=input(advancedFields,'ICE server URL');iceURL.placeholder='stun:stun.example.test:3478';
|
||||||
|
const iceUsername=input(advancedFields,'TURN username'),iceCredential=input(advancedFields,'TURN credential','password');
|
||||||
|
const iceExpiry=input(advancedFields,'TURN credential expiry (UTC)','datetime-local');
|
||||||
|
const diagnosticsActions=make('div');diagnosticsActions.className='adaptive-actions';
|
||||||
|
const report=make('div');report.setAttribute('aria-live','polite');
|
||||||
|
let transportResults=[],busy=false;
|
||||||
|
const run=async(action,label)=>{
|
||||||
|
if(busy||!game.user.isGM)return;
|
||||||
|
busy=true;retainError.hidden=true;render();
|
||||||
|
try{await action();}
|
||||||
|
catch(error){
|
||||||
|
busy=false;render();error.field?.focus?.();
|
||||||
|
retainError.textContent=`${typeof label==='function'?label(error):label}. ${connectionMessage(error)}`;retainError.hidden=false;onError(error);
|
||||||
|
}finally{busy=false;render();}
|
||||||
|
};
|
||||||
|
const button=(parent,label,action)=>{
|
||||||
|
const b=make('button',label,parent);b.type='button';b.addEventListener('click',action);return b;
|
||||||
|
};
|
||||||
|
const pageUrl=()=>dom.location?.href??globalThis.location?.href??'https://foundry.invalid';
|
||||||
|
function validatedAddress(){
|
||||||
|
try{return gmAccessPolicy(address.value.trim(),pageUrl()).origin;}
|
||||||
|
catch(error){if(error.code==='denied')throw {code:'address-invalid'};throw error;}
|
||||||
|
}
|
||||||
|
function retainedToken(){
|
||||||
|
const draft=connection.draftFields??{};
|
||||||
|
try{return draft.retainedToken===true&&new URL(draft.maUrl).origin===validatedAddress();}
|
||||||
|
catch{return false;}
|
||||||
|
}
|
||||||
|
const connect=button(actions,'Connect',()=>run(async()=>{
|
||||||
|
let maUrl;
|
||||||
|
const useSaved=!address.value.trim()&&connection.draftFields?.savedConnection;
|
||||||
|
if(!useSaved)try{maUrl=validatedAddress();}catch(error){throw {code:error.code,field:address};}
|
||||||
|
if(!token.value.trim()&&(useSaved||!retainedToken()))throw {code:'token-required',field:token};
|
||||||
|
if(/[\r\n]/.test(token.value))throw {code:'token-invalid',field:token};
|
||||||
|
const targetName=name.value.trim();
|
||||||
|
if(targetName.length>120||/[\x00-\x1f\x7f]/.test(name.value)){advanced.open=true;throw {code:'receiver-name-invalid',field:name};}
|
||||||
|
let listenerNetwork;
|
||||||
|
try{listenerNetwork=iceConfiguration({url:iceURL.value.trim(),username:iceUsername.value.trim(),credential:iceCredential.value,expires:iceExpiry.value});}
|
||||||
|
catch{advanced.open=true;throw {code:'ice-config-invalid',field:iceURL};}
|
||||||
|
status.textContent='Contacting Music Assistant…';
|
||||||
|
let result;
|
||||||
|
try{result=await connection.open({maUrl,token:token.value.trim(),...(targetName&&{targetName}),...(listenerNetwork&&{listenerNetwork})});}
|
||||||
|
finally{if(connection.status.hasPrivateDraft){token.value='';iceCredential.value='';}}
|
||||||
|
address.value=connection.draftFields?.maUrl??address.value;
|
||||||
|
await onCatalog();
|
||||||
|
status.textContent=result?.attachedExistingQueue?'Connected. The existing queue is preserved. Enable automation from Playback when you’re ready.':'Campaign audio connected. Choose playlists for your scene.';
|
||||||
|
},error=>['address-invalid','token-invalid','token-required','receiver-name-invalid','ice-config-invalid'].includes(error.code)?'Check your settings':failureStage(error)));
|
||||||
|
connect.className='adaptive-primary';
|
||||||
|
const nextButton=button(actions,'Choose scene music',()=>next?.());
|
||||||
|
const disconnect=button(actions,'Disconnect',()=>run(async()=>{
|
||||||
|
await connection.disconnect();token.value='';iceCredential.value='';status.textContent='Disconnected. The receiver is remembered for next time.';await onCatalog();
|
||||||
|
},'Disconnect failed'));
|
||||||
|
button(diagnosticsActions,'Check browser connection',()=>run(async()=>{
|
||||||
|
report.replaceChildren();transportResults=await probeWebSockets(validatedAddress());
|
||||||
|
for(const result of transportResults)make('p',`${result.path} — ${diagnosticMessage(result)}`,report);
|
||||||
|
status.textContent='Browser checks complete.';
|
||||||
|
},'Browser connection check failed'));
|
||||||
|
button(diagnosticsActions,'Copy connection diagnostics',()=>run(async()=>{
|
||||||
|
const d=connection.status;
|
||||||
|
await navigator.clipboard.writeText(JSON.stringify({state:d.state,stage:d.stage,catalog:d.catalog,audioContext:d.audioContext,decodedFrames:d.decodedFrames,scheduledFrames:d.scheduledFrames,droppedLate:d.droppedLate,droppedAhead:d.droppedAhead,muted:d.muted,pauseMode:d.pauseMode,signalRMS:d.rms,outputRMS:d.outputRMS,listenerConnections:d.peers??0,lastError:d.lastError,listenerDiagnostics:d.listenerDiagnostics,transport:transportResults,secureContext:globalThis.isSecureContext},null,2));
|
||||||
|
status.textContent='Connection diagnostics copied.';
|
||||||
|
},'Could not copy diagnostics'));
|
||||||
|
const advancedActions=make('div',null,advanced);advancedActions.className='adaptive-actions';
|
||||||
|
const refresh=button(advancedActions,'Refresh playlists',()=>run(async()=>{await connection.refresh();await onCatalog();status.textContent='Playlists refreshed.';},'Catalog refresh failed'));
|
||||||
|
const forget=button(advancedActions,'Forget saved connection',()=>run(async()=>{
|
||||||
|
await connection.forgetReceiver();address.value='';token.value='';iceCredential.value='';name.value='';status.textContent='Saved connection removed from this account.';await onCatalog();
|
||||||
|
},'Could not forget the connection'));
|
||||||
|
if(advancedContent)advanced.append(advancedContent);
|
||||||
|
function render(){
|
||||||
|
const d=connection.status,connected=d.state==='connected';
|
||||||
|
const label=connected?'Connected':busy?'Working':d.state==='connection-lost'?'Connection lost':'Disconnected';
|
||||||
|
const summary=connected?`${label} · ${d.catalog??0} catalog choices`:
|
||||||
|
busy&&d.stage&&d.stage!=='idle'?`${label} · ${d.stage}`:label;
|
||||||
|
if(state.textContent!==summary)state.textContent=summary;
|
||||||
|
state.dataset.connected=String(connected);
|
||||||
|
connect.hidden=connected;connect.disabled=busy;connect.textContent=busy?'Connecting…':'Connect';
|
||||||
|
disconnect.hidden=!connected;disconnect.disabled=busy;
|
||||||
|
nextButton.hidden=!connected||!next;nextButton.disabled=busy;refresh.hidden=!connected;
|
||||||
|
forget.disabled=busy||(!d.hasPrivateDraft&&!connection.draftFields?.savedConnection);
|
||||||
|
for(const field of [address,token,name,iceURL,iceUsername,iceCredential,iceExpiry])field.disabled=connected||busy;
|
||||||
|
token.placeholder=retainedToken()?'Retained for this address':'Paste your access token';
|
||||||
|
}
|
||||||
|
address.addEventListener('input',render);
|
||||||
|
render();
|
||||||
|
return render;
|
||||||
|
}
|
||||||
+134
-22
@@ -1,46 +1,158 @@
|
|||||||
|
import {connectionMessage} from './connection-wizard.mjs';
|
||||||
|
import {ReceiverVault} from './receiver-vault.mjs';
|
||||||
|
import {connectionDraft} from './connection-draft.mjs';
|
||||||
import {startNativeRuntime,primaryGM} from './runtime.mjs';
|
import {startNativeRuntime,primaryGM} from './runtime.mjs';
|
||||||
import {startConfigurationInterfaces,mountPlaylistConfiguration} from './configuration.mjs';
|
import {startConfigurationInterfaces,mountPlaylistConfiguration} from './configuration.mjs';
|
||||||
import {GatewayClient} from '../providers/ma/remote.mjs';
|
import {GatewayClient} from '../providers/ma/remote.mjs';
|
||||||
import {GMAudioHost} from '../audio/gm-host.mjs';
|
import {GMAudioHost,gmAccessPolicy} from '../audio/gm-host.mjs';
|
||||||
|
import {AutoListeners} from '../audio/auto-listeners.mjs';
|
||||||
import {PeerAudio} from '../audio/peer-audio.mjs';
|
import {PeerAudio} from '../audio/peer-audio.mjs';
|
||||||
import {ListenerAudio} from './listener-audio.mjs';
|
import {ListenerAudio} from './listener-audio.mjs';
|
||||||
import {createSetupClass,createListenerClass} from './setup.mjs';
|
import {createSetupClass,createListenerClass} from './setup.mjs';
|
||||||
|
import {MusicError} from '../core/controller.mjs';
|
||||||
|
import {openAccountConnection,sealAccountConnection} from './account-connection.mjs';
|
||||||
const id='adaptive-music';
|
const id='adaptive-music';
|
||||||
let runtime,interfaces,gateway,audio,renewTimer,gmHost,peers,remoteAudio;let authorityHooks=[];
|
const receiverVault=new ReceiverVault();
|
||||||
|
const receiverScope=profile=>({campaign:game.world.id,userId:game.user.id,maUrl:profile.maUrl});
|
||||||
|
const accountScope=()=>JSON.stringify([location.origin,game.world.id,game.user.id]);
|
||||||
|
const savedConnection=()=>game.settings.get(id,'savedConnection');
|
||||||
|
let runtime,interfaces,gateway,audio,renewTimer,gmHost,peers,remoteAudio;let authorityHooks=[];let bootstrap,privateProfile,privateDraft,inviteTimer,latestInvite,listenerStopped=false,listenerState='Waiting for GM audio.',inviteTail=Promise.resolve();const sentInvites=new Map();let connectionGeneration=0,connectionTesting=false;let listenerContext,listenerSource;
|
||||||
|
let automationRunning=false,previousController;
|
||||||
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 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 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.');
|
const onError=error=>{if(error?.code==='uncertain')stop();ui.notifications.warn('Adaptive Music: '+connectionMessage(error));};
|
||||||
function start(){
|
function ensureRuntime(){
|
||||||
if(!game.user.isGM||runtime)return;
|
runtime??=startNativeRuntime({game,Hooks,campaign:game.world.id,session:gmHost?.connected?gmHost.session:globalThis.crypto.randomUUID(),ownedPlaylistIds:owned(),maProvider:gmHost?.connected?gmHost:gateway,
|
||||||
runtime=startNativeRuntime({game,Hooks,campaign:game.world.id,session:gmHost?.connected?gmHost.session:globalThis.crypto.randomUUID(),ownedPlaylistIds:owned(),maProvider:gmHost?.connected?gmHost:gateway,onError});
|
isEnabled:()=>automationRunning,authority:gmAuthority,previousController,onError});
|
||||||
runtime.refresh().catch(onError);
|
return runtime;
|
||||||
}
|
}
|
||||||
function stop(){runtime?.dispose();runtime=null;}
|
function start(){
|
||||||
function setOverrides(value){if(!runtime)throw Error('Automation is disabled');return runtime.setOverrides(value);}
|
if(!gmAuthority()||automationRunning)return;
|
||||||
|
automationRunning=true;
|
||||||
|
return ensureRuntime().refresh().catch(onError);
|
||||||
|
}
|
||||||
|
function stop(){
|
||||||
|
automationRunning=false;
|
||||||
|
if(runtime){runtime.dispose();previousController=runtime.controller;runtime=null;}
|
||||||
|
}
|
||||||
|
function setOverrides(value){if(!automationRunning)throw new MusicError('automation-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 draftFields(){return {maUrl:privateDraft?.maUrl,targetName:privateDraft?.targetName,retainedToken:!!privateDraft?.token,savedConnection:savedConnection()?.version===1};},
|
||||||
|
get status(){const listeners=peers?.diagnostics();return {...(gmHost?.status??{state:'disconnected',catalog:0,audioContext:'closed'}),hasPrivateDraft:!!privateDraft,selectedName:privateProfile?.targetName,listenerDiagnostics:listeners,peers:listeners?.peers.filter(p=>p.connection==='connected').length??0,automationRunning};},
|
||||||
|
async open(profile){
|
||||||
|
if(!gmAuthority()||connectionTesting||gmHost.connected||gateway.connected)throw new MusicError('denied');
|
||||||
|
// Claim browser audio activation before authentication performs asynchronous work.
|
||||||
|
const audioContext=gmHost.createContext();
|
||||||
|
const generation=connectionGeneration;
|
||||||
|
try{
|
||||||
|
void audioContext.resume().catch(()=>{});
|
||||||
|
if(!profile.maUrl){
|
||||||
|
const remembered=await openAccountConnection(savedConnection(),profile.token,accountScope());
|
||||||
|
gmAccessPolicy(remembered.maUrl,location.href);
|
||||||
|
profile={...profile,maUrl:remembered.maUrl,targetName:profile.targetName??remembered.targetName};
|
||||||
|
}
|
||||||
|
if(generation!==connectionGeneration||!gmAuthority())throw new MusicError('stale');
|
||||||
|
const {target}=await connection.test(profile);
|
||||||
|
return await connection.connect(target,{audioContext});
|
||||||
|
}catch(error){
|
||||||
|
if(audioContext.state!=='closed')await audioContext.close();
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
async test(profile){
|
||||||
|
if(connectionTesting||gmHost.connected||gmHost.status.state==='connecting'||gateway.connected)throw {code:'denied'};
|
||||||
|
connectionTesting=true;stop();const generation=++connectionGeneration;privateProfile=null;
|
||||||
|
const check=()=>{if(generation!==connectionGeneration)throw {code:'stale'};};
|
||||||
|
try{
|
||||||
|
await gmHost.close();check();
|
||||||
|
const candidate=connectionDraft(privateDraft,profile,game.world.id);privateDraft=candidate;
|
||||||
|
if(!candidate.identityStorage?.['sendspin-identity-sk'])Object.assign(candidate,await receiverVault.load(receiverScope(candidate))??{});check();
|
||||||
|
candidate.targetName??='Adaptive Music '+game.world.title;candidate.allowCatalogPlayback=true;candidate.portableCatalog=true;
|
||||||
|
const result=await gmHost.prepare(candidate);check();
|
||||||
|
await receiverVault.save(receiverScope(result),result);check();
|
||||||
|
privateProfile=result;privateDraft=result;return {target:result.target,targetName:result.targetName};
|
||||||
|
}catch(error){error.stage??='API authentication';throw error;}
|
||||||
|
finally{connectionTesting=false;}
|
||||||
|
},
|
||||||
|
async connect(target,{resumeAutomation=true,audioContext}={}){
|
||||||
|
if(!privateProfile||target!==privateProfile.target||gateway.connected)throw new MusicError('denied');
|
||||||
|
stop();const profile=privateProfile,generation=connectionGeneration;
|
||||||
|
let result;
|
||||||
|
try{result=await gmHost.start(profile,{audioContext});}
|
||||||
|
finally{if(generation===connectionGeneration)await receiverVault.save(receiverScope(profile),profile);}
|
||||||
|
if(generation!==connectionGeneration||!gmAuthority())throw new MusicError('stale');
|
||||||
|
try{
|
||||||
|
const saved=await sealAccountConnection(profile,profile.token,accountScope());
|
||||||
|
if(generation===connectionGeneration)await game.settings.set(id,'savedConnection',saved);
|
||||||
|
}catch{onError(new MusicError('saved-connection-write-failed'));}
|
||||||
|
if(generation!==connectionGeneration||!gmAuthority())throw new MusicError('stale');
|
||||||
|
peers.setSource(gmHost.stream);sentInvites.clear();await sendInvites();
|
||||||
|
if(resumeAutomation&&game.settings.get(id,'enabled')&&!result.attachedExistingQueue)start();
|
||||||
|
return result;
|
||||||
|
},
|
||||||
|
async reconnect(){if(!privateProfile||!gmAuthority())throw {code:'denied'};const generation=++connectionGeneration;stop();peers?.reset();sentInvites.clear();await gmHost.close();if(generation!==connectionGeneration)throw {code:'stale'};return connection.connect(privateProfile.target,{resumeAutomation:false});},
|
||||||
|
refresh:()=>gmHost.refreshCatalog(),resume:()=>gmHost.resumeAudio(),setVolume:value=>gmHost.setVolume(value),
|
||||||
|
async playback(){
|
||||||
|
if(!gmAuthority())throw new MusicError('denied');
|
||||||
|
const current=runtime?.controller.current?.playlist;
|
||||||
|
if(current?.provider==='native'){
|
||||||
|
const sound=[...game.playlists.get(current.id)?.sounds??[]].find(sound=>sound.playing);
|
||||||
|
return {source:'Foundry',state:sound?'playing':'idle',title:sound?.name??''};
|
||||||
|
}
|
||||||
|
if(gmHost.connected)return {source:'Music Assistant',...await gmHost.playbackStatus()};
|
||||||
|
return {state:'idle',title:''};
|
||||||
|
},
|
||||||
|
control(action,value){
|
||||||
|
if(!gmAuthority()||!gmHost.connected||runtime?.controller.current?.playlist?.provider==='native')throw new MusicError('denied');
|
||||||
|
return ensureRuntime().controller.control(action,value);
|
||||||
|
},
|
||||||
|
async forgetReceiver(){
|
||||||
|
const scope=privateDraft&&receiverScope(privateDraft);
|
||||||
|
await connection.disconnect();
|
||||||
|
await game.settings.set(id,'savedConnection',{});
|
||||||
|
if(scope)await receiverVault.forget(scope);
|
||||||
|
},
|
||||||
|
async disconnect(){connectionGeneration++;stop();peers?.reset();sentInvites.clear();privateProfile=null;privateDraft=null;await gmHost.close();}
|
||||||
|
};
|
||||||
function listenWebRTC(invite){
|
function listenWebRTC(invite){
|
||||||
if(game.user.isGM||!peers)throw Error('Listener only');
|
if(game.user.isGM||!peers)throw Error('Listener only');
|
||||||
if(!remoteAudio){remoteAudio=document.createElement('audio');document.body.append(remoteAudio);}
|
ensureRemoteAudio().play().catch(()=>{});listenerState='Connecting to GM audio…';return peers.listen(invite);
|
||||||
remoteAudio.play().catch(()=>{});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',()=>{
|
Hooks.once('init',()=>{
|
||||||
|
game.settings.register(id,'savedConnection',{scope:'user',config:false,type:Object,default:{}});
|
||||||
|
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,'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,'ownedPlaylistIds',{scope:'world',config:false,type:String,default:'',requiresReload:true});
|
||||||
game.settings.register(id,'musicDefaults',{scope:'world',config:false,type:Object,default:{}});
|
game.settings.register(id,'musicDefaults',{scope:'world',config:false,type:Object,default:{}});
|
||||||
if(game.settings.registerMenu){
|
if(game.settings.registerMenu){
|
||||||
// The factory reads live module state when the settings menu is rendered.
|
// 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)},
|
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});
|
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});
|
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 (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,'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:'Native ownership, world/scene assignments, boss overrides, gateway and audio diagnostics.',icon:'fas fa-music',type:Setup,restricted:true});
|
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',()=>{
|
Hooks.once('ready',()=>{
|
||||||
gmHost=new GMAudioHost({authority:gmAuthority});
|
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=>{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){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(gmHost.connected&&!gmAuthority()){stop();gmHost.close();peers.reset();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();
|
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);}
|
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={
|
game.modules.get(id).api={
|
||||||
@@ -52,10 +164,10 @@ Hooks.once('ready',()=>{
|
|||||||
inviteListener:(userId,options)=>peers.invite(userId,options),
|
inviteListener:(userId,options)=>peers.invite(userId,options),
|
||||||
listenWebRTC,
|
listenWebRTC,
|
||||||
peerStats:()=>peers.stats(),
|
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});},
|
async mountConfiguration(document,container){return mountPlaylistConfiguration({document,container,game,choices:await choices(),onError});},
|
||||||
enableAudio(code){return audio.start(gateway.audioRequest(code));},stopAudio:()=>audio.stop(),
|
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();
|
if(game.settings.get(id,'enabled'))start();
|
||||||
});
|
});
|
||||||
@@ -17,16 +17,17 @@ export function musicSelect(dom,choices,current,{nativeOnly=false,empty='Use wor
|
|||||||
const select=dom.createElement('select');
|
const select=dom.createElement('select');
|
||||||
const add=(value,text)=>{const option=dom.createElement('option');option.value=value;option.textContent=text;select.append(option);};
|
const add=(value,text)=>{const option=dom.createElement('option');option.value=value;option.textContent=text;select.append(option);};
|
||||||
add('',empty);
|
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)');
|
const replacement=current?.provider==='ma'&&choices.find(c=>c.provider==='ma'&&c.legacyId===current.id);
|
||||||
select.value=referenceKey(current);return select;
|
if(current&&!replacement&&!choices.some(c=>referenceKey(c)===referenceKey(current)))add(referenceKey(current),'Saved selection (catalog unavailable)');
|
||||||
|
select.value=referenceKey(replacement||current);return select;
|
||||||
}
|
}
|
||||||
export function mountMusicAssignments({document,game,container,choices,defaults=false,onError=()=>{}}){
|
export function mountMusicAssignments({document,game,container,choices,defaults=false,onError=()=>{}}){
|
||||||
if(!game.user?.isGM)return null;
|
if(!game.user?.isGM)return null;
|
||||||
const dom=container.ownerDocument,panel=dom.createElement('fieldset');panel.dataset.adaptiveMusic='assignments';
|
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 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 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={};
|
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);}
|
for(const field of musicFields){const label=dom.createElement('label');label.textContent=labels[field]+' ';const current=previous[field]??(field==='ambient'?previous.playlist:null);controls[field]=musicSelect(dom,choices,current,{nativeOnly:field==='fallback',empty:defaults?(field==='fallback'?'No native fallback':'No world default'):'Use world default / silence'});label.append(controls[field]);panel.append(label);}
|
||||||
const note=dom.createElement('p');note.textContent='One music layer: combat interrupts ambient music. Concurrent ambient layers and crossfade are not implemented. Native AmbientSound and effects remain separate.';panel.append(note);
|
const 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);
|
||||||
|
|||||||
@@ -0,0 +1,101 @@
|
|||||||
|
import {connectionMessage} from './connection-wizard.mjs';
|
||||||
|
import {referenceKey,selection} from '../core/scene-music.mjs';
|
||||||
|
|
||||||
|
const clock=value=>`${Math.floor(value/60)}:${String(value%60).padStart(2,'0')}`;
|
||||||
|
const states={playing:'Playing',paused:'Paused',idle:'Stopped'};
|
||||||
|
|
||||||
|
export function mountPlaybackPanel({game,container,connection,getChoices,start,stop,setOverrides,onError}) {
|
||||||
|
const dom=container.ownerDocument;
|
||||||
|
const make=(tag,text,parent=container)=>{const node=dom.createElement(tag);if(text)node.textContent=text;parent.append(node);return node;};
|
||||||
|
make('h2','Playback');
|
||||||
|
const now=make('section');now.className='adaptive-now';
|
||||||
|
const state=make('p','Stopped',now);state.className='adaptive-state';
|
||||||
|
const track=make('h3','Nothing playing',now);
|
||||||
|
const timing=make('p',null,now);
|
||||||
|
const controls=make('div');controls.className='adaptive-actions';
|
||||||
|
const output=make('div');output.className='adaptive-fields';
|
||||||
|
const volumeLabel=make('label','Campaign volume',output),volume=make('input',null,volumeLabel);
|
||||||
|
volume.type='range';volume.min='0';volume.max='100';volume.value='100';
|
||||||
|
const seekLabel=make('label','Playback position',output),seek=make('input',null,seekLabel);
|
||||||
|
seek.type='range';seek.min='0';seek.max='0';seek.step='1';seek.value='0';
|
||||||
|
const summary=make('div');summary.className='adaptive-playback-summary';
|
||||||
|
const automationText=make('p',null,summary),listeners=make('p',null,summary);
|
||||||
|
const status=make('p');status.setAttribute('role','status');
|
||||||
|
const failure=make('p');failure.setAttribute('role','alert');failure.hidden=true;
|
||||||
|
let trackStatus,refreshing=false,busy=false,volumeEditing=false,seekEditing=false,oldChoices='';
|
||||||
|
|
||||||
|
const button=(parent,label,action)=>{
|
||||||
|
const b=make('button',label,parent);b.type='button';b.addEventListener('click',()=>run(action));return b;
|
||||||
|
};
|
||||||
|
const toggle=button(controls,'Pause',()=>connection.control(trackStatus.state==='playing'?'pause':'resume'));
|
||||||
|
toggle.className='adaptive-primary';
|
||||||
|
const stopTrack=button(controls,'Stop playback',()=>connection.control('stop'));
|
||||||
|
const unlock=button(controls,'Enable GM audio',()=>connection.resume());
|
||||||
|
const automation=button(summary,'Enable automation',async()=>{
|
||||||
|
const enable=!isRunning();
|
||||||
|
if(!enable)stop();
|
||||||
|
await game.settings.set('adaptive-music','enabled',enable);
|
||||||
|
if(enable)await start();
|
||||||
|
status.textContent=enable?'Scene automation enabled.':'Scene automation disabled.';
|
||||||
|
});
|
||||||
|
|
||||||
|
const manual=make('details');make('summary','Manual playlist override',manual);
|
||||||
|
const label=make('label','Override playlist',manual),select=make('select',null,label);
|
||||||
|
const manualActions=make('div',null,manual);manualActions.className='adaptive-actions';
|
||||||
|
button(manualActions,'Apply override',()=>setOverrides([{id:'gm-manual',playlist:selection(select.value,getChoices())}]));
|
||||||
|
button(manualActions,'Clear override',()=>setOverrides([]));
|
||||||
|
function isRunning(){return connection?.status.automationRunning??game.settings.get('adaptive-music','enabled');}
|
||||||
|
|
||||||
|
volume.addEventListener('input',()=>{volumeEditing=true;volume.setAttribute('aria-valuetext',`${volume.value}%`);});
|
||||||
|
volume.addEventListener('change',()=>run(()=>connection.setVolume(Number(volume.value))).finally(()=>{volumeEditing=false;}));
|
||||||
|
seek.addEventListener('input',()=>{seekEditing=true;seek.setAttribute('aria-valuetext',clock(Number(seek.value)));});
|
||||||
|
seek.addEventListener('change',()=>run(()=>connection.control('seek',Number(seek.value))).finally(()=>{seekEditing=false;}));
|
||||||
|
|
||||||
|
async function run(action){
|
||||||
|
if(busy||!game.user.isGM)return;
|
||||||
|
busy=true;failure.hidden=true;render();
|
||||||
|
try{await action();}
|
||||||
|
catch(error){failure.textContent=`Playback action failed. ${connectionMessage(error)}`;failure.hidden=false;onError(error);}
|
||||||
|
finally{busy=false;await refresh();}
|
||||||
|
}
|
||||||
|
function render(){
|
||||||
|
const d=connection?.status??{},connected=d.state==='connected',playing=trackStatus?.state==='playing',paused=trackStatus?.state==='paused';
|
||||||
|
const canControl=connected&&trackStatus?.source==='Music Assistant'&&d.lastError?.code!=='uncertain';
|
||||||
|
state.textContent=states[trackStatus?.state]??(trackStatus?'Playback status unavailable':'Stopped');
|
||||||
|
track.textContent=trackStatus?.title||'Nothing playing';
|
||||||
|
timing.textContent=trackStatus?.duration?`${clock(trackStatus.position)} / ${clock(trackStatus.duration)}`:'';
|
||||||
|
if(!volumeEditing){volume.value=String(d.volume??100);volume.setAttribute('aria-valuetext',`${volume.value}%`);}
|
||||||
|
if(!seekEditing){
|
||||||
|
seek.max=String(Math.max(0,(trackStatus?.duration??0)-1));seek.value=String(Math.min(Number(seek.max),trackStatus?.position??0));
|
||||||
|
seek.setAttribute('aria-valuetext',clock(Number(seek.value)));
|
||||||
|
}
|
||||||
|
toggle.textContent=paused?'Resume':'Pause';toggle.disabled=busy||!canControl||!(playing||paused);
|
||||||
|
stopTrack.disabled=busy||!canControl||!(playing||paused);
|
||||||
|
volume.disabled=busy||!connected;seek.disabled=busy||!canControl||!(playing||paused)||Number(seek.max)<=0;
|
||||||
|
unlock.hidden=!connected||d.audioContext==='running';unlock.disabled=busy;
|
||||||
|
const enabled=isRunning();
|
||||||
|
automationText.textContent=enabled?'Automation active':game.settings.get('adaptive-music','enabled')?'Automation paused':'Automation off';
|
||||||
|
automation.textContent=enabled?'Disable automation':'Enable automation';automation.disabled=busy;
|
||||||
|
const count=d.peers??0;listeners.textContent=`${count} connected ${count===1?'listener':'listeners'}`;
|
||||||
|
if(d.lastError?.code==='uncertain'){
|
||||||
|
failure.textContent=`Queue needs review. ${connectionMessage(d.lastError)}`;failure.hidden=false;
|
||||||
|
}
|
||||||
|
const choices=getChoices();const display=JSON.stringify(choices.map(choice=>[referenceKey(choice),choice.name]));
|
||||||
|
if(display!==oldChoices){
|
||||||
|
const previous=select.value;select.replaceChildren();
|
||||||
|
const empty=make('option','Silence',select);empty.value='';
|
||||||
|
for(const choice of choices){const option=make('option',choice.name,select);option.value=referenceKey(choice);}
|
||||||
|
if(choices.some(choice=>referenceKey(choice)===previous))select.value=previous;
|
||||||
|
oldChoices=display;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async function refresh(){
|
||||||
|
render();if(refreshing||busy)return;
|
||||||
|
refreshing=true;
|
||||||
|
try{trackStatus=await connection?.playback?.();}
|
||||||
|
catch{trackStatus={state:'unavailable'};}
|
||||||
|
finally{refreshing=false;render();}
|
||||||
|
}
|
||||||
|
render();
|
||||||
|
return refresh;
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import {MusicError} from '../core/controller.mjs';
|
||||||
|
// GM browser profile only. A non-extractable key protects the stored receiver
|
||||||
|
// material; same-origin scripts and the browser profile owner remain trusted.
|
||||||
|
// MA access tokens are intentionally excluded from the serialization surface.
|
||||||
|
export class ReceiverVault{
|
||||||
|
#database;#tail=Promise.resolve();
|
||||||
|
async #db(){
|
||||||
|
if(!globalThis.indexedDB)throw new MusicError('private-storage-unavailable');
|
||||||
|
this.#database??=new Promise((resolve,reject)=>{const request=indexedDB.open('adaptive-music-private-receivers',1);request.onupgradeneeded=()=>request.result.createObjectStore('records');request.onsuccess=()=>resolve(request.result);request.onerror=()=>reject(new MusicError('private-storage-unavailable'));request.onblocked=()=>reject(new MusicError('private-storage-unavailable'));});
|
||||||
|
return this.#database;
|
||||||
|
}
|
||||||
|
async #scope({campaign,userId,maUrl}){
|
||||||
|
if(!campaign||!userId)throw new MusicError('denied');
|
||||||
|
return Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',new TextEncoder().encode(JSON.stringify([campaign,userId,new URL(maUrl).origin])))),n=>n.toString(16).padStart(2,'0')).join('');
|
||||||
|
}
|
||||||
|
async #transaction(key,value,remove=false){
|
||||||
|
const db=await this.#db();return new Promise((resolve,reject)=>{
|
||||||
|
const tx=db.transaction('records',value!==undefined||remove?'readwrite':'readonly'),store=tx.objectStore('records');
|
||||||
|
const request=remove?store.delete(key):value!==undefined?store.put(value,key):store.get(key);
|
||||||
|
tx.oncomplete=()=>resolve(request.result);tx.onerror=tx.onabort=()=>reject(new MusicError('private-storage-unavailable'));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
async load(scope){
|
||||||
|
const id=await this.#scope(scope),record=await this.#transaction(id);if(!record)return null;
|
||||||
|
try{
|
||||||
|
const bytes=await crypto.subtle.decrypt({name:'AES-GCM',iv:record.iv,additionalData:new TextEncoder().encode(id)},record.key,record.data);
|
||||||
|
const value=JSON.parse(new TextDecoder().decode(bytes));
|
||||||
|
if(value.version!==1||typeof value.identityStorage?.['sendspin-identity-sk']!=='string')throw Error();return value;
|
||||||
|
}catch{throw new MusicError('private-storage-corrupt');}
|
||||||
|
}
|
||||||
|
save(scope,profile){
|
||||||
|
const op=this.#tail.catch(()=>{}).then(async()=>{
|
||||||
|
const id=await this.#scope(scope),old=await this.#transaction(id);
|
||||||
|
const key=old?.key??await crypto.subtle.generateKey({name:'AES-GCM',length:256},false,['encrypt','decrypt']);
|
||||||
|
const value={version:1,identityStorage:profile.identityStorage,targetName:profile.targetName,catalogKey:profile.catalogKey,namespace:profile.namespace};
|
||||||
|
const bytes=new TextEncoder().encode(JSON.stringify(value));if(bytes.length>65536||!value.identityStorage?.['sendspin-identity-sk'])throw new MusicError('denied');
|
||||||
|
const iv=crypto.getRandomValues(new Uint8Array(12)),data=await crypto.subtle.encrypt({name:'AES-GCM',iv,additionalData:new TextEncoder().encode(id)},key,bytes);
|
||||||
|
await this.#transaction(id,{key,iv,data});
|
||||||
|
});this.#tail=op;return op;
|
||||||
|
}
|
||||||
|
async forget(scope){await this.#tail.catch(()=>{});await this.#transaction(await this.#scope(scope),undefined,true);}
|
||||||
|
}
|
||||||
+10
-4
@@ -5,15 +5,21 @@ export const primaryGM = users => [...users].filter(u => u.active && u.isGM)
|
|||||||
.sort((a,b) => a.id.localeCompare(b.id))[0]?.id;
|
.sort((a,b) => a.id.localeCompare(b.id))[0]?.id;
|
||||||
// Explicit development bootstrap. No hooks or document mutations occur on import.
|
// Explicit development bootstrap. No hooks or document mutations occur on import.
|
||||||
// All music configuration uses module-owned flags; no actor/system schema access.
|
// All music configuration uses module-owned flags; no actor/system schema access.
|
||||||
export function startNativeRuntime({ game, Hooks, campaign, session, ownedPlaylistIds, maProvider, onError = () => {} }) {
|
export function startNativeRuntime({ game, Hooks, campaign, session, ownedPlaylistIds, maProvider,
|
||||||
|
isEnabled = () => true, authority = () => game.ready && primaryGM(game.users) === game.user.id,
|
||||||
|
previousController, onError = () => {} }) {
|
||||||
const flag = d => d?.getFlag('adaptive-music', 'music');
|
const flag = d => d?.getFlag('adaptive-music', 'music');
|
||||||
const provider = new NativeProvider({ playlists: game.playlists, ownedPlaylistIds, campaign, session,
|
const provider = new NativeProvider({ playlists: game.playlists, ownedPlaylistIds, campaign, session,
|
||||||
sceneConflict: id => [...game.scenes].some(s => s.active && (s.playlist?.id ?? s.playlist) === id) });
|
sceneConflict: id => [...game.scenes].some(s => s.active && (s.playlist?.id ?? s.playlist) === id) });
|
||||||
const controller = new MusicController({ campaign, session, providers: { native: provider,...(maProvider?{ma:maProvider}:{}) },
|
const controller = new MusicController({ campaign, session, providers: { native: provider,...(maProvider?{ma:maProvider}:{}) },
|
||||||
authority: () => game.ready && primaryGM(game.users) === game.user.id });
|
authority });
|
||||||
|
if (previousController) {
|
||||||
|
controller.generation = previousController.generation;
|
||||||
|
controller.tail = previousController.tail;
|
||||||
|
}
|
||||||
let overrides = [];
|
let overrides = [];
|
||||||
const refresh = () => {
|
const refresh = () => {
|
||||||
if (!game.ready || primaryGM(game.users) !== game.user.id) return Promise.resolve();
|
if (!isEnabled() || !authority()) return Promise.resolve();
|
||||||
const scene = [...game.scenes].find(s => s.active);
|
const scene = [...game.scenes].find(s => s.active);
|
||||||
const defaults=game.settings.get('adaptive-music','musicDefaults')??{};
|
const defaults=game.settings.get('adaptive-music','musicDefaults')??{};
|
||||||
const choose=(ref,fallback)=>ref?.provider==='ma'&&!maProvider?.supports(ref)?fallback??null:ref;
|
const choose=(ref,fallback)=>ref?.provider==='ma'&&!maProvider?.supports(ref)?fallback??null:ref;
|
||||||
@@ -30,6 +36,6 @@ export function startNativeRuntime({ game, Hooks, campaign, session, ownedPlayli
|
|||||||
const subscriptions = events.map(event => [event, Hooks.on(event, () => refresh().catch(onError))]);
|
const subscriptions = events.map(event => [event, Hooks.on(event, () => refresh().catch(onError))]);
|
||||||
return { controller, refresh,
|
return { controller, refresh,
|
||||||
setOverrides: value => { overrides = structuredClone(value); return refresh(); },
|
setOverrides: value => { overrides = structuredClone(value); return refresh(); },
|
||||||
dispose: () => { for (const [event,id] of subscriptions) Hooks.off(event,id); controller.generation++; controller.abort?.abort(); }
|
dispose: () => { for (const [event,id] of subscriptions) Hooks.off(event,id); controller.cancel(); }
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
+130
-48
@@ -1,65 +1,147 @@
|
|||||||
|
import {mountConnectionWizard,connectionMessage} from './connection-wizard.mjs';
|
||||||
import {MusicError} from '../core/controller.mjs';
|
import {MusicError} from '../core/controller.mjs';
|
||||||
import {selection} from '../core/scene-music.mjs';
|
import {mountMusicAssignments,mountBossEditor} from './music-editor.mjs';
|
||||||
import {mountMusicAssignments,mountBossEditor,musicSelect} from './music-editor.mjs';
|
import {mountPlaybackPanel} from './playback-panel.mjs';
|
||||||
export function createSetupClass({game,gateway,audio,getChoices,start,stop,setOverrides,onError,canConnect=()=>true,Base=globalThis.foundry.applications.api.ApplicationV2}){
|
|
||||||
|
const namespace='adaptive-music';
|
||||||
|
const tabs=[['connection','Connection'],['scene','Scene Music'],['playback','Playback']];
|
||||||
|
|
||||||
|
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 {
|
return class AdaptiveMusicSetup extends Base {
|
||||||
static DEFAULT_OPTIONS={id:'adaptive-music-setup',window:{title:'Adaptive Music setup'},position:{width:640,height:'auto'}};
|
static DEFAULT_OPTIONS={id:'adaptive-music-setup',window:{title:'Adaptive Music',resizable:true},position:{width:760,height:620}};
|
||||||
|
#tab='connection';
|
||||||
|
#scene;
|
||||||
|
#timer;
|
||||||
|
|
||||||
async _renderHTML(){
|
async _renderHTML(){
|
||||||
if(!game.user.isGM)throw new MusicError('denied');
|
if(!game.user.isGM)throw new MusicError('denied');
|
||||||
const dom=globalThis.document,root=dom.createElement('div');root.className='adaptive-music-setup';
|
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 make=(tag,text,parent=root)=>{const node=dom.createElement(tag);if(text)node.textContent=text;parent.append(node);return node;};
|
||||||
const status=text('Automation is opt-in. Configure dedicated music playlists and assignments before enabling it.');status.setAttribute('role','status');
|
const nav=make('div');nav.className='adaptive-tabs';nav.setAttribute('role','tablist');nav.setAttribute('aria-label','Adaptive Music setup');
|
||||||
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 panels=new Map();
|
||||||
const owned=new Set(game.settings.get('adaptive-music','ownedPlaylistIds').split(',').filter(Boolean));
|
let refreshPlayback=()=>{};
|
||||||
const boxes=[];const ownedPanel=dom.createElement('fieldset');const legend=dom.createElement('legend');legend.textContent='Dedicated native music playlists';ownedPanel.append(legend);
|
const switchTab=(id,focus=false)=>{
|
||||||
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);
|
this.#tab=id;
|
||||||
text('Opt in only dedicated music playlists. Do not select AmbientSound, effects or shared playlists. Saving ownership disables automation and requires a reload.');
|
for(const [key,{tab,panel}] of panels){
|
||||||
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 selected=key===id;tab.setAttribute('aria-selected',String(selected));tab.tabIndex=selected?0:-1;panel.hidden=!selected;
|
||||||
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.');
|
if(focus)panels.get(id).tab.focus?.();
|
||||||
const diagnostics=text('Gateway disconnected. Owned native playlists work without it.');
|
if(id==='playback')void refreshPlayback();
|
||||||
const assignmentRoot=dom.createElement('div');
|
|
||||||
const show=()=>{const d=gateway.status;diagnostics.textContent=d?`Target: ${d.target}. Playback authorization: ${d.playbackEnabled?'enabled for approved test IDs':'disabled'}. Audio: ${d.audioSource} (test transport only). Sendspin receiver: unavailable. Crossfade: unavailable.`:'Gateway disconnected. Owned native fallback is available.';};
|
|
||||||
button('Connect and load MA catalog',async()=>{if(!canConnect())throw new MusicError('denied');const value=code.value;code.value='';await gateway.connect(value);show();await renderAssignments();});
|
|
||||||
button('Refresh connection diagnostics',async()=>{await gateway.refresh();show();await renderAssignments();});
|
|
||||||
button('Disconnect gateway',async()=>{await gateway.disconnect();show();status.textContent='Gateway disconnected. Existing MA playback, if any, is retained; automatic fallback cannot bypass an unreachable owned target.';});
|
|
||||||
const renderAssignments=async()=>{
|
|
||||||
assignmentRoot.replaceChildren();const choices=await getChoices();
|
|
||||||
mountMusicAssignments({game,container:assignmentRoot,choices,defaults:true,onError});
|
|
||||||
const sceneLabel=dom.createElement('label');sceneLabel.textContent='Scene ';const scenes=dom.createElement('select');
|
|
||||||
for(const scene of game.scenes){const option=dom.createElement('option');option.value=scene.id;option.textContent=scene.name;scenes.append(option);}sceneLabel.append(scenes);assignmentRoot.append(sceneLabel);
|
|
||||||
const scenePanel=dom.createElement('div');assignmentRoot.append(scenePanel);
|
|
||||||
const showScene=()=>{scenePanel.replaceChildren();const scene=game.scenes.get(scenes.value);if(scene)mountMusicAssignments({document:scene,game,container:scenePanel,choices,onError});};
|
|
||||||
const active=[...game.scenes].find(s=>s.active);if(active)scenes.value=active.id;scenes.addEventListener('change',showScene);showScene();
|
|
||||||
const bossLabel=dom.createElement('label');bossLabel.textContent='Boss combatant ';const bosses=dom.createElement('select'),documents=new Map();
|
|
||||||
for(const combat of game.combats)for(const combatant of combat.combatants){const option=dom.createElement('option');option.value=combat.id+':'+combatant.id;option.textContent=combatant.name??combatant.id;documents.set(option.value,combatant);bosses.append(option);}bossLabel.append(bosses);assignmentRoot.append(bossLabel);
|
|
||||||
const bossPanel=dom.createElement('div');assignmentRoot.append(bossPanel);const showBoss=()=>{bossPanel.replaceChildren();const document=documents.get(bosses.value);if(document)mountBossEditor({document,game,container:bossPanel,choices,onError});};bosses.addEventListener('change',showBoss);showBoss();
|
|
||||||
const manual=musicSelect(dom,choices,null,{empty:'Silence'});manual.setAttribute('aria-label','Manual music override');assignmentRoot.append(manual);
|
|
||||||
for(const [label,action]of [['Apply manual override',()=>setOverrides([{id:'gm-manual',playlist:selection(manual.value,choices)}])],['Clear manual override',()=>setOverrides([])]]){const b=dom.createElement('button');b.type='button';b.textContent=label;b.addEventListener('click',()=>Promise.resolve().then(action).catch(onError));assignmentRoot.append(b);}
|
|
||||||
};
|
};
|
||||||
await renderAssignments();root.append(assignmentRoot);
|
for(const [index,[id,label]] of tabs.entries()){
|
||||||
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);
|
const tab=make('button',label,nav);tab.type='button';tab.id=`adaptive-tab-${id}`;tab.setAttribute('role','tab');
|
||||||
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 panel=make('section');panel.className='adaptive-panel';panel.id=`adaptive-panel-${id}`;panel.setAttribute('role','tabpanel');
|
||||||
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);
|
tab.setAttribute('aria-controls',panel.id);panel.setAttribute('aria-labelledby',tab.id);
|
||||||
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.');
|
tab.addEventListener('click',()=>switchTab(id));
|
||||||
// Start directly in the click task so AudioContext.resume retains user activation.
|
tab.addEventListener('keydown',event=>{
|
||||||
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);
|
const positions={ArrowRight:(index+1)%tabs.length,ArrowLeft:(index+tabs.length-1)%tabs.length,Home:0,End:tabs.length-1};
|
||||||
button('Stop test audio',()=>audio.stop());show();return root;
|
if(!Object.hasOwn(positions,event.key))return;
|
||||||
|
event.preventDefault();switchTab(tabs[positions[event.key]][0],true);
|
||||||
|
});
|
||||||
|
panels.set(id,{tab,panel});
|
||||||
|
}
|
||||||
|
const connectionPanel=panels.get('connection').panel,scenePanel=panels.get('scene').panel,playbackPanel=panels.get('playback').panel;
|
||||||
|
const button=(parent,label,action,status,className)=>{
|
||||||
|
const b=make('button',label,parent);b.type='button';if(className)b.className=className;
|
||||||
|
b.addEventListener('click',async()=>{
|
||||||
|
if(!game.user.isGM||b.disabled)return;
|
||||||
|
b.disabled=true;
|
||||||
|
try{await action();}catch(error){if(status)status.textContent=connectionMessage(error);onError(error);}finally{b.disabled=false;}
|
||||||
|
});return b;
|
||||||
|
};
|
||||||
|
const addOption=(select,value,label)=>{const option=make('option',label,select);option.value=value;return option;};
|
||||||
|
|
||||||
|
make('h2','Assign scene music',scenePanel);
|
||||||
|
const sceneLabel=make('label','Scene',scenePanel),scenes=make('select',null,sceneLabel);
|
||||||
|
for(const scene of game.scenes)addOption(scenes,scene.id,scene.name);
|
||||||
|
const selected=game.scenes.get(this.#scene)??[...game.scenes].find(scene=>scene.active);
|
||||||
|
if(selected)scenes.value=selected.id;
|
||||||
|
const assignments=make('div',null,scenePanel);
|
||||||
|
const sceneActions=make('div',null,scenePanel);sceneActions.className='adaptive-actions';
|
||||||
|
button(sceneActions,'Go to Playback',()=>switchTab('playback',true));
|
||||||
|
const defaults=make('details',null,scenePanel);make('summary','World defaults and boss combatants',defaults);
|
||||||
|
const defaultBody=make('div',null,defaults),bossLabel=make('label','Boss combatant',defaults);
|
||||||
|
const bosses=make('select',null,bossLabel),bossBody=make('div',null,defaults),documents=new Map();
|
||||||
|
for(const combat of game.combats??[])for(const combatant of combat.combatants){
|
||||||
|
const key=`${combat.id}:${combatant.id}`;documents.set(key,combatant);addOption(bosses,key,combatant.name??combatant.id);
|
||||||
|
}
|
||||||
|
if(!documents.size){bossLabel.hidden=true;make('p','Create a combatant to assign a boss override.',defaults);}
|
||||||
|
const ownedDetails=make('details',null,scenePanel);make('summary','Foundry fallback playlists',ownedDetails);
|
||||||
|
make('p','Select dedicated music playlists for fallback playback. After saving ownership, reload the world before enabling automation.',ownedDetails);
|
||||||
|
const owned=new Set(game.settings.get(namespace,'ownedPlaylistIds').split(',').filter(Boolean)),boxes=[];
|
||||||
|
const ownedChoices=make('div',null,ownedDetails);ownedChoices.className='adaptive-checklist';
|
||||||
|
for(const playlist of game.playlists){
|
||||||
|
const label=make('label',null,ownedChoices),check=make('input',null,label);check.type='checkbox';check.checked=owned.has(playlist.id);
|
||||||
|
make('span',playlist.name,label);boxes.push({id:playlist.id,check});
|
||||||
|
}
|
||||||
|
const ownershipStatus=make('p',null,ownedDetails);ownershipStatus.setAttribute('role','status');
|
||||||
|
button(ownedDetails,'Save fallback ownership',async()=>{
|
||||||
|
stop();await game.settings.set(namespace,'enabled',false);
|
||||||
|
await game.settings.set(namespace,'ownedPlaylistIds',boxes.filter(box=>box.check.checked).map(box=>box.id).join(','));
|
||||||
|
ownershipStatus.textContent='Ownership saved. Reload this world before enabling automation.';
|
||||||
|
},ownershipStatus);
|
||||||
|
|
||||||
|
let choices=[];
|
||||||
|
const showScene=()=>{
|
||||||
|
this.#scene=scenes.value;assignments.replaceChildren();const scene=game.scenes.get(scenes.value);
|
||||||
|
if(scene)mountMusicAssignments({document:scene,game,container:assignments,choices,onError});
|
||||||
|
else make('p','Create a scene to assign its playlists.',assignments);
|
||||||
|
};
|
||||||
|
const showBoss=()=>{
|
||||||
|
bossBody.replaceChildren();const document=documents.get(bosses.value);
|
||||||
|
if(document)mountBossEditor({document,game,container:bossBody,choices,onError});
|
||||||
|
};
|
||||||
|
const refreshAssignments=async()=>{
|
||||||
|
choices=await getChoices();showScene();showBoss();defaultBody.replaceChildren();
|
||||||
|
mountMusicAssignments({game,container:defaultBody,choices,defaults:true,onError});
|
||||||
|
};
|
||||||
|
scenes.addEventListener('change',showScene);bosses.addEventListener('change',showBoss);
|
||||||
|
await refreshAssignments();
|
||||||
|
|
||||||
|
let development;
|
||||||
|
if(game.settings.get(namespace,'advancedDevelopment')===true){
|
||||||
|
development=dom.createElement('section');make('h3','Optional companion',development);
|
||||||
|
const label=make('label','Companion controller code',development),code=make('input',null,label);code.type='password';code.autocomplete='off';
|
||||||
|
const status=make('p',null,development);status.setAttribute('role','status');
|
||||||
|
button(development,'Connect optional companion',async()=>{if(!canConnect())throw new MusicError('denied');const value=code.value;code.value='';await gateway.connect(value);await refreshAssignments();},status);
|
||||||
|
button(development,'Disconnect optional companion',async()=>{await gateway.disconnect();await refreshAssignments();},status);
|
||||||
|
const capabilityLabel=make('label','Companion test capability',development),capability=make('input',null,capabilityLabel);capability.type='password';
|
||||||
|
button(development,'Enable synthetic test audio',async()=>{const value=JSON.parse(capability.value);capability.value='';await audio.start(gateway.audioRequest(value));},status);
|
||||||
|
button(development,'Stop test audio',()=>audio.stop(),status);
|
||||||
|
}
|
||||||
|
const refreshConnection=connection?mountConnectionWizard({game,container:connectionPanel,connection,onCatalog:refreshAssignments,onError,next:()=>switchTab('scene',true),advancedContent:development}):()=>{};
|
||||||
|
refreshPlayback=mountPlaybackPanel({game,container:playbackPanel,connection,getChoices:()=>choices,start,stop,setOverrides,onError});
|
||||||
|
switchTab(this.#tab);
|
||||||
|
clearInterval(this.#timer);
|
||||||
|
if(globalThis.document===dom&&typeof root.isConnected==='boolean'){
|
||||||
|
this.#timer=setInterval(()=>{
|
||||||
|
if(!root.isConnected)return;
|
||||||
|
if(this.#tab==='connection')refreshConnection();
|
||||||
|
if(this.#tab==='playback')void refreshPlayback();
|
||||||
|
},1500);
|
||||||
|
}
|
||||||
|
return root;
|
||||||
}
|
}
|
||||||
_replaceHTML(result,content){content.replaceChildren(result);}
|
_replaceHTML(result,content){content.replaceChildren(result);}
|
||||||
|
_onClose(...args){clearInterval(this.#timer);super._onClose?.(...args);}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
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 {
|
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(){
|
async _renderHTML(){
|
||||||
const dom=globalThis.document,root=dom.createElement('div');root.className='adaptive-music-setup';
|
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 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 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');status.textContent=listenerStatus();root.append(status);
|
||||||
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',()=>{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 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();status.textContent='Audio stopped. Select Enable Audio to reconnect.';});root.append(stop);
|
||||||
const stop=dom.createElement('button');stop.type='button';stop.textContent='Stop Audio';stop.addEventListener('click',()=>{stopWebRTC();audio.stop();});root.append(stop);return root;
|
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);}
|
_replaceHTML(result,content){content.replaceChildren(result);}
|
||||||
};
|
};
|
||||||
|
|||||||
+35
-15
@@ -2,8 +2,8 @@ import {randomKey,hmac,base64url} from './webcrypto.mjs';
|
|||||||
import { MusicError } from '../../core/controller.mjs';
|
import { MusicError } from '../../core/controller.mjs';
|
||||||
// Shared trusted-GM/optional-companion transport. Never construct with MA credentials on a player client.
|
// Shared trusted-GM/optional-companion transport. Never construct with MA credentials on a player client.
|
||||||
export class MAReadClient {
|
export class MAReadClient {
|
||||||
#base; #token; #target; #fetch; #providers; #catalog = new Map(); #catalogKey; #campaign; #expectedName; #expectedProvider; #writes = Promise.resolve(); #synthetic; #uncertain = false; #authorizedMedia = new Set(); #targetVolume;
|
#base; #token; #target; #fetch; #providers; #catalog = new Map(); #catalogKey; #legacyCatalogKey; #campaign; #expectedName; #expectedProvider; #writes = Promise.resolve(); #synthetic; #uncertain; #authorizedMedia = new Set(); #targetVolume; #nativePause;
|
||||||
constructor({ baseUrl, token, target, approvedProviders = [], catalogKey = randomKey(), campaign = 'default', expectedName, expectedProvider, syntheticSequences = {}, fetchImpl = fetch }) {
|
constructor({ baseUrl, token, target, approvedProviders = [], catalogKey = randomKey(), legacyCatalogKey, campaign = 'default', expectedName, expectedProvider, syntheticSequences = {}, fetchImpl = fetch }) {
|
||||||
const url = new URL(baseUrl);
|
const url = new URL(baseUrl);
|
||||||
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password ||
|
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password ||
|
||||||
url.search || url.hash || url.pathname !== '/' || typeof token !== 'string' || !token ||
|
url.search || url.hash || url.pathname !== '/' || typeof token !== 'string' || !token ||
|
||||||
@@ -13,6 +13,7 @@ export class MAReadClient {
|
|||||||
if (!(catalogKey instanceof Uint8Array) || catalogKey.length !== 32 || !campaign) throw new MusicError('denied');
|
if (!(catalogKey instanceof Uint8Array) || catalogKey.length !== 32 || !campaign) throw new MusicError('denied');
|
||||||
this.#providers = [...new Set(approvedProviders)];
|
this.#providers = [...new Set(approvedProviders)];
|
||||||
this.#catalogKey = Uint8Array.from(catalogKey); this.#campaign = campaign;
|
this.#catalogKey = Uint8Array.from(catalogKey); this.#campaign = campaign;
|
||||||
|
if (legacyCatalogKey) this.#legacyCatalogKey = Uint8Array.from(legacyCatalogKey);
|
||||||
if(!syntheticSequences || typeof syntheticSequences!=='object' || Object.values(syntheticSequences).some(v=>!Array.isArray(v)||!v.length||v.length>5000||v.some(uri=>typeof uri!=='string'||!uri.startsWith('builtin://track/http://'))))throw new MusicError('denied');
|
if(!syntheticSequences || typeof syntheticSequences!=='object' || Object.values(syntheticSequences).some(v=>!Array.isArray(v)||!v.length||v.length>5000||v.some(uri=>typeof uri!=='string'||!uri.startsWith('builtin://track/http://'))))throw new MusicError('denied');
|
||||||
this.#synthetic = structuredClone(syntheticSequences);
|
this.#synthetic = structuredClone(syntheticSequences);
|
||||||
for(const uri of Object.values(this.#synthetic).flat())this.#authorizedMedia.add(uri);
|
for(const uri of Object.values(this.#synthetic).flat())this.#authorizedMedia.add(uri);
|
||||||
@@ -21,7 +22,7 @@ export class MAReadClient {
|
|||||||
async #read(command, args, messageId = 'adaptive-music-read') {
|
async #read(command, args, messageId = 'adaptive-music-read') {
|
||||||
try {
|
try {
|
||||||
const response = await this.#fetch(`${this.#base}/api`, { method: 'POST', redirect: 'error',
|
const response = await this.#fetch(`${this.#base}/api`, { method: 'POST', redirect: 'error',
|
||||||
signal: AbortSignal.timeout(5000), headers: { Authorization: `Bearer ${this.#token}`, 'Content-Type': 'application/json' },
|
signal: AbortSignal.timeout(['player_queues/play_media','player_queues/play_index'].includes(command)?60000:10000), headers: { Authorization: `Bearer ${this.#token}`, 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify({ message_id: messageId, command, args }) });
|
body: JSON.stringify({ message_id: messageId, command, args }) });
|
||||||
if (!response.ok) throw new MusicError(response.status === 403 ? 'denied' : 'unavailable');
|
if (!response.ok) throw new MusicError(response.status === 403 ? 'denied' : 'unavailable');
|
||||||
const reader = response.body?.getReader();
|
const reader = response.body?.getReader();
|
||||||
@@ -39,18 +40,29 @@ export class MAReadClient {
|
|||||||
const body = new TextDecoder().decode(bytes);
|
const body = new TextDecoder().decode(bytes);
|
||||||
return body ? JSON.parse(body) : null;
|
return body ? JSON.parse(body) : null;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw new MusicError(error instanceof MusicError ? error.code : 'unavailable');
|
if(error instanceof MusicError)throw error;throw new MusicError('unavailable');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
async getOwnedQueue(target) {
|
async getOwnedQueue(target, {checkRegistration} = {}) {
|
||||||
if (target !== this.#target) throw new MusicError('denied');
|
if (target !== this.#target) throw new MusicError('denied');
|
||||||
const queue = await this.#read('player_queues/get', { queue_id: this.#target });
|
const args = {queue_id: this.#target};
|
||||||
|
let queue = await this.#read('player_queues/get', args);
|
||||||
|
if (checkRegistration && queue === null) {
|
||||||
|
// MA publishes the player before its saved queue finishes loading.
|
||||||
|
const deadline = performance.now() + 5000;
|
||||||
|
while (queue === null && performance.now() < deadline) {
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 250));
|
||||||
|
checkRegistration();
|
||||||
|
queue = await this.#read('player_queues/get', args);
|
||||||
|
}
|
||||||
|
if (queue === null) throw new MusicError('receiver-queue-unavailable');
|
||||||
|
}
|
||||||
if (queue?.queue_id !== this.#target || queue.active !== true) throw new MusicError('denied');
|
if (queue?.queue_id !== this.#target || queue.active !== true) throw new MusicError('denied');
|
||||||
return { state: queue.state, items: queue.items };
|
return { state: queue.state, items: queue.items };
|
||||||
}
|
}
|
||||||
async verifyTarget({allowUnavailable=false}={}) {
|
async verifyTarget({allowUnavailable=false,checkRegistration}={}) {
|
||||||
if(!allowUnavailable && this.#expectedName && this.#expectedProvider){
|
if(!allowUnavailable && this.#expectedName && this.#expectedProvider){
|
||||||
await this.getOwnedQueue(this.#target);
|
await this.getOwnedQueue(this.#target,{checkRegistration});
|
||||||
const active=await this.#read('player_queues/get_active_queue',{player_id:this.#target});
|
const active=await this.#read('player_queues/get_active_queue',{player_id:this.#target});
|
||||||
if(active?.queue_id!==this.#target)throw new MusicError('denied');
|
if(active?.queue_id!==this.#target)throw new MusicError('denied');
|
||||||
}
|
}
|
||||||
@@ -61,9 +73,11 @@ export class MAReadClient {
|
|||||||
!player.provider?.startsWith('sendspin') || player.active_group || player.synced_to ||
|
!player.provider?.startsWith('sendspin') || player.active_group || player.synced_to ||
|
||||||
['group_members','group_childs','static_group_members'].some(k => !Array.isArray(player[k]) || player[k].some(id => id !== this.#target))) throw new MusicError('denied');
|
['group_members','group_childs','static_group_members'].some(k => !Array.isArray(player[k]) || player[k].some(id => id !== this.#target))) throw new MusicError('denied');
|
||||||
if(!allowUnavailable&&(!this.#expectedName || !this.#expectedProvider))await this.getOwnedQueue(this.#target);
|
if(!allowUnavailable&&(!this.#expectedName || !this.#expectedProvider))await this.getOwnedQueue(this.#target);
|
||||||
|
this.#nativePause=Array.isArray(player.supported_features)?player.supported_features.includes('pause'):undefined;
|
||||||
this.#targetVolume=Number.isFinite(player.volume_level)&&typeof player.volume_muted==='boolean'?{volume:Math.min(100,Math.max(0,player.volume_level)),muted:player.volume_muted}:null;
|
this.#targetVolume=Number.isFinite(player.volume_level)&&typeof player.volume_muted==='boolean'?{volume:Math.min(100,Math.max(0,player.volume_level)),muted:player.volume_muted}:null;
|
||||||
return { dedicated: true, available: player.available===true, standalone: true };
|
return { dedicated: true, available: player.available===true, standalone: true };
|
||||||
}
|
}
|
||||||
|
supportsNativePause(){return this.#nativePause;}
|
||||||
targetVolumeState(){if(!this.#targetVolume)throw new MusicError('unsupported');return {...this.#targetVolume};}
|
targetVolumeState(){if(!this.#targetVolume)throw new MusicError('unsupported');return {...this.#targetVolume};}
|
||||||
async catalog() {
|
async catalog() {
|
||||||
if (!this.#providers.length) throw new MusicError('denied');
|
if (!this.#providers.length) throw new MusicError('denied');
|
||||||
@@ -83,8 +97,9 @@ export class MAReadClient {
|
|||||||
const key = JSON.stringify([type, mapping.provider_instance, mapping.item_id]);
|
const key = JSON.stringify([type, mapping.provider_instance, mapping.item_id]);
|
||||||
if (next.has(key)) continue;
|
if (next.has(key)) continue;
|
||||||
const id = base64url(await hmac(this.#catalogKey,JSON.stringify([this.#campaign,key])));
|
const id = base64url(await hmac(this.#catalogKey,JSON.stringify([this.#campaign,key])));
|
||||||
next.set(key, { id, type, provider: mapping.provider_instance, itemId: mapping.item_id, dynamic: item.is_dynamic === true });
|
const legacyId = this.#legacyCatalogKey && base64url(await hmac(this.#legacyCatalogKey,JSON.stringify([this.#campaign,key])));
|
||||||
choices.push({ provider: 'ma', id, kind: type, name: item.name.replace(/[\x00-\x1f\x7f]/g,'').slice(0,160) });
|
next.set(key, { id, legacyId, type, provider: mapping.provider_instance, itemId: mapping.item_id, dynamic: item.is_dynamic === true });
|
||||||
|
choices.push({ provider: 'ma', id, ...(legacyId && {legacyId}), kind: type, name: item.name.replace(/[\x00-\x1f\x7f]/g,'').slice(0,160) });
|
||||||
}
|
}
|
||||||
if (page.length < 100) { complete = true; break; }
|
if (page.length < 100) { complete = true; break; }
|
||||||
}
|
}
|
||||||
@@ -95,7 +110,7 @@ export class MAReadClient {
|
|||||||
}
|
}
|
||||||
resolveCatalog(ref) {
|
resolveCatalog(ref) {
|
||||||
if (ref?.provider !== 'ma') throw new MusicError('denied');
|
if (ref?.provider !== 'ma') throw new MusicError('denied');
|
||||||
const entry = [...this.#catalog.values()].find(e => e.id === ref.id);
|
const entry = [...this.#catalog.values()].find(e => e.id === ref.id || e.legacyId && e.legacyId === ref.id);
|
||||||
if (!entry) throw new MusicError('expired-media');
|
if (!entry) throw new MusicError('expired-media');
|
||||||
if(entry.dynamic)throw new MusicError('unsupported');
|
if(entry.dynamic)throw new MusicError('unsupported');
|
||||||
const uri=`${entry.provider}://${entry.type}/${entry.itemId}`;this.#authorizedMedia.add(uri);return uri;
|
const uri=`${entry.provider}://${entry.type}/${entry.itemId}`;this.#authorizedMedia.add(uri);return uri;
|
||||||
@@ -110,7 +125,7 @@ export class MAReadClient {
|
|||||||
await this.inspectSynthetic(media);
|
await this.inspectSynthetic(media);
|
||||||
return media;
|
return media;
|
||||||
}
|
}
|
||||||
const entry=[...this.#catalog.values()].find(e=>e.id===ref.id);
|
const entry=[...this.#catalog.values()].find(e=>e.id===ref.id || e.legacyId && e.legacyId===ref.id);
|
||||||
if(entry.type==='radio')return media;
|
if(entry.type==='radio')return media;
|
||||||
const playlist=await this.#read('music/playlists/get',{item_id:entry.itemId,provider_instance_id_or_domain:entry.provider,allow_update_metadata:false});
|
const playlist=await this.#read('music/playlists/get',{item_id:entry.itemId,provider_instance_id_or_domain:entry.provider,allow_update_metadata:false});
|
||||||
if(playlist?.is_dynamic!==false)throw new MusicError('unsupported');
|
if(playlist?.is_dynamic!==false)throw new MusicError('unsupported');
|
||||||
@@ -166,13 +181,18 @@ export class MAReadClient {
|
|||||||
const captured = structuredClone(args);
|
const captured = structuredClone(args);
|
||||||
const operation = this.#writes.catch(() => {}).then(async () => {
|
const operation = this.#writes.catch(() => {}).then(async () => {
|
||||||
ctx.check();
|
ctx.check();
|
||||||
if(this.#uncertain)throw new MusicError('uncertain');
|
if(this.#uncertain)throw this.#uncertain;
|
||||||
const queue = await this.queueState();
|
const queue = await this.queueState();
|
||||||
if (queue.is_dynamic !== false || queue.autoplay_enabled !== false || queue.dont_stop_the_music_enabled !== false || queue.overlay_enabled !== false || queue.playback_speed !== 1) throw new MusicError('unsupported');
|
if (queue.is_dynamic !== false || queue.autoplay_enabled !== false || queue.dont_stop_the_music_enabled !== false || queue.overlay_enabled !== false || queue.playback_speed !== 1) throw new MusicError('unsupported');
|
||||||
await this.verifyTarget();
|
await this.verifyTarget();
|
||||||
ctx.check(); // Recheck authority after all reads, immediately before dispatch.
|
ctx.check(); // Recheck authority after all reads, immediately before dispatch.
|
||||||
try{await this.#read(`player_queues/${action}`, {...captured,queue_id:this.#target},`adaptive-music-write-${crypto.randomUUID()}`);}
|
const command = `player_queues/${action}`;
|
||||||
catch{this.#uncertain=true;throw new MusicError('uncertain');}
|
try{await this.#read(command, {...captured,queue_id:this.#target},`adaptive-music-write-${crypto.randomUUID()}`);}
|
||||||
|
catch(error){
|
||||||
|
const failure=new MusicError('uncertain');
|
||||||
|
failure.command=command;failure.upstreamCode=error.upstreamCode;failure.translationKey=error.translationKey;
|
||||||
|
this.#uncertain=failure;throw failure;
|
||||||
|
}
|
||||||
ctx.check();
|
ctx.check();
|
||||||
});
|
});
|
||||||
this.#writes = operation;
|
this.#writes = operation;
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
// Token-free transport checks. Browser WebSocket APIs intentionally hide HTTP/TLS
|
||||||
|
// failure details; never turn an opaque failure into a claimed root cause.
|
||||||
|
export async function probeWebSockets(baseUrl,{createSocket=url=>new WebSocket(url),events=globalThis.document,timeoutMs=5000}={}){
|
||||||
|
const base=new URL(baseUrl);
|
||||||
|
if(base.username||base.password||base.search||base.hash||base.pathname!=='/'||!['https:','http:'].includes(base.protocol))throw {code:'address-invalid'};
|
||||||
|
if(globalThis.location?.protocol==='https:'&&base.protocol!=='https:')throw {code:'mixed-content'};
|
||||||
|
const results=[];
|
||||||
|
// Sequential, bounded and deliberately unauthenticated. No player or queue commands.
|
||||||
|
for(const path of ['/ws','/sendspin']){
|
||||||
|
const url=new URL(path,base);url.protocol=base.protocol==='https:'?'wss:':'ws:';
|
||||||
|
results.push(await new Promise(resolve=>{
|
||||||
|
let socket,timer,done=false,csp=false;
|
||||||
|
const finish=code=>{if(done)return;done=true;clearTimeout(timer);events?.removeEventListener('securitypolicyviolation',policy);if(socket){socket.onopen=socket.onerror=socket.onclose=null;socket.close();}resolve({path,code});};
|
||||||
|
const policy=event=>{if(event.disposition==='enforce'&&['connect-src','default-src'].includes(event.effectiveDirective)&&event.blockedURI===url.href){csp=true;finish('csp-blocked');}};
|
||||||
|
events?.addEventListener('securitypolicyviolation',policy);
|
||||||
|
timer=setTimeout(()=>finish(csp?'csp-blocked':'upgrade-timeout'),timeoutMs);
|
||||||
|
try{socket=createSocket(url.href);socket.onopen=()=>finish('upgrade-ok');socket.onerror=()=>setTimeout(()=>finish(csp?'csp-blocked':'upgrade-failed'),25);socket.onclose=()=>setTimeout(()=>finish(csp?'csp-blocked':'upgrade-failed'),25);}catch{setTimeout(()=>finish(csp?'csp-blocked':'upgrade-failed'),50);}
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
return results;
|
||||||
|
}
|
||||||
|
export const diagnosticMessage=result=>({
|
||||||
|
'upgrade-ok':'WebSocket upgrade succeeded from this page. Authentication, receiver pairing and audio are still untested.',
|
||||||
|
'csp-blocked':'This page’s enforced Content Security Policy blocked the connection. Ask the Foundry host administrator to allow the exact trusted MA WSS origin in connect-src; retain existing policy restrictions.',
|
||||||
|
'upgrade-timeout':'No WebSocket upgrade within 5 seconds. Check the private route and compare from the MA page. Browser APIs cannot identify DNS, TLS or firewall causes.',
|
||||||
|
'upgrade-failed':'The browser did not expose a successful upgrade. Compare the same check from the MA origin. Check the exact Origin at the reverse proxy and page policy. HTTP status and TLS errors are hidden by browsers; 101 from another client does not prove this path works.'
|
||||||
|
}[result.code]??'Diagnostic unavailable.');
|
||||||
@@ -2,12 +2,27 @@ import {hmac,hex,verifyHmac} from './webcrypto.mjs';
|
|||||||
import { MusicError } from '../../core/controller.mjs';
|
import { MusicError } from '../../core/controller.mjs';
|
||||||
const identity = items => JSON.stringify(items.map(i => i.queue_item_id));
|
const identity = items => JSON.stringify(items.map(i => i.queue_item_id));
|
||||||
export class MAPlaybackProvider {
|
export class MAPlaybackProvider {
|
||||||
#client; #campaign; #session; #fence; #authority; #key; #generation = 0; #prepared = new WeakMap(); #operations = new Map(); #epoch = 0;
|
#client; #campaign; #session; #fence; #authority; #key; #generation = 0; #prepared = new WeakMap(); #operations = new Map(); #epoch = 0; #paused;
|
||||||
constructor({ client, campaign, session, fence, authority, snapshotKey }) {
|
constructor({ client, campaign, session, fence, authority, snapshotKey }) {
|
||||||
if (!campaign || !session || !Number.isSafeInteger(fence) || fence < 1 || typeof authority !== 'function' || snapshotKey?.length !== 32) throw new MusicError('denied');
|
if (!campaign || !session || !Number.isSafeInteger(fence) || fence < 1 || typeof authority !== 'function' || snapshotKey?.length !== 32) throw new MusicError('denied');
|
||||||
this.#client=client; this.#campaign=campaign; this.#session=session; this.#fence=fence; this.#authority=authority; this.#key=Uint8Array.from(snapshotKey);
|
this.#client=client; this.#campaign=campaign; this.#session=session; this.#fence=fence; this.#authority=authority; this.#key=Uint8Array.from(snapshotKey);
|
||||||
}
|
}
|
||||||
capabilities() { return {seek:true,exactOrderRestore:false,exactUnshuffledRestore:true,concurrentLayers:false,volume:false}; }
|
capabilities() { return {seek:true,exactOrderRestore:false,exactUnshuffledRestore:true,concurrentLayers:false,volume:false}; }
|
||||||
|
async playbackStatus() {
|
||||||
|
this.#authority(this.#fence);
|
||||||
|
const queue = await this.#client.queueState();
|
||||||
|
this.#authority(this.#fence);
|
||||||
|
const item = queue.current_item;
|
||||||
|
const paused = this.#paused && queue.state === 'idle' && queue.current_index === this.#paused.index;
|
||||||
|
const elapsed = paused ? this.#paused.position : queue.elapsed_time;
|
||||||
|
const position = Number.isFinite(elapsed) ? Math.max(0, Math.floor(elapsed)) : 0;
|
||||||
|
return {
|
||||||
|
state: paused ? 'paused' : queue.state,
|
||||||
|
title: typeof item?.name === 'string' ? item.name.replace(/[\x00-\x1f\x7f]/g, '').slice(0, 180) : '',
|
||||||
|
duration: Number.isFinite(item?.duration) ? Math.max(0, Math.floor(item.duration)) : 0,
|
||||||
|
position,
|
||||||
|
};
|
||||||
|
}
|
||||||
#check(ctx) {
|
#check(ctx) {
|
||||||
if (ctx?.campaign !== this.#campaign || ctx?.session !== this.#session || !Number.isSafeInteger(ctx.generation) || ctx.generation < this.#generation || ctx.generation < 1) throw new MusicError('stale');
|
if (ctx?.campaign !== this.#campaign || ctx?.session !== this.#session || !Number.isSafeInteger(ctx.generation) || ctx.generation < this.#generation || ctx.generation < 1) throw new MusicError('stale');
|
||||||
ctx.check(); this.#authority(this.#fence); this.#generation=ctx.generation;
|
ctx.check(); this.#authority(this.#fence); this.#generation=ctx.generation;
|
||||||
@@ -39,9 +54,11 @@ export class MAPlaybackProvider {
|
|||||||
const position=Math.floor(elapsed ?? 0);
|
const position=Math.floor(elapsed ?? 0);
|
||||||
if (!Number.isSafeInteger(position) || position<0 || (position>0 && !(items[after.current_index]?.duration>position))) throw new MusicError('unsupported');
|
if (!Number.isSafeInteger(position) || position<0 || (position>0 && !(items[after.current_index]?.duration>position))) throw new MusicError('unsupported');
|
||||||
this.#check(ctx);
|
this.#check(ctx);
|
||||||
return {version:1,campaign:this.#campaign,session:this.#session,fence:this.#fence,generation:ctx.generation,expires:Date.now()+300000,
|
const value={version:1,campaign:this.#campaign,session:this.#session,fence:this.#fence,generation:ctx.generation,expires:Date.now()+43200000,
|
||||||
state:after.state,repeat:after.repeat_mode,shuffle:false,index:after.current_index,position,
|
state:after.state,repeat:after.repeat_mode,shuffle:false,index:after.current_index,position,
|
||||||
items:items.map(item=>({uri:this.#client.mediaURI(item),duration:item.duration ?? 0}))};
|
items:items.map(item=>({uri:this.#client.mediaURI(item),duration:item.duration ?? 0}))};
|
||||||
|
if(this.#paused){if(value.state!=='idle'||JSON.stringify(value.items)!==JSON.stringify(this.#paused.items))throw new MusicError('stale');return {...value,state:'paused',index:this.#paused.index,position:this.#paused.position};}
|
||||||
|
return value;
|
||||||
}
|
}
|
||||||
async #sign(value) { return hex(await hmac(this.#key,'snapshot-v1\0'+JSON.stringify(value))); }
|
async #sign(value) { return hex(await hmac(this.#key,'snapshot-v1\0'+JSON.stringify(value))); }
|
||||||
async snapshot(ctx) { const value=await this.#capture(ctx);return {value,signature:await this.#sign(value)}; }
|
async snapshot(ctx) { const value=await this.#capture(ctx);return {value,signature:await this.#sign(value)}; }
|
||||||
@@ -49,15 +66,25 @@ export class MAPlaybackProvider {
|
|||||||
this.#check(ctx);if(!this.#prepared.has(prepared))throw new MusicError('denied');
|
this.#check(ctx);if(!this.#prepared.has(prepared))throw new MusicError('denied');
|
||||||
const media=this.#prepared.get(prepared);
|
const media=this.#prepared.get(prepared);
|
||||||
return this.#once(ctx,`apply:${JSON.stringify(media)}`,async()=>{
|
return this.#once(ctx,`apply:${JSON.stringify(media)}`,async()=>{
|
||||||
await this.#client.mutate('play_media',{media,option:'replace',shuffle:false},this.#context(ctx));this.#epoch++;
|
this.#paused=undefined;await this.#client.mutate('play_media',{media,option:'replace',shuffle:false},this.#context(ctx));this.#epoch++;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
async stopOwned(ctx) { return this.#once(ctx,`stop:${this.#epoch}`,()=>this.#client.mutate('stop',{},this.#context(ctx))); }
|
async stopOwned(ctx) { return this.#once(ctx,`stop:${this.#epoch}`,()=>{this.#paused=undefined;return this.#client.mutate('stop',{},this.#context(ctx));}); }
|
||||||
async control(action,value,ctx) {
|
async control(action,value,ctx) {
|
||||||
this.#check(ctx);
|
this.#check(ctx);
|
||||||
const args={pause:{},resume:{},stop:{},seek:{position:value},shuffle:{shuffle_enabled:value},repeat:{repeat_mode:value}};
|
const args={pause:{},resume:{},stop:{},seek:{position:value},shuffle:{shuffle_enabled:value},repeat:{repeat_mode:value}};
|
||||||
if(!Object.hasOwn(args,action))throw new MusicError('denied');
|
if(!Object.hasOwn(args,action))throw new MusicError('denied');
|
||||||
return this.#once(ctx,`control:${action}:${JSON.stringify(value)}`,async()=>{await this.#client.mutate(action,args[action],this.#context(ctx));this.#epoch++;});
|
return this.#once(ctx,`control:${action}:${JSON.stringify(value)}`,async()=>{
|
||||||
|
if(action==='pause'&&this.#client.supportsNativePause?.()===false){
|
||||||
|
const captured=await this.#capture(ctx);if(!captured.items.length)return;
|
||||||
|
await this.#client.mutate('stop',{},this.#context(ctx));this.#paused=captured;
|
||||||
|
}else if(action==='resume'&&this.#paused){
|
||||||
|
const captured=await this.#capture(ctx);await this.#client.mutate('play_index',{index:captured.index,seek_position:captured.position},this.#context(ctx));this.#paused=undefined;
|
||||||
|
}else if(action==='seek'&&this.#paused){
|
||||||
|
const captured=await this.#capture(ctx);if(!Number.isSafeInteger(value)||value<0||!(captured.items[captured.index]?.duration>value))throw new MusicError('unsupported');this.#paused={...captured,position:value};
|
||||||
|
}else{if(action==='stop')this.#paused=undefined;await this.#client.mutate(action,args[action],this.#context(ctx));}
|
||||||
|
this.#epoch++;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
async restore(snapshot,ctx) {
|
async restore(snapshot,ctx) {
|
||||||
this.#check(ctx);
|
this.#check(ctx);
|
||||||
@@ -68,15 +95,15 @@ export class MAPlaybackProvider {
|
|||||||
value.expires<=Date.now() || value.version!==1 || value.campaign!==this.#campaign || value.session!==this.#session || value.fence!==this.#fence || value.generation>ctx.generation)throw new MusicError('stale');
|
value.expires<=Date.now() || value.version!==1 || value.campaign!==this.#campaign || value.session!==this.#session || value.fence!==this.#fence || value.generation>ctx.generation)throw new MusicError('stale');
|
||||||
return this.#once(ctx,`restore:${snapshot.signature}`,async()=>{
|
return this.#once(ctx,`restore:${snapshot.signature}`,async()=>{
|
||||||
const write=async(action,args)=>{await this.#client.mutate(action,args,this.#context(ctx));this.#epoch++;};
|
const write=async(action,args)=>{await this.#client.mutate(action,args,this.#context(ctx));this.#epoch++;};
|
||||||
await write('stop',{});await write('clear',{});
|
this.#paused=undefined;await write('stop',{});await write('clear',{});
|
||||||
await write('repeat',{repeat_mode:value.repeat});
|
await write('repeat',{repeat_mode:value.repeat});
|
||||||
if(value.items.length){
|
if(value.items.length){
|
||||||
await write('play_media',{media:value.items.map(i=>i.uri),option:'add',shuffle:false});
|
await write('play_media',{media:value.items.map(i=>i.uri),option:'add',shuffle:false});
|
||||||
// Validate complete ordered occurrences before starting any rebuilt item.
|
// Validate complete ordered occurrences before starting any rebuilt item.
|
||||||
const rebuilt=[];for(let offset=0;offset<value.items.length;offset+=100)rebuilt.push(...await this.#client.queueItems(offset));
|
const rebuilt=[];for(let offset=0;offset<value.items.length;offset+=100)rebuilt.push(...await this.#client.queueItems(offset));
|
||||||
if(JSON.stringify(rebuilt.map(i=>this.#client.mediaURI(i)))!==JSON.stringify(value.items.map(i=>i.uri)))throw new MusicError('unsupported');
|
if(JSON.stringify(rebuilt.map(i=>this.#client.mediaURI(i)))!==JSON.stringify(value.items.map(i=>i.uri)))throw new MusicError('unsupported');
|
||||||
await write('play_index',{index:value.index,seek_position:value.position});
|
if(value.state==='paused'&&this.#client.supportsNativePause?.()===false)this.#paused=structuredClone(value);
|
||||||
if(value.state==='paused')await write('pause',{});
|
else{await write('play_index',{index:value.index,seek_position:value.position});if(value.state==='paused')await write('pause',{});}
|
||||||
if(value.state==='idle')await write('stop',{});
|
if(value.state==='idle')await write('stop',{});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,27 +1,28 @@
|
|||||||
import {MusicError} from '../../core/controller.mjs';
|
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(['sendspin/pair_web_player','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.
|
// GM-local adapter for MA's public /ws API. No HTTP CORS dependency or server proxy.
|
||||||
export class GMMAWebSocket{
|
export class GMMAWebSocket{
|
||||||
#base;#token;#socket;#connect;#pending=new Map();#factory;#closed=false;
|
#base;#token;#socket;#connect;#pending=new Map();#factory;#closed=false;#authenticated=false;#onDisconnect;
|
||||||
constructor({baseUrl,token,createSocket=url=>new WebSocket(url)}){this.#base=new URL(baseUrl).origin;this.#token=token;this.#factory=createSocket;}
|
constructor({baseUrl,token,createSocket=url=>new WebSocket(url),onDisconnect=()=>{}}){this.#onDisconnect=onDisconnect;this.#base=new URL(baseUrl).origin;this.#token=token;this.#factory=createSocket;}
|
||||||
async connect(){
|
async connect(){
|
||||||
if(this.#closed)throw new MusicError('unavailable');if(this.#connect)return this.#connect;
|
if(this.#closed)throw new MusicError('unavailable');if(this.#connect)return this.#connect;
|
||||||
this.#connect=new Promise((resolve,reject)=>{
|
this.#connect=new Promise((resolve,reject)=>{
|
||||||
const url=new URL('/ws',this.#base);url.protocol=url.protocol==='https:'?'wss:':'ws:';const socket=this.#socket=this.#factory(url.href);
|
const url=new URL('/ws',this.#base);url.protocol=url.protocol==='https:'?'wss:':'ws:';let socket;try{socket=this.#socket=this.#factory(url.href);}catch{reject(new MusicError('ws-upgrade-failed'));return;}
|
||||||
const id='auth-'+crypto.randomUUID(),timer=setTimeout(()=>{reject(new MusicError('unavailable'));this.close();},8000);
|
let opened=false;
|
||||||
socket.onopen=()=>socket.send(JSON.stringify({message_id:id,command:'auth',args:{token:this.#token}}));
|
const id='auth-'+crypto.randomUUID(),timer=setTimeout(()=>{reject(new MusicError(opened?'ws-auth-timeout':'ws-upgrade-failed'));this.close();},8000);
|
||||||
|
socket.onopen=()=>{opened=true;socket.send(JSON.stringify({message_id:id,command:'auth',args:{token:this.#token}}));};
|
||||||
socket.onmessage=event=>{
|
socket.onmessage=event=>{
|
||||||
if(typeof event.data!=='string'||event.data.length>1048576){this.close();return;}
|
if(typeof event.data!=='string'||event.data.length>1048576){this.close();return;}
|
||||||
let msg;try{msg=JSON.parse(event.data);}catch{this.close();return;}
|
let msg;try{msg=JSON.parse(event.data);}catch{this.close();return;}
|
||||||
if(msg.message_id===id){clearTimeout(timer);if(msg.result?.authenticated===true)resolve();else{reject(new MusicError('denied'));this.close();}return;}
|
if(msg.message_id===id){clearTimeout(timer);if(msg.result?.authenticated===true){this.#authenticated=true;resolve();}else{reject(new MusicError('ws-auth-denied'));this.close();}return;}
|
||||||
const pending=this.#pending.get(msg.message_id);if(!pending)return; // Drop unsolicited metadata/events.
|
const pending=this.#pending.get(msg.message_id);if(!pending)return; // Drop unsolicited metadata/events.
|
||||||
if(Object.hasOwn(msg,'error_code')){pending.fail(new MusicError('unavailable'));return;}
|
if(Object.hasOwn(msg,'error_code')){const error=new MusicError('ws-command-failed');error.command=pending.command;error.upstreamCode=Number.isSafeInteger(msg.error_code)?msg.error_code:null;error.translationKey=typeof msg.translation_key==='string'&&/^[a-z0-9_.-]{1,100}$/.test(msg.translation_key)?msg.translation_key:null;pending.fail(error);return;}
|
||||||
pending.bytes+=event.data.length;if(pending.bytes>1048576){pending.fail(new MusicError('unavailable'));return;}
|
pending.bytes+=event.data.length;if(pending.bytes>1048576){pending.fail(new MusicError('unavailable'));return;}
|
||||||
if(msg.partial===true){if(!Array.isArray(msg.result)||pending.parts.length+msg.result.length>5000){pending.fail(new MusicError('unavailable'));return;}pending.parts.push(...msg.result);return;}
|
if(msg.partial===true){if(!Array.isArray(msg.result)||pending.parts.length+msg.result.length>5000){pending.fail(new MusicError('unavailable'));return;}pending.parts.push(...msg.result);return;}
|
||||||
pending.finish(pending.parts.length?[...pending.parts,...(Array.isArray(msg.result)?msg.result:[])]:msg.result);
|
pending.finish(pending.parts.length?[...pending.parts,...(Array.isArray(msg.result)?msg.result:[])]:msg.result);
|
||||||
};
|
};
|
||||||
socket.onerror=()=>{clearTimeout(timer);reject(new MusicError('unavailable'));this.close();};
|
socket.onerror=()=>{const notify=this.#authenticated&&!this.#closed;clearTimeout(timer);reject(new MusicError(opened?'ws-disconnected':'ws-upgrade-failed'));this.close();if(notify)this.#onDisconnect();};
|
||||||
socket.onclose=()=>{clearTimeout(timer);reject(new MusicError('unavailable'));this.#closed=true;for(const p of [...this.#pending.values()])p.fail(new MusicError('unavailable'));};
|
socket.onclose=()=>{const notify=this.#authenticated&&!this.#closed;clearTimeout(timer);reject(new MusicError(opened?'ws-disconnected':'ws-upgrade-failed'));this.#closed=true;this.#token=null;for(const p of [...this.#pending.values()])p.fail(new MusicError('unavailable'));if(notify)this.#onDisconnect();};
|
||||||
});return this.#connect;
|
});return this.#connect;
|
||||||
}
|
}
|
||||||
fetch=async(url,options)=>{
|
fetch=async(url,options)=>{
|
||||||
@@ -33,10 +34,10 @@ export class GMMAWebSocket{
|
|||||||
const id=crypto.randomUUID();let pending;
|
const id=crypto.randomUUID();let pending;
|
||||||
const cleanup=()=>{clearTimeout(timer);options.signal?.removeEventListener('abort',abort);this.#pending.delete(id);};
|
const cleanup=()=>{clearTimeout(timer);options.signal?.removeEventListener('abort',abort);this.#pending.delete(id);};
|
||||||
const finish=value=>{cleanup();const body=JSON.stringify(value??null);if(body.length>1048576){reject(new MusicError('unavailable'));return;}resolve(new Response(body,{headers:{'Content-Type':'application/json'}}));};
|
const finish=value=>{cleanup();const body=JSON.stringify(value??null);if(body.length>1048576){reject(new MusicError('unavailable'));return;}resolve(new Response(body,{headers:{'Content-Type':'application/json'}}));};
|
||||||
const fail=error=>{cleanup();reject(error);};const abort=()=>fail(new MusicError('unavailable'));const timer=setTimeout(abort,5000);
|
const fail=error=>{if(!error.command)error.command=request.command;cleanup();reject(error);};const abort=()=>fail(new MusicError('ws-command-timeout'));const timer=setTimeout(abort,request.command==='sendspin/pair_web_player'?25000:['player_queues/play_media','player_queues/play_index'].includes(request.command)?60000:10000);
|
||||||
pending={parts:[],bytes:0,finish,fail};this.#pending.set(id,pending);options.signal?.addEventListener('abort',abort,{once:true});
|
pending={command:request.command,parts:[],bytes:0,finish,fail};this.#pending.set(id,pending);options.signal?.addEventListener('abort',abort,{once:true});
|
||||||
try{this.#socket.send(JSON.stringify({...request,message_id:id}));}catch{fail(new MusicError('unavailable'));}
|
try{this.#socket.send(JSON.stringify({...request,message_id:id}));}catch{fail(new MusicError('unavailable'));}
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
close(){if(this.#closed)return;this.#closed=true;for(const p of [...this.#pending.values()])p.fail(new MusicError('unavailable'));this.#socket?.close();this.#token=null;}
|
close(){if(this.#closed)return;this.#closed=true;this.#token=null;for(const p of [...this.#pending.values()])p.fail(new MusicError('unavailable'));this.#socket?.close();this.#token=null;}
|
||||||
}
|
}
|
||||||
@@ -1,7 +1,45 @@
|
|||||||
.adaptive-music-setup {display:grid;gap:0.7rem;max-height:75vh;overflow:auto;padding:0.5rem;}
|
.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.5rem;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 fieldset:first-of-type {max-height:18rem;overflow:auto;}
|
.adaptive-music-setup legend {font-weight:700;padding:0 0.4rem;}
|
||||||
.adaptive-music-setup label,[data-adaptive-music="assignments"] label {display:grid;gap:0.3rem;}
|
.adaptive-music-setup label,[data-adaptive-music="assignments"] label {display:grid;gap:0.35rem;}
|
||||||
.adaptive-music-setup select,[data-adaptive-music="assignments"] select {width:100%;min-width:0;}
|
.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 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;}
|
||||||
|
/* ApplicationV2 and small windows must not inherit theme flex label sizing. */
|
||||||
|
#adaptive-music-setup .window-content {min-width:0;overflow:auto;}
|
||||||
|
#adaptive-music-setup .adaptive-music-setup {width:100%;min-width:0;box-sizing:border-box;align-content:start;}
|
||||||
|
#adaptive-music-setup .adaptive-music-setup label {display:grid;grid-template-columns:minmax(0,1fr);width:100%;height:auto;white-space:normal;}
|
||||||
|
#adaptive-music-setup .adaptive-music-setup input {box-sizing:border-box;}
|
||||||
|
#adaptive-music-setup .adaptive-music-setup input[type="file"] {max-width:100%;height:auto;}
|
||||||
|
#adaptive-music-setup .adaptive-music-setup button {width:100%;flex:none;}
|
||||||
|
|
||||||
|
/* Foundry owns the window. Its content pane is the only scrolling surface. */
|
||||||
|
#adaptive-music-setup {max-inline-size:calc(100vw - 12px);max-block-size:calc(100dvh - 12px);min-inline-size:min(320px,calc(100vw - 12px));min-block-size:min(280px,calc(100dvh - 12px));}
|
||||||
|
#adaptive-music-setup .window-content {overflow:auto;overscroll-behavior:contain;padding:0;}
|
||||||
|
#adaptive-music-setup .adaptive-music-setup {display:block;overflow:visible;max-height:none;padding:0;}
|
||||||
|
#adaptive-music-setup .adaptive-tabs {display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:0.25rem;padding:0.4rem 1rem 0;border-bottom:1px solid var(--color-border-light-primary,#777);}
|
||||||
|
#adaptive-music-setup .adaptive-tabs button {background:transparent;color:inherit;border:0;border-bottom:3px solid transparent;border-radius:0;padding:0.65rem 0.2rem;font-weight:650;line-height:1.25;}
|
||||||
|
#adaptive-music-setup .adaptive-tabs [aria-selected="true"] {border-bottom-color:var(--color-warm-2,#b86b42);color:var(--color-text-emphatic,inherit);}
|
||||||
|
#adaptive-music-setup .adaptive-panel {display:grid;gap:0.8rem;padding:clamp(0.7rem,3vw,1.35rem);min-width:0;}
|
||||||
|
#adaptive-music-setup [hidden] {display:none!important;}
|
||||||
|
#adaptive-music-setup .adaptive-panel h2,#adaptive-music-setup .adaptive-now h3 {margin:0;overflow-wrap:anywhere;}
|
||||||
|
#adaptive-music-setup .adaptive-panel h2 {font-size:1.3rem;font-weight:700;}
|
||||||
|
#adaptive-music-setup .adaptive-fields {display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,13rem),1fr));gap:0.7rem;}
|
||||||
|
#adaptive-music-setup .adaptive-panel label {gap:0.3rem;min-width:0;}
|
||||||
|
#adaptive-music-setup .adaptive-panel input,#adaptive-music-setup .adaptive-panel select {max-width:100%;min-height:2rem;}
|
||||||
|
#adaptive-music-setup .adaptive-actions {display:flex;flex-wrap:wrap;gap:0.45rem;align-items:center;}
|
||||||
|
#adaptive-music-setup .adaptive-actions button,#adaptive-music-setup .adaptive-playback-summary button {width:auto;max-width:100%;padding-inline:0.7rem;}
|
||||||
|
#adaptive-music-setup .adaptive-panel button.adaptive-primary {background:var(--color-cool-4,#264852);color:white;border-color:var(--color-cool-4,#264852);font-weight:700;min-width:min(100%,7.5rem);}
|
||||||
|
#adaptive-music-setup .adaptive-state {font-size:0.85rem;font-weight:700;overflow-wrap:anywhere;}
|
||||||
|
#adaptive-music-setup .adaptive-state[data-connected="true"] {color:var(--color-level-success,#326b48);}
|
||||||
|
#adaptive-music-setup .adaptive-now {display:grid;gap:0.3rem;padding:0.85rem 1rem;border:1px solid var(--color-border-light-primary,#777);border-radius:0.45rem;}
|
||||||
|
#adaptive-music-setup .adaptive-playback-summary {display:flex;align-items:center;flex-wrap:wrap;gap:0.55rem 1rem;}
|
||||||
|
#adaptive-music-setup .adaptive-checklist label {display:flex;align-items:center;gap:0.5rem;}
|
||||||
|
#adaptive-music-setup .adaptive-checklist input {min-height:0;}
|
||||||
|
#adaptive-music-setup details[open] > :not(summary) {margin-block-start:0.5rem;}
|
||||||
|
#adaptive-music-setup [role="alert"] {padding:0.55rem;border-inline-start:3px solid var(--color-level-error,#aa3b30);overflow-wrap:anywhere;}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
<!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>
|
||||||
|
<section id="adaptive-music-setup"><main id="app" class="window-content"></main></section>
|
||||||
|
<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:[]};
|
||||||
|
let trackState='playing',position=12;window.controlActions=[];
|
||||||
|
const connection={status:{state:'disconnected',catalog:0,audioContext:'closed'},open: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:'connected',catalog:2,audioContext:'running',hasPrivateDraft:true,peers:2}},refresh:async()=>{},resume:async()=>{},disconnect:async()=>{},playback:async()=>({source:'Music Assistant',state:trackState,title:'Forest at night',position,duration:90}),
|
||||||
|
control:async(action,value)=>{window.controlActions.push(action);if(action==='seek')position=value;else trackState={pause:'paused',resume:'playing',stop:'idle'}[action];},setVolume:value=>{connection.status.volume=value;}};
|
||||||
|
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>
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import {test} from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import {openAccountConnection,sealAccountConnection} from '../../src/foundry/account-connection.mjs';
|
||||||
|
import {MAReadClient} from '../../src/providers/ma/client.mjs';
|
||||||
|
import {hmac} from '../../src/providers/ma/webcrypto.mjs';
|
||||||
|
|
||||||
|
test('saved account connection is portable ciphertext bound to the same token, world and user',async()=>{
|
||||||
|
const config={maUrl:'https://ma.example.test',targetName:'Development receiver',token:'fixture-token',identityStorage:{secret:'excluded'}};
|
||||||
|
const scope='["https://foundry.example.test","world","gm"]';
|
||||||
|
const saved=await sealAccountConnection(config,config.token,scope);
|
||||||
|
assert.ok(!JSON.stringify(saved).includes(config.maUrl));
|
||||||
|
assert.ok(!JSON.stringify(saved).includes(config.token));
|
||||||
|
assert.deepEqual(await openAccountConnection(JSON.parse(JSON.stringify(saved)),config.token,scope),{maUrl:config.maUrl,targetName:config.targetName});
|
||||||
|
await assert.rejects(openAccountConnection(saved,'different-token',scope),{code:'saved-connection-unavailable'});
|
||||||
|
await assert.rejects(openAccountConnection(saved,config.token,scope.replace('gm','player')),{code:'saved-connection-unavailable'});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('new playlist references are shared across browsers and the original can still resolve its old reference',async()=>{
|
||||||
|
const fetchImpl=async(_url,options)=>Response.json(JSON.parse(options.body).command.includes('/playlists/')?[
|
||||||
|
{name:'Ambient',media_type:'playlist',is_playable:true,provider_mappings:[{provider_instance:'music',item_id:'ambient',available:true}]},
|
||||||
|
]:[]);
|
||||||
|
const common={baseUrl:'https://ma.example.test',token:'fixture-token',target:'dedicated',approvedProviders:['music'],campaign:'test',fetchImpl};
|
||||||
|
const catalogKey=await hmac(new TextEncoder().encode(common.token),'test portable catalog');
|
||||||
|
const originalKey=new Uint8Array(32).fill(1),otherKey=new Uint8Array(32).fill(2);
|
||||||
|
const [old]=await new MAReadClient({...common,catalogKey:originalKey}).catalog();
|
||||||
|
const first=new MAReadClient({...common,catalogKey,legacyCatalogKey:originalKey});
|
||||||
|
const other=new MAReadClient({...common,catalogKey,legacyCatalogKey:otherKey});
|
||||||
|
const [a]=await first.catalog(),[b]=await other.catalog();
|
||||||
|
assert.equal(a.id,b.id);
|
||||||
|
assert.equal(a.legacyId,old.id);
|
||||||
|
assert.notEqual(a.legacyId,b.legacyId);
|
||||||
|
assert.equal(first.resolveCatalog(old),other.resolveCatalog(a));
|
||||||
|
});
|
||||||
@@ -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();}
|
||||||
|
});
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import {test} from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import {connectionDraft} from '../../src/foundry/connection-draft.mjs';
|
||||||
|
import {probeWebSockets,diagnosticMessage} from '../../src/providers/ma/diagnostics.mjs';
|
||||||
|
import {GMMAWebSocket} from '../../src/providers/ma/websocket.mjs';
|
||||||
|
test('failed setup draft retains private inputs only for the same exact origin',()=>{
|
||||||
|
const old={maUrl:'https://ma.example.test',token:'fixture',identityStorage:{'sendspin-identity-sk':'key'},target:'dedicated'};
|
||||||
|
const retry=connectionDraft(old,{maUrl:old.maUrl,token:'',identityStorage:{}},'world');
|
||||||
|
assert.equal(retry.token,'fixture');assert.deepEqual(retry.identityStorage,old.identityStorage);
|
||||||
|
for(const maUrl of ['https://other.example.test','http://ma.example.test','https://ma.example.test:9000']){
|
||||||
|
const changed=connectionDraft(old,{maUrl,token:'',identityStorage:{}},'world');assert.equal(changed.token,undefined);assert.equal(changed.target,undefined);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
test('token-free diagnostics check only two fixed routes, distinguish enforced CSP, and remove listeners',async()=>{
|
||||||
|
const events=new EventTarget(),urls=[];let sends=0,closes=0;
|
||||||
|
const results=await probeWebSockets('https://ma.example.test',{events,createSocket:url=>{
|
||||||
|
urls.push(url);const socket={send(){sends++;},close(){closes++;}};
|
||||||
|
queueMicrotask(()=>{if(url.endsWith('/ws'))socket.onopen();else{const event=new Event('securitypolicyviolation');Object.assign(event,{disposition:'enforce',effectiveDirective:'connect-src',blockedURI:url});events.dispatchEvent(event);}});return socket;
|
||||||
|
}});
|
||||||
|
assert.deepEqual(urls,['wss://ma.example.test/ws','wss://ma.example.test/sendspin']);assert.equal(sends,0);assert.equal(closes,2);
|
||||||
|
assert.deepEqual(results.map(r=>r.code),['upgrade-ok','csp-blocked']);assert.match(diagnosticMessage(results[1]),/Content Security Policy/);
|
||||||
|
await assert.rejects(probeWebSockets('https://ma.example.test/path'),{code:'address-invalid'});
|
||||||
|
});
|
||||||
|
test('API failure identifies rejected authentication separately from pre-upgrade failure',async()=>{
|
||||||
|
for(const [mode,code]of [['denied','ws-auth-denied'],['upgrade','ws-upgrade-failed']]){
|
||||||
|
const adapter=new GMMAWebSocket({baseUrl:'https://ma.example.test',token:'fixture',createSocket:()=>{
|
||||||
|
const socket={close(){this.onclose?.();},send(text){const m=JSON.parse(text);queueMicrotask(()=>this.onmessage({data:JSON.stringify({message_id:m.message_id,error_code:1})}));}};
|
||||||
|
queueMicrotask(()=>mode==='upgrade'?socket.onerror():socket.onopen());return socket;
|
||||||
|
}});
|
||||||
|
await assert.rejects(adapter.connect(),{code});adapter.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
test('synchronous browser CSP rejection waits for the asynchronous enforcement event',async()=>{
|
||||||
|
const events=new EventTarget();
|
||||||
|
const results=await probeWebSockets('https://ma.example.test',{events,createSocket:url=>{
|
||||||
|
setTimeout(()=>{const event=new Event('securitypolicyviolation');Object.assign(event,{disposition:'enforce',effectiveDirective:'connect-src',blockedURI:url});events.dispatchEvent(event);},0);
|
||||||
|
throw new DOMException('Blocked','SecurityError');
|
||||||
|
}});
|
||||||
|
assert.deepEqual(results.map(r=>r.code),['csp-blocked','csp-blocked']);
|
||||||
|
});
|
||||||
@@ -25,6 +25,22 @@ test('policy precedence and explicit silence', () => {
|
|||||||
assert.equal(candidates({defaultPlaylist:ref('world')})[0].playlist.id,'world');
|
assert.equal(candidates({defaultPlaylist:ref('world')})[0].playlist.id,'world');
|
||||||
assert.equal(candidates({})[0].playlist,null);
|
assert.equal(candidates({})[0].playlist,null);
|
||||||
});
|
});
|
||||||
|
test('manual MA controls wait for the scene transition and carry the current fence', async () => {
|
||||||
|
const {controller,provider,log}=fixture();
|
||||||
|
controller.providers.ma=provider;
|
||||||
|
provider.control=async(action,value,ctx)=>{
|
||||||
|
ctx.check();
|
||||||
|
log.push([action,value,ctx.campaign,ctx.session,ctx.generation]);
|
||||||
|
};
|
||||||
|
const transition=controller.update({scene:{id:'ambient',playlist:{provider:'ma',id:'ambient'}}});
|
||||||
|
const pause=controller.control('pause');
|
||||||
|
await Promise.all([transition,pause]);
|
||||||
|
assert.deepEqual(log,[['resolve','ambient'],['apply','ambient'],['pause',undefined,'campaign','session',2]]);
|
||||||
|
const obsolete=controller.control('resume');
|
||||||
|
controller.cancel();
|
||||||
|
await assert.rejects(obsolete,{code:'stale'});
|
||||||
|
assert.equal(log.length,3);
|
||||||
|
});
|
||||||
test('inactive, unstarted and other scene combats ignored; boss ties stable', () => {
|
test('inactive, unstarted and other scene combats ignored; boss ties stable', () => {
|
||||||
for (const change of [{active:false},{started:false},{sceneId:'B'}]) {
|
for (const change of [{active:false},{started:false},{sceneId:'B'}]) {
|
||||||
assert.equal(candidates({scene:scene(),combats:[{...combat([boss()]),...change}]})[0].playlist.id,'A');
|
assert.equal(candidates({scene:scene(),combats:[{...combat([boss()]),...change}]})[0].playlist.id,'A');
|
||||||
@@ -74,6 +90,16 @@ test('partial apply failure restores outgoing playback', async () => {
|
|||||||
f.provider.apply=async()=>{throw new MusicError('unavailable');};
|
f.provider.apply=async()=>{throw new MusicError('unavailable');};
|
||||||
await assert.rejects(f.controller.update({scene:scene('B')})); assert.equal(f.playback.items[0],'A');
|
await assert.rejects(f.controller.update({scene:scene('B')})); assert.equal(f.playback.items[0],'A');
|
||||||
});
|
});
|
||||||
|
test('uncertain apply preserves the failed command and skips transition rollback', async () => {
|
||||||
|
const f = fixture();
|
||||||
|
await f.controller.update({scene: scene()});
|
||||||
|
const failure = Object.assign(new MusicError('uncertain'), {command: 'player_queues/play_media'});
|
||||||
|
f.provider.apply = async () => { throw failure; };
|
||||||
|
|
||||||
|
await assert.rejects(f.controller.update({scene: scene('B')}), error => error === failure);
|
||||||
|
assert.equal(f.controller.current, null);
|
||||||
|
assert.deepEqual(f.log.filter(([action]) => ['stop', 'restore'].includes(action)), [['stop']]);
|
||||||
|
});
|
||||||
test('obsolete async resolve is rejected before stop/apply', async () => {
|
test('obsolete async resolve is rejected before stop/apply', async () => {
|
||||||
const f=fixture(); let resume, entered;
|
const f=fixture(); let resume, entered;
|
||||||
const ready=new Promise(r=>entered=r), normal=f.provider.resolve;
|
const ready=new Promise(r=>entered=r), normal=f.provider.resolve;
|
||||||
|
|||||||
@@ -64,3 +64,91 @@ test('peer signaling bounds queued work and rejects expired invites before alloc
|
|||||||
const listener=new PeerAudio({socket,userId:'player',isGM:()=>false,createPeer:()=>{allocations++;}});
|
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();}
|
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'});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('automatic provisioning uses the bound API session, waits for queue registration and reconnects',async()=>{
|
||||||
|
const sockets=[],commands=[];let paired=false,softwareVolume,core,losses=0,lockHeld=false,queueReads=0;
|
||||||
|
const player={player_id:'campaign-receiver',name:'Campaign receiver',provider:'sendspin-fixture',enabled:true,available:true,volume_level:null,volume_muted:null,group_members:[],group_childs:[],static_group_members:[]};
|
||||||
|
const queue={queue_id:player.player_id,active:true,available:true,items:0,state:'idle',is_dynamic:false,autoplay_enabled:false,dont_stop_the_music_enabled:false,overlay_enabled:false,playback_speed:1};
|
||||||
|
const createSocket=url=>{
|
||||||
|
const socket={url,bound:false,authenticated:false,send(text){const msg=JSON.parse(text);commands.push(msg.command??msg.type);queueMicrotask(()=>{
|
||||||
|
if(url.endsWith('/sendspin')){for(const api of sockets.filter(s=>s.url.endsWith('/ws')&&s.authenticated))api.bound=true;socket.onmessage?.({data:JSON.stringify({type:'auth_ok'})});return;}
|
||||||
|
if(msg.command==='auth')socket.authenticated=true;
|
||||||
|
if(msg.command==='players/get')assert.equal(socket.bound,true,'new receiver access belongs to the preexisting API session');
|
||||||
|
if(msg.command==='sendspin/pair_web_player'){assert.equal(socket.bound,true);paired=true;}
|
||||||
|
let result=msg.command==='auth'?{authenticated:true}:msg.command==='providers'?[{instance_id:'music',available:true}]:msg.command==='players/get'?player:msg.command.includes('library_items')?[]:msg.command==='sendspin/pair_web_player'?null:queue;
|
||||||
|
if(msg.command==='player_queues/get'&&++queueReads===1)result=null;
|
||||||
|
socket.onmessage?.({data:JSON.stringify({message_id:msg.message_id,result})});
|
||||||
|
});},close(){socket.onclose?.();}};sockets.push(socket);queueMicrotask(()=>socket.onopen?.());return socket;
|
||||||
|
};
|
||||||
|
const sdk={loadSendspinClientIdentity(storage){if(!storage.getItem('sendspin-identity-sk'))storage.setItem('sendspin-identity-sk','A'.repeat(43));return {clientId:player.player_id};},SendspinCore:class{
|
||||||
|
timeSyncInfo={synced:true};pairingToken='private-pairing-fixture';constructor(config){core=this;this.config=config;softwareVolume=config.useHardwareVolume===false;}async connect(){this.config.storage.setItem('pairing-fixture','retained');}disconnect(){}
|
||||||
|
}};
|
||||||
|
const context={state:'running',destination:{},resume:async()=>{},createMediaStreamDestination:()=>({stream:{getTracks:()=>[]}}),createGain:()=>({connect(){}}),close:async()=>{}};
|
||||||
|
const locks={async request(_name,_options,callback){
|
||||||
|
if(lockHeld)return callback(null);
|
||||||
|
lockHeld=true;
|
||||||
|
try{await callback({});}finally{lockHeld=false;}
|
||||||
|
}};
|
||||||
|
const oldNavigator=globalThis.navigator;Object.defineProperty(globalThis,'navigator',{configurable:true,value:{locks}});
|
||||||
|
const host=new GMAudioHost({authority:()=>true,pageUrl:'https://foundry.example.test',createSocket,createContext:()=>context,loadSDK:async()=>sdk,onDisconnect:()=>{losses++;}});
|
||||||
|
try{
|
||||||
|
const profile=await host.prepare({maUrl:'https://ma.example.test',token:'private-fixture',campaign:'campaign',targetName:player.name});
|
||||||
|
assert.equal(profile.identityStorage['sendspin-identity-sk'],'A'.repeat(43));await host.start(profile);
|
||||||
|
assert.equal(paired,true);assert.equal(softwareVolume,true);assert.equal(profile.identityStorage['pairing-fixture'],'retained');assert.equal(host.connected,true);
|
||||||
|
assert.equal(queueReads,3);
|
||||||
|
assert.equal(queueReads,3);
|
||||||
|
assert.ok(commands.every(command=>!/^player_queues\/(play_media|play_index|stop|clear|repeat)$/.test(command)));
|
||||||
|
const firstSession=host.session;
|
||||||
|
const firstCore=core;
|
||||||
|
firstCore.onConnectionClose();
|
||||||
|
assert.equal(host.status.state,'connection-lost');
|
||||||
|
await host.start(profile);
|
||||||
|
assert.notEqual(host.session,firstSession);
|
||||||
|
firstCore.onConnectionClose();
|
||||||
|
assert.equal(host.connected,true);
|
||||||
|
assert.equal(losses,1);
|
||||||
|
assert.ok(!commands.includes('players/all'));
|
||||||
|
}finally{await host.close();Object.defineProperty(globalThis,'navigator',{configurable:true,value:oldNavigator});}
|
||||||
|
});
|
||||||
|
test('Firefox session sendrecv default is overridden by recvonly audio without permitting sender or extra media',async()=>{
|
||||||
|
const {validateAudioSDP}=await import('../../src/audio/peer-audio.mjs');
|
||||||
|
const firefox='v=0\r\na=sendrecv\r\nm=audio 9 UDP/TLS/RTP/SAVPF 109\r\na=recvonly\r\n';
|
||||||
|
assert.doesNotThrow(()=>validateAudioSDP(firefox,'offer'));
|
||||||
|
assert.doesNotThrow(()=>validateAudioSDP(firefox.replace('a=recvonly','a=sendonly'),'answer'));
|
||||||
|
for(const bad of [firefox.replace('a=recvonly','a=sendonly'),firefox.replace('a=recvonly','a=sendrecv'),firefox+'m=video 9 UDP/TLS/RTP/SAVPF 96\r\na=recvonly\r\n',firefox+'m=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\n',firefox+'a=sendonly\r\n',firefox.replace('a=recvonly\r\n','')])assert.throws(()=>validateAudioSDP(bad,'offer'),{code:'denied'});
|
||||||
|
});
|
||||||
@@ -79,8 +79,8 @@ test('ambiguous wire mutation failure latches closed instead of retrying or rest
|
|||||||
if(command==='player_queues/get'||command==='player_queues/get_active_queue')return Response.json({queue_id:'dev',active:true,available:true,is_dynamic:false,autoplay_enabled:false,dont_stop_the_music_enabled:false,overlay_enabled:false,playback_speed:1});
|
if(command==='player_queues/get'||command==='player_queues/get_active_queue')return Response.json({queue_id:'dev',active:true,available:true,is_dynamic:false,autoplay_enabled:false,dont_stop_the_music_enabled:false,overlay_enabled:false,playback_speed:1});
|
||||||
effects++;throw Error('lost response');
|
effects++;throw Error('lost response');
|
||||||
}});
|
}});
|
||||||
await assert.rejects(client.mutate('pause',{}, {check(){}}),{code:'uncertain'});
|
await assert.rejects(client.mutate('pause',{}, {check(){}}),{code:'uncertain',command:'player_queues/pause'});
|
||||||
await assert.rejects(client.mutate('pause',{}, {check(){}}),{code:'uncertain'});assert.equal(effects,1);
|
await assert.rejects(client.mutate('pause',{}, {check(){}}),{code:'uncertain',command:'player_queues/pause'});assert.equal(effects,1);
|
||||||
});
|
});
|
||||||
test('listener cannot obtain a playback fence guard or renew a controller lease',async()=>{
|
test('listener cannot obtain a playback fence guard or renew a controller lease',async()=>{
|
||||||
const {GatewayControl}=await import('../../gateway/control.mjs');
|
const {GatewayControl}=await import('../../gateway/control.mjs');
|
||||||
@@ -99,3 +99,17 @@ test('playlist preparation expands approved ordered tracks before any playback m
|
|||||||
}});
|
}});
|
||||||
const catalog=await client.catalog();assert.deepEqual(await client.prepareMedia(catalog[0]),['approved://track/a','approved://track/a','approved://track/b']);assert.ok(!commands.some(c=>c.startsWith('player_queues/')));
|
const catalog=await client.catalog();assert.deepEqual(await client.prepareMedia(catalog[0]),['approved://track/a','approved://track/a','approved://track/b']);assert.ok(!commands.some(c=>c.startsWith('player_queues/')));
|
||||||
});
|
});
|
||||||
|
test('ambient snapshot remains restorable after a combat longer than five minutes',async()=>{
|
||||||
|
const f=fixture(),snapshot=await f.provider.snapshot(f.ctx),now=Date.now;
|
||||||
|
try{Date.now=()=>now()+10*60*1000;await f.provider.restore(snapshot,{...f.ctx,generation:2});assert.equal(f.state.state,'paused');assert.equal(f.state.elapsed_time,17);}finally{Date.now=now;}
|
||||||
|
});
|
||||||
|
test('Sendspin pause emulation retains position and restores paused queues without briefly playing',async()=>{
|
||||||
|
const f=fixture();f.state.state='playing';f.client.supportsNativePause=()=>false;
|
||||||
|
await f.provider.control('pause',null,f.ctx);assert.equal(f.state.state,'idle');
|
||||||
|
const paused=await f.provider.snapshot({...f.ctx,generation:2});assert.equal(paused.value.state,'paused');assert.equal(paused.value.position,17);
|
||||||
|
await f.provider.control('seek',3,{...f.ctx,generation:3});const sought=await f.provider.snapshot({...f.ctx,generation:4});assert.equal(sought.value.position,3);
|
||||||
|
await f.provider.control('resume',null,{...f.ctx,generation:5});assert.equal(f.state.state,'playing');assert.equal(f.state.elapsed_time,3);
|
||||||
|
const before=f.writes.length;await f.provider.restore(paused,{...f.ctx,generation:6});
|
||||||
|
assert.deepEqual(f.writes.slice(before).map(w=>w.action),['stop','clear','repeat','play_media']);
|
||||||
|
const again=await f.provider.snapshot({...f.ctx,generation:7});assert.equal(again.value.state,'paused');assert.equal(again.value.index,1);assert.equal(again.value.position,17);
|
||||||
|
});
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import {test} from 'node:test';
|
import {test} from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
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';
|
import {ListenerAudio} from '../../src/foundry/listener-audio.mjs';
|
||||||
class Element{
|
class Element{
|
||||||
constructor(tag,dom){this.tag=tag;this.ownerDocument=dom;this.children=[];this.listeners={};this.dataset={};this.value='';}
|
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 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;};
|
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;
|
const dom={createElement:tag=>new Element(tag,dom)};globalThis.document=dom;
|
||||||
let flag={},catalog=[];const settings={ownedPlaylistIds:'owned',musicDefaults:{},enabled:false},writes=[];
|
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 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 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 open(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'}];this.status={state:'connected',hasPrivateDraft:true,catalog:1};},refresh:async()=>{},disconnect:async()=>{}};
|
||||||
try{
|
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 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';
|
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';
|
||||||
await descendants(root).find(e=>e.tag==='button'&&e.textContent==='Connect and load MA catalog').listeners.click();assert.equal(code.value,'');
|
await descendants(root).find(e=>e.tag==='button'&&e.textContent==='Connect').listeners.click();assert.equal(code.value,'');assert.ok(!descendants(root).some(e=>e.textContent==='Connect optional companion'));assert.ok(descendants(root).some(e=>e.textContent==='Choose scene music'));
|
||||||
const panel=descendants(root).find(e=>e.tag==='fieldset'&&e.children.some(c=>c.tag==='legend'&&c.textContent==='Scene music'));
|
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')));
|
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"]';
|
selects[0].value='["ma","opaque-ma"]';selects[1].value='["native","owned"]';selects[3].value='["native","owned"]';
|
||||||
@@ -35,3 +35,20 @@ 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 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'));
|
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;}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('failed wizard authentication can retry without reentering token',async()=>{
|
||||||
|
const {connectionDraft}=await import('../../src/foundry/connection-draft.mjs');
|
||||||
|
const {mountConnectionWizard}=await import('../../src/foundry/connection-wizard.mjs');
|
||||||
|
const dom={createElement:tag=>new Element(tag,dom)};const container=new Element('div',dom);let draft,attempts=0,errors=0;
|
||||||
|
const connection={get status(){return {hasPrivateDraft:!!draft,state:'disconnected',catalog:0};},get draftFields(){return draft?{maUrl:draft.maUrl,retainedToken:!!draft.token}:{};},async open(profile){draft=connectionDraft(draft,profile,'world');attempts++;assert.equal(draft.token,'private-fixture');if(attempts===1)throw {code:'ws-auth-denied'};}};
|
||||||
|
mountConnectionWizard({game:{user:{isGM:true}},container,connection,onError:()=>errors++});
|
||||||
|
const all=()=>descendants(container);all().find(e=>e.type==='url').value='https://ma.example.test';const token=all().find(e=>e.type==='password');token.value='private-fixture';
|
||||||
|
assert.equal(all().filter(e=>e.type==='file').length,0);
|
||||||
|
const submit=all().find(e=>e.textContent==='Connect');await submit.listeners.click();assert.equal(errors,1);assert.equal(token.value,'');
|
||||||
|
await submit.listeners.click();assert.equal(attempts,2);assert.equal(errors,1);
|
||||||
|
});
|
||||||
@@ -35,6 +35,9 @@ class ReleaseTests(unittest.TestCase):
|
|||||||
with zipfile.ZipFile(io.BytesIO(outer.read('adaptive-music-source.zip'))) as source:
|
with zipfile.ZipFile(io.BytesIO(outer.read('adaptive-music-source.zip'))) as source:
|
||||||
self.assertIn('adaptive-music-source/gateway/ma-client.mjs',source.namelist())
|
self.assertIn('adaptive-music-source/gateway/ma-client.mjs',source.namelist())
|
||||||
self.assertFalse(any('/.local/' in n or '/node_modules/' in n for n in source.namelist()))
|
self.assertFalse(any('/.local/' in n or '/node_modules/' in n for n in source.namelist()))
|
||||||
|
evidence=f"evidence/v{standalone['version']}-live.json"
|
||||||
|
if (ROOT/evidence).is_file():
|
||||||
|
self.assertEqual(outer.read(evidence),source.read(f'adaptive-music-source/{evidence}'))
|
||||||
release.validate_package(root/'adaptive-music.zip',standalone)
|
release.validate_package(root/'adaptive-music.zip',standalone)
|
||||||
(root/'licenses').mkdir(exist_ok=True)
|
(root/'licenses').mkdir(exist_ok=True)
|
||||||
(root/'licenses/unmanaged.txt').write_text('must not be swept into the release')
|
(root/'licenses/unmanaged.txt').write_text('must not be swept into the release')
|
||||||
|
|||||||
Reference in new issue
Block a user