Cloud sync data-loss prevention (4-layer defense) (#742)

* feat(sync-guard): extend SyncState with BLOCKED + add shrink event variants

* feat(sync-guard): add detectSuspiciousShrink pure function with 12 unit tests

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* polish(sync-guard): drop unnecessary cast, sharpen test naming, pin priority invariant

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(test): include domain/*.test.ts in npm test glob

* feat(sync-guard): gate syncToProvider with shrink detection + force-push override

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(sync-guard): reset overrideShrinkOnce before early return for invariant strictness

* fix(sync-guard): extend shrink guard to syncAllProviders (the actual sync entry point)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(sync-guard): apply empty-vault guard uniformly to auto and manual sync

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(sync-guard): preserve merge base on same-account re-auth

Adds providerAccountId persistence; completePKCEAuth and completeGitHubAuth
now only clear syncBase/anchor when the authenticated account id differs from
the previously stored one, preventing zombie-entry resurrection on token
refresh. disconnectProvider clears the stored id so a reconnect starts fresh.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(sync-guard): add i18n strings for sync-blocked banner + force-push modal

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(sync-guard): add SyncBlockedBanner showing shrink findings with restore/force-push actions

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(sync-guard): stable subscribeToEvents reference + type-safe finding narrowing

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(sync-guard): force-push confirmation modal + scroll restore button into view

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* ux(local-backups): show version as title, demote reason+timestamp to meta line

* feat(local-backups): record + display sync data version (v5/v6...) on each backup

Each backup now captures the live CloudSyncManager.localVersion at creation
time. UI shows it as title (v5, v6, ...) with timestamp + reason demoted to
the meta line. Backups created before this field existed (or before any
successful cloud sync) fall back to timestamp as title.

Replaces the earlier app-version-transition title which conflated app
version with sync data version.

* fix(sync-guard): consume override flag at sync entry + restore provider status on block

- Snapshot+clear overrideShrinkOnce at top of syncToProvider and
  syncAllProviders so an early-return cannot leak the flag to a later
  unrelated sync (Codex P1).
- Restore provider status to 'connected' when shrink-block returns from
  syncToProvider; previously left provider stuck on 'syncing' in the
  UI (Codex P2).
- Process pre-existing check errors before returning from the
  shouldBlockAll branch in syncAllProviders so a check-failed provider
  isn't dropped from results (Codex P2).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(sync-guard): refactor force-push to parameter passing + add credential-availability guard

The previous design used a one-shot boolean flag on CloudSyncManager set
by forcePushOverrideShrink(). Even with snapshot+clear at sync entry
points, the renderer wrapper's await ensureUnlocked() could throw before
the flag was consumed, leaving it armed for the next unrelated sync.

Fix: pass overrideShrink as a call-time parameter through the chain.
Eliminates the persistent flag and its leak surface.

Also: force-push now runs the same ensureSyncablePayload(...) guard the
other manual sync entry points use, so a vault with encrypted-credential
placeholders won't be uploaded via the force path either.

Addresses the latest two Codex P1/P2 findings on #742.

* fix(sync-guard): backfill account id from in-memory state for upgrade-path re-auth

Users upgrading to this PR have no netcatty.sync.accountId.* persisted yet.
On their first re-auth the guard saw previousId=null and cleared the
merge base anyway, defeating the point of the same-account preservation.

Snapshot the in-memory account id BEFORE overwriting providers[provider]
and use it as a fallback when the persisted id is missing. New users
(no prior connection at all) still get the clear-on-first-auth path.

Addresses Codex P1 on #742.

* fix(sync-guard): inspect force-push results + mark blocked single-provider as error

- Force-push handler now inspects syncNow result entries: applies any
  mergedPayload to local state, only clears the banner when all providers
  report success, surfaces a toast error otherwise. Previously the banner
  cleared unconditionally regardless of network/auth failures (Codex P1).

- syncToProvider shrink-block branches now mark provider status as
  'error' with a 'Sync blocked: would delete too much' message instead
  of 'connected'. Status aggregators treat 'connected' as healthy, so
  the blocked upload was surfacing as 'synced' in the UI (Codex P2).
  syncAllProviders already used this pattern; this brings the
  single-provider path in line.

* fix(sync-guard): exempt USE_LOCAL conflict + clear post-merge BLOCKED + expose 'blocked' status

- USE_LOCAL conflict resolution now passes { overrideShrink: true }: the
  conflict modal already served as user confirmation, and shrink-blocking
  it left users with a closed modal and an opaque banner (Review C-1).

- Post-merge round-trip in useAutoSync now detects shrink-blocked results
  and resets syncState to IDLE via new manager.clearShrinkBlockedState().
  The merged data is already applied locally; the next user-triggered
  sync will re-check, and we don't wedge the manager in BLOCKED with no
  visible banner outside the Settings tab (Review I-1).

- overallSyncStatus now reports 'blocked' as a distinct value from
  'error', so downstream UI (status icon, future badges) can offer
  shrink-block-specific affordances (Review I-2).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(sync-guard): stabilize banner subscription dep + map 'blocked' status to error indicator

- The SyncBlockedBanner subscription useEffect depended on [sync] (the
  whole hook return object), which gets a new reference every render.
  This caused the listener to be unsubscribed+resubscribed on every
  render, opening a tiny race window where a SYNC_BLOCKED_SHRINK event
  could be missed and the banner would never appear. Destructure
  subscribeToEvents (already useCallback-stable) and depend on it
  directly, so the effect runs exactly once on mount.

- SyncStatusButton's status mapping had no arm for the new 'blocked'
  value, falling through to 'none' (idle). The global status indicator
  said healthy while the in-page banner said paused. Map 'blocked' to
  the same error indicator used for 'conflict' so the UI is consistent.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(sync-guard): only clear banner on actual success + hydrate from manager state

- Banner subscription now clears only on SYNC_COMPLETED with result.success.
  SYNC_STARTED (auto-sync timer ticks) and SYNC_FORCED (fires BEFORE upload)
  could clear the banner prematurely, removing the user's recovery affordance
  while the underlying issue was unresolved (Codex P2).

- Manager now persists the last shrink finding in state.lastShrinkFinding
  alongside the SYNC_BLOCKED_SHRINK emission. New public getter
  getShrinkBlockedFinding() returns it when syncState is BLOCKED. Renderer
  hydrates the banner on mount so a block that happened off-screen
  (auto-sync while user was on another tab) is still visible when they
  open Sync Settings (Codex P2).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(sync-guard): unified BLOCKED-cleared event + USE_LOCAL inspects results

- USE_LOCAL conflict resolution now inspects syncNow() results, applies
  any mergedPayload to local state, surfaces a toast error and KEEPS the
  modal open on failure (so user can switch to USE_REMOTE). Mirrors the
  force-push handler pattern. Without this, USE_LOCAL silently 'succeeded'
  even when providers failed (Codex CLI P1).

- New SYNC_BLOCKED_CLEARED event emitted on every BLOCKED -> non-BLOCKED
  transition via a private exitBlockedState() helper. Banner subscribes to
  this single signal instead of guessing from per-provider SYNC_COMPLETED
  events. Fixes:
    - Multi-provider scenarios where first SYNC_COMPLETED clears the banner
      while a later provider was still going to fail (Codex CLI P1).
    - clearShrinkBlockedState() (post-merge self-heal) silently leaving
      the banner stuck because no event was emitted (Codex CLI P2).

- disconnectProvider() now also exits BLOCKED state. Disconnecting
  implicitly resolves any pending shrink-block warning, otherwise the
  stale alert carried over to the next-account reconnect (Codex CLI P2).

- All BLOCKED -> non-BLOCKED transitions consolidated through
  exitBlockedState() so lastShrinkFinding cleanup + event emission are
  always paired (Codex CLI P3 #6 covered).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(sync-guard): only clear BLOCKED on actual success, not on transient ERROR/SYNCING/CONFLICT

Previous patch called exitBlockedState() at every BLOCKED -> non-BLOCKED
transition, but this clears the banner on transitions that don't actually
resolve the shrink concern:

- SYNCING (sync just started — about to try, may fail)
- ERROR (transient transport failure, shrink concern still real)
- CONFLICT (separate concern; doesn't resolve the shrink)

If a user was in BLOCKED then triggered a sync that failed for an unrelated
reason (network, auth), the banner cleared and they lost the warning.

Restrict exitBlockedState() to terminal-success transitions:
- IDLE on successful upload (data made it to cloud — concern resolved)
- explicit clears (disconnectProvider, clearShrinkBlockedState)
- conflict resolution (USE_REMOTE/USE_LOCAL also end in IDLE)

Found by Codex CLI review of commit 12d7fa7b.

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
陈大猫
2026-04-16 22:43:19 +08:00
committed by GitHub
parent 8ef91e1266
commit 54b26511a1
15 changed files with 944 additions and 55 deletions

View File

@@ -472,6 +472,30 @@ const en: Messages = {
'sync.autoSync.emptyVaultConflict.keepEmpty': 'Keep Empty',
'sync.autoSync.emptyVaultConflict.keepEmptyDesc': 'Start fresh with an empty vault',
'sync.autoSync.emptyVaultConflict.cloudSummary': '{hosts} hosts, {keys} keys, {snippets} snippets',
'sync.autoSync.emptyVaultManual': 'Cannot sync: the local vault is empty. Restore from a local backup or enable Force Push in the sync panel first.',
'sync.blocked.title': 'Sync paused',
'sync.blocked.reason.bulkShrink': 'Would delete {lost} of {baseCount} {entityType} from cloud ({percent}% reduction).',
'sync.blocked.reason.largeShrink': 'Would delete {lost} {entityType} from cloud.',
'sync.blocked.detail': 'This is usually caused by a degraded local state (keychain failure, partial data load). Restore from a local backup, or force-push if you truly meant to remove these entries.',
'sync.blocked.restoreButton': 'Restore from local backup',
'sync.blocked.forcePushButton': 'Force push anyway',
'sync.forcePush.title': 'Confirm force push',
'sync.forcePush.body': 'You are about to remove {lost} {entityType} from the cloud. This cannot be undone. Proceed?',
'sync.forcePush.confirm': 'Yes, push anyway',
'sync.forcePush.cancel': 'Cancel',
'sync.entityType.hosts': 'hosts',
'sync.entityType.keys': 'keys',
'sync.entityType.identities': 'identities',
'sync.entityType.snippets': 'snippets',
'sync.entityType.customGroups': 'groups',
'sync.entityType.snippetPackages': 'snippet packages',
'sync.entityType.knownHosts': 'known-host entries',
'sync.entityType.portForwardingRules': 'port-forwarding rules',
'sync.entityType.groupConfigs': 'group configs',
'sync.credentialsUnavailable': 'This device cannot decrypt some saved credentials. Re-enter credentials locally before syncing.',
'time.never': 'Never',
'time.justNow': 'Just now',

View File

@@ -291,6 +291,30 @@ const zhCN: Messages = {
'sync.autoSync.emptyVaultConflict.keepEmpty': '保持为空',
'sync.autoSync.emptyVaultConflict.keepEmptyDesc': '从头开始,使用空的主机库',
'sync.autoSync.emptyVaultConflict.cloudSummary': '{hosts} 台主机,{keys} 个密钥,{snippets} 个代码片段',
'sync.autoSync.emptyVaultManual': '无法同步:本地 vault 为空。请先从本地备份恢复,或在同步面板里使用"强制推送"。',
'sync.blocked.title': '同步已暂停',
'sync.blocked.reason.bulkShrink': '即将从云端删除 {baseCount} 条 {entityType} 中的 {lost} 条(缩减 {percent}%)。',
'sync.blocked.reason.largeShrink': '即将从云端删除 {lost} 条 {entityType}。',
'sync.blocked.detail': '通常是本地状态异常(钥匙串故障、数据加载不全)导致。请从本地备份恢复,如果确实要删这些条目请使用强制推送。',
'sync.blocked.restoreButton': '从本地备份恢复',
'sync.blocked.forcePushButton': '强制推送',
'sync.forcePush.title': '确认强制推送',
'sync.forcePush.body': '你将从云端移除 {lost} 条 {entityType},此操作不可撤销。继续?',
'sync.forcePush.confirm': '确认推送',
'sync.forcePush.cancel': '取消',
'sync.entityType.hosts': '主机',
'sync.entityType.keys': '密钥',
'sync.entityType.identities': '身份',
'sync.entityType.snippets': '代码片段',
'sync.entityType.customGroups': '分组',
'sync.entityType.snippetPackages': '片段包',
'sync.entityType.knownHosts': '主机密钥记录',
'sync.entityType.portForwardingRules': '端口转发规则',
'sync.entityType.groupConfigs': '分组配置',
'sync.credentialsUnavailable': '当前设备无法解密部分已保存凭据。请先在本地重新输入凭据后再同步。',
'time.never': '从未',
'time.justNow': '刚刚',

View File

@@ -6,15 +6,38 @@ import {
STORAGE_KEY_VAULT_RESTORE_IN_PROGRESS_UNTIL,
} from '../infrastructure/config/storageKeys';
import { localStorageAdapter } from '../infrastructure/persistence/localStorageAdapter';
import { getCloudSyncManager } from '../infrastructure/services/CloudSyncManager';
import { netcattyBridge } from '../infrastructure/services/netcattyBridge';
import { hasMeaningfulSyncData } from './syncPayload';
/**
* Snapshot the current sync data version (the integer that increments
* on each successful cloud sync). Returns undefined when the value is
* 0 (never synced) or unavailable, so the UI can fall back to timestamp.
*/
function captureCurrentSyncDataVersion(): number | undefined {
try {
const state = getCloudSyncManager().getState();
const v = state.localVersion;
return typeof v === 'number' && v > 0 ? v : undefined;
} catch {
return undefined;
}
}
export type LocalVaultBackupReason = 'app_version_change' | 'before_restore';
export interface LocalVaultBackupPreview {
id: string;
createdAt: number;
reason: LocalVaultBackupReason;
/** Sync-data version at the time the snapshot was taken (the integer
* that the CloudSyncManager increments on each successful cloud sync).
* Undefined when the user had never synced yet, or for legacy backups
* persisted before this field was added. */
syncDataVersion?: number;
/** App version transition fields, only for `app_version_change` records.
* Kept for backward compatibility with already-persisted backups. */
sourceAppVersion?: string;
targetAppVersion?: string;
fingerprint: string;
@@ -94,6 +117,7 @@ export async function createLocalVaultBackup(
payload: SyncPayload,
options: {
reason: LocalVaultBackupReason;
syncDataVersion?: number;
sourceAppVersion?: string;
targetAppVersion?: string;
maxCount?: number;
@@ -118,6 +142,10 @@ export async function createLocalVaultBackup(
const result = await bridge.createVaultBackup({
payload,
reason: options.reason,
// Default to the live cloud-sync version so every new backup carries
// it even when the caller didn't pass one explicitly. Bridge sanitizer
// drops invalid values (non-positive / non-finite), so this is safe.
syncDataVersion: options.syncDataVersion ?? captureCurrentSyncDataVersion(),
sourceAppVersion: options.sourceAppVersion,
targetAppVersion: options.targetAppVersion,
maxCount: options.maxCount ?? getLocalVaultBackupMaxCount(),

View File

@@ -247,19 +247,23 @@ export const useAutoSync = (config: AutoSyncConfig) => {
throw new Error(t('sync.credentialsUnavailable'));
}
// Prevent pushing an empty vault to cloud. This is almost always
// Refuse to push an empty vault to cloud. This is almost always
// a sign that the local state was lost (update, import failure,
// storage corruption) rather than a deliberate "delete everything".
// We only block auto-sync — manual trigger from Settings can still
// push if the user explicitly wants to.
// Both auto and manual triggers are blocked; the user can still
// use Force Push from the SyncBlocked banner if they genuinely
// want to wipe the cloud.
//
// This pairs with the inspect-failure "fail open" behavior in
// checkRemoteVersion below: if inspect transiently errors we still
// let auto-sync run, trusting this guard to refuse if local is
// truly empty rather than letting an empty state clobber remote.
if (!hasMeaningfulSyncData(payload) && trigger === 'auto') {
console.warn('[AutoSync] Blocked: refusing to auto-sync an empty vault to cloud');
return;
if (!hasMeaningfulSyncData(payload)) {
if (trigger === 'auto') {
console.warn('[AutoSync] Blocked: refusing to auto-sync an empty vault to cloud');
return;
}
throw new Error(t('sync.autoSync.emptyVaultManual'));
}
const results = await sync.syncNow(payload);
@@ -479,7 +483,20 @@ export const useAutoSync = (config: AutoSyncConfig) => {
// that only approximated the correct ordering.
if (mergeResult.payload) {
try {
await manager.syncAllProviders(mergeResult.payload);
const roundTripResults = await manager.syncAllProviders(mergeResult.payload);
const wasShrinkBlocked = Array.from(roundTripResults.values()).some(
(r) => r.shrinkBlocked === true,
);
if (wasShrinkBlocked) {
// The merged payload is already applied locally and is the source of truth
// for THIS device. The blocking only prevents pushing it to cloud, which
// is acceptable here — the next user-edit-triggered sync will re-check
// (and the user can also force-push from the Settings banner if they
// navigate there). Reset syncState so we don't leave the manager wedged
// in BLOCKED with no banner visible.
console.warn('[AutoSync] Post-merge round-trip was shrink-blocked; merged data applied locally, reset syncState to IDLE for next attempt.');
manager.clearShrinkBlockedState();
}
// Suppress the debounced follow-up tick that otherwise fires
// once React commits the applied state, since we've just
// already pushed that exact payload upstream.

View File

@@ -26,7 +26,9 @@ import {
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';
@@ -55,7 +57,7 @@ export interface CloudSyncHook {
// Computed
hasAnyConnectedProvider: boolean;
connectedProviderCount: number;
overallSyncStatus: 'none' | 'synced' | 'syncing' | 'error' | 'conflict';
overallSyncStatus: 'none' | 'synced' | 'syncing' | 'error' | 'conflict' | 'blocked';
// Master Key Actions
setupMasterKey: (password: string, confirmPassword: string) => Promise<void>;
@@ -86,8 +88,8 @@ export interface CloudSyncHook {
resetProviderStatus: (provider: CloudProvider) => void;
// Sync Actions
syncNow: (payload: SyncPayload) => Promise<Map<CloudProvider, SyncResult>>;
syncToProvider: (provider: CloudProvider, payload: SyncPayload) => Promise<SyncResult>;
syncNow: (payload: SyncPayload, opts?: { overrideShrink?: boolean }) => Promise<Map<CloudProvider, SyncResult>>;
syncToProvider: (provider: CloudProvider, payload: SyncPayload, opts?: { overrideShrink?: boolean }) => Promise<SyncResult>;
downloadFromProvider: (provider: CloudProvider) => Promise<SyncPayload | null>;
resolveConflict: (resolution: ConflictResolution) => Promise<SyncPayload | null>;
@@ -116,6 +118,12 @@ export interface CloudSyncHook {
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;
}
// ============================================================================
@@ -190,7 +198,8 @@ export const useCloudSync = (): CloudSyncHook => {
).length;
}, [state.providers]);
const overallSyncStatus = useMemo((): 'none' | 'synced' | 'syncing' | 'error' | 'conflict' => {
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';
@@ -422,14 +431,14 @@ export const useCloudSync = (): CloudSyncHook => {
throw new Error('Vault is locked');
}, []);
const syncNowWithUnlock = useCallback(async (payload: SyncPayload) => {
const syncNowWithUnlock = useCallback(async (payload: SyncPayload, opts?: { overrideShrink?: boolean }) => {
await ensureUnlocked();
return await manager.syncAllProviders(payload);
return await manager.syncAllProviders(payload, opts);
}, [ensureUnlocked]);
const syncToProviderWithUnlock = useCallback(async (provider: CloudProvider, payload: SyncPayload) => {
const syncToProviderWithUnlock = useCallback(async (provider: CloudProvider, payload: SyncPayload, opts?: { overrideShrink?: boolean }) => {
await ensureUnlocked();
return await manager.syncToProvider(provider, payload);
return await manager.syncToProvider(provider, payload, opts);
}, [ensureUnlocked]);
const downloadFromProviderWithUnlock = useCallback(async (provider: CloudProvider) => {
@@ -437,6 +446,16 @@ export const useCloudSync = (): CloudSyncHook => {
return await manager.downloadFromProvider(provider);
}, [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);
@@ -505,6 +524,12 @@ export const useCloudSync = (): CloudSyncHook => {
formatLastSync,
getProviderDotColor,
refresh,
// Event subscription
subscribeToEvents,
// Shrink-block state query
getShrinkBlockedFinding,
};
};

View File

@@ -7,7 +7,7 @@
* - Sync status and conflict resolution
*/
import React, { useState, useCallback, useEffect } from 'react';
import React, { useState, useCallback, useEffect, useRef } from 'react';
import {
AlertTriangle,
Check,
@@ -43,7 +43,9 @@ import { useI18n } from '../application/i18n/I18nProvider';
import {
findSyncPayloadEncryptedCredentialPaths,
} from '../domain/credentials';
import { isProviderReadyForSync, type CloudProvider, type ConflictInfo, type SyncPayload, type WebDAVAuthType, type WebDAVConfig, type S3Config } from '../domain/sync';
import { isProviderReadyForSync, type CloudProvider, type ConflictInfo, type SyncPayload, type SyncResult, type WebDAVAuthType, type WebDAVConfig, type S3Config } from '../domain/sync';
import type { ShrinkFinding } from '../domain/syncGuards';
import { SyncBlockedBanner } from './sync/SyncBlockedBanner';
import { cn } from '../lib/utils';
import { Button } from './ui/button';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from './ui/dialog';
@@ -897,20 +899,29 @@ const LocalBackupsPanel: React.FC<LocalBackupsPanelProps> = ({
className="flex items-center gap-3 rounded-lg border border-border/60 p-3"
>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 flex-wrap">
<span className="text-sm font-medium">
{getReasonLabel(backup.reason)}
</span>
<span className="text-xs text-muted-foreground">
{formatTimestamp(backup.createdAt)}
</span>
<div className="text-sm font-medium">
{backup.syncDataVersion
? `v${backup.syncDataVersion}`
: formatTimestamp(backup.createdAt)}
</div>
<div className="text-xs text-muted-foreground mt-1 flex items-center gap-1 flex-wrap">
<span>{getReasonLabel(backup.reason)}</span>
{backup.syncDataVersion && (
<>
<span aria-hidden="true">·</span>
<span>{formatTimestamp(backup.createdAt)}</span>
</>
)}
{backup.sourceAppVersion && backup.targetAppVersion && (
<span className="text-xs text-muted-foreground">
{t('cloudSync.localBackups.versionChange', {
from: backup.sourceAppVersion,
to: backup.targetAppVersion,
})}
</span>
<>
<span aria-hidden="true">·</span>
<span>
{t('cloudSync.localBackups.versionChange', {
from: backup.sourceAppVersion,
to: backup.targetAppVersion,
})}
</span>
</>
)}
</div>
<div className="text-xs text-muted-foreground mt-1">
@@ -974,13 +985,30 @@ const LocalBackupsPanel: React.FC<LocalBackupsPanelProps> = ({
</DialogHeader>
{pendingRestoreBackup && (
<div className="rounded-lg border border-border/60 bg-muted/30 p-3 text-xs space-y-1">
<div className="flex items-center gap-2 flex-wrap">
<span className="font-medium">
{getReasonLabel(pendingRestoreBackup.reason)}
</span>
<span className="text-muted-foreground">
{formatTimestamp(pendingRestoreBackup.createdAt)}
</span>
<div className="font-medium">
{pendingRestoreBackup.syncDataVersion
? `v${pendingRestoreBackup.syncDataVersion}`
: formatTimestamp(pendingRestoreBackup.createdAt)}
</div>
<div className="text-muted-foreground flex items-center gap-1 flex-wrap">
<span>{getReasonLabel(pendingRestoreBackup.reason)}</span>
{pendingRestoreBackup.syncDataVersion && (
<>
<span aria-hidden="true">·</span>
<span>{formatTimestamp(pendingRestoreBackup.createdAt)}</span>
</>
)}
{pendingRestoreBackup.sourceAppVersion && pendingRestoreBackup.targetAppVersion && (
<>
<span aria-hidden="true">·</span>
<span>
{t('cloudSync.localBackups.versionChange', {
from: pendingRestoreBackup.sourceAppVersion,
to: pendingRestoreBackup.targetAppVersion,
})}
</span>
</>
)}
</div>
<div className="text-muted-foreground">
{t('cloudSync.localBackups.counts', {
@@ -1172,6 +1200,17 @@ const SyncDashboard: React.FC<SyncDashboardProps> = ({
// Clear local data dialog
const [showClearLocalDialog, setShowClearLocalDialog] = useState(false);
// Sync-blocked banner (Task 7) + force-push confirmation modal (Task 8)
const [blockedFinding, setBlockedFinding] = useState<Extract<ShrinkFinding, { suspicious: true }> | null>(null);
const [showForcePushConfirm, setShowForcePushConfirm] = useState(false);
// Ref for scrolling to LocalBackupsPanel when the banner's Restore button is clicked
const localBackupsRef = useRef<HTMLDivElement>(null);
// Active tab state — lets the banner's "Restore" button switch to the
// local-backups tab without a separate DOM query.
const [activeTab, setActiveTab] = useState<'providers' | 'status'>('providers');
const ensureSyncablePayload = useCallback(
(payload: SyncPayload): boolean => {
const encryptedCredentialPaths = findSyncPayloadEncryptedCredentialPaths(payload);
@@ -1190,6 +1229,35 @@ const SyncDashboard: React.FC<SyncDashboardProps> = ({
}
}, [sync.currentConflict]);
// Subscribe to sync events to show/clear the blocked-shrink banner.
// Destructure the stable useCallback reference so the effect runs once on
// mount rather than re-subscribing on every render when `sync` object ref changes.
const { subscribeToEvents, getShrinkBlockedFinding } = sync;
// Hydrate from current manager state in case a shrink-block happened
// before this component mounted (e.g., auto-sync ran while the user
// was on a different tab). Without this, the banner only shows
// blocks that occur after Settings is open.
useEffect(() => {
const existing = getShrinkBlockedFinding();
if (existing) {
setBlockedFinding(existing);
}
}, [getShrinkBlockedFinding]);
useEffect(() => {
const unsub = subscribeToEvents((event) => {
if (event.type === 'SYNC_BLOCKED_SHRINK') {
if (event.finding.suspicious) {
setBlockedFinding(event.finding);
}
} else if (event.type === 'SYNC_BLOCKED_CLEARED') {
setBlockedFinding(null);
}
});
return unsub;
}, [subscribeToEvents]);
// If we have a master key but we're still locked (e.g. older installs),
// prompt once and persist the password via safeStorage.
useEffect(() => {
@@ -1441,9 +1509,30 @@ const SyncDashboard: React.FC<SyncDashboardProps> = ({
// window's push, not ours.
const localPayload = onBuildPayload();
if (!ensureSyncablePayload(localPayload)) return;
let results: Map<CloudProvider, SyncResult> | null = null;
await withRestoreBarrier(async () => {
await sync.syncNow(localPayload);
results = await sync.syncNow(localPayload, { overrideShrink: true });
});
if (results) {
// Apply any merged payload BEFORE closing the modal so local state
// reflects what's now on cloud (in case remote changed during the merge).
for (const result of (results as Map<CloudProvider, SyncResult>).values()) {
if (result.mergedPayload) {
await Promise.resolve(onApplyPayload(result.mergedPayload));
break;
}
}
const allOk = Array.from((results as Map<CloudProvider, SyncResult>).values()).every((r) => r.success);
if (!allOk) {
const firstError = Array.from((results as Map<CloudProvider, SyncResult>).values())
.find((r) => !r.success)?.error
?? t('common.unknownError');
toast.error(firstError, t('cloudSync.resolve.failedTitle'));
return; // KEEP the modal open so user can retry / pick USE_REMOTE
}
}
toast.success(t('cloudSync.resolve.uploaded'));
}
setShowConflictModal(false);
@@ -1554,7 +1643,20 @@ const SyncDashboard: React.FC<SyncDashboardProps> = ({
</div>
</div>
<Tabs defaultValue="providers" className="space-y-4">
{blockedFinding && (
<SyncBlockedBanner
finding={blockedFinding}
onRestore={() => {
setActiveTab('status');
requestAnimationFrame(() => {
localBackupsRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' });
});
}}
onForcePush={() => setShowForcePushConfirm(true)}
/>
)}
<Tabs value={activeTab} onValueChange={(v) => setActiveTab(v as 'providers' | 'status')} className="space-y-4">
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="providers">{t('cloudSync.providers.title')}</TabsTrigger>
<TabsTrigger value="status">{t('cloudSync.status.title')}</TabsTrigger>
@@ -1739,9 +1841,11 @@ const SyncDashboard: React.FC<SyncDashboardProps> = ({
</div>
)}
<LocalBackupsPanel
onApplyPayload={onApplyPayload}
/>
<div ref={localBackupsRef}>
<LocalBackupsPanel
onApplyPayload={onApplyPayload}
/>
</div>
{/* Clear Local Data */}
<div className="p-4 rounded-lg border border-destructive/30 bg-destructive/5">
@@ -2361,6 +2465,69 @@ const SyncDashboard: React.FC<SyncDashboardProps> = ({
</DialogFooter>
</DialogContent>
</Dialog>
{/* Force-push confirmation modal (Task 8) */}
{showForcePushConfirm && blockedFinding && (
<Dialog open onOpenChange={(open) => !open && setShowForcePushConfirm(false)}>
<DialogContent>
<DialogHeader>
<DialogTitle>{t('sync.forcePush.title')}</DialogTitle>
</DialogHeader>
<p className="text-sm">
{t('sync.forcePush.body', {
lost: blockedFinding.lost,
entityType: t(`sync.entityType.${blockedFinding.entityType}`),
})}
</p>
<DialogFooter>
<Button variant="outline" onClick={() => setShowForcePushConfirm(false)}>
{t('sync.forcePush.cancel')}
</Button>
<Button
variant="destructive"
onClick={async () => {
const localPayload = onBuildPayload();
if (!ensureSyncablePayload(localPayload)) {
setShowForcePushConfirm(false);
return;
}
setShowForcePushConfirm(false);
try {
const results = await sync.syncNow(localPayload, { overrideShrink: true });
// Apply any merged payload BEFORE clearing the banner. If a merge happened
// during force-push (remote changed), the merged result is what the cloud
// now has — applying it to local state prevents the next sync from
// re-deleting the remote additions we just merged in.
for (const result of results.values()) {
if (result.mergedPayload) {
await Promise.resolve(onApplyPayload(result.mergedPayload));
break; // All providers share the same merged payload
}
}
const allOk = Array.from(results.values()).every((r) => r.success);
if (allOk) {
setBlockedFinding(null);
} else {
// Surface the failure but KEEP the banner so the user can retry or
// restore. Find the first error string to display.
const firstError = Array.from(results.values())
.find((r) => !r.success)
?.error ?? t('sync.toast.errorTitle');
toast.error(firstError, t('sync.toast.errorTitle'));
}
} catch (err) {
toast.error(String(err), t('sync.toast.errorTitle'));
}
}}
>
{t('sync.forcePush.confirm')}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)}
</div>
);
};

View File

@@ -136,7 +136,13 @@ export const SyncStatusButton: React.FC<SyncStatusButtonProps> = ({
// Determine overall status for the button indicator
const getOverallStatus = (): StatusIndicatorProps['status'] => {
if (sync.overallSyncStatus === 'syncing') return 'syncing';
if (sync.overallSyncStatus === 'error' || sync.overallSyncStatus === 'conflict') return 'error';
if (
sync.overallSyncStatus === 'error' ||
sync.overallSyncStatus === 'conflict' ||
sync.overallSyncStatus === 'blocked'
) {
return 'error';
}
if (sync.overallSyncStatus === 'synced') return 'synced';
return 'none';
};

View File

@@ -0,0 +1,51 @@
import React from 'react';
import { AlertTriangle } from 'lucide-react';
import type { ShrinkFinding } from '../../domain/syncGuards';
import { Button } from '../ui/button';
import { useI18n } from '../../application/i18n/I18nProvider';
interface Props {
finding: Extract<ShrinkFinding, { suspicious: true }>;
onRestore: () => void;
onForcePush: () => void;
}
export const SyncBlockedBanner: React.FC<Props> = ({ finding, onRestore, onForcePush }) => {
const { t } = useI18n();
const entityLabel = t(`sync.entityType.${finding.entityType}`);
const percent = finding.baseCount > 0 ? Math.round((finding.lost / finding.baseCount) * 100) : 0;
const reasonText = finding.reason === 'bulk-shrink'
? t('sync.blocked.reason.bulkShrink', {
lost: finding.lost,
baseCount: finding.baseCount,
entityType: entityLabel,
percent,
})
: t('sync.blocked.reason.largeShrink', {
lost: finding.lost,
entityType: entityLabel,
});
return (
<div
role="alert"
className="flex flex-col gap-2 rounded-md border border-amber-500/40 bg-amber-500/10 p-4"
>
<div className="flex items-center gap-2 font-semibold">
<AlertTriangle className="h-4 w-4 text-amber-500" />
<span>{t('sync.blocked.title')}</span>
</div>
<p className="text-sm">{reasonText}</p>
<p className="text-xs opacity-70">{t('sync.blocked.detail')}</p>
<div className="flex gap-2">
<Button variant="default" size="sm" onClick={onRestore}>
{t('sync.blocked.restoreButton')}
</Button>
<Button variant="outline" size="sm" onClick={onForcePush}>
{t('sync.blocked.forcePushButton')}
</Button>
</div>
</div>
);
};

View File

@@ -1,10 +1,12 @@
/**
* Cloud Sync Domain Types & Interfaces
*
*
* Zero-Knowledge Encrypted Multi-Cloud Sync System
* Supports: GitHub Gist, Google Drive, Microsoft OneDrive, WebDAV, S3 Compatible
*/
import type { ShrinkFinding } from './syncGuards';
// ============================================================================
// Security State Machine
// ============================================================================
@@ -22,10 +24,11 @@ export type SecurityState =
* Sync Operation State Machine
* Tracks the current sync operation status
*/
export type SyncState =
export type SyncState =
| 'IDLE' // Waiting for sync trigger
| 'SYNCING' // Active sync operation in progress
| 'CONFLICT' // Version conflict detected - needs resolution
| 'BLOCKED' // Outgoing payload would delete too much — user must choose restore or force-push
| 'ERROR'; // Operation failed - needs attention
/**
@@ -284,6 +287,10 @@ export interface SyncResult {
conflictDetected?: boolean;
/** Present when action === 'merge'; caller should apply this to update local state */
mergedPayload?: import('./sync').SyncPayload;
/** True when a shrink-detection guard blocked the upload */
shrinkBlocked?: boolean;
/** The finding that triggered the shrink block or force-push */
finding?: ShrinkFinding;
}
/**
@@ -351,10 +358,13 @@ export type SyncEvent =
| { type: 'SYNC_COMPLETED'; provider: CloudProvider; result: SyncResult }
| { type: 'SYNC_ERROR'; provider: CloudProvider; error: string }
| { type: 'CONFLICT_DETECTED'; conflict: ConflictInfo }
| { type: 'SYNC_BLOCKED_SHRINK'; provider: CloudProvider; finding: ShrinkFinding }
| { type: 'SYNC_FORCED'; provider: CloudProvider; finding: ShrinkFinding }
| { type: 'CONFLICT_RESOLVED'; resolution: ConflictResolution }
| { type: 'AUTH_REQUIRED'; provider: CloudProvider }
| { type: 'AUTH_COMPLETED'; provider: CloudProvider; account: ProviderAccount }
| { type: 'SECURITY_STATE_CHANGED'; state: SecurityState };
| { type: 'SECURITY_STATE_CHANGED'; state: SecurityState }
| { type: 'SYNC_BLOCKED_CLEARED' };
// ============================================================================
// Storage Keys

139
domain/syncGuards.test.ts Normal file
View File

@@ -0,0 +1,139 @@
import test from "node:test";
import assert from "node:assert/strict";
import { detectSuspiciousShrink } from "./syncGuards.ts";
import type { SyncPayload } from "./sync.ts";
function payload(overrides: Partial<SyncPayload> = {}): SyncPayload {
return {
hosts: [],
keys: [],
identities: [],
snippets: [],
customGroups: [],
snippetPackages: [],
knownHosts: [],
portForwardingRules: [],
groupConfigs: [],
settings: undefined,
syncedAt: 0,
...overrides,
};
}
function hosts(n: number): SyncPayload["hosts"] {
return Array.from({ length: n }, (_, i) => ({
id: `h${i}`,
label: `h${i}`,
hostname: `h${i}.example`,
port: 22,
username: "root",
protocol: "ssh",
})) as SyncPayload["hosts"];
}
test("null base → not suspicious (first sync / null after re-auth)", () => {
const result = detectSuspiciousShrink(payload({ hosts: hosts(1) }), null);
assert.deepEqual(result, { suspicious: false });
});
test("no shrink — same counts → not suspicious", () => {
const base = payload({ hosts: hosts(5) });
const out = payload({ hosts: hosts(5) });
assert.deepEqual(detectSuspiciousShrink(out, base), { suspicious: false });
});
test("growth only → not suspicious", () => {
const base = payload({ hosts: hosts(5) });
const out = payload({ hosts: hosts(10) });
assert.deepEqual(detectSuspiciousShrink(out, base), { suspicious: false });
});
test("shrink under both thresholds → not suspicious (delete 2 of 4)", () => {
const base = payload({ hosts: hosts(4) });
const out = payload({ hosts: hosts(2) });
assert.deepEqual(detectSuspiciousShrink(out, base), { suspicious: false });
});
test("bulk-shrink 50% AND absolute 3 — exactly at threshold → suspicious", () => {
const base = payload({ hosts: hosts(6) });
const out = payload({ hosts: hosts(3) });
assert.deepEqual(detectSuspiciousShrink(out, base), {
suspicious: true,
reason: "bulk-shrink",
entityType: "hosts",
baseCount: 6,
outgoingCount: 3,
lost: 3,
});
});
test("bulk-shrink 50% but absolute 2 → not suspicious (absolute gate)", () => {
const base = payload({ hosts: hosts(4) });
const out = payload({ hosts: hosts(2) });
assert.deepEqual(detectSuspiciousShrink(out, base), { suspicious: false });
});
test("bulk-shrink 40% absolute 4 → not suspicious (ratio gate)", () => {
const base = payload({ hosts: hosts(10) });
const out = payload({ hosts: hosts(6) });
assert.deepEqual(detectSuspiciousShrink(out, base), { suspicious: false });
});
test("large-shrink absolute 10 regardless of ratio → suspicious", () => {
const base = payload({ hosts: hosts(100) });
const out = payload({ hosts: hosts(90) });
assert.deepEqual(detectSuspiciousShrink(out, base), {
suspicious: true,
reason: "large-shrink",
entityType: "hosts",
baseCount: 100,
outgoingCount: 90,
lost: 10,
});
});
test("dual-trigger (large-shrink AND bulk-shrink both satisfied) → reason is 'large-shrink'", () => {
// base=20, lost=10: satisfies large-shrink (>=10) AND bulk-shrink (50%, >=3)
const base = payload({ hosts: hosts(20) });
const out = payload({ hosts: hosts(10) });
const result = detectSuspiciousShrink(out, base);
assert.equal(result.suspicious, true);
if (result.suspicious) assert.equal(result.reason, "large-shrink");
});
test("multiple entity types shrinking — returns first in declaration order (hosts before keys)", () => {
const base = payload({ hosts: hosts(6), keys: Array.from({ length: 6 }, (_, i) => ({ id: `k${i}`, label: `k${i}`, privateKey: "x" })) as SyncPayload["keys"] });
const out = payload({ hosts: hosts(3), keys: Array.from({ length: 3 }, (_, i) => ({ id: `k${i}`, label: `k${i}`, privateKey: "x" })) as SyncPayload["keys"] });
const result = detectSuspiciousShrink(out, base);
assert.equal(result.suspicious, true);
if (result.suspicious) assert.equal(result.entityType, "hosts");
});
test("only non-hosts entity shrinks → reports that entity", () => {
const snippets = (n: number) => Array.from({ length: n }, (_, i) => ({ id: `s${i}`, label: `s${i}`, command: "" })) as SyncPayload["snippets"];
const base = payload({ snippets: snippets(10) });
const out = payload({ snippets: snippets(0) });
const result = detectSuspiciousShrink(out, base);
assert.equal(result.suspicious, true);
if (result.suspicious) {
assert.equal(result.entityType, "snippets");
assert.equal(result.reason, "large-shrink");
}
});
test("knownHosts shrink triggers (security-sensitive)", () => {
const kh = (n: number) => Array.from({ length: n }, (_, i) => ({ id: `kh${i}`, hostname: `h${i}`, port: 22, keyType: "rsa", fingerprint: "x" })) as unknown as SyncPayload["knownHosts"];
const base = payload({ knownHosts: kh(12) });
const out = payload({ knownHosts: kh(2) });
const result = detectSuspiciousShrink(out, base);
assert.equal(result.suspicious, true);
if (result.suspicious) assert.equal(result.entityType, "knownHosts");
});
test("empty base (all zeros) — no shrink possible, returns not suspicious", () => {
const base = payload();
const out = payload({ hosts: hosts(5) });
// All base counts are 0; no shrink possible
assert.deepEqual(detectSuspiciousShrink(out, base), { suspicious: false });
});

85
domain/syncGuards.ts Normal file
View File

@@ -0,0 +1,85 @@
import type { SyncPayload } from './sync';
export type ShrinkFinding =
| { suspicious: false }
| {
suspicious: true;
reason: 'bulk-shrink' | 'large-shrink';
entityType:
| 'hosts'
| 'keys'
| 'identities'
| 'snippets'
| 'customGroups'
| 'snippetPackages'
| 'knownHosts'
| 'portForwardingRules'
| 'groupConfigs';
baseCount: number;
outgoingCount: number;
lost: number;
};
// Keep in sync with all array-typed fields of SyncPayload. When a new
// array entity type is added there, add it here too — there is no
// compile-time check enforcing this.
const CHECKED_ENTITIES = [
'hosts',
'keys',
'identities',
'snippets',
'customGroups',
'snippetPackages',
'knownHosts',
'portForwardingRules',
'groupConfigs',
] as const;
type CheckedEntityType = typeof CHECKED_ENTITIES[number];
const BULK_SHRINK_RATIO = 0.5;
const BULK_SHRINK_MIN_ABSOLUTE = 3;
const LARGE_SHRINK_ABSOLUTE = 10;
function countOf(p: SyncPayload, key: CheckedEntityType): number {
const v = p[key];
return Array.isArray(v) ? v.length : 0;
}
export function detectSuspiciousShrink(
outgoing: SyncPayload,
base: SyncPayload | null,
): ShrinkFinding {
if (!base) return { suspicious: false };
for (const entityType of CHECKED_ENTITIES) {
const baseCount = countOf(base, entityType);
const outgoingCount = countOf(outgoing, entityType);
const lost = baseCount - outgoingCount;
if (lost <= 0) continue;
if (lost >= LARGE_SHRINK_ABSOLUTE) {
return {
suspicious: true,
reason: 'large-shrink',
entityType,
baseCount,
outgoingCount,
lost,
};
}
if (baseCount > 0 && lost / baseCount >= BULK_SHRINK_RATIO && lost >= BULK_SHRINK_MIN_ABSOLUTE) {
return {
suspicious: true,
reason: 'bulk-shrink',
entityType,
baseCount,
outgoingCount,
lost,
};
}
}
return { suspicious: false };
}

View File

@@ -97,6 +97,7 @@ function toBackupSummary(record) {
id: record.id,
createdAt: record.createdAt,
reason: record.reason,
syncDataVersion: record.syncDataVersion,
sourceAppVersion: record.sourceAppVersion,
targetAppVersion: record.targetAppVersion,
preview: record.preview,
@@ -131,6 +132,15 @@ function sanitizeOptionalVersionString(value) {
return trimmed;
}
// Sync data version is the integer that the CloudSyncManager increments
// on each successful cloud sync. Reject anything non-finite, non-positive,
// or non-integer so the persisted record only carries meaningful values.
function sanitizeOptionalSyncDataVersion(value) {
if (typeof value !== "number" || !Number.isFinite(value)) return undefined;
if (value < 1) return undefined;
return Math.floor(value);
}
// UTF-8 byte length of a payload's JSON serialization. Earlier revisions
// returned `JSON.stringify(payload).length` (UTF-16 code units), which
// under-counted by ~3x for non-ASCII vaults — a deck full of CJK snippet
@@ -415,6 +425,7 @@ function createVaultBackupService({ app, safeStorage, shell }) {
id,
createdAt,
reason: sanitizeReason(options.reason),
syncDataVersion: sanitizeOptionalSyncDataVersion(options.syncDataVersion),
sourceAppVersion: sanitizeOptionalVersionString(options.sourceAppVersion),
targetAppVersion: sanitizeOptionalVersionString(options.targetAppVersion),
fingerprint,

View File

@@ -417,6 +417,70 @@ test("createBackup accepts a legitimate SemVer-ish version string", async () =>
}
});
test("createBackup persists syncDataVersion when given a positive integer", async () => {
const rootDir = createTempRoot();
const service = createService(rootDir);
try {
const result = await service.createBackup({
payload: samplePayload(),
reason: "before_restore",
syncDataVersion: 5,
});
assert.equal(result.created, true);
assert.equal(result.backup.syncDataVersion, 5);
// Round-trip via list
const listed = await service.listBackups();
assert.equal(listed[0].syncDataVersion, 5);
} finally {
fs.rmSync(rootDir, { recursive: true, force: true });
}
});
test("createBackup drops invalid syncDataVersion values (zero, negative, non-finite, non-numeric)", async () => {
const rootDir = createTempRoot();
const service = createService(rootDir);
try {
const cases = [0, -1, NaN, Infinity, "5", null, undefined];
let idx = 0;
for (const syncDataVersion of cases) {
// Vary an actual content-bearing field to avoid fingerprint dedupe
// (top-level syncedAt is normalized away in the fingerprint).
const payload = samplePayload({
hosts: [{ ...samplePayload().hosts[0], id: `h-case-${idx}` }],
});
const result = await service.createBackup({
payload,
reason: "before_restore",
syncDataVersion,
});
assert.equal(result.created, true, `iteration ${idx}: created should be true`);
assert.equal(result.backup.syncDataVersion, undefined, `value ${String(syncDataVersion)} should be dropped`);
idx += 1;
}
} finally {
fs.rmSync(rootDir, { recursive: true, force: true });
}
});
test("createBackup floors a fractional syncDataVersion", async () => {
const rootDir = createTempRoot();
const service = createService(rootDir);
try {
const result = await service.createBackup({
payload: samplePayload(),
reason: "before_restore",
syncDataVersion: 7.9,
});
assert.equal(result.backup.syncDataVersion, 7);
} finally {
fs.rmSync(rootDir, { recursive: true, force: true });
}
});
test("createBackup rejects an array payload (not an object)", async () => {
const rootDir = createTempRoot();
const service = createService(rootDir);

View File

@@ -45,6 +45,7 @@ import {
encryptProviderSecrets,
} from '../persistence/secureFieldAdapter';
import { mergeSyncPayloads } from '../../domain/syncMerge';
import { detectSuspiciousShrink, type ShrinkFinding } from '../../domain/syncGuards';
// Extracted into a plain ESM module so the signature logic is covered by
// the node --test harness (see syncSignature.test.mjs). The previous
// inline implementation only hashed a handful of meta fields and was
@@ -77,6 +78,12 @@ export interface SyncManagerState {
autoSyncEnabled: boolean;
autoSyncInterval: number;
syncHistory: SyncHistoryEntry[];
/** Last shrink finding that put us into BLOCKED state, retained until
* a sync actually succeeds (SYNC_COMPLETED with result.success) or
* `clearShrinkBlockedState()` is called. Renderer hydrates the banner
* from this on mount so a block that happened off-screen is still
* visible to the user. */
lastShrinkFinding?: Extract<ShrinkFinding, { suspicious: true }>;
}
export type SyncEventCallback = (event: SyncEvent) => void;
@@ -752,6 +759,12 @@ export class CloudSyncManager {
const ghAdapter = adapter as GitHubAdapter;
try {
// Snapshot the prior account BEFORE we overwrite providers[provider].
// Used as a fallback for the same-account comparison when the persisted
// accountId key is absent (e.g., first re-auth after upgrading to this
// version, where the key didn't exist yet).
const previousAccount = this.state.providers.github?.account;
const tokens = await ghAdapter.completeAuth(deviceCode, interval, expiresAt, onPending);
++this.providerDecryptSeq.github;
@@ -769,9 +782,20 @@ export class CloudSyncManager {
}
await this.saveProviderConnection('github', this.state.providers.github);
// Clear merge base when (re)authenticating to a potentially different account
this.removeFromStorage(this.syncBaseKey('github'));
this.clearSyncAnchor('github');
// Only clear the merge base if the authenticated account identity differs
// from the previously-stored one. See notes in completePKCEAuth.
const newId = ghAdapter.accountInfo?.id ?? null;
const previousId = this.loadProviderAccountId('github') ?? previousAccount?.id ?? null;
const sameAccount = newId !== null && previousId !== null && newId === previousId;
if (!sameAccount) {
this.removeFromStorage(this.syncBaseKey('github'));
this.clearSyncAnchor('github');
}
if (newId) {
this.saveProviderAccountId('github', newId);
}
this.emit({
type: 'AUTH_COMPLETED',
provider: 'github',
@@ -797,6 +821,12 @@ export class CloudSyncManager {
}
try {
// Snapshot the prior account BEFORE we overwrite providers[provider].
// Used as a fallback for the same-account comparison when the persisted
// accountId key is absent (e.g., first re-auth after upgrading to this
// version, where the key didn't exist yet).
const previousAccount = this.state.providers[provider]?.account;
let tokens: OAuthTokens;
let account;
@@ -825,9 +855,22 @@ export class CloudSyncManager {
}
await this.saveProviderConnection(provider, this.state.providers[provider]);
// Clear merge base when (re)authenticating to a potentially different account
this.removeFromStorage(this.syncBaseKey(provider));
this.clearSyncAnchor(provider);
// Only clear the merge base if the authenticated account identity differs
// from the previously-stored one. Same-account re-auth preserves the base
// so the next sync computes correct local-deletions instead of treating
// it as "first sync" and resurrecting zombie entries via null-base union.
const newId = account?.id ?? null;
const previousId = this.loadProviderAccountId(provider) ?? previousAccount?.id ?? null;
const sameAccount = newId !== null && previousId !== null && newId === previousId;
if (!sameAccount) {
this.removeFromStorage(this.syncBaseKey(provider));
this.clearSyncAnchor(provider);
}
if (newId) {
this.saveProviderAccountId(provider, newId);
}
this.emit({
type: 'AUTH_COMPLETED',
provider,
@@ -912,6 +955,13 @@ export class CloudSyncManager {
// account/resource doesn't reuse an unrelated snapshot
this.removeFromStorage(this.syncBaseKey(provider));
this.clearSyncAnchor(provider);
this.removeFromStorage(this.providerAccountIdKey(provider));
// Reset BLOCKED state if it was present — disconnect implicitly resolves
// any pending shrink-block warning since there's no provider to push to.
this.exitBlockedState();
if (this.state.syncState === 'BLOCKED') {
this.state.syncState = 'IDLE';
}
this.notifyStateChange(); // Ensure UI updates immediately after disconnect
}
@@ -1227,7 +1277,8 @@ export class CloudSyncManager {
*/
async syncToProvider(
provider: CloudProvider,
payload: SyncPayload
payload: SyncPayload,
opts: { overrideShrink?: boolean } = {},
): Promise<SyncResult> {
if (this.state.securityState !== 'UNLOCKED') {
return {
@@ -1247,6 +1298,8 @@ export class CloudSyncManager {
};
}
const overrideShrinkRequested = opts.overrideShrink === true;
let adapter: CloudAdapter;
try {
adapter = await this.getConnectedAdapter(provider);
@@ -1288,6 +1341,30 @@ export class CloudSyncManager {
console.info('[CloudSyncManager] Three-way merge completed', mergeResult.summary);
// Shrink guard: refuse to push a merged payload that silently deletes
// entities we still have in base. The merge itself is correct if local
// state is trustworthy — but a degraded local (keychain failure,
// partial load) can make merge produce a smaller-than-expected result.
const mergedShrink = detectSuspiciousShrink(mergeResult.payload, base);
const shouldBlockMerged = mergedShrink.suspicious && !overrideShrinkRequested;
const shouldForceMerged = mergedShrink.suspicious && overrideShrinkRequested;
if (shouldBlockMerged) {
this.state.syncState = 'BLOCKED';
this.state.lastShrinkFinding = mergedShrink;
this.emit({ type: 'SYNC_BLOCKED_SHRINK', provider, finding: mergedShrink });
this.updateProviderStatus(provider, 'error', 'Sync blocked: would delete too much');
return {
success: false,
provider,
action: 'none',
shrinkBlocked: true,
finding: mergedShrink,
};
}
if (shouldForceMerged) {
this.emit({ type: 'SYNC_FORCED', provider, finding: mergedShrink });
}
// Encrypt and upload merged payload
const mergedSyncedFile = await EncryptionService.encryptPayload(
mergeResult.payload,
@@ -1309,6 +1386,7 @@ export class CloudSyncManager {
// Base was persisted inside uploadToProvider before the
// anchor advanced, so a crash between them cannot leave a
// stale base pointing at pre-merge state.
this.exitBlockedState();
this.state.syncState = 'IDLE';
this.addSyncHistoryEntry({
@@ -1361,6 +1439,29 @@ export class CloudSyncManager {
}
}
// Shrink guard (no-conflict path): same rationale as the merge branch —
// refuse a payload that drops entities versus the stored base.
const directBase = await this.loadSyncBase(provider);
const directShrink = detectSuspiciousShrink(payload, directBase);
const shouldBlockDirect = directShrink.suspicious && !overrideShrinkRequested;
const shouldForceDirect = directShrink.suspicious && overrideShrinkRequested;
if (shouldBlockDirect) {
this.state.syncState = 'BLOCKED';
this.state.lastShrinkFinding = directShrink;
this.emit({ type: 'SYNC_BLOCKED_SHRINK', provider, finding: directShrink });
this.updateProviderStatus(provider, 'error', 'Sync blocked: would delete too much');
return {
success: false,
provider,
action: 'none',
shrinkBlocked: true,
finding: directShrink,
};
}
if (shouldForceDirect) {
this.emit({ type: 'SYNC_FORCED', provider, finding: directShrink });
}
// 2. Encrypt
const syncedFile = await EncryptionService.encryptPayload(
payload,
@@ -1377,7 +1478,9 @@ export class CloudSyncManager {
const result = await this.uploadToProvider(provider, adapter, syncedFile, payload);
if (result.success) {
this.exitBlockedState();
this.state.syncState = 'IDLE';
this.state.lastShrinkFinding = undefined;
} else {
this.state.syncState = 'ERROR';
if (result.error) {
@@ -1550,26 +1653,73 @@ export class CloudSyncManager {
// Download and return remote data
const payload = await this.downloadFromProvider(provider);
this.state.currentConflict = null;
this.exitBlockedState();
this.state.syncState = 'IDLE';
this.notifyStateChange(); // Notify UI of conflict resolution
return payload;
} else {
// USE_LOCAL - just clear conflict, caller will re-sync
this.state.currentConflict = null;
this.exitBlockedState();
this.state.syncState = 'IDLE';
this.notifyStateChange(); // Notify UI of conflict resolution
return null;
}
}
/**
* Side-effect helper: called BEFORE any syncState assignment that transitions
* away from BLOCKED. Clears lastShrinkFinding and emits SYNC_BLOCKED_CLEARED
* so the UI banner (and any other subscriber) gets a single, authoritative
* "block resolved" signal. The guard on syncState === 'BLOCKED' makes it safe
* to call unconditionally at every non-BLOCKED assignment site — it no-ops
* when the state was already non-BLOCKED.
*/
private exitBlockedState(): void {
if (this.state.syncState === 'BLOCKED') {
this.state.lastShrinkFinding = undefined;
this.emit({ type: 'SYNC_BLOCKED_CLEARED' });
}
}
/**
* Reset BLOCKED back to IDLE without going through a successful sync.
* Used by post-merge round-trip to avoid wedging the manager in BLOCKED
* when the merge already produced safe local state and the round-trip
* push is just an optimization.
*/
clearShrinkBlockedState(): void {
if (this.state.syncState === 'BLOCKED') {
this.exitBlockedState();
this.state.syncState = 'IDLE';
this.notifyStateChange();
}
}
/**
* Returns the last shrink finding that triggered BLOCKED state, or
* null if not currently blocked. Used by the renderer to hydrate the
* SyncBlockedBanner when opening Settings after a block happened
* off-screen.
*/
getShrinkBlockedFinding(): Extract<ShrinkFinding, { suspicious: true }> | null {
if (this.state.syncState !== 'BLOCKED') return null;
return this.state.lastShrinkFinding ?? null;
}
/**
* Sync to all connected providers
*/
async syncAllProviders(inputPayload?: SyncPayload): Promise<Map<CloudProvider, SyncResult>> {
async syncAllProviders(
inputPayload?: SyncPayload,
opts: { overrideShrink?: boolean } = {},
): Promise<Map<CloudProvider, SyncResult>> {
const results = new Map<CloudProvider, SyncResult>();
let payload = inputPayload;
let wasMerged = false;
const overrideShrinkRequested = opts.overrideShrink === true;
if (!payload) {
// Caller should provide payload from app state
return results;
@@ -1743,6 +1893,80 @@ export class CloudSyncManager {
}
}
// Shrink guard (multi-provider): check the final outgoing payload against
// each provider's stored base. If ANY provider would suffer a suspicious
// shrink, block ALL uploads — the same payload goes to every provider, so
// any one provider's "would lose too much" is a global block. Override flag
// is one-shot and clears regardless of outcome.
const shrinkSuspectByProvider: Array<{
provider: CloudProvider;
finding: Extract<ShrinkFinding, { suspicious: true }>;
}> = [];
const candidateProviders = checkResults
.filter((r) => !r.error && !r.check?.conflict && r.adapter)
.map((r) => r.provider as CloudProvider);
for (const provider of candidateProviders) {
const providerBase = await this.loadSyncBase(provider);
const finding = detectSuspiciousShrink(payload, providerBase);
if (finding.suspicious) {
shrinkSuspectByProvider.push({ provider, finding });
}
}
const shouldBlockAll = shrinkSuspectByProvider.length > 0 && !overrideShrinkRequested;
const shouldForceAll = shrinkSuspectByProvider.length > 0 && overrideShrinkRequested;
if (shouldBlockAll) {
this.state.syncState = 'BLOCKED';
this.state.lastShrinkFinding = shrinkSuspectByProvider[0].finding;
for (const { provider, finding } of shrinkSuspectByProvider) {
this.emit({ type: 'SYNC_BLOCKED_SHRINK', provider, finding });
this.updateProviderStatus(provider, 'error', 'Sync blocked: would delete too much');
results.set(provider, {
success: false,
provider,
action: 'none',
shrinkBlocked: true,
finding,
});
}
// Process check errors from the parallel check phase so a provider that
// failed during checkProviderConflict is not silently dropped from results.
checkResults.forEach((r) => {
if (r.error) {
results.set(r.provider as CloudProvider, {
success: false,
provider: r.provider as CloudProvider,
action: 'none',
error: r.error,
});
this.updateProviderStatus(r.provider as CloudProvider, 'error', r.error);
this.emit({ type: 'SYNC_ERROR', provider: r.provider as CloudProvider, error: r.error });
}
});
// Providers in candidateProviders that didn't trip the shrink check still
// share the same payload — mark them as not-uploaded so the caller doesn't
// think a "successful" no-op happened.
const blockedProviders = new Set(shrinkSuspectByProvider.map((e) => e.provider));
for (const provider of candidateProviders) {
if (!results.has(provider) && !blockedProviders.has(provider)) {
results.set(provider, {
success: false,
provider,
action: 'none',
error: 'Sync blocked: another provider would lose too much data',
});
this.updateProviderStatus(provider, 'error', 'Sync blocked due to peer provider');
}
}
return results;
}
if (shouldForceAll) {
for (const { provider, finding } of shrinkSuspectByProvider) {
this.emit({ type: 'SYNC_FORCED', provider, finding });
}
}
// 3. Encrypt Once
const validUploads = checkResults.filter(
(r) => !r.error && !r.check?.conflict && r.adapter
@@ -1819,7 +2043,9 @@ export class CloudSyncManager {
// 5. Final State Update
const hasSuccess = Array.from(results.values()).some((r) => r.success);
if (hasSuccess) {
this.exitBlockedState();
this.state.syncState = 'IDLE';
this.state.lastShrinkFinding = undefined;
// If a merge happened, attach the merged payload to successful results
// so callers can apply remote additions to local state
@@ -1922,6 +2148,18 @@ export class CloudSyncManager {
return `${SYNC_STORAGE_KEYS.SYNC_BASE_PAYLOAD}${suffix}`;
}
private providerAccountIdKey(provider: CloudProvider): string {
return `netcatty.sync.accountId.${provider}`;
}
private loadProviderAccountId(provider: CloudProvider): string | null {
return this.loadFromStorage<string>(this.providerAccountIdKey(provider)) ?? null;
}
private saveProviderAccountId(provider: CloudProvider, id: string): void {
this.saveToStorage(this.providerAccountIdKey(provider), id);
}
async saveSyncBase(payload: SyncPayload, provider?: CloudProvider): Promise<void> {
const key = this.state.unlockedKey?.derivedKey;
if (!key) return;

View File

@@ -30,7 +30,7 @@
"tool:cli": "node electron/cli/netcatty-tool-cli.cjs",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"test": "node --test --import tsx electron/bridges/*.test.cjs application/state/*.test.ts"
"test": "node --test --import tsx electron/bridges/*.test.cjs application/state/*.test.ts domain/*.test.ts"
},
"dependencies": {
"@ai-sdk/anthropic": "^3.0.58",