Files
Netcatty/application/state/useCloudSync.ts
T
13fa68a720 feat(plugins): add sync providers and encrypted sidecar sync (#2713)
* feat(plugins): add sync providers and encrypted sidecar sync

Implement PR 8 of the plugin platform (#2269): namespaced sync Providers
with provider.sync, encrypted-object storage operations, WebDAV through the
shared storage surface, dynamic cloud provider IDs, and non-cascade sidecars
for sync:true plugin settings plus account/CRDT baselines.

Related to #2269

* fix(plugins): wire sync providers and sidecars into production paths

Close PR 8 integration gaps: dynamic plugin provider registry and
getConnectedAdapter createPluginStorage, WebDAV through EncryptedObjectStorage,
cloud payload collect/apply for pluginSidecars, and IPC/preload bridges.

Related to #2269

* fix(plugins): preserve WebDAV auth reuse and resourceId through EOS wrap

encryptedObjectStorageAsCloudAdapter now reports initiallyAuthenticated when
config exists (matching raw WebDAVAdapter) so getConnectedAdapter reuses the
cached instance, and preserves/refreshes resourceId from the backing adapter
instead of always forcing the default object key.

Related to #2269

* fix(plugins): address Codex PR 8 review findings

Carry pluginSidecars through merge/convergent uploads, lazy-connect before
object I/O with revision-aware writes, fail closed on sidecar collect errors,
expose connectPluginProvider, preserve remote timestamps, and drop deleted
installed-plugin settings from collection.

Related to #2269

* fix(plugins): close remaining Codex P1/P2 sync issues

Lazy stream cancel for inline sync reads, must-not-exist conditional writes,
three-way sidecar merge for local resets, validated apply path for settings,
and merge remote sidecars into convergent uploads.

Related to #2269

* fix(plugins): harden sidecar collect/apply and write verification

Preserve last-known sidecars when the host is offline, apply remote
deletions for installed plugins, force convergent upload on sidecar
divergence, verify plugin object writes, and pick plugin providers in
auto-sync startup checks.

Related to #2269

* fix(plugins): close remaining Codex sidecar/sync path gaps

Include sidecars in auto-sync payload and hash, keep explicit empty bundles,
fail apply when host is offline, require getCapabilities, and carry merged
sidecars into convergent local apply/upload decisions.

Related to #2269

* fix(plugins): close Codex P1 sidecar collect/apply/merge gaps

Treat null host responses as unavailable, persist collected settings into
the non-cascade table, retain decoded convergent payloads, use three-way
sidecar merge for deletions, and fail apply only on operational errors.
Also treat non-empty plugin sidecars as meaningful sync data and re-run
auto-sync when plugin contributions change.

Related to #2269

* fix(plugins): close remaining Codex P1 sidecar and provider gaps

Replay offline-cached sidecars before collect, keep explicit empty
sidecar fields after three-way merge, thread sidecars through convergent
conflict/downgrade materialization, keep gated-off plugin providers from
joining sync as connected, and rebind plugin EOS sessions after runtime
replacement.

Related to #2269

* fix(plugins): separate pending remote sidecars from last-known cache

Replay only host-offline remote applies into the DB, keep last-known as
upload fallback, use contribution reset for deleted settings, probe real
plugin host readiness, rebind storage events for plugin providers, clear
plugin bases on reset, and swallow disconnect rejections.

Related to #2269

* fix(plugins): hydrate retained sidecars and gate missing providers

Materialize installed-plugin settings from retained sidecars before
collect pruning, clear sidecars on setting reset, fail closed when
pending remote replay fails, and only restore plugin providers that are
contribution-available. Also initialize dynamic provider counters on
connect.

Related to #2269

* fix(plugins): surface plugin sync providers and preserve conflict sidecars

Collect live sidecars before convergent conflict apply/upload, include
dynamic providers in status and disconnect paths, and list plugin sync
providers in Cloud Sync settings for connect/disconnect.

Related to #2269

* fix(plugins): per-provider sidecar baselines and safer collect/UI

Merge convergent sidecars against each provider's own baseline, keep
retained settings in sidecars without unvalidated plugin_settings writes,
guard isConnectDisabled for never-connected plugins, and fall back plugin
provider labels/icons in the status popup.

Related to #2269

* fix(plugins): correct plugin provider discovery and sidecar reverify

Read nested contribution metadata for sync provider cards, gate empty-config
connects, enforce single-provider disconnect for plugins, and re-verify after
sidecar-only convergent uploads so baselines track the post-write payload.

Related to #2269

* fix(plugins): refresh sync provider availability from live contributions

Replace the contribution-available provider ID set when plugins change so
disabled or uninstalled sync providers leave the auto-sync ready set and
drop to disconnected with config retained.

Related to #2269

* fix(plugins): preserve sidecars in backups, pending queue, and migration

Attach last-known plugin sidecars to protective local vault backups, fail
operationally when pending/last-known storage writes are rejected, carry
sidecars through convergent migration publish, and reject trailing garbage
on encrypted object parse.

Related to #2269

* fix(plugins): abort conflict collect failures and merge migration sidecars

Rethrow operational sidecar collection errors during convergent conflict
resolution, LWW-union all local/provider sidecars during convergent
migration, re-collect last-known after apply, and prefer live host collect
for protective local vault backups.

Related to #2269

* fix(plugins): restore pluginBridge tests, fix import path, union downgrade sidecars

Correct SettingsSyncTab dynamic import path so production builds resolve,
add ipcMain.on to the plugin bridge test double, union all provider
sidecars on convergent downgrade, keep empty last-known resets, and skip
force-delete when contribution reset validation rejects.

Related to #2269

* fix(plugins): abort backup collect failures and honor empty remote wipes

Only fall back to last-known sidecars when the host is unavailable during
protective backups, treat explicit empty remote sidecar bundles as
authoritative wipes, remove lint-blocking anys from harness tests, and
use a stable equal-timestamp sidecar tie-break.

Related to #2269

* fix(plugins): include sidecars in equality, preserve merge base on reconnect

Compare pluginSidecars in cloudSyncPayloadsEqual for migration freshness,
clear plugin merge state only when account/resource changes on reconnect,
cancel accepted sync read streams on failure, and stop re-connecting the
plugin EOS adapter on every I/O.

Related to #2269

* fix(plugins): drop cached adapters on contribution refresh

Invalidate plugin sync adapters when live contributions change so a
restarted runtime gets a fresh connect, take offline any non-disconnected
missing providers, and latch version-change backups only after cancellation
checks pass.

Related to #2269

* fix(plugins): preserve omitted sidecars and hydrate on plugin enable

Treat missing pluginSidecars as legacy/unsupported in three-way merge
(only explicit empty is a wipe), hydrate retained settings when a plugin
enables, and re-enable retained provider configs when contributions return.

Related to #2269

* fix(plugins): keep newer retained sidecars over older stored settings

When collection merges existing sidecars with plugin_settings rows, prefer
the newer updatedAt so a schema-rejected remote value retained only in
the sidecar table is not overwritten by a stale local setting.

Related to #2269

* fix(plugins): seal plugin provider config and clear base on config change

Encrypt opaque plugin provider configuration before persistence, clear
merge state when reconnect configuration changes, and stream sync objects
below a base64-safe inline threshold so control-plane JSON stays in budget.

Related to #2269

* fix(plugins): seal plugin configs by provider id and hydrate before start

Encrypt plugin provider configuration only for non-builtin provider IDs
so field-name collisions cannot skip sealing, hydrate retained sidecars
before plugin enable starts the runtime, and stop tearing down live
adapters on no-op availability refreshes.

Related to #2269

* fix(plugins): seal scalar configs, safe inline reads, stable config fingerprint

Encrypt any non-builtin plugin configuration JSON shape, enforce the
base64-safe inline read cutoff, and compare reconnect configurations with
order-independent fingerprints so merge bases are not cleared spuriously.

Related to #2269

* fix(plugins): thread sync credentials and harden availability checks

Pass SyncConnectPayload.credential through the object-storage and IPC host
path, treat only null/undefined config as missing, and avoid wiping the
plugin provider availability catalog on transient discovery failures.

Related to #2269

* fix(plugins): unblock schema-required sync connect and scalar configs

Add a JSON config dialog for plugin sync providers that declare a
required configurationSchema, reuse retained configs on reconnect, and
treat falsy scalar configs as present in readiness and adapter lookup.

Related to #2269

* fix(plugins): rebind sync adapters on contribution refresh

Drop cached plugin sync adapters when live contributions still include
the provider so replaced runtimes get a fresh connect, and seal falsy
scalar plugin configs with nullish presence checks end-to-end.

Related to #2269

* fix(plugins): apply sidecars under current declared setting scopes

When a plugin update changes a syncable setting scope, write under the
live declaration and drop the obsolete scope row so collection does not
republish duplicates.

Related to #2269

* fix(plugins): seal config envelopes and stabilize provider counters

Use an unambiguous host-owned sealed-config envelope, initialize
dynamic-provider sequence counters before cross-window decrypt, keep
three-way sidecar deletions during convergent migration, and create the
sidecar table for existing schema-1 plugin databases.

Related to #2269

* fix(plugins): avoid mid-sync adapter drops and sidecar resurrection

Keep plugin adapters across setting-only contribution refreshes and
rebind sessions on ensureConnected; stop preserving local-only missing
plugin sidecars when remote already mentions the plugin; compare configs
with nullish semantics across windows; swallow quick-connect failures
after toasting.

Related to #2269

* fix(plugins): restore remoteKeys for installed sidecar resets

Reintroduce the remote key set used when dropping installed-plugin
settings the remote no longer carries so applyFromSync cannot throw
after replacing the sidecar table.

Related to #2269

* fix(plugins): honor conflict policy and re-key scoped sidecars

Pass preferCloud/preferLocal into three-way sidecar merge, use
per-provider baselines on convergent downgrade so local resets are not
resurrected, and re-key applied settings under the current declared
scope coordinates.

Related to #2269

* fix(plugins): keep strategy on final sidecar merge and block dual legacy

Pass preferCloud/preferLocal through the final verified sidecar merge,
avoid auto-reactivating a retained plugin while another legacy provider
is already connected, cache plugin adapters only after initializeSync,
and preserve explicit null configuration values.

Related to #2269

* fix(plugins): strip plugin avatars and protect last-known sidecars

Do not load plugin-supplied avatar URLs in the main renderer, and avoid
overwriting last-known sidecars with an unmerged remote bundle when the
post-apply collect fails or is non-authoritative.

Related to #2269

* fix(plugins): strip top-bar plugin avatars and stop always-rebind

Hide plugin avatar URLs in the sync status popover, drop always-on
rebindSession for plugin adapters, and read convergent mode from the
local config module when deciding whether to auto-reactivate providers.

Related to #2269

* fix(plugins): use window.netcatty for sync IPC and allow null configs

Read plugin sync and sidecar APIs from the production preload global,
and treat an explicit config property (including JSON null) as present
for readiness and adapter lookup.

Related to #2269

* fix(plugins): close residual Codex P2 sync edge cases

Three-way merge sidecars during v2 convergent migration so local
resets are not resurrected, preserve explicit null plugin configs on
adapter rebuild, rebind EOS sessions after I/O failure for replaced
runtimes, and accept the public inlineObjectBytes limit on readObject.

Related to #2269

* fix(plugins): keep inline read cutoff under control-plane budget

Restore the base64-safe inline cutoff so advertised-size reads cannot
overflow the 128 KiB provider JSON envelope; providers near the public
inlineObjectBytes limit must stream.

Related to #2269

* fix(plugins): harden sidecar empty-vault, hydrate LWW, and credential seals

Close remaining Codex/review gaps for PR8: keep empty sidecar shells from
bypassing upload guards, skip startup hydrate when local settings are newer,
seal/validate durable plugin credential refs, and cover schema 1→2 migration.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(plugins): rebind plugin sync sessions and keep null configs

Address Codex P2 on 8ae52c54: re-issue connect after runtime replacement,
and treat stored config:null as present in the dashboard reconnect path.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(plugins): defer empty sidecar last-known until sync succeeds

Keep prior non-empty last-known across an authoritative empty collect so the
empty-vault guard can still recognize a plugin-only reset, then commit the
empty cache after a successful upload.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(plugins): avoid restricted localStorage global in sidecar test

Bind the mock to a local binding so eslint no-restricted-globals stays clean.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(plugins): commit applied sidecar cache and reset orphan settings

Prefer merged payload sidecars when updating last-known after sync, and clear
syncable plugin_settings that lack sidecar rows on authoritative remote deletes.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(plugins): reseal marker-shaped plugin configs instead of skipping

Exact __netcatty_plugin_config_v1 collisions no longer bypass encryption; trusted
host envelopes are unwrapped then resealed, and false collisions are sealed whole.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(plugins): keep merged sidecars in last-known after apply collect fails

Return applyFromSync entries from IPC and use them when follow-up collect fails,
so preserved missing-plugin rows are not dropped from the offline upload cache.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(plugins): delete stale-scope settings at stored coordinates on reset

After resetSetting against the current declared scope, also remove the row at
the sidecar's stored scope so scope migrations cannot republish remote deletes.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(plugins): close sync-provider credential, stream, and sidecar gaps

Make SecretRef usable end-to-end via lease-bound network.request, keep
renderer/main transfers abortable and bounded, and stop sidecar
last-known/pending from corrupting backups and conflict apply.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(plugins): harden single-provider, secret schema, and conditional conflicts

Keep legacy restart from dual-connecting providers, extract writeOnly schema
secrets into OS storage, and surface conditional-write precondition failures
as conflict UI instead of a generic sync error.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(plugins): dedupe sync type imports for lint

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: address Codex review on PR #2713

* fix(plugins): wait for sidecar host before version backup latch

Defer the one-shot upgrade snapshot until the plugin sidecar host is ready (or a short grace), and catch getDataHash failures so pending/baseline paths do not reject unhandled.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(plugins): require sidecar grace before version backup

Always wait for contributions/grace tick before the upgrade snapshot, and only latch after a non-cancelled attempt so cleanup cannot suppress retries.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
2026-08-05 18:43:10 +08:00

1006 lines
35 KiB
TypeScript

/**
* useCloudSync - React Hook for Cloud Sync State Management
*
* Provides a complete React interface to the CloudSyncManager.
* Handles security state machine, provider connections, and sync operations.
* Uses useSyncExternalStore for real-time state synchronization across all components.
*/
import { useCallback, useEffect, useMemo, useRef, useSyncExternalStore } from 'react';
import {
type CloudProvider,
type SecurityState,
type SyncState,
type ProviderConnection,
type ConflictInfo,
type ConflictResolution,
type RemoteSyncPayload,
type SyncedFile,
type SyncPayload,
type SyncResult,
type SyncHistoryEntry,
type ConvergentFieldConflict,
type WebDAVConfig,
type S3Config,
formatLastSync,
getSyncDotColor,
isProviderReadyForSync,
} from '../../domain/sync';
import type { CloudSyncStrategy } from '../../domain/syncStrategy';
import type { CloudSyncConflictAction } from '../../domain/syncStrategy';
import {
getCloudSyncManager,
type SyncManagerState,
type SyncEventCallback,
} from '../../infrastructure/services/CloudSyncManager';
import type { ShrinkFinding } from '../../domain/syncGuards';
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
import type { DeviceFlowState } from '../../infrastructure/services/adapters/GitHubAdapter';
import {
getConvergentSyncLocalConfig,
getConvergentSyncLocalConfigSnapshot,
pauseConvergentSync,
refreshConvergentSyncLocalConfigSnapshot,
setConvergentSyncLocalConfig,
subscribeConvergentSyncLocalConfig,
type ConvergentSyncLocalConfig,
} from '../../infrastructure/services/convergentSyncConfig';
// ============================================================================
// Types
// ============================================================================
type ConvergentPayloadApplier = (
payload: SyncPayload,
commitReplica: () => Promise<void>,
) => Promise<void>;
interface CloudSyncRunOptions {
overrideShrink?: boolean;
conflictActionOverride?: CloudSyncConflictAction;
applyConvergentPayload?: ConvergentPayloadApplier;
signal?: AbortSignal;
}
export interface CloudSyncHook {
// State
securityState: SecurityState;
syncState: SyncState;
isUnlocked: boolean;
isSyncing: boolean;
providers: Record<CloudProvider, ProviderConnection>;
currentConflict: ConflictInfo | null;
lastError: string | null;
deviceName: string;
autoSyncEnabled: boolean;
autoSyncInterval: number;
syncStrategy: CloudSyncStrategy;
localVersion: number;
localUpdatedAt: number;
remoteVersion: number;
remoteUpdatedAt: number;
syncHistory: SyncHistoryEntry[];
pendingLocalSync: boolean;
convergentConflicts: ConvergentFieldConflict[];
convergentSyncConfig: ConvergentSyncLocalConfig;
pendingBrowserAuthProvider: 'google' | 'onedrive' | null;
// Computed
hasAnyConnectedProvider: boolean;
connectedProviderCount: number;
overallSyncStatus: 'none' | 'synced' | 'syncing' | 'error' | 'conflict' | 'blocked';
// Master Key Actions
setupMasterKey: (password: string, confirmPassword: string) => Promise<void>;
unlock: (password: string) => Promise<boolean>;
lock: () => void;
changeMasterKey: (oldPassword: string, newPassword: string) => Promise<boolean>;
verifyPassword: (password: string) => Promise<boolean>;
// Provider Actions
connectGitHub: () => Promise<DeviceFlowState>;
completeGitHubAuth: (
deviceCode: string,
interval: number,
expiresAt: number,
onPending?: () => void,
signal?: AbortSignal,
authAttemptId?: number
) => Promise<void>;
connectGoogle: () => Promise<string>;
/** Connect a namespaced plugin sync Provider (encrypted-object storage only). */
connectPluginProvider: (
providerId: string,
configuration?: unknown,
credential?: unknown,
) => Promise<void>;
connectOneDrive: () => Promise<string>;
connectWebDAV: (config: WebDAVConfig) => Promise<void>;
connectS3: (config: S3Config) => Promise<void>;
completePKCEAuth: (
provider: 'google' | 'onedrive',
code: string,
redirectUri: string
) => Promise<void>;
cancelOAuthConnect: () => void;
disconnectProvider: (provider: CloudProvider) => Promise<void>;
resetProviderStatus: (provider: CloudProvider) => void;
// Sync Actions
syncNow: (payload: SyncPayload, opts?: CloudSyncRunOptions) => Promise<Map<CloudProvider, SyncResult>>;
syncToProvider: (
provider: CloudProvider,
payload: SyncPayload,
opts?: Pick<CloudSyncRunOptions, 'overrideShrink' | 'applyConvergentPayload' | 'signal'>,
) => Promise<SyncResult>;
downloadFromProvider: (provider: CloudProvider) => Promise<RemoteSyncPayload | null>;
commitRemoteInspection: (provider: CloudProvider, remoteFile: SyncedFile, payload: SyncPayload, opts?: { recordDownload?: boolean }) => Promise<void>;
resolveConflict: (resolution: ConflictResolution) => Promise<RemoteSyncPayload | null>;
resolveConvergentConflict: (
addressKey: string,
candidateDot: string,
applyPayload: (
payload: SyncPayload,
commitReplica: () => Promise<void>,
) => Promise<void>,
) => Promise<{ payload: SyncPayload; results: Map<CloudProvider, SyncResult> }>;
downgradeConvergentSync: (
confirmed: boolean,
buildLocalPayload: () => SyncPayload | Promise<SyncPayload>,
applyPayload: (
payload: SyncPayload,
commitReplica: () => Promise<void>,
) => Promise<void>,
) => Promise<Map<CloudProvider, SyncResult>>;
// Gist Revision History
getGistRevisionHistory: () => Promise<Array<{ version: string; date: Date }>>;
downloadGistRevision: (sha: string) => Promise<{
payload: SyncPayload;
meta: import('../../domain/sync').SyncFileMeta;
preview: {
hostCount: number;
keyCount: number;
snippetCount: number;
noteCount: number;
identityCount: number;
portForwardingRuleCount: number;
};
} | null>;
// Settings
setAutoSync: (enabled: boolean, intervalMinutes?: number) => void;
setDeviceName: (name: string) => void;
setSyncStrategy: (strategy: CloudSyncStrategy) => void;
setConvergentSyncEnabled: (enabled: boolean) => ConvergentSyncLocalConfig;
refreshConvergentSyncConfig: () => ConvergentSyncLocalConfig;
// Local Data Reset
resetLocalVersion: () => void;
// Utilities
formatLastSync: (timestamp?: number) => string;
getProviderDotColor: (provider: CloudProvider) => string;
refresh: () => void;
// Event subscription (for non-state events like SYNC_BLOCKED_SHRINK)
subscribeToEvents: (callback: SyncEventCallback) => () => void;
// Shrink-block state query (for banner hydration on mount)
getShrinkBlockedFinding: () => Extract<ShrinkFinding, { suspicious: true }> | null;
}
type PendingBrowserAuthState = {
provider: 'google' | 'onedrive';
sessionId: string;
authAttemptId?: number;
} | null;
let pendingBrowserAuthState: PendingBrowserAuthState = null;
const pendingBrowserAuthListeners = new Set<() => void>();
let activeOAuthBrowserHandoff:
| { sessionId: string; cancel: () => void }
| null = null;
const cancelledOAuthSessionIds = new Set<string>();
const getPendingBrowserAuthState = (): PendingBrowserAuthState => pendingBrowserAuthState;
const subscribePendingBrowserAuthState = (callback: () => void) => {
pendingBrowserAuthListeners.add(callback);
return () => pendingBrowserAuthListeners.delete(callback);
};
const setPendingBrowserAuthState = (next: PendingBrowserAuthState) => {
pendingBrowserAuthState = next;
pendingBrowserAuthListeners.forEach((callback) => callback());
};
const clearPendingBrowserAuthState = (
match?: { provider: 'google' | 'onedrive'; sessionId: string; authAttemptId?: number }
) => {
if (!match) {
setPendingBrowserAuthState(null);
return;
}
if (
pendingBrowserAuthState &&
pendingBrowserAuthState.provider === match.provider &&
pendingBrowserAuthState.sessionId === match.sessionId
) {
setPendingBrowserAuthState(null);
}
};
// ============================================================================
// Hook Implementation
// ============================================================================
// Singleton manager instance
const manager = getCloudSyncManager();
// Subscribe function for useSyncExternalStore
const subscribe = (callback: () => void) => {
return manager.subscribeToStateChanges(callback);
};
// Get snapshot function for useSyncExternalStore
const getSnapshot = (): SyncManagerState => {
return manager.getState();
};
export const useCloudSync = (): CloudSyncHook => {
// Use useSyncExternalStore for real-time state sync across all components
const state = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
const pendingBrowserAuth = useSyncExternalStore(
subscribePendingBrowserAuthState,
getPendingBrowserAuthState,
getPendingBrowserAuthState
);
const activeOAuthSessionIdRef = useRef<string | null>(null);
const activeOAuthProviderRef = useRef<'google' | 'onedrive' | null>(null);
const activeGitHubAuthAbortRef = useRef<AbortController | null>(null);
const activeGitHubAuthAttemptIdRef = useRef<number | null>(null);
const convergentSyncConfig = useSyncExternalStore(
subscribeConvergentSyncLocalConfig,
getConvergentSyncLocalConfigSnapshot,
getConvergentSyncLocalConfigSnapshot,
);
// Auto-unlock: if a master key exists, retrieve the persisted password (Electron safeStorage)
// and unlock silently so users don't have to manage a LOCKED state in the UI.
// Track the master key config hash to detect when a new master key is set up in another window.
const lastMasterKeyHashRef = useRef<string | null>(null);
const attemptedAutoUnlockRef = useRef(false);
useEffect(() => {
// Compute a simple hash of the master key config to detect changes
const currentHash = state.masterKeyConfig
? JSON.stringify({ salt: state.masterKeyConfig.salt, kdf: state.masterKeyConfig.kdf })
: null;
// If master key config changed (e.g., set up in settings window), reset the attempt flag
if (currentHash !== lastMasterKeyHashRef.current) {
lastMasterKeyHashRef.current = currentHash;
attemptedAutoUnlockRef.current = false;
}
if (attemptedAutoUnlockRef.current) return;
if (state.securityState !== 'LOCKED') return;
attemptedAutoUnlockRef.current = true;
void (async () => {
try {
const bridge = netcattyBridge.get();
const password = await bridge?.cloudSyncGetSessionPassword?.();
if (!password) return;
const ok = await manager.unlock(password);
if (!ok) {
void bridge?.cloudSyncClearSessionPassword?.();
}
} catch {
// Ignore auto-unlock errors; manual actions will surface them.
}
})();
}, [state.securityState, state.masterKeyConfig]);
useEffect(() => {
if (state.securityState !== 'UNLOCKED') return;
if (!getConvergentSyncLocalConfig().initialized) return;
void manager.refreshConvergentConflicts().catch(() => {
// A missing/corrupt replica is surfaced by the next explicit sync.
});
}, [state.securityState]);
// Keep plugin sync provider availability aligned with live contributions so
// disabled/uninstalled providers leave the auto-sync ready set after restart.
useEffect(() => {
let cancelled = false;
const refreshAvailable = async () => {
try {
const { pluginExtensionBridge } = await import('./pluginExtensionBridge');
const listed = await pluginExtensionBridge.listProviders('sync');
if (cancelled) return;
const ids = (listed ?? []).map((entry) => {
const nested = (entry as { provider?: { id?: string } }).provider;
return typeof nested?.id === 'string' ? nested.id : '';
}).filter((id) => id.length > 0);
manager.setAvailablePluginSyncProviders(ids);
} catch {
// Transient IPC / host startup failures must not wipe the availability
// catalog; leave the previous set until a successful discovery.
}
};
void refreshAvailable();
let unsubscribe = () => {};
void import('./pluginExtensionBridge').then(({ pluginExtensionBridge }) => {
if (cancelled) return;
unsubscribe = pluginExtensionBridge.onContributionsChanged(() => {
void refreshAvailable();
});
});
return () => {
cancelled = true;
unsubscribe();
};
}, []);
// ========== Computed Values ==========
const hasAnyConnectedProvider = useMemo(() => {
return (Object.values(state.providers) as ProviderConnection[]).some(
(p) => isProviderReadyForSync(p)
);
}, [state.providers]);
const connectedProviderCount = useMemo(() => {
return (Object.values(state.providers) as ProviderConnection[]).filter(
(p) => isProviderReadyForSync(p)
).length;
}, [state.providers]);
const overallSyncStatus = useMemo((): 'none' | 'synced' | 'syncing' | 'error' | 'conflict' | 'blocked' => {
if (state.syncState === 'BLOCKED') return 'blocked';
if (state.syncState === 'CONFLICT') return 'conflict';
if (state.syncState === 'ERROR') return 'error';
if (state.syncState === 'SYNCING') return 'syncing';
const statuses = (Object.values(state.providers) as ProviderConnection[]).map(p => p.status);
if (statuses.some(s => s === 'syncing')) return 'syncing';
if (statuses.some(s => s === 'error')) return 'error';
if (statuses.some(s => s === 'connected')) return 'synced';
return 'none';
}, [state.syncState, state.providers]);
// ========== Master Key Actions ==========
// Note: No need for setState calls - useSyncExternalStore automatically updates
// when manager emits events and calls notifyStateChange()
const setupMasterKey = useCallback(async (password: string, confirmPassword: string) => {
if (password !== confirmPassword) {
throw new Error('Passwords do not match');
}
if (password.length < 8) {
throw new Error('Password must be at least 8 characters');
}
await manager.setupMasterKey(password);
void netcattyBridge.get()?.cloudSyncSetSessionPassword?.(password);
}, []);
const unlock = useCallback(async (password: string): Promise<boolean> => {
const ok = await manager.unlock(password);
if (ok) {
void netcattyBridge.get()?.cloudSyncSetSessionPassword?.(password);
}
return ok;
}, []);
const lock = useCallback(() => {
void netcattyBridge.get()?.cloudSyncClearSessionPassword?.();
manager.lock();
}, []);
const changeMasterKey = useCallback(async (
oldPassword: string,
newPassword: string
): Promise<boolean> => {
const ok = await manager.changeMasterKey(oldPassword, newPassword);
if (ok) {
void netcattyBridge.get()?.cloudSyncSetSessionPassword?.(newPassword);
}
return ok;
}, []);
const verifyPassword = useCallback(async (password: string): Promise<boolean> => {
return manager.verifyPassword(password);
}, []);
// ========== Provider Actions ==========
const connectGitHub = useCallback(async (): Promise<DeviceFlowState> => {
const result = await manager.startProviderAuth('github');
if (result.type !== 'device_code') {
throw new Error('Unexpected auth type');
}
activeGitHubAuthAttemptIdRef.current = result.data.authAttemptId ?? null;
return result.data;
}, []);
const completeGitHubAuth = useCallback(async (
deviceCode: string,
interval: number,
expiresAt: number,
onPending?: () => void,
signal?: AbortSignal,
authAttemptId?: number
): Promise<void> => {
const controller = new AbortController();
const abort = () => controller.abort();
if (signal?.aborted) {
abort();
} else if (signal) {
signal.addEventListener('abort', abort, { once: true });
}
activeGitHubAuthAbortRef.current = controller;
try {
await manager.completeGitHubAuth(
deviceCode,
interval,
expiresAt,
onPending,
controller.signal,
authAttemptId
);
} finally {
if (signal) {
signal.removeEventListener('abort', abort);
}
if (activeGitHubAuthAbortRef.current === controller) {
activeGitHubAuthAbortRef.current = null;
}
if (activeGitHubAuthAttemptIdRef.current === (authAttemptId ?? null)) {
activeGitHubAuthAttemptIdRef.current = null;
}
}
}, []);
const cancelActivePKCEAuth = useCallback(async () => {
const pending = getPendingBrowserAuthState();
const sessionId = pending?.sessionId ?? activeOAuthSessionIdRef.current;
const provider = pending?.provider ?? activeOAuthProviderRef.current;
const authAttemptId = pending?.authAttemptId;
if (!sessionId || !provider) return;
cancelledOAuthSessionIds.add(sessionId);
if (activeOAuthBrowserHandoff?.sessionId === sessionId) {
activeOAuthBrowserHandoff.cancel();
activeOAuthBrowserHandoff = null;
}
manager.cancelProviderAuthAttempt(provider, authAttemptId);
activeOAuthSessionIdRef.current = null;
activeOAuthProviderRef.current = null;
clearPendingBrowserAuthState(
pending
? {
provider: pending.provider,
sessionId: pending.sessionId,
authAttemptId: pending.authAttemptId,
}
: undefined
);
try {
await netcattyBridge.get()?.cancelOAuthCallback?.(sessionId);
} catch {
// Best-effort cleanup
}
}, []);
const runPKCEAuth = useCallback(
async (provider: 'google' | 'onedrive'): Promise<string> => {
const bridge = netcattyBridge.get();
const prepare = bridge?.prepareOAuthCallback;
const awaitCallback = bridge?.awaitOAuthCallback;
const openExternal = bridge?.openExternal;
if (!prepare || !awaitCallback || !openExternal) {
throw new Error('OAuth bridge is unavailable');
}
// Only one loopback OAuth flow can be active at a time. If the user
// starts another provider while a previous browser hop is still pending,
// cancel the stale one first so the new attempt owns the callback port.
await cancelActivePKCEAuth();
// Bind the loopback callback server first so we know which port to put
// in the provider's redirect_uri (#823: 45678 may be in use).
const { redirectUri, sessionId } = await prepare();
activeOAuthSessionIdRef.current = sessionId;
activeOAuthProviderRef.current = provider;
setPendingBrowserAuthState({ provider, sessionId });
try {
const result = await manager.startProviderAuth(provider, redirectUri);
if (result.type !== 'url') {
throw new Error('Unexpected auth type');
}
const data = result.data;
if (cancelledOAuthSessionIds.has(sessionId)) {
throw new Error('OAuth flow cancelled');
}
const adapter = manager.getAdapter(provider) as
| { getPKCEState?: () => string | null }
| undefined;
const expectedState = adapter?.getPKCEState?.() || undefined;
const callbackPromise = awaitCallback(expectedState, sessionId);
// Use system browser to avoid white-screen issues in popup windows (#563).
// Once the browser has opened, let the rest of the PKCE handshake
// continue in the background so closing the browser later does not
// leave the whole settings page locked waiting on a timeout.
let openTimer: ReturnType<typeof setTimeout> | null = null;
let browserOpened = false;
let rejectBrowserPromise: ((error: Error) => void) | null = null;
const browserPromise = new Promise<void>((resolve, reject) => {
rejectBrowserPromise = reject;
openTimer = setTimeout(async () => {
try {
await openExternal(data.url);
browserOpened = true;
resolve();
} catch (err) {
bridge?.cancelOAuthCallback?.(sessionId);
reject(
err instanceof Error
? err
: new Error('Failed to open browser for authentication')
);
}
}, 100);
});
activeOAuthBrowserHandoff = {
sessionId,
cancel: () => {
if (openTimer) {
clearTimeout(openTimer);
openTimer = null;
}
if (rejectBrowserPromise) {
rejectBrowserPromise(new Error('OAuth flow cancelled'));
rejectBrowserPromise = null;
}
},
};
try {
await Promise.race([
browserPromise,
callbackPromise.then(
() => {
throw new Error('OAuth callback completed before browser handoff');
},
(error) => {
if (browserOpened) {
return new Promise<void>(() => {});
}
throw error;
}
),
]);
} finally {
if (openTimer) clearTimeout(openTimer);
if (activeOAuthBrowserHandoff?.sessionId === sessionId) {
activeOAuthBrowserHandoff = null;
}
}
setPendingBrowserAuthState({
provider,
sessionId,
authAttemptId: data.authAttemptId,
});
const completionPromise = (async () => {
try {
const { code } = await callbackPromise;
await manager.completePKCEAuth(provider, code, data.redirectUri, data.authAttemptId);
} catch (error) {
const ownsActiveSession =
activeOAuthSessionIdRef.current === sessionId &&
activeOAuthProviderRef.current === provider;
const message = error instanceof Error ? error.message : String(error);
const cancelledOrSuperseded =
message.includes('cancelled') || message.includes('auth superseded');
const timedOut = message.toLowerCase().includes('timeout');
if (ownsActiveSession && (cancelledOrSuperseded || timedOut)) {
activeOAuthSessionIdRef.current = null;
activeOAuthProviderRef.current = null;
cancelledOAuthSessionIds.delete(sessionId);
clearPendingBrowserAuthState({
provider,
sessionId,
authAttemptId: data.authAttemptId,
});
manager.resetProviderStatus(provider);
} else if (ownsActiveSession) {
activeOAuthSessionIdRef.current = null;
activeOAuthProviderRef.current = null;
cancelledOAuthSessionIds.delete(sessionId);
clearPendingBrowserAuthState({
provider,
sessionId,
authAttemptId: data.authAttemptId,
});
manager.setProviderError(provider, message);
}
} finally {
if (
activeOAuthSessionIdRef.current === sessionId &&
activeOAuthProviderRef.current === provider
) {
activeOAuthSessionIdRef.current = null;
activeOAuthProviderRef.current = null;
}
cancelledOAuthSessionIds.delete(sessionId);
clearPendingBrowserAuthState({
provider,
sessionId,
authAttemptId: data.authAttemptId,
});
}
})();
// Release the transient "connecting" UI once the browser handoff has
// happened. The callback session remains active in the background and
// will mark the provider connected when the redirect completes.
// Do NOT use resetProviderStatus here — it would restore from the
// auth snapshot and delete the adapter we just created, making the
// eventual completePKCEAuth call fail with "adapter not initialized".
manager.clearConnectingStatus(provider);
manager.clearProviderError(provider);
void completionPromise;
return data.url;
} catch (err) {
const ownsActiveSession =
activeOAuthSessionIdRef.current === sessionId &&
activeOAuthProviderRef.current === provider;
try {
await bridge?.cancelOAuthCallback?.(sessionId);
} catch {
// Best-effort cleanup
}
if (ownsActiveSession) {
activeOAuthSessionIdRef.current = null;
activeOAuthProviderRef.current = null;
manager.cancelProviderAuthAttempt(provider);
manager.resetProviderStatus(provider);
}
throw err;
}
},
[cancelActivePKCEAuth]
);
const connectGoogle = useCallback(async (): Promise<string> => {
return runPKCEAuth('google');
}, [runPKCEAuth]);
const connectOneDrive = useCallback(async (): Promise<string> => {
return runPKCEAuth('onedrive');
}, [runPKCEAuth]);
const completePKCEAuth = useCallback(async (
provider: 'google' | 'onedrive',
code: string,
redirectUri: string
): Promise<void> => {
await manager.completePKCEAuth(provider, code, redirectUri);
}, []);
const disconnectProvider = useCallback(async (provider: CloudProvider): Promise<void> => {
await manager.disconnectProvider(provider);
}, []);
const resetProviderStatus = useCallback((provider: CloudProvider): void => {
manager.resetProviderStatus(provider);
}, []);
const connectWebDAV = useCallback(async (config: WebDAVConfig): Promise<void> => {
await manager.connectConfigProvider('webdav', config);
}, []);
const connectS3 = useCallback(async (config: S3Config): Promise<void> => {
await manager.connectConfigProvider('s3', config);
}, []);
/**
* Connect a namespaced plugin sync Provider (encrypted-object storage only).
* Configuration is opaque plugin-owned JSON; encryption stays host-owned.
*/
const connectPluginProvider = useCallback(async (
providerId: string,
configuration: unknown = {},
credential?: unknown,
): Promise<void> => {
await manager.connectPluginProvider(providerId, configuration, credential);
}, []);
const cancelOAuthConnect = useCallback(() => {
const githubAbort = activeGitHubAuthAbortRef.current;
if (githubAbort) {
manager.cancelProviderAuthAttempt('github', activeGitHubAuthAttemptIdRef.current ?? undefined);
activeGitHubAuthAttemptIdRef.current = null;
githubAbort.abort();
return;
}
void cancelActivePKCEAuth();
}, [cancelActivePKCEAuth]);
// ========== Settings ==========
const setAutoSync = useCallback((enabled: boolean, intervalMinutes?: number) => {
manager.setAutoSync(enabled, intervalMinutes);
}, []);
const setDeviceName = useCallback((name: string) => {
manager.setDeviceName(name);
}, []);
const setSyncStrategy = useCallback((strategy: CloudSyncStrategy) => {
manager.setSyncStrategy(strategy);
}, []);
// ========== Utilities ==========
const getProviderDotColor = useCallback((provider: CloudProvider): string => {
return getSyncDotColor(state.providers[provider].status);
}, [state.providers]);
const refresh = useCallback(() => {
// Force a re-render by triggering state change notification
// This is now a no-op since useSyncExternalStore handles updates automatically
}, []);
const ensureUnlocked = useCallback(async (): Promise<void> => {
const current = manager.getState();
if (current.securityState === 'UNLOCKED') return;
if (current.securityState === 'NO_KEY') {
throw new Error('No master key configured');
}
const bridge = netcattyBridge.get();
const password = await bridge?.cloudSyncGetSessionPassword?.();
if (password) {
const ok = await manager.unlock(password);
if (ok) return;
void bridge?.cloudSyncClearSessionPassword?.();
}
throw new Error('Vault is locked');
}, []);
const syncNowWithUnlock = useCallback(async (payload: SyncPayload, opts?: CloudSyncRunOptions) => {
await ensureUnlocked();
const controller = new AbortController();
let onAbort: (() => void) | undefined;
if (opts?.signal) {
if (opts.signal.aborted) controller.abort();
else {
onAbort = () => controller.abort();
opts.signal.addEventListener('abort', onAbort, { once: true });
}
}
try {
const results = await manager.syncAllProviders(payload, { ...opts, signal: controller.signal });
const { commitPluginSidecarsAfterSuccessfulSync } = await import('../pluginSyncSidecarBridge');
commitPluginSidecarsAfterSuccessfulSync(payload, results.values());
return results;
} finally {
if (opts?.signal && onAbort) opts.signal.removeEventListener('abort', onAbort);
}
}, [ensureUnlocked]);
const syncToProviderWithUnlock = useCallback(async (
provider: CloudProvider,
payload: SyncPayload,
opts?: Pick<CloudSyncRunOptions, 'overrideShrink' | 'applyConvergentPayload' | 'signal'>,
) => {
await ensureUnlocked();
const controller = new AbortController();
let onAbort: (() => void) | undefined;
if (opts?.signal) {
if (opts.signal.aborted) controller.abort();
else {
onAbort = () => controller.abort();
opts.signal.addEventListener('abort', onAbort, { once: true });
}
}
try {
const result = await manager.syncToProvider(provider, payload, { ...opts, signal: controller.signal });
const { commitPluginSidecarsAfterSuccessfulSync } = await import('../pluginSyncSidecarBridge');
commitPluginSidecarsAfterSuccessfulSync(payload, [result]);
return result;
} finally {
if (opts?.signal && onAbort) opts.signal.removeEventListener('abort', onAbort);
}
}, [ensureUnlocked]);
const downloadFromProviderWithUnlock = useCallback(async (provider: CloudProvider) => {
await ensureUnlocked();
return await manager.downloadFromProvider(provider);
}, [ensureUnlocked]);
const commitRemoteInspectionWithUnlock = useCallback(async (
provider: CloudProvider,
remoteFile: SyncedFile,
payload: SyncPayload,
opts: { recordDownload?: boolean } = {},
) => {
await ensureUnlocked();
await manager.commitRemoteInspection(provider, remoteFile, payload, opts);
}, [ensureUnlocked]);
const subscribeToEvents = useCallback(
(callback: SyncEventCallback) => manager.subscribe(callback),
[],
);
const getShrinkBlockedFinding = useCallback(
() => manager.getShrinkBlockedFinding(),
[],
);
const resolveConflictWithUnlock = useCallback(async (resolution: ConflictResolution) => {
await ensureUnlocked();
return await manager.resolveConflict(resolution);
}, [ensureUnlocked]);
const resolveConvergentConflictWithUnlock = useCallback(async (
addressKey: string,
candidateDot: string,
applyPayload: (
payload: SyncPayload,
commitReplica: () => Promise<void>,
) => Promise<void>,
) => {
await ensureUnlocked();
// Collect live sidecars so conflict apply/upload does not revert plugin
// settings that changed after the last provider baseline. Operational
// collection failures must abort (not proceed as empty). Host gated off /
// non-authoritative collect must omit the field (not last-known cache) so
// apply preserves local DB sidecars.
const {
collectPluginSyncSidecarsFromHost,
isPluginSidecarHostUnavailableError,
} = await import('../pluginSyncSidecarBridge');
let pluginSidecars: SyncPayload['pluginSidecars'] | undefined;
try {
const collected = await collectPluginSyncSidecarsFromHost({ liveOnly: true });
if (collected) pluginSidecars = collected;
} catch (error) {
if (isPluginSidecarHostUnavailableError(error)) {
// Host gated off: omit field so apply preserves local sidecars.
} else {
throw error;
}
}
return manager.resolveConvergentConflict(addressKey, candidateDot, applyPayload, {
pluginSidecars,
});
}, [ensureUnlocked]);
const refreshConvergentSyncConfig = useCallback(() => {
return refreshConvergentSyncLocalConfigSnapshot();
}, []);
const setConvergentSyncEnabled = useCallback((enabled: boolean) => {
const current = getConvergentSyncLocalConfig();
const next = enabled
? setConvergentSyncLocalConfig({ enabled: true, initialized: current.initialized })
: pauseConvergentSync();
return next;
}, []);
const downgradeConvergentSyncWithUnlock = useCallback(async (
confirmed: boolean,
buildLocalPayload: () => SyncPayload | Promise<SyncPayload>,
applyPayload: (
payload: SyncPayload,
commitReplica: () => Promise<void>,
) => Promise<void>,
) => {
await ensureUnlocked();
return manager.downgradeConvergentSync(confirmed, buildLocalPayload, applyPayload);
}, [ensureUnlocked]);
return {
// State
securityState: state.securityState,
syncState: state.syncState,
isUnlocked: state.securityState === 'UNLOCKED',
isSyncing: state.syncState === 'SYNCING',
providers: state.providers,
currentConflict: state.currentConflict,
lastError: state.lastError,
deviceName: state.deviceName,
autoSyncEnabled: state.autoSyncEnabled,
autoSyncInterval: state.autoSyncInterval,
syncStrategy: state.syncStrategy,
localVersion: state.localVersion,
localUpdatedAt: state.localUpdatedAt,
remoteVersion: state.remoteVersion,
remoteUpdatedAt: state.remoteUpdatedAt,
syncHistory: state.syncHistory,
pendingLocalSync: state.pendingLocalSync,
convergentConflicts: state.convergentConflicts,
convergentSyncConfig,
pendingBrowserAuthProvider: pendingBrowserAuth?.provider ?? null,
// Computed
hasAnyConnectedProvider,
connectedProviderCount,
overallSyncStatus,
// Master Key Actions
setupMasterKey,
unlock,
lock,
changeMasterKey,
verifyPassword,
// Provider Actions
connectGitHub,
completeGitHubAuth,
connectGoogle,
connectOneDrive,
connectWebDAV,
connectS3,
connectPluginProvider,
completePKCEAuth,
cancelOAuthConnect,
disconnectProvider,
resetProviderStatus,
// Sync Actions
syncNow: syncNowWithUnlock,
syncToProvider: syncToProviderWithUnlock,
downloadFromProvider: downloadFromProviderWithUnlock,
commitRemoteInspection: commitRemoteInspectionWithUnlock,
resolveConflict: resolveConflictWithUnlock,
resolveConvergentConflict: resolveConvergentConflictWithUnlock,
downgradeConvergentSync: downgradeConvergentSyncWithUnlock,
// Gist Revision History (#679)
getGistRevisionHistory: manager.getGistRevisionHistory.bind(manager),
downloadGistRevision: manager.downloadGistRevision.bind(manager),
// Settings
setAutoSync,
setDeviceName,
setSyncStrategy,
setConvergentSyncEnabled,
refreshConvergentSyncConfig,
// Local Data Reset
resetLocalVersion: () => manager.resetLocalVersion(),
// Utilities
formatLastSync,
getProviderDotColor,
refresh,
// Event subscription
subscribeToEvents,
// Shrink-block state query
getShrinkBlockedFinding,
};
};
export default useCloudSync;