Files
Netcatty/application/state/useCloudSync.ts
T
陈大猫andClaude Opus 4.6 2a75f863f8 fix: reset cloud sync connect button when OAuth popup is closed (#544)
* fix: reset cloud sync connect button when OAuth popup is closed

When users close the OAuth popup without completing authorization,
the connect button was stuck in "Connecting" state indefinitely
(up to 5-minute timeout).

Changes:
- Track OAuth popup window and poll for closure (Google, OneDrive)
- Cancel OAuth callback server when popup is closed, immediately
  rejecting the pending promise instead of waiting for timeout
- Reset provider status via disconnectProvider on auth failure so
  the connect button returns to clickable state
- Suppress toast for user-initiated cancellation (popup closed)
- Also reset GitHub provider status on device flow failure

Closes #542

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

* fix: use resetProviderStatus instead of disconnectProvider on auth failure

disconnectProvider tears down existing connections (signOut, delete
adapter, clear merge base). If a user was re-authenticating and
cancelled, this would destroy their working connection.

Add resetProviderStatus() that only resets the UI status to
'disconnected' without any teardown side effects.

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

* fix: add resetProviderStatus to CloudSyncHook interface

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

* fix: remove noreferrer from OAuth popup to enable window tracking

noreferrer implies noopener in browser spec, causing window.open()
to return null and defeating the popup closure detection entirely.
Safe to remove since OAuth targets are trusted providers (Google,
Microsoft) and the Referer is just a localhost URL.

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

* fix: guard resetProviderStatus and cancel delayed popup on early failure

- resetProviderStatus only resets if status is 'connecting', preserving
  already-authenticated providers when sync initialization fails
- Cancel the delayed setTimeout for window.open if callbackPromise
  rejects before 100ms, preventing a stray popup and leaking interval

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

* fix: reset GitHub provider status when device flow modal is closed

The modal onClose only hid the modal and stopped the polling flag,
but the provider status stayed at 'connecting'. Now calls
resetProviderStatus('github') so the button returns to clickable.

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-27 19:24:06 +08:00

496 lines
17 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 SyncPayload,
type SyncResult,
type SyncHistoryEntry,
type WebDAVConfig,
type S3Config,
formatLastSync,
getSyncDotColor,
isProviderReadyForSync,
} from '../../domain/sync';
import {
getCloudSyncManager,
type SyncManagerState,
} from '../../infrastructure/services/CloudSyncManager';
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
import type { DeviceFlowState } from '../../infrastructure/services/adapters/GitHubAdapter';
// ============================================================================
// Types
// ============================================================================
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;
localVersion: number;
localUpdatedAt: number;
remoteVersion: number;
remoteUpdatedAt: number;
syncHistory: SyncHistoryEntry[];
// Computed
hasAnyConnectedProvider: boolean;
connectedProviderCount: number;
overallSyncStatus: 'none' | 'synced' | 'syncing' | 'error' | 'conflict';
// 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
) => Promise<void>;
connectGoogle: () => Promise<string>;
connectOneDrive: () => Promise<string>;
connectWebDAV: (config: WebDAVConfig) => Promise<void>;
connectS3: (config: S3Config) => Promise<void>;
completePKCEAuth: (
provider: 'google' | 'onedrive',
code: string,
redirectUri: string
) => Promise<void>;
disconnectProvider: (provider: CloudProvider) => Promise<void>;
resetProviderStatus: (provider: CloudProvider) => void;
// Sync Actions
syncNow: (payload: SyncPayload) => Promise<Map<CloudProvider, SyncResult>>;
syncToProvider: (provider: CloudProvider, payload: SyncPayload) => Promise<SyncResult>;
downloadFromProvider: (provider: CloudProvider) => Promise<SyncPayload | null>;
resolveConflict: (resolution: ConflictResolution) => Promise<SyncPayload | null>;
// Settings
setAutoSync: (enabled: boolean, intervalMinutes?: number) => void;
setDeviceName: (name: string) => void;
// Local Data Reset
resetLocalVersion: () => void;
// Utilities
formatLastSync: (timestamp?: number) => string;
getProviderDotColor: (provider: CloudProvider) => string;
refresh: () => void;
}
// ============================================================================
// 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);
// 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]);
// ========== 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' => {
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');
}
return result.data as DeviceFlowState;
}, []);
const completeGitHubAuth = useCallback(async (
deviceCode: string,
interval: number,
expiresAt: number,
onPending?: () => void
): Promise<void> => {
await manager.completeGitHubAuth(deviceCode, interval, expiresAt, onPending);
}, []);
const connectGoogle = useCallback(async (): Promise<string> => {
const result = await manager.startProviderAuth('google');
if (result.type !== 'url') {
throw new Error('Unexpected auth type');
}
const data = result.data as { url: string; redirectUri: string };
// Start OAuth callback server in Electron and wait for authorization
const bridge = netcattyBridge.get();
const startCallback = bridge?.startOAuthCallback;
if (startCallback) {
// Get state from adapter for CSRF protection
const adapter = manager.getAdapter('google') as { getPKCEState?: () => string | null } | undefined;
const expectedState = adapter?.getPKCEState?.() || undefined;
// Start callback server and open browser
const callbackPromise = startCallback(expectedState);
// Open browser after starting server — omit noopener/noreferrer so we can track the popup
let popup: Window | null = null;
let popupPollTimer: ReturnType<typeof setInterval> | null = null;
const openTimer = setTimeout(() => {
popup = window.open(data.url, "_blank", "width=600,height=700");
// Poll for popup closure — if user closes it, cancel the OAuth flow
if (popup) {
popupPollTimer = setInterval(() => {
if (popup?.closed) {
if (popupPollTimer) clearInterval(popupPollTimer);
bridge?.cancelOAuthCallback?.();
}
}, 500);
}
}, 100);
try {
// Wait for callback
const { code } = await callbackPromise;
// Complete auth with the received code
await manager.completePKCEAuth('google', code, data.redirectUri);
} finally {
clearTimeout(openTimer);
if (popupPollTimer) clearInterval(popupPollTimer);
}
}
return data.url;
}, []);
const connectOneDrive = useCallback(async (): Promise<string> => {
const result = await manager.startProviderAuth('onedrive');
if (result.type !== 'url') {
throw new Error('Unexpected auth type');
}
const data = result.data as { url: string; redirectUri: string };
// Start OAuth callback server in Electron and wait for authorization
const bridge = netcattyBridge.get();
const startCallback = bridge?.startOAuthCallback;
if (startCallback) {
// Get state from adapter for CSRF protection
const adapter = manager.getAdapter('onedrive') as { getPKCEState?: () => string | null } | undefined;
const expectedState = adapter?.getPKCEState?.() || undefined;
// Start callback server and open browser
const callbackPromise = startCallback(expectedState);
// Open browser after starting server — omit noopener/noreferrer so we can track the popup
let popup: Window | null = null;
let popupPollTimer: ReturnType<typeof setInterval> | null = null;
const openTimer = setTimeout(() => {
popup = window.open(data.url, "_blank", "width=600,height=700");
// Poll for popup closure — if user closes it, cancel the OAuth flow
if (popup) {
popupPollTimer = setInterval(() => {
if (popup?.closed) {
if (popupPollTimer) clearInterval(popupPollTimer);
bridge?.cancelOAuthCallback?.();
}
}, 500);
}
}, 100);
try {
// Wait for callback
const { code } = await callbackPromise;
// Complete auth with the received code
await manager.completePKCEAuth('onedrive', code, data.redirectUri);
} finally {
clearTimeout(openTimer);
if (popupPollTimer) clearInterval(popupPollTimer);
}
}
return data.url;
}, []);
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);
}, []);
// ========== Settings ==========
const setAutoSync = useCallback((enabled: boolean, intervalMinutes?: number) => {
manager.setAutoSync(enabled, intervalMinutes);
}, []);
const setDeviceName = useCallback((name: string) => {
manager.setDeviceName(name);
}, []);
// ========== 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) => {
await ensureUnlocked();
return await manager.syncAllProviders(payload);
}, [ensureUnlocked]);
const syncToProviderWithUnlock = useCallback(async (provider: CloudProvider, payload: SyncPayload) => {
await ensureUnlocked();
return await manager.syncToProvider(provider, payload);
}, [ensureUnlocked]);
const downloadFromProviderWithUnlock = useCallback(async (provider: CloudProvider) => {
await ensureUnlocked();
return await manager.downloadFromProvider(provider);
}, [ensureUnlocked]);
const resolveConflictWithUnlock = useCallback(async (resolution: ConflictResolution) => {
await ensureUnlocked();
return await manager.resolveConflict(resolution);
}, [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,
localVersion: state.localVersion,
localUpdatedAt: state.localUpdatedAt,
remoteVersion: state.remoteVersion,
remoteUpdatedAt: state.remoteUpdatedAt,
syncHistory: state.syncHistory,
// Computed
hasAnyConnectedProvider,
connectedProviderCount,
overallSyncStatus,
// Master Key Actions
setupMasterKey,
unlock,
lock,
changeMasterKey,
verifyPassword,
// Provider Actions
connectGitHub,
completeGitHubAuth,
connectGoogle,
connectOneDrive,
connectWebDAV,
connectS3,
completePKCEAuth,
disconnectProvider,
resetProviderStatus,
// Sync Actions
syncNow: syncNowWithUnlock,
syncToProvider: syncToProviderWithUnlock,
downloadFromProvider: downloadFromProviderWithUnlock,
resolveConflict: resolveConflictWithUnlock,
// Settings
setAutoSync,
setDeviceName,
// Local Data Reset
resetLocalVersion: () => manager.resetLocalVersion(),
// Utilities
formatLastSync,
getProviderDotColor,
refresh,
};
};
export default useCloudSync;