Files
plezy/lib/services/sensitive_prefs.dart
T
edde746 7f0cad339c fix(startup): report and repair a failed launch instead of showing "Error"
Since 2.10.0 the whole app sits behind one all-or-nothing initialization
gate, and that gate discarded the only evidence of its own failure. It
caught the error, logged nothing but `error.runtimeType`, rendered an
icon plus the word "Error" plus Retry, and never reported the error
because catching it kept the crash reporter from ever seeing it. There
is no log file on any platform, the buffer is in memory only, a
double-clicked Windows release build has no console, and the log viewer
lives in Settings, behind the gate that just failed. #1732 is the result:
a Windows 11 user whose app will not boot and who cannot produce a single
byte of diagnostic detail.

The gate now names its phases. Each step is wrapped so a throw carries
the phase it came from, replacing a `Future.wait` that discarded every
error but the first and could not attribute it to any of four concurrent
steps. The failure screen renders the phase, the exception type, the
message and an expandable stack, plus copy and upload actions that reuse
the existing log-relay flow. The record is persisted next to the database
so the next successful launch can surface it in Settings > Logs, and it
is reported to the crash reporter explicitly.

Only preferences and the database still gate the launch. Window chrome,
locale, crash-reporting init, TV/performance detection, the image-cache
budget and download storage are best-effort and time-bounded, so a
stalled platform thread degrades instead of holding the splash forever.
Sentry no longer receives the startup work as its `appRunner`: that made
a startup failure indistinguishable from a Sentry failure, and the guard
would then have re-run migrations and the database open a second time.

The two remaining fatal steps become recoverable. Preference reads
tolerate a value whose stored type no longer matches, dropping the key
and defaulting instead of failing the boot. A store that cannot be parsed
is detected before either desktop plugin backend can memoise it, which is
what makes an in-process repair possible at all. Repair is never
automatic: it states what it will cost, salvages the credential-vault key
and every tracker and Seerr session it can validate out of the damaged
bytes, reseeds them, and moves the original aside rather than deleting
it. Servers and profiles survive a salvaged key because their tokens are
ciphertext in the database; tracker and Seerr sessions are plaintext
preference entries, so the copy says they may still need reconnecting.

Nothing derived from the store reaches a diagnostic. `FormatException`
prints an excerpt of whatever it failed to parse, and during startup that
document holds the vault key, refresh tokens and session cookies while
the redaction manager still has nothing registered, so the wrapper keeps
only the cause's type and offset and the record is an allowlist of
already-redacted fields. The quarantined copy is labelled as containing
credentials, is never offered for upload, and can be deleted from the
dialog.

Also self-heals orphaned WAL/SHM sidecars on desktop rather than only
tvOS, makes every `createTable` migration step idempotent, keeps MSVC
link by-products out of the Windows bundle, and asserts bundle contents
in CI.

Refs #1732
2026-07-31 21:45:32 +02:00

80 lines
3.7 KiB
Dart

/// Preference keys whose stored values are credentials.
///
/// `shared_preferences` is the most credential-dense artifact in a Plezy
/// installation. On the desktop platforms it is a single plaintext JSON file
/// next to the database, and it holds:
///
/// * [credentialVaultKeyPref] — the AES-256 key that `CredentialVault` uses to
/// protect every server/profile token stored in the Drift
/// `connections.config_json` and `profile_connections.user_token` columns.
/// Losing it orphans every one of those ciphertexts permanently.
/// * tracker sessions — `TrackerAccountStore` persists `TrackerSession.encode()`
/// verbatim, so raw OAuth `access_token`/`refresh_token` pairs for MAL,
/// AniList, Simkl and Trakt live here in plaintext.
/// * Seerr sessions — `SeerrSessionStore` persists a raw `connect.sid` cookie
/// alongside a vault-protected password.
/// * [legacyPlexTokenPref] — the pre-connection-registry Plex token slot. It is
/// drained by the connection migration but can linger on old installs.
///
/// Two subsystems consult this list, both added for #1732:
///
/// * the tolerant preference reads in `BaseSharedPreferencesService` must never
/// silently drop one of these keys — an unreadable credential has to surface
/// as an explicit repair prompt, not as a silent re-authentication;
/// * the corrupt-store repair in `PrefsRecovery` salvages exactly these keys
/// out of a damaged store before quarantining it.
///
/// Keep this list exhaustive. A credential slot that is missing here is
/// silently dropped on a type mismatch and silently lost on a repair.
///
/// This lives apart from `CredentialVault`, `TrackerAccountStore` and
/// `SeerrSessionStore` so `BaseSharedPreferencesService` can depend on it
/// without an import cycle.
library;
/// Key holding the base64 `CredentialVault` AES-256 key.
const String credentialVaultKeyPref = 'credential_vault_key_v1';
/// Legacy single-slot Plex token, superseded by the connection registry.
const String legacyPlexTokenPref = 'plex_token';
/// Unscoped base keys used by `TrackerAccountStore`, one per tracker service.
const List<String> trackerSessionBaseKeys = <String>[
'mal_session',
'anilist_session',
'simkl_session',
'trakt_session',
];
/// Unscoped base key used by `SeerrSessionStore`.
const String seerrSessionBaseKey = 'seerr_session';
/// Every credential slot that is profile-scoped through `profileScopedPrefsKey`,
/// so a stored key is either the bare base key or `user_{scope}_{baseKey}`.
const List<String> profileScopedCredentialBaseKeys = <String>[...trackerSessionBaseKeys, seerrSessionBaseKey];
final RegExp _profileScopedCredentialPattern = RegExp(
'^(?:user_.+_)?(?:${profileScopedCredentialBaseKeys.join('|')})\$',
);
/// The unscoped base key [key] resolves to, or null when [key] is not a
/// profile-scoped credential slot.
String? profileScopedCredentialBaseKey(String key) {
if (!_profileScopedCredentialPattern.hasMatch(key)) return null;
for (final base in profileScopedCredentialBaseKeys) {
if (key == base || key.endsWith('_$base')) return base;
}
return null;
}
/// Whether [key] is a profile-scoped or global tracker session slot.
bool isTrackerSessionPrefKey(String key) => trackerSessionBaseKeys.contains(profileScopedCredentialBaseKey(key));
/// Whether [key] is a profile-scoped or global Seerr session slot.
bool isSeerrSessionPrefKey(String key) => profileScopedCredentialBaseKey(key) == seerrSessionBaseKey;
/// Whether [key] holds a credential and must never be dropped or exported
/// without an explicit, informed user decision.
bool isSensitivePrefKey(String key) =>
key == credentialVaultKeyPref || key == legacyPlexTokenPref || profileScopedCredentialBaseKey(key) != null;