mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-17 13:01:24 +00:00
* Auto-refresh OneDrive sync token and prompt reconnect on dead refresh token OneDrive cloud sync (#1189) broke for users on 1.1.20 and only recovered after disconnecting and re-authorizing. Two gaps caused this: 1. Refreshed tokens were never persisted. When OneDriveAdapter silently refreshed the access token mid-session, the rotated tokens lived only in the adapter's in-memory state — CloudSyncManager never read them back or saved them. Microsoft consumer refresh tokens rotate on every refresh and invalidate the previous one, so the next app launch loaded a stale, rotated-out refresh token. Eventually that stored token was dead and sync failed, forcing a manual reconnect. Fix: OneDriveAdapter now exposes setOnTokensRefreshed(); the manager wires it so every silent refresh writes the rotated tokens back into provider state and encrypted storage (attachTokenRefreshPersistence / persistRefreshedProviderTokens), keeping the stored refresh token current. 2. A genuinely dead refresh token surfaced as a raw, generic error with no guidance. The bridge now detects invalid_grant / interaction_required / consent_required / login_required on refresh and tags the error with a stable marker. OneDriveAdapter normalizes these to OneDriveReauthRequiredError; the marker survives IPC and error re-wrapping so the condition stays detectable, and the UI strips it to show a clean "OneDrive session expired, please reconnect." message. Shared marker + detection/clean helpers live in domain/sync.ts so the bridge, adapter, and UI use one source of truth. Scope is limited to OneDrive; other providers (Gist/iCloud/Google/WebDAV/S3) are untouched. Tests: OneDriveAdapter refresh-persistence + reauth detection, manager token-persistence wiring, and bridge invalid_grant tagging. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * Drop OneDrive to a reconnect state when its refresh token is dead codex review: detecting a dead refresh token was not enough. A provider in `error` state that still holds tokens stays "ready for sync" (isProviderReadyForSync), and syncAllProviders resets such providers back to `connected` and retries — so auto-sync kept hammering the dead refresh token and the user never got a stable reconnect prompt. Now, when a sync/download error indicates OneDrive reauth is required, the manager clears the stale tokens and tears down the cached adapter (handleProviderReauthRequired), leaving the provider in an error state with no credentials. With no tokens, isProviderReadyForSync returns false so auto-sync stops retrying, and the card shows a clean "please reconnect" message with a Connect button. The account is preserved for display; the error message is stripped of the internal marker. Wired into the syncToProvider / uploadToProvider / downloadFromProvider error paths. Added tests for the clear-on-reauth behavior and provider/error scoping. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * Clear OneDrive reauth during inspection paths; include service tests in npm test codex review round 2: P2 — A dead OneDrive refresh token can also surface during startup remote inspection and the syncAllProviders preflight conflict check, both of which run through inspectProviderRemoteState. That path swallowed the error into an {error} tuple without clearing the stale tokens, so the provider stayed retryable. Wired the reauth handler into inspectProviderRemoteState's catch, covering sync preflight, syncAll preflight, and startup inspection in one place. Made the handler idempotent so the operation's own catch can also call it without re-saving. P3 — New tests live under infrastructure/services/, which npm test's globs did not cover (the pre-existing syncAllStorageMethods.test.ts was also uncovered). Added infrastructure/services/*.test.ts and infrastructure/services/*/*.test.ts to the test script. Full suite: 1400 tests, 0 failures. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * test: drop unmatched services test glob from npm test The npm test script listed both infrastructure/services/*.test.ts and the nested infrastructure/services/*/*.test.ts. No .test.ts files live directly under infrastructure/services/ (the OneDrive adapter and cloudSync tests are in adapters/ and cloudSync/ subdirs), so the flat glob never matched. Under a default POSIX shell (sh/bash without nullglob), an unmatched glob is passed through literally, so node --test received the raw pattern. On Node versions without test-runner glob support this aborts with "Could not find '.../infrastructure/services/*.test.ts'" before any test runs, breaking npm test. Remove the redundant flat glob; the nested glob already covers the new OneDrive adapter and cloudSync tests. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
210 lines
7.0 KiB
TypeScript
210 lines
7.0 KiB
TypeScript
import assert from 'node:assert/strict';
|
|
import test from 'node:test';
|
|
|
|
import {
|
|
OneDriveAdapter,
|
|
OneDriveReauthRequiredError,
|
|
isOneDriveReauthRequiredError,
|
|
} from './OneDriveAdapter.ts';
|
|
import {
|
|
ONEDRIVE_REAUTH_REQUIRED_MARKER,
|
|
cleanOneDriveErrorMessage,
|
|
type OAuthTokens,
|
|
} from '../../../domain/sync.ts';
|
|
|
|
type WindowGlobal = typeof globalThis & { window?: unknown };
|
|
|
|
function setBridge(bridge: Record<string, unknown>): () => void {
|
|
const g = globalThis as WindowGlobal;
|
|
const original = g.window;
|
|
// Loosely typed: the real window.netcatty is a large NetcattyBridge; tests
|
|
// only stub the handful of OneDrive methods the adapter actually calls.
|
|
g.window = { netcatty: bridge } as unknown as Window & typeof globalThis;
|
|
return () => {
|
|
g.window = original;
|
|
};
|
|
}
|
|
|
|
const expiredTokens = (): OAuthTokens => ({
|
|
accessToken: 'old-access',
|
|
refreshToken: 'old-refresh',
|
|
// Already expired so any operation forces a refresh.
|
|
expiresAt: Date.now() - 60_000,
|
|
tokenType: 'Bearer',
|
|
});
|
|
|
|
test('isOneDriveReauthRequiredError detects the marker and the error class', () => {
|
|
assert.equal(isOneDriveReauthRequiredError(new OneDriveReauthRequiredError()), true);
|
|
assert.equal(
|
|
isOneDriveReauthRequiredError(new Error(`${ONEDRIVE_REAUTH_REQUIRED_MARKER}: x`)),
|
|
true,
|
|
);
|
|
// Survives re-wrapping the way the sync pipeline re-wraps errors.
|
|
const wrapped = new Error(String(new OneDriveReauthRequiredError('boom')));
|
|
assert.equal(isOneDriveReauthRequiredError(wrapped), true);
|
|
assert.equal(isOneDriveReauthRequiredError(new Error('network down')), false);
|
|
});
|
|
|
|
test('cleanOneDriveErrorMessage strips the marker and wrapping prefixes', () => {
|
|
const wrapped = `Error: OneDriveReauthRequiredError: ${ONEDRIVE_REAUTH_REQUIRED_MARKER}: OneDrive session expired, please reconnect. (AADSTS70000)`;
|
|
assert.equal(
|
|
cleanOneDriveErrorMessage(wrapped),
|
|
'OneDrive session expired, please reconnect. (AADSTS70000)',
|
|
);
|
|
// No marker -> returned unchanged.
|
|
assert.equal(cleanOneDriveErrorMessage('plain network error'), 'plain network error');
|
|
});
|
|
|
|
test('OneDriveReauthRequiredError always carries the marker in its message', () => {
|
|
assert.ok(new OneDriveReauthRequiredError('hi').message.includes(ONEDRIVE_REAUTH_REQUIRED_MARKER));
|
|
// Does not double-prefix when the marker is already present.
|
|
const once = new OneDriveReauthRequiredError(`${ONEDRIVE_REAUTH_REQUIRED_MARKER}: hi`).message;
|
|
assert.equal(once.indexOf(ONEDRIVE_REAUTH_REQUIRED_MARKER), once.lastIndexOf(ONEDRIVE_REAUTH_REQUIRED_MARKER));
|
|
});
|
|
|
|
test('refreshing tokens during an operation fires the persistence callback with rotated tokens', async () => {
|
|
const rotated: OAuthTokens = {
|
|
accessToken: 'fresh-access',
|
|
refreshToken: 'rotated-refresh',
|
|
expiresAt: Date.now() + 3_600_000,
|
|
tokenType: 'Bearer',
|
|
};
|
|
let refreshCalledWith: string | undefined;
|
|
// Returning a non-null synced file avoids the eventual-consistency retry loop
|
|
// (retryOnNotFound) that backs off on a null result and would slow the test.
|
|
const remoteSyncedFile = { meta: { version: 1 }, payload: 'x' };
|
|
const restore = setBridge({
|
|
onedriveRefreshAccessToken: async ({ refreshToken }: { refreshToken: string }) => {
|
|
refreshCalledWith = refreshToken;
|
|
return rotated;
|
|
},
|
|
onedriveDownloadSyncFile: async ({ accessToken }: { accessToken: string }) => {
|
|
// Operation must run with the refreshed access token.
|
|
assert.equal(accessToken, 'fresh-access');
|
|
return { syncedFile: remoteSyncedFile };
|
|
},
|
|
});
|
|
|
|
try {
|
|
const adapter = new OneDriveAdapter(expiredTokens(), 'file-1');
|
|
const persisted: OAuthTokens[] = [];
|
|
adapter.setOnTokensRefreshed((tokens) => persisted.push(tokens));
|
|
|
|
const result = await adapter.download();
|
|
|
|
assert.deepEqual(result, remoteSyncedFile);
|
|
assert.equal(refreshCalledWith, 'old-refresh');
|
|
assert.equal(persisted.length, 1);
|
|
assert.deepEqual(persisted[0], rotated);
|
|
// Adapter also exposes the rotated tokens for the caller to persist.
|
|
assert.deepEqual(adapter.getTokens(), rotated);
|
|
} finally {
|
|
restore();
|
|
}
|
|
});
|
|
|
|
test('a dead refresh token surfaces OneDriveReauthRequiredError and does not fire the callback', async () => {
|
|
const restore = setBridge({
|
|
onedriveRefreshAccessToken: async () => {
|
|
throw new Error(
|
|
`${ONEDRIVE_REAUTH_REQUIRED_MARKER}: OneDrive session expired, please reconnect. (AADSTS70000)`,
|
|
);
|
|
},
|
|
});
|
|
|
|
try {
|
|
const adapter = new OneDriveAdapter(expiredTokens(), 'file-1');
|
|
let callbackFired = false;
|
|
adapter.setOnTokensRefreshed(() => {
|
|
callbackFired = true;
|
|
});
|
|
|
|
await assert.rejects(
|
|
() => adapter.download(),
|
|
(err) => {
|
|
assert.equal(isOneDriveReauthRequiredError(err), true);
|
|
assert.ok(err instanceof OneDriveReauthRequiredError);
|
|
return true;
|
|
},
|
|
);
|
|
assert.equal(callbackFired, false);
|
|
} finally {
|
|
restore();
|
|
}
|
|
});
|
|
|
|
test('setTokens refreshes an expired token and persists the rotated tokens', async () => {
|
|
const rotated: OAuthTokens = {
|
|
accessToken: 'fresh-access',
|
|
refreshToken: 'rotated-refresh',
|
|
expiresAt: Date.now() + 3_600_000,
|
|
tokenType: 'Bearer',
|
|
};
|
|
const restore = setBridge({
|
|
onedriveRefreshAccessToken: async () => rotated,
|
|
onedriveGetUserInfo: async () => ({ id: 'u1', email: 'u@example.com', name: 'User' }),
|
|
});
|
|
|
|
try {
|
|
const adapter = new OneDriveAdapter();
|
|
const persisted: OAuthTokens[] = [];
|
|
adapter.setOnTokensRefreshed((tokens) => persisted.push(tokens));
|
|
|
|
await adapter.setTokens(expiredTokens());
|
|
|
|
assert.deepEqual(persisted, [rotated]);
|
|
assert.deepEqual(adapter.getTokens(), rotated);
|
|
assert.equal(adapter.accountInfo?.id, 'u1');
|
|
} finally {
|
|
restore();
|
|
}
|
|
});
|
|
|
|
test('setTokens with an expired token and no refresh token requires reconnect', async () => {
|
|
const restore = setBridge({});
|
|
try {
|
|
const adapter = new OneDriveAdapter();
|
|
await assert.rejects(
|
|
() =>
|
|
adapter.setTokens({
|
|
accessToken: 'old-access',
|
|
expiresAt: Date.now() - 60_000,
|
|
tokenType: 'Bearer',
|
|
}),
|
|
(err) => {
|
|
assert.equal(isOneDriveReauthRequiredError(err), true);
|
|
return true;
|
|
},
|
|
);
|
|
} finally {
|
|
restore();
|
|
}
|
|
});
|
|
|
|
test('signOut clears the refresh persistence callback', async () => {
|
|
const rotated: OAuthTokens = {
|
|
accessToken: 'fresh-access',
|
|
refreshToken: 'rotated-refresh',
|
|
expiresAt: Date.now() + 3_600_000,
|
|
tokenType: 'Bearer',
|
|
};
|
|
const restore = setBridge({
|
|
onedriveRefreshAccessToken: async () => rotated,
|
|
onedriveGetUserInfo: async () => ({ id: 'u1', email: 'u@example.com', name: 'User' }),
|
|
});
|
|
|
|
try {
|
|
const adapter = new OneDriveAdapter(expiredTokens(), 'file-1');
|
|
let callbackFired = false;
|
|
adapter.setOnTokensRefreshed(() => {
|
|
callbackFired = true;
|
|
});
|
|
adapter.signOut();
|
|
// Re-arm tokens and refresh; the callback must not fire after signOut.
|
|
await adapter.setTokens(expiredTokens());
|
|
assert.equal(callbackFired, false);
|
|
} finally {
|
|
restore();
|
|
}
|
|
});
|