Skip to content

feat(playback): open the control socket with a v2 ticket - #378

Merged
Quick104 merged 3 commits into
mainfrom
apiv2-stack/30-control-socket-v2
Sep 23, 2026
Merged

Quick104 merged 3 commits into
mainfrom
apiv2-stack/30-control-socket-v2

Conversation

@Quick104

Copy link
Copy Markdown
Contributor

Problem

The player's remote-control socket (inventory row 85) still upgraded /api/v1/playback/sessions/{id}/control/ws and sent the account's bearer token in the Authorization header (PlaybackRealtimeClient.makeRequest). A 1.0 server answers every v1 call except health with 410, so SiloRemote and other controllers would lose the player.

APIv2Client.playbackControlRequest already built the v2 handshake, but nothing called it. Its ticket builder also refused plain-http servers other than loopback (controlRequiresTLS), so switching to it as written would have broken remote control on plain-http LAN servers.

Solution

  • Fresh ticket on every connect. Each connect and reconnect calls APIv2Client.playbackControlHandshake(sessionID:installationID:auth:) in APIv2Client+Playback.swift. It reads GET /api/v2/playback/sessions/control/capabilities (200), then mints a ticket with POST /api/v2/playback/sessions/{session_id}/control/ws-ticket (200, {installation_id}). Both requests run through playbackRequest, which fences them to the captured owner. The upgrade goes to /api/v2/playback/sessions/{session_id}/control/ws and carries Sec-WebSocket-Protocol: silo.playback-control.v2, silo.ticket.<ticket>. It sends no Authorization header and never reuses a ticket.
  • Session owner. PlayerViewModel binds the socket through PlaybackSessionBridge.committedProtocolV3Authority(sessionId:), so tickets are minted for the owner and installation_id that started the committed session. A late bind for a replaced session binds nothing.
  • D11. The client-side TLS-only rule and PlaybackSequencedError.controlRequiresTLS are gone. An http server gets a ws upgrade and an https server gets wss. Ticket validation stays in place: protocol, positive lifetimes (a connection lifetime above one day is refused), ticket charset, a UUID session id, and a server URL with no credentials, query or fragment.
  • Connection lifetime. The socket closes when the ticket's max_connection_seconds runs out, and the loop reconnects with a new ticket.
  • Terminal failures stop the loop. An owner change, a capability that does not serve the handshake (controlUnavailable) or a v1-only server (serverUpdateRequired) marks realtime control unavailable right away. Before this, each of these burned the 8-attempt reconnect budget. Transient failures keep the existing backoff and circuit breaker. HTTPError.requestIdentityChanged counts as transient: the HTTP client also throws it while an identity transition that keeps the owner (removing another server, a refused sign-out) holds the dispatch gate, and the owner check before the next attempt still stops the loop on a real owner change.
  • Dispatch gate. The handshake waits for HTTPClient.waitForRequestDispatchOpen() before minting, so a running identity transition does not use up the reconnect budget.
  • Owner fence on frames. Inbound frames are dropped, and the loop ends, once the session's owner is no longer current.
  • Stale socket. A superseded loop no longer closes the socket of the session that replaced it: the binding is checked before closeSocket().
  • Deleted. The v1 URL builder and its bearer header, PlaybackRealtimeTransportError.serverUrlNotConfigured, invalidServerURL and missingAccessToken, and APIv2Client.playbackControlRequest, which moved to the playback extension under its new name.

Frames are unchanged: the server's v2 handler "changes no frame".

Failure outcomes (createPlaybackControlSocketTicket, natural_idempotent)

Outcome Behavior
Definite success (200, valid ticket) Upgrade once with that ticket, then discard it.
Definite failure: capability not served or not allowed No mint. Realtime control is marked unavailable and the loop stops. Local playback continues.
Definite failure: owner changed, or v1-only server No mint, or the minted ticket is not used. The loop stops and control is marked unavailable.
Definite failure: other non-2xx (403/404/409/429/5xx), a requestIdentityChanged refusal while the owner is unchanged, or the upgrade is refused Counted as a failed connect. The client backs off (0.5/1/2/5 s) and mints a new ticket on the next try. After 8 consecutive failures it marks control unavailable.
Uncertain (sent, no response) Same as a failed connect. Minting is naturally idempotent: an unused ticket expires within 30 s, so the next attempt mints a new one. Nothing is held.

Validation

  • iOS, tvOS and macOS builds passed on this branch.
  • Focused tests passed on iOS (PlaybackRealtimeClientTests, APIv2ContractTests, PlaybackProtocolV3Tests, PlaybackSessionTransportTests) and on tvOS (the same four classes plus SubtitleAIControllerTests).
  • scripts/ci/check-no-api-v1.sh passed. PlaybackRealtimeClient.swift drops to 0 v1 literals. Its allowlist entry is left for Z1.
  • New and updated tests (on StubURLProtocol/APIv2TestStub or injected closures) cover:
    • the mint: GET capabilities, then POST ws-ticket with {"installation_id": …} and X-Profile-Id, under a base-path server URL;
    • the handshake for http://192.168.1.20:8096/silo: ws://…/silo/api/v2/playback/sessions/{id}/control/ws, with both subprotocols and no Authorization header;
    • a disallowed capability throwing controlUnavailable without a mint, a 409 on the mint surfacing as a problem, and a non-canonical session id making no request;
    • handshake construction for https→wss and http→ws, and refusal of bad schemes, credentials, queries, session ids, protocols, lifetimes (including a max_connection_seconds that would overflow the lifetime timer) and ticket characters;
    • reconnects minting one ticket per attempt until the circuit breaker trips at 8, controlUnavailable stopping after one mint, a non-current owner minting nothing, and a requestIdentityChanged refusal under an unchanged owner minting a second ticket and leaving control available.
  • A standalone check on the build Mac confirmed that URLSessionWebSocketTask sends a Sec-WebSocket-Protocol header set on the URLRequest unchanged, sends no Origin header (which the server's origin check accepts), and completes the handshake over plain ws.
  • The final stack passed the full suites (iOS 1981 tests and tvOS 1792 tests, 0 failures), the macOS build and the v1 path guard, and every branch in the stack builds on its own.

Risks and follow-ups

  • Not verified manually. The plan's check (iOS remote controlling tvOS against a live server) was not run. The server side of the handshake was checked against source at 84ed9e596 (playback_control_socket_v2.go), not against a live server.
  • Refresh on the mint. HTTPClient.shouldAttemptRefresh excludes the ws-ticket POST from 401 refresh. The capability GET before it does refresh, so an expired access token is normally renewed before the mint. If the token expires between the two requests, that attempt fails and the next reconnect succeeds.
  • Lifetime with short access tokens. The server ends a connection when the access token behind the ticket expires. The client treats that as a dropped connection and reconnects after 0.5 s with a new ticket.
  • Open-PR conflicts. Open PR feat(watch-party): add iOS and tvOS rooms and synchronized playback #347 (watch party) edits PlayerViewModel.swift and APIv2PlaybackModels.swift, so expect textual conflicts.

AI disclosure

Code and description written by Claude Opus 5.5 (claude-opus-5-5) agents in Claude Code (T3 Code), orchestrated by a Claude Code workflow.


Part 30 of 50 in the Apple API v2 stack. Base: apiv2-stack/29-playback-sessions-v2. Merge in order from the bottom of the stack. The plan and full index are in PR 01.

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Advanced

Run ID: 68ac2ce5-04d6-44a6-a7a4-d64195cd82c1

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Quick104 has reached the 50-credit limit for trial accounts. To continue receiving code reviews, upgrade your plan.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-23T13:46:39.840795Z b8e695f New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@Quick104

Copy link
Copy Markdown
Contributor Author

Code review summary

Reviewed head: 0f3aa8bf (apiv2-stack/30-control-socket-v2).

Process: an adversarial review of this PR's diff with each candidate finding independently verified before any fix, a simplify pass for medium and larger PRs, and a whole-stack review across contract conformance, authority and failure handling, data integrity, user-visible behavior and cross-PR integration.

Verified findings, all fixed on this branch:

  • minor: A brief network-client lock during an account change permanently stops remote control, even when the owner never changes
  • minor: An oversized max_connection_seconds overflows the lifetime timer and crashes the app

Validation: this branch builds on its own for iOS, tvOS and macOS, and its focused tests passed. The completed stack passed the full iOS suite (1981 tests) and tvOS suite (1792 tests) with 0 failures, the macOS build and the v1 path guard. The final stack was also exercised on iOS and tvOS simulators against a v1/v2 bridge server: sign-in (password and QR), restore, browse, search, detail, favorites and watchlist, playback (direct play, transcode, subtitles, stop), audiobooks, downloads with offline playback, settings, requests, profiles, push registration and diagnostics. Server logs showed no /api/v1 request from the new builds except the retained health probe.

Remaining: no open verified findings. Merge in stack order.

Mergeability: 8/10 — conditional. The approach holds up and every verified finding is fixed. Conditions: this PR's CI must pass (it was pending at review time), and the owner still plans a physical-device check of the completed stack.

Review by Claude Opus 5.5 (claude-opus-5-5) agents in Claude Code (T3 Code).

@Quick104
Quick104 force-pushed the apiv2-stack/29-playback-sessions-v2 branch from 5c233a7 to c425351 Compare September 23, 2026 13:19
@Quick104
Quick104 force-pushed the apiv2-stack/30-control-socket-v2 branch from 0f3aa8b to 2e3a00b Compare September 23, 2026 13:19
@Quick104
Quick104 force-pushed the apiv2-stack/29-playback-sessions-v2 branch from c425351 to 6b2151c Compare September 23, 2026 13:41
Base automatically changed from apiv2-stack/29-playback-sessions-v2 to main September 23, 2026 13:41
Quick104 and others added 3 commits September 23, 2026 09:41
The player's remote-control socket still upgraded
/api/v1/playback/sessions/{id}/control/ws with the account's bearer token
in the Authorization header. A 1.0 server answers every v1 call except
health with 410, so remote control would stop working. The v2 ticket
builder that already existed had no callers. It also refused plain-http
servers other than loopback, so moving to it unchanged would have broken
remote control on plain-http LAN servers.

Every connect and reconnect now checks the control capability, mints a
single-use ticket with POST .../control/ws-ticket for the session's
installation under the owner that started the session, and upgrades
/api/v2/playback/sessions/{id}/control/ws. The ticket travels only as the
second Sec-WebSocket-Protocol entry. No bearer header is sent and no
ticket is reused. Following D11, a plain-http server gets a ws upgrade.
The socket closes and reconnects with a new ticket when
max_connection_seconds runs out. An owner change, a server that does not
serve the handshake, or a v1-only server ends the connection loop at
once instead of burning the reconnect budget. Frames are dropped once the
session's owner is no longer current. The v1 URL builder and its
transport errors are deleted.

Stack-PR: W2-D
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…keep the owner

The control loop treated HTTPError.requestIdentityChanged as terminal. The
HTTP client throws it whenever any identity transition holds the dispatch
gate, including ones that leave the session's owner in place, such as
removing another server or a refused sign-out. A reconnect that overlapped
one marked realtime control unavailable for the rest of the session.

That error now takes the ordinary backoff, and the owner check at the top
of each attempt still stops the loop when the owner really changed. The
default handshake also waits for the dispatch gate to reopen before minting
a ticket, so a running transition does not use up the reconnect budget.

Stack-PR: W2-D
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…fetime

The ticket's max_connection_seconds had no upper bound, and the lifetime
timer multiplies it into nanoseconds as UInt64. A value of 18_446_744_074
or more trapped on overflow and crashed the app mid-playback.

The handshake now refuses a ticket whose lifetime exceeds one day as an
invalid response, like its other malformed fields. The server sends four
hours.

Stack-PR: W2-D
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@Quick104
Quick104 force-pushed the apiv2-stack/30-control-socket-v2 branch from 2e3a00b to b8e695f Compare September 23, 2026 13:41
@Quick104
Quick104 merged commit 793b22c into main Sep 23, 2026
3 of 6 checks passed
@Quick104
Quick104 deleted the apiv2-stack/30-control-socket-v2 branch September 23, 2026 13:41

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b8e695fd45

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

UUID(uuidString: sessionID) != nil,
var url = URLComponents(string: serverURL),
["http", "https"].contains(url.scheme), let host = url.host,
["http", "https"].contains(url.scheme), url.host != nil,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Normalize the server URL scheme before validating it

When a saved server URL uses a valid case variant such as HTTPS://host, URLComponents preserves that spelling, so this case-sensitive check rejects the freshly minted ticket with invalidResponse and remote control exhausts its reconnect budget. This can affect legacy-migrated or paired entries because ServerRegistry.normalize(url:) preserves the original scheme spelling, while the replaced v1 request builder explicitly lowercased the scheme. Compare a lowercased scheme here before selecting ws or wss.

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant