Files
plezy/lib/services/credential_vault.dart
T
edde746 05fd622968 feat(emby): add Emby as a MediaBrowser backend alongside Jellyfin
Emby is Jellyfin's upstream ancestor and speaks a near-identical MediaBrowser
API, so the existing Jellyfin stack is parameterised by a `MediaBrowserDialect`
rather than forked. `JellyfinClient`, its auth service, endpoint discovery, LAN
discovery, and the add/edit connection screens all take the dialect and keep one
implementation; `MediaBackend.emby` and `ConnectionKind.emby` carry it through
the neutral models, the Drift `kind` discriminator, downloads, and caches.

Every divergence below was measured against a live Emby 4.9.5 server, not
inferred from documentation, and each is documented at its capability getter.
Jellyfin's request strings stay byte-identical so nothing about its behaviour
changes.

Routes and auth
- Emby only accepts the pre-10.9 user-scoped item routes (`/Users/{id}/Items/…`,
  `/Users/{id}/PlayedItems/…`, `/Users/{id}/FavoriteItems/…`); the unprefixed
  forms Jellyfin 10.11 added return 404.
- The API is also served under a legacy `/emby` prefix, and both dialects accept
  the token as `X-Emby-Token` or `api_key=`.
- Emby answers only its own LAN discovery datagram ("who is EmbyServer?") and
  ignores Jellyfin's; its default HTTPS port is 8920.
- No `/QuickConnect` route exists, so Quick Connect stays Jellyfin-only.

Row fields Emby withholds
- `ProductionYear`, `OfficialRating`, `PremiereDate` and `DateCreated` are absent
  from list rows unless named in `Fields`, which would otherwise strip the year
  and age-rating badge from every card in the app.
- `UserData.LastPlayedDate` never appears on a list row under `Fields=UserData`,
  `EnableUserData=true` or the user-scoped `Ids=` form — only on the single-item
  detail route, or when the Emby-specific `UserDataLastPlayedDate` token is
  requested. Without it every recency-ordered surface silently degrades to
  library-add time, and `JellyfinApiCache.applyWatchState` stamps
  `DateTime.now()` on watched rows, so an offline watch-state pull would rewrite
  the cached play time of everything it walked.

Continue Watching and Next Up
- Emby computes Next Up per series only: the library-wide `/Shows/NextUp` query
  returns nothing under every parameter combination tried. The shelf is
  therefore reconstructed from a played-episode recency scan plus one
  `/Shows/NextUp?SeriesId=` per distinct series, bounded by a shared wall clock
  that covers the scan as well — per-request timeouts cannot bound the pass
  because `MediaServerHttpClient` times the connect and receive phases
  independently. Rows are stamped with their series' newest play from the same
  response that ordered them, so no per-series enrichment request is needed.
- `/Shows/NextUp` ignores `NextUpDateCutoff`, and no server-side played-date
  filter exists to delegate to (`MinDatePlayed` and `MinDateLastPlayed` are
  ignored; `MinDateLastSaved`, `MinDateCreated` and `MinPremiereDate` filter
  unrelated dates), so the 365-day window is applied to the scanned dates.
- The resume route returns items with no saved position, including plain next
  episodes, so the Emby resume leg reads from `/Items?Filters=IsResumable`.
- Emby is ahead of Jellyfin in one place: `/Users/{id}/Items/{id}/HideFromResume`
  makes Continue Watching removal a real capability.

Everything else
- `/Sessions/Playing` and `/Sessions/Playing/Progress` reject a body with no
  `PlaySessionId` (HTTP 400), so playback reporting always sends one.
- Passing any `MediaTypes` value to the playlist query returns an empty list.
- There is no aggregate `/Items/Filters` route; the four filter facets are
  reassembled from `/Genres`, `/OfficialRatings`, `/Studios` and `/Tags`.
- Metadata writes take name-pair lists (`Genres: [{'Name': 'Action'}]`); the
  plain string array is accepted and then silently discarded.
- Custom artwork uploads must be base64 text, not raw bytes — which was broken
  for Jellyfin too and is fixed for both.
- Trickplay, media segments and lyrics 404 on Emby, so scrub previews are absent
  and intro/credit markers fall back to chapter names.

Verified against a local Emby 4.9.5 and a Jellyfin 10.11.11 control server:
onboarding, browse, detail, playable stream URLs serving real bytes, subtitle
sidecars, watch-state write and restore, hubs, cross-server aggregation and
search across both backends simultaneously.
2026-08-05 06:09:26 +02:00

183 lines
7.4 KiB
Dart

import 'dart:convert';
import 'dart:math';
import 'package:cryptography/cryptography.dart';
import 'package:flutter/foundation.dart' show visibleForTesting;
import '../utils/app_logger.dart';
import 'base_shared_preferences_service.dart';
import 'sensitive_prefs.dart';
/// Encrypts credentials before they are persisted in Drift config/token
/// columns. The database no longer stores raw server tokens; registries
/// decrypt at their boundaries and rewrite legacy plaintext values on read.
///
/// Security model: the key is stored in SharedPreferences, so this is
/// obfuscation-at-rest against casual database inspection/export rather than
/// OS-backed Keychain/Keystore protection. Anyone with full access to both app
/// prefs and the database can recover the tokens.
class CredentialVault {
CredentialVault._();
static const String _keyPref = credentialVaultKeyPref;
static const String _prefix = 'enc:v1:';
static final AesGcm _algorithm = AesGcm.with256bits();
static Future<SecretKey>? _secretKey;
/// Drops the memoized key so tests can simulate key loss/divergence.
@visibleForTesting
static void resetKeyForTesting() {
_secretKey = null;
}
static bool isProtected(String? value) => value != null && value.startsWith(_prefix);
static Future<String> protect(String value) async {
if (value.isEmpty || isProtected(value)) return value;
final key = await _getSecretKey();
final box = await _algorithm.encrypt(utf8.encode(value), secretKey: key);
return '$_prefix${jsonEncode({'n': base64Encode(box.nonce), 'c': base64Encode(box.cipherText), 'm': base64Encode(box.mac.bytes)})}';
}
/// Decrypts a protected value, or returns it unchanged when it isn't
/// protected. Returns null when decryption fails — a failed MAC check
/// (key/ciphertext divergence: restored backup, clobbered prefs, racing
/// key generation) or a corrupt payload means the credential is *lost*,
/// never a reason to crash; callers treat null as "re-acquire the token".
static Future<String?> reveal(String value) async {
if (!isProtected(value)) return value;
try {
final payload = jsonDecode(value.substring(_prefix.length)) as Map<String, dynamic>;
final box = SecretBox(
base64Decode(payload['c'] as String),
nonce: base64Decode(payload['n'] as String),
mac: Mac(base64Decode(payload['m'] as String)),
);
final clear = await _algorithm.decrypt(box, secretKey: await _getSecretKey());
return utf8.decode(clear);
} catch (e) {
appLogger.w('CredentialVault: failed to decrypt stored credential, treating as lost', error: e);
return null;
}
}
static Future<Map<String, Object?>> protectConnectionConfig(String kind, Map<String, Object?> config) async {
final copy = Map<String, Object?>.from(config);
final tokenKey = _tokenKeyForKind(kind);
final token = tokenKey == null ? null : copy[tokenKey];
if (token is String) copy[tokenKey!] = await protect(token);
if (kind == 'plex') {
copy['servers'] = await _protectPlexServers(copy['servers']);
}
return copy;
}
static Future<({Map<String, dynamic> config, bool migrated})> revealConnectionConfig(
String kind,
Map<String, dynamic> config,
) async {
final copy = Map<String, dynamic>.from(config);
final tokenKey = _tokenKeyForKind(kind);
var migrated = false;
final token = tokenKey == null ? null : copy[tokenKey];
if (token is String && token.isNotEmpty) {
final revealed = await reveal(token);
// An undecryptable token becomes the empty string — the shared
// "no credential, re-auth" shape — and must not be rewritten back.
migrated = revealed != null && !isProtected(token);
copy[tokenKey!] = revealed ?? '';
}
if (kind == 'plex') {
final result = await _revealPlexServers(copy['servers']);
copy['servers'] = result.servers;
migrated = migrated || result.migrated;
}
return (config: copy, migrated: migrated);
}
/// Config key holding the long-lived credential for a `connections.kind`
/// value. Returning `null` means "nothing to encrypt", so every new kind MUST
/// be listed here — an omission silently persists the token in plaintext.
static String? _tokenKeyForKind(String kind) => switch (kind) {
'plex' => 'accountToken',
'jellyfin' || 'emby' => 'accessToken',
_ => null,
};
static Future<Object?> _protectPlexServers(Object? rawServers) async {
if (rawServers is! List) return rawServers;
final servers = <Object?>[];
for (final raw in rawServers) {
if (raw is! Map) {
servers.add(raw);
continue;
}
final server = Map<String, Object?>.from(raw);
final token = server['accessToken'];
if (token is String) server['accessToken'] = await protect(token);
servers.add(server);
}
return servers;
}
static Future<({Object? servers, bool migrated})> _revealPlexServers(Object? rawServers) async {
if (rawServers is! List) return (servers: rawServers, migrated: false);
var migrated = false;
final servers = <Object?>[];
for (final raw in rawServers) {
if (raw is! Map) {
servers.add(raw);
continue;
}
final server = Map<String, dynamic>.from(raw);
final token = server['accessToken'];
if (token is String && token.isNotEmpty) {
final revealed = await reveal(token);
migrated = migrated || (revealed != null && !isProtected(token));
server['accessToken'] = revealed ?? '';
}
servers.add(server);
}
return (servers: servers, migrated: migrated);
}
static Future<SecretKey> _getSecretKey() {
return _secretKey ??= () async {
final prefs = await BaseSharedPreferencesService.sharedCache();
// The cached snapshot can predate a key written by another isolate
// (background downloader, first-run migration); generating "fresh" over
// it would clobber the real key and orphan every stored ciphertext.
// Reload before deciding, and after writing re-read and adopt whatever
// actually landed so all isolates converge on a single key.
try {
await prefs.reloadCache();
} catch (e) {
appLogger.d('CredentialVault: prefs reload before key check failed', error: e);
}
// Tolerant read: a wrong-typed key must surface as a repairable
// failure, not be mistaken for 'no key yet' and silently replaced —
// that would orphan every ciphertext in the database (#1732).
final stored = readTolerantString(prefs, _keyPref);
if (stored != null && stored.isNotEmpty) {
return SecretKey(base64Decode(stored));
}
final bytes = List<int>.generate(32, (_) => Random.secure().nextInt(256));
await prefs.setString(_keyPref, base64Encode(bytes));
try {
await prefs.reloadCache();
} catch (e) {
appLogger.d('CredentialVault: prefs re-read after key write failed', error: e);
}
// Outside the catch: if another isolate raced us and left a wrong-typed
// value, swallowing it here would return a key that never durably
// landed, and every ciphertext written under it would be unreadable on
// the next launch. Surface it for repair instead (#1732).
final settled = readTolerantString(prefs, _keyPref);
if (settled != null && settled.isNotEmpty) {
return SecretKey(base64Decode(settled));
}
return SecretKey(bytes);
}();
}
}