Files
readest/apps/readest-app/src/utils/bridge.ts
T
Huang Xin 712d564e9d feat(sync): encrypted OPDS credentials + Tauri keychain (PR 4c + 4d) (#4090)
* feat(sync): encrypt opds_catalog credentials end-to-end (TS path)

Wires encrypted-credential sync for opds_catalog via the CryptoSession
shipped in PR 4a (#4084) plus a new publish/pull crypto middleware.
TS-only — native still uses ephemeral storage (re-enter passphrase per
launch); PR 4d wires the OS keychain.

- ReplicaAdapter gains optional `encryptedFields: readonly string[]`.
  Adapters stay sync; the middleware handles the crypto round trip.
- replicaCryptoMiddleware.ts: encryptPackedFields drops the named
  fields from the push when the session is locked (no plaintext
  leak); decryptRowFields drops them on pull failure (local
  plaintext preserved by the store merge).
- replicaPublish / replicaPullAndApply invoke the middleware.
- OPDS adapter declares encryptedFields = [username, password] and
  now pack/unpack them as plaintext.
- passphraseGate.ts: ensurePassphraseUnlocked coalesces concurrent
  calls, prompts via the registered prompter with kind=setup|unlock,
  throws NO_PASSPHRASE on cancel.
- PassphrasePromptModal mounted at the Providers root; registers
  itself as the gate prompter.
- CryptoSession.forget() wipes server-side envelopes + salts.
- Migration 010 + replica_keys_forget RPC; DELETE
  /api/sync/replica-keys + client wrapper.
- SyncPassphraseSection on the user page: status / Set / Unlock /
  Lock / Forgot.
- CatalogManager pre-save: ensurePassphraseUnlocked when credentials
  are present; user cancel saves locally without sync.

Plan updated: PR 4 split documented as 4a/4b/4c/4d.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(sync): persist sync passphrase via OS keychain (Tauri)

Replaces the EphemeralPassphraseStore stub on native with real
OS-keychain storage so users don't re-enter their sync passphrase
every launch. Web stays on the in-memory ephemeral store by design.

Native bridge plugin gains 4 commands wired across all platforms:

- Rust desktop (`keyring` crate): macOS Keychain on apple-native,
  Windows Credential Manager on windows-native, Linux libsecret/
  Secret Service on sync-secret-service. Per-target features so each
  platform compiles only the backend it needs.
- iOS Swift: Security framework Keychain (kSecClassGenericPassword,
  SecItemAdd / Copy / Delete).
- Android Kotlin: androidx.security EncryptedSharedPreferences
  (AndroidKeystore-derived AES-GCM master key,
  AES256_SIV / AES256_GCM key/value encryption).

TS layer:

- TauriPassphraseStore wraps the bridge calls. set is fail-loud
  (surfaces keychain rejection); get is fail-soft (returns null on
  any error so the gate prompts).
- createPassphraseStore returns ephemeral synchronously;
  upgradeToKeychainIfAvailable swaps the singleton to
  TauriPassphraseStore on Tauri after probing the bridge. CryptoSession
  resolves the store via createPassphraseStore() each touch so the
  swap is transparent.
- CryptoSession.tryRestoreFromStore: silent unlock at boot. Stale-
  entry recovery clears the store when the account has no salt
  server-side. unlock/setup persist; forget also clears the store.
- Providers boot effect: upgrade keychain → silent restore.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(sync): make encrypted-credential pull actually decrypt + UX polish

PR 4c shipped the encrypt path but the pull side silently dropped
ciphers when locked, the modal was busy with double-rings, and web
re-prompted on every page refresh. This rolls up the post-test
fixes + UX polish:

Pull-side decrypt:
- decryptRowFields takes an `onLocked` callback the orchestrator
  wires to the passphrase gate; encountering a cipher field with a
  locked session now triggers the lazy-prompt path instead of
  dropping the field.
- replicaPullAndApply re-applies the unpacked row for metadata-only
  kinds even when a local copy exists, so the now-decrypted creds
  reach the store (the binary-kind skip-if-local optimization
  doesn't apply).
- Cipher fingerprint comparison: capture the row's `cipher.c` for
  each encrypted field, compare against the local record's
  lastSeenCipher. Same → skip prompt + decrypt entirely. Different
  (rotation / value change on another device) → prompt to
  re-decrypt. Fingerprint persists via OPDSCatalog.lastSeenCipher.

Web persistence:
- SessionStoragePassphraseStore: passphrase survives page refresh
  within the same tab, dies on tab close. Replaces
  EphemeralPassphraseStore as the default on web. Avoids
  localStorage / IndexedDB to keep the tab-scoped trust boundary.

UI:
- Renamed PassphrasePromptModal → PassphrasePrompt; modernized: filled
  input style with single subtle focus border, btn-primary +
  btn-ghost replaced with leaner custom buttons. eink-bordered +
  btn-primary classes give the dialog correct e-paper rendering.
- globals.css: suppress redundant outline/box-shadow on focused text
  inputs / textareas (the element's own border is the focus
  indicator).
- AGENTS.md: documents the e-ink convention (`eink-bordered`,
  `btn-primary` for inverted CTAs, etc.) so future widgets ship with
  e-paper support.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 13:22:49 +02:00

262 lines
6.7 KiB
TypeScript

import { invoke } from '@tauri-apps/api/core';
export interface CopyURIRequest {
uri: string;
dst: string;
}
export interface CopyURIResponse {
success: boolean;
error?: string;
}
export interface UseBackgroundAudioRequest {
enabled: boolean;
}
export interface InstallPackageRequest {
path: string;
}
export interface InstallPackageResponse {
success: boolean;
error?: string;
}
export interface SetSystemUIVisibilityRequest {
visible: boolean;
darkMode: boolean;
}
export interface SetSystemUIVisibilityResponse {
success: boolean;
error?: string;
}
export interface GetStatusBarHeightResponse {
height: number;
error?: string;
}
export interface GetSystemFontsListResponse {
fonts: Record<string, string>; // { fontName: fontFamily }
error?: string;
}
export interface InterceptKeysRequest {
volumeKeys?: boolean;
backKey?: boolean;
}
export interface LockScreenRequest {
orientation: 'portrait' | 'landscape' | 'auto';
}
export interface GetSystemColorSchemeResponse {
colorScheme: 'light' | 'dark';
error?: string;
}
export interface GetSafeAreaInsetsResponse {
top: number;
right: number;
bottom: number;
left: number;
error?: string;
}
interface GetScreenBrightnessResponse {
brightness: number; // 0.0 to 1.0
error?: string;
}
interface SetScreenBrightnessRequest {
brightness: number; // 0.0 to 1.0
}
interface SetScreenBrightnessResponse {
success: boolean;
error?: string;
}
interface GetExternalSDCardPathResponse {
path: string | null;
error?: string;
}
interface SelectDirectoryResponse {
cancelled?: boolean;
uri?: string;
path?: string;
error?: string;
}
export interface GetStorefrontRegionCodeResponse {
regionCode?: string;
error?: string;
}
export async function copyURIToPath(request: CopyURIRequest): Promise<CopyURIResponse> {
const result = await invoke<CopyURIResponse>('plugin:native-bridge|copy_uri_to_path', {
payload: request,
});
return result;
}
export async function invokeUseBackgroundAudio(request: UseBackgroundAudioRequest): Promise<void> {
await invoke('plugin:native-bridge|use_background_audio', {
payload: request,
});
}
export async function installPackage(
request: InstallPackageRequest,
): Promise<InstallPackageResponse> {
const result = await invoke<InstallPackageResponse>('plugin:native-bridge|install_package', {
payload: request,
});
return result;
}
export async function setSystemUIVisibility(
request: SetSystemUIVisibilityRequest,
): Promise<SetSystemUIVisibilityResponse> {
const result = await invoke<SetSystemUIVisibilityResponse>(
'plugin:native-bridge|set_system_ui_visibility',
{
payload: request,
},
);
return result;
}
export async function getStatusBarHeight(): Promise<GetStatusBarHeightResponse> {
const result = await invoke<GetStatusBarHeightResponse>(
'plugin:native-bridge|get_status_bar_height',
);
return result;
}
let cachedSysFontsResult: GetSystemFontsListResponse | null = null;
export async function getSysFontsList(): Promise<GetSystemFontsListResponse> {
if (cachedSysFontsResult) {
return cachedSysFontsResult;
}
const result = await invoke<GetSystemFontsListResponse>(
'plugin:native-bridge|get_sys_fonts_list',
);
cachedSysFontsResult = result;
return result;
}
export async function interceptKeys(request: InterceptKeysRequest): Promise<void> {
await invoke('plugin:native-bridge|intercept_keys', {
payload: request,
});
}
export async function lockScreenOrientation(request: LockScreenRequest): Promise<void> {
await invoke('plugin:native-bridge|lock_screen_orientation', {
payload: request,
});
}
export async function getSystemColorScheme(): Promise<GetSystemColorSchemeResponse> {
const result = await invoke<GetSystemColorSchemeResponse>(
'plugin:native-bridge|get_system_color_scheme',
);
return result;
}
export async function getSafeAreaInsets(): Promise<GetSafeAreaInsetsResponse> {
const result = await invoke<GetSafeAreaInsetsResponse>(
'plugin:native-bridge|get_safe_area_insets',
);
return result;
}
export async function getScreenBrightness(): Promise<GetScreenBrightnessResponse> {
const result = await invoke<GetScreenBrightnessResponse>(
'plugin:native-bridge|get_screen_brightness',
);
return result;
}
export async function setScreenBrightness(
request: SetScreenBrightnessRequest,
): Promise<SetScreenBrightnessResponse> {
const result = await invoke<SetScreenBrightnessResponse>(
'plugin:native-bridge|set_screen_brightness',
{
payload: request,
},
);
return result;
}
export async function getExternalSDCardPath(): Promise<GetExternalSDCardPathResponse> {
const result = await invoke<GetExternalSDCardPathResponse>(
'plugin:native-bridge|get_external_sdcard_path',
);
return result;
}
export async function selectDirectory(): Promise<SelectDirectoryResponse> {
const result = await invoke<SelectDirectoryResponse>('plugin:native-bridge|select_directory');
return result;
}
export async function getStorefrontRegionCode(): Promise<GetStorefrontRegionCodeResponse> {
const result = await invoke<GetStorefrontRegionCodeResponse>(
'plugin:native-bridge|get_storefront_region_code',
);
return result;
}
// ── Sync passphrase keychain ────────────────────────────────────────────
// Tauri-only. Wired into the TauriPassphraseStore (src/libs/crypto/
// passphrase.ts) so the user's sync passphrase persists across app
// launches via the OS keychain (macOS Keychain, Windows Credential
// Manager, Linux libsecret, iOS Keychain, Android EncryptedSharedPrefs).
export interface SetSyncPassphraseRequest {
passphrase: string;
}
export interface SyncPassphraseResponse {
success: boolean;
error?: string;
}
export interface GetSyncPassphraseResponse {
passphrase?: string;
error?: string;
}
export interface SyncKeychainAvailableResponse {
available: boolean;
error?: string;
}
export async function setSyncPassphrase(
request: SetSyncPassphraseRequest,
): Promise<SyncPassphraseResponse> {
return invoke<SyncPassphraseResponse>('plugin:native-bridge|set_sync_passphrase', {
payload: request,
});
}
export async function getSyncPassphrase(): Promise<GetSyncPassphraseResponse> {
return invoke<GetSyncPassphraseResponse>('plugin:native-bridge|get_sync_passphrase');
}
export async function clearSyncPassphrase(): Promise<SyncPassphraseResponse> {
return invoke<SyncPassphraseResponse>('plugin:native-bridge|clear_sync_passphrase');
}
export async function isSyncKeychainAvailable(): Promise<SyncKeychainAvailableResponse> {
return invoke<SyncKeychainAvailableResponse>('plugin:native-bridge|is_sync_keychain_available');
}