Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1ed30567fb | ||
|
|
83d168f5a1 |
No files matched your search
+77
-100
@@ -1,115 +1,92 @@
|
|||||||
# Adaptive Music architecture — 0.6.0
|
# Adaptive Music architecture — 0.7.0
|
||||||
|
|
||||||
Independent project by CheddahBoxMB, system-independent, targeting Foundry v14.371
|
Adaptive Music is an independent project by CheddahBoxMB for Foundry v14.371 and
|
||||||
and MA 2.10.6. Standard distribution is one Foundry module ZIP. No additional module,
|
MA 2.10.6, with no system dependency or additional required process. The expanded
|
||||||
container, VM/LXC, OS service, subscription, telemetry or core patch is required.
|
operator authorization selects direct trusted-GM browser access and GM-local
|
||||||
The user reports successful v0.5.0 publication/install/activation and window rendering;
|
credential handling for the standalone module; it supersedes the older gateway-only
|
||||||
this revision's live MA/Foundry audio is not verified.
|
scaffolding rule. Optional historical gateway source is not required or deployed.
|
||||||
|
|
||||||
## Connection and catalog
|
## Setup and receiver ownership
|
||||||
|
|
||||||
`connection-wizard.mjs` mounts into the GM ApplicationV2 setup. It collects the MA
|
The GM supplies the private trusted HTTPS MA origin and access token. Authentication
|
||||||
origin, private access token, exact dedicated receiver name, existing private
|
reads account-authorized music providers. The official pinned Sendspin SDK generates
|
||||||
identity/pairing backup and ownership/logging/playback acknowledgments. There are
|
one X25519 identity for the campaign, GM user and MA origin. Its identity, pairing
|
||||||
no credential-bearing world settings, localStorage entries, URLs or logs. The private
|
storage, catalog key and name are encrypted in local IndexedDB with a non-extractable
|
||||||
connection profile lives in module closure memory until disconnect/reload. A trusted
|
AES-GCM key. The key is stored in the same browser; this does not protect against
|
||||||
GM can inspect their own browser memory; all same-origin code must be trusted.
|
trusted-origin scripts or theft of the complete browser profile. The token is never
|
||||||
|
persisted. Failed attempts retain private inputs in tab memory; changing the MA
|
||||||
|
origin never reuses its token or identity.
|
||||||
|
|
||||||
The pinned SDK derives the one known receiver ID from the imported X25519 private
|
Connect audio first authenticates the `/ws` API session, then authenticates
|
||||||
identity. The wizard queries only `players/get` for that ID, checks the exact name
|
`/sendspin` using that token and the SDK-generated client ID. MA 2.10.6 associates
|
||||||
and Sendspin provider, then validates standalone topology with the shared MA client.
|
this new web receiver with already-authenticated API sessions for the token. The
|
||||||
It never enumerates household players or registers a new receiver. The selector
|
same API session must therefore survive pairing, catalog reads and playback.
|
||||||
contains only this verified imported receiver; import a different authorized backup
|
`sendspin/pair_web_player` pairs only this identity to the calling account. Noise
|
||||||
to select a different dedicated receiver. Selection alone grants no household control.
|
activation and clock synchronization precede exact ID/name/provider/topology checks.
|
||||||
Read-only setup allows the existing receiver to be unavailable during handover; writes
|
During startup, a successful null queue lookup is retried briefly on the same
|
||||||
still require an available/enabled standalone target with its own active queue.
|
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.
|
||||||
|
|
||||||
A fixed `providers` read filtered to music supplies account-authorized provider IDs.
|
The receiver uses SDK software volume. Fresh receivers do not report volume before
|
||||||
The existing bounded catalog reader paginates library playlists/radios, validates
|
capabilities are advertised, so volume cannot be a preconnection requirement. Static
|
||||||
provider mappings and returns opaque HMAC references and display names. Normal
|
account-authorized playlist tracks become opaque HMAC references bound to the stored
|
||||||
selectors show playlists; radio and synthetic transport remain outside normal setup.
|
catalog key and campaign. Scene/world flags persist those references, never MA URIs,
|
||||||
Catalog keys derive from the private identity and world ID, so reconnecting with the
|
endpoints, tokens or receiver secrets.
|
||||||
same identity/world preserves selections. A full legacy profile can retain its
|
|
||||||
catalogKey/namespace. Saved references never contain upstream URIs or credentials.
|
|
||||||
|
|
||||||
The `/ws` API uses first-message token authentication and bounded correlated responses;
|
## Audio and listeners
|
||||||
`/sendspin` uses first-message authentication followed by official SDK Noise transport.
|
|
||||||
No HTTP CORS dependency or arbitrary MA proxy is introduced. The SDK/dependency
|
|
||||||
versions, hashes and licenses remain unchanged from v0.5.0. No upstream install hooks.
|
|
||||||
|
|
||||||
## Audio and automatic listeners
|
The pinned official SDK negotiates PCM, performs Noise and time synchronization,
|
||||||
|
and decodes audio. A bounded Web Audio scheduler accepts the normal approximately
|
||||||
|
four-second stream-ahead window (six-second ceiling, 512 nodes and 2 MiB of decoded
|
||||||
|
buffers). Timestamped partial clears trim only affected audio. Full clears and ends
|
||||||
|
stop the stream. A software gain and output meter feed the GM speakers and a single
|
||||||
|
MediaStreamDestination track for listener distribution.
|
||||||
|
|
||||||
```mermaid
|
User document public keys authenticate ephemeral ECDH/AES-GCM invitation delivery.
|
||||||
flowchart LR
|
Private keys stay in memory. Invitations are bound to world, sender, recipient,
|
||||||
C[Scene and combat controller] --> N[Owned Foundry playlists]
|
epochs and expiry. Each player receives only its own WebRTC capability. Bounded
|
||||||
C --> G[Guarded provider in GM browser]
|
AES-GCM envelopes carry SDP over Foundry’s module socket; audio uses DTLS-SRTP,
|
||||||
G -->|Private authenticated WSS| MA[Music Assistant]
|
never PCM over that socket. Firefox’s session-level SDP direction default is
|
||||||
MA -->|Authenticated Sendspin| S[GM SDK and Web Audio]
|
correctly overridden by the sole audio media direction. Offers remain recvonly;
|
||||||
S -->|DTLS SRTP audio| P[Active player browsers]
|
answers remain sendonly. Video, data and injected sender media are rejected.
|
||||||
U[Permission controlled User public keys] --> E[Encrypted invitation bootstrap]
|
|
||||||
E --> P
|
|
||||||
S <-->|Encrypted bounded SDP via Foundry module socket| P
|
|
||||||
```
|
|
||||||
|
|
||||||
At ready each client generates a memory-only non-extractable P-256 private key and
|
Up to eight listeners negotiate automatically. Invitations renew after 20 minutes
|
||||||
publishes only its public key and random epoch to its own User document flag.
|
and expire after 30. Failed negotiation times out after 20 seconds; disconnected
|
||||||
Foundry's server-enforced User update permissions are the authentication boundary;
|
peers are revoked after 10 seconds and the 15-second reconciliation loop can issue
|
||||||
socket `from`/`isGM` claims alone are never trusted. The single active GM derives an
|
fresh invitations. One user gesture unlocks browser audio when required. A stable
|
||||||
AES-GCM key by ECDH with the intended active non-GM's current document public key.
|
HTMLAudioElement pumps the incoming remote track; Web Audio provides an optional
|
||||||
Only an encrypted expiring audio invitation is broadcast, bound to world, sender,
|
activated playback path. Default ICE has no public STUN/TURN service. WAN delivery
|
||||||
recipient and both epochs. Players authenticate against the current active GM's
|
requires a viable existing ICE route and is not inferred from local tests.
|
||||||
User public key. Tampering, unknown fields, replay, wrong world/recipient/epoch,
|
|
||||||
expired capability and role changes fail closed. Document permission behavior must
|
|
||||||
also be checked with distinct users in real Foundry before live acceptance.
|
|
||||||
|
|
||||||
The invitation contains a unique per-peer 256-bit capability, never MA credentials,
|
## Transitions and recovery
|
||||||
SDK keys or endpoint. The existing SignalCodec then encrypts/authenticates bounded
|
|
||||||
SDP/ICE/DTLS signaling with session/peer/direction/sequence/expiry binding. Audio uses
|
|
||||||
WebRTC audio tracks, never PCM over Foundry sockets. No microphone, video or data
|
|
||||||
channel. Up to eight peers; fresh invites replace each user's prior peer. Invitations
|
|
||||||
last 30 minutes and renew after 20 minutes; failed peers are retried on the 15-second
|
|
||||||
reconciliation timer. New logins/key epochs trigger delivery. Default ICE servers
|
|
||||||
are empty. Optional private backup `listenerNetwork` holds explicit ICE settings.
|
|
||||||
|
|
||||||
The listener automatically negotiates and attempts playback. If autoplay is denied,
|
Manual override/silence > explicit boss > started combat in the active scene >
|
||||||
Campaign audio → Enable Audio uses a direct click. Stop Audio opts out until Enable
|
ambient > world default > silence. No system actor schemas are used. The existing
|
||||||
Audio. The same HTMLAudioElement survives normal renewals. Latest tab publishing a
|
serialized controller checks campaign/session/generation and current authority.
|
||||||
User key receives subsequent invitations; use one audio tab per account. Reloads,
|
A single active GM plus a Web Lock excludes common duplicate tabs; this is not a
|
||||||
network failures, browser suspends and relay expiry can require reconnecting.
|
server-side distributed fence or seamless handover protocol.
|
||||||
The GM also hears decoded audio and can resume their AudioContext through the UI.
|
|
||||||
|
|
||||||
## Policy, authority and fallback
|
Every queue mutation verifies the exact dedicated target, standalone topology and
|
||||||
|
its own active queue. Signed snapshots retain ordered duplicates, index, repeat,
|
||||||
|
whole-second position and state, scoped to campaign/session/fence/generation for up
|
||||||
|
to 12 hours. Ambiguous writes latch closed and stop automation; they are not retried.
|
||||||
|
MA Sendspin lacks native pause in 2.10.6, so pause retains a logical stopped-queue
|
||||||
|
snapshot and resume explicitly seeks its item. A paused restore rebuilds without
|
||||||
|
briefly playing. This logical pause state is memory-only.
|
||||||
|
|
||||||
Manual override/silence > explicit eligible boss > started scene combat > scene
|
Reconnecting to a remembered owned receiver can attach to its existing queue
|
||||||
ambient > world default > silence. Scene/world flags and module settings persist
|
without replacing it. Automation remains paused for explicit resumption when that
|
||||||
ambient/combat/boss/native fallback references. Legacy assignments and native ownership
|
queue is nonempty. Crash/reload cannot guarantee restoration of an interrupted
|
||||||
remain supported. Effects and AmbientSound documents are outside the owned music set.
|
ambient stack or logical pause position. No crossfade or independent simultaneous
|
||||||
Bosses use explicit module flags, not system actor schemas. Boss/manual controls are
|
layers is implemented with the single upstream queue. Native playback uses only
|
||||||
in a disclosure; companion/synthetic/manual capability tools require advanced development.
|
explicitly owned playlists; effects and AmbientSound remain untouched.
|
||||||
|
|
||||||
Explicit catalog playback opt-in enables registered static catalog playlists through
|
## Verification boundary
|
||||||
the existing serialized guarded provider. Dynamic/shuffled/autoplay/overlay/ended or
|
|
||||||
nonstandard speed states remain unsupported. Every mutation checks campaign/session/
|
|
||||||
generation, current authority, exact target/name/provider, standalone topology and own
|
|
||||||
active queue. Startup requires an empty idle queue. Signed five-minute snapshots retain
|
|
||||||
ordered duplicates, index, whole-second position, pause/state and repeat. Ambiguous
|
|
||||||
writes latch closed; no blind retry or arbitrary queue transfer/group/global stop.
|
|
||||||
Native fallback uses only explicitly owned Foundry playlists and does not reconcile
|
|
||||||
an uncertain active MA target automatically.
|
|
||||||
|
|
||||||
A single active GM plus same-origin Web Lock excludes common duplicate GM tabs.
|
Source archive evidence separates real MA authentication/provisioning/catalog/audio,
|
||||||
This is not a distributed MA server-side fence. Foundry disconnect/GM role loss ends
|
actual browser WebRTC, actual Foundry ApplicationV2 rendering and offline regressions.
|
||||||
forwarding and writes; it does not guarantee crash restoration. No seamless GM
|
Browser integration uses the deployed Foundry origin with local source assets supplied
|
||||||
handover, long-run drift/synchronization guarantee, crossfade or simultaneous layers.
|
by Playwright, not an installed logged-in Foundry world. Mac networking, actual User
|
||||||
The optional companion remains in gateway/ as development source. No host worker or
|
permission enforcement, Foundry socket delivery and WAN behavior still require the
|
||||||
TLS route is installed; any production change requires separate authorization.
|
single consolidated acceptance sequence in TESTING.md.
|
||||||
|
|
||||||
## Evidence
|
|
||||||
|
|
||||||
Offline tests and a Chromium DOM fixture cover this revision. Historical
|
|
||||||
`evidence/browser-audio.json` measured two local synthetic listeners using the official
|
|
||||||
PCM decoder, Web Audio and WebRTC: signal at 1.757 s, about 42.3 kbit/s aggregate RTP.
|
|
||||||
It was not Foundry, real MA, WAN, audibility or synchronization verification. Prior
|
|
||||||
read-only catalog/target checks and idle queue controls remain separate evidence.
|
|
||||||
No new credential use, receiver registration, production connection or playback
|
|
||||||
mutation was performed for v0.6.0. See TESTING.md for remaining acceptance gates.
|
|
||||||
@@ -1,5 +1,28 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## 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
|
## 0.6.0 — GM connection interface
|
||||||
|
|
||||||
- Add a GM Music Assistant connection wizard: private server/token entry, existing
|
- Add a GM Music Assistant connection wizard: private server/token entry, existing
|
||||||
|
|||||||
+74
-169
@@ -1,184 +1,89 @@
|
|||||||
# Adaptive Music 0.6.0 — setup and manual publication
|
# Install and connect — 0.7.0
|
||||||
|
|
||||||
One Foundry module ZIP, ID **adaptive-music**, author **CheddahBoxMB**, targeting
|
## Normal setup
|
||||||
Foundry v14.371 and MA 2.10.6. No other Foundry modules, Docker containers, VMs/LXCs
|
|
||||||
or mandatory services. Native music can be configured without Music Assistant.
|
|
||||||
|
|
||||||
The user reports v0.5.0 installed/activated with D&D 5e 6.1.2 and both windows
|
1. Install or update **Adaptive Music** using the existing Foundry manifest URL.
|
||||||
rendering. v0.6.0 has offline/fixture validation; live MA audio remains to be tested.
|
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. Enter the private
|
||||||
|
trusted **HTTPS Music Assistant server address** and the dedicated account’s access
|
||||||
|
token, then select **Authenticate**. Use the origin, without a subpath or query.
|
||||||
|
3. Select **Connect audio**. The module automatically creates or reconnects its own
|
||||||
|
campaign receiver and pairs it to the authenticated account. No receiver identity
|
||||||
|
export or JSON backup import is needed. The selector includes only this browser’s
|
||||||
|
campaign-owned receiver; it does not enumerate household speakers.
|
||||||
|
4. Assign ambient and combat playlists to the selected scene and save assignments.
|
||||||
|
World defaults and boss/manual controls are optional. Enable music automation.
|
||||||
|
5. Players connect automatically. If a browser requires activation, open Campaign
|
||||||
|
audio and select **Enable Audio** once. Keep one audio tab per account.
|
||||||
|
|
||||||
## GM setup
|
The token stays in this tab’s memory, including across failed attempts and setup
|
||||||
|
window closure. Reload or Disconnect forgets it. Receiver identity is encrypted in
|
||||||
|
this GM browser’s local storage and reused after reauthentication. A changed MA
|
||||||
|
origin needs a new login and a separately scoped receiver. Clearing site storage
|
||||||
|
forgets the receiver. Receiver options can name a new receiver; existing remembered
|
||||||
|
names remain identity-bound. Forget remembered receiver removes the local identity
|
||||||
|
only, leaving MA resources and queues untouched.
|
||||||
|
|
||||||
Open Settings → Adaptive Music setup → Configure music.
|
Connection recovery → Reconnect remembered receiver reuses this tab’s credentials and preserves the queue while pausing automation. Optional existing STUN/TURN settings are in Receiver options; no public ICE service is enabled by default.
|
||||||
|
|
||||||
1. Enter the **Music Assistant server address**, using a trusted private HTTPS origin
|
Reconnecting to an owned nonempty queue preserves it. Apply the automation setting
|
||||||
such as `https://ma.example.test` (placeholder). Use the server origin without a
|
when ready to resume scene control. Unknown mutation outcomes stop automation and
|
||||||
subpath, query, username or password. The browser uses `wss://…/ws` for control
|
require review; they are never silently replayed. Pause is emulated for MA 2.10.6
|
||||||
and `wss://…/sendspin` for receiver audio. It does not use cross-origin HTTP `/api`.
|
Sendspin by preserving a stopped queue’s index/position in the active GM session.
|
||||||
2. Enter a **private GM access token** from an MA account authorized for the dedicated
|
Crossfade and restoration after a GM crash/reload are not guaranteed. Old experimental identity-based assignments may need playlist reselection once; the remembered v0.7.0 receiver keeps subsequent catalog references stable.
|
||||||
campaign receiver and music providers. Never give this token to players. It remains
|
|
||||||
only in this GM tab's memory and is cleared from the input after testing.
|
|
||||||
3. Import the **existing dedicated receiver's private identity/pairing backup** as JSON
|
|
||||||
and enter its exact MA player name (default: Adaptive Music DEV). A flat Sendspin
|
|
||||||
storage map or an existing full private GM profile containing `identityStorage`
|
|
||||||
is accepted, up to 64 KiB. The map must include `sendspin-identity-sk` and the
|
|
||||||
associated `sendspin-*` pairing/trust records from that receiver's SDK storage.
|
|
||||||
Keep the complete backup private; never put it in Foundry settings, module files,
|
|
||||||
chat or a release. Development backups belong in ignored `.local/`, mode 0600.
|
|
||||||
4. Confirm dedicated campaign ownership and that MA **VERBOSE raw WebSocket frame
|
|
||||||
logging is disabled**. The pinned MA source can log token-bearing auth frames
|
|
||||||
at that level. Review this before connecting; the wizard cannot check remote logs.
|
|
||||||
5. Optionally allow **catalog playlist playback**. Test connection and load playlists
|
|
||||||
performs read-only authentication/target/provider/catalog checks, with no queue
|
|
||||||
mutations. The player selector contains only the receiver verified from the
|
|
||||||
imported private identity. To select another owned receiver, import its matching
|
|
||||||
backup and name. Household speakers are never enumerated or selected.
|
|
||||||
6. Stop the original web receiver before handover. Reconcile the dedicated queue to
|
|
||||||
**empty and idle** in MA. Select **Connect audio** to start the GM SDK receiver.
|
|
||||||
If time sync/Noise pairing cannot complete, the operation fails closed. Keep one
|
|
||||||
active GM and one GM host tab. The GM hears receiver audio; Enable GM audio resumes
|
|
||||||
the context if the browser suspends it.
|
|
||||||
7. Select dedicated **Foundry music and fallback** playlists, save ownership and reload
|
|
||||||
if ownership changed. Reconnect MA after reload. Choose world defaults and a scene's
|
|
||||||
**ambient playlist**, **combat playlist** and optional Foundry fallback. Save assignments.
|
|
||||||
Boss and manual controls are in their disclosure. Enable music automation when ready.
|
|
||||||
|
|
||||||
The module cannot reconstruct a receiver identity from a player name/ID or MA token.
|
## Connection diagnostics
|
||||||
It deliberately does not create/register a new receiver. If you have no matching
|
|
||||||
private SDK backup, MA audio cannot start; native playback still works. Obtain an
|
|
||||||
authorized backup from the existing dedicated web receiver's operator. The backup
|
|
||||||
must come from the SDK/browser instance that owns that receiver, not a server API
|
|
||||||
player export. No generic export feature or production provisioning is assumed.
|
|
||||||
Malformed/mismatched identities fail before a receiver connection. Existing pairing
|
|
||||||
trust must match the MA server; this wizard does not silently enable unpaired access.
|
|
||||||
|
|
||||||
Profiles from v0.5.0 may include catalogKey/namespace to preserve legacy opaque IDs.
|
Setup displays the actual stage: authentication, Sendspin connection, pairing,
|
||||||
Otherwise IDs derive consistently from the imported private identity and world ID.
|
clock sync, catalog or ready. It shows decoded frames, GM audio state and connected
|
||||||
Scene assignments persist across reconnect/reload and display a saved unavailable
|
listeners. **Check browser connection (no MA token)** tests both WebSocket routes
|
||||||
choice while offline. Re-enter GM authentication/import the same backup after reload.
|
from the actual Foundry page and identifies enforced CSP blocks. It does not send
|
||||||
Disconnect clears the private profile, stops automation/forwarding and leaves MA queue
|
an MA authentication frame; normal browser cookies may still accompany the handshake.
|
||||||
state for review; it does not promise automatic restoration after a crash or disconnect.
|
**Copy connection diagnostics** supplies a report without address, token, receiver
|
||||||
|
keys or playlist titles. No browser developer console is required.
|
||||||
|
|
||||||
## Players
|
| Result | Action |
|
||||||
|
|
||||||
Players need no MA login, address, receiver identity or pasted invitation. Active
|
|
||||||
non-GM accounts publish only an ephemeral public key through their own Foundry User
|
|
||||||
document. The connected GM automatically sends individually encrypted expiring audio
|
|
||||||
invitations, then WebRTC negotiates audio. If sound is blocked by autoplay, open
|
|
||||||
Settings → Campaign audio → **Enable Audio** once. Stop Audio opts out until enabled
|
|
||||||
again. No microphone permission is requested. Use one listening tab per account.
|
|
||||||
Native Foundry playback uses Foundry's existing browser audio controls.
|
|
||||||
|
|
||||||
Invitation renewal and new player logins are automatic while the GM stays online.
|
|
||||||
The default supports up to eight listeners and uses no external STUN/TURN. A network
|
|
||||||
failure, suspended browser or expired relay credential may need reconnecting. GM loss
|
|
||||||
stops forwarding; seamless failover, crash restore and exact listener synchronization
|
|
||||||
are not promised. Client key/permission/socket behavior still needs live v14 acceptance.
|
|
||||||
|
|
||||||
## HTTPS/WSS requirements and diagnostics
|
|
||||||
|
|
||||||
| Path | Requirement |
|
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| Remote browser → Foundry | Trusted HTTPS and working Foundry socket. Web Crypto/Web Locks need a secure context. |
|
| 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. |
|
||||||
| GM browser → MA control | Trusted private HTTPS origin with WSS upgrade on `/ws`; first-message token auth. |
|
| 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. |
|
||||||
| GM browser → receiver | Same origin's WSS `/sendspin` route, first-message auth and SDK pairing/trust. |
|
| API auth denied | Enter a valid token; the remembered receiver is retained. |
|
||||||
| Player → MA | No route or credential required. Players talk only to Foundry and the GM's WebRTC peer. |
|
| Sendspin auth/pair/sync fails | Check the separate authenticated /sendspin route and the account’s web-player control permission. |
|
||||||
| GM ↔ player media | A viable WebRTC ICE path; restrictive NAT/firewalls may require an existing approved TURN relay. |
|
| 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. |
|
||||||
|
|
||||||
HTTPS Foundry cannot use plain HTTP/ws MA in the supported configuration, even if
|
Use trusted HTTPS for Foundry and private HTTPS/WSS for both MA `/ws` and `/sendspin`.
|
||||||
Sendspin encrypts its payload. The module rejects this, including loopback downgrade.
|
Keep Nginx access restrictions, Origin, certificate validation and browser protections.
|
||||||
Remote plain HTTP Foundry is also rejected for GM MA connections. Loopback HTTP is
|
Keep MA raw-frame VERBOSE logging disabled. No public API/proxy, core modification,
|
||||||
reserved for offline development, not a remote deployment solution. Browser exceptions
|
additional container, service, VM or LXC is required by this module. A direct HTTP MA
|
||||||
are not a supported workaround. Do not enable insecure content, disable certificate
|
address cannot be used from HTTPS Foundry. Default ICE does not use a public relay;
|
||||||
checks or Web security, or expose an unrestricted MA proxy publicly.
|
remote players still need a viable existing WebRTC path.
|
||||||
|
|
||||||
A valid solution uses an **existing private trusted TLS endpoint** reachable from the
|
Ubuntu Firefox and Chromium reached the deployed HTTPS endpoints from the Foundry
|
||||||
GM browser: MA's supported TLS endpoint if already available, or an operator-approved
|
origin through normal public DNS resolution. The operator’s Mac instead maps MA to
|
||||||
TLS virtual host on existing infrastructure forwarding the authenticated `/ws` and
|
the private proxy; that private proxy’s TCP 443 route times out from Ubuntu before
|
||||||
`/sendspin` WebSocket routes to the private MA service. Preserve upgrade headers,
|
TLS. A single temporary VM-to-proxy TCP 443 flow has been proposed to the operator
|
||||||
Origin and MA authentication; use browser-trusted certificates and private access
|
with rollback in ignored .local/PRIVATE-ROUTE-REQUEST.md; it has not been applied.
|
||||||
control. Both routes must work, not just the MA homepage. The origin is dedicated
|
No persistent DNS or broad proxy change is requested. The original Mac path remains
|
||||||
because the current client resolves routes from `/`; subpath deployments are unsupported.
|
unverified. Run TESTING.md’s one acceptance sequence before public publication.
|
||||||
No route, certificate, Nginx, firewall or service configuration was changed here.
|
|
||||||
The user's actual HTTP MA endpoint remains blocked until this TLS prerequisite is
|
|
||||||
satisfied. There is no release-only JavaScript fix for an unreachable/insecure endpoint.
|
|
||||||
|
|
||||||
Foundry CSP `connect-src` must permit that private WSS origin. MA/reverse proxy must
|
## Manual Gitea publication
|
||||||
accept the Foundry browser Origin without stripping authentication. Browser local-network
|
|
||||||
permission, private DNS/VPN/routing and certificate trust are separate checks; enabling
|
|
||||||
CORS on `/api` alone does not solve WSS. Browser WebSocket errors intentionally reveal
|
|
||||||
little. Diagnostics describe likely causes without logging raw upstream responses/tokens.
|
|
||||||
Inspect browser network status privately if required; never share token-bearing frames.
|
|
||||||
|
|
||||||
For WAN ICE, a full private backup may include `listenerNetwork` with `iceServers`
|
The existing stable manifest and versioned download mechanism is preserved:
|
||||||
and optional `relayOnly: true`. Use only an existing approved STUN/TURN endpoint and
|
|
||||||
short-lived TURN username/credential/`expires` (Unix milliseconds, at most one hour).
|
|
||||||
No silent public relay is configured. Relay-only needs TURN. Renew expired relay
|
|
||||||
credentials by disconnecting and importing an updated private profile. No additional
|
|
||||||
service, container, VM or machine is installed. Without a viable ICE path, automatic
|
|
||||||
setup cannot make audio reach a remote browser.
|
|
||||||
|
|
||||||
| Diagnostic | Action |
|
- Manifest: `https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/raw/branch/main/module.json`
|
||||||
| --- | --- |
|
- v0.7.0 asset: `https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/releases/download/v0.7.0/adaptive-music.zip`
|
||||||
| Mixed content / insecure context | Supply trusted HTTPS/WSS; do not bypass browser protections. |
|
|
||||||
| Identity required / mismatch | Import the matching dedicated SDK identity and pairing backup. |
|
|
||||||
| Dedicated target denied | Check exact name, account target permission and standalone topology. |
|
|
||||||
| Reconciliation required | Empty/idle the dedicated queue and stop its other web receiver before handover. |
|
|
||||||
| No catalog providers/items | Check account provider scopes, library contents and provider availability. |
|
|
||||||
| WSS unavailable | Check TLS trust, both upgrade routes, Origin/CSP, token and private connectivity. |
|
|
||||||
| Connected but silent | Check MA playback, mute/volume, GM context, player Enable Audio and ICE connectivity. |
|
|
||||||
| Authority changed | Use one active GM; stop automation and explicitly reconnect. |
|
|
||||||
|
|
||||||
Reference: [MDN mixed content](https://developer.mozilla.org/en-US/docs/Web/Security/Defenses/Mixed_content),
|
These are the established repository’s URLs; this work never contacted Gitea or
|
||||||
[Web Audio practices](https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API/Best_practices),
|
verified public asset availability. After acceptance, manually publish the included
|
||||||
[WebRTC connectivity](https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Connectivity),
|
source to your existing repository, create tag/release `v0.7.0`, attach
|
||||||
[Foundry v14 User documents](https://foundryvtt.com/api/v14/classes/foundry.documents.User.html).
|
`adaptive-music.zip` and the included manifest/checksums, and update the branch
|
||||||
Pinned MA/SDK source provenance is in `evidence/upstream.json` and `vendor/provenance.json`.
|
manifest only after its versioned asset exists. The outer bundle includes full
|
||||||
The network arrangement above is a deployment requirement, not verified connectivity
|
source, docs, licenses, metadata and SHA256SUMS. Keep the previous immutable release
|
||||||
or authorization to change production. Any such change needs separate concrete review.
|
assets for rollback. To roll back, restore the prior branch manifest/module ZIP;
|
||||||
|
MA queues and remembered browser identities are not automatically deleted.
|
||||||
## Advanced development
|
|
||||||
|
|
||||||
Settings → Show advanced development controls (client setting, defaults off) reveals
|
|
||||||
optional companion controller/synthetic test controls and manual listener capability
|
|
||||||
entry. These are not required for normal operation. Companion source remains in
|
|
||||||
`gateway/`; no companion or co-located worker is installed or started by the module.
|
|
||||||
|
|
||||||
## Build and publish manually to the existing Gitea
|
|
||||||
|
|
||||||
The repository and v0.5.0 publication are user-reported. This work did not access,
|
|
||||||
authenticate to, push to or verify the Git server. Existing manifest URL is preserved.
|
|
||||||
|
|
||||||
```sh
|
|
||||||
python3 scripts/release.py
|
|
||||||
python3 scripts/release.py --validate dist/releases/v0.6.0/adaptive-music.zip
|
|
||||||
```
|
|
||||||
|
|
||||||
Output `dist/releases/v0.6.0/adaptive-music-release-v0.6.0.zip` contains installable
|
|
||||||
`adaptive-music.zip`, standalone `module.json`, complete `adaptive-music-source.zip`,
|
|
||||||
docs, notices/licenses, release metadata and SHA256SUMS. An adjacent `.sha256` checks
|
|
||||||
the outer bundle. Source metadata identifies the base commit; the included source
|
|
||||||
archive and its digest identify the actual release sources, including current edits.
|
|
||||||
Packaging is offline, requires no credentials and never contacts the Git server.
|
|
||||||
|
|
||||||
1. Back up the world and existing module. Review CHANGELOG and remaining acceptance
|
|
||||||
limits. Unpack the outer bundle locally; check SHA256SUMS.
|
|
||||||
2. Import the **source archive contents** through your normal Gitea/local Git workflow,
|
|
||||||
preserving directories/notices. Do not upload `.local/`, credentials, node_modules
|
|
||||||
or deployment files. Prepare on a release branch; keep the old main manifest until
|
|
||||||
the new versioned asset is available.
|
|
||||||
3. Create immutable tag/release **v0.6.0** in your existing repository. Upload
|
|
||||||
**adaptive-music.zip** and **module.json** with those exact attachment names.
|
|
||||||
The source archive, checksums and outer bundle can be extra review artifacts.
|
|
||||||
4. Confirm the ZIP is anonymously downloadable with the expected checksum at:
|
|
||||||
`https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/releases/download/v0.6.0/adaptive-music.zip`
|
|
||||||
5. Promote the generated standalone manifest to **main/module.json** only after the
|
|
||||||
attachment exists. Preserve the existing stable install/update URL:
|
|
||||||
`https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/raw/branch/main/module.json`
|
|
||||||
6. Use Foundry Setup → Update Modules, then activate in an isolated v14.371 world
|
|
||||||
and follow TESTING.md. Do not use the source/outer ZIP as Foundry's module download.
|
|
||||||
No `compatibility.verified` claim is added based on offline checks or v0.5.0 rendering.
|
|
||||||
|
|
||||||
Repository base can be changed offline with `--repository https://github.com/OWNER/REPOSITORY`
|
|
||||||
and a separate `--output dist/alternate-release`. No URL in this guide was contacted
|
|
||||||
by this build. No automatic publication or production deployment is performed.
|
|
||||||
+43
-52
@@ -1,59 +1,50 @@
|
|||||||
# Adaptive Music progress — 0.6.0
|
# Adaptive Music progress — 0.7.0 staged acceptance
|
||||||
|
|
||||||
The user reports v0.5.0 published to their existing Gitea, installed through the manifest,
|
Standalone module work now includes automatic campaign receiver provisioning and
|
||||||
activated on Foundry v14.371 with D&D 5e 6.1.2, and configuration/listener windows rendering.
|
account-bound pairing, remembered encrypted browser-local identity, memory-only token
|
||||||
That supersedes the previous unknown publication/install status for v0.5.0 only. This
|
retention/retry, scene assignments, listener bootstrap, guarded transitions and queue
|
||||||
work did not access the Git server, use MA credentials or change production services.
|
restoration. Existing Gitea URLs/manual release mechanism are preserved. No Git host
|
||||||
|
was accessed and no production infrastructure/core versions were changed.
|
||||||
|
|
||||||
## Implemented for v0.6.0
|
## Defects
|
||||||
|
|
||||||
- Three-step GM connection wizard: private server/token, dedicated existing receiver
|
| Defect | Implemented and tested | Remaining acceptance |
|
||||||
backup/name and ownership/logging/playback acknowledgments, read-only target/catalog
|
| --- | --- | --- |
|
||||||
check, verified receiver selection, Connect audio, resume/disconnect and diagnostics.
|
| AM-001 layout | Actual Foundry v14.371 ApplicationV2 at 380/640px; Chromium fixture at 380/640/1000px | Operator’s logged-in-world theme |
|
||||||
- Existing official Sendspin/Web Audio/WebRTC host integrated with the UI. GM hears
|
| AM-002 provisioning | SDK-created identity, authenticated dedicated web-receiver pairing, no normal JSON import; real MA tests | Normal installed-world flow on Mac |
|
||||||
receiver audio; explicitly authorized static catalog playlists are eligible through
|
| 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 |
|
||||||
the existing guarded serialized provider, rather than only synthetic sequences.
|
| 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 |
|
||||||
- Automatic encrypted listener bootstrap with memory-only P-256 private keys, public
|
| AM-005 cross-origin | Real deployed-origin authentication works in Ubuntu Firefox/Chromium; same-session receiver ACL, Firefox SDP and buffer bugs fixed | Original Mac-specific pre-upgrade failure is not reproduced or independently resolved |
|
||||||
keys on permission-controlled User documents, AES-GCM invitation delivery bound to
|
| MA catalog playback | Firefox 159 and Chromium 159 measured real audio at both listeners across ambient, combat and restoration | Actual Foundry world, physical devices and WAN acceptance |
|
||||||
world/account/epochs, and existing per-peer encrypted SDP. No credential/address/SDK
|
|
||||||
identity goes to players. Default eight peers, 30-minute invites renewed after 20
|
|
||||||
minutes, retries/reconciliation every 15 seconds while GM host is online.
|
|
||||||
- Player interface normally needs only Enable Audio when browser activation is required.
|
|
||||||
No pasted code or MA login. Native playback/fallback, persistent scene ambient/combat/
|
|
||||||
boss references, world defaults and explicit playlist ownership remain intact.
|
|
||||||
- Companion/synthetic/manual capability controls hidden behind a client-scoped advanced
|
|
||||||
development setting. World defaults and boss/manual controls use disclosures.
|
|
||||||
- Offline manual release v0.6.0: one installable ZIP, stable existing manifest URL,
|
|
||||||
immutable version-specific download, complete source, docs/licenses and checksums.
|
|
||||||
No new dependencies, mandatory services/containers, core patches or browser bypass.
|
|
||||||
|
|
||||||
## Verification and unresolved prerequisites
|
## Technical findings
|
||||||
|
|
||||||
91 JavaScript and 15 Python regressions, privacy/attribution audit and pinned upstream
|
- Tested Foundry page has no CSP header/meta policy. Both HTTPS origins authenticate
|
||||||
verification are recorded in `evidence/v0.6.0-checks.txt`. A Chromium 143.0.7499.4 DOM
|
from Ubuntu using public DNS. The Mac’s private proxy route is a different path; TCP 443 to that proxy times out from Ubuntu. One narrowly scoped temporary access proposal with rollback is prepared under ignored .local/PRIVATE-ROUTE-REQUEST.md and awaits operator execution.
|
||||||
fixture verifies the wizard, catalog selection/save, private field clearing, hidden
|
- MA grants a new browser receiver access through API sessions authenticated before
|
||||||
advanced controls and listener activation. These are offline fixtures, not live
|
Sendspin auth. Replacing the API socket breaks a restricted account’s access.
|
||||||
Foundry/MA playback or network verification. Historical decoder/WebRTC synthetic
|
- Firefox reached an available paired receiver before MA returned its queue. Setup
|
||||||
measurements and live idle/read-only MA evidence remain separately identified.
|
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.
|
||||||
|
|
||||||
The actual private MA deployment still needs browser-trusted HTTPS/WSS for both `/ws`
|
The live follow-up records real PCM and two listener signals, emulated pause, seek,
|
||||||
and `/sendspin`; the previous HTTP endpoint is unsupported from HTTPS Foundry. INSTALL.md
|
resume, volume, and queue restoration in Firefox and Chromium. Earlier catalog
|
||||||
now explains TLS, private routing, Origin/CSP and ICE requirements. No JavaScript-only
|
startup failed with MA `MediaNotFoundError` in both engines. The cause of those
|
||||||
workaround can replace a secure reachable endpoint. No route, logging or certificate
|
failures remains unconfirmed. The controller preserves the failed command and skips
|
||||||
configuration was inspected or changed. A matching existing SDK identity/pairing backup
|
rollback after an uncertain write. See `evidence/v0.7.0-live-follow-up.json`.
|
||||||
is also required; no receiver was registered or commandeered. GM authentication is
|
|
||||||
memory-only and must be entered after reload. A private legacy catalog key/namespace
|
|
||||||
can be imported to preserve old IDs.
|
|
||||||
|
|
||||||
Remaining live acceptance includes v0.6.0 ApplicationV2/SceneConfig behavior, Foundry
|
The v0.7.0 bundle is staged locally for acceptance. Publication remains pending the
|
||||||
User document permission enforcement/socket signaling with distinct users, MA pairing/
|
Mac private route, actual Foundry hooks, sockets and User permissions, and physical
|
||||||
time sync and audible real playlist playback, nonempty interruption/restore, normal
|
device, WAN and invitation-renewal checks in TESTING.md.
|
||||||
one-click audio activation across browsers, renewal/reconnect and WAN/NAT/TURN paths.
|
Crossfade, durable crash restoration, seamless handover and WAN synchronization
|
||||||
The user must separately authorize credentials/production changes. No such action
|
remain unsupported.
|
||||||
was taken. TESTING.md gives isolated acceptance steps and exact limits.
|
|
||||||
|
|
||||||
Browser-only authority still uses a single active GM and same-origin Web Lock, not a
|
|
||||||
distributed server fence. GM loss/crash cannot guarantee restoration or continuity.
|
|
||||||
Crossfade, independent simultaneous layers and synchronization/drift guarantees remain
|
|
||||||
unimplemented/unverified. Optional companion source is preserved in gateway/ and the
|
|
||||||
historical experimental branch; no infrastructure is deployed or mandatory.
|
|
||||||
@@ -1,46 +1,29 @@
|
|||||||
# Adaptive Music — 0.6.0
|
# Adaptive Music — 0.7.0
|
||||||
|
|
||||||
Independent open-source project by **CheddahBoxMB**, targeting Foundry VTT
|
Independent open-source Foundry VTT music automation by **CheddahBoxMB**, targeting
|
||||||
**v14.371** and Music Assistant **2.10.6**. System-independent; no other modules,
|
Foundry v14.371 and Music Assistant 2.10.6. System-independent; one Foundry module
|
||||||
containers, VMs/LXCs or mandatory services. Install the single Foundry module ZIP.
|
ZIP, no other required module, container, VM/LXC or companion service.
|
||||||
|
|
||||||
GM setup now includes a Music Assistant connection wizard, private GM authentication,
|
Enter your private HTTPS MA address and authenticate in Adaptive Music setup.
|
||||||
existing dedicated receiver selection by identity backup, catalog-backed playlist
|
Connect the automatically provisioned dedicated campaign receiver, assign ambient
|
||||||
selectors, audio connection and diagnostics. World defaults and separate scene
|
and combat playlists, and enable automation. Players receive WebRTC audio
|
||||||
ambient/combat/boss/Foundry fallback selections persist in Foundry. Native effects
|
automatically, with one Enable Audio click if their browser requires it. No receiver
|
||||||
and AmbientSound documents remain untouched. Automation defaults off.
|
identity export or JSON import is part of setup.
|
||||||
|
|
||||||
The GM browser hosts the bundled official Sendspin SDK, decodes PCM with Web Audio,
|
MA tokens stay in the GM tab’s memory. A campaign/GM/origin-scoped receiver identity
|
||||||
and sends audio to authorized active players over WebRTC. Players connect automatically
|
is encrypted in that browser’s IndexedDB so reconnecting does not create another
|
||||||
and may need one **Enable Audio** click. Neither MA credentials nor its address are
|
receiver. Players receive individually encrypted invitations, not MA credentials.
|
||||||
sent to players. Private credentials and receiver identity stay in GM tab memory;
|
Only that dedicated receiver and explicitly owned Foundry music playlists are
|
||||||
reloading the GM tab requires reconnecting. All code running in the GM browser origin
|
controlled. Household speakers, grouping, queue transfers, sound effects and
|
||||||
must be trusted. Optional companion controls are hidden under advanced development.
|
AmbientSound documents are outside the control surface.
|
||||||
|
|
||||||
MA needs trusted private HTTPS/WSS reachable by the GM, an existing dedicated receiver
|
Real MA/browser integration evidence is included in the source archive. Actual
|
||||||
identity/pairing backup, account permissions and authentication-log review. This release
|
Foundry v14.371 ApplicationV2 rendering was tested; a logged-in-world test on the
|
||||||
does not create a receiver or change any service/network configuration. WAN audio may
|
operator’s Mac remains necessary. Ubuntu browser success does not establish Mac
|
||||||
need an already available approved TURN relay. No browser bypasses, public MA proxy,
|
network permissions or WAN reachability. This package is staged for that acceptance;
|
||||||
new service or guaranteed synchronization is provided. See [INSTALL.md](INSTALL.md).
|
publication has not occurred and no Git host was accessed.
|
||||||
|
|
||||||
The user reports v0.5.0 published to their existing Gitea, installed/activated in
|
See INSTALL.md for setup/manual publication, TESTING.md for the consolidated Mac
|
||||||
Foundry v14.371 with D&D 5e 6.1.2, and both windows rendering. This is user-supplied
|
acceptance sequence, SECURITY.md for trust boundaries and PROGRESS.md for status.
|
||||||
installation evidence, not a claim of MA playback. v0.6.0 is checked with offline
|
Crossfade, seamless GM handover, durable crash restore and WAN synchronization
|
||||||
regressions and a Chromium UI fixture; live Foundry/MA audio and WAN acceptance remain
|
claims are not implemented. Attribution and licenses remain in THIRD-PARTY-NOTICES.
|
||||||
pending. Earlier synthetic browser measurements are recorded separately.
|
|
||||||
|
|
||||||
Build without contacting a Git server:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
python3 scripts/release.py
|
|
||||||
python3 scripts/release.py --validate dist/releases/v0.6.0/adaptive-music.zip
|
|
||||||
```
|
|
||||||
|
|
||||||
Manual upload bundle: `dist/releases/v0.6.0/adaptive-music-release-v0.6.0.zip`.
|
|
||||||
It includes the installable module, standalone manifest, complete source archive,
|
|
||||||
documentation, licenses and checksums. [INSTALL.md](INSTALL.md) explains manual
|
|
||||||
publication to the existing Gitea. No Git server was accessed by this work.
|
|
||||||
|
|
||||||
MIT project license. Upstream MIT/Apache notices and licenses remain in
|
|
||||||
`THIRD-PARTY-NOTICES` and `licenses/`. See [TESTING.md](TESTING.md),
|
|
||||||
[PROGRESS.md](PROGRESS.md), [ARCHITECTURE.md](ARCHITECTURE.md) and [SECURITY.md](SECURITY.md).
|
|
||||||
+53
-74
@@ -1,85 +1,64 @@
|
|||||||
# Adaptive Music security — 0.6.0
|
# Adaptive Music security — 0.7.0
|
||||||
|
|
||||||
## Private GM connection
|
## Credentials and browser trust
|
||||||
|
|
||||||
MA endpoint, access token, receiver private identity, pairing records and provider
|
The MA access token remains in the trusted GM tab’s closure memory. It is excluded
|
||||||
configuration stay in the GM tab's closure memory. They are never registered as
|
from Foundry settings, flags, sockets, URLs, console logging, IndexedDB serialization
|
||||||
Foundry settings, saved to document flags/localStorage, sent in module sockets,
|
and release archives. Setup failures retain it in this tab; disconnect or reload
|
||||||
embedded in URLs, logged or shipped. Closing/reloading requires private re-entry.
|
forgets it. Tokens are never reused after an origin change. Use a restricted MA
|
||||||
The user supplies a local identity backup; development/private copies belong under
|
account with only the intended music providers and dedicated receiver permissions.
|
||||||
ignored `.local/` (directory 0700, regular secret files 0600). No private configuration
|
|
||||||
or deployment files are included in releases. No credential was used in this work.
|
|
||||||
|
|
||||||
GM browser users, debuggers and code executing in that origin can inspect the GM's
|
Receiver private identity and pairing material are encrypted in the GM browser’s
|
||||||
secrets. Trust Foundry and every enabled module. This architecture cannot hide tokens
|
IndexedDB under a campaign/user/origin-derived scope. Encryption uses AES-GCM and
|
||||||
from the GM, same-origin compromise or the host administrator. Players receive only
|
a non-extractable key stored in the same browser. It avoids plaintext receiver
|
||||||
scoped encrypted audio invitations, never an MA credential, endpoint or SDK identity.
|
storage; it cannot protect against same-origin scripts, a compromised enabled
|
||||||
Use a restricted MA account scoped to the dedicated target and authorized music
|
module, the local profile owner or theft of a complete browser profile. Use separate
|
||||||
providers; application-side filtering is defense in depth, not an account restriction.
|
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.
|
||||||
|
|
||||||
MA 2.10.6's inspected WebSocket handler logs received raw frames at VERBOSE, including
|
Private development endpoints, tokens, identities, account/catalog results and
|
||||||
authentication. Before token-bearing connections the GM must confirm raw-frame
|
snapshots remain under ignored .local/ (0700; secret files 0600). MA raw WebSocket
|
||||||
logging is disabled. The wizard cannot verify or redact remote logs and does not
|
frames can include credentials at VERBOSE logging. Keep raw-frame logging disabled;
|
||||||
change logging configuration. No live WebSocket token test was performed here.
|
the module does not change production log settings. Expanded operator authorization
|
||||||
|
covers the dedicated live development tests; no production infrastructure was changed.
|
||||||
|
|
||||||
## Transport and authorization
|
## Network and authority
|
||||||
|
|
||||||
Use trusted HTTPS for remote Foundry and trusted HTTPS/WSS for private GM-to-MA
|
Trusted HTTPS Foundry and private HTTPS/WSS MA are required. TLS validation, browser
|
||||||
access. HTTPS → HTTP/ws is rejected, including loopback downgrade. Plain remote
|
security, Origin and private access controls remain enabled. No public MA endpoint,
|
||||||
Foundry HTTP is rejected for GM MA access. CORS exceptions, encrypted Sendspin payloads
|
Origin forgery, CORS wildcard change or unrestricted proxy is introduced. Both `/ws`
|
||||||
and browser local-network permissions do not replace TLS, CSP or Origin policy.
|
and `/sendspin` must reach their authenticated MA routes. Token-free diagnostics
|
||||||
Never disable mixed-content protection, certificate validation, Web security or MA
|
send no explicit MA auth frame; browsers may still send their normal ambient cookies.
|
||||||
authentication. No public/unrestricted MA HTTP/WS/Sendspin proxy is provided.
|
Browser APIs do not expose arbitrary HTTP/TLS errors and diagnostics do not invent
|
||||||
|
those causes.
|
||||||
|
|
||||||
Private imported X25519 identity determines one existing receiver ID. Exact name,
|
Only the SDK-generated and locally remembered campaign receiver is paired or
|
||||||
Sendspin provider, enabled/available state, standalone topology and own active queue
|
controlled. The account-bound pairing API is used after the API session is bound
|
||||||
are rechecked before each write. There is no household discovery/select list, queue
|
by Sendspin authentication. Exact identity/name/provider, enabled/available state,
|
||||||
transfer, speaker grouping, global stop or automatic receiver registration. Setup
|
standalone topology and own active queue are checked before writes. No household
|
||||||
reads can inspect that known target while unavailable during handover; mutation
|
selection, grouping, transfer or global stop is offered. Unknown writes latch closed.
|
||||||
guards are not relaxed. Catalog playback requires explicit GM opt-in and uses only
|
Queue snapshots are signed and campaign/session/fence/generation-bound; later
|
||||||
registered static playlist media from approved music providers.
|
sessions reject them. Browser authority cannot replace a distributed server fence.
|
||||||
|
|
||||||
Automatic listeners use public ephemeral P-256 keys in User flags and private keys
|
Players receive scoped expiring encrypted capabilities, not MA secrets or addresses.
|
||||||
in memory. User document permissions, enforced by Foundry's server, bind public keys
|
Public ephemeral keys on permission-controlled User documents authenticate invitation
|
||||||
to accounts. Server/admin/GM and own-browser trust remain necessary. No MA secrets
|
delivery. Server-enforced User permissions and role checks are essential; their
|
||||||
or listener capabilities are stored in those flags. A fixed encrypted invitation
|
actual-world behavior remains an acceptance gate. SDP is encrypted, bounded and
|
||||||
bootstrap authenticates both document keys, binds world/epochs/recipient and limits
|
replay protected, and validated for one audio direction with media-level SDP
|
||||||
size/concurrent decrypts/replay. Only one active GM and active non-GM participants
|
inheritance. No microphone, video or data channel is requested. Audio uses DTLS-SRTP.
|
||||||
are eligible. Server User permission enforcement is a real-Foundry acceptance gate,
|
Recipients can record audio or disclose their own capability. Direct peers can
|
||||||
not proven by fixtures. Do not use this scheme with a modified server that permits
|
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.
|
||||||
players to edit another account's User flags or GM role.
|
|
||||||
|
|
||||||
Capabilities are individual and expire after at most 30 minutes. SDP/ICE is protected
|
## Recovery and distribution
|
||||||
by the existing AES-GCM SignalCodec with session/peer/sequence/direction binding.
|
|
||||||
No raw continuous audio, token, upstream URL or queue data goes over module sockets.
|
|
||||||
Audio uses DTLS-SRTP. No microphone/video/control data channel. Role loss, disconnect,
|
|
||||||
revocation and expiry tear down peers. A recipient can forward its own capability
|
|
||||||
or record received audio; browser code cannot prevent that. Authorized direct peers
|
|
||||||
may learn each other's network addresses. Relay-only mode reduces direct candidate
|
|
||||||
exposure when a suitable existing TURN service is configured.
|
|
||||||
|
|
||||||
No silent public STUN/TURN. TURN credentials must expire within an hour; expired
|
API/Sendspin loss stops automation and listener forwarding. Retained tab inputs
|
||||||
credentials require renewed operator configuration. No service is provisioned.
|
support a deliberate reconnect; the owned queue is not replaced during reattachment.
|
||||||
Foundry socket flooding remains an availability concern even though bounded queues,
|
No blind mutation retry or automatic crash restoration is promised. Logical pause
|
||||||
strict envelopes and decrypt limits prevent unbounded application work.
|
and interruption snapshots do not survive a reload. Native fallback cannot silently
|
||||||
|
resolve an uncertain remote queue.
|
||||||
|
|
||||||
## Authority, recovery and distribution
|
The release builder is offline, preserves the existing Gitea update mechanism,
|
||||||
|
checks import/assets closure, SDK hash, licenses, privacy patterns and checksums,
|
||||||
Transitions remain serialized and generation checked with signed, campaign/session/
|
and includes complete source. No new distributed dependency, runtime CDN, upstream
|
||||||
fence-scoped snapshots. Uncertain writes latch closed. Browser Web Locks and a
|
install hook, telemetry, core patch or mandatory companion service was added. The
|
||||||
single active GM are not a server-side distributed fence. Crashes/offline browsers
|
pinned SDK and noble notices remain intact. No Git host was contacted.
|
||||||
cannot guarantee MA restore; no automatic split-brain handover or durable recovery.
|
|
||||||
Native fallback cannot silently resolve an uncertain active remote queue. Effects
|
|
||||||
and AmbientSound remain unowned. No production service/network version is changed.
|
|
||||||
|
|
||||||
The optional companion source and manual test transports remain advanced development
|
|
||||||
features. No additional service/container is mandatory or installed. Production routes,
|
|
||||||
logging changes or credential use require separate explicit authorization.
|
|
||||||
|
|
||||||
Release generation is offline and checks browser import closure, manifests, SDK hash,
|
|
||||||
notices/licenses, deterministic packaging and private-file patterns. Included source
|
|
||||||
archive represents this revision, including uncommitted edits; metadata names the base
|
|
||||||
Git revision and source archive digest. These checks supplement, rather than replace,
|
|
||||||
secret review. Official SDK 5.0.0, noble dependencies and notices remain pinned; no
|
|
||||||
new dependencies, runtime CDN, upstream install hooks or telemetry. PCM-only vendor
|
|
||||||
build omits optional Opus fallback binaries. No Git server was contacted or published to.
|
|
||||||
+98
-83
@@ -1,96 +1,111 @@
|
|||||||
# Adaptive Music verification — 0.6.0
|
# Adaptive Music verification — 0.7.0
|
||||||
|
|
||||||
## Offline regression and packaging
|
## Executed evidence
|
||||||
|
|
||||||
Use pinned Node 24.23.0 and Python standard library:
|
The source archive includes sanitized evidence separately from private .local inputs.
|
||||||
|
|
||||||
|
- 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, Authenticate, then Connect audio. 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. Choose two authorized static playlists for an active scene’s ambient/combat music,
|
||||||
|
save, and 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.
|
||||||
|
|
||||||
|
Acceptance requires audible output on the actual Mac/player devices, a successful
|
||||||
|
original Mac connection path, actual Foundry hooks, socket delivery and User
|
||||||
|
permissions, and the renewal and WAN checks above. Public release readiness remains
|
||||||
|
false until these checks are recorded. If the Mac still cannot reach WSS before
|
||||||
|
opening, its exact device-side cause remains external to the tested Ubuntu path;
|
||||||
|
the exact private-route access request is consolidated in ignored .local/PRIVATE-ROUTE-REQUEST.md. It proposes only temporary VM-to-proxy TCP 443 access with rollback, not a public API or disabled browser protection.
|
||||||
|
|
||||||
|
## 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.
|
||||||
|
|
||||||
```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_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.6.0/adaptive-music.zip
|
|
||||||
```
|
```
|
||||||
|
|
||||||
The v0.6.0 suite contains 91 JavaScript tests and 15 Python tests. See
|
Live scripts require authorized private configuration/token in ignored .local/ and
|
||||||
`evidence/v0.6.0-checks.txt` for executed results. Loopback fixture servers and headless
|
must only operate on their generated `Adaptive Music integration …` receivers.
|
||||||
Chromium need permission to bind/launch in restricted environments. No production
|
`--fresh` exercises module provisioning directly and keeps the generated receiver
|
||||||
endpoint, credential or Git server is needed. Upstream verification reads ignored
|
identity and reports in a separate private directory under .local/.
|
||||||
pinned local research copies; it does not fetch/install them.
|
Browser transport evidence includes no TLS bypass. Headless Chromium’s local test
|
||||||
|
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.
|
||||||
|
|
||||||
New regressions cover private wizard input clearing, catalog-to-scene ambient/combat
|
## Limits
|
||||||
persistence, normal listener activation without token/code fields, identity-bound
|
|
||||||
player lookup, stable catalog IDs, explicitly enabled playlist support, canceled
|
|
||||||
startup, and encrypted bootstrap tampering/replay/rotation/role/expiry rejection.
|
|
||||||
Existing controller, native restoration/fallback, signed snapshots, queue/topology,
|
|
||||||
companion, WebSocket correlation and distribution regressions remain.
|
|
||||||
|
|
||||||
`check_setup_browser.mjs` actually renders the setup/listener DOM in Chromium
|
No Mac/Safari execution, physical audibility, installed-world acceptance, real User
|
||||||
143.0.7499.4 using fake Foundry documents and a fake connection. It clicks the wizard,
|
permission adversarial test, WAN relay test, long-run skew/drift, seamless GM handover,
|
||||||
connects the fixture, loads/chooses/saves ambient and combat choices, confirms the
|
crash restore or crossfade is claimed. The upstream single queue does not provide
|
||||||
private input clears, advanced controls are absent, and player activation works.
|
simultaneous outgoing/incoming streams for a true crossfade. Pause is emulated and
|
||||||
A preview is written under ignored `dist/previews/`. This is an offline UI check,
|
its saved position remains in memory; a full reload cannot recover that position.
|
||||||
not an actual Foundry ApplicationV2 host or an MA connection/audio test. The development
|
|
||||||
browser runs with `--no-sandbox` for the local test environment only; the module never
|
|
||||||
sets browser flags or requires users to bypass browser security.
|
|
||||||
|
|
||||||
Python tests check repeatable complete ZIPs, manifest/import/assets closure, attribution,
|
|
||||||
privacy patterns, checksums and rebuilding source without Git metadata. Builder
|
|
||||||
validation does not prove URL availability. No additional dependency was introduced;
|
|
||||||
SDK/browser assets remain prebuilt/pinned. Rebuilding them, when needed, uses
|
|
||||||
`npm ci --ignore-scripts` and `node scripts/build_sendspin.mjs`. The earlier zero-advisory
|
|
||||||
audit is historical, not a new online audit or a security guarantee for this revision.
|
|
||||||
|
|
||||||
## User report and historical evidence
|
|
||||||
|
|
||||||
The user reports v0.5.0 successfully published to existing Gitea, installed through
|
|
||||||
the manifest, activated on Foundry v14.371 with D&D 5e 6.1.2, and both windows rendering.
|
|
||||||
This is explicitly user-supplied evidence for that version. No v0.6.0 live install,
|
|
||||||
MA authentication, receiver handshake or playlist playback was performed here.
|
|
||||||
|
|
||||||
Historical `evidence/browser-audio.json`: actual Chromium official Sendspin decoder
|
|
||||||
→ Web Audio → WebRTC → two listeners, original synthetic 440 Hz PCM, signal at 1.757 s,
|
|
||||||
RMS about 0.054, 42.3 kbit/s aggregate RTP over 4.766 s. Localhost socket shim, no
|
|
||||||
real Foundry or MA/Noise handshake, no WAN, skew/drift or hardware audibility result.
|
|
||||||
Historical MA read-only catalogs/target checks and bounded idle controls are retained;
|
|
||||||
those live controls restored an empty idle queue. Synthetic URI ingestion previously
|
|
||||||
failed; no real MA music audio or nonempty live queue restore is established.
|
|
||||||
|
|
||||||
## Remaining isolated live acceptance
|
|
||||||
|
|
||||||
1. Install/update the v0.6.0 ZIP in an isolated Foundry v14.371 world. Test the actual
|
|
||||||
ApplicationV2 windows and SceneConfig hooks. Save world/scene ambient and combat,
|
|
||||||
reload, reconnect with the same identity, verify references remain selected. Test
|
|
||||||
native ownership, boss/manual rules, rapid transitions, native snapshot/restoration,
|
|
||||||
fallback, and confirm AmbientSound/effects are untouched. No system dependency.
|
|
||||||
2. With separate explicit credential authorization, supply trusted private MA HTTPS/WSS,
|
|
||||||
an existing matching dedicated SDK identity/pairing backup and remote log review.
|
|
||||||
Check read-only target/catalog diagnostics first; confirm no household enumeration
|
|
||||||
or unintended target selection. Confirm token/endpoint/SDK secrets never appear in
|
|
||||||
player settings/documents/socket/network/logs or release artifacts.
|
|
||||||
3. Test server-enforced User flags with two distinct logged-in players: each can update
|
|
||||||
only its own key, cannot change another player's or GM's key/role, and forged socket
|
|
||||||
sender IDs do not authorize audio. Test banned/inactive/promoted users, multiple GMs,
|
|
||||||
key rotation/new login, renewal, revoke, disconnect and latest-tab behavior. Fixtures
|
|
||||||
validate cryptography, not production Foundry server permissions.
|
|
||||||
4. Before writes, capture dedicated target state, arrange an empty idle handover and
|
|
||||||
approved test content. Opt in catalog playback, connect SDK and verify pairing/time
|
|
||||||
sync and audible GM/player output. Exercise ambient → combat → boss → restore,
|
|
||||||
offsets, duplicate occurrences and pause/repeat. Capture original state and report
|
|
||||||
restoration failures explicitly. Real playlists need operator-approved content;
|
|
||||||
packaging authorization is not approval to play production content in this session.
|
|
||||||
5. Test automatic listener delivery and one Enable Audio click in supported Chrome,
|
|
||||||
Firefox and Safari configurations; background/suspend/reload behavior may vary.
|
|
||||||
Check audio after renewal, Stop/Enable and disconnect. Only Chromium DOM fixtures
|
|
||||||
ran here. GM audio/stream drift and true synchronization are unmeasured.
|
|
||||||
6. Test real remote networks with an explicitly approved existing relay if necessary.
|
|
||||||
Measure ICE success, RTT/jitter/loss, upload, latency/skew and 30-minute drift. Default
|
|
||||||
ICE has no public relay. Expired TURN credentials need operator renewal. Do not infer
|
|
||||||
WAN acceptance from loopback synthetic audio.
|
|
||||||
|
|
||||||
No production route, logging, Nginx/firewall/service version or Foundry/MA installation
|
|
||||||
was changed. Browser-only distributed fencing, durable crash restore, seamless GM
|
|
||||||
handover, crossfade and concurrent layers remain unsupported. Live acceptance is
|
|
||||||
pending; neither fixture tests nor the user's v0.5.0 rendering report waive it.
|
|
||||||
@@ -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,72 +1,256 @@
|
|||||||
{
|
{
|
||||||
"version": "0.6.0",
|
"version": "0.7.0",
|
||||||
"scope": "offline regressions, actual Chromium DOM fixture, pinned-source and package checks; no v0.6.0 live Foundry/MA verification",
|
"publicationReady": false,
|
||||||
"connection_configuration": "three-step GM wizard; memory-only endpoint/token/identity; imported existing dedicated receiver only",
|
"completedCoreRunPassed": true,
|
||||||
"catalog_and_assignments": "connected catalog playlists, explicit playback opt-in and persistent scene ambient/combat/boss/native fallback and world defaults",
|
"macPrivateRouteVerified": false,
|
||||||
"audio": "existing official Sendspin GM host integrated; automatic individually encrypted WebRTC listener invitations; browser activation when required",
|
"foundryLoggedInWorldVerified": false,
|
||||||
"bootstrap": "ephemeral ECDH P-256 keys bound to permission-controlled Foundry User documents; AES-GCM encrypted capabilities; live server permissions remain an acceptance gate",
|
"actualMAAuthentication": true,
|
||||||
"companion": "hidden by default; client-scoped advanced development setting; no mandatory service",
|
"actualMACatalogPlaylists": 11,
|
||||||
"https_wss": "trusted private MA origin with /ws and /sendspin WSS required from HTTPS Foundry; no mixed-content or certificate bypass; deployment untouched",
|
"actualMADedicatedProvisioning": true,
|
||||||
"distribution": "one installable module ZIP plus complete offline manual publication bundle, sources, docs, licenses and checksums",
|
"actualMAAudioAndTwoListeners": true,
|
||||||
"regression": {
|
"actualAmbientCombatRestore": true,
|
||||||
"javascript": 91,
|
"actualNativePause": false,
|
||||||
"python": 15,
|
"logicalPauseEmulation": true,
|
||||||
"passed": 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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
},
|
},
|
||||||
"browser_ui": {
|
"networkBoundary": {
|
||||||
"browser": "Chromium 143.0.7499.4",
|
"sandboxNormalDNS": "public addresses",
|
||||||
"passed": true,
|
"operatorMacMAResolution": "private proxy mapping",
|
||||||
"scope": "fake Foundry documents and fake connection; no MA or actual Foundry",
|
"sandboxPrivateProxyTCP443": "timeout before TLS",
|
||||||
"pageErrors": []
|
"temporaryAccessRequestPrepared": true,
|
||||||
|
"infrastructureChanged": false
|
||||||
},
|
},
|
||||||
"user_report": {
|
"remaining": [
|
||||||
"version": "0.5.0",
|
"operator private-route access and Mac original failure acceptance",
|
||||||
"giteaPublished": true,
|
"logged-in Foundry hooks, socket and User permission acceptance",
|
||||||
"manifestInstalled": true,
|
"WAN/30-minute behavior and hardware audibility"
|
||||||
"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"
|
|
||||||
],
|
],
|
||||||
|
"evidenceScope": "deployed Foundry origin with local source overlay; actual MA, PCM, Web Audio and WebRTC; test-runner signaling, not installed world",
|
||||||
|
"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": [
|
"history": [
|
||||||
{
|
{
|
||||||
"version": "0.5.0",
|
"version": "0.7.0",
|
||||||
"scope": "offline package audit; actual browser synthetic experiment separate from MA/Foundry acceptance",
|
"scope": "Local acceptance package with isolated browser checks, deployed Foundry ApplicationV2 rendering and dedicated MA receiver tests",
|
||||||
"connection_configuration": "GM-local in-memory developer API; optional companion setup retained; no one-click GM MA wizard",
|
"publicationReady": false,
|
||||||
"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",
|
"foundryInstalledWorldVerified": false,
|
||||||
"audio": "official SDK PCM and WebRTC implemented experimentally; measured synthetic loopback browser audio, no live MA receiver connection",
|
"originalMacConnectionVerified": false,
|
||||||
"crossfade": "unimplemented",
|
"deployedOriginAuthentication": "Ubuntu Chromium and Firefox",
|
||||||
"companion": "optional source and experimental/companion-0.4.0 branch; no deployment",
|
"maReceiver": {
|
||||||
"distribution": "one module ZIP; configurable Git-hosted stable manifest + versioned download; offline bundle/checksums/tests pass; no hosted install/update verification",
|
"chromiumPlaybackPassed": true,
|
||||||
"ma_mutations_this_revision": 0,
|
"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"
|
||||||
|
],
|
||||||
"regression": {
|
"regression": {
|
||||||
"javascript": 85,
|
"javascript": 101,
|
||||||
"python": 15
|
"python": 15
|
||||||
},
|
},
|
||||||
"blocking_infrastructure": [
|
"giteaContacted": false,
|
||||||
"isolated Foundry v14.371 world",
|
"productionInfrastructureChanged": false,
|
||||||
"existing DEV private identity/pairing",
|
"remainingAcceptance": [
|
||||||
"secure private browser MA access",
|
"Mac private MA route",
|
||||||
"operator WebSocket auth log review",
|
"installed Foundry world hooks, socket and User permissions",
|
||||||
"approved synthetic MA ingestion",
|
"listener renewal, actual player devices and WAN route"
|
||||||
"explicit existing TURN relay if required by NAT"
|
|
||||||
],
|
],
|
||||||
"gitea_contacted": false
|
"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
|
||||||
}
|
}
|
||||||
+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,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,35 @@
|
|||||||
|
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 sandbox cannot reach the Mac's private proxy route on TCP 443 (timeout before
|
||||||
|
TLS). A temporary exact-flow proposal/rollback is under ignored .local/ and awaits
|
||||||
|
operator execution. No infrastructure change was made. Original Mac path, logged-in
|
||||||
|
world/User permissions, WAN/renewal and physical audibility remain unverified.
|
||||||
|
Publication readiness is false. No Gitea access or publication occurred.
|
||||||
@@ -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,135 @@
|
|||||||
|
{
|
||||||
|
"version": "0.7.0",
|
||||||
|
"publicationReady": false,
|
||||||
|
"completedCoreRunPassed": true,
|
||||||
|
"macPrivateRouteVerified": false,
|
||||||
|
"foundryLoggedInWorldVerified": false,
|
||||||
|
"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",
|
||||||
|
"sandboxPrivateProxyTCP443": "timeout before TLS",
|
||||||
|
"temporaryAccessRequestPrepared": true,
|
||||||
|
"infrastructureChanged": false
|
||||||
|
},
|
||||||
|
"remaining": [
|
||||||
|
"operator private-route access and Mac original failure acceptance",
|
||||||
|
"logged-in Foundry hooks, socket and User permission acceptance",
|
||||||
|
"WAN/30-minute behavior and hardware audibility"
|
||||||
|
],
|
||||||
|
"evidenceScope": "deployed Foundry origin with local source overlay; actual MA, PCM, Web Audio and WebRTC; test-runner signaling, not installed world",
|
||||||
|
"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
|
||||||
|
}
|
||||||
+2
-2
@@ -2,7 +2,7 @@
|
|||||||
"id": "adaptive-music",
|
"id": "adaptive-music",
|
||||||
"title": "Adaptive Music",
|
"title": "Adaptive Music",
|
||||||
"description": "Scene and combat playlist automation with native Foundry fallback, private GM Music Assistant setup and Sendspin/WebRTC campaign audio.",
|
"description": "Scene and combat playlist automation with native Foundry fallback, private GM Music Assistant setup and Sendspin/WebRTC campaign audio.",
|
||||||
"version": "0.6.0",
|
"version": "0.7.0",
|
||||||
"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.6.0/adaptive-music.zip"
|
"download": "https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/releases/download/v0.7.0/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();}
|
||||||
@@ -11,15 +11,19 @@ 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));
|
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);
|
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);
|
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.getByRole('button',{name:'Connect audio',exact:true}).isVisible(),false,'hidden steps 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.getByLabel('Music Assistant server address').fill('https://ma.example.test');await page.getByLabel('Private GM access token').fill('fixture-token');
|
||||||
await page.getByLabel('I checked MA logging: raw WebSocket frames at VERBOSE are disabled').check();await page.getByRole('button',{name:'Next: dedicated receiver'}).click();await page.getByLabel('I own this dedicated campaign receiver').check();
|
await page.getByRole('button',{name:'Authenticate',exact:true}).click();await page.getByText('Authenticated. Connect this dedicated campaign receiver',{exact:false}).waitFor();
|
||||||
await page.getByRole('button',{name:'Test connection and load playlists',exact:true}).click();await page.getByText('Authenticated; dedicated player and catalog verified.',{exact:false}).waitFor();
|
|
||||||
assert.equal(await page.getByLabel('Private GM access token').inputValue(),'');
|
assert.equal(await page.getByLabel('Private GM access token').inputValue(),'');
|
||||||
await page.getByRole('button',{name:'Connect audio',exact:true}).click();await page.getByText('GM audio connected.',{exact:false}).waitFor();
|
await page.getByRole('button',{name:'Connect audio',exact:true}).click();await page.getByText('Campaign audio connected.',{exact:false}).waitFor();
|
||||||
const panel=page.locator('fieldset').filter({has:page.locator('legend',{hasText:'Scene music'})});
|
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();
|
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'});
|
assert.deepEqual(await page.evaluate(()=>window.saved.ambient),{provider:'ma',id:'ambient'});assert.deepEqual(await page.evaluate(()=>window.saved.combat),{provider:'ma',id:'combat'});
|
||||||
await mkdir(resolve(root,'dist/previews'),{recursive:true});await page.locator('.adaptive-music-setup').evaluate(el=>el.scrollTop=0);await page.screenshot({path:resolve(root,'dist/previews/v0.6.0-setup.png'),fullPage:true});
|
await mkdir(resolve(root,'dist/previews'),{recursive:true});await page.locator('.adaptive-music-setup').evaluate(el=>el.scrollTop=0);await page.screenshot({path:resolve(root,'dist/previews/v0.7.0-setup.png'),fullPage:true});
|
||||||
await page.evaluate(()=>window.listener());assert.equal(await page.locator('input').count(),0);await page.getByRole('button',{name:'Enable Audio'}).click();assert.equal(await page.evaluate(()=>window.activated),true);assert.deepEqual(errors,[]);
|
await page.evaluate(()=>window.listener());assert.equal(await page.locator('input').count(),0);await page.getByRole('button',{name:'Enable Audio'}).click();assert.equal(await page.evaluate(()=>window.activated),true);assert.deepEqual(errors,[]);
|
||||||
console.log(JSON.stringify({status:'pass',browser:browser.version(),scope:'offline DOM fixture; no live Foundry or MA',checks:['wizard render','private field clearing','catalog selectors','ambient/combat save','advanced controls hidden','listener activation'],pageErrors:errors},null,2));
|
console.log(JSON.stringify({status:'pass',browser:browser.version(),scope:'offline DOM fixture; no live Foundry or MA',checks:['380/640/1000px layout','hidden steps','wizard render','private field clearing','catalog selectors','ambient/combat save','advanced controls hidden','listener activation'],pageErrors:errors},null,2));
|
||||||
}finally{await browser?.close();await new Promise(resolve=>server.close(resolve));}
|
}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,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));
|
||||||
|
}
|
||||||
@@ -147,6 +147,12 @@ def build_release(repository=DEFAULT_REPOSITORY,version=None,output=None):
|
|||||||
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(),'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}
|
'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_file=ROOT/'evidence/v0.7.0-live.json'
|
||||||
|
acceptance=json.loads(acceptance_file.read_text()) if acceptance_file.is_file() 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())))
|
||||||
|
|||||||
+88
-40
@@ -4,23 +4,39 @@ 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 {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:')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');
|
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; #catalogPlayback=false; #status='disconnected'; #starting=false; #epoch=0;
|
#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,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;}
|
constructor({authority,onDisconnect=()=>{},pageUrl=globalThis.location?.href,loadSDK=()=>import('../../vendor/sendspin-5.0.0.mjs'),createContext=()=>new AudioContext(),createSocket=url=>new WebSocket(url)}){this.#authority=authority;this.onDisconnect=onDisconnect;this.pageUrl=pageUrl;this.loadSDK=loadSDK;this.createContext=createContext;this.createSocket=createSocket;}
|
||||||
get status(){return {state:this.#live?'connected':this.#starting?'connecting':this.#status,catalog:this.#catalog.length,audioContext:this.#context?.state??'closed',catalogPlayback:this.#catalogPlayback};}
|
get 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 ref?.provider==='ma'&&this.#live&&(this.#allowed.has(ref.id)||this.#catalogPlayback&&this.#catalog.some(c=>c.id===ref.id&&c.kind==='playlist')); }
|
supports(ref){return ref?.provider==='ma'&&this.#live&&(this.#allowed.has(ref.id)||this.#catalogPlayback&&this.#catalog.some(c=>c.id===ref.id&&c.kind==='playlist')); }
|
||||||
async inspect(profile){
|
async prepare(profile){
|
||||||
|
if(!this.#authority()||this.#live)throw new MusicError('denied');
|
||||||
|
const base=gmAccessPolicy(profile.maUrl,this.pageUrl);this.#phase='API authentication';
|
||||||
|
const transport=new GMMAWebSocket({baseUrl:base.origin,token:profile.token,createSocket:this.createSocket});
|
||||||
|
try{
|
||||||
|
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 inspect(profile,{transport:existingTransport}={}){
|
||||||
if(!this.#authority()||this.#live)throw new MusicError('denied');
|
if(!this.#authority()||this.#live)throw new MusicError('denied');
|
||||||
if(profile.webSocketAuthLogSafe!==true)throw new MusicError('auth-log-review-required');
|
if(profile.webSocketAuthLogSafe!==true)throw new MusicError('auth-log-review-required');
|
||||||
const base=gmAccessPolicy(profile.maUrl,this.pageUrl);
|
const base=gmAccessPolicy(profile.maUrl,this.pageUrl);
|
||||||
@@ -28,7 +44,7 @@ export class GMAudioHost{
|
|||||||
if(typeof sk!=='string'||!/^[A-Za-z0-9_-]{43}$/.test(sk))throw new MusicError('identity-required');
|
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));
|
const sdk=await this.loadSDK(),identity=sdk.loadSendspinClientIdentity(memoryStorage(profile.identityStorage));
|
||||||
if(profile.target&&profile.target!==identity.clientId)throw new MusicError('identity-mismatch');
|
if(profile.target&&profile.target!==identity.clientId)throw new MusicError('identity-mismatch');
|
||||||
const transport=new GMMAWebSocket({baseUrl:base.origin,token:profile.token,createSocket:this.createSocket});
|
const transport=existingTransport??new GMMAWebSocket({baseUrl:base.origin,token:profile.token,createSocket:this.createSocket});
|
||||||
const read=async(command,args)=>{
|
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();
|
const response=await transport.fetch(base.origin+'/api',{method:'POST',redirect:'error',body:JSON.stringify({command,args})});return response.json();
|
||||||
};
|
};
|
||||||
@@ -40,79 +56,111 @@ export class GMAudioHost{
|
|||||||
if(!approvedProviders.length)throw new MusicError('catalog-empty');
|
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)))));
|
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};
|
return {...profile,maUrl:base.origin,target:identity.clientId,expectedProvider:player.provider,approvedProviders,catalogKey,namespace:profile.namespace??profile.campaign};
|
||||||
}finally{transport.close();}
|
}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;}
|
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();}
|
resumeAudio(){return this.#context?.resume();}
|
||||||
async readCatalog(profile,{reconnecting=false}={}){
|
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);
|
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');
|
const key=Uint8Array.from(atob(profile.catalogKey),c=>c.charCodeAt(0));if(key.length!==32||!profile.targetName)throw new MusicError('denied');
|
||||||
this.#apiTransport?.close();this.#apiTransport=new GMMAWebSocket({baseUrl:base.origin,token:profile.token,createSocket:this.createSocket});
|
if(!preserveTransport){this.#apiTransport?.close();this.#apiTransport=new GMMAWebSocket({baseUrl:base.origin,token:profile.token,createSocket:this.createSocket});}
|
||||||
this.#client=new MAReadClient({baseUrl:base.origin,token:profile.token,target:profile.target,expectedName:profile.targetName,expectedProvider:profile.expectedProvider,approvedProviders:profile.approvedProviders,catalogKey:key,campaign:profile.namespace,syntheticSequences:profile.syntheticSequences??{},fetchImpl:this.#apiTransport.fetch});
|
this.#client=new MAReadClient({baseUrl:base.origin,token:profile.token,target:profile.target,expectedName:profile.targetName,expectedProvider:profile.expectedProvider,approvedProviders:profile.approvedProviders,catalogKey:key,campaign:profile.namespace,syntheticSequences:profile.syntheticSequences??{},fetchImpl:this.#apiTransport.fetch});
|
||||||
try{await this.#client.verifyTarget({allowUnavailable:reconnecting});this.#catalog=await this.#client.catalog();this.#status='catalog-ready';return this.catalog;}catch(error){await this.close();throw error;}
|
try{await this.#client.verifyTarget({allowUnavailable:reconnecting});this.#catalog=await this.#client.catalog();this.#status='catalog-ready';return this.catalog;}catch(error){await this.close();throw error;}
|
||||||
}
|
}
|
||||||
start(profile){if(this.#starting)return Promise.reject(new MusicError('denied'));this.#starting=true;return this.#start(profile).finally(()=>{this.#starting=false;});}
|
start(profile){if(this.#starting)return Promise.reject(new MusicError('denied'));this.#starting=true;return this.#start(profile).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){
|
async #start(profile){
|
||||||
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||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');
|
||||||
const epoch=this.#epoch,check=()=>{if(epoch!==this.#epoch||!this.#authority())throw new MusicError('stale');};
|
const epoch=this.#epoch,check=()=>{if(epoch!==this.#epoch||!this.#authority())throw new MusicError('stale');};
|
||||||
// Unlock synchronously in the caller's gesture before SDK/network work.
|
this.#lastError=undefined;this.#attachedQueue=false;this.#context=this.createContext();const unlocked=this.#context.resume();this.#destination=this.#context.createMediaStreamDestination();this.#frames=this.#samples=this.#energy=this.#lastAudio=this.#scheduled=this.#late=this.#ahead=0;
|
||||||
this.#context=this.createContext();const unlocked=this.#context.resume();this.#destination=this.#context.createMediaStreamDestination();
|
|
||||||
try{
|
try{
|
||||||
this.#sdk=await this.loadSDK();await unlocked;check();
|
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});check();
|
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});check();
|
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();}
|
||||||
|
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);check();
|
|
||||||
this.#core=new this.#sdk.SendspinCore({webSocket:this.#socket,storage,clientName:profile.targetName,productName:'Web Browser',codecs:['pcm'],bufferCapacity:768000,requiredLeadTimeMs:250,minBufferMs:250,useHardwareVolume:true,getExternalVolume:()=>volumeState,onVolumeCommand:(volume,muted)=>{volumeState={volume,muted};},unpairedAccess:false,reconnect:{enabled:false}});
|
|
||||||
this.#gain=this.#context.createGain();this.#gain.connect(this.#destination);this.#gain.connect(this.#context.destination);
|
|
||||||
this.#core.onVolumeUpdate=()=>this.#gain.gain.setTargetAtTime(this.#core.muted?0:Math.pow(Math.min(100,Math.max(0,this.#core.volume))/100,1.5),this.#context.currentTime,0.015);
|
|
||||||
this.#core.onAudioData=chunk=>this.#schedule(chunk);
|
|
||||||
this.#core.onConnectionClose=()=>{const wasLive=this.#live;this.#status='connection-lost';this.#live=false;if(wasLive)this.onDisconnect();this.#clear();for(const track of this.#destination?.stream.getTracks()??[])track.stop();};
|
|
||||||
this.#core.onStreamClear=()=>this.#clear();this.#core.onStreamEnd=()=>this.#clear();
|
|
||||||
this.#session=crypto.randomUUID();this.#catalogPlayback=profile.allowCatalogPlayback===true;this.#live=true;
|
|
||||||
this.#provider=new MAPlaybackProvider({client:this.#client,campaign:profile.campaign,session:this.#session,fence:1,snapshotKey:randomKey(),authority:()=>{if(!this.#live||!this.#authority())throw new MusicError('stale');}});
|
this.#provider=new MAPlaybackProvider({client:this.#client,campaign:profile.campaign,session:this.#session,fence:1,snapshotKey:randomKey(),authority:()=>{if(!this.#live||!this.#authority())throw new MusicError('stale');}});
|
||||||
await this.#core.connect();check();const deadline=Date.now()+10000;while(this.#live&&!this.#core.timeSyncInfo.synced&&Date.now()<deadline)await new Promise(resolve=>setTimeout(resolve,50));if(!this.#live||!this.#core.timeSyncInfo.synced)throw new MusicError('unavailable');await this.#client.verifyTarget();check();return {clientIdVerified:true,catalog:this.#catalog.length,codecs:['pcm'],remoteAudio:'webrtc',audioMeasured:false,distributedFencing:false};
|
return {clientIdVerified:true,catalog:this.#catalog.length,codecs:['pcm'],remoteAudio:'webrtc',audioMeasured:false,distributedFencing:false,attachedExistingQueue:this.#attachedQueue};
|
||||||
}catch(error){if(epoch===this.#epoch)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 new MusicError(this.#lastError.code);}
|
||||||
}
|
}
|
||||||
#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);this.#socket=socket;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.#epoch++;this.#status='disconnected';this.#catalogPlayback=false;this.#live=false;this.#releaseLock?.();this.#releaseLock=null;this.#clear();this.#core?.disconnect('user_request');this.#socket?.close();this.#core=null;this.#socket=null;this.#provider=null;this.#apiTransport?.close();this.#apiTransport=null;this.#client=null;this.#catalog=[];this.#allowed.clear();for(const track of this.#destination?.stream.getTracks()??[])track.stop();this.#destination=null;const context=this.#context;this.#context=null;if(context&&context.state!=='closed')await context.close();}
|
control(action,value,ctx){return this.#observe(()=>this.#ready().control(action,value,ctx));}
|
||||||
|
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();}
|
||||||
}
|
}
|
||||||
+30
-14
@@ -9,20 +9,30 @@ 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;}
|
||||||
@@ -47,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);}
|
||||||
@@ -56,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;}
|
||||||
}
|
}
|
||||||
@@ -64,9 +64,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,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};
|
||||||
|
}
|
||||||
@@ -1,63 +1,90 @@
|
|||||||
|
import {validateIceServers} from '../audio/peer-audio.mjs';
|
||||||
|
import {probeWebSockets,diagnosticMessage} from '../providers/ma/diagnostics.mjs';
|
||||||
const messages={
|
const messages={
|
||||||
'insecure-context':'Open Foundry over trusted HTTPS. Remote plain HTTP cannot provide the secure browser APIs required for GM audio.',
|
'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.',
|
||||||
'mixed-content':'This Foundry page uses HTTPS. Use a trusted HTTPS Music Assistant address (WSS for /ws and /sendspin). HTTP/ws is blocked.',
|
'address-invalid':'Enter the MA server origin, such as https://ma.example.test, without a path or query.',
|
||||||
'auth-log-review-required':'Confirm that MA raw WebSocket frame logging at VERBOSE is disabled before sending a token.',
|
'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.',
|
||||||
'identity-required':'Import the private backup for your existing dedicated Sendspin receiver. Its sendspin-identity-sk is required.',
|
'ws-auth-timeout':'The API socket opened, but authentication did not finish. Check that /ws reaches MA rather than a login portal.',
|
||||||
'identity-mismatch':'The private receiver identity does not match the selected player. Import the matching backup.',
|
'ws-auth-denied':'MA rejected the token. Enter a replacement and Authenticate again; the receiver is remembered.',
|
||||||
'dedicated-target-required':'The imported identity and dedicated player name do not match a Sendspin target. Check the name and backup; no other player was selected.',
|
'ws-disconnected':'The API socket closed. Your private inputs remain in this tab. Retry after checking the private route.',
|
||||||
'reconcile-required':'The dedicated queue must be empty and idle before handover. Reconcile it in Music Assistant, then reconnect.',
|
'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.',
|
||||||
'catalog-empty':'No authorized music providers were found. Check the MA account’s provider permissions.',
|
'ws-command-failed':'MA rejected a command. The account needs music-provider access and permission to control and pair its dedicated web receiver.',
|
||||||
'unsupported':'This browser or queue mode is unsupported. Use HTTPS, Web Locks, Web Audio and WebRTC; disable shuffle, dynamic queues and autoplay.',
|
'sendspin-auth-failed':'The receiver socket opened, but Sendspin authentication failed. Verify the authenticated /sendspin route, separate from /ws.',
|
||||||
'profile-required':'Check the server, authentication and dedicated receiver backup.',
|
'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.',
|
||||||
'denied':'Connection denied. Check the private MA token, dedicated target, single active GM and account permissions.',
|
'insecure-context':'Open Foundry over trusted HTTPS to use secure browser audio APIs.',
|
||||||
'stale':'Authority changed. Keep one active GM, stop automation and reconnect.',
|
'mixed-content':'HTTPS Foundry requires a trusted HTTPS MA address. Browser security cannot permit an HTTP/ws downgrade.',
|
||||||
'unavailable':'Cannot reach Music Assistant. Check trusted TLS, /ws and /sendspin upgrades, Origin/CSP permissions, private routing and the MA token.'
|
'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=>messages[error?.code]??messages.unavailable;
|
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;
|
||||||
export function mountConnectionWizard({game,container,connection,onCatalog=()=>{},onError=()=>{}}){
|
export function mountConnectionWizard({game,container,connection,onCatalog=()=>{},onError=()=>{}}){
|
||||||
const dom=container.ownerDocument,panel=dom.createElement('fieldset');
|
const dom=container.ownerDocument,panel=dom.createElement('fieldset'),legend=dom.createElement('legend');legend.textContent='1. Music Assistant';panel.append(legend);
|
||||||
const legend=dom.createElement('legend');legend.textContent='1. Connect Music Assistant';panel.append(legend);
|
const note=dom.createElement('p');note.textContent='Enter your server and access token. A dedicated campaign receiver is created and paired automatically. The token stays in this GM tab; its receiver identity is remembered privately in this browser.';panel.append(note);
|
||||||
const note=dom.createElement('p');note.textContent='Optional. Authentication stays in this GM tab’s memory; reconnect after reload. Trust every module running in this browser.';panel.append(note);
|
|
||||||
const heading=dom.createElement('p');heading.setAttribute('role','status');panel.append(heading);
|
|
||||||
const steps=Array.from({length:3},()=>{const step=dom.createElement('div');step.className='adaptive-music-step';panel.append(step);return step;});
|
|
||||||
const go=index=>{steps.forEach((step,i)=>{step.hidden=i!==index;});heading.textContent=['Step 1 of 3: Server and private authentication','Step 2 of 3: Dedicated receiver','Step 3 of 3: Connect campaign audio'][index];};
|
|
||||||
const status=dom.createElement('p');status.setAttribute('role','status');panel.append(status);
|
const status=dom.createElement('p');status.setAttribute('role','status');panel.append(status);
|
||||||
|
const steps=Array.from({length:2},()=>{const step=dom.createElement('div');step.className='adaptive-music-step';panel.append(step);return step;});
|
||||||
|
const go=index=>steps.forEach((step,i)=>{step.hidden=i!==index;});
|
||||||
const field=(parent,label,type='text')=>{const l=dom.createElement('label');l.textContent=label;const input=dom.createElement('input');input.type=type;input.autocomplete='off';input.spellcheck=false;l.append(input);parent.append(l);return input;};
|
const field=(parent,label,type='text')=>{const l=dom.createElement('label');l.textContent=label;const input=dom.createElement('input');input.type=type;input.autocomplete='off';input.spellcheck=false;l.append(input);parent.append(l);return input;};
|
||||||
const button=(parent,label,action)=>{const b=dom.createElement('button');b.type='button';b.textContent=label;b.addEventListener('click',async()=>{b.disabled=true;try{if(!game.user.isGM)throw {code:'denied'};await action();}catch(error){status.textContent=connectionMessage(error);onError();}finally{b.disabled=false;show();}});parent.append(b);return b;};
|
const button=(parent,label,action)=>{const b=dom.createElement('button');b.type='button';b.textContent=label;b.addEventListener('click',async()=>{b.disabled=true;try{if(!game.user.isGM)throw {code:'denied'};await action();}catch(error){status.textContent=connectionMessage(error);onError(error);}finally{b.disabled=false;show();}});parent.append(b);return b;};
|
||||||
const address=field(steps[0],'Music Assistant server address','url');address.placeholder='https://ma.example.test';
|
const draft=connection.draftFields??{},address=field(steps[0],'Music Assistant server address','url');address.placeholder='https://ma.example.test';address.value=draft.maUrl??'';
|
||||||
const token=field(steps[0],'Private GM access token','password');
|
const token=field(steps[0],'Private GM access token','password');
|
||||||
const logs=field(steps[0],'I checked MA logging: raw WebSocket frames at VERBOSE are disabled','checkbox');
|
const advanced=dom.createElement('details'),summary=dom.createElement('summary');summary.textContent='Receiver options';advanced.append(summary);steps[0].append(advanced);
|
||||||
const logNote=dom.createElement('p');logNote.textContent='Review server logging before sending a token. See connection requirements below. Native music works without Music Assistant.';steps[0].append(logNote);
|
const name=field(advanced,'Dedicated receiver name');name.value=draft.targetName??'Adaptive Music '+(game.world?.title??'campaign');
|
||||||
button(steps[0],'Next: dedicated receiver',()=>{if(!address.value.trim()||!logs.checked)throw {code:'profile-required'};go(1);status.textContent='Import the existing dedicated receiver backup, then test the connection.';});
|
const iceURL=field(advanced,'Existing ICE server URL (optional)');iceURL.placeholder='stun:stun.example.test:3478';
|
||||||
const name=field(steps[1],'Dedicated receiver name');name.value='Adaptive Music DEV';
|
const iceUsername=field(advanced,'TURN username (if required)'),iceCredential=field(advanced,'Short-lived TURN credential','password'),iceExpiry=field(advanced,'TURN credential expiry (UTC)','datetime-local');
|
||||||
const backup=field(steps[1],'Private receiver backup (.json)','file');backup.accept='.json,application/json';
|
const networkNote=dom.createElement('p');networkNote.textContent='Direct connections use no external ICE service. For remote players, you may supply an existing STUN/TURN service. TURN credentials must expire within one hour; no service is installed.';advanced.append(networkNote);
|
||||||
const backupNote=dom.createElement('p');backupNote.textContent='Import the existing Sendspin identity and pairing backup. Only that receiver is eligible; no new receiver is registered. Keep this file private.';steps[1].append(backupNote);
|
const logging=dom.createElement('p');logging.textContent='Keep MA raw-frame VERBOSE logging disabled: it can record authentication frames. No server logging settings are changed by this module.';advanced.append(logging);
|
||||||
const owned=field(steps[1],'I own this dedicated campaign receiver','checkbox');
|
button(steps[0],'Authenticate',async()=>{
|
||||||
const playback=field(steps[1],'Allow scene automation to play my catalog playlists on this receiver','checkbox');
|
if(!address.value.trim())throw {code:'address-invalid'};status.textContent='Authenticating with Music Assistant…';
|
||||||
button(steps[1],'Back: server',()=>go(0));
|
const network={};
|
||||||
button(steps[1],'Test connection and load playlists',async()=>{
|
if(iceURL.value.trim()){
|
||||||
connect.disabled=true;
|
const server={urls:iceURL.value.trim()};
|
||||||
if(!owned.checked||!logs.checked)throw {code:'denied'};
|
if(/^turns?:/.test(server.urls)){server.username=iceUsername.value.trim();server.credential=iceCredential.value;server.expires=Date.parse(iceExpiry.value+'Z');}
|
||||||
let imported={};
|
try{validateIceServers([server]);}catch{throw {code:'ice-config-invalid'};}network.listenerNetwork={iceServers:[server]};
|
||||||
try{const file=backup.files?.[0];if(file){if(file.size>65536)throw Error();imported=JSON.parse(await file.text());}}catch{throw {code:'identity-required'};}
|
}
|
||||||
const profile={...imported,maUrl:address.value.trim(),token:token.value,identityStorage:imported.identityStorage??imported,targetName:name.value.trim(),webSocketAuthLogSafe:true,allowCatalogPlayback:playback.checked};
|
let result;try{result=await connection.test({maUrl:address.value.trim(),token:token.value,targetName:name.value.trim(),allowCatalogPlayback:true,webSocketAuthLogSafe:true,...network});}
|
||||||
token.value='';backup.value='';
|
finally{if(connection.status.hasPrivateDraft){token.value='';}}
|
||||||
const result=await connection.test(profile);setTarget(result.target,result.targetName);
|
token.value='';setTarget(result.target,result.targetName);go(1);connect.disabled=false;
|
||||||
connect.disabled=false;go(2);status.textContent='Authenticated; dedicated player and catalog verified. Select Connect audio to start the GM receiver.';await onCatalog();
|
status.textContent='Authenticated. Connect this dedicated campaign receiver to pair it and load your playlists.';
|
||||||
});
|
});
|
||||||
const target=dom.createElement('select'),targetLabel=dom.createElement('label');targetLabel.textContent='Dedicated player';target.disabled=true;targetLabel.append(target);steps[2].append(targetLabel);
|
const target=dom.createElement('select'),label=dom.createElement('label');label.textContent='Dedicated campaign receiver';label.append(target);steps[1].append(label);
|
||||||
const setTarget=(id,name)=>{target.replaceChildren();const option=dom.createElement('option');option.value=id;option.textContent=name;target.append(option);target.value=id;target.disabled=false;};
|
const setTarget=(id,name)=>{target.replaceChildren();const option=dom.createElement('option');option.value=id;option.textContent=name;target.append(option);target.value=id;};
|
||||||
const diagnostics=dom.createElement('p');diagnostics.setAttribute('role','status');steps[2].append(diagnostics);
|
const connect=button(steps[1],'Connect audio',async()=>{
|
||||||
const show=()=>{const d=connection.status;if(d.state==='connected')connect.disabled=true;diagnostics.textContent=`Connection: ${d.state}. Catalog: ${d.catalog} items. GM audio: ${d.audioContext}. ${d.catalogPlayback?'Catalog playback enabled.':'Catalog playback disabled.'} ${d.peers??0} listener connections.`;};
|
status.textContent='Connecting and pairing the dedicated receiver…';
|
||||||
const connect=button(steps[2],'Connect audio',async()=>{
|
const result=await connection.connect(target.value);await onCatalog();status.textContent=result?.attachedExistingQueue?'Campaign audio reconnected. The existing queue was preserved. Apply the automation setting below when ready to resume scene control.':'Campaign audio connected. Assign ambient and combat playlists below, then enable automation. Players connect automatically.';
|
||||||
// Call before the first await to retain the browser activation gesture.
|
});
|
||||||
const pending=connection.connect(target.value);await pending;status.textContent='GM audio connected. Active players connect automatically; a browser may ask them to Enable Audio once.';await onCatalog();
|
button(steps[1],'Enable GM audio',()=>connection.resume());
|
||||||
});connect.disabled=true;
|
const volume=field(steps[1],'Campaign volume','range');volume.min='0';volume.max='100';volume.value=String(connection.status.volume??100);volume.addEventListener('change',()=>{try{connection.setVolume?.(Number(volume.value));}catch(error){status.textContent=connectionMessage(error);onError(error);}});
|
||||||
button(steps[2],'Refresh catalog and diagnostics',async()=>{await connection.refresh();await onCatalog();status.textContent='Catalog and target checks refreshed.';});
|
button(steps[1],'Refresh playlists',async()=>{await connection.refresh();await onCatalog();status.textContent='Playlists refreshed.';});
|
||||||
button(steps[2],'Enable GM audio',()=>connection.resume());
|
button(steps[1],'Back to authentication',()=>go(0));
|
||||||
button(steps[2],'Back: receiver',()=>go(1));
|
const diagnostics=dom.createElement('p');diagnostics.setAttribute('role','status');panel.append(diagnostics);
|
||||||
button(steps[2],'Disconnect Music Assistant',async()=>{await connection.disconnect();token.value='';backup.value='';target.replaceChildren();connect.disabled=true;go(0);status.textContent='Disconnected. Automation is stopped; existing remote queue state is retained for review.';await onCatalog();});
|
const report=dom.createElement('div');report.setAttribute('aria-live','polite');panel.append(report);let transportResults=[];
|
||||||
const help=dom.createElement('a');help.href='modules/adaptive-music/INSTALL.md';help.target='_blank';help.rel='noopener';help.textContent='Connection requirements and troubleshooting';panel.append(help);
|
button(panel,'Check browser connection (no MA token)',async()=>{
|
||||||
const d=connection.status;if(d.selectedTarget){setTarget(d.selectedTarget,d.selectedName);connect.disabled=d.state==='connected';go(2);}else go(0);
|
report.replaceChildren();status.textContent='Checking both WebSocket routes from this Foundry page…';
|
||||||
show();container.append(panel);return panel;
|
try{transportResults=await probeWebSockets(address.value.trim());}catch(error){throw error?.code?error:{code:'address-invalid'};}
|
||||||
|
for(const result of transportResults){const line=dom.createElement('p');line.textContent=result.path+': '+diagnosticMessage(result);report.append(line);}
|
||||||
|
status.textContent='Browser checks complete. No MA token was sent. An open socket still needs authentication, pairing and clock synchronization.';
|
||||||
|
});
|
||||||
|
button(panel,'Copy connection diagnostics',async()=>{
|
||||||
|
const d=connection.status;const text=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,listenerConnections:d.peers??0,lastError:d.lastError,listenerDiagnostics:d.listenerDiagnostics,transport:transportResults,secureContext:globalThis.isSecureContext},null,2);
|
||||||
|
await navigator.clipboard.writeText(text);status.textContent='Diagnostics copied. The report excludes the address, token, receiver identity and catalog titles.';
|
||||||
|
});
|
||||||
|
button(panel,'Disconnect Music Assistant',async()=>{await connection.disconnect();token.value='';iceCredential.value='';target.replaceChildren();go(0);status.textContent='Disconnected. The token was forgotten; this browser remembers its campaign receiver.';await onCatalog();});
|
||||||
|
const recovery=dom.createElement('details'),recoveryTitle=dom.createElement('summary');recoveryTitle.textContent='Connection recovery';recovery.append(recoveryTitle);panel.append(recovery);
|
||||||
|
button(recovery,'Reconnect remembered receiver',async()=>{await connection.reconnect();await onCatalog();status.textContent='Receiver reconnected using retained private inputs. The queue was preserved and automation is paused. Review it, then Apply automation setting when ready.';});
|
||||||
|
button(recovery,'Forget remembered receiver',async()=>{await (connection.forgetReceiver?.()??connection.disconnect());token.value='';iceCredential.value='';target.replaceChildren();go(0);status.textContent='Local receiver identity forgotten. Reauthenticate to provision a new receiver. Existing MA queues were left untouched.';await onCatalog();});
|
||||||
|
const show=()=>{const d=connection.status;volume.disabled=d.state!=='connected';if(d.hasPrivateDraft)token.placeholder='Retained in this tab; leave blank to retry';connect.disabled=d.state==='connected'||d.state==='connecting';diagnostics.textContent=`${d.state}. ${d.stage??''} Playlists: ${d.catalog??0}. GM audio: ${d.audioContext??'closed'}. Decoded frames: ${d.decodedFrames??0}. Connected listeners: ${d.peers??0}.`;};
|
||||||
|
const d=connection.status;if(d.selectedTarget){setTarget(d.selectedTarget,d.selectedName);go(1);}else go(0);show();container.append(panel);
|
||||||
|
// Refresh while the actual ApplicationV2 window is mounted; no secret-bearing events.
|
||||||
|
if(globalThis.document===dom&&typeof panel.isConnected==='boolean'){const timer=setInterval(()=>{if(!panel.isConnected){clearInterval(timer);return;}show();},1000);}
|
||||||
|
return panel;
|
||||||
}
|
}
|
||||||
+28
-7
@@ -1,3 +1,6 @@
|
|||||||
|
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';
|
||||||
@@ -7,11 +10,13 @@ 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';
|
||||||
const id='adaptive-music';
|
const id='adaptive-music';
|
||||||
let runtime,interfaces,gateway,audio,renewTimer,gmHost,peers,remoteAudio;let authorityHooks=[];let bootstrap,privateProfile,inviteTimer,latestInvite,listenerStopped=false,listenerState='Waiting for GM audio.',inviteTail=Promise.resolve();const sentInvites=new Map();let connectionGeneration=0;let listenerContext,listenerSource;
|
const receiverVault=new ReceiverVault();
|
||||||
|
const receiverScope=profile=>({campaign:game.world.id,userId:game.user.id,maUrl:profile.maUrl});
|
||||||
|
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;
|
||||||
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.filter(c=>c.kind==='playlist'||c.kind==='sequence'):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 start(){
|
||||||
if(!game.user.isGM||runtime)return;
|
if(!game.user.isGM||runtime)return;
|
||||||
runtime=startNativeRuntime({game,Hooks,campaign:game.world.id,session:gmHost?.connected?gmHost.session:globalThis.crypto.randomUUID(),ownedPlaylistIds:owned(),maProvider:gmHost?.connected?gmHost:gateway,onError});
|
runtime=startNativeRuntime({game,Hooks,campaign:game.world.id,session:gmHost?.connected?gmHost.session:globalThis.crypto.randomUUID(),ownedPlaylistIds:owned(),maProvider:gmHost?.connected?gmHost:gateway,onError});
|
||||||
@@ -33,11 +38,27 @@ function sendInvites(){
|
|||||||
});return inviteTail;
|
});return inviteTail;
|
||||||
}
|
}
|
||||||
const connection={
|
const connection={
|
||||||
get status(){return {...(gmHost?.status??{state:'disconnected',catalog:0,audioContext:'closed'}),selectedTarget:privateProfile?.target,selectedName:privateProfile?.targetName,peers:peers?.diagnostics().peers.filter(p=>p.connection==='connected').length??0};},
|
get draftFields(){return privateDraft?{maUrl:privateDraft.maUrl,targetName:privateDraft.targetName,webSocketAuthLogSafe:privateDraft.webSocketAuthLogSafe,allowCatalogPlayback:privateDraft.allowCatalogPlayback}:{};},
|
||||||
async test(profile){if(gmHost.connected||gmHost.status.state==='connecting'||gateway.connected)throw {code:'denied'};stop();const generation=++connectionGeneration;const old=privateProfile;privateProfile=null;await gmHost.close();const candidate={...old,...profile,token:profile.token||old?.token,identityStorage:profile.identityStorage?.['sendspin-identity-sk']?profile.identityStorage:old?.identityStorage,campaign:game.world.id};const result=await gmHost.inspect(candidate);await gmHost.readCatalog(result,{reconnecting:true});if(generation!==connectionGeneration)throw {code:'stale'};privateProfile=result;return {target:result.target,targetName:result.targetName};},
|
get status(){return {...(gmHost?.status??{state:'disconnected',catalog:0,audioContext:'closed'}),hasPrivateDraft:!!privateDraft,selectedTarget:privateProfile?.target,selectedName:privateProfile?.targetName,listenerDiagnostics:peers?.diagnostics(),peers:peers?.diagnostics().peers.filter(p=>p.connection==='connected').length??0};},
|
||||||
async connect(target){if(!privateProfile||target!==privateProfile.target||gateway.connected)throw {code:'denied'};stop();const pending=gmHost.start(privateProfile);await pending;peers.setSource(gmHost.stream);sentInvites.clear();await sendInvites();if(game.settings.get(id,'enabled'))start();},
|
async test(profile){
|
||||||
refresh:()=>gmHost.refreshCatalog(),resume:()=>gmHost.resumeAudio(),
|
if(connectionTesting||gmHost.connected||gmHost.status.state==='connecting'||gateway.connected)throw {code:'denied'};
|
||||||
async disconnect(){connectionGeneration++;stop();peers?.reset();sentInvites.clear();privateProfile=null;await gmHost.close();}
|
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;
|
||||||
|
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};
|
||||||
|
}finally{connectionTesting=false;}
|
||||||
|
},
|
||||||
|
async connect(target,{resumeAutomation=true}={}){if(!privateProfile||target!==privateProfile.target||gateway.connected)throw {code:'denied'};stop();const pending=gmHost.start(privateProfile);let result;try{result=await pending;}finally{if(privateProfile)await receiverVault.save(receiverScope(privateProfile),privateProfile);}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 forgetReceiver(){if(privateDraft){const scope=receiverScope(privateDraft);await connection.disconnect();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');
|
||||||
|
|||||||
@@ -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);}
|
||||||
|
}
|
||||||
+28
-10
@@ -2,7 +2,7 @@ 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; #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(), 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 ||
|
||||||
@@ -21,7 +21,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 +39,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 +72,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');
|
||||||
@@ -166,13 +179,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,7 +2,7 @@ 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);
|
||||||
@@ -39,9 +39,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 +51,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 +80,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(['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)]);
|
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;}
|
||||||
}
|
}
|
||||||
@@ -12,3 +12,10 @@
|
|||||||
.adaptive-music-setup summary {cursor:pointer;font-weight:600;}
|
.adaptive-music-setup summary {cursor:pointer;font-weight:600;}
|
||||||
.adaptive-music-step {display:grid;gap:0.65rem;}
|
.adaptive-music-step {display:grid;gap:0.65rem;}
|
||||||
.adaptive-music-step[hidden] {display:none;}
|
.adaptive-music-step[hidden] {display:none;}
|
||||||
|
/* 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;}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
<!doctype html><meta charset="utf-8"><title>Adaptive Music setup fixture</title>
|
<!doctype html><meta charset="utf-8"><title>Adaptive Music setup fixture</title>
|
||||||
<link rel="stylesheet" href="/styles/adaptive-music.css">
|
<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>
|
<style>body{font:16px system-ui;background:#222;color:#eee;margin:2rem auto;max-width:640px}input,select,button{font:inherit;padding:.4rem;box-sizing:border-box}button{cursor:pointer}a{color:#9bd}</style>
|
||||||
<main id="app"></main>
|
<section id="adaptive-music-setup"><main id="app" class="window-content"></main></section>
|
||||||
<script type="module">
|
<script type="module">
|
||||||
import {createSetupClass,createListenerClass} from '/src/foundry/setup.mjs';
|
import {createSetupClass,createListenerClass} from '/src/foundry/setup.mjs';
|
||||||
let flag={},catalog=[];const settings={ownedPlaylistIds:'native',musicDefaults:{},enabled:false,advancedDevelopment:false};
|
let flag={},catalog=[];const settings={ownedPlaylistIds:'native',musicDefaults:{},enabled:false,advancedDevelopment:false};
|
||||||
|
|||||||
@@ -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']);
|
||||||
|
});
|
||||||
@@ -74,6 +74,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;
|
||||||
|
|||||||
@@ -99,3 +99,56 @@ test('disconnect cancels pending GM startup before any authenticated receiver co
|
|||||||
assert.throws(()=>gmAccessPolicy('http://localhost','https://foundry.example.test'),{code:'mixed-content'});
|
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'});
|
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);
|
||||||
|
});
|
||||||
@@ -19,8 +19,8 @@ test('GM setup connects catalog into independent scene editors and never persist
|
|||||||
const connection={status:{state:'disconnected',catalog:0,audioContext:'closed'},async test(profile){assert.equal(profile.token,'capability-fixture');assert.equal(profile.maUrl,'https://ma.example.test');catalog=[{provider:'ma',id:'opaque-ma',name:'MA fixture',kind:'playlist'}];return {target:'dedicated',targetName:'Adaptive Music DEV'};},async connect(target){assert.equal(target,'dedicated');},refresh:async()=>{},disconnect:async()=>{}};
|
const connection={status:{state:'disconnected',catalog:0,audioContext:'closed'},async test(profile){assert.equal(profile.token,'capability-fixture');assert.equal(profile.maUrl,'https://ma.example.test');catalog=[{provider:'ma',id:'opaque-ma',name:'MA fixture',kind:'playlist'}];return {target:'dedicated',targetName:'Adaptive Music DEV'};},async connect(target){assert.equal(target,'dedicated');},refresh:async()=>{},disconnect:async()=>{}};
|
||||||
try{
|
try{
|
||||||
const Setup=createSetupClass({game,connection,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';descendants(root).find(e=>e.type==='url').value='https://ma.example.test';const checks=descendants(root).filter(e=>e.type==='checkbox');checks[0].checked=true;checks[1].checked=true;
|
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==='Test connection and load playlists').listeners.click();assert.equal(code.value,'');assert.ok(!descendants(root).some(e=>e.textContent==='Connect optional companion'));await descendants(root).find(e=>e.textContent==='Connect audio').listeners.click();
|
await descendants(root).find(e=>e.tag==='button'&&e.textContent==='Authenticate').listeners.click();assert.equal(code.value,'');assert.ok(!descendants(root).some(e=>e.textContent==='Connect optional companion'));await descendants(root).find(e=>e.textContent==='Connect audio').listeners.click();
|
||||||
const panel=descendants(root).find(e=>e.tag==='fieldset'&&e.children.some(c=>c.tag==='legend'&&c.textContent==='Scene music'));
|
const 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"]';
|
||||||
@@ -40,3 +40,15 @@ test('normal listener has one activation action and no token or invitation entry
|
|||||||
const dom={createElement:tag=>new Element(tag,dom)};globalThis.document=dom;let clicks=0;
|
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;}
|
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};},async test(profile){draft=connectionDraft(draft,profile,'world');attempts++;assert.equal(draft.token,'private-fixture');if(attempts===1)throw {code:'ws-auth-denied'};return {target:'dedicated',targetName:'Campaign receiver'};}};
|
||||||
|
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==='Authenticate');await submit.listeners.click();assert.equal(errors,1);assert.equal(token.value,'');
|
||||||
|
await submit.listeners.click();assert.equal(attempts,2);assert.equal(errors,1);
|
||||||
|
});
|
||||||
Reference in new issue
Block a user