Skip to content

Add temporary phone identity handoff for remote playback - #360

Merged
Quick104 merged 1 commit into
mainfrom
codex/remote-playback-phone-identity
Jul 10, 2026
Merged

Quick104 merged 1 commit into
mainfrom
codex/remote-playback-phone-identity

Conversation

@Quick104

@Quick104 Quick104 commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • extend device login with a dedicated remote_playback temporary-session purpose
  • bind approval to the authenticated phone user and selected profile
  • issue a one-time, profile-scoped TV session capped at 24 hours
  • advertise protocol-v2 handoff capability and add the required database constraints

Why

Phone-initiated TV playback should use the phone's server, account, and selected profile so permissions, resume state, progress, and preferences are attributed correctly. Ordinary remote control of playback already on the TV remains TV-owned.

The phone approves the server-issued match code; no phone bearer or profile credentials cross the LAN control channel.

Companion clients

Validation

  • make migrate-validate
  • GOWORK=off go test ./internal/auth ./internal/api/handlers ./internal/access
  • git diff --check

Summary by CodeRabbit

  • New Features
    • Added remote playback handoff support to device login.
    • Added an endpoint to advertise handoff capabilities and supported protocol versions.
    • Added an authenticated approval flow for remote playback requests.
    • Device login responses now include purpose, temporary status, profile details, and session expiration information.
  • Bug Fixes
    • Improved handling of invalid, conflicting, expired, or unauthorized device approval requests.
  • Tests
    • Added coverage for capability reporting and device-login validation scenarios.

@coderabbitai

coderabbitai Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Device login now supports purpose-aware requests, temporary remote playback approvals, profile validation and token issuance, capability discovery, and expanded API responses. Database constraints and routes were updated, with unit and handler tests covering the new behavior.

Changes

Remote playback handoff

Layer / File(s) Summary
Device login data and persistence
migrations/sql/..., internal/auth/device_login.go
Device login records and database persistence store client purpose, temporary state, and approved profile identity.
Purpose-aware approval and polling
internal/auth/device_login.go, internal/auth/device_login_test.go
The service separates login and remote playback approval, validates profile ownership, caps temporary session expiry, mints profile tokens, and returns expanded poll data.
Capability and handoff API integration
internal/api/handlers/auth_device.go, internal/api/router.go, internal/api/handlers/auth_device_test.go
Handlers and routes expose capability discovery and protected handoff approval while propagating metadata and mapping new service errors.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant DeviceClient
  participant AuthHandler
  participant DeviceLoginService
  participant UserStore
  participant ProfileTokenService
  DeviceClient->>AuthHandler: POST /device/approve-handoff
  AuthHandler->>DeviceLoginService: ApproveRemotePlayback
  DeviceLoginService->>UserStore: validate profile ownership
  DeviceClient->>AuthHandler: poll device login
  AuthHandler->>DeviceLoginService: Poll
  DeviceLoginService->>ProfileTokenService: mint profile token
  ProfileTokenService-->>DeviceLoginService: profile token
  DeviceLoginService-->>AuthHandler: profile and session data
  AuthHandler-->>DeviceClient: temporary poll response
Loading
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: adding temporary remote-playback handoff support.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/remote-playback-phone-identity

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

@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: e73cd6c2a1

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +496 to +500
if record.Temporary {
remoteExpiry := now.Add(remotePlaybackSessionTTL)
if remoteExpiry.Before(sessionExpiresAt) {
sessionExpiresAt = remoteExpiry
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve the temporary-session cap across refreshes

When a remote_playback handoff is polled on deployments with the normal refresh expiry longer than 24h (the default is 30d), this only caps the auth_sessions row at creation. The response also includes a standard refresh token, and auth.Service.Refresh unconditionally calls ExtendExpiresAt(now + s.jwt.RefreshExpiry()), so refreshing before 24h converts the temporary TV session into a normal long-lived session. Please persist a per-session cap/temporary marker or mint refresh credentials that cannot extend past the 24h handoff limit.

Useful? React with 👍 / 👎.

Comment on lines +13 to +16
ADD CONSTRAINT device_login_requests_approved_profile_fkey
FOREIGN KEY (approved_by_user_id, approved_profile_id)
REFERENCES user_profiles(user_id, id)
ON DELETE SET NULL;

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 Avoid reintroducing a Postgres profile FK

On userdb.backend=sqlite deployments, valid profiles live in per-user SQLite stores rather than public.user_profiles (the repo already dropped the analogous user_devices FK for this reason in 20260701225607_drop_user_devices_profile_fkey.sql). ApproveRemotePlayback validates the profile through UserStoreProvider, but this FK then rejects the approved_profile_id update for those valid SQLite-backed profiles, causing handoff approval to return an internal DB error. Keep this cleanup/ownership check in application code instead of requiring the profile row to exist in Postgres.

Useful? React with 👍 / 👎.

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 1

🧹 Nitpick comments (3)
migrations/sql/20260709233718_add_remote_playback_handoff_to_device_login.sql (2)

13-16: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Deleting an approved profile also clears approved_by_user_id, losing the approver identity.

With MATCH SIMPLE (default), when a referenced user_profiles row is deleted, ON DELETE SET NULL nulls both FK columns — approved_profile_id and approved_by_user_id — even though approved_by_user_id identifies the user account, not the profile, and the account may still exist. This erases the approval audit trail (who approved the login) purely because a profile was later deleted.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@migrations/sql/20260709233718_add_remote_playback_handoff_to_device_login.sql`
around lines 13 - 16, The composite foreign key
device_login_requests_approved_profile_fkey incorrectly clears
approved_by_user_id when an approved profile is deleted. Replace this
relationship with a foreign key on approved_profile_id only, referencing the
profile identifier and using ON DELETE SET NULL, while retaining
approved_by_user_id independently so the approver audit identity is preserved.

8-16: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

New constraints will table-scan and block writes; consider NOT VALID + VALIDATE CONSTRAINT.

Static analysis flags all three new constraints (two CHECKs and the FK). Adding them without NOT VALID acquires a lock and scans the full table, blocking writes on device_login_requests for the duration. Since this is a live production table, splitting into ADD CONSTRAINT ... NOT VALID followed by a separate VALIDATE CONSTRAINT (in a later transaction/migration) avoids the write-blocking scan.

♻️ Proposed fix using NOT VALID + VALIDATE CONSTRAINT
 ALTER TABLE device_login_requests
     ADD CONSTRAINT device_login_requests_client_purpose_check
-        CHECK (client_purpose IN ('device_login', 'remote_playback')),
+        CHECK (client_purpose IN ('device_login', 'remote_playback')) NOT VALID,
     ADD CONSTRAINT device_login_requests_temporary_purpose_check
-        CHECK (temporary = (client_purpose = 'remote_playback')),
+        CHECK (temporary = (client_purpose = 'remote_playback')) NOT VALID,
     ADD CONSTRAINT device_login_requests_approved_profile_fkey
         FOREIGN KEY (approved_by_user_id, approved_profile_id)
         REFERENCES user_profiles(user_id, id)
-        ON DELETE SET NULL;
+        ON DELETE SET NULL NOT VALID;
+
+ALTER TABLE device_login_requests VALIDATE CONSTRAINT device_login_requests_client_purpose_check;
+ALTER TABLE device_login_requests VALIDATE CONSTRAINT device_login_requests_temporary_purpose_check;
+ALTER TABLE device_login_requests VALIDATE CONSTRAINT device_login_requests_approved_profile_fkey;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@migrations/sql/20260709233718_add_remote_playback_handoff_to_device_login.sql`
around lines 8 - 16, Update the migration’s constraints in the ALTER TABLE
statement to use NOT VALID for both CHECK constraints and the approved_profile
foreign key, then add separate validation statements in a later transaction or
follow-up migration using VALIDATE CONSTRAINT for each named constraint.

Source: Linters/SAST tools

internal/api/router.go (1)

1647-1647: 🔒 Security & Privacy | 🔵 Trivial | 💤 Low value

/device/capability is unconditionally registered and unrated, while sibling public device endpoints are rate-limited.

/device/start, /device, and /device/poll are conditionally wrapped with deps.RateLimitMW.AuthEndpointHandler(...) when available, but /device/capability is registered before that check with no rate-limit wrapper. Low risk given it's static/stateless, but worth aligning for consistency with the rest of the /auth/device/* surface.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/api/router.go` at line 1647, Align the /device/capability route
registration with the other public device endpoints by applying
deps.RateLimitMW.AuthEndpointHandler when rate limiting is available, while
preserving an unwrapped fallback when it is not. Move or restructure the
registration near the existing rate-limit conditional, using
authHandler.HandleDeviceCapability as the handler.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/api/handlers/auth_device.go`:
- Around line 77-82: Update HandleDeviceCapability to advertise
RemotePlaybackHandoff only when the handoff route is available: verify the same
viewerAccessMiddleware/handler wiring condition used when mounting
/auth/device/approve-handoff and ensure h.device is non-nil. Return false
otherwise, while preserving the ProtocolVersions response.

---

Nitpick comments:
In `@internal/api/router.go`:
- Line 1647: Align the /device/capability route registration with the other
public device endpoints by applying deps.RateLimitMW.AuthEndpointHandler when
rate limiting is available, while preserving an unwrapped fallback when it is
not. Move or restructure the registration near the existing rate-limit
conditional, using authHandler.HandleDeviceCapability as the handler.

In
`@migrations/sql/20260709233718_add_remote_playback_handoff_to_device_login.sql`:
- Around line 13-16: The composite foreign key
device_login_requests_approved_profile_fkey incorrectly clears
approved_by_user_id when an approved profile is deleted. Replace this
relationship with a foreign key on approved_profile_id only, referencing the
profile identifier and using ON DELETE SET NULL, while retaining
approved_by_user_id independently so the approver audit identity is preserved.
- Around line 8-16: Update the migration’s constraints in the ALTER TABLE
statement to use NOT VALID for both CHECK constraints and the approved_profile
foreign key, then add separate validation statements in a later transaction or
follow-up migration using VALIDATE CONSTRAINT for each named constraint.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 56cec383-8bff-4bff-b87d-3189938b63ff

📥 Commits

Reviewing files that changed from the base of the PR and between c25ad81 and e73cd6c.

📒 Files selected for processing (6)
  • internal/api/handlers/auth_device.go
  • internal/api/handlers/auth_device_test.go
  • internal/api/router.go
  • internal/auth/device_login.go
  • internal/auth/device_login_test.go
  • migrations/sql/20260709233718_add_remote_playback_handoff_to_device_login.sql

Comment on lines +77 to +82
func (h *AuthHandler) HandleDeviceCapability(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, deviceLoginCapabilityResponse{
RemotePlaybackHandoff: true,
ProtocolVersions: []int{2},
})
}

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail
printf 'Files:\n'
git ls-files 'internal/api/handlers/auth_device.go' 'internal/api/router.go' 'internal/**/router.go' | sed 's#^`#-` #'
printf '\nOutline auth_device.go:\n'
ast-grep outline internal/api/handlers/auth_device.go --view expanded
printf '\nOutline router.go candidates:\n'
for f in $(git ls-files 'internal/**/router.go'); do echo "--- $f"; ast-grep outline "$f" --view expanded | sed -n '1,220p'; done

Repository: Silo-Server/silo-server

Length of output: 11260


🏁 Script executed:

#!/bin/bash
set -euo pipefail
printf 'auth_device.go lines:\n'
cat -n internal/api/handlers/auth_device.go | sed -n '1,220p'
printf '\nrouter-related occurrences:\n'
rg -n "approve-handoff|HandleDeviceCapability|viewerAccessMiddleware|UserStoreProvider|device capability|RemotePlaybackHandoff|ApproveRemotePlayback|remotePlaybackHandoff" internal -S

Repository: Silo-Server/silo-server

Length of output: 37488


🏁 Script executed:

#!/bin/bash
set -euo pipefail
printf 'AuthHandler definition/constructor:\n'
ast-grep outline internal/api/handlers/auth.go --view expanded 2>/dev/null || true
rg -n "type AuthHandler struct|func NewAuthHandler|device\s+auth\.|handle.*Device|approve-handoff" internal/api/handlers internal/api/router.go -S
printf '\nrouter slice around device routes:\n'
sed -n '1608,1712p' internal/api/router.go | cat -n

Repository: Silo-Server/silo-server

Length of output: 13300


🏁 Script executed:

#!/bin/bash
set -euo pipefail
cat -n internal/api/handlers/auth_device.go | sed -n '213,290p'

Repository: Silo-Server/silo-server

Length of output: 3007


Return remote_playback_handoff only when the handoff route is actually wired. HandleDeviceCapability always advertises support, but /auth/device/approve-handoff is only mounted when viewerAccessMiddleware exists, and the device handlers return 503 when h.device == nil. Clients can be sent to a feature that isn’t available.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/api/handlers/auth_device.go` around lines 77 - 82, Update
HandleDeviceCapability to advertise RemotePlaybackHandoff only when the handoff
route is available: verify the same viewerAccessMiddleware/handler wiring
condition used when mounting /auth/device/approve-handoff and ensure h.device is
non-nil. Return false otherwise, while preserving the ProtocolVersions response.

@Quick104
Quick104 merged commit eb2b9da into main Jul 10, 2026
6 checks passed
@Quick104
Quick104 deleted the codex/remote-playback-phone-identity branch July 10, 2026 03:08
Quick104 added a commit that referenced this pull request Jul 10, 2026
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