mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-17 13:01:24 +00:00
* 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>
765 lines
28 KiB
TypeScript
765 lines
28 KiB
TypeScript
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
|
|
|
|
import { EncryptionService } from '../EncryptionService';
|
|
import { createAdapter, type CloudAdapter } from '../adapters';
|
|
import type GitHubAdapter from '../adapters/GitHubAdapter';
|
|
import type GoogleDriveAdapter from '../adapters/GoogleDriveAdapter';
|
|
import type OneDriveAdapter from '../adapters/OneDriveAdapter';
|
|
import { createSyncedFileSignature as createSyncedFileSignatureCore } from '../syncSignature.js';
|
|
import { decideRemoteChanged } from '../syncAnchorDecision.js';
|
|
import type {
|
|
CloudProvider,
|
|
OAuthTokens,
|
|
ProviderAccount,
|
|
ProviderConnection,
|
|
S3Config,
|
|
SyncedFile,
|
|
SyncPayload,
|
|
WebDAVConfig,
|
|
} from '../../../domain/sync';
|
|
import { normalizeDurablePluginSyncCredentialRef } from '../../../domain/sync';
|
|
import { isPluginCloudProviderId } from '../../../domain/cloudProviderIds';
|
|
import type {
|
|
ProviderSyncAnchor,
|
|
StartProviderAuthResult,
|
|
} from '../CloudSyncManager';
|
|
import {
|
|
registerPluginProviderIdImpl,
|
|
unregisterPluginProviderIdImpl,
|
|
} from './stateAndSecurityMethods';
|
|
|
|
const SYNC_REMOTE_ANCHOR_STORAGE_KEY = 'netcatty_sync_remote_anchor_v1';
|
|
|
|
export function clearProviderMergeStateImpl(this: any, provider: CloudProvider): void {
|
|
this.removeFromStorage(this.syncBaseKey(provider));
|
|
this.removeFromStorage(this.convergentProviderBaselineKey(provider));
|
|
this.clearSyncAnchor(provider);
|
|
}
|
|
|
|
export async function startProviderAuthImpl(this: any,
|
|
provider: CloudProvider,
|
|
redirectUri?: string
|
|
): Promise<StartProviderAuthResult> {
|
|
if (provider === 'webdav' || provider === 's3') {
|
|
throw new Error('Provider requires manual configuration');
|
|
}
|
|
const authAttemptId = ++this.providerAuthAttemptSeq[provider];
|
|
this.providerAuthRestoreState[provider] = {
|
|
attemptId: authAttemptId,
|
|
connection: { ...this.state.providers[provider] },
|
|
adapter: this.adapters.get(provider) ?? null,
|
|
};
|
|
const adapter = await createAdapter(provider);
|
|
if (!this.isActiveAuthAttempt(provider, authAttemptId)) {
|
|
throw new Error(`${provider} auth superseded`);
|
|
}
|
|
this.adapters.set(provider, adapter);
|
|
|
|
this.updateProviderStatus(provider, 'connecting');
|
|
try {
|
|
if (provider === 'github') {
|
|
// GitHub uses Device Flow
|
|
const ghAdapter = adapter as GitHubAdapter;
|
|
const deviceFlow = await ghAdapter.startAuth();
|
|
|
|
return {
|
|
type: 'device_code',
|
|
data: { ...deviceFlow, authAttemptId },
|
|
};
|
|
} else {
|
|
// Google and OneDrive use PKCE with redirect
|
|
if (!redirectUri) {
|
|
throw new Error(
|
|
`startProviderAuth('${provider}') requires a redirectUri — ` +
|
|
'call prepareOAuthCallback on the bridge first and pass its redirectUri through.'
|
|
);
|
|
}
|
|
|
|
if (provider === 'google') {
|
|
const gdAdapter = adapter as GoogleDriveAdapter;
|
|
const url = await gdAdapter.startAuth(redirectUri);
|
|
return { type: 'url', data: { url, redirectUri, authAttemptId } };
|
|
} else {
|
|
const odAdapter = adapter as OneDriveAdapter;
|
|
const url = await odAdapter.startAuth(redirectUri);
|
|
return { type: 'url', data: { url, redirectUri, authAttemptId } };
|
|
}
|
|
}
|
|
} catch (error) {
|
|
if (!this.isActiveAuthAttempt(provider, authAttemptId)) {
|
|
throw error;
|
|
}
|
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
console.error(`[CloudSync] ${provider} connect failed`, {
|
|
error: errorMessage,
|
|
});
|
|
this.updateProviderStatus(provider, 'error', errorMessage);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
export async function completeGitHubAuthImpl(this: any,
|
|
deviceCode: string,
|
|
interval: number,
|
|
expiresAt: number,
|
|
onPending?: () => void,
|
|
signal?: AbortSignal,
|
|
authAttemptId?: number
|
|
): Promise<void> {
|
|
if (authAttemptId != null && !this.isActiveAuthAttempt('github', authAttemptId)) {
|
|
throw new Error('github auth superseded');
|
|
}
|
|
const adapter = this.adapters.get('github');
|
|
if (!adapter) {
|
|
throw new Error('GitHub adapter not initialized');
|
|
}
|
|
|
|
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, signal);
|
|
if (authAttemptId != null && !this.isActiveAuthAttempt('github', authAttemptId)) {
|
|
throw new Error('github auth superseded');
|
|
}
|
|
const resourceId = await ghAdapter.initializeSync(signal);
|
|
|
|
if (authAttemptId != null && !this.isActiveAuthAttempt('github', authAttemptId)) {
|
|
throw new Error('github auth superseded');
|
|
}
|
|
|
|
++this.providerDecryptSeq.github;
|
|
this.state.providers.github = {
|
|
...this.state.providers.github,
|
|
status: 'connected',
|
|
tokens,
|
|
account: ghAdapter.accountInfo || undefined,
|
|
};
|
|
|
|
if (resourceId) {
|
|
this.state.providers.github.resourceId = resourceId;
|
|
}
|
|
|
|
await this.saveProviderConnection('github', this.state.providers.github, authAttemptId);
|
|
if (authAttemptId != null && !this.isActiveAuthAttempt('github', authAttemptId)) {
|
|
throw new Error('github auth superseded');
|
|
}
|
|
|
|
// 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) {
|
|
clearProviderMergeStateImpl.call(this, 'github');
|
|
}
|
|
if (newId) {
|
|
this.saveProviderAccountId('github', newId);
|
|
}
|
|
|
|
this.emit({
|
|
type: 'AUTH_COMPLETED',
|
|
provider: 'github',
|
|
account: ghAdapter.accountInfo!,
|
|
});
|
|
this.providerAuthRestoreState.github = null;
|
|
} catch (error) {
|
|
if (authAttemptId != null && !this.isActiveAuthAttempt('github', authAttemptId)) {
|
|
throw error;
|
|
}
|
|
if (error instanceof Error && error.message.includes('auth superseded')) {
|
|
throw error;
|
|
}
|
|
if (error instanceof Error && error.name === 'AbortError') {
|
|
this.resetProviderStatus('github', authAttemptId);
|
|
throw error;
|
|
}
|
|
this.resetProviderStatus('github', authAttemptId);
|
|
this.setProviderError('github', String(error));
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
export async function completePKCEAuthImpl(this: any,
|
|
provider: 'google' | 'onedrive',
|
|
code: string,
|
|
redirectUri: string,
|
|
authAttemptId?: number
|
|
): Promise<void> {
|
|
if (authAttemptId != null && !this.isActiveAuthAttempt(provider, authAttemptId)) {
|
|
throw new Error(`${provider} auth superseded`);
|
|
}
|
|
const adapter = this.adapters.get(provider);
|
|
if (!adapter) {
|
|
throw new Error(`${provider} adapter not initialized`);
|
|
}
|
|
|
|
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;
|
|
|
|
if (provider === 'google') {
|
|
const gdAdapter = adapter as GoogleDriveAdapter;
|
|
tokens = await gdAdapter.completeAuth(code, redirectUri);
|
|
account = gdAdapter.accountInfo;
|
|
} else {
|
|
const odAdapter = adapter as OneDriveAdapter;
|
|
tokens = await odAdapter.completeAuth(code, redirectUri);
|
|
account = odAdapter.accountInfo;
|
|
}
|
|
|
|
if (authAttemptId != null && !this.isActiveAuthAttempt(provider, authAttemptId)) {
|
|
throw new Error(`${provider} auth superseded`);
|
|
}
|
|
|
|
const resourceId = await adapter.initializeSync();
|
|
|
|
if (authAttemptId != null && !this.isActiveAuthAttempt(provider, authAttemptId)) {
|
|
throw new Error(`${provider} auth superseded`);
|
|
}
|
|
|
|
++this.providerDecryptSeq[provider];
|
|
this.state.providers[provider] = {
|
|
...this.state.providers[provider],
|
|
status: 'connected',
|
|
tokens,
|
|
account: account || undefined,
|
|
};
|
|
|
|
if (resourceId) {
|
|
this.state.providers[provider].resourceId = resourceId;
|
|
}
|
|
|
|
await this.saveProviderConnection(provider, this.state.providers[provider], authAttemptId);
|
|
if (authAttemptId != null && !this.isActiveAuthAttempt(provider, authAttemptId)) {
|
|
throw new Error(`${provider} auth superseded`);
|
|
}
|
|
|
|
// 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) {
|
|
clearProviderMergeStateImpl.call(this, provider);
|
|
}
|
|
if (newId) {
|
|
this.saveProviderAccountId(provider, newId);
|
|
}
|
|
|
|
this.emit({
|
|
type: 'AUTH_COMPLETED',
|
|
provider,
|
|
account: account!,
|
|
});
|
|
this.providerAuthRestoreState[provider] = null;
|
|
} catch (error) {
|
|
if (authAttemptId != null && !this.isActiveAuthAttempt(provider, authAttemptId)) {
|
|
throw error;
|
|
}
|
|
if (error instanceof Error && error.message.includes('auth superseded')) {
|
|
throw error;
|
|
}
|
|
this.resetProviderStatus(provider, authAttemptId);
|
|
this.setProviderError(provider, String(error));
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
export async function connectConfigProviderImpl(this: any,
|
|
provider: 'webdav' | 's3',
|
|
config: WebDAVConfig | S3Config
|
|
): Promise<void> {
|
|
const adapter = await createAdapter(provider, undefined, undefined, config);
|
|
this.adapters.set(provider, adapter);
|
|
this.updateProviderStatus(provider, 'connecting');
|
|
|
|
try {
|
|
const resourceId = await adapter.initializeSync();
|
|
const account = adapter.accountInfo || this.buildAccountFromConfig(provider, config);
|
|
|
|
++this.providerDecryptSeq[provider];
|
|
this.state.providers[provider] = {
|
|
provider,
|
|
status: 'connected',
|
|
config,
|
|
account,
|
|
resourceId: resourceId || undefined,
|
|
};
|
|
|
|
await this.saveProviderConnection(provider, this.state.providers[provider]);
|
|
// Clear all trusted merge state when changing endpoint or bucket.
|
|
clearProviderMergeStateImpl.call(this, provider);
|
|
this.emit({
|
|
type: 'AUTH_COMPLETED',
|
|
provider,
|
|
account,
|
|
});
|
|
} catch (error) {
|
|
this.updateProviderStatus(provider, 'error', String(error));
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Connect a namespaced plugin sync Provider. Configuration is opaque plugin-
|
|
* owned JSON; Netcatty still owns encryption and only forwards encrypted objects.
|
|
*/
|
|
export async function connectPluginProviderImpl(
|
|
this: any,
|
|
providerId: string,
|
|
configuration: unknown = {},
|
|
credential?: unknown,
|
|
): Promise<void> {
|
|
if (!isPluginCloudProviderId(providerId)) {
|
|
throw new Error(`Invalid plugin sync provider ID: ${providerId}`);
|
|
}
|
|
// Initialize sequence counters before the first status write so cross-window
|
|
// handlers never see NaN and discard every later update.
|
|
if (this.providerWriteSeq[providerId] == null || Number.isNaN(this.providerWriteSeq[providerId])) {
|
|
this.providerWriteSeq[providerId] = 0;
|
|
}
|
|
if (this.providerDecryptSeq[providerId] == null || Number.isNaN(this.providerDecryptSeq[providerId])) {
|
|
this.providerDecryptSeq[providerId] = 0;
|
|
}
|
|
if (this.providerDecrypted[providerId] == null) this.providerDecrypted[providerId] = true;
|
|
if (this.providerAuthAttemptSeq[providerId] == null || Number.isNaN(this.providerAuthAttemptSeq[providerId])) {
|
|
this.providerAuthAttemptSeq[providerId] = 0;
|
|
}
|
|
this.updateProviderStatus(providerId, 'connecting');
|
|
try {
|
|
const createPluginStorage = async (id: string) => {
|
|
if (typeof this.createPluginStorage === 'function') {
|
|
return this.createPluginStorage(id, {
|
|
provider: id,
|
|
status: 'connecting',
|
|
config: configuration as ProviderConnection['config'],
|
|
});
|
|
}
|
|
const { createPluginSyncIpcHost, isPluginSyncIpcAvailable } = await import(
|
|
'../adapters/pluginSyncIpcHost'
|
|
);
|
|
const { createPluginSyncObjectStorage } = await import('../adapters/pluginSyncObjectStorage');
|
|
if (!isPluginSyncIpcAvailable()) {
|
|
throw new Error(`Plugin sync provider ${id} is unavailable (plugin host not enabled)`);
|
|
}
|
|
return createPluginSyncObjectStorage({
|
|
providerId: id,
|
|
host: createPluginSyncIpcHost(),
|
|
configuration,
|
|
credential: credential as import('../adapters/pluginSyncObjectStorage').PluginSyncCredentialRef | undefined,
|
|
});
|
|
};
|
|
const adapter = await createAdapter(
|
|
providerId,
|
|
undefined,
|
|
undefined,
|
|
undefined,
|
|
{ createPluginStorage },
|
|
);
|
|
// Only cache after initializeSync succeeds so a rejected reconnect cannot
|
|
// leave a half-authenticated adapter pinned for later auto-sync.
|
|
let resourceId: string | null;
|
|
try {
|
|
resourceId = await adapter.initializeSync();
|
|
} catch (error) {
|
|
try { adapter.signOut(); } catch { /* ignore */ }
|
|
this.adapters.delete(providerId);
|
|
throw error;
|
|
}
|
|
this.adapters.set(providerId, adapter);
|
|
const account = adapter.accountInfo ?? { id: providerId };
|
|
if (this.providerDecryptSeq[providerId] == null) this.providerDecryptSeq[providerId] = 0;
|
|
if (this.providerWriteSeq[providerId] == null) this.providerWriteSeq[providerId] = 0;
|
|
if (this.providerDecrypted[providerId] == null) this.providerDecrypted[providerId] = true;
|
|
++this.providerDecryptSeq[providerId];
|
|
// Capture pre-connect identity before overwriting state.
|
|
const previous = this.state.providers[providerId];
|
|
const previousAccountId = previous?.account?.id ?? null;
|
|
const previousResource = previous?.resourceId ?? null;
|
|
const configFingerprint = (value: unknown): string => {
|
|
const normalize = (input: unknown): unknown => {
|
|
if (Array.isArray(input)) return input.map(normalize);
|
|
if (input && typeof input === 'object') {
|
|
return Object.fromEntries(
|
|
Object.keys(input as Record<string, unknown>)
|
|
.sort()
|
|
.map((key) => [key, normalize((input as Record<string, unknown>)[key])]),
|
|
);
|
|
}
|
|
return input;
|
|
};
|
|
try {
|
|
return JSON.stringify(normalize(value ?? null));
|
|
} catch {
|
|
return String(value);
|
|
}
|
|
};
|
|
const previousConfigFp = configFingerprint(previous?.config ?? null);
|
|
const nextAccountId = account?.id ?? null;
|
|
const nextResource = resourceId || null;
|
|
const nextConfigFp = configFingerprint(configuration ?? null);
|
|
this.state.providers[providerId] = {
|
|
provider: providerId,
|
|
status: 'connected',
|
|
config: configuration as ProviderConnection['config'],
|
|
...((() => {
|
|
const ref = normalizeDurablePluginSyncCredentialRef(credential);
|
|
return ref ? { credential: ref } : {};
|
|
})()),
|
|
account,
|
|
resourceId: resourceId || undefined,
|
|
};
|
|
registerPluginProviderIdImpl.call(this, providerId);
|
|
await this.saveProviderConnection(providerId, this.state.providers[providerId]);
|
|
// Preserve merge base / anchors when reconnecting the same account+resource
|
|
// and configuration; clear when backend identity or config changes.
|
|
const previousCredentialFp = `${previous?.credential?.kind ?? ''}\0${previous?.credential?.id ?? ''}\0${previous?.credential?.key ?? ''}`;
|
|
const nextCredentialFp = `${this.state.providers[providerId].credential?.kind ?? ''}\0${this.state.providers[providerId].credential?.id ?? ''}\0${this.state.providers[providerId].credential?.key ?? ''}`;
|
|
if (
|
|
previousAccountId !== nextAccountId
|
|
|| previousResource !== nextResource
|
|
|| previousConfigFp !== nextConfigFp
|
|
|| previousCredentialFp !== nextCredentialFp
|
|
) {
|
|
clearProviderMergeStateImpl.call(this, providerId);
|
|
}
|
|
this.emit({
|
|
type: 'AUTH_COMPLETED',
|
|
provider: providerId,
|
|
account,
|
|
});
|
|
this.notifyStateChange();
|
|
} catch (error) {
|
|
this.updateProviderStatus(providerId, 'error', String(error));
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
export function resetProviderStatusImpl(this: any,provider: CloudProvider, authAttemptId?: number): void {
|
|
const restoreState = this.providerAuthRestoreState[provider];
|
|
if (
|
|
authAttemptId != null &&
|
|
restoreState &&
|
|
restoreState.attemptId !== authAttemptId
|
|
) {
|
|
return;
|
|
}
|
|
|
|
if (restoreState) {
|
|
this.state.providers[provider] = { ...restoreState.connection };
|
|
if (restoreState.adapter) {
|
|
this.adapters.set(provider, restoreState.adapter);
|
|
} else {
|
|
this.adapters.delete(provider);
|
|
}
|
|
this.notifyStateChange();
|
|
} else if (this.state.providers[provider]?.status === 'connecting') {
|
|
this.updateProviderStatus(provider, 'disconnected');
|
|
return;
|
|
}
|
|
if (!restoreState || authAttemptId == null || restoreState.attemptId === authAttemptId) {
|
|
this.providerAuthRestoreState[provider] = null;
|
|
}
|
|
}
|
|
|
|
export function setProviderErrorImpl(this: any,provider: CloudProvider, error: string): void {
|
|
this.updateProviderStatus(provider, 'error', error);
|
|
}
|
|
|
|
export function clearConnectingStatusImpl(this: any,provider: CloudProvider): void {
|
|
if (this.state.providers[provider]?.status !== 'connecting') {
|
|
return;
|
|
}
|
|
this.updateProviderStatus(provider, 'disconnected');
|
|
}
|
|
|
|
export function clearProviderErrorImpl(this: any,provider: CloudProvider): void {
|
|
const connection = this.state.providers[provider];
|
|
if (!connection?.error && connection?.status !== 'error') {
|
|
return;
|
|
}
|
|
this.state.providers[provider] = {
|
|
...connection,
|
|
status: connection.status === 'error' ? 'disconnected' : connection.status,
|
|
error: undefined,
|
|
};
|
|
this.notifyStateChange();
|
|
}
|
|
|
|
export function cancelProviderAuthAttemptImpl(this: any,provider: CloudProvider, authAttemptId?: number): void {
|
|
if (
|
|
authAttemptId != null &&
|
|
!this.isActiveAuthAttempt(provider, authAttemptId)
|
|
) {
|
|
return;
|
|
}
|
|
this.resetProviderStatus(provider, authAttemptId);
|
|
++this.providerAuthAttemptSeq[provider];
|
|
const restoreState = this.providerAuthRestoreState[provider];
|
|
if (!restoreState || authAttemptId == null || restoreState.attemptId === authAttemptId) {
|
|
this.providerAuthRestoreState[provider] = null;
|
|
}
|
|
}
|
|
|
|
export async function disconnectProviderImpl(this: any,provider: CloudProvider): Promise<void> {
|
|
this.cancelProviderAuthAttempt(provider);
|
|
const adapter = this.adapters.get(provider);
|
|
if (adapter) {
|
|
adapter.signOut();
|
|
this.adapters.delete(provider);
|
|
}
|
|
|
|
++this.providerDecryptSeq[provider];
|
|
this.state.providers[provider] = {
|
|
provider,
|
|
status: 'disconnected',
|
|
};
|
|
|
|
await this.saveProviderConnection(provider, this.state.providers[provider]);
|
|
// Explicit disconnect removes the dynamic provider from the restart registry.
|
|
// Missing plugins with preserved config remain registered and are not coerced away.
|
|
unregisterPluginProviderIdImpl.call(this, provider);
|
|
// Clear all trusted merge state so a later account/resource cannot reuse
|
|
// an unrelated snapshot or convergent baseline.
|
|
clearProviderMergeStateImpl.call(this, provider);
|
|
this.removeFromStorage(this.providerAccountIdKey(provider));
|
|
// Drop OS-backed sync secrets so disconnect does not leave reusable passwords.
|
|
if (isPluginCloudProviderId(provider)) {
|
|
try {
|
|
const { deletePluginSyncSecrets } = await import('../adapters/pluginSyncIpcHost');
|
|
await deletePluginSyncSecrets({ providerId: provider });
|
|
} catch {
|
|
/* best-effort; disconnect still succeeds */
|
|
}
|
|
}
|
|
// 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
|
|
}
|
|
|
|
export function updateProviderStatusImpl(this: any,
|
|
provider: CloudProvider,
|
|
status: ProviderConnection['status'],
|
|
error?: string
|
|
): void {
|
|
// Bump sequence to invalidate any in-flight async decrypt for this provider
|
|
++this.providerDecryptSeq[provider];
|
|
this.state.providers[provider] = {
|
|
...this.state.providers[provider],
|
|
status,
|
|
error,
|
|
};
|
|
this.notifyStateChange(); // Notify UI of status change
|
|
}
|
|
|
|
export function isActiveAuthAttemptImpl(this: any,provider: CloudProvider, authAttemptId: number): boolean {
|
|
return this.providerAuthAttemptSeq[provider] === authAttemptId;
|
|
}
|
|
|
|
export function buildAccountFromConfigImpl(this: any,
|
|
provider: 'webdav' | 's3',
|
|
config: WebDAVConfig | S3Config
|
|
): ProviderAccount {
|
|
if (provider === 'webdav') {
|
|
const endpoint = (config as WebDAVConfig).endpoint;
|
|
return { id: endpoint, name: endpoint };
|
|
}
|
|
const s3 = config as S3Config;
|
|
return { id: `${s3.bucket}@${s3.endpoint}`, name: `${s3.bucket} (${s3.region})` };
|
|
}
|
|
|
|
export function syncAnchorKeyImpl(this: any,provider: CloudProvider): string {
|
|
return `${SYNC_REMOTE_ANCHOR_STORAGE_KEY}_${provider}`;
|
|
}
|
|
|
|
export function createSyncedFileSignatureImpl(this: any,syncedFile: SyncedFile | null): Promise<string | null> {
|
|
return createSyncedFileSignatureCore(syncedFile);
|
|
}
|
|
|
|
export function loadSyncAnchorImpl(this: any,provider: CloudProvider): ProviderSyncAnchor | null {
|
|
return this.loadFromStorage<ProviderSyncAnchor>(this.syncAnchorKey(provider));
|
|
}
|
|
|
|
export async function saveSyncAnchorImpl(this: any,
|
|
provider: CloudProvider,
|
|
syncedFile: SyncedFile | null,
|
|
resourceId?: string | null,
|
|
): Promise<void> {
|
|
this.saveToStorage(this.syncAnchorKey(provider), {
|
|
signature: await this.createSyncedFileSignature(syncedFile),
|
|
version: syncedFile?.meta.version ?? 0,
|
|
updatedAt: syncedFile?.meta.updatedAt ?? 0,
|
|
deviceId: syncedFile?.meta.deviceId,
|
|
resourceId: resourceId ?? this.state.providers[provider].resourceId ?? null,
|
|
observedAt: Date.now(),
|
|
} satisfies ProviderSyncAnchor);
|
|
}
|
|
|
|
export function clearSyncAnchorImpl(this: any,provider?: CloudProvider): void {
|
|
if (provider) {
|
|
this.removeFromStorage(this.syncAnchorKey(provider));
|
|
return;
|
|
}
|
|
const providers = new Set<CloudProvider>([
|
|
'github', 'google', 'onedrive', 'webdav', 's3',
|
|
]);
|
|
for (const id of Object.keys(this.state?.providers ?? {})) {
|
|
providers.add(id as CloudProvider);
|
|
}
|
|
if (typeof this.listRegisteredPluginProviderIds === 'function') {
|
|
for (const id of this.listRegisteredPluginProviderIds()) {
|
|
providers.add(id as CloudProvider);
|
|
}
|
|
}
|
|
for (const p of providers) {
|
|
this.removeFromStorage(this.syncAnchorKey(p));
|
|
}
|
|
}
|
|
|
|
export async function inspectProviderRemoteStateImpl(this: any,
|
|
provider: CloudProvider,
|
|
adapter: CloudAdapter,
|
|
): Promise<{
|
|
remoteChanged: boolean;
|
|
remoteFile: SyncedFile | null;
|
|
error?: string;
|
|
}> {
|
|
try {
|
|
const remoteFile = await adapter.download();
|
|
const currentSignature = await this.createSyncedFileSignature(remoteFile);
|
|
const anchor = this.loadSyncAnchor(provider);
|
|
const currentResourceId = adapter.resourceId || this.state.providers[provider].resourceId || null;
|
|
|
|
const decision = decideRemoteChanged({
|
|
currentSignature,
|
|
currentResourceId,
|
|
anchor,
|
|
hasRemoteFile: Boolean(remoteFile),
|
|
});
|
|
|
|
return {
|
|
remoteChanged: decision.remoteChanged,
|
|
remoteFile,
|
|
};
|
|
} catch (error) {
|
|
// A dead OneDrive refresh token surfaces here during sync preflight,
|
|
// syncAll preflight, and startup inspection. Clear the stale credentials
|
|
// so the provider drops to a reconnect state instead of being retried.
|
|
if (typeof this.handleProviderReauthRequired === 'function') {
|
|
this.handleProviderReauthRequired(provider, error);
|
|
}
|
|
return {
|
|
remoteChanged: false,
|
|
remoteFile: null,
|
|
error: String(error),
|
|
};
|
|
}
|
|
}
|
|
|
|
export async function checkProviderConflictImpl(this: any,
|
|
provider: CloudProvider,
|
|
adapter: CloudAdapter
|
|
): Promise<{
|
|
conflict: boolean;
|
|
remoteFile?: SyncedFile;
|
|
}> {
|
|
const inspection = await this.inspectProviderRemoteState(provider, adapter);
|
|
if (inspection.error) {
|
|
throw new Error(inspection.error);
|
|
}
|
|
return {
|
|
conflict: inspection.remoteChanged && Boolean(inspection.remoteFile),
|
|
remoteFile: inspection.remoteFile ?? undefined,
|
|
};
|
|
}
|
|
|
|
export async function inspectProviderRemoteImpl(this: any,provider: CloudProvider): Promise<{
|
|
remoteChanged: boolean;
|
|
remoteFile: SyncedFile | null;
|
|
payload: SyncPayload | null;
|
|
}> {
|
|
if (this.state.securityState !== 'UNLOCKED' || !this.masterPassword) {
|
|
throw new Error('Vault is locked');
|
|
}
|
|
|
|
const adapter = await this.getConnectedAdapter(provider);
|
|
const inspection = await this.inspectProviderRemoteState(provider, adapter);
|
|
if (inspection.error) {
|
|
throw new Error(inspection.error);
|
|
}
|
|
|
|
if (!inspection.remoteFile) {
|
|
return {
|
|
remoteChanged: inspection.remoteChanged,
|
|
remoteFile: null,
|
|
payload: null,
|
|
};
|
|
}
|
|
|
|
return {
|
|
remoteChanged: inspection.remoteChanged,
|
|
remoteFile: inspection.remoteFile,
|
|
payload: await EncryptionService.decryptPayload(inspection.remoteFile, this.masterPassword),
|
|
};
|
|
}
|
|
|
|
export async function commitRemoteInspectionImpl(this: any,
|
|
provider: CloudProvider,
|
|
remoteFile: SyncedFile,
|
|
payload: SyncPayload,
|
|
opts: { recordDownload?: boolean } = {},
|
|
): Promise<void> {
|
|
const adapter = await this.getConnectedAdapter(provider);
|
|
const resourceId = adapter.resourceId || this.state.providers[provider].resourceId || null;
|
|
if (resourceId && this.state.providers[provider].resourceId !== resourceId) {
|
|
++this.providerDecryptSeq[provider];
|
|
this.state.providers[provider] = {
|
|
...this.state.providers[provider],
|
|
resourceId,
|
|
};
|
|
}
|
|
|
|
this.state.localVersion = remoteFile.meta.version;
|
|
this.state.localUpdatedAt = remoteFile.meta.updatedAt;
|
|
this.state.remoteVersion = remoteFile.meta.version;
|
|
this.state.remoteUpdatedAt = remoteFile.meta.updatedAt;
|
|
this.state.providers[provider].lastSync = Date.now();
|
|
this.state.providers[provider].lastSyncVersion = remoteFile.meta.version;
|
|
|
|
await this.saveSyncBase(payload, provider);
|
|
this.saveSyncConfig();
|
|
await this.saveSyncAnchor(provider, remoteFile, resourceId);
|
|
await this.saveProviderConnection(provider, this.state.providers[provider]);
|
|
if (opts.recordDownload === true) {
|
|
this.addSyncHistoryEntry({
|
|
timestamp: Date.now(),
|
|
provider,
|
|
action: 'download',
|
|
success: true,
|
|
localVersion: remoteFile.meta.version,
|
|
remoteVersion: remoteFile.meta.version,
|
|
deviceName: remoteFile.meta.deviceName,
|
|
});
|
|
}
|
|
this.notifyStateChange();
|
|
}
|