11 Commits
Author SHA1 Message Date
Jason 8c07a468a4 Synchronize Gitea manifest upload 2026-12-04 11:15:28 -05:00
CheddahBoxMB 4f3fac5f1c Upload files to "/" 2026-12-04 11:13:48 -05:00
Jason 398749210a Release v0.7.2 - Redesigned interface and persistent account settings
Validate and generate manual release / package (push) Waiting to run
2026-12-04 11:08:09 -05:00
Jason 1d894f59fb Reconcile Gitea uploads before v0.7.2 2026-12-04 11:07:31 -05:00
CheddahBoxMB 0b1607cd20 Upload files to "/" 2026-12-04 09:00:20 -05:00
Jason 1ed30567fb Release v0.7.0 - Automatic pairing and validated MA audio playback
Validate and generate manual release / package (push) Waiting to run
2026-12-04 08:58:47 -05:00
CheddahBoxMB 83d168f5a1 Upload files to "/" 2026-12-03 20:16:23 -05:00
Jason eb9536f903 Release v0.6.0 - Music Assistant wizard and automatic listener connections
Validate and generate manual release / package (push) Waiting to run
2026-12-03 20:11:10 -05:00
CheddahBoxMB 5319177c58 Upload files to "/" 2026-12-03 16:20:06 -05:00
Jason f9f891d779 Merge remote-tracking branch 'origin/main'
Validate and generate manual release / package (push) Canceled after 0s
2026-12-03 16:15:54 -05:00
Jason 14f0d8c26b Initial Adaptive Music v0.5.0 release 2026-12-03 16:11:47 -05:00
150 changed files with 12221 additions and 1 deletions

No files matched your search

+29
View File
@@ -0,0 +1,29 @@
name: Validate and generate manual release
on:
push:
tags: ['v*']
workflow_dispatch:
jobs:
package:
# Map this existing runner label to a host/shell executor, not a Docker image.
runs-on: [self-hosted, linux, adaptive-music-release]
steps:
- uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
with:
persist-credentials: false
- name: Validate and generate offline artifacts
env:
RELEASE_REPOSITORY: ${{ vars.RELEASE_REPOSITORY }}
run: |
node --version
node --test tests/js/*.test.mjs
python3 -m unittest discover -s tests -v
python3 scripts/audit_repository.py
python3 scripts/ci_release.py
# Gitea's artifact protocol varies by instance version; this pinned v3 action
# is for compatible existing instances. Manual local generation needs no CI.
- uses: https://github.com/actions/upload-artifact@c6a366c94c3e0affe28c06c8df20a878f24da3cf
with:
name: adaptive-music-manual-release
path: dist/releases/
if-no-files-found: error
+29
View File
@@ -0,0 +1,29 @@
name: Validate and generate manual release
on:
push:
tags: ['v*']
workflow_dispatch:
permissions:
contents: read
jobs:
package:
# Existing shell runner only; this workflow provisions no VM/container/service.
runs-on: [self-hosted, linux, adaptive-music-release]
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
with:
persist-credentials: false
- name: Validate and generate offline artifacts
env:
RELEASE_REPOSITORY: ${{ vars.RELEASE_REPOSITORY }}
run: |
node --version
node --test tests/js/*.test.mjs
python3 -m unittest discover -s tests -v
python3 scripts/audit_repository.py
python3 scripts/ci_release.py
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
with:
name: adaptive-music-manual-release
path: dist/releases/
if-no-files-found: error
+12
View File
@@ -0,0 +1,12 @@
.local/
.env
.env.*
!.env.example
node_modules/
dist/
coverage/
__pycache__/
*.pyc
*.pem
*.key
*.log
+31
View File
@@ -0,0 +1,31 @@
# Adaptive Music contributor instructions
Adaptive Music is an independent open-source project by CheddahBoxMB targeting
Foundry VTT v14.371 and Music Assistant (MA) 2.10.6. It is system-independent.
- Read ARCHITECTURE.md, SECURITY.md, TESTING.md and PROGRESS.md before changes.
- Milestone 1 is research and repository scaffolding. No installable module or
working gateway exists yet. Never label design, source inspection, mocks or
offline checks as verified live integration.
- Require no other Foundry modules. Do not import ATLAS, system-specific actor
schemas, proprietary source, subscription services or telemetry.
- Do not alter production Foundry, MA, Sonos, Nginx, firewall or service versions.
Ask before credential use or production changes. Never request unrestricted root.
- Keep endpoints, credentials, campaign/player mappings and deployment files under
ignored .local/ (directory mode 0700, secret files 0600). Never place MA tokens in
Foundry settings, browser bundles, flags, URLs or logs. Examples use placeholders.
- MA access belongs on the gateway; browsers receive campaign-scoped capabilities.
Never implement an unrestricted MA HTTP/WebSocket/Sendspin proxy.
- Only a campaign-owned dedicated audio target is eligible for control. Do not
discover-and-select household players, transfer queues, group speakers or issue
global stops. Native sound effects and AmbientSound documents are out of scope.
- Serialize transitions under a fenced authority lease; snapshots and commands
carry campaign, session and generation. Reject stale events and restores.
- Preserve upstream notices for reused source. Record exact versions, commits,
licenses and dependencies before adding code. Do not run upstream install hooks
merely to inspect source. Lock and audit dependencies before distribution.
- Run `python3 -m unittest discover -s tests -v` and
`python3 scripts/audit_repository.py` before a commit. Run
`python3 scripts/verify_upstream.py` when local research checkouts are available.
- Update evidence and verification status with every meaningful implementation.
Do not invent Gitea remotes, release URLs, Foundry verification or test results.
+107
View File
@@ -0,0 +1,107 @@
# Adaptive Music architecture — 0.7.2
Adaptive Music is an independent project by CheddahBoxMB for Foundry v14.371 and
MA 2.10.6, with no system dependency or additional required process. The expanded
operator authorization selects direct trusted-GM browser access and GM-local
credential handling for the standalone module; it supersedes the older gateway-only
scaffolding rule. Optional historical gateway source is not required or deployed.
## Setup and receiver ownership
The Connection tab validates the server, token and optional Advanced network fields
before authentication. The Connect gesture starts the GM audio context before
authentication, receiver provisioning and catalog loading. Playback reads the
dedicated MA queue and submits controls on the same controller as scene transitions.
The GM supplies the private trusted HTTPS MA origin and access token. Authentication
reads account-authorized music providers. The official pinned Sendspin SDK generates
one X25519 identity for the campaign, GM user and MA origin. Its identity, pairing
storage, catalog key and name are encrypted in local IndexedDB with a non-extractable
AES-GCM key. The key is stored in the same browser; this does not protect against
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 logged-in GM account can retain an AES-GCM envelope containing the last
successfully connected MA address and receiver name in a Foundry User Setting.
The MA token supplied for a connection unlocks the envelope. Its key is derived
with a separate purpose label and bound to the Foundry origin, world and user.
Foundry persists the encrypted record across devices and server restarts.
Connect audio first authenticates the `/ws` API session, then authenticates
`/sendspin` using that token and the SDK-generated client ID. MA 2.10.6 associates
this new web receiver with already-authenticated API sessions for the token. The
same API session must therefore survive pairing, catalog reads and playback.
`sendspin/pair_web_player` pairs only this identity to the calling account. Noise
activation and clock synchronization precede exact ID/name/provider/topology checks.
During startup, a successful null queue lookup is retried briefly on the same
authenticated API session because MA can expose the player before registering its
queue. Playback requires the receiver’s own active queue.
There is no household player list or arbitrary target selector.
The receiver uses SDK software volume. Fresh receivers do not report volume before
capabilities are advertised, so volume cannot be a preconnection requirement. Static
account-authorized playlist tracks become opaque HMAC references bound to the stored
catalog key and campaign. New references use a separate key derived from the MA
token, MA origin and campaign so the same authorized catalog resolves on another
browser. A browser with its original receiver vault still resolves legacy IDs.
Saving that scene again writes the new reference. Scene/world flags hold opaque
references. Live connections still depend on the active GM browser and its audio
context. Disconnect stops the session and clears the in-memory token.
## Audio and 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.
User document public keys authenticate ephemeral ECDH/AES-GCM invitation delivery.
Private keys stay in memory. Invitations are bound to world, sender, recipient,
epochs and expiry. Each player receives only its own WebRTC capability. Bounded
AES-GCM envelopes carry SDP over Foundry’s module socket; audio uses DTLS-SRTP,
never PCM over that socket. Firefox’s session-level SDP direction default is
correctly overridden by the sole audio media direction. Offers remain recvonly;
answers remain sendonly. Video, data and injected sender media are rejected.
Up to eight listeners negotiate automatically. Invitations renew after 20 minutes
and expire after 30. Failed negotiation times out after 20 seconds; disconnected
peers are revoked after 10 seconds and the 15-second reconciliation loop can issue
fresh invitations. One user gesture unlocks browser audio when required. A stable
HTMLAudioElement pumps the incoming remote track; Web Audio provides an optional
activated playback path. Default ICE has no public STUN/TURN service. WAN delivery
requires a viable existing ICE route and is not inferred from local tests.
## Transitions and recovery
Manual override/silence > explicit boss > started combat in the active scene >
ambient > world default > silence. No system actor schemas are used. The existing
serialized controller checks campaign/session/generation and current authority.
A single active GM plus a Web Lock excludes common duplicate tabs; this is not a
server-side distributed fence or seamless handover protocol.
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.
Reconnecting to a remembered owned receiver can attach to its existing queue
without replacing it. Automation remains paused for explicit resumption when that
queue is nonempty. Crash/reload cannot guarantee restoration of an interrupted
ambient stack or logical pause position. No crossfade or independent simultaneous
layers is implemented with the single upstream queue. Native playback uses only
explicitly owned playlists; effects and AmbientSound remain untouched.
## Verification boundary
The installed v0.7.0 module was tested in a logged-in Foundry v14.371 development
world through the private Nginx route. The GM connected to MA and two players
received audio using Foundry’s module socket for signaling. The test also exercised
real combat hooks, ordered ambient restoration, and User document permissions.
Earlier browser tests used a Playwright source overlay. The original Mac path,
physical-device audibility, invitation renewal and WAN behavior remain unverified.
+86
View File
@@ -0,0 +1,86 @@
# Changelog
## 0.7.2 — account-scoped connection setup
- Remember the Music Assistant address and receiver name in an encrypted Foundry User Setting. Enter the MA token to unlock the saved address and connect in a new browser session.
- Make newly saved catalog assignments readable across browsers that use the same MA token, server and Foundry world. Preserve legacy reference resolution in the browser that created it.
## 0.7.1 — AM-006 setup usability
- Give the resizable GM window three tabs for Connection, Scene Music and Playback.
- Connect with one action that validates the inputs, authenticates, provisions the
dedicated receiver and loads playlists. Keep listener networking under Advanced.
- Show the current track, position, volume, automation state and connected listener
count. Queue pause, resume, seek and stop through the existing playback authority.
## 0.7.0 — integrated campaign receiver
- Replace receiver JSON import with authenticated automatic dedicated web-receiver
provisioning and account-bound pairing. Remember the receiver privately in the
GM browser; retain the MA token only in tab memory.
- Keep one authenticated API session established before Sendspin so restricted MA
accounts retain the receiver’s session permissions. Wait briefly for MA to
register the dedicated queue during setup. Use SDK software volume.
- Fix Firefox SDP direction inheritance, PCM stream-ahead scheduling and timestamped
partial clears. Add transport, authentication, pairing, clock, audio and listener
diagnostics in the interface. Fix narrow ApplicationV2 layout.
- Preserve inputs across failures, retain receiver identity across reloads, and allow
reconnection to the owned queue without replacing it. Pause automation on uncertain
writes; do not retry queue mutations blindly. Bound failed listener negotiation.
- Emulate pause for MA 2.10.6 Sendspin using stopped queue plus saved index/position;
restore paused queues without briefly playing them. Keep active-session interruption
snapshots for up to 12 hours rather than five minutes.
- Exercise actual MA catalog audio, two browser listeners, combat transitions and queue
restoration in Firefox and Chromium. Preserve the failing queue command in
diagnostics and skip rollback on uncertain writes.
- Preserve existing Gitea manifest/update URLs and manual publication bundles.
Crossfade and durable crash restoration remain unsupported.
## 0.6.0 — GM connection interface
- Add a GM Music Assistant connection wizard: private server/token entry, existing
receiver backup import, dedicated target verification, catalog loading, audio
connection and actionable diagnostics. Credentials remain in GM tab memory.
- Enable explicitly authorized catalog playlist playback through the existing guarded
provider. Keep native ownership, ambient/combat/boss assignments and fallback.
- Automatically deliver encrypted listener invitations using ephemeral ECDH keys
bound to Foundry User documents; players normally need only Enable Audio.
- Hide optional companion and synthetic/manual test controls behind a client-scoped
advanced development setting. Simplify the primary setup and listener windows.
- Document trusted HTTPS/WSS, logging, identity/pairing, browser activation and ICE
requirements without bypasses or additional mandatory infrastructure.
- User reports v0.5.0 published/installed/activated on Foundry v14.371 and D&D 5e
6.1.2 with both windows rendering. v0.6.0 live Foundry/MA audio remains unverified.
## 0.5.0 — local release candidate
- Prepare one standard Foundry module ZIP and offline manual-upload release bundle
for the planned Gitea destination, with configurable GitHub/Gitea URL generation,
stable update manifest, immutable versioned download and SHA256 checksums.
- Preserve validated native playback, scene/world assignments, combat/boss/manual
policy, catalog, guarded MA transport and queue restoration. Share the same
transport/provider implementation between the optional companion and trusted GM
browser using Web Crypto.
- Add pinned official Sendspin JS 5.0.0 PCM-only bundle with dependency lock, audit,
full notices and recorded modification (optional Opus fallback omitted).
- Add experimental GM-local SDK decoding/Web Audio and encrypted, per-listener
capability-signaled WebRTC audio. Module sockets carry no continuous raw audio.
- Keep the companion as an optional, undeployed co-located fallback; no container,
VM/LXC, OS-service installer, core patch or sandbox runtime dependency.
- Remote MA audio is not yet verified: existing DEV private identity, secure browser
reachability, synthetic ingestion and real NAT/browser/Foundry gates remain.
Crossfade, simultaneous ambient layers and seamless GM handover remain unsupported.
## 0.4.0-dev
- Connected GM setup, scene ambient/combat/boss defaults and native fallback with the
private companion and MA catalog. Measured connected read-only MA catalog locally;
added synthetic PCM browser sink and loopback integration tests.
## 0.3.0-dev
- Added guarded MA playback provider, durable catalog identifiers, signed ordered
queue snapshots/restoration and isolated native Foundry development package.
- Live idle queue control tests restored original state. Synthetic ingestion failed;
no nonempty MA queue or real playlist playback was verified.
+82
View File
@@ -0,0 +1,82 @@
# Install and connect — 0.7.2
## Normal setup
1. Install or update **Adaptive Music** using the existing Foundry manifest URL.
For the staged acceptance build, extract `adaptive-music.zip` into the existing
Foundry user-data `Data/modules/` directory and reload the isolated test world.
The ZIP contains one `adaptive-music/` directory. Do not install the outer release
bundle or source archive as the module.
2. As the single active GM, open Settings → Adaptive Music setup. In **Connection**,
enter the private **HTTPS Music Assistant server address** and the dedicated
account’s access token. Use the server origin and select **Connect** to create or
reconnect the campaign receiver, pair it, and load playlists.
3. Select **Choose scene music**. In **Scene Music**, choose the scene and save its
ambient, combat, boss and native fallback assignments. You can also set world
defaults and individual boss overrides.
4. Open **Playback** to enable automation, see the current track and listeners, or
adjust campaign volume and control the dedicated MA queue.
5. Players connect automatically. If a browser requires activation, open Campaign
audio and select **Enable Audio** once. Keep one audio tab per account.
After a successful connection, the GM’s Foundry account remembers the encrypted
server address and receiver name. On another computer or after reload, enter the
same MA token and select **Connect** to unlock the saved address. Reload and
**Disconnect** clear the in-memory token. If the token changes, enter the server
address with the replacement token. **Advanced → Forget saved connection** clears
the account record. The receiver identity remains encrypted in its browser vault.
New MA playlist assignments resolve across browsers using the same MA token and
origin. To update a legacy assignment, connect from the browser that originally
saved it and save the scene again. From a different browser, reselect its playlists.
Keep the active GM browser open for live MA playback and listener forwarding.
Reconnecting to an owned nonempty queue preserves it. Enable automation in Playback
when ready to resume scene control. Unknown mutation outcomes stop automation and
require review. Pause preserves a stopped queue’s index and position for the active
GM session.
## Connection diagnostics
Connection shows authentication, receiver setup and catalog progress. **Check browser
connection** tests both WebSocket routes from the actual Foundry page without sending
an MA authentication frame. Normal browser cookies can accompany the handshake.
**Copy connection diagnostics** supplies a report without address, token, receiver
keys or playlist titles. No browser developer console is required.
| Result | Action |
| --- | --- |
| 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. |
| 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. |
| API auth denied | Enter a valid token; the remembered receiver is retained. |
| Sendspin auth/pair/sync fails | Check the separate authenticated /sendspin route and the account’s web-player control permission. |
| Dedicated queue unavailable after pairing | Retry connecting the remembered receiver after MA has registered its queue. |
| Frames arrive but audio is suspended | Select Enable GM audio or the player’s Enable Audio once. |
| Listener fails negotiation | Check its diagnostics and existing network/ICE route. It is automatically retried after timeout. |
| MA error 2 on playlist startup | MA could not find playable media even if catalog metadata exists. Check that content/provider in MA; this is separate from a WebSocket upgrade failure. |
| Unknown queue write | Review the dedicated queue, then deliberately reconnect; no blind retry occurs. |
Use trusted HTTPS for Foundry and private HTTPS/WSS for both MA `/ws` and `/sendspin`.
Keep Nginx access restrictions, Origin, certificate validation and browser protections.
Keep MA raw-frame VERBOSE logging disabled. No public API/proxy, core modification,
additional container, service, VM or LXC is required by this module. A direct HTTP MA
address cannot be used from HTTPS Foundry. Default ICE does not use a public relay;
remote players still need a viable existing WebRTC path.
See TESTING.md for private-route evidence and the outstanding installed, Mac and WAN checks.
## Manual Gitea publication
The existing stable manifest and versioned download mechanism is preserved:
- Manifest: `https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/raw/branch/main/module.json`
- v0.7.2 asset: `https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/releases/download/v0.7.2/adaptive-music.zip`
These are the established repository’s URLs; this work never contacted Gitea or
verified public asset availability. After acceptance, manually publish the included
source to your existing repository, create tag/release `v0.7.2`, attach
`adaptive-music.zip` and the included manifest/checksums, and update the branch
manifest only after its versioned asset exists. The outer bundle includes full
source, docs, licenses, metadata and SHA256SUMS. Keep the previous immutable release
assets for rollback. To roll back, restore the prior branch manifest/module ZIP;
MA queues and remembered browser identities are not automatically deleted.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 CheddahBoxMB
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+56
View File
@@ -0,0 +1,56 @@
# Adaptive Music progress — 0.7.2 staged acceptance
Standalone module work now includes automatic campaign receiver provisioning and
account-bound pairing, remembered encrypted browser-local identity, memory-only token
retention/retry, scene assignments, listener bootstrap, guarded transitions and queue
restoration. Existing Gitea URLs/manual release mechanism are preserved. No Git host
was accessed and no production infrastructure/core versions were changed.
## Defects
| Defect | Implemented and tested | Remaining acceptance |
| --- | --- | --- |
| AM-001 layout | Actual Foundry v14.371 ApplicationV2 at 380/640px; Chromium fixture at 380/640/1000px | Operator’s logged-in-world theme |
| AM-002 provisioning | SDK-created identity, authenticated dedicated web-receiver pairing, no normal JSON import; real MA tests | Normal installed-world flow on Mac |
| 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 |
| 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 |
| AM-005 cross-origin | Both WSS routes open through private Nginx in Ubuntu Chromium and Firefox. Chromium authenticated and paired in the installed Foundry world. The MA front end’s unauthenticated Sendspin interceptor explains the failing control probe. | Original Mac-specific pre-upgrade failure remains unresolved |
| AM-006 setup usability | The v0.7.1 browser preview passed layout at 380 and 760 pixels, one-click connection, scene assignment and real playback controls in the development world. | Retry the same workflow with v0.7.1 installed on the server |
| Account persistence | The v0.7.2 preview saved an encrypted connection record in the Foundry GM account and connected from a fresh browser with the token alone. New scene references are portable across browsers using that token. | v0.7.2 server installation and Mac acceptance |
| MA catalog playback | The installed module delivered audio to two real Foundry players during ambient, combat and restoration to a seven-second offset. Stop/Enable and reload were exercised. | Physical devices, invitation renewal and WAN acceptance |
## Technical findings
- The operator’s scoped firewall exception enabled TCP 443 and trusted TLS to the
private Nginx proxy. The test verified the proxy peer before signing in on the
normal Foundry hostname. The signed-in page had no enforced CSP header or meta
policy and both MA WebSocket upgrades returned HTTP 101.
- Browser playback analysers measured audio on both real Foundry listeners even
while Chromium’s inbound RTP energy statistic reported zero. The integration
test uses the rendered playback signal. No module runtime change was required.
- MA grants a new browser receiver access through API sessions authenticated before
Sendspin auth. Replacing the API socket breaks a restricted account’s access.
- Firefox reached an available paired receiver before MA returned its queue. Setup
now waits briefly for a missing queue on the same session. The regression fixture
exercises the delayed reply; the live follow-up received the queue immediately.
- A new receiver’s volume is initially null. SDK software volume avoids that startup
dependency and provides campaign volume without controlling unrelated players.
- Firefox adds a session sendrecv default after ICE gathering. Correct SDP validation
honors the audio media recvonly override and still rejects sender/video/data offers.
- MA sends PCM roughly four seconds ahead. The old two-second scheduler cutoff dropped
most real audio; bounded six-second scheduling and timestamped clears address it.
- MA 2.10.6 Sendspin has no native pause. Logical stop-plus-position pause is implemented
and tested, including paused restoration without briefly playing.
- Five-minute snapshot expiry was too short for combat. Signed active-session snapshots
now last up to 12 hours and remain campaign/session/fence/generation-bound.
The live follow-up records real PCM and two listener signals, emulated pause, seek,
resume, volume, and queue restoration in Firefox and Chromium. Earlier catalog
startup failed with MA `MediaNotFoundError` in both engines. The cause of those
failures remains unconfirmed. The controller preserves the failed command and skips
rollback after an uncertain write. See `evidence/v0.7.0-live-follow-up.json`.
The installed-world evidence is in `evidence/v0.7.0-foundry-private.json`. Publication
remains pending Mac, physical-device, WAN and invitation-renewal checks in TESTING.md.
Crossfade, durable crash restoration, seamless handover and WAN synchronization
remain unsupported.
+28 -1
View File
@@ -1,2 +1,29 @@
# adaptive-music # Adaptive Music — 0.7.2
Independent open-source Foundry VTT music automation by **CheddahBoxMB**, targeting
Foundry v14.371 and Music Assistant 2.10.6. System-independent; one Foundry module
ZIP, no other required module, container, VM/LXC or companion service.
Enter your private HTTPS MA address and token in **Connection**, then select
**Connect**. Assign playlists in **Scene Music** and enable automation in
**Playback**. Players receive WebRTC audio
automatically, with one Enable Audio click if their browser requires it. No receiver
identity export or JSON import is part of setup.
The signed-in GM account remembers the encrypted Music Assistant address. Enter the
MA token and select **Connect** to unlock it in a new browser session. MA tokens
stay in the GM tab’s memory. A campaign/GM/origin-scoped receiver identity
is encrypted in that browser’s IndexedDB so reconnecting does not create another
receiver. Players receive individually encrypted invitations, not MA credentials.
Only that dedicated receiver and explicitly owned Foundry music playlists are
controlled. Household speakers, grouping, queue transfers, sound effects and
AmbientSound documents are outside the control surface.
The v0.7.1 browser preview passed the new graphical setup and playback workflow
in a real Foundry v14.371 development world with two listeners. See TESTING.md
for the test scope and remaining installed-build checks.
See INSTALL.md for setup/manual publication, TESTING.md for the consolidated Mac
acceptance sequence, SECURITY.md for trust boundaries and PROGRESS.md for status.
Crossfade, seamless GM handover, durable crash restore and WAN synchronization
claims are not implemented. Attribution and licenses remain in THIRD-PARTY-NOTICES.
+70
View File
@@ -0,0 +1,70 @@
# Adaptive Music security — 0.7.2
## Credentials and browser trust
The MA access token remains in the trusted GM tab’s closure memory. It is excluded
from Foundry settings, flags, sockets, URLs, console logging, IndexedDB serialization
and release archives. Setup failures retain it in this tab; disconnect or reload
forgets it. Tokens are never reused after an origin change. Use a restricted MA
account with only the intended music providers and dedicated receiver permissions.
The Foundry User Setting stores only a version, random nonce and encrypted MA
address and receiver name. The encryption key is derived from the user-entered MA
token for this account and world. Use a generated, high-entropy MA token. The
envelope cannot be unlocked after rotating that token. Connect with the explicit
address and new token to replace it. Forget saved connection removes the envelope.
Receiver private identity and pairing material are encrypted in the GM browser’s
IndexedDB under a campaign/user/origin-derived scope. Encryption uses AES-GCM and
a non-extractable key stored in the same browser. It avoids plaintext receiver
storage; it cannot protect against same-origin scripts, a compromised enabled
module, the local profile owner or theft of a complete browser profile. Use separate
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.
Private development endpoints, tokens, identities, account/catalog results and
snapshots remain under ignored .local/ (0700; secret files 0600). MA raw WebSocket
frames can include credentials at VERBOSE logging. Keep raw-frame logging disabled;
the module does not change production log settings. Expanded operator authorization
covers the dedicated live development tests; no production infrastructure was changed.
## Network and authority
Trusted HTTPS Foundry and private HTTPS/WSS MA are required. TLS validation, browser
security, Origin and private access controls remain enabled. No public MA endpoint,
Origin forgery, CORS wildcard change or unrestricted proxy is introduced. Both `/ws`
and `/sendspin` must reach their authenticated MA routes. Token-free diagnostics
send no explicit MA auth frame; browsers may still send their normal ambient cookies.
Browser APIs do not expose arbitrary HTTP/TLS errors and diagnostics do not invent
those causes.
Only the SDK-generated and locally remembered campaign receiver is paired or
controlled. The account-bound pairing API is used after the API session is bound
by Sendspin authentication. Exact identity/name/provider, enabled/available state,
standalone topology and own active queue are checked before writes. No household
selection, grouping, transfer or global stop is offered. Unknown writes latch closed.
Queue snapshots are signed and campaign/session/fence/generation-bound; later
sessions reject them. Browser authority cannot replace a distributed server fence.
Players receive scoped expiring encrypted capabilities, not MA secrets or addresses.
Public ephemeral keys on permission-controlled User documents authenticate invitation
delivery. Both ordinary test players were denied a write to the GM’s User flags in
the installed development world. SDP is encrypted, bounded and
replay protected, and validated for one audio direction with media-level SDP
inheritance. No microphone, video or data channel is requested. Audio uses DTLS-SRTP.
Recipients can record audio or disclose their own capability. Direct peers can
learn network addresses. No public STUN/TURN is silently configured. Optional existing ICE URLs and short-lived TURN credentials are entered in the GM interface, kept in tab memory, and delivered only inside the encrypted per-player invitation.
## Recovery and distribution
API/Sendspin loss stops automation and listener forwarding. Retained tab inputs
support a deliberate reconnect; the owned queue is not replaced during reattachment.
No blind mutation retry or automatic crash restoration is promised. Logical pause
and interruption snapshots do not survive a reload. Native fallback cannot silently
resolve an uncertain remote queue.
The release builder is offline, preserves the existing Gitea update mechanism,
checks import/assets closure, SDK hash, licenses, privacy patterns and checksums,
and includes complete source. No new distributed dependency, runtime CDN, upstream
install hook, telemetry, core patch or mandatory companion service was added. The
pinned SDK and noble notices remain intact. No Git host was contacted.
+1
View File
@@ -0,0 +1 @@
1ccdd229e40e1e02f0fa76d8fc553877c66c9494
+175
View File
@@ -0,0 +1,175 @@
# Adaptive Music verification — 0.7.2
## Executed evidence
The source archive includes sanitized evidence separately from private .local inputs.
### Account persistence and v0.7.0 GUI review
The installed v0.7.0 was exercised again through Foundry’s Settings and Adaptive
Music menus. Playwright filled the server address and access token and pressed
Authenticate and Connect audio. The run used the private proxy route with normal
TLS validation and did not replace module assets. The GM saved ambient and combat
assignments on a review scene and confirmed the GM decoder received live audio.
The scene was left in the development world. In the same world, a browser-supplied
v0.7.2 candidate saved an encrypted Foundry User Setting. A new browser session
logged into the same GM account and connected with the token alone. The server
continued serving v0.7.0 during both tests. Closing the GM audio tab ends the
browser-hosted connection. See `evidence/v0.7.2-live.json`.
### AM-006 live graphical workflow
The v0.7.1 interface ran inside the actual Foundry v14.371 development world with
module assets supplied to the test browser by Playwright. The graphical window
passed sizing, horizontal fit, scroll containment, keyboard navigation, Advanced
visibility and input validation at 380 and 760 pixels. Through the private route,
one Connect action authenticated, provisioned the receiver and loaded the catalog.
The GM saved scene assignments and enabled automation through the tabs. Both
listeners measured audio during real combat and ambient restoration to eight seconds.
The Playback tab showed the track and both listeners. Volume, pause, resume and stop
worked through the graphical controls. Listener Stop/Enable and reload also passed.
The earlier private-route timeout and an ambient startup attempt without a queue
write are recorded alongside the passing rerun in `evidence/v0.7.1-live.json`.
Verification of the v0.7.1 ZIP installed on the server is pending.
### Installed development world over private Nginx
- Chromium 159 signed into Foundry v14.371 as the GM and both players. The installed
v0.7.0 module authenticated to MA and paired a dedicated Sendspin receiver. Both
WebSocket routes returned HTTP 101 from the signed-in page, which exposed no
enforced CSP header or meta policy.
- Both players received encrypted invitations through the real Foundry module socket.
Foundry denied both ordinary players’ attempts to update a flag on the GM’s User
document. Both players measured signal in their actual playback graphs during
ambient, combat and restored ambient. The original queue order and seven-second
offset were restored. Audio also returned after Stop/Enable and a player reload.
Chromium’s inbound RTP energy counter stayed at zero while the playback graphs
showed audio, so the test uses the playback signal.
- The MA control page replaces `window.WebSocket` and intercepts Sendspin. Its
unauthenticated interceptor failed the bare `/sendspin` probe. The native browser
constructor opened the same URL from the same page in Chromium and Firefox.
The original Mac-specific AM-005 failure did not reproduce on this Ubuntu route.
The Ubuntu Firefox build completed transport checks. Its Foundry join UI failed
to render in this environment, which could not create a WebGL context.
See `evidence/v0.7.0-foundry-private.json` for the installed-world results.
### Earlier browser and source-overlay checks
- Ubuntu Firefox 159.0 and Chromium 159.0.8154.6
authenticated from Foundry’s origin and MA’s origin and retrieved seven providers.
The unauthenticated Foundry page returned no enforced CSP header or meta policy.
- Both browsers paired a dedicated MA web receiver, completed Noise and clock sync,
and loaded eleven catalog playlists.
- Firefox 159 and Chromium 159 delivered real MA audio to two WebRTC listeners
after one activation click each. Both listeners measured audio during ambient,
combat and restored ambient. The runs exercised emulated pause, seek, resume,
volume, ordered track/offset restoration and final queue restoration.
- Both browsers reconnected the same receiver after an induced Sendspin disconnect
and browser reload. Reattachment preserved the idle nonempty queue without
writes, retained the identity without the token and rejected a stale snapshot.
- One Firefox startup received an available player but no queue. Startup now waits
briefly for that queue to register. The delayed reply is covered by a regression
fixture. The passing live playback follow-up received the queue on the first read.
- The browser source assets were supplied locally by Playwright under the deployed
Foundry origin. Controller inputs were explicit scene/combat states and signaling
used an encrypted-envelope relay through the test runner. This was not an installed,
logged-in Foundry world or real Foundry socket/user-permission test.
- Actual deployed Foundry v14.371 ApplicationV2 rendered the setup at 380/640px with
in-memory sample documents. Real IndexedDB receiver vault reopen, user isolation,
token exclusion and forgetting passed. No world documents were changed.
- Real browser signaling exposed Firefox’s session-default SDP inheritance; its fix
was retested in Firefox 144.0.2 and Chromium 143.0.7499.4.
Trusted local-CA HTTPS/WSS policy tests cover
allowed cross-origin, enforced/report-only CSP and server Origin rejection.
See `evidence/v0.7.0-live-follow-up.json`, `evidence/v0.7.0-live.json`,
`evidence/foundry-application-v070.json` and `evidence/v0.7.0-checks.txt` in the source
archive. Earlier Firefox and Chromium runs received MA `MediaNotFoundError` (code 2)
during playlist startup despite playable track metadata. Its cause remains
unconfirmed. Those failures are retained alongside the passing follow-up. The live
runs used dedicated MA development receivers exclusively.
## One consolidated Mac / logged-in-world acceptance
Run this in an isolated test world with the actual Foundry v14.371 host and existing
private HTTPS MA endpoint. It needs no developer console or diagnostic shell commands.
1. Install the staged module ZIP, reload, and log in as the sole active GM from your
Mac. Open setup at normal and narrow window sizes. Enter the HTTPS MA address and
dedicated token, then select **Connect**. The receiver should be provisioned
and playlists should load without a backup file. If MA reports media error 2 after connection, verify the same content in MA’s own dedicated web player before treating it as a browser transport failure. If connection fails, select Check
browser connection and Copy connection diagnostics once, and report that single
report with browser/version and whether MA’s own page works in that same browser.
2. In **Scene Music**, choose two authorized static playlists for an active scene’s
ambient/combat music and save. In **Playback**, enable automation. Check the GM
hears ambient and decoded frames increase.
Only the campaign receiver may be controlled. Native fallback remains optional.
3. Log in as two ordinary players using separate browser profiles/devices. They should
receive audio automatically, needing at most one Enable Audio click. Check late login,
Stop/Enable and one player reload. An unrelated user must not receive another user’s
invitation; verify Foundry still prevents players from editing other User keys/roles.
4. Note the ambient track/offset in MA. Start an actual Foundry combat in this scene,
then end/delete it. Both players should hear combat then ambient at the saved offset,
rather than restarting ambient. Repeat a rapid start/end and confirm no duplicate queue.
5. Close/reopen setup and retry one failed login with a replacement token. The private
draft/receiver should remain; after a browser reload only the token needs reentry.
Reconnect the same owned receiver and confirm its queue is not replaced. Apply the
automation setting explicitly if a nonempty queue was retained.
6. Continue listening for at least 30 minutes across invitation renewal. Exercise one
brief network interruption, reconnect, and one background/suspend cycle. Report
failures with Copy connection diagnostics. Repeat on the actual WAN player route;
loopback/LAN signal does not establish NAT/TURN reachability or synchronization.
The installed-world run covered real Foundry hooks, socket delivery and User
permissions. Public release acceptance still requires audibility on the actual
Mac/player devices, the original Mac connection, invitation renewal and WAN checks.
If AM-005 reproduces on the Mac, correlate its browser connection stage and timestamp
with the private proxy’s request and upstream status or TCP counters. The procedure
and temporary VM-to-proxy access rollback are in ignored .local/PRIVATE-ROUTE-REQUEST.md.
## Reproduce development checks
Use the existing pinned Node 24.23.0, Python standard library and Playwright 1.57.0.
No upstream installation hook is required.
For private-route diagnostics, run `node scripts/check_foundry_private_route.mjs`
with the existing browser path settings. The probe verifies the HTTPS peer address
for both origins and compares WSS upgrades from Foundry and Music Assistant. It
captures handshake status and browser policy metadata. Add `--logged-in` after the
private route is reachable and the dedicated development world is active. That
mode verifies the installed module version, signs in with the three configured
test accounts in separate browser contexts, and adds the authenticated Foundry
page as a comparison. `--playback` also exercises actual MA audio, Foundry combat,
listener recovery, and cleanup with temporary development-world documents and a
dedicated integration receiver. Configuration and results remain under ignored
`.local/`.
```sh
npm test
python3 -m unittest discover -s tests -v
python3 scripts/audit_repository.py
python3 scripts/verify_upstream.py
PLAYWRIGHT_BROWSERS_PATH=.local/browsers node scripts/check_setup_browser.mjs
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
```
Live scripts require authorized private configuration/token in ignored .local/ and
must only operate on their generated `Adaptive Music integration …` receivers.
`--fresh` exercises module provisioning directly and keeps the generated receiver
identity and reports in a separate private directory under .local/.
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.
## Limits
Mac/Safari behavior, physical audibility, WAN relay, long-run skew/drift, seamless
GM handover, crash restore and crossfade remain unverified or unsupported. The
upstream single queue provides one playback stream. Pause is emulated and its
saved position lasts for the active GM session.
+51
View File
@@ -0,0 +1,51 @@
Adaptive Music — independent open-source project by CheddahBoxMB.
Not an official Foundry VTT, Music Assistant, Sendspin or VGM product.
Milestone 1 records research; the subsequent source prototype adapts VGM per-sound
stop and pausedTime restoration in src/providers/native/provider.mjs. The controller
and Foundry bootstrap are new implementations informed by the audited VGM behavior.
The browser SDK and cryptographic dependencies listed below are now bundled.
Preserve this attribution and the full licenses supplied alongside the module.
Video Game Music (VGM)
https://github.com/Sayshal/vgmusic
Release release-1.4.5; commit eba07a08c9925f31b9c8adb72faf95de11ae705c
Authors named by manifest: Furyspark and Tyler (Sayshal).
Copyright (c) 2025 3 Death Saves
MIT License. Full copyright, grant and disclaimer: licenses/VGM-MIT.txt.
The notice and permission text must accompany copies/substantial portions.
Music Assistant server
https://github.com/music-assistant/server
2.10.6; commit c24866405bd2068c25a60e1014e5ef8c3f6445bb
Music Assistant frontend
https://github.com/music-assistant/frontend
2.17.297; commit e779b9d359e47cd210c2801f16a0ce6263571903
Sendspin JS — Sendspin Protocol Authors / Open Home Foundation
https://github.com/Sendspin/sendspin-js
5.0.0; commit 7d103075138dda5c8909045647bb42b33c2d44fc
6.1.0; commit 7ee7ca35ac29ae3ef5f2eeeeaac1e24751a8790b (comparison)
aiosendspin — Sendspin Protocol Authors
https://pypi.org/project/aiosendspin/9.1.1/
These inspected sources declare Apache-2.0. Full license: licenses/Apache-2.0.txt.
Bundled browser runtime (vendor/sendspin-5.0.0.mjs):
- @sendspin/sendspin-js 5.0.0, Apache-2.0; licenses/vendor/-sendspin-sendspin-js.txt.
- @noble/ciphers 1.3.0, MIT; licenses/vendor/-noble-ciphers.txt.
- @noble/curves 1.9.7, MIT; licenses/vendor/-noble-curves.txt.
- @noble/hashes 1.8.0, MIT; licenses/vendor/-noble-hashes.txt.
Exact registry integrity hashes, build inputs and bundle SHA256 are recorded in
vendor/provenance.json and evidence/sdk-adoption.json. Modified distribution:
bundled/minified exports, PCM-only; optional Opus decoder imports are replaced by
explicit unsupported-codec stubs. No Opus/WASM decoder or codec binaries ship.
No upstream NOTICE file was present in the inspected SDK package. Full upstream
copyright/license texts accompany this modified distribution. No runtime CDN.
Build/test dependencies (not required by the installed module): esbuild 0.27.1
(MIT), Playwright 1.57.0 (Apache-2.0), exact transitive pins in package-lock.json.
Their installed source/binaries are not included. opus-encdec 0.1.1 is installed
as an SDK dependency for reproducible inspection but excluded from the browser
bundle; its MIT and embedded libopus/Speex BSD licenses were reviewed. See
evidence/sdk-adoption.json for the distribution boundary and audit results.
Foundry VTT public documentation is a reference only. Foundry software is not
redistributed. No third-party music assets are included; browser tests generate original tones. No upstream source has been relicensed.
+104
View File
@@ -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.
+37
View File
@@ -0,0 +1,37 @@
# Sendspin provisioning research — 2026-12-03
Evidence class: source inspection only. MA 2.10.6, commit
`c24866405bd2068c25a60e1014e5ef8c3f6445bb`; new inspected file hashes recorded in
`upstream.json`. No upstream code copied, dependency installed or provisioning run.
`providers/sendspin/provider.py:656` defines `create_virtual_player(owner_instance_id,
display_name, player_id=None)`. This is an in-server Python provider API, not a
registered external HTTP command. It requires a loaded provider owner, checks
ownership/collisions, prefixes stable IDs, registers the client and queue, and
persists the owner marker. Removal deletes configuration; unloading the owner
removes its targets. Restart requires the owner to recreate the anchor. See the
same directory's README, “Virtual Players”, and `_register_virtual_player_client`.
This anchor discards its own audio. Its documented delivery mechanism attaches
member players through standard grouping. That mechanism does not meet Adaptive
Music's no-grouping boundary and is not an adopted gateway audio source. Creating
an anchor alone would not terminate audio at the gateway.
`player.py:_refresh_client_info` recognizes web/app clients from device information
and makes them standalone/private. A future isolated gateway Sendspin client with
an operator-assigned stable identity could be researched as a dedicated receiver,
but needs protocol/Noise/codec and reconnect tests, licensing/dependency review,
explicit target creation approval, and an operator update of the nonempty account
player filter. An arbitrary new identity must never be automatically selected.
No public automatic provisioning path suitable for the current external gateway
was established. Existing Adaptive Music DEV remains the only authorized target.
Decision: retain the manually provisioned development target. Do not add an MA
plugin, use grouping, create resources, or change production settings in this milestone.
## 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.
+46
View File
@@ -0,0 +1,46 @@
# Dedicated gateway receiver — public-interface investigation
Checked 2026-12-03. Evidence class: official public protocol/SDK documentation and
pinned source inspection, not a running receiver or a live MA handshake.
Official references:
- [Client implementation guide](https://www.sendspin-audio.com/build/guide/client/)
- [Protocol specification](https://www.sendspin-audio.com/build/spec/)
- [aiosendspin SDK](https://github.com/Sendspin/aiosendspin)
A separate player-role client is the supported public interface. Persist its X25519
identity and pairing records privately; advertise only player capability, use Noise
transport, pin the intended server identity, and never advertise controller/source
roles or forward MA traffic. The public protocol supports client-initiated discovery
and connection as well as server-initiated connections. Prefer an operator-configured
private MA peer with no broad household discovery. Read the exact pinned SDK
behavior rather than assuming today's mutable specification matches every field.
Inspected aiosendspin 9.1.1 source distribution (already recorded archive SHA256):
`client/client.py:SendspinClient` takes identity, pairing store, roles and player
support; `connect(url, expected_server_id=...)` supplies a public connection path;
`add_audio_chunk_listener` exposes decoded PCM, negotiated format and server
presentation timestamps. Its time mapping methods convert presentation time.
These methods avoid MA provider internals and virtual-player provisioning.
This makes a gateway-owned receiver feasible as a source-derived design. A worker
can terminate Noise/codec state locally, validate PCM format/timestamps, and feed a
campaign-specific bounded ring. Neither upstream control frames, pairing messages,
MA credentials nor client-selected identities may reach listeners. The new strict
WAV-to-PCM fixture pipeline exercises only local PCM validation/distribution, not
that handshake or time mapping.
No SDK dependency has been installed, copied, adopted or bundled. The distribution
is Apache-2.0 and its declared client dependencies include aiohttp, cpace,
cryptography, mashumaro, noiseprotocol, orjson and zeroconf; a locked transitive and
codec review is still required before adoption. The SDK's own README calls its
client a test/reference client. No compatibility claim follows from API inspection.
Infrastructure needed for a live receiver experiment: isolated non-root worker,
private writable identity/trust storage (0700/0600), operator-approved persistent
receiver identity, explicit pairing to the pinned MA server, and an operator update
to the account's nonempty player filter/target binding after verifying the new
identity. The current authorization covers only Adaptive Music DEV, so no additional
receiver identity was registered or selected. No mDNS advertisement, MA source edit,
internal virtual-player API, grouping or production configuration was used.
+127
View File
@@ -0,0 +1,127 @@
# Upstream source audit
Inspected 2026-12-03 using GitHub release metadata, shallow tagged Git checkouts and
PyPI source distribution. Full commits and selected file SHA-256 values are in
[upstream.json](upstream.json). Checkouts are ignored under .local/upstream; no
install hooks or upstream application code executed. Hashes establish reproducibility,
not signature verification or a security audit. Release selection excludes drafts
and prereleases; package version placeholders are not reliable release identifiers.
| Component | Inspected release | Role | License |
| --- | --- | --- | --- |
| Sayshal/vgmusic | release-1.4.5 | Latest stable observed; behavioral reference | MIT |
| music-assistant/server | 2.10.6 | Deployment target source | Apache-2.0 |
| music-assistant/frontend | 2.17.297 | Exact server dependency | Apache-2.0 |
| sendspin/sendspin-js | 5.0.0 | Exact pinned frontend dependency | Apache-2.0 |
| sendspin/sendspin-js | 6.1.0 | Latest stable observed; comparison only | Apache-2.0 |
| aiosendspin | 9.1.1 | Exact server Sendspin dependency; PyPI sdist | Apache-2.0 |
Latest frontend release observed was 2.17.388 at commit
e19509049634795d69abd4dec417f1281201deb8, pinning Sendspin JS 6.1.0. It was inspected
for comparison before checking out the server-pinned frontend. Latest MA stable
observed was 2.10.15. Neither is a recommendation to upgrade production.
## VGM findings
[Release source](https://github.com/Sayshal/vgmusic/tree/eba07a08c9925f31b9c8adb72faf95de11ae705c)
contains module.json declaring Foundry minimum/verified 14 and **requires 3ds-atlas**.
`package.json` has no runtime npm dependencies; development dependencies include
Rollup, Terser, ESLint/JSDoc, Prettier, Stylelint, lint-staged, copy and PostCSS
plugins. Its package-lock has 396 non-root package entries. At the initial source audit, no npm vulnerability
scan or install was run because Node/npm were absent. The later prototype uses no
third-party packages and has not installed or audited VGM development dependencies. This is an inventory, not a
finding that dependencies are safe. Manifest version/download are build placeholders
and package.json says 1.0.0; GitHub stable release tag is the version evidence.
`scripts/music-controller.mjs` uses ATLAS primary-GM arbitration/logging, resolves
scene/combat/token/actor contexts, pauses/restores track offsets via document flags,
and stops per-playlist sounds to avoid reseeding shuffle. `scripts/hooks.mjs` listens
to core combat, scene, token and actor hooks; other source includes optional
Calendaria and Minstrel interaction. These integrations are not required by this
project. Snapshot concept is useful, but no MA provider, secure gateway, campaign
isolation or demonstrated full queue restoration was found. MIT permits reuse with
the copyright and permission notice; see THIRD-PARTY-NOTICES.
## Music Assistant API findings (2.10.6 source)
All paths below are within
[the pinned server](https://github.com/music-assistant/server/tree/c24866405bd2068c25a60e1014e5ef8c3f6445bb).
- `music_assistant/controllers/webserver/controller.py`: GET `/info`, GET `/ws`,
POST `/api`, generated `/api-docs/commands.json`, schemas and OpenAPI routes.
Source identifies these routes; only `/` and `/info` were probed live: initially timed out, now both HTTP 200
with `/info` reporting 2.10.6. No authenticated API command has been sent.
- `websocket_client.py`: server info on connect, command envelopes parsed as
CommandMessage (`message_id`, `command`, `args` as used by frontend), special
`auth` command with token; authenticated event subscriptions. Not a generic
arbitrary JSON-RPC-over-WebSocket assumption. HTTP API has separate JSON-RPC handler.
- `auth.py` and `helpers/auth_middleware.py`: built-in credential and token paths,
`auth/login`, `auth/token/create`, `auth/token/revoke`, scopes, player/provider
filters and Bearer-header support. No credentials used, account created or token
minted. Effective least-privilege scopes must be checked in an authorized test.
- `player_queues/controller.py`: `all/get/items` (items default limit 500 and offset),
`play_media`, `play_index`, `seek`, `pause/resume`, `shuffle/repeat`, `transfer`.
`play_media` accepts queue_id, media, option, start_item and shuffle among others.
Seek rejects no-duration or out-of-range media. Queue read/control scopes are
declared, but do not assume all handlers enforce identical resource filters.
`_check_player_permission` permits an own-client exception and tests a *nonempty*
player filter; empty filters are not restrictive. Gateway must independently
validate all resources, methods, arguments and returned metadata.
- No public atomic full queue snapshot/restore pair found in the inspected controller.
Rebuilding requires ordered items, duplicate occurrence/index, position, mode and
state; shuffled future order and dynamic playlists remain PoC questions.
- `providers/sendspin/manifest.json`: builtin beta-stage provider;
`aiosendspin[server]==9.1.1`, `av==16.1.0`. Server pyproject requires Python >=3.14
and frontend==2.17.297; sandbox Python 3.12 cannot run this MA server version.
## Sendspin findings
[Pinned frontend](https://github.com/music-assistant/frontend/tree/e779b9d359e47cd210c2801f16a0ce6263571903)
`package.json` pins Sendspin JS **5.0.0**. `src/plugins/sendspin-connection.ts` wraps
WebSocket authentication `{type:"auth", token, client_id}` and provides alternate
remote DataChannel handling. We will not enable MA remote mode.
MA `controllers/webserver/sendspin_proxy.py` authenticates the first message then
forwards bidirectionally, optionally registering the chosen client ID with that
session. Authentication is not demonstrated campaign-level authorization. No claim
that forwarding this socket safely restricts listeners is justified.
[Sendspin JS 5.0.0 source](https://github.com/Sendspin/sendspin-js/tree/7d103075138dda5c8909045647bb42b33c2d44fc)
uses Noise transport and advertises `player@v1`, `controller@v1`, `metadata@v1` in
`src/core/protocol-handler.ts`. Codec type includes PCM, FLAC and Opus; browser code
uses AudioContext/WebCodecs and an opus-encdec fallback. Comments identify Firefox
Opus limitations; those are upstream claims, not tested here. Both inspected JS
versions depend on @noble/ciphers, @noble/curves, @noble/hashes and opus-encdec.
5.0.0 and 6.1.0 package version fields are 0.1.0 build placeholders. Both require
Node >=20.19.0. Pin release tags/commits and verify published package before adoption.
aiosendspin 9.1.1 sdist SHA-256 matches PyPI metadata. It requires Python >=3.12 and
has client/server implementations with protocol version 1, Noise, legacy transport
handling, pairing and role machinery. Runtime dependencies: aiohttp, cpace,
cryptography, mashumaro, noiseprotocol, orjson, zeroconf; optional server adds av,
numpy and pillow. Source was extracted safely and inspected, not installed or run.
It is a plausible gateway-worker candidate, not a verified compatible solution.
All transitive licenses (especially bundled codec/WASM assets), distribution NOTICE
files and vulnerability results must be reviewed before packaging dependencies.
No runtime dependency has been adopted by Adaptive Music at this milestone.
## Foundry public API evidence
Official [v14 Playlist API](https://foundryvtt.com/api/classes/foundry.documents.Playlist.html)
and [PlaylistSound API](https://foundryvtt.com/api/classes/foundry.documents.PlaylistSound.html)
were inspected. Public Playlist playback and document update APIs are the native
adapter boundary. A v14 API reference and VGM's v14 manifest do not verify behavior
on build 14.371. No Foundry binaries or proprietary source were obtained.
## Implementation follow-through — 2026-12-03
Selected pins and hashes still pass `verify_upstream.py`. The native prototype
adapts the VGM per-sound update/pausedTime pattern with its 2025 3 Death Saves MIT
notice. Core policy and local GM/settings/hooks are new code; ATLAS and optional
integrations were not copied. No upstream runtime dependency was installed.
The official v14 Playlist/PlaylistSound public API pages were rechecked; they remain
API references, not build 14.371 playback evidence. Native document tests are mocks.
MA PoC uses the source-inspected HTTP envelope (raw response, not a JSON-RPC result
wrapper). Account-role/token limitations are recorded in gateway/README.md.
+31
View File
@@ -0,0 +1,31 @@
{
"checked_at": "2026-12-03T20:37:24.512Z",
"evidence_class": "real Chromium localhost SDK PCM decoder/WebAudio/WebRTC; synthetic input; socket relay shim, not Foundry or MA",
"browser": "143.0.7499.4",
"listeners": 2,
"first_all_listeners_signal_ms": 1757,
"observation_seconds": 4.766,
"sdk_decoded_frames": 255,
"listeners_measured": [
{
"rms": 0.05391,
"peak_hz": 445.3125
},
{
"rms": 0.05396,
"peak_hz": 445.3125
}
],
"gm_rtp_bytes_sent": 25198,
"aggregate_media_kbps": 42.3,
"signaling_messages": 4,
"max_signal_bytes": 2078,
"socket_payloads_are_encrypted_control_only": true,
"turn_used": false,
"public_network_test": false,
"ma_handshake_test": false,
"ma_audio_playback": false,
"interlistener_skew_measured": false,
"autoplay_gesture": "actual page click",
"sandbox_note": "headless browser only used --no-sandbox; not a deployment setting"
}
+22
View File
@@ -0,0 +1,22 @@
{
"checked_at": "2026-12-03T20:42:10.993912+00:00",
"source": "official GitHub Git-ref API; no planned Gitea access",
"actions": [
{
"repository": "actions/checkout",
"version": "v4.2.2",
"commit": "11bd71901bbe5b1630ceea73d27597364c9af683"
},
{
"repository": "actions/upload-artifact",
"version": "v4.6.2",
"commit": "ea165f8d65b6e75b540449e92b4886f43607fa02"
},
{
"repository": "actions/upload-artifact",
"version": "v3.2.2",
"commit": "c6a366c94c3e0affe28c06c8df20a878f24da3cf"
}
],
"execution": "not run on either hosting platform; Gitea artifact protocol needs instance compatibility check"
}
+12
View File
@@ -0,0 +1,12 @@
{
"checked_at": "2026-12-03T19:56:36.693Z",
"evidence_class": "live MA reads through local companion and browser-safe client; no real Foundry browser",
"target": "verified",
"playlists": 11,
"radios": 1,
"browser_payloads_private": true,
"playback_enabled": false,
"mutations_sent": 0,
"foundry_verified": false,
"tls_verified": false
}
+16
View File
@@ -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.
+21
View File
@@ -0,0 +1,21 @@
{
"checked_at": "2026-12-03T16:17:30.410831+00:00",
"authenticated": false,
"results": [
{
"path": "/",
"status": 200,
"content_type": "text/html",
"bytes": 31252,
"elapsed_seconds": 0.0
},
{
"path": "/info",
"status": 200,
"content_type": "application/json; charset=utf-8",
"bytes": 386,
"elapsed_seconds": 0.0
}
],
"server_version": "2.10.6"
}
+86
View File
@@ -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
}
+405
View File
@@ -0,0 +1,405 @@
UTC 2026-12-03T20:59:41.184630+00:00
Evidence: offline regressions/source/package checks. Separate actual synthetic browser and live read-only MA results are in browser-audio.json and module-only-prerequisites.json. No live MA audio/Foundry/WAN verification.
$ node --version
v24.23.0
exit=0
$ npm --version
11.21.3
exit=0
$ python3 --version
Python 3.12.3
exit=0
$ npm test
> adaptive-music@0.5.0 test
> node --test tests/js/*.test.mjs
✔ catalog paginates, strips private metadata and filters unapproved mappings (38.46361ms)
✔ empty provider allowlist denies without I/O; malformed and endless pages fail (20.827361ms)
✔ target validation rejects group, changed identity and unavailable player (1.374042ms)
✔ synthetic audio isolates simultaneous campaigns and copies every frame (0.435995ms)
✔ audio denies forged origin/session/role, unknown fields and cross-campaign grants (0.222736ms)
✔ active listener revocation/expiry and slow-client overflow close handles (0.404296ms)
✔ synthetic source rejects stale sessions/generations, oversized frames; connections are bounded (0.35765ms)
✔ catalog authorization denies listener and injection before upstream (0.360554ms)
✔ scene/combat configuration preserves independent flags and stores only tagged references (1.270817ms)
✔ role loss, stale selection and arbitrary URL/ID fail before document write (0.329095ms)
✔ editor uses text for catalog labels and rechecks GM on actual save event (0.360413ms)
✔ configuration hook disposal prevents pending asynchronous render from mounting (0.195415ms)
✔ packaged browser client connects through real loopback companion/MA wire fixtures and restores combat queue (96.38079ms)
✔ companion denies listener control, wrong scope/Origin, upstream injection and unknown routes (9.391963ms)
✔ browser accepts only relative same-origin paths and never persists a connection grant (0.171381ms)
✔ companion operation replay is idempotent and same ID with changed payload is denied (12.023186ms)
✔ companion listener stream rejects controller grant and closes on live revocation and expiry (90.295314ms)
✔ catalog revocation during upstream I/O suppresses the response at the companion boundary (6.811085ms)
✔ policy precedence and explicit silence (1.288631ms)
✔ inactive, unstarted and other scene combats ignored; boss ties stable (3.916738ms)
✔ scene -> combat -> boss -> nested manual -> unwind restores offsets, duplicates and pause (1.549288ms)
✔ scene change during manual never resurrects previous scene (0.270146ms)
✔ boss removed during manual and deleted combat cannot return (0.290985ms)
✔ duplicate intent causes zero provider mutations (0.138488ms)
✔ prepare failure leaves current playback intact (0.445754ms)
✔ partial apply failure restores outgoing playback (0.220112ms)
✔ obsolete async resolve is rejected before stop/apply (0.243806ms)
✔ lease loss during stop prevents apply and stale rollback (0.231364ms)
✔ provider switch and bounded nested stack (0.299902ms)
✔ no authority retains playback without provider access (0.105036ms)
✔ queued state is captured at submission rather than read after caller mutation (0.06934ms)
✔ supersession after snapshot prevents mutations (0.16576ms)
✔ failed cross-provider apply cleans new owned audio before outgoing restoration (0.147205ms)
✔ superseded cross-provider apply is reconciled by stopping partially touched target (0.166159ms)
✔ extracted companion launches privately with fixture credentials, serves catalog diagnostics and listener PCM (193.762492ms)
✔ gateway binds target server-side and sanitizes metadata (1.054182ms)
✔ forged, wrong origin/campaign/session and unknown args deny before upstream (0.367508ms)
✔ listener cannot read queues or acquire controller lease (0.162183ms)
✔ expiry, revocation, stale fence and replay reject (0.269445ms)
✔ lease cannot be stolen and increases fence after revoke (0.138238ms)
✔ revocation during upstream I/O suppresses response (0.705801ms)
✔ MA adapter uses pinned envelope, Bearer header, fixed path, no redirects and returns no metadata (12.7784ms)
✔ MA mismatched queue, upstream failures and redirects fail with sanitized errors (1.87536ms)
✔ MA rejects URL credentials, query/fragment, paths and non-HTTP configuration (0.214121ms)
✔ MA read adapter performs real local HTTP POST against an isolated fixture (16.7976ms)
✔ signaling is confidential, per-listener authenticated, scoped and replay resistant (6.537352ms)
✔ signaling denies expired invitation, unknown/audio message types and unapproved TURN secrets (0.630831ms)
✔ GM browser policy refuses mixed content and SDK identity mismatch before any MA connection (0.568644ms)
✔ official pinned SDK decodes real binary PCM frames and discards stale generations (0.309118ms)
✔ parallel signaling replay cannot pass the asynchronous authentication check twice (1.495718ms)
✔ GM API WebSocket adapter authenticates privately, assembles partial results and refuses broad commands (14.752335ms)
✔ loopback transport denies unauthenticated, cross-campaign, controller, query and wrong-origin requests (14.358346ms)
✔ loopback streams synthetic PCM bytes and closes an active stream on revocation (41.212213ms)
✔ loopback closes idle synthetic stream when its listener capability expires (21.925676ms)
✔ MA snapshots ordered duplicate occurrences, pause and seek then reconstructs exact unshuffled order (7.914799ms)
✔ tampered, foreign/future snapshots and stale authority deny before MA mutations (1.351109ms)
✔ shuffled snapshot fails before interruption rather than promising exact restore (0.158526ms)
✔ prepared media cannot be forged and stale generations cannot issue controls (0.190847ms)
✔ every wire mutation revalidates exact identity/topology and uses fixed dedicated queue (14.987794ms)
✔ queue injection, transfer, arbitrary media URL and authority loss deny without writes (0.548456ms)
✔ catalog IDs survive independent adapter construction and differ across campaigns (2.585898ms)
✔ same-generation duplicate controls and restores issue no duplicate mutations (0.707344ms)
✔ MA provider with mock MA client composes with controller for nested contexts and rapid supersession (3.595579ms)
✔ ambiguous wire mutation failure latches closed instead of retrying or restoring blindly (0.911135ms)
✔ listener cannot obtain a playback fence guard or renew a controller lease (0.765943ms)
✔ playlist preparation expands approved ordered tracks before any playback mutation (0.954477ms)
✔ installable development entry defaults automation off and imports no gateway (7.147644ms)
✔ native captures actual offset and paused state, stops per sound, restores repeat/volume (1.230282ms)
✔ native resolves sequential playlist and touches only owned documents (0.396662ms)
✔ native rejects unsupported shuffle and empty playlist (0.118061ms)
✔ native rejects expired tracks, changed playlist membership and foreign/future snapshots before mutation (0.157575ms)
✔ native reports nonseekable restoration and clamps near-end seek (0.142567ms)
✔ scene-linked playlist conflict and lost authority fail before mutation (0.18704ms)
✔ GM election deterministic and no GM means none (4.923312ms)
✔ Foundry bootstrap registers local settings/hooks and disposes without ambient or actor access (0.768578ms)
✔ synthetic WAV termination emits fixed PCM frames through campaign listener authorization (0.871321ms)
✔ malformed, truncated and incompatible WAV formats fail closed before PCM publication (6.066001ms)
✔ credential loader rejects permissive modes, symlinks and malformed secrets (4.9003ms)
✔ private catalog identity key persists and unsafe key permissions fail (53.152506ms)
✔ scene assignments persist independently and world defaults/boss priority resolve without actor schemas (1.187302ms)
✔ native fallback is explicit, manual silence wins and legacy ambient does not resurrect after clearing (0.690973ms)
✔ unavailable saved MA selections are preserved but new forged IDs/non-native fallback and role loss deny (0.380373ms)
✔ GM setup connects catalog into independent scene editors and never persists its connection code (1.961399ms)
✔ browser PCM sink resumes from gesture, decodes stereo frames and closes its context on stream end (16.382984ms)
ℹ tests 84
ℹ suites 0
ℹ pass 84
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 1326.873707
exit=0
$ python3 -m unittest discover -s tests -v
test_companion_is_separate_complete_and_excludes_private_configuration (test_package.DevelopmentPackageTests.test_companion_is_separate_complete_and_excludes_private_configuration) ... ok
test_package_excludes_gateway_private_state_and_false_verification (test_package.DevelopmentPackageTests.test_package_excludes_gateway_private_state_and_false_verification) ... ok
test_complete_offline_bundle_is_repeatable_and_checksums_match (test_release.ReleaseTests.test_complete_offline_bundle_is_repeatable_and_checksums_match) ... ok
test_gitea_github_stable_manifest_and_immutable_download_contract (test_release.ReleaseTests.test_gitea_github_stable_manifest_and_immutable_download_contract) ... ok
test_source_archive_rebuild_does_not_need_a_git_remote_or_metadata (test_release.ReleaseTests.test_source_archive_rebuild_does_not_need_a_git_remote_or_metadata) ... ok
test_tampered_manifest_or_missing_asset_is_rejected (test_release.ReleaseTests.test_tampered_manifest_or_missing_asset_is_rejected) ... ok
test_documentation_versions_are_not_private_addresses (test_repository.RepositorySafetyTests.test_documentation_versions_are_not_private_addresses) ... ok
test_embedded_url_credentials_rejected (test_repository.RepositorySafetyTests.test_embedded_url_credentials_rejected) ... ok
test_key_material_rejected (test_repository.RepositorySafetyTests.test_key_material_rejected) ... ok
test_network_evidence_is_unauthenticated (test_repository.RepositorySafetyTests.test_network_evidence_is_unauthenticated) ... ok
test_private_addresses_rejected (test_repository.RepositorySafetyTests.test_private_addresses_rejected) ... ok
test_private_config_rejected_even_when_forced_into_git (test_repository.RepositorySafetyTests.test_private_config_rejected_even_when_forced_into_git) ... ok
test_private_paths_are_ignored (test_repository.RepositorySafetyTests.test_private_paths_are_ignored) ... ok
test_provenance_pins_have_hashes (test_repository.RepositorySafetyTests.test_provenance_pins_have_hashes) ... ok
test_repository_guardrails (test_repository.RepositorySafetyTests.test_repository_guardrails) ... ok
----------------------------------------------------------------------
Ran 15 tests in 0.209s
OK
exit=0
$ python3 scripts/audit_repository.py
PASS: repository privacy/attribution guardrails
exit=0
$ python3 scripts/verify_upstream.py
PASS: all recorded Git heads, source and distribution file hashes
exit=0
$ git diff --check
exit=0
Final after peer signaling bound/tests:
$ npm test
> adaptive-music@0.5.0 test
> node --test tests/js/*.test.mjs
✔ catalog paginates, strips private metadata and filters unapproved mappings (34.489068ms)
✔ empty provider allowlist denies without I/O; malformed and endless pages fail (19.785397ms)
✔ target validation rejects group, changed identity and unavailable player (0.905344ms)
✔ synthetic audio isolates simultaneous campaigns and copies every frame (0.447057ms)
✔ audio denies forged origin/session/role, unknown fields and cross-campaign grants (0.209794ms)
✔ active listener revocation/expiry and slow-client overflow close handles (0.258885ms)
✔ synthetic source rejects stale sessions/generations, oversized frames; connections are bounded (0.312956ms)
✔ catalog authorization denies listener and injection before upstream (0.324718ms)
✔ scene/combat configuration preserves independent flags and stores only tagged references (1.271449ms)
✔ role loss, stale selection and arbitrary URL/ID fail before document write (0.321131ms)
✔ editor uses text for catalog labels and rechecks GM on actual save event (0.353852ms)
✔ configuration hook disposal prevents pending asynchronous render from mounting (0.188401ms)
✔ packaged browser client connects through real loopback companion/MA wire fixtures and restores combat queue (96.734315ms)
✔ companion denies listener control, wrong scope/Origin, upstream injection and unknown routes (8.058096ms)
✔ browser accepts only relative same-origin paths and never persists a connection grant (0.173145ms)
✔ companion operation replay is idempotent and same ID with changed payload is denied (11.338403ms)
✔ companion listener stream rejects controller grant and closes on live revocation and expiry (91.136521ms)
✔ catalog revocation during upstream I/O suppresses the response at the companion boundary (7.375589ms)
✔ policy precedence and explicit silence (1.319699ms)
✔ inactive, unstarted and other scene combats ignored; boss ties stable (4.027014ms)
✔ scene -> combat -> boss -> nested manual -> unwind restores offsets, duplicates and pause (1.273683ms)
✔ scene change during manual never resurrects previous scene (0.207358ms)
✔ boss removed during manual and deleted combat cannot return (0.249657ms)
✔ duplicate intent causes zero provider mutations (0.114244ms)
✔ prepare failure leaves current playback intact (0.378869ms)
✔ partial apply failure restores outgoing playback (0.232705ms)
✔ obsolete async resolve is rejected before stop/apply (0.222235ms)
✔ lease loss during stop prevents apply and stale rollback (4.212221ms)
✔ provider switch and bounded nested stack (0.292198ms)
✔ no authority retains playback without provider access (0.105488ms)
✔ queued state is captured at submission rather than read after caller mutation (0.09027ms)
✔ supersession after snapshot prevents mutations (0.166812ms)
✔ failed cross-provider apply cleans new owned audio before outgoing restoration (0.16018ms)
✔ superseded cross-provider apply is reconciled by stopping partially touched target (0.177582ms)
✔ extracted companion launches privately with fixture credentials, serves catalog diagnostics and listener PCM (201.412951ms)
✔ gateway binds target server-side and sanitizes metadata (1.013095ms)
✔ forged, wrong origin/campaign/session and unknown args deny before upstream (0.391262ms)
✔ listener cannot read queues or acquire controller lease (0.179616ms)
✔ expiry, revocation, stale fence and replay reject (0.201757ms)
✔ lease cannot be stolen and increases fence after revoke (0.129522ms)
✔ revocation during upstream I/O suppresses response (0.134181ms)
✔ MA adapter uses pinned envelope, Bearer header, fixed path, no redirects and returns no metadata (16.0455ms)
✔ MA mismatched queue, upstream failures and redirects fail with sanitized errors (1.798383ms)
✔ MA rejects URL credentials, query/fragment, paths and non-HTTP configuration (0.211004ms)
✔ MA read adapter performs real local HTTP POST against an isolated fixture (16.105082ms)
✔ signaling is confidential, per-listener authenticated, scoped and replay resistant (6.635415ms)
✔ signaling denies expired invitation, unknown/audio message types and unapproved TURN secrets (0.54029ms)
✔ GM browser policy refuses mixed content and SDK identity mismatch before any MA connection (0.715168ms)
✔ official pinned SDK decodes real binary PCM frames and discards stale generations (0.248766ms)
✔ parallel signaling replay cannot pass the asynchronous authentication check twice (1.826007ms)
✔ GM API WebSocket adapter authenticates privately, assembles partial results and refuses broad commands (12.583653ms)
✔ peer signaling bounds queued work and rejects expired invites before allocating a connection (25.202933ms)
✔ loopback transport denies unauthenticated, cross-campaign, controller, query and wrong-origin requests (12.953336ms)
✔ loopback streams synthetic PCM bytes and closes an active stream on revocation (43.258833ms)
✔ loopback closes idle synthetic stream when its listener capability expires (22.15983ms)
✔ MA snapshots ordered duplicate occurrences, pause and seek then reconstructs exact unshuffled order (7.12461ms)
✔ tampered, foreign/future snapshots and stale authority deny before MA mutations (0.866281ms)
✔ shuffled snapshot fails before interruption rather than promising exact restore (0.122439ms)
✔ prepared media cannot be forged and stale generations cannot issue controls (0.207959ms)
✔ every wire mutation revalidates exact identity/topology and uses fixed dedicated queue (15.898154ms)
✔ queue injection, transfer, arbitrary media URL and authority loss deny without writes (0.583201ms)
✔ catalog IDs survive independent adapter construction and differ across campaigns (1.436568ms)
✔ same-generation duplicate controls and restores issue no duplicate mutations (0.550701ms)
✔ MA provider with mock MA client composes with controller for nested contexts and rapid supersession (3.584397ms)
✔ ambiguous wire mutation failure latches closed instead of retrying or restoring blindly (0.947353ms)
✔ listener cannot obtain a playback fence guard or renew a controller lease (0.867032ms)
✔ playlist preparation expands approved ordered tracks before any playback mutation (1.429755ms)
✔ installable development entry defaults automation off and imports no gateway (7.558522ms)
✔ native captures actual offset and paused state, stops per sound, restores repeat/volume (1.465481ms)
✔ native resolves sequential playlist and touches only owned documents (0.502239ms)
✔ native rejects unsupported shuffle and empty playlist (0.147065ms)
✔ native rejects expired tracks, changed playlist membership and foreign/future snapshots before mutation (0.194464ms)
✔ native reports nonseekable restoration and clamps near-end seek (0.177542ms)
✔ scene-linked playlist conflict and lost authority fail before mutation (0.220453ms)
✔ GM election deterministic and no GM means none (4.613983ms)
✔ Foundry bootstrap registers local settings/hooks and disposes without ambient or actor access (0.664022ms)
✔ synthetic WAV termination emits fixed PCM frames through campaign listener authorization (0.875678ms)
✔ malformed, truncated and incompatible WAV formats fail closed before PCM publication (5.881385ms)
✔ credential loader rejects permissive modes, symlinks and malformed secrets (5.428296ms)
✔ private catalog identity key persists and unsafe key permissions fail (41.697223ms)
✔ scene assignments persist independently and world defaults/boss priority resolve without actor schemas (1.144961ms)
✔ native fallback is explicit, manual silence wins and legacy ambient does not resurrect after clearing (1.34135ms)
✔ unavailable saved MA selections are preserved but new forged IDs/non-native fallback and role loss deny (0.431697ms)
✔ GM setup connects catalog into independent scene editors and never persists its connection code (2.344586ms)
✔ browser PCM sink resumes from gesture, decodes stereo frames and closes its context on stream end (17.582896ms)
ℹ tests 85
ℹ suites 0
ℹ pass 85
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 1347.229561
$ python3 -m unittest discover -s tests -v
test_companion_is_separate_complete_and_excludes_private_configuration (test_package.DevelopmentPackageTests.test_companion_is_separate_complete_and_excludes_private_configuration) ... ok
test_package_excludes_gateway_private_state_and_false_verification (test_package.DevelopmentPackageTests.test_package_excludes_gateway_private_state_and_false_verification) ... ok
test_complete_offline_bundle_is_repeatable_and_checksums_match (test_release.ReleaseTests.test_complete_offline_bundle_is_repeatable_and_checksums_match) ... ok
test_gitea_github_stable_manifest_and_immutable_download_contract (test_release.ReleaseTests.test_gitea_github_stable_manifest_and_immutable_download_contract) ... ok
test_source_archive_rebuild_does_not_need_a_git_remote_or_metadata (test_release.ReleaseTests.test_source_archive_rebuild_does_not_need_a_git_remote_or_metadata) ... ok
test_tampered_manifest_or_missing_asset_is_rejected (test_release.ReleaseTests.test_tampered_manifest_or_missing_asset_is_rejected) ... ok
test_documentation_versions_are_not_private_addresses (test_repository.RepositorySafetyTests.test_documentation_versions_are_not_private_addresses) ... ok
test_embedded_url_credentials_rejected (test_repository.RepositorySafetyTests.test_embedded_url_credentials_rejected) ... ok
test_key_material_rejected (test_repository.RepositorySafetyTests.test_key_material_rejected) ... ok
test_network_evidence_is_unauthenticated (test_repository.RepositorySafetyTests.test_network_evidence_is_unauthenticated) ... ok
test_private_addresses_rejected (test_repository.RepositorySafetyTests.test_private_addresses_rejected) ... ok
test_private_config_rejected_even_when_forced_into_git (test_repository.RepositorySafetyTests.test_private_config_rejected_even_when_forced_into_git) ... ok
test_private_paths_are_ignored (test_repository.RepositorySafetyTests.test_private_paths_are_ignored) ... ok
test_provenance_pins_have_hashes (test_repository.RepositorySafetyTests.test_provenance_pins_have_hashes) ... ok
test_repository_guardrails (test_repository.RepositorySafetyTests.test_repository_guardrails) ... ok
----------------------------------------------------------------------
Ran 15 tests in 0.193s
OK
Final backend mutual-exclusion check:
$ npm test
> adaptive-music@0.5.0 test
> node --test tests/js/*.test.mjs
✔ catalog paginates, strips private metadata and filters unapproved mappings (34.696629ms)
✔ empty provider allowlist denies without I/O; malformed and endless pages fail (20.325816ms)
✔ target validation rejects group, changed identity and unavailable player (1.810717ms)
✔ synthetic audio isolates simultaneous campaigns and copies every frame (0.554908ms)
✔ audio denies forged origin/session/role, unknown fields and cross-campaign grants (0.381735ms)
✔ active listener revocation/expiry and slow-client overflow close handles (0.470911ms)
✔ synthetic source rejects stale sessions/generations, oversized frames; connections are bounded (0.358902ms)
✔ catalog authorization denies listener and injection before upstream (0.314629ms)
✔ scene/combat configuration preserves independent flags and stores only tagged references (1.750965ms)
✔ role loss, stale selection and arbitrary URL/ID fail before document write (0.331429ms)
✔ editor uses text for catalog labels and rechecks GM on actual save event (0.414065ms)
✔ configuration hook disposal prevents pending asynchronous render from mounting (0.190486ms)
✔ packaged browser client connects through real loopback companion/MA wire fixtures and restores combat queue (100.68071ms)
✔ companion denies listener control, wrong scope/Origin, upstream injection and unknown routes (8.076499ms)
✔ browser accepts only relative same-origin paths and never persists a connection grant (0.16008ms)
✔ companion operation replay is idempotent and same ID with changed payload is denied (11.60538ms)
✔ companion listener stream rejects controller grant and closes on live revocation and expiry (90.26337ms)
✔ catalog revocation during upstream I/O suppresses the response at the companion boundary (6.482046ms)
✔ policy precedence and explicit silence (1.518581ms)
✔ inactive, unstarted and other scene combats ignored; boss ties stable (4.045799ms)
✔ scene -> combat -> boss -> nested manual -> unwind restores offsets, duplicates and pause (1.253274ms)
✔ scene change during manual never resurrects previous scene (0.222587ms)
✔ boss removed during manual and deleted combat cannot return (0.291025ms)
✔ duplicate intent causes zero provider mutations (0.125034ms)
✔ prepare failure leaves current playback intact (0.343953ms)
✔ partial apply failure restores outgoing playback (0.183673ms)
✔ obsolete async resolve is rejected before stop/apply (0.309378ms)
✔ lease loss during stop prevents apply and stale rollback (0.230632ms)
✔ provider switch and bounded nested stack (1.168335ms)
✔ no authority retains playback without provider access (0.107982ms)
✔ queued state is captured at submission rather than read after caller mutation (0.068407ms)
✔ supersession after snapshot prevents mutations (0.16593ms)
✔ failed cross-provider apply cleans new owned audio before outgoing restoration (0.168415ms)
✔ superseded cross-provider apply is reconciled by stopping partially touched target (0.173114ms)
✔ extracted companion launches privately with fixture credentials, serves catalog diagnostics and listener PCM (196.285252ms)
✔ gateway binds target server-side and sanitizes metadata (0.985664ms)
✔ forged, wrong origin/campaign/session and unknown args deny before upstream (0.376113ms)
✔ listener cannot read queues or acquire controller lease (0.188895ms)
✔ expiry, revocation, stale fence and replay reject (0.190857ms)
✔ lease cannot be stolen and increases fence after revoke (0.121416ms)
✔ revocation during upstream I/O suppresses response (0.738723ms)
✔ MA adapter uses pinned envelope, Bearer header, fixed path, no redirects and returns no metadata (13.573212ms)
✔ MA mismatched queue, upstream failures and redirects fail with sanitized errors (1.742879ms)
✔ MA rejects URL credentials, query/fragment, paths and non-HTTP configuration (0.191988ms)
✔ MA read adapter performs real local HTTP POST against an isolated fixture (15.582672ms)
✔ signaling is confidential, per-listener authenticated, scoped and replay resistant (6.879711ms)
✔ signaling denies expired invitation, unknown/audio message types and unapproved TURN secrets (0.633104ms)
✔ GM browser policy refuses mixed content and SDK identity mismatch before any MA connection (0.540021ms)
✔ official pinned SDK decodes real binary PCM frames and discards stale generations (0.258925ms)
✔ parallel signaling replay cannot pass the asynchronous authentication check twice (1.449151ms)
✔ GM API WebSocket adapter authenticates privately, assembles partial results and refuses broad commands (12.419294ms)
✔ peer signaling bounds queued work and rejects expired invites before allocating a connection (24.838497ms)
✔ loopback transport denies unauthenticated, cross-campaign, controller, query and wrong-origin requests (13.373719ms)
✔ loopback streams synthetic PCM bytes and closes an active stream on revocation (42.631304ms)
✔ loopback closes idle synthetic stream when its listener capability expires (21.663446ms)
✔ MA snapshots ordered duplicate occurrences, pause and seek then reconstructs exact unshuffled order (8.238082ms)
✔ tampered, foreign/future snapshots and stale authority deny before MA mutations (1.022132ms)
✔ shuffled snapshot fails before interruption rather than promising exact restore (0.140523ms)
✔ prepared media cannot be forged and stale generations cannot issue controls (0.198481ms)
✔ every wire mutation revalidates exact identity/topology and uses fixed dedicated queue (15.718245ms)
✔ queue injection, transfer, arbitrary media URL and authority loss deny without writes (0.588681ms)
✔ catalog IDs survive independent adapter construction and differ across campaigns (2.752148ms)
✔ same-generation duplicate controls and restores issue no duplicate mutations (0.661507ms)
✔ MA provider with mock MA client composes with controller for nested contexts and rapid supersession (3.769762ms)
✔ ambiguous wire mutation failure latches closed instead of retrying or restoring blindly (0.612365ms)
✔ listener cannot obtain a playback fence guard or renew a controller lease (0.730557ms)
✔ playlist preparation expands approved ordered tracks before any playback mutation (2.677008ms)
✔ installable development entry defaults automation off and imports no gateway (9.722018ms)
✔ native captures actual offset and paused state, stops per sound, restores repeat/volume (4.196049ms)
✔ native resolves sequential playlist and touches only owned documents (0.489666ms)
✔ native rejects unsupported shuffle and empty playlist (0.149099ms)
✔ native rejects expired tracks, changed playlist membership and foreign/future snapshots before mutation (0.263082ms)
✔ native reports nonseekable restoration and clamps near-end seek (0.168274ms)
✔ scene-linked playlist conflict and lost authority fail before mutation (0.185315ms)
✔ GM election deterministic and no GM means none (3.762779ms)
✔ Foundry bootstrap registers local settings/hooks and disposes without ambient or actor access (0.648934ms)
✔ synthetic WAV termination emits fixed PCM frames through campaign listener authorization (0.819092ms)
✔ malformed, truncated and incompatible WAV formats fail closed before PCM publication (6.152892ms)
✔ credential loader rejects permissive modes, symlinks and malformed secrets (6.562927ms)
✔ private catalog identity key persists and unsafe key permissions fail (34.527232ms)
✔ scene assignments persist independently and world defaults/boss priority resolve without actor schemas (1.210996ms)
✔ native fallback is explicit, manual silence wins and legacy ambient does not resurrect after clearing (0.620279ms)
✔ unavailable saved MA selections are preserved but new forged IDs/non-native fallback and role loss deny (0.43879ms)
✔ GM setup connects catalog into independent scene editors and never persists its connection code (1.952823ms)
✔ browser PCM sink resumes from gesture, decodes stereo frames and closes its context on stream end (14.895866ms)
ℹ tests 85
ℹ suites 0
ℹ pass 85
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 1347.263856
$ python3 -m unittest discover -s tests -v
test_companion_is_separate_complete_and_excludes_private_configuration (test_package.DevelopmentPackageTests.test_companion_is_separate_complete_and_excludes_private_configuration) ... ok
test_package_excludes_gateway_private_state_and_false_verification (test_package.DevelopmentPackageTests.test_package_excludes_gateway_private_state_and_false_verification) ... ok
test_complete_offline_bundle_is_repeatable_and_checksums_match (test_release.ReleaseTests.test_complete_offline_bundle_is_repeatable_and_checksums_match) ... ok
test_gitea_github_stable_manifest_and_immutable_download_contract (test_release.ReleaseTests.test_gitea_github_stable_manifest_and_immutable_download_contract) ... ok
test_source_archive_rebuild_does_not_need_a_git_remote_or_metadata (test_release.ReleaseTests.test_source_archive_rebuild_does_not_need_a_git_remote_or_metadata) ... ok
test_tampered_manifest_or_missing_asset_is_rejected (test_release.ReleaseTests.test_tampered_manifest_or_missing_asset_is_rejected) ... ok
test_documentation_versions_are_not_private_addresses (test_repository.RepositorySafetyTests.test_documentation_versions_are_not_private_addresses) ... ok
test_embedded_url_credentials_rejected (test_repository.RepositorySafetyTests.test_embedded_url_credentials_rejected) ... ok
test_key_material_rejected (test_repository.RepositorySafetyTests.test_key_material_rejected) ... ok
test_network_evidence_is_unauthenticated (test_repository.RepositorySafetyTests.test_network_evidence_is_unauthenticated) ... ok
test_private_addresses_rejected (test_repository.RepositorySafetyTests.test_private_addresses_rejected) ... ok
test_private_config_rejected_even_when_forced_into_git (test_repository.RepositorySafetyTests.test_private_config_rejected_even_when_forced_into_git) ... ok
test_private_paths_are_ignored (test_repository.RepositorySafetyTests.test_private_paths_are_ignored) ... ok
test_provenance_pins_have_hashes (test_repository.RepositorySafetyTests.test_provenance_pins_have_hashes) ... ok
test_repository_guardrails (test_repository.RepositorySafetyTests.test_repository_guardrails) ... ok
----------------------------------------------------------------------
Ran 15 tests in 0.184s
OK
$ python3 scripts/audit_repository.py
PASS: repository privacy/attribution guardrails
$ python3 scripts/verify_upstream.py
PASS: all recorded Git heads, source and distribution file hashes
+24
View File
@@ -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
}
+12
View File
@@ -0,0 +1,12 @@
{
"checked_at": "2026-12-03T17:24:19.084Z",
"target": {
"dedicated": true,
"available": true,
"standalone": true
},
"playlists": 11,
"radios": 1,
"sanitized": true,
"independent_adapter_ids_match": true
}
+12
View File
@@ -0,0 +1,12 @@
{
"evidence_class": "live dedicated MA control tests; no content playback",
"runs": [
{"checked_at":"2026-12-03T17:16:04.878Z","successful_mutations":9,"original_state":"empty idle queue","restored":true},
{"checked_at":"2026-12-03T17:24:18.937Z","successful_mutations":0,"result":"session mismatch denied before mutations; harness corrected"},
{"checked_at":"2026-12-03T17:24:30.986Z","successful_mutations":9,"original_state":"empty idle queue","restored":true}
],
"total_successful_mutations":18,
"content_playback_mutations":0,
"synthetic_ingestion": "five-second metadata request failed; longer diagnostic returned HTTP 400; no queue mutation",
"limitations": "No pause/resume/seek with content, ordered nonempty restore, live combat/boss/manual or actual MA playlist playback verified"
}
+50
View File
@@ -0,0 +1,50 @@
{
"checked_at": "2026-12-03T17:24:30.986Z",
"evidence_class": "live dedicated MA",
"mutations": 9,
"checks": [
{
"action": "shuffle",
"value": true,
"result": "pass",
"scope": "idle queue controls"
},
{
"action": "shuffle",
"value": false,
"result": "pass",
"scope": "idle queue controls"
},
{
"action": "repeat",
"value": "one",
"result": "pass",
"scope": "idle queue controls"
},
{
"action": "repeat",
"value": "all",
"result": "pass",
"scope": "idle queue controls"
},
{
"action": "repeat",
"value": "off",
"result": "pass",
"scope": "idle queue controls"
},
{
"action": "stop",
"value": null,
"result": "pass",
"scope": "idle queue controls"
}
],
"restored": true,
"isolation_verified": true,
"original": {
"state": "idle",
"items": 0,
"position": 0
}
}
+40
View File
@@ -0,0 +1,40 @@
{
"checked_at": "2026-12-03T16:58:07.948228+00:00",
"credential": {
"directory_mode": "0700",
"token_mode": "0600",
"git_ignored": true,
"token_absent_reachable_history": true,
"token_absent_tracked_files": true
},
"authentication": true,
"role": "user",
"player_filter_count": 1,
"provider_filter_count": 7,
"dedicated_name_matches": true,
"player_available": true,
"sendspin_provider": true,
"standalone_topology": true,
"queue_id_matches_player": true,
"queue_active": true,
"synthetic_target_denial_status": 403,
"synthetic_provider_denial_status": 403,
"role_scopes": [
"config.core.read",
"config.players.read",
"config.providers.read",
"library.read",
"library.write",
"players.control",
"players.read",
"providers.read",
"queues.control",
"queues.read",
"system.read",
"users.invite"
],
"playlists_count": 11,
"playlists_approved_mappings": true,
"radios_count": 1,
"radios_approved_mappings": true
}
+16
View File
@@ -0,0 +1,16 @@
test_documentation_versions_are_not_private_addresses (test_repository.RepositorySafetyTests.test_documentation_versions_are_not_private_addresses) ... ok
test_embedded_url_credentials_rejected (test_repository.RepositorySafetyTests.test_embedded_url_credentials_rejected) ... ok
test_key_material_rejected (test_repository.RepositorySafetyTests.test_key_material_rejected) ... ok
test_network_evidence_is_unauthenticated (test_repository.RepositorySafetyTests.test_network_evidence_is_unauthenticated) ... ok
test_private_addresses_rejected (test_repository.RepositorySafetyTests.test_private_addresses_rejected) ... ok
test_private_config_rejected_even_when_forced_into_git (test_repository.RepositorySafetyTests.test_private_config_rejected_even_when_forced_into_git) ... ok
test_private_paths_are_ignored (test_repository.RepositorySafetyTests.test_private_paths_are_ignored) ... ok
test_provenance_pins_have_hashes (test_repository.RepositorySafetyTests.test_provenance_pins_have_hashes) ... ok
test_repository_guardrails (test_repository.RepositorySafetyTests.test_repository_guardrails) ... ok
----------------------------------------------------------------------
Ran 9 tests in 0.010s
OK
PASS: repository privacy/attribution guardrails
PASS: all recorded Git heads and source file hashes
+17
View File
@@ -0,0 +1,17 @@
{
"checked_at": "2026-12-03T20:42:10.945Z",
"evidence_class": "live MA target/queue reads plus browser-policy/source checks; no live browser-to-MA connection",
"target_verified": true,
"queue_state": "idle",
"queue_items": 0,
"target_identity_format_compatible": true,
"configured_ma_scheme": "http:",
"https_foundry_origin_policy": "mixed-content",
"gm_identity_profile_present": false,
"sendspin_connections": 0,
"identities_created": 0,
"mutations_sent": 0,
"actual_ma_audio": "blocked pending existing DEV private identity, secure private browser access and approved synthetic ingestion",
"websocket_auth_log_safety": "not verified live; source logs raw inbound auth at VERBOSE, explicit operator review required",
"live_websocket_auth_attempts": 0
}
+44
View File
@@ -0,0 +1,44 @@
{
"checked_at": "2026-12-03T21:01:48.898612+00:00",
"version": "0.5.0",
"artifacts": [
{
"artifact": "dist/adaptive-music-dev.zip",
"sha256": "ec45c0a3e4f8eae2593c7ae9cf1bdc3d724b5c6e6e9afd199ff6a506db71163f",
"bytes": 115735,
"files": 36
},
{
"artifact": "dist/releases/v0.5.0/adaptive-music.zip",
"sha256": "a9f904cb9e0844fe9b6a5c3a19f24358dfa6a0c4ca995aea9b1a3f81b301d584",
"bytes": 115735,
"files": 36
}
],
"foundry_live_verified": false,
"browser_zip_has_server_code": false,
"automation_default": false,
"history": [
{
"checked_at": "2026-12-03T20:07:10.575810+00:00",
"version": "0.4.0-dev",
"artifacts": [
{
"artifact": "dist/adaptive-music-dev.zip",
"sha256": "28637fd0a4b9754d591893a8224d059fc71a9371f6a978bfb5b935088e0956c2",
"bytes": 27681,
"files": 17
},
{
"artifact": "dist/adaptive-music-companion-dev.zip",
"sha256": "05427fc4998d8bef6d3d5ccb61d68931cd98fae2e28f6b777b9468d993c5558e",
"bytes": 33191,
"files": 19
}
],
"foundry_live_verified": false,
"browser_zip_has_server_code": false,
"automation_default": false
}
]
}
+53
View File
@@ -0,0 +1,53 @@
{
"checked_at": "2026-12-03T19:50:32.141285+00:00",
"audited_version": "0.3.0-dev",
"sha256": "2e0d5370a64e854b4bbdbea12d6969e6467b3eef9f5846361886d45058d3e801",
"files": [
"adaptive-music/module.json",
"adaptive-music/LICENSE",
"adaptive-music/THIRD-PARTY-NOTICES",
"adaptive-music/README.md",
"adaptive-music/src/core/controller.mjs",
"adaptive-music/src/foundry/configuration.mjs",
"adaptive-music/src/foundry/module.mjs",
"adaptive-music/src/foundry/runtime.mjs",
"adaptive-music/src/providers/native/provider.mjs",
"adaptive-music/licenses/Apache-2.0.txt",
"adaptive-music/licenses/VGM-MIT.txt"
],
"findings": {
"ma_connection_setup": false,
"browser_gateway_client": false,
"ma_catalog_in_configuration": false,
"separate_scene_ambient_combat": false,
"sendspin_browser_playback": false,
"crossfade": false
},
"assessment": "Native-only development package; server-side components were not connected to its browser entrypoint.",
"rebuilt_assessment": {
"version": "0.4.0-dev",
"ma_connection_setup": "operator capability + private same-origin companion route",
"browser_gateway_client": true,
"ma_catalog_in_configuration": true,
"separate_scene_ambient_combat": true,
"world_defaults_boss_native_fallback": true,
"synthetic_pcm_browser_sink": true,
"sendspin_browser_playback": false,
"crossfade": false,
"foundry_live_verified": false,
"artifacts": [
{
"artifact": "dist/adaptive-music-dev.zip",
"sha256": "28637fd0a4b9754d591893a8224d059fc71a9371f6a978bfb5b935088e0956c2",
"bytes": 27681,
"files": 17
},
{
"artifact": "dist/adaptive-music-companion-dev.zip",
"sha256": "05427fc4998d8bef6d3d5ccb61d68931cd98fae2e28f6b777b9468d993c5558e",
"bytes": 33191,
"files": 19
}
]
}
}
+12
View File
@@ -0,0 +1,12 @@
{
"checked_at": "2026-12-03T20:59:20.741930+00:00",
"local_directory_mode": "0700",
"token_file_mode": "0600",
"token_ignored": true,
"local_files_tracked": false,
"git_history_blob_count": 136,
"credential_in_git_history": false,
"generated_module_and_source_private_value_scan": "pass",
"gitea_contacted": false,
"limitations": "exact credential and configured private endpoint/target scan supplements repository heuristics; not a comprehensive secret detector"
}
+259
View File
@@ -0,0 +1,259 @@
{
"version": "0.7.0",
"publicationReady": false,
"completedCoreRunPassed": true,
"macPrivateRouteVerified": false,
"foundryLoggedInWorldVerified": true,
"actualMAAuthentication": true,
"actualMACatalogPlaylists": 11,
"actualMADedicatedProvisioning": true,
"actualMAAudioAndTwoListeners": true,
"actualAmbientCombatRestore": true,
"actualNativePause": false,
"logicalPauseEmulation": true,
"browserAudioHardwareAudibilityVerified": false,
"crossfade": false,
"coreSuccessEvidence": "evidence/v0.7.0-live-chromium.json",
"browserAuthentication": {
"at": "2026-12-04T03:13:45.898Z",
"scope": "actual origins, read-only API authentication; Ubuntu browsers, not Mac",
"browsers": [
{
"browser": "firefox",
"version": "159.0",
"origin": "foundry",
"maRoute": "normal resolver",
"httpStatus": 200,
"csp": null,
"result": {
"stage": "authenticated",
"providerCount": 7,
"commandError": null,
"metaCSP": [],
"blocked": [],
"secureContext": true
}
},
{
"browser": "firefox",
"version": "159.0",
"origin": "ma",
"maRoute": "normal resolver",
"httpStatus": 200,
"csp": null,
"result": {
"stage": "authenticated",
"providerCount": 7,
"commandError": null,
"metaCSP": [],
"blocked": [],
"secureContext": true
}
},
{
"browser": "chromium",
"version": "159.0.8154.6",
"origin": "foundry",
"maRoute": "normal resolver",
"httpStatus": 200,
"csp": null,
"result": {
"stage": "authenticated",
"providerCount": 7,
"commandError": null,
"metaCSP": [],
"blocked": [],
"secureContext": true
}
},
{
"browser": "chromium",
"version": "159.0.8154.6",
"origin": "ma",
"maRoute": "normal resolver",
"httpStatus": 200,
"csp": null,
"result": {
"stage": "authenticated",
"providerCount": 7,
"commandError": null,
"metaCSP": [],
"blocked": [],
"secureContext": true
}
}
]
},
"networkBoundary": {
"sandboxNormalDNS": "public addresses",
"operatorMacMAResolution": "private proxy mapping",
"temporaryAccessRequestPrepared": true,
"initialUbuntuPrivateProxyTCP443": "timeout before TLS",
"followUpUbuntuPrivateProxyTCP443": "verified TLS and installed Foundry browser through operator-scoped firewall access",
"infrastructureChangedByTestAgent": false
},
"remaining": [
"original Mac connection and AM-005 reproduction if the symptom persists",
"WAN/30-minute behavior and hardware audibility"
],
"credentialUseAuthorized": true,
"dedicatedReceiverMutationsPerformed": true,
"latestCatalogReplayPassed": true,
"freshProvisioningObserved": {
"browser": "Firefox 144.0.2",
"at": "2026-12-04T03:10:40.566Z",
"path": "module creates a fresh identity; no manual protocol pre-provisioning",
"pairing": true,
"audioTwoListeners": true,
"ambientOrderAndOffsetRestored": true,
"finalQueueRestored": true,
"source": "observed live driver output; private driver reports were subsequently superseded by current-browser reruns"
},
"productionDependencyAudit": {
"info": 0,
"low": 0,
"moderate": 0,
"high": 0,
"critical": 0,
"total": 0
},
"history": [
{
"version": "0.7.0",
"scope": "Local acceptance package with isolated browser checks, deployed Foundry ApplicationV2 rendering and dedicated MA receiver tests",
"publicationReady": false,
"foundryInstalledWorldVerified": true,
"originalMacConnectionVerified": false,
"deployedOriginAuthentication": "Ubuntu Chromium and Firefox",
"maReceiver": {
"chromiumPlaybackPassed": true,
"firefoxFreshProvisioningPassed": true,
"firefoxPlaybackPassed": true,
"priorFirefoxPlaybackError": "MA MediaNotFoundError on the first ambient play_media command"
},
"evidence": [
"evidence/v0.7.0-live.json",
"evidence/v0.7.0-live-follow-up.json",
"evidence/foundry-application-v070.json",
"evidence/v0.7.0-checks.txt",
"evidence/v0.7.0-foundry-private.json"
],
"regression": {
"javascript": 101,
"python": 15
},
"giteaContacted": false,
"productionInfrastructureChanged": false,
"remainingAcceptance": [
"Mac private MA route",
"listener renewal, actual player devices and WAN route"
],
"history": [
{
"version": "0.6.0",
"scope": "offline regressions, actual Chromium DOM fixture, pinned-source and package checks; no v0.6.0 live Foundry/MA verification",
"connection_configuration": "three-step GM wizard; memory-only endpoint/token/identity; imported existing dedicated receiver only",
"catalog_and_assignments": "connected catalog playlists, explicit playback opt-in and persistent scene ambient/combat/boss/native fallback and world defaults",
"audio": "existing official Sendspin GM host integrated; automatic individually encrypted WebRTC listener invitations; browser activation when required",
"bootstrap": "ephemeral ECDH P-256 keys bound to permission-controlled Foundry User documents; AES-GCM encrypted capabilities; live server permissions remain an acceptance gate",
"companion": "hidden by default; client-scoped advanced development setting; no mandatory service",
"https_wss": "trusted private MA origin with /ws and /sendspin WSS required from HTTPS Foundry; no mixed-content or certificate bypass; deployment untouched",
"distribution": "one installable module ZIP plus complete offline manual publication bundle, sources, docs, licenses and checksums",
"regression": {
"javascript": 91,
"python": 15,
"passed": true
},
"browser_ui": {
"browser": "Chromium 143.0.7499.4",
"passed": true,
"scope": "fake Foundry documents and fake connection; no MA or actual Foundry",
"pageErrors": []
},
"user_report": {
"version": "0.5.0",
"giteaPublished": true,
"manifestInstalled": true,
"foundry": "14.371",
"system": "D&D 5e 6.1.2",
"activated": true,
"configurationAndListenerWindowsRender": true,
"source": "user report; not independently accessed"
},
"ma_mutations_this_revision": 0,
"credential_use_this_revision": false,
"gitea_contacted": false,
"production_changes": false,
"v060_live_audio_verified": false,
"remaining_acceptance": [
"real Foundry v14.371 ApplicationV2 and User permissions",
"trusted private MA HTTPS/WSS",
"matching dedicated Sendspin identity/pairing backup",
"authentication logging review",
"authorized audible catalog playback and nonempty restore",
"autoplay/renewal/reconnect across browsers",
"WAN ICE/TURN and drift"
],
"unreleased_follow_up": {
"publication_ready": false,
"deployed_root_cause_confirmed": false,
"integrated_provisioning": false,
"production_credentials_used": false,
"production_changes": false,
"javascript_tests": 96,
"browser_policy_evidence": "evidence/cross-origin-browser.json",
"details": "evidence/CROSS-ORIGIN-INVESTIGATION.md",
"pending": [
"current trusted Foundry and MA origins",
"explicit read-only credential approval",
"deployed diagnosis and accepted correction",
"dedicated receiver provisioning and audio acceptance"
]
}
},
{
"version": "0.5.0",
"scope": "offline package audit; actual browser synthetic experiment separate from MA/Foundry acceptance",
"connection_configuration": "GM-local in-memory developer API; optional companion setup retained; no one-click GM MA wizard",
"catalog_and_assignments": "shared MA catalog connected to existing GM choices and persistent scene ambient/combat/boss/native fallback + world defaults; real MA playback gated",
"audio": "official SDK PCM and WebRTC implemented experimentally; measured synthetic loopback browser audio, no live MA receiver connection",
"crossfade": "unimplemented",
"companion": "optional source and experimental/companion-0.4.0 branch; no deployment",
"distribution": "one module ZIP; configurable Git-hosted stable manifest + versioned download; offline bundle/checksums/tests pass; no hosted install/update verification",
"ma_mutations_this_revision": 0,
"regression": {
"javascript": 85,
"python": 15
},
"blocking_infrastructure": [
"isolated Foundry v14.371 world",
"existing DEV private identity/pairing",
"secure private browser MA access",
"operator WebSocket auth log review",
"approved synthetic MA ingestion",
"explicit existing TURN relay if required by NAT"
],
"gitea_contacted": false
}
]
}
],
"priorFirefoxFailureEvidence": "evidence/v0.7.0-live-firefox-latest.json",
"priorChromiumFailureEvidence": "evidence/v0.7.0-live-chromium-latest.json",
"latestFirefoxEvidence": "evidence/v0.7.0-live-follow-up.json",
"latestChromiumEvidence": "evidence/v0.7.0-live-follow-up.json",
"priorMAError": {
"code": 2,
"meaning": "MediaNotFound",
"phase": "player_queues/play_media",
"bothBrowserEngines": true,
"catalogMetadataStillPlayable": true,
"exactUpstreamResolutionCause": "unconfirmed",
"automaticMutationRetries": false
},
"dedicatedReceiverReconnectPassed": true,
"privateNginxRouteVerifiedFromUbuntu": true,
"installedFoundryEvidence": "evidence/v0.7.0-foundry-private.json",
"priorBrowserEvidenceScope": "deployed Foundry origin with local source overlay; actual MA, PCM, Web Audio and WebRTC; test-runner signaling, not installed world",
"evidenceScope": "Installed Foundry and actual MA over the private Nginx HTTPS route. Two real player accounts used Foundry module signaling and browser-measured WebRTC playback."
}
+32
View File
@@ -0,0 +1,32 @@
{
"sdk": "@sendspin/sendspin-js",
"version": "5.0.0",
"git_commit": "7d103075138dda5c8909045647bb42b33c2d44fc",
"license": "Apache-2.0",
"integrity": "sha512-yRRjPsz6TyR1GzRYO7ur7oAzwZ11tELK1PEp6Ci7fscXOI0JdtP6BbwPhw+/CR0TWQxu/VwtVPtXT9SH/xhzFw==",
"inspected_before_install": true,
"install_hooks": false,
"dependency_pins": {
"@noble/ciphers": "1.3.0",
"@noble/curves": "1.9.7",
"@noble/hashes": "1.8.0",
"opus-encdec": "0.1.1"
},
"tool_pins": {
"esbuild": "0.27.1",
"playwright": "1.57.0"
},
"distribution_gate": "Pinned bundle hash, all notices and release validator required; no install hooks executed",
"license_review": "Reviewed Apache-2.0 SDK and full MIT noble license texts copied to licenses/vendor; optional opus-encdec fallback disabled, not distributed",
"lockfile": "package-lock.json",
"audit_checked_at": "2026-12-03T20:42:10.993687+00:00",
"vulnerabilities": {
"info": 0,
"low": 0,
"moderate": 0,
"high": 0,
"critical": 0,
"total": 0
},
"bundle_sha256": "b3a7c91e87c0a45e4bdb5a3bd3f323a12ffde9b54babd5ba38351d5dfd4d8556"
}
+42
View File
@@ -0,0 +1,42 @@
{
"license": "MIT; original mathematically generated tones",
"sample_rate": 24000,
"channels": 2,
"duration_seconds": 90,
"sequences": {
"ambient": [
{
"file": "ambient-1.wav",
"frequency_hz": 110,
"sha256": "12ec19bfe12e8a8e3d0f29e79de31812127f1f7e360ac4a2175026e5f210211e"
},
{
"file": "ambient-2.wav",
"frequency_hz": 165,
"sha256": "b12e11c31154dae190c9e448165577decd932d53af5f1969eaa8869db4ea690f"
},
{
"file": "ambient-3.wav",
"frequency_hz": 220,
"sha256": "c9bf2501ba41d16f0c1055b8b383db05f7de714206af35446eb0aad82476376b"
}
],
"combat": [
{
"file": "combat-1.wav",
"frequency_hz": 440,
"sha256": "4e6ba740d0fba4115e6117a118faec5eb74d5d171b1d4051602f86e004b9ee2e"
},
{
"file": "combat-2.wav",
"frequency_hz": 660,
"sha256": "95e8758c279780d4687011a755f7d79528e359e1b9221fb9739602eade7c5b08"
},
{
"file": "combat-3.wav",
"frequency_hz": 880,
"sha256": "cb83457277efdaa44e181697eadc7b8542fe60d00199bb10d547a5c21c29d4e9"
}
]
}
}
+6
View File
@@ -0,0 +1,6 @@
{
"checked_at": "2026-12-03T17:18:24.860Z",
"synthetic_ingestion": false,
"error": "unavailable",
"playback_mutations": 0
}
+8
View File
@@ -0,0 +1,8 @@
{
"checked_at": "2026-12-03T17:25:16.043Z",
"evidence_class": "local generated audio decoding",
"tracks": 6,
"frames": 27000,
"duration_seconds": 540,
"hashes_match": true
}
+150
View File
@@ -0,0 +1,150 @@
{
"checked_at": "2026-12-03",
"git_sources": [
{
"repository": "https://github.com/Sayshal/vgmusic",
"tag": "release-1.4.5",
"commit": "eba07a08c9925f31b9c8adb72faf95de11ae705c",
"local_directory": "vgmusic",
"files": {
"LICENSE": "8da4373e2f64fdd0289d5aba0ad81856f39742582dfa8caf49b22eece53e62d0",
"module.json": "2a50f7dfaaf91e953f6ffde97c8d58f5c88ab3cf2499863cf873d8f264539357",
"package.json": "6e607c8234023df368935e22fd7463d15ac6ab357e604899999c8a78ee1747fa",
"package-lock.json": "245c2723ddfc25a549e600630a324603e9cb234553dc392c8c5c92cc6da896f2",
"scripts/music-controller.mjs": "fc51195eda3c9cb8e04b9fc90ab9a4bd91c99ce6735a54929cf2bf3fa7404ccf",
"scripts/hooks.mjs": "069f1ede780ef1d55c51d65ff17322606f2d89f83d7d02284d2b1149a44898a0",
"scripts/playlist-context.mjs": "5126fbdef6b8129e6a8050da098a6fd904b02684565db014b9afe53d00bd2c0f"
}
},
{
"repository": "https://github.com/music-assistant/server",
"tag": "2.10.6",
"commit": "c24866405bd2068c25a60e1014e5ef8c3f6445bb",
"local_directory": "server",
"files": {
"LICENSE": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4",
"pyproject.toml": "39e6e2cd3962b081b6b8d2b905846d1e79a3ebc21f330d8003bf748f6913c84c",
"requirements_all.txt": "bf97bece2eaca5c0a9beead3a9a2f4e9cf66228c891e6580cb074219c1b2a141",
"music_assistant/controllers/webserver/controller.py": "93a3784d2c2070be512ed2f4619a6ea32088cb91aaa13879ab2fc2a7725a2f06",
"music_assistant/controllers/webserver/auth.py": "462717a6b2486c692d18f3917b26cf12eb036d1bb31ab1a4d0281a9ab505b116",
"music_assistant/controllers/webserver/websocket_client.py": "7ad62ba1f015914cdea6f99c8cac384a4c10ee33fb5b03ab0b6049cce729ecfd",
"music_assistant/controllers/webserver/sendspin_proxy.py": "0b2a25363786e8ef13a460b18c43e1a4a9d0ba30d816349a61f8db7421b85e7e",
"music_assistant/controllers/player_queues/controller.py": "3d610ee9b643a5a338104fbf13d67d2b680b7d4570bc7dfe2364e4d9712b4588",
"music_assistant/providers/sendspin/manifest.json": "cb99a3715f32c573a5120b960e5c3a31c6823bfc269f4963b8d72910132e38ea",
"music_assistant/controllers/webserver/helpers/auth_middleware.py": "f1c45cc4927c9a5e71193b13ff9d4300daaa65dc7b849d255c924fa495fb24a5",
"music_assistant/controllers/players/controller.py": "fd4a66cfe2b28ab7859f46990b3c45f58778d9fbb8dfb196346bed516a012c99",
"music_assistant/controllers/music/media/base.py": "a47aa23c9ed1039e303db1e4da1903c84d2122ed7c66c2b66ad8edd2d7341d45",
"music_assistant/providers/sendspin/provider.py": "9ba7235cd48723255a1d7e4af28f8f90f0e7448f4b234228571e219fa92ccb14",
"music_assistant/providers/sendspin/player.py": "306251735f52295cce3293549ca7f226fe37cab4d454966e8fb657aca7c535c6",
"music_assistant/providers/sendspin/README.md": "ee43c336550a7f4b8cac188f77e6d4e0b580d47d94321f392738d93da9e2c890",
"music_assistant/controllers/player_queues/queue_loader.py": "ead02948ca4450d3651d0c90683df16a16e8b6e23a040bf16b3eb877756e7a0e",
"music_assistant/helpers/uri.py": "c97c43f28db833910635bc89268dd44cb2487b3c26005737f55eb6c1f55521ca",
"music_assistant/providers/builtin/__init__.py": "54349ff427defa5a8c6664ccbcaf47c6564e1eb1606def5b8572c6d57e77df91",
"music_assistant/controllers/music/media/playlists.py": "7dbc38f93688a2b4f6fcd0501607a22942af55766d40f81795beef0dc037eb3e",
"music_assistant/controllers/player_queues/helpers.py": "0206927895599dae0b1dd4842a37d11d5d8e0de539e8f710b07684572de25529",
"music_assistant/controllers/config/core.py": "4703113e383c70edd4d2e2b997fb3c0d6cbd86209cb076eb21e723991e49c634"
}
},
{
"repository": "https://github.com/music-assistant/frontend",
"tag": "2.17.297",
"commit": "e779b9d359e47cd210c2801f16a0ce6263571903",
"local_directory": "frontend",
"files": {
"LICENSE": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4",
"package.json": "83c66acc4371e0f10119ee50ee3d6940e3126fbf36898de02875331a590847c6",
"pnpm-lock.yaml": "129e7a8526a2e96c37f53bcc1895292cb56a73443c373198974ac7aa90b40093",
"src/plugins/sendspin-connection.ts": "780f52ad85fa38b1789267a50f03c744d59b59fa3dca3599ae0f742b150173ee"
}
},
{
"repository": "https://github.com/sendspin/sendspin-js",
"tag": "5.0.0",
"commit": "7d103075138dda5c8909045647bb42b33c2d44fc",
"local_directory": "sendspin-js-5",
"files": {
"LICENSE": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4",
"package.json": "6e1a04d4cf82ddae3e09ac7964952c718395b22a6de260f2e092d9848235aa88",
"src/core/protocol-handler.ts": "b3108d57fbaf974dd7aaf2b8bf0102817928fa1de501b0806b52bdd50a5d9436",
"src/core/transport.ts": "0d855eab42e1f94ef94e5aa324244eadd0e6fe99cb8be8e528199ab07cedb6b2",
"src/audio/clock-source.ts": "bd1c7321702211db42e3bedac746c0fa490a1e12215c3e34ec6b372a2c48a0e6",
"src/audio/decoder.ts": "0abefd87c26079cde9e2f87ad4c8d77a19818818d4ae745002e22930afac1e6a",
"src/audio/output-latency-tracker.ts": "1f5f6492fbb8ee7c1b2dc15c0299c7bbb62aa7dd356c8845c6c4e4178017d7c7",
"src/audio/platform-output-latency.ts": "ad916a598042e1a28578e9568668cdf2c3f880950f9232c438eebbdb34a1519a",
"src/audio/recorrection-monitor.ts": "075660439b7d1ae4140979c20d92a4b15d0842adf4d66f2ad32be031d2116858",
"src/audio/scheduler.ts": "d6d5b134d83d06c0d93b3da49aa70503e38da2fe5800f5029f299b233dd38b9a",
"src/client-identity.ts": "27b645e35d7967577c3a63246128b26350989e4a6ec8cfd66687682c048c4726",
"src/core/activate-authorization.ts": "e2a23dec97ef03829baafee8a4c83075e29c4c265d281926b2ce921d0ec1ccab",
"src/core/codec-support.ts": "fe160adfa40d2c5e0a3b3edd255ea94a283bf98e77431846ae3a0048e6cc50ce",
"src/core/core.ts": "44ce239896faca0887dbf33b5d5b7de924a3ee94c8babfe4e631ef6a82c2c5db",
"src/core/noise/base64url.ts": "0a8fc8f065de1b79497cd166cdfd02f0b1a8558d371bd641c0f8ab6f13cb9a16",
"src/core/noise/cipher-state.ts": "f31000531f6c5aecdbab4cb7ea3d2bfe3911fb58136b72c9e9a58cd0c386cd5d",
"src/core/noise/constants.ts": "bde591118b52136f90cd7e41f6901494c4a1cfae61cb0edaea26b599337829de",
"src/core/noise/handshake.ts": "40caa0df0098d1121a50547614b3564837241945d136fd2faab9202d8228ee3a",
"src/core/noise/identity.ts": "9f23c76b71aa7558aed9a6d416a5c9e75c69798cd74748454d96e96b9791022e",
"src/core/noise/index.ts": "0facbc17a2621f2e9ebf86dd1fadf5efece71028a495eb7165c62c8fe68c8218",
"src/core/noise/pairing-token.ts": "dfbc2e88478bbf9b7e4559c6597206b2262de431007143f8b3d099000980b762",
"src/core/noise/psk.ts": "7c5028446c85ff15e61f1afbee8fa6cc95628afb670018a107f0bd33622acafd",
"src/core/noise/session.ts": "fc1c6747c3d556920e5ac21726f1baa401c575ff6efe9546c8aa6687ebc95c50",
"src/core/noise/suites.ts": "59ba4f407a462c82afbd15568af682de823b012e5e831e67b368a2506d696abc",
"src/core/noise/symmetric-state.ts": "c498ce9caaf89af44076fa89dbd1fc8919289c6ca1b6de2a9670f4b99496a5f9",
"src/core/pairing.ts": "59c0994b3cd422035b98812268e2e87a87b99554786e8da46936af751cbcdc34",
"src/core/pake/cpace.ts": "fed37dbc91bb0f7711492a8481598982c887f14e244c0d1ef1ec0d59a103a2ec",
"src/core/pake/pin.ts": "5852b68967caa92626636f9cb48be3fd527ebee6911ddd54228740674efb71e4",
"src/core/state-manager.ts": "827fff0bbbb6153d807f21456a952f73b61b3aa81fa7bcd5b7aad7362ad122f9",
"src/core/static-delay-store.ts": "265dddae81afe28a8d1b376560e70cbe8c8c26f996ace0bf0bd1be84079d8f29",
"src/core/time-filter.ts": "0d562c167deb3cbdc2b7a23e5baa6f2dc70f214e5307b89903762f01dd6000f7",
"src/core/time-sync-manager.ts": "d64b7b648422333f68bafa878b2b3e2c084bd91d00f980b88c51c4ad8b07f913",
"src/core/websocket-manager.ts": "4acada3e75f19f63f2f7e6d367c545e2dc37a8735fdb32a40e100d94e6bb96db",
"src/index.ts": "e4ba034a7ab604ab80786ca255c73821cd4951ffc4a80c1bf24c4db3fb8d173b",
"src/internal-types.ts": "26e818c95bf831a7123788ca79cba104fc05c887e654c5e67bae06b9669cc2e2",
"src/opus-encdec.d.ts": "e05ec654daf12453bfe44d81b0ec8bc5162d1cd47a12df4502d0e879ca6be40a",
"src/sync-delay.ts": "8bdc54745a7b75da3d2dc78133e82601241323f9e33ee381f9c657d58c58916f",
"src/types.ts": "939c8df601891ad7b483fafa49df2b837e834881685f7e2278eb9e2ffd5dea15"
}
},
{
"repository": "https://github.com/sendspin/sendspin-js",
"tag": "6.1.0",
"commit": "7ee7ca35ac29ae3ef5f2eeeeaac1e24751a8790b",
"local_directory": "sendspin-js",
"files": {
"LICENSE": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4",
"package.json": "b6cae2c9836e467941bb7baab35bde2ead29f3171ce8be18fdb23b758d6b30e9",
"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"
}
}
],
"pypi_sources": [
{
"version": "9.1.1",
"url": "https://files.pythonhosted.org/packages/73/f0/03f798813a0e09f4e1565691d2e5138f0750c98b36d93f522d06c44efe66/aiosendspin-9.1.1.tar.gz",
"sha256": "1e9a33ec5b6dcbc16b4f03c07586195beaa80eb2e5ba4254b97979ae0e0ec4b7",
"inspected_files": {
"LICENSE": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4",
"README.md": "c7f2aaeb734b6628edf06ea9b4a5b425f25a5949a606a3d7f1f3dfb2268c749d",
"pyproject.toml": "940b19e327b155d56ca4935a6d62b946a28b60b734e4f35f61c49bd7b194798c",
"aiosendspin/client/client.py": "1fb7911997417fc97b85221de84935a0c4ae6cfc71d6dc29ca2e2aef5e4b4a08",
"aiosendspin/noise/trust_store.py": "b5a8dbd3f5d6692dca9ccdd4e9eba8eb9b706fa1ced69ef91bb8dcccb0d3f37f"
},
"local_directory": "aiosendspin/aiosendspin-9.1.1"
},
{
"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"
}
]
}
+29
View File
@@ -0,0 +1,29 @@
Adaptive Music v0.6.0 validation — 2026-12-03
/home/ubuntu/.nvm/versions/node/v24.23.0/bin/node --test --test-reporter=tap tests/js/*.test.mjs
PASS: 91 tests, 0 failed, 0 skipped. Full output: v0.6.0-js-tests.txt.
Temporary loopback fixture servers required execution outside the restricted sandbox.
python3 -m unittest discover -s tests -v
PASS: 15 tests, OK.
python3 scripts/audit_repository.py
PASS: repository privacy/attribution guardrails.
python3 scripts/verify_upstream.py
PASS: all recorded Git heads, source and distribution file hashes.
Read local pinned research checkouts; did not fetch or install dependencies.
git diff --check
PASS: no whitespace errors.
PLAYWRIGHT_BROWSERS_PATH=.local/browsers node scripts/check_setup_browser.mjs
PASS: Chromium 143.0.7499.4 actual DOM fixture; wizard render/steps,
private field clearing, catalog selectors, scene ambient/combat save,
hidden advanced controls, listener activation; no page errors.
Temporary loopback HTTP and headless browser; fixture documents/connection only.
No v0.6.0 live Foundry or MA connection/playback, no production credential use,
no Git server access, and no production service/network changes.
User-reported v0.5.0 publication/install/window rendering is recorded separately.
Release import/manifest/license/privacy/checksum validation is performed by release.py.
+556
View File
@@ -0,0 +1,556 @@
TAP version 13
# Subtest: automatic invitations use document-bound ephemeral keys and never broadcast the capability
ok 1 - automatic invitations use document-bound ephemeral keys and never broadcast the capability
---
duration_ms: 11.117677
type: 'test'
...
# Subtest: forged GM claims, recipient changes, tampering and rotated document keys fail closed
ok 2 - forged GM claims, recipient changes, tampering and rotated document keys fail closed
---
duration_ms: 2.082811
type: 'test'
...
# Subtest: parallel bootstrap replay, multiple GMs, revoked roles and expired capabilities cannot connect
ok 3 - parallel bootstrap replay, multiple GMs, revoked roles and expired capabilities cannot connect
---
duration_ms: 2.475986
type: 'test'
...
# Subtest: catalog paginates, strips private metadata and filters unapproved mappings
ok 4 - catalog paginates, strips private metadata and filters unapproved mappings
---
duration_ms: 32.850148
type: 'test'
...
# Subtest: empty provider allowlist denies without I/O; malformed and endless pages fail
ok 5 - empty provider allowlist denies without I/O; malformed and endless pages fail
---
duration_ms: 18.296825
type: 'test'
...
# Subtest: target validation rejects group, changed identity and unavailable player
ok 6 - target validation rejects group, changed identity and unavailable player
---
duration_ms: 1.442234
type: 'test'
...
# Subtest: synthetic audio isolates simultaneous campaigns and copies every frame
ok 7 - synthetic audio isolates simultaneous campaigns and copies every frame
---
duration_ms: 0.485778
type: 'test'
...
# Subtest: audio denies forged origin/session/role, unknown fields and cross-campaign grants
ok 8 - audio denies forged origin/session/role, unknown fields and cross-campaign grants
---
duration_ms: 0.315819
type: 'test'
...
# Subtest: active listener revocation/expiry and slow-client overflow close handles
ok 9 - active listener revocation/expiry and slow-client overflow close handles
---
duration_ms: 0.506526
type: 'test'
...
# Subtest: synthetic source rejects stale sessions/generations, oversized frames; connections are bounded
ok 10 - synthetic source rejects stale sessions/generations, oversized frames; connections are bounded
---
duration_ms: 0.400789
type: 'test'
...
# Subtest: catalog authorization denies listener and injection before upstream
ok 11 - catalog authorization denies listener and injection before upstream
---
duration_ms: 0.376122
type: 'test'
...
# Subtest: scene/combat configuration preserves independent flags and stores only tagged references
ok 12 - scene/combat configuration preserves independent flags and stores only tagged references
---
duration_ms: 4.695721
type: 'test'
...
# Subtest: role loss, stale selection and arbitrary URL/ID fail before document write
ok 13 - role loss, stale selection and arbitrary URL/ID fail before document write
---
duration_ms: 0.347479
type: 'test'
...
# Subtest: editor uses text for catalog labels and rechecks GM on actual save event
ok 14 - editor uses text for catalog labels and rechecks GM on actual save event
---
duration_ms: 0.372166
type: 'test'
...
# Subtest: configuration hook disposal prevents pending asynchronous render from mounting
ok 15 - configuration hook disposal prevents pending asynchronous render from mounting
---
duration_ms: 0.222887
type: 'test'
...
# Subtest: packaged browser client connects through real loopback companion/MA wire fixtures and restores combat queue
ok 16 - packaged browser client connects through real loopback companion/MA wire fixtures and restores combat queue
---
duration_ms: 94.0349
type: 'test'
...
# Subtest: companion denies listener control, wrong scope/Origin, upstream injection and unknown routes
ok 17 - companion denies listener control, wrong scope/Origin, upstream injection and unknown routes
---
duration_ms: 11.775335
type: 'test'
...
# Subtest: browser accepts only relative same-origin paths and never persists a connection grant
ok 18 - browser accepts only relative same-origin paths and never persists a connection grant
---
duration_ms: 0.275675
type: 'test'
...
# Subtest: companion operation replay is idempotent and same ID with changed payload is denied
ok 19 - companion operation replay is idempotent and same ID with changed payload is denied
---
duration_ms: 12.942194
type: 'test'
...
# Subtest: companion listener stream rejects controller grant and closes on live revocation and expiry
ok 20 - companion listener stream rejects controller grant and closes on live revocation and expiry
---
duration_ms: 92.342037
type: 'test'
...
# Subtest: catalog revocation during upstream I/O suppresses the response at the companion boundary
ok 21 - catalog revocation during upstream I/O suppresses the response at the companion boundary
---
duration_ms: 8.904953
type: 'test'
...
# Subtest: policy precedence and explicit silence
ok 22 - policy precedence and explicit silence
---
duration_ms: 1.199009
type: 'test'
...
# Subtest: inactive, unstarted and other scene combats ignored; boss ties stable
ok 23 - inactive, unstarted and other scene combats ignored; boss ties stable
---
duration_ms: 3.984422
type: 'test'
...
# Subtest: scene -> combat -> boss -> nested manual -> unwind restores offsets, duplicates and pause
ok 24 - scene -> combat -> boss -> nested manual -> unwind restores offsets, duplicates and pause
---
duration_ms: 1.248452
type: 'test'
...
# Subtest: scene change during manual never resurrects previous scene
ok 25 - scene change during manual never resurrects previous scene
---
duration_ms: 0.257202
type: 'test'
...
# Subtest: boss removed during manual and deleted combat cannot return
ok 26 - boss removed during manual and deleted combat cannot return
---
duration_ms: 0.309818
type: 'test'
...
# Subtest: duplicate intent causes zero provider mutations
ok 27 - duplicate intent causes zero provider mutations
---
duration_ms: 0.115966
type: 'test'
...
# Subtest: prepare failure leaves current playback intact
ok 28 - prepare failure leaves current playback intact
---
duration_ms: 0.348671
type: 'test'
...
# Subtest: partial apply failure restores outgoing playback
ok 29 - partial apply failure restores outgoing playback
---
duration_ms: 3.387266
type: 'test'
...
# Subtest: obsolete async resolve is rejected before stop/apply
ok 30 - obsolete async resolve is rejected before stop/apply
---
duration_ms: 0.246049
type: 'test'
...
# Subtest: lease loss during stop prevents apply and stale rollback
ok 31 - lease loss during stop prevents apply and stale rollback
---
duration_ms: 0.785727
type: 'test'
...
# Subtest: provider switch and bounded nested stack
ok 32 - provider switch and bounded nested stack
---
duration_ms: 0.299308
type: 'test'
...
# Subtest: no authority retains playback without provider access
ok 33 - no authority retains playback without provider access
---
duration_ms: 0.104495
type: 'test'
...
# Subtest: queued state is captured at submission rather than read after caller mutation
ok 34 - queued state is captured at submission rather than read after caller mutation
---
duration_ms: 0.070922
type: 'test'
...
# Subtest: supersession after snapshot prevents mutations
ok 35 - supersession after snapshot prevents mutations
---
duration_ms: 0.179354
type: 'test'
...
# Subtest: failed cross-provider apply cleans new owned audio before outgoing restoration
ok 36 - failed cross-provider apply cleans new owned audio before outgoing restoration
---
duration_ms: 0.158736
type: 'test'
...
# Subtest: superseded cross-provider apply is reconciled by stopping partially touched target
ok 37 - superseded cross-provider apply is reconciled by stopping partially touched target
---
duration_ms: 0.161141
type: 'test'
...
# Subtest: extracted companion launches privately with fixture credentials, serves catalog diagnostics and listener PCM
ok 38 - extracted companion launches privately with fixture credentials, serves catalog diagnostics and listener PCM
---
duration_ms: 202.3378
type: 'test'
...
# Subtest: gateway binds target server-side and sanitizes metadata
ok 39 - gateway binds target server-side and sanitizes metadata
---
duration_ms: 1.026207
type: 'test'
...
# Subtest: forged, wrong origin/campaign/session and unknown args deny before upstream
ok 40 - forged, wrong origin/campaign/session and unknown args deny before upstream
---
duration_ms: 0.381642
type: 'test'
...
# Subtest: listener cannot read queues or acquire controller lease
ok 41 - listener cannot read queues or acquire controller lease
---
duration_ms: 0.165018
type: 'test'
...
# Subtest: expiry, revocation, stale fence and replay reject
ok 42 - expiry, revocation, stale fence and replay reject
---
duration_ms: 0.216595
type: 'test'
...
# Subtest: lease cannot be stolen and increases fence after revoke
ok 43 - lease cannot be stolen and increases fence after revoke
---
duration_ms: 0.125214
type: 'test'
...
# Subtest: revocation during upstream I/O suppresses response
ok 44 - revocation during upstream I/O suppresses response
---
duration_ms: 0.132218
type: 'test'
...
# Subtest: MA adapter uses pinned envelope, Bearer header, fixed path, no redirects and returns no metadata
ok 45 - MA adapter uses pinned envelope, Bearer header, fixed path, no redirects and returns no metadata
---
duration_ms: 13.038734
type: 'test'
...
# Subtest: MA mismatched queue, upstream failures and redirects fail with sanitized errors
ok 46 - MA mismatched queue, upstream failures and redirects fail with sanitized errors
---
duration_ms: 1.733057
type: 'test'
...
# Subtest: MA rejects URL credentials, query/fragment, paths and non-HTTP configuration
ok 47 - MA rejects URL credentials, query/fragment, paths and non-HTTP configuration
---
duration_ms: 0.276196
type: 'test'
...
# Subtest: MA read adapter performs real local HTTP POST against an isolated fixture
ok 48 - MA read adapter performs real local HTTP POST against an isolated fixture
---
duration_ms: 16.08324
type: 'test'
...
# Subtest: signaling is confidential, per-listener authenticated, scoped and replay resistant
ok 49 - signaling is confidential, per-listener authenticated, scoped and replay resistant
---
duration_ms: 6.13541
type: 'test'
...
# Subtest: signaling denies expired invitation, unknown/audio message types and unapproved TURN secrets
ok 50 - signaling denies expired invitation, unknown/audio message types and unapproved TURN secrets
---
duration_ms: 3.598632
type: 'test'
...
# Subtest: GM browser policy refuses mixed content and SDK identity mismatch before any MA connection
ok 51 - GM browser policy refuses mixed content and SDK identity mismatch before any MA connection
---
duration_ms: 0.721157
type: 'test'
...
# Subtest: official pinned SDK decodes real binary PCM frames and discards stale generations
ok 52 - official pinned SDK decodes real binary PCM frames and discards stale generations
---
duration_ms: 0.249546
type: 'test'
...
# Subtest: parallel signaling replay cannot pass the asynchronous authentication check twice
ok 53 - parallel signaling replay cannot pass the asynchronous authentication check twice
---
duration_ms: 1.522783
type: 'test'
...
# Subtest: GM API WebSocket adapter authenticates privately, assembles partial results and refuses broad commands
ok 54 - GM API WebSocket adapter authenticates privately, assembles partial results and refuses broad commands
---
duration_ms: 12.304332
type: 'test'
...
# Subtest: peer signaling bounds queued work and rejects expired invites before allocating a connection
ok 55 - peer signaling bounds queued work and rejects expired invites before allocating a connection
---
duration_ms: 23.16561
type: 'test'
...
# Subtest: wizard inspects only the imported dedicated identity, loads stable catalog IDs and enables guarded playlist playback
ok 56 - wizard inspects only the imported dedicated identity, loads stable catalog IDs and enables guarded playlist playback
---
duration_ms: 6.110794
type: 'test'
...
# Subtest: disconnect cancels pending GM startup before any authenticated receiver connection
ok 57 - disconnect cancels pending GM startup before any authenticated receiver connection
---
duration_ms: 0.285383
type: 'test'
...
# Subtest: loopback transport denies unauthenticated, cross-campaign, controller, query and wrong-origin requests
ok 58 - loopback transport denies unauthenticated, cross-campaign, controller, query and wrong-origin requests
---
duration_ms: 15.412999
type: 'test'
...
# Subtest: loopback streams synthetic PCM bytes and closes an active stream on revocation
ok 59 - loopback streams synthetic PCM bytes and closes an active stream on revocation
---
duration_ms: 42.102941
type: 'test'
...
# Subtest: loopback closes idle synthetic stream when its listener capability expires
ok 60 - loopback closes idle synthetic stream when its listener capability expires
---
duration_ms: 22.434864
type: 'test'
...
# Subtest: MA snapshots ordered duplicate occurrences, pause and seek then reconstructs exact unshuffled order
ok 61 - MA snapshots ordered duplicate occurrences, pause and seek then reconstructs exact unshuffled order
---
duration_ms: 7.970949
type: 'test'
...
# Subtest: tampered, foreign/future snapshots and stale authority deny before MA mutations
ok 62 - tampered, foreign/future snapshots and stale authority deny before MA mutations
---
duration_ms: 0.994428
type: 'test'
...
# Subtest: shuffled snapshot fails before interruption rather than promising exact restore
ok 63 - shuffled snapshot fails before interruption rather than promising exact restore
---
duration_ms: 0.12279
type: 'test'
...
# Subtest: prepared media cannot be forged and stale generations cannot issue controls
ok 64 - prepared media cannot be forged and stale generations cannot issue controls
---
duration_ms: 0.197099
type: 'test'
...
# Subtest: every wire mutation revalidates exact identity/topology and uses fixed dedicated queue
ok 65 - every wire mutation revalidates exact identity/topology and uses fixed dedicated queue
---
duration_ms: 16.659427
type: 'test'
...
# Subtest: queue injection, transfer, arbitrary media URL and authority loss deny without writes
ok 66 - queue injection, transfer, arbitrary media URL and authority loss deny without writes
---
duration_ms: 0.561489
type: 'test'
...
# Subtest: catalog IDs survive independent adapter construction and differ across campaigns
ok 67 - catalog IDs survive independent adapter construction and differ across campaigns
---
duration_ms: 2.228873
type: 'test'
...
# Subtest: same-generation duplicate controls and restores issue no duplicate mutations
ok 68 - same-generation duplicate controls and restores issue no duplicate mutations
---
duration_ms: 0.864215
type: 'test'
...
# Subtest: MA provider with mock MA client composes with controller for nested contexts and rapid supersession
ok 69 - MA provider with mock MA client composes with controller for nested contexts and rapid supersession
---
duration_ms: 2.850994
type: 'test'
...
# Subtest: ambiguous wire mutation failure latches closed instead of retrying or restoring blindly
ok 70 - ambiguous wire mutation failure latches closed instead of retrying or restoring blindly
---
duration_ms: 0.537284
type: 'test'
...
# Subtest: listener cannot obtain a playback fence guard or renew a controller lease
ok 71 - listener cannot obtain a playback fence guard or renew a controller lease
---
duration_ms: 0.734622
type: 'test'
...
# Subtest: playlist preparation expands approved ordered tracks before any playback mutation
ok 72 - playlist preparation expands approved ordered tracks before any playback mutation
---
duration_ms: 0.80827
type: 'test'
...
# Subtest: installable development entry defaults automation off and imports no gateway
ok 73 - installable development entry defaults automation off and imports no gateway
---
duration_ms: 7.235745
type: 'test'
...
# Subtest: native captures actual offset and paused state, stops per sound, restores repeat/volume
ok 74 - native captures actual offset and paused state, stops per sound, restores repeat/volume
---
duration_ms: 1.289138
type: 'test'
...
# Subtest: native resolves sequential playlist and touches only owned documents
ok 75 - native resolves sequential playlist and touches only owned documents
---
duration_ms: 0.389277
type: 'test'
...
# Subtest: native rejects unsupported shuffle and empty playlist
ok 76 - native rejects unsupported shuffle and empty playlist
---
duration_ms: 0.136165
type: 'test'
...
# Subtest: native rejects expired tracks, changed playlist membership and foreign/future snapshots before mutation
ok 77 - native rejects expired tracks, changed playlist membership and foreign/future snapshots before mutation
---
duration_ms: 0.153157
type: 'test'
...
# Subtest: native reports nonseekable restoration and clamps near-end seek
ok 78 - native reports nonseekable restoration and clamps near-end seek
---
duration_ms: 0.166301
type: 'test'
...
# Subtest: scene-linked playlist conflict and lost authority fail before mutation
ok 79 - scene-linked playlist conflict and lost authority fail before mutation
---
duration_ms: 0.16035
type: 'test'
...
# Subtest: GM election deterministic and no GM means none
ok 80 - GM election deterministic and no GM means none
---
duration_ms: 3.895297
type: 'test'
...
# Subtest: Foundry bootstrap registers local settings/hooks and disposes without ambient or actor access
ok 81 - Foundry bootstrap registers local settings/hooks and disposes without ambient or actor access
---
duration_ms: 0.706259
type: 'test'
...
# Subtest: synthetic WAV termination emits fixed PCM frames through campaign listener authorization
ok 82 - synthetic WAV termination emits fixed PCM frames through campaign listener authorization
---
duration_ms: 0.897347
type: 'test'
...
# Subtest: malformed, truncated and incompatible WAV formats fail closed before PCM publication
ok 83 - malformed, truncated and incompatible WAV formats fail closed before PCM publication
---
duration_ms: 5.927141
type: 'test'
...
# Subtest: credential loader rejects permissive modes, symlinks and malformed secrets
ok 84 - credential loader rejects permissive modes, symlinks and malformed secrets
---
duration_ms: 5.456782
type: 'test'
...
# Subtest: private catalog identity key persists and unsafe key permissions fail
ok 85 - private catalog identity key persists and unsafe key permissions fail
---
duration_ms: 52.916147
type: 'test'
...
# Subtest: scene assignments persist independently and world defaults/boss priority resolve without actor schemas
ok 86 - scene assignments persist independently and world defaults/boss priority resolve without actor schemas
---
duration_ms: 1.092932
type: 'test'
...
# Subtest: native fallback is explicit, manual silence wins and legacy ambient does not resurrect after clearing
ok 87 - native fallback is explicit, manual silence wins and legacy ambient does not resurrect after clearing
---
duration_ms: 0.897637
type: 'test'
...
# Subtest: unavailable saved MA selections are preserved but new forged IDs/non-native fallback and role loss deny
ok 88 - unavailable saved MA selections are preserved but new forged IDs/non-native fallback and role loss deny
---
duration_ms: 0.389588
type: 'test'
...
# Subtest: GM setup connects catalog into independent scene editors and never persists private GM authentication
ok 89 - GM setup connects catalog into independent scene editors and never persists private GM authentication
---
duration_ms: 3.130998
type: 'test'
...
# Subtest: browser PCM sink resumes from gesture, decodes stereo frames and closes its context on stream end
ok 90 - browser PCM sink resumes from gesture, decodes stereo frames and closes its context on stream end
---
duration_ms: 15.104151
type: 'test'
...
# Subtest: normal listener has one activation action and no token or invitation entry
ok 91 - normal listener has one activation action and no token or invitation entry
---
duration_ms: 0.236251
type: 'test'
...
1..91
# tests 91
# suites 0
# pass 91
# fail 0
# cancelled 0
# skipped 0
# todo 0
# duration_ms 1421.813847
+19
View File
@@ -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
}
+37
View File
@@ -0,0 +1,37 @@
v0.7.0 staged acceptance — updated 2026-12-04
Node 24.23.0 JavaScript suite: 101 passed, 0 failed.
Python repository/release suite: 15 passed.
Repository privacy/attribution audit: PASS.
Pinned upstream Git heads and file hashes: PASS.
Production dependency npm audit: 0 reported advisories (not a security guarantee).
Chromium DOM fixture: PASS, 380/640/1000px, no page errors.
Actual Foundry 14.371 ApplicationV2 / browser IndexedDB: PASS at 380/640px.
Browser signaling: Firefox/Chromium real negotiation PASS after SDP fix.
Trusted local-CA HTTPS/WSS policy matrix: six scenarios PASS.
Actual deployed-origin authentication: Firefox 159 and Chromium 159 PASS through
normal sandbox DNS (public addresses); seven providers.
Actual MA catalog/audio + two browser listeners + emulated pause/seek/resume/volume
+ combat interruption and ordered/position restoration: complete passing live runs
recorded separately, including Chromium 159 and a fresh module-created receiver in
Firefox 144. The listener relay is in the test runner, not Foundry's module socket.
Earlier Firefox and Chromium 159 runs received MA error 2 / MediaNotFound on catalog
startup. The cause remains unconfirmed. Both engines subsequently passed full live
playback with two listeners, ambient/combat/ambient, pause, seek, volume and starting
queue restoration. Both engines also passed dedicated receiver reconnect after
transport loss and page reload. See v0.7.0-live-follow-up.json.
A Firefox startup attempt reached an available paired receiver before MA returned
its queue. Startup now retries a null queue read briefly on the bound API session.
The offline regression exercises the waiting path. In the passing live reruns both
browsers received the queue on the first read.
The initial VM-to-proxy TCP probe timed out before TLS. After the operator enabled
the scoped firewall exception, private Nginx TLS and Chromium GM/player login passed.
Real Foundry signaling, Player User flag denial, dedicated MA playback for both
listeners, combat/ambient restore to seven seconds, and listener Stop/Enable and
reload passed. See v0.7.0-foundry-private.json. The original Mac issue did not
reproduce on Ubuntu. Mac, WAN, renewal and physical audibility remain unverified.
Publication readiness remains false.
+612
View File
@@ -0,0 +1,612 @@
{
"scope": "Foundry and Music Assistant through the operator private Nginx HTTPS route, with trusted TLS and a verified proxy peer",
"foundryVersion": "14.371",
"installedModuleVersion": "0.7.0",
"privateRouteVerified": true,
"transport": [
{
"engine": "chromium",
"version": "159.0.8154.6",
"at": "2026-12-04T15:00:10.335Z",
"checks": {
"foundryAnonymous": {
"pageStatus": 200,
"privatePeerVerified": true,
"cspHeaderPresent": false,
"reportOnlyCspHeaderPresent": false,
"cspMetaPresent": false,
"secureContext": true,
"pageReplacesWebSocket": false,
"upgrades": [
{
"path": "/ws",
"code": "upgrade-ok"
},
{
"path": "/sendspin",
"code": "upgrade-ok"
}
],
"handshakeReplies": [
{
"path": "/ws",
"httpStatus": 101
},
{
"path": "/sendspin",
"httpStatus": 101
}
],
"failedRequests": [],
"policyIssues": []
},
"maSameOrigin": {
"pageStatus": 200,
"privatePeerVerified": true,
"cspHeaderPresent": false,
"reportOnlyCspHeaderPresent": false,
"cspMetaPresent": false,
"secureContext": true,
"pageReplacesWebSocket": true,
"upgrades": [
{
"path": "/ws",
"code": "upgrade-ok"
},
{
"path": "/sendspin",
"code": "upgrade-failed"
}
],
"handshakeReplies": [
{
"path": "/ws",
"httpStatus": 101
},
{
"path": "/ws",
"httpStatus": 101
},
{
"path": "/ws",
"httpStatus": 101
},
{
"path": "/sendspin",
"httpStatus": 101
}
],
"failedRequests": [],
"policyIssues": [],
"nativeSendspinUpgrade": "upgrade-ok"
},
"foundryLoggedIn": {
"pageStatus": 200,
"privatePeerVerified": true,
"cspHeaderPresent": false,
"reportOnlyCspHeaderPresent": false,
"cspMetaPresent": false,
"secureContext": true,
"pageReplacesWebSocket": false,
"upgrades": [
{
"path": "/ws",
"code": "upgrade-ok"
},
{
"path": "/sendspin",
"code": "upgrade-ok"
}
],
"handshakeReplies": [
{
"path": "/ws",
"httpStatus": 101
},
{
"path": "/sendspin",
"httpStatus": 101
}
],
"failedRequests": [],
"policyIssues": []
}
}
},
{
"engine": "firefox",
"version": "159.0",
"at": "2026-12-04T14:51:41.129Z",
"checks": {
"foundryAnonymous": {
"pageStatus": 200,
"privatePeerVerified": true,
"cspHeaderPresent": false,
"reportOnlyCspHeaderPresent": false,
"cspMetaPresent": false,
"secureContext": true,
"pageReplacesWebSocket": false,
"upgrades": [
{
"path": "/ws",
"code": "upgrade-ok"
},
{
"path": "/sendspin",
"code": "upgrade-ok"
}
],
"handshakeReplies": [],
"failedRequests": [],
"policyIssues": []
},
"maSameOrigin": {
"pageStatus": 200,
"privatePeerVerified": true,
"cspHeaderPresent": false,
"reportOnlyCspHeaderPresent": false,
"cspMetaPresent": false,
"secureContext": true,
"pageReplacesWebSocket": true,
"upgrades": [
{
"path": "/ws",
"code": "upgrade-ok"
},
{
"path": "/sendspin",
"code": "upgrade-failed"
}
],
"handshakeReplies": [],
"failedRequests": [],
"policyIssues": [],
"nativeSendspinUpgrade": "upgrade-ok"
}
}
}
],
"signedInPlayers": [
{
"worldVerified": true,
"foundry": "14.371",
"moduleVersion": "0.7.0",
"foreignWriteDenied": true,
"gmActive": true,
"apiReady": true,
"publicKeyPublished": true
},
{
"worldVerified": true,
"foundry": "14.371",
"moduleVersion": "0.7.0",
"foreignWriteDenied": true,
"gmActive": true,
"apiReady": true,
"publicKeyPublished": true
}
],
"gmVerified": true,
"maControlPageFinding": "The Music Assistant frontend replaces window.WebSocket and intercepts Sendspin. The intercepted call failed on its unauthenticated page. The same page opened Sendspin with the native constructor retained before frontend scripts.",
"originalMacAM005Reproduced": false,
"originalMacAM005RootCauseConfirmed": false,
"threeAccountsVerifiedTogether": true,
"installedWorldPlaybackBaseline": {
"at": "2026-12-04T15:00:10.335Z",
"engine": "chromium",
"playback": {
"stage": "ambient",
"publicKeys": [
true,
true,
true
],
"playerCannotWriteGMFlag": true,
"maAPIAuthenticated": true,
"sendspinAuthenticated": true,
"accountPairingPassed": true,
"catalogChoices": 11,
"listenerStatsAtFailure": [
{
"bytes": 125468,
"energy": 0,
"samples": 1560000
},
{
"bytes": 125468,
"energy": 0,
"samples": 1560480
}
],
"queueWrites": [
{
"command": "player_queues/play_media",
"reply": true,
"error": null
}
],
"gmAudioDiagnostics": {
"stage": "ready",
"state": "connected",
"audioContext": "running",
"decoded": 1367,
"scheduled": 1367,
"droppedLate": 0,
"droppedAhead": 0,
"signalRMS": 0.1258655905070254,
"muted": false,
"listenerConnections": 2,
"volume": 100
},
"browserAudio": [
{
"decodedFrames": 1367,
"signaling": {
"invitationsForMe": 0,
"invitationEvents": 0,
"offers": 2,
"answers": 0,
"sentInvitations": 2,
"sentSignals": 2
},
"browsers": [
{
"connection": "connected",
"ice": "connected",
"signaling": "stable"
},
{
"connection": "connected",
"ice": "connected",
"signaling": "stable"
}
]
},
{
"decodedFrames": null,
"signaling": {
"invitationsForMe": 1,
"invitationEvents": 2,
"offers": 1,
"answers": 2,
"sentInvitations": 0,
"sentSignals": 1
},
"browsers": [
{
"connection": "connected",
"ice": "connected",
"signaling": "stable"
}
]
},
{
"decodedFrames": null,
"signaling": {
"invitationsForMe": 1,
"invitationEvents": 2,
"offers": 1,
"answers": 2,
"sentInvitations": 0,
"sentSignals": 1
},
"browsers": [
{
"connection": "connected",
"ice": "connected",
"signaling": "stable"
}
]
}
],
"temporaryWorldChangesRestored": true
},
"failure": {
"stage": "installed-world-playback",
"code": "listener-audio-energy-did-not-increase"
},
"interpretation": "Chromium reported zero inbound RTP energy although later direct Web Audio playback measurements in the installed world were positive with the same module files."
},
"diagnosticBeforePlaybackMeters": {
"inboundStats": [
{
"bytes": 124880,
"energy": 0,
"samples": 1558080
},
{
"bytes": 124937,
"energy": 0,
"samples": 1558080
}
],
"senderEnergy": [
4.082235420083857,
4.082235420083857
],
"gmAnalyserRMS": [
0.1651397004235531
]
},
"installedWorldPlaybackPass": {
"at": "2026-12-04T15:05:54.779Z",
"engine": "chromium",
"browser": "159.0.8154.6",
"accounts": {
"gm-login": {
"worldMatches": true,
"accountMatches": true,
"gm": true,
"foundryVersion": "14.371",
"system": "dnd5e",
"otherActiveGMs": 0,
"adaptiveMusicActive": true,
"adaptiveMusicVersion": "0.7.0",
"canvasTickerPaused": true
},
"player-1-login": {
"worldMatches": true,
"accountMatches": true,
"gm": false,
"foundryVersion": "14.371",
"system": "dnd5e",
"otherActiveGMs": 1,
"adaptiveMusicActive": true,
"adaptiveMusicVersion": "0.7.0",
"canvasTickerPaused": true
},
"player-2-login": {
"worldMatches": true,
"accountMatches": true,
"gm": false,
"foundryVersion": "14.371",
"system": "dnd5e",
"otherActiveGMs": 1,
"adaptiveMusicActive": true,
"adaptiveMusicVersion": "0.7.0",
"canvasTickerPaused": true
}
},
"playback": {
"stage": "passed",
"publicKeys": [
true,
true,
true
],
"playerCannotWriteGMFlag": true,
"maAPIAuthenticated": true,
"sendspinAuthenticated": true,
"accountPairingPassed": true,
"catalogChoices": 11,
"ambient": [
{
"bytesIncreased": true,
"energyIncrease": 0,
"playbackRMS": 0.004791336274277526,
"samplesIncreased": true
},
{
"bytesIncreased": true,
"energyIncrease": 0,
"playbackRMS": 0.004743247823567246,
"samplesIncreased": true
}
],
"combat": [
{
"bytesIncreased": true,
"energyIncrease": 0,
"playbackRMS": 0.12556049134588929,
"samplesIncreased": true
},
{
"bytesIncreased": true,
"energyIncrease": 0,
"playbackRMS": 0.1205585037803511,
"samplesIncreased": true
}
],
"ambientOrderRestored": true,
"ambientRestoreOffset": {
"index": 0,
"seconds": 7
},
"ambientIndexAndOffsetRestored": true,
"restoredAmbient": [
{
"bytesIncreased": true,
"energyIncrease": 0,
"playbackRMS": 0.0457946358080247,
"samplesIncreased": true
},
{
"bytesIncreased": true,
"energyIncrease": 0,
"playbackRMS": 0.04364745631856095,
"samplesIncreased": true
}
],
"onlyDedicatedQueueWritten": true,
"afterListenerResume": [
{
"bytesIncreased": true,
"energyIncrease": 0,
"playbackRMS": 0.04998535387418037,
"samplesIncreased": true
},
{
"bytesIncreased": true,
"energyIncrease": 0,
"playbackRMS": 0.051046648244698796,
"samplesIncreased": true
}
],
"afterListenerReload": [
{
"bytesIncreased": true,
"energyIncrease": 0,
"playbackRMS": 0.1276089199898213,
"samplesIncreased": true
},
{
"bytesIncreased": true,
"energyIncrease": 0,
"playbackRMS": 0.09472793662374407,
"samplesIncreased": true
}
],
"queueWrites": [
{
"command": "player_queues/play_media",
"reply": true,
"error": null
},
{
"command": "player_queues/stop",
"reply": true,
"error": null
},
{
"command": "player_queues/play_media",
"reply": true,
"error": null
},
{
"command": "player_queues/stop",
"reply": true,
"error": null
},
{
"command": "player_queues/stop",
"reply": true,
"error": null
},
{
"command": "player_queues/clear",
"reply": true,
"error": null
},
{
"command": "player_queues/repeat",
"reply": true,
"error": null
},
{
"command": "player_queues/play_media",
"reply": true,
"error": null
},
{
"command": "player_queues/play_index",
"reply": true,
"error": null
}
],
"gmAudioDiagnostics": {
"stage": "ready",
"state": "connected",
"audioContext": "running",
"decoded": 1608,
"scheduled": 1608,
"droppedLate": 0,
"droppedAhead": 0,
"signalRMS": 0.13149861108647076,
"muted": false,
"listenerConnections": 2,
"volume": 100
},
"browserAudio": [
{
"decodedFrames": 1608,
"signaling": {
"invitationsForMe": 0,
"invitationEvents": 0,
"offers": 4,
"answers": 0,
"sentInvitations": 5,
"sentSignals": 4
},
"contexts": [
{
"state": "running",
"time": 35.735510204081635,
"track": "live"
}
],
"analyserRMS": [
0.2428510186200088
],
"browsers": [
{
"connection": "closed",
"ice": "closed",
"signaling": "closed"
},
{
"connection": "closed",
"ice": "closed",
"signaling": "closed"
},
{
"connection": "connected",
"ice": "connected",
"signaling": "stable",
"outgoingEnergy": 4.711130388295272
},
{
"connection": "closed",
"ice": "closed",
"signaling": "closed"
},
{
"connection": "connected",
"ice": "connected",
"signaling": "stable",
"outgoingEnergy": 0.2959549249485192
}
]
},
{
"decodedFrames": null,
"signaling": {
"invitationsForMe": 2,
"invitationEvents": 5,
"offers": 2,
"answers": 4,
"sentInvitations": 0,
"sentSignals": 2
},
"contexts": [],
"analyserRMS": [],
"browsers": [
{
"connection": "closed",
"ice": "closed",
"signaling": "closed"
},
{
"connection": "connected",
"ice": "connected",
"signaling": "stable"
}
]
},
{
"decodedFrames": null,
"contexts": [],
"analyserRMS": [],
"browsers": [
{
"connection": "connected",
"ice": "connected",
"signaling": "stable"
}
]
}
],
"temporaryWorldChangesRestored": true
}
},
"firefoxInstalledWorldBlocker": "The Firefox build completed WSS probes, but the Foundry join form did not render on this headless or Xvfb host. A WebGL 2 context was unavailable."
}
+109
View File
@@ -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
}
+253
View File
@@ -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
}
+119
View File
@@ -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
}
+178
View File
@@ -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
}
+138
View File
@@ -0,0 +1,138 @@
{
"version": "0.7.0",
"publicationReady": false,
"completedCoreRunPassed": true,
"macPrivateRouteVerified": false,
"foundryLoggedInWorldVerified": true,
"actualMAAuthentication": true,
"actualMACatalogPlaylists": 11,
"actualMADedicatedProvisioning": true,
"actualMAAudioAndTwoListeners": true,
"actualAmbientCombatRestore": true,
"actualNativePause": false,
"logicalPauseEmulation": true,
"browserAudioHardwareAudibilityVerified": false,
"crossfade": false,
"coreSuccessEvidence": "evidence/v0.7.0-live-chromium.json",
"browserAuthentication": {
"at": "2026-12-04T03:13:45.898Z",
"scope": "actual origins, read-only API authentication; Ubuntu browsers, not Mac",
"browsers": [
{
"browser": "firefox",
"version": "159.0",
"origin": "foundry",
"maRoute": "normal resolver",
"httpStatus": 200,
"csp": null,
"result": {
"stage": "authenticated",
"providerCount": 7,
"commandError": null,
"metaCSP": [],
"blocked": [],
"secureContext": true
}
},
{
"browser": "firefox",
"version": "159.0",
"origin": "ma",
"maRoute": "normal resolver",
"httpStatus": 200,
"csp": null,
"result": {
"stage": "authenticated",
"providerCount": 7,
"commandError": null,
"metaCSP": [],
"blocked": [],
"secureContext": true
}
},
{
"browser": "chromium",
"version": "159.0.8154.6",
"origin": "foundry",
"maRoute": "normal resolver",
"httpStatus": 200,
"csp": null,
"result": {
"stage": "authenticated",
"providerCount": 7,
"commandError": null,
"metaCSP": [],
"blocked": [],
"secureContext": true
}
},
{
"browser": "chromium",
"version": "159.0.8154.6",
"origin": "ma",
"maRoute": "normal resolver",
"httpStatus": 200,
"csp": null,
"result": {
"stage": "authenticated",
"providerCount": 7,
"commandError": null,
"metaCSP": [],
"blocked": [],
"secureContext": true
}
}
]
},
"networkBoundary": {
"sandboxNormalDNS": "public addresses",
"operatorMacMAResolution": "private proxy mapping",
"temporaryAccessRequestPrepared": true,
"initialUbuntuPrivateProxyTCP443": "timeout before TLS",
"followUpUbuntuPrivateProxyTCP443": "verified TLS and installed Foundry browser through operator-scoped firewall access",
"infrastructureChangedByTestAgent": false
},
"remaining": [
"original Mac connection and AM-005 reproduction if the symptom persists",
"WAN/30-minute behavior and hardware audibility"
],
"credentialUseAuthorized": true,
"dedicatedReceiverMutationsPerformed": true,
"latestCatalogReplayPassed": true,
"freshProvisioningObserved": {
"browser": "Firefox 144.0.2",
"at": "2026-12-04T03:10:40.566Z",
"path": "module creates a fresh identity; no manual protocol pre-provisioning",
"pairing": true,
"audioTwoListeners": true,
"ambientOrderAndOffsetRestored": true,
"finalQueueRestored": true,
"source": "observed live driver output; private driver reports were subsequently superseded by current-browser reruns"
},
"productionDependencyAudit": {
"info": 0,
"low": 0,
"moderate": 0,
"high": 0,
"critical": 0,
"total": 0
},
"priorFirefoxFailureEvidence": "evidence/v0.7.0-live-firefox-latest.json",
"priorChromiumFailureEvidence": "evidence/v0.7.0-live-chromium-latest.json",
"latestFirefoxEvidence": "evidence/v0.7.0-live-follow-up.json",
"latestChromiumEvidence": "evidence/v0.7.0-live-follow-up.json",
"priorMAError": {
"code": 2,
"meaning": "MediaNotFound",
"phase": "player_queues/play_media",
"bothBrowserEngines": true,
"catalogMetadataStillPlayable": true,
"exactUpstreamResolutionCause": "unconfirmed",
"automaticMutationRetries": false
},
"dedicatedReceiverReconnectPassed": true,
"privateNginxRouteVerifiedFromUbuntu": true,
"installedFoundryEvidence": "evidence/v0.7.0-foundry-private.json",
"priorBrowserEvidenceScope": "deployed Foundry origin with local source overlay; actual MA, PCM, Web Audio and WebRTC; test-runner signaling, not installed world",
"evidenceScope": "Installed Foundry and actual MA over the private Nginx HTTPS route. Two real player accounts used Foundry module signaling and browser-measured WebRTC playback."
}
+536
View File
@@ -0,0 +1,536 @@
{
"version": "0.7.1",
"defect": "AM-006",
"publicationReady": false,
"completedCoreRunPassed": true,
"macPrivateRouteVerified": false,
"foundryLoggedInWorldVerified": false,
"verifiedGraphicalPreview": {
"at": "2026-12-04T15:29:05.529Z",
"scope": "private Nginx HTTPS route",
"checks": {},
"engine": "chromium",
"browser": "159.0.8154.6",
"moduleAssets": "workspace module assets in the test browser",
"accounts": {
"gm-login": {
"worldMatches": true,
"accountMatches": true,
"gm": true,
"foundryVersion": "14.371",
"system": "dnd5e",
"otherActiveGMs": 0,
"adaptiveMusicActive": true,
"adaptiveMusicVersion": "0.7.0",
"canvasTickerPaused": true
}
},
"layout": {
"resizable": true,
"layout": [
{
"width": 760,
"tab": "Connection",
"horizontalFit": true,
"nestedScroll": false
},
{
"width": 760,
"tab": "Scene Music",
"horizontalFit": true,
"nestedScroll": false
},
{
"width": 760,
"tab": "Playback",
"horizontalFit": true,
"nestedScroll": false
},
{
"width": 380,
"tab": "Connection",
"horizontalFit": true,
"nestedScroll": false
},
{
"width": 380,
"tab": "Scene Music",
"horizontalFit": true,
"nestedScroll": false
},
{
"width": 380,
"tab": "Playback",
"horizontalFit": true,
"nestedScroll": false
}
],
"keyboardTabs": true,
"advancedCollapsed": true,
"invalidAddressRejected": true,
"missingTokenRejected": true,
"routeDiagnostics": [
{
"path": "/ws",
"opened": true
},
{
"path": "/sendspin",
"opened": true
}
]
},
"completed": true
},
"regression": {
"javascript": 102,
"python": 15,
"offlineBrowserControls": [
"connect",
"tabs",
"save assignments",
"current track",
"pause",
"resume",
"seek",
"volume",
"stop"
]
},
"remaining": [
"verify the packaged candidate after a server-side installation in the development environment",
"Mac and WAN acceptance"
],
"previousInstalledWorldEvidence": "evidence/v0.7.0-foundry-private.json",
"verifiedLiveWorkflowPreview": {
"at": "2026-12-04T15:32:01.859Z",
"scope": "private Nginx HTTPS route",
"checks": {
"foundryAnonymous": {
"pageStatus": 200,
"privatePeerVerified": true,
"cspHeaderPresent": false,
"reportOnlyCspHeaderPresent": false,
"cspMetaPresent": false,
"secureContext": true,
"pageReplacesWebSocket": false,
"upgrades": [
{
"path": "/ws",
"code": "upgrade-ok"
},
{
"path": "/sendspin",
"code": "upgrade-ok"
}
],
"handshakeReplies": [
{
"path": "/ws",
"httpStatus": 101
},
{
"path": "/sendspin",
"httpStatus": 101
}
],
"failedRequests": [],
"policyIssues": []
},
"maSameOrigin": {
"pageStatus": 200,
"privatePeerVerified": true,
"cspHeaderPresent": false,
"reportOnlyCspHeaderPresent": false,
"cspMetaPresent": false,
"secureContext": true,
"pageReplacesWebSocket": true,
"upgrades": [
{
"path": "/ws",
"code": "upgrade-ok"
},
{
"path": "/sendspin",
"code": "upgrade-failed"
}
],
"handshakeReplies": [
{
"path": "/ws",
"httpStatus": 101
},
{
"path": "/ws",
"httpStatus": 101
},
{
"path": "/sendspin",
"httpStatus": 101
}
],
"failedRequests": [],
"policyIssues": [],
"nativeSendspinUpgrade": "upgrade-ok"
},
"foundryLoggedIn": {
"pageStatus": 200,
"privatePeerVerified": true,
"cspHeaderPresent": false,
"reportOnlyCspHeaderPresent": false,
"cspMetaPresent": false,
"secureContext": true,
"pageReplacesWebSocket": false,
"upgrades": [
{
"path": "/ws",
"code": "upgrade-ok"
},
{
"path": "/sendspin",
"code": "upgrade-ok"
}
],
"handshakeReplies": [
{
"path": "/ws",
"httpStatus": 101
},
{
"path": "/sendspin",
"httpStatus": 101
}
],
"failedRequests": [],
"policyIssues": []
}
},
"engine": "chromium",
"browser": "159.0.8154.6",
"moduleAssets": "workspace module assets in the test browser",
"accounts": {
"gm-login": {
"worldMatches": true,
"accountMatches": true,
"gm": true,
"foundryVersion": "14.371",
"system": "dnd5e",
"otherActiveGMs": 0,
"adaptiveMusicActive": true,
"adaptiveMusicVersion": "0.7.0",
"canvasTickerPaused": true
},
"player-1-login": {
"worldMatches": true,
"accountMatches": true,
"gm": false,
"foundryVersion": "14.371",
"system": "dnd5e",
"otherActiveGMs": 1,
"adaptiveMusicActive": true,
"adaptiveMusicVersion": "0.7.0",
"canvasTickerPaused": true
},
"player-2-login": {
"worldMatches": true,
"accountMatches": true,
"gm": false,
"foundryVersion": "14.371",
"system": "dnd5e",
"otherActiveGMs": 1,
"adaptiveMusicActive": true,
"adaptiveMusicVersion": "0.7.0",
"canvasTickerPaused": true
}
},
"playback": {
"stage": "passed",
"publicKeys": [
true,
true,
true
],
"playerCannotWriteGMFlag": true,
"advancedInitiallyCollapsed": true,
"formRejectedMissingTokenWithoutNetwork": true,
"oneClickConnection": true,
"maAPIAuthenticated": true,
"sendspinAuthenticated": true,
"accountPairingPassed": true,
"catalogChoices": 11,
"sceneAssignmentVerified": true,
"ambient": [
{
"bytesIncreased": true,
"energyIncrease": 0,
"playbackRMS": 0.008014325143255013,
"samplesIncreased": true
},
{
"bytesIncreased": true,
"energyIncrease": 0,
"playbackRMS": 0.007670743474125928,
"samplesIncreased": true
}
],
"combat": [
{
"bytesIncreased": true,
"energyIncrease": 0,
"playbackRMS": 0.12679305568945426,
"samplesIncreased": true
},
{
"bytesIncreased": true,
"energyIncrease": 0,
"playbackRMS": 0.12893801659879386,
"samplesIncreased": true
}
],
"ambientOrderRestored": true,
"ambientRestoreOffset": {
"index": 0,
"seconds": 8
},
"ambientIndexAndOffsetRestored": true,
"restoredAmbient": [
{
"bytesIncreased": true,
"energyIncrease": 0,
"playbackRMS": 0.09003888968411675,
"samplesIncreased": true
},
{
"bytesIncreased": true,
"energyIncrease": 0,
"playbackRMS": 0.09750464413094424,
"samplesIncreased": true
}
],
"onlyDedicatedQueueWritten": true,
"afterListenerResume": [
{
"bytesIncreased": true,
"energyIncrease": 0,
"playbackRMS": 0.0868827545622943,
"samplesIncreased": true
},
{
"bytesIncreased": true,
"energyIncrease": 0,
"playbackRMS": 0.09662535253515621,
"samplesIncreased": true
}
],
"afterListenerReload": [
{
"bytesIncreased": true,
"energyIncrease": 0,
"playbackRMS": 0.08775154314156451,
"samplesIncreased": true
},
{
"bytesIncreased": true,
"energyIncrease": 0,
"playbackRMS": 0.08398555055737364,
"samplesIncreased": true
}
],
"afterPlaybackResume": [
{
"bytesIncreased": true,
"energyIncrease": 0,
"playbackRMS": 0.10693401545725446,
"samplesIncreased": true
},
{
"bytesIncreased": true,
"energyIncrease": 0,
"playbackRMS": 0.14311589172943934,
"samplesIncreased": true
}
],
"playbackTabControls": true,
"queueWrites": [
{
"command": "player_queues/play_media",
"reply": true,
"error": null
},
{
"command": "player_queues/stop",
"reply": true,
"error": null
},
{
"command": "player_queues/play_media",
"reply": true,
"error": null
},
{
"command": "player_queues/stop",
"reply": true,
"error": null
},
{
"command": "player_queues/stop",
"reply": true,
"error": null
},
{
"command": "player_queues/clear",
"reply": true,
"error": null
},
{
"command": "player_queues/repeat",
"reply": true,
"error": null
},
{
"command": "player_queues/play_media",
"reply": true,
"error": null
},
{
"command": "player_queues/play_index",
"reply": true,
"error": null
},
{
"command": "player_queues/stop",
"reply": true,
"error": null
},
{
"command": "player_queues/play_index",
"reply": true,
"error": null
},
{
"command": "player_queues/stop",
"reply": true,
"error": null
}
],
"gmAudioDiagnostics": {
"stage": "ready",
"state": "connected",
"audioContext": "running",
"decoded": 1829,
"scheduled": 1829,
"droppedLate": 0,
"droppedAhead": 0,
"signalRMS": 0.12175643489717901,
"muted": false,
"listenerConnections": 2,
"volume": 99
},
"browserAudio": [
{
"decodedFrames": null,
"signaling": {
"invitationsForMe": 0,
"invitationEvents": 0,
"offers": 4,
"answers": 0,
"sentInvitations": 4,
"sentSignals": 4
},
"contexts": [
{
"state": "running",
"time": 101.05324263038548,
"track": "live"
}
],
"analyserRMS": [
0
],
"browsers": [
{
"connection": "closed",
"ice": "closed",
"signaling": "closed"
},
{
"connection": "closed",
"ice": "closed",
"signaling": "closed"
},
{
"connection": "connected",
"ice": "connected",
"signaling": "stable",
"outgoingEnergy": 2.5731208355109527
},
{
"connection": "connected",
"ice": "connected",
"signaling": "stable",
"outgoingEnergy": 0.4176949028255943
}
]
},
{
"decodedFrames": null,
"signaling": {
"invitationsForMe": 2,
"invitationEvents": 4,
"offers": 2,
"answers": 4,
"sentInvitations": 0,
"sentSignals": 2
},
"contexts": [],
"analyserRMS": [],
"browsers": [
{
"connection": "closed",
"ice": "closed",
"signaling": "closed"
},
{
"connection": "connected",
"ice": "connected",
"signaling": "stable"
}
]
},
{
"decodedFrames": null,
"contexts": [],
"analyserRMS": [],
"browsers": [
{
"connection": "connected",
"ice": "connected",
"signaling": "stable"
}
]
}
],
"temporaryWorldChangesRestored": true
},
"completed": true
},
"earlierAttempts": [
"The private Foundry vhost served the logged-in application. The Music Assistant vhost completed trusted TLS and supplied no HTTP response before the deadline. The in-window token-free checks opened neither WebSocket.",
{
"at": "2026-12-04T15:29:22.993Z",
"failure": {
"stage": "installed-world-playback",
"code": "ma-play-media-not-observed"
},
"restoredWorld": true
}
],
"productionDependencyAudit": {
"info": 0,
"low": 0,
"moderate": 0,
"high": 0,
"critical": 0,
"total": 0
}
}
+49
View File
@@ -0,0 +1,49 @@
{
"version": "0.7.2",
"publicationReady": false,
"completedCoreRunPassed": false,
"foundryLoggedInWorldVerified": false,
"installedV070GuiReview": {
"at": "2026-12-04T15:55:39.842Z",
"moduleVersion": "0.7.0",
"assetOverrides": false,
"injectedRuntimeScripts": false,
"manualGuiControls": true,
"authenticatedAndConnected": true,
"catalogCount": 12,
"savedScene": true,
"decodedFrames": 299,
"passed": true,
"reviewScene": "Adaptive Music \u2014 GM review"
},
"accountPersistence": "Encrypted address and name in a Foundry User Setting. The MA token is required for each new browser session. The server does not host the browser audio relay.",
"regression": {
"javascript": 104,
"python": 15
},
"candidateAccountSettingVerified": {
"scope": "Actual development world, v0.7.2 candidate assets supplied in Playwright only",
"firstSession": {
"settingScope": "user",
"hasEnvelope": true,
"connected": true,
"manualAddressEntry": true,
"addressRestored": true
},
"newBrowserSession": {
"settingScope": "user",
"hasEnvelope": true,
"connected": true,
"manualAddressEntry": false,
"addressRestored": true
}
},
"productionDependencyAudit": {
"info": 0,
"low": 0,
"moderate": 0,
"high": 0,
"critical": 0,
"total": 0
}
}
+84
View File
@@ -0,0 +1,84 @@
> Optional experimental companion fallback. The standard module has no mandatory
> companion or sandbox dependency. See ../ARCHITECTURE.md and ../INSTALL.md for
> the 0.5.0 module-only experiment and remaining deployment gates. This guide
> does not authorize host routing, service installation or production changes.
# Private companion — 0.4.0 development
The companion now connects the browser-safe provider/catalog interface to the
existing MA client, fenced control and playback provider. It is a separate server
artifact; no gateway code or MA credential is bundled into Foundry. Follow
[SETUP.md](SETUP.md) for exact isolated-world setup and infrastructure gates.
`development-service.mjs` accepts only fixed controller phases: connect, diagnostics,
catalog, renew, release, prepare, snapshot, apply, restore and stop. Server-bound
campaign/session/target identity, controller role, lease/fence/generation and
operation IDs constrain requests. Preparation and raw signed snapshots stay in
server memory behind expiring opaque handles. Prepared handles bind their generation;
restore handles bind fenced session and expiry. Same-ID changed payloads deny;
replayed operations do not issue duplicate effects. Queue selectors, raw media,
upstream commands/paths and proxy operations are not accepted from browsers.
`development-http.mjs` binds loopback only, with exact Host/Origin, header-only auth,
fixed POST routes, bounded headers/body/responses/connections/request rate and queued
work. The browser client uses same-origin relative `/adaptive-music-gateway` routes,
credentials omitted and no redirects, with capability codes held in memory only.
A private HTTPS route is still an operator infrastructure requirement. No public
exposure, proxy/firewall change, CORS wildcard or MA Sendspin pass-through exists.
This prototype still lacks permanent hosting, durable fencing/process locks and
automatic Foundry login verification. Do not expose it publicly.
`run-development.mjs` loads protected ignored `.local/` config and pins the prior
verified account's sole target, exact name Adaptive Music DEV and provider. It
serves five minutes with separate controller/listener grants and starts no playback.
Playback defaults off; explicit synthetic opt-in authorizes only generated sequence
IDs. Real MA catalog entries remain selectable for configuration but unplayable
under the current authorization. There is no automatic household discovery or
selection, queue transfer, grouping or new receiver provisioning.
The browser package saves separate scene ambient/combat/boss/native-fallback refs,
world defaults and explicit boss flags. Native fallback applies before preparation
when MA is disconnected, expired or not authorized for that selection. It never
bypasses an uncertain active MA target to start overlapping native audio. The
controller still uses one base music layer interrupted by combat/boss/manual;
concurrent ambient layers and crossfade are not implemented.
The existing `ma-provider.mjs` and `ma-client.mjs` retain fixed guarded commands:
play_media, play_index, pause, resume, stop, seek, shuffle, repeat and clear. Every
mutation rechecks supported queue modes, active queue identity and exact player/
provider/topology, then authority immediately before dispatch. Registered approved
media only; no arbitrary URI injection. Ambiguous responses latch the client closed
with `uncertain`, without retries or blind restoration. The public MA API cannot
atomically bind topology checks to a write; concurrent external changes and restart
reconciliation remain development limitations.
Signed snapshots preserve ordered duplicate occurrences, index, whole-second
position, state and repeat for supported unshuffled static queues. They expire in
five minutes and bind campaign/session/fence/generation. Capture repeats bounded
pagination; restore stages items, checks order, then seeks/plays and reapplies pause
or idle. Shuffle/dynamic/autoplay/overlay/ended/nonstandard-speed restoration is
unsupported. Volume is unchanged. Losing topology/authority can prevent recovery;
report it rather than bypass guards. Durable recovery still needs further work.
Private `.local/catalog-key` and `.local/catalog-namespace.json` give opaque
campaign-scoped catalog IDs persistence across companion restarts. Refresh the
catalog to rebuild private mappings; back up those files. Secrets/config require
0600 and directory 0700, owner checks and symlink refusal. MA tokens never enter
browser assets/settings/flags/storage/URLs/logs. The upstream user role remains
broader than read-only and queue reads lack player filtering in pinned source, so
gateway boundaries remain essential even with account filters.
Separate listener POST /audio accepts listener capabilities only and streams quiet
companion-generated PCM; joining causes no MA effects. Expiry/revocation/backpressure
closes active sockets. The packaged Web Audio sink validates PCM and starts only
on Enable Audio. This is a **synthetic test stream, not MA/Sendspin audio**. A
supported public-interface dedicated receiver, private pairing, audited codecs and
protocol/time tests are still needed; see `evidence/SENDSPIN-RECEIVER.md` in the repo.
Crossfade remains explicitly unavailable in setup and diagnostics.
Actual connected live reading: verified DEV target, **11 playlists / 1 radio**, no
MA token/endpoint/target ID in browser-facing responses, playback disabled and zero
mutations. This exercised a local HTTP client/companion, not Foundry or TLS. New
phase/queue restoration tests use an isolated fake MA HTTP server. Earlier live
idle-queue controls/restoration and failed synthetic ingestion remain separately
recorded; no new playback mutation occurred in this revision.
+94
View File
@@ -0,0 +1,94 @@
> Optional experimental companion fallback. The standard module has no mandatory
> companion or sandbox dependency. See ../ARCHITECTURE.md and ../INSTALL.md for
> the 0.5.0 module-only experiment and remaining deployment gates. This guide
> does not authorize host routing, service installation or production changes.
# Private companion setup — 0.4.0-dev
This is a development companion, not a public deployment. It always binds an
ephemeral **127.0.0.1** port, runs for five minutes, and starts no MA playback on
launch. No firewall, reverse proxy, MA service or production Foundry configuration
has been changed by this project. Node 24.23.0 or later; no npm install is needed.
The module and companion are separate artifacts. Extract the module into an isolated
Foundry Data/modules directory. Extract `adaptive-music-companion-dev.zip` on the
operator's private gateway host (or run the repository). All operator data stays in
an owner-controlled `.local/` directory mode 0700, JSON/secret files mode 0600.
The module ZIP contains only browser code; the companion ZIP contains server code
and notices, never actual endpoint configuration or secrets.
For the existing authorized DEV target, provide private `.local/environment.json`
with `ma_url`, `.local/ma-token`, and `.local/ma-readonly-results.json` generated by
the existing approved read-only probe. The launcher pins that verified account's
sole player, exact name Adaptive Music DEV and provider instance. It does not list
or choose household players. Back up `.local/catalog-key` and
`.local/catalog-namespace.json` to retain catalog IDs across restarts. Corrupt or
unsafe existing namespace/key files fail rather than silently changing IDs.
Create `.local/development-gateway.json` with these operator values (placeholders):
```json
{
"foundryOrigin": "https://foundry.example.invalid",
"proxyHost": true,
"syntheticAudio": true,
"enableSyntheticControl": false
}
```
Use the exact isolated Foundry origin, with no trailing slash/path. HTTPS is
required except for localhost development. `proxyHost: true` requires the preserved
Host header to match that origin. With `proxyHost: false`, only the ephemeral
loopback Host is accepted (for local harnesses, not browser deployment). The process
also requires an exact Origin and header-only grants; it rejects arbitrary paths,
query strings, commands, target selectors, oversized bodies and excess requests.
Run `node gateway/run-development.mjs` from the companion/repository root. The
loopback address is written to `.local/development-gateway-runtime.json`, never
browser settings. The operator must already have, or separately approve and review,
a **private same-origin HTTPS route** `/adaptive-music-gateway` from the isolated
Foundry origin to this local companion, preserving Host, Origin and Authorization,
streaming responses without buffering or token/header logging. Preserve every
existing network restriction. No proxy template was applied, no route has been
created and this build does not bypass mixed-content/private-network protections.
A remote browser cannot reach the operator's loopback listener without that
infrastructure. This ephemeral prototype is not suitable for permanent hosting.
Privately deliver `.local/controller-bootstrap.json` to the elected active GM.
In Foundry settings → Configure Settings → Adaptive Music setup, paste the JSON
into the password field and choose **Connect and load MA catalog**. The field is
cleared and the capability stays in memory only. Do not paste an MA token. The
module never receives one. Diagnostics show target availability, catalog contents,
content authorization and the missing Sendspin/crossfade capabilities. Capabilities
expire after five minutes; get a fresh bootstrap after restarting the companion.
Only the elected active GM should connect; other GMs may configure native music.
Set owned native playlists using checkboxes, reload, then configure world defaults
and each scene's ambient, combat, boss and native fallback choices. Boss combatants
can override playlist, priority and inactive state in setup. Enable automation only
after configuration. MA catalog assignments persist as opaque IDs, but real MA
playlist playback remains disallowed under the current synthetic-only authorization.
Unavailable/unapproved MA assignments choose the explicit scene/world native
fallback or silence before preparing playback. A target with uncertain active MA
playback cannot be bypassed by silently starting fallback audio.
`enableSyntheticControl: true` is an explicit operator opt-in for the **existing
approved generated fixtures only**. It requires `.local/fixture-origin.json` and
MA-readable synthetic files; it adds generated ambient/combat sequence choices.
All real MA catalog IDs remain excluded from playback authorization. The earlier
fixture ingestion attempt failed, so this is still an infrastructure gate. Do not
modify existing playlists or select other MA players to work around it.
For browser audio, give listeners `.local/listener-bootstrap.json` privately. They
open **Campaign audio (development)** and press Enable Audio. The separate listener
grant cannot browse catalog, acquire a lease or control queues. This plays the
companion's quiet synthetic PCM tone through Web Audio; it is independent of the
DEV target and does **not** prove Sendspin/MA audio playback. Closing/stopping audio
or capability expiry/revocation closes the stream. Browser rendering and autoplay
still need actual Foundry/browser validation. Joining never changes any MA player.
For Sendspin audio, a separately approved gateway-owned public-interface receiver,
private pairing/identity storage, codec review and termination are still needed.
No direct MA Sendspin proxy is provided. Crossfade and concurrent ambient layers
remain unimplemented, and the UI says so. See TESTING.md/PROGRESS.md in the repository
for exact offline/live evidence. Do not expose this companion publicly.
+78
View File
@@ -0,0 +1,78 @@
// In-process, read-only security PoC. No HTTP/WSS listener or live credential bootstrap.
import { randomBytes } from 'node:crypto';
import { MusicError } from '../src/core/controller.mjs';
export class GatewayControl {
#grants = new Map(); #leases = new Map();
constructor({ campaigns, origin, now = () => Date.now() }) {
this.campaigns = new Map(Object.entries(campaigns)); this.origin = origin; this.now = now;
}
// Operator-only API. Never expose mint/revoke/acquire directly to unauthenticated browsers.
mint({ campaign, session, role, ttlMs = 60000 }) {
if (!this.campaigns.has(campaign) || !['controller','listener'].includes(role) ||
!session || !(ttlMs > 0 && ttlMs <= 300000)) throw new MusicError('denied');
const token = randomBytes(32).toString('base64url');
this.#grants.set(token, { campaign, session, role, expires: this.now()+ttlMs }); return token;
}
revoke(token) { this.#grants.delete(token); }
authorize(token, origin, campaign, session, role) {
const grant = this.#grants.get(token);
if (origin !== this.origin || !grant || grant.expires <= this.now() ||
grant.campaign !== campaign || grant.session !== session || grant.role !== role) throw new MusicError('denied');
return grant;
}
acquire(request) {
const g = this.authorize(request.token, request.origin, request.campaign, request.session, 'controller');
const previous = this.#leases.get(g.campaign);
// No live takeover: new controller waits for expiry/revocation, then gets a greater fence.
if (previous && previous.expires > this.now() && this.#grants.has(previous.token)) throw new MusicError('denied');
const lease = { token: request.token, session: g.session, fence: (previous?.fence ?? 0)+1, generation: 0,
expires: Math.min(g.expires, this.now()+30000) };
this.#leases.set(g.campaign, lease); return { fence: lease.fence, expires: lease.expires };
}
// Server-only guard for a provider bound to this exact controller lease.
fenceGuard(request) {
const captured = {...request};
return fence => {
this.authorize(captured.token,captured.origin,captured.campaign,captured.session,'controller');
const lease=this.#leases.get(captured.campaign);
if (!lease || lease.token!==captured.token || lease.session!==captured.session ||
lease.fence!==fence || fence!==captured.fence || lease.expires<=this.now()) throw new MusicError('stale');
};
}
release(request) {this.fenceGuard(request)(request.fence);this.#leases.get(request.campaign).expires=this.now();}
renew(request) {
this.fenceGuard(request)(request.fence);
const grant=this.authorize(request.token,request.origin,request.campaign,request.session,'controller');
const lease=this.#leases.get(request.campaign);
lease.expires=Math.min(grant.expires,this.now()+30000);
return {fence:lease.fence,expires:lease.expires};
}
async #controllerRead(request, operation) {
const allowed = new Set(['token','origin','campaign','session','fence','generation']);
if (Object.keys(request).some(k => !allowed.has(k))) throw new MusicError('denied');
const check = () => {
this.authorize(request.token, request.origin, request.campaign, request.session, 'controller');
const lease = this.#leases.get(request.campaign);
if (!lease || lease.token !== request.token || lease.session !== request.session || lease.expires <= this.now() ||
lease.fence !== request.fence || !Number.isSafeInteger(request.generation) ||
request.generation <= lease.generation) throw new MusicError('stale');
return lease;
};
const lease = check();
// Consume generation before I/O so concurrent/replayed requests cannot both pass.
lease.generation = request.generation;
const result = await operation(this.campaigns.get(request.campaign));
this.authorize(request.token, request.origin, request.campaign, request.session, 'controller');
if (this.#leases.get(request.campaign) !== lease || lease.generation !== request.generation || lease.expires <= this.now()) throw new MusicError('stale');
return result;
}
async readCatalog(request) {
return this.#controllerRead(request, ({client}) => client.catalog());
}
async readQueue(request) {
const queue = await this.#controllerRead(request, ({client,target}) => client.getOwnedQueue(target));
// No URIs, names, upstream IDs, artwork or raw metadata leave the queue response.
return { state: ['playing','paused','idle'].includes(queue.state) ? queue.state : 'unknown',
items: Number.isSafeInteger(queue.items) && queue.items >= 0 ? queue.items : 0 };
}
}
+38
View File
@@ -0,0 +1,38 @@
import {createServer} from 'node:http';
import {MusicError} from '../src/core/controller.mjs';
// Development companion: fixed loopback binding. Public exposure is deliberately unavailable.
export async function startDevelopmentHTTP({service,origin,prefix='/adaptive-music-gateway',expectedHost}){
const streams=new Set(),rates=new Map();
const server=createServer({maxHeaderSize:4096},async(req,res)=>{
const respond=(status,data)=>{res.writeHead(status,{'Content-Type':'application/json','Cache-Control':'no-store','X-Content-Type-Options':'nosniff'});res.end(JSON.stringify(data));};
let handle;
try{
if(req.method!=='POST'||![prefix+'/rpc',prefix+'/audio'].includes(req.url)||req.headers.host!==(expectedHost??`127.0.0.1:${server.address().port}`)||req.headers.origin!==origin||
req.headers['content-type']!=='application/json'||typeof req.headers.authorization!=='string'||!req.headers.authorization.startsWith('Bearer '))throw new MusicError('denied');
// Fixed peer count: this listener only accepts local peers, never arbitrary IP maps.
const peer=req.socket.remoteAddress,now=Date.now(),rate=rates.get(peer);
if(!rate||now-rate.start>60000)rates.set(peer,{start:now,count:1});else if(++rate.count>600)throw new MusicError('denied');
const chunks=[];let size=0;
for await(const chunk of req){size+=chunk.length;if(size>16384)throw new MusicError('denied');chunks.push(chunk);}
let body;try{body=JSON.parse(Buffer.concat(chunks).toString('utf8'));}catch{throw new MusicError('denied');}
if(!body||typeof body!=='object'||Array.isArray(body))throw new MusicError('denied');
const token=req.headers.authorization.slice(7);
if(req.url===prefix+'/rpc'){
const value=await service.rpc(token,origin,body);service.authorize(token,origin,body);
if(JSON.stringify(value).length>1048576)throw new MusicError('unavailable');respond(200,value);return;
}
if(Object.keys(body).sort().join(',')!=='campaign,session'||!service.audio)throw new MusicError('denied');
service.authorize(token,origin,body,'listener');
handle=service.audio.connect({token,origin,...body});
res.writeHead(200,{'Content-Type':'application/octet-stream','Cache-Control':'no-store','X-Content-Type-Options':'nosniff','X-Audio-Format':'pcm16le;rate=24000;channels=2'});res.flushHeaders();
const connection={res,handle,timer:setInterval(()=>{
try{const frame=handle.next();if(frame&&!res.write(frame.pcm))res.destroy();}catch{res.destroy();}
},20)};
streams.add(connection);
res.on('close',()=>{clearInterval(connection.timer);handle.close();streams.delete(connection);});
}catch(error){handle?.close();if(res.headersSent)res.destroy();else respond(error.code==='denied'?403:409,{code:['denied','stale','unsupported','unavailable','uncertain','expired-media'].includes(error.code)?error.code:'unavailable'});}
});
server.maxHeadersCount=16;server.headersTimeout=2000;server.requestTimeout=5000;server.keepAliveTimeout=1000;server.maxConnections=32;
await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(0,'127.0.0.1',resolve);});
return {url:`http://127.0.0.1:${server.address().port}${prefix}`,async close(){for(const {res,handle,timer}of streams){clearInterval(timer);handle.close();res.destroy();}const done=new Promise(resolve=>server.close(resolve));server.closeAllConnections();await done;}};
}
+68
View File
@@ -0,0 +1,68 @@
import {randomUUID} from 'node:crypto';
import {MusicError} from '../src/core/controller.mjs';
import {MAPlaybackProvider} from './ma-provider.mjs';
// Server-only bridge. No upstream IDs, raw snapshots, arbitrary commands or URLs cross it.
export class DevelopmentService {
#control; #campaign; #session; #client; #key; #allowed; #provider; #binding; #latest=0; #tail=Promise.resolve(); #handles=new Map(); #cache=new Map(); #pending=0;
constructor({control,campaign,session,client,snapshotKey,allowedIds=[],playbackEnabled=false,audio}){
this.#control=control;this.#campaign=campaign;this.#session=session;this.#client=client;this.#key=snapshotKey;
this.#allowed=new Set(allowedIds);this.playbackEnabled=playbackEnabled;this.audio=audio;
}
authorize(token,origin,body,role='controller'){
this.#control.authorize(token,origin,body.campaign,body.session,role);
if(body.campaign!==this.#campaign||body.session!==this.#session)throw new MusicError('denied');
}
async rpc(token,origin,body){
this.authorize(token,origin,body);
const base=['action','campaign','session'];
const shape={connect:[],diagnostics:[],catalog:[],renew:['fence'],release:['fence'],prepare:['generation','operationId','fence','id'],snapshot:['generation','operationId','fence'],apply:['generation','operationId','fence','handle'],restore:['generation','operationId','fence','handle'],stop:['generation','operationId','fence']};
if(!Object.hasOwn(shape,body.action)||Object.keys(body).some(k=>![...base,...shape[body.action]].includes(k)))throw new MusicError('denied');
const request={token,origin,campaign:this.#campaign,session:this.#session,fence:body.fence};
if(body.action==='connect'){
const lease=this.#control.acquire(request);request.fence=lease.fence;
this.#binding=request;this.#latest=0;this.#handles.clear();this.#cache.clear();
this.#provider=new MAPlaybackProvider({client:this.#client,campaign:this.#campaign,session:this.#session,fence:lease.fence,authority:this.#control.fenceGuard(request),snapshotKey:this.#key});return lease;
}
if(body.action==='diagnostics'){
let target='unavailable';try{await this.#client.verifyTarget();target='verified';}catch{}
this.authorize(token,origin,body);
return {target,catalog:true,playbackEnabled:this.playbackEnabled && target==='verified',allowedIds:[...this.#allowed],
expiresAt:this.#control.authorize(token,origin,body.campaign,body.session,'controller').expires,audioSource:this.audio?'synthetic-pcm':'none',sendspin:false,crossfade:false,ambientLayers:1};
}
if(body.action==='catalog'){const items=await this.#client.catalog();this.authorize(token,origin,body);return [...items,...[...this.#allowed].filter(id=>id.startsWith('synthetic-')).map(id=>({provider:'ma',id,kind:'sequence',name:id==='synthetic-ambient'?'Generated ambient test sequence':'Generated combat test sequence'}))];}
if(body.action==='renew')return this.#control.renew(request);
if(body.action==='release'){this.#control.release(request);return {ok:true};}
if(!this.playbackEnabled || !this.#provider || !Number.isSafeInteger(body.generation)||body.generation<1 || typeof body.operationId!=='string'||body.operationId.length>80 || !body.operationId ||
this.#binding.token!==token || this.#binding.fence!==body.fence)throw new MusicError('denied');
this.#control.fenceGuard(request)(body.fence);
if(body.generation<this.#latest)throw new MusicError('stale');
this.#latest=body.generation;
const signature=JSON.stringify(body),cached=this.#cache.get(body.operationId);
if(cached){if(cached.signature!==signature)throw new MusicError('denied');return cached.result;}
const ctx={campaign:this.#campaign,session:this.#session,generation:body.generation,check:()=>{
this.authorize(token,origin,body);this.#control.fenceGuard(request)(body.fence);if(body.generation!==this.#latest)throw new MusicError('stale');
}};
const put=(type,value)=>{
ctx.check();
for(const [id,entry]of this.#handles)if(entry.expires<=Date.now())this.#handles.delete(id);
if(this.#handles.size>=64)throw new MusicError('unavailable');
const handle=randomUUID(),expires=Date.now()+300000;this.#handles.set(handle,{type,value,expires,generation:body.generation});return {handle,expires};
};
const get=type=>{const entry=this.#handles.get(body.handle);if(!entry||entry.type!==type||entry.expires<=Date.now()||type==='prepared'&&entry.generation!==body.generation)throw new MusicError('expired-media');return entry.value;};
for(const [id,entry]of this.#cache)if(entry.generation<body.generation)this.#cache.delete(id);
if(this.#cache.size>=128||this.#pending>=16)throw new MusicError('unavailable');
this.#pending++;
const operation=this.#tail.catch(()=>{}).then(async()=>{
ctx.check();
switch(body.action){
case 'prepare':if(!this.#allowed.has(body.id))throw new MusicError('denied');return put('prepared',await this.#provider.resolve({provider:'ma',id:body.id},ctx));
case 'snapshot':return put('snapshot',await this.#provider.snapshot(ctx));
case 'apply':await this.#provider.apply(get('prepared'),ctx);return {ok:true};
case 'restore':await this.#provider.restore(get('snapshot'),ctx);return {ok:true};
case 'stop':await this.#provider.stopOwned(ctx);return {ok:true};
}
}).finally(()=>{this.#pending--;});
this.#tail=operation;
this.#cache.set(body.operationId,{signature,result:operation,generation:body.generation});return operation;
}
}
+43
View File
@@ -0,0 +1,43 @@
import { createServer } from 'node:http';
// Local experiment only. No public binding, MA dependency, credential, control route or deployment entrypoint.
// Wire format: raw signed stereo PCM16 little endian, 24 kHz, 20 ms per frame.
export async function startLoopbackAudio({ audio, campaign, session }) {
const active = new Set();
const server = createServer({ maxHeaderSize: 4096 }, (req, res) => {
let listener;
try {
if (req.method !== 'GET' || req.url !== '/audio' || req.headers.host !== `127.0.0.1:${server.address().port}` ||
req.headers['content-length'] || req.headers['transfer-encoding'] ||
typeof req.headers.authorization !== 'string' || !req.headers.authorization.startsWith('Bearer ')) throw Error();
listener = audio.connect({ campaign, session, origin: req.headers.origin,
token: req.headers.authorization.slice(7) });
} catch { res.writeHead(403, { 'Cache-Control': 'no-store' }); res.end(); return; }
res.writeHead(200, { 'Content-Type': 'application/octet-stream', 'Cache-Control': 'no-store',
'X-Content-Type-Options': 'nosniff', 'X-Audio-Format': 'pcm16le;rate=24000;channels=2' });
res.flushHeaders();
const connection = { res, listener, timer: null };
const close = () => { clearInterval(connection.timer); listener.close(); active.delete(connection); };
res.on('close', close);
connection.timer = setInterval(() => {
try {
const frame = listener.next();
// Never queue an unbounded stream for a slow consumer.
if (frame && !res.write(frame.pcm)) res.destroy();
} catch { res.destroy(); }
}, 20);
active.add(connection);
});
server.maxHeadersCount = 16; server.headersTimeout = 1000;
server.requestTimeout = 1000; server.keepAliveTimeout = 1000;
server.maxConnections = 32;
await new Promise((resolve,reject) => { server.once('error',reject); server.listen(0,'127.0.0.1',resolve); });
return {
url: `http://127.0.0.1:${server.address().port}/audio`,
async close() {
for (const {res,listener,timer} of active) { clearInterval(timer); listener.close(); res.destroy(); }
active.clear();
const closed = new Promise((resolve,reject) => server.close(error => error ? reject(error) : resolve()));
server.closeAllConnections(); await closed;
}
};
}
+2
View File
@@ -0,0 +1,2 @@
// Compatibility export; validated transport is shared with the GM-local browser path.
export {MAReadClient} from '../src/providers/ma/client.mjs';
+2
View File
@@ -0,0 +1,2 @@
// Compatibility export; the same provider now runs with browser Web Crypto.
export {MAPlaybackProvider} from '../src/providers/ma/provider.mjs';
+19
View File
@@ -0,0 +1,19 @@
import { MusicError } from '../src/core/controller.mjs';
// Strict local-fixture decoder only. No file/network fetch or third-party codec.
export function* pcmFixtureFrames(input) {
const data=Buffer.from(input);
if(data.length<44 || data.length>9000000 || data.toString('ascii',0,4)!=='RIFF' || data.toString('ascii',8,12)!=='WAVE' || data.readUInt32LE(4)+8!==data.length)throw new MusicError('unsupported');
let format=false,pcm;
for(let offset=12;offset+8<=data.length;){
const kind=data.toString('ascii',offset,offset+4),length=data.readUInt32LE(offset+4);offset+=8;
if(offset+length>data.length)throw new MusicError('unsupported');
if(kind==='fmt '){
if(length<16 || data.readUInt16LE(offset)!==1 || data.readUInt16LE(offset+2)!==2 || data.readUInt32LE(offset+4)!==24000 || data.readUInt16LE(offset+12)!==4 || data.readUInt16LE(offset+14)!==16)throw new MusicError('unsupported');
format=true;
}
if(kind==='data'){if(pcm)throw new MusicError('unsupported');pcm=data.subarray(offset,offset+length);}
offset+=length+(length%2);
}
if(!format || !pcm?.length || pcm.length%1920!==0)throw new MusicError('unsupported');
for(let offset=0;offset<pcm.length;offset+=1920)yield Uint8Array.from(pcm.subarray(offset,offset+1920));
}
+38
View File
@@ -0,0 +1,38 @@
import { lstat, open } from 'node:fs/promises';
import { constants } from 'node:fs';
import { join } from 'node:path';
import { MusicError } from '../src/core/controller.mjs';
// Fixed private file only. No environment secret, URL parameter or browser input.
export async function loadMAToken(directory) {
try {
const dir = await lstat(directory);
if (!dir.isDirectory() || dir.isSymbolicLink() || (dir.mode & 0o777) !== 0o700 || dir.uid !== process.getuid()) throw Error();
const file = await open(join(directory, 'ma-token'), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
try {
const info = await file.stat();
if (!info.isFile() || (info.mode & 0o777) !== 0o600 || info.uid !== process.getuid() || info.size > 16384) throw Error();
const token = (await file.readFile('utf8')).trim();
if (!token || /[\r\n]/.test(token)) throw Error();
return token;
} finally { await file.close(); }
} catch { throw new MusicError('denied'); }
}
// Separate from the MA token. Back up this private key to preserve scene identifiers.
export async function loadCatalogKey(directory) {
const { randomBytes } = await import('node:crypto');
const path = join(directory, 'catalog-key');
// Reuse the directory/token owner-mode validation before creating private state.
await loadMAToken(directory);
try {
const created = await open(path, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
try { await created.writeFile(randomBytes(32)); await created.sync(); }
finally { await created.close(); }
} catch (error) { if (error.code !== 'EEXIST') throw new MusicError('denied'); }
const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
try {
const info = await file.stat();
if (!info.isFile() || info.uid !== process.getuid() || (info.mode & 0o777) !== 0o600 || info.size !== 32) throw new MusicError('denied');
return await file.readFile();
} finally { await file.close(); }
}
+45
View File
@@ -0,0 +1,45 @@
// Explicit private development companion. Never launched by the Foundry module.
import {open} from 'node:fs/promises';
import {constants} from 'node:fs';
import {randomUUID} from 'node:crypto';
import {MAReadClient} from './ma-client.mjs';
import {loadMAToken,loadCatalogKey} from './private-config.mjs';
import {GatewayControl} from './control.mjs';
import {DevelopmentService} from './development-service.mjs';
import {startDevelopmentHTTP} from './development-http.mjs';
import {SyntheticAudioGateway} from './synthetic-audio.mjs';
async function privateJSON(name,value){const file=await open(`.local/${name}`,constants.O_WRONLY|constants.O_CREAT|constants.O_NOFOLLOW,0o600);try{const info=await file.stat();if(!info.isFile()||(info.mode&0o777)!==0o600||info.uid!==process.getuid())throw Error();await file.truncate(0);await file.writeFile(JSON.stringify(value,null,2));}finally{await file.close();}}
let activeServer,sourceTimer;
async function readPrivate(name){const file=await open(`.local/${name}`,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const info=await file.stat();if(!info.isFile()||(info.mode&0o777)!==0o600||info.uid!==process.getuid()||info.size>1048576)throw Error();return JSON.parse(await file.readFile('utf8'));}finally{await file.close();}}
try{
await loadMAToken('.local');
const config=await readPrivate('development-gateway.json');
if(Object.keys(config).some(k=>!['foundryOrigin','proxyHost','syntheticAudio','enableSyntheticControl'].includes(k))||['proxyHost','syntheticAudio','enableSyntheticControl'].some(k=>config[k]!==undefined&&typeof config[k]!=='boolean'))throw Error();
const environment=await readPrivate('environment.json');
const verified=await readPrivate('ma-readonly-results.json');
const origin=new URL(config.foundryOrigin);
if(origin.origin!==config.foundryOrigin||origin.protocol!=='https:'&&!['localhost','127.0.0.1'].includes(origin.hostname)||verified.me.player_filter.length!==1||verified.player.name!=='Adaptive Music DEV')throw Error();
const campaign=randomUUID(),session=randomUUID(),snapshotKey=await loadCatalogKey('.local');
// Persist the opaque campaign namespace independently from ephemeral session/grants.
let namespace;
try{namespace=(await readPrivate('catalog-namespace.json')).campaign;}catch(error){if(error.code!=='ENOENT')throw error;namespace=randomUUID();await privateJSON('catalog-namespace.json',{campaign:namespace});}
if(typeof namespace!=='string'||!namespace||namespace.length>256)throw Error();
let sequences={};if(config.enableSyntheticControl){const fixture=await readPrivate('fixture-origin.json');sequences=Object.fromEntries(Object.entries(fixture.sequences).map(([kind,names])=>[`synthetic-${kind}`,names.map(name=>`builtin://track/${fixture.base_url}/${name}`)]));}
const client=new MAReadClient({baseUrl:environment.ma_url,token:await loadMAToken('.local'),target:verified.me.player_filter[0],approvedProviders:verified.me.provider_filter,
catalogKey:snapshotKey,campaign:namespace,expectedName:'Adaptive Music DEV',expectedProvider:verified.player.provider,syntheticSequences:sequences});
const control=new GatewayControl({campaigns:{[campaign]:{client}},origin:origin.origin});
const controller=control.mint({campaign,session,role:'controller',ttlMs:300000}),listener=control.mint({campaign,session,role:'listener',ttlMs:300000});
let audio;if(config.syntheticAudio){audio=new SyntheticAudioGateway({control});audio.provision({campaign,session});}
const service=new DevelopmentService({control,campaign,session,client,snapshotKey,allowedIds:Object.keys(sequences),playbackEnabled:config.enableSyntheticControl===true,audio});
const server=await startDevelopmentHTTP({service,origin:origin.origin,expectedHost:config.proxyHost?origin.host:undefined});
activeServer=server;
await privateJSON('development-gateway-runtime.json',{url:server.url,expires:new Date(Date.now()+300000).toISOString()});
await privateJSON('controller-bootstrap.json',{token:controller,campaign,session});
await privateJSON('listener-bootstrap.json',{token:listener,campaign,session});
let generation=0,sample=0;
const timer=sourceTimer=audio&&setInterval(()=>{const pcm=new Uint8Array(1920),view=new DataView(pcm.buffer);for(let i=0;i<480;i++){const value=Math.round(500*Math.sin(2*Math.PI*220*sample++/24000));view.setInt16(i*4,value,true);view.setInt16(i*4+2,value,true);}audio.publish({campaign,session,generation:++generation,pcm});},20);
let closing=false;
const close=async()=>{if(closing)return;closing=true;clearInterval(timer);control.revoke(controller);control.revoke(listener);await server.close();process.exitCode=0;};
process.once('SIGINT',close);process.once('SIGTERM',close);setTimeout(close,300000).unref();
console.log('Private loopback companion ready for five minutes. Connection codes and address are in .local/; no MA playback starts on launch.');
}catch{clearInterval(sourceTimer);await activeServer?.close();console.error('Companion startup failed; check protected .local configuration and origin. Details withheld.');process.exitCode=1;}
+63
View File
@@ -0,0 +1,63 @@
import { MusicError } from '../src/core/controller.mjs';
// In-process transport prototype; accepts only operator-generated 20 ms PCM fixtures.
// No Sendspin socket, upstream URL, codec negotiation, network listener or MA connection.
export class SyntheticAudioGateway {
#control; #streams = new Map(); #connections = new Set();
constructor({ control }) { this.#control = control; }
// Operator-only session bootstrap; rotate on gateway restart. Never a browser route.
provision({ campaign, session }) {
if (!this.#control.campaigns.has(campaign) || !session || this.#streams.has(campaign)) throw new MusicError('denied');
this.#streams.set(campaign, { session, generation: 0, frames: [] });
}
// Operator-only synthetic source. Real sources must acquire/check the authority fence.
publish({ campaign, session, generation, pcm }) {
const stream = this.#streams.get(campaign);
if (!stream || stream.session !== session || !Number.isSafeInteger(generation) || generation !== stream.generation + 1) throw new MusicError('stale');
if (!(pcm instanceof Uint8Array) || pcm.byteLength !== 1920) throw new MusicError('denied');
stream.generation = generation;
stream.frames.push({ generation, pcm: Uint8Array.from(pcm) });
// At most 200 ms of stereo PCM16 at 24 kHz per campaign, no disk cache.
if (stream.frames.length > 10) stream.frames.shift();
}
#check(request) {
if (!request || Object.keys(request).sort().join(',') !== 'campaign,origin,session,token') throw new MusicError('denied');
this.#control.authorize(request.token, request.origin, request.campaign, request.session, 'listener');
const stream = this.#streams.get(request.campaign);
if (!stream || stream.session !== request.session) throw new MusicError('denied');
return stream;
}
connect(request) {
const stream = this.#check(request);
this.sweep();
if ([...this.#connections].filter(c => c.request.campaign === request.campaign).length >= 16) throw new MusicError('denied');
const connection = { request: { ...request }, cursor: stream.generation, closed: false };
this.#connections.add(connection);
const close = () => { connection.closed = true; this.#connections.delete(connection); };
return {
close,
get closed() { return connection.closed; },
next: () => {
try {
if (connection.closed) throw new MusicError('denied');
const current = this.#check(connection.request);
const frame = current.frames.find(f => f.generation > connection.cursor);
// Fail closed for listeners that fell behind the bounded ring.
if (current.frames.length && connection.cursor < current.frames[0].generation - 1) throw new MusicError('stale');
if (!frame) return null;
connection.cursor = frame.generation;
return { generation: frame.generation, pcm: Uint8Array.from(frame.pcm), sampleRate: 24000, channels: 2 };
} catch (error) { close(); throw error; }
}
};
}
// A future transport must schedule this and close its socket when a handle closes.
sweep() {
for (const connection of this.#connections) {
try { this.#check(connection.request); }
catch { connection.closed = true; this.#connections.delete(connection); }
}
}
purge(campaign) {
this.#streams.delete(campaign); this.sweep();
}
}
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2025 3 Death Saves
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+22
View File
@@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2022 Paul Miller (https://paulmillr.com)
Copyright (c) 2016 Thomas Pornin <pornin@bolet.org>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2022 Paul Miller (https://paulmillr.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2022 Paul Miller (https://paulmillr.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+28
View File
@@ -0,0 +1,28 @@
{
"id": "adaptive-music",
"title": "Adaptive Music",
"description": "Scene and combat playlist automation with native Foundry fallback, private GM Music Assistant setup and Sendspin/WebRTC campaign audio.",
"version": "0.7.2",
"authors": [
{
"name": "CheddahBoxMB"
}
],
"compatibility": {
"minimum": "14",
"maximum": "14"
},
"esmodules": [
"src/foundry/module.mjs"
],
"relationships": {
"requires": []
},
"styles": [
"styles/adaptive-music.css"
],
"socket": true,
"url": "https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music",
"manifest": "https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/raw/branch/main/module.json",
"download": "https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/releases/download/v0.7.2/adaptive-music.zip"
}
+614
View File
@@ -0,0 +1,614 @@
{
"name": "adaptive-music",
"version": "0.5.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "adaptive-music",
"version": "0.5.0",
"license": "MIT",
"dependencies": {
"@sendspin/sendspin-js": "5.0.0"
},
"devDependencies": {
"esbuild": "0.27.1",
"playwright": "1.57.0"
},
"engines": {
"node": ">=24.23.0"
}
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.1.tgz",
"integrity": "sha512-HHB50pdsBX6k47S4u5g/CaLjqS3qwaOVE5ILsq64jyzgMhLuCuZ8rGzM9yhsAjfjkbgUPMzZEPa7DAp7yz6vuA==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"aix"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.1.tgz",
"integrity": "sha512-kFqa6/UcaTbGm/NncN9kzVOODjhZW8e+FRdSeypWe6j33gzclHtwlANs26JrupOntlcWmB0u8+8HZo8s7thHvg==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm64": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.1.tgz",
"integrity": "sha512-45fuKmAJpxnQWixOGCrS+ro4Uvb4Re9+UTieUY2f8AEc+t7d4AaZ6eUJ3Hva7dtrxAAWHtlEFsXFMAgNnGU9uQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-x64": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.1.tgz",
"integrity": "sha512-LBEpOz0BsgMEeHgenf5aqmn/lLNTFXVfoWMUox8CtWWYK9X4jmQzWjoGoNb8lmAYml/tQ/Ysvm8q7szu7BoxRQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-arm64": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.1.tgz",
"integrity": "sha512-veg7fL8eMSCVKL7IW4pxb54QERtedFDfY/ASrumK/SbFsXnRazxY4YykN/THYqFnFwJ0aVjiUrVG2PwcdAEqQQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-x64": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.1.tgz",
"integrity": "sha512-+3ELd+nTzhfWb07Vol7EZ+5PTbJ/u74nC6iv4/lwIU99Ip5uuY6QoIf0Hn4m2HoV0qcnRivN3KSqc+FyCHjoVQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-arm64": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.1.tgz",
"integrity": "sha512-/8Rfgns4XD9XOSXlzUDepG8PX+AVWHliYlUkFI3K3GB6tqbdjYqdhcb4BKRd7C0BhZSoaCxhv8kTcBrcZWP+xg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-x64": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.1.tgz",
"integrity": "sha512-GITpD8dK9C+r+5yRT/UKVT36h/DQLOHdwGVwwoHidlnA168oD3uxA878XloXebK4Ul3gDBBIvEdL7go9gCUFzQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.1.tgz",
"integrity": "sha512-ieMID0JRZY/ZeCrsFQ3Y3NlHNCqIhTprJfDgSB3/lv5jJZ8FX3hqPyXWhe+gvS5ARMBJ242PM+VNz/ctNj//eA==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm64": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.1.tgz",
"integrity": "sha512-W9//kCrh/6in9rWIBdKaMtuTTzNj6jSeG/haWBADqLLa9P8O5YSRDzgD5y9QBok4AYlzS6ARHifAb75V6G670Q==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ia32": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.1.tgz",
"integrity": "sha512-VIUV4z8GD8rtSVMfAj1aXFahsi/+tcoXXNYmXgzISL+KB381vbSTNdeZHHHIYqFyXcoEhu9n5cT+05tRv13rlw==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-loong64": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.1.tgz",
"integrity": "sha512-l4rfiiJRN7sTNI//ff65zJ9z8U+k6zcCg0LALU5iEWzY+a1mVZ8iWC1k5EsNKThZ7XCQ6YWtsZ8EWYm7r1UEsg==",
"cpu": [
"loong64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-mips64el": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.1.tgz",
"integrity": "sha512-U0bEuAOLvO/DWFdygTHWY8C067FXz+UbzKgxYhXC0fDieFa0kDIra1FAhsAARRJbvEyso8aAqvPdNxzWuStBnA==",
"cpu": [
"mips64el"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ppc64": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.1.tgz",
"integrity": "sha512-NzdQ/Xwu6vPSf/GkdmRNsOfIeSGnh7muundsWItmBsVpMoNPVpM61qNzAVY3pZ1glzzAxLR40UyYM23eaDDbYQ==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-riscv64": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.1.tgz",
"integrity": "sha512-7zlw8p3IApcsN7mFw0O1Z1PyEk6PlKMu18roImfl3iQHTnr/yAfYv6s4hXPidbDoI2Q0pW+5xeoM4eTCC0UdrQ==",
"cpu": [
"riscv64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-s390x": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.1.tgz",
"integrity": "sha512-cGj5wli+G+nkVQdZo3+7FDKC25Uh4ZVwOAK6A06Hsvgr8WqBBuOy/1s+PUEd/6Je+vjfm6stX0kmib5b/O2Ykw==",
"cpu": [
"s390x"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-x64": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.1.tgz",
"integrity": "sha512-z3H/HYI9MM0HTv3hQZ81f+AKb+yEoCRlUby1F80vbQ5XdzEMyY/9iNlAmhqiBKw4MJXwfgsh7ERGEOhrM1niMA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-arm64": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.1.tgz",
"integrity": "sha512-wzC24DxAvk8Em01YmVXyjl96Mr+ecTPyOuADAvjGg+fyBpGmxmcr2E5ttf7Im8D0sXZihpxzO1isus8MdjMCXQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-x64": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.1.tgz",
"integrity": "sha512-1YQ8ybGi2yIXswu6eNzJsrYIGFpnlzEWRl6iR5gMgmsrR0FcNoV1m9k9sc3PuP5rUBLshOZylc9nqSgymI+TYg==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-arm64": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.1.tgz",
"integrity": "sha512-5Z+DzLCrq5wmU7RDaMDe2DVXMRm2tTDvX2KU14JJVBN2CT/qov7XVix85QoJqHltpvAOZUAc3ndU56HSMWrv8g==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-x64": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.1.tgz",
"integrity": "sha512-Q73ENzIdPF5jap4wqLtsfh8YbYSZ8Q0wnxplOlZUOyZy7B4ZKW8DXGWgTCZmF8VWD7Tciwv5F4NsRf6vYlZtqg==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openharmony-arm64": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.1.tgz",
"integrity": "sha512-ajbHrGM/XiK+sXM0JzEbJAen+0E+JMQZ2l4RR4VFwvV9JEERx+oxtgkpoKv1SevhjavK2z2ReHk32pjzktWbGg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openharmony"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/sunos-x64": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.1.tgz",
"integrity": "sha512-IPUW+y4VIjuDVn+OMzHc5FV4GubIwPnsz6ubkvN8cuhEqH81NovB53IUlrlBkPMEPxvNnf79MGBoz8rZ2iW8HA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"sunos"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-arm64": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.1.tgz",
"integrity": "sha512-RIVRWiljWA6CdVu8zkWcRmGP7iRRIIwvhDKem8UMBjPql2TXM5PkDVvvrzMtj1V+WFPB4K7zkIGM7VzRtFkjdg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-ia32": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.1.tgz",
"integrity": "sha512-2BR5M8CPbptC1AK5JbJT1fWrHLvejwZidKx3UMSF0ecHMa+smhi16drIrCEggkgviBwLYd5nwrFLSl5Kho96RQ==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-x64": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.1.tgz",
"integrity": "sha512-d5X6RMYv6taIymSk8JBP+nxv8DQAMY6A51GPgusqLdK9wBz5wWIXy1KjTck6HnjE9hqJzJRdk+1p/t5soSbCtw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@noble/ciphers": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-1.3.0.tgz",
"integrity": "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==",
"license": "MIT",
"engines": {
"node": "^14.21.3 || >=16"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@noble/curves": {
"version": "1.9.7",
"resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.7.tgz",
"integrity": "sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw==",
"license": "MIT",
"dependencies": {
"@noble/hashes": "1.8.0"
},
"engines": {
"node": "^14.21.3 || >=16"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@noble/hashes": {
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz",
"integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==",
"license": "MIT",
"engines": {
"node": "^14.21.3 || >=16"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@sendspin/sendspin-js": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/@sendspin/sendspin-js/-/sendspin-js-5.0.0.tgz",
"integrity": "sha512-yRRjPsz6TyR1GzRYO7ur7oAzwZ11tELK1PEp6Ci7fscXOI0JdtP6BbwPhw+/CR0TWQxu/VwtVPtXT9SH/xhzFw==",
"license": "Apache-2.0",
"dependencies": {
"@noble/ciphers": "^1.2.1",
"@noble/curves": "^1.8.1",
"@noble/hashes": "^1.7.1",
"opus-encdec": "^0.1.1"
},
"engines": {
"node": ">=16.0.0"
}
},
"node_modules/esbuild": {
"version": "0.27.1",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.1.tgz",
"integrity": "sha512-yY35KZckJJuVVPXpvjgxiCuVEJT67F6zDeVTv4rizyPrfGBUpZQsvmxnN+C371c2esD/hNMjj4tpBhuueLN7aA==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"bin": {
"esbuild": "bin/esbuild"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"@esbuild/aix-ppc64": "0.27.1",
"@esbuild/android-arm": "0.27.1",
"@esbuild/android-arm64": "0.27.1",
"@esbuild/android-x64": "0.27.1",
"@esbuild/darwin-arm64": "0.27.1",
"@esbuild/darwin-x64": "0.27.1",
"@esbuild/freebsd-arm64": "0.27.1",
"@esbuild/freebsd-x64": "0.27.1",
"@esbuild/linux-arm": "0.27.1",
"@esbuild/linux-arm64": "0.27.1",
"@esbuild/linux-ia32": "0.27.1",
"@esbuild/linux-loong64": "0.27.1",
"@esbuild/linux-mips64el": "0.27.1",
"@esbuild/linux-ppc64": "0.27.1",
"@esbuild/linux-riscv64": "0.27.1",
"@esbuild/linux-s390x": "0.27.1",
"@esbuild/linux-x64": "0.27.1",
"@esbuild/netbsd-arm64": "0.27.1",
"@esbuild/netbsd-x64": "0.27.1",
"@esbuild/openbsd-arm64": "0.27.1",
"@esbuild/openbsd-x64": "0.27.1",
"@esbuild/openharmony-arm64": "0.27.1",
"@esbuild/sunos-x64": "0.27.1",
"@esbuild/win32-arm64": "0.27.1",
"@esbuild/win32-ia32": "0.27.1",
"@esbuild/win32-x64": "0.27.1"
}
},
"node_modules/fsevents": {
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/opus-encdec": {
"version": "0.1.1",
"resolved": "https://registry.npmjs.org/opus-encdec/-/opus-encdec-0.1.1.tgz",
"integrity": "sha512-TDzyGqYqrwn5UEUNaLsfLGu8Ma+HRNrgLYj7Vx5wfTnafAA21G6Bnm/qTIa3orQi/yZPZYmkdpO/gez4nfA1Rw==",
"license": "MIT"
},
"node_modules/playwright": {
"version": "1.57.0",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.57.0.tgz",
"integrity": "sha512-ilYQj1s8sr2ppEJ2YVadYBN0Mb3mdo9J0wQ+UuDhzYqURwSoW4n1Xs5vs7ORwgDGmyEh33tRMeS8KhdkMoLXQw==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright-core": "1.57.0"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"fsevents": "2.3.2"
}
},
"node_modules/playwright-core": {
"version": "1.57.0",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.57.0.tgz",
"integrity": "sha512-agTcKlMw/mjBWOnD6kFZttAAGHgi/Nw0CZ2o6JqWSbMlI219lAFLZZCyqByTsvVAJq5XA5H8cA6PrvBRpBWEuQ==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
},
"engines": {
"node": ">=18"
}
}
}
}
+31
View File
@@ -0,0 +1,31 @@
{
"name": "adaptive-music",
"version": "0.5.0",
"private": true,
"type": "module",
"license": "MIT",
"engines": {
"node": ">=24.23.0"
},
"scripts": {
"test": "node --test tests/js/*.test.mjs",
"package:module": "python3 scripts/package_module.py",
"gateway:dev": "node gateway/run-development.mjs",
"build:vendor": "node scripts/build_sendspin.mjs",
"release": "python3 scripts/release.py",
"test:browser-audio": "node scripts/measure_browser_audio.mjs"
},
"dependencies": {
"@sendspin/sendspin-js": "5.0.0"
},
"devDependencies": {
"esbuild": "0.27.1",
"playwright": "1.57.0"
},
"overrides": {
"@noble/ciphers": "1.3.0",
"@noble/curves": "1.9.7",
"@noble/hashes": "1.8.0",
"opus-encdec": "0.1.1"
}
}
+52
View File
@@ -0,0 +1,52 @@
"""Offline tracked/unignored-file guardrails; not a complete secret scanner."""
from __future__ import annotations
import ipaddress
from pathlib import Path
import re
import subprocess
ROOT = Path(__file__).resolve().parents[1]
REQUIRED = ('AGENTS.md', 'ARCHITECTURE.md', 'PROGRESS.md', 'TESTING.md',
'SECURITY.md', 'THIRD-PARTY-NOTICES', '.gitignore')
def findings(name: str, data: str) -> list[str]:
issues = []
if name.startswith('.local/') or Path(name).name.startswith('.env'):
issues.append('private configuration file included')
for candidate in re.findall(r'(?<![\w.])(?:\d{1,3}\.){3}\d{1,3}(?![\w.])', data):
try:
address = ipaddress.ip_address(candidate)
except ValueError:
continue
if address.is_private and not address.is_loopback:
issues.append('private IP address included')
if re.search(r'-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----', data):
issues.append('private key material included')
if re.search(r'https?://[^\s/@]+:[^\s/@]+@', data):
issues.append('URL credentials included')
return sorted(set(issues))
def audit() -> list[str]:
errors = [f'missing {name}' for name in REQUIRED if not (ROOT / name).is_file()]
paths = subprocess.check_output(
['git', 'ls-files', '-z', '--cached', '--others', '--exclude-standard'],
cwd=ROOT).decode().split('\0')
for name in sorted(set(filter(None, paths))):
path = ROOT / name
if path.is_file():
errors.extend(f'{name}: {reason}' for reason in findings(
name, path.read_text(errors='replace')))
notices = (ROOT / 'THIRD-PARTY-NOTICES').read_text()
for credit in ('CheddahBoxMB', '3 Death Saves', 'Furyspark', 'Tyler', 'Apache-2.0'):
if credit not in notices:
errors.append(f'missing attribution: {credit}')
return errors
if __name__ == '__main__':
problems = audit()
print('\n'.join(problems) if problems else 'PASS: repository privacy/attribution guardrails')
raise SystemExit(bool(problems))
+16
View File
@@ -0,0 +1,16 @@
// Rebuild only with npm ci --ignore-scripts from the audited lock. Releases use committed output.
import {build} from 'esbuild';
import {readFile,writeFile,copyFile,mkdir} from 'node:fs/promises';
import {createHash} from 'node:crypto';
await mkdir('vendor',{recursive:true});await mkdir('licenses/vendor',{recursive:true});
const result=await build({stdin:{contents:"export {SendspinCore,SendspinDecoder,loadSendspinClientIdentity} from '@sendspin/sendspin-js';",resolveDir:process.cwd()},bundle:true,format:'esm',platform:'browser',target:'es2022',minify:true,legalComments:'eof',write:false,metafile:true,
plugins:[{name:'pcm-only-no-optional-codec',setup(builder){builder.onResolve({filter:/^opus-encdec\//},()=>({path:'disabled-codec',namespace:'pcm-only'}));builder.onLoad({filter:/.*/,namespace:'pcm-only'},()=>({contents:"throw new Error('Optional Opus fallback is not distributed; negotiate PCM'); export default undefined;",loader:'js'}));}}]});
const banner='// @sendspin/sendspin-js 5.0.0 (Apache-2.0), bundled with audited noble MIT dependencies.\n// Modification: optional opus-encdec decoder imports disabled; this build negotiates PCM only.\n// See licenses/vendor and THIRD-PARTY-NOTICES. No source maps or remote imports.\n';
const bytes=banner+result.outputFiles[0].text;await writeFile('vendor/sendspin-5.0.0.mjs',bytes);
const licenses=[['@sendspin/sendspin-js','LICENSE'],['@noble/ciphers','LICENSE'],['@noble/curves','LICENSE'],['@noble/hashes','LICENSE']];
for(const [name,file]of licenses)await copyFile(`node_modules/${name}/${file}`,`licenses/vendor/${name.replace(/[@/]/g,'-')}.txt`);
const lock=JSON.parse(await readFile('package-lock.json','utf8'));
const provenance={sdk:'@sendspin/sendspin-js',version:'5.0.0',sha256:createHash('sha256').update(bytes).digest('hex'),build:'scripts/build_sendspin.mjs',pcm_only:true,optional_opus_fallback_distributed:false,
packages:licenses.map(([name])=>({name,version:lock.packages['node_modules/'+name].version,integrity:lock.packages['node_modules/'+name].integrity})),input_files:Object.keys(result.metafile.inputs).filter(p=>p.startsWith('node_modules/'))};
await writeFile('vendor/provenance.json',JSON.stringify(provenance,null,2)+'\n');
console.log('Built pinned PCM-only official SDK bundle and copied notices.');
+32
View File
@@ -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));}
+26
View File
@@ -0,0 +1,26 @@
// Authorized reads only: browser-safe client -> loopback companion -> dedicated live MA.
import {readFile,writeFile} from 'node:fs/promises';
import {liveClient} from './live_ma_preflight.mjs';
import {GatewayControl} from '../gateway/control.mjs';
import {DevelopmentService} from '../gateway/development-service.mjs';
import {startDevelopmentHTTP} from '../gateway/development-http.mjs';
import {GatewayClient} from '../src/providers/ma/remote.mjs';
const origin='https://foundry.example.test';let server,browser;
try{
const {client,catalogKey}=await liveClient();
const campaign='read-only-local',session='read-only-session';
const control=new GatewayControl({campaigns:{[campaign]:{client}},origin});
const token=control.mint({campaign,session,role:'controller'});
const service=new DevelopmentService({control,campaign,session,client,snapshotKey:catalogKey,playbackEnabled:false});
server=await startDevelopmentHTTP({service,origin});const wire=[];
browser=new GatewayClient({origin,fetchImpl:async(path,options)=>{const response=await fetch(server.url+path.replace('/adaptive-music-gateway',''),{...options,headers:{...options.headers,Origin:origin}});wire.push(await response.clone().text());return response;}});
const status=await browser.connect({token,campaign,session});
const maToken=(await readFile('.local/ma-token','utf8')).trim(),environment=JSON.parse(await readFile('.local/environment.json','utf8')),prior=JSON.parse(await readFile('.local/ma-readonly-results.json','utf8'));
const report={checked_at:new Date().toISOString(),evidence_class:'live MA reads through local companion and browser-safe client; no real Foundry browser',target:status.target,
playlists:browser.catalog.filter(c=>c.kind==='playlist').length,radios:browser.catalog.filter(c=>c.kind==='radio').length,
browser_payloads_private:!wire.join('').includes(maToken)&&!wire.join('').includes(environment.ma_url)&&!wire.join('').includes(prior.me.player_filter[0]),
playback_enabled:status.playbackEnabled,mutations_sent:0,foundry_verified:false,tls_verified:false};
await writeFile('evidence/connected-ma-readonly.json',JSON.stringify(report,null,2)+'\n');console.log(JSON.stringify(report,null,2));
if(report.target!=='verified'||!report.browser_payloads_private)process.exitCode=1;
}catch(error){console.error('Connected catalog check failed:',error.code??'unavailable');process.exitCode=1;}
finally{await browser?.disconnect();await server?.close();}
+59
View File
@@ -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))));}
+30
View File
@@ -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();}
+288
View File
@@ -0,0 +1,288 @@
// Browser diagnostics on the actual private HTTPS hosts. Records metadata only.
import {readFile, stat, writeFile} from 'node:fs/promises';
import {lookup} from 'node:dns/promises';
import {isIP} from 'node:net';
import {resolve} from 'node:path';
import {probeWebSockets} from '../src/providers/ma/diagnostics.mjs';
const report = {at: new Date().toISOString(), scope: 'private Nginx HTTPS route', checks: {}};
const playback = process.argv.includes('--playback');
const layoutOnly = process.argv.includes('--layout-only');
const loggedIn = playback || layoutOnly || process.argv.includes('--logged-in');
const engine = process.argv.includes('--firefox') ? 'firefox' : 'chromium';
const previewModule = process.argv.includes('--preview-module');
const expect = (ok, code) => { if (!ok) throw new Error(code); };
async function privateJSON(name) {
const file = `.local/${name}.json`;
expect(((await stat(file)).mode & 0o777) === 0o600, 'private-file-mode');
return JSON.parse(await readFile(file, 'utf8'));
}
function httpsOrigin(value) {
const url = new URL(value);
expect(url.protocol === 'https:' && !url.username && !url.password && url.pathname === '/' &&
!url.search && !url.hash && (!url.port || url.port === '443') &&
/^[a-z0-9.-]+$/i.test(url.hostname) && !isIP(url.hostname), 'invalid-https-origin');
return url;
}
async function verifyPrivateResponse(response, origin, proxyIP) {
expect(response && new URL(response.url()).origin === origin, 'unexpected-navigation-origin');
expect((await response.serverAddr())?.ipAddress === proxyIP, 'unexpected-server-address');
expect(await response.securityDetails(), 'missing-tls-details');
}
async function openPrivatePage(page, url, proxyIP) {
const response = await page.goto(url.href, {waitUntil: 'domcontentloaded', timeout: 30000});
await verifyPrivateResponse(response, url.origin, proxyIP);
return response;
}
async function retainBrowserWebSocket(page) {
await page.addInitScript(() => {
Object.defineProperty(window, '__adaptiveMusicProbeNativeSocket', {value: window.WebSocket});
});
}
async function collectTransport(page, response, ma) {
const headers = await response.allHeaders();
const session = engine === 'chromium' ? await page.context().newCDPSession(page) : null;
const requests = new Map();
const socketResults = [];
const failedRequests = [];
const policyIssues = [];
session?.on('Network.webSocketCreated', ({requestId, url}) => {
for (const path of ['/ws', '/sendspin']) {
if (url === `wss://${ma.host}${path}`) requests.set(requestId, path);
}
});
session?.on('Network.webSocketHandshakeResponseReceived', ({requestId, response}) => {
if (requests.has(requestId)) socketResults.push({path: requests.get(requestId), httpStatus: response.status});
});
session?.on('Network.loadingFailed', ({requestId, errorText, blockedReason}) => {
if (!requests.has(requestId)) return;
const error = /^net::ERR_[A-Z0-9_]+$/.test(errorText) ? errorText : null;
failedRequests.push({path: requests.get(requestId), error, blockedReason: blockedReason ?? null});
});
session?.on('Network.webSocketFrameError', ({requestId, errorMessage}) => {
if (!requests.has(requestId)) return;
const status = errorMessage?.match(/Unexpected response code: (\d{3})/);
const error = errorMessage?.match(/\bnet::ERR_[A-Z0-9_]+\b/);
if (status || error) failedRequests.push({path: requests.get(requestId), httpStatus: status ? Number(status[1]) : null, error: error?.[0] ?? null});
});
session?.on('Audits.issueAdded', ({issue}) => {
const detail = issue.details?.corsIssueDetails ?? issue.details?.contentSecurityPolicyIssueDetails;
const url = detail?.request?.url ?? detail?.blockedURL;
if (!URL.canParse(url) || ![ma.origin, `wss://${ma.host}`].includes(new URL(url).origin)) return;
policyIssues.push({code: issue.code, reason: detail.corsErrorStatus?.corsError ?? detail.contentSecurityPolicyViolationType});
});
try {
await session?.send('Network.enable');
await session?.send('Audits.enable');
const details = {
pageStatus: response.status(),
privatePeerVerified: true,
cspHeaderPresent: Boolean(headers['content-security-policy']),
reportOnlyCspHeaderPresent: Boolean(headers['content-security-policy-report-only']),
cspMetaPresent: await page.locator('meta[http-equiv="Content-Security-Policy" i]').count() > 0,
secureContext: await page.evaluate(() => globalThis.isSecureContext),
pageReplacesWebSocket: await page.evaluate(() => window.WebSocket !== window.__adaptiveMusicProbeNativeSocket),
upgrades: await page.evaluate(probeWebSockets, ma.origin),
handshakeReplies: socketResults,
failedRequests,
policyIssues,
};
if (details.pageReplacesWebSocket) {
details.nativeSendspinUpgrade = await page.evaluate(host => new Promise(resolve => {
const socket = new window.__adaptiveMusicProbeNativeSocket(`wss://${host}/sendspin`);
const timer = setTimeout(() => finish('upgrade-timeout'), 5000);
function finish(code) {
clearTimeout(timer);
socket.onopen = socket.onerror = socket.onclose = null;
socket.close();
resolve(code);
}
socket.onopen = () => finish('upgrade-ok');
socket.onerror = socket.onclose = () => finish('upgrade-failed');
}), ma.host);
}
return details;
} finally {
await session?.detach();
}
}
async function joinWorld(browser, foundry, proxyIP, world, {name, gm, password}, progress) {
expect(typeof name === 'string' && name && typeof password === 'string' && typeof gm === 'boolean', 'invalid-test-account');
const page = await browser.newPage({viewport: {width: 1440, height: 1000}, screen: {width: 1440, height: 1000}});
if (previewModule) {
const prefix='/modules/adaptive-music/';
const root=resolve(import.meta.dirname,'..');
await page.context().route(`${foundry.origin}${prefix}**`,async route=>{
const file=new URL(route.request().url()).pathname.slice(prefix.length);
if(!/^(src\/.+\.mjs|styles\/.+\.css|vendor\/.+\.mjs)$/.test(file)||file.split('/').includes('..'))return route.continue();
await route.fulfill({path:resolve(root,file),contentType:file.endsWith('.css')?'text/css':'text/javascript'});
});
}
page.setDefaultTimeout(20000);
await retainBrowserWebSocket(page);
if (playback) await page.addInitScript(() => {
const peers = [];
const contexts = [];
const analysers = [];
const listenerAnalysers = [];
window.__adaptiveMusicTestAudio = {contexts, analysers, listenerAnalysers};
const createStream = AudioContext.prototype.createMediaStreamDestination;
AudioContext.prototype.createMediaStreamDestination = function () {
const destination = createStream.call(this);
contexts.push({context: this, destination});
return destination;
};
const createAnalyser = AudioContext.prototype.createAnalyser;
AudioContext.prototype.createAnalyser = function () {
const analyser = createAnalyser.call(this);
analysers.push(analyser);
return analyser;
};
const createSource = AudioContext.prototype.createMediaStreamSource;
AudioContext.prototype.createMediaStreamSource = function (stream) {
const source = createSource.call(this, stream);
const analyser = createAnalyser.call(this);
source.connect(analyser);
listenerAnalysers.push({context: this, stream, analyser});
return source;
};
window.__adaptiveMusicTestPeers = peers;
window.RTCPeerConnection = new Proxy(window.RTCPeerConnection, {
construct(target, args, newTarget) {
const peer = Reflect.construct(target, args, newTarget);
peers.push(peer);
return peer;
},
});
});
const url = new URL('/join', foundry);
progress('join-page');
await openPrivatePage(page, url, proxyIP);
await page.getByText(world.title, {exact: true}).first().waitFor({timeout: 30000});
expect(new URL(page.url()).pathname === '/join', 'unexpected-join-path');
progress('select-account');
const form = page.locator('#join-game-form');
const users = form.locator('select[name="userId"]');
await users.waitFor({state: 'visible'});
const option = await users.evaluate((select, name) => {
const user = [...select.options].find(option => option.label === name);
return user ? {value: user.value, disabled: user.disabled} : null;
}, name);
expect(option?.value, 'development-account-not-found');
expect(!option.disabled, 'development-account-unavailable');
await users.selectOption({value: option.value});
await form.locator('input[type="password"]').fill(password);
progress('submit-join');
const navigation = page.waitForResponse(response => response.request().isNavigationRequest() &&
response.request().frame() === page.mainFrame() && new URL(response.url()).pathname === '/game');
const [response] = await Promise.all([navigation, form.locator('[type="submit"]').click()]);
await verifyPrivateResponse(response, foundry.origin, proxyIP);
progress('wait-for-game-ready');
await page.bringToFront();
await page.waitForFunction(() => globalThis.game?.ready && game.socket?.connected, undefined, {polling: 250, timeout: 55000});
const state = await page.evaluate(({id, title, account}) => ({
worldMatches: game.world.id === id && game.world.title === title,
accountMatches: game.user.name === account,
gm: game.user.isGM,
foundryVersion: game.version,
system: game.system.id,
otherActiveGMs: game.users.filter(user => user.id !== game.user.id && user.active && user.isGM).length,
adaptiveMusicActive: game.modules.get('adaptive-music')?.active === true,
adaptiveMusicVersion: game.modules.get('adaptive-music')?.version ?? null,
}), {id: world.id, title: world.title, account: name});
expect(state.worldMatches && state.accountMatches && state.gm === gm, 'unexpected-world-account-or-role');
expect(state.foundryVersion === '14.371' && state.system === 'dnd5e', 'unexpected-foundry-or-system');
expect(state.otherActiveGMs === (state.gm ? 0 : 1), 'unexpected-active-gm-count');
expect(state.adaptiveMusicActive, 'adaptive-music-inactive');
// Keep the unattended canvases from saturating the shared headless renderer.
state.canvasTickerPaused = await page.evaluate(() => {
const ticker = globalThis.canvas?.app?.ticker;
if (!ticker?.started) return false;
ticker.stop();
return true;
});
return {page, response, state};
}
let browser, stage = 'configuration';
try {
const config = await privateJSON('live-environment');
const foundry = httpsOrigin(config.foundry), ma = httpsOrigin(config.ma);
const proxyIP = config.proxy_ip;
expect(isIP(proxyIP) === 4 && foundry.host !== ma.host, 'invalid-private-route');
const playwright = await import(process.env.AM_PLAYWRIGHT_MODULE ?? 'playwright');
stage = 'browser-launch';
if (engine === 'firefox') {
for (const host of [foundry.hostname, ma.hostname]) {
const answers = await lookup(host, {all: true});
expect(answers.length && answers.every(answer => answer.address === proxyIP), 'private-hostname-resolution-required');
}
}
browser = await playwright[engine].launch(engine === 'chromium' ? {args: ['--no-sandbox', '--no-proxy-server',
`--host-resolver-rules=MAP ${foundry.hostname} ${proxyIP}, MAP ${ma.hostname} ${proxyIP}`]} :
{firefoxUserPrefs: {'network.trr.mode': 5, 'network.proxy.type': 0}});
report.engine = engine;
report.browser = browser.version();
report.moduleAssets = previewModule ? 'workspace module assets in the test browser' : 'installed module assets';
for (const [name, origin] of (layoutOnly ? [] : [['foundryAnonymous', foundry], ['maSameOrigin', ma]])) {
stage = name;
const page = await browser.newPage();
await retainBrowserWebSocket(page);
const response = await openPrivatePage(page, origin, proxyIP);
report.checks[name] = await collectTransport(page, response, ma);
await page.context().close();
}
if (loggedIn) {
stage = 'development-world-configuration';
const {world, accounts} = await privateJSON('foundry-development');
expect(typeof world?.id === 'string' && world.id && typeof world.title === 'string' && world.title &&
Array.isArray(accounts) && accounts.length === 3 && accounts.every((account, index) => account?.gm === (index === 0)) &&
new Set(accounts.map(account => account.name)).size === 3, 'invalid-development-world-configuration');
report.accounts = {};
const pages = [];
for (const [index, account] of (layoutOnly ? accounts.slice(0,1) : accounts).entries()) {
const login = index === 0 ? 'gm-login' : `player-${index}-login`;
const {page, response, state} = await joinWorld(browser, foundry, proxyIP, world, account, step => {
stage = `${login}-${step}`;
console.error(`Development world authentication stage: ${stage}`);
});
report.accounts[login] = state;
pages.push(page);
if (index === 0 && !layoutOnly) {
stage = 'foundryLoggedIn';
report.checks[stage] = await collectTransport(page, response, ma);
}
}
if(layoutOnly){
stage='foundry-graphical-layout';
const {checkFoundryLayout}=await import('./live_foundry_playback.mjs');
report.layout=await checkFoundryLayout(pages[0],ma);
}
if (playback) {
stage = 'installed-world-playback';
const {checkFoundryPlayback} = await import('./live_foundry_playback.mjs');
report.playback = {};
await checkFoundryPlayback({pages, ma, world, report: report.playback});
}
}
report.completed = true;
} catch (error) {
report.completed = false;
report.failure = {stage, code: /^[a-z][a-z-]+$/.test(error.message) ? error.message : error.code ?? error.name};
process.exitCode = 1;
} finally {
await browser?.close();
const resultName=previewModule?`foundry-am006-preview-${engine}`:`foundry-private-route-${engine}`;
await writeFile(`.local/${resultName}.json`, JSON.stringify(report, null, 2) + '\n', {mode: 0o600});
console.log(JSON.stringify(report, null, 2));
}
+13
View File
@@ -0,0 +1,13 @@
// Authorized target/catalog reads only; compare two independent adapters for restart identity.
import { writeFile } from 'node:fs/promises';
import { liveClient } from './live_ma_preflight.mjs';
try {
const {client}=await liveClient();const target=await client.verifyTarget();const catalog=await client.catalog();
const restarted=await liveClient();const after=await restarted.client.catalog();
const ids=items=>items.map(c=>c.id).sort().join(',');
const report={checked_at:new Date().toISOString(),target,playlists:catalog.filter(c=>c.kind==='playlist').length,
radios:catalog.filter(c=>c.kind==='radio').length,sanitized:catalog.every(c=>Object.keys(c).sort().join(',')==='id,kind,name,provider'),
independent_adapter_ids_match:ids(catalog)===ids(after)};
await writeFile('evidence/ma-adapter.json',JSON.stringify(report,null,2)+'\n');console.log(JSON.stringify(report,null,2));
if(!report.independent_adapter_ids_match)process.exitCode=1;
}catch{console.error('MA adapter verification failed (details withheld)');process.exitCode=1;}
@@ -0,0 +1,15 @@
// Authorized live read-only preflight. No Sendspin connection, pairing, new identity or playback.
import {readFile,writeFile,access} from 'node:fs/promises';
import {liveClient} from './live_ma_preflight.mjs';
import {gmAccessPolicy} from '../src/audio/gm-host.mjs';
const environment=JSON.parse(await readFile('.local/environment.json','utf8'));
const previous=JSON.parse(await readFile('.local/ma-readonly-results.json','utf8'));
const {client}=await liveClient();await client.verifyTarget();const queue=await client.queueState();
let policy='allowed';try{gmAccessPolicy(environment.ma_url,'https://foundry.example.test/');}catch(error){policy=error.code??'denied';}
let identityProfilePresent=false;try{await access('.local/gm-profile.json');identityProfilePresent=true;}catch{}
const result={checked_at:new Date().toISOString(),evidence_class:'live MA target/queue reads plus browser-policy/source checks; no live browser-to-MA connection',
target_verified:true,queue_state:queue.state,queue_items:queue.items,target_identity_format_compatible:/^[A-Za-z0-9_-]{43}$/.test(previous.player.player_id),
configured_ma_scheme:new URL(environment.ma_url).protocol,https_foundry_origin_policy:policy,gm_identity_profile_present:identityProfilePresent,sendspin_connections:0,identities_created:0,mutations_sent:0,
websocket_auth_log_safety:'not verified live; source logs raw inbound auth at VERBOSE, explicit operator review required',live_websocket_auth_attempts:0,
actual_ma_audio:'blocked pending existing DEV private identity, secure private browser access and approved synthetic ingestion'};
await writeFile('evidence/module-only-prerequisites.json',JSON.stringify(result,null,2)+'\n');console.log(JSON.stringify(result,null,2));
+37
View File
@@ -0,0 +1,37 @@
// Offline Chromium UI fixture. No Foundry, MA, Git host, token or production access.
import {createServer} from 'node:http';
import {readFile,mkdir} from 'node:fs/promises';
import {resolve,extname} from 'node:path';
import {chromium} from 'playwright';
import assert from 'node:assert/strict';
const root=resolve(import.meta.dirname,'..');
const server=createServer(async(req,res)=>{try{const path=resolve(root,'.'+new URL(req.url,'http://localhost').pathname);if(!path.startsWith(root+'/'))throw Error();const data=await readFile(path);res.setHeader('Content-Type',extname(path)==='.mjs'?'text/javascript':extname(path)==='.css'?'text/css':'text/html');res.end(data);}catch{res.writeHead(404);res.end();}});
await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));let browser;
try{
browser=await chromium.launch({headless:true,args:['--no-sandbox']});const page=await browser.newPage({viewport:{width:1000,height:1000}}),errors=[];page.on('pageerror',e=>errors.push(e.message));
await page.goto(`http://127.0.0.1:${server.address().port}/tests/browser/setup.html`);await page.waitForFunction(()=>window.ready);
assert.equal(await page.getByText('Connect optional companion',{exact:true}).count(),0);
for(const width of [380,640,1000]){
await page.setViewportSize({width,height:1000});
assert.equal(await page.locator('.adaptive-music-setup').evaluate(el=>el.scrollWidth<=el.clientWidth+1),true,'setup must fit narrow window');
assert.equal(await page.getByLabel('ICE server URL').isVisible(),false,'advanced fields must remain hidden');
}
await page.getByLabel('Music Assistant server address').fill('https://ma.example.test');await page.getByLabel('Private GM access token').fill('fixture-token');
await page.getByRole('button',{name:'Connect',exact:true}).click();await page.getByText('Campaign audio connected.',{exact:false}).waitFor();
assert.equal(await page.getByLabel('Private GM access token').inputValue(),'');
await page.getByRole('button',{name:'Choose scene music',exact:true}).click();
const panel=page.locator('fieldset').filter({has:page.locator('legend',{hasText:'Scene music'})});
await panel.locator('select').nth(0).selectOption('["ma","ambient"]');await panel.locator('select').nth(1).selectOption('["ma","combat"]');await panel.getByRole('button',{name:'Save assignments'}).click();
assert.deepEqual(await page.evaluate(()=>window.saved.ambient),{provider:'ma',id:'ambient'});assert.deepEqual(await page.evaluate(()=>window.saved.combat),{provider:'ma',id:'combat'});
await page.getByRole('button',{name:'Go to Playback',exact:true}).click();await page.getByRole('heading',{name:'Forest at night'}).waitFor();
await page.getByText('2 connected listeners',{exact:true}).waitFor();
await page.getByRole('button',{name:'Pause',exact:true}).click();await page.getByRole('button',{name:'Resume',exact:true}).click();
await page.getByLabel('Playback position').press('ArrowRight');await page.getByText('0:13 / 1:30',{exact:true}).waitFor();
await page.getByLabel('Campaign volume').press('ArrowLeft');
assert.equal(await page.getByLabel('Campaign volume').inputValue(),'99');
await page.getByRole('button',{name:'Stop playback',exact:true}).click();await page.getByText('Stopped',{exact:true}).waitFor();
assert.deepEqual(await page.evaluate(()=>window.controlActions),['pause','resume','seek','stop']);
await mkdir(resolve(root,'dist/previews'),{recursive:true});await page.screenshot({path:resolve(root,'dist/previews/am006-setup.png'),fullPage:true});
await page.evaluate(()=>window.listener());assert.equal(await page.locator('input').count(),0);await page.getByRole('button',{name:'Enable Audio'}).click();assert.equal(await page.evaluate(()=>window.activated),true);assert.deepEqual(errors,[]);
console.log(JSON.stringify({status:'pass',browser:browser.version(),scope:'offline DOM fixture; no live Foundry or MA',checks:['380/640/1000px layout','three setup tabs','private field clearing','catalog selectors','ambient/combat save','advanced controls hidden','track and listeners','pause/resume/seek/volume/stop','listener activation'],pageErrors:errors},null,2));
}finally{await browser?.close();await new Promise(resolve=>server.close(resolve));}
+15
View File
@@ -0,0 +1,15 @@
import {readFile,writeFile} from 'node:fs/promises';
import {liveClient} from './live_ma_preflight.mjs';
export async function syntheticSequences(){
const source=JSON.parse(await readFile('.local/fixture-origin.json','utf8'));
return Object.fromEntries(Object.entries(source.sequences).map(([kind,files])=>[`synthetic-${kind}`,files.map(name=>`builtin://track/${source.base_url}/${name}`)]));
}
try{
const {client}=await liveClient(await syntheticSequences());await client.verifyTarget();
const tracks=await client.inspectSynthetic();
const report={checked_at:new Date().toISOString(),synthetic_ingestion:true,tracks:tracks.length,durations:tracks.map(t=>t.duration),playback_mutations:0};
await writeFile('evidence/synthetic-ingestion.json',JSON.stringify(report,null,2)+'\n');console.log(JSON.stringify(report));
}catch(error){
const report={checked_at:new Date().toISOString(),synthetic_ingestion:false,error:error.code??'unavailable',playback_mutations:0};
await writeFile('evidence/synthetic-ingestion.json',JSON.stringify(report,null,2)+'\n');console.log(JSON.stringify(report));process.exitCode=1;
}
+12
View File
@@ -0,0 +1,12 @@
import {readFile,writeFile} from 'node:fs/promises';
import {createHash} from 'node:crypto';
import {pcmFixtureFrames} from '../gateway/pcm-fixture.mjs';
const manifest=JSON.parse(await readFile('.local/synthetic-audio/manifest.json','utf8'));
const result={checked_at:new Date().toISOString(),evidence_class:'local generated audio decoding',tracks:0,frames:0,duration_seconds:0,hashes_match:true};
for(const tracks of Object.values(manifest.sequences))for(const track of tracks){
const bytes=await readFile(`.local/synthetic-audio/${track.file}`);
if(createHash('sha256').update(bytes).digest('hex')!==track.sha256)throw Error('fixture mismatch');
let frames=0;for(const frame of pcmFixtureFrames(bytes)){if(frame.length!==1920)throw Error('frame mismatch');frames++;}
if(frames!==4500)throw Error('duration mismatch');result.tracks++;result.frames+=frames;result.duration_seconds+=frames*.02;
}
await writeFile('evidence/synthetic-pipeline.json',JSON.stringify(result,null,2)+'\n');console.log(JSON.stringify(result));
+12
View File
@@ -0,0 +1,12 @@
"""Runner-neutral artifact generation; no publish/upload/git-host API calls."""
import os
from pathlib import Path
import json
from release import ROOT,DEFAULT_REPOSITORY,build_release
manifest=json.loads((ROOT/'module.json').read_text())
ref=os.environ.get('GITHUB_REF_NAME') or os.environ.get('GITEA_REF_NAME','')
if ref.startswith('v') and ref!='v'+manifest['version']:raise SystemExit('tag/manifest version mismatch')
repository=os.environ.get('RELEASE_REPOSITORY')
if not repository and os.environ.get('GITHUB_SERVER_URL')=='https://github.com' and os.environ.get('GITHUB_REPOSITORY'):repository='https://github.com/'+os.environ['GITHUB_REPOSITORY']
repository=repository or DEFAULT_REPOSITORY
print(build_release(repository))
+18
View File
@@ -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));
+39
View File
@@ -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));
+458
View File
@@ -0,0 +1,458 @@
// Exercises the installed module through the authorized development world.
import {randomUUID} from 'node:crypto';
import {setTimeout as delay} from 'node:timers/promises';
import {loadMAToken} from '../gateway/private-config.mjs';
const moduleId = 'adaptive-music';
const check = (value, code) => { if (!value) throw new Error(code); };
async function until(read, accept, code, timeout = 25000) {
const end = Date.now() + timeout;
do {
const result = await read();
if (accept(result)) return result;
await delay(300);
} while (Date.now() < end);
throw new Error(code);
}
function observeMA(page, ma) {
const commands = [];
let sendspinAuthenticated = false;
const json = event => {
if (typeof event.payload !== 'string') return null;
try { return JSON.parse(event.payload); } catch { return null; }
};
page.on('websocket', socket => {
if (socket.url() === `wss://${ma.host}/sendspin`) {
socket.on('framereceived', event => {
if (json(event)?.type === 'auth_ok') sendspinAuthenticated = true;
});
}
if (socket.url() !== `wss://${ma.host}/ws`) return;
const pending = new Map();
socket.on('framesent', event => {
const frame = json(event);
if (!frame?.message_id || typeof frame.command !== 'string') return;
const entry = {command: frame.command, args: frame.command.startsWith('player_queues/') ? frame.args : null};
commands.push(entry);
pending.set(frame.message_id, entry);
});
socket.on('framereceived', event => {
const frame = json(event);
const entry = pending.get(frame?.message_id);
if (!entry || frame.partial) return;
pending.delete(frame.message_id);
entry.reply = true;
entry.error = frame.error_code ?? null;
if (entry.command === 'auth') entry.authenticated = frame.result?.authenticated === true;
if (entry.command === 'players/get' && frame.result) entry.player = {id:frame.result.player_id,name:frame.result.name};
if (entry.command === 'player_queues/get' && frame.result) {
const {state, current_index, elapsed_time} = frame.result;
entry.queue = {state, index: current_index, position: elapsed_time};
}
});
});
return {commands, sendspinAuthenticated: () => sendspinAuthenticated};
}
function safeStats(page) {
return page.evaluate(async moduleId => {
const stats = await game.modules.get(moduleId).api.peerStats();
const streams = [...document.querySelectorAll('audio')].map(element => element.srcObject).filter(Boolean);
const rms = (window.__adaptiveMusicTestAudio?.listenerAnalysers ?? []).filter(sensor => streams.includes(sensor.stream))
.reduce((max, {analyser}) => {
const samples = new Float32Array(analyser.fftSize);
analyser.getFloatTimeDomainData(samples);
return Math.max(max, Math.sqrt(samples.reduce((sum, sample) => sum + sample ** 2, 0) / samples.length));
}, 0);
return stats.filter(row => row.type === 'inbound-rtp').reduce((result, row) => ({
rms,
bytes: result.bytes + (row.bytesReceived ?? 0),
energy: result.energy + (row.totalAudioEnergy ?? 0),
samples: result.samples + (row.totalSamplesReceived ?? 0),
}), {rms, bytes: 0, energy: 0, samples: 0});
}, moduleId);
}
async function gmAudioDiagnostics(page, setup) {
await page.evaluate(() => {
Object.defineProperty(navigator.clipboard, 'writeText', {
configurable: true,
value: async text => { window.__adaptiveMusicTestDiagnostics = JSON.parse(text); },
});
});
await setup.getByRole('button', {name: 'Copy connection diagnostics', exact: true}).click({timeout: 3000});
return page.evaluate(() => {
const d = window.__adaptiveMusicTestDiagnostics;
if (!d) return null;
return {
stage: d.stage, state: d.state, audioContext: d.audioContext, decoded: d.decodedFrames,
scheduled: d.scheduledFrames, droppedLate: d.droppedLate, droppedAhead: d.droppedAhead,
signalRMS: d.signalRMS, muted: d.muted, listenerConnections: d.listenerConnections,
volume: Number([...document.querySelectorAll('#adaptive-music-setup input[type="range"]')][0]?.value),
};
});
}
async function openMenu(page, name) {
await page.evaluate(async key => {
const type = game.settings.menus.get(key)?.type;
if (!type) throw Error('missing-installed-module-menu');
const app=new type();
await app.render({force: true});
window.__adaptiveTestWindow=app;
}, `${moduleId}.${name}`);
}
const writes = new Set(['stop', 'clear', 'play_media', 'play_index', 'repeat'].map(action => 'player_queues/' + action));
export async function checkFoundryLayout(page,ma){
await openMenu(page,'setup');
const setup=page.locator('#adaptive-music-setup');
const tabs=setup.getByRole('tab');
check(await tabs.count()===3,'three-foundry-tabs-required');
const resizable=await page.evaluate(()=>window.__adaptiveTestWindow.options.window.resizable);
check(resizable===true,'foundry-window-not-resizable');
const originalWidth=Math.round((await setup.boundingBox()).width);
const layout=[];
for(const width of [originalWidth,380]){
await page.evaluate(width=>window.__adaptiveTestWindow.setPosition({width,height:490}),width);
for(const label of ['Connection','Scene Music','Playback']){
await setup.getByRole('tab',{name:label,exact:true}).click();
const panel=setup.getByRole('tabpanel');
await panel.waitFor({state:'visible'});
const measurements=await panel.evaluate(el=>{
const content=el.closest('.window-content');
const horizontalFit=el.scrollWidth<=el.clientWidth+1&&content.scrollWidth<=content.clientWidth+1;
const nestedScroll=[...content.querySelectorAll('div,section,details,fieldset')].some(node=>['auto','scroll'].includes(getComputedStyle(node).overflowY));
return {horizontalFit,nestedScroll};
});
check(measurements.horizontalFit&&!measurements.nestedScroll,'foundry-layout-overflow');
layout.push({width,tab:label,...measurements});
}
}
await setup.getByRole('tab',{name:'Connection',exact:true}).press('ArrowRight');
check(await setup.getByRole('tabpanel',{name:'Scene Music'}).isVisible(),'tab-keyboard-navigation-failed');
await setup.getByRole('tab',{name:'Connection',exact:true}).click();
const advanced=setup.getByText('Advanced',{exact:true});
check(!await setup.getByLabel('ICE server URL').isVisible(),'advanced-visible-by-default');
await advanced.click();
check(await setup.getByLabel('ICE server URL').isVisible(),'advanced-controls-unreachable');
await advanced.click();
await setup.getByLabel('Music Assistant server address').fill('https://ma.example.test/path');
await setup.getByRole('button',{name:'Connect',exact:true}).click();
await setup.getByRole('alert').filter({hasText:'Enter the MA server origin'}).waitFor();
await setup.getByLabel('Music Assistant server address').fill(ma.origin);
await setup.getByRole('button',{name:'Connect',exact:true}).click();
await setup.getByRole('alert').filter({hasText:'Enter a Music Assistant access token'}).waitFor();
await setup.getByRole('button',{name:'Check browser connection',exact:true}).click();
await setup.getByText('Browser checks complete.',{exact:true}).waitFor();
const routeDiagnostics=await setup.locator('[aria-live="polite"] p').evaluateAll(lines=>lines.map(line=>({
path:line.textContent.startsWith('/ws')?'/ws':'/sendspin',opened:line.textContent.includes('upgrade succeeded'),
})));
check(routeDiagnostics.length===2,'missing-graphical-route-diagnostics');
return {resizable,layout,keyboardTabs:true,advancedCollapsed:true,invalidAddressRejected:true,missingTokenRejected:true,routeDiagnostics};
}
export async function checkFoundryPlayback({pages, ma, world, report}) {
const [gm, ...players] = pages;
const run = randomUUID().slice(0, 8);
const receiverName = `Adaptive Music integration ${run}`;
const fixtureName = `Adaptive Music verification ${run}`;
const setup = gm.locator('#adaptive-music-setup');
const wire = observeMA(gm, ma);
const stage = name => {
report.stage = name;
console.error(`Installed-world playback stage: ${name}`);
};
let baseline, sceneId, combatId, receiver;
const fixture = data => gm.evaluate(async ({world, moduleId, ...data}) => {
if (!game.ready || game.world.id !== world || !game.user.isGM || !game.socket?.connected) throw Error('wrong-development-world');
if (data.action === 'scene') {
const scene = await CONFIG.Scene.documentClass.create({name: data.fixtureName, width: 1200, height: 1000, navigation: false, tokenVision: false});
return scene.id;
}
if (data.action === 'combat') {
const combat = await CONFIG.Combat.documentClass.create({scene: data.sceneId, active: true});
await combat.createEmbeddedDocuments('Combatant', [{name: data.fixtureName, initiative: 12}]);
return combat.id;
}
if (data.action === 'start-combat') {
const combat = game.combats.get(data.combatId);
await combat.startCombat();
return Boolean(combat.started && combat.active);
}
if (data.action === 'delete-combat') return game.combats.get(data.combatId)?.delete().then(() => true);
if (data.action === 'activate-scene') return game.scenes.get(data.sceneId)?.activate().then(() => true);
if (data.action === 'baseline') {
const enabled = game.settings.get(moduleId, 'enabled');
const scene = game.scenes.active?.id ?? null;
if (enabled) {
game.modules.get(moduleId).api.stopDevelopment();
await game.settings.set(moduleId, 'enabled', false);
}
return {enabled, scene};
}
if (data.action === 'cleanup') {
const api = game.modules.get(moduleId).api;
api.stopDevelopment();
await api.closeGMHost();
if (data.combatId) await game.combats.get(data.combatId)?.delete();
if (data.baseline.scene && game.scenes.active?.id !== data.baseline.scene) await game.scenes.get(data.baseline.scene)?.activate();
if (data.sceneId) await game.scenes.get(data.sceneId)?.delete();
if (game.settings.get(moduleId, 'enabled') !== data.baseline.enabled) await game.settings.set(moduleId, 'enabled', data.baseline.enabled);
return (!data.sceneId || !game.scenes.has(data.sceneId)) && (!data.combatId || !game.combats.has(data.combatId)) &&
game.settings.get(moduleId, 'enabled') === data.baseline.enabled;
}
throw Error('unknown-fixture-operation');
}, {world: world.id, moduleId, ...data});
const command = (from, name, predicate = () => true) => until(
() => wire.commands.slice(from).find(entry => entry.command === `player_queues/${name}` && entry.reply && predicate(entry.args)),
Boolean, `ma-${name.replaceAll('_', '-')}-not-observed`, 70000).then(entry => {
if (entry.error !== null) report.upstreamError = {command: entry.command, code: entry.error};
check(entry.error === null, 'ma-queue-command-failed');
return entry;
});
const audio = async () => {
const before = await Promise.all(players.map(safeStats));
try {
return await Promise.all(players.map(async (page, index) => {
const after = await until(() => safeStats(page), value => value.bytes > before[index].bytes &&
(value.energy - before[index].energy > 1e-6 || value.rms > 0.001),
'listener-audio-energy-did-not-increase', 30000);
return {bytesIncreased: true, energyIncrease: after.energy - before[index].energy, playbackRMS: after.rms,
samplesIncreased: after.samples > before[index].samples};
}));
} catch (error) {
report.listenerStatsAtFailure = await Promise.all(players.map(page => safeStats(page).catch(() => null)));
throw error;
}
};
try {
stage('world-readiness');
await gm.waitForFunction(({moduleId, count}) => game.modules.get(moduleId)?.api &&
[...game.users].filter(user => user.active && !user.isGM).length >= count &&
[...game.users].filter(user => user.active && user.isGM).length === 1, {moduleId, count: players.length});
report.publicKeys = await Promise.all(pages.map(page => page.waitForFunction(moduleId => Boolean(game.user.getFlag(moduleId, 'audioPublicKey')?.key), moduleId, {timeout: 8000}).then(() => true, () => false)));
await Promise.all(pages.map(page => page.evaluate(() => {
const tally = {invitationsForMe: 0, invitationEvents: 0, offers: 0, answers: 0, sentInvitations: 0, sentSignals: 0};
window.__adaptiveMusicTestSignaling = tally;
game.socket.on('module.adaptive-music', frame => {
if (frame?.type === 'audio-invite-v1') {
tally.invitationEvents++;
if (frame.to === game.user.id) tally.invitationsForMe++;
}
if (frame?.v === 1 && frame.from === 'listener') tally.offers++;
if (frame?.v === 1 && frame.from === 'gm') tally.answers++;
});
game.socket.onAnyOutgoing?.((event, frame) => {
if (event !== 'module.adaptive-music') return;
if (frame?.type === 'audio-invite-v1') tally.sentInvitations++;
if (frame?.v === 1 && typeof frame.cipher === 'string') tally.sentSignals++;
});
})));
stage('user-document-permissions');
const gmId = await gm.evaluate(() => game.user.id);
const probeFlag = `integrationProbe${run}`;
report.playerCannotWriteGMFlag = await players[0].evaluate(async ({gmId, moduleId, probeFlag}) => {
try { await game.users.get(gmId).setFlag(moduleId, probeFlag, true); return false; }
catch { return true; }
}, {gmId, moduleId, probeFlag});
if (!report.playerCannotWriteGMFlag) await gm.evaluate(({moduleId, probeFlag}) => game.user.unsetFlag(moduleId, probeFlag), {moduleId, probeFlag});
stage('create-test-scene');
baseline = await fixture({action: 'baseline'});
sceneId = await fixture({action: 'scene', fixtureName});
await fixture({action: 'activate-scene', sceneId});
await openMenu(gm, 'setup');
await gm.evaluate(()=>{
window.__adaptiveTestNotifications=[];
const observer=new MutationObserver(()=>{
for(const node of document.querySelectorAll('#notifications .notification')){
const text=node.textContent.trim();
if(text.startsWith('Adaptive Music: ')&&!window.__adaptiveTestNotifications.includes(text))window.__adaptiveTestNotifications.push(text);
}
});
observer.observe(document.body,{childList:true,subtree:true});
});
stage('ma-authentication');
const tabbed=await setup.getByRole('tab',{name:'Connection',exact:true}).count()>0;
await setup.getByLabel('Music Assistant server address').fill(ma.origin);
if(tabbed){
const before=wire.commands.length;
report.advancedInitiallyCollapsed=!await setup.getByLabel('ICE server URL').isVisible();
await setup.getByRole('button',{name:'Connect',exact:true}).click();
await setup.getByRole('alert').filter({hasText:'Enter a Music Assistant access token'}).waitFor();
report.formRejectedMissingTokenWithoutNetwork=wire.commands.length===before;
check(report.formRejectedMissingTokenWithoutNetwork&&report.advancedInitiallyCollapsed,'connection-form-validation-failed');
await setup.getByText('Advanced',{exact:true}).click();
await setup.getByLabel('Dedicated receiver name').fill(receiverName);
await setup.getByText('Advanced',{exact:true}).click();
await setup.getByLabel('Private GM access token').fill(await loadMAToken('.local'));
await setup.getByRole('button',{name:'Connect',exact:true}).click();
await setup.getByText(/^Campaign audio connected\./).waitFor({timeout:50000});
receiver=wire.commands.findLast(entry=>entry.player?.name===receiverName)?.player.id;
check(receiver,'receiver-identity-not-verified');
report.oneClickConnection=true;
await setup.getByRole('button',{name:'Choose scene music'}).click();
}else{
await setup.getByLabel('Private GM access token').fill(await loadMAToken('.local'));
await setup.getByText('Receiver options',{exact:true}).click();
await setup.getByLabel('Dedicated receiver name').fill(receiverName);
await setup.getByRole('button',{name:'Authenticate',exact:true}).click();
const selector=setup.getByLabel('Dedicated campaign receiver');
await selector.locator('option').filter({hasText:receiverName}).waitFor({state:'attached',timeout:25000});
receiver=await selector.inputValue();
await setup.getByRole('button',{name:'Connect audio',exact:true}).click();
}
report.maAPIAuthenticated = wire.commands.some(entry => entry.authenticated);
check(receiver && report.maAPIAuthenticated, 'receiver-identity-not-verified');
stage('dedicated-sendspin-connection');
if(!tabbed)await setup.getByText(/^Campaign audio connected\./).waitFor({timeout: 50000});
report.sendspinAuthenticated = wire.sendspinAuthenticated();
report.accountPairingPassed = wire.commands.some(entry => entry.command === 'sendspin/pair_web_player' && entry.reply && entry.error === null);
check(report.sendspinAuthenticated && report.accountPairingPassed, 'sendspin-pairing-not-observed');
stage('scene-assignments');
const assignments = setup.locator('fieldset[data-adaptive-music="assignments"]').filter({has: gm.locator('legend', {hasText: /^Scene music$/})});
const ambient = assignments.getByLabel('Ambient playlist');
const references = await ambient.locator('option').evaluateAll(options => options.map(option => option.value).filter(value => value.startsWith('["ma",')));
report.catalogChoices = references.length;
check(references.length >= 2, 'insufficient-ma-catalog-choices');
await ambient.selectOption(references[0]);
await assignments.getByLabel('Combat playlist').selectOption(references[1]);
if(tabbed)await assignments.getByLabel('Default boss music').selectOption(references[1]);
await assignments.getByRole('button', {name: 'Save assignments', exact: true}).click();
await assignments.getByText('Assignments saved.', {exact: true}).waitFor();
report.sceneAssignmentVerified=await gm.evaluate(({sceneId,ambient})=>{
const scene=game.scenes.get(sceneId);
return scene?.active===true&&JSON.stringify(['ma',scene.getFlag('adaptive-music','music')?.ambient?.id])===ambient;
},{sceneId,ambient:references[0]});
check(report.sceneAssignmentVerified,'assignment-not-saved-to-active-scene');
stage('activate-listener-audio');
await Promise.all(players.map(async page => {
await openMenu(page, 'listen');
await page.locator('#adaptive-music-listener').getByRole('button', {name: 'Enable Audio', exact: true}).click();
}));
stage('ambient');
const start = wire.commands.length;
if(tabbed){
await setup.getByRole('button',{name:'Go to Playback'}).click();
await setup.getByRole('button',{name:'Enable automation'}).click();
await setup.getByText('Automation active',{exact:true}).waitFor({timeout:10000});
}else{
await setup.getByLabel('Enable music automation').check();
await setup.getByRole('button',{name:'Apply automation setting',exact:true}).click();
}
const ambientPlay = await command(start, 'play_media', args => args.option === 'replace');
report.ambient = await audio();
await delay(6500);
stage('actual-combat');
combatId = await fixture({action: 'combat', sceneId, fixtureName});
const interrupt = wire.commands.length;
check(await fixture({action: 'start-combat', combatId}), 'foundry-combat-did-not-start');
const combatPlay = await command(interrupt, 'play_media', args => args.option === 'replace');
check(JSON.stringify(combatPlay.args.media) !== JSON.stringify(ambientPlay.args.media), 'combat-playlist-was-not-distinct');
await delay(4500);
report.combat = await audio();
stage('ambient-restoration');
const restore = wire.commands.length;
check(await fixture({action: 'delete-combat', combatId}), 'foundry-combat-delete-not-observed');
const restored = await command(restore, 'play_media', args => args.option === 'add');
const seek = await command(restore, 'play_index');
report.ambientOrderRestored = JSON.stringify(restored.args.media) === JSON.stringify(ambientPlay.args.media);
const snapshot = wire.commands.slice(interrupt, wire.commands.indexOf(combatPlay)).findLast(entry => entry.queue?.state === 'playing')?.queue;
report.ambientRestoreOffset = {index: seek.args.index, seconds: seek.args.seek_position};
report.ambientIndexAndOffsetRestored = Boolean(snapshot && seek.args.seek_position > 0 &&
snapshot.index === seek.args.index && Math.abs(snapshot.position - seek.args.seek_position) <= 2);
await delay(4500);
report.restoredAmbient = await audio();
report.onlyDedicatedQueueWritten = wire.commands.filter(entry => writes.has(entry.command)).every(entry => entry.args?.queue_id === receiver);
check(report.ambientOrderRestored && report.ambientIndexAndOffsetRestored && report.onlyDedicatedQueueWritten, 'queue-restore-or-ownership-mismatch');
stage('listener-stop-and-resume');
const listener = players[0].locator('#adaptive-music-listener');
await listener.getByRole('button', {name: 'Stop Audio', exact: true}).click();
await until(() => safeStats(players[0]), stats => stats.bytes === 0, 'listener-stop-did-not-close-peer');
await listener.getByRole('button', {name: 'Enable Audio', exact: true}).click();
report.afterListenerResume = await audio();
stage('listener-reload');
const reloaded = players[1];
await reloaded.reload({waitUntil: 'domcontentloaded', timeout: 30000});
await reloaded.waitForFunction(id => game.ready && game.world.id === id && !game.user.isGM && game.socket?.connected,
world.id, {polling: 250, timeout: 45000});
await openMenu(reloaded, 'listen');
await reloaded.locator('#adaptive-music-listener').getByRole('button', {name: 'Enable Audio', exact: true}).click();
report.afterListenerReload = await audio();
if(tabbed){
stage('playback-tab-controls');
await setup.getByText('2 connected listeners',{exact:true}).waitFor();
await setup.locator('.adaptive-now h3').filter({hasText:/^(?!Nothing playing).+/}).waitFor();
const slider=setup.getByLabel('Campaign volume');
await slider.press('ArrowLeft');
await setup.getByRole('button',{name:'Pause',exact:true}).click();
await setup.getByRole('button',{name:'Resume',exact:true}).click();
report.afterPlaybackResume=await audio();
await setup.getByRole('button',{name:'Stop playback',exact:true}).click();
await setup.getByText('Stopped',{exact:true}).waitFor();
report.playbackTabControls=true;
}
stage('passed');
} finally {
report.maAPIAuthenticated = wire.commands.some(entry => entry.authenticated);
report.sendspinAuthenticated = wire.sendspinAuthenticated();
report.accountPairingPassed = wire.commands.some(entry => entry.command === 'sendspin/pair_web_player' && entry.reply && entry.error === null);
report.queueWrites = wire.commands.filter(entry => writes.has(entry.command)).map(({command, reply, error}) => ({command, reply: reply === true, error}));
if(report.stage!=='passed')report.playbackFailureDetails={
notifications:await gm.evaluate(()=>window.__adaptiveTestNotifications??[]).catch(()=>[]),
recentMACommands:wire.commands.slice(-20).map(({command,reply,error})=>({command,reply:reply===true,error})),
};
if (receiver) {
if(await setup.getByRole('tab',{name:'Connection',exact:true}).count())await setup.getByRole('tab',{name:'Connection',exact:true}).click().catch(()=>{});
report.gmAudioDiagnostics = await gmAudioDiagnostics(gm, setup).catch(() => null);
}
report.browserAudio = await Promise.all(pages.map(page => page.evaluate(async () => {
const diagnostic = [...document.querySelectorAll('#adaptive-music-setup [role="status"]')].map(node => node.textContent).find(text => text.includes('Decoded frames:'));
const {contexts = [], analysers = []} = window.__adaptiveMusicTestAudio ?? {};
return {
decodedFrames: diagnostic ? Number(diagnostic.match(/Decoded frames: (\d+)/)?.[1] ?? 0) : null,
signaling: window.__adaptiveMusicTestSignaling,
contexts: contexts.map(({context, destination}) => ({state: context.state, time: context.currentTime, track: destination.stream.getAudioTracks()[0]?.readyState})),
analyserRMS: analysers.map(analyser => {
const samples = new Float32Array(analyser.fftSize);
analyser.getFloatTimeDomainData(samples);
return Math.sqrt(samples.reduce((sum, sample) => sum + sample ** 2, 0) / samples.length);
}),
browsers: await Promise.all((window.__adaptiveMusicTestPeers ?? []).map(async peer => {
const stats = peer.connectionState === 'connected' ? [...(await peer.getStats()).values()] : [];
return {connection: peer.connectionState, ice: peer.iceConnectionState, signaling: peer.signalingState,
outgoingEnergy: stats.find(row => row.type === 'media-source' && row.kind === 'audio')?.totalAudioEnergy};
})),
};
}).catch(() => null)));
if (!report.upstreamError) {
const lastError = wire.commands.findLast(entry => entry.reply && entry.error !== null);
if (lastError) report.upstreamError = {command: lastError.command, code: lastError.error};
}
if (baseline) {
try {
if (report.stage === 'passed') await gm.evaluate(moduleId => game.modules.get(moduleId).api.setOverrides([{id: 'integration-cleanup', playlist: null}]), moduleId);
} finally {
report.temporaryWorldChangesRestored = await fixture({action: 'cleanup', sceneId, combatId, baseline}).catch(() => false);
}
}
}
}
+83
View File
@@ -0,0 +1,83 @@
// Explicit bounded DEV-only experiment. No browser or network control endpoint.
import { randomUUID } from 'node:crypto';
import { readFile,writeFile } from 'node:fs/promises';
import { liveClient,savePrivate } from './live_ma_preflight.mjs';
import { MAPlaybackProvider } from '../gateway/ma-provider.mjs';
import { GatewayControl } from '../gateway/control.mjs';
import { MusicController } from '../src/core/controller.mjs';
const report={checked_at:new Date().toISOString(),evidence_class:'live dedicated MA',mutations:0,checks:[],restored:false};
let provider,original,client,gateway,request,timer,controller,generation=0;
const session=randomUUID();
const ctx=()=>({campaign:'development',session,generation:(generation=Math.max(generation,controller?.generation??0)+1),check(){if(generation>10000)throw Error('stale');}});
const delay=ms=>new Promise(resolve=>setTimeout(resolve,ms));
try {
if(!process.argv.includes('--controls-only') && !process.argv.includes('--synthetic'))throw Object.assign(Error(),{code:'mode-required'});
let sequences;
if(process.argv.includes('--synthetic')) {
const source=JSON.parse(await readFile('.local/fixture-origin.json','utf8'));
sequences=Object.fromEntries(Object.entries(source.sequences).map(([kind,files])=>[`synthetic-${kind}`,files.map(name=>`builtin://track/${source.base_url}/${name}`)]));
}
const loaded=await liveClient(sequences);client=loaded.client;
if(sequences){await client.inspectSynthetic();report.content='original synthetic sequences; not MA playlists';}
await client.verifyTarget();report.isolation_verified=true;
gateway=new GatewayControl({campaigns:{development:{client}},origin:'https://example.test'});
request={campaign:'development',session,origin:'https://example.test',token:gateway.mint({campaign:'development',session,role:'controller',ttlMs:300000})};request.fence=gateway.acquire(request).fence;
timer=setInterval(()=>{try{gateway.renew(request);}catch{clearInterval(timer);}},10000);
const mutate=client.mutate.bind(client);client.mutate=async(...args)=>{await mutate(...args);report.mutations++;};
provider=new MAPlaybackProvider({client,campaign:request.campaign,session:request.session,fence:request.fence,authority:gateway.fenceGuard(request),snapshotKey:loaded.catalogKey});
original=await provider.snapshot(ctx());await savePrivate('ma-original-snapshot.json',original);
report.original={state:original.value.state,items:original.value.items.length,position:original.value.position};
// Abort instead of interrupting unexpected existing playback in a controls-only run.
if(process.argv.includes('--controls-only')){
if(original.value.items.length || original.value.state!=='idle')throw Object.assign(Error(),{code:'unsupported'});
for(const [action,value] of [['shuffle',true],['shuffle',false],['repeat','one'],['repeat','all'],['repeat','off'],['stop',null]]){
await provider.control(action,value,ctx());const q=await client.queueState();
if(action==='shuffle' && q.shuffle_enabled!==value || action==='repeat' && q.repeat_mode!==value)throw Error();
report.checks.push({action,value,result:'pass',scope:'idle queue controls'});
}
}else{
// Original generated fixtures only; actual MA playlist playback needs separate acceptance.
const refs=['synthetic-ambient','synthetic-combat'].map(id=>({provider:'ma',id}));
await provider.apply(await provider.resolve(refs[0],ctx()),ctx());await delay(1500);
for(const [action,value] of [['pause',null],['resume',null],['seek',3],['shuffle',true],['shuffle',false],['repeat','one'],['repeat','all'],['repeat','off']]){
await provider.control(action,value,ctx());await delay(250);report.checks.push({action,result:'command accepted'});
}
// Park the ambient fixture for exact offset comparisons through nested contexts.
await provider.control('pause',null,ctx());await delay(250);
const ambient=await provider.snapshot(ctx());
controller=new MusicController({campaign:request.campaign,session:request.session,providers:{ma:provider},authority:()=>true});
controller.generation=generation;
const base={scene:{id:'fixture',playlist:refs[0]},combats:[]};
// Adopt the existing fixture as current rather than restarting it.
const {candidates}=await import('../src/core/controller.mjs');controller.current=candidates(base)[0];
const combat={id:'fixture-combat',sceneId:'fixture',active:true,started:true,playlist:refs[1],bosses:[]};
await controller.update({...base,combats:[combat]});await delay(500);
const bossState={...base,combats:[{...combat,bosses:[{id:'boss',active:true,priority:1,playlist:refs[0]}]}]};
await controller.update(bossState);
await controller.update({...bossState,overrides:[{id:'manual',playlist:refs[1]}]});
await controller.update(bossState);
await controller.update({...base,combats:[combat]});await controller.update(base);
generation=controller.generation;const restored=await provider.snapshot(ctx());
if(JSON.stringify(restored.value.items)!==JSON.stringify(ambient.value.items) || restored.value.index!==ambient.value.index || Math.abs(restored.value.position-ambient.value.position)>1 || restored.value.state!==ambient.value.state)throw Object.assign(Error(),{code:'restore-mismatch'});
report.checks.push({action:'nested combat/boss/manual unwind',result:'pass'});
controller.generation=generation;
const mutationsBefore=report.mutations;
const results=await Promise.allSettled([controller.update({...base,combats:[combat]}),controller.update({...base,overrides:[{id:'rapid',playlist:refs[1]}]}),controller.update(base)]);
generation=controller.generation;report.checks.push({action:'rapid contexts',settled:results.map(r=>r.status),result:'completed',mutations:report.mutations-mutationsBefore});
if(report.mutations!==mutationsBefore)throw Object.assign(Error(),{code:'duplicate-mutation'});
}
}catch(error){report.error=error.code??'unavailable';}
finally{
if(original && provider){
try{
await provider.restore(original,ctx());await delay(250);const after=await provider.snapshot(ctx());
const fields=v=>JSON.stringify([v.state,v.items,v.index,v.repeat,v.shuffle,v.position]);
report.restored=fields(after.value)===fields(original.value);
if(!report.restored)report.restore_error='state mismatch';
}catch(error){report.restore_error=error.code??'unavailable';}
}
if(!original && report.mutations===0){report.original_unchanged=true;report.restored=null;}
clearInterval(timer);if(gateway&&request)gateway.revoke(request.token);
await writeFile(process.argv.includes('--synthetic')?'evidence/ma-synthetic-playback.json':'evidence/ma-playback.json',JSON.stringify(report,null,2)+'\n');console.log(JSON.stringify(report,null,2));
if(report.error || !report.restored)process.exitCode=1;
}
+23
View File
@@ -0,0 +1,23 @@
// Read-only; original state and identifiers remain in private storage.
import { constants } from 'node:fs';
import { readFile, open } from 'node:fs/promises';
import { MAReadClient } from '../gateway/ma-client.mjs';
import { loadMAToken,loadCatalogKey } from '../gateway/private-config.mjs';
export async function liveClient(syntheticSequences = {}) {
const config=JSON.parse(await readFile('.local/environment.json','utf8'));
const prior=JSON.parse(await readFile('.local/ma-readonly-results.json','utf8'));
if(prior.me.player_filter.length!==1 || prior.player.name!=='Adaptive Music DEV')throw Error('denied');
const catalogKey=await loadCatalogKey('.local');
const client=new MAReadClient({baseUrl:config.ma_url,token:await loadMAToken('.local'),target:prior.me.player_filter[0],
approvedProviders:prior.me.provider_filter,syntheticSequences,catalogKey,campaign:'development',expectedName:'Adaptive Music DEV',expectedProvider:prior.player.provider});
return {client,catalogKey};
}
export async function savePrivate(name,data) {
const file=await open(`.local/${name}`,constants.O_WRONLY|constants.O_CREAT|constants.O_NOFOLLOW,0o600);
try {const info=await file.stat();if(!info.isFile() || info.uid!==process.getuid() || (info.mode&0o777)!==0o600)throw Error('denied');await file.truncate(0);await file.writeFile(JSON.stringify(data,null,2)+'\n');await file.sync();}finally{await file.close();}
}
if(process.argv[1]?.endsWith('live_ma_preflight.mjs')) {
try {const {client}=await liveClient();await client.verifyTarget();const q=await client.queueState();const choices=await client.catalog();
console.log(JSON.stringify({isolation_verified:true,state:q.state,items:q.items,shuffle:q.shuffle_enabled,playlists:choices.filter(c=>c.kind==='playlist').length}));
} catch(error){console.log(JSON.stringify({isolation_verified:false,error:error.code??'unavailable',mutations_sent:0}));process.exitCode=1;}
}
+271
View File
@@ -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));
}
+31
View File
@@ -0,0 +1,31 @@
// Local synthetic media benchmark. No real MA account, endpoint, SDK identity or Git host is accessed.
import {chromium} from 'playwright';
import {createServer} from 'node:http';
import {readFile,writeFile} from 'node:fs/promises';
import {resolve,extname} from 'node:path';
const root=process.cwd();const http=createServer(async(req,res)=>{
try{const path=req.url==='/'?'/tests/browser/audio.html':req.url;if(!/^\/(src|vendor|tests\/browser)\//.test(path)||path.includes('..')||path.includes('?'))throw Error();const file=resolve(root,'.'+path);const bytes=await readFile(file);res.writeHead(200,{'Content-Type':extname(file)==='.html'?'text/html':'text/javascript','Cache-Control':'no-store'});res.end(bytes);}catch{res.writeHead(404);res.end();}
});await new Promise(resolve=>http.listen(0,'127.0.0.1',resolve));
let browser;const pages=[],signals=[];
try{
browser=await chromium.launch({headless:true,args:['--no-sandbox']});
for(const [role,id]of [['gm','gm'],['listener','player-a'],['listener','player-b']]){
const context=await browser.newContext();const page=await context.newPage();pages.push(page);
await page.exposeFunction('relay',async(name,frame)=>{signals.push({name,bytes:JSON.stringify(frame).length,keys:Object.keys(frame)});await Promise.all(pages.filter(p=>p!==page).map(p=>p.evaluate(({name,frame})=>window.deliver?.(name,frame),{name,frame})));});
await page.goto(`http://127.0.0.1:${http.address().port}/`);await page.waitForFunction(()=>window.ready);await page.evaluate(({role,id})=>window.configure({role,id}),{role,id});await page.click('#enable');await page.waitForFunction(()=>window.unlocked);
}
const started=Date.now();
for(let i=1;i<pages.length;i++){const invite=await pages[0].evaluate(id=>window.makeInvite(id),i===1?'player-a':'player-b');await pages[i].evaluate(invite=>window.join(invite),invite);}
for(const page of pages.slice(1))await page.waitForFunction(()=>window.measure()?.rms>0.01,{},{timeout:15000});
const firstAudioMs=Date.now()-started;await new Promise(resolve=>setTimeout(resolve,3000));
const measurements=await Promise.all(pages.slice(1).map(p=>p.evaluate(()=>window.measure()))),stats=await pages[0].evaluate(()=>window.stats());
const source=await pages[0].evaluate(()=>({frames:window.decodedFrames,started:window.sourceStarted}));
const seconds=(Date.now()-started)/1000,bytesSent=stats.filter(s=>s.type==='outbound-rtp').reduce((sum,s)=>sum+(s.bytesSent??0),0);
const report={checked_at:new Date().toISOString(),evidence_class:'real Chromium localhost SDK PCM decoder/WebAudio/WebRTC; synthetic input; socket relay shim, not Foundry or MA',browser:await browser.version(),listeners:2,
first_all_listeners_signal_ms:firstAudioMs,observation_seconds:seconds,sdk_decoded_frames:source.frames,listeners_measured:measurements.map(m=>({rms:Number(m.rms.toFixed(5)),peak_hz:m.peakHz})),
gm_rtp_bytes_sent:bytesSent,aggregate_media_kbps:Number((bytesSent*8/seconds/1000).toFixed(2)),signaling_messages:signals.length,max_signal_bytes:Math.max(...signals.map(s=>s.bytes)),
socket_payloads_are_encrypted_control_only:signals.every(s=>s.name==='module.adaptive-music'&&s.keys.sort().join(',')==='cipher,from,iv,peer,seq,session,v'),
turn_used:false,public_network_test:false,ma_handshake_test:false,ma_audio_playback:false,interlistener_skew_measured:false,autoplay_gesture:'actual page click',sandbox_note:'headless browser only used --no-sandbox; not a deployment setting'};
if(measurements.some(m=>m.rms<0.01||Math.abs(m.peakHz-440)>30)||!report.socket_payloads_are_encrypted_control_only)throw Error('audio acceptance failed');
await writeFile('evidence/browser-audio.json',JSON.stringify(report,null,2)+'\n');console.log(JSON.stringify(report,null,2));
}catch(error){for(const page of pages)console.log(JSON.stringify(await page.evaluate(async()=>({diagnostics:await window.diagnostics?.(),decoded:window.decodedFrames,measurement:window.measure?.(),sample:Array.from(window.sampleValue??[]),error:window.lastError,playError:window.lastPlayError})).catch(()=>({}))));throw error;}finally{for(const page of pages)await page.evaluate(()=>window.finish?.()).catch(()=>{});await browser?.close();await new Promise(resolve=>http.close(resolve));}
+49
View File
@@ -0,0 +1,49 @@
"""Build a local development ZIP from an explicit public browser-source allowlist."""
import json
from pathlib import Path
import zipfile
ROOT = Path(__file__).resolve().parents[1]
def build(destination=None):
destination = destination or ROOT / 'dist/adaptive-music-dev.zip'
destination.parent.mkdir(parents=True,exist_ok=True)
names = ['module.json','LICENSE','THIRD-PARTY-NOTICES','README.md','INSTALL.md','CHANGELOG.md','ARCHITECTURE.md','SECURITY.md','TESTING.md','PROGRESS.md']
names += [str(p.relative_to(ROOT)) for p in sorted((ROOT/'src').rglob('*.mjs'))]
names += [str(p.relative_to(ROOT)) for p in sorted((ROOT/'licenses').rglob('*.txt'))]
names += [str(p.relative_to(ROOT)) for p in sorted((ROOT/'styles').glob('*.css'))]
names += [str(p.relative_to(ROOT)) for p in sorted((ROOT/'vendor').glob('*')) if p.is_file()]
manifest=json.loads((ROOT/'module.json').read_text())
if manifest['id']!='adaptive-music' or 'verified' in manifest['compatibility']:
raise ValueError('invalid development manifest')
with zipfile.ZipFile(destination,'w',zipfile.ZIP_DEFLATED) as archive:
for name in names:
path=ROOT/name
if path.is_symlink(): raise ValueError('symlink refused')
data=path.read_bytes()
if name.endswith('.mjs') and (b'node:' in data or b'gateway/' in data):
raise ValueError('server source in browser package')
entry=zipfile.ZipInfo('adaptive-music/'+name,date_time=(2026,12,3,0,0,0))
entry.compress_type=zipfile.ZIP_DEFLATED
entry.external_attr=0o100644<<16
archive.writestr(entry,data)
return destination
def build_companion(destination=None):
destination=destination or ROOT/'dist/adaptive-music-companion-dev.zip'
destination.parent.mkdir(parents=True,exist_ok=True)
names=['LICENSE','THIRD-PARTY-NOTICES','package.json','package-lock.json','src/core/controller.mjs','src/providers/ma/client.mjs','src/providers/ma/provider.mjs','src/providers/ma/webcrypto.mjs']
names += [str(p.relative_to(ROOT)) for p in sorted((ROOT/'gateway').glob('*.mjs'))]
names += ['gateway/README.md','gateway/SETUP.md']
names += [str(p.relative_to(ROOT)) for p in sorted((ROOT/'licenses').rglob('*.txt'))]
with zipfile.ZipFile(destination,'w',zipfile.ZIP_DEFLATED) as archive:
for name in names:
path=ROOT/name
if path.is_symlink(): raise ValueError('symlink refused')
entry=zipfile.ZipInfo('adaptive-music-companion/'+name,date_time=(2026,12,3,0,0,0))
entry.compress_type=zipfile.ZIP_DEFLATED;entry.external_attr=0o100644<<16
archive.writestr(entry,path.read_bytes())
return destination
if __name__=='__main__':
print(build().relative_to(ROOT))
# The optional companion remains source/experimental fallback, not a required release artifact.
+42
View File
@@ -0,0 +1,42 @@
"""Explicitly invoked, read-only unauthenticated diagnostics; raw data stays private."""
import json
from pathlib import Path
import time
import urllib.error
import urllib.request
ROOT = Path(__file__).resolve().parents[1]
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
def probe(base_url: str) -> list[dict]:
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect())
results = []
for path in ('/', '/info'):
start = time.monotonic()
result = {'path': path}
try:
req = urllib.request.Request(base_url.rstrip('/') + path, method='GET')
with opener.open(req, timeout=5) as response:
body = response.read(65536)
result.update(status=response.status,
content_type=response.headers.get('content-type'),
bytes=len(body))
# Deliberately do not log bodies, Location headers, URLs or exception text.
except urllib.error.HTTPError as exc:
result['status'] = exc.code
except (OSError, urllib.error.URLError) as exc:
result.update(error_type=type(exc).__name__,
reason_type=type(getattr(exc, 'reason', None)).__name__)
result['elapsed_seconds'] = round(time.monotonic() - start, 2)
results.append(result)
return results
if __name__ == '__main__':
config = json.loads((ROOT / '.local/environment.json').read_text())
print(json.dumps(probe(config['ma_url']), indent=2))
+172
View File
@@ -0,0 +1,172 @@
"""Offline Foundry/Gitea/GitHub release generation. Never contacts a Git host."""
from __future__ import annotations
import argparse
import hashlib
import ipaddress
import json
from pathlib import Path
import re
import subprocess
import sys
import urllib.parse
import zipfile
ROOT=Path(__file__).resolve().parents[1]
DEFAULT_REPOSITORY='https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music'
ZIP_TIME=(2000,1,1,0,0,0)
if str(ROOT/'scripts') not in sys.path:sys.path.insert(0,str(ROOT/'scripts'))
def public_url(value):
parsed=urllib.parse.urlsplit(value)
if parsed.scheme!='https' or not parsed.hostname or parsed.username or parsed.password or parsed.query or parsed.fragment:
raise ValueError('public HTTPS URL required')
try:
address=ipaddress.ip_address(parsed.hostname)
except ValueError:
if parsed.hostname in ('localhost',) or parsed.hostname.endswith(('.local','.invalid')):raise ValueError('placeholder/local release URL')
else:
if not address.is_global:raise ValueError('private release address')
return value.rstrip('/')
def urls(repository,version,branch='main'):
repository=public_url(repository)
parsed=urllib.parse.urlsplit(repository)
if repository.endswith('.git'):repository=repository[:-4]
if not re.fullmatch(r'[A-Za-z0-9._-]+',branch):raise ValueError('invalid branch')
if not re.fullmatch(r'\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?',version):raise ValueError('invalid release version')
if parsed.hostname=='github.com':
parts=urllib.parse.urlsplit(repository).path.strip('/').split('/')
if len(parts)!=2:raise ValueError('GitHub owner/repo required')
manifest=f'https://raw.githubusercontent.com/{parts[0]}/{parts[1]}/{branch}/module.json'
else:manifest=f'{repository}/raw/branch/{branch}/module.json'
return {'url':repository,'manifest':manifest,'download':f'{repository}/releases/download/v{version}/adaptive-music.zip'}
def release_manifest(repository=DEFAULT_REPOSITORY,version=None,branch='main'):
manifest=json.loads((ROOT/'module.json').read_text())
if version is not None and version!=manifest['version']:raise ValueError('tag/version must match source module.json')
manifest['version']=version or manifest['version'];manifest.update(urls(repository,manifest['version'],branch))
validate_manifest(manifest);return manifest
def validate_manifest(manifest):
if not isinstance(manifest,dict) or any(k not in manifest for k in ('id','authors','compatibility','version','url','manifest','download','esmodules')):raise ValueError('incomplete manifest')
if manifest.get('id')!='adaptive-music' or manifest.get('authors')!=[{'name':'CheddahBoxMB'}]:raise ValueError('module identity mismatch')
if manifest.get('compatibility',{}).get('minimum')!='14' or manifest['compatibility'].get('maximum')!='14' or 'verified' in manifest['compatibility']:raise ValueError('unsupported compatibility claim')
if manifest.get('relationships',{}).get('requires',[]) or manifest.get('systems'):raise ValueError('mandatory system/module dependency')
expected=urls(manifest['url'],manifest['version'])
for key in ('manifest','download'):
public_url(manifest[key])
if manifest[key]!=expected[key]:raise ValueError('manifest/update URL mismatch')
if 'v'+manifest['version'] not in manifest['download']:raise ValueError('unversioned download')
def module_files():
names=['module.json','README.md','INSTALL.md','CHANGELOG.md','ARCHITECTURE.md','SECURITY.md','TESTING.md','PROGRESS.md','LICENSE','THIRD-PARTY-NOTICES']
for directory,pattern in [('src','*.mjs'),('styles','*.css'),('licenses','*'),('vendor','*')]:
names.extend(str(p.relative_to(ROOT)) for p in sorted((ROOT/directory).rglob(pattern)) if p.is_file())
return names
def write_zip(path,entries):
path.parent.mkdir(parents=True,exist_ok=True)
with zipfile.ZipFile(path,'w',zipfile.ZIP_DEFLATED) as archive:
for name,data in sorted(entries.items()):
info=zipfile.ZipInfo(name,ZIP_TIME);info.compress_type=zipfile.ZIP_DEFLATED;info.external_attr=0o100644<<16
archive.writestr(info,data)
def module_entries(manifest):
result={}
for name in module_files():
path=ROOT/name
if path.is_symlink():raise ValueError('package symlink refused')
data=(json.dumps(manifest,indent=2)+'\n').encode() if name=='module.json' else path.read_bytes()
if name.endswith('.mjs') and (b'node:' in data or b"from '../../gateway/" in data):raise ValueError('server code in browser package')
result['adaptive-music/'+name]=data
return result
def validate_package(path,manifest=None):
from audit_repository import findings
with zipfile.ZipFile(path) as archive:
names=archive.namelist()
if len(names)!=len(set(names)) or any(not n.startswith('adaptive-music/') or '..' in Path(n).parts or '/.local/' in n or '/node_modules/' in n or '/gateway/' in n for n in names):raise ValueError('unsafe package inventory')
actual=json.loads(archive.read('adaptive-music/module.json'));validate_manifest(actual)
if manifest and actual!=manifest:raise ValueError('embedded and standalone manifest mismatch')
for name in names:
data=archive.read(name);problems=findings(name,data.decode(errors='replace'))
if problems:raise ValueError('private content in release: '+name)
if name.endswith('.mjs'):
text=data.decode();relative_imports=re.findall(r"(?:from\s*|import\s*\()['\"](\.[^'\"]+)['\"]",text)
import posixpath
for relative in relative_imports:
resolved=posixpath.normpath(posixpath.join(posixpath.dirname(name),relative))
if resolved not in names:raise ValueError('missing browser import: '+resolved)
for asset in actual['esmodules']+actual.get('styles',[]):
if 'adaptive-music/'+asset not in names:raise ValueError('missing manifest asset')
provenance=json.loads(archive.read('adaptive-music/vendor/provenance.json'))
if hashlib.sha256(archive.read('adaptive-music/vendor/sendspin-5.0.0.mjs')).hexdigest()!=provenance['sha256']:raise ValueError('SDK bundle hash mismatch')
required=['licenses/VGM-MIT.txt','licenses/Apache-2.0.txt','licenses/vendor/-sendspin-sendspin-js.txt','licenses/vendor/-noble-ciphers.txt','licenses/vendor/-noble-curves.txt','licenses/vendor/-noble-hashes.txt']
if any('adaptive-music/'+name not in names for name in required):raise ValueError('missing license')
return actual
def local_revision():
try:return subprocess.check_output(['git','rev-parse','HEAD'],cwd=ROOT,text=True,stderr=subprocess.DEVNULL).strip()
except (subprocess.CalledProcessError,FileNotFoundError):
file=ROOT/'SOURCE_REVISION.txt'
return file.read_text().strip() if file.is_file() else 'unknown (source archive without Git metadata)'
def source_entries(manifest):
from audit_repository import findings
try:names=subprocess.check_output(['git','ls-files','-z','--cached','--others','--exclude-standard'],cwd=ROOT,stderr=subprocess.DEVNULL).decode().split('\0')
except (subprocess.CalledProcessError,FileNotFoundError):
names=[p.name for p in ROOT.iterdir() if p.is_file() and p.name in {'.gitignore','AGENTS.md','ARCHITECTURE.md','SECURITY.md','TESTING.md','PROGRESS.md','module.json','package.json','package-lock.json','README.md','INSTALL.md','CHANGELOG.md','ARCHITECTURE.md','SECURITY.md','TESTING.md','PROGRESS.md','LICENSE','THIRD-PARTY-NOTICES','SOURCE_REVISION.txt'}]
for directory in ('src','styles','licenses','vendor','gateway','scripts','tests','evidence','.github','.gitea'):
names.extend(str(p.relative_to(ROOT)) for p in (ROOT/directory).rglob('*') if p.is_file() and '__pycache__' not in p.parts and p.suffix!='.pyc')
entries={}
for name in sorted(set(filter(None,names))):
path=ROOT/name
if name.startswith(('.local/','dist/','node_modules/','.git/')) or path.is_symlink():raise ValueError('private/unsafe source path')
if path.is_file():
data=path.read_bytes()
if findings(name,data.decode(errors='replace')):raise ValueError('private material in source: '+name)
entries['adaptive-music-source/'+name]=data
entries['adaptive-music-source/module.json']=(json.dumps(manifest,indent=2)+'\n').encode()
entries['adaptive-music-source/SOURCE_REVISION.txt']=(local_revision()+'\n').encode()
return entries
def build_release(repository=DEFAULT_REPOSITORY,version=None,output=None):
manifest=release_manifest(repository,version);version=manifest['version'];output=output or ROOT/'dist/releases'/('v'+version)
output=Path(output).resolve()
if output.is_relative_to(ROOT) and not output.is_relative_to(ROOT/'dist'):raise ValueError('in-repository output must be under ignored dist/')
output.mkdir(parents=True,exist_ok=True)
allowed={'adaptive-music.zip','module.json','adaptive-music-source.zip','README.md','INSTALL.md','CHANGELOG.md','ARCHITECTURE.md','SECURITY.md','TESTING.md','PROGRESS.md','LICENSE','THIRD-PARTY-NOTICES','release.json','SHA256SUMS',f'adaptive-music-release-v{version}.zip',f'adaptive-music-release-v{version}.zip.sha256'}
evidence_name=f'evidence/v{version}-live.json'
if (ROOT/evidence_name).is_file():allowed.add(evidence_name)
allowed.update(str(p.relative_to(ROOT)) for p in (ROOT/'licenses').rglob('*') if p.is_file())
for file in output.rglob('*'):
if file.is_symlink() or file.is_file() and str(file.relative_to(output)) not in allowed:raise ValueError('unmanaged file in release output')
write_zip(output/'adaptive-music.zip',module_entries(manifest));validate_package(output/'adaptive-music.zip',manifest)
(output/'module.json').write_text(json.dumps(manifest,indent=2)+'\n')
source=source_entries(manifest)
write_zip(output/'adaptive-music-source.zip',source)
evidence=source.get(f'adaptive-music-source/{evidence_name}')
if evidence is not None:
(output/evidence_name).parent.mkdir(parents=True,exist_ok=True)
(output/evidence_name).write_bytes(evidence)
for name in ('README.md','INSTALL.md','CHANGELOG.md','ARCHITECTURE.md','SECURITY.md','TESTING.md','PROGRESS.md','LICENSE','THIRD-PARTY-NOTICES'):(output/name).write_bytes((ROOT/name).read_bytes())
for path in (ROOT/'licenses').rglob('*'):
if path.is_file():target=output/path.relative_to(ROOT);target.parent.mkdir(parents=True,exist_ok=True);target.write_bytes(path.read_bytes())
metadata={'version':version,'repository':manifest['url'],'manifest':manifest['manifest'],'download':manifest['download'],
'sourceCommit':local_revision(),'sourceRevisionStatus':'base revision; included source archive is authoritative','sourceArchiveSHA256':hashlib.sha256((output/'adaptive-music-source.zip').read_bytes()).hexdigest(),'destinationStatus':'user-reported existing Gitea; never contacted by this builder','foundryLiveVerified':False,'networkAccessRequired':False}
acceptance=json.loads(evidence) if evidence is not None else {}
metadata['publicationReady']=acceptance.get('publicationReady') is True
metadata['maCoreFlowDemonstrated']=acceptance.get('completedCoreRunPassed') is True
metadata['macPrivateRouteVerified']=acceptance.get('macPrivateRouteVerified') is True
metadata['acceptanceStatus']='staged; operator Mac and logged-in-world acceptance required' if not metadata['publicationReady'] else 'operator acceptance recorded'
(output/'release.json').write_text(json.dumps(metadata,indent=2)+'\n')
files={str(p.relative_to(output)):p.read_bytes() for p in output.rglob('*') if p.is_file() and p.name not in ('SHA256SUMS',) and not p.name.startswith('adaptive-music-release-')}
(output/'SHA256SUMS').write_text(''.join(f'{hashlib.sha256(data).hexdigest()} {name}\n' for name,data in sorted(files.items())))
files['SHA256SUMS']=(output/'SHA256SUMS').read_bytes();bundle=output/f'adaptive-music-release-v{version}.zip';write_zip(bundle,files)
(output/(bundle.name+'.sha256')).write_text(hashlib.sha256(bundle.read_bytes()).hexdigest()+' '+bundle.name+'\n')
return bundle
if __name__=='__main__':
parser=argparse.ArgumentParser();parser.add_argument('--repository',default=DEFAULT_REPOSITORY);parser.add_argument('--version');parser.add_argument('--output',type=Path);parser.add_argument('--validate',type=Path);args=parser.parse_args()
if args.validate:validate_package(args.validate);print('PASS: standalone Foundry package, imports, manifest/update URLs, privacy and licenses')
else:print(build_release(args.repository,args.version,args.output))
+92
View File
@@ -0,0 +1,92 @@
"""Generate original quiet tones and optionally serve only them on a private interface.
No MA library, playlist, provider configuration or firewall changes are performed.
"""
from array import array
import argparse
import hashlib
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import ipaddress
import json
import math
import os
from pathlib import Path
import socket
import threading
import wave
from urllib.parse import urlsplit
ROOT=Path(__file__).resolve().parents[1]
FOLDER=ROOT/'.local/synthetic-audio'
def generate():
FOLDER.mkdir(mode=0o700,parents=True,exist_ok=True)
manifest={'license':'MIT; original mathematically generated tones','sample_rate':24000,'channels':2,'duration_seconds':90,'sequences':{}}
for kind,frequencies in [('ambient',[110,165,220]),('combat',[440,660,880])]:
manifest['sequences'][kind]=[]
for number,frequency in enumerate(frequencies,1):
name=f'{kind}-{number}.wav'; path=FOLDER/name
# Gentle fades and low amplitude; no borrowed recordings or samples.
samples=array('h')
for frame in range(24000*90):
envelope=min(1,frame/2400,(24000*90-frame)/2400)
value=round(700*envelope*math.sin(2*math.pi*frequency*frame/24000))
samples.extend((value,value))
import sys
if sys.byteorder!='little': samples.byteswap()
with wave.open(str(path),'wb') as audio:
audio.setparams((2,2,24000,0,'NONE','not compressed'));audio.writeframes(samples.tobytes())
path.chmod(0o600)
manifest['sequences'][kind].append({'file':name,'frequency_hz':frequency,'sha256':hashlib.sha256(path.read_bytes()).hexdigest()})
path=FOLDER/'manifest.json';path.write_text(json.dumps(manifest,indent=2)+'\n');path.chmod(0o600)
return manifest
def serve():
manifest=json.loads((FOLDER/'manifest.json').read_text())
remote=socket.gethostbyname(urlsplit(json.loads((ROOT/'.local/environment.json').read_text())['ma_url']).hostname)
with socket.socket(socket.AF_INET,socket.SOCK_DGRAM) as route:
route.connect((remote,9));address=route.getsockname()[0]
if not ipaddress.ip_address(address).is_private or not ipaddress.ip_address(remote).is_private:
raise ValueError('private interface required')
names={row['file'] for rows in manifest['sequences'].values() for row in rows}
class Handler(BaseHTTPRequestHandler):
def log_message(self,*args): pass
def do_HEAD(self): self.respond(False)
def do_GET(self): self.respond(True)
def respond(self,body):
name=self.path.removeprefix('/')
if self.client_address[0] not in (remote,address) or name not in names:
self.send_error(403);return
path=FOLDER/name;size=path.stat().st_size;start=0;end=size-1
if request_range:=self.headers.get('Range'):
import re
match=re.fullmatch(r'bytes=(\d+)-(\d*)',request_range)
if not match: self.send_error(416);return
start=int(match[1]);end=min(size-1,int(match[2])) if match[2] else size-1
if start>end: self.send_error(416);return
self.send_response(206 if request_range else 200)
self.send_header('Content-Type','audio/wav');self.send_header('Accept-Ranges','bytes')
self.send_header('Content-Length',str(end-start+1));self.send_header('Cache-Control','no-store')
if request_range:self.send_header('Content-Range',f'bytes {start}-{end}/{size}')
self.end_headers()
if body:
try:
with path.open('rb') as audio:
audio.seek(start);remaining=end-start+1
while remaining:
data=audio.read(min(65536,remaining))
if not data: break
self.wfile.write(data);remaining-=len(data)
except (BrokenPipeError,ConnectionResetError): pass
server=ThreadingHTTPServer((address,0),Handler);server.daemon_threads=True
configuration={'base_url':f'http://{address}:{server.server_port}','sequences':{kind:[row['file'] for row in rows] for kind,rows in manifest['sequences'].items()}}
path=ROOT/'.local/fixture-origin.json';path.write_text(json.dumps(configuration));path.chmod(0o600)
timer=threading.Timer(300,server.shutdown);timer.daemon=True;timer.start()
print('Private synthetic fixture origin ready; MA-source IP allowlist; five-minute lifetime.',flush=True)
try:server.serve_forever()
finally:timer.cancel();server.server_close()
if __name__=='__main__':
parser=argparse.ArgumentParser();parser.add_argument('--serve',action='store_true');args=parser.parse_args()
if args.serve:serve()
else:
manifest=generate();print('Generated six original 90-second stereo fixtures in private storage.')
(ROOT/'evidence/synthetic-fixtures.json').write_text(json.dumps(manifest,indent=2)+'\n')
+114
View File
@@ -0,0 +1,114 @@
"""Authorized read-only MA probe. Never print raw responses, secrets or private IDs."""
import datetime
import json
import os
from pathlib import Path
import stat
import subprocess
import urllib.error
import urllib.request
from probe_ma import NoRedirect
ROOT = Path(__file__).resolve().parents[1]
def credential_check():
directory = ROOT / '.local'
path = directory / 'ma-token'
if directory.is_symlink() or path.is_symlink():
raise ValueError('credential symlink refused')
if stat.S_IMODE(directory.stat().st_mode) != 0o700 or stat.S_IMODE(path.stat().st_mode) != 0o600:
raise ValueError('private permissions required')
if path.stat().st_uid != os.getuid() or not path.is_file():
raise ValueError('credential owner/type refused')
token = path.read_bytes().strip()
if not token or b'\n' in token or b'\r' in token:
raise ValueError('invalid credential format')
ignored = subprocess.run(['git','check-ignore','-q','.local/ma-token'], cwd=ROOT).returncode == 0
# Inspect file paths and blob contents across all reachable refs, without logging matches.
objects = subprocess.check_output(['git','rev-list','--objects','--all'], cwd=ROOT).splitlines()
for entry in objects:
oid, _, name = entry.partition(b' ')
if name.startswith(b'.local/'):
raise ValueError('private path in history')
if subprocess.check_output(['git','cat-file','-t',oid], cwd=ROOT).strip() == b'blob':
if token in subprocess.check_output(['git','cat-file','blob',oid], cwd=ROOT):
raise ValueError('credential in history')
for name in subprocess.check_output(['git','ls-files','-z'],cwd=ROOT).split(b'\0'):
if name and token in (ROOT / os.fsdecode(name)).read_bytes():
raise ValueError('credential in tracked working tree')
if not ignored:
raise ValueError('credential not ignored')
return token.decode(), {'directory_mode':'0700','token_mode':'0600','git_ignored':True,
'token_absent_reachable_history':True,'token_absent_tracked_files':True}
def main():
token, safety = credential_check()
base = json.loads((ROOT / '.local/environment.json').read_text())['ma_url']
from urllib.parse import urlsplit
url = urlsplit(base)
if url.scheme not in ('http','https') or url.username or url.password or url.query or url.fragment or url.path not in ('','/'):
raise ValueError('invalid upstream')
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect())
allowed = {'auth/me','auth/scopes','players/get','player_queues/get','music/playlists/library_items','music/radios/library_items'}
def call(command, args=None):
if command not in allowed:
raise ValueError('command refused')
request = urllib.request.Request(base.rstrip('/')+'/api',data=json.dumps({
'message_id':'adaptive-music-read','command':command,'args':args or {}}).encode(),
headers={'Authorization':'Bearer '+token,'Content-Type':'application/json'},method='POST')
try:
with opener.open(request,timeout=10) as response:
data=response.read(1048577)
if len(data)>1048576:
raise ValueError('response limit')
return json.loads(data)
except urllib.error.HTTPError as exc:
return {'probe_http_status':exc.code}
me=call('auth/me')
report={'checked_at':datetime.datetime.now(datetime.timezone.utc).isoformat(), 'credential':safety,
'authentication':me.get('username') == 'adaptive-music' and me.get('enabled') is True}
raw={'me':me}
if report['authentication']:
raw['scopes']=call('auth/scopes')
filters=me.get('player_filter',[]); providers=me.get('provider_filter',[])
report.update(role=me.get('role'), player_filter_count=len(filters),provider_filter_count=len(providers))
if len(filters)==1:
player=call('players/get',{'player_id':filters[0]}); raw['player']=player
report['dedicated_name_matches']=player.get('name')=='Adaptive Music DEV'
report['player_available']=player.get('available')
report['sendspin_provider']=str(player.get('provider','')).startswith('sendspin')
report['standalone_topology']=not any(player.get(k) for k in ('active_group','synced_to','group_members','group_childs','static_group_members'))
if report['dedicated_name_matches']:
queue=call('player_queues/get',{'queue_id':filters[0]}); raw['queue']=queue
report['queue_id_matches_player']=queue.get('queue_id')==filters[0]
report['queue_active']=queue.get('active')
# Negative read uses a nonexistent synthetic ID, never a household player.
negative=call('players/get',{'player_id':'adaptive-music-forbidden-synthetic'})
report['synthetic_target_denial_status']=negative.get('probe_http_status')
if providers:
negative_provider=call('music/playlists/library_items',{'provider':['adaptive-music-forbidden-synthetic'],'limit':1})
report['synthetic_provider_denial_status']=negative_provider.get('probe_http_status') if isinstance(negative_provider,dict) else None
report['role_scopes']=raw['scopes'].get(me.get('role'),[])
for kind in ('playlists','radios'):
items=[]
for offset in range(0,5000,100):
page=call(f'music/{kind}/library_items',{'provider':providers,'limit':100,'offset':offset,'order_by':'name','summary':False})
if not isinstance(page,list):
report[kind+'_error']=True; break
items.extend(page)
if len(page)<100: break
raw[kind]=items; report[kind+'_count']=len(items)
report[kind+'_approved_mappings']=all(any(m.get('provider_instance') in providers and m.get('available') is True for m in i.get('provider_mappings',[])) for i in items)
else:
report['catalog_blocker']='No explicit approved provider filter; catalog reads skipped'
private=ROOT/'.local/ma-readonly-results.json'
fd=os.open(private,os.O_WRONLY|os.O_CREAT|os.O_TRUNC|os.O_NOFOLLOW,0o600)
with os.fdopen(fd,'w') as output: json.dump(raw,output)
(ROOT/'evidence/ma-readonly.json').write_text(json.dumps(report,indent=2)+'\n')
print(json.dumps(report,indent=2))
if __name__=='__main__':
try: main()
except Exception as exc:
print('Read-only probe failed:',type(exc).__name__)
raise SystemExit(1)
+41
View File
@@ -0,0 +1,41 @@
"""Validate local research copies against recorded pins. No network or installation."""
import hashlib
import json
from pathlib import Path
import subprocess
ROOT = Path(__file__).resolve().parents[1]
def verify() -> list[str]:
evidence = json.loads((ROOT / 'evidence/upstream.json').read_text())
errors = []
for source in evidence['git_sources']:
path = ROOT / '.local/upstream' / source['local_directory']
label = source['tag'] + ':' + source['local_directory']
if not (path / '.git').is_dir():
errors.append(f'{label}: missing checkout')
continue
head = subprocess.check_output(['git', '-C', str(path), 'rev-parse', 'HEAD'],
text=True).strip()
if head != source['commit']:
errors.append(f'{label}: commit mismatch')
for name, expected in source['files'].items():
file = path / name
if not file.is_file() or hashlib.sha256(file.read_bytes()).hexdigest() != expected:
errors.append(f'{label}: file mismatch: {name}')
for source in evidence.get('pypi_sources', []):
if not source.get('inspected_files'):
continue
directory = ROOT / '.local/upstream' / source['local_directory']
for name, expected in source['inspected_files'].items():
file = directory / name
if not file.is_file() or hashlib.sha256(file.read_bytes()).hexdigest() != expected:
errors.append(f"{source['version']}: distribution file mismatch: {name}")
return errors
if __name__ == '__main__':
problems = verify()
print('\n'.join(problems) if problems else 'PASS: all recorded Git heads, source and distribution file hashes')
raise SystemExit(bool(problems))
Loaded 100 of 150 files, more files were not shown because too many files have changed in this diff. Show more