712d564e9d
* 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>
262 lines
10 KiB
TypeScript
262 lines
10 KiB
TypeScript
import { create } from 'zustand';
|
|
import type { EnvConfigType } from '@/services/environment';
|
|
import type { OPDSCatalog } from '@/types/opds';
|
|
import { useSettingsStore } from './settingsStore';
|
|
import { getReplicaPersistEnv } from '@/services/sync/replicaPersist';
|
|
import { publishReplicaDelete, publishReplicaUpsert } from '@/services/sync/replicaPublish';
|
|
import {
|
|
computeOpdsCatalogContentId,
|
|
OPDS_CATALOG_KIND,
|
|
} from '@/services/sync/adapters/opdsCatalog';
|
|
|
|
const publishOpdsUpsert = (catalog: OPDSCatalog): void => {
|
|
if (!catalog.contentId) return;
|
|
void publishReplicaUpsert(OPDS_CATALOG_KIND, catalog, catalog.contentId, catalog.reincarnation);
|
|
};
|
|
|
|
const publishOpdsDelete = (contentId: string): void => {
|
|
void publishReplicaDelete(OPDS_CATALOG_KIND, contentId);
|
|
};
|
|
|
|
/**
|
|
* Backfill `contentId` (and `addedAt`) on legacy catalogs that predate
|
|
* replica sync. Returns the same array reference if no changes were
|
|
* required so callers can cheaply detect a no-op.
|
|
*
|
|
* `addedAt` is assigned per array index so the existing display order
|
|
* survives the migration: index 0 (newest in the legacy array) gets
|
|
* the largest timestamp, index N gets the smallest. The total span is
|
|
* tiny (≤ N ms) so newly-imported catalogs (with `Date.now()`) still
|
|
* sort above the migrated set, which matches the legacy "prepend new
|
|
* entries" UX.
|
|
*/
|
|
const backfillSyncFields = (catalogs: OPDSCatalog[]): OPDSCatalog[] => {
|
|
let mutated = false;
|
|
const baseTime = Date.now();
|
|
const next = catalogs.map((c, i) => {
|
|
if (c.contentId && c.addedAt !== undefined) return c;
|
|
mutated = true;
|
|
return {
|
|
...c,
|
|
contentId: c.contentId ?? computeOpdsCatalogContentId(c.url),
|
|
addedAt: c.addedAt ?? baseTime - i,
|
|
};
|
|
});
|
|
return mutated ? next : catalogs;
|
|
};
|
|
|
|
interface OPDSStoreState {
|
|
catalogs: OPDSCatalog[];
|
|
loading: boolean;
|
|
|
|
/** Visible catalogs sorted by `addedAt` descending (newest first). */
|
|
getAvailableCatalogs(): OPDSCatalog[];
|
|
getCatalog(id: string): OPDSCatalog | undefined;
|
|
/** Look up by URL — used for popular-catalog dedup (independent of contentId). */
|
|
findByUrl(url: string): OPDSCatalog | undefined;
|
|
/** Look up by stable cross-device content id. */
|
|
findByContentId(contentId: string): OPDSCatalog | undefined;
|
|
|
|
/**
|
|
* Add (or revive) a catalog. Computes `contentId` from URL if absent.
|
|
* Re-import of a previously soft-deleted entry mints a reincarnation
|
|
* token so the server-side tombstone is replaced with a fresh row.
|
|
*/
|
|
addCatalog(catalog: Omit<OPDSCatalog, 'contentId'> & { contentId?: string }): OPDSCatalog;
|
|
/**
|
|
* Patch a catalog's mutable fields. Only the patched fields are
|
|
* republished — credentials (username/password) are NOT in the
|
|
* synced field set yet, so editing them stays local-only until the
|
|
* encrypted-field PR lands.
|
|
*/
|
|
updateCatalog(id: string, patch: Partial<OPDSCatalog>): OPDSCatalog | undefined;
|
|
/** Soft-delete by id; pushes a tombstone if the entry has a contentId. */
|
|
removeCatalog(id: string): boolean;
|
|
|
|
/**
|
|
* Add a catalog received via replica sync from another device. Same
|
|
* effect on local state as addCatalog, but does NOT republish.
|
|
*/
|
|
applyRemoteCatalog(catalog: OPDSCatalog): void;
|
|
/** Mirror a server-side tombstone locally without re-publishing. */
|
|
softDeleteByContentId(contentId: string): void;
|
|
|
|
/** Hydrate from `settings.opdsCatalogs`. Backfills sync fields if needed. */
|
|
loadCustomOPDSCatalogs(envConfig: EnvConfigType): Promise<void>;
|
|
/** Persist current state back into settings. */
|
|
saveCustomOPDSCatalogs(envConfig: EnvConfigType): Promise<void>;
|
|
}
|
|
|
|
export const useCustomOPDSStore = create<OPDSStoreState>((set, get) => ({
|
|
catalogs: [],
|
|
loading: false,
|
|
|
|
getAvailableCatalogs: () =>
|
|
get()
|
|
.catalogs.filter((c) => !c.deletedAt)
|
|
.sort((a, b) => (b.addedAt || 0) - (a.addedAt || 0)),
|
|
|
|
getCatalog: (id) => get().catalogs.find((c) => c.id === id),
|
|
|
|
findByUrl: (url) => {
|
|
const normalized = url.trim().toLowerCase();
|
|
return get().catalogs.find((c) => c.url.trim().toLowerCase() === normalized && !c.deletedAt);
|
|
},
|
|
|
|
findByContentId: (contentId) =>
|
|
contentId ? get().catalogs.find((c) => c.contentId === contentId) : undefined,
|
|
|
|
addCatalog: (input) => {
|
|
const contentId = input.contentId ?? computeOpdsCatalogContentId(input.url);
|
|
// Revive tombstoned entry under a reincarnation token so the
|
|
// server-side tombstone gets replaced rather than stuck.
|
|
const existing = get().catalogs.find((c) => c.contentId === contentId);
|
|
const reincarnation =
|
|
existing?.deletedAt && !input.reincarnation
|
|
? Math.random().toString(36).slice(2)
|
|
: input.reincarnation;
|
|
const catalog: OPDSCatalog = {
|
|
...input,
|
|
contentId,
|
|
addedAt: input.addedAt ?? existing?.addedAt ?? Date.now(),
|
|
deletedAt: undefined,
|
|
reincarnation,
|
|
};
|
|
set((state) => {
|
|
const idx = state.catalogs.findIndex((c) => c.contentId === contentId);
|
|
const catalogs =
|
|
idx >= 0
|
|
? state.catalogs.map((c, i) => (i === idx ? catalog : c))
|
|
: [...state.catalogs, catalog];
|
|
return { catalogs };
|
|
});
|
|
publishOpdsUpsert(catalog);
|
|
return catalog;
|
|
},
|
|
|
|
updateCatalog: (id, patch) => {
|
|
let updated: OPDSCatalog | undefined;
|
|
set((state) => {
|
|
const idx = state.catalogs.findIndex((c) => c.id === id);
|
|
if (idx < 0) return state;
|
|
const old = state.catalogs[idx]!;
|
|
if (old.deletedAt) return state;
|
|
updated = { ...old, ...patch };
|
|
// Recompute contentId only if the URL itself changed; otherwise
|
|
// preserve the existing one so we keep the same server row.
|
|
if (patch.url && patch.url !== old.url) {
|
|
updated.contentId = computeOpdsCatalogContentId(patch.url);
|
|
}
|
|
return {
|
|
catalogs: state.catalogs.map((c, i) => (i === idx ? updated! : c)),
|
|
};
|
|
});
|
|
if (updated) publishOpdsUpsert(updated);
|
|
return updated;
|
|
},
|
|
|
|
removeCatalog: (id) => {
|
|
const catalog = get().catalogs.find((c) => c.id === id);
|
|
if (!catalog) return false;
|
|
set((state) => ({
|
|
catalogs: state.catalogs.map((c) => (c.id === id ? { ...c, deletedAt: Date.now() } : c)),
|
|
}));
|
|
if (catalog.contentId) publishOpdsDelete(catalog.contentId);
|
|
return true;
|
|
},
|
|
|
|
applyRemoteCatalog: (catalog) => {
|
|
set((state) => {
|
|
const idx = state.catalogs.findIndex((c) => c.contentId === catalog.contentId);
|
|
if (idx >= 0) {
|
|
// Preserve local credentials when remote arrives without them
|
|
// (publishing device hadn't unlocked the CryptoSession, or the
|
|
// local session couldn't decrypt). When remote DOES include
|
|
// decrypted creds, accept them — that's the cross-device sync
|
|
// path enabled by replicaCryptoMiddleware.decryptRowFields.
|
|
// `??` is nullish so an explicit "" from remote (user cleared
|
|
// the password) still overwrites.
|
|
const old = state.catalogs[idx]!;
|
|
const merged: OPDSCatalog = {
|
|
...catalog,
|
|
username: catalog.username ?? old.username,
|
|
password: catalog.password ?? old.password,
|
|
// Preserve the previously-applied cipher fingerprint when
|
|
// the orchestrator didn't attach a fresh one (e.g., row
|
|
// carried no cipher fields, or every decrypt failed).
|
|
// Without this fallback the next pull would treat the row
|
|
// as "never decrypted" and prompt again unnecessarily.
|
|
lastSeenCipher: catalog.lastSeenCipher ?? old.lastSeenCipher,
|
|
deletedAt: undefined,
|
|
};
|
|
return { catalogs: state.catalogs.map((c, i) => (i === idx ? merged : c)) };
|
|
}
|
|
return { catalogs: [...state.catalogs, catalog] };
|
|
});
|
|
const env = getReplicaPersistEnv();
|
|
if (env) void get().saveCustomOPDSCatalogs(env);
|
|
},
|
|
|
|
softDeleteByContentId: (contentId) => {
|
|
const target = get().catalogs.find((c) => c.contentId === contentId && !c.deletedAt);
|
|
if (!target) return;
|
|
set((state) => ({
|
|
catalogs: state.catalogs.map((c) =>
|
|
c.id === target.id ? { ...c, deletedAt: Date.now() } : c,
|
|
),
|
|
}));
|
|
const env = getReplicaPersistEnv();
|
|
if (env) void get().saveCustomOPDSCatalogs(env);
|
|
},
|
|
|
|
loadCustomOPDSCatalogs: async (_envConfig) => {
|
|
try {
|
|
const { settings } = useSettingsStore.getState();
|
|
const persisted = settings?.opdsCatalogs ?? [];
|
|
const backfilled = backfillSyncFields(persisted);
|
|
set({ catalogs: backfilled });
|
|
// If backfill mutated anything, persist + publish the fresh
|
|
// contentIds so existing catalogs start syncing on next push.
|
|
if (backfilled !== persisted) {
|
|
await get().saveCustomOPDSCatalogs(_envConfig);
|
|
for (const c of backfilled) {
|
|
if (c.contentId && !c.deletedAt) publishOpdsUpsert(c);
|
|
}
|
|
}
|
|
} catch (error) {
|
|
console.error('Failed to load OPDS catalogs:', error);
|
|
}
|
|
},
|
|
|
|
saveCustomOPDSCatalogs: async (_envConfig) => {
|
|
try {
|
|
const { settings, setSettings, saveSettings } = useSettingsStore.getState();
|
|
const { catalogs } = get();
|
|
// Tombstoned entries stay in memory so the orchestrator can detect
|
|
// re-import / reincarnation, but they're stripped at the
|
|
// persistence boundary. The next pull will mirror server-side
|
|
// tombstones back into memory if the row is still deleted.
|
|
settings.opdsCatalogs = catalogs.filter((c) => !c.deletedAt);
|
|
setSettings(settings);
|
|
saveSettings(_envConfig, settings);
|
|
} catch (error) {
|
|
console.error('Failed to save OPDS catalogs:', error);
|
|
throw error;
|
|
}
|
|
},
|
|
}));
|
|
|
|
/**
|
|
* Look up an OPDS catalog by its cross-device contentId, falling back to
|
|
* the persisted settings when the in-memory store is empty. The pull-side
|
|
* orchestrator runs before the OPDS page mounts; without the fallback
|
|
* every refresh would treat existing catalogs as new and double up.
|
|
*/
|
|
export const findOPDSCatalogByContentId = (contentId: string): OPDSCatalog | undefined => {
|
|
if (!contentId) return undefined;
|
|
const inMemory = useCustomOPDSStore.getState().findByContentId(contentId);
|
|
if (inMemory) return inMemory;
|
|
const persisted = useSettingsStore.getState().settings?.opdsCatalogs ?? [];
|
|
return persisted.find((c) => c.contentId === contentId && !c.deletedAt);
|
|
};
|