Skip to content

Add scoped companion history access and stable playback identity - #3

Open
303inmyheart wants to merge 2 commits into
TypeType-Video:devfrom
303inmyheart:companion-presence-api
Open

303inmyheart wants to merge 2 commits into
TypeType-Video:devfrom
303inmyheart:companion-presence-api

Conversation

@303inmyheart

@303inmyheart 303inmyheart commented Dec 6, 2026 •

Copy link
Copy Markdown

Problem and resulting behavior

A read-only companion can poll current playback, but it cannot safely distinguish key rotation from an account/instance change or read existing watch history without receiving a normal login token. Current presence also lacks channel identity, live status and playback speed.

This adds a scoped, pull-based companion API to the Go server's dev branch. The companion requests data and the server responds through the existing HTTP API; there are no callbacks, extra ports, new services or new Go dependencies.

API changes

Endpoint Authentication Behavior
GET /presence/identity Presence key Persistent instanceId, exact owning user/profile accountId, and current scopes
GET /presence/now-playing Presence key Existing response plus instance/account identity and nullable channelId, channelUrl, isLive, playbackSpeed
GET /presence/history?limit=100&cursor=... Presence key with explicit history:read Bounded, account-isolated pages of saved watch-history records
PUT /presence/keys/{id} Owning account's normal login Explicitly grant or revoke history access for that key

POST /presence/keys optionally accepts scopes. Omitting them retains the original presence:read permission. Existing metadata keeps the legacy scope field and adds the complete scopes array. Both normal and /api-prefixed routes remain supported.

Owner opt-in for an existing key:

{ "scopes": ["presence:read", "history:read"] }

Sending only presence:read revokes history access without replacing the token.

Privacy and authorization

  • Existing keys never acquire history access automatically. A presence-only key receives HTTP 403 with presence_scope_required for history.
  • The normal JWT is required to manage grants. Read-only keys cannot elevate themselves, write/delete history, report playback or access normal account APIs.
  • Every companion request checks the stored key and grant. Revoked keys and keys belonging to suspended/deleted users are rejected; changes are not hidden by a per-process permission cache.
  • Only token hashes are persisted. One-time tokens, identity and history responses use Cache-Control: no-store; no access tokens, names or email addresses are added to the identity response.
  • Database failures are reported as server failures instead of being mistaken for invalid tokens. Row/scan errors are handled rather than silently dropping data.
  • The ten-key limit is serialized per account to prevent concurrent requests from exceeding it.

Playback and channel handling

The existing authenticated /sessions/playback/start and /progress requests accept the four optional metadata fields. Unknown live status/speed remain null; a missing duration does not imply live playback. Channel URLs are normalized, and provider IDs are extracted only from unambiguous supported URLs. YouTube handles and Twitch logins are not presented as immutable IDs.

For older clients, channel identity can be recovered from the same account's saved record for the exact currently reported video. Channels are never matched by display name, and no provider requests are made for this enrichment.

Partial progress retains metadata for the same device/video within the existing presence TTL, even with admin session tracking disabled. Starting/changing a video resets old metadata; explicit false/default values are respected. A stop from another device no longer clears the current device's presence. Account deletion clears the additional in-memory playback state.

History semantics and migration

History uses descending watchedAt/id keyset pagination, including records sharing a timestamp. Follow nextCursor until null; page size is 1–1000. Pages retain their initial upper timestamp bound, so newer playback does not shift offsets. Concurrent deletion/backdated imports are not an immutable snapshot. The endpoint exposes stored records and does not manufacture completed views or recreate deleted/unrecorded history.

History duration/progress remain in seconds; playback positions/durations and history timestamps use milliseconds.

The normal startup migration adds:

  • presence_keys.history_read NOT NULL DEFAULT FALSE;
  • a singleton go_instance_identity table initialized once with a random UUID;
  • an index for looking up current channel metadata.

No users, keys or history are deleted/replaced. Identity survives URL changes, key rotation, container restarts and database restore. A separately operated database clone needs an administrator-assigned new identity, documented in the guide. The existing generic TYPE_TYPE_INSTANCE_ID push label is unchanged.

Validation performed

All accounts, tokens, media and playback reports used for these checks were synthetic. No live instance credentials or personal playback data are included.

  • Go 1.27.4: go vet ./... and go test -race -count=1 ./..., with disposable PostgreSQL 17 and Redis 7 as the protocol-compatible test cache, passed across all packages.
  • Repeated go test -race -count=2 ./internal/auth ./internal/api ./internal/db passed. The existing account-deletion test now uses unique fixture IDs and cleans up its unaffected control account, fixing a failure on repeated runs.
  • New regressions cover explicit grants/revocation, self-escalation attempts, ownership, cross-account isolation, key rotation, restart/migration persistence, concurrent key limits, tied history timestamps, malformed cursors, units, partial progress, live/speed/pause values, TTL expiry and deletion cleanup.
  • govulncheck found no vulnerabilities. Changed YAML parsed successfully and all 20 new/transitive OpenAPI references resolved.
  • The existing Dockerfile built both linux/amd64 and linux/arm64; extracted ELF headers confirmed the actual architectures.
  • A real native amd64, non-root container with a read-only root filesystem passed HTTP checks for identity, history consent and synthetic live playback. An actual stop/start preserved identity, token and history grant, while transient playback correctly became inactive. ARM64 was build/ELF-checked, not run on ARM hardware.
  • A new GitHub Actions workflow runs the database-backed vet/race suite and static amd64/arm64 builds. Successful fork CI.

The upstream pull-request workflow is awaiting maintainer approval for this external contribution (run); the independent fork workflow above has passed.

Client follow-up and limits

This is a server-only change. The inspected Android playback DTO does not send the new metadata fields. The inspected TV RemotePresence.playbackStart skips non-positive-duration media, including live streams. Those clients must send their actual live playback and speed through the existing session requests before live presence can work end to end; a stream list or extraction request cannot prove watching.

The companion's consumption of the new identity/history/metadata, actual Android/TV live playback after client updates, and ARM64 runtime behavior remain integration checks. No real Discord-profile test is claimed by this PR.

Full request/response semantics, examples, migration and the client follow-up are in docs/companion-api.md, with schemas in api/openapi/paths/presence.yaml and api/openapi/paths/session-playback.yaml.

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