Files
romm/backend/endpoints/activity.py
Georges-Antoine Assi f66950551a fix(sync): bind device tokens to their device; dial only known push-pull hosts (#5460)
* fix(sync): bind device tokens to their device; dial only known push-pull hosts

A client token paired to one device could read, reconfigure, delete, sync
saves for and record play sessions as any other device of the same user.
Device CRUD, sync negotiate/complete, push-pull trigger, the save device
resolver and play-session ingest now treat another device as not found for
a bound token, through a shared require_token_device helper. GET /api/devices
lists only the bound device.

Push-pull let any user with devices.write point ssh_host at any host and
port, and the connection error surfaced through the sync session, so the
worker could be used to probe the internal network. The SSH handler now
refuses a host with no trusted key or CA in the admin's known_hosts before
dialling it, which keeps LAN handhelds working while nothing else is
reached.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(device): revoke a deleted device's tokens; scope registration matches

Addresses Greptile review on #5460. Deleting a device now deletes the client
tokens paired to it, since the foreign key's SET NULL turned them into unbound
tokens that reach every device. Registration with a bound token only matches
its own device by fingerprint, so it can no longer reset syncs or overwrite
capabilities on another device.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(sync): bind heartbeat, sync session and online reads; pin push-pull ports

pr-ready step 2 (code-review xhigh --fix).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(device): one require_device helper; parse known_hosts once

pr-ready step 3 (simplify).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(sync): narrow await_args before reading known_hosts

pr-ready step 4 (review-polish).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(sync): plainer comments on the push-pull allowlist and token revoke

pr-ready step 5 (humanizer).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(device): keep bound tokens off other tokens; cascade tokens with their device

A device-bound token can no longer create tokens, or regenerate, pair or
revoke a token of another device or an unbound one. The save session_id
counter only counts a session of the caller's bound device.

client_tokens.device_id now cascades on device delete (0159), so no path
can leave an unbound token behind, and deleting a device records a
client_token.revoke audit event for each token it takes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore(env): drop the push-pull allowlist note from env.template

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 08:57:33 -05:00

107 lines
3.9 KiB
Python

from fastapi import HTTPException, Request, status
from pydantic import BaseModel, Field
from decorators.auth import protected_route
from endpoints.responses.activity import ActivityEntrySchema
from handler.activity_handler import ActivityEntry, activity_handler
from handler.auth.constants import Scope
from handler.auth.dependencies import get_permissions
from handler.database import db_device_handler, db_rom_handler
from utils.auth import require_device, require_token_device
from utils.router import APIRouter
router = APIRouter(
prefix="/activity",
tags=["activity"],
)
def _visible_activity(
request: Request, entries: list[ActivityEntry]
) -> list[ActivityEntrySchema]:
"""Drop sessions whose ROM is hidden from the caller (platform or rom hide)."""
visibility = get_permissions(request).rom_visibility
if not visibility.is_unrestricted:
hidden = db_rom_handler.get_hidden_rom_ids_among(
[e["rom_id"] for e in entries], visibility
)
entries = [e for e in entries if e["rom_id"] not in hidden]
return [ActivityEntrySchema(**e) for e in entries]
def _is_hidden(request: Request, rom_id: int) -> bool:
"""Whether the caller's visibility rules hide the ROM."""
visibility = get_permissions(request).rom_visibility
if visibility.is_unrestricted:
return False
return rom_id in db_rom_handler.get_hidden_rom_ids_among([rom_id], visibility)
class DeviceHeartbeatPayload(BaseModel):
rom_id: int = Field(ge=1)
device_id: str = Field(min_length=1, max_length=255)
@protected_route(router.get, "", [Scope.ROMS_USER_READ])
async def get_all_activity(request: Request) -> list[ActivityEntrySchema]:
"""Return every currently active play session across all users."""
entries = await activity_handler.get_all_active()
return _visible_activity(request, entries)
@protected_route(router.get, "/rom/{rom_id}", [Scope.ROMS_USER_READ])
async def get_rom_activity(request: Request, rom_id: int) -> list[ActivityEntrySchema]:
"""Return all active play sessions for a specific ROM."""
entries = await activity_handler.get_active_for_rom(rom_id)
return _visible_activity(request, entries)
@protected_route(router.post, "/heartbeat", [Scope.ROMS_USER_WRITE])
async def device_heartbeat(
request: Request, payload: DeviceHeartbeatPayload
) -> ActivityEntrySchema:
"""Heartbeat endpoint for external devices (muOS, Android, etc.).
Called periodically by devices while the user is playing a game. Writes
activity state to Redis and sends an ``activity:update`` event to the
users who can see the ROM.
"""
device = require_device(request, payload.device_id)
# build_entry does the ROM lookup; None back from it is a missing ROM, and a
# hidden one answers the same 404.
entry = None
if not _is_hidden(request, payload.rom_id):
entry = await activity_handler.build_entry(
user_id=request.user.id,
device_id=device.id,
rom_id=payload.rom_id,
preserve_started_at=True,
device_type=device.client or "unknown",
)
if entry is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"ROM {payload.rom_id} not found",
)
await activity_handler.publish_active(entry)
# Update the device last_seen as a side-effect (mirrors play session ingest).
db_device_handler.update_last_seen(device_id=device.id, user_id=request.user.id)
return ActivityEntrySchema(**entry)
@protected_route(
router.delete,
"/heartbeat",
[Scope.ROMS_USER_WRITE],
status_code=status.HTTP_204_NO_CONTENT,
)
async def clear_device_activity(request: Request, device_id: str) -> None:
"""Immediately clear an active session for a device (e.g. on graceful exit)."""
require_token_device(request, device_id)
await activity_handler.publish_clear(request.user.id, device_id)
return None