commit 14f0d8c26b8c43e29db207882acd7ef6446ab7e0 Author: Jason Date: Thu Dec 3 16:11:47 2026 -0500 Initial Adaptive Music v0.5.0 release diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml new file mode 100644 index 0000000..0759478 --- /dev/null +++ b/.gitea/workflows/release.yml @@ -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 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..f56252c --- /dev/null +++ b/.github/workflows/release.yml @@ -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 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..57d7b26 --- /dev/null +++ b/.gitignore @@ -0,0 +1,12 @@ +.local/ +.env +.env.* +!.env.example +node_modules/ +dist/ +coverage/ +__pycache__/ +*.pyc +*.pem +*.key +*.log diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..8c7adfd --- /dev/null +++ b/AGENTS.md @@ -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. diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md new file mode 100644 index 0000000..f8e4be7 --- /dev/null +++ b/ARCHITECTURE.md @@ -0,0 +1,193 @@ +# Adaptive Music architecture — 0.5.0 local release candidate + +Independent project by **CheddahBoxMB**, system-independent, targeting Foundry +**v14.371** and MA **2.10.6**. Standard distribution is **one Foundry module ZIP** +with a stable Git-hosted manifest and immutable version-specific download URL. +No mandatory Foundry modules, containers, VMs/LXCs, sandbox runtime, core patches, +OS-service installer, subscription or telemetry. Planned Gitea URLs are configured +but the host/repository has not been contacted or confirmed to exist. + +## Decision after reevaluation + +The 0.4.0 companion is **not a mandatory architecture**. Native playback and all +scene/world/combat/boss/manual rules remain entirely module-local. The preferred +MA experiment is a trusted GM-browser host using the official Sendspin browser +SDK, Web Audio and WebRTC audio tracks. Its feasibility is conditional on secure +private MA reachability, an authorized existing receiver identity, GM availability, +participant capabilities and a working ICE path. It cannot yet be represented as +reliable module-only remote MA audio for arbitrary networks. + +The validated companion remains under `gateway/` and local branch +`experimental/companion-0.4.0`; provider/catalog/restoration code is preserved. +Shared Web Crypto transport/provider implementations now serve both GM and optional +companion, with compatibility exports at the original gateway paths. All original +regressions remain. If the browser gates cannot be met, propose one manually run, +restricted process **co-located on the existing Foundry host**. No new machine, +container or automatic service is proposed or deployed. Placement/routing and any +manual service registration require explicit approval after concrete review. + +```mermaid +flowchart LR + F[Foundry scene and combat policy] --> C[Existing serialized controller] + C --> N[Owned native playlist provider] + C --> M[Shared guarded MA provider in trusted GM browser] + M -->|private authenticated API WebSocket| A[Private MA 2.10.6] + A -->|authenticated Sendspin to pinned existing identity| S[Official SDK in GM browser] + S --> W[Web Audio MediaStream] + W -->|DTLS SRTP media tracks| P[Authorized player browsers] + G[Foundry module socket] <-->|bounded encrypted SDP only| S + G <-->|bounded encrypted SDP only| P +``` + +No raw audio or MA token uses the ordinary module socket. No MA HTTP/WS/Sendspin +proxy is exposed to players. No microphone is requested and no RTC control data +channel is accepted. A GM's credentials are **not hidden from that GM/browser user**; +all code executing in that browser origin must be trusted. Other player browsers +never receive the MA credential, SDK identity, private queue snapshots or endpoint. + +## What is measured + +`evidence/browser-audio.json`: actual Chromium **143.0.7499.4**, two independent +listener browser contexts, original 440 Hz synthetic PCM encoded in Sendspin binary +frames and decoded by the pinned official SDK, Web Audio -> WebRTC -> HTMLAudio / +listener analyser. Both listeners had signal after **1,757 ms**, FFT peak **445.3125 +Hz** (bin resolution around the 440 Hz source), RMS about **0.054**, aggregate GM RTP +payload **42.3 kbps** over **4.766 seconds**. Four encrypted signaling messages, +maximum **2,078 bytes**; no audio on the signaling channel. Localhost, no TURN, no +MA/Noise handshake, no real Foundry socket, no hardware audibility claim, no WAN, +interlistener skew or long-run drift measurement. These are synthetic path results, +not MA playlist playback or synchronization verification. + +Live dedicated target/queue reads still verify the existing DEV identity and an +empty idle queue. `module-only-prerequisites.json`: the configured MA origin is +HTTP, the HTTPS-host access policy rejects it as mixed content, and no authorized +DEV private SDK identity is available locally. **Zero new Sendspin connections, +identities or playback mutations.** Earlier read-only catalogs and bounded idle +controls remain separate evidence; synthetic ingestion previously failed. + +## Browser access and GM-local authentication + +`GMAudioHost` uses a private, memory-only profile supplied by the GM, with canonical +MA origin, dedicated target ID/name/provider, approved provider filter, catalog key/ +namespace and existing SDK identity/pairing storage. Nothing is saved into Foundry +settings, flags, browser localStorage, module socket or a release. Catalog IDs remain +HMAC-derived and stable when the operator retains the same private key/namespace. + +The official public `/ws` control API avoids dependence on cross-origin HTTP `/api` +preflight, which is not configured for that route in the inspected MA pin. The same +fixed client command allowlist, response bounds, timeout, redirect policy, target +checks and registered-media rules are preserved through the WebSocket adapter. +Its initial auth command carries the GM's token in a private connection, never a +URL; unsolicited events are discarded. The Sendspin `/sendspin` connection uses +the official frontend's first-message auth pattern, then the official SDK's Noise +transport. The SDK's fixed roles include controller/metadata; it runs only in the +trusted GM host, never as a supposedly restricted player listener. + +A source-derived privacy gate matters: pinned MA `websocket_client.py` logs raw +received frames at VERBOSE, including auth. The GM profile requires an explicit +operator `webSocketAuthLogSafe` acknowledgment after ensuring such payload logging +is disabled. This has **not** been verified live or changed by the agent. No live +WebSocket token test was attempted. The module logs no credential and does not +modify MA logging/core. An adapter cannot redact the remote server's own logs. + +HTTPS Foundry -> plain HTTP/ws private MA is not a generally portable browser path, +even with encrypted Sendspin payloads. CSP, browser local-network access rules, +Origin policy, TLS trust and private routing still apply. Current policy refuses +that deployment rather than disabling browser protections. Local-network exceptions +in particular browsers are not a cross-browser guarantee. A private trusted HTTPS/ +WSS MA endpoint reachable by the GM, or the approved co-located restricted worker, +is required. Players do not need MA network access. + +SDK identity is derived from an X25519 private key. A player name or ID alone cannot +reconstruct it. The code checks the supplied identity matches **Adaptive Music DEV** +before any receiver connection; no random replacement, discovery-and-select, pairing +or internal virtual-player provisioning occurs. Operator-controlled handover from +the original web player is needed. Read-only identity/topology checks may inspect +the known unavailable target during handover; every mutation still requires full +availability, exact name/provider, own active queue and standalone topology. + +## WebRTC signaling, authorization and transport + +Foundry's supported `game.socket`/module channel is a relay, not an authenticated +claim of sender identity. We do **not** trust a payload `userId`/`isGM` or assume +that broadcast destinations enforce confidentiality. The GM explicitly issues a +unique short-lived 256-bit per-listener invitation, delivered over an authenticated +private channel outside the module broadcast. Possession authorizes only that peer; +it does not prove a Foundry login cryptographically, and a recipient can forward +its own capability/audio. No automatically broadcast bootstrap exists. + +`SignalCodec` authenticates/encrypts SDP (including ICE addresses/DTLS fingerprints) +with AES-GCM, session/peer/direction/sequence binding, nonce, expiry, size/type limits +and replay checks rechecked after asynchronous decryption. A listener can affect +only its own peer; another peer has another key. `PeerAudio` permits one recvonly +listener offer and audio-only answer, rejects video/data/outbound listener audio, +bounds peers, drops unknown frames, permits at most two explicit ICE restarts, and +revokes on expiry, disconnect or authorization reconciliation. Continuous media is +browser-managed DTLS-SRTP, never JSON PCM over Foundry sockets. + +Default ICE servers are **empty**: no silent external STUN/TURN or telemetry. +Operator-provided STUN/TURN configuration is explicit. TURN credentials must be +short-lived; relay-only mode requires TURN and avoids direct peer candidates. +Authorized peers can inspect their own ICE/network details and credentials. Direct +P2P may disclose GM/peer network addresses to the authorized peer; encryption hides +SDP from other world clients, not its intended recipient. No secrets are protected +from the browser's own user. Existing public-interface references: +[Foundry Game/socket](https://foundryvtt.com/api/v14/classes/foundry.Game.html), +[WebRTC connectivity](https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Connectivity), +[mixed content](https://developer.mozilla.org/en-US/docs/Web/Security/Defenses/Mixed_content). + +Symmetric NAT, CGNAT, UDP filtering and restrictive corporate networks can need TURN; +STUN alone cannot guarantee connectivity. A relay must already exist or be separately +approved, not installed as another container/VM by this module. One GM peer connection +per listener means approximately linear GM upload/encoding cost. The 42.3 kbps local +measurement is two listeners and short synthetic content, not a capacity promise. +Browser jitter buffers, suspend/background policy and output devices introduce +independent playout delay: Sendspin's upstream timestamps do not create synchronized +WebRTC outputs automatically. Measure WAN jitter/skew and 30-minute drift before any +sync guarantee. Crossfade and concurrent ambient layers remain unimplemented. + +## Authority, lifecycle and restoration + +Policy remains manual (including silence) > explicit eligible boss > started active +combat for the scene > scene ambient > world default > silence. Bosses use module +flags/priority, no actor HP/schema. Scene/world assignments, explicit native fallback, +legacy flag migration, snapshots, interrupted paused offsets and duplicate ordered +occurrences are preserved. Ambient is currently the single interrupted base queue; +AmbientSound and effects remain untouched. Optional companion control retains its +expiring fenced lease; native document ownership stays explicitly opted in. + +GM-local control shares the same serialized, generation-checked provider and target +checks. A Web Lock excludes duplicate GM tabs on the same origin; startup requires +one active GM and a known empty idle target. This is **not a distributed server fence** +and cannot prevent a malicious/stale independent GM client with its own MA token. +The module refuses automatic split-brain handover and invalidates authority on +Foundry disconnect. Permanent strict multi-writer fencing needs the approved worker. +No browser-only design can manufacture an MA server-side compare-and-swap lease. + +GM loss stops WebRTC forwarding and automated writes; it cannot guarantee immediate +restoration after a crashed/offline browser, and already delivered audio cannot be +revoked from a recipient. SDK-adopted sockets do not auto-reconnect. Explicit reconnect +requires target reconciliation, same identity, secure access, new peer invitations +and role checks. Native fallback cannot silently bypass an uncertain active MA target. + +The preserved MA snapshots are signed, scoped to campaign/session/fence/generation, +expire after five minutes and carry ordered occurrences, index, whole-second offset, +pause/state and repeat. Capture repeats pagination; restore stages ordered items, +checks them and seeks. Shuffled/dynamic/autoplay/overlay/ended/nonstandard speed +states are unsupported. Remote ambiguity latches closed rather than retrying blindly. +Restart/crash durability, shuffled restoration and true cross-client fencing remain +acceptance gates. The bounded live harness still captures/restores original state; +closing an experimental GM tab is not claimed to restore MA automatically. + +## Optional minimal co-located fallback + +If secure private browser reachability, network traversal or GM uptime is unacceptable, +review a single non-root worker on the **existing Foundry host**, using existing host +runtime/network capacity and protected state. It would terminate only the dedicated +MA receiver, hold credentials server-side, enforce controller/listener authorization +and expose restricted campaign audio/control through the existing TLS origin. It +must never forward arbitrary MA API/WS/Sendspin messages. Existing `gateway/` code is +a validated starting point, but actual Sendspin termination, durability and production +security remain work. No system service is installed automatically, no host is +provisioned and no Foundry/MA core is changed. Any real route/placement/deployment +must be proposed concretely and approved first; nothing is deployed here. diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..17e1792 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,33 @@ +# Changelog + +## 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. diff --git a/INSTALL.md b/INSTALL.md new file mode 100644 index 0000000..6daaa1b --- /dev/null +++ b/INSTALL.md @@ -0,0 +1,150 @@ +# Adaptive Music 0.5.0 — manual release and installation + +Module ID **adaptive-music**, author **CheddahBoxMB**, Foundry generation **14**; +system-independent, no mandatory Foundry modules. Native operation needs only this +module ZIP. No container, VM/LXC, Ubuntu sandbox, core patch or automatically installed +OS service is required. GM-local MA/WebRTC audio remains experimental; limitations +and measured results are in ARCHITECTURE.md and evidence/browser-audio.json. + +## Build offline without Git credentials or a remote + +From this repository (Python 3 standard library; local Git metadata is optional): + +``` +python3 scripts/release.py +python3 scripts/release.py --validate dist/releases/v0.5.0/adaptive-music.zip +``` + +This creates `dist/releases/v0.5.0/adaptive-music-release-v0.5.0.zip`. It contains: +`adaptive-music.zip`, standalone `module.json`, `adaptive-music-source.zip`, README, +this INSTALL guide, CHANGELOG, LICENSE, THIRD-PARTY-NOTICES, all vendor license +texts, `release.json` and `SHA256SUMS`. The SDK bundle is committed, so packaging +needs no npm installation, browser download, network, Git token or Git-host access. +The builder never verifies, contacts, creates or pushes a remote repository. + +For another host, for example your own public GitHub repository: + +``` +python3 scripts/release.py --repository https://github.com/OWNER/adaptive-music --output dist/github-release +``` + +Use a real destination under your control. The generated manifest's `url`, stable +`manifest` and version-specific `download` are changed together. The builder does +not write to the Git host or alter the root manifest. It validates identity, v14 +compatibility, import/assets closure, SDK hash, licenses, private-file exclusion and +public HTTPS URL shape locally. This cannot prove that a planned URL exists. + +## Upload to the planned Gitea destination manually + +Planned repository (existence/access **not checked**): +`https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music` + +1. On your own initiative, use Gitea's web UI to create/confirm that repository and + enable public read access to the source manifest and release attachments. Foundry + must be able to fetch them without Git credentials. This exposes release files, + not MA. This agent has not accessed or authenticated with your Gitea server. +2. Unpack the **source archive**, not the outer release bundle, into the repository + using your normal Git/web upload workflow. Preserve directory structure, notices, + scripts and the generated root `module.json`. Exclude `.local/`, node_modules, + private deployment files and credentials. Do not upload an outer bundle as the + module contents. If web upload cannot preserve folders, use your own local Git + client; no credential is needed by the release builder itself. +3. Create tag/release **v0.5.0** for this version. Keep that tag immutable. Paste the + CHANGELOG entry into the release notes. Do not mark this unverified development + release as Foundry-verified or production-ready. +4. Upload **adaptive-music.zip** and **module.json** as release attachments with + those exact names. Upload source/archive, SHA256SUMS, docs/notices or the full + outer bundle as additional review artifacts. Never use the source ZIP or outer + bundle as the module download attachment. +5. After publishing, manually verify anonymous downloads and checksums. The module + ZIP should resolve at: + `https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/releases/download/v0.5.0/adaptive-music.zip` +6. Ensure `main/module.json` is the generated standalone manifest. The stable + installation/update URL is: + `https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/raw/branch/main/module.json` + This URL is deliberately stable across releases. Do not give Foundry a tag-specific + manifest URL if you expect automatic version discovery. + +No URL above was requested by the build/validation process. Uploading/publishing is +manual; no token, remote connection, automatic push or release publication is used. + +## Install and update through Foundry + +Once the public manifest and release attachments actually exist: + +1. In isolated Foundry v14 Setup → Add-on Modules → Install Module, paste the stable + manifest URL above and install. Enable Adaptive Music in the isolated world. +2. Configure Settings → Adaptive Music setup: select dedicated native music playlists, + save ownership/reload, set world/scene ambient/combat/boss/native fallback choices, + then enable automation. Sound effects/AmbientSound are excluded. Automation + defaults off. Test real v14.371 behavior before considering production use. +3. For later versions, preserve the module ID and stable manifest URL. Bump semantic + version in module.json/package.json/lockfile, update CHANGELOG and build a new + immutable tag-specific release. The versioned ZIP URL must change with version. +4. Publish new attachments **before promoting the new standalone manifest to main**. + Prepare on a release branch/tag if needed, leaving the previous main manifest + untouched until assets are available. Never overwrite a previous version's ZIP. +5. Foundry Setup → Update Modules should discover the newer manifest version and + download its new ZIP while keeping world/document settings. This is the standard + update contract and is validated structurally, not measured against your server. + +GitHub uses the same ZIP and upload process, with a stable generated manifest at +`https://raw.githubusercontent.com/OWNER/adaptive-music/main/module.json` and ZIP at +`https://github.com/OWNER/adaptive-music/releases/download/v0.5.0/adaptive-music.zip`. +Optional pinned GitHub/Gitea CI workflows only test/build artifacts for manual +publication on an already provisioned runner. They install no runner/service or +runtime infrastructure. CI/host execution has not been validated on your Gitea. + +## GM-local MA and WebRTC experiment + +The intended module-only path is: private MA → official Sendspin JS SDK in the GM +browser → Web Audio → encrypted WebRTC audio tracks → authorized player browsers. +Foundry module sockets carry only encrypted bounded SDP/control, never continuous +raw audio or an MA token. No STUN/TURN service is silently selected. Per-listener +invitations must be delivered privately, not posted to a module socket/public flag. + +The GM must be able to reach MA privately over a browser-allowed secure connection. +An HTTPS Foundry page cannot be assumed to access plain HTTP/ws MA just because the +Sendspin payload is encrypted. CSP, local-network permissions and server Origin policy also apply. The GM-local control adapter uses the official /ws API because HTTP /api CORS preflight is not enabled in the inspected MA pin. +No mixed-content bypass or public MA route is provided. Browser-local MA credentials +are visible to that GM/user and any compromised code running in their browser; +this design does not claim otherwise. Players never receive those credentials. + +Developer API (explicit operator actions; no automatic playback on module enable): + +- `api = game.modules.get('adaptive-music').api` +- `api.readGMCatalog(profile)` reads through GM-local authentication. +- `api.startGMHost(profile)` must be invoked directly by a user gesture with automation + stopped and the optional companion disconnected. `profile` stays in GM memory. +- `api.inviteListener(userId, {iceServers: []})` creates a unique expiring invitation. + Deliver it over a private authenticated channel to that participant. +- Player gesture: `api.listenWebRTC(invitation)`. No microphone/control channel. +- `api.peerStats()` returns sanitized bandwidth/jitter statistics. +- `api.closeGMHost()` tears down the local host. MA state recovery still requires + the existing guarded bounded test procedure; do not assume tab closure restores MA. + +The private profile requires MA origin/token, pinned existing DEV ID/name/provider, +approved providers, a base64 32-byte catalogKey and namespace retained privately, +plus the **existing DEV Sendspin identity and pairing storage**, and `webSocketAuthLogSafe: true` only after verifying that MA raw WebSocket payload logging at VERBOSE is disabled. The pinned server would otherwise log the auth frame/token; no logging configuration was changed or verified here. No real profile is bundled or +stored in world settings/flags/localStorage. `campaign` is supplied by the module. +Use only previously approved generated synthetic sequences and explicit synthetic +playback opt-in; real library playlist playback is a separate authorization gate. + +The current sandbox has **no existing DEV private identity**. The module refuses to +register a random replacement or hijack a name-matching player. The GM must privately +supply an authorized export of the existing web player's identity, or separately +approve a new dedicated identity and update the target/account binding. No such +provisioning has occurred. Synthetic files also still need to be reachable by MA. + +WebRTC without a configured relay cannot guarantee remote connections behind all +NAT/firewall combinations. TURN, if required, must be an explicitly approved existing +service with short-lived credentials; no new container/VM or service is installed. +The GM's upload scales with listener count and their browser must stay running. +Startup also requires one active GM, a browser Web Lock and a reconciled empty idle test target. Read-only identity checks can inspect the known unavailable target during operator handover; every mutation still rechecks full availability/topology. GM loss stops forwarding, invalidates automation authority and requires explicit +reconciliation/reconnection; no seamless handover or distributed MA fence is claimed. + +If browser access/NAT/GM-availability gates cannot be satisfied, an optional minimal +co-located worker on the **existing Foundry host** is the fallback design. Its source +is retained in gateway/ and branch experimental/companion-0.4.0. It is not installed, +started or required by the module. Any host placement, TLS route or manual service +registration needs separate approval; MA remains private. No core modifications. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..0226beb --- /dev/null +++ b/LICENSE @@ -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. diff --git a/PROGRESS.md b/PROGRESS.md new file mode 100644 index 0000000..f0c1c13 --- /dev/null +++ b/PROGRESS.md @@ -0,0 +1,104 @@ +# Adaptive Music progress — 0.5.0 + +Continued from `50c3a7c`; the complete 0.4.0 companion implementation is preserved +at local branch `experimental/companion-0.4.0` as well as in `gateway/`. The original +0.3.0 ZIP gap audit remains `evidence/package-objective-audit.json`; it describes +that historical package, not the current release. No validated code was discarded. + +## Implemented + +The standard release is one module ZIP, ID `adaptive-music`, author CheddahBoxMB, +Foundry generation 14, no mandatory modules or system dependency. Python's offline +builder produces a complete manual upload bundle, stable manifest/versioned download, +source archive, docs/licenses and checksums. Gitea/GitHub repository base is configurable. +The default destination is the user's **planned, unconfirmed** Gitea repository. +It was not contacted, authenticated with, created or pushed to. Git remotes and +credentials are not required. CI artifact workflows are prepared but unexecuted; +no runner or OS service is installed. Publication and hosted updates are unverified. + +Native playback and scene/world/combat/boss/manual configuration are preserved. +Persistent ambient/combat/boss/native fallback references, world defaults, legacy +migration, explicit combatant flags and native ownership remain connected to the +existing controller. The shared guarded MA client/provider now use Web Crypto, +retaining the optional companion import paths and stable catalog IDs/signatures. + +The new experimental GM host uses the official pinned Sendspin 5.0.0 SDK, a +reproducible PCM-only browser bundle with audited notices, Web Audio termination +and WebRTC audio tracks. GM-local MA authentication uses the public `/ws` API; +no raw unrestricted proxy, browser player credential or external CDN is introduced. +The existing DEV private identity must match before a receiver connection; no new +identity/target/pairing or internal provisioning was attempted. Only approved +synthetic sequences can be controlled by this path. Real catalog selections are +available through the developer connection API and existing assignment UI; actual +playlist playback is still separately gated. GM setup for MA remains developer-API +based; there is no claim of a finished one-click connection wizard. + +Listener capabilities are separate from controller access. Foundry module sockets +carry per-peer encrypted bounded SDP/control; WebRTC transports continuous audio. +No microphone, video, data channel, automatic STUN/TURN or raw PCM socket transport. +Expiry, revocation, role changes and disconnect tear down peers; there are bounded +explicit ICE restarts. Same-origin GM Web Locks and a single-active-GM check reject +obvious conflicts, but do not constitute a distributed MA fence. Memory-only secret +handling cannot hide secrets from the GM browser's own user. + +## Actual observations + +- **85 JS / 15 Python tests pass**; repository privacy/attribution and recorded + upstream hashes pass. Online npm advisory audit reports zero vulnerabilities. + The SDK and dependencies are pinned; no installation hooks ran. Exact command + evidence is retained in `evidence/development-checks.txt`. +- An actual Chromium decoder → Web Audio → WebRTC experiment delivered original + synthetic PCM to two listeners: signal at 1.757 s, RMS approximately 0.054, + aggregate GM RTP payload approximately 42.3 kbit/s. Four encrypted control messages. + This was a loopback socket shim, not actual Foundry, MA, WAN or a sync measurement. + See `evidence/browser-audio.json`. +- Fresh live MA read-only checks verified the dedicated DEV identity/topology and + empty idle queue. Configured MA is HTTP; HTTPS Foundry would fail mixed-content + policy. No existing DEV private identity is present in the GM profile. No receiver + connection, new identity or playback mutation was made in this revision. +- Pinned MA source logs received WebSocket frames at VERBOSE. Before token-bearing + WS auth the module requires explicit operator acknowledgment that payload logging + is disabled. This was neither checked nor changed live. No WS auth test occurred. +- Previous restricted catalog and idle-state live controls are retained. Prior + bounded runs restored their original empty idle state. Synthetic ingestion failed + previously (timeout/HTTP 400). No actual MA music audio, nonempty live restore, + combat/boss interruption with audible MA content or real playlist acceptance. + +## Testable inside isolated Foundry + +Without infrastructure: install/enable the module, GM native ownership/setup, +world and scene assignments surviving reload, boss flags/priority, manual overrides, +active combat policy, native playback/restoration and explicit native fallback. +These behaviors are unit/fixture tested; real Foundry v14.371 testing remains pending. + +With separately supplied secure private MA access, existing DEV identity/pairing, +log review and synthetic ingestion: developer GM connection/catalog and synthetic +control, then listener WebRTC invitations and audio. Test actual Foundry socket +relay with distinct logged-in users before assuming the loopback benchmark applies. +See INSTALL.md and TESTING.md for precise steps/acceptance boundaries. + +## Remaining blockers and next infrastructure decision + +1. Supply a licensed isolated Foundry v14.371 world/browser session for actual install, + native playback, socket, document and reconnect acceptance; production is excluded. +2. Operator must provide private trusted HTTPS/WSS MA access reachable by the GM, + the existing DEV identity/pairing, and authentication-log review. No public MA + endpoint or network configuration weakening is acceptable. New identity/target + binding would require separate explicit authorization. +3. Make the generated synthetic tracks readable through an approved existing MA + provider/private range-capable source. Do not modify existing playlists. This + minimum ingestion change is still unimplemented/unverified, not silently waived. +4. WAN peers may require an explicitly approved existing TURN relay with short-lived + credentials. Measure NAT reachability, latency, bandwidth, skew and reconnect. +5. Browser-only GM loss/crash cannot guarantee automatic restore or continuity; + durable distributed fencing and crash recovery need the optional minimal worker + on the existing Foundry host. Actual Sendspin termination in that worker remains + work. Deployment/routing/service changes need a concrete proposal and approval; + nothing has been deployed. No additional machine/container is proposed. +6. Crossfade, independent concurrent ambient layers, shuffled exact restoration and + actual MA playlist playback remain unsupported/unaccepted. No production readiness. + +The manual release can be uploaded without any of those runtime prerequisites; +they gate MA audio acceptance, not native module packaging. Next authorization, if +browser gates cannot be met, is review of a concrete restricted co-located worker +and existing-host TLS route. This release does not authorize deploying that fallback. diff --git a/README.md b/README.md new file mode 100644 index 0000000..f4508e6 --- /dev/null +++ b/README.md @@ -0,0 +1,61 @@ +# Adaptive Music — 0.5.0 development + +Independent open-source project by **CheddahBoxMB**, targeting Foundry VTT **v14.371** +and Music Assistant **2.10.6**, independent of game system and other modules. +This is a development release; it has not been exercised inside an actual Foundry +world. No production installation or external service is changed by building it. + +Install `adaptive-music.zip` through Foundry's normal module manifest mechanism. +[INSTALL.md](INSTALL.md) covers manual Gitea publication, installation, updates and +isolated testing. The configured repository is **planned, not confirmed**. No +connection to it was made. An uploaded, anonymously readable manifest and release +asset are required before Foundry installation by URL can work. + +The standard module includes native playlist playback, persistent separate scene +ambient/combat/boss/native fallback assignments, global defaults, manual overrides, +combat automation and the existing snapshot/restore controller. The GM setup menu +configures native ownership and assignments. Automation defaults off. Only +explicitly owned native music playlists are eligible; sound effects are out of scope. + +The new **experimental GM browser host** shares the validated MA provider/catalog +code, uses the bundled official Sendspin SDK's PCM decoder and Web Audio, and +sends audio to invited listeners with WebRTC. Supported Foundry module sockets carry +only encrypted bounded signaling, never continuous audio. GM credentials remain in +GM memory and are visible to that browser's user; players receive individual +expiring audio capabilities. No Docker, VM, LXC, external module, permanent sandbox, +core patch, OS service or public MA endpoint is required by the module. + +This path is a developer API experiment, not a completed one-click MA setup. +The existing DEV receiver's private identity/pairing, private browser-reachable TLS, +authentication-log review and MA ingestion of the approved synthetic sequences are +still prerequisites. Real catalog entries can be displayed/assigned, but only the +authorized synthetic sequences are enabled for experimental MA playback. The +companion implementation remains optional experimental source and is preserved at +local branch `experimental/companion-0.4.0`; it is not needed for native playback. + +Measured in Chromium: the official decoder and WebRTC delivered synthetic 440 Hz +PCM to **two** listener contexts, with first signal at **1.757 s** and approximately +**42.3 kbit/s** aggregate GM RTP payload. This used a loopback signaling shim, not +Foundry or MA. WAN/NAT/TURN, inter-listener synchronization, audible MA output and +nonempty live queue restoration remain unverified. Crossfade and simultaneous +ambient layers are not implemented. GM loss ends forwarding; seamless failover or +crash restoration is not promised. + +Build a complete manual release bundle locally, without Git credentials or a remote: + +```sh +python3 scripts/release.py +# To prepare the same release for GitHub instead: +python3 scripts/release.py --repository https://github.com/OWNER/REPOSITORY --output dist/github +``` + +Output: `dist/releases/v0.5.0/adaptive-music-release-v0.5.0.zip`, containing the +installable module, standalone manifest, source archive, documentation, licenses +and SHA256 checksums. The manifest uses a stable branch URL and a version-specific +release download. Build automation validates both but does not publish anything. +Prebuilt browser assets are included; end users do not need Node/npm or Python. + +For contributor commands and evidence see [TESTING.md](TESTING.md), +[PROGRESS.md](PROGRESS.md), [ARCHITECTURE.md](ARCHITECTURE.md) and +[SECURITY.md](SECURITY.md). MIT project license; upstream MIT/Apache notices and +full dependency licenses are retained in `THIRD-PARTY-NOTICES` and `licenses/`. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..b74ac7a --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,133 @@ +# Security — standalone module and optional host fallback + +The module installs through the normal Foundry manifest/ZIP mechanism. No runtime +Docker/VM/LXC, sandbox host, third-party Foundry module, core modification, service +installer or public MA endpoint is required or created. The optional companion is +retained as experimental source/branch, not a mandatory backend. Co-located host +placement/routing/manual service setup is a proposal requiring separate approval. + +## Trust boundaries + +Only an elected single active GM may initiate GM-local MA access. The GM explicitly +supplies a memory-only private profile; that GM/browser user can inspect its token, +identity and private data. JavaScript private fields are not a secret store against +the browser owner, debugger, compromised same-origin code or server administrator. +No contrary claim is made. Trust all code served into the GM origin. A player never +receives the GM's MA token/profile, SDK private key, upstream URL or queue payload. + +Profiles/tokens are not persisted in Foundry settings, flags, localStorage, sockets, +logs, release files or URLs. Operator private backups belong outside the module's +public files; existing development secrets stay under ignored `.local/` (0700, +regular owner-matching files 0600, symlinks refused). Catalog references are opaque +HMAC identifiers, stable only with retained operator key/namespace. Configured native +ownership and scene/world references are public world data, never MA credentials. + +GM control uses the official private MA `/ws` API, with fixed command allowlists, +correlated bounded responses and discarded unsolicited events, behind the preserved +MA target/media/provider checks. The MA account's role still grants broader writes; +filtering is defense in depth, not the sole boundary. No endpoint selector, queue +transfer, grouping, unrestricted HTTP/WS/Sendspin proxy or household discovery is +available to players. No new identity is registered: supplied X25519 SDK identity +must match the already verified DEV target before connecting; reconnecting an existing +known unavailable target never relaxes mutation guards. SDK auth is first-message, +not a token URL. Only original synthetic test sequences may be enabled for playback. + +A precise upstream logging limitation: MA 2.10.6's WebSocket handler logs raw frames +at VERBOSE, including auth payloads. No live token WebSocket test was attempted and +no upstream log configuration was read/changed. The GM profile requires explicit +`webSocketAuthLogSafe` operator review of disabled raw-frame logging before use. +The module's own logs omit credentials; it cannot redact MA's logs without changing +that upstream behavior. Do not assume default logging or ignore this gate. + +## Browser network/security policy + +Private network access from an HTTPS Foundry page still needs permitted routing, +trusted TLS/WSS, CSP and server/browser Origin/local-network policies. Sendspin Noise +does not waive mixed-content restrictions. Current module policy refuses HTTPS -> +non-loopback HTTP/ws MA; modern per-browser local-network exceptions are not a +portable supported deployment. HTTP `/api` CORS is also insufficient in the inspected +pin; GM control instead uses the public authenticated WebSocket API, not a CORS +bypass proxy. No private API is exposed publicly to fix browser access. + +No public third-party STUN/TURN is silently used. Default ICE servers are empty; +relay configuration is explicit and TURN credentials must be short-lived. Browser +users necessarily see their own relay credentials and decrypted peer signaling. +Direct P2P can reveal network addresses to the authorized peer; relay-only mode can +reduce that exposure if an approved relay already exists. It cannot guarantee WAN +connectivity without appropriate infrastructure. No service/container is provisioned. + +## Signaling and players + +Ordinary Foundry module sockets carry only bounded encrypted SDP/control envelopes, +never continuous PCM/audio chunks, MA commands, media URLs, tokens or invitation +secrets. Claimed sender IDs/GM flags are not trusted as authentication. The GM issues +a unique expiring 256-bit per-listener capability out of band over a private +authenticated channel. Possession authorizes that one peer, not a proven login. +A recipient can share its own capability/record received audio; this cannot be +prevented by browser JavaScript. Do not distribute a controller/MA secret as an invite. + +AES-GCM covers SDP/ICE/DTLS fingerprints with session/peer/direction/sequence binding, +nonce/expiry, strict fields/types/size limits and asynchronous replay rechecks. A +listener may negotiate one recvonly audio m-line; video, outbound listener audio and +RTC data/control channels are rejected. Keys are per listener, so one recipient +cannot forge another listener's authorized exchange. Invalid broadcast frames are +dropped; world-server/socket flooding is still a server-side availability concern, +not solved by client encryption. Explicit peer/expiry/restart bounds limit our work. + +Media uses browser DTLS-SRTP WebRTC audio tracks. No microphone is requested. GM +revocation stops new media, but cannot erase audio already delivered or force a +malicious recipient to discard buffered/recorded content. Real Foundry identity, +packet validation, WAN/NAT and browsers still need live acceptance. + +## Authority, failure and original state + +Target identity/provider, own active queue, standalone topology and current authority +are rechecked immediately before each mutation. Snapshot and prepared data remain +scoped, generation-checked and serialized. Signed snapshots preserve ordered duplicates, +index/offset/state/repeat for static unshuffled supported queues; expiry, foreign, +tampered or future state denies. Ambiguous remote writes latch closed with no blind +retry. Unsupported shuffle/dynamic/autoplay/overlay/ended/speed states fail closed. +Only the campaign-owned target is eligible; volume/mute state is read before SDK +handover instead of assuming maximum output. Native effects/AmbientSound stay unowned. + +The optional companion retains its process-local fenced lease checks. GM-local control +has one-GM checks and a same-origin Web Lock, **not a distributed MA server fence**. +It cannot protect against a malicious/stale independent GM with MA credentials. +Multiple-GM automation/hard fencing remains a readiness blocker. No automatic GM +handover, queue ownership transfer or speaker grouping exists. Foundry disconnect +stops forwarding and future writes; an offline/crashed GM cannot guarantee restoration. +Native fallback never skips reconciliation of an uncertain active MA target. + +Existing bounded live harnesses still capture original state and report restoration +success/failure explicitly. No new playback mutation or Sendspin pairing was attempted +in this revision; the read-only check observed an empty idle dedicated queue. The browser measurement +used original synthetic PCM, not real MA or licensed-service content. Existing +synthetic ingestion failure and identity/TLS/logging gates remain. Crossfade, +simultaneous layers, durable recovery and deployment security are not claimed complete. + +## Release and supply-chain safeguards + +The release builder runs offline, uses no Git credential/remote API and never contacts +the planned Gitea server. It validates public HTTPS URL shape, stable manifest and +versioned ZIP consistency, module ID/author/v14 compatibility, no false `verified` +claim, no mandatory systems/modules, import closure, notices, SDK hash and privacy +patterns. It rejects private/symlinked package files. Exact private token/endpoint/target +scans of history and artifacts supplement these guardrails; they are not a +comprehensive secret scanner or proof of uncontacted server availability. + +Official SDK 5.0.0 and noble dependencies are pinned/audited and bundled locally; +there is no runtime CDN or installer. Full Apache/MIT texts accompany releases. +Optional Opus fallback imports are explicitly disabled in the PCM-only SDK build; +libopus/speex/opus-encdec binaries are not distributed. WebRTC's browser codec is not +bundled by this project. Install hooks were disabled. Developer-only Playwright/ +esbuild tools and local Chromium are not shipped or a runtime dependency. + +CI workflows use pinned action commits on an existing shell runner, build artifacts +for manual publication, and install no services or infrastructure. No Git host was +accessed/authenticated/created/pushed on the user's behalf. Public release files +contain no private MA addresses/credentials/deployment data. A source archive is not +an installable Foundry ZIP; documentation distinguishes both. + +Peer signaling also bounds each peer to four queued control frames and 64 received +control attempts per invitation, limiting asynchronous decrypt/SDP backlog. Socket +flooding of the Foundry server remains a server/operator availability concern. diff --git a/SOURCE_REVISION.txt b/SOURCE_REVISION.txt new file mode 100644 index 0000000..aab0c1e --- /dev/null +++ b/SOURCE_REVISION.txt @@ -0,0 +1 @@ +1ccdd229e40e1e02f0fa76d8fc553877c66c9494 diff --git a/TESTING.md b/TESTING.md new file mode 100644 index 0000000..61889cf --- /dev/null +++ b/TESTING.md @@ -0,0 +1,102 @@ +# Adaptive Music verification — 0.5.0 + +## Regression and offline release validation + +The current suite has **85 JavaScript tests** and **15 Python tests**. Tests cover +controller transitions, signed snapshots, target/topology guards, durable catalog +IDs, native restore behavior, scene/default/combat interfaces, optional companion +scope/replay protection, GM access policy, official PCM decoder, encrypted WebRTC +signaling/replay checks, public MA WebSocket correlation and offline release contracts. +These are fixtures and source checks, not live Foundry/MA playback tests. + +```sh +PATH="$HOME/.nvm/versions/node/v24.23.0/bin:$PATH" npm test +python3 -m unittest discover -s tests -v +python3 scripts/audit_repository.py +python3 scripts/verify_upstream.py +python3 scripts/release.py +python3 scripts/release.py --validate dist/releases/v0.5.0/adaptive-music.zip +``` + +Python uses the standard library. Upstream verification requires ignored pinned +research copies; it does not fetch/install them. Browser assets are prebuilt and +SHA256 verified. Optional rebuilding uses Node 24.23.0, `npm ci --ignore-scripts` +and `node scripts/build_sendspin.mjs`. No install hooks were run. The online npm +advisory audit of the pinned dependency tree reported **zero vulnerabilities**; +this is an advisory observation, not a safety guarantee or an offline audit. + +Release tests exercise repeatable ZIP generation, embedded/standalone manifest +identity, missing import/asset rejection, URL versioning, GitHub configuration, +checksums, attribution, private-content exclusion and rebuilding from a source +archive without Git metadata. Neither the builder nor these tests contact Gitea. +CI workflows generate artifacts only on an already provisioned shell runner. +They have not run on GitHub or Gitea; Gitea Actions/artifact compatibility is untested. + +## Measured browser audio experiment + +`evidence/browser-audio.json` records an actual Chromium 143.0.7499.4 experiment: +official Sendspin 5.0.0 decoder → Web Audio → WebRTC → two listener browser contexts. +The original 440 Hz synthetic tone produced RMS 0.05391/0.05396 and FFT peaks +445.3125 Hz (nearest frequency bin). All listeners had signal at 1.757 s; during +4.766 s observation, the GM sent 25,198 RTP payload bytes, approximately 42.3 kbit/s +aggregate. Four encrypted signaling messages (maximum 2,078 bytes), no raw audio +on signaling. AudioContexts/HTMLAudioElements were unlocked by actual page clicks. + +Optional reproduction after a separate Playwright Chromium download: + +```sh +PLAYWRIGHT_BROWSERS_PATH=.local/browsers node scripts/measure_browser_audio.mjs +``` + +The harness starts a temporary loopback static server and a socket shim, uses +headless Chromium with `--no-sandbox` only for the development experiment and +closes them afterwards. This is not a real Foundry socket integration, live MA +Sendspin handshake, WAN/NAT/TURN test, perceptual quality test or synchronization +measurement. Browser dependencies/binaries do not ship with the module. + +## Live MA evidence and limits + +`ma-readonly.json` records prior authenticated restricted account checks, dedicated +target/provider restrictions and catalog reads. `ma-adapter.json` records eleven +playlists/one radio and stable opaque identifiers across adapter reconstruction. +`ma-live-history.json` and `ma-playback.json` record prior bounded idle-queue runs: +shuffle/repeat/stop and exact restoration to empty/idle/unshuffled/repeat-off/zero. +They verify neither audible music nor restoration of a nonempty queue. + +`module-only-prerequisites.json` adds fresh authenticated **read-only HTTP** +verification of the fixed DEV identity/topology and empty idle queue. The configured +MA endpoint is HTTP; an HTTPS Foundry page fails the module mixed-content gate. +The existing receiver private identity is absent from the GM profile. No receiver +was created, no Sendspin connection attempted and no playback command issued in +this revision. MA 2.10.6 source logs received WebSocket frames at VERBOSE: operator +log review is required before token-bearing `/ws` authentication. No live WS auth +was attempted. Route behavior and authentication protocol are source-derived. + +Prior synthetic URI ingestion timed out/returned HTTP 400; approved six-track +ambient/combat WAV sequences are not established as ingestible. Actual MA playlist +playback remains a separate content-approval acceptance test. Synthetic browser +PCM does not satisfy it. Household devices, grouping, queue transfers, production +Foundry and network/service configuration remain untouched. + +## Remaining acceptance tests + +In an isolated Foundry v14.371 world: install/enable ZIP, test native ownership, +scene ambient/combat/boss and world defaults, explicit combatant flags, manual +silence/clear, rapid transitions and native fallback. Validate supported socket +signaling using two logged-in users; private invite delivery and revocation, user +role changes, disconnects and automation shutdown need real-world confirmation. + +Before live MA audio: operator supplies the existing DEV identity/pairing without +registering a new target; makes private secure MA browser access available without +public exposure; confirms token-bearing WS frames cannot enter logs; supplies +approved synthetic ingestion. Recheck exact target/group/queue before every write. +Capture and restore original state with a bounded harness. Then test seeking, +interrupt/restore, rapid/nested contexts and stereo/format handling with listeners. +Do not treat mocked nonempty restoration as live evidence. Real playlists require +separate approved content. Record an explicit restoration failure if it occurs. + +Remote WAN trials must measure ICE/TURN reachability, expiry/reconnect, throughput, +latency and listener skew; none is inferred from the loopback result. GM restart, +durable nonempty live restore, distributed fencing, crossfade, background tab +behavior and service fallback termination remain unsupported or unverified as +specified in ARCHITECTURE.md. No production readiness claim. diff --git a/THIRD-PARTY-NOTICES b/THIRD-PARTY-NOTICES new file mode 100644 index 0000000..52a3672 --- /dev/null +++ b/THIRD-PARTY-NOTICES @@ -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. diff --git a/evidence/SENDSPIN-PROVISIONING.md b/evidence/SENDSPIN-PROVISIONING.md new file mode 100644 index 0000000..964c269 --- /dev/null +++ b/evidence/SENDSPIN-PROVISIONING.md @@ -0,0 +1,30 @@ +# Sendspin provisioning research — 2026-12-03 + +Evidence class: source inspection only. MA 2.10.6, commit +`c24866405bd2068c25a60e1014e5ef8c3f6445bb`; new inspected file hashes recorded in +`upstream.json`. No upstream code copied, dependency installed or provisioning run. + +`providers/sendspin/provider.py:656` defines `create_virtual_player(owner_instance_id, +display_name, player_id=None)`. This is an in-server Python provider API, not a +registered external HTTP command. It requires a loaded provider owner, checks +ownership/collisions, prefixes stable IDs, registers the client and queue, and +persists the owner marker. Removal deletes configuration; unloading the owner +removes its targets. Restart requires the owner to recreate the anchor. See the +same directory's README, “Virtual Players”, and `_register_virtual_player_client`. + +This anchor discards its own audio. Its documented delivery mechanism attaches +member players through standard grouping. That mechanism does not meet Adaptive +Music's no-grouping boundary and is not an adopted gateway audio source. Creating +an anchor alone would not terminate audio at the gateway. + +`player.py:_refresh_client_info` recognizes web/app clients from device information +and makes them standalone/private. A future isolated gateway Sendspin client with +an operator-assigned stable identity could be researched as a dedicated receiver, +but needs protocol/Noise/codec and reconnect tests, licensing/dependency review, +explicit target creation approval, and an operator update of the nonempty account +player filter. An arbitrary new identity must never be automatically selected. +No public automatic provisioning path suitable for the current external gateway +was established. Existing Adaptive Music DEV remains the only authorized target. + +Decision: retain the manually provisioned development target. Do not add an MA +plugin, use grouping, create resources, or change production settings in this milestone. diff --git a/evidence/SENDSPIN-RECEIVER.md b/evidence/SENDSPIN-RECEIVER.md new file mode 100644 index 0000000..2a10e7f --- /dev/null +++ b/evidence/SENDSPIN-RECEIVER.md @@ -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. diff --git a/evidence/UPSTREAM.md b/evidence/UPSTREAM.md new file mode 100644 index 0000000..bd9af4a --- /dev/null +++ b/evidence/UPSTREAM.md @@ -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. diff --git a/evidence/browser-audio.json b/evidence/browser-audio.json new file mode 100644 index 0000000..dd586d1 --- /dev/null +++ b/evidence/browser-audio.json @@ -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" +} diff --git a/evidence/ci-actions.json b/evidence/ci-actions.json new file mode 100644 index 0000000..e59396a --- /dev/null +++ b/evidence/ci-actions.json @@ -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" +} diff --git a/evidence/connected-ma-readonly.json b/evidence/connected-ma-readonly.json new file mode 100644 index 0000000..89acc12 --- /dev/null +++ b/evidence/connected-ma-readonly.json @@ -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 +} diff --git a/evidence/connectivity.json b/evidence/connectivity.json new file mode 100644 index 0000000..8503ee5 --- /dev/null +++ b/evidence/connectivity.json @@ -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" +} diff --git a/evidence/development-checks.txt b/evidence/development-checks.txt new file mode 100644 index 0000000..98da569 --- /dev/null +++ b/evidence/development-checks.txt @@ -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 diff --git a/evidence/ma-adapter.json b/evidence/ma-adapter.json new file mode 100644 index 0000000..b2b7ec0 --- /dev/null +++ b/evidence/ma-adapter.json @@ -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 +} diff --git a/evidence/ma-live-history.json b/evidence/ma-live-history.json new file mode 100644 index 0000000..af83361 --- /dev/null +++ b/evidence/ma-live-history.json @@ -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" +} diff --git a/evidence/ma-playback.json b/evidence/ma-playback.json new file mode 100644 index 0000000..c3904ad --- /dev/null +++ b/evidence/ma-playback.json @@ -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 + } +} diff --git a/evidence/ma-readonly.json b/evidence/ma-readonly.json new file mode 100644 index 0000000..0b18d4f --- /dev/null +++ b/evidence/ma-readonly.json @@ -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 +} diff --git a/evidence/milestone-checks.txt b/evidence/milestone-checks.txt new file mode 100644 index 0000000..3c6648b --- /dev/null +++ b/evidence/milestone-checks.txt @@ -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 diff --git a/evidence/module-only-prerequisites.json b/evidence/module-only-prerequisites.json new file mode 100644 index 0000000..bcc598c --- /dev/null +++ b/evidence/module-only-prerequisites.json @@ -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 +} diff --git a/evidence/module-package.json b/evidence/module-package.json new file mode 100644 index 0000000..b5b4e33 --- /dev/null +++ b/evidence/module-package.json @@ -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 + } + ] +} diff --git a/evidence/package-objective-audit.json b/evidence/package-objective-audit.json new file mode 100644 index 0000000..04bd989 --- /dev/null +++ b/evidence/package-objective-audit.json @@ -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 + } + ] + } +} diff --git a/evidence/privacy-audit.json b/evidence/privacy-audit.json new file mode 100644 index 0000000..a8f5c70 --- /dev/null +++ b/evidence/privacy-audit.json @@ -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" +} diff --git a/evidence/release-acceptance.json b/evidence/release-acceptance.json new file mode 100644 index 0000000..0d6bb46 --- /dev/null +++ b/evidence/release-acceptance.json @@ -0,0 +1,24 @@ +{ + "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 +} diff --git a/evidence/sdk-adoption.json b/evidence/sdk-adoption.json new file mode 100644 index 0000000..a4652c6 --- /dev/null +++ b/evidence/sdk-adoption.json @@ -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" +} diff --git a/evidence/synthetic-fixtures.json b/evidence/synthetic-fixtures.json new file mode 100644 index 0000000..ade9995 --- /dev/null +++ b/evidence/synthetic-fixtures.json @@ -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" + } + ] + } +} diff --git a/evidence/synthetic-ingestion.json b/evidence/synthetic-ingestion.json new file mode 100644 index 0000000..0e70d2e --- /dev/null +++ b/evidence/synthetic-ingestion.json @@ -0,0 +1,6 @@ +{ + "checked_at": "2026-12-03T17:18:24.860Z", + "synthetic_ingestion": false, + "error": "unavailable", + "playback_mutations": 0 +} diff --git a/evidence/synthetic-pipeline.json b/evidence/synthetic-pipeline.json new file mode 100644 index 0000000..41ed1d4 --- /dev/null +++ b/evidence/synthetic-pipeline.json @@ -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 +} diff --git a/evidence/upstream.json b/evidence/upstream.json new file mode 100644 index 0000000..fde04cc --- /dev/null +++ b/evidence/upstream.json @@ -0,0 +1,131 @@ +{ + "checked_at": "2026-12-03", + "git_sources": [ + { + "repository": "https://github.com/Sayshal/vgmusic", + "tag": "release-1.4.5", + "commit": "eba07a08c9925f31b9c8adb72faf95de11ae705c", + "local_directory": "vgmusic", + "files": { + "LICENSE": "8da4373e2f64fdd0289d5aba0ad81856f39742582dfa8caf49b22eece53e62d0", + "module.json": "2a50f7dfaaf91e953f6ffde97c8d58f5c88ab3cf2499863cf873d8f264539357", + "package.json": "6e607c8234023df368935e22fd7463d15ac6ab357e604899999c8a78ee1747fa", + "package-lock.json": "245c2723ddfc25a549e600630a324603e9cb234553dc392c8c5c92cc6da896f2", + "scripts/music-controller.mjs": "fc51195eda3c9cb8e04b9fc90ab9a4bd91c99ce6735a54929cf2bf3fa7404ccf", + "scripts/hooks.mjs": "069f1ede780ef1d55c51d65ff17322606f2d89f83d7d02284d2b1149a44898a0", + "scripts/playlist-context.mjs": "5126fbdef6b8129e6a8050da098a6fd904b02684565db014b9afe53d00bd2c0f" + } + }, + { + "repository": "https://github.com/music-assistant/server", + "tag": "2.10.6", + "commit": "c24866405bd2068c25a60e1014e5ef8c3f6445bb", + "local_directory": "server", + "files": { + "LICENSE": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4", + "pyproject.toml": "39e6e2cd3962b081b6b8d2b905846d1e79a3ebc21f330d8003bf748f6913c84c", + "requirements_all.txt": "bf97bece2eaca5c0a9beead3a9a2f4e9cf66228c891e6580cb074219c1b2a141", + "music_assistant/controllers/webserver/controller.py": "93a3784d2c2070be512ed2f4619a6ea32088cb91aaa13879ab2fc2a7725a2f06", + "music_assistant/controllers/webserver/auth.py": "462717a6b2486c692d18f3917b26cf12eb036d1bb31ab1a4d0281a9ab505b116", + "music_assistant/controllers/webserver/websocket_client.py": "7ad62ba1f015914cdea6f99c8cac384a4c10ee33fb5b03ab0b6049cce729ecfd", + "music_assistant/controllers/webserver/sendspin_proxy.py": "0b2a25363786e8ef13a460b18c43e1a4a9d0ba30d816349a61f8db7421b85e7e", + "music_assistant/controllers/player_queues/controller.py": "3d610ee9b643a5a338104fbf13d67d2b680b7d4570bc7dfe2364e4d9712b4588", + "music_assistant/providers/sendspin/manifest.json": "cb99a3715f32c573a5120b960e5c3a31c6823bfc269f4963b8d72910132e38ea", + "music_assistant/controllers/webserver/helpers/auth_middleware.py": "f1c45cc4927c9a5e71193b13ff9d4300daaa65dc7b849d255c924fa495fb24a5", + "music_assistant/controllers/players/controller.py": "fd4a66cfe2b28ab7859f46990b3c45f58778d9fbb8dfb196346bed516a012c99", + "music_assistant/controllers/music/media/base.py": "a47aa23c9ed1039e303db1e4da1903c84d2122ed7c66c2b66ad8edd2d7341d45", + "music_assistant/providers/sendspin/provider.py": "9ba7235cd48723255a1d7e4af28f8f90f0e7448f4b234228571e219fa92ccb14", + "music_assistant/providers/sendspin/player.py": "306251735f52295cce3293549ca7f226fe37cab4d454966e8fb657aca7c535c6", + "music_assistant/providers/sendspin/README.md": "ee43c336550a7f4b8cac188f77e6d4e0b580d47d94321f392738d93da9e2c890", + "music_assistant/controllers/player_queues/queue_loader.py": "ead02948ca4450d3651d0c90683df16a16e8b6e23a040bf16b3eb877756e7a0e", + "music_assistant/helpers/uri.py": "c97c43f28db833910635bc89268dd44cb2487b3c26005737f55eb6c1f55521ca", + "music_assistant/providers/builtin/__init__.py": "54349ff427defa5a8c6664ccbcaf47c6564e1eb1606def5b8572c6d57e77df91", + "music_assistant/controllers/music/media/playlists.py": "7dbc38f93688a2b4f6fcd0501607a22942af55766d40f81795beef0dc037eb3e", + "music_assistant/controllers/player_queues/helpers.py": "0206927895599dae0b1dd4842a37d11d5d8e0de539e8f710b07684572de25529" + } + }, + { + "repository": "https://github.com/music-assistant/frontend", + "tag": "2.17.297", + "commit": "e779b9d359e47cd210c2801f16a0ce6263571903", + "local_directory": "frontend", + "files": { + "LICENSE": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4", + "package.json": "83c66acc4371e0f10119ee50ee3d6940e3126fbf36898de02875331a590847c6", + "pnpm-lock.yaml": "129e7a8526a2e96c37f53bcc1895292cb56a73443c373198974ac7aa90b40093", + "src/plugins/sendspin-connection.ts": "780f52ad85fa38b1789267a50f03c744d59b59fa3dca3599ae0f742b150173ee" + } + }, + { + "repository": "https://github.com/sendspin/sendspin-js", + "tag": "5.0.0", + "commit": "7d103075138dda5c8909045647bb42b33c2d44fc", + "local_directory": "sendspin-js-5", + "files": { + "LICENSE": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4", + "package.json": "6e1a04d4cf82ddae3e09ac7964952c718395b22a6de260f2e092d9848235aa88", + "src/core/protocol-handler.ts": "b3108d57fbaf974dd7aaf2b8bf0102817928fa1de501b0806b52bdd50a5d9436", + "src/core/transport.ts": "0d855eab42e1f94ef94e5aa324244eadd0e6fe99cb8be8e528199ab07cedb6b2", + "src/audio/clock-source.ts": "bd1c7321702211db42e3bedac746c0fa490a1e12215c3e34ec6b372a2c48a0e6", + "src/audio/decoder.ts": "0abefd87c26079cde9e2f87ad4c8d77a19818818d4ae745002e22930afac1e6a", + "src/audio/output-latency-tracker.ts": "1f5f6492fbb8ee7c1b2dc15c0299c7bbb62aa7dd356c8845c6c4e4178017d7c7", + "src/audio/platform-output-latency.ts": "ad916a598042e1a28578e9568668cdf2c3f880950f9232c438eebbdb34a1519a", + "src/audio/recorrection-monitor.ts": "075660439b7d1ae4140979c20d92a4b15d0842adf4d66f2ad32be031d2116858", + "src/audio/scheduler.ts": "d6d5b134d83d06c0d93b3da49aa70503e38da2fe5800f5029f299b233dd38b9a", + "src/client-identity.ts": "27b645e35d7967577c3a63246128b26350989e4a6ec8cfd66687682c048c4726", + "src/core/activate-authorization.ts": "e2a23dec97ef03829baafee8a4c83075e29c4c265d281926b2ce921d0ec1ccab", + "src/core/codec-support.ts": "fe160adfa40d2c5e0a3b3edd255ea94a283bf98e77431846ae3a0048e6cc50ce", + "src/core/core.ts": "44ce239896faca0887dbf33b5d5b7de924a3ee94c8babfe4e631ef6a82c2c5db", + "src/core/noise/base64url.ts": "0a8fc8f065de1b79497cd166cdfd02f0b1a8558d371bd641c0f8ab6f13cb9a16", + "src/core/noise/cipher-state.ts": "f31000531f6c5aecdbab4cb7ea3d2bfe3911fb58136b72c9e9a58cd0c386cd5d", + "src/core/noise/constants.ts": "bde591118b52136f90cd7e41f6901494c4a1cfae61cb0edaea26b599337829de", + "src/core/noise/handshake.ts": "40caa0df0098d1121a50547614b3564837241945d136fd2faab9202d8228ee3a", + "src/core/noise/identity.ts": "9f23c76b71aa7558aed9a6d416a5c9e75c69798cd74748454d96e96b9791022e", + "src/core/noise/index.ts": "0facbc17a2621f2e9ebf86dd1fadf5efece71028a495eb7165c62c8fe68c8218", + "src/core/noise/pairing-token.ts": "dfbc2e88478bbf9b7e4559c6597206b2262de431007143f8b3d099000980b762", + "src/core/noise/psk.ts": "7c5028446c85ff15e61f1afbee8fa6cc95628afb670018a107f0bd33622acafd", + "src/core/noise/session.ts": "fc1c6747c3d556920e5ac21726f1baa401c575ff6efe9546c8aa6687ebc95c50", + "src/core/noise/suites.ts": "59ba4f407a462c82afbd15568af682de823b012e5e831e67b368a2506d696abc", + "src/core/noise/symmetric-state.ts": "c498ce9caaf89af44076fa89dbd1fc8919289c6ca1b6de2a9670f4b99496a5f9", + "src/core/pairing.ts": "59c0994b3cd422035b98812268e2e87a87b99554786e8da46936af751cbcdc34", + "src/core/pake/cpace.ts": "fed37dbc91bb0f7711492a8481598982c887f14e244c0d1ef1ec0d59a103a2ec", + "src/core/pake/pin.ts": "5852b68967caa92626636f9cb48be3fd527ebee6911ddd54228740674efb71e4", + "src/core/state-manager.ts": "827fff0bbbb6153d807f21456a952f73b61b3aa81fa7bcd5b7aad7362ad122f9", + "src/core/static-delay-store.ts": "265dddae81afe28a8d1b376560e70cbe8c8c26f996ace0bf0bd1be84079d8f29", + "src/core/time-filter.ts": "0d562c167deb3cbdc2b7a23e5baa6f2dc70f214e5307b89903762f01dd6000f7", + "src/core/time-sync-manager.ts": "d64b7b648422333f68bafa878b2b3e2c084bd91d00f980b88c51c4ad8b07f913", + "src/core/websocket-manager.ts": "4acada3e75f19f63f2f7e6d367c545e2dc37a8735fdb32a40e100d94e6bb96db", + "src/index.ts": "e4ba034a7ab604ab80786ca255c73821cd4951ffc4a80c1bf24c4db3fb8d173b", + "src/internal-types.ts": "26e818c95bf831a7123788ca79cba104fc05c887e654c5e67bae06b9669cc2e2", + "src/opus-encdec.d.ts": "e05ec654daf12453bfe44d81b0ec8bc5162d1cd47a12df4502d0e879ca6be40a", + "src/sync-delay.ts": "8bdc54745a7b75da3d2dc78133e82601241323f9e33ee381f9c657d58c58916f", + "src/types.ts": "939c8df601891ad7b483fafa49df2b837e834881685f7e2278eb9e2ffd5dea15" + } + }, + { + "repository": "https://github.com/sendspin/sendspin-js", + "tag": "6.1.0", + "commit": "7ee7ca35ac29ae3ef5f2eeeeaac1e24751a8790b", + "local_directory": "sendspin-js", + "files": { + "LICENSE": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4", + "package.json": "b6cae2c9836e467941bb7baab35bde2ead29f3171ce8be18fdb23b758d6b30e9" + } + } + ], + "pypi_sources": [ + { + "version": "9.1.1", + "url": "https://files.pythonhosted.org/packages/73/f0/03f798813a0e09f4e1565691d2e5138f0750c98b36d93f522d06c44efe66/aiosendspin-9.1.1.tar.gz", + "sha256": "1e9a33ec5b6dcbc16b4f03c07586195beaa80eb2e5ba4254b97979ae0e0ec4b7", + "inspected_files": { + "LICENSE": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4", + "README.md": "c7f2aaeb734b6628edf06ea9b4a5b425f25a5949a606a3d7f1f3dfb2268c749d", + "pyproject.toml": "940b19e327b155d56ca4935a6d62b946a28b60b734e4f35f61c49bd7b194798c", + "aiosendspin/client/client.py": "1fb7911997417fc97b85221de84935a0c4ae6cfc71d6dc29ca2e2aef5e4b4a08", + "aiosendspin/noise/trust_store.py": "b5a8dbd3f5d6692dca9ccdd4e9eba8eb9b706fa1ced69ef91bb8dcccb0d3f37f" + }, + "local_directory": "aiosendspin/aiosendspin-9.1.1" + } + ] +} diff --git a/gateway/README.md b/gateway/README.md new file mode 100644 index 0000000..87b64f5 --- /dev/null +++ b/gateway/README.md @@ -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. diff --git a/gateway/SETUP.md b/gateway/SETUP.md new file mode 100644 index 0000000..6893da0 --- /dev/null +++ b/gateway/SETUP.md @@ -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. diff --git a/gateway/control.mjs b/gateway/control.mjs new file mode 100644 index 0000000..0c9beb6 --- /dev/null +++ b/gateway/control.mjs @@ -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 }; + } +} diff --git a/gateway/development-http.mjs b/gateway/development-http.mjs new file mode 100644 index 0000000..8dc6376 --- /dev/null +++ b/gateway/development-http.mjs @@ -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;}}; +} diff --git a/gateway/development-service.mjs b/gateway/development-service.mjs new file mode 100644 index 0000000..aca7cf8 --- /dev/null +++ b/gateway/development-service.mjs @@ -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.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=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; + } +} diff --git a/gateway/loopback-audio.mjs b/gateway/loopback-audio.mjs new file mode 100644 index 0000000..98ec66f --- /dev/null +++ b/gateway/loopback-audio.mjs @@ -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; + } + }; +} diff --git a/gateway/ma-client.mjs b/gateway/ma-client.mjs new file mode 100644 index 0000000..d86ba6b --- /dev/null +++ b/gateway/ma-client.mjs @@ -0,0 +1,2 @@ +// Compatibility export; validated transport is shared with the GM-local browser path. +export {MAReadClient} from '../src/providers/ma/client.mjs'; diff --git a/gateway/ma-provider.mjs b/gateway/ma-provider.mjs new file mode 100644 index 0000000..4a1b6b8 --- /dev/null +++ b/gateway/ma-provider.mjs @@ -0,0 +1,2 @@ +// Compatibility export; the same provider now runs with browser Web Crypto. +export {MAPlaybackProvider} from '../src/providers/ma/provider.mjs'; diff --git a/gateway/pcm-fixture.mjs b/gateway/pcm-fixture.mjs new file mode 100644 index 0000000..caaf875 --- /dev/null +++ b/gateway/pcm-fixture.mjs @@ -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 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(); } +} diff --git a/gateway/run-development.mjs b/gateway/run-development.mjs new file mode 100644 index 0000000..242dc9a --- /dev/null +++ b/gateway/run-development.mjs @@ -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;} diff --git a/gateway/synthetic-audio.mjs b/gateway/synthetic-audio.mjs new file mode 100644 index 0000000..6cf952f --- /dev/null +++ b/gateway/synthetic-audio.mjs @@ -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(); + } +} diff --git a/licenses/Apache-2.0.txt b/licenses/Apache-2.0.txt new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/licenses/Apache-2.0.txt @@ -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. diff --git a/licenses/VGM-MIT.txt b/licenses/VGM-MIT.txt new file mode 100644 index 0000000..75e7c5d --- /dev/null +++ b/licenses/VGM-MIT.txt @@ -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. diff --git a/licenses/vendor/-noble-ciphers.txt b/licenses/vendor/-noble-ciphers.txt new file mode 100644 index 0000000..5a53d5f --- /dev/null +++ b/licenses/vendor/-noble-ciphers.txt @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) +Copyright (c) 2016 Thomas Pornin + +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. \ No newline at end of file diff --git a/licenses/vendor/-noble-curves.txt b/licenses/vendor/-noble-curves.txt new file mode 100644 index 0000000..9297a04 --- /dev/null +++ b/licenses/vendor/-noble-curves.txt @@ -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. \ No newline at end of file diff --git a/licenses/vendor/-noble-hashes.txt b/licenses/vendor/-noble-hashes.txt new file mode 100644 index 0000000..9297a04 --- /dev/null +++ b/licenses/vendor/-noble-hashes.txt @@ -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. \ No newline at end of file diff --git a/licenses/vendor/-sendspin-sendspin-js.txt b/licenses/vendor/-sendspin-sendspin-js.txt new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/licenses/vendor/-sendspin-sendspin-js.txt @@ -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. diff --git a/module.json b/module.json new file mode 100644 index 0000000..8dec30a --- /dev/null +++ b/module.json @@ -0,0 +1,28 @@ +{ + "id": "adaptive-music", + "title": "Adaptive Music \u2014 Development", + "description": "Independent scene/combat music automation and experimental GM-local Sendspin/WebRTC audio. Native playback works without a companion; remote MA audio requires validated browser/network access.", + "version": "0.5.0", + "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.5.0/adaptive-music.zip" +} diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..9f997a8 --- /dev/null +++ b/package-lock.json @@ -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" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..6f124fb --- /dev/null +++ b/package.json @@ -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" + } +} diff --git a/scripts/audit_repository.py b/scripts/audit_repository.py new file mode 100644 index 0000000..de13570 --- /dev/null +++ b/scripts/audit_repository.py @@ -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'(? 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)) diff --git a/scripts/build_sendspin.mjs b/scripts/build_sendspin.mjs new file mode 100644 index 0000000..8f5aa98 --- /dev/null +++ b/scripts/build_sendspin.mjs @@ -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.'); diff --git a/scripts/check_connected_catalog.mjs b/scripts/check_connected_catalog.mjs new file mode 100644 index 0000000..c815f2f --- /dev/null +++ b/scripts/check_connected_catalog.mjs @@ -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();} diff --git a/scripts/check_ma_adapter.mjs b/scripts/check_ma_adapter.mjs new file mode 100644 index 0000000..94f5293 --- /dev/null +++ b/scripts/check_ma_adapter.mjs @@ -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;} diff --git a/scripts/check_module_only_prerequisites.mjs b/scripts/check_module_only_prerequisites.mjs new file mode 100644 index 0000000..e336080 --- /dev/null +++ b/scripts/check_module_only_prerequisites.mjs @@ -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)); diff --git a/scripts/check_synthetic_ingestion.mjs b/scripts/check_synthetic_ingestion.mjs new file mode 100644 index 0000000..d8c8569 --- /dev/null +++ b/scripts/check_synthetic_ingestion.mjs @@ -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; +} diff --git a/scripts/check_synthetic_pipeline.mjs b/scripts/check_synthetic_pipeline.mjs new file mode 100644 index 0000000..8cc53cb --- /dev/null +++ b/scripts/check_synthetic_pipeline.mjs @@ -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)); diff --git a/scripts/ci_release.py b/scripts/ci_release.py new file mode 100644 index 0000000..502a38a --- /dev/null +++ b/scripts/ci_release.py @@ -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)) diff --git a/scripts/live_ma_playback.mjs b/scripts/live_ma_playback.mjs new file mode 100644 index 0000000..821ddf7 --- /dev/null +++ b/scripts/live_ma_playback.mjs @@ -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; +} diff --git a/scripts/live_ma_preflight.mjs b/scripts/live_ma_preflight.mjs new file mode 100644 index 0000000..aa9f73b --- /dev/null +++ b/scripts/live_ma_preflight.mjs @@ -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;} +} diff --git a/scripts/measure_browser_audio.mjs b/scripts/measure_browser_audio.mjs new file mode 100644 index 0000000..f07ff2c --- /dev/null +++ b/scripts/measure_browser_audio.mjs @@ -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;iwindow.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));} diff --git a/scripts/package_module.py b/scripts/package_module.py new file mode 100644 index 0000000..5a30e6f --- /dev/null +++ b/scripts/package_module.py @@ -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. diff --git a/scripts/probe_ma.py b/scripts/probe_ma.py new file mode 100644 index 0000000..b9eae68 --- /dev/null +++ b/scripts/probe_ma.py @@ -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)) diff --git a/scripts/release.py b/scripts/release.py new file mode 100644 index 0000000..c8b1bb6 --- /dev/null +++ b/scripts/release.py @@ -0,0 +1,160 @@ +"""Offline Foundry/Gitea/GitHub release generation. Never contacts a Git host.""" +from __future__ import annotations +import argparse +import hashlib +import ipaddress +import json +from pathlib import Path +import re +import subprocess +import sys +import urllib.parse +import zipfile +ROOT=Path(__file__).resolve().parents[1] +DEFAULT_REPOSITORY='https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music' +ZIP_TIME=(2000,1,1,0,0,0) +if str(ROOT/'scripts') not in sys.path:sys.path.insert(0,str(ROOT/'scripts')) + +def public_url(value): + parsed=urllib.parse.urlsplit(value) + if parsed.scheme!='https' or not parsed.hostname or parsed.username or parsed.password or parsed.query or parsed.fragment: + raise ValueError('public HTTPS URL required') + try: + address=ipaddress.ip_address(parsed.hostname) + except ValueError: + if parsed.hostname in ('localhost',) or parsed.hostname.endswith(('.local','.invalid')):raise ValueError('placeholder/local release URL') + else: + if not address.is_global:raise ValueError('private release address') + return value.rstrip('/') + +def urls(repository,version,branch='main'): + repository=public_url(repository) + parsed=urllib.parse.urlsplit(repository) + if repository.endswith('.git'):repository=repository[:-4] + if not re.fullmatch(r'[A-Za-z0-9._-]+',branch):raise ValueError('invalid branch') + if not re.fullmatch(r'\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?',version):raise ValueError('invalid release version') + if parsed.hostname=='github.com': + parts=urllib.parse.urlsplit(repository).path.strip('/').split('/') + if len(parts)!=2:raise ValueError('GitHub owner/repo required') + manifest=f'https://raw.githubusercontent.com/{parts[0]}/{parts[1]}/{branch}/module.json' + else:manifest=f'{repository}/raw/branch/{branch}/module.json' + return {'url':repository,'manifest':manifest,'download':f'{repository}/releases/download/v{version}/adaptive-music.zip'} + +def release_manifest(repository=DEFAULT_REPOSITORY,version=None,branch='main'): + manifest=json.loads((ROOT/'module.json').read_text()) + if version is not None and version!=manifest['version']:raise ValueError('tag/version must match source module.json') + manifest['version']=version or manifest['version'];manifest.update(urls(repository,manifest['version'],branch)) + validate_manifest(manifest);return manifest + +def validate_manifest(manifest): + if not isinstance(manifest,dict) or any(k not in manifest for k in ('id','authors','compatibility','version','url','manifest','download','esmodules')):raise ValueError('incomplete manifest') + if manifest.get('id')!='adaptive-music' or manifest.get('authors')!=[{'name':'CheddahBoxMB'}]:raise ValueError('module identity mismatch') + if manifest.get('compatibility',{}).get('minimum')!='14' or manifest['compatibility'].get('maximum')!='14' or 'verified' in manifest['compatibility']:raise ValueError('unsupported compatibility claim') + if manifest.get('relationships',{}).get('requires',[]) or manifest.get('systems'):raise ValueError('mandatory system/module dependency') + expected=urls(manifest['url'],manifest['version']) + for key in ('manifest','download'): + public_url(manifest[key]) + if manifest[key]!=expected[key]:raise ValueError('manifest/update URL mismatch') + if 'v'+manifest['version'] not in manifest['download']:raise ValueError('unversioned download') + + +def module_files(): + names=['module.json','README.md','INSTALL.md','CHANGELOG.md','ARCHITECTURE.md','SECURITY.md','TESTING.md','PROGRESS.md','LICENSE','THIRD-PARTY-NOTICES'] + for directory,pattern in [('src','*.mjs'),('styles','*.css'),('licenses','*'),('vendor','*')]: + names.extend(str(p.relative_to(ROOT)) for p in sorted((ROOT/directory).rglob(pattern)) if p.is_file()) + return names + +def write_zip(path,entries): + path.parent.mkdir(parents=True,exist_ok=True) + with zipfile.ZipFile(path,'w',zipfile.ZIP_DEFLATED) as archive: + for name,data in sorted(entries.items()): + info=zipfile.ZipInfo(name,ZIP_TIME);info.compress_type=zipfile.ZIP_DEFLATED;info.external_attr=0o100644<<16 + archive.writestr(info,data) + +def module_entries(manifest): + result={} + for name in module_files(): + path=ROOT/name + if path.is_symlink():raise ValueError('package symlink refused') + data=(json.dumps(manifest,indent=2)+'\n').encode() if name=='module.json' else path.read_bytes() + if name.endswith('.mjs') and (b'node:' in data or b"from '../../gateway/" in data):raise ValueError('server code in browser package') + result['adaptive-music/'+name]=data + return result + +def validate_package(path,manifest=None): + from audit_repository import findings + with zipfile.ZipFile(path) as archive: + names=archive.namelist() + if len(names)!=len(set(names)) or any(not n.startswith('adaptive-music/') or '..' in Path(n).parts or '/.local/' in n or '/node_modules/' in n or '/gateway/' in n for n in names):raise ValueError('unsafe package inventory') + actual=json.loads(archive.read('adaptive-music/module.json'));validate_manifest(actual) + if manifest and actual!=manifest:raise ValueError('embedded and standalone manifest mismatch') + for name in names: + data=archive.read(name);problems=findings(name,data.decode(errors='replace')) + if problems:raise ValueError('private content in release: '+name) + if name.endswith('.mjs'): + text=data.decode();relative_imports=re.findall(r"(?:from\s*|import\s*\()['\"](\.[^'\"]+)['\"]",text) + import posixpath + for relative in relative_imports: + resolved=posixpath.normpath(posixpath.join(posixpath.dirname(name),relative)) + if resolved not in names:raise ValueError('missing browser import: '+resolved) + for asset in actual['esmodules']+actual.get('styles',[]): + if 'adaptive-music/'+asset not in names:raise ValueError('missing manifest asset') + provenance=json.loads(archive.read('adaptive-music/vendor/provenance.json')) + if hashlib.sha256(archive.read('adaptive-music/vendor/sendspin-5.0.0.mjs')).hexdigest()!=provenance['sha256']:raise ValueError('SDK bundle hash mismatch') + required=['licenses/VGM-MIT.txt','licenses/Apache-2.0.txt','licenses/vendor/-sendspin-sendspin-js.txt','licenses/vendor/-noble-ciphers.txt','licenses/vendor/-noble-curves.txt','licenses/vendor/-noble-hashes.txt'] + if any('adaptive-music/'+name not in names for name in required):raise ValueError('missing license') + return actual + +def local_revision(): + try:return subprocess.check_output(['git','rev-parse','HEAD'],cwd=ROOT,text=True,stderr=subprocess.DEVNULL).strip() + except (subprocess.CalledProcessError,FileNotFoundError): + file=ROOT/'SOURCE_REVISION.txt' + return file.read_text().strip() if file.is_file() else 'unknown (source archive without Git metadata)' + +def source_entries(manifest): + from audit_repository import findings + try:names=subprocess.check_output(['git','ls-files','-z','--cached','--others','--exclude-standard'],cwd=ROOT,stderr=subprocess.DEVNULL).decode().split('\0') + except (subprocess.CalledProcessError,FileNotFoundError): + names=[p.name for p in ROOT.iterdir() if p.is_file() and p.name in {'.gitignore','AGENTS.md','ARCHITECTURE.md','SECURITY.md','TESTING.md','PROGRESS.md','module.json','package.json','package-lock.json','README.md','INSTALL.md','CHANGELOG.md','ARCHITECTURE.md','SECURITY.md','TESTING.md','PROGRESS.md','LICENSE','THIRD-PARTY-NOTICES','SOURCE_REVISION.txt'}] + for directory in ('src','styles','licenses','vendor','gateway','scripts','tests','evidence','.github','.gitea'): + names.extend(str(p.relative_to(ROOT)) for p in (ROOT/directory).rglob('*') if p.is_file() and '__pycache__' not in p.parts and p.suffix!='.pyc') + entries={} + for name in sorted(set(filter(None,names))): + path=ROOT/name + if name.startswith(('.local/','dist/','node_modules/','.git/')) or path.is_symlink():raise ValueError('private/unsafe source path') + if path.is_file(): + data=path.read_bytes() + if findings(name,data.decode(errors='replace')):raise ValueError('private material in source: '+name) + entries['adaptive-music-source/'+name]=data + entries['adaptive-music-source/module.json']=(json.dumps(manifest,indent=2)+'\n').encode() + entries['adaptive-music-source/SOURCE_REVISION.txt']=(local_revision()+'\n').encode() + return entries + +def build_release(repository=DEFAULT_REPOSITORY,version=None,output=None): + manifest=release_manifest(repository,version);version=manifest['version'];output=output or ROOT/'dist/releases'/('v'+version) + output=Path(output).resolve() + if output.is_relative_to(ROOT) and not output.is_relative_to(ROOT/'dist'):raise ValueError('in-repository output must be under ignored dist/') + output.mkdir(parents=True,exist_ok=True) + allowed={'adaptive-music.zip','module.json','adaptive-music-source.zip','README.md','INSTALL.md','CHANGELOG.md','ARCHITECTURE.md','SECURITY.md','TESTING.md','PROGRESS.md','LICENSE','THIRD-PARTY-NOTICES','release.json','SHA256SUMS',f'adaptive-music-release-v{version}.zip',f'adaptive-music-release-v{version}.zip.sha256'} + allowed.update(str(p.relative_to(ROOT)) for p in (ROOT/'licenses').rglob('*') if p.is_file()) + for file in output.rglob('*'): + if file.is_symlink() or file.is_file() and str(file.relative_to(output)) not in allowed:raise ValueError('unmanaged file in release output') + write_zip(output/'adaptive-music.zip',module_entries(manifest));validate_package(output/'adaptive-music.zip',manifest) + (output/'module.json').write_text(json.dumps(manifest,indent=2)+'\n') + write_zip(output/'adaptive-music-source.zip',source_entries(manifest)) + for name in ('README.md','INSTALL.md','CHANGELOG.md','ARCHITECTURE.md','SECURITY.md','TESTING.md','PROGRESS.md','LICENSE','THIRD-PARTY-NOTICES'):(output/name).write_bytes((ROOT/name).read_bytes()) + for path in (ROOT/'licenses').rglob('*'): + if path.is_file():target=output/path.relative_to(ROOT);target.parent.mkdir(parents=True,exist_ok=True);target.write_bytes(path.read_bytes()) + metadata={'version':version,'repository':manifest['url'],'manifest':manifest['manifest'],'download':manifest['download'], + 'sourceCommit':local_revision(),'destinationStatus':'planned; never contacted by this builder','foundryLiveVerified':False,'networkAccessRequired':False} + (output/'release.json').write_text(json.dumps(metadata,indent=2)+'\n') + files={str(p.relative_to(output)):p.read_bytes() for p in output.rglob('*') if p.is_file() and p.name not in ('SHA256SUMS',) and not p.name.startswith('adaptive-music-release-')} + (output/'SHA256SUMS').write_text(''.join(f'{hashlib.sha256(data).hexdigest()} {name}\n' for name,data in sorted(files.items()))) + files['SHA256SUMS']=(output/'SHA256SUMS').read_bytes();bundle=output/f'adaptive-music-release-v{version}.zip';write_zip(bundle,files) + (output/(bundle.name+'.sha256')).write_text(hashlib.sha256(bundle.read_bytes()).hexdigest()+' '+bundle.name+'\n') + return bundle + +if __name__=='__main__': + parser=argparse.ArgumentParser();parser.add_argument('--repository',default=DEFAULT_REPOSITORY);parser.add_argument('--version');parser.add_argument('--output',type=Path);parser.add_argument('--validate',type=Path);args=parser.parse_args() + if args.validate:validate_package(args.validate);print('PASS: standalone Foundry package, imports, manifest/update URLs, privacy and licenses') + else:print(build_release(args.repository,args.version,args.output)) diff --git a/scripts/synthetic_fixtures.py b/scripts/synthetic_fixtures.py new file mode 100644 index 0000000..2a0e361 --- /dev/null +++ b/scripts/synthetic_fixtures.py @@ -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') diff --git a/scripts/verify_ma_readonly.py b/scripts/verify_ma_readonly.py new file mode 100644 index 0000000..8918814 --- /dev/null +++ b/scripts/verify_ma_readonly.py @@ -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) diff --git a/scripts/verify_upstream.py b/scripts/verify_upstream.py new file mode 100644 index 0000000..dce7ef2 --- /dev/null +++ b/scripts/verify_upstream.py @@ -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)) diff --git a/src/audio/gm-host.mjs b/src/audio/gm-host.mjs new file mode 100644 index 0000000..b4bfb0a --- /dev/null +++ b/src/audio/gm-host.mjs @@ -0,0 +1,90 @@ +import {MusicError} from '../core/controller.mjs'; +import {MAReadClient} from '../providers/ma/client.mjs'; +import {MAPlaybackProvider} from '../providers/ma/provider.mjs'; +import {GMMAWebSocket} from '../providers/ma/websocket.mjs'; +import {randomKey} from '../providers/ma/webcrypto.mjs'; +export function gmAccessPolicy(baseUrl,pageUrl){ + const target=new URL(baseUrl),page=new URL(pageUrl); + if(target.username||target.password||target.search||target.hash||target.pathname!=='/'||!['http:','https:'].includes(target.protocol))throw new MusicError('denied'); + if(page.protocol==='https:'&&target.protocol!=='https:'&&!['localhost','127.0.0.1','[::1]'].includes(target.hostname))throw new MusicError('mixed-content'); + return target; +} +function memoryStorage(values){const map=new Map(Object.entries(values));return {getItem:k=>map.get(k)??null,setItem:(k,v)=>map.set(k,v),removeItem:k=>map.delete(k)};} +export class GMAudioHost{ + #authority;#sdk;#core;#context;#destination;#nodes=new Set();#client;#provider;#catalog=[];#session;#live=false;#socket;#generation=-1; #allowed=new Set(); #apiTransport; #gain; #releaseLock; + constructor({authority,pageUrl=globalThis.location?.href,loadSDK=()=>import('../../vendor/sendspin-5.0.0.mjs'),createContext=()=>new AudioContext(),createSocket=url=>new WebSocket(url)}){this.#authority=authority;this.pageUrl=pageUrl;this.loadSDK=loadSDK;this.createContext=createContext;this.createSocket=createSocket;} + get catalog(){return structuredClone(this.#catalog);} + get session(){return this.#session;} + get stream(){return this.#destination?.stream;} + get connected(){return this.#live;} + supports(ref){return this.#live&&this.#allowed.has(ref.id);} + async readCatalog(profile,{reconnecting=false}={}){ + if(!this.#authority()||this.#live)throw new MusicError('denied');if(profile.webSocketAuthLogSafe!==true)throw new MusicError('auth-log-review-required');const base=gmAccessPolicy(profile.maUrl,this.pageUrl); + const key=Uint8Array.from(atob(profile.catalogKey),c=>c.charCodeAt(0));if(key.length!==32||profile.targetName!=='Adaptive Music DEV')throw new MusicError('denied'); + this.#apiTransport?.close();this.#apiTransport=new GMMAWebSocket({baseUrl:base.origin,token:profile.token,createSocket:this.createSocket}); + this.#client=new MAReadClient({baseUrl:base.origin,token:profile.token,target:profile.target,expectedName:profile.targetName,expectedProvider:profile.expectedProvider,approvedProviders:profile.approvedProviders,catalogKey:key,campaign:profile.namespace,syntheticSequences:profile.syntheticSequences??{},fetchImpl:this.#apiTransport.fetch}); + await this.#client.verifyTarget({allowUnavailable:reconnecting});this.#catalog=await this.#client.catalog();return this.catalog; + } + async start(profile){ + if(!this.#authority()||this.#live)throw new MusicError('denied'); + const base=gmAccessPolicy(profile.maUrl,this.pageUrl); + if(profile.targetName!=='Adaptive Music DEV'||typeof profile.target!=='string'||!profile.expectedProvider?.startsWith('sendspin')||!profile.identityStorage?.['sendspin-identity-sk']||!Array.isArray(profile.approvedProviders)||!profile.catalogKey||!profile.namespace)throw new MusicError('profile-required'); + // Unlock synchronously in the caller's gesture before SDK/network work. + this.#context=this.createContext();const unlocked=this.#context.resume();this.#destination=this.#context.createMediaStreamDestination(); + try{ + this.#sdk=await this.loadSDK();await unlocked; + const storage=memoryStorage(profile.identityStorage),identity=this.#sdk.loadSendspinClientIdentity(storage); + // Never register a fresh identity or silently select a new/household player. + if(identity.clientId!==profile.target)throw new MusicError('identity-mismatch'); + const key=Uint8Array.from(atob(profile.catalogKey),c=>c.charCodeAt(0));if(key.length!==32)throw new MusicError('denied'); + if(!globalThis.navigator?.locks)throw new MusicError('unsupported'); + const lockName='adaptive-music-'+Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',new TextEncoder().encode(base.origin+profile.target))),n=>n.toString(16).padStart(2,'0')).join(''); + const released=new Promise(resolve=>{this.#releaseLock=resolve;}); + await new Promise((resolve,reject)=>{navigator.locks.request(lockName,{ifAvailable:true},async lock=>{if(!lock){reject(new MusicError('denied'));return;}resolve();await released;}).catch(()=>reject(new MusicError('unavailable')));}); + await this.readCatalog(profile,{reconnecting:true}); + const original=await this.#client.queueState({allowUnavailable:true}); + if(original.items!==0||original.state!=='idle')throw new MusicError('reconcile-required'); + if(profile.allowSyntheticPlayback===true){ + for(const id of Object.keys(profile.syntheticSequences??{})){if(!['synthetic-ambient','synthetic-combat'].includes(id))throw new MusicError('denied');this.#allowed.add(id);} + this.#catalog.push(...[...this.#allowed].map(id=>({provider:'ma',id,kind:'sequence',name:'Generated '+id.slice(10)+' sequence'}))); + } + let volumeState=this.#client.targetVolumeState(); + this.#socket=await this.#authenticatedSocket(base,profile.token,identity.clientId); + this.#core=new this.#sdk.SendspinCore({webSocket:this.#socket,storage,clientName:profile.targetName,productName:'Web Browser',codecs:['pcm'],bufferCapacity:768000,requiredLeadTimeMs:250,minBufferMs:250,useHardwareVolume:true,getExternalVolume:()=>volumeState,onVolumeCommand:(volume,muted)=>{volumeState={volume,muted};},unpairedAccess:false,reconnect:{enabled:false}}); + this.#gain=this.#context.createGain();this.#gain.connect(this.#destination); + this.#core.onVolumeUpdate=()=>this.#gain.gain.setTargetAtTime(this.#core.muted?0:Math.pow(Math.min(100,Math.max(0,this.#core.volume))/100,1.5),this.#context.currentTime,0.015); + this.#core.onAudioData=chunk=>this.#schedule(chunk); + this.#core.onConnectionClose=()=>{this.#live=false;this.#clear();for(const track of this.#destination?.stream.getTracks()??[])track.stop();}; + this.#core.onStreamClear=()=>this.#clear();this.#core.onStreamEnd=()=>this.#clear(); + this.#session=crypto.randomUUID();this.#live=true; + this.#provider=new MAPlaybackProvider({client:this.#client,campaign:profile.campaign,session:this.#session,fence:1,snapshotKey:randomKey(),authority:()=>{if(!this.#live||!this.#authority())throw new MusicError('stale');}}); + await this.#core.connect();const deadline=Date.now()+10000;while(this.#live&&!this.#core.timeSyncInfo.synced&&Date.now()setTimeout(resolve,50));if(!this.#live||!this.#core.timeSyncInfo.synced)throw new MusicError('unavailable');await this.#client.verifyTarget();return {clientIdVerified:true,catalog:this.#catalog.length,codecs:['pcm'],remoteAudio:'webrtc',audioMeasured:false,distributedFencing:false}; + }catch(error){await this.close();throw new MusicError(error instanceof MusicError?error.code:'unavailable');} + } + #authenticatedSocket(base,token,clientId){ + const url=new URL('/sendspin',base);url.protocol=base.protocol==='https:'?'wss:':'ws:'; + return new Promise((resolve,reject)=>{const socket=this.createSocket(url.href);socket.binaryType='arraybuffer';const timer=setTimeout(()=>{socket.close();reject(new MusicError('unavailable'));},8000); + const fail=()=>{clearTimeout(timer);socket.close();reject(new MusicError('unavailable'));};socket.onerror=fail;socket.onclose=fail; + socket.onopen=()=>socket.send(JSON.stringify({type:'auth',token,client_id:clientId})); + socket.onmessage=event=>{try{if(JSON.parse(event.data).type!=='auth_ok')throw Error();clearTimeout(timer);socket.onerror=null;socket.onclose=null;socket.onmessage=null;resolve(socket);}catch{fail();}}; + }); + } + #schedule(chunk){ + if(!this.#live||!this.#authority()){this.#clear();return;} + if(!this.#core.timeSyncInfo.synced||!Array.isArray(chunk.samples)||chunk.samples.length>2||!chunk.samples.length||!Number.isFinite(chunk.sampleRate)||chunk.sampleRate<8000||chunk.sampleRate>96000)return; + const frames=chunk.samples[0].length;if(frames<1||frames>chunk.sampleRate/4||chunk.samples.some(c=>c.length!==frames))return; + if(chunk.generation!==this.#generation){this.#clear();this.#generation=chunk.generation;} + const lead=(chunk.serverTimeUs-this.#core.getCurrentServerTimeUs())/1000000; + if(!Number.isFinite(lead)||lead>2||lead+frames/chunk.sampleRate<0||this.#nodes.size>=128)return; + const buffer=this.#context.createBuffer(chunk.samples.length,frames,chunk.sampleRate);chunk.samples.forEach((samples,i)=>buffer.getChannelData(i).set(samples)); + const node=this.#context.createBufferSource();node.buffer=buffer;node.connect(this.#gain);this.#gain.gain.setTargetAtTime(this.#core.muted?0:Math.pow(Math.min(100,Math.max(0,this.#core.volume))/100,1.5),this.#context.currentTime,0.015);node.onended=()=>this.#nodes.delete(node);this.#nodes.add(node);node.start(Math.max(this.#context.currentTime+0.01,this.#context.currentTime+lead)); + } + #clear(){for(const node of this.#nodes){try{node.stop();}catch{}}this.#nodes.clear();} + #ready(){if(!this.#live||!this.#authority()||!this.#provider)throw new MusicError('stale');return this.#provider;} + resolve(ref,ctx){if(!this.supports(ref))throw new MusicError('denied');return this.#ready().resolve(ref,ctx);} + snapshot(ctx){return this.#ready().snapshot(ctx);} + apply(prepared,ctx){return this.#ready().apply(prepared,ctx);} + restore(snapshot,ctx){return this.#ready().restore(snapshot,ctx);} + stopOwned(ctx){return this.#ready().stopOwned(ctx);} + async close(){this.#live=false;this.#releaseLock?.();this.#releaseLock=null;this.#clear();this.#core?.disconnect('user_request');this.#socket?.close();this.#core=null;this.#socket=null;this.#provider=null;this.#apiTransport?.close();this.#apiTransport=null;this.#client=null;this.#catalog=[];this.#allowed.clear();for(const track of this.#destination?.stream.getTracks()??[])track.stop();this.#destination=null;const context=this.#context;this.#context=null;if(context&&context.state!=='closed')await context.close();} +} diff --git a/src/audio/peer-audio.mjs b/src/audio/peer-audio.mjs new file mode 100644 index 0000000..10654ea --- /dev/null +++ b/src/audio/peer-audio.mjs @@ -0,0 +1,79 @@ +import {MusicError} from '../core/controller.mjs'; +import {SignalCodec,newAudioInvite} from './signal-codec.mjs'; +export function validateIceServers(servers){ + if(!Array.isArray(servers)||servers.length>4)throw new MusicError('denied'); + for(const server of servers){ + const urls=Array.isArray(server.urls)?server.urls:[server.urls]; + if(!urls.length||urls.length>4||urls.some(u=>typeof u!=='string'||!/^(stun|stuns|turn|turns):[^\s@]+$/.test(u)))throw new MusicError('denied'); + if(urls.some(u=>/^turns?:/.test(u))&&(!server.username||!server.credential||!Number.isFinite(server.expires)||server.expires<=Date.now()||server.expires>Date.now()+3600000))throw new MusicError('denied'); + } + return servers.map(({urls,username,credential})=>({urls,...(username?{username,credential}:{})})); +} +function audioOnly(sdp,remote){ + if(typeof sdp!=='string'||sdp.length>65536)throw new MusicError('denied'); + const media=sdp.split(/\r?\n/).filter(line=>line.startsWith('m=')); + if(media.length!==1||!media[0].startsWith('m=audio ')||/a=sendrecv|a=sendonly/.test(sdp)&&remote==='answer')throw new MusicError('denied'); +} +async function gathered(pc){ + if(pc.iceGatheringState==='complete')return; + await new Promise((resolve,reject)=>{const timer=setTimeout(()=>{pc.removeEventListener('icegatheringstatechange',check);reject(new MusicError('unavailable'));},5000);const check=()=>{if(pc.iceGatheringState==='complete'){clearTimeout(timer);pc.removeEventListener('icegatheringstatechange',check);resolve();}};pc.addEventListener('icegatheringstatechange',check);check();}); +} +export class PeerAudio{ + #socket;#userId;#isGM;#peers=new Map();#session=crypto.randomUUID();#stream;#handler;#disconnect;#create;#onStream;#onError; #rejected=0; + constructor({socket,userId,isGM,isAuthorizedUser=()=>true,onStream=()=>{},onError=()=>{},createPeer=config=>new RTCPeerConnection(config)}){ + this.#socket=socket;this.#userId=userId;this.#isGM=isGM;this.authorized=isAuthorizedUser;this.#create=createPeer;this.#onStream=onStream;this.#onError=onError; + this.#handler=frame=>{this.#receive(frame).catch(()=>{this.#rejected++;});};this.#disconnect=()=>this.reset(); + socket.on('module.adaptive-music',this.#handler);socket.on('disconnect',this.#disconnect); + } + setSource(stream){if(!this.#isGM()||stream.getAudioTracks().length!==1)throw new MusicError('denied');this.#stream=stream;} + invite(userId,{iceServers=[],ttlMs=300000,relayOnly=false}={}){ + if(!this.#isGM()||!this.authorized(userId)||!this.#stream||this.#peers.size>=8)throw new MusicError('denied');validateIceServers(iceServers); + const invite=newAudioInvite({session:this.#session,userId,iceServers,ttlMs,relayOnly});this.#entry(invite,'gm');return invite; + } + async listen(invite){ + if(this.#isGM()||invite.userId!==this.#userId||this.#peers.size)throw new MusicError('denied'); + const entry=this.#entry(invite,'listener'); + // Listener sends only a recvonly offer. No microphone or control/data channel. + entry.pc.addTransceiver('audio',{direction:'recvonly'}); + await entry.pc.setLocalDescription(await entry.pc.createOffer());await gathered(entry.pc); + await this.#send(entry,{type:'offer',sdp:entry.pc.localDescription.sdp}); + } + #entry(invite,role){ + const iceServers=validateIceServers(invite.iceServers??[]); + if(invite.relayOnly&&!iceServers.some(s=>(Array.isArray(s.urls)?s.urls:[s.urls]).some(url=>/^turns?:/.test(url))))throw new MusicError('denied'); + const codec=new SignalCodec(invite,role); // Validate before allocating a browser connection. + const pc=this.#create({iceServers,iceTransportPolicy:invite.relayOnly?'relay':'all'}),entry={invite:structuredClone(invite),role,pc,codec,tail:Promise.resolve(),restarts:0,pending:0,signals:0}; + entry.timer=setTimeout(()=>this.revoke(invite.peer),Math.max(1,invite.expires-Date.now())); + pc.ontrack=event=>{if(role!=='listener'||event.track.kind!=='audio'){event.track.stop();return;}this.#onStream(event.streams[0]??new MediaStream([event.track]));}; + pc.ondatachannel=event=>event.channel.close(); + pc.onconnectionstatechange=()=>{if(['failed','closed'].includes(pc.connectionState)){this.#onError(new MusicError('unavailable'));this.revoke(invite.peer);}}; + this.#peers.set(invite.peer,entry);return entry; + } + async #send(entry,payload){if(this.#peers.get(entry.invite.peer)!==entry)return;const frame=await entry.codec.seal(payload);if(this.#peers.get(entry.invite.peer)!==entry||entry.invite.expires<=Date.now())return;this.#socket.emit('module.adaptive-music',frame);} + async #receive(frame){ + const entry=this.#peers.get(frame?.peer);if(!entry||frame.session!==entry.invite.session)return; + if(entry.pending>=4||++entry.signals>64)throw new MusicError('denied');entry.pending++; + entry.tail=entry.tail.catch(()=>{}).then(async()=>{ + if(entry.role==='gm'&&(!this.#isGM()||!this.authorized(entry.invite.userId)))throw new MusicError('denied'); + const payload=await entry.codec.open(frame); + if(payload.type==='bye'){this.revoke(frame.peer);return;} + if(entry.role==='gm'&&payload.type==='offer'){ + // The listener's SDP is recvonly: reject video, data, injected outbound audio. + audioOnly(payload.sdp,'answer'); + if(!entry.started){entry.pc.addTrack(this.#stream.getAudioTracks()[0],this.#stream);entry.started=true;} + await entry.pc.setRemoteDescription({type:'offer',sdp:payload.sdp}); + await entry.pc.setLocalDescription(await entry.pc.createAnswer());await gathered(entry.pc); + await this.#send(entry,{type:'answer',sdp:entry.pc.localDescription.sdp}); + }else if(entry.role==='listener'&&payload.type==='answer'){ + audioOnly(payload.sdp,'offer');await entry.pc.setRemoteDescription({type:'answer',sdp:payload.sdp}); + }else throw new MusicError('denied'); + });return entry.tail.finally(()=>{entry.pending--;}); + } + async restart(peer){const entry=this.#peers.get(peer);if(!entry||entry.role!=='listener'||++entry.restarts>2)throw new MusicError('denied');await entry.pc.setLocalDescription(await entry.pc.createOffer({iceRestart:true}));await gathered(entry.pc);await this.#send(entry,{type:'offer',sdp:entry.pc.localDescription.sdp});} + revoke(peer){const entry=this.#peers.get(peer);if(!entry)return;clearTimeout(entry.timer);this.#peers.delete(peer);entry.pc.onconnectionstatechange=null;entry.pc.ontrack=null;entry.pc.close();} + reset(){for(const peer of [...this.#peers.keys()])this.revoke(peer);this.#stream=null;this.#session=crypto.randomUUID();} + close(){this.reset();this.#socket.off('module.adaptive-music',this.#handler);this.#socket.off('disconnect',this.#disconnect);} + reconcile(){for(const [peer,entry]of this.#peers)if(entry.role==='gm'&&(!this.#isGM()||!this.authorized(entry.invite.userId)))this.revoke(peer);} + diagnostics(){return {rejectedSignals:this.#rejected,peers:[...this.#peers.values()].map(e=>({role:e.role,connection:e.pc.connectionState,ice:e.pc.iceConnectionState,signaling:e.pc.signalingState}))};} + async stats(){const results=[];for(const entry of this.#peers.values()){const stats=await entry.pc.getStats();for(const item of stats.values())if(['inbound-rtp','outbound-rtp','candidate-pair'].includes(item.type))results.push({type:item.type,bytesSent:item.bytesSent,bytesReceived:item.bytesReceived,jitter:item.jitter,packetsLost:item.packetsLost,audioLevel:item.audioLevel,totalAudioEnergy:item.totalAudioEnergy,totalSamplesReceived:item.totalSamplesReceived,currentRoundTripTime:item.currentRoundTripTime});}return results;} +} diff --git a/src/audio/signal-codec.mjs b/src/audio/signal-codec.mjs new file mode 100644 index 0000000..c1baeaf --- /dev/null +++ b/src/audio/signal-codec.mjs @@ -0,0 +1,33 @@ +import {MusicError} from '../core/controller.mjs'; +const encode=bytes=>btoa(String.fromCharCode(...bytes)).replace(/\+/g,'-').replace(/\//g,'_').replace(/=+$/,''); +const decode=value=>{if(typeof value!=='string'||!/^[A-Za-z0-9_-]+$/.test(value))throw new MusicError('denied');return Uint8Array.from(atob(value.replace(/-/g,'+').replace(/_/g,'/')),c=>c.charCodeAt(0));}; +export function newAudioInvite({session,userId,ttlMs=300000,iceServers=[],relayOnly=false}){ + if(!session||!userId||!(ttlMs>0&&ttlMs<=1800000))throw new MusicError('denied'); + return {transport:'webrtc-v1',session,peer:crypto.randomUUID(),userId,secret:encode(crypto.getRandomValues(new Uint8Array(32))),expires:Date.now()+ttlMs,relayOnly,iceServers:structuredClone(iceServers)}; +} +// Module sockets carry only encrypted SDP/ICE control envelopes, never audio or MA credentials. +export class SignalCodec{ + #invite;#key;#sent=0;#received=0;#role; + constructor(invite,role){ + if(!invite||invite.transport!=='webrtc-v1'||!['gm','listener'].includes(role)||typeof invite.session!=='string'||typeof invite.peer!=='string'||!Number.isFinite(invite.expires)||invite.expires<=Date.now()||invite.expires>Date.now()+1800000||decode(invite.secret).length!==32)throw new MusicError('denied'); + this.#invite=structuredClone(invite);this.#role=role;this.#key=crypto.subtle.importKey('raw',decode(invite.secret),'AES-GCM',false,['encrypt','decrypt']); + } + async seal(payload){ + if(Date.now()>=this.#invite.expires||this.#sent>=1000||!['offer','answer','bye'].includes(payload?.type)||Object.keys(payload).some(k=>!['type','sdp'].includes(k))||payload.type!=='bye'&&(typeof payload.sdp!=='string'||payload.sdp.length>65536))throw new MusicError('denied'); + const frame={v:1,session:this.#invite.session,peer:this.#invite.peer,from:this.#role,seq:++this.#sent}; + const plain=new TextEncoder().encode(JSON.stringify(payload));if(plain.length>65536)throw new MusicError('denied'); + const iv=crypto.getRandomValues(new Uint8Array(12)),cipher=await crypto.subtle.encrypt({name:'AES-GCM',iv,additionalData:new TextEncoder().encode(JSON.stringify(frame))},await this.#key,plain); + return {...frame,iv:encode(iv),cipher:encode(new Uint8Array(cipher))}; + } + async open(frame){ + if(!frame||Object.keys(frame).sort().join(',')!=='cipher,from,iv,peer,seq,session,v'||frame.v!==1||frame.session!==this.#invite.session||frame.peer!==this.#invite.peer||frame.from==this.#role||!['gm','listener'].includes(frame.from)||!Number.isSafeInteger(frame.seq)||frame.seq<=this.#received||frame.seq>1000||typeof frame.cipher!=='string'||frame.cipher.length>88000||Date.now()>=this.#invite.expires)throw new MusicError('denied'); + try{ + const {iv,cipher,...header}=frame;const nonce=decode(iv);if(nonce.length!==12)throw Error(); + const bytes=await crypto.subtle.decrypt({name:'AES-GCM',iv:nonce,additionalData:new TextEncoder().encode(JSON.stringify(header))},await this.#key,decode(cipher)); + const payload=JSON.parse(new TextDecoder().decode(bytes)); + if(!['offer','answer','bye'].includes(payload?.type)||Object.keys(payload).some(k=>!['type','sdp'].includes(k))||payload.type!=='bye'&&(typeof payload.sdp!=='string'||payload.sdp.length>65536))throw Error(); + if(Date.now()>=this.#invite.expires||frame.seq<=this.#received)throw Error(); + this.#received=frame.seq;return payload; + }catch{throw new MusicError('denied');} + } +} diff --git a/src/core/controller.mjs b/src/core/controller.mjs new file mode 100644 index 0000000..9c3c7e7 --- /dev/null +++ b/src/core/controller.mjs @@ -0,0 +1,82 @@ +// Independent implementation informed by VGM release-1.4.5; see THIRD-PARTY-NOTICES. +export class MusicError extends Error { + constructor(code) { super(code); this.code = code; } +} +export function candidates(state) { + const scene = state.scene; + const combats = (state.combats ?? []).filter(c => c.active && c.started && c.sceneId === scene?.id); + const bosses = combats.flatMap(c => c.bosses ?? []).filter(b => b.active && b.playlist) + .sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0) || a.id.localeCompare(b.id)); + const make = (key, playlist) => ({ key, playlist: playlist ?? null }); + return [ + ...(state.overrides ?? []).slice().reverse().map(o => make(`manual:${o.id}`, o.playlist)), + ...bosses.map(b => make(`boss:${scene.id}:${b.id}`, b.playlist)), + ...combats.filter(c => c.playlist).sort((a,b) => a.id.localeCompare(b.id)) + .map(c => make(`combat:${scene.id}:${c.id}`, c.playlist)), + ...(scene?.playlist ? [make(`scene:${scene.id}`, scene.playlist)] : []), + make('default', state.defaultPlaylist) + ].map(i => ({ ...i, key: `${i.key}:${JSON.stringify(i.playlist)}` })); +} +export class MusicController { + constructor({ campaign, session, providers, authority, maxFrames = 16 }) { + Object.assign(this, { campaign, session, providers, authority, maxFrames }); + this.dirty = new Set(); + this.generation = 0; this.frames = []; this.current = null; this.tail = Promise.resolve(); + } + update(state) { + const input = structuredClone(state); + const generation = ++this.generation; + this.abort?.abort(); this.abort = new AbortController(); + const context = { campaign: this.campaign, session: this.session, generation, + signal: this.abort.signal, check: () => { + if (generation !== this.generation || !this.authority()) throw new MusicError('stale'); + } }; + const task = this.tail.catch(() => {}).then(() => this.transition(input, context)); + this.tail = task; return task; + } + async transition(state, ctx) { + ctx.check(); + const choices = candidates(state), next = choices[0]; + const valid = new Set(choices.map(i => i.key)); + this.frames = this.frames.filter(f => valid.has(f.intent.key)); + if (this.current?.key === next.key) return { unchanged: true }; + const provider = next.playlist && this.providers[next.playlist.provider]; + if (next.playlist && !provider) throw new MusicError('unsupported'); + const prepared = provider ? await provider.resolve(next.playlist, ctx) : null; + ctx.check(); + const old = this.current, outgoing = old?.playlist && this.providers[old.playlist.provider]; + const snapshot = outgoing ? await outgoing.snapshot(ctx) : null; + ctx.check(); + const frame = this.frames.findLast(f => f.intent.key === next.key); + if (old && snapshot && valid.has(old.key)) { + this.frames = this.frames.filter(f => f.intent.key !== old.key); + this.frames.push({ intent: old, snapshot }); + this.frames = this.frames.slice(-this.maxFrames); + } + const cleanup = new Set([...this.dirty, outgoing].filter(Boolean)); + for (const p of [outgoing, provider]) if (p) this.dirty.add(p); + try { + for (const p of cleanup) { ctx.check(); await p.stopOwned(ctx); } + ctx.check(); + if (provider) { + if (frame) await provider.restore(frame.snapshot, ctx); + else await provider.apply(prepared, ctx); + } + ctx.check(); + } catch (error) { + // Never restore an obsolete transition. Reconciliation is explicit after stale writes. + this.current = null; + if (error.code !== 'stale') { + ctx.check(); + for (const p of this.dirty) { ctx.check(); await p.stopOwned(ctx); } + if (snapshot) { ctx.check(); await outgoing.restore(snapshot, ctx); this.current = old; } + this.dirty.clear(); + } + throw error; + } + this.frames = this.frames.filter(f => f.intent.key !== next.key).slice(-this.maxFrames); + this.dirty.clear(); + this.current = next; + return { intent: next, restored: Boolean(frame) }; + } +} diff --git a/src/core/scene-music.mjs b/src/core/scene-music.mjs new file mode 100644 index 0000000..661efbe --- /dev/null +++ b/src/core/scene-music.mjs @@ -0,0 +1,21 @@ +import { MusicError } from './controller.mjs'; +export const musicFields = ['ambient','combat','boss','fallback']; +export const referenceKey = ref => ref ? JSON.stringify([ref.provider,ref.id]) : ''; +export function selection(value, choices, {nativeOnly=false}={}) { + if(value==='')return null; + const choice=choices.find(c=>referenceKey(c)===value && ['native','ma'].includes(c.provider) && typeof c.id==='string' && c.id.length<=256); + if(!choice || nativeOnly && choice.provider!=='native')throw new MusicError('denied'); + return {provider:choice.provider,id:choice.id}; +} +// Single music layer: ambient is the base queue interrupted by combat/boss/manual. +// These assignments do not address Foundry AmbientSound or sound effects. +export function buildMusicState({scene,combats=[],defaults={},overrides=[],choose=ref=>ref}) { + const config=scene?.music??{}; + const ambient=(Object.hasOwn(config,'ambient')?config.ambient:config.playlist)??defaults.ambient??null; + const fallback=config.fallback??defaults.fallback??null; + const selected=ref=>ref ? choose(ref,fallback) : null; + return {scene:scene && {id:scene.id,playlist:selected(ambient)},defaultPlaylist:scene ? null : selected(defaults.ambient), + overrides:overrides.map(o=>({...o,playlist:selected(o.playlist)})), + combats:combats.map(c=>({...c,playlist:selected(c.playlist??config.combat??defaults.combat), + bosses:(c.bosses??[]).map(b=>({...b,playlist:selected(b.playlist??config.boss??defaults.boss)}))}))}; +} diff --git a/src/foundry/configuration.mjs b/src/foundry/configuration.mjs new file mode 100644 index 0000000..648b74f --- /dev/null +++ b/src/foundry/configuration.mjs @@ -0,0 +1,67 @@ +import {mountMusicAssignments} from './music-editor.mjs'; +import { MusicError } from '../core/controller.mjs'; +const namespace = 'adaptive-music'; +const key = ref => JSON.stringify([ref?.provider, ref?.id]); +function validChoice(choice) { + return choice && ['native','ma'].includes(choice.provider) && typeof choice.id === 'string' && + choice.id.length > 0 && choice.id.length <= 256 && typeof choice.name === 'string'; +} +// Pass only owned native playlists and controller-authorized MA catalog choices. +// No gateway credential, endpoint or upstream URI belongs in this interface. +export async function savePlaylistConfiguration({ document, game, choices, selected }) { + if (!game.user?.isGM) throw new MusicError('denied'); + const choice = selected === '' ? null : choices.find(c => validChoice(c) && key(c) === selected); + if (selected !== '' && !choice) throw new MusicError('denied'); + const previous = document.getFlag(namespace, 'music') ?? {}; + await document.setFlag(namespace, 'music', { ...previous, + playlist: choice ? { provider: choice.provider, id: choice.id } : null }); +} +export function mountPlaylistConfiguration({ document, game, container, choices, onError = () => {} }) { + if (!game.user?.isGM || container.querySelector('[data-adaptive-music]')) return null; + if(document.documentName==='Scene')return mountMusicAssignments({document,game,container,choices,onError}); + const dom = container.ownerDocument; + const panel = dom.createElement('fieldset'); panel.dataset.adaptiveMusic = 'configuration'; + const legend = dom.createElement('legend'); legend.textContent = 'Adaptive Music'; panel.append(legend); + const label = dom.createElement('label'); label.append(dom.createTextNode('Music playlist ')); + const select = dom.createElement('select'); label.append(select); panel.append(label); + const available = choices.filter(validChoice).map(c => ({provider:c.provider,id:c.id,name:c.name})); + const add = (value, text) => { const option = dom.createElement('option'); option.value = value; option.textContent = text; select.append(option); }; + add('', 'Use the next applicable music rule'); + for (const choice of available) add(key(choice), `${choice.provider === 'ma' ? 'Music Assistant' : 'Foundry'}: ${choice.name}`); + const current = document.getFlag(namespace, 'music')?.playlist; + if (current && !available.some(c => key(c) === key(current))) add(key(current), 'Previously selected playlist is unavailable'); + select.value = current ? key(current) : ''; + const note = dom.createElement('p'); note.textContent = 'Music Assistant playback requires a separately configured gateway; this development module uses Foundry playlists.'; panel.append(note); + const status = dom.createElement('p'); status.setAttribute('role','status'); panel.append(status); + const save = dom.createElement('button'); save.type = 'button'; save.textContent = 'Save music playlist'; panel.append(save); + let saving = false; + save.addEventListener('click', async () => { + if (saving) return; + saving = true; save.disabled = true; + try { + await savePlaylistConfiguration({document,game,choices:available,selected:select.value}); + status.textContent = 'Music playlist saved.'; + } catch (error) { status.textContent = 'Music playlist could not be saved.'; onError(new MusicError(error instanceof MusicError ? error.code : 'unavailable')); } + finally { saving = false; save.disabled = false; } + }); + container.append(panel); return panel; +} +// Explicit development-only UI bootstrap. Importing this file registers nothing. +export function startConfigurationInterfaces({ game, Hooks, getChoices, onError = () => {} }) { + let disposed = false; + const panels = new Set(); + const render = async (app, html) => { + if (!game.user?.isGM) return; + const container = html?.querySelector ? html : html?.[0]; + const document = app.document; + if (!document || !container) return; + try { + const choices = await getChoices(); + if (disposed) return; + const panel = mountPlaylistConfiguration({document,game,container,choices,onError}); + if (panel) panels.add(panel); + } catch { onError(new MusicError('unavailable')); } + }; + const hooks = ['renderSceneConfig','renderCombatConfig'].map(event => [event,Hooks.on(event, render)]); + return { dispose() { disposed = true; for (const [event,id] of hooks) Hooks.off(event,id); for (const panel of panels) panel.remove(); panels.clear(); } }; +} diff --git a/src/foundry/listener-audio.mjs b/src/foundry/listener-audio.mjs new file mode 100644 index 0000000..b9d8d69 --- /dev/null +++ b/src/foundry/listener-audio.mjs @@ -0,0 +1,34 @@ +import {MusicError} from '../core/controller.mjs'; +// Gateway-terminated PCM test transport, NOT a Sendspin pass-through client. +export class ListenerAudio { + #context; #abort; #nodes=new Set(); #fetch; + constructor({fetchImpl=globalThis.fetch,createContext=()=>new AudioContext()}={}){this.#fetch=fetchImpl;this.createContext=createContext;} + async start(request){ + const stopped=this.stop();const context=this.createContext();this.#context=context; + // Called directly from Enable Audio; retain the autoplay gesture before network work. + const resumed=context.resume();await stopped;await resumed;if(this.#context!==context)throw new MusicError('stale');const abort=new AbortController();this.#abort=abort; + try{ + const response=await this.#fetch(request.url,{...request.options,signal:abort.signal}); + if(!response.ok||response.headers.get('X-Audio-Format')!=='pcm16le;rate=24000;channels=2')throw new MusicError('denied'); + const reader=response.body.getReader();let pending=new Uint8Array(),next=context.currentTime+0.06; + try{ + while(true){const {value,done}=await reader.read();if(done)break; + if(value.length>65536)throw new MusicError('unavailable'); + const bytes=new Uint8Array(pending.length+value.length);bytes.set(pending);bytes.set(value,pending.length);let offset=0; + while(offset+1920<=bytes.length){ + if(this.#abort!==abort)throw new MusicError('stale'); + if(next0.25)throw new MusicError('unavailable'); + const buffer=context.createBuffer(2,480,24000),view=new DataView(bytes.buffer,bytes.byteOffset+offset,1920); + for(let sample=0;sample<480;sample++)for(let channel=0;channel<2;channel++)buffer.getChannelData(channel)[sample]=view.getInt16((sample*2+channel)*2,true)/32768; + const node=context.createBufferSource();node.buffer=buffer;node.connect(context.destination);this.#nodes.add(node);node.onended=()=>this.#nodes.delete(node);node.start(next);next+=0.02;offset+=1920; + } + pending=bytes.slice(offset); + } + if(pending.length)throw new MusicError('unavailable'); + }finally{await reader.cancel().catch(()=>{});reader.releaseLock();} + }catch(error){if(!abort.signal.aborted)throw new MusicError(error instanceof MusicError?error.code:'unavailable');} + finally{if(this.#abort===abort)await this.stop();} + } + async stop(){this.#abort?.abort();this.#abort=null;for(const node of this.#nodes){try{node.stop();}catch{}}this.#nodes.clear();const context=this.#context;this.#context=null;if(context)await context.close();} +} diff --git a/src/foundry/module.mjs b/src/foundry/module.mjs new file mode 100644 index 0000000..d037b50 --- /dev/null +++ b/src/foundry/module.mjs @@ -0,0 +1,61 @@ +import {startNativeRuntime,primaryGM} from './runtime.mjs'; +import {startConfigurationInterfaces,mountPlaylistConfiguration} from './configuration.mjs'; +import {GatewayClient} from '../providers/ma/remote.mjs'; +import {GMAudioHost} from '../audio/gm-host.mjs'; +import {PeerAudio} from '../audio/peer-audio.mjs'; +import {ListenerAudio} from './listener-audio.mjs'; +import {createSetupClass,createListenerClass} from './setup.mjs'; +const id='adaptive-music'; +let runtime,interfaces,gateway,audio,renewTimer,gmHost,peers,remoteAudio;let authorityHooks=[]; +const gmAuthority=()=>game.ready&&game.user.isGM&&primaryGM(game.users)===game.user.id&&[...game.users].filter(u=>u.active&&u.isGM).length===1&&game.socket?.connected===true; +const owned=()=>game.settings.get(id,'ownedPlaylistIds').split(',').map(s=>s.trim()).filter(Boolean); +const choices=async()=>[...[...game.playlists].filter(p=>owned().includes(p.id)).map(p=>({provider:'native',id:p.id,name:p.name})),...(gmHost?.catalog.length?gmHost.catalog:gateway?.catalog??[])]; +const onError=()=>ui.notifications.warn('Adaptive Music could not complete the operation. Open Adaptive Music setup for connection diagnostics and ownership checks.'); +function start(){ + if(!game.user.isGM||runtime)return; + runtime=startNativeRuntime({game,Hooks,campaign:game.world.id,session:gmHost?.connected?gmHost.session:globalThis.crypto.randomUUID(),ownedPlaylistIds:owned(),maProvider:gmHost?.connected?gmHost:gateway,onError}); + runtime.refresh().catch(onError); +} +function stop(){runtime?.dispose();runtime=null;} +function setOverrides(value){if(!runtime)throw Error('Automation is disabled');return runtime.setOverrides(value);} +function listenWebRTC(invite){ + if(game.user.isGM||!peers)throw Error('Listener only'); + if(!remoteAudio){remoteAudio=document.createElement('audio');document.body.append(remoteAudio);} + remoteAudio.play().catch(()=>{});return peers.listen(invite); +} +function stopWebRTC(){peers?.reset();remoteAudio?.pause();if(remoteAudio)remoteAudio.srcObject=null;} +Hooks.once('init',()=>{ + game.settings.register(id,'enabled',{name:'Enable music automation',hint:'Configure through Adaptive Music setup. Defaults off.',scope:'world',config:false,type:Boolean,default:false}); + game.settings.register(id,'ownedPlaylistIds',{scope:'world',config:false,type:String,default:'',requiresReload:true}); + game.settings.register(id,'musicDefaults',{scope:'world',config:false,type:Object,default:{}}); + if(game.settings.registerMenu){ + // The factory reads live module state when the settings menu is rendered. + const Setup=createSetupClass({game,gateway:{get status(){return gateway?.status;},connect:async code=>{if(gmHost?.connected)throw Error('Disconnect GM host first');const result=await gateway.connect(code);await runtime?.refresh();return result;},refresh:()=>gateway.refresh(),disconnect:()=>gateway.disconnect(),audioRequest:code=>gateway.audioRequest(code)}, + audio:{start:request=>audio.start(request),stop:()=>audio.stop()},getChoices:choices,start,stop,setOverrides,onError,canConnect:()=>!gmHost?.connected&&primaryGM(game.users)===game.user.id}); + const Listener=createListenerClass({game,gateway:{audioRequest:code=>gateway.audioRequest(code)},audio:{start:request=>audio.start(request),stop:()=>audio.stop()},listenWebRTC,stopWebRTC,onError}); + game.settings.registerMenu(id,'listen',{name:'Campaign audio (development)',label:'Enable Audio',hint:'Private WebRTC invitation, or optional companion synthetic test.',icon:'fas fa-headphones',type:Listener,restricted:false}); + game.settings.registerMenu(id,'setup',{name:'Adaptive Music setup',label:'Configure music',hint:'Native ownership, world/scene assignments, boss overrides, gateway and audio diagnostics.',icon:'fas fa-music',type:Setup,restricted:true}); + } +}); +Hooks.once('ready',()=>{ + gmHost=new GMAudioHost({authority:gmAuthority}); + if(game.socket){peers=new PeerAudio({socket:game.socket,userId:game.user.id,isGM:gmAuthority,isAuthorizedUser:id=>{const user=game.users.get(id);return user?.active&&!user.isGM&&!user.isBanned;},onError,onStream:stream=>{if(!remoteAudio){remoteAudio=document.createElement('audio');remoteAudio.autoplay=true;document.body.append(remoteAudio);}remoteAudio.srcObject=stream;remoteAudio.play().catch(onError);}});game.socket.on('disconnect',()=>{stop();gmHost.close();peers.reset();remoteAudio?.pause();});} + if(game.socket)authorityHooks=['updateUser','deleteUser'].map(event=>[event,Hooks.on(event,()=>{peers.reconcile();if(gmHost.connected&&!gmAuthority()){stop();gmHost.close();peers.reset();remoteAudio?.pause();}})]); + gateway=new GatewayClient({origin:globalThis.location?.origin??'http://localhost'});audio=new ListenerAudio(); + if(game.user.isGM){interfaces=startConfigurationInterfaces({game,Hooks,getChoices:choices,onError});renewTimer=setInterval(()=>{if(gateway.connected&&primaryGM(game.users)===game.user.id)gateway.renew().catch(onError);},10000);} + game.modules.get(id).api={ + startDevelopment:start,stopDevelopment:stop,setOverrides, + async connectGateway(code){if(!game.user.isGM||primaryGM(game.users)!==game.user.id||gmHost?.connected)throw Error('Controller unavailable');const result=await gateway.connect(code);await runtime?.refresh();return result;}, + gatewayDiagnostics:()=>gateway.status, + async readGMCatalog(profile){if(runtime||gateway.connected)throw Error('Stop automation and disconnect optional companion first');return gmHost.readCatalog({...profile,campaign:game.world.id});}, + async startGMHost(profile){if(runtime||gateway.connected)throw Error('Stop automation and disconnect optional companion first');const result=await gmHost.start({...profile,campaign:game.world.id});peers.setSource(gmHost.stream);return result;}, + inviteListener:(userId,options)=>peers.invite(userId,options), + listenWebRTC, + peerStats:()=>peers.stats(), + async closeGMHost(){stop();peers?.reset();await gmHost.close();}, + async mountConfiguration(document,container){return mountPlaylistConfiguration({document,container,game,choices:await choices(),onError});}, + enableAudio(code){return audio.start(gateway.audioRequest(code));},stopAudio:()=>audio.stop(), + dispose(){stop();for(const [event,hook]of authorityHooks)Hooks.off(event,hook);authorityHooks=[];interfaces?.dispose();clearInterval(renewTimer);gateway.disconnect();audio.stop();gmHost?.close();peers?.close();remoteAudio?.pause();remoteAudio?.remove();interfaces=null;} + }; + if(game.settings.get(id,'enabled'))start(); +}); diff --git a/src/foundry/music-editor.mjs b/src/foundry/music-editor.mjs new file mode 100644 index 0000000..7523ed0 --- /dev/null +++ b/src/foundry/music-editor.mjs @@ -0,0 +1,48 @@ +import {MusicError} from '../core/controller.mjs'; +import {musicFields,referenceKey,selection} from '../core/scene-music.mjs'; +const namespace='adaptive-music'; +export async function saveMusicAssignments({document,game,choices,values,defaults=false}){ + if(!game.user?.isGM||Object.keys(values).some(k=>!musicFields.includes(k)))throw new MusicError('denied'); + const previous=defaults?game.settings.get(namespace,'musicDefaults')??{}:document.getFlag(namespace,'music')??{}; + const result={...previous}; + for(const field of musicFields){ + if(!Object.hasOwn(values,field))continue; + // Keep an unchanged offline catalog selection; never permit a forged new one. + if(values[field]===referenceKey(previous[field]) && previous[field]){if(field==='fallback'&&previous[field].provider!=='native')throw new MusicError('denied');result[field]={provider:previous[field].provider,id:previous[field].id};continue;} + result[field]=selection(values[field],choices,{nativeOnly:field==='fallback'}); + } + if(defaults)await game.settings.set(namespace,'musicDefaults',result);else await document.setFlag(namespace,'music',result); +} +export function musicSelect(dom,choices,current,{nativeOnly=false,empty='Use world default / silence'}={}){ + const select=dom.createElement('select'); + const add=(value,text)=>{const option=dom.createElement('option');option.value=value;option.textContent=text;select.append(option);}; + add('',empty); + for(const c of choices.filter(c=>!nativeOnly||c.provider==='native'))add(referenceKey(c),`${c.provider==='ma'?'MA':'Foundry'}: ${c.name}`); + if(current&&!choices.some(c=>referenceKey(c)===referenceKey(current)))add(referenceKey(current),'Saved selection (catalog unavailable)'); + select.value=referenceKey(current);return select; +} +export function mountMusicAssignments({document,game,container,choices,defaults=false,onError=()=>{}}){ + if(!game.user?.isGM)return null; + const dom=container.ownerDocument,panel=dom.createElement('fieldset');panel.dataset.adaptiveMusic='assignments'; + const legend=dom.createElement('legend');legend.textContent=defaults?'World music defaults':'Scene music';panel.append(legend); + const previous=defaults?game.settings.get(namespace,'musicDefaults')??{}:document.getFlag(namespace,'music')??{}; + const labels={ambient:'Ambient music (base queue)',combat:'Combat music',boss:'Default boss music',fallback:'Native fallback when MA is unavailable'}; + const controls={}; + for(const field of musicFields){const label=dom.createElement('label');label.textContent=labels[field]+' ';const current=previous[field]??(field==='ambient'?previous.playlist:null);controls[field]=musicSelect(dom,choices,current,{nativeOnly:field==='fallback',empty:defaults?(field==='fallback'?'No native fallback':'No world default'):'Use world default / silence'});label.append(controls[field]);panel.append(label);} + const note=dom.createElement('p');note.textContent='One music layer: combat interrupts ambient music. Concurrent ambient layers and crossfade are not implemented. Native AmbientSound and effects remain separate.';panel.append(note); + const status=dom.createElement('p');status.setAttribute('role','status');panel.append(status); + const button=dom.createElement('button');button.type='button';button.textContent='Save assignments';panel.append(button); + button.addEventListener('click',async()=>{button.disabled=true;try{await saveMusicAssignments({document,game,choices,defaults,values:Object.fromEntries(musicFields.map(k=>[k,controls[k].value]))});status.textContent='Assignments saved.';}catch{status.textContent='Assignments could not be saved.';onError(new MusicError('denied'));}finally{button.disabled=false;}}); + container.append(panel);return panel; +} +export function mountBossEditor({document,game,container,choices,onError=()=>{}}){ + if(!game.user?.isGM)return null; + const dom=container.ownerDocument,panel=dom.createElement('fieldset'),flag=document.getFlag(namespace,'music')??{}; + const label=dom.createElement('label');label.textContent='Boss override ';const enabled=dom.createElement('input');enabled.type='checkbox';enabled.checked=flag.boss===true;label.append(enabled);panel.append(label); + const priority=dom.createElement('input');priority.type='number';priority.value=String(flag.priority??0);priority.setAttribute('aria-label','Boss priority');panel.append(priority); + const inactive=dom.createElement('input');inactive.type='checkbox';inactive.checked=flag.inactive===true;const inactiveLabel=dom.createElement('label');inactiveLabel.textContent='Boss inactive ';inactiveLabel.append(inactive);panel.append(inactiveLabel); + const select=musicSelect(dom,choices,flag.playlist,{empty:'Use scene / world boss music'});select.setAttribute('aria-label','Boss playlist');panel.append(select); + const save=dom.createElement('button');save.type='button';save.textContent='Save boss override';panel.append(save); + save.addEventListener('click',async()=>{try{if(!game.user.isGM||!Number.isFinite(Number(priority.value)))throw new MusicError('denied');const previous=document.getFlag(namespace,'music')??{};const playlist=select.value===referenceKey(previous.playlist)?previous.playlist??null:selection(select.value,choices);await document.setFlag(namespace,'music',{...previous,boss:enabled.checked,inactive:inactive.checked,priority:Number(priority.value),playlist});}catch{onError(new MusicError('denied'));}}); + container.append(panel);return panel; +} diff --git a/src/foundry/runtime.mjs b/src/foundry/runtime.mjs new file mode 100644 index 0000000..9b965b6 --- /dev/null +++ b/src/foundry/runtime.mjs @@ -0,0 +1,35 @@ +import { MusicController } from '../core/controller.mjs'; +import { buildMusicState } from '../core/scene-music.mjs'; +import { NativeProvider } from '../providers/native/provider.mjs'; +export const primaryGM = users => [...users].filter(u => u.active && u.isGM) + .sort((a,b) => a.id.localeCompare(b.id))[0]?.id; +// Explicit development bootstrap. No hooks or document mutations occur on import. +// All music configuration uses module-owned flags; no actor/system schema access. +export function startNativeRuntime({ game, Hooks, campaign, session, ownedPlaylistIds, maProvider, onError = () => {} }) { + const flag = d => d?.getFlag('adaptive-music', 'music'); + const provider = new NativeProvider({ playlists: game.playlists, ownedPlaylistIds, campaign, session, + sceneConflict: id => [...game.scenes].some(s => s.active && (s.playlist?.id ?? s.playlist) === id) }); + const controller = new MusicController({ campaign, session, providers: { native: provider,...(maProvider?{ma:maProvider}:{}) }, + authority: () => game.ready && primaryGM(game.users) === game.user.id }); + let overrides = []; + const refresh = () => { + if (!game.ready || primaryGM(game.users) !== game.user.id) return Promise.resolve(); + const scene = [...game.scenes].find(s => s.active); + const defaults=game.settings.get('adaptive-music','musicDefaults')??{}; + const choose=(ref,fallback)=>ref?.provider==='ma'&&!maProvider?.supports(ref)?fallback??null:ref; + const state=buildMusicState({scene:scene&&{id:scene.id,music:flag(scene)}, + defaults:{...defaults,ambient:Object.hasOwn(defaults,'ambient')?defaults.ambient:game.settings.get('adaptive-music','defaultPlaylist')},overrides,choose, + combats:[...game.combats].map(c=>({id:c.id,sceneId:c.scene?.id??c.scene,active:c.active,started:c.started,playlist:flag(c)?.playlist, + bosses:[...c.combatants].map(b=>{const f=flag(b)??flag(b.token)??{};return {id:b.id,active:f.boss===true&&f.inactive!==true,priority:Number.isFinite(f.priority)?f.priority:0,playlist:f.playlist};})}))}); + return controller.update(state); + + }; + if(!game.settings.settings?.has('adaptive-music.defaultPlaylist'))game.settings.register('adaptive-music', 'defaultPlaylist', { scope: 'world', config: false, type: Object, default: null }); + const events = ['updateScene', 'createCombat', 'updateCombat', 'deleteCombat', 'createCombatant', + 'updateCombatant', 'deleteCombatant', 'updateToken', 'updateSetting', 'updateUser', 'deletePlaylist', 'deletePlaylistSound']; + const subscriptions = events.map(event => [event, Hooks.on(event, () => refresh().catch(onError))]); + return { controller, refresh, + setOverrides: value => { overrides = structuredClone(value); return refresh(); }, + dispose: () => { for (const [event,id] of subscriptions) Hooks.off(event,id); controller.generation++; controller.abort?.abort(); } + }; +} diff --git a/src/foundry/setup.mjs b/src/foundry/setup.mjs new file mode 100644 index 0000000..e1f1466 --- /dev/null +++ b/src/foundry/setup.mjs @@ -0,0 +1,66 @@ +import {MusicError} from '../core/controller.mjs'; +import {selection} from '../core/scene-music.mjs'; +import {mountMusicAssignments,mountBossEditor,musicSelect} from './music-editor.mjs'; +export function createSetupClass({game,gateway,audio,getChoices,start,stop,setOverrides,onError,canConnect=()=>true,Base=globalThis.foundry.applications.api.ApplicationV2}){ + return class AdaptiveMusicSetup extends Base { + static DEFAULT_OPTIONS={id:'adaptive-music-setup',window:{title:'Adaptive Music setup'},position:{width:640,height:'auto'}}; + async _renderHTML(){ + if(!game.user.isGM)throw new MusicError('denied'); + const dom=globalThis.document,root=dom.createElement('div');root.className='adaptive-music-setup'; + const text=value=>{const p=dom.createElement('p');p.textContent=value;root.append(p);return p;}; + const status=text('Automation is opt-in. Configure dedicated music playlists and assignments before enabling it.');status.setAttribute('role','status'); + const button=(label,action)=>{const b=dom.createElement('button');b.type='button';b.textContent=label;b.addEventListener('click',async()=>{b.disabled=true;try{if(!game.user.isGM)throw new MusicError('denied');await action();}catch(e){status.textContent=e?.code==='denied'?'Connection or selection denied. Check capability role/expiry, active GM, and native ownership.':e?.code==='stale'?'Controller lease changed. Reconnect with a fresh connection code.':'Gateway unavailable. Check the private same-origin route, TLS, companion process and target diagnostics. Native configuration can be used offline.';onError(e);}finally{b.disabled=false;}});root.append(b);return b;}; + const owned=new Set(game.settings.get('adaptive-music','ownedPlaylistIds').split(',').filter(Boolean)); + const boxes=[];const ownedPanel=dom.createElement('fieldset');const legend=dom.createElement('legend');legend.textContent='Dedicated native music playlists';ownedPanel.append(legend); + for(const playlist of game.playlists){const label=dom.createElement('label'),input=dom.createElement('input');input.type='checkbox';input.checked=owned.has(playlist.id);label.textContent=playlist.name+' ';label.append(input);ownedPanel.append(label);boxes.push({id:playlist.id,input});}root.append(ownedPanel); + text('Opt in only dedicated music playlists. Do not select AmbientSound, effects or shared playlists. Saving ownership disables automation and requires a reload.'); + button('Save native ownership',async()=>{stop();await game.settings.set('adaptive-music','enabled',false);await game.settings.set('adaptive-music','ownedPlaylistIds',boxes.filter(b=>b.input.checked).map(b=>b.id).join(','));status.textContent='Ownership saved. Reload this world before enabling automation.';}); + const codeLabel=dom.createElement('label');codeLabel.textContent='Optional companion controller code (memory only; never an MA token) ';const code=dom.createElement('input');code.type='password';code.autocomplete='off';codeLabel.append(code);root.append(codeLabel); + text('Native playback requires no companion. The optional companion uses a private same-origin route. The module-only GM-host API uses private GM-local authentication; see INSTALL.md. Never share MA credentials with listeners.'); + const diagnostics=text('Gateway disconnected. Owned native playlists work without it.'); + const assignmentRoot=dom.createElement('div'); + const show=()=>{const d=gateway.status;diagnostics.textContent=d?`Target: ${d.target}. Playback authorization: ${d.playbackEnabled?'enabled for approved test IDs':'disabled'}. Audio: ${d.audioSource} (test transport only). Sendspin receiver: unavailable. Crossfade: unavailable.`:'Gateway disconnected. Owned native fallback is available.';}; + button('Connect and load MA catalog',async()=>{if(!canConnect())throw new MusicError('denied');const value=code.value;code.value='';await gateway.connect(value);show();await renderAssignments();}); + button('Refresh connection diagnostics',async()=>{await gateway.refresh();show();await renderAssignments();}); + button('Disconnect gateway',async()=>{await gateway.disconnect();show();status.textContent='Gateway disconnected. Existing MA playback, if any, is retained; automatic fallback cannot bypass an unreachable owned target.';}); + const renderAssignments=async()=>{ + assignmentRoot.replaceChildren();const choices=await getChoices(); + mountMusicAssignments({game,container:assignmentRoot,choices,defaults:true,onError}); + const sceneLabel=dom.createElement('label');sceneLabel.textContent='Scene ';const scenes=dom.createElement('select'); + for(const scene of game.scenes){const option=dom.createElement('option');option.value=scene.id;option.textContent=scene.name;scenes.append(option);}sceneLabel.append(scenes);assignmentRoot.append(sceneLabel); + const scenePanel=dom.createElement('div');assignmentRoot.append(scenePanel); + const showScene=()=>{scenePanel.replaceChildren();const scene=game.scenes.get(scenes.value);if(scene)mountMusicAssignments({document:scene,game,container:scenePanel,choices,onError});}; + const active=[...game.scenes].find(s=>s.active);if(active)scenes.value=active.id;scenes.addEventListener('change',showScene);showScene(); + const bossLabel=dom.createElement('label');bossLabel.textContent='Boss combatant ';const bosses=dom.createElement('select'),documents=new Map(); + for(const combat of game.combats)for(const combatant of combat.combatants){const option=dom.createElement('option');option.value=combat.id+':'+combatant.id;option.textContent=combatant.name??combatant.id;documents.set(option.value,combatant);bosses.append(option);}bossLabel.append(bosses);assignmentRoot.append(bossLabel); + const bossPanel=dom.createElement('div');assignmentRoot.append(bossPanel);const showBoss=()=>{bossPanel.replaceChildren();const document=documents.get(bosses.value);if(document)mountBossEditor({document,game,container:bossPanel,choices,onError});};bosses.addEventListener('change',showBoss);showBoss(); + const manual=musicSelect(dom,choices,null,{empty:'Silence'});manual.setAttribute('aria-label','Manual music override');assignmentRoot.append(manual); + for(const [label,action]of [['Apply manual override',()=>setOverrides([{id:'gm-manual',playlist:selection(manual.value,choices)}])],['Clear manual override',()=>setOverrides([])]]){const b=dom.createElement('button');b.type='button';b.textContent=label;b.addEventListener('click',()=>Promise.resolve().then(action).catch(onError));assignmentRoot.append(b);} + }; + await renderAssignments();root.append(assignmentRoot); + const enabledLabel=dom.createElement('label');enabledLabel.textContent='Enable music automation ';const enabled=dom.createElement('input');enabled.type='checkbox';enabled.checked=game.settings.get('adaptive-music','enabled');enabledLabel.append(enabled);root.append(enabledLabel); + button('Apply automation setting',async()=>{await game.settings.set('adaptive-music','enabled',enabled.checked);if(enabled.checked)start();else stop();status.textContent=enabled.checked?'Automation enabled. MA assignments require authorized content; otherwise the configured native fallback is selected.':'Automation disabled; current playback is retained.';}); + const listenerLabel=dom.createElement('label');listenerLabel.textContent='Separate listener connection code (memory only) ';const listener=dom.createElement('input');listener.type='password';listener.autocomplete='off';listenerLabel.append(listener);root.append(listenerLabel); + text('Enable Audio plays only the companion synthetic PCM test tone. It does not relay the MA DEV player or Sendspin audio. Crossfade is not available.'); + // Start directly in the click task so AudioContext.resume retains user activation. + const enable=dom.createElement('button');enable.type='button';enable.textContent='Enable synthetic test audio';enable.addEventListener('click',()=>{try{const value=JSON.parse(listener.value);listener.value='';audio.start(gateway.audioRequest(value)).catch(onError);}catch{onError(new MusicError('denied'));}});root.append(enable); + button('Stop test audio',()=>audio.stop());show();return root; + } + _replaceHTML(result,content){content.replaceChildren(result);} + }; +} + +export function createListenerClass({game,gateway,audio,listenWebRTC,stopWebRTC=()=>{},onError,Base=globalThis.foundry.applications.api.ApplicationV2}){ + return class AdaptiveMusicListener extends Base { + static DEFAULT_OPTIONS={id:'adaptive-music-listener',window:{title:'Campaign audio (development)'},position:{width:480}}; + async _renderHTML(){ + const dom=globalThis.document,root=dom.createElement('div');root.className='adaptive-music-setup'; + const note=dom.createElement('p');note.textContent='Use a private GM WebRTC invitation, or an optional companion test code. No microphone or MA credentials are sent by players. GM-local MA audio remains experimental; never paste an MA token here.';root.append(note); + const label=dom.createElement('label');label.textContent='Listener connection code ';const input=dom.createElement('input');input.type='password';input.autocomplete='off';label.append(input);root.append(label); + const status=dom.createElement('p');status.setAttribute('role','status');root.append(status); + const enable=dom.createElement('button');enable.type='button';enable.textContent='Enable Audio';enable.addEventListener('click',()=>{try{const code=JSON.parse(input.value);input.value='';status.textContent='Connecting to campaign audio…';const task=code.transport==='webrtc-v1'?listenWebRTC(code):audio.start(gateway.audioRequest(code));Promise.resolve(task).then(()=>{status.textContent=code.transport==='webrtc-v1'?'Peer negotiation sent; waiting for GM media.':'Audio stopped.';}).catch(()=>{status.textContent='Audio unavailable. Check the private route, listener code and expiry.';onError(new MusicError('unavailable'));});}catch{status.textContent='Invalid listener code.';}});root.append(enable); + const stop=dom.createElement('button');stop.type='button';stop.textContent='Stop Audio';stop.addEventListener('click',()=>{stopWebRTC();audio.stop();});root.append(stop);return root; + } + _replaceHTML(result,content){content.replaceChildren(result);} + }; +} diff --git a/src/providers/ma/client.mjs b/src/providers/ma/client.mjs new file mode 100644 index 0000000..f2c7725 --- /dev/null +++ b/src/providers/ma/client.mjs @@ -0,0 +1,182 @@ +import {randomKey,hmac,base64url} from './webcrypto.mjs'; +import { MusicError } from '../../core/controller.mjs'; +// Shared trusted-GM/optional-companion transport. Never construct with MA credentials on a player client. +export class MAReadClient { + #base; #token; #target; #fetch; #providers; #catalog = new Map(); #catalogKey; #campaign; #expectedName; #expectedProvider; #writes = Promise.resolve(); #synthetic; #uncertain = false; #authorizedMedia = new Set(); #targetVolume; + constructor({ baseUrl, token, target, approvedProviders = [], catalogKey = randomKey(), campaign = 'default', expectedName, expectedProvider, syntheticSequences = {}, fetchImpl = fetch }) { + const url = new URL(baseUrl); + if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || + url.search || url.hash || url.pathname !== '/' || typeof token !== 'string' || !token || + /[\r\n]/.test(token) || typeof target !== 'string' || !target || + !Array.isArray(approvedProviders) || approvedProviders.some(p => typeof p !== 'string' || !p)) throw new MusicError('denied'); + this.#base = url.origin; this.#token = token; this.#target = target; this.#fetch = fetchImpl; + if (!(catalogKey instanceof Uint8Array) || catalogKey.length !== 32 || !campaign) throw new MusicError('denied'); + this.#providers = [...new Set(approvedProviders)]; + this.#catalogKey = Uint8Array.from(catalogKey); this.#campaign = campaign; + if(!syntheticSequences || typeof syntheticSequences!=='object' || Object.values(syntheticSequences).some(v=>!Array.isArray(v)||!v.length||v.length>5000||v.some(uri=>typeof uri!=='string'||!uri.startsWith('builtin://track/http://'))))throw new MusicError('denied'); + this.#synthetic = structuredClone(syntheticSequences); + for(const uri of Object.values(this.#synthetic).flat())this.#authorizedMedia.add(uri); + this.#expectedName = expectedName; this.#expectedProvider = expectedProvider; + } + async #read(command, args, messageId = 'adaptive-music-read') { + try { + const response = await this.#fetch(`${this.#base}/api`, { method: 'POST', redirect: 'error', + signal: AbortSignal.timeout(5000), headers: { Authorization: `Bearer ${this.#token}`, 'Content-Type': 'application/json' }, + body: JSON.stringify({ message_id: messageId, command, args }) }); + if (!response.ok) throw new MusicError(response.status === 403 ? 'denied' : 'unavailable'); + const reader = response.body?.getReader(); + if (!reader) return null; + const chunks = []; let size = 0; + try { + while (true) { + const { value, done } = await reader.read(); if (done) break; + size += value.byteLength; + if (size > 1048576) { await reader.cancel(); throw new MusicError('unavailable'); } + chunks.push(value); + } + } finally { reader.releaseLock(); } + const bytes=new Uint8Array(size);let offset=0;for(const chunk of chunks){bytes.set(chunk,offset);offset+=chunk.length;} + const body = new TextDecoder().decode(bytes); + return body ? JSON.parse(body) : null; + } catch (error) { + throw new MusicError(error instanceof MusicError ? error.code : 'unavailable'); + } + } + async getOwnedQueue(target) { + if (target !== this.#target) throw new MusicError('denied'); + const queue = await this.#read('player_queues/get', { queue_id: this.#target }); + if (queue?.queue_id !== this.#target || queue.active !== true) throw new MusicError('denied'); + return { state: queue.state, items: queue.items }; + } + async verifyTarget({allowUnavailable=false}={}) { + if(!allowUnavailable && this.#expectedName && this.#expectedProvider){ + await this.getOwnedQueue(this.#target); + const active=await this.#read('player_queues/get_active_queue',{player_id:this.#target}); + if(active?.queue_id!==this.#target)throw new MusicError('denied'); + } + const player = await this.#read('players/get', { player_id: this.#target }); + if (player?.player_id !== this.#target || !allowUnavailable&&player.available !== true || player.enabled !== true || + (this.#expectedName && player.name !== this.#expectedName) || + (this.#expectedProvider && player.provider !== this.#expectedProvider) || + !player.provider?.startsWith('sendspin') || player.active_group || player.synced_to || + ['group_members','group_childs','static_group_members'].some(k => !Array.isArray(player[k]) || player[k].some(id => id !== this.#target))) throw new MusicError('denied'); + if(!allowUnavailable&&(!this.#expectedName || !this.#expectedProvider))await this.getOwnedQueue(this.#target); + this.#targetVolume=Number.isFinite(player.volume_level)&&typeof player.volume_muted==='boolean'?{volume:Math.min(100,Math.max(0,player.volume_level)),muted:player.volume_muted}:null; + return { dedicated: true, available: player.available===true, standalone: true }; + } + targetVolumeState(){if(!this.#targetVolume)throw new MusicError('unsupported');return {...this.#targetVolume};} + async catalog() { + if (!this.#providers.length) throw new MusicError('denied'); + const next = new Map(); const choices = []; + // Bounded all-or-nothing pagination; a full final page fails rather than truncating silently. + for (const [kind, type] of [['playlists','playlist'],['radios','radio']]) { + let complete = false; + for (let offset = 0; offset < 5000; offset += 100) { + const page = await this.#read(`music/${kind}/library_items`, { + provider: this.#providers, limit: 100, offset, order_by: 'name', summary: false }); + if (!Array.isArray(page) || page.length > 100) throw new MusicError('unavailable'); + for (const item of page) { + const mapping = Array.isArray(item?.provider_mappings) && [...item.provider_mappings].sort((a,b) => String(a?.provider_instance).localeCompare(String(b?.provider_instance))).find(m => m && this.#providers.includes(m.provider_instance) && m.available === true); + if (!mapping || item.media_type !== type || item.is_playable !== true || + typeof item.name !== 'string' || typeof mapping.item_id !== 'string') continue; + // Keyed campaign-scoped identity survives restart with the same private key. + const key = JSON.stringify([type, mapping.provider_instance, mapping.item_id]); + if (next.has(key)) continue; + const id = base64url(await hmac(this.#catalogKey,JSON.stringify([this.#campaign,key]))); + next.set(key, { id, type, provider: mapping.provider_instance, itemId: mapping.item_id, dynamic: item.is_dynamic === true }); + choices.push({ provider: 'ma', id, kind: type, name: item.name.replace(/[\x00-\x1f\x7f]/g,'').slice(0,160) }); + } + if (page.length < 100) { complete = true; break; } + } + if (!complete) throw new MusicError('unavailable'); + } + this.#catalog = next; + return choices; + } + resolveCatalog(ref) { + if (ref?.provider !== 'ma') throw new MusicError('denied'); + const entry = [...this.#catalog.values()].find(e => e.id === ref.id); + if (!entry) throw new MusicError('expired-media'); + if(entry.dynamic)throw new MusicError('unsupported'); + const uri=`${entry.provider}://${entry.type}/${entry.itemId}`;this.#authorizedMedia.add(uri);return uri; + } + resolveMedia(ref) { + if (ref?.provider === 'ma' && Object.hasOwn(this.#synthetic,ref.id)) return [...this.#synthetic[ref.id]]; + return [this.resolveCatalog(ref)]; + } + async prepareMedia(ref) { + const media=this.resolveMedia(ref); + if(Object.hasOwn(this.#synthetic,ref.id)) { + await this.inspectSynthetic(media); + return media; + } + const entry=[...this.#catalog.values()].find(e=>e.id===ref.id); + if(entry.type==='radio')return media; + const playlist=await this.#read('music/playlists/get',{item_id:entry.itemId,provider_instance_id_or_domain:entry.provider,allow_update_metadata:false}); + if(playlist?.is_dynamic!==false)throw new MusicError('unsupported'); + const tracks=await this.#read('music/playlists/playlist_tracks',{item_id:entry.itemId,provider_instance_id_or_domain:entry.provider,allow_dynamic_tracks:false}); + if(!Array.isArray(tracks) || !tracks.length || tracks.length>5000)throw new MusicError('unavailable'); + return tracks.map(track=>this.mediaURI({media_item:track})); + } + async inspectSynthetic(selected) { + const approved=Object.values(this.#synthetic).flat(); + const uris=selected??approved; + if(!Array.isArray(uris) || uris.some(uri=>!approved.includes(uri)))throw new MusicError('denied'); + if(!this.#providers.includes('builtin') || !uris.length)throw new MusicError('denied'); + const result=[]; + for(const uri of uris){ + if(typeof uri!=='string' || !uri.startsWith('builtin://track/http://'))throw new MusicError('denied'); + const track=await this.#read('music/tracks/get',{item_id:uri.slice('builtin://track/'.length),provider_instance_id_or_domain:'builtin',allow_update_metadata:false}); + if(!(track?.duration>=60))throw new MusicError('unavailable'); + result.push({duration:track.duration}); + } + return result; + } + async queueState({allowUnavailable=false}={}) { + const queue = await this.#read('player_queues/get', {queue_id:this.#target}); + if (queue?.queue_id !== this.#target || !allowUnavailable&&(queue.active !== true || queue.available !== true)) throw new MusicError('denied'); + return queue; + } + async queueItems(offset = 0) { + if (!Number.isSafeInteger(offset) || offset < 0 || offset >= 5000) throw new MusicError('denied'); + const items = await this.#read('player_queues/items', {queue_id:this.#target,limit:100,offset}); + if (!Array.isArray(items) || items.length > 100) throw new MusicError('unavailable'); + return items; + } + mediaURI(item) { + const media = item?.media_item; + const mapping = Array.isArray(media?.provider_mappings) && media.provider_mappings.find(m => m && this.#providers.includes(m.provider_instance) && m.available === true); + if (!mapping || !['track','radio'].includes(media.media_type) || typeof mapping.item_id !== 'string') throw new MusicError('unsupported'); + const uri=`${mapping.provider_instance}://${media.media_type}/${mapping.item_id}`;this.#authorizedMedia.add(uri);return uri; + } + // Server-only fixed command surface, never a browser route. Target is not an argument. + async mutate(action, args, ctx) { + const fields = {stop:[],pause:[],resume:[],clear:[],seek:['position'],shuffle:['shuffle_enabled'],repeat:['repeat_mode'], + play_index:['index','seek_position'],play_media:['media','option','shuffle']}; + if (!Object.hasOwn(fields,action) || !args || Object.keys(args).some(k => !fields[action].includes(k)) || + !this.#expectedName || !this.#expectedProvider || !ctx?.check) throw new MusicError('denied'); + if (action === 'seek' && (!Number.isSafeInteger(args.position) || args.position < 0)) throw new MusicError('denied'); + if (action === 'shuffle' && typeof args.shuffle_enabled !== 'boolean') throw new MusicError('denied'); + if (action === 'repeat' && !['off','one','all'].includes(args.repeat_mode)) throw new MusicError('denied'); + if (action === 'play_index' && (!Number.isSafeInteger(args.index) || args.index < 0 || !Number.isSafeInteger(args.seek_position) || args.seek_position < 0)) throw new MusicError('denied'); + if (action === 'play_media') { + if (!['replace','add'].includes(args.option) || typeof args.shuffle !== 'boolean' || !Array.isArray(args.media) || !args.media.length || args.media.length > 5000 || + args.media.some(uri => typeof uri !== 'string' || !this.#authorizedMedia.has(uri) || !this.#providers.some(p => uri.startsWith(`${p}://track/`) || uri.startsWith(`${p}://playlist/`) || uri.startsWith(`${p}://radio/`)))) throw new MusicError('denied'); + } + const captured = structuredClone(args); + const operation = this.#writes.catch(() => {}).then(async () => { + ctx.check(); + if(this.#uncertain)throw new MusicError('uncertain'); + const queue = await this.queueState(); + if (queue.is_dynamic !== false || queue.autoplay_enabled !== false || queue.dont_stop_the_music_enabled !== false || queue.overlay_enabled !== false || queue.playback_speed !== 1) throw new MusicError('unsupported'); + await this.verifyTarget(); + ctx.check(); // Recheck authority after all reads, immediately before dispatch. + try{await this.#read(`player_queues/${action}`, {...captured,queue_id:this.#target},`adaptive-music-write-${crypto.randomUUID()}`);} + catch{this.#uncertain=true;throw new MusicError('uncertain');} + ctx.check(); + }); + this.#writes = operation; + return operation; + } + +} diff --git a/src/providers/ma/provider.mjs b/src/providers/ma/provider.mjs new file mode 100644 index 0000000..4393b31 --- /dev/null +++ b/src/providers/ma/provider.mjs @@ -0,0 +1,84 @@ +import {hmac,hex,verifyHmac} from './webcrypto.mjs'; +import { MusicError } from '../../core/controller.mjs'; +const identity = items => JSON.stringify(items.map(i => i.queue_item_id)); +export class MAPlaybackProvider { + #client; #campaign; #session; #fence; #authority; #key; #generation = 0; #prepared = new WeakMap(); #operations = new Map(); #epoch = 0; + constructor({ client, campaign, session, fence, authority, snapshotKey }) { + if (!campaign || !session || !Number.isSafeInteger(fence) || fence < 1 || typeof authority !== 'function' || snapshotKey?.length !== 32) throw new MusicError('denied'); + this.#client=client; this.#campaign=campaign; this.#session=session; this.#fence=fence; this.#authority=authority; this.#key=Uint8Array.from(snapshotKey); + } + capabilities() { return {seek:true,exactOrderRestore:false,exactUnshuffledRestore:true,concurrentLayers:false,volume:false}; } + #check(ctx) { + if (ctx?.campaign !== this.#campaign || ctx?.session !== this.#session || !Number.isSafeInteger(ctx.generation) || ctx.generation < this.#generation || ctx.generation < 1) throw new MusicError('stale'); + ctx.check(); this.#authority(this.#fence); this.#generation=ctx.generation; + } + #context(ctx) { return {check:()=>this.#check(ctx)}; } + #once(ctx,label,operation) { + this.#check(ctx); + const key=`${ctx.generation}:${label}`; + if(this.#operations.has(key))return this.#operations.get(key); + for(const previous of this.#operations.keys())if(!previous.startsWith(`${ctx.generation}:`))this.#operations.delete(previous); + const result=operation();this.#operations.set(key,result);return result; + } + async resolve(ref,ctx) { + this.#check(ctx); const media=this.#client.prepareMedia ? await this.#client.prepareMedia(ref) : this.#client.resolveMedia ? this.#client.resolveMedia(ref) : [this.#client.resolveCatalog(ref)]; this.#check(ctx);const prepared=Object.freeze({});this.#prepared.set(prepared,Object.freeze([...media]));return prepared; + } + async #capture(ctx) { + this.#check(ctx);await this.#client.verifyTarget(); + const before=await this.#client.queueState(); + if (before.shuffle_enabled || before.is_dynamic || before.autoplay_enabled || before.dont_stop_the_music_enabled || before.overlay_enabled || before.playback_speed !== 1 || before.ended) throw new MusicError('unsupported'); + const items=[]; + for(let offset=0;offset<5000;offset+=100){this.#check(ctx);const page=await this.#client.queueItems(offset);items.push(...page);if(page.length<100)break;if(offset===4900)throw new MusicError('unsupported');} + const after=await this.#client.queueState(); + const again=[];for(let offset=0;offsetJSON.stringify([q.items,q.current_index,q.current_item?.queue_item_id,q.state,q.shuffle_enabled,q.repeat_mode,q.is_dynamic,q.autoplay_enabled,q.dont_stop_the_music_enabled,q.overlay_enabled,q.playback_speed,q.ended]); + if (before.items!==items.length || stable(before)!==stable(after) || identity(items)!==identity(again)) throw new MusicError('stale'); + if (!['idle','playing','paused'].includes(after.state) || !['off','one','all'].includes(after.repeat_mode) || + (items.length && (!Number.isSafeInteger(after.current_index) || after.current_index<0 || after.current_index>=items.length))) throw new MusicError('unsupported'); + const elapsed=after.state==='playing' ? after.elapsed_time+Math.max(0,Date.now()/1000-after.elapsed_time_last_updated) : after.elapsed_time; + const position=Math.floor(elapsed ?? 0); + if (!Number.isSafeInteger(position) || position<0 || (position>0 && !(items[after.current_index]?.duration>position))) throw new MusicError('unsupported'); + this.#check(ctx); + return {version:1,campaign:this.#campaign,session:this.#session,fence:this.#fence,generation:ctx.generation,expires:Date.now()+300000, + state:after.state,repeat:after.repeat_mode,shuffle:false,index:after.current_index,position, + items:items.map(item=>({uri:this.#client.mediaURI(item),duration:item.duration ?? 0}))}; + } + async #sign(value) { return hex(await hmac(this.#key,'snapshot-v1\0'+JSON.stringify(value))); } + async snapshot(ctx) { const value=await this.#capture(ctx);return {value,signature:await this.#sign(value)}; } + async apply(prepared,ctx) { + this.#check(ctx);if(!this.#prepared.has(prepared))throw new MusicError('denied'); + const media=this.#prepared.get(prepared); + return this.#once(ctx,`apply:${JSON.stringify(media)}`,async()=>{ + await this.#client.mutate('play_media',{media,option:'replace',shuffle:false},this.#context(ctx));this.#epoch++; + }); + } + async stopOwned(ctx) { return this.#once(ctx,`stop:${this.#epoch}`,()=>this.#client.mutate('stop',{},this.#context(ctx))); } + async control(action,value,ctx) { + this.#check(ctx); + const args={pause:{},resume:{},stop:{},seek:{position:value},shuffle:{shuffle_enabled:value},repeat:{repeat_mode:value}}; + if(!Object.hasOwn(args,action))throw new MusicError('denied'); + return this.#once(ctx,`control:${action}:${JSON.stringify(value)}`,async()=>{await this.#client.mutate(action,args[action],this.#context(ctx));this.#epoch++;}); + } + async restore(snapshot,ctx) { + this.#check(ctx); + try{snapshot=structuredClone(snapshot);}catch{throw new MusicError('stale');} + const value=snapshot?.value; + if(!value || typeof snapshot.signature!=='string' || !/^[a-f0-9]{64}$/.test(snapshot.signature) || + !await verifyHmac(this.#key,'snapshot-v1\0'+JSON.stringify(value),snapshot.signature) || + value.expires<=Date.now() || value.version!==1 || value.campaign!==this.#campaign || value.session!==this.#session || value.fence!==this.#fence || value.generation>ctx.generation)throw new MusicError('stale'); + return this.#once(ctx,`restore:${snapshot.signature}`,async()=>{ + const write=async(action,args)=>{await this.#client.mutate(action,args,this.#context(ctx));this.#epoch++;}; + await write('stop',{});await write('clear',{}); + await write('repeat',{repeat_mode:value.repeat}); + if(value.items.length){ + await write('play_media',{media:value.items.map(i=>i.uri),option:'add',shuffle:false}); + // Validate complete ordered occurrences before starting any rebuilt item. + const rebuilt=[];for(let offset=0;offsetthis.#client.mediaURI(i)))!==JSON.stringify(value.items.map(i=>i.uri)))throw new MusicError('unsupported'); + await write('play_index',{index:value.index,seek_position:value.position}); + if(value.state==='paused')await write('pause',{}); + if(value.state==='idle')await write('stop',{}); + } + }); + } +} diff --git a/src/providers/ma/remote.mjs b/src/providers/ma/remote.mjs new file mode 100644 index 0000000..c29acde --- /dev/null +++ b/src/providers/ma/remote.mjs @@ -0,0 +1,58 @@ +import { MusicError } from '../../core/controller.mjs'; +// Browser-safe client. Only same-origin relative application routes and campaign grants. +export class GatewayClient { + #fetch; #path; #origin; #grant; #fence; #catalog=[]; #status=null; + constructor({path='/adaptive-music-gateway',origin=globalThis.location?.origin,fetchImpl=globalThis.fetch}={}) { + if(typeof path!=='string' || !/^\/[a-zA-Z0-9/_-]+$/.test(path) || path.includes('//') || !origin)throw new MusicError('denied'); + this.#path=path.replace(/\/$/,'');this.#origin=origin;this.#fetch=fetchImpl; + } + get connected(){return !!this.#grant&&(!this.#status||this.#status.expiresAt>Date.now());} + get status(){return this.#status&&{...structuredClone(this.#status),playbackEnabled:this.canControl};} + get catalog(){return structuredClone(this.#catalog);} + get canControl(){return this.connected && this.#status?.playbackEnabled===true && this.#status.expiresAt>Date.now();} + supports(ref){return this.canControl && this.#status.allowedIds?.includes(ref.id);} + async #request(action,args={},ctx) { + if(!this.#grant)throw new MusicError('unavailable');ctx?.check(); + const grant=this.#grant; + try{ + const response=await this.#fetch(this.#path+'/rpc',{method:'POST',redirect:'error',credentials:'omit',cache:'no-store', + signal:AbortSignal.timeout(8000),headers:{'Content-Type':'application/json',Authorization:`Bearer ${grant.token}`}, + body:JSON.stringify({action,...args,campaign:grant.campaign,session:grant.session,...(ctx?{generation:ctx.generation,operationId:globalThis.crypto.randomUUID(),fence:this.#fence}:{})})}); + const reader=response.body?.getReader();if(!reader)throw new MusicError('unavailable'); + const chunks=[];let size=0; + try{while(true){const {value,done}=await reader.read();if(done)break;size+=value.length;if(size>1048576){await reader.cancel();throw new MusicError('unavailable');}chunks.push(value);}}finally{reader.releaseLock();} + const bytes=new Uint8Array(size);let offset=0;for(const chunk of chunks){bytes.set(chunk,offset);offset+=chunk.length;}const text=new TextDecoder().decode(bytes); + const data=JSON.parse(text); + if(!response.ok)throw new MusicError(['denied','stale','unsupported','unavailable','uncertain','expired-media'].includes(data.code)?data.code:'unavailable'); + if(this.#grant!==grant)throw new MusicError('stale');ctx?.check();return data; + }catch(error){if(this.#status)this.#status.playbackEnabled=false;throw new MusicError(error instanceof MusicError?error.code:'unavailable');} + } + async connect(code) { + await this.disconnect(); + let grant;try{grant=typeof code==='string'?JSON.parse(code):structuredClone(code);}catch{throw new MusicError('denied');} + if(!grant || Object.keys(grant).sort().join(',')!=='campaign,session,token' || ['token','campaign','session'].some(k=>typeof grant[k]!=='string'||!grant[k]||grant[k].length>512))throw new MusicError('denied'); + this.#grant=grant; + try{const lease=await this.#request('connect');this.#fence=lease.fence;return await this.refresh();} + catch(error){await this.disconnect();throw error;} + } + async refresh(){ + const status=await this.#request('diagnostics'); + if(!status||!['verified','unavailable'].includes(status.target)||typeof status.playbackEnabled!=='boolean'||!Number.isFinite(status.expiresAt)||!Array.isArray(status.allowedIds)||status.allowedIds.some(id=>typeof id!=='string'||id.length>256)||!['none','synthetic-pcm'].includes(status.audioSource))throw new MusicError('unavailable'); + this.#status={target:status.target,playbackEnabled:status.playbackEnabled,expiresAt:status.expiresAt,allowedIds:[...status.allowedIds],audioSource:status.audioSource,sendspin:false,crossfade:false,ambientLayers:1};const catalog=await this.#request('catalog'); + if(!Array.isArray(catalog)||catalog.length>10000||catalog.some(c=>c?.provider!=='ma'||typeof c.id!=='string'||c.id.length>256||typeof c.name!=='string'||c.name.length>160||!['playlist','radio','sequence'].includes(c.kind)))throw new MusicError('unavailable'); + this.#catalog=catalog.map(({provider,id,name,kind})=>({provider,id,name,kind}));return this.status; + } + async renew(){return this.#request('renew',{fence:this.#fence});} + async disconnect(){try{if(this.#grant&&this.#fence)await this.#request('release',{fence:this.#fence});}catch{}finally{this.#grant=null;this.#catalog=[];this.#status=null;this.#fence=null;}} + async resolve(ref,ctx){if(!this.supports(ref))throw new MusicError('unsupported');return this.#request('prepare',{id:ref.id},ctx);} + snapshot(ctx){return this.#request('snapshot',{},ctx);} + apply(prepared,ctx){return this.#request('apply',{handle:prepared.handle},ctx);} + restore(snapshot,ctx){return this.#request('restore',{handle:snapshot.handle},ctx);} + stopOwned(ctx){return this.#request('stop',{},ctx);} + // Listener access is supplied separately, never derived from or shared with the GM grant. + audioRequest(code){ + if(!code || Object.keys(code).sort().join(',')!=='campaign,session,token' || ['token','campaign','session'].some(k=>typeof code[k]!=='string'||!code[k]||code[k].length>512))throw new MusicError('denied'); + return {url:this.#path+'/audio',options:{method:'POST',redirect:'error',credentials:'omit',cache:'no-store', + headers:{'Content-Type':'application/json',Authorization:`Bearer ${code.token}`},body:JSON.stringify({campaign:code.campaign,session:code.session})}}; + } +} diff --git a/src/providers/ma/webcrypto.mjs b/src/providers/ma/webcrypto.mjs new file mode 100644 index 0000000..5b86ff7 --- /dev/null +++ b/src/providers/ma/webcrypto.mjs @@ -0,0 +1,13 @@ +// Shared Web Crypto implementation: runs in a secure browser and Node 24. +export const randomKey=()=>globalThis.crypto.getRandomValues(new Uint8Array(32)); +export const hex=bytes=>[...bytes].map(n=>n.toString(16).padStart(2,'0')).join(''); +export async function hmac(key,text){ + const imported=await crypto.subtle.importKey('raw',key,{name:'HMAC',hash:'SHA-256'},false,['sign']); + return new Uint8Array(await crypto.subtle.sign('HMAC',imported,new TextEncoder().encode(text))); +} +export async function verifyHmac(key,text,signature){ + const imported=await crypto.subtle.importKey('raw',key,{name:'HMAC',hash:'SHA-256'},false,['verify']); + const bytes=Uint8Array.from(signature.match(/../g)??[],s=>parseInt(s,16)); + return crypto.subtle.verify('HMAC',imported,bytes,new TextEncoder().encode(text)); +} +export const base64url=bytes=>btoa(String.fromCharCode(...bytes)).replace(/\+/g,'-').replace(/\//g,'_').replace(/=+$/,''); diff --git a/src/providers/ma/websocket.mjs b/src/providers/ma/websocket.mjs new file mode 100644 index 0000000..9e18533 --- /dev/null +++ b/src/providers/ma/websocket.mjs @@ -0,0 +1,42 @@ +import {MusicError} from '../../core/controller.mjs'; +const commands=new Set(['players/get','player_queues/get','player_queues/get_active_queue','player_queues/items','music/playlists/library_items','music/radios/library_items','music/playlists/get','music/playlists/playlist_tracks','music/tracks/get',...['play_media','play_index','pause','resume','stop','seek','shuffle','repeat','clear'].map(a=>'player_queues/'+a)]); +// GM-local adapter for MA's public /ws API. No HTTP CORS dependency or server proxy. +export class GMMAWebSocket{ + #base;#token;#socket;#connect;#pending=new Map();#factory;#closed=false; + constructor({baseUrl,token,createSocket=url=>new WebSocket(url)}){this.#base=new URL(baseUrl).origin;this.#token=token;this.#factory=createSocket;} + async connect(){ + if(this.#closed)throw new MusicError('unavailable');if(this.#connect)return this.#connect; + this.#connect=new Promise((resolve,reject)=>{ + const url=new URL('/ws',this.#base);url.protocol=url.protocol==='https:'?'wss:':'ws:';const socket=this.#socket=this.#factory(url.href); + const id='auth-'+crypto.randomUUID(),timer=setTimeout(()=>{reject(new MusicError('unavailable'));this.close();},8000); + socket.onopen=()=>socket.send(JSON.stringify({message_id:id,command:'auth',args:{token:this.#token}})); + socket.onmessage=event=>{ + if(typeof event.data!=='string'||event.data.length>1048576){this.close();return;} + let msg;try{msg=JSON.parse(event.data);}catch{this.close();return;} + if(msg.message_id===id){clearTimeout(timer);if(msg.result?.authenticated===true)resolve();else{reject(new MusicError('denied'));this.close();}return;} + const pending=this.#pending.get(msg.message_id);if(!pending)return; // Drop unsolicited metadata/events. + if(Object.hasOwn(msg,'error_code')){pending.fail(new MusicError('unavailable'));return;} + pending.bytes+=event.data.length;if(pending.bytes>1048576){pending.fail(new MusicError('unavailable'));return;} + if(msg.partial===true){if(!Array.isArray(msg.result)||pending.parts.length+msg.result.length>5000){pending.fail(new MusicError('unavailable'));return;}pending.parts.push(...msg.result);return;} + pending.finish(pending.parts.length?[...pending.parts,...(Array.isArray(msg.result)?msg.result:[])]:msg.result); + }; + socket.onerror=()=>{clearTimeout(timer);reject(new MusicError('unavailable'));this.close();}; + socket.onclose=()=>{clearTimeout(timer);reject(new MusicError('unavailable'));this.#closed=true;for(const p of [...this.#pending.values()])p.fail(new MusicError('unavailable'));}; + });return this.#connect; + } + fetch=async(url,options)=>{ + if(url!==this.#base+'/api'||options.method!=='POST'||options.redirect!=='error')throw new MusicError('denied'); + let request;try{request=JSON.parse(options.body);}catch{throw new MusicError('denied');} + if(!commands.has(request.command))throw new MusicError('denied');await this.connect(); + if(options.signal?.aborted||this.#pending.size>=16)throw new MusicError('unavailable'); + return new Promise((resolve,reject)=>{ + const id=crypto.randomUUID();let pending; + const cleanup=()=>{clearTimeout(timer);options.signal?.removeEventListener('abort',abort);this.#pending.delete(id);}; + const finish=value=>{cleanup();const body=JSON.stringify(value??null);if(body.length>1048576){reject(new MusicError('unavailable'));return;}resolve(new Response(body,{headers:{'Content-Type':'application/json'}}));}; + const fail=error=>{cleanup();reject(error);};const abort=()=>fail(new MusicError('unavailable'));const timer=setTimeout(abort,5000); + pending={parts:[],bytes:0,finish,fail};this.#pending.set(id,pending);options.signal?.addEventListener('abort',abort,{once:true}); + try{this.#socket.send(JSON.stringify({...request,message_id:id}));}catch{fail(new MusicError('unavailable'));} + }); + }; + close(){if(this.#closed)return;this.#closed=true;for(const p of [...this.#pending.values()])p.fail(new MusicError('unavailable'));this.#socket?.close();this.#token=null;} +} diff --git a/src/providers/native/provider.mjs b/src/providers/native/provider.mjs new file mode 100644 index 0000000..354de93 --- /dev/null +++ b/src/providers/native/provider.mjs @@ -0,0 +1,71 @@ +// Per-sound stop and pausedTime approach adapted from VGM (MIT), release-1.4.5. +// Copyright (c) 2025 3 Death Saves. Full notice: licenses/VGM-MIT.txt. +import { MusicError } from '../../core/controller.mjs'; +export class NativeProvider { + constructor({ playlists, ownedPlaylistIds, campaign, session, sceneConflict = () => false }) { + Object.assign(this, { playlists, campaign, session, sceneConflict }); + this.owned = new Set(ownedPlaylistIds); + } + capabilities() { return { seek: true, exactOrderRestore: false, concurrentLayers: false, volume: true }; } + playlist(id, ctx) { + ctx.check(); + if (ctx.campaign !== this.campaign || ctx.session !== this.session || !this.owned.has(id)) throw new MusicError('denied'); + const p = this.playlists.get(id); + if (!p) throw new MusicError('unavailable'); + if (this.sceneConflict(id)) throw new MusicError('scene-conflict'); + return p; + } + async resolve(ref, ctx) { + const p = this.playlist(ref.id, ctx); + // Sequential single-track start only; automatic shuffled order is not an exact restore API. + if (p.mode !== 0) throw new MusicError('unsupported'); + const sound = [...p.sounds].sort((a,b) => a.sort-b.sort || a.id.localeCompare(b.id))[0]; + if (!sound) throw new MusicError('unavailable'); + return { id: p.id, soundId: sound.id }; + } + async snapshot(ctx) { + const playlists = [...this.owned].map(id => { + const p = this.playlist(id, ctx); + return { id, mode: p.mode, sounds: [...p.sounds].map(s => ({ + id: s.id, playing: s.playing, pausedTime: s.playing ? (s.sound?.currentTime ?? 0) : s.pausedTime, + repeat: s.repeat, volume: s.volume + })) }; + }); + return { version: 1, campaign: ctx.campaign, session: ctx.session, generation: ctx.generation, playlists }; + } + async stopOwned(ctx) { + for (const id of this.owned) { + const p = this.playlist(id, ctx); + const updates = [...p.sounds].filter(s => s.playing).map(s => ({ _id: s.id, playing: false, pausedTime: null })); + if (updates.length) { ctx.check(); await p.updateEmbeddedDocuments('PlaylistSound', updates); } + } + } + async apply(prepared, ctx) { + const p = this.playlist(prepared.id, ctx); + if (p.mode !== 0) throw new MusicError('unsupported'); + if (!p.sounds.get(prepared.soundId)) throw new MusicError('unavailable'); + ctx.check(); await p.updateEmbeddedDocuments('PlaylistSound', [{ _id: prepared.soundId, playing: true, pausedTime: 0 }]); + } + async restore(snapshot, ctx) { + ctx.check(); + if (snapshot.version !== 1 || snapshot.campaign !== ctx.campaign || snapshot.session !== ctx.session || + snapshot.generation > ctx.generation) throw new MusicError('stale'); + // Validate the entire restore before any mutation; never silently restart nonseekable audio. + const plans = snapshot.playlists.map(saved => { + const p = this.playlist(saved.id, ctx); + if (p.mode !== saved.mode || p.mode !== 0) throw new MusicError('unsupported'); + if (p.sounds.size !== saved.sounds.length) throw new MusicError('expired-media'); + const updates = saved.sounds.map(s => { + const live = p.sounds.get(s.id); + if (!live) throw new MusicError('expired-media'); + const offset = s.pausedTime; + const duration = live.sound?.duration; + if (offset != null && (!Number.isFinite(offset) || offset < 0 || + (offset > 0 && !(Number.isFinite(duration) && duration > 0)))) throw new MusicError('unsupported'); + return { _id: s.id, playing: s.playing, pausedTime: offset == null ? null : Math.min(offset, Math.max(0, (duration ?? 0)-0.01)), repeat: s.repeat, volume: s.volume }; + }); + return { p, updates }; + }); + for (const { p, updates } of plans) { ctx.check(); await p.updateEmbeddedDocuments('PlaylistSound', updates); } + } +} diff --git a/styles/adaptive-music.css b/styles/adaptive-music.css new file mode 100644 index 0000000..06a30e0 --- /dev/null +++ b/styles/adaptive-music.css @@ -0,0 +1,7 @@ +.adaptive-music-setup {display:grid;gap:0.7rem;max-height:75vh;overflow:auto;padding:0.5rem;} +.adaptive-music-setup fieldset,[data-adaptive-music="assignments"] {display:grid;gap:0.5rem;padding:0.75rem;} +.adaptive-music-setup fieldset:first-of-type {max-height:18rem;overflow:auto;} +.adaptive-music-setup label,[data-adaptive-music="assignments"] label {display:grid;gap:0.3rem;} +.adaptive-music-setup select,[data-adaptive-music="assignments"] select {width:100%;min-width:0;} +.adaptive-music-setup input[type="checkbox"] {justify-self:start;} +.adaptive-music-setup [role="status"] {font-weight:600;} diff --git a/tests/browser/audio.html b/tests/browser/audio.html new file mode 100644 index 0000000..e0f15a7 --- /dev/null +++ b/tests/browser/audio.html @@ -0,0 +1,29 @@ +Adaptive Music local audio experiment + + diff --git a/tests/js/catalog-audio.test.mjs b/tests/js/catalog-audio.test.mjs new file mode 100644 index 0000000..10294b7 --- /dev/null +++ b/tests/js/catalog-audio.test.mjs @@ -0,0 +1,69 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { MAReadClient } from '../../gateway/ma-client.mjs'; +import { GatewayControl } from '../../gateway/control.mjs'; +import { SyntheticAudioGateway } from '../../gateway/synthetic-audio.mjs'; +const item=(id,provider='approved')=>({media_type:'playlist',is_playable:true,name:'Safe ',provider_mappings:[{provider_instance:provider,item_id:id,available:true}],uri:'private',metadata:{secret:'private'}}); +function client(fetchImpl,approvedProviders=['approved']) { return new MAReadClient({baseUrl:'http://localhost',token:'fixture',target:'dedicated',approvedProviders,fetchImpl}); } +test('catalog paginates, strips private metadata and filters unapproved mappings',async()=>{ + const calls=[]; + const c=client(async(url,opts)=>{ + const {command,args}=JSON.parse(opts.body); calls.push({command,args}); + assert.deepEqual(args.provider,['approved']); + return Response.json(command.includes('/radios/')?[]:args.offset===0?Array.from({length:100},(_,i)=>item(String(i))):[item('100'),item('bad','forbidden')]); + }); + const result=await c.catalog(); assert.equal(result.length,101); + assert.equal(calls.length,3);assert.equal(calls[1].args.offset,100); + assert.deepEqual(Object.keys(result[0]).sort(),['id','kind','name','provider']); + const again=await c.catalog();assert.equal(result[0].id,again[0].id); + assert.ok(!JSON.stringify(result).includes('private')); +}); +test('empty provider allowlist denies without I/O; malformed and endless pages fail',async()=>{ + let calls=0;const c=client(async()=>{calls++;},[]); + await assert.rejects(c.catalog(),{code:'denied'});assert.equal(calls,0); + await assert.rejects(client(async()=>Response.json({error:'private'})).catalog(),{code:'unavailable'}); + await assert.rejects(client(async()=>Response.json(Array.from({length:100},(_,i)=>item(String(i))))).catalog(),{code:'unavailable'}); +}); +test('target validation rejects group, changed identity and unavailable player',async()=>{ + const valid={player_id:'dedicated',provider:'sendspin',available:true,enabled:true,group_members:[],group_childs:[],static_group_members:[]}; + for(const patch of [{active_group:'other'},{synced_to:'other'},{group_members:['household']},{player_id:'wrong'},{available:false},{provider:'sonos'}]) { + await assert.rejects(client(async()=>Response.json({...valid,...patch})).verifyTarget(),{code:'denied'}); + } +}); +function audioFixture(){ + let now=0; const control=new GatewayControl({campaigns:{a:{},b:{}},origin:'https://example.test',now:()=>now}); + const audio=new SyntheticAudioGateway({control});for(const campaign of ['a','b'])audio.provision({campaign,session:'s'}); + const request={campaign:'a',session:'s',origin:'https://example.test',token:control.mint({campaign:'a',session:'s',role:'listener',ttlMs:1000})}; + const publish=(campaign,generation,value)=>audio.publish({campaign,session:'s',generation,pcm:new Uint8Array(1920).fill(value)}); + return {control,audio,request,publish,set now(value){now=value;}}; +} +test('synthetic audio isolates simultaneous campaigns and copies every frame',()=>{ + const f=audioFixture(),a=f.audio.connect(f.request),b=f.audio.connect({...f.request,campaign:'b',token:f.control.mint({campaign:'b',session:'s',role:'listener'})}); + f.publish('a',1,11);f.publish('b',1,22); + assert.equal(a.next().pcm[0],11);assert.equal(b.next().pcm[0],22);assert.equal(a.next(),null); + f.publish('a',2,33);const frame=a.next();frame.pcm.fill(0);assert.equal(frame.sampleRate,24000); +}); +test('audio denies forged origin/session/role, unknown fields and cross-campaign grants',()=>{ + const f=audioFixture(); + for(const patch of [{token:'forged'},{origin:'https://evil.test'},{session:'other'},{campaign:'b'},{command:'group'},{url:'http://localhost'},{token:f.control.mint({campaign:'a',session:'s',role:'controller'})}])assert.throws(()=>f.audio.connect({...f.request,...patch}),{code:'denied'}); +}); +test('active listener revocation/expiry and slow-client overflow close handles',()=>{ + const f=audioFixture(),a=f.audio.connect(f.request);f.control.revoke(f.request.token);f.audio.sweep();assert.equal(a.closed,true); + const e=audioFixture(),b=e.audio.connect(e.request);e.now=1001;assert.throws(()=>b.next(),{code:'denied'});assert.equal(b.closed,true); + const s=audioFixture(),c=s.audio.connect(s.request);for(let i=1;i<=11;i++)s.publish('a',i,0); + assert.throws(()=>c.next(),{code:'stale'});assert.equal(c.closed,true); +}); +test('synthetic source rejects stale sessions/generations, oversized frames; connections are bounded',()=>{ + const f=audioFixture();f.publish('a',1,0);assert.throws(()=>f.publish('a',1,0),{code:'stale'}); + assert.throws(()=>f.audio.publish({campaign:'a',session:'old',generation:2,pcm:new Uint8Array(1920)}),{code:'stale'}); + assert.throws(()=>f.audio.publish({campaign:'a',session:'s',generation:2,pcm:new Uint8Array(1921)}),{code:'denied'}); + for(let i=0;i<16;i++)f.audio.connect(f.request);assert.throws(()=>f.audio.connect(f.request),{code:'denied'}); + f.audio.purge('a');assert.throws(()=>f.audio.connect(f.request),{code:'denied'}); +}); +test('catalog authorization denies listener and injection before upstream',async()=>{ + let calls=0;const control=new GatewayControl({campaigns:{a:{client:{catalog:async()=>{calls++;return [];}}}},origin:'https://example.test'}); + const request={campaign:'a',session:'s',origin:'https://example.test',token:control.mint({campaign:'a',session:'s',role:'controller'}),generation:1};request.fence=control.acquire(request).fence; + await assert.rejects(control.readCatalog({...request,provider:'forbidden'}),{code:'denied'}); + await assert.rejects(control.readCatalog({...request,token:control.mint({campaign:'a',session:'s',role:'listener'})}),{code:'denied'});assert.equal(calls,0); + assert.deepEqual(await control.readCatalog(request),[]);assert.equal(calls,1); +}); diff --git a/tests/js/configuration.test.mjs b/tests/js/configuration.test.mjs new file mode 100644 index 0000000..f5cd2c1 --- /dev/null +++ b/tests/js/configuration.test.mjs @@ -0,0 +1,43 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { savePlaylistConfiguration, mountPlaylistConfiguration, startConfigurationInterfaces } from '../../src/foundry/configuration.mjs'; +const choices=[{provider:'native',id:'owned',name:'Scene music'},{provider:'ma',id:'opaque',name:'Catalog music'}]; +function fixture(){ + let flag={boss:true,priority:7};const writes=[]; + const document={getFlag:()=>flag,async setFlag(ns,k,value){writes.push({ns,k,value});flag=value;}}; + return {document,writes,game:{user:{isGM:true}}}; +} +test('scene/combat configuration preserves independent flags and stores only tagged references',async()=>{ + for(const choice of choices){const f=fixture();await savePlaylistConfiguration({...f,choices,selected:JSON.stringify([choice.provider,choice.id])}); + assert.deepEqual(f.writes,[{ns:'adaptive-music',k:'music',value:{boss:true,priority:7,playlist:{provider:choice.provider,id:choice.id}}}]); + await savePlaylistConfiguration({...f,choices,selected:''});assert.equal(f.writes[1].value.playlist,null); + } +}); +test('role loss, stale selection and arbitrary URL/ID fail before document write',async()=>{ + const f=fixture();for(const selected of ['https://example.test/audio',JSON.stringify(['native','household']),JSON.stringify(['ma','stale'])])await assert.rejects(savePlaylistConfiguration({...f,choices,selected}),{code:'denied'}); + f.game.user.isGM=false;await assert.rejects(savePlaylistConfiguration({...f,choices,selected:''}),{code:'denied'});assert.equal(f.writes.length,0); +}); +// Tiny DOM harness exercises event wiring/text sinks; it is not Foundry/browser evidence. +class Element { + constructor(tag,ownerDocument){this.tag=tag;this.ownerDocument=ownerDocument;this.children=[];this.dataset={};this.listeners={};} + append(...children){this.children.push(...children);} + querySelector(){return this.children.find(c=>c.dataset?.adaptiveMusic);} + setAttribute(){} + addEventListener(name,fn){this.listeners[name]=fn;} + remove(){this.removed=true;} +} +function container(){const dom={createElement:tag=>new Element(tag,dom),createTextNode:text=>({textContent:text})};return new Element('div',dom);} +test('editor uses text for catalog labels and rechecks GM on actual save event',async()=>{ + const f=fixture(),root=container();const panel=mountPlaylistConfiguration({...f,container:root,choices:[...choices,{provider:'ma',id:'x',name:''}]}); + assert.equal(mountPlaylistConfiguration({...f,container:root,choices}),null); + const label=panel.children.find(c=>c.tag==='label'),select=label.children.find(c=>c.tag==='select'); + assert.ok(select.children.some(c=>c.textContent.includes('c.tag==='button'); + await button.listeners.click();assert.equal(f.writes.length,1); + f.game.user.isGM=false;await button.listeners.click();assert.equal(f.writes.length,1); +}); +test('configuration hook disposal prevents pending asynchronous render from mounting',async()=>{ + const f=fixture(),callbacks=new Map();let resolve;const off=[]; + const ui=startConfigurationInterfaces({...f,Hooks:{on(e,fn){callbacks.set(e,fn);return e;},off(...args){off.push(args);}},getChoices:()=>new Promise(r=>{resolve=r;})}); + const root=container();const pending=callbacks.get('renderSceneConfig')({document:f.document},root);ui.dispose();resolve(choices);await pending;assert.equal(root.children.length,0);assert.equal(off.length,2); +}); diff --git a/tests/js/connected-gateway.test.mjs b/tests/js/connected-gateway.test.mjs new file mode 100644 index 0000000..4f9496a --- /dev/null +++ b/tests/js/connected-gateway.test.mjs @@ -0,0 +1,100 @@ +import {test} from 'node:test'; +import assert from 'node:assert/strict'; +import {createServer} from 'node:http'; +import {MAReadClient} from '../../gateway/ma-client.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'; +import {SyntheticAudioGateway} from '../../gateway/synthetic-audio.mjs'; +import {MusicController} from '../../src/core/controller.mjs'; +const origin='https://foundry.example.test'; +async function fixture(){ + let items=[],state='idle',index=null,position=0;const writes=[],browserResponses=[]; + const track=id=>({queue_item_id:'occurrence-'+id,media_item:{media_type:'track',provider_mappings:[{provider_instance:'approved',item_id:id,available:true}]},duration:120}); + const queue=()=>({queue_id:'dev-only',active:true,available:true,items:items.length,state,current_index:index,current_item:items[index],elapsed_time:position,elapsed_time_last_updated:Date.now()/1000,repeat_mode:'off',shuffle_enabled:false,is_dynamic:false,autoplay_enabled:false,dont_stop_the_music_enabled:false,overlay_enabled:false,playback_speed:1,ended:false}); + let grouped=false; + const ma=createServer(async(req,res)=>{ + assert.equal(req.headers.authorization,'Bearer MA-secret-fixture');let text='';for await(const chunk of req)text+=chunk;const {command,args}=JSON.parse(text);let result; + if(command==='players/get')result={player_id:'dev-only',name:'Adaptive Music DEV',provider:'sendspin-fixture',available:true,enabled:true,group_members:grouped?['other']:[],group_childs:[],static_group_members:[]}; + else if(command==='player_queues/get'||command==='player_queues/get_active_queue')result=queue(); + else if(command==='player_queues/items')result=items.slice(args.offset,args.offset+args.limit); + else if(command==='music/playlists/library_items')result=['ambient','combat'].map(id=>({name:'Fixture '+id,media_type:'playlist',is_playable:true,is_dynamic:false,provider_mappings:[{provider_instance:'approved',item_id:id,available:true}]})); + else if(command==='music/radios/library_items')result=[]; + else if(command==='music/playlists/get')result={is_dynamic:false}; + else if(command==='music/playlists/playlist_tracks')result=[track(args.item_id+'-1').media_item,track(args.item_id+'-2').media_item]; + else{ + assert.equal(args.queue_id,'dev-only');writes.push(command); + if(command==='player_queues/stop')state='idle'; + if(command==='player_queues/clear'){items=[];index=null;position=0;} + if(command==='player_queues/play_media'){items=args.media.map(uri=>track(uri.split('/').at(-1)));index=0;position=0;if(args.option==='replace')state='playing';} + if(command==='player_queues/play_index'){index=args.index;position=args.seek_position;state='playing';} + if(command==='player_queues/pause')state='paused';result=null; + } + res.writeHead(200,{'Content-Type':'application/json'});res.end(JSON.stringify(result)); + });await new Promise(resolve=>ma.listen(0,'127.0.0.1',resolve)); + const client=new MAReadClient({baseUrl:`http://127.0.0.1:${ma.address().port}`,token:'MA-secret-fixture',target:'dev-only',approvedProviders:['approved'],catalogKey:Buffer.alloc(32,1),campaign:'server-c',expectedName:'Adaptive Music DEV',expectedProvider:'sendspin-fixture'}); + const choices=await client.catalog(); + let offset=0;const control=new GatewayControl({campaigns:{'server-c':{client}},origin,now:()=>Date.now()+offset});const grant=role=>({token:control.mint({campaign:'server-c',session:'server-s',role}),campaign:'server-c',session:'server-s'}); + const controller=grant('controller'),listener=grant('listener'); + const audio=new SyntheticAudioGateway({control});audio.provision({campaign:'server-c',session:'server-s'}); + const service=new DevelopmentService({control,campaign:'server-c',session:'server-s',client,snapshotKey:Buffer.alloc(32,2),allowedIds:choices.map(c=>c.id),playbackEnabled:true,audio}); + const http=await startDevelopmentHTTP({service,origin}); + const fetchImpl=async(path,options)=>{const response=await fetch(http.url+path.replace('/adaptive-music-gateway',''),{...options,headers:{...options.headers,Origin:origin}});browserResponses.push(await response.clone().text());return response;}; + const browser=new GatewayClient({origin,fetchImpl}); + return {browser,http,control,controller,listener,service,choices,writes,browserResponses,audio,client,expire(){offset=60001;},set grouped(value){grouped=value;},async close(){await browser.disconnect();await http.close();await new Promise(resolve=>ma.close(resolve));ma.closeAllConnections();}}; +} +test('packaged browser client connects through real loopback companion/MA wire fixtures and restores combat queue',async()=>{ + const f=await fixture();try{ + const status=await f.browser.connect(f.controller);assert.equal(status.target,'verified');assert.equal(f.browser.catalog.length,2); + const controller=new MusicController({campaign:'browser-world',session:'browser-session',providers:{ma:f.browser},authority:()=>true}); + const base={scene:{id:'scene',playlist:{provider:'ma',id:f.choices[0].id}},combats:[]}; + await controller.update(base);const combat={...base,combats:[{id:'combat',sceneId:'scene',active:true,started:true,playlist:{provider:'ma',id:f.choices[1].id}}]}; + await controller.update(combat);await controller.update(base);assert.equal(controller.current.playlist.id,f.choices[0].id); + const before=f.writes.length;await Promise.allSettled([controller.update(combat),controller.update(base)]);assert.equal(f.writes.length,before); + const wire=f.browserResponses.join('');assert.ok(!wire.includes('MA-secret-fixture'));assert.ok(!wire.includes('approved://'));assert.ok(!wire.includes('dev-only'));assert.ok(wire.includes('handle')); + f.grouped=true;await assert.rejects(f.browser.stopOwned({generation:++controller.generation,check(){}}),{code:'denied'});assert.equal(f.writes.length,before); + }finally{await f.close();} +}); +test('companion denies listener control, wrong scope/Origin, upstream injection and unknown routes',async()=>{ + const f=await fixture();try{ + await assert.rejects(f.browser.connect(f.listener),{code:'denied'}); + const rpc=async(body,{grant=f.controller,requestOrigin=origin,path='/rpc'}={})=>fetch(f.http.url+path,{method:'POST',headers:{Origin:requestOrigin,Authorization:`Bearer ${grant.token}`,'Content-Type':'application/json'},body:JSON.stringify({...grant,token:undefined,...body})}); + for(const patch of [{campaign:'other',action:'catalog'},{action:'catalog',queue_id:'household'},{action:'transfer'}]){const res=await rpc(patch);assert.equal(res.status,403);} + assert.equal((await rpc({action:'catalog'},{requestOrigin:'https://evil.test'})).status,403); + assert.equal((await rpc({action:'catalog'},{path:'/api'})).status,403);assert.equal(f.writes.length,0); + }finally{await f.close();} +}); +test('browser accepts only relative same-origin paths and never persists a connection grant',()=>{ + for(const path of ['https://example.test','//evil.test','/../api','/api?token=x','/api#x'])assert.throws(()=>new GatewayClient({origin,path}),{code:'denied'}); +}); +test('companion operation replay is idempotent and same ID with changed payload is denied',async()=>{ + const f=await fixture();try{ + await f.browser.connect(f.controller); + const body={action:'stop',campaign:f.controller.campaign,session:f.controller.session,fence:1,generation:1,operationId:'same-operation'}; + const send=patch=>fetch(f.http.url+'/rpc',{method:'POST',headers:{Origin:origin,Authorization:`Bearer ${f.controller.token}`,'Content-Type':'application/json'},body:JSON.stringify({...body,...patch})}); + assert.equal((await send()).status,200);assert.equal((await send()).status,200);assert.equal(f.writes.filter(c=>c==='player_queues/stop').length,1); + assert.equal((await send({action:'snapshot'})).status,403);assert.equal((await send({generation:0,operationId:'stale'})).status,403); + }finally{await f.close();} +}); +test('companion listener stream rejects controller grant and closes on live revocation and expiry',async()=>{ + for(const mode of ['revoke','expire']){ + const f=await fixture();try{ + const open=grant=>fetch(f.http.url+'/audio',{method:'POST',headers:{Origin:origin,Authorization:`Bearer ${grant.token}`,'Content-Type':'application/json'},body:JSON.stringify({campaign:grant.campaign,session:grant.session})}); + const denied=await open(f.controller);assert.equal(denied.status,403); + const response=await open(f.listener);assert.equal(response.status,200);const reader=response.body.getReader(); + f.audio.publish({campaign:'server-c',session:'server-s',generation:1,pcm:new Uint8Array(1920).fill(7)});assert.equal((await reader.read()).value[0],7); + if(mode==='revoke')f.control.revoke(f.listener.token);else f.expire(); + let timer;try{await assert.rejects(Promise.race([reader.read(),new Promise((resolve,reject)=>{timer=setTimeout(()=>reject(Error('stream did not close promptly')),500);})]),{name:'TypeError'});}finally{clearTimeout(timer);} + assert.equal(f.writes.length,0); + }finally{await f.close();} + } +}); + +test('catalog revocation during upstream I/O suppresses the response at the companion boundary',async()=>{ + const f=await fixture();try{ + f.client.catalog=async()=>{f.control.revoke(f.controller.token);return [{name:'must never leave'}];}; + await assert.rejects(f.browser.connect(f.controller),{code:'denied'}); + assert.ok(!f.browserResponses.join('').includes('must never leave'));assert.equal(f.writes.length,0); + }finally{await f.close();} +}); diff --git a/tests/js/controller.test.mjs b/tests/js/controller.test.mjs new file mode 100644 index 0000000..b7adf20 --- /dev/null +++ b/tests/js/controller.test.mjs @@ -0,0 +1,128 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { MusicController, MusicError, candidates } from '../../src/core/controller.mjs'; +const ref = id => ({ provider: 'native', id }); +const scene = (id = 'A') => ({ id, playlist: ref(id) }); +const combat = (bosses = []) => ({ id: 'fight', active: true, started: true, sceneId: 'A', playlist: ref('combat'), bosses }); +const boss = (id = 'boss', priority = 1) => ({ id, priority, active: true, playlist: ref(id) }); +function fixture(options = {}) { + const log = []; let playback = { items: ['duplicate','duplicate','third'], index: 1, offset: 42, paused: true }; + const provider = { + async resolve(r,c) { log.push(['resolve',r.id]); return r; }, + async snapshot(c) { return { ...structuredClone(playback), campaign: c.campaign, session: c.session, generation: c.generation }; }, + async stopOwned(c) { c.check(); log.push(['stop']); }, + async apply(r,c) { c.check(); log.push(['apply',r.id]); playback = { items: [r.id], index: 0, offset: 0, paused: false }; }, + async restore(s,c) { c.check(); log.push(['restore',s]); playback = structuredClone(s); } + }; + const controller = new MusicController({ campaign: 'campaign', session: 'session', providers: { native: provider, other: provider }, authority: () => true, ...options }); + return { controller, provider, log, get playback() { return playback; }, set playback(p) { playback=p; } }; +} +test('policy precedence and explicit silence', () => { + assert.equal(candidates({scene:scene(),combats:[combat([boss()])],overrides:[{id:'silence',playlist:null}]})[0].playlist,null); + assert.equal(candidates({scene:scene(),combats:[combat([boss()])]})[0].playlist.id,'boss'); + assert.equal(candidates({scene:scene(),combats:[combat()]})[0].playlist.id,'combat'); + assert.equal(candidates({scene:scene()})[0].playlist.id,'A'); + assert.equal(candidates({defaultPlaylist:ref('world')})[0].playlist.id,'world'); + assert.equal(candidates({})[0].playlist,null); +}); +test('inactive, unstarted and other scene combats ignored; boss ties stable', () => { + for (const change of [{active:false},{started:false},{sceneId:'B'}]) { + assert.equal(candidates({scene:scene(),combats:[{...combat([boss()]),...change}]})[0].playlist.id,'A'); + } + assert.equal(candidates({scene:scene(),combats:[combat([boss('z',3),boss('a',3),boss('b',2)])]})[0].playlist.id,'a'); +}); +test('scene -> combat -> boss -> nested manual -> unwind restores offsets, duplicates and pause', async () => { + const f=fixture(), c=f.controller; + const base={scene:scene()}, fight={...base,combats:[combat()]}, big={...base,combats:[combat([boss()])]}; + await c.update(base); f.playback={items:['same','same','end'],index:1,offset:42,paused:true}; + await c.update(fight); await c.update(big); + await c.update({...big,overrides:[{id:'one',playlist:ref('one')}]}); + await c.update({...big,overrides:[{id:'one',playlist:ref('one')},{id:'two',playlist:null}]}); + assert.equal((await c.update({...big,overrides:[{id:'one',playlist:ref('one')}]})).restored,true); + assert.equal((await c.update(big)).restored,true); + assert.equal((await c.update(fight)).restored,true); + assert.equal((await c.update(base)).restored,true); + assert.deepEqual(f.playback.items,['same','same','end']); assert.equal(f.playback.index,1); + assert.equal(f.playback.offset,42); assert.equal(f.playback.paused,true); +}); +test('scene change during manual never resurrects previous scene', async () => { + const f=fixture(); const overrides=[{id:'manual',playlist:ref('manual')}]; + await f.controller.update({scene:scene()}); await f.controller.update({scene:scene(),overrides}); + await f.controller.update({scene:scene('B'),overrides}); await f.controller.update({scene:scene('B')}); + assert.equal(f.playback.items[0],'B'); assert.equal(f.controller.frames.length,0); +}); +test('boss removed during manual and deleted combat cannot return', async () => { + const f=fixture(); const base={scene:scene()}, big={...base,combats:[combat([boss()])]}; + await f.controller.update(base); await f.controller.update(big); + await f.controller.update({...big,overrides:[{id:'m',playlist:ref('m')}]}); + await f.controller.update({...base,overrides:[{id:'m',playlist:ref('m')}]}); + await f.controller.update(base); assert.equal(f.playback.items[0],'A'); + assert.equal(f.controller.frames.length,0); +}); +test('duplicate intent causes zero provider mutations', async () => { + const f=fixture(); await f.controller.update({scene:scene()}); const before=f.log.length; + assert.equal((await f.controller.update({scene:scene()})).unchanged,true); assert.equal(f.log.length,before); +}); +test('prepare failure leaves current playback intact', async () => { + const f=fixture(); await f.controller.update({scene:scene()}); + f.provider.resolve=async()=>{throw new MusicError('unavailable');}; + await assert.rejects(f.controller.update({scene:scene('B')}),{code:'unavailable'}); + assert.equal(f.playback.items[0],'A'); assert.equal(f.log.filter(x=>x[0]==='stop').length,0); +}); +test('partial apply failure restores outgoing playback', async () => { + const f=fixture(); await f.controller.update({scene:scene()}); + f.provider.apply=async()=>{throw new MusicError('unavailable');}; + await assert.rejects(f.controller.update({scene:scene('B')})); assert.equal(f.playback.items[0],'A'); +}); +test('obsolete async resolve is rejected before stop/apply', async () => { + const f=fixture(); let resume, entered; + const ready=new Promise(r=>entered=r), normal=f.provider.resolve; + f.provider.resolve=async(r,c)=>{if(r.id==='A'){entered();await new Promise(r=>resume=r);} return normal(r,c);}; + const first=f.controller.update({scene:scene()}); await ready; + const second=f.controller.update({scene:scene('B')}); resume(); + await assert.rejects(first,{code:'stale'}); await second; + assert.deepEqual(f.log.filter(x=>x[0]==='apply'),[['apply','B']]); +}); +test('lease loss during stop prevents apply and stale rollback', async () => { + let active=true; const f=fixture({authority:()=>active}); await f.controller.update({scene:scene()}); + f.provider.stopOwned=async()=>{active=false;}; + await assert.rejects(f.controller.update({scene:scene(),combats:[combat()]}),{code:'stale'}); + assert.equal(f.log.filter(x=>x[0]==='restore').length,0); +}); +test('provider switch and bounded nested stack', async () => { + const f=fixture({maxFrames:2}); await f.controller.update({scene:scene()}); + await f.controller.update({scene:{id:'B',playlist:{provider:'other',id:'other'}}}); + assert.equal(f.playback.items[0],'other'); + for(let i=0;i<5;i++) await f.controller.update({scene:scene(),overrides:Array.from({length:i+1},(_,j)=>({id:String(j),playlist:ref(String(j))}))}); + assert.ok(f.controller.frames.length<=2); +}); +test('no authority retains playback without provider access', async () => { + const f=fixture({authority:()=>false}); await assert.rejects(f.controller.update({scene:scene()}),{code:'stale'}); assert.deepEqual(f.log,[]); +}); +test('queued state is captured at submission rather than read after caller mutation',async()=>{ + const f=fixture(),state={scene:scene()};const pending=f.controller.update(state);state.scene.playlist=ref('mutated'); + await pending;assert.equal(f.playback.items[0],'A'); +}); +test('supersession after snapshot prevents mutations',async()=>{ + const f=fixture();await f.controller.update({scene:scene()}); + let resume,entered;const ready=new Promise(r=>entered=r),normal=f.provider.snapshot; + f.provider.snapshot=async c=>{const s=await normal(c);entered();await new Promise(r=>resume=r);return s;}; + const first=f.controller.update({scene:scene(),combats:[combat()]});await ready; + f.provider.snapshot=normal;const second=f.controller.update({scene:scene('B')});resume(); + await assert.rejects(first,{code:'stale'});await second; + assert.equal(f.log.filter(x=>x[0]==='apply'&&x[1]==='combat').length,0); +}); +test('failed cross-provider apply cleans new owned audio before outgoing restoration',async()=>{ + const f=fixture();await f.controller.update({scene:scene()});const effects=[]; + f.controller.providers.other={resolve:async r=>r,apply:async()=>{effects.push('partial');throw new Error('failed');},stopOwned:async()=>effects.push('cleanup')}; + await assert.rejects(f.controller.update({scene:{id:'B',playlist:{provider:'other',id:'B'}}})); + assert.deepEqual(effects,['partial','cleanup']);assert.equal(f.playback.items[0],'A'); +}); +test('superseded cross-provider apply is reconciled by stopping partially touched target',async()=>{ + const f=fixture();await f.controller.update({scene:scene()}); + let resume,entered;const ready=new Promise(r=>entered=r);let cleanups=0; + f.controller.providers.other={resolve:async r=>r,apply:async()=>{entered();await new Promise(r=>resume=r);},stopOwned:async()=>{cleanups++;}}; + const stale=f.controller.update({scene:{id:'B',playlist:{provider:'other',id:'B'}}});await ready; + const newest=f.controller.update({scene:scene()});resume();await assert.rejects(stale,{code:'stale'});await newest; + assert.equal(cleanups,1);assert.equal(f.playback.items[0],'A'); +}); diff --git a/tests/js/development-launcher.test.mjs b/tests/js/development-launcher.test.mjs new file mode 100644 index 0000000..2ee4d08 --- /dev/null +++ b/tests/js/development-launcher.test.mjs @@ -0,0 +1,38 @@ +import {test} from 'node:test'; +import assert from 'node:assert/strict'; +import {mkdtemp,mkdir,writeFile,readFile,rm} from 'node:fs/promises'; +import {tmpdir} from 'node:os'; +import {join} from 'node:path'; +import {fileURLToPath} from 'node:url'; +import {spawn,spawnSync} from 'node:child_process'; +import {createServer} from 'node:http'; +test('extracted companion launches privately with fixture credentials, serves catalog diagnostics and listener PCM',async()=>{ + const folder=await mkdtemp(join(tmpdir(),'adaptive-companion-')),commands=[]; + const ma=createServer(async(req,res)=>{let text='';for await(const chunk of req)text+=chunk;const {command}=JSON.parse(text);commands.push(command);let result; + if(command==='players/get')result={player_id:'dev-only',name:'Adaptive Music DEV',provider:'sendspin-fixture',enabled:true,available:true,group_members:[],group_childs:[],static_group_members:[]}; + else if(command.startsWith('player_queues/get'))result={queue_id:'dev-only',active:true,available:true};else result=[]; + res.writeHead(200,{'Content-Type':'application/json'});res.end(JSON.stringify(result));}); + await new Promise(resolve=>ma.listen(0,'127.0.0.1',resolve));let child; + try{ + const source=fileURLToPath(new URL('../../scripts/package_module.py',import.meta.url)); + const script="import importlib.util,pathlib,sys,zipfile;s=importlib.util.spec_from_file_location('p',sys.argv[1]);m=importlib.util.module_from_spec(s);s.loader.exec_module(m);p=m.build_companion(pathlib.Path(sys.argv[2])/'companion.zip');zipfile.ZipFile(p).extractall(sys.argv[2])"; + const built=spawnSync('python3',['-c',script,source,folder],{encoding:'utf8'});assert.equal(built.status,0,built.stderr); + const root=join(folder,'adaptive-music-companion'),local=join(root,'.local');await mkdir(local,{mode:0o700}); + const json=(name,value)=>writeFile(join(local,name),JSON.stringify(value),{mode:0o600}); + await writeFile(join(local,'ma-token'),'fixture-MA-secret',{mode:0o600}); + await json('environment.json',{ma_url:`http://127.0.0.1:${ma.address().port}`});await json('development-gateway.json',{foundryOrigin:'https://foundry.example.test',syntheticAudio:true}); + await json('ma-readonly-results.json',{me:{player_filter:['dev-only'],provider_filter:['approved']},player:{name:'Adaptive Music DEV',provider:'sendspin-fixture'}}); + child=spawn(process.execPath,['gateway/run-development.mjs'],{cwd:root,stdio:['ignore','pipe','pipe']});let output='';child.stdout.on('data',chunk=>{output+=chunk;});child.stderr.on('data',chunk=>{output+=chunk;}); + for(let attempt=0;attempt<200;attempt++){try{await readFile(join(local,'listener-bootstrap.json'));break;}catch{await new Promise(resolve=>setTimeout(resolve,10));}} + const runtime=JSON.parse(await readFile(join(local,'development-gateway-runtime.json'),'utf8')),controller=JSON.parse(await readFile(join(local,'controller-bootstrap.json'),'utf8')),listener=JSON.parse(await readFile(join(local,'listener-bootstrap.json'),'utf8')); + assert.ok(runtime.url.startsWith('http://127.0.0.1:'));assert.ok(!output.includes('fixture-MA-secret')); + const rpc=async(action)=>fetch(runtime.url+'/rpc',{method:'POST',headers:{Origin:'https://foundry.example.test','Content-Type':'application/json',Authorization:`Bearer ${controller.token}`},body:JSON.stringify({action,campaign:controller.campaign,session:controller.session})}); + assert.equal((await rpc('connect')).status,200);const d=await (await rpc('diagnostics')).json();assert.equal(d.target,'verified');assert.equal(d.playbackEnabled,false);assert.deepEqual(await (await rpc('catalog')).json(),[]); + const before=commands.length; + const audio=await fetch(runtime.url+'/audio',{method:'POST',headers:{Origin:'https://foundry.example.test','Content-Type':'application/json',Authorization:`Bearer ${listener.token}`},body:JSON.stringify({campaign:listener.campaign,session:listener.session})}); + assert.equal(audio.status,200);const reader=audio.body.getReader();const frame=await reader.read();assert.ok(frame.value.length>=1920);await reader.cancel();assert.equal(commands.length,before);assert.ok(!commands.some(c=>['player_queues/play_media','player_queues/stop'].includes(c))); + }finally{ + if(child&&child.exitCode===null){const exited=new Promise(resolve=>child.once('exit',resolve));child.kill('SIGTERM');await exited;} + ma.closeAllConnections();await new Promise(resolve=>ma.close(resolve));await rm(folder,{recursive:true,force:true}); + } +}); diff --git a/tests/js/gateway.test.mjs b/tests/js/gateway.test.mjs new file mode 100644 index 0000000..6781dc9 --- /dev/null +++ b/tests/js/gateway.test.mjs @@ -0,0 +1,79 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { GatewayControl } from '../../gateway/control.mjs'; +import { MAReadClient } from '../../gateway/ma-client.mjs'; +function fixture() { + let now=1000,calls=0; + const g=new GatewayControl({campaigns:{a:{target:'dedicated-a',client:{async getOwnedQueue(id){assert.equal(id,'dedicated-a');calls++;return {state:'playing',items:3,secret:'must never leave'};}}},b:{target:'dedicated-b'}},origin:'https://example.test',now:()=>now}); + const token=g.mint({campaign:'a',session:'s',role:'controller'}); + const request={token,origin:'https://example.test',campaign:'a',session:'s',generation:1}; + request.fence=g.acquire(request).fence; + return {g,request,get calls(){return calls;},set now(value){now=value;}}; +} +test('gateway binds target server-side and sanitizes metadata',async()=>{ + const f=fixture();assert.deepEqual(await f.g.readQueue(f.request),{state:'playing',items:3});assert.equal(f.calls,1); +}); +test('forged, wrong origin/campaign/session and unknown args deny before upstream',async()=>{ + const f=fixture(); + for(const patch of [{token:'forged'},{origin:'https://evil.test'},{campaign:'b'},{session:'other'},{queue_id:'household'},{command:'player_queues/transfer'},{uri:'http://example.test/'}]) + await assert.rejects(f.g.readQueue({...f.request,...patch}),{code:'denied'}); + assert.equal(f.calls,0); +}); +test('listener cannot read queues or acquire controller lease',async()=>{ + const f=fixture(),token=f.g.mint({campaign:'a',session:'s',role:'listener'}); + await assert.rejects(f.g.readQueue({...f.request,token}),{code:'denied'}); + assert.throws(()=>f.g.acquire({...f.request,token}),{code:'denied'});assert.equal(f.calls,0); +}); +test('expiry, revocation, stale fence and replay reject',async()=>{ + const f=fixture();await f.g.readQueue(f.request); + await assert.rejects(f.g.readQueue(f.request),{code:'stale'}); + await assert.rejects(f.g.readQueue({...f.request,generation:2,fence:999}),{code:'stale'}); + f.now=40000;await assert.rejects(f.g.readQueue({...f.request,generation:2}),{code:'stale'}); + f.g.revoke(f.request.token);await assert.rejects(f.g.readQueue({...f.request,generation:2}),{code:'denied'}); +}); +test('lease cannot be stolen and increases fence after revoke',()=>{ + const f=fixture(),token=f.g.mint({campaign:'a',session:'s2',role:'controller'}); + assert.throws(()=>f.g.acquire({...f.request,token,session:'s2'}),{code:'denied'}); + f.g.revoke(f.request.token);const next=f.g.acquire({...f.request,token,session:'s2'});assert.equal(next.fence,2); +}); +test('revocation during upstream I/O suppresses response',async()=>{ + const f=fixture();f.g.campaigns.get('a').client.getOwnedQueue=async()=>{f.g.revoke(f.request.token);return {state:'playing',items:1};}; + await assert.rejects(f.g.readQueue(f.request),{code:'denied'}); +}); +test('MA adapter uses pinned envelope, Bearer header, fixed path, no redirects and returns no metadata',async()=>{ + const client=new MAReadClient({baseUrl:'http://localhost:9999',token:'fixture-token',target:'owned',fetchImpl:async(url,options)=>{ + assert.equal(url,'http://localhost:9999/api');assert.equal(options.redirect,'error'); + assert.equal(options.headers.Authorization,'Bearer fixture-token'); + assert.deepEqual(JSON.parse(options.body),{message_id:'adaptive-music-read',command:'player_queues/get',args:{queue_id:'owned'}}); + return new Response(JSON.stringify({queue_id:'owned',active:true,state:'paused',items:2,uri:'secret'})); + }}); + assert.deepEqual(await client.getOwnedQueue('owned'),{state:'paused',items:2}); + await assert.rejects(client.getOwnedQueue('household'),{code:'denied'}); +}); +test('MA mismatched queue, upstream failures and redirects fail with sanitized errors',async()=>{ + for(const fetchImpl of [async()=>new Response(JSON.stringify({queue_id:'household',active:true})), async()=>{throw new Error('private URL and secret');},async()=>new Response('failure',{status:403}),async()=>new Response('x'.repeat(1048577))]){ + const client=new MAReadClient({baseUrl:'http://localhost:9999',token:'fixture',target:'owned',fetchImpl}); + await assert.rejects(client.getOwnedQueue('owned'),e=>['denied','unavailable'].includes(e.message)); + } +}); +test('MA rejects URL credentials, query/fragment, paths and non-HTTP configuration',()=>{ + for(const baseUrl of ['file:///etc/passwd','http://localhost/path','http://localhost/?token=x','http://localhost/#x','http://' + 'user:pass' + '@localhost/']) + assert.throws(()=>new MAReadClient({baseUrl,token:'fixture',target:'owned'})); +}); +test('MA read adapter performs real local HTTP POST against an isolated fixture',async()=>{ + const {createServer}=await import('node:http'); + const requests=[]; + const server=createServer(async(req,res)=>{ + let body='';for await(const chunk of req)body+=chunk; + requests.push({method:req.method,path:req.url,auth:req.headers.authorization,body:JSON.parse(body)}); + res.writeHead(200,{'Content-Type':'application/json'}); + res.end(JSON.stringify({queue_id:'fixture-target',active:true,state:'paused',items:3})); + }); + await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve)); + try { + const client=new MAReadClient({baseUrl:`http://127.0.0.1:${server.address().port}`,token:'offline-fixture-only',target:'fixture-target'}); + assert.deepEqual(await client.getOwnedQueue('fixture-target'),{state:'paused',items:3}); + assert.equal(requests.length,1);assert.equal(requests[0].path,'/api');assert.equal(requests[0].method,'POST'); + assert.equal(requests[0].body.args.queue_id,'fixture-target');assert.equal(requests[0].auth,'Bearer offline-fixture-only'); + } finally { await new Promise(resolve=>server.close(resolve)); } +}); diff --git a/tests/js/gm-audio.test.mjs b/tests/js/gm-audio.test.mjs new file mode 100644 index 0000000..36ffc5c --- /dev/null +++ b/tests/js/gm-audio.test.mjs @@ -0,0 +1,66 @@ +import {test} from 'node:test'; +import assert from 'node:assert/strict'; +import {SignalCodec,newAudioInvite} from '../../src/audio/signal-codec.mjs'; +import {PeerAudio,validateIceServers} from '../../src/audio/peer-audio.mjs'; +import {gmAccessPolicy,GMAudioHost} from '../../src/audio/gm-host.mjs'; +import {SendspinDecoder} from '../../vendor/sendspin-5.0.0.mjs'; +test('signaling is confidential, per-listener authenticated, scoped and replay resistant',async()=>{ + const invite=newAudioInvite({session:'s',userId:'player'}),gm=new SignalCodec(invite,'gm'),listener=new SignalCodec(invite,'listener'); + const secretSdp='v=0\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\na=sendonly\r\n'; + const frame=await gm.seal({type:'answer',sdp:secretSdp});assert.ok(!JSON.stringify(frame).includes('m=audio')); + assert.deepEqual(await listener.open(frame),{type:'answer',sdp:secretSdp});await assert.rejects(listener.open(frame),{code:'denied'}); + const other=new SignalCodec(newAudioInvite({session:'s',userId:'other'}),'listener');await assert.rejects(other.open(frame),{code:'denied'}); + await assert.rejects(new SignalCodec(invite,'listener').open({...frame,seq:2}),{code:'denied'}); + await assert.rejects(gm.seal({type:'answer',sdp:secretSdp,token:'must not be sent'}),{code:'denied'}); +}); +test('signaling denies expired invitation, unknown/audio message types and unapproved TURN secrets',async()=>{ + assert.throws(()=>new SignalCodec({...newAudioInvite({session:'s',userId:'p'}),expires:0},'gm'),{code:'denied'}); + const codec=new SignalCodec(newAudioInvite({session:'s',userId:'p'}),'gm');await assert.rejects(codec.seal({type:'audio',pcm:[1,2]}),{code:'denied'}); + assert.deepEqual(validateIceServers([]),[]); + assert.throws(()=>validateIceServers([{urls:'turn:relay.example.test',username:'static',credential:'secret'}]),{code:'denied'}); + assert.throws(()=>validateIceServers([{urls:'https://example.test'}]),{code:'denied'}); + assert.throws(()=>validateIceServers([{urls:'stun:user@relay.example.test'}]),{code:'denied'}); +}); +test('GM browser policy refuses mixed content and SDK identity mismatch before any MA connection',async()=>{ + assert.throws(()=>gmAccessPolicy('http://ma.example.test/','https://foundry.example.test/'),{code:'mixed-content'}); + assert.throws(()=>gmAccessPolicy('https://ma.example.test/?token=no','https://foundry.example.test/'),{code:'denied'}); + let sockets=0,closed=0;const host=new GMAudioHost({authority:()=>true,pageUrl:'https://foundry.example.test/',loadSDK:async()=>({loadSendspinClientIdentity:()=>({clientId:'wrong'})}),createSocket:()=>{sockets++;},createContext:()=>({state:'running',resume:async()=>{},createMediaStreamDestination:()=>({stream:{getTracks:()=>[]}}),close:async()=>{closed++;}})}); + await assert.rejects(host.readCatalog({}),{code:'auth-log-review-required'});assert.equal(sockets,0); + await assert.rejects(host.start({maUrl:'https://ma.example.test/',target:'existing',targetName:'Adaptive Music DEV',expectedProvider:'sendspin-fixture',identityStorage:{'sendspin-identity-sk':'fixture'},approvedProviders:[],catalogKey:'fixture',namespace:'n'}),{code:'identity-mismatch'});assert.equal(sockets,0);assert.equal(closed,1); +}); +test('official pinned SDK decodes real binary PCM frames and discards stale generations',async()=>{ + const chunks=[];let generation=1;const decoder=new SendspinDecoder(chunk=>chunks.push(chunk),()=>generation); + const frame=new ArrayBuffer(9+8);const view=new DataView(frame);view.setUint8(0,4);view.setBigInt64(1,123456n,false);for(let i=0;i<4;i++)view.setInt16(9+i*2,16384,true); + const format={codec:'pcm',channels:2,sample_rate:24000,bit_depth:16};await decoder.handleBinaryMessage(frame,format,1);assert.equal(chunks.length,1);assert.equal(chunks[0].samples[0][0],0.5);assert.equal(chunks[0].serverTimeUs,123456); + generation=2;await decoder.handleBinaryMessage(frame,format,1);assert.equal(chunks.length,1);decoder.close(); +}); +test('parallel signaling replay cannot pass the asynchronous authentication check twice',async()=>{ + const invite=newAudioInvite({session:'parallel',userId:'p'}),sender=new SignalCodec(invite,'gm'),receiver=new SignalCodec(invite,'listener'); + const frame=await sender.seal({type:'bye'});const results=await Promise.allSettled([receiver.open(frame),receiver.open(frame)]);assert.equal(results.filter(r=>r.status==='fulfilled').length,1); +}); +test('GM API WebSocket adapter authenticates privately, assembles partial results and refuses broad commands',async()=>{ + const {GMMAWebSocket}=await import('../../src/providers/ma/websocket.mjs');const sent=[]; + const bridge=new GMMAWebSocket({baseUrl:'https://ma.example.test',token:'GM-fixture-only',createSocket:url=>{ + assert.equal(url,'wss://ma.example.test/ws'); + const socket={send(text){const msg=JSON.parse(text);sent.push(msg);queueMicrotask(()=>{if(msg.command==='auth')socket.onmessage({data:JSON.stringify({message_id:msg.message_id,result:{authenticated:true}})});else{socket.onmessage({data:JSON.stringify({message_id:msg.message_id,partial:true,result:[{fixture:1}]})});socket.onmessage({data:JSON.stringify({message_id:msg.message_id,result:[{fixture:2}]})});}});},close(){this.onclose?.();}}; + queueMicrotask(()=>socket.onopen());return socket; + }}); + try{ + const response=await bridge.fetch('https://ma.example.test/api',{method:'POST',redirect:'error',body:JSON.stringify({command:'music/playlists/library_items',args:{},message_id:'local'})});assert.deepEqual(await response.json(),[{fixture:1},{fixture:2}]); + assert.equal(sent[0].command,'auth');assert.equal(sent[0].args.token,'GM-fixture-only');assert.ok(!JSON.stringify(sent[1]).includes('GM-fixture-only')); + await assert.rejects(bridge.fetch('https://ma.example.test/api',{method:'POST',redirect:'error',body:JSON.stringify({command:'players/all'})}),{code:'denied'}); + }finally{bridge.close();} +}); + +test('peer signaling bounds queued work and rejects expired invites before allocating a connection',async()=>{ + const handlers=new Map();let allocations=0; + const socket={on:(name,fn)=>handlers.set(name,fn),off:name=>handlers.delete(name),emit(){}}; + const peer=new PeerAudio({socket,userId:'gm',isGM:()=>true,createPeer:()=>{allocations++;return {close(){}};}}); + try{ + peer.setSource({getAudioTracks:()=>[{}]});const invite=peer.invite('player'); + for(let i=0;i<1000;i++)handlers.get('module.adaptive-music')({peer:invite.peer,session:invite.session}); + await new Promise(resolve=>setTimeout(resolve,20));assert.equal(peer.diagnostics().rejectedSignals,1000);assert.equal(allocations,1); + }finally{peer.close();} + const listener=new PeerAudio({socket,userId:'player',isGM:()=>false,createPeer:()=>{allocations++;}}); + try{await assert.rejects(listener.listen({...newAudioInvite({session:'s',userId:'player'}),expires:0}),{code:'denied'});assert.equal(allocations,1);}finally{listener.close();} +}); diff --git a/tests/js/loopback-audio.test.mjs b/tests/js/loopback-audio.test.mjs new file mode 100644 index 0000000..7c7d030 --- /dev/null +++ b/tests/js/loopback-audio.test.mjs @@ -0,0 +1,55 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { request } from 'node:http'; +import { GatewayControl } from '../../gateway/control.mjs'; +import { SyntheticAudioGateway } from '../../gateway/synthetic-audio.mjs'; +import { startLoopbackAudio } from '../../gateway/loopback-audio.mjs'; +const origin='https://example.test'; +async function setup(){ + let now=0;const control=new GatewayControl({campaigns:{a:{},b:{}},origin,now:()=>now}); + const audio=new SyntheticAudioGateway({control});audio.provision({campaign:'a',session:'s'}); + const token=control.mint({campaign:'a',session:'s',role:'listener',ttlMs:1000}); + const transport=await startLoopbackAudio({audio,campaign:'a',session:'s'}); + return {control,audio,token,transport,set now(value){now=value;}}; +} +function open(url,headers={}){ + return new Promise((resolve,reject)=>{const req=request(url,{headers},resolve);req.on('error',reject);req.setTimeout(2000,()=>req.destroy(new Error('fixture timeout')));req.end();}); +} +test('loopback transport denies unauthenticated, cross-campaign, controller, query and wrong-origin requests',async()=>{ + const f=await setup(); + try { + for(const [url,headers] of [[f.transport.url,{}],[f.transport.url,{origin,Authorization:'Bearer forged'}], + [f.transport.url,{origin:'https://evil.test',Authorization:`Bearer ${f.token}`}], + [f.transport.url+'?token=forbidden',{origin,Authorization:`Bearer ${f.token}`}], + [f.transport.url,{origin,Authorization:`Bearer ${f.control.mint({campaign:'b',session:'s',role:'listener'})}`}], + [f.transport.url,{origin,Authorization:`Bearer ${f.control.mint({campaign:'a',session:'s',role:'controller'})}`}], + [f.transport.url,{origin,host:'evil.test',Authorization:`Bearer ${f.token}`}]] ) { + const response=await open(url,headers);assert.equal(response.statusCode,403);let size=0; + for await(const chunk of response)size+=chunk.length;assert.equal(size,0); + } + } finally {await f.transport.close();} +}); +test('loopback streams synthetic PCM bytes and closes an active stream on revocation',async()=>{ + const f=await setup(); + try { + const response=await open(f.transport.url,{origin,Authorization:`Bearer ${f.token}`}); + assert.equal(response.statusCode,200);assert.equal(response.headers['cache-control'],'no-store'); + const samples=new Int16Array(960);for(let i=0;i<480;i++)samples[i*2]=samples[i*2+1]=Math.round(Math.sin(i*2*Math.PI*440/24000)*1000); + const pcm=new Uint8Array(samples.buffer); + const received=new Promise((resolve,reject)=>{response.once('data',resolve);response.once('error',reject);}); + f.audio.publish({campaign:'a',session:'s',generation:1,pcm}); + assert.deepEqual(new Uint8Array(await received),pcm); + const closed=new Promise(resolve=>response.once('close',resolve)); + // An aborted HTTP stream emits an expected error alongside close. + response.on('error',()=>{});f.control.revoke(f.token);await closed; + assert.equal(response.destroyed,true); + } finally {await f.transport.close();} +}); +test('loopback closes idle synthetic stream when its listener capability expires',async()=>{ + const f=await setup(); + try { + const response=await open(f.transport.url,{origin,Authorization:`Bearer ${f.token}`}); + response.on('error',()=>{});const closed=new Promise(resolve=>response.once('close',resolve)); + f.now=1001;await closed;assert.equal(response.destroyed,true); + } finally {await f.transport.close();} +}); diff --git a/tests/js/ma-provider.test.mjs b/tests/js/ma-provider.test.mjs new file mode 100644 index 0000000..b8c9038 --- /dev/null +++ b/tests/js/ma-provider.test.mjs @@ -0,0 +1,101 @@ +import {test} from 'node:test'; +import assert from 'node:assert/strict'; +import {MAPlaybackProvider} from '../../gateway/ma-provider.mjs'; +import {MAReadClient} from '../../gateway/ma-client.mjs'; +const key=Buffer.alloc(32,7); +const track=(id)=>({queue_item_id:id,duration:120,media_item:{media_type:'track',provider_mappings:[{provider_instance:'approved',item_id:id,available:true}]}}); +function fixture(){ + let items=[track('a'),track('a'),track('b')],state={items:3,state:'paused',repeat_mode:'all',shuffle_enabled:false,current_index:1,elapsed_time:17,elapsed_time_last_updated:Date.now()/1000,playback_speed:1}; + const writes=[];let allowed=true; + const client={verifyTarget:async()=>{},queueState:async()=>({...state,current_item:items[state.current_index]}),queueItems:async offset=>items.slice(offset,offset+100),mediaURI:i=>`approved://track/${i.media_item.provider_mappings[0].item_id}`,resolveCatalog:ref=> `approved://playlist/${ref.id}`, + async mutate(action,args,ctx){ctx.check();writes.push({action,args});if(action==='stop')state.state='idle';if(action==='clear'){items=[];state.items=0;state.current_index=null;state.elapsed_time=0;}if(action==='play_media'){items=args.media.flatMap(uri=>uri.includes('://playlist/')?[track(uri.split('/').at(-1)+'1'),track(uri.split('/').at(-1)+'2')]:[track(uri.split('/').at(-1))]);state.items=items.length;state.current_index=0;state.elapsed_time=0;if(args.option==='replace')state.state='playing';}if(action==='play_index'){state.current_index=args.index;state.elapsed_time=args.seek_position;state.state='playing';}if(action==='pause')state.state='paused';}}; + const provider=new MAPlaybackProvider({client,campaign:'c',session:'s',fence:1,authority:()=>{if(!allowed)throw Object.assign(Error(),{code:'stale'});},snapshotKey:key}); + const ctx={campaign:'c',session:'s',generation:1,check(){}}; + return {provider,client,ctx,writes,state,set allowed(v){allowed=v;}}; +} +test('MA snapshots ordered duplicate occurrences, pause and seek then reconstructs exact unshuffled order',async()=>{ + const f=fixture(),snapshot=await f.provider.snapshot(f.ctx);assert.equal(snapshot.value.items.length,3);assert.equal(snapshot.value.index,1);assert.equal(snapshot.value.position,17); + await f.provider.restore(snapshot,{...f.ctx,generation:2});assert.deepEqual(f.writes.map(w=>w.action),['stop','clear','repeat','play_media','play_index','pause']);assert.equal(f.state.current_index,1);assert.equal(f.state.elapsed_time,17);assert.equal(f.state.state,'paused'); +}); +test('tampered, foreign/future snapshots and stale authority deny before MA mutations',async()=>{ + const f=fixture(),snapshot=await f.provider.snapshot(f.ctx);const bad=structuredClone(snapshot);bad.value.position=0; + await assert.rejects(f.provider.restore(bad,f.ctx),{code:'stale'}); + await assert.rejects(f.provider.restore(snapshot,{...f.ctx,campaign:'other'}),{code:'stale'}); + f.allowed=false;await assert.rejects(f.provider.restore(snapshot,{...f.ctx,generation:2}),{code:'stale'});assert.equal(f.writes.length,0); +}); +test('shuffled snapshot fails before interruption rather than promising exact restore',async()=>{ + const f=fixture();f.state.shuffle_enabled=true;await assert.rejects(f.provider.snapshot(f.ctx),{code:'unsupported'});assert.equal(f.writes.length,0); +}); +test('prepared media cannot be forged and stale generations cannot issue controls',async()=>{ + const f=fixture();await assert.rejects(f.provider.apply({uri:'approved://playlist/forged'},f.ctx),{code:'denied'}); + await f.provider.control('pause',null,{...f.ctx,generation:4});await assert.rejects(f.provider.control('resume',null,{...f.ctx,generation:3}),{code:'stale'}); +}); +function wireFixture(){ + const commands=[];let grouped=false,expired=false; + const player={player_id:'dev',name:'Adaptive Music DEV',provider:'sendspin-test',enabled:true,available:true,group_members:[],group_childs:[],static_group_members:[]}; + const client=new MAReadClient({baseUrl:'http://localhost',token:'fixture',target:'dev',approvedProviders:['approved'],expectedName:player.name,expectedProvider:player.provider, + fetchImpl:async(url,options)=>{const body=JSON.parse(options.body);commands.push(body);if(body.command==='players/get')return Response.json({...player,active_group:grouped?'household':null});if(['player_queues/get','player_queues/get_active_queue'].includes(body.command)){expired=true;return Response.json({queue_id:'dev',active:true,available:true,is_dynamic:false,autoplay_enabled:false,dont_stop_the_music_enabled:false,overlay_enabled:false,playback_speed:1});}return new Response(null,{status:200});}}); + return {client,commands,set grouped(v){grouped=v;},get expired(){return expired;}}; +} +test('every wire mutation revalidates exact identity/topology and uses fixed dedicated queue',async()=>{ + const f=wireFixture(),ctx={check(){}};await f.client.mutate('pause',{},ctx);await f.client.mutate('resume',{},ctx); + assert.equal(f.commands.filter(c=>c.command==='players/get').length,2); + assert.ok(f.commands.filter(c=>c.command.startsWith('player_queues/')).every(c=>c.args.queue_id==='dev'||c.command==='player_queues/get_active_queue'&&c.args.player_id==='dev')); + f.grouped=true;await assert.rejects(f.client.mutate('stop',{},ctx),{code:'denied'});assert.equal(f.commands.filter(c=>c.command==='player_queues/stop').length,0); +}); +test('queue injection, transfer, arbitrary media URL and authority loss deny without writes',async()=>{ + const f=wireFixture();for(const [action,args] of [['transfer',{}],['pause',{queue_id:'household'}],['play_media',{media:['approved://track/unregistered'],option:'replace',shuffle:false}],['play_media',{media:['https://example.test/secret'],option:'replace',shuffle:false}]])await assert.rejects(f.client.mutate(action,args,{check(){}}),{code:'denied'}); + await assert.rejects(f.client.mutate('pause',{}, {check(){if(f.expired)throw Object.assign(Error(),{code:'stale'});}}),{code:'stale'}); + assert.ok(!f.commands.some(c=>c.command==='player_queues/pause')); +}); +test('catalog IDs survive independent adapter construction and differ across campaigns',async()=>{ + const make=campaign=>new MAReadClient({baseUrl:'http://localhost',token:'fixture',target:'dev',approvedProviders:['approved'],catalogKey:key,campaign, + fetchImpl:async(url,opts)=>Response.json(JSON.parse(opts.body).command.includes('/radios/')?[]:[{name:'music',media_type:'playlist',is_playable:true,provider_mappings:[{provider_instance:'approved',item_id:'p',available:true}]}])}); + const a=await make('a').catalog(),again=await make('a').catalog(),b=await make('b').catalog();assert.equal(a[0].id,again[0].id);assert.notEqual(a[0].id,b[0].id); +}); +test('same-generation duplicate controls and restores issue no duplicate mutations',async()=>{ + const f=fixture(),snapshot=await f.provider.snapshot(f.ctx); + await Promise.all([f.provider.control('pause',null,f.ctx),f.provider.control('pause',null,f.ctx)]);assert.equal(f.writes.length,1); + const context={...f.ctx,generation:2};await Promise.all([f.provider.restore(snapshot,context),f.provider.restore(snapshot,context)]);assert.equal(f.writes.length,7); +}); +test('MA provider with mock MA client composes with controller for nested contexts and rapid supersession',async()=>{ + const {MusicController}=await import('../../src/core/controller.mjs'); + const f=fixture(); + const controller=new MusicController({campaign:'c',session:'s',providers:{ma:f.provider},authority:()=>true}); + const ref=id=>({provider:'ma',id}); + const base={scene:{id:'scene',playlist:ref('ambient')},combats:[]}; + const combat={id:'combat',sceneId:'scene',active:true,started:true,playlist:ref('combat'),bosses:[]}; + await controller.update(base);await controller.update({...base,combats:[combat]}); + await controller.update({...base,combats:[{...combat,bosses:[{id:'boss',active:true,priority:1,playlist:ref('boss')}]}]}); + await controller.update({...base,combats:[combat],overrides:[{id:'manual',playlist:ref('manual')}]}); + await controller.update({...base,combats:[combat]});await controller.update(base); + const before=f.writes.length;const results=await Promise.allSettled([controller.update({...base,combats:[combat]}),controller.update({...base,overrides:[{id:'rapid',playlist:ref('manual')}]}),controller.update(base)]); + assert.equal(f.writes.length,before);assert.equal(results.at(-1).status,'fulfilled');assert.equal(controller.current.playlist.id,'ambient'); +}); +test('ambiguous wire mutation failure latches closed instead of retrying or restoring blindly',async()=>{ + let effects=0;const client=new MAReadClient({baseUrl:'http://localhost',token:'fixture',target:'dev',approvedProviders:['approved'],expectedName:'Adaptive Music DEV',expectedProvider:'sendspin-test',fetchImpl:async(url,options)=>{ + const {command}=JSON.parse(options.body); + if(command==='players/get')return Response.json({player_id:'dev',name:'Adaptive Music DEV',provider:'sendspin-test',enabled:true,available:true,group_members:[],group_childs:[],static_group_members:[]}); + if(command==='player_queues/get'||command==='player_queues/get_active_queue')return Response.json({queue_id:'dev',active:true,available:true,is_dynamic:false,autoplay_enabled:false,dont_stop_the_music_enabled:false,overlay_enabled:false,playback_speed:1}); + effects++;throw Error('lost response'); + }}); + await assert.rejects(client.mutate('pause',{}, {check(){}}),{code:'uncertain'}); + await assert.rejects(client.mutate('pause',{}, {check(){}}),{code:'uncertain'});assert.equal(effects,1); +}); +test('listener cannot obtain a playback fence guard or renew a controller lease',async()=>{ + const {GatewayControl}=await import('../../gateway/control.mjs'); + const g=new GatewayControl({campaigns:{c:{}},origin:'https://example.test'}); + const request={campaign:'c',session:'s',origin:'https://example.test',token:g.mint({campaign:'c',session:'s',role:'listener'}),fence:1}; + assert.throws(()=>g.fenceGuard(request)(1),{code:'denied'});assert.throws(()=>g.renew(request),{code:'denied'}); +}); +test('playlist preparation expands approved ordered tracks before any playback mutation',async()=>{ + const commands=[];const client=new MAReadClient({baseUrl:'http://localhost',token:'fixture',target:'dev',approvedProviders:['approved'],fetchImpl:async(url,options)=>{ + const {command}=JSON.parse(options.body);commands.push(command); + if(command==='music/playlists/library_items')return Response.json([{name:'Fixture catalog',is_playable:true,is_dynamic:false,media_type:'playlist',provider_mappings:[{provider_instance:'approved',item_id:'p',available:true}]}]); + if(command==='music/radios/library_items')return Response.json([]); + if(command==='music/playlists/get')return Response.json({is_dynamic:false}); + if(command==='music/playlists/playlist_tracks')return Response.json([track('a').media_item,track('a').media_item,track('b').media_item]); + throw Error('unexpected command'); + }}); + const catalog=await client.catalog();assert.deepEqual(await client.prepareMedia(catalog[0]),['approved://track/a','approved://track/a','approved://track/b']);assert.ok(!commands.some(c=>c.startsWith('player_queues/'))); +}); diff --git a/tests/js/module.test.mjs b/tests/js/module.test.mjs new file mode 100644 index 0000000..2fb732e --- /dev/null +++ b/tests/js/module.test.mjs @@ -0,0 +1,13 @@ +import {test} from 'node:test'; +import assert from 'node:assert/strict'; +test('installable development entry defaults automation off and imports no gateway',async()=>{ + const once=new Map(),settings=new Map(),module={};let registrations=0; + globalThis.Hooks={once(e,fn){once.set(e,fn);},on(){registrations++;},off(){}}; + globalThis.game={user:{isGM:true},playlists:[],modules:{get:()=>module},settings:{register(ns,key,definition){settings.set(key,definition);},get(ns,key){return settings.get(key).default;}}}; + globalThis.ui={notifications:{warn(){}}}; + try{ + await import('../../src/foundry/module.mjs');once.get('init')();once.get('ready')(); + assert.equal(settings.get('enabled').default,false);assert.equal(settings.get('ownedPlaylistIds').default,''); + assert.equal(registrations,2);assert.equal(typeof module.api.mountConfiguration,'function');assert.throws(()=>module.api.setOverrides([]));module.api.dispose(); + }finally{delete globalThis.game;delete globalThis.Hooks;delete globalThis.ui;} +}); diff --git a/tests/js/native.test.mjs b/tests/js/native.test.mjs new file mode 100644 index 0000000..60095cd --- /dev/null +++ b/tests/js/native.test.mjs @@ -0,0 +1,64 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { NativeProvider } from '../../src/providers/native/provider.mjs'; +import { primaryGM, startNativeRuntime } from '../../src/foundry/runtime.mjs'; +const collection = items => { const m=new Map(items.map(x=>[x.id,x])); m[Symbol.iterator]=function*(){yield* this.values();}; return m; }; +function fixture() { + const calls=[]; + const p={id:'owned',mode:0,sounds:collection([ + {id:'a',sort:0,playing:true,pausedTime:null,repeat:true,volume:0.4,sound:{currentTime:42,duration:100}}, + {id:'b',sort:1,playing:false,pausedTime:12,repeat:false,volume:0.7,sound:{duration:100}} + ]), async updateEmbeddedDocuments(type,updates){calls.push({type,updates}); for(const u of updates)Object.assign(this.sounds.get(u._id),u);} }; + const other={id:'household',sounds:collection([]),async updateEmbeddedDocuments(){assert.fail('unowned mutation');}}; + const provider=new NativeProvider({playlists:collection([p,other]),ownedPlaylistIds:['owned'],campaign:'c',session:'s'}); + const ctx={campaign:'c',session:'s',generation:4,check(){}}; + return {provider,p,ctx,calls}; +} +test('native captures actual offset and paused state, stops per sound, restores repeat/volume',async()=>{ + const {provider,p,ctx,calls}=fixture(); const snap=await provider.snapshot(ctx); + assert.equal(snap.playlists[0].sounds[0].pausedTime,42); + await provider.stopOwned(ctx); assert.equal(calls[0].type,'PlaylistSound'); assert.equal(calls[0].updates.length,1); + await provider.restore(snap,{...ctx,generation:5}); + assert.equal(p.sounds.get('a').pausedTime,42); assert.equal(p.sounds.get('a').repeat,true); + assert.equal(p.sounds.get('b').playing,false); assert.equal(p.sounds.get('b').pausedTime,12); +}); +test('native resolves sequential playlist and touches only owned documents',async()=>{ + const {provider,ctx,calls}=fixture(); const prepared=await provider.resolve({id:'owned'},ctx); + await provider.apply(prepared,ctx); assert.equal(calls[0].updates[0]._id,'a'); + await assert.rejects(provider.resolve({id:'household'},ctx),{code:'denied'}); + await assert.rejects(provider.resolve({id:'owned'},{...ctx,campaign:'other'}),{code:'denied'}); +}); +test('native rejects unsupported shuffle and empty playlist',async()=>{ + const {provider,p,ctx}=fixture(); p.mode=1; + await assert.rejects(provider.resolve({id:p.id},ctx),{code:'unsupported'}); + p.mode=0;p.sounds.clear();await assert.rejects(provider.resolve({id:p.id},ctx),{code:'unavailable'}); +}); +test('native rejects expired tracks, changed playlist membership and foreign/future snapshots before mutation',async()=>{ + const {provider,p,ctx,calls}=fixture();const snap=await provider.snapshot(ctx); + for(const patch of [{campaign:'other'},{session:'other'},{generation:100}])await assert.rejects(provider.restore({...snap,...patch},ctx),{code:'stale'}); + p.sounds.delete('b'); await assert.rejects(provider.restore(snap,ctx),{code:'expired-media'});assert.equal(calls.length,0); +}); +test('native reports nonseekable restoration and clamps near-end seek',async()=>{ + const {provider,p,ctx,calls}=fixture();const snap=await provider.snapshot(ctx); + p.sounds.get('a').sound.duration=Infinity; + await assert.rejects(provider.restore(snap,ctx),{code:'unsupported'});assert.equal(calls.length,0); + p.sounds.get('a').sound.duration=40;await provider.restore(snap,ctx);assert.equal(p.sounds.get('a').pausedTime,39.99); +}); +test('scene-linked playlist conflict and lost authority fail before mutation',async()=>{ + const {provider,ctx,calls}=fixture();provider.sceneConflict=()=>true; + await assert.rejects(provider.resolve({id:'owned'},ctx),{code:'scene-conflict'}); + provider.sceneConflict=()=>false; + await assert.rejects(provider.stopOwned({...ctx,check(){throw new Error('lost');}}));assert.equal(calls.length,0); +}); +test('GM election deterministic and no GM means none',()=>{ + assert.equal(primaryGM([{id:'z',active:true,isGM:true},{id:'a',active:true,isGM:true},{id:'0',active:false,isGM:true}]),'a'); + assert.equal(primaryGM([]),undefined); +}); +test('Foundry bootstrap registers local settings/hooks and disposes without ambient or actor access',async()=>{ + const callbacks=new Map();let index=0,registered=0; + const Hooks={on(e,cb){callbacks.set(++index,cb);return index;},off(e,id){callbacks.delete(id);}}; + const game={ready:true,user:{id:'gm'},users:[{id:'gm',isGM:true,active:true}],playlists:collection([]),scenes:[],combats:[], + settings:{register(){registered++;},get(){return null;}}}; + const runtime=startNativeRuntime({game,Hooks,campaign:'c',session:'s',ownedPlaylistIds:[]}); + await runtime.refresh();assert.equal(registered,1);assert.ok(callbacks.size>0);runtime.dispose();assert.equal(callbacks.size,0); +}); diff --git a/tests/js/pcm-fixture.test.mjs b/tests/js/pcm-fixture.test.mjs new file mode 100644 index 0000000..7f94c6b --- /dev/null +++ b/tests/js/pcm-fixture.test.mjs @@ -0,0 +1,17 @@ +import {test} from 'node:test'; +import assert from 'node:assert/strict'; +import {pcmFixtureFrames} from '../../gateway/pcm-fixture.mjs'; +import {SyntheticAudioGateway} from '../../gateway/synthetic-audio.mjs'; +import {GatewayControl} from '../../gateway/control.mjs'; +function wav(){const data=Buffer.alloc(44+1920*2);data.write('RIFF');data.writeUInt32LE(data.length-8,4);data.write('WAVEfmt ',8);data.writeUInt32LE(16,16);data.writeUInt16LE(1,20);data.writeUInt16LE(2,22);data.writeUInt32LE(24000,24);data.writeUInt32LE(96000,28);data.writeUInt16LE(4,32);data.writeUInt16LE(16,34);data.write('data',36);data.writeUInt32LE(3840,40);data.fill(23,44);return data;} +test('synthetic WAV termination emits fixed PCM frames through campaign listener authorization',()=>{ + const control=new GatewayControl({campaigns:{a:{}},origin:'https://example.test'}); + const audio=new SyntheticAudioGateway({control});audio.provision({campaign:'a',session:'s'}); + const listener=audio.connect({campaign:'a',session:'s',origin:'https://example.test',token:control.mint({campaign:'a',session:'s',role:'listener'})}); + let generation=0;for(const pcm of pcmFixtureFrames(wav())){audio.publish({campaign:'a',session:'s',generation:++generation,pcm});assert.equal(listener.next().pcm[0],23);}assert.equal(generation,2);listener.close(); +}); +test('malformed, truncated and incompatible WAV formats fail closed before PCM publication',()=>{ + const original=wav();const badRate=wav();badRate.writeUInt32LE(48000,24); + const badCodec=wav();badCodec.writeUInt16LE(3,20); + for(const input of [original.subarray(0,20),badRate,badCodec,Buffer.alloc(9000001)])assert.throws(()=>[...pcmFixtureFrames(input)],{code:'unsupported'}); +}); diff --git a/tests/js/private-config.test.mjs b/tests/js/private-config.test.mjs new file mode 100644 index 0000000..2df3265 --- /dev/null +++ b/tests/js/private-config.test.mjs @@ -0,0 +1,24 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtemp, writeFile, chmod, rm, symlink } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { loadMAToken } from '../../gateway/private-config.mjs'; +test('credential loader rejects permissive modes, symlinks and malformed secrets',async()=>{ + const dir=await mkdtemp(join(tmpdir(),'adaptive-music-')); + try { + await chmod(dir,0o700);const path=join(dir,'ma-token');await writeFile(path,'fixture-only\n',{mode:0o600}); + assert.equal(await loadMAToken(dir),'fixture-only'); + await chmod(path,0o644);await assert.rejects(loadMAToken(dir),{code:'denied'});await chmod(path,0o600); + await chmod(dir,0o755);await assert.rejects(loadMAToken(dir),{code:'denied'});await chmod(dir,0o700); + await writeFile(path,'line1\nline2');await assert.rejects(loadMAToken(dir),{code:'denied'}); + await rm(path);await symlink('missing',path);await assert.rejects(loadMAToken(dir),{code:'denied'}); + } finally {await rm(dir,{recursive:true,force:true});} +}); +test('private catalog identity key persists and unsafe key permissions fail',async()=>{ + const {loadCatalogKey}=await import('../../gateway/private-config.mjs');const dir=await mkdtemp(join(tmpdir(),'adaptive-music-key-')); + try{await chmod(dir,0o700);await writeFile(join(dir,'ma-token'),'fixture',{mode:0o600}); + const first=await loadCatalogKey(dir),second=await loadCatalogKey(dir);assert.equal(first.length,32);assert.deepEqual(first,second); + await chmod(join(dir,'catalog-key'),0o644);await assert.rejects(loadCatalogKey(dir),{code:'denied'}); + }finally{await rm(dir,{recursive:true,force:true});} +}); diff --git a/tests/js/scene-music.test.mjs b/tests/js/scene-music.test.mjs new file mode 100644 index 0000000..fa63e25 --- /dev/null +++ b/tests/js/scene-music.test.mjs @@ -0,0 +1,27 @@ +import {test} from 'node:test'; +import assert from 'node:assert/strict'; +import {buildMusicState,referenceKey} from '../../src/core/scene-music.mjs'; +import {candidates} from '../../src/core/controller.mjs'; +import {saveMusicAssignments} from '../../src/foundry/music-editor.mjs'; +const native=id=>({provider:'native',id}),ma=id=>({provider:'ma',id}); +const choices=[{...native('fallback'),name:'Owned'},{...ma('ambient'),name:'Ambient'},{...ma('combat'),name:'Combat'},{...ma('boss'),name:'Boss'}]; +test('scene assignments persist independently and world defaults/boss priority resolve without actor schemas',async()=>{ + let flag={custom:'keep'},world={};const game={user:{isGM:true},settings:{get:()=>world,set:async(ns,k,v)=>{world=v;}}}; + const document={getFlag:()=>flag,setFlag:async(ns,k,v)=>{flag=v;}}; + await saveMusicAssignments({document,game,choices,values:{ambient:referenceKey(ma('ambient')),combat:referenceKey(ma('combat')),boss:referenceKey(ma('boss')),fallback:referenceKey(native('fallback'))}}); + assert.deepEqual(flag,{custom:'keep',ambient:ma('ambient'),combat:ma('combat'),boss:ma('boss'),fallback:native('fallback')}); + await saveMusicAssignments({game,choices,defaults:true,values:{combat:referenceKey(ma('combat'))}});assert.deepEqual(world.combat,ma('combat')); + const state=buildMusicState({scene:{id:'s',music:flag},combats:[{id:'c',sceneId:'s',active:true,started:true,bosses:[{id:'b',active:true,priority:10}]}]}); + assert.equal(candidates(state)[0].playlist.id,'boss');assert.equal(candidates({...state,combats:state.combats.map(c=>({...c,bosses:[]}))})[0].playlist.id,'combat');assert.equal(candidates({...state,combats:[]})[0].playlist.id,'ambient'); +}); +test('native fallback is explicit, manual silence wins and legacy ambient does not resurrect after clearing',()=>{ + const state=buildMusicState({scene:{id:'s',music:{ambient:ma('offline'),combat:ma('blocked'),fallback:native('fallback')}},combats:[{id:'c',sceneId:'s',active:true,started:true}],choose:(ref,fallback)=>ref.provider==='ma'?fallback:ref,overrides:[{id:'silence',playlist:null}]}); + assert.equal(candidates(state)[0].playlist,null);assert.equal(state.scene.playlist.id,'fallback');assert.equal(state.combats[0].playlist.id,'fallback'); + assert.equal(buildMusicState({scene:{id:'s',music:{ambient:null,playlist:native('old')}}}).scene.playlist,null); +}); +test('unavailable saved MA selections are preserved but new forged IDs/non-native fallback and role loss deny',async()=>{ + let flag={ambient:ma('old')};const document={getFlag:()=>flag,setFlag:async(ns,k,v)=>{flag=v;}};const game={user:{isGM:true}}; + await saveMusicAssignments({document,game,choices:[],values:{ambient:referenceKey(ma('old'))}});assert.equal(flag.ambient.id,'old'); + for(const values of [{ambient:referenceKey(ma('forged'))},{fallback:referenceKey(ma('ambient'))}])await assert.rejects(saveMusicAssignments({document,game,choices,values}),{code:'denied'}); + game.user.isGM=false;await assert.rejects(saveMusicAssignments({document,game,choices,values:{ambient:''}}),{code:'denied'}); +}); diff --git a/tests/js/setup-audio.test.mjs b/tests/js/setup-audio.test.mjs new file mode 100644 index 0000000..3c91e11 --- /dev/null +++ b/tests/js/setup-audio.test.mjs @@ -0,0 +1,37 @@ +import {test} from 'node:test'; +import assert from 'node:assert/strict'; +import {createSetupClass} from '../../src/foundry/setup.mjs'; +import {ListenerAudio} from '../../src/foundry/listener-audio.mjs'; +class Element{ + constructor(tag,dom){this.tag=tag;this.ownerDocument=dom;this.children=[];this.listeners={};this.dataset={};this.value='';} + append(...children){this.children.push(...children);if(this.tag==='select'&&!this.value&&children[0]?.tag==='option')this.value=children[0].value;} + replaceChildren(...children){this.children=[];this.append(...children);} + setAttribute(){} + addEventListener(name,fn){this.listeners[name]=fn;} +} +const descendants=node=>[node,...node.children.flatMap(descendants)]; +const collection=items=>{const map=new Map(items.map(i=>[i.id,i]));map[Symbol.iterator]=function*(){yield*map.values();};return map;}; +test('GM setup connects catalog into independent scene editors and never persists its connection code',async()=>{ + const dom={createElement:tag=>new Element(tag,dom)};globalThis.document=dom; + let flag={},catalog=[];const settings={ownedPlaylistIds:'owned',musicDefaults:{},enabled:false},writes=[]; + const scene={id:'scene',name:'Scene',active:true,getFlag:()=>flag,setFlag:async(ns,k,value)=>{flag=value;}}; + const game={user:{isGM:true},playlists:collection([{id:'owned',name:'Owned'}]),scenes:collection([scene]),combats:[],settings:{get:(ns,k)=>settings[k],set:async(ns,k,value)=>{settings[k]=value;writes.push({k,value});}}}; + const gateway={status:null,async connect(code){assert.equal(code,'capability-fixture');catalog=[{provider:'ma',id:'opaque-ma',name:'MA fixture',kind:'playlist'}];this.status={target:'verified',playbackEnabled:false,audioSource:'none'};},refresh:async()=>{},disconnect:async()=>{}}; + try{ + const Setup=createSetupClass({game,gateway,audio:{},getChoices:async()=>[{provider:'native',id:'owned',name:'Owned'},...catalog],start(){},stop(){},setOverrides(){},onError:assert.fail,Base:class{}}); + const root=await new Setup()._renderHTML();const code=descendants(root).find(e=>e.tag==='input'&&e.type==='password');code.value='capability-fixture'; + await descendants(root).find(e=>e.tag==='button'&&e.textContent==='Connect and load MA catalog').listeners.click();assert.equal(code.value,''); + const panel=descendants(root).find(e=>e.tag==='fieldset'&&e.children.some(c=>c.tag==='legend'&&c.textContent==='Scene music')); + const selects=descendants(panel).filter(e=>e.tag==='select');assert.equal(selects.length,4);assert.ok(selects[0].children.some(o=>o.textContent.includes('MA fixture'))); + selects[0].value='["ma","opaque-ma"]';selects[1].value='["native","owned"]';selects[3].value='["native","owned"]'; + await descendants(panel).find(e=>e.tag==='button').listeners.click();assert.deepEqual(flag.ambient,{provider:'ma',id:'opaque-ma'});assert.deepEqual(flag.combat,{provider:'native',id:'owned'});assert.ok(!JSON.stringify({flag,writes}).includes('capability-fixture')); + }finally{delete globalThis.document;} +}); +test('browser PCM sink resumes from gesture, decodes stereo frames and closes its context on stream end',async()=>{ + const calls=[],buffers=[];const context={currentTime:0,destination:{},resume(){calls.push('resume');return Promise.resolve();},close(){calls.push('close');return Promise.resolve();}, + createBuffer(channels,length,rate){assert.equal(rate,24000);const channelsData=[new Float32Array(length),new Float32Array(length)];buffers.push(channelsData);return {getChannelData:i=>channelsData[i]};}, + createBufferSource(){return {connect(){},start(){calls.push('start');},stop(){calls.push('stop');}};}}; + const pcm=new Uint8Array(1920),view=new DataView(pcm.buffer);for(let i=0;i<960;i++)view.setInt16(i*2,16384,true); + const audio=new ListenerAudio({createContext:()=>context,fetchImpl:async()=>{calls.push('fetch');return new Response(pcm,{headers:{'X-Audio-Format':'pcm16le;rate=24000;channels=2'}});}}); + const pending=audio.start({url:'/audio',options:{}});assert.equal(calls[0],'resume');await pending;assert.equal(buffers[0][0][0],0.5);assert.equal(buffers[0][1][0],0.5);assert.ok(calls.includes('close'));assert.ok(calls.indexOf('resume')()=>(e&&(A=e(e=0)),A);var dr=(e,A)=>{for(var t in A)lr(e,t,{get:A[t],enumerable:!0})};var fe={};dr(fe,{default:()=>fr});var fr,pe=ur(()=>{throw new Error("Optional Opus fallback is not distributed; negotiate PCM");fr=void 0});var GA=class{constructor(A,t){this.webCodecsDecoder=null,this.webCodecsDecoderReady=null,this.webCodecsFormat=null,this.useNativeOpus=!0,this.nativeDecoderQueue=[],this.opusDecoder=null,this.opusDecoderModule=null,this.opusDecoderReady=null,this.flacDecodingContext=null,this.flacDecodingContextSampleRate=0,this.flacDecodingContextChannels=0,this.onDecodedChunk=A,this.currentGeneration=t}async handleBinaryMessage(A,t,n){if(new Uint8Array(A)[0]===4){let r=new DataView(A,1,8),i=Number(r.getBigInt64(0,!1)),a=A.slice(9);if(t.codec==="opus"&&this.useNativeOpus&&(await this.initWebCodecsDecoder(t),this.useNativeOpus&&this.webCodecsDecoder&&this.queueToNativeOpusDecoder(a,i,n)))return;try{let o=await this.decode(a,t);o&&n===this.currentGeneration()&&this.onDecodedChunk({samples:o.samples,sampleRate:o.sampleRate,serverTimeUs:i,generation:n})}catch(o){console.error("Sendspin: Failed to decode audio buffer:",o)}}}async decode(A,t){return t.codec==="opus"?this.decodeOpusWithEncdec(A,t):t.codec==="flac"?this.decodeFLAC(A,t):t.codec==="pcm"?this.decodePCM(A,t):null}decodePCM(A,t){let n=t.bit_depth??16;if(n!==16&&n!==24&&n!==32)return console.warn(`Sendspin: unsupported PCM bit_depth ${n}`),null;let s=n/8,r=new DataView(A),i=A.byteLength/(s*t.channels),a=[];for(let o=0;oh.charCodeAt(0)),o=new Uint8Array(a.length+A.byteLength);o.set(a,0),o.set(new Uint8Array(A),a.length),n=o.buffer}let r=await this.getFlacDecodingContext(t.sample_rate,t.channels).decodeAudioData(n),i=[];for(let a=0;a{if(!this.webCodecsDecoder)return!1;let n=!!this.webCodecsFormat&&this.webCodecsFormat.sample_rate===A.sample_rate&&this.webCodecsFormat.channels===A.channels;if(this.webCodecsDecoder.state==="configured"&&n)return!0;if(this.webCodecsDecoder.state==="closed")return!1;try{return this.webCodecsDecoder.configure({codec:"opus",sampleRate:A.sample_rate,numberOfChannels:A.channels}),this.webCodecsFormat=A,!0}catch{return!1}};if(!t()){if(this.webCodecsDecoderReady){if(await this.webCodecsDecoderReady,t())return;try{this.webCodecsDecoder?.close()}catch{}this.webCodecsDecoder=null,this.webCodecsDecoderReady=null,this.webCodecsFormat=null}if(this.webCodecsDecoderReady){await this.webCodecsDecoderReady;return}this.webCodecsDecoderReady=this.createWebCodecsDecoder(A),await this.webCodecsDecoderReady}}async createWebCodecsDecoder(A){if(typeof AudioDecoder>"u"){this.useNativeOpus=!1;return}try{if(!(await AudioDecoder.isConfigSupported({codec:"opus",sampleRate:A.sample_rate,numberOfChannels:A.channels})).supported){console.log("[NativeOpus] WebCodecs Opus not supported, will use fallback"),this.useNativeOpus=!1;return}this.webCodecsDecoder=new AudioDecoder({output:n=>this.handleAudioData(n),error:n=>{console.error("[NativeOpus] WebCodecs decoder error:",n)}}),this.webCodecsDecoder.configure({codec:"opus",sampleRate:A.sample_rate,numberOfChannels:A.channels}),this.webCodecsFormat=A,console.log(`[NativeOpus] Using WebCodecs AudioDecoder: ${A.sample_rate}Hz, ${A.channels}ch`)}catch(t){console.warn("[NativeOpus] WebCodecs init failed, will use fallback:",t),this.useNativeOpus=!1}}handleAudioData(A){try{let t=Number(A.timestamp),n=this.nativeDecoderQueue.shift();if(!n){console.warn(`[NativeOpus] Dropping frame with empty decode queue (out ts=${t})`),A.close();return}let{serverTimeUs:s,generation:r}=n,i=this.webCodecsFormat;if(!i){A.close();return}if(r!==this.currentGeneration()){console.warn(`[NativeOpus] Dropping old-stream frame (ts=${s}, gen=${r} != current=${this.currentGeneration()})`),A.close();return}let a=A.numberOfChannels,o=A.numberOfFrames,h=A.format,l=[];for(let u=0;u0&&this.nativeDecoderQueue.pop(),console.error("[NativeOpus] WebCodecs queue error:",s),!1}}resolveOpusDecoderModule(A){let t=A?.default,n=A?.["module.exports"],s=t??n??A;if(!s||typeof s!="object")throw new Error("[Opus] Invalid libopus decoder module export");return s}resolveOggOpusDecoderClass(A){let t=A?.default,n=A?.["module.exports"],s=t??n??A,r=s?.OggOpusDecoder??s;if(typeof r!="function")throw new Error("[Opus] OggOpusDecoder class export not found");return r}async waitForOpusReady(A){if(!A.isReady){if(Object.isExtensible(A)){await new Promise(t=>{A.onready=()=>t()});return}for(;!A.isReady;)await new Promise(t=>setTimeout(t,20))}}async initOpusEncdecDecoder(A){if(this.opusDecoderReady){await this.opusDecoderReady;return}this.opusDecoderReady=(async()=>{console.log("[Opus] Initializing decoder (opus-encdec)...");let[t,n]=await Promise.all([Promise.resolve().then(()=>(pe(),fe)),Promise.resolve().then(()=>(pe(),fe))]);this.opusDecoderModule=this.resolveOpusDecoderModule(t);let s=this.resolveOggOpusDecoderClass(n);await this.waitForOpusReady(this.opusDecoderModule),this.opusDecoder=new s({rawOpus:!0,decoderSampleRate:A.sample_rate,outputBufferSampleRate:A.sample_rate,numberOfChannels:A.channels},this.opusDecoderModule),await this.waitForOpusReady(this.opusDecoder),console.log("[Opus] Decoder ready")})(),await this.opusDecoderReady}async decodeOpusWithEncdec(A,t){try{await this.initOpusEncdecDecoder(t);let n=new Uint8Array(A),s=[];if(this.opusDecoder.decodeRaw(n,o=>{s.push(new Float32Array(o))}),s.length===0)return console.warn("[Opus] Fallback decoder produced no samples"),null;let r=s[0],i=r.length/t.channels,a=[];for(let o=0;o{this.startTimeSyncBurstIfIdle(),this.scheduleNextTimeSyncBurstTick()},1e4);this.stateManager.setTimeSyncInterval(A)}startTimeSyncBurstIfIdle(){this.timeSyncBurstActive||(this.timeSyncBurstActive=!0,this.timeSyncBurstSentCount=0,this.timeSyncBurstSamples=[],this.timeSyncInFlightClientTransmitted=null,this.sendNextTimeSyncBurstProbe())}sendNextTimeSyncBurstProbe(){if(!this.timeSyncBurstActive||this.timeSyncInFlightClientTransmitted!==null)return;if(this.timeSyncBurstSentCount>=8){this.finalizeTimeSyncBurst();return}let A=this.sendTimeSync();this.timeSyncBurstSentCount+=1,this.timeSyncInFlightClientTransmitted=A,this.armTimeSyncProbeTimeout(A)}armTimeSyncProbeTimeout(A){this.clearTimeSyncProbeTimeout(),this.timeSyncInFlightTimeout=globalThis.setTimeout(()=>{this.handleTimeSyncProbeTimeout(A)},2e3)}clearTimeSyncProbeTimeout(){this.timeSyncInFlightTimeout!==null&&(clearTimeout(this.timeSyncInFlightTimeout),this.timeSyncInFlightTimeout=null)}handleTimeSyncProbeTimeout(A){!this.timeSyncBurstActive||this.timeSyncInFlightClientTransmitted!==A||(console.warn("Sendspin: Time sync probe timed out, aborting current burst"),this.abortTimeSyncBurst())}finalizeTimeSyncBurst(){this.clearTimeSyncProbeTimeout();let A=this.selectTimeSyncBurstCandidate();A&&this.timeFilter.update(A.measurement,A.maxError,A.t4),this.timeSyncBurstActive=!1,this.timeSyncBurstSentCount=0,this.timeSyncInFlightClientTransmitted=null,this.timeSyncBurstSamples=[]}selectTimeSyncBurstCandidate(){if(this.timeSyncBurstSamples.length===0)return null;let t=[...[...this.timeSyncBurstSamples].sort((n,s)=>n.rttTerm-s.rttTerm).slice(0,Math.min(3,this.timeSyncBurstSamples.length))].sort((n,s)=>n.measurement-s.measurement);return t[Math.floor(t.length/2)]}abortTimeSyncBurst(){this.clearTimeSyncProbeTimeout(),this.timeSyncBurstActive=!1,this.timeSyncBurstSentCount=0,this.timeSyncInFlightClientTransmitted=null,this.timeSyncBurstSamples=[]}stop(){this.stateManager.clearTimeSyncInterval(),this.abortTimeSyncBurst()}handleServerTime(A){if(!this.timeSyncBurstActive||this.timeSyncInFlightClientTransmitted===null)return;let t=A.payload.client_transmitted;if(t!==this.timeSyncInFlightClientTransmitted){console.warn("Sendspin: Ignoring out-of-order time response",t,this.timeSyncInFlightClientTransmitted);return}let n=Math.floor(performance.now()*1e3),s=A.payload.server_received,r=A.payload.server_transmitted,i=(s-t+(r-n))/2,a=Math.max(0,n-t-(r-s)),o=Math.max(1e3,a/2);if(this.timeSyncBurstSamples.push({measurement:i,maxError:o,t4:n,rttTerm:a}),this.clearTimeSyncProbeTimeout(),this.timeSyncInFlightClientTransmitted=null,this.timeSyncBurstSentCount>=8){this.finalizeTimeSyncBurst();return}this.sendNextTimeSyncBurstProbe()}sendTimeSync(A=Math.floor(performance.now()*1e3)){let t={type:"client/time",payload:{client_transmitted:A}};return this.sender.sendControl(t),A}};function pr(){let e=typeof navigator<"u"?navigator.userAgent:"",A=/^((?!chrome|android).)*safari/i.test(e),t=/firefox/i.test(e),n=typeof AudioDecoder<"u";return n||(typeof window<"u"&&!window.isSecureContext?console.warn("[Opus] Running in insecure context, falling back to FLAC/PCM"):console.warn("[Opus] Native decoder not available, falling back to FLAC/PCM")),A?new Set(["pcm","opus"]):t?new Set(["pcm","flac"]):n?new Set(["pcm","opus","flac"]):new Set(["pcm","flac"])}function It(e){let A=pr(),t=[];for(let n of e)A.has(n)&&(n==="opus"?t.push({codec:"opus",sample_rate:48e3,channels:2,bit_depth:16}):(t.push({codec:n,sample_rate:48e3,channels:2,bit_depth:16}),t.push({codec:n,sample_rate:44100,channels:2,bit_depth:16})));if(t.length===0)throw new Error(`No supported codecs: requested [${e.join(", ")}], browser supports [${[...A].join(", ")}]`);return t}function mr(e){let A=e.sample_rate*e.channels*Math.ceil(e.bit_depth/8);switch(e.codec){case"opus":return 64e3;case"flac":return A*1.02;default:return A}}function gn(e){let A=Math.max(...e.map(mr));return Math.ceil(A*30)}function gA(e){return isFinite(e)?Math.max(0,Math.min(5e3,Math.round(e))):0}var yn=5e3,gr=250,yr=250;function Jt(e,A){if(!isFinite(e)||e<0)throw new RangeError(`${A} must be a non-negative finite number`)}var Bt=class{constructor(A,t,n,s,r,i={}){this.sender=A,this.helloContext=t,this.streamHandler=n,this.stateManager=s,this.timeFilter=r,this.activated=!1,this.activeRoles=null,this.pairingSuspended=!1,this.lastSentPlayer=null,this.clientName=i.clientName??"Sendspin Player",this.productName=i.productName,this.codecs=i.codecs??["opus","flac","pcm"],this.bufferCapacity=i.bufferCapacity,this.requiredLeadTimeMs=i.requiredLeadTimeMs??gr,Jt(this.requiredLeadTimeMs,"requiredLeadTimeMs"),this.minBufferMs=i.minBufferMs??yr,Jt(this.minBufferMs,"minBufferMs"),this.useHardwareVolume=i.useHardwareVolume??!1,this.onVolumeCommand=i.onVolumeCommand,this.onDelayCommand=i.onDelayCommand,this.getExternalVolume=i.getExternalVolume,this.timeSyncManager=new vt(A,s,r)}handleServerMessage(A){switch(A.type){case"server/hello":this.handleServerHello();break;case"server/activate":this.handleServerActivate(A);break;case"server/time":this.timeSyncManager.handleServerTime(A);break;case"stream/start":this.handleStreamStart(A);break;case"stream/clear":this.handleStreamClear(A);break;case"stream/end":this.handleStreamEnd(A);break;case"server/command":this.handleServerCommand(A);break;case"server/state":this.stateManager.updateServerState(A.payload);break;case"group/update":this.stateManager.updateGroupState(A.payload);break}}handleServerHello(){console.log("Sendspin: Connected to server"),this.sendClientHello()}handleServerActivate(A){this.pairingSuspended=!1;let t=!1;if(A.payload.active_roles!==void 0){let s=new Set(A.payload.active_roles);t=this.activeRoles===null||s.size!==this.activeRoles.size||[...s].some(r=>!this.activeRoles.has(r)),this.activeRoles=s}if(this.activated){t&&this.sendStateUpdate();return}this.activated=!0,this.sendStateUpdate(),this.timeSyncManager.startAndSchedule();let n=globalThis.setInterval(()=>this.sendStateUpdate(),yn);this.stateManager.setStateUpdateInterval(n)}restartStateUpdateInterval(){let A=globalThis.setInterval(()=>this.sendStateUpdate(),yn);this.stateManager.setStateUpdateInterval(A)}stopTimeSync(){this.timeSyncManager.stop()}suspendForPairing(){this.pairingSuspended=!0,this.activated=!1,this.activeRoles=new Set,this.timeSyncManager.stop(),this.stateManager.clearStateUpdateInterval()}resetActivation(A=!1){this.pairingSuspended=!1,this.activated=!1,A||(this.activeRoles=null),this.timeSyncManager.stop(),this.stateManager.clearStateUpdateInterval()}handleStreamStart(A){let t=this.stateManager.currentStreamFormat!==null;this.stateManager.currentStreamFormat=A.payload.player,console.log(t?"Sendspin: Stream format updated":"Sendspin: Stream started",this.stateManager.currentStreamFormat),console.log(`Sendspin: Codec=${this.stateManager.currentStreamFormat.codec.toUpperCase()}, SampleRate=${this.stateManager.currentStreamFormat.sample_rate}Hz, Channels=${this.stateManager.currentStreamFormat.channels}, BitDepth=${this.stateManager.currentStreamFormat.bit_depth}bit`),this.streamHandler.handleStreamStart(this.stateManager.currentStreamFormat,t),this.stateManager.isPlaying=!0,typeof navigator<"u"&&navigator.mediaSession&&(navigator.mediaSession.playbackState="playing")}handleStreamClear(A){let t=A.payload.roles;(!t||t.includes("player"))&&(console.log("Sendspin: Stream clear (seek)"),this.streamHandler.handleStreamClear())}handleStreamEnd(A){let t=A.payload?.roles;(!t||t.includes("player"))&&(console.log("Sendspin: Stream ended"),this.streamHandler.handleStreamEnd(),this.stateManager.currentStreamFormat=null,this.stateManager.isPlaying=!1,typeof navigator<"u"&&navigator.mediaSession&&(navigator.mediaSession.playbackState="paused"),this.sendStateUpdate())}handleServerCommand(A){let t=A.payload.player;if(t){switch(t.command){case"volume":t.volume!==void 0&&(this.stateManager.volume=t.volume,this.streamHandler.handleVolumeUpdate(),this.useHardwareVolume&&this.onVolumeCommand&&this.onVolumeCommand(t.volume,this.stateManager.muted));break;case"mute":t.mute!==void 0&&(this.stateManager.muted=t.mute,this.streamHandler.handleVolumeUpdate(),this.useHardwareVolume&&this.onVolumeCommand&&this.onVolumeCommand(this.stateManager.volume,t.mute));break;case"set_static_delay":{let n=t.static_delay_ms;if(typeof n=="number"&&isFinite(n)){let s=gA(n);this.streamHandler.handleSyncDelayChange(s),this.onDelayCommand?.(s)}break}}this.restartStateUpdateInterval(),this.sendStateUpdate(!0)}}sendClientHello(){let A=It(this.codecs),t={type:"client/hello",payload:{name:this.clientName,supported_roles:["player@v1","controller@v1","metadata@v1"],trust_level:this.helloContext.trustLevel(),supported_pair_methods:this.helloContext.pairMethods(),unpaired_access:{enabled:this.helloContext.unpairedAccess},device_info:{product_name:this.productName,manufacturer:typeof navigator<"u"&&navigator.vendor||"Unknown",software_version:typeof navigator<"u"&&navigator.userAgent||"Unknown"},"player@v1_support":{supported_formats:A,buffer_capacity:this.bufferCapacity??gn(A),supported_commands:["volume","mute"]}}};this.lastSentPlayer=null,this.sender.sendControl(t)}setRequiredLeadTimeMs(A){Jt(A,"requiredLeadTimeMs"),this.requiredLeadTimeMs=A,this.sendStateUpdate()}setMinBufferMs(A){Jt(A,"minBufferMs"),this.minBufferMs=A,this.sendStateUpdate()}sendStateUpdate(A=!1){if(this.pairingSuspended)return;let t=this.stateManager.volume,n=this.stateManager.muted;if(!A&&this.useHardwareVolume&&this.getExternalVolume){let o=this.getExternalVolume();t=o.volume,n=o.muted}let s=this.streamHandler.getSyncDelayMs(),r=gA(s),i={available:!0};if(this.activeRoles===null||this.activeRoles.has("player@v1")){let o={volume:t,muted:n,static_delay_ms:r,required_lead_time_ms:this.requiredLeadTimeMs,min_buffer_ms:this.minBufferMs},h=this.lastSentPlayer;if(h===null)i.player={...o,supported_commands:["set_static_delay"]};else{let l={};o.static_delay_ms!==h.static_delay_ms&&(l.static_delay_ms=o.static_delay_ms),o.volume!==h.volume&&(l.volume=o.volume),o.muted!==h.muted&&(l.muted=o.muted),o.required_lead_time_ms!==h.required_lead_time_ms&&(l.required_lead_time_ms=o.required_lead_time_ms),o.min_buffer_ms!==h.min_buffer_ms&&(l.min_buffer_ms=o.min_buffer_ms),i.player=l}this.lastSentPlayer=o}let a={type:"client/state",payload:i};this.sender.sendControl(a)}sendGoodbye(A){this.sender.sendControl({type:"client/goodbye",payload:{reason:A}})}sendCommand(A,t){this.pairingSuspended||!this.activeRoles?.has("controller@v1")||this.sender.sendControl({type:"client/command",payload:{controller:{command:A,...t}}})}};function me(e,A){let t={...e};for(let n of Object.keys(A)){let s=A[n];if(s===null)delete t[n];else if(s!==void 0){let r=t[n];typeof s=="object"&&!Array.isArray(s)&&typeof r=="object"&&r!==null&&!Array.isArray(r)?t[n]=me(r,s):t[n]=s}}return t}var Pt=class{constructor(A){this._volume=100,this._muted=!1,this._playerState="synchronized",this._isPlaying=!1,this._currentStreamFormat=null,this._streamStartServerTime=0,this._streamStartAudioTime=0,this._streamGeneration=0,this._serverState={},this._groupState={},this.timeSyncInterval=null,this.stateUpdateInterval=null,this.onStateChangeCallback=A}get volume(){return this._volume}set volume(A){this._volume=Math.max(0,Math.min(100,A)),this.notifyStateChange()}get muted(){return this._muted}set muted(A){this._muted=A,this.notifyStateChange()}get playerState(){return this._playerState}set playerState(A){this._playerState=A,this.notifyStateChange()}get isPlaying(){return this._isPlaying}set isPlaying(A){this._isPlaying=A,this.notifyStateChange()}get currentStreamFormat(){return this._currentStreamFormat}set currentStreamFormat(A){this._currentStreamFormat=A}get streamStartServerTime(){return this._streamStartServerTime}set streamStartServerTime(A){this._streamStartServerTime=A}get streamStartAudioTime(){return this._streamStartAudioTime}set streamStartAudioTime(A){this._streamStartAudioTime=A}resetStreamAnchors(){this._streamStartServerTime=0,this._streamStartAudioTime=0,this._streamGeneration++}get streamGeneration(){return this._streamGeneration}setTimeSyncInterval(A){this.clearTimeSyncInterval(),this.timeSyncInterval=A}clearTimeSyncInterval(){this.timeSyncInterval!==null&&(clearTimeout(this.timeSyncInterval),this.timeSyncInterval=null)}setStateUpdateInterval(A){this.clearStateUpdateInterval(),this.stateUpdateInterval=A}clearStateUpdateInterval(){this.stateUpdateInterval!==null&&(clearInterval(this.stateUpdateInterval),this.stateUpdateInterval=null)}clearAllIntervals(){this.clearTimeSyncInterval(),this.clearStateUpdateInterval()}reset(){this._volume=100,this._muted=!1,this._playerState="synchronized",this._isPlaying=!1,this._currentStreamFormat=null,this._streamStartServerTime=0,this._streamStartAudioTime=0,this._serverState={},this._groupState={},this.clearAllIntervals()}notifyStateChange(){this.onStateChangeCallback&&this.onStateChangeCallback({isPlaying:this._isPlaying,volume:this._volume,muted:this._muted,playerState:this._playerState,serverState:this._serverState,groupState:this._groupState})}updateServerState(A){this._serverState=me(this._serverState,A),this.notifyStateChange()}updateGroupState(A){this._groupState=me(this._groupState,A),this.notifyStateChange()}get serverState(){return this._serverState}get groupState(){return this._groupState}};var Rt=class{constructor(A){this.ws=null,this.reconnectTimeout=null,this.shouldReconnect=!1,this.isReconnecting=!1,this.reconnectAttempt=0,this.baseDelayMs=Math.max(0,A?.baseDelayMs??1e3),this.maxDelayMs=Math.max(this.baseDelayMs,A?.maxDelayMs??15e3),this.maxAttempts=A?.maxAttempts===void 0?1/0:Math.max(0,A.maxAttempts),this.onReconnecting=A?.onReconnecting,this.onReconnected=A?.onReconnected,this.onExhausted=A?.onExhausted}adopt(A,t,n,s,r){if(A.readyState!==WebSocket.OPEN&&A.readyState!==WebSocket.CONNECTING)throw new Error(`Sendspin: Cannot adopt WebSocket in readyState ${A.readyState} (must be OPEN or CONNECTING)`);if(this.onOpenHandler=t,this.onMessageHandler=n,this.onErrorHandler=s,this.onCloseHandler=r,this.ws){let i=this.ws;i.onopen=null,i.onmessage=null,i.onerror=null,i.onclose=null,i.close(),this.ws=null}return this.ws=A,this.ws.binaryType="arraybuffer",this.shouldReconnect=!1,this.clearReconnectState(),this.ws.onmessage=i=>{this.onMessageHandler&&this.onMessageHandler(i)},this.ws.onerror=i=>{console.error("Sendspin: WebSocket error",i),this.onErrorHandler&&this.onErrorHandler(i)},this.ws.onclose=()=>{console.log("Sendspin: WebSocket disconnected"),this.onCloseHandler&&this.onCloseHandler()},new Promise((i,a)=>{let o=()=>{this.onOpenHandler&&this.onOpenHandler(),i()};if(A.readyState===WebSocket.OPEN){console.log("Sendspin: Adopted open WebSocket"),o();return}let h=this.ws.onclose;this.ws.onopen=()=>{console.log("Sendspin: Adopted WebSocket connected"),o()},this.ws.onclose=l=>{h&&h.call(this.ws,l),a(new Error("Sendspin: Adopted WebSocket closed before opening"))}})}async connect(A,t,n,s,r){if(this.onOpenHandler=t,this.onMessageHandler=n,this.onErrorHandler=s,this.onCloseHandler=r,this.shouldReconnect=!1,this.clearReconnectState(),this.ws){let i=this.ws;i.onopen=null,i.onmessage=null,i.onerror=null,i.onclose=null,i.close(),this.ws=null}return this.openSocket(A)}openSocket(A){return new Promise((t,n)=>{try{console.log("Sendspin: Connecting to",A),this.ws=new WebSocket(A),this.ws.binaryType="arraybuffer",this.shouldReconnect=!0;let s=!1;this.ws.onopen=()=>{console.log("Sendspin: WebSocket connected"),s=!0;let r=this.isReconnecting;this.isReconnecting=!1,this.reconnectAttempt=0,this.onOpenHandler&&this.onOpenHandler(),r&&this.onReconnected?.(),t()},this.ws.onmessage=r=>{this.onMessageHandler&&this.onMessageHandler(r)},this.ws.onerror=r=>{console.error("Sendspin: WebSocket error",r),this.onErrorHandler&&this.onErrorHandler(r),n(r)},this.ws.onclose=()=>{console.log("Sendspin: WebSocket disconnected"),s&&this.onCloseHandler&&this.onCloseHandler(),this.shouldReconnect&&this.scheduleReconnect(A)}}catch(s){console.error("Sendspin: Failed to connect",s),n(s)}})}getReconnectDelayMs(A){let t=this.baseDelayMs*2**(A-1);return Math.min(t,this.maxDelayMs)}scheduleReconnect(A){this.reconnectTimeout!==null&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null);let t=this.reconnectAttempt+1;if(t>this.maxAttempts){console.warn(`Sendspin: Reconnect exhausted after ${this.maxAttempts} attempt(s)`),this.shouldReconnect=!1,this.isReconnecting=!1,this.reconnectAttempt=0,this.onExhausted?.();return}this.reconnectAttempt=t,this.isReconnecting=!0;let n=this.getReconnectDelayMs(t);this.reconnectTimeout=globalThis.setTimeout(()=>{this.reconnectTimeout=null,this.shouldReconnect&&(this.onReconnecting?.(t),console.log(`Sendspin: Attempting to reconnect (attempt ${t}${this.maxAttempts===1/0?"":`/${this.maxAttempts}`})...`),this.openSocket(A).catch(s=>{console.error("Sendspin: Reconnection failed",s)}))},n)}clearReconnectState(){this.reconnectTimeout!==null&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.isReconnecting=!1,this.reconnectAttempt=0}disconnect(){this.shouldReconnect=!1,this.clearReconnectState(),this.ws&&(this.ws.close(),this.ws=null)}sendText(A){this.ws&&this.ws.readyState===WebSocket.OPEN?this.ws.send(A):console.warn("Sendspin: Cannot send text, WebSocket not connected")}sendBinary(A){this.ws&&this.ws.readyState===WebSocket.OPEN?this.ws.send(A):console.warn("Sendspin: Cannot send binary, WebSocket not connected")}isConnected(){return this.ws!==null&&this.ws.readyState===WebSocket.OPEN}getReadyState(){return this.ws?this.ws.readyState:WebSocket.CLOSED}};var nt=class{constructor(A=.01,t=1.1,n=2,s=0){this._last_update=0,this._count=0,this._measurements_processed=0,this._offset=0,this._drift=0,this._offset_covariance=1/0,this._offset_drift_covariance=0,this._drift_covariance=0,this._use_drift=!1,this._offset_process_variance=A*A,this._drift_process_variance=s*s,this._forget_variance_factor=t*t,this._drift_significance_threshold_squared=n*n,this._current_time_element=this._createDefaultTimeElement()}_createDefaultTimeElement(){return{last_update:0,offset:0,drift:0}}update(A,t,n){if(n<=this._last_update)return;let s=n-this._last_update;this._last_update=n,this._measurements_processed+=1;let r=t,i=r*r;if(this._count<=0){this._count+=1,this._offset=A,this._offset_covariance=i,this._drift=0,this._current_time_element={last_update:this._last_update,offset:this._offset,drift:this._drift},this._use_drift=!1;return}if(this._count===1){this._count+=1,this._drift=(A-this._offset)/s,this._offset=A,this._drift_covariance=(this._offset_covariance+i)/(s*s),this._offset_covariance=i,this._current_time_element={last_update:this._last_update,offset:this._offset,drift:this._drift},this._use_drift=!1;return}let a=this._offset+this._drift*s,o=s*s,h=s*this._drift_process_variance,l=this._drift_covariance+h,c=this._offset_drift_covariance+this._drift_covariance*s+0,f=s*this._offset_process_variance,d=this._offset_covariance+2*this._offset_drift_covariance*s+this._drift_covariance*o+f,g=A-a,m=t*2;this._count<100?this._count+=1:Math.abs(g)>m&&(l*=this._forget_variance_factor,c*=this._forget_variance_factor,d*=this._forget_variance_factor);let p=1/(d+i),y=d*p,S=c*p;this._offset=a+y*g,this._drift+=S*g,this._drift_covariance=l-S*c,this._offset_drift_covariance=c-S*d,this._offset_covariance=d-y*d;let _=this._drift*this._drift;this._use_drift=_>this._drift_significance_threshold_squared*this._drift_covariance,this._current_time_element={last_update:this._last_update,offset:this._offset,drift:this._drift}}computeServerTime(A){let t=A-this._current_time_element.last_update,n=this._use_drift?this._current_time_element.drift:0,s=Math.round(this._current_time_element.offset+n*t);return A+s}computeClientTime(A){let t=this._use_drift?this._current_time_element.drift:0;return Math.round((A-this._current_time_element.offset+t*this._current_time_element.last_update)/(1+t))}reset(){this._count=0,this._measurements_processed=0,this._last_update=0,this._offset=0,this._drift=0,this._offset_covariance=1/0,this._offset_drift_covariance=0,this._drift_covariance=0,this._use_drift=!1,this._current_time_element=this._createDefaultTimeElement()}get count(){return this._measurements_processed}get is_synchronized(){return this._count>=1&&isFinite(this._offset_covariance)}get error(){return Math.round(Math.sqrt(this._offset_covariance))}get covariance(){return Math.round(this._offset_covariance)}get offset(){return this._offset}get drift(){return this._drift}};var Sn="sendspin-static-delay-ms-v2",Ot=class{constructor(A){this.storage=A}load(){if(!this.storage)return null;try{let A=this.storage.getItem(Sn);if(A===null)return null;let t=parseFloat(A);return isNaN(t)?null:gA(t)}catch{return null}}save(A){if(this.storage)try{this.storage.setItem(Sn,A.toString())}catch{}}};var BA=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function PA(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function st(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function W(e,...A){if(!PA(e))throw new Error("Uint8Array expected");if(A.length>0&&!A.includes(e.length))throw new Error("Uint8Array expected of length "+A+", got length="+e.length)}function Cn(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");st(e.outputLen),st(e.blockLen)}function YA(e,A=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(A&&e.finished)throw new Error("Hash#digest() has already been called")}function wn(e,A){W(e);let t=A.outputLen;if(e.length>>A}var kn=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Sr=Array.from({length:256},(e,A)=>A.toString(16).padStart(2,"0"));function RA(e){if(W(e),kn)return e.toHex();let A="";for(let t=0;t=yA._0&&e<=yA._9)return e-yA._0;if(e>=yA.A&&e<=yA.F)return e-(yA.A-10);if(e>=yA.a&&e<=yA.f)return e-(yA.a-10)}function Ut(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(kn)return Uint8Array.fromHex(e);let A=e.length,t=A/2;if(A%2)throw new Error("hex string expected, got unpadded hex of length "+A);let n=new Uint8Array(t);for(let s=0,r=0;se().update(rt(n)).digest(),t=e();return A.outputLen=t.outputLen,A.blockLen=t.blockLen,A.create=()=>e(),A}function it(e=32){if(BA&&typeof BA.getRandomValues=="function")return BA.getRandomValues(new Uint8Array(e));if(BA&&typeof BA.randomBytes=="function")return Uint8Array.from(BA.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function Mr(e,A,t,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(A,t,n);let s=BigInt(32),r=BigInt(4294967295),i=Number(t>>s&r),a=Number(t&r),o=n?4:0,h=n?0:4;e.setUint32(A+o,i,n),e.setUint32(A+h,a,n)}function _n(e,A,t){return e&A^~e&t}function xn(e,A,t){return e&A^e&t^A&t}var ot=class extends ZA{constructor(A,t,n,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=A,this.outputLen=t,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(A),this.view=Lt(this.buffer)}update(A){YA(this),A=rt(A),W(A);let{view:t,buffer:n,blockLen:s}=this,r=A.length;for(let i=0;is-i&&(this.process(n,0),i=0);for(let u=i;ul.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u>En&zt)}:{h:Number(e>>En&zt)|0,l:Number(e&zt)|0}}function bn(e,A=!1){let t=e.length,n=new Uint32Array(t),s=new Uint32Array(t);for(let r=0;re>>>t,Me=(e,A,t)=>e<<32-t|A>>>t,OA=(e,A,t)=>e>>>t|A<<32-t,LA=(e,A,t)=>e<<32-t|A>>>t,at=(e,A,t)=>e<<64-t|A>>>t-32,ct=(e,A,t)=>e>>>t-32|A<<64-t;function cA(e,A,t,n){let s=(A>>>0)+(n>>>0);return{h:e+t+(s/2**32|0)|0,l:s|0}}var Tn=(e,A,t)=>(e>>>0)+(A>>>0)+(t>>>0),Dn=(e,A,t,n)=>A+t+n+(e/2**32|0)|0,vn=(e,A,t,n)=>(e>>>0)+(A>>>0)+(t>>>0)+(n>>>0),In=(e,A,t,n,s)=>A+t+n+s+(e/2**32|0)|0,Jn=(e,A,t,n,s)=>(e>>>0)+(A>>>0)+(t>>>0)+(n>>>0)+(s>>>0),Bn=(e,A,t,n,s,r)=>A+t+n+s+r+(e/2**32|0)|0;var kr=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),bA=new Uint32Array(64),Ce=class extends ot{constructor(A=32){super(64,A,8,!1),this.A=MA[0]|0,this.B=MA[1]|0,this.C=MA[2]|0,this.D=MA[3]|0,this.E=MA[4]|0,this.F=MA[5]|0,this.G=MA[6]|0,this.H=MA[7]|0}get(){let{A,B:t,C:n,D:s,E:r,F:i,G:a,H:o}=this;return[A,t,n,s,r,i,a,o]}set(A,t,n,s,r,i,a,o){this.A=A|0,this.B=t|0,this.C=n|0,this.D=s|0,this.E=r|0,this.F=i|0,this.G=a|0,this.H=o|0}process(A,t){for(let u=0;u<16;u++,t+=4)bA[u]=A.getUint32(t,!1);for(let u=16;u<64;u++){let c=bA[u-15],f=bA[u-2],d=nA(c,7)^nA(c,18)^c>>>3,g=nA(f,17)^nA(f,19)^f>>>10;bA[u]=g+bA[u-7]+d+bA[u-16]|0}let{A:n,B:s,C:r,D:i,E:a,F:o,G:h,H:l}=this;for(let u=0;u<64;u++){let c=nA(a,6)^nA(a,11)^nA(a,25),f=l+c+_n(a,o,h)+kr[u]+bA[u]|0,g=(nA(n,2)^nA(n,13)^nA(n,22))+xn(n,s,r)|0;l=h,h=o,o=a,a=i+f|0,i=r,r=s,s=n,n=f+g|0}n=n+this.A|0,s=s+this.B|0,r=r+this.C|0,i=i+this.D|0,a=a+this.E|0,o=o+this.F|0,h=h+this.G|0,l=l+this.H|0,this.set(n,s,r,i,a,o,h,l)}roundClean(){SA(bA)}destroy(){this.set(0,0,0,0,0,0,0,0),SA(this.buffer)}};var Pn=bn(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),_r=Pn[0],xr=Pn[1],TA=new Uint32Array(80),DA=new Uint32Array(80),we=class extends ot{constructor(A=64){super(128,A,16,!1),this.Ah=Z[0]|0,this.Al=Z[1]|0,this.Bh=Z[2]|0,this.Bl=Z[3]|0,this.Ch=Z[4]|0,this.Cl=Z[5]|0,this.Dh=Z[6]|0,this.Dl=Z[7]|0,this.Eh=Z[8]|0,this.El=Z[9]|0,this.Fh=Z[10]|0,this.Fl=Z[11]|0,this.Gh=Z[12]|0,this.Gl=Z[13]|0,this.Hh=Z[14]|0,this.Hl=Z[15]|0}get(){let{Ah:A,Al:t,Bh:n,Bl:s,Ch:r,Cl:i,Dh:a,Dl:o,Eh:h,El:l,Fh:u,Fl:c,Gh:f,Gl:d,Hh:g,Hl:m}=this;return[A,t,n,s,r,i,a,o,h,l,u,c,f,d,g,m]}set(A,t,n,s,r,i,a,o,h,l,u,c,f,d,g,m){this.Ah=A|0,this.Al=t|0,this.Bh=n|0,this.Bl=s|0,this.Ch=r|0,this.Cl=i|0,this.Dh=a|0,this.Dl=o|0,this.Eh=h|0,this.El=l|0,this.Fh=u|0,this.Fl=c|0,this.Gh=f|0,this.Gl=d|0,this.Hh=g|0,this.Hl=m|0}process(A,t){for(let S=0;S<16;S++,t+=4)TA[S]=A.getUint32(t),DA[S]=A.getUint32(t+=4);for(let S=16;S<80;S++){let _=TA[S-15]|0,I=DA[S-15]|0,J=OA(_,I,1)^OA(_,I,8)^Se(_,I,7),B=LA(_,I,1)^LA(_,I,8)^Me(_,I,7),v=TA[S-2]|0,M=DA[S-2]|0,C=OA(v,M,19)^at(v,M,61)^Se(v,M,6),E=LA(v,M,19)^ct(v,M,61)^Me(v,M,6),T=vn(B,E,DA[S-7],DA[S-16]),w=In(T,J,C,TA[S-7],TA[S-16]);TA[S]=w|0,DA[S]=T|0}let{Ah:n,Al:s,Bh:r,Bl:i,Ch:a,Cl:o,Dh:h,Dl:l,Eh:u,El:c,Fh:f,Fl:d,Gh:g,Gl:m,Hh:p,Hl:y}=this;for(let S=0;S<80;S++){let _=OA(u,c,14)^OA(u,c,18)^at(u,c,41),I=LA(u,c,14)^LA(u,c,18)^ct(u,c,41),J=u&f^~u&g,B=c&d^~c&m,v=Jn(y,I,B,xr[S],DA[S]),M=Bn(v,p,_,J,_r[S],TA[S]),C=v|0,E=OA(n,s,28)^at(n,s,34)^at(n,s,39),T=LA(n,s,28)^ct(n,s,34)^ct(n,s,39),w=n&r^n&a^r&a,x=s&i^s&o^i&o;p=g|0,y=m|0,g=f|0,m=d|0,f=u|0,d=c|0,{h:u,l:c}=cA(h|0,l|0,M|0,C|0),h=a|0,l=o|0,a=r|0,o=i|0,r=n|0,i=s|0;let D=Tn(C,T,x);n=Dn(D,M,E,w),s=D|0}({h:n,l:s}=cA(this.Ah|0,this.Al|0,n|0,s|0)),{h:r,l:i}=cA(this.Bh|0,this.Bl|0,r|0,i|0),{h:a,l:o}=cA(this.Ch|0,this.Cl|0,a|0,o|0),{h,l}=cA(this.Dh|0,this.Dl|0,h|0,l|0),{h:u,l:c}=cA(this.Eh|0,this.El|0,u|0,c|0),{h:f,l:d}=cA(this.Fh|0,this.Fl|0,f|0,d|0),{h:g,l:m}=cA(this.Gh|0,this.Gl|0,g|0,m|0),{h:p,l:y}=cA(this.Hh|0,this.Hl|0,p|0,y|0),this.set(n,s,r,i,a,o,h,l,u,c,f,d,g,m,p,y)}roundClean(){SA(TA,DA)}destroy(){SA(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var j=ye(()=>new Ce);var UA=ye(()=>new we);var xe=BigInt(0),_e=BigInt(1);function Qt(e,A=""){if(typeof e!="boolean"){let t=A&&`"${A}"`;throw new Error(t+"expected boolean, got type="+typeof e)}return e}function ht(e,A,t=""){let n=PA(e),s=e?.length,r=A!==void 0;if(!n||r&&s!==A){let i=t&&`"${t}" `,a=r?` of length ${A}`:"",o=n?`length=${s}`:`type=${typeof e}`;throw new Error(i+"expected Uint8Array"+a+", got "+o)}return e}function Rn(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?xe:BigInt("0x"+e)}function On(e){return Rn(RA(e))}function sA(e){return W(e),Rn(RA(Uint8Array.from(e).reverse()))}function Ee(e,A){return Ut(e.toString(16).padStart(A*2,"0"))}function Nt(e,A){return Ee(e,A).reverse()}function X(e,A,t){let n;if(typeof A=="string")try{n=Ut(A)}catch(r){throw new Error(e+" must be hex string or Uint8Array, cause: "+r)}else if(PA(A))n=Uint8Array.from(A);else throw new Error(e+" must be hex string or Uint8Array");let s=n.length;if(typeof t=="number"&&s!==t)throw new Error(e+" of length "+t+" expected, got "+s);return n}function Ln(e,A){if(e.length!==A.length)return!1;let t=0;for(let n=0;ntypeof e=="bigint"&&xe<=e;function Er(e,A,t){return ke(e)&&ke(A)&&ke(t)&&A<=e&&exe;e>>=_e,A+=1);return A}var lt=e=>(_e<n(s,r,!1)),Object.entries(t).forEach(([s,r])=>n(s,r,!0))}var Te=()=>{throw new Error("not implemented")};function De(e){let A=new WeakMap;return(t,...n)=>{let s=A.get(t);if(s!==void 0)return s;let r=e(t,...n);return A.set(t,r),r}}var AA=BigInt(0),$=BigInt(1),QA=BigInt(2),Nn=BigInt(3),Hn=BigInt(4),Kn=BigInt(5),br=BigInt(7),Fn=BigInt(8),Tr=BigInt(9),Gn=BigInt(16);function N(e,A){let t=e%A;return t>=AA?t:A+t}function tA(e,A,t){let n=e;for(;A-- >AA;)n*=n,n%=t;return n}function zn(e,A){if(e===AA)throw new Error("invert: expected non-zero number");if(A<=AA)throw new Error("invert: expected positive modulus, got "+A);let t=N(e,A),n=A,s=AA,r=$,i=$,a=AA;for(;t!==AA;){let h=n/t,l=n%t,u=s-i*h,c=r-a*h;n=t,t=l,s=i,r=a,i=u,a=c}if(n!==$)throw new Error("invert: does not exist");return N(s,A)}function ve(e,A,t){if(!e.eql(e.sqr(A),t))throw new Error("Cannot find square root")}function Zn(e,A){let t=(e.ORDER+$)/Hn,n=e.pow(A,t);return ve(e,n,A),n}function Dr(e,A){let t=(e.ORDER-Kn)/Fn,n=e.mul(A,QA),s=e.pow(n,t),r=e.mul(A,s),i=e.mul(e.mul(r,QA),s),a=e.mul(r,e.sub(i,e.ONE));return ve(e,a,A),a}function vr(e){let A=wA(e),t=Yn(e),n=t(A,A.neg(A.ONE)),s=t(A,n),r=t(A,A.neg(n)),i=(e+br)/Gn;return(a,o)=>{let h=a.pow(o,i),l=a.mul(h,n),u=a.mul(h,s),c=a.mul(h,r),f=a.eql(a.sqr(l),o),d=a.eql(a.sqr(u),o);h=a.cmov(h,l,f),l=a.cmov(c,u,d);let g=a.eql(a.sqr(l),o),m=a.cmov(h,l,g);return ve(a,m,o),m}}function Yn(e){if(e1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return Zn;let r=s.pow(n,A),i=(A+$)/QA;return function(o,h){if(o.is0(h))return h;if(Qn(o,h)!==1)throw new Error("Cannot find square root");let l=t,u=o.mul(o.ONE,r),c=o.pow(h,A),f=o.pow(h,i);for(;!o.eql(c,o.ONE);){if(o.is0(c))return o.ZERO;let d=1,g=o.sqr(c);for(;!o.eql(g,o.ONE);)if(d++,g=o.sqr(g),d===l)throw new Error("Cannot find square root");let m=$<(N(e,A)&$)===$,Jr=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function qn(e){let A={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},t=Jr.reduce((n,s)=>(n[s]="function",n),A);return zA(e,t),e}function Br(e,A,t){if(tAA;)t&$&&(n=e.mul(n,s)),s=e.sqr(s),t>>=$;return n}function Ht(e,A,t=!1){let n=new Array(A.length).fill(t?e.ZERO:void 0),s=A.reduce((i,a,o)=>e.is0(a)?i:(n[o]=i,e.mul(i,a)),e.ONE),r=e.inv(s);return A.reduceRight((i,a,o)=>e.is0(a)?i:(n[o]=e.mul(i,n[o]),e.mul(i,a)),r),n}function Qn(e,A){let t=(e.ORDER-$)/QA,n=e.pow(A,t),s=e.eql(n,e.ONE),r=e.eql(n,e.ZERO),i=e.eql(n,e.neg(e.ONE));if(!s&&!r&&!i)throw new Error("invalid Legendre symbol result");return s?1:r?0:-1}function Vn(e,A){A!==void 0&&st(A);let t=A!==void 0?A:e.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function wA(e,A,t=!1,n={}){if(e<=AA)throw new Error("invalid field: expected ORDER > 0, got "+e);let s,r,i=!1,a;if(typeof A=="object"&&A!=null){if(n.sqrt||t)throw new Error("cannot specify opts in two arguments");let c=A;c.BITS&&(s=c.BITS),c.sqrt&&(r=c.sqrt),typeof c.isLE=="boolean"&&(t=c.isLE),typeof c.modFromBytes=="boolean"&&(i=c.modFromBytes),a=c.allowedLengths}else typeof A=="number"&&(s=A),n.sqrt&&(r=n.sqrt);let{nBitLength:o,nByteLength:h}=Vn(e,s);if(h>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let l,u=Object.freeze({ORDER:e,isLE:t,BITS:o,BYTES:h,MASK:lt(o),ZERO:AA,ONE:$,allowedLengths:a,create:c=>N(c,e),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return AA<=c&&cc===AA,isValidNot0:c=>!u.is0(c)&&u.isValid(c),isOdd:c=>(c&$)===$,neg:c=>N(-c,e),eql:(c,f)=>c===f,sqr:c=>N(c*c,e),add:(c,f)=>N(c+f,e),sub:(c,f)=>N(c-f,e),mul:(c,f)=>N(c*f,e),pow:(c,f)=>Br(u,c,f),div:(c,f)=>N(c*zn(f,e),e),sqrN:c=>c*c,addN:(c,f)=>c+f,subN:(c,f)=>c-f,mulN:(c,f)=>c*f,inv:c=>zn(c,e),sqrt:r||(c=>(l||(l=Ir(e)),l(u,c))),toBytes:c=>t?Nt(c,h):Ee(c,h),fromBytes:(c,f=!0)=>{if(a){if(!a.includes(c.length)||c.length>h)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+c.length);let g=new Uint8Array(h);g.set(c,t?0:g.length-c.length),c=g}if(c.length!==h)throw new Error("Field.fromBytes: expected "+h+" bytes, got "+c.length);let d=t?sA(c):On(c);if(i&&(d=N(d,e)),!f&&!u.isValid(d))throw new Error("invalid field element: outside of range 0..ORDER");return d},invertBatch:c=>Ht(u,c),cmov:(c,f,d)=>d?f:c});return Object.freeze(u)}var Kt=BigInt(0),Pe=BigInt(1);function Wn(e,A){let t=A.negate();return e?t:A}function ut(e,A){let t=Ht(e.Fp,A.map(n=>n.Z));return A.map((n,s)=>e.fromAffine(n.toAffine(t[s])))}function As(e,A){if(!Number.isSafeInteger(e)||e<=0||e>A)throw new Error("invalid window size, expected [1.."+A+"], got W="+e)}function Ie(e,A){As(e,A);let t=Math.ceil(A/e)+1,n=2**(e-1),s=2**e,r=lt(e),i=BigInt(e);return{windows:t,windowSize:n,mask:r,maxNumber:s,shiftBy:i}}function jn(e,A,t){let{windowSize:n,mask:s,maxNumber:r,shiftBy:i}=t,a=Number(e&s),o=e>>i;a>n&&(a-=r,o+=Pe);let h=A*n,l=h+Math.abs(a)-1,u=a===0,c=a<0,f=A%2!==0;return{nextN:o,offset:l,isZero:u,isNeg:c,isNegF:f,offsetF:h}}function Pr(e,A){if(!Array.isArray(e))throw new Error("array expected");e.forEach((t,n)=>{if(!(t instanceof A))throw new Error("invalid point at index "+n)})}function Rr(e,A){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((t,n)=>{if(!A.isValid(t))throw new Error("invalid scalar at index "+n)})}var Je=new WeakMap,ts=new WeakMap;function Be(e){return ts.get(e)||1}function Xn(e){if(e!==Kt)throw new Error("invalid wNAF")}var Ft=class{constructor(A,t){this.BASE=A.BASE,this.ZERO=A.ZERO,this.Fn=A.Fn,this.bits=t}_unsafeLadder(A,t,n=this.ZERO){let s=A;for(;t>Kt;)t&Pe&&(n=n.add(s)),s=s.double(),t>>=Pe;return n}precomputeWindow(A,t){let{windows:n,windowSize:s}=Ie(t,this.bits),r=[],i=A,a=i;for(let o=0;o12?o=a-3:a>4?o=a-2:a>0&&(o=2);let h=lt(o),l=new Array(Number(h)+1).fill(i),u=Math.floor((A.BITS-1)/o)*o,c=i;for(let f=u;f>=0;f-=o){l.fill(i);for(let g=0;g>BigInt(f)&h);l[p]=l[p].add(t[g])}let d=i;for(let g=l.length-1,m=i;g>0;g--)m=m.add(l[g]),d=d.add(m);if(c=c.add(d),f!==0)for(let g=0;gKt))throw new Error(`CURVE.${o} must be positive bigint`)}let s=$n(A.p,t.Fp,n),r=$n(A.n,t.Fn,n),a=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let o of a)if(!s.isValid(A[o]))throw new Error(`CURVE.${o} must be valid field element of CURVE.Fp`);return A=Object.freeze(Object.assign({},A)),{CURVE:A,Fp:s,Fn:r}}var vA=BigInt(0),G=BigInt(1),Re=BigInt(2),Or=BigInt(8);function Lr(e,A,t,n){let s=e.sqr(t),r=e.sqr(n),i=e.add(e.mul(A.a,s),r),a=e.add(e.ONE,e.mul(A.d,e.mul(s,r)));return e.eql(i,a)}function Ur(e,A={}){let t=es("edwards",e,A,A.FpFnLE),{Fp:n,Fn:s}=t,r=t.CURVE,{h:i}=r;zA(A,{},{uvRatio:"function"});let a=Re<n.create(m),h=A.uvRatio||((m,p)=>{try{return{isValid:!0,value:n.sqrt(n.div(m,p))}}catch{return{isValid:!1,value:vA}}});if(!Lr(n,r,r.Gx,r.Gy))throw new Error("bad curve params: generator point");function l(m,p,y=!1){let S=y?G:vA;return VA("coordinate "+m,p,S,a),p}function u(m){if(!(m instanceof d))throw new Error("ExtendedPoint expected")}let c=De((m,p)=>{let{X:y,Y:S,Z:_}=m,I=m.is0();p==null&&(p=I?Or:n.inv(_));let J=o(y*p),B=o(S*p),v=n.mul(_,p);if(I)return{x:vA,y:G};if(v!==G)throw new Error("invZ was invalid");return{x:J,y:B}}),f=De(m=>{let{a:p,d:y}=r;if(m.is0())throw new Error("bad point: ZERO");let{X:S,Y:_,Z:I,T:J}=m,B=o(S*S),v=o(_*_),M=o(I*I),C=o(M*M),E=o(B*p),T=o(M*o(E+v)),w=o(C+o(y*o(B*v)));if(T!==w)throw new Error("bad point: equation left != right (1)");let x=o(S*_),D=o(I*J);if(x!==D)throw new Error("bad point: equation left != right (2)");return!0});class d{constructor(p,y,S,_){this.X=l("x",p),this.Y=l("y",y),this.Z=l("z",S,!0),this.T=l("t",_),Object.freeze(this)}static CURVE(){return r}static fromAffine(p){if(p instanceof d)throw new Error("extended point not allowed");let{x:y,y:S}=p||{};return l("x",y),l("y",S),new d(y,S,G,o(y*S))}static fromBytes(p,y=!1){let S=n.BYTES,{a:_,d:I}=r;p=be(ht(p,S,"point")),Qt(y,"zip215");let J=be(p),B=p[S-1];J[S-1]=B&-129;let v=sA(J),M=y?a:n.ORDER;VA("point.y",v,vA,M);let C=o(v*v),E=o(C-G),T=o(I*C-_),{isValid:w,value:x}=h(E,T);if(!w)throw new Error("bad point: invalid y coordinate");let D=(x&G)===G,P=(B&128)!==0;if(!y&&x===vA&&P)throw new Error("bad point: x=0 and x_0=1");return P!==D&&(x=o(-x)),d.fromAffine({x,y:v})}static fromHex(p,y=!1){return d.fromBytes(X("point",p),y)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(p=8,y=!0){return g.createCache(this,p),y||this.multiply(Re),this}assertValidity(){f(this)}equals(p){u(p);let{X:y,Y:S,Z:_}=this,{X:I,Y:J,Z:B}=p,v=o(y*B),M=o(I*_),C=o(S*B),E=o(J*_);return v===M&&C===E}is0(){return this.equals(d.ZERO)}negate(){return new d(o(-this.X),this.Y,this.Z,o(-this.T))}double(){let{a:p}=r,{X:y,Y:S,Z:_}=this,I=o(y*y),J=o(S*S),B=o(Re*o(_*_)),v=o(p*I),M=y+S,C=o(o(M*M)-I-J),E=v+J,T=E-B,w=v-J,x=o(C*T),D=o(E*w),P=o(C*w),R=o(T*E);return new d(x,D,R,P)}add(p){u(p);let{a:y,d:S}=r,{X:_,Y:I,Z:J,T:B}=this,{X:v,Y:M,Z:C,T:E}=p,T=o(_*v),w=o(I*M),x=o(B*S*E),D=o(J*C),P=o((_+I)*(v+M)-T-w),R=D-x,O=D+x,k=o(w-y*T),L=o(P*R),U=o(O*k),z=o(P*k),V=o(R*O);return new d(L,U,V,z)}subtract(p){return this.add(p.negate())}multiply(p){if(!s.isValidNot0(p))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:y,f:S}=g.cached(this,p,_=>ut(d,_));return ut(d,[y,S])[0]}multiplyUnsafe(p,y=d.ZERO){if(!s.isValid(p))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return p===vA?d.ZERO:this.is0()||p===G?this:g.unsafe(this,p,S=>ut(d,S),y)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return g.unsafe(this,r.n).is0()}toAffine(p){return c(this,p)}clearCofactor(){return i===G?this:this.multiplyUnsafe(i)}toBytes(){let{x:p,y}=this.toAffine(),S=n.toBytes(y);return S[S.length-1]|=p&G?128:0,S}toHex(){return RA(this.toBytes())}toString(){return``}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(p){return ut(d,p)}static msm(p,y){return Gt(d,s,p,y)}_setWindowSize(p){this.precompute(p)}toRawBytes(){return this.toBytes()}}d.BASE=new d(r.Gx,r.Gy,G,o(r.Gx*r.Gy)),d.ZERO=new d(vA,G,G,vA),d.Fp=n,d.Fn=s;let g=new Ft(d,s.BITS);return d.BASE.precompute(8),d}var Zt=class{constructor(A){this.ep=A}static fromBytes(A){Te()}static fromHex(A){Te()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(A){return this.ep.toAffine(A)}toHex(){return RA(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(A){return this.assertSame(A),this.init(this.ep.add(A.ep))}subtract(A){return this.assertSame(A),this.init(this.ep.subtract(A.ep))}multiply(A){return this.init(this.ep.multiply(A))}multiplyUnsafe(A){return this.init(this.ep.multiplyUnsafe(A))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(A,t){return this.init(this.ep.precompute(A,t))}toRawBytes(){return this.toBytes()}};function zr(e,A,t={}){if(typeof A!="function")throw new Error('"hash" function param is required');zA(t,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=t,{BASE:s,Fp:r,Fn:i}=e,a=t.randomBytes||it,o=t.adjustScalarBytes||(M=>M),h=t.domain||((M,C,E)=>{if(Qt(E,"phflag"),C.length||E)throw new Error("Contexts/pre-hash are not supported");return M});function l(M){return i.create(sA(M))}function u(M){let C=S.secretKey;M=X("private key",M,C);let E=X("hashed private key",A(M),2*C),T=o(E.slice(0,C)),w=E.slice(C,2*C),x=l(T);return{head:T,prefix:w,scalar:x}}function c(M){let{head:C,prefix:E,scalar:T}=u(M),w=s.multiply(T),x=w.toBytes();return{head:C,prefix:E,scalar:T,point:w,pointBytes:x}}function f(M){return c(M).pointBytes}function d(M=Uint8Array.of(),...C){let E=qA(...C);return l(A(h(E,X("context",M),!!n)))}function g(M,C,E={}){M=X("message",M),n&&(M=n(M));let{prefix:T,scalar:w,pointBytes:x}=c(C),D=d(E.context,T,M),P=s.multiply(D).toBytes(),R=d(E.context,P,x,M),O=i.create(D+R*w);if(!i.isValid(O))throw new Error("sign failed: invalid s");let k=qA(P,i.toBytes(O));return ht(k,S.signature,"result")}let m={zip215:!0};function p(M,C,E,T=m){let{context:w,zip215:x}=T,D=S.signature;M=X("signature",M,D),C=X("message",C),E=X("publicKey",E,S.publicKey),x!==void 0&&Qt(x,"zip215"),n&&(C=n(C));let P=D/2,R=M.subarray(0,P),O=sA(M.subarray(P,D)),k,L,U;try{k=e.fromBytes(E,x),L=e.fromBytes(R,x),U=s.multiplyUnsafe(O)}catch{return!1}if(!x&&k.isSmallOrder())return!1;let z=d(w,L.toBytes(),k.toBytes(),C);return L.add(k.multiplyUnsafe(z)).subtract(U).clearCofactor().is0()}let y=r.BYTES,S={secretKey:y,publicKey:y,signature:2*y,seed:y};function _(M=a(S.seed)){return ht(M,S.seed,"seed")}function I(M){let C=v.randomSecretKey(M);return{secretKey:C,publicKey:f(C)}}function J(M){return PA(M)&&M.length===i.BYTES}function B(M,C){try{return!!e.fromBytes(M,C)}catch{return!1}}let v={getExtendedPublicKey:c,randomSecretKey:_,isValidSecretKey:J,isValidPublicKey:B,toMontgomery(M){let{y:C}=e.fromBytes(M),E=S.publicKey,T=E===32;if(!T&&E!==57)throw new Error("only defined for 25519 and 448");let w=T?r.div(G+C,G-C):r.div(C-G,C+G);return r.toBytes(w)},toMontgomerySecret(M){let C=S.secretKey;ht(M,C);let E=A(M.subarray(0,C));return o(E).subarray(0,C)},randomPrivateKey:_,precompute(M=8,C=e.BASE){return C.precompute(M,!1)}};return Object.freeze({keygen:I,getPublicKey:f,sign:g,verify:p,utils:v,Point:e,lengths:S})}function Qr(e){let A={a:e.a,d:e.d,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},t=e.Fp,n=wA(A.n,e.nBitLength,!0),s={Fp:t,Fn:n,uvRatio:e.uvRatio},r={randomBytes:e.randomBytes,adjustScalarBytes:e.adjustScalarBytes,domain:e.domain,prehash:e.prehash,mapToCurve:e.mapToCurve};return{CURVE:A,curveOpts:s,hash:e.hash,eddsaOpts:r}}function Nr(e,A){let t=A.Point;return Object.assign({},A,{ExtendedPoint:t,CURVE:e,nBitLength:t.Fn.BITS,nByteLength:t.Fn.BYTES})}function ns(e){let{CURVE:A,curveOpts:t,hash:n,eddsaOpts:s}=Qr(e),r=Ur(A,t),i=zr(r,n,s);return Nr(e,i)}var dt=BigInt(0),WA=BigInt(1),Yt=BigInt(2);function Hr(e){return zA(e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...e})}function ss(e){let A=Hr(e),{P:t,type:n,adjustScalarBytes:s,powPminus2:r,randomBytes:i}=A,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");let o=i||it,h=a?255:448,l=a?32:56,u=BigInt(a?9:5),c=BigInt(a?121665:39081),f=a?Yt**BigInt(254):Yt**BigInt(447),d=a?BigInt(8)*Yt**BigInt(251)-WA:BigInt(4)*Yt**BigInt(445)-WA,g=f+d+WA,m=w=>N(w,t),p=y(u);function y(w){return Nt(m(w),l)}function S(w){let x=X("u coordinate",w,l);return a&&(x[31]&=127),m(sA(x))}function _(w){return sA(s(X("scalar",w,l)))}function I(w,x){let D=v(S(x),_(w));if(D===dt)throw new Error("invalid private or public key received");return y(D)}function J(w){return I(w,p)}function B(w,x,D){let P=m(w*(x-D));return x=m(x-P),D=m(D+P),{x_2:x,x_3:D}}function v(w,x){VA("u",w,dt,t),VA("scalar",x,f,g);let D=x,P=w,R=WA,O=dt,k=w,L=WA,U=dt;for(let V=BigInt(h-1);V>=dt;V--){let rA=D>>V&WA;U^=rA,{x_2:R,x_3:k}=B(U,R,k),{x_2:O,x_3:L}=B(U,O,L),U=rA;let iA=R+O,oA=m(iA*iA),aA=R-O,pA=m(aA*aA),mA=oA-pA,cr=k+L,hr=k-L,dn=m(hr*iA),fn=m(cr*aA),pn=dn+fn,mn=dn-fn;k=m(pn*pn),L=m(P*m(mn*mn)),R=m(oA*pA),O=m(mA*(oA+m(c*mA)))}({x_2:R,x_3:k}=B(U,R,k)),{x_2:O,x_3:L}=B(U,O,L);let z=r(O);return m(R*z)}let M={secretKey:l,publicKey:l,seed:l},C=(w=o(l))=>(W(w,M.seed),w);function E(w){let x=C(w);return{secretKey:x,publicKey:J(x)}}return{keygen:E,getSharedSecret:(w,x)=>I(w,x),getPublicKey:w=>J(w),scalarMult:I,scalarMultBase:J,utils:{randomSecretKey:C,randomPrivateKey:C},GuBytes:p.slice(),lengths:M}}var Kr=BigInt(0),_A=BigInt(1),rs=BigInt(2),Fr=BigInt(3),Gr=BigInt(5),Zr=BigInt(8),jA=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),ft={p:jA,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Zr,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function as(e){let A=BigInt(10),t=BigInt(20),n=BigInt(40),s=BigInt(80),r=jA,a=e*e%r*e%r,o=tA(a,rs,r)*a%r,h=tA(o,_A,r)*e%r,l=tA(h,Gr,r)*h%r,u=tA(l,A,r)*l%r,c=tA(u,t,r)*u%r,f=tA(c,n,r)*c%r,d=tA(f,s,r)*f%r,g=tA(d,s,r)*f%r,m=tA(g,A,r)*l%r;return{pow_p_5_8:tA(m,rs,r)*e%r,b2:a}}function cs(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var Oe=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function ze(e,A){let t=jA,n=N(A*A*A,t),s=N(n*n*A,t),r=as(e*s).pow_p_5_8,i=N(e*n*r,t),a=N(A*i*i,t),o=i,h=N(i*Oe,t),l=a===e,u=a===N(-e,t),c=a===N(-e*Oe,t);return l&&(i=o),(u||c)&&(i=h),CA(i,t)&&(i=N(-i,t)),{isValid:l||u,value:i}}var kA=wA(ft.p,{isLE:!0}),Yr=wA(ft.n,{isLE:!0}),qr={...ft,Fp:kA,hash:UA,adjustScalarBytes:cs,uvRatio:ze},NA=ns(qr);var HA=(()=>{let e=kA.ORDER;return ss({P:e,type:"x25519",powPminus2:A=>{let{pow_p_5_8:t,b2:n}=as(A);return N(tA(t,Fr,e)*n,e)},adjustScalarBytes:cs})})();var Le=Oe,Vr=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Wr=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),jr=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),Xr=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),is=e=>ze(_A,e),$r=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Ue=e=>NA.Point.Fp.create(sA(e)&$r);function os(e){let{d:A}=ft,t=jA,n=p=>kA.create(p),s=n(Le*e*e),r=n((s+_A)*jr),i=BigInt(-1),a=n((i-A*s)*n(s+A)),{isValid:o,value:h}=ze(r,a),l=n(h*e);CA(l,t)||(l=n(-l)),o||(h=l),o||(i=s);let u=n(i*(s-_A)*Xr-a),c=h*h,f=n((h+h)*a),d=n(u*Vr),g=n(_A-c),m=n(_A+c);return new NA.Point(n(f*m),n(g*d),n(d*m),n(f*g))}function Ai(e){W(e,64);let A=Ue(e.subarray(0,32)),t=os(A),n=Ue(e.subarray(32,64)),s=os(n);return new xA(t.add(s))}var xA=class e extends Zt{constructor(A){super(A)}static fromAffine(A){return new e(NA.Point.fromAffine(A))}assertSame(A){if(!(A instanceof e))throw new Error("RistrettoPoint expected")}init(A){return new e(A)}static hashToCurve(A){return Ai(X("ristrettoHash",A,64))}static fromBytes(A){W(A,32);let{a:t,d:n}=ft,s=jA,r=_=>kA.create(_),i=Ue(A);if(!Ln(kA.toBytes(i),A)||CA(i,s))throw new Error("invalid ristretto255 encoding 1");let a=r(i*i),o=r(_A+t*a),h=r(_A-t*a),l=r(o*o),u=r(h*h),c=r(t*n*l-u),{isValid:f,value:d}=is(r(c*u)),g=r(d*h),m=r(d*g*c),p=r((i+i)*g);CA(p,s)&&(p=r(-p));let y=r(o*m),S=r(p*y);if(!f||CA(S,s)||y===Kr)throw new Error("invalid ristretto255 encoding 2");return new e(new NA.Point(p,y,_A,S))}static fromHex(A){return e.fromBytes(X("ristrettoHex",A,32))}static msm(A,t){return Gt(e,NA.Point.Fn,A,t)}toBytes(){let{X:A,Y:t,Z:n,T:s}=this.ep,r=jA,i=m=>kA.create(m),a=i(i(n+t)*i(n-t)),o=i(A*t),h=i(o*o),{value:l}=is(i(a*h)),u=i(l*a),c=i(l*o),f=i(u*c*s),d;if(CA(s*f,r)){let m=i(t*Le),p=i(A*Le);A=m,t=p,d=i(u*Wr)}else d=c;CA(A*f,r)&&(t=i(-t));let g=i((n-t)*d);return CA(g,r)&&(g=i(-g)),kA.toBytes(g)}equals(A){this.assertSame(A);let{X:t,Y:n}=this.ep,{X:s,Y:r}=A.ep,i=h=>kA.create(h),a=i(t*r)===i(n*s),o=i(n*r)===i(t*s);return a||o}is0(){return this.equals(e.ZERO)}};xA.BASE=new xA(NA.Point.BASE);xA.ZERO=new xA(NA.Point.ZERO);xA.Fp=kA;xA.Fn=Yr;function hs(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Vt(e){if(typeof e!="boolean")throw new Error(`boolean expected, not ${e}`)}function Wt(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Q(e,...A){if(!hs(e))throw new Error("Uint8Array expected");if(A.length>0&&!A.includes(e.length))throw new Error("Uint8Array expected of length "+A+", got length="+e.length)}function IA(e,A=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(A&&e.finished)throw new Error("Hash#digest() has already been called")}function pt(e,A){Q(e);let t=A.outputLen;if(e.length{function t(n,...s){if(Q(n),!ti)throw new Error("Non little-endian hardware is not yet supported");if(e.nonceLength!==void 0){let l=s[0];if(!l)throw new Error("nonce / iv required");e.varSizeNonce?Q(l):Q(l,e.nonceLength)}let r=e.tagLength;r&&s[1]!==void 0&&Q(s[1]);let i=A(n,...s),a=(l,u)=>{if(u!==void 0){if(l!==2)throw new Error("cipher output not supported");Q(u)}},o=!1;return{encrypt(l,u){if(o)throw new Error("cannot encrypt() twice with same key + nonce");return o=!0,Q(l),a(i.encrypt.length,u),i.encrypt(l,u)},decrypt(l,u){if(Q(l),r&&l.length>s&r),a=Number(t&r),o=n?4:0,h=n?0:4;e.setUint32(A+o,i,n),e.setUint32(A+h,a,n)}function Xt(e,A,t){Vt(t);let n=new Uint8Array(16),s=XA(n);return qt(s,0,BigInt(A),t),qt(s,8,BigInt(e),t),n}function yt(e){return e.byteOffset%4===0}function lA(e){return Uint8Array.from(e)}var fs=e=>Uint8Array.from(e.split("").map(A=>A.charCodeAt(0))),ni=fs("expand 16-byte k"),si=fs("expand 32-byte k"),ri=K(ni),ii=K(si);function b(e,A){return e<>>32-A}function Qe(e){return e.byteOffset%4===0}var $t=64,oi=16,ps=2**32-1,ds=new Uint32Array;function ai(e,A,t,n,s,r,i,a){let o=s.length,h=new Uint8Array($t),l=K(h),u=Qe(s)&&Qe(r),c=u?K(s):ds,f=u?K(r):ds;for(let d=0;d=ps)throw new Error("arx: counter overflow");let g=Math.min($t,o-d);if(u&&g===$t){let m=d/4;if(d%4!==0)throw new Error("arx: invalid block position");for(let p=0,y;p{Q(a),Q(o),Q(h);let c=h.length;if(l===void 0&&(l=new Uint8Array(c)),Q(l),Wt(u),u<0||u>=ps)throw new Error("arx: counter overflow");if(l.lengthe[A++]&255|(e[A++]&255)<<8,He=class{constructor(A){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,A=hA(A),Q(A,32);let t=Y(A,0),n=Y(A,2),s=Y(A,4),r=Y(A,6),i=Y(A,8),a=Y(A,10),o=Y(A,12),h=Y(A,14);this.r[0]=t&8191,this.r[1]=(t>>>13|n<<3)&8191,this.r[2]=(n>>>10|s<<6)&7939,this.r[3]=(s>>>7|r<<9)&8191,this.r[4]=(r>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|a<<2)&8191,this.r[7]=(a>>>11|o<<5)&8065,this.r[8]=(o>>>8|h<<8)&8191,this.r[9]=h>>>5&127;for(let l=0;l<8;l++)this.pad[l]=Y(A,16+2*l)}process(A,t,n=!1){let s=n?0:2048,{h:r,r:i}=this,a=i[0],o=i[1],h=i[2],l=i[3],u=i[4],c=i[5],f=i[6],d=i[7],g=i[8],m=i[9],p=Y(A,t+0),y=Y(A,t+2),S=Y(A,t+4),_=Y(A,t+6),I=Y(A,t+8),J=Y(A,t+10),B=Y(A,t+12),v=Y(A,t+14),M=r[0]+(p&8191),C=r[1]+((p>>>13|y<<3)&8191),E=r[2]+((y>>>10|S<<6)&8191),T=r[3]+((S>>>7|_<<9)&8191),w=r[4]+((_>>>4|I<<12)&8191),x=r[5]+(I>>>1&8191),D=r[6]+((I>>>14|J<<2)&8191),P=r[7]+((J>>>11|B<<5)&8191),R=r[8]+((B>>>8|v<<8)&8191),O=r[9]+(v>>>5|s),k=0,L=k+M*a+C*(5*m)+E*(5*g)+T*(5*d)+w*(5*f);k=L>>>13,L&=8191,L+=x*(5*c)+D*(5*u)+P*(5*l)+R*(5*h)+O*(5*o),k+=L>>>13,L&=8191;let U=k+M*o+C*a+E*(5*m)+T*(5*g)+w*(5*d);k=U>>>13,U&=8191,U+=x*(5*f)+D*(5*c)+P*(5*u)+R*(5*l)+O*(5*h),k+=U>>>13,U&=8191;let z=k+M*h+C*o+E*a+T*(5*m)+w*(5*g);k=z>>>13,z&=8191,z+=x*(5*d)+D*(5*f)+P*(5*c)+R*(5*u)+O*(5*l),k+=z>>>13,z&=8191;let V=k+M*l+C*h+E*o+T*a+w*(5*m);k=V>>>13,V&=8191,V+=x*(5*g)+D*(5*d)+P*(5*f)+R*(5*c)+O*(5*u),k+=V>>>13,V&=8191;let rA=k+M*u+C*l+E*h+T*o+w*a;k=rA>>>13,rA&=8191,rA+=x*(5*m)+D*(5*g)+P*(5*d)+R*(5*f)+O*(5*c),k+=rA>>>13,rA&=8191;let iA=k+M*c+C*u+E*l+T*h+w*o;k=iA>>>13,iA&=8191,iA+=x*a+D*(5*m)+P*(5*g)+R*(5*d)+O*(5*f),k+=iA>>>13,iA&=8191;let oA=k+M*f+C*c+E*u+T*l+w*h;k=oA>>>13,oA&=8191,oA+=x*o+D*a+P*(5*m)+R*(5*g)+O*(5*d),k+=oA>>>13,oA&=8191;let aA=k+M*d+C*f+E*c+T*u+w*l;k=aA>>>13,aA&=8191,aA+=x*h+D*o+P*a+R*(5*m)+O*(5*g),k+=aA>>>13,aA&=8191;let pA=k+M*g+C*d+E*f+T*c+w*u;k=pA>>>13,pA&=8191,pA+=x*l+D*h+P*o+R*a+O*(5*m),k+=pA>>>13,pA&=8191;let mA=k+M*m+C*g+E*d+T*f+w*c;k=mA>>>13,mA&=8191,mA+=x*u+D*l+P*h+R*o+O*a,k+=mA>>>13,mA&=8191,k=(k<<2)+k|0,k=k+L|0,L=k&8191,k=k>>>13,U+=k,r[0]=L,r[1]=U,r[2]=z,r[3]=V,r[4]=rA,r[5]=iA,r[6]=oA,r[7]=aA,r[8]=pA,r[9]=mA}finalize(){let{h:A,pad:t}=this,n=new Uint16Array(10),s=A[1]>>>13;A[1]&=8191;for(let a=2;a<10;a++)A[a]+=s,s=A[a]>>>13,A[a]&=8191;A[0]+=s*5,s=A[0]>>>13,A[0]&=8191,A[1]+=s,s=A[1]>>>13,A[1]&=8191,A[2]+=s,n[0]=A[0]+5,s=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=A[a]+s,s=n[a]>>>13,n[a]&=8191;n[9]-=8192;let r=(s^1)-1;for(let a=0;a<10;a++)n[a]&=r;r=~r;for(let a=0;a<10;a++)A[a]=A[a]&r|n[a];A[0]=(A[0]|A[1]<<13)&65535,A[1]=(A[1]>>>3|A[2]<<10)&65535,A[2]=(A[2]>>>6|A[3]<<7)&65535,A[3]=(A[3]>>>9|A[4]<<4)&65535,A[4]=(A[4]>>>12|A[5]<<1|A[6]<<14)&65535,A[5]=(A[6]>>>2|A[7]<<11)&65535,A[6]=(A[7]>>>5|A[8]<<8)&65535,A[7]=(A[8]>>>8|A[9]<<5)&65535;let i=A[0]+t[0];A[0]=i&65535;for(let a=1;a<8;a++)i=(A[a]+t[a]|0)+(i>>>16)|0,A[a]=i&65535;F(n)}update(A){IA(this),A=hA(A),Q(A);let{buffer:t,blockLen:n}=this,s=A.length;for(let r=0;r>>0,A[r++]=n[i]>>>8;return A}digest(){let{buffer:A,outputLen:t}=this;this.digestInto(A);let n=A.slice(0,t);return this.destroy(),n}};function ci(e){let A=(n,s)=>e(s).update(hA(n)).digest(),t=e(new Uint8Array(32));return A.outputLen=t.outputLen,A.blockLen=t.blockLen,A.create=n=>e(n),A}var ms=ci(e=>new He(e));function Ss(e,A,t,n,s,r=20){let i=e[0],a=e[1],o=e[2],h=e[3],l=A[0],u=A[1],c=A[2],f=A[3],d=A[4],g=A[5],m=A[6],p=A[7],y=s,S=t[0],_=t[1],I=t[2],J=i,B=a,v=o,M=h,C=l,E=u,T=c,w=f,x=d,D=g,P=m,R=p,O=y,k=S,L=_,U=I;for(let V=0;V{e.update(A);let t=A.length%16;t&&e.update(di.subarray(t))},fi=new Uint8Array(32);function ys(e,A,t,n,s){let r=e(A,t,fi),i=ms.create(r);s&&gs(i,s),gs(i,n);let a=Xt(n.length,s?s.length:0,!0);i.update(a);let o=i.digest();return F(r,a),o}var Ms=e=>(A,t,n)=>({encrypt(r,i){let a=r.length;i=gt(a+16,i,!1),i.set(r);let o=i.subarray(0,-16);e(A,t,o,o,1);let h=ys(e,A,t,o,n);return i.set(h,a),F(h),i},decrypt(r,i){i=gt(r.length-16,i,!1);let a=r.subarray(0,-16),o=r.subarray(-16),h=ys(e,A,t,a,n);if(!jt(o,h))throw new Error("invalid tag");return i.set(r.subarray(0,-16)),e(A,t,i,i,1),F(h),i}}),Ke=mt({blockSize:64,nonceLength:12,tagLength:16},Ms(li)),oa=mt({blockSize:64,nonceLength:24,tagLength:16},Ms(ui));var EA=16,Ge=new Uint8Array(16),uA=K(Ge),pi=225,mi=(e,A,t,n)=>{let s=n&1;return{s3:t<<31|n>>>1,s2:A<<31|t>>>1,s1:e<<31|A>>>1,s0:e>>>1^pi<<24&-(s&1)}},eA=e=>(e>>>0&255)<<24|(e>>>8&255)<<16|(e>>>16&255)<<8|e>>>24&255|0;function gi(e){e.reverse();let A=e[15]&1,t=0;for(let n=0;n>>1|t,t=(s&1)<<7}return e[0]^=-A&225,e}var yi=e=>e>64*1024?8:e>1024?4:2,Ae=class{constructor(A,t){this.blockLen=EA,this.outputLen=EA,this.s0=0,this.s1=0,this.s2=0,this.s3=0,this.finished=!1,A=hA(A),Q(A,16);let n=XA(A),s=n.getUint32(0,!1),r=n.getUint32(4,!1),i=n.getUint32(8,!1),a=n.getUint32(12,!1),o=[];for(let d=0;d<128;d++)o.push({s0:eA(s),s1:eA(r),s2:eA(i),s3:eA(a)}),{s0:s,s1:r,s2:i,s3:a}=mi(s,r,i,a);let h=yi(t||1024);if(![1,2,4,8].includes(h))throw new Error("ghash: invalid window size, expected 2, 4 or 8");this.W=h;let u=128/h,c=this.windowSize=2**h,f=[];for(let d=0;d>>h-_-1&1))continue;let{s0:J,s1:B,s2:v,s3:M}=o[h*d+_];m^=J,p^=B,y^=v,S^=M}f.push({s0:m,s1:p,s2:y,s3:S})}this.t=f}_updateBlock(A,t,n,s){A^=this.s0,t^=this.s1,n^=this.s2,s^=this.s3;let{W:r,t:i,windowSize:a}=this,o=0,h=0,l=0,u=0,c=(1<>>8*g&255;for(let p=8/r-1;p>=0;p--){let y=m>>>r*p&c,{s0:S,s1:_,s2:I,s3:J}=i[f*a+y];o^=S,h^=_,l^=I,u^=J,f+=1}}this.s0=o,this.s1=h,this.s2=l,this.s3=u}update(A){IA(this),A=hA(A),Q(A);let t=K(A),n=Math.floor(A.length/EA),s=A.length%EA;for(let r=0;re(s,n.length).update(hA(n)).digest(),t=e(new Uint8Array(16),0);return A.outputLen=t.outputLen,A.blockLen=t.blockLen,A.create=(n,s)=>e(n,s),A}var Ze=Cs((e,A)=>new Ae(e,A)),Si=Cs((e,A)=>new Fe(e,A));var qe=16,Mi=4,te=new Uint8Array(qe),Ci=283;function Ve(e){return e<<1^Ci&-(e>>7)}function ws(e,A){let t=0;for(;A>0;A>>=1)t^=e&-(A&1),e=Ve(e);return t}var wi=(()=>{let e=new Uint8Array(256);for(let t=0,n=1;t<256;t++,n^=Ve(n))e[t]=n;let A=new Uint8Array(256);A[0]=99;for(let t=0;t<255;t++){let n=e[255-t];n|=n<<8,A[e[t]]=(n^n>>4^n>>5^n>>6^n>>7^99)&255}return F(e),A})();var ki=e=>e<<24|e>>>8,Ye=e=>e<<8|e>>>24;function _i(e,A){if(e.length!==256)throw new Error("Wrong sbox length");let t=new Uint32Array(256).map((h,l)=>A(e[l])),n=t.map(Ye),s=n.map(Ye),r=s.map(Ye),i=new Uint32Array(256*256),a=new Uint32Array(256*256),o=new Uint16Array(256*256);for(let h=0;h<256;h++)for(let l=0;l<256;l++){let u=h*256+l;i[u]=t[h]^n[l],a[u]=s[h]^r[l],o[u]=e[h]<<8|e[l]}return{sbox:e,sbox2:o,T0:t,T1:n,T2:s,T3:r,T01:i,T23:a}}var _s=_i(wi,e=>ws(e,3)<<24|e<<16|e<<8|ws(e,2));var xi=(()=>{let e=new Uint8Array(16);for(let A=0,t=1;A<16;A++,t=Ve(t))e[A]=t;return e})();function Ei(e){Q(e);let A=e.length;if(![16,24,32].includes(A))throw new Error("aes: invalid key size, should be 16, 24 or 32, got "+A);let{sbox2:t}=_s,n=[];yt(e)||n.push(e=lA(e));let s=K(e),r=s.length,i=o=>St(t,o,o,o,o),a=new Uint32Array(A+28);a.set(s);for(let o=r;o6&&o%r===4&&(h=i(h)),a[o]=a[o-r]^h}return F(...n),a}function ee(e,A,t,n,s,r){return e[t<<8&65280|n>>>8&255]^A[s>>>8&65280|r>>>24&255]}function St(e,A,t,n,s){return e[A&255|t&65280]|e[n>>>16&255|s>>>16&65280]<<16}function ks(e,A,t,n,s){let{sbox2:r,T01:i,T23:a}=_s,o=0;A^=e[o++],t^=e[o++],n^=e[o++],s^=e[o++];let h=e.length/4-2;for(let d=0;d>>0,a.setUint32(l,c,A),{s0:f,s1:d,s2:g,s3:m}=ks(e,i[0],i[1],i[2],i[3]);let p=qe*Math.floor(o.length/Mi);if(pHA.getSharedSecret(e,A),Ts=e=>HA.getPublicKey(e),Ds=()=>{let e=HA.utils.randomSecretKey();return{privateKey:e,publicKey:HA.getPublicKey(e)}},$A={chacha:{name:"ChaChaPoly",dhLen:32,dh:bs,generateKeypair:Ds,publicKey:Ts,hash:j,aeadEncrypt:(e,A,t,n)=>Ke(e,xs(A),t).encrypt(n),aeadDecrypt:(e,A,t,n)=>Ke(e,xs(A),t).decrypt(n)},aesgcm:{name:"AESGCM",dhLen:32,dh:bs,generateKeypair:Ds,publicKey:Ts,hash:j,aeadEncrypt:(e,A,t,n)=>We(e,Es(A),t).encrypt(n),aeadDecrypt:(e,A,t,n)=>We(e,Es(A),t).decrypt(n)}},Is={chacha:"25519_ChaChaPoly_SHA256",aesgcm:"25519_AESGCM_SHA256"};function H(e){let A="";for(let t=0;ts?A.create().update(n).digest():n);for(let i=0;inew re(e,A).update(t).digest();JA.create=(e,A)=>new re(e,A);var Rs=new Uint8Array(0),et=class{constructor(A){this.suite=A,this.k=null,this.n=0n}initializeKey(A){this.k=A,this.n=0n}hasKey(){return this.k!==null}encryptWithAd(A,t){if(this.k===null)return t;let n=this.suite.aeadEncrypt(this.k,this.n,A,t);return this.n+=1n,n}decryptWithAd(A,t){if(this.k===null)return t;let n=this.suite.aeadDecrypt(this.k,this.n,A,t);return this.n+=1n,n}};var Os=32;function tn(e,A,t){let n=JA(j,e,A),s=JA(j,n,Uint8Array.of(1)),r=JA(j,n,en(s,Uint8Array.of(2)));if(t===2)return[s,r];let i=JA(j,n,en(r,Uint8Array.of(3)));return[s,r,i]}function en(...e){let A=e.reduce((s,r)=>s+r.length,0),t=new Uint8Array(A),n=0;for(let s of e)t.set(s,n),n+=s.length;return t}var ie=class{constructor(A){this.suite=A,this.cipher=new et(A)}initialize(A){let t=new TextEncoder().encode(A);if(t.length<=Os){let n=new Uint8Array(Os);n.set(t),this.h=n}else this.h=this.suite.hash(t);this.ck=this.h,this.cipher.initializeKey(null)}mixHash(A){this.h=this.suite.hash(en(this.h,A))}mixKey(A){let[t,n]=tn(this.ck,A,2);this.ck=t,this.cipher.initializeKey(n.slice(0,32))}mixKeyAndHash(A){let[t,n,s]=tn(this.ck,A,3);this.ck=t,this.mixHash(n),this.cipher.initializeKey(s.slice(0,32))}encryptAndHash(A){let t=this.cipher.encryptWithAd(this.h,A);return this.mixHash(t),t}decryptAndHash(A){let t=this.cipher.decryptWithAd(this.h,A);return this.mixHash(A),t}split(){let[A,t]=tn(this.ck,Rs,2),n=new et(this.suite),s=new et(this.suite);return n.initializeKey(A.slice(0,32)),s.initializeKey(t.slice(0,32)),[n,s]}};var sn=["e","es","ss"],rn=["e","ee","se","psk"];function nn(e,A){let t=new Uint8Array(e.length+A.length);return t.set(e,0),t.set(A,e.length),t}var Mt=class{constructor(A){this.suite=A.suite,this.role=A.role,this.s=A.s,this.rs=A.rs,this.psk=A.psk,this.fixedEphemeral=A.fixedEphemeral,this.sym=new ie(A.suite),this.sym.initialize(`Noise_KKpsk2_25519_${A.suite.name}_SHA256`),this.sym.mixHash(A.prologue);let t=A.role==="initiator"?A.s.publicKey:A.rs,n=A.role==="responder"?A.s.publicKey:A.rs;this.sym.mixHash(t),this.sym.mixHash(n)}get handshakeHash(){return this.sym.h}setPsk(A){this.psk=A}dhToken(A){let t=this.role==="initiator";switch(A){case"ee":return this.suite.dh(this.e.privateKey,this.re);case"ss":return this.suite.dh(this.s.privateKey,this.rs);case"es":return t?this.suite.dh(this.e.privateKey,this.rs):this.suite.dh(this.s.privateKey,this.re);case"se":return t?this.suite.dh(this.s.privateKey,this.re):this.suite.dh(this.e.privateKey,this.rs)}}processTokenWrite(A,t){A==="e"?(this.e=this.fixedEphemeral??this.suite.generateKeypair(),this.sym.mixHash(this.e.publicKey),this.sym.mixKey(this.e.publicKey),t.buf=nn(t.buf,this.e.publicKey)):A==="s"?t.buf=nn(t.buf,this.sym.encryptAndHash(this.s.publicKey)):A==="psk"?this.sym.mixKeyAndHash(this.psk):this.sym.mixKey(this.dhToken(A))}processTokenRead(A,t){if(A==="e")this.re=t.buf.slice(0,this.suite.dhLen),t.buf=t.buf.slice(this.suite.dhLen),this.sym.mixHash(this.re),this.sym.mixKey(this.re);else if(A==="s"){let n=this.suite.dhLen+16;this.sym.decryptAndHash(t.buf.slice(0,n)),t.buf=t.buf.slice(n)}else A==="psk"?this.sym.mixKeyAndHash(this.psk):this.sym.mixKey(this.dhToken(A))}writeMessage(A,t){let n={buf:new Uint8Array(0)};for(let s of A)this.processTokenWrite(s,n);return n.buf=nn(n.buf,this.sym.encryptAndHash(t)),n.buf}readMessage(A,t){let n={buf:t};for(let s of A)this.processTokenRead(s,n);return this.sym.decryptAndHash(n.buf)}split(){return this.sym.split()}};var Ls=new Uint8Array(0),Ct=class{constructor(A,t){let[n,s]=t;A==="initiator"?(this.sendCs=n,this.recvCs=s):(this.sendCs=s,this.recvCs=n)}encrypt(A){return this.sendCs.encryptWithAd(Ls,A)}decrypt(A){return this.recvCs.decryptWithAd(Ls,A)}};function Us(e,A,t){if(e==="long_term"){if(A.has("pairing"))return A.size===1;for(let n of A)if(n!=="playback"&&n!=="management")return!1;return!0}return e==="pairing"?A.size===1&&A.has("pairing"):A.size===0||A.size===1&&A.has("pairing")?!0:A.size===1&&A.has("playback")?t:!1}function zs(e,A,t,n){if(!Us(e,A,n))return!1;if(t){let s=new Set(A);if(s.add("playback"),!Us(e,s,n))return!1}return!0}function Qs(e,A,t,n){let s=new Set(A),r=!!t&&t.length>0;return zs(e,s,r,n)?{ok:!0}:e==="sentinel"&&!n&&zs(e,s,r,!0)?{ok:!1,goodbye:"pairing_required"}:{ok:!1,goodbye:"unauthorized"}}var wt=new TextEncoder,oe=new TextDecoder,Ti=3e4,Ks=65519,Di=Ks+16,Ns=4*1024*1024;function Hs(e,A){let t=new Uint8Array(e.length+A.length);return t.set(e,0),t.set(A,e.length),t}var kt=class e{constructor(A,t,n){this.wsManager=A,this.deps=t,this.cb=n,this.state="idle",this.hs=null,this.session=null,this.matched=null,this.serverId="",this.rawClientInit=new Uint8Array(0),this.rawServerInit=new Uint8Array(0),this.timeout=null,this.frag=null,this.lastHandshakeHash=new Uint8Array(0),this.quiesced=!1,this.outboundQueue=[],this.seenActivate=!1,this.effectiveActiveRoles=void 0}get suite(){return $A[this.deps.suiteId]}get ready(){return this.state==="transport"}get handshakeInfo(){return this.matched?{trustLevel:this.matched.category==="long_term"?"user":"none",category:this.matched.category,serverId:this.serverId,entry:this.matched}:null}get handshakeHash(){return this.lastHandshakeHash}start(){this.resetSession();let A=JSON.stringify({type:"client/init",payload:{client_id:this.deps.identity.clientId,version:1,suite:Is[this.deps.suiteId]}});this.rawClientInit=wt.encode(A),this.wsManager.sendText(A),this.state="await_server_init",this.armTimeout()}resetSession(){this.hs=null,this.session=null,this.matched=null,this.frag=null,this.serverId="",this.rawServerInit=new Uint8Array(0),this.quiesced=!1,this.outboundQueue=[],this.lastHandshakeHash=new Uint8Array(0),this.seenActivate=!1,this.effectiveActiveRoles=void 0}onSocketClosed(){this.clearTimeout(),this.resetSession(),this.state="idle"}close(){this.clearTimeout(),this.wsManager.disconnect()}handleRaw(A){if(this.state==="transport"){if(typeof A.data=="string")return this.fail();let t;try{let n=new Uint8Array(A.data);if(n.length>Di)return this.fail();t=this.session.decrypt(n)}catch{return this.fail()}if(t.length<1)return this.fail();try{this.dispatchPlain(t)}catch(n){console.warn("Sendspin: dropped malformed transport message",n)}return}try{if(typeof A.data!="string")return this.fail();this.handleHandshakeText(A.data)}catch{this.fail()}}handleHandshakeText(A){let t=JSON.parse(A);if(this.state==="await_server_init"&&t.type==="server/init"){if(t.payload.version!==1)return this.fail();this.serverId=String(t.payload.server_id),this.rawServerInit=wt.encode(A),this.hs=new Mt({suite:this.suite,role:"responder",prologue:Hs(this.rawClientInit,this.rawServerInit),s:this.deps.identity.keypair,rs:q(this.serverId)}),this.state="await_noise1",this.armTimeout();return}if(this.state==="await_noise1"&&t.type==="noise/handshake"){this.processNoise1(q(String(t.payload.data)));return}this.fail()}processNoise1(A){let t=this.hs.readMessage(sn,A),{psk_id:n}=JSON.parse(oe.decode(t)),s=this.deps.pskStore.lookup(n);if(!s)return this.fail();if(s.category==="long_term"&&s.serverId!==void 0&&s.serverId!==this.serverId)return this.fail();this.hs.setPsk(s.psk);let r=this.hs.writeMessage(rn,wt.encode("{}"));this.wsManager.sendText(JSON.stringify({type:"noise/handshake",payload:{data:H(r)}})),this.session=new Ct("responder",this.hs.split()),this.matched=s,this.state="transport",this.clearTimeout(),this.lastHandshakeHash=this.hs.handshakeHash,this.cb.onHandshakeComplete(this.handshakeInfo)}dispatchPlain(A){let t=A[0];t===0?this.handleControl(JSON.parse(oe.decode(A.subarray(1)))):t===2||t===3?this.handleFragment(t,A.subarray(1)):this.cb.onBinaryMessage(A)}handleFragment(A,t){if(A===2&&this.frag===null){if(t.length<1)return this.fail();if(t[0]===2||t[0]===3)return this.fail();let i=t.subarray(1);this.frag={origType:t[0],parts:[i],size:i.length};return}if(A===2)return this.frag.parts.push(t),this.frag.size+=t.length,this.frag.size>Ns?(this.frag=null,this.fail()):void 0;if(this.frag===null)return this.fail();if(this.frag.parts.push(t),this.frag.size+=t.length,this.frag.size>Ns)return this.frag=null,this.fail();let n=this.frag.origType,s=new Uint8Array(this.frag.size+1);s[0]=n;let r=1;for(let i of this.frag.parts)s.set(i,r),r+=i.length;this.frag=null,n===0?this.handleControl(JSON.parse(oe.decode(s.subarray(1)))):this.cb.onBinaryMessage(s)}handleControl(A){if(A.type==="noise/handshake"){this.handleRehandshake(A);return}if(A.type==="server/activate"){this.handleActivate(A);return}if(A.type==="server/unpair"){this.handleUnpair();return}this.cb.onControlMessage(A)}handleRehandshake(A){let t=new Mt({suite:this.suite,role:"responder",prologue:this.lastHandshakeHash,s:this.deps.identity.keypair,rs:q(this.serverId)}),n=t.readMessage(sn,q(A.payload.data)),{psk_id:s}=JSON.parse(oe.decode(n)),r=this.deps.pskStore.lookup(s);if(!r)return this.fail();if(r.category==="long_term"&&r.serverId!==void 0&&r.serverId!==this.serverId)return this.fail();t.setPsk(r.psk);let i=t.writeMessage(rn,wt.encode("{}"));this.quiesced=!0,this.armTimeout(),this.encryptSend({type:"noise/handshake",payload:{data:H(i)}}),this.session=new Ct("responder",t.split()),this.matched=r,this.lastHandshakeHash=t.handshakeHash,this.seenActivate=!1,this.effectiveActiveRoles=void 0,this.cb.onHandshakeComplete(this.handshakeInfo)}handleActivate(A){let t=A.payload.active_roles;if(!this.seenActivate&&t===void 0){this.sendGoodbyeAndClose("unauthorized");return}t!==void 0&&(this.effectiveActiveRoles=t),this.seenActivate=!0;let n=Qs(this.matched.category,A.payload.activities,this.effectiveActiveRoles,this.deps.unpairedAccess);if(!n.ok){this.sendGoodbyeAndClose(n.goodbye);return}this.clearTimeout();let s=!A.payload.activities.includes("pairing")&&this.effectiveActiveRoles?.includes("controller@v1")?this.outboundQueue.filter(r=>r.type==="client/command"):[];this.quiesced=!1,this.outboundQueue=[],this.cb.onControlMessage(A);for(let r of s)this.encryptSend(r)}handleUnpair(){this.matched?.category==="long_term"&&(this.deps.pskStore.removeByPskId(this.matched.pskId),this.sendGoodbyeAndClose("unpaired"))}sendGoodbyeAndClose(A){try{this.encryptSend({type:"client/goodbye",payload:{reason:A}})}catch{}this.close()}sendControl(A){if(this.state!=="transport"||!this.session){console.warn("Sendspin: sendControl before transport ready");return}let t=A.type;if(this.quiesced&&t!==void 0&&e.QUIESCED_TYPES.has(t)){this.outboundQueue.push(A);return}this.encryptSend(A)}encryptSend(A){let t=wt.encode(JSON.stringify(A)),n=Hs(Uint8Array.of(0),t);if(n.length>Ks)throw new Error("Sendspin: control message exceeds single-frame limit");this.wsManager.sendBinary(this.session.encrypt(n))}armTimeout(){this.clearTimeout(),this.timeout=globalThis.setTimeout(()=>this.fail(),Ti)}clearTimeout(){this.timeout!==null&&(clearTimeout(this.timeout),this.timeout=null)}fail(){this.clearTimeout(),this.wsManager.disconnect()}};kt.QUIESCED_TYPES=new Set(["client/command","client/time","client/state"]);var dA=2n**255n-19n,on=486662n,vi=2n,ae=32,ce=32,qs=64,Fs=cn("CPace255"),Ii=cn("CPace255_ISK"),Ji=cn("CPaceMac"),Bi=128,fA=class extends Error{};function cn(e){return new TextEncoder().encode(e)}function xt(...e){let A=new Uint8Array(e.reduce((n,s)=>n+s.length,0)),t=0;for(let n of e)A.set(n,t),t+=n.length;return A}function an(e){let A=e.length,t=[];for(;t.push(A<128?A:A&127|128),A>>=7,A!==0;);return xt(new Uint8Array(t),e)}function _t(...e){return xt(...e.map(an))}function Pi(e,A,t){let n=Math.max(0,Bi-1-an(e).length-an(Fs).length);return _t(Fs,e,new Uint8Array(n),A,t)}function FA(e,A){let t=e%A;return t<0n?t+A:t}function Vs(e,A,t){let n=1n,s=FA(e,t),r=A;for(;r>0n;)r&1n&&(n=n*s%t),s=s*s%t,r>>=1n;return n}function Gs(e,A){return Vs(e,A-2n,A)}function Ri(e){let A=e.slice();A[A.length-1]&=127;let t=0n;for(let n=A.length-1;n>=0;n--)t=t<<8n|BigInt(A[n]);return t}function Oi(e){let A=new Uint8Array(ae),t=e;for(let n=0;n>=8n;return A}function Li(e){let A=FA(e,dA),t=FA(-on*Gs(FA(1n+vi*A*A,dA),dA),dA),n=Vs(FA(t*t*t+on*t*t+t,dA),(dA-1n)/2n,dA),s=FA(n*t-FA(1n-n,dA)*on*Gs(2n,dA),dA);return Oi(s)}function Ui(e,A,t){let n=UA(Pi(e,A,t)).slice(0,ae);return Li(Ri(n))}function Zs(e,A,t){let n;try{n=HA.scalarMult(e,A)}catch{throw new fA(`${t} encodes a low-order point`)}if(n.every(s=>s===0))throw new fA(`${t} encodes a low-order point`);return n}function Ys(e,A){if(e.length!==A.length)return!1;let t=0;for(let n=0;nnew TextEncoder().encode(e);function Ni(...e){let A=new Uint8Array(e.reduce((n,s)=>n+s.length,0)),t=0;for(let n of e)A.set(n,t),t+=n.length;return A}var Hi="sendspin-pair-pake-v1",Ki=le("sendspin-pair-psk-wrap-v1"),er=le("server"),nr=le("client"),Fi=12e4,Gi=3e5,Zi=10,Yi=6,sr="sendspin-pair-failures",qi=["dynamic_pin","static_pin"];function rr(e,A){return A?.length?{...e,locations:A}:e}function Vi(e){if(!(!Array.isArray(e)||e.length===0))return e.every(A=>typeof A=="string"&&A!=="")?e:void 0}var he=class{constructor(A){if(this.deps=A,this.pendingPsk=null,this.phase="idle",this.method=null,this.cpace=null,this.nonceB=null,this.attemptTimer=null,this.windowTimer=null,this.windowOpen=!1,this.currentSid=null,this.pairingActivateCount=0,this.attemptIndex=0,this.pinLength=null,A.staticPin!==void 0&&!Xs(A.staticPin))throw new Error("staticPin must be exactly 8 decimal digits");this.minPinLength=Math.min(un,Math.max(Ws,A.minPinLength??js)),!A.storage&&A.onPin&&console.warn("sendspin: dynamic PIN pairing is enabled without storage, so the failure counter will not persist across reboots."),this.failures=this.loadFailures()}descriptors(){let A=[rr({method:"pairing_psk"},this.deps.pairingPskLocations)];return this.deps.staticPin!==void 0&&A.push(rr({method:"static_pin"},this.deps.staticPinLocations)),this.deps.onPin&&A.push({method:"dynamic_pin",out_channels:this.deps.pinOutChannels??["display"],min_pin_length:this.minPinLength}),A}isDynamicPinEscalated(){return this.failures>=Zi}openPairingWindow(){if(this.phase==="await-window"){this.startAttempt();return}this.windowOpen=!0,this.windowTimer&&clearTimeout(this.windowTimer),this.windowTimer=setTimeout(()=>this.closeWindow(),Gi)}closeWindow(){this.windowOpen=!1,this.windowTimer&&clearTimeout(this.windowTimer),this.windowTimer=null}cancelPairing(){this.phase!=="idle"&&this.abort("user_cancelled")}onActivate(A,t){if(!A.includes("pairing"))return this.abandonAttempt("server_cancelled"),!1;this.abandonAttempt("superseded"),this.pairingActivateCount+=1,this.attemptIndex=this.pairingActivateCount;let s=t?.method,r=this.descriptors().map(a=>a.method),i=s==="pairing_psk"==(this.deps.matchedCategory()==="pairing");if(!s)return console.warn("sendspin: server/activate carried no pairing method, so the server is not speaking the current specification."),this.fail(),!0;if(!i||!r.includes(s))return this.abort("method_not_supported"),!0;if(this.method=s,s==="pairing_psk")return this.sendFinalize(),this.phase="await-finalize",this.armAttemptTimer(),this.deps.onEvent?.("started"),!0;if(s==="dynamic_pin"){let a=t.pin_length;if(typeof a!="number"||!Number.isInteger(a))return this.fail(),!0;if(aun)return this.abort("pin_length_unacceptable"),!0;this.pinLength=a,this.languages=Vi(t.languages)}return this.isGestureGated()&&!this.windowOpen?(this.phase="await-window",this.deps.sendControl({type:"client/pair-pending",payload:{pairing_index:this.attemptIndex}}),this.deps.onEvent?.("pending"),!0):(this.startAttempt(),!0)}isGestureGated(){return this.method==="static_pin"?!0:this.method!=="dynamic_pin"?!1:this.isDynamicPinEscalated()||this.pinLengththis.abort("attempt_timeout"),Fi)}abort(A){this.clearAttempt(),this.deps.sendControl({type:"pair/abort",payload:{reason:A}}),this.deps.onEvent?.("aborted",A),A==="concurrent_attempt"&&this.deps.close()}fail(){this.clearAttempt(),this.deps.close()}clearAttempt(){this.attemptTimer&&clearTimeout(this.attemptTimer),this.attemptTimer=null,this.method&&qi.includes(this.method)&&this.deps.onPin?.(null),this.pendingPsk=null,this.phase="idle",this.method=null,this.cpace=null,this.currentSid=null,this.nonceB=null,this.pinLength=null,this.languages=void 0}abandonAttempt(A){this.phase==="idle"&&!this.pendingPsk||(this.clearAttempt(),this.deps.onEvent?.("aborted",A))}decode(A,t){if(typeof A!="string")return null;try{let n=q(A);return n.length===t?n:null}catch{return null}}loadFailures(){try{let A=this.deps.storage?.getItem(sr);return A?JSON.parse(A).dynamic_pin??0:0}catch{return 0}}saveFailures(){this.deps.storage?.setItem(sr,JSON.stringify({dynamic_pin:this.failures}))}recordFailure(){this.failures+=1,this.saveFailures()}resetFailures(){this.failures=0,this.saveFailures()}};var ir="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",ue=32;function Wi(e){let A=0,t=0,n="";for(let s of e){for(t=t<<8|s,A+=8;A>=5;)n+=ir[t>>>A-5&31],A-=5;t&=(1<0&&(n+=ir[t<<5-A&31]),n}function de(e,A){let t=q(e),n=q(A);if(t.length!==ue)throw new Error(`clientId must decode to ${ue} bytes`);if(n.length!==ue)throw new Error(`pairingPsk must decode to ${ue} bytes`);let s=new Uint8Array(t.length+n.length);return s.set(t),s.set(n,t.length),`SP:0${Wi(s).replace(/2/g,"9")}`}var Tt=class{constructor(A){this.handshakeInfo=null,A.codecs&&It(A.codecs),this.hasStorage=(A.storage??null)!==null,this.identity=At.loadOrCreate(A.storage??null);let t=A.clientName??`Sendspin JS Client (${this.identity.clientId.slice(0,6)})`;this.config={...A,clientName:t},this.delayStore=new Ot(A.storage??null);let n=this.delayStore.load(),s=A.syncDelay??n??A.defaultSyncDelay??0;this._syncDelayMs=gA(s),this.timeFilter=new nt(0,1.1,2,1e-12),this.stateManager=new Pt(A.onStateChange),this.decoder=new GA(i=>this._onAudioData?.(i),()=>this.stateManager.streamGeneration),this.wsManager=new Rt(A.reconnect),this.pskStore=new tt(A.storage??null);for(let i of A.longTermPsks??[])this.pskStore.addLongTerm(q(i.psk),i.serverId);this.hasStorage&&this.pskStore.getOrCreatePairingPsk(),this.transport=new kt(this.wsManager,{identity:this.identity,pskStore:this.pskStore,suiteId:A.suite??"chacha",unpairedAccess:A.unpairedAccess??!0},{onHandshakeComplete:i=>{let a=this.handshakeInfo!==null;this.handshakeInfo=i,this.pairing.reset(),this.protocolHandler.resetActivation(a)},onControlMessage:i=>this.routeControl(i),onBinaryMessage:i=>this.handleBinaryMessage(i.buffer)}),this.pairing=new he({sendControl:i=>this.transport.sendControl(i),close:()=>this.transport.close(),pskStore:this.pskStore,serverId:()=>this.handshakeInfo?.serverId??"",matchedCategory:()=>this.handshakeInfo?.category??"sentinel",handshakeHash:()=>this.transport.handshakeHash,aeadSeal:(i,a)=>$A[A.suite??"chacha"].aeadEncrypt(i,0n,new Uint8Array(0),a),storage:A.storage??null,onPin:A.onPairingPin??null,pinOutChannels:A.pinOutChannels,minPinLength:A.minPinLength,staticPin:A.staticPin,staticPinLocations:A.staticPinLocations,pairingPskLocations:A.pairingPskLocations,onEvent:(i,a)=>this.config.onPairing?.(i,a)});let r={trustLevel:()=>this.handshakeInfo?.trustLevel??"none",pairMethods:()=>this.hasStorage?this.pairing.descriptors():[],unpairedAccess:A.unpairedAccess??!0};this.protocolHandler=new Bt(this.transport,r,this,this.stateManager,this.timeFilter,{clientName:t,productName:A.productName,codecs:A.codecs,bufferCapacity:A.bufferCapacity,requiredLeadTimeMs:A.requiredLeadTimeMs,minBufferMs:A.minBufferMs,useHardwareVolume:A.useHardwareVolume,onVolumeCommand:A.onVolumeCommand,onDelayCommand:A.onDelayCommand,getExternalVolume:A.getExternalVolume})}routeControl(A){if(A.type==="server/activate"){let t=A.payload??{};t.activities?.includes("pairing")&&this.protocolHandler.suspendForPairing(),this.pairing.onActivate(t.activities??[],t.pairing)||this.protocolHandler.handleServerMessage(A);return}if(A.type==="server/pair-init")return this.pairing.onPairInit(A.payload??{});if(A.type==="server/pair-auth")return this.pairing.onPairAuth(A.payload??{});if(A.type==="server/pair-confirm")return this.pairing.onPairConfirm(A.payload??{});if(A.type==="server/pair-finalize")return this.pairing.onPairFinalize();if(A.type==="pair/abort")return this.pairing.onAbort((A.payload??{}).reason??"");this.protocolHandler.handleServerMessage(A)}onTransportClose(){this.transport.onSocketClosed(),this.handshakeInfo=null,this.protocolHandler.stopTimeSync(),this.protocolHandler.resetActivation(),this.pairing.reset(),this.stateManager.clearStateUpdateInterval(),console.log("Sendspin: Connection closed"),this._onConnectionClose?.()}handleBinaryMessage(A){let t=this.stateManager.currentStreamFormat;if(!t){console.warn("Sendspin: Received audio chunk but no stream format set");return}let n=this.stateManager.streamGeneration;this.decoder.handleBinaryMessage(A,t,n)}handleStreamStart(A,t){t||this.decoder.clearState(),this._onStreamStart?.(A,t)}handleStreamClear(){this.decoder.clearState(),this._onStreamClear?.()}handleStreamEnd(){this.decoder.clearState(),this._onStreamEnd?.()}handleVolumeUpdate(){this._onVolumeUpdate?.()}applyDelay(A){this._syncDelayMs=gA(A),this.delayStore.save(this._syncDelayMs),this._onSyncDelayChange?.(this._syncDelayMs)}handleSyncDelayChange(A){this.applyDelay(A)}getSyncDelayMs(){return this._syncDelayMs}set onAudioData(A){this._onAudioData=A}set onStreamStart(A){this._onStreamStart=A}set onStreamClear(A){this._onStreamClear=A}set onStreamEnd(A){this._onStreamEnd=A}set onVolumeUpdate(A){this._onVolumeUpdate=A}set onSyncDelayChange(A){this._onSyncDelayChange=A}set onConnectionOpen(A){this._onConnectionOpen=A}set onConnectionClose(A){this._onConnectionClose=A}async connect(){let A=()=>{this._onConnectionOpen?.(),this.transport.start()},t=r=>{this.transport.handleRaw(r)},n=r=>{console.error("Sendspin: WebSocket error",r)},s=()=>this.onTransportClose();if(this.config.webSocket)await this.wsManager.adopt(this.config.webSocket,A,t,n,s);else{if(!this.config.baseUrl)throw new Error("SendspinCore requires either baseUrl or webSocket to be provided.");let r=new URL(this.config.baseUrl,typeof window<"u"?window.location.href:void 0),i=r.protocol==="https:"?"wss:":"ws:",a=r.pathname.replace(/\/$/,""),o=a.endsWith("/sendspin")?`${i}//${r.host}${a}`:`${i}//${r.host}${a}/sendspin`;await this.wsManager.connect(o,A,t,n,s)}}resetPlaybackState(){this.stateManager.isPlaying=!1,this.stateManager.currentStreamFormat=null}disconnect(A="restart"){this.transport.ready&&this.protocolHandler.sendGoodbye(A),this.protocolHandler.stopTimeSync(),this.stateManager.clearAllIntervals(),this.wsManager.disconnect(),this.decoder.close(),this.timeFilter.reset(),this.stateManager.reset()}setVolume(A){this.stateManager.volume=A,this._onVolumeUpdate?.(),this.protocolHandler.sendStateUpdate()}setMuted(A){this.stateManager.muted=A,this._onVolumeUpdate?.(),this.protocolHandler.sendStateUpdate()}setSyncDelay(A){this.applyDelay(A),this.protocolHandler.sendStateUpdate()}setRequiredLeadTimeMs(A){this.protocolHandler.setRequiredLeadTimeMs(A)}setMinBufferMs(A){this.protocolHandler.setMinBufferMs(A)}sendCommand(A,t){let n=this.stateManager.serverState.controller?.supported_commands;if(n&&!n.includes(A))throw new Error(`Command '${A}' is not supported by the server. Supported commands: ${n.join(", ")}`);this.protocolHandler.sendCommand(A,t)}get isPlaying(){return this.stateManager.isPlaying}get volume(){return this.stateManager.volume}get muted(){return this.stateManager.muted}get playerState(){return this.stateManager.playerState}get currentFormat(){return this.stateManager.currentStreamFormat}get isConnected(){return this.wsManager.isConnected()}get clientId(){return this.identity.clientId}get pairingPsk(){return this.hasStorage?H(this.pskStore.getOrCreatePairingPsk()):null}get pairingToken(){let A=this.pairingPsk;return A?de(this.clientId,A):null}rotatePairingPsk(){return this.hasStorage?(this.pskStore.rotatePairingPsk(),this.pairingPsk):null}openPairingWindow(){this.pairing.openPairingWindow()}cancelPairing(){this.pairing.cancelPairing()}isDynamicPinEscalated(){return this.pairing.isDynamicPinEscalated()}get timeSyncInfo(){return{synced:this.timeFilter.is_synchronized,offset:Math.round(this.timeFilter.offset/1e3),error:Math.round(this.timeFilter.error/1e3)}}getCurrentServerTimeUs(){return this.timeFilter.computeServerTime(Math.floor(performance.now()*1e3))}get trackProgress(){let A=this.stateManager.serverState.metadata;if(!A?.progress||A.timestamp===void 0)return null;let n=this.getCurrentServerTimeUs()-A.timestamp,s=A.progress.track_progress+n*A.progress.playback_speed/1e6,r=A.progress.track_duration;return{positionMs:r===0?Math.max(0,s):Math.max(0,Math.min(s,r)),durationMs:r,playbackSpeed:A.progress.playback_speed/1e3}}get _stateManager(){return this.stateManager}get _timeFilter(){return this.timeFilter}};var Dt=8,ji=1,Xi=Math.min(1,2*ji/Dt),$i=new Float32Array(Dt);for(let e=0;e