Skip to content

Serve the pairing token to its own subnet, until a server pairs, for local pairing - #110

Merged
chrisuthe merged 14 commits into
mainfrom
chrisuthe/task/serve-the-pairing-token-on-an-internal-endpoint
Nov 19, 2026
Merged

chrisuthe merged 14 commits into
mainfrom
chrisuthe/task/serve-the-pairing-token-on-an-internal-endpoint

Conversation

@chrisuthe

@chrisuthe chrisuthe commented Oct 31, 2026 •

Copy link
Copy Markdown
Member

Adds --pairing-token-endpoint <address>:<port> (config key pairing-token-endpoint). With it set, and until a server pairs, the player:

  • answers GET / with the pairing token as plain text (text/plain, Cache-Control: no-store) on that one address, to peers on that address's own subnet only;
  • lists _ohf_local_pairing@v1 in client/hello supported_roles with "_ohf_local_pairing@v1_support": {"port": N}.

How it stays local

  • One address, never a wildcard. The address is required and must be a numeric IPv4 or bracketed IPv6 literal. A bare port, a hostname, 0.0.0.0, :: or ::ffff:0.0.0.0 is refused at parse time. If the address cannot be bound, or no interface holds it, the player exits before it advertises anything.
  • Only the address's own subnet is answered. At listen() the player finds the local interface whose subnet holds the address (getifaddrs, or GetAdaptersAddresses on Windows) and answers any peer outside it with 403. That is 172.30.32.0/23 for Home Assistant OS's 172.30.32.1 and 127.0.0.0/8 for 127.0.0.1. Without this, a LAN machine could route packets to 172.30.32.1 and be answered, since Linux accepts a local address on any interface.
  • Only until a server pairs. A Pairing PSK admits every server, so a token served for the player's whole life would let anything that fetched it pair another server later. The main loop checks once a second for a pairing record and closes the endpoint when one appears. A player that is already paired at startup neither listens nor advertises the role.
  • Bounded requests. The request head is read byte by byte up to 4 KiB (431 beyond that) and no body is ever read, so a huge Content-Length cannot be buffered. At most four connections are served at once; a fifth is closed as soon as it is accepted. stop() cancels requests still being read, so closing the endpoint on the main loop does not wait out their 5 s deadline.
  • The request must name it. A Host that is not the endpoint's own address and port gets 421 and no token, so a page that DNS-rebinds its hostname to the address cannot read it. The comparison is by address, so equivalent IPv6 spellings match.
  • The token stays out of the log. Requests are logged at debug with the peer address and status only. With the endpoint on, the startup line that otherwise prints the token points at sendspin-cli pair-token instead, because add-on logs are visible in the UI.

Docs: the wiki Configuration key, the Advanced Usage section "Pairing with a server on the same host" with the security model (including that on a loopback address every local user can reach it, which pair-token's owner-only control socket would not allow), --help, and a README paragraph.

Decisions

  • Plain text on GET /, matching Pair Sendspin players on the Home Assistant host with their local token music-assistant/server#7371's fetch. An earlier revision answered GET /pairing-token with JSON carrying the client id. MA's pair_with_token already refuses a token issued for another client id, so the reply carries only the token.
  • Close once paired rather than answer 403. Nothing stays listening, and nothing is advertised after a restart. A further server pairs with sendspin-cli pair-token.
  • Allowed peers derived from the interface, not configured. Nothing more to set on Home Assistant OS, and a loopback address needs no special case: its subnet is loopback.
  • An ix::SocketServer subclass, not ix::HttpServer. In IXWebSocket v12.0.1, ix::HttpServer counts only upgraded WebSocket clients against its connection limit, so plain requests were never capped. The subclass counts every accepted connection, from the accept loop until its worker thread is reaped, and reads requests itself instead of ix::Http::parseRequest, which honours any Content-Length.
  • cli, not the add-on wrapper. The cli already advertises the role and holds the key. Serving the token from the same process means the advertised port is bound before client/hello goes out.
  • Role name _ohf_local_pairing@v1, following the ohf_ prefix suggestion on backlog#86. Still provisional. Pair Sendspin players on the Home Assistant host with their local token music-assistant/server#7371 uses the same name.

Requires upstream

Builds on #115 (sendspin-cpp 78b13d5e, with #218's SendspinClientConfig::application_roles), which is merged into this branch along with main. Until #115 merges, its commits show here too; this PR's own are 91f59b1, d60bf52, edb2a9e, 9787cd2 and 8fb95dd, plus the merge de09eb9, which moves the endpoint to client_pairing_token().

Compatibility

Nothing breaks for CLI users: no existing flag, config key, control-socket message, state format or exit code changes, and the option is off by default. application_roles defaults to empty, so hello is unchanged unless the new option is set.

Testing

  • Unit tests, 18 for the endpoint: address and port parsing; the reply on and off the path; Host matching by address (equivalent IPv6 spellings accepted; another name, port or family, an empty port, or none refused); request-head parsing, including two Host headers and malformed request lines; subnet containment, including Home Assistant OS's /23 edge and IPv6; the loopback subnet found on this machine, and an address no interface holds refused. Over real sockets: the token served with both headers, nothing on 127.0.0.2 (skipped on macOS, which configures only 127.0.0.1), 421 to a rebinding Host, the fifth connection closed, 431 to an oversized head, an answer without waiting for a promised body, and stop() returning promptly with a request stalled half-way. Removing the cancel from stop() makes that last test fail at 4.8 s.
  • End to end, the real binary under WSL with curl: unpaired on 127.0.0.1, GET / returns the same token as pair-token and a rebinding Host gets 421. Bound to eth0's 172.24.111.40/20, a peer on that subnet gets 200 and the same request sent from 127.0.0.1 gets 403. 192.0.2.1 stops the player with "no network interface on this machine holds 192.0.2.1".
  • Full suites, -DSENDSPIN_CLI_WERROR=ON: Linux (Ubuntu 24.04, gcc 13) 579/579 and scripts/smoke_test.sh; Windows (clang-cl) 571/571, with the symlink test skipped as on main. The endpoint tests also passed five parallel runs in a row on each. clang-format 20.1.8 on every changed file.
  • Not tested end to end: closing the endpoint once a server pairs, which needs a real server to pair.

Part of Sendspin/backlog#86.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Critical issues leave ordinary HTTP connections unbounded, enabling resource exhaustion, and allow DNS rebinding to expose the pairing token because the Host header is not validated.

2 open issues
What changed in this PR

Adds an opt-in HTTP pairing-token endpoint so a server on the same host can pair with the player without manually copying a token.

Changes:

  • Adds CLI and config options requiring an explicit, non-wildcard IP address.
  • Binds the endpoint before client startup, advertises its role and port, and suppresses startup token logging when enabled.
  • Updates the library pin and adds parser, HTTP, and address-binding tests plus security documentation.
File Description
tests/​pairing_endpoint_test.cpp Tests responses, HTTP serving, and address isolation.
tests/​config_file_test.cpp Tests endpoint configuration and wildcard rejection.
tests/​cli_test.cpp Tests defaults and address/port validation.
src/​pairing_endpoint.h Declares the endpoint interface and role constants.
src/​pairing_endpoint.cpp Implements parsing, HTTP responses, and listener lifecycle.
src/​main.cpp Integrates binding, advertisement, logging, and shutdown.
src/​cli.h Adds endpoint option fields.
src/​cli.cpp Adds flag/config parsing and help text.
README.md Documents the new option.
docs/​wiki/​Configuration.md Documents the configuration key.
docs/​wiki/​Advanced-Usage.md Explains same-host pairing and its security model.
CMakeLists.txt Updates the dependency pin and registers endpoint sources and tests.

Review effort: Balanced

Comment thread src/pairing_endpoint.cpp Resolved
Comment thread src/pairing_endpoint.cpp Resolved
chrisuthe and others added 3 commits November 5, 2026 16:41
3a3722a8 is sendspin-cpp#218 as merged, which adds application-specific roles. It brings #234, which removes ConnectionTrust and on_trust_changed() for SendspinClient::is_paired(). The main loop now polls it and logs "Connected server is paired/not paired" when a session is new or re-keyed, as the callback did. status reads it before is_connected(), as the library asks. Its trust line loses "unknown": a connected session is always paired or not.
--pairing-token-endpoint <address>:<port> answers GET /pairing-token with the client id and token on that one address, and advertises _ohf_local_pairing@v1 {"port":N} in client/hello. A wildcard or missing address is refused, so it never listens on every interface. Part of Sendspin/backlog#86.
Music Assistant fetches GET / and reads the body as the token, so answer that instead of a JSON object on /pairing-token. The role stays _ohf_local_pairing@v1. pair_with_token already refuses a token for another client id, so the reply no longer carries one.
ix::HttpServer counts only upgraded WebSocket clients against its
connection limit, so each plain HTTP connection got its own worker
thread with no cap. Serve from an ix::SocketServer subclass that counts
every accepted connection until its worker is reaped, and drop the
WebSocket upgrade handling that is no longer reachable.

Answer only a request whose Host names the endpoint's own address and
port, so a page that rebinds its hostname to that address gets 421 and
no token.
…s up

A new session's first server/activate can start pairing, and loop()
delivers that start before is_connected() first reads true. Clearing
the attempt on the session's rising edge then wiped the live attempt,
and status reported no pairing while one was in progress.

Clear it on the falling edge instead: an attempt on a dropped
connection is the only one that never reports its end. PairingListener
moves to its own file so its tick and callback ordering can be tested.
Moves the pin to the head of sendspin-cpp main, seven commits past
3a3722a8. None of them touches is_paired(), is_connected() or the pairing
callbacks this PR relies on. connect_to() now takes its URL by value, which
the existing call site compiles against unchanged. None of the library gaps
listed in the roadmap is closed by these commits.
3c28f669 broke the linux-armv6 build: CONNECTION_BLOCK_BYTES left 32
bytes for the shared_ptr control block, and Raspbian's libstdc++ uses the
mutex lock policy, which needs 48. sendspin-cpp#263 fixes that and merged
as 78b13d5e.

The commits between them deprecate the callbacks and accessors this CLI
used, and -Werror turns each use into an error. The CLI now overrides
on_pairing_attempt, on_paired, on_pairing_aborted, on_pairing_code and
on_track_metadata, and reads server_information() and
client_pairing_token(). Their text arrives as string_view, valid only for
the callback or until the next loop(), so whatever status, the hooks or
the state store keep is copied first.
At this pin a server that cancels pairing with a server/activate ends the
attempt with no callback at all: on_trust_changed, which used to clear it,
is gone, and the prompt dismissals fire only for an attempt that showed a
code or a window. A token attempt cancelled that way stayed in status as
in progress until the connection dropped.

The library arms a 120 s deadline when an attempt starts, so an attempt
that shows no prompt has an outcome, a timeout or a dropped connection by
then unless the server cancelled it. The listener now forgets such an
attempt 150 s after a tick first saw it.

A dropped connection now forgets only an attempt an earlier tick saw. One
that loop() delivered in the same pass may be the next session's first
attempt.
Brings in #116, so macOS builds on the macos-15 runner, and everything since through #119.
Brings the re-pin to sendspin-cpp 78b13d5e and main through #119. The endpoint now reads the token through client_pairing_token(), which replaces the deprecated pairing_token().
… server pairs

A Pairing PSK admits every server, so the token served for the player's
whole life let anything that fetched it pair another server later. The
endpoint now closes once a pairing record exists, and a player that is
already paired neither listens nor advertises the role.

The listening address's own subnet is now the only one answered: the
player looks up the interface that holds the address and refuses, with
403, any peer outside it. A LAN machine that routes packets to
172.30.32.1 was otherwise answered, since Linux accepts a local address on
any interface. An address no interface holds is refused at startup.

The request head is read byte by byte up to 4 KiB and no body is ever
read, so a large Content-Length can no longer be buffered. stop()
cancels requests still being read, since it now runs on the main loop.

The Host header is compared as an address, so equivalent IPv6 spellings
match, and URL bracketing is shared. The docs say who can reach the
endpoint, including other local users on a loopback address.
ctest runs each test in its own process at once, and IXWebSocket sets
SO_REUSEADDR, which on Windows lets a second process bind a port that is
already listening. Tests drawing from one range could then connect to
another test's endpoint. Each test now takes its own ten ports.

The body test also sends no body bytes after the head: closing on unread
data resets the connection, and on Windows the reset can arrive before
the reply.
@chrisuthe chrisuthe changed the title Serve the pairing token on an internal endpoint for local pairing Serve the pairing token to its own subnet, until a server pairs, for local pairing Nov 12, 2026
acuntex pushed a commit to acuntex/music-assistant-server that referenced this pull request Nov 19, 2026
…en (music-assistant#7371)

# What does this implement/fix?

A software Sendspin player running on the same HAOS host as the Music
Assistant add-on (the Local Audio app) now pairs automatically, with no
token copying. This is music-assistant#7315 again without the part that got it reverted
(music-assistant#7370): the Home Assistant ESPHome auto-pairing (`HassAutoPairer` and
the hass provider's `subscribe_sendspin_clients` /
`get_sendspin_pairing_token`) stays as it is. The two cover different
players: ESPHome devices pair through Home Assistant, software players
through their local token.

How it works:
- The player lists the application-specific role `_ohf_local_pairing@v1`
(provisional name, with the `ohf_` prefix asked for on
Sendspin/backlog#86) in `client/hello` and sends
`"_ohf_local_pairing@v1_support": {"port": N}`.
Sendspin/sendspin-cpp-cli#110 is the player side.
- When it connects encrypted and unpaired, offering the token pair
method, and no manual pairing is running, MA fetches `GET
http://172.30.32.1:N/` (plain-text token). It then pairs through
`pair_with_token`, which rejects a token for another client id.
- The address is fixed, never taken from the client. The port must be an
int in 1024-65535. The fetch uses `mass.http_session` with a 5 s
timeout, no redirects, 200 only and a 512-byte cap. The token is never
logged.
- Only active when running as the HA add-on, behind a hidden
`local_pairing` entry (default on), like `allow_legacy_clients`.

No same-host check in this version: aiosendspin exposes no public peer
address. A client cannot pair this way without the PSK, because the
handshake fails, so the check would only stop other hosts from
triggering the local fetch.

If a proxy is set via `HTTP(S)_PROXY` without `NO_PROXY` covering
`172.30.32.1`, the fetch goes through it, because `mass.http_session`
honours proxy env vars.

Bumps `aiosendspin[server]` to 10.3.0, which keeps `application_objects`
on the hello (Sendspin/aiosendspin#586).

**Related issue (if applicable):**

- related issue Sendspin/backlog#86
- reverted earlier version: music-assistant#7315, music-assistant#7370

## Types of changes

- [ ] Bugfix (non-breaking change which fixes an issue) — `bugfix`
- [x] New feature (non-breaking change which adds functionality) —
`new-feature`
- [ ] Enhancement to an existing feature — `enhancement`
- [ ] New music/player/metadata/plugin provider — `new-provider`
- [ ] Breaking change (fix or feature that would cause existing
functionality to not work as expected) — `breaking-change`
- [ ] Refactor (no behaviour change) — `refactor`
- [ ] Documentation only — `documentation`
- [ ] Maintenance / chore — `maintenance`
- [ ] CI / workflow change — `ci`
- [ ] Dependencies bump — `dependencies`

## Checklist

- [x] The code change is tested and works locally.
- [x] `pre-commit run --all-files` passes.
- [x] `pytest` passes, and tests have been added/updated under `tests/`
where applicable.
- [ ] For changes to shared models, the companion PR in
`music-assistant/models` is linked.
- [ ] For changes affecting the UI, the companion PR in
`music-assistant/frontend` is linked.
- [x] I have read and complied with the project's [AI
Policy](https://github.com/music-assistant/.github/blob/main/AI_POLICY.md)
for any AI-assisted contributions.
- [ ] I have [raised a PR against the documentation
repository](https://github.com/music-assistant/music-assistant.io/blob/main/CONTRIBUTING.md)
targeting the main or beta branch as appropriate.

---------

Co-authored-by: Artur Pragacz <[email protected]>
@chrisuthe
chrisuthe requested an adaptive review from Copilot November 19, 2026 14:52

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Failed state writes can leave the reusable pairing token downloadable after pairing completes, while stale stream-hook metadata and off-subnet connection-slot exhaustion also remain unresolved.

3 open issues
2 resolved since last review

Review effort: Max (adaptive)

Comment thread src/main.cpp Resolved
Comment thread src/main.cpp Resolved
Comment thread src/pairing_endpoint.cpp Resolved
Music Assistant only fetches from 1024-65535, so a lower port would be advertised and never used.
…r pairs

An off-subnet peer could hold one of the four slots for the full read deadline. The endpoint now also closes on on_paired(), so a pairing whose record failed to save no longer leaves the token downloadable.
@chrisuthe
chrisuthe merged commit 4f8aa74 into main Nov 19, 2026
21 checks passed
chrisuthe added a commit to rfavreau/local-audio-addon that referenced this pull request Nov 20, 2026
…oken endpoint

On by default in the add-on, bound to the hassio bridge address, and off
with a log line on a host that lacks it. Pins sendspin-cli to the branch of
Sendspin/sendspin-cpp-cli#110 until it is released.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Requires-Upstream Requires and Upstream Change in sendspin-cpp.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants