The previous commit gated the on-load discovery sweep to a cold start,
but a second, redundant DOMContentLoaded handler still called
triggerDiscovery() ungated on every admin load, so /admin kept kicking
off a full sweep (and its reseed) even with devices already known. The
second handler only duplicated fetchDevices + fetchSettings + the
ungated trigger, all of which the first (gated) handler already does, so
remove it outright. That also drops the duplicate per-device live /info
refresh the second handler caused.
Also drop two em dashes (a code comment and the landing meta description).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The admin console ran a full discovery sweep on every page load whenever
discovery was enabled (DOMContentLoaded -> triggerDiscovery). With devices
already in the datastore, that re-probed every host (including offline
ones) on each visit, which felt slow and surprising.
Gate the on-load sweep on a cold start only: fetch the cached device list
first, and trigger discovery just when it is empty. With devices known,
rely on the cached list, the periodic sweep, and the explicit Discover
button. fetchDevices now returns the device count for that check.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
SeedExtraDevices probed each datastore host serially via AddDeviceByHost,
whose /info call blocks up to its 10 s timeout for an unknown host. With
offline speakers in the datastore, a re-sync (e.g. the admin page's
discovery sweep on load, or the periodic discovery) stalled for 10 s per
offline device, one after another.
Fan the per-host probes out across goroutines and wait for all of them,
so the seed costs roughly a single timeout regardless of how many devices
are offline. AddDeviceByHost is already registry-safe under concurrency
(covered by TestRegistryConcurrent).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Post-merge, "/" was the admin console with a small text link to the
player. This makes "/" a neutral chooser and unifies the chrome across
all three surfaces (landing, player, admin).
- "/" now serves a lean chooser page (web/landing.html): a calm, self-
contained page (no framework, inline CSS) that routes to the Player
(/app) or the Admin & Setup console (/admin), with the console framed
as the privileged surface. API/speaker clients (non-HTML Accept) still
get the version JSON from "/" unchanged.
- The admin console moved to /admin (HandleAdmin); its assets and APIs
are absolute, so it works unchanged at the new path.
- New persisted setting default_landing (chooser|app|admin): when set to
app or admin, "/" 302-redirects straight there. Exposed in the admin
Settings tab; defaults to the chooser.
- Shared header: all three carry the same accent bar (braille mark +
"AfterTouch" + "Bose SoundTouch Toolkit"); the mark is the home link
back to "/". Shared footer: all three show the same version line
(the landing fetches /api/setup/version with a tiny vanilla script).
Light/dark and mobile refinements are deliberately left for a later
pass; the admin keeps its existing light-only styling for now.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The merge of soundtouch-web into soundtouch-service was asymmetric:
manual device *adds* propagated to the player UI (HandleAddManualDevice
notifies, the hook re-seeds + broadcasts), but *removals* did not. The
datastore-removal handler never notified, and the web registry's sync
only ever added entries — its map was append-only, so a removed device
lingered in the player UI until restart.
This adds the missing removal path:
- DELETE /api/control/devices/{id} (HandleDeleteDevice). The registry is
keyed by host/IP; the datastore by device ID (MAC), so the handler
resolves one to the other via the connection's DeviceInfo, cascades to
the datastore through a new RemoveDeviceHook (embedded build only),
prunes the in-memory entry, and broadcasts the updated list.
- WebApp.RemoveDevice prunes the registry and stops the per-device
goroutines (status poller + WebSocket reconnect loop) via a new
done-channel + Close() on DeviceConnection — previously both ran for
the life of the process.
- Server.RemoveDeviceByID extracts the cross-account lookup + remove from
HandleRemoveDevice and now fires notifyDevicesChanged, so the admin
Devices tab removal also propagates to the player UI.
- Player UI: a quiet per-card Remove control (visible on hover), a
confirm dialog, optimistic prune, and a note that a still-online
device may reappear after the next discovery scan (honest v1 — no
ignore-list).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Make the datastore the single source of truth for the embedded web UI and
stop running a second mDNS/UPnP stack inside the same process.
- The embedded web app no longer creates its own discovery service. Its
"discover" action (POST /api/control/discover) now triggers the service's
own sweep via a new WebApp.TriggerDiscovery hook (wired to
server.DiscoverDevices), which writes results to the shared datastore.
- DiscoverDevices: when TriggerDiscovery is set it runs the external sweep
and re-syncs from ExtraDeviceHosts (the datastore) without any own mDNS;
it only runs its own sweep when given a non-nil discovery service
(standalone soundtouch-web, unchanged).
- Liveness: server.SetDevicesChangedHook fires after a discovery sweep
(server.DiscoverDevices) and after a manual add (HandleAddManualDevice);
the embedded build re-seeds the web registry and broadcasts the updated
device list, so speakers found by the service's periodic discovery or
added via /setup appear in the UI without a manual refresh.
- setupRouter no longer takes a web discovery service (it was always nil
for the service); MountWeb is mounted with a nil discovery service.
Removing devices live still needs a web-registry delete path (the registry
only adds today); that is a separate follow-up. Routes are unchanged, so
the router golden file is untouched.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Fold soundtouch-web into soundtouch-service as an additive mount, so a
single process serves both the speaker/cloud-replacement API and the LAN
control UI. No new auth and no opt-in flag: the web surface sits at the
same LAN-trust tier as /setup (which -web already calls without
credentials), and -web is LAN-only by nature.
- newEmbeddedWebApp builds the web app with release metadata, a loopback
ServiceURL (plain HTTP, no CA needed) for the TTS / Play URL proxy, and
an initial discovery sweep. setupRouter gains the web app + discovery
service and mounts the portable surface (MountWeb) additively:
/api/control/* and /app/* (+ /app/static/*). The service keeps its own
/, /health and /static; nothing collides. webApp is optional so the
router unit tests that only exercise the service surface pass nil.
- Manual devices with discovery off: the web app's ExtraDeviceHosts hook
is pointed at the service datastore (ListAllDevices), and
SeedExtraDevices (run from DiscoverDevices, i.e. at startup and on each
/api/control/discover) registers them via the existing AddDeviceByHost.
So speakers added via /setup show up in the UI even when periodic
discovery is disabled.
- The admin page at / now links to the player UI at /app; the speaker /
JSON contract is unchanged.
- Router golden file regenerated: the diff is purely the additive
/api/control + /app routes.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Prepare soundtouch-web to be folded into soundtouch-service as an additive
mount. Two changes, no behaviour change for the standalone binary:
- Move the embedded assets from /static/* to /app/static/*, so the whole
web UI lives under /api/control + /app and nothing contends with a host
router's own /static (e.g. the optional Stockholm bridge's root catch-all).
index.html and app.js asset references are updated in lockstep.
- Split Mount into a portable core and a standalone wrapper. MountWeb
registers only the portable surface (/app/static/*, /api/control/*,
/app/*) and nothing outside those subtrees (no /, no /health), so it can
be mounted into another router additively. Mount (used by cmd/soundtouch-web)
now calls MountWeb and adds the standalone-only /health and /->/app redirect.
mount_test.go exercises MountWeb (asserts the portable surface owns nothing
outside /api/control + /app) and Mount (asserts it adds / and /health).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Move the web UI's app-wide event stream (device list, discovery status,
per-device status updates) from top-level /ws to /api/control/ws. It is
the read/event half of the control surface, so it belongs under the same
namespace as the rest of the web API (the per-device socket already sits
at /api/control/devices/{id}/ws). The bundled app.js WebSocket URL is
updated in lockstep.
This brings soundtouch-web's entire HTTP surface under two clean subtrees
(/api/control/* for the API, /app/* for the SPA), so folding -web into
-service becomes a near-additive mount.
mount_test.go now asserts /api/control/ws is registered and top-level /ws
is gone.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Model tunein, radiobrowser, playurl and tts as content "providers" and
give them a uniform /providers namespace, so the surface is consistent
and extensible (Spotify/Amazon slot in later as new providers).
Two kinds of provider operation fall out naturally:
- Browsable providers (a catalog you search/navigate) expose global
browse routes:
GET /api/control/providers/tunein/{search,search/next,navigate,navigate/*}
GET /api/control/providers/radiobrowser/search
- Every provider plays on a device via a uniform `play` verb:
POST /api/control/devices/{id}/providers/tunein/play
POST /api/control/devices/{id}/providers/radiobrowser/play
POST /api/control/devices/{id}/providers/url/play (was play-url)
POST /api/control/devices/{id}/providers/tts/play (was speak)
Input providers (url, tts) have no catalog, so they appear only as a
device play. The generic POST /devices/{id}/play (raw ContentItem) stays
the low-level primitive, not a provider. /providers stays a literal
namespace with literal provider children (no {provider} param), so there
is still zero static-vs-param ambiguity.
The bundled api.js is updated in lockstep. mount_test.go now asserts the
provider routes exist and the pre-infix flat paths are gone.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Move the soundtouch-web single-page app from top-level page paths
(/devices, /tunein, ...) under one /app subtree, so the whole web UI
lives under /app/* and folding -web into -service stays an additive
mount. The client navigates via component state rather than the URL and
all assets are referenced absolutely (/static/...), so this is a pure
routing change: no frontend edits needed.
The bare root / now redirects into the app (standalone convenience).
When -web is folded into -service, / instead serves a landing page
(admin vs app) and this redirect is replaced.
Extend mount_test.go with TestMountSPARoutes: the SPA resolves under
/app, the old top-level page paths are gone, and / remains only as the
redirect.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Restructure soundtouch-web's control API to the post-merge canonical
shape so folding -web into -service later is a near-additive mount.
Device-scoped actions now nest under /api/control/devices/{id}/...,
making every direct child of /api/control a literal namespace (devices,
tunein, radiobrowser, version, discover) with no static-vs-param sibling
ambiguity. Browse/search endpoints (tunein, radiobrowser) stay global.
This is a direct migration (no dual-mount, no deprecation middleware):
-web's only client is its own bundled frontend, so a reload picks up the
new paths. The bundled api.js/app.js are updated in lockstep.
Add mount_test.go: the first test that exercises Mount() itself. It
walks the registered routes to assert (a) registration never panics and
(b) the invariant that every web /api/* route lives under /api/control/*
so no flat route is left behind. Handler unit tests call handlers
directly with injected params, so their request-path literals were
cosmetic; updated to the new nested shape for accurate documentation.
SPA routes and the main /ws socket are unchanged here; they move in
follow-up steps.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
So the eventual 1.x removal of the legacy admin paths can be data-driven (cut a
route only once it has gone quiet across real deployments), record usage of the
pre-/api paths without changing their behavior.
- New DeprecatedRouteMiddleware: after serving, counts the hit keyed by
"METHOD <route-pattern>" and logs a one-time warning per route pointing at the
/api equivalent. Wired onto the legacy /setup and /mgmt mounts only — NOT the
/api/* twins, NOT the externally-pinned OAuth callbacks, NOT the Stockholm
setup-wizard catch-all.
- Counts are exposed in the diagnostic export (deprecated_route_hits), so the
shared bundles show whether the old paths are still in use.
Legacy paths keep working unchanged. make test-http-client: 95 requests, 0
failed (the suite still exercises /mgmt directly and now emits the one-time
warnings). go test + golangci-lint clean.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Point soundtouch-web's TTS proxy at the new canonical /api/setup/tts/speak path
(request URL and doc comment). No behavior change; the legacy path still works.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Move the internal self-reachability probe onto the new /api/setup/version path
(updating the doc comment and the unit test accordingly). No behavior change
(the legacy path still works); keeps our own code off the soon-to-be-legacy
/setup/* surface.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Switch the bundled admin SPA's requests from the legacy /setup/* and /mgmt/*
paths to the new canonical /api/setup/* and /api/mgmt/* aliases. Behaviour is
unchanged (the aliases serve the same handlers; TestDualRouteEquivalence pins
that), and the legacy paths stay live, so this is a no-break move. The OAuth
callback URLs are not referenced by the SPA and stay at /mgmt regardless.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Close the speaker/service-contract gaps found comparing against a reference
implementation — three real Bose routes we did not serve:
- DELETE /streaming/account/{account}/source/{sourceID} — removes a configured
source from every device of the account (HandleMargeDeleteSource +
marge.RemoveSourceFromAccount), mirroring the account-level POST add-source.
Bare 200, empty body. Previously source removal was only reachable via the
admin /setup surface.
- GET /bmx/tunein — bare TuneIn service descriptor (the registry's `self` link),
HandleTuneInService. chi routes both /bmx/tunein and /bmx/tunein/.
- GET /core02/svc-bmx-adapter-orion/prod/orion — bare Orion (LOCAL_INTERNET_RADIO)
adapter descriptor, HandleOrionService.
The two descriptors reuse the existing extractBMXService + applyBMXTemplate
helpers (same {BMX_SERVER}/{MEDIA_SERVER} substitution the registry applies).
Contract tests added (delete_source.http, get_bmx_service_descriptors.http);
router + frozen-coverage goldens updated.
make test-http-client: 95 requests, 0 failed. go test + golangci-lint clean.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Shrink the route surface the #451 refactor must preserve by retiring the
/accounts/{account}/* compatibility mirror. Across the full recording corpus
(all _/backup/*, _/mitm, _/i195, _/issue-94, captures + data/ + tests/, 139k+
.http files) no speaker or app uses the /accounts prefix, and every operation it
offered is served by the /streaming/account/* paths real clients actually use.
- New HandleUnsupported: returns 501 and logs the full request + client IP + a
"please report this" message, so any real-world use surfaces instead of being
silently dropped, and the prefix becomes a clean removal candidate.
- Re-point every /accounts/* route to it. The frozen /streaming/* contract is
left entirely on its real handlers (those stay even where our corpus didn't
exercise them — absence of capture is not proof of disuse).
- Migrate the integration tests off the /accounts mirror onto their recorded
/streaming/account/* equivalents (register/unregister/spotify_full_flow), then
pin the mirror's 501 contract in unsupported_routes.http.
- Router + frozen-route-coverage golden files updated accordingly.
make test-http-client: 91 requests, 0 failed. go test + golangci-lint clean.
Note for release time: call out the intentional /accounts/* 501 breakage in the
release notes' Noteworthy section (use /streaming/account/* instead).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The integration suite flaked in CI: with three `go run` mocks now compiling
concurrently, the spotify/amazon mocks weren't listening within the fixed
`sleep 10`, so the registration requests at the start of the suite hit a
connection-refused and the "Account exists" assertions (and the cascading amazon
oauth token test) failed. Locally it passed because the mock builds were warm.
Replace the fixed sleep with real readiness gating:
- Add a /healthz endpoint to the spotify, amazon and tunein mocks.
- Give all four CI services (the three mocks + soundtouch-service) a compose
healthcheck (busybox wget; all images are alpine-based), and make the service
depend_on the mocks being service_healthy.
- `docker compose up -d --build --wait` blocks until everything is healthy, so
the JetBrains client only runs against a fully-ready stack.
Also clear the two semgrep advisories on the new TuneIn mock:
- cmd/mock-*: annotate the intentional plaintext ListenAndServe with nosemgrep
(throwaway loopback/CI test servers, never production).
- pkg/testutils/tunein: sanitize the query-supplied guide id to a safe charset
before interpolating it into the JSON/XML response (raw-html-format).
make test-http-client: 73 requests, 0 failed (clean testdata, healthcheck-gated).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Per the repo's no-real-data rule (CLAUDE.md), scrub committed files only (the
gitignored _/ local captures are left as-is):
- Real Bose-OUI device ID 08DF1F0BA325 -> placeholder AABBCCDDEE0A across 4 docs
and 8 Go test files (consistent 1:1 rename; affected packages tested green).
- Personal/topology LAN IPs -> RFC-5737: the lab runbook's AP subnet
192.168.10.x -> 198.51.100.x (192.0.2.x is already used contrastively there)
and 192.168.100.1 -> 203.0.113.1; illustrative example IPs in
ANONYMIZATION-SUMMARY / spotify-overview / TROUBLESHOOTING -> 192.0.2.x.
- Kept factual RFC-1918 range citations (10.0.0.0/8 trusted-proxy example,
192.168.0.0/16 "all private subnets") since they name the ranges themselves.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Make the BMX TuneIn integration tests independent of the live TuneIn
(radiotime.com) service, the same way Spotify/Amazon are already mocked.
- pkg/service/bmx: the TuneIn upstream base URLs become configurable vars with
a SetTuneInEndpoints(opmlBase, apiBase) setter that also registers the host in
the outbound allowlist. Defaults are unchanged (real radiotime hosts), so
production behaviour is identical; tests can redirect to a mock.
- cmd/soundtouch-service: new --tunein-opml-url / --tunein-api-url flags
(TUNEIN_OPML_URL / TUNEIN_API_URL) wired through to SetTuneInEndpoints.
- cmd/mock-tunein + pkg/testutils/tunein: a mock TuneIn server serving Tune.ashx
(stream URLs) and describe.ashx (name/logo) with RFC-5737 values; unmocked
endpoints 404 so a test needing them fails loudly.
- docker-compose.ci.yml: add the tunein-mock service and point the service at it.
- tunein_playback_station.http now asserts the mock-served stream URL + name,
proving the path is offline. tunein_favorite.http covers the local-only
favorite add/remove (202).
- TUNEIN-MOCK-MISSING.md lists the upstream captures still needed (episode /
navigate / search) before those routes can be mocked + tested.
make test-http-client: 61 requests, 0 failed. golangci-lint clean.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
A server_url configured with a trailing slash (e.g. http://host:8000/)
flowed verbatim into the BMX registry base ("{BMX_SERVER}/bmx/tunein"),
so speakers were handed "http://host:8000//bmx/tunein" and requested
"//bmx/tunein/v1/playback/station/{id}". The chi router does not match
the doubled-slash path, so TuneIn playback returned 404 and the speaker
reported INVALID_SOURCE. Confirmed from a reporter's diagnostic export.
- Add NormalizeServerURL (trim whitespace + trailing slashes); apply in
NewServer so the BMX base is always clean.
- Normalize server_url at ingestion in main (flag + persisted) so the
margeServerUrl/bmxRegistryUrl pushed to speakers stays clean too.
- Normalize in the live settings-update path so a UI-saved trailing slash
is trimmed before validate/persist.
- Mount chi middleware.CleanPath as a defensive net: any "//" path
collapses to "/" before routing, regardless of source.
- Regression tests: NormalizeServerURL table + BMX registry must not emit
"//bmx"/"//media" for a trailing-slash server_url.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The #458 empty/0-byte resilience logging logged the raw xml.Unmarshal error with
%v. A parse error can echo attacker-controlled file content, so a newline-bearing
error string reached the log unsanitized (CodeQL go/log-injection, medium). Wrap
the error with sanitizeErr (strips \n/\r), the barrier logutil.go documents.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
atomicWriteFile wrote a temp file and renamed it, but never fsync'd — so an
unclean power-cut on a journaling NAND filesystem (UBIFS on the speaker's
/mnt/nv) could leave the renamed datastore file present but 0 bytes (the rename
was journalled, the data blocks were not flushed). Now fsync the temp file
before the rename and the parent directory after, via os.Root.OpenFile/Open;
directory fsync is best-effort (unsupported on some filesystems).
Pairs with the read-side resilience fix (#459): durability prevents the 0-byte
files; resilience tolerates any that already exist.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
A power-cut on the speaker's NAND can leave a datastore file present but 0-byte
(a not-yet-flushed atomicWriteFile write). The read paths now treat empty/0-byte/
unparseable Presets/Recents/Sources the same as missing: GetConfiguredSources
serves the managed defaults (so /full self-heals instead of wiping the speaker),
GetPresets/GetRecents return an empty list (no more HTTP 500 on the device-level
endpoints), and HasConfiguredSources reports a 0-byte file as absent (so the
create_default_sources health quick fix is offered again).
Read-side resilience only; the write-side durability fix (fsync in
atomicWriteFile) follows in a separate PR.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
A speaker with a wrong clock fails TLS to any HTTPS host because the
certificate appears not-yet-valid or expired (the CURL ErrorCode 60 seen
in #345, where the failing speaker had a wrong clock, the only one of
several speakers that was off, with a failing NTP sync; these speakers
default to the year 2000 at boot until NTP succeeds). Nothing surfaced
this before.
The check reads each speaker's /clockTime and compares its UTC epoch to
the service's epoch. Using the epoch (ClockTime.GetUTC, not GetTime) keeps
the comparison timezone-independent. Tiers: under 60s no finding; 60s-5m
info; 5m-24h warning; 24h-or-more, or a time outside the year 2000..2100
plausibility window, error. Findings note a stale or missing NTP sync.
A set_clock quick-fix on the warning and error findings pushes the current
time to the speaker via POST /clockTime (client.SetClockTime). That call is
plain HTTP on :8090, so it works regardless of the speaker's wrong clock or
TLS state. It is a band-aid: if NTP is still failing the clock drifts again
and resets on reboot, so the confirm dialog and success message point at
restoring time sync as the durable fix. An SSH set-clock fallback is left
for later since the HTTP path is confirmed on firmware 27.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
When a speaker resolves the firmware-hardcoded content.api.bose.io through
the operator's own DNS instead of AfterTouch, TuneIn/BMX content requests
escape AfterTouch and fail (CURL 60, or a dead-cloud 404), so the speaker
reports INVALID_SOURCE. The existing dns_sanity check only probes AfterTouch's
own answering side over loopback, so it passes even when no speaker uses
AfterTouch as its resolver. This adds a speaker-side, on-demand check.
dns_speaker_usage:
- pkg/discovery/dns.go tracks distinct non-loopback clients that query an
intercepted Bose hostname (interceptClients set, populated in recordQuery,
exposed via InterceptClientIPs()). Loopback is excluded so dns_sanity's own
probes don't register.
- The check lists each unconfirmed speaker as an info finding with a "Test DNS
path" quick-fix. It never emits a standing warning, so it does not
false-positive after a restart (the querier set is in-memory and starts empty).
Active probe (the "Test DNS path" quick-fix; also POST /setup/health/dns-path-probe):
- Sends a /speaker notification carrying a per-probe nonce as the app_key. To
accept it the speaker must resolve audionotification.api.bosecm.com
(intercepted) and call back GET /v1/auth with that nonce; the callback
arriving is direct proof the speaker resolves Bose hosts through AfterTouch.
- HandleSpeakerAuth returns 403 for a matching nonce so the speaker refuses the
notification (silent, no audio, confirmed on hardware); any other key still
gets 200 so real TTS is untouched. Reuses resolveTTSHost for SSRF-safe
targeting; the nonce is never logged. Registered without refresh so the probe
result stays visible in the Health tab.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
An <updates> frame whose only child is an element the WebSocketEvent
struct doesn't model (e.g. nowSelectionUpdated, sent by SoundTouch 10
firmware around a play action) produced no known event types, so
handleEvent logged "Received unknown event types: []" repeatedly. The
empty list carried no information and flooded soundtouch-web's logs and
the CLI events subscribe output we point people at for debugging.
Capture unmodeled <updates> children by name via an xml:",any" catch-all
on WebSocketEvent and log the actual element names ("[nowSelectionUpdated]"),
skipping frames that carry no child events entirely. A regression test
confirms a modeled event is not also captured as unknown.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
soundtouch-web had no logging on its play/select paths, which made
issues like #345 (a source rejected by the speaker) hard to diagnose:
a SoundTouch /select returns HTTP 200 even when the source is then
rejected, so the failure only surfaces asynchronously as a now_playing
transition to an error source, and nothing recorded it.
Add two log points:
- logPlaybackRequest: one line per play/select with the resolved
source, sourceAccount, location and itemName, from all five handlers
(source-select, device-play, play-url, radiobrowser, tunein). This is
often the only record of what was actually requested. sourceAccount
here is an account identifier, not a bearer credential.
- logNowPlayingError: logs when a device's now_playing enters an error
source (INVALID_SOURCE or any *_ERROR), deduped per transition, which
is the real signal that a selection failed on the speaker.
The two TuneIn/RadioBrowser handlers now resolve the ContentItem via
stations.ResolveContentItem and select it directly so the log shows the
authoritative outgoing source; the now-unused stations.Play wrapper is
removed.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The /api/control/{host}/source handler hardcoded an empty sourceAccount,
so devices that share source="AUX" across multiple jacks (e.g. the ST-5
CD/Aux inputs, disambiguated by AUX/AUX1/AUX2) always received
sourceAccount="AUX" and rejected the wrong jack with internal error 1005.
Read the account query parameter and forward it to SelectSource, matching
what the frontend already sends and what the CLI already does.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
soundtouch-web's "Speak" feature proxies to the AfterTouch service's
/setup/tts/speak endpoint. Two issues blocked it end to end.
1. TLS: the proxy used http.DefaultClient, which trusts only system
roots, so the HTTPS call to a service using its own self-signed CA
failed with "x509: certificate signed by unknown authority". Add a
--service-ca flag (SERVICE_CA env) that loads the CA PEM, appends it
to the system pool, and uses a custom client for the TTS call.
2. Target: soundtouch-web sent device.Client.Host() (a full base URL
like http://ip:8090), but the service's SSRF guard exact-matches the
target against bare datastore IPs, returning "host ... is not a known
device". Prefer the device ID (the canonical key) and send a bare-IP
host fallback. Also normalize the incoming host in resolveTTSHost so a
URL/host:port form still resolves; it still only ever returns a
datastore IP, so the SSRF guarantee is unchanged.
Adds unit tests for the CA client builder, hostOnly, and resolveTTSHost
(including the preserved unknown-host/device rejections). Documents
--service-ca in the soundtouch-web README and TROUBLESHOOTING guide.
Wires SERVICE_URL and SERVICE_CA (empty defaults) into the Raspberry Pi
install-web.sh env file and documents them in the Pi guide.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
HandleTTSSpeak passed the request's `host` straight to
client.NewClientFromHost, so the resolved value flowed into the client's
baseURL and the outbound request (client.go post -> httpClient.Do) — a
caller could point the service at an arbitrary host:8090 (SSRF).
resolveTTSHost now always returns an IP looked up from the datastore:
match by deviceId, or by host equal to a known device's IP, and return
that stored IPAddress (never the caller-supplied string). Unknown
hosts/devices are rejected. This both mitigates the SSRF and breaks the
tainted data flow. Adds regression cases for unknown host/device.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Mirrors the TTS view's "configured -> locked" behavior. HandlePlayURL
already prefers the server-side --service-url over the client value, so
when it's set the browser field's edits are ignored anyway; reflect that
by rendering it read-only with a note, and editable only as a fallback
when no --service-url is configured. (Play URL has no SSRF: the URL is
handed to the speaker, not fetched by soundtouch-web.)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
CodeQL flagged "uncontrolled data used in network request": the
soundtouch-web TTS proxy built its outbound request URL from the
client-supplied serviceUrl, letting any LAN caller use the endpoint as an
SSRF proxy. The proxy target must be the operator-configured --service-url.
- handler: use only app.ServiceURL; drop the client-supplied serviceUrl
field and fallback.
- web TTS view: show the configured service URL read-only with an
explanation of why it can't be edited here (Play URL differs — its URL
is handed to the speaker, not fetched by soundtouch-web, so no SSRF).
- api.speak no longer sends serviceUrl.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
soundcork#104 confirms speakers validate the /speaker audio-notification
app_key against audionotification.api.bosecm.com (100 calls/day on real
Bose). Our /v1/auth shim accepts it, but a host-seeded migration only
worked if the speaker resolved that host to us. DNS interception already
covers it (bosecm.com substring), but the /etc/hosts migration domain
list did not — so the speaker method would fail on hosts-based setups.
Seed both audionotification.api.bosecm.com and the dev variant
(audionotificationdev.api.bosecm.com; firmware may use either) into the
migration /etc/hosts lists, and update the mock fixtures/docs accordingly.
/v1/auth is path-based, so it already answers regardless of which host the
speaker thinks it is calling.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Confirmed working on a real speaker (Bose_Lisa/27.0.6): the speaker GETs
/v1/auth at audionotification.api.bosecm.com (DNS-redirected to us) with
the app_key in an "Apikeyheader" header, and an empty 200 is sufficient.
- Make "speaker" the default playback method (ducks + resumes the current
playback, supports volume) for the speak endpoint, the CLI --method flag,
and the web UI button; "radio" remains opt-in.
- Remove the temporary full-request debug dump from /v1/auth now that the
contract is understood; document it in the handler comment instead.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
/setup/tts/speak now accepts a "method" field (and the CLI a --method
flag): "radio" (default, LOCAL_INTERNET_RADIO, no app_key, replaces
source) or "speaker" (POST /speaker notification, ducks+resumes, honours
volume). The speaker method defaults the app_key to "aftertouch" when
none is configured, since the speaker validates it via GET /v1/auth which
we answer 200 regardless.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Root cause of the failed TTS playback: the /speaker notification path
makes the speaker validate the app_key via GET /v1/auth against the
service, which returned 404 -> the speaker reports an invalid app key
(HandleInvalidAppKeyCb) and refuses to play. Our /media/tts hosting was
fine all along (confirmed by a direct GET returning the mp3).
Two fixes:
- TTS speak now plays the synthesized clip as a LOCAL_INTERNET_RADIO
ContentItem via the /custom/v1/playback proxy (the same mechanism the
"ding" health check uses), which needs no app_key. New
buildCustomPlaybackURL helper + tts.Service.BaseURL().
- Add GET /v1/auth -> 200 so the /speaker notification path also works
(we're the cloud replacement; a 404 there is read as "invalid app
key"). Includes a TEMPORARY full-request debug dump on /v1/auth to
learn how the speaker presents the app_key; to be removed later.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The TTS speak/config endpoints were under /mgmt (Basic-Auth protected),
but the soundtouch-web proxy and CLI authenticated with their own
mgmt-password default (empty) while the service defaults to "change_me!",
so speaking from -web returned 401.
This was also inconsistent: the Google API key is configured via the
unauthenticated /setup/settings, and Play URL already proxies to /setup,
so gating only TTS playback behind mgmt auth made no sense. Move
/mgmt/tts/{speak,config} to /setup/tts/{speak,config} (LAN-trust, like
the rest of the setup surface), rename the handlers accordingly, and drop
the now-unused mgmt-credential plumbing from soundtouch-web and the CLI
tts command.
Verified: POST /setup/tts/speak now reaches the handler without auth
(502 only because the test speaker IP is unreachable; previously 401).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The Google Cloud TTS API key (and app_key / provider / language / voice /
volume) can now be set in the service settings page, persisted to
settings.json, and applied at runtime — same model as Spotify/Amazon
(CLI/env wins at startup, else persisted; secrets masked as "***" over
the wire; a save triggers ReinitTTSService without a restart).
To keep the settings page from bloating as integrations grow, Spotify,
Amazon, and Google Cloud TTS are now collapsible <details> panels under
an "Integrations" heading, each showing an Active/Saved/Inactive badge in
its summary that stays visible when collapsed. Adding a future provider
(e.g. Apple Music) is now just another panel.
Provider construction moved from cmd initTTSService into
handlers.Server.ReinitTTSService so the UI can re-apply changes; the
tts-provider flag default is now empty (empty => translate) so a value
saved in the UI can take effect.
Also: the soundtouch-web TTS source view now shows the AfterTouch service
URL with an override (shared with Play URL via localStorage), and
/api/device-speak accepts a serviceUrl override, mirroring Play URL.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Adds text-to-speech that synthesizes higher-quality audio (Google Cloud
TTS) and plays it on a speaker via the /speaker endpoint. Because Cloud
TTS returns audio bytes (not a fetchable URL), the service caches the
clip and hosts it at GET /media/tts/{id}, mirroring the "ding" endpoint,
then points the speaker at that local URL.
The design is a pluggable Provider interface (pkg/service/tts) wrapping
two modes:
- translate: hands the speaker the (undocumented) Google Translate URL
directly (no credentials), reusing models.BuildTranslateTTSURL.
- google-cloud: REST API key auth (no SDK/gRPC), bytes cached locally.
Surfaces:
- service: POST /mgmt/tts/speak, GET /mgmt/tts/config, GET /media/tts/{id};
configured via TTS_PROVIDER / TTS_GOOGLE_API_KEY / TTS_LANGUAGE /
TTS_VOICE / TTS_APP_KEY / TTS_VOLUME.
- CLI: `soundtouch-cli tts speak` (calls the service with mgmt Basic Auth).
- web: a "TTS" source view (like Play URL / TuneIn), proxied to the
service via /api/device-speak/{id}.
The /speaker app_key requirement and model limitations still apply; see
docs/content/docs/reference/SPEAKER-ENDPOINT.md.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The diagnostic export captured the symptom of #345 (a TuneIn select
escaping to the dead Bose Apigee gateway → BMX_HTTP_ERROR 4501 →
INVALID_SOURCE) but none of the data that decides where a speaker sends
its marge/BMX/streaming traffic, so we couldn't tell whether the request
was ever redirected to AfterTouch.
Collect that per speaker:
- New collectSpeakerRedirectConfig prefers the on-device
SoundTouchSdkPrivateCfg.xml over SSH (archives raw + parses
marge/stats/swUpdate/bmxRegistry URLs), and falls back to
`getpdo CurrentSystemConfiguration` over telnet when SSH is
unavailable — the same channel the telnet migration uses. Parsed URLs
and provenance land in diagnostic.json as redirect_config: source
(ssh|telnet|none), ssh_reachable, and inferred_migration_method
(telnet when only telnet answered, since xml/hosts/resolv all need SSH).
- Pull redirection-relevant files over SSH: /etc/hosts(.original),
/etc/resolv.conf, the resolv-method hook, /mnt/nv/remote_services, and
the pre-migration .original backups (CA bundle and the URL config).
- Dump the speaker firewall (iptables-save; ip6tables-save is empty on
FW 27.0.6 but harmless) to catch self-inflicted DROP rules (cf. #354).
Export ParseGetpdoConfig from pkg/service/setup and add a test pinning
the field-name contract the export depends on.
Diagnostic-collection only; does not change migration or playback.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Root cause of #334's INVALID_SOURCE: a speaker reports device-local slots
(STORED_MUSIC_MEDIA_RENDERER, UPNP) in /sources; AfterTouch imports them
verbatim and re-serves them in /full. PrepareConfiguredSource fills
sourceproviderid only for types in constants.StaticProviders, so these go
out with an empty <sourceproviderid> — a required protobuf field — and the
speaker rejects them as INVALID_SOURCE, which then re-syncs back into the
datastore.
Fix, keyed on the principle (no hardcoded denylist in production):
- HasResolvableProviderID(s): true if the source already carries a provider
id, or its source-key type resolves via StaticProviders.
- Serve-side guard in getAccountSources: drop any source whose resolved
sourceproviderid is still empty (generalises the existing AUX/#195 skip).
Heals already-polluted datastores on the next /full, no resync needed.
- Import-side filter in syncConfiguredSources (marge) and both branches of
syncSources (setup): drop unresolvable sources before persisting, stopping
future pollution and the re-import loop.
Tests: reproduction converted to regression test
(TestI334FullOmitsSourcesWithoutProviderID) seeded from a sanitised real
#334 /sources capture; explicit servable/non-servable tables in
TestHasResolvableProviderID. Two pre-existing fixtures that relied on
sources with no provider id were given valid ones.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
TuneIn's Tune.ashx returns several stream URLs per station (different
bitrates/CDNs) so a speaker can fail over when one is dead. TuneInPlayback
parsed the full list but forwarded only urls[0], wrapping a single URL in
the audio.streams[] array. When TuneIn listed a dead variant first (e.g.
station s56857 / NDR 2 Niedersachsen, whose aac/low 404s while mp3/128
plays), the speaker had no fallback and dead-ended retrying the 404.
Add BuildCustomStreamResponseFromURLs to emit one Stream per candidate in
provider order (top-level StreamUrl mirrors urls[0] for compatibility),
have the single-URL BuildCustomStreamResponse delegate to it, and forward
the full slice from TuneInPlayback. The other single-URL callers
(PlayCustomStream, the custom-stream handler) are unchanged.
Confirmed on real hardware: the speaker now fails over from the 404'd
aac/low to the working mp3/128 stream and plays.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Add a provider-neutral station orchestration layer and expose it in the
CLI so TuneIn and Radio Browser search work consistently without
depending on the speaker's (dead) cloud search. Substance of #338.
- pkg/service/stations: new package with Search/SearchNext/Navigate/
ResolveContentItem/Play over both providers; centralises the
SourceAccount placeholder guard.
- soundtouchweb: the six TuneIn/Radio Browser handlers become thin
adapters over the new package (behaviour preserved; bmxpkg retained
for HandlePlayURL).
- bmx/radiobrowser: add offset/cursor pagination
(RadioBrowserSearchPage + RadioBrowserSearchNext) mirroring the
TuneIn opaque-cursor pattern; BmxNext only on full pages.
- marge: classifyLearnedSource gains a provider-39 (RADIO_BROWSER)
case + classifyAsRadioBrowser helper (candidate fix for #334
INVALID_SOURCE; location-substring match still to be confirmed
against a real recording).
- cli: new `station search-radiobrowser` sibling and unified
`station find --provider tunein|radiobrowser [--more]`. The existing
generic device-side `station search --source` is kept unchanged.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The power, mute, shuffle, and repeat buttons used Unicode emoji (⏻ 🔇🔀🔁) which Android/mobile browsers render through the OS emoji font
with platform-specific colour styling, ignoring CSS color entirely.
This caused them to look like colourful emoji badges rather than flat
monochrome controls.
Replace each with an inline SVG using stroke/fill="currentColor" so
they inherit the button's text colour automatically — flat in both light
and dark mode, and correctly inverted when a button is in its active
(accent-background) state without any extra CSS filter.
The .ctrl-btn rule gains display:inline-flex + align-items:center to
vertically centre both text-character (⏮ ⏸ ⏭) and SVG content
consistently. The .volume-icon label in the volume row switches from
an emoji span to the same currentColor SVG at 16 px.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
The speaker WebSocket was cycling every ~65 s because the gorilla pong
handler was never set, so the 60-second read deadline in readLoop fired
after each ping cycle (30 s interval + 5 s reconnect = ~65 s loop).
Setting a pong handler that extends the deadline on every pong response
keeps the connection alive indefinitely during quiet periods.
After any (re)connect the Go server now immediately fetches current
device state via HTTP, because Bose speakers do not replay WebSocket
events on new connections — anything that changed during a disconnect
window would otherwise stay stale until the next speaker-side event.
A 30-second periodic HTTP poll per device is added as a backstop for
Spotify Connect track changes that the SoundTouch API does not surface
as nowPlayingUpdated WebSocket events.
On the browser side, track identity (TrackID / ContentItem.Location) is
added to the NowPlaying timer effect deps so the local counter resets
whenever the track changes regardless of start position, and the time
label is clamped to the song total to prevent "4:17 / 4:09" overruns.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>