Skip to content

fix(api): let packaged TV apps open v2 sockets and read subtitle sidecars - #3327

Merged
Quick104 merged 4 commits into
Silo-Server:mainfrom
Brady3035:origin_fix
Nov 3, 2026
Merged

Quick104 merged 4 commits into
Silo-Server:mainfrom
Brady3035:origin_fix

Conversation

@Brady3035

@Brady3035 Brady3035 commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: N/A
Validation tasks: unblocks #1206 C1

Packaged TV web apps can't open any Silo v2 WebSocket. webOS and Tizen apps load their pages from the device, not from Silo, so the browser sends an Origin of null, file:// or an app scheme. The app can't change it. socketOriginAllowed refuses every one of those with 403 origin refused, so the events, playback-control and Watch Together sockets never open on a TV. Moonfin Smart-TV hits this today.

This change treats an opaque (null) or non-http(s) scheme:// Origin the same as a missing one, which native clients already send. The socket ticket still decides.

Subtitles from external and downloaded sidecars don't render on a TV either. handleSubtitle sets Access-Control-Allow-Origin: * only on the embedded-extract branch, so the 200 for an external or downloaded sidecar has no CORS header. The packaged app fetches it with an opaque Origin, and the browser discards the answer before the app can read it. Found on webOS: the request shows as failed with no response headers, while the server logs getPlaybackSubtitle 200.

Approach

The Origin check guards against cross-site WebSocket hijacking, where a hostile page opens a socket that the browser authenticates for it. These sockets don't take ambient credentials. They take a single-use ticket offered in Sec-WebSocket-Protocol, minted by an authenticated POST .../ws-ticket. /api/v2 sends no CORS headers on JSON routes, including the ticket mint, so a hostile page can't read a mint answer and has no ticket to offer, whatever Origin it sends. A sandboxed iframe that sends null is in the same position as an originless native client.

http and https origins keep the exact match against the public origin, the request's own origin and connected overlay origins, so a foreign web page (including one on localhost) is still refused. A value without scheme://, such as a bare host:port (which url.Parse reads as a scheme), is still refused. The shared check also covers the admin-logs socket. TV apps don't use it, but it takes the same ticket, so splitting the rule wasn't worth it. The frozen v1 checkWebSocketOrigin is unchanged, so a packaged app still can't open v1 sockets. On Silo, Smart-TV opens only /api/v2/events/ws. Its Xbox build serves the page from an ordinary http:// origin, which stays refused, so it will open that socket from native code instead, with no Origin.

An admin setting listing extra allowed origins was the other option. I didn't take it because every admin running TV clients would have to know to set it, and it guards nothing the ticket doesn't already guard.

docs/realtime-api.md and docs/architecture/native-raw-handshakes.md now describe the rule. The Origin header description on the four v2 socket operations in the OpenAPI contract (and the generated web types) says the same. The three #3434 breaking-change approvals are removed, since they match nothing once that change is on main and fail the contract check for any later spec change. Native Apple and Android clients send no Origin and need no change. jellycompat has no equivalent check to match.

The exported HandleSubtitle now sets Access-Control-Allow-Origin: * once, before anything else, so every answer carries it (external, embedded, downloaded, HEAD, and errors, including a malformed timestamp_offset 400), not just the embedded extract. A sidecar URL authorizes itself with the session ID and token in its query, not a cookie, so the wildcard lets a page read only a URL it already holds. The embedded branch and the font route already answer with *.

Validation

  • go test ./internal/api/handlers/: pass. The origin table now covers null, file://, an app scheme, a foreign localhost origin, and schemeless and bare host:port values.

  • go build ./..., go vet ./internal/api/..., gofmt, make lint-changed and make verify-local-paths: pass.

  • Test server on main (8b526b17f), before and after this commit. Each row is one handshake to /api/v2/events/ws with a fresh ticket:

  • TestSubtitleExternalSRTServesOriginalOrConvertedRepresentation now asserts Access-Control-Allow-Origin: * on the external sidecar. It fails without the fix and passes with it.

  • go test ./internal/api/handlers/, go vet, gofmt and make lint-changed pass on both commits.

  • Not run: the rest of the full gate (web, make test-go, contract verifiers). Nothing outside internal/api/handlers and two docs changed. Not checked on TV hardware. Packaged webOS and Tizen apps load index.html from a file:// document. Public reports show Origin: null from webOS and Origin: file:// from Tizen; which one appears depends on the web engine version. Both are accepted.

Evidence

Origin Before After
(none) 101 101
null 403 101
file:// 403 101
app://com.example.tv 403 101
http://localhost:8085 (foreign) 403 403
https://evil.test 403 403
evil.test:443 403 403
the server's own origin 101 101
null with an invalid ticket 403 401

Risks

Security: an opaque or non-web Origin no longer stops a handshake before the ticket check. This is safe only while every v2 socket authenticates with a ticket from the handshake protocols and never with a cookie. A future socket that accepts a cookie would need its own Origin rule. Browser-extension pages (chrome-extension://, moz-extension://) also pass the Origin check now. Like any other caller, they still need a ticket minted with the user's credentials.

A page that somehow holds a sidecar URL, with its session ID and token, can now read the subtitle across origins. That URL is already a bearer credential for the same bytes, the same as a stream URL.

Checklist

  • I read and can explain the complete diff.
  • This pull request addresses one concern.
  • Each test this pull request adds meets "Decide what to test" in CONTRIBUTING.md.
  • The Evidence section shows every change a user can see, or says there is none.

AI Disclosure

  • Harness: Claude Code
  • Tool(s): Claude Code
  • Model(s): claude-opus-5-5
  • Involvement: AI-assisted
  • Adversarial review: Claude Code /code-review on the full diff, looking for ways the new rule admits a hostile caller. It confirmed that /api/v2 sends no CORS headers and that every v2 socket requires the ticket. It found that a bare host:port Origin parsed as an app scheme and was accepted. That's fixed and has test rows now. It also raised extension origins, the admin-logs socket and v1 sockets; the Approach and Risks sections cover those.

🤖 Generated with Claude Code

Note

Accept opaque and non-web Origins on v2 sockets and set wildcard CORS on subtitle responses

  • Socket Origin validation in events_socket_v2.go now accepts the opaque Origin value (null) and non-HTTP(S) Origins in scheme:// form, matching how packaged TV apps connect with ticket auth. Matching HTTP(S) Origins and absent Origins still pass; malformed Origins stay rejected.
  • Moves the wildcard Access-Control-Allow-Origin assignment to the start of HandleSubtitle in stream_subtitle_offset.go, so all subtitle responses include the header, including error responses. Removes the old assignment in stream.go.
  • Updates Origin docs across realtime-api.md, native-raw-handshakes.md, openapi.json, and schema.ts.
  • Risk: sockets with any well-formed non-web Origin are now accepted — check the Origin-validation helper in events_socket_v2.go if stricter scheme checking is needed. HandleSubtitle now always sends Access-Control-Allow-Origin: *, including error paths.

Macroscope summarized e1a77f2.

Packaged TV web apps (webOS, Tizen) load their pages from the device, so
their WebSocket handshakes carry an Origin of "null", "file://" or an app
scheme. The v2 socket origin check refused all of these with 403, so the
events, playback-control and Watch Together sockets never opened on a TV.

Treat an opaque or non-http(s) Origin like a missing one. The single-use
ticket in the handshake protocols is what authorizes the socket, and a
cross-site page cannot read a ticket mint answer. http(s) origins keep the
exact public, request and overlay origin match.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@silo-triage silo-triage Bot added the size/M 50–199 added + deleted lines (all files); change volume, not priority. label Oct 31, 2026
@silo-kody

silo-kody Bot commented Oct 31, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@silo-triage silo-triage Bot added bug Something isn't working impact: compat Breaks a supported client or server path priority: P1 Core-path bug; painful workaround — next after P0 labels Oct 31, 2026
@coderabbitai

coderabbitai Bot commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review.

Walkthrough

The events socket Origin check now accepts opaque and qualifying non-HTTP(S) Origins. The subtitle handler sets a wildcard CORS header before authentication and request validation. Tests and documentation cover the updated behavior.

Changes: Socket Origin handling

Layer / File(s) Summary
Origin acceptance, tests, and documentation
internal/api/handlers/events_socket_v2.go, internal/api/handlers/socket_origin_proxy_test.go, internal/api/handlers/watch_together_socket_v2_test.go, docs/architecture/native-raw-handshakes.md, docs/realtime-api.md
socketOriginAllowed accepts opaque (null) and parsed non-HTTP(S) Origins written with ://. Tests cover accepted app Origins, rejected malformed and foreign Origins, and the updated Watch Together malformed-request case. Documentation describes HTTP(S) scheme-and-host matching, treatment of opaque and non-web Origins, and socket authentication requirements.

Subtitle CORS header

Layer / File(s) Summary
Subtitle response CORS behavior
internal/api/handlers/stream.go, internal/api/handlers/stream_subtitle_identity_test.go
handleSubtitle sets Access-Control-Allow-Origin: * before authentication and request checks. The embedded subtitle helper no longer sets the header. The conversion test checks the header on WebVTT responses.

Estimated code review effort: 2 (Simple) | ~12 minutes

Change: Bug fix

Possibly related PRs

  • Silo-Server/silo-server#2739: Adds admission and lifecycle handling to the v2 event-socket path, which includes the Origin and ticket admission flow.
  • Silo-Server/silo-server#3187: Changes v2 event-socket ticket credentials and authority validation, within the same handshake authorization boundary.

Suggested labels: go, api-v2, impact: usability, impact: security

Suggested reviewers: zzebrahz

Merge Risk: Minimal · up to 99721

No actionable issue is identified for this change; it is mergeable after the normal checks.

Security architecture risk: Low · up to f3909

The change broadens cross-origin access without removing the independent authentication and ownership checks. No introduced authorization bypass was established. Risk remains concentrated in preserving ticket confidentiality and keeping subtitle access tied to existing account and playback-session authority.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The maximum functional scope includes realtime events, playback control, room synchronization and privileged log streaming within the deployment. Newly admitted Origins still need credentials carrying the corresponding existing authority; subtitle readability expands for authorized sidecar responses on both API versions.

Security Findings and Attack Paths

  • inferred — An attacker-controlled opaque Origin can now pass the preliminary socket gate, but Origin acceptance alone does not complete an attack path. The inspected consumers still require a valid ticket and current authority. No newly reachable unauthenticated upgrade or cross-account subtitle disclosure was established.

Trust Boundaries and Controls

  • inferred — For newly accepted opaque Origins, security depends on possession of a confidential, authority-bound ticket rather than browser-origin provenance. The inspected mint operations require authenticated authority, and no browser-readable cross-origin ticket response was identified in the application routes. Deployment-added headers remain outside this verification.

Resilience and Maintainability Implications

  • observed — The Origin change preserves ticket expiry, audience separation and single-use consumption. Repeated or concurrent use does not create additional authority, and failed post-consumption authorization cannot reuse the consumed ticket.

Hardening Proposals

  • proposed — Preserve a deployed boundary check that an opaque browser context cannot read ticket-mint responses and that every shared-Origin socket rejects absent, replayed or wrong-scope tickets. This would detect future CORS or authentication drift without treating Origin as the authoritative credential.
Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documenta… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title clearly summarizes the two main changes: support for packaged TV apps opening v2 sockets and reading subtitle sidecars.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description check Passed The description is specific and on-topic. It explains that packaged TV apps (webOS and Tizen) send opaque or non-HTTP(S) Origins that the v2 socket check rejects, and that the change accepts those Ori…
Full details: Description check

Explanation

The description is specific and on-topic. It explains that packaged TV apps (webOS and Tizen) send opaque or non-HTTP(S) Origins that the v2 socket check rejects, and that the change accepts those Origins while keeping ticket auth. It also covers the subtitle CORS fix in handleSubtitle, the documentation updates, validation runs, and a test table that matches the code and raw summary. The description clearly describes parts of the changeset, so it passes.

Full details: Docstring Coverage

Explanation

Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 4 functions across 5 files.

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

CodeRabbit Verify

  • Run CodeRabbit Verify to test the changes in this pull request.
Recent review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: fbff2640-b701-494f-8b2a-a109bad7a765
Commits

Reviewing files that changed from the base of the PR and between f39099d and 9972165.

Files selected for processing: 1
  • internal/api/handlers/stream.go
Files with no reviewable changes: 1
  • internal/api/handlers/stream.go

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 3 remain after this review.

@macroscopeapp

macroscopeapp Bot commented Oct 31, 2026

Copy link
Copy Markdown
  • internal/api/handlers/events_socket_v2.go: Packaged TV/desktop clients can now connect to v2 realtime sockets that previously refused their Origin. The before/after handshake table is under Validation, not Evidence; include handshake response excerpts for the same test setup in Evidence and name the client surface and build/commit.

Suggested fix: Move or repeat the handshake table under Evidence and add the surface and build/commit.

Automated check: Macroscope check run agent (gpt-6-luna). Evidence was not reviewed for correctness.

Posted via Macroscope — Visible change evidence

@coderabbitai coderabbitai Bot added api-v2 API v2 / Huma migration program (epic #135); long-running, stacked by phase go Pull requests that update go code impact: security Auth, privacy, or permission boundary impact: usability Core flow broken or severely blocked labels Oct 31, 2026
@Brady3035

Copy link
Copy Markdown
Contributor Author

This should be ready, I'm making Moonfin for webOS compatible with Silo and this change blocks any app on those tv's not just Moonfin.

Packaged TV web apps (webOS, Tizen) fetch subtitle sidecars from a page
with an opaque Origin. Only the embedded-extract branch of the subtitle
handler set Access-Control-Allow-Origin, so the browser discarded a 200
for an external or downloaded sidecar and the subtitle never rendered.

Set the header once at the top of the handler so every branch, including
errors and HEAD, carries it. The session token rides in the URL, not a
cookie, so the wildcard grants nothing a cross-site page could use.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Brady3035 Brady3035 changed the title fix(api): let packaged apps with an opaque Origin open v2 sockets fix(api): let packaged TV apps open v2 sockets and read subtitle sidecars Nov 1, 2026
@silo-kody

silo-kody Bot commented Nov 1, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@Brady3035

Copy link
Copy Markdown
Contributor Author

Had to make an edit for subtitles.

@macroscopeapp

macroscopeapp Bot commented Nov 1, 2026

Copy link
Copy Markdown

Evidence is incomplete for these visible changes:

  • internal/api/handlers/events_socket_v2.go: The Evidence table shows handshake status changes, but does not identify the client surface or the exact before-and-after server commits. Add the same /api/v2/events/ws response excerpts with the packaged-TV surface and both commits named.
  • internal/api/handlers/stream.go: The Evidence section does not show the subtitle sidecar change. Add before-and-after response excerpts for the same sidecar request showing the Access-Control-Allow-Origin header, and name the client surface and server commits.

Automated check: Macroscope check run agent (gpt-6-luna). Evidence was not reviewed for correctness.

Posted via Macroscope — Visible change evidence

@Quick104 Quick104 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.

Two low-severity findings. Neither affects the socket authorization argument, which holds up: all four v2 sockets consume and recheck a ticket from Sec-WebSocket-Protocol, and the native API sends no CORS headers and reads no cookies, so a hostile page has no ticket to offer.

1. The published v2 contract still describes the old Origin rule (low). socketOriginHeaderDoc in internal/apiv2/admin_logs_socket.go documents the Origin header on all four socket operations: "Browser origin must match the configured public origin, the request origin, or a connected network access overlay origin." After this PR, null and non-web scheme origins are accepted, so contracts/api/v2/openapi.json and web/src/api/v2/schema.ts disagree with the code and with the updated prose docs. A third-party TV client reading the contract would conclude its packaged app is refused. Repair: reword the string and regenerate both artifacts. I'm fixing this in a commit on this branch, so there's no need to change it yourself. That commit also empties the three #3434 entries in contracts/api/v2/breaking-approvals.json. They now match nothing on main, so verify-apiv2-contract fails on any spec change until they're removed.

I merged main into the branch first (99721650d), because #3331 changed streamEmbeddedSubtitle. It merged cleanly.

🤖 Claude Code (claude-opus-5-5)

Comment thread internal/api/handlers/stream.go Resolved
…itle answer

The v2 contract's Origin description on the four socket operations still
said every browser origin must match, while the handler now accepts
opaque and non-web scheme origins. Reword it and regenerate the OpenAPI
artifact and web types. Empty the three Silo-Server#3434 breaking-change approvals,
which match nothing once that change is on main and fail the contract
check for any later spec change.

Set Access-Control-Allow-Origin at the top of the exported HandleSubtitle
instead of handleSubtitle, so a malformed timestamp_offset 400 is
readable from a packaged app too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@silo-kody

silo-kody Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@Quick104

Quick104 commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

Review summary

Reviewed head: e1a77f212 (99721650d plus review fixes). 99721650d is the PR's two commits with main merged in, because #3331 changed streamEmbeddedSubtitle. The merge was clean.

Fit: 9/10 · Readiness: 8/10 — conditional (assuming CI is green)

Fit: the change lets third-party packaged TV clients use the native realtime sockets without a new setting, and makes the change once, in the shared check. The security argument holds. All four v2 sockets (events, playback control, Watch Together, admin logs) authorize only with a single-use ticket offered in Sec-WebSocket-Protocol. The native API has no CORS middleware and reads no cookies. The only wildcard CORS handlers are on jellycompat and the media proxy, without credentials, and neither mints native tickets. A hostile page therefore has no ticket to offer, whatever Origin it sends. http and https origins keep the exact match.

Readiness: the socket and subtitle tests this PR adds fail on main (opaque packaged app, file packaged app, app scheme, and the external-SRT Access-Control-Allow-Origin assertion) and pass on the head. The one open condition is the Evidence check below.

Addressed

  • The OpenAPI Origin description on the four socket operations now states the new rule. openapi.json and web/src/api/v2/schema.ts were regenerated. The three #3434 breaking-change approvals, which match nothing once that change is on main, were removed so verify-apiv2-contract passes. Earlier spec changes such as feat(diagnostics): accept the roku platform #3298 cleared their predecessors' approvals the same way.
  • A malformed timestamp_offset 400 now carries Access-Control-Allow-Origin: *. The header moved to the exported HandleSubtitle, and TestSubtitleTimestampOffsetExternalTrack checks it on every row. The 400 rows fail on 99721650d.

Left for maintainers

  • The Evidence check reports "Evidence required" (action_required). The PR body's handshake table is from the author's test server, and nothing was run on TV hardware.
  • The header also reaches /api/v1/stream/{session_id}/subtitles/{track}, which shares the handler. The v1 embedded branch already sent it, so v1 now answers its other sidecar branches the same way.
  • Packaged apps still get no CORS answer from /api/v2 JSON routes, including the ticket mint, which carries Authorization and so needs a preflight. These calls work only on TV runtimes that exempt packaged apps from CORS for API requests. The author reports that this holds for Moonfin on webOS. I could not confirm it.

Checks

  • Validated features: no passed case reaches this code. Validation tasks: unblocks Active sessions / now-playing / remote control — Server #1206 C1 (not yet run). The PR body is updated to match.
  • User manual: unaffected. No siloserver.org page describes the socket Origin rule or packaged TV apps.
  • Clients: Apple and Android send no Origin and need no change. jellycompat's socket accepts every origin already, and frozen v1 sockets keep their check.
  • Cross-provider review (Codex gpt-6.1-sol, one round on 99721650d): no further findings.

🤖 Claude Code (claude-opus-5-5)

@Quick104
Quick104 merged commit 527e404 into Silo-Server:main Nov 3, 2026
19 of 21 checks passed
@Brady3035
Brady3035 deleted the origin_fix branch November 3, 2026 17:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

api-v2 API v2 / Huma migration program (epic #135); long-running, stacked by phase bug Something isn't working go Pull requests that update go code impact: compat Breaks a supported client or server path impact: security Auth, privacy, or permission boundary impact: usability Core flow broken or severely blocked priority: P1 Core-path bug; painful workaround — next after P0 size/M 50–199 added + deleted lines (all files); change volume, not priority.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants