Enables OneDrive sync via Electron bridge APIs

Integrates OneDrive cloud sync operations with Electron main process to bypass CORS and improve security.
Updates OAuth endpoints, client ID, and bridges all relevant sync file methods.
Simplifies error logging for provider connect failures.
Improves error message display in the UI.
This commit is contained in:
LAPTOP-O016UC3M\Qi Chen committed 2025-12-23 12:09:08 +08:00
1 parent 21a17accce
commit 4c382fcb62
8 files changed
+433 -21

No files matched your search

+6 -1
View File
@@ -356,7 +356,12 @@ const ProviderCard: React.FC<ProviderCardProps> = ({
</span>
</div>
) : error ? (
<p className="text-xs text-red-500 truncate mt-1">{error}</p>
<p
className="text-xs text-red-500 truncate mt-1 max-w-[360px] cursor-help"
title={error}
>
{error}
</p>
) : (
<p className="text-xs text-muted-foreground mt-1">{t('cloudSync.provider.notConnected')}</p>
)}
+3 -3
View File
@@ -403,7 +403,7 @@ export const SYNC_CONSTANTS = {
// OAuth
GITHUB_CLIENT_ID: 'Ov23liuLdkw1H393rtT4', // Public client ID for Device Flow
GOOGLE_CLIENT_ID: '840441747394-n58o8ibgivgd3frqsn0bo5revf4viq2a.apps.googleusercontent.com',
ONEDRIVE_CLIENT_ID: 'your-onedrive-client-id',
ONEDRIVE_CLIENT_ID: '138bb0b6-b919-4e9d-80c6-64136ffc02a3',
// API endpoints
GITHUB_DEVICE_CODE_URL: 'https://github.com/login/device/code',
@@ -414,8 +414,8 @@ export const SYNC_CONSTANTS = {
GOOGLE_TOKEN_URL: 'https://oauth2.googleapis.com/token',
GOOGLE_DRIVE_API: 'https://www.googleapis.com/drive/v3',
ONEDRIVE_AUTH_URL: 'https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize',
ONEDRIVE_TOKEN_URL: 'https://login.microsoftonline.com/consumers/oauth2/v2.0/token',
ONEDRIVE_AUTH_URL: 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize',
ONEDRIVE_TOKEN_URL: 'https://login.microsoftonline.com/common/oauth2/v2.0/token',
ONEDRIVE_GRAPH_API: 'https://graph.microsoft.com/v1.0',
} as const;
+299
View File
@@ -0,0 +1,299 @@
/**
* OneDrive OAuth + Graph Bridge (main process)
*
* Renderer fetches to Microsoft token/Graph endpoints can be blocked by CORS.
* This bridge proxies token exchange/refresh and Graph requests via main process.
*/
const ONEDRIVE_TOKEN_URL = "https://login.microsoftonline.com/consumers/oauth2/v2.0/token";
const ONEDRIVE_GRAPH_API = "https://graph.microsoft.com/v1.0";
const APP_FOLDER_PATH = "/drive/special/approot";
const DEFAULT_SYNC_FILE_NAME = "netcatty-vault.json";
const isNonEmptyString = (v) => typeof v === "string" && v.trim().length > 0;
const safeJsonParse = (text) => {
try {
return JSON.parse(text);
} catch {
return null;
}
};
const describeNetworkError = (err) => {
const msg = err?.message || String(err);
const cause = err?.cause;
const causeCode = cause?.code ? ` (${cause.code})` : "";
const causeMsg = cause?.message ? `: ${cause.message}` : "";
return `${msg}${causeCode}${causeMsg}`.trim();
};
const base64FromArrayBuffer = (buffer) => {
return Buffer.from(buffer).toString("base64");
};
/**
* @param {Electron.IpcMain} ipcMain
* @param {import('electron')=} electronModule
*/
function registerHandlers(ipcMain, electronModule) {
const fetchImpl =
electronModule?.net?.fetch ? electronModule.net.fetch.bind(electronModule.net) : fetch;
ipcMain.handle("netcatty:onedrive:oauth:exchange", async (_event, payload) => {
const clientId = payload?.clientId;
const code = payload?.code;
const codeVerifier = payload?.codeVerifier;
const redirectUri = payload?.redirectUri;
if (!isNonEmptyString(clientId)) throw new Error("Missing OneDrive clientId");
if (!isNonEmptyString(code)) throw new Error("Missing authorization code");
if (!isNonEmptyString(codeVerifier)) throw new Error("Missing codeVerifier");
if (!isNonEmptyString(redirectUri)) throw new Error("Missing redirectUri");
const body = new URLSearchParams({
client_id: clientId,
code,
code_verifier: codeVerifier,
grant_type: "authorization_code",
redirect_uri: redirectUri,
});
let res;
try {
res = await fetchImpl(ONEDRIVE_TOKEN_URL, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/x-www-form-urlencoded",
},
body: body.toString(),
});
} catch (err) {
throw new Error(
`OneDrive token exchange network error. Check your network/VPN and whether Microsoft services are reachable. (${describeNetworkError(err)})`
);
}
const text = await res.text();
if (!res.ok) {
const data = safeJsonParse(text) || { error: text };
throw new Error(
`OneDrive token exchange failed: ${data.error_description || data.error || res.status}`
);
}
const data = safeJsonParse(text);
if (!data) {
throw new Error(`OneDrive token exchange invalid JSON: ${text.slice(0, 200)}`);
}
return {
accessToken: data.access_token,
refreshToken: data.refresh_token,
expiresAt: Date.now() + (data.expires_in || 0) * 1000,
tokenType: data.token_type,
scope: data.scope,
};
});
ipcMain.handle("netcatty:onedrive:oauth:refresh", async (_event, payload) => {
const clientId = payload?.clientId;
const refreshToken = payload?.refreshToken;
if (!isNonEmptyString(clientId)) throw new Error("Missing OneDrive clientId");
if (!isNonEmptyString(refreshToken)) throw new Error("Missing refreshToken");
const body = new URLSearchParams({
client_id: clientId,
refresh_token: refreshToken,
grant_type: "refresh_token",
});
let res;
try {
res = await fetchImpl(ONEDRIVE_TOKEN_URL, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/x-www-form-urlencoded",
},
body: body.toString(),
});
} catch (err) {
throw new Error(
`OneDrive token refresh network error. Check your network/VPN and whether Microsoft services are reachable. (${describeNetworkError(err)})`
);
}
const text = await res.text();
if (!res.ok) {
const data = safeJsonParse(text) || { error: text };
throw new Error(
`OneDrive token refresh failed: ${data.error_description || data.error || res.status}`
);
}
const data = safeJsonParse(text);
if (!data) {
throw new Error(`OneDrive token refresh invalid JSON: ${text.slice(0, 200)}`);
}
return {
accessToken: data.access_token,
refreshToken: data.refresh_token || refreshToken,
expiresAt: Date.now() + (data.expires_in || 0) * 1000,
tokenType: data.token_type,
scope: data.scope,
};
});
ipcMain.handle("netcatty:onedrive:oauth:userinfo", async (_event, payload) => {
const accessToken = payload?.accessToken;
if (!isNonEmptyString(accessToken)) throw new Error("Missing accessToken");
let res;
try {
res = await fetchImpl(`${ONEDRIVE_GRAPH_API}/me`, {
headers: { Authorization: `Bearer ${accessToken}` },
});
} catch (err) {
throw new Error(
`OneDrive userinfo network error. Check your network/VPN and whether Microsoft services are reachable. (${describeNetworkError(err)})`
);
}
const text = await res.text();
if (!res.ok) {
throw new Error(`OneDrive userinfo failed: ${res.status} - ${text.slice(0, 200)}`);
}
const user = safeJsonParse(text);
if (!user) {
throw new Error(`OneDrive userinfo invalid JSON: ${text.slice(0, 200)}`);
}
let avatarDataUrl;
try {
const photoRes = await fetchImpl(`${ONEDRIVE_GRAPH_API}/me/photo/$value`, {
headers: { Authorization: `Bearer ${accessToken}` },
});
if (photoRes.ok) {
const buffer = await photoRes.arrayBuffer();
const contentType = photoRes.headers.get("content-type") || "image/jpeg";
avatarDataUrl = `data:${contentType};base64,${base64FromArrayBuffer(buffer)}`;
}
} catch {
// Ignore photo errors
}
return {
id: user.id,
email: user.mail || user.userPrincipalName,
name: user.displayName,
avatarDataUrl,
};
});
ipcMain.handle("netcatty:onedrive:drive:findSyncFile", async (_event, payload) => {
const accessToken = payload?.accessToken;
const fileName = isNonEmptyString(payload?.fileName) ? payload.fileName : DEFAULT_SYNC_FILE_NAME;
if (!isNonEmptyString(accessToken)) throw new Error("Missing accessToken");
const url = `${ONEDRIVE_GRAPH_API}/me${APP_FOLDER_PATH}:/${encodeURIComponent(fileName)}`;
const res = await fetchImpl(url, {
headers: { Authorization: `Bearer ${accessToken}` },
});
if (res.status === 404) {
return { fileId: null };
}
if (!res.ok) {
const text = await res.text();
throw new Error(`OneDrive find sync file failed: ${res.status} - ${text.slice(0, 200)}`);
}
const item = await res.json();
return { fileId: item?.id || null };
});
ipcMain.handle("netcatty:onedrive:drive:uploadSyncFile", async (_event, payload) => {
const accessToken = payload?.accessToken;
const fileName = isNonEmptyString(payload?.fileName) ? payload.fileName : DEFAULT_SYNC_FILE_NAME;
const syncedFile = payload?.syncedFile;
if (!isNonEmptyString(accessToken)) throw new Error("Missing accessToken");
if (!syncedFile) throw new Error("Missing syncedFile");
const url = `${ONEDRIVE_GRAPH_API}/me${APP_FOLDER_PATH}:/${encodeURIComponent(fileName)}:/content`;
const res = await fetchImpl(url, {
method: "PUT",
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify(syncedFile, null, 2),
});
const text = await res.text();
if (!res.ok) {
throw new Error(`OneDrive upload failed: ${res.status} - ${text.slice(0, 200)}`);
}
const item = safeJsonParse(text) || {};
return { fileId: item.id || null };
});
ipcMain.handle("netcatty:onedrive:drive:downloadSyncFile", async (_event, payload) => {
const accessToken = payload?.accessToken;
const fileId = payload?.fileId;
const fileName = isNonEmptyString(payload?.fileName) ? payload.fileName : DEFAULT_SYNC_FILE_NAME;
if (!isNonEmptyString(accessToken)) throw new Error("Missing accessToken");
const url = fileId
? `${ONEDRIVE_GRAPH_API}/me/drive/items/${fileId}/content`
: `${ONEDRIVE_GRAPH_API}/me${APP_FOLDER_PATH}:/${encodeURIComponent(fileName)}:/content`;
const res = await fetchImpl(url, {
headers: { Authorization: `Bearer ${accessToken}` },
});
if (res.status === 404) {
return { syncedFile: null };
}
const text = await res.text();
if (!res.ok) {
throw new Error(`OneDrive download failed: ${res.status} - ${text.slice(0, 200)}`);
}
const data = safeJsonParse(text);
if (!data) {
throw new Error(`OneDrive download invalid JSON: ${text.slice(0, 200)}`);
}
return { syncedFile: data };
});
ipcMain.handle("netcatty:onedrive:drive:deleteSyncFile", async (_event, payload) => {
const accessToken = payload?.accessToken;
const fileId = payload?.fileId;
if (!isNonEmptyString(accessToken)) throw new Error("Missing accessToken");
if (!isNonEmptyString(fileId)) throw new Error("Missing fileId");
const url = `${ONEDRIVE_GRAPH_API}/me/drive/items/${fileId}`;
const res = await fetchImpl(url, {
method: "DELETE",
headers: { Authorization: `Bearer ${accessToken}` },
});
if (!res.ok && res.status !== 404) {
const text = await res.text();
throw new Error(`OneDrive delete failed: ${res.status} - ${text.slice(0, 200)}`);
}
return { ok: true };
});
}
module.exports = {
registerHandlers,
};
+2
View File
@@ -74,6 +74,7 @@ const terminalBridge = require("./bridges/terminalBridge.cjs");
const oauthBridge = require("./bridges/oauthBridge.cjs");
const githubAuthBridge = require("./bridges/githubAuthBridge.cjs");
const googleAuthBridge = require("./bridges/googleAuthBridge.cjs");
const onedriveAuthBridge = require("./bridges/onedriveAuthBridge.cjs");
const cloudSyncBridge = require("./bridges/cloudSyncBridge.cjs");
const windowManager = require("./bridges/windowManager.cjs");
@@ -369,6 +370,7 @@ const registerBridges = (win) => {
oauthBridge.setupOAuthBridge(ipcMain);
githubAuthBridge.registerHandlers(ipcMain);
googleAuthBridge.registerHandlers(ipcMain, electronModule);
onedriveAuthBridge.registerHandlers(ipcMain, electronModule);
cloudSyncBridge.registerHandlers(ipcMain);
// Settings window handler
+16
View File
@@ -472,6 +472,22 @@ const api = {
ipcRenderer.invoke("netcatty:google:drive:downloadSyncFile", options),
googleDriveDeleteSyncFile: (options) =>
ipcRenderer.invoke("netcatty:google:drive:deleteSyncFile", options),
// OneDrive OAuth + Graph (proxied via main process to avoid CORS)
onedriveExchangeCodeForTokens: (options) =>
ipcRenderer.invoke("netcatty:onedrive:oauth:exchange", options),
onedriveRefreshAccessToken: (options) =>
ipcRenderer.invoke("netcatty:onedrive:oauth:refresh", options),
onedriveGetUserInfo: (options) =>
ipcRenderer.invoke("netcatty:onedrive:oauth:userinfo", options),
onedriveFindSyncFile: (options) =>
ipcRenderer.invoke("netcatty:onedrive:drive:findSyncFile", options),
onedriveUploadSyncFile: (options) =>
ipcRenderer.invoke("netcatty:onedrive:drive:uploadSyncFile", options),
onedriveDownloadSyncFile: (options) =>
ipcRenderer.invoke("netcatty:onedrive:drive:downloadSyncFile", options),
onedriveDeleteSyncFile: (options) =>
ipcRenderer.invoke("netcatty:onedrive:drive:deleteSyncFile", options),
};
// Merge with existing netcatty (if any) to avoid stale objects on hot reload
Vendored
+34
View File
@@ -345,6 +345,40 @@ interface NetcattyBridge {
googleDriveUpdateSyncFile?(options: { accessToken: string; fileId: string; syncedFile: unknown }): Promise<{ ok: true }>;
googleDriveDownloadSyncFile?(options: { accessToken: string; fileId: string }): Promise<{ syncedFile: unknown | null }>;
googleDriveDeleteSyncFile?(options: { accessToken: string; fileId: string }): Promise<{ ok: true }>;
// OneDrive OAuth + Graph (cloud sync) - proxied via main process to avoid CORS
onedriveExchangeCodeForTokens?(options: {
clientId: string;
code: string;
codeVerifier: string;
redirectUri: string;
}): Promise<{
accessToken: string;
refreshToken?: string;
expiresAt?: number;
tokenType: string;
scope?: string;
}>;
onedriveRefreshAccessToken?(options: {
clientId: string;
refreshToken: string;
}): Promise<{
accessToken: string;
refreshToken: string;
expiresAt?: number;
tokenType: string;
scope?: string;
}>;
onedriveGetUserInfo?(options: { accessToken: string }): Promise<{
id: string;
email: string;
name: string;
avatarDataUrl?: string;
}>;
onedriveFindSyncFile?(options: { accessToken: string; fileName?: string }): Promise<{ fileId: string | null }>;
onedriveUploadSyncFile?(options: { accessToken: string; fileName?: string; syncedFile: unknown }): Promise<{ fileId: string | null }>;
onedriveDownloadSyncFile?(options: { accessToken: string; fileId?: string; fileName?: string }): Promise<{ syncedFile: unknown | null }>;
onedriveDeleteSyncFile?(options: { accessToken: string; fileId: string }): Promise<{ ok: true }>;
}
interface Window {
+3 -17
View File
@@ -588,23 +588,9 @@ export class CloudSyncManager {
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
if (provider === 'webdav') {
const webdav = config as WebDAVConfig;
console.error('[CloudSync] WebDAV connect failed', {
endpoint: webdav.endpoint,
authType: webdav.authType,
error: errorMessage,
});
} else {
const s3 = config as S3Config;
console.error('[CloudSync] S3 connect failed', {
endpoint: s3.endpoint,
region: s3.region,
bucket: s3.bucket,
forcePathStyle: s3.forcePathStyle,
error: errorMessage,
});
}
console.error(`[CloudSync] ${provider} connect failed`, {
error: errorMessage,
});
this.updateProviderStatus(provider, 'error', errorMessage);
throw error;
}
@@ -19,6 +19,7 @@ import {
type SyncedFile,
type PKCEChallenge,
} from '../../../domain/sync';
import { netcattyBridge } from '../netcattyBridge';
import { arrayBufferToBase64, generateRandomBytes } from '../EncryptionService';
// ============================================================================
@@ -125,6 +126,15 @@ export const exchangeCodeForTokens = async (
codeVerifier: string,
redirectUri: string
): Promise<OAuthTokens> => {
const bridge = netcattyBridge.get();
if (bridge?.onedriveExchangeCodeForTokens) {
return bridge.onedriveExchangeCodeForTokens({
clientId: SYNC_CONSTANTS.ONEDRIVE_CLIENT_ID,
code,
codeVerifier,
redirectUri,
});
}
const response = await fetch(SYNC_CONSTANTS.ONEDRIVE_TOKEN_URL, {
method: 'POST',
headers: {
@@ -159,6 +169,13 @@ export const exchangeCodeForTokens = async (
* Refresh access token
*/
export const refreshAccessToken = async (refreshToken: string): Promise<OAuthTokens> => {
const bridge = netcattyBridge.get();
if (bridge?.onedriveRefreshAccessToken) {
return bridge.onedriveRefreshAccessToken({
clientId: SYNC_CONSTANTS.ONEDRIVE_CLIENT_ID,
refreshToken,
});
}
const response = await fetch(SYNC_CONSTANTS.ONEDRIVE_TOKEN_URL, {
method: 'POST',
headers: {
@@ -194,6 +211,16 @@ export const refreshAccessToken = async (refreshToken: string): Promise<OAuthTok
* Get authenticated user info
*/
export const getUserInfo = async (accessToken: string): Promise<ProviderAccount> => {
const bridge = netcattyBridge.get();
if (bridge?.onedriveGetUserInfo) {
const user = await bridge.onedriveGetUserInfo({ accessToken });
return {
id: user.id,
email: user.email,
name: user.name,
avatarUrl: user.avatarDataUrl,
};
}
const response = await fetch(`${SYNC_CONSTANTS.ONEDRIVE_GRAPH_API}/me`, {
headers: {
'Authorization': `Bearer ${accessToken}`,
@@ -235,6 +262,15 @@ export const getUserInfo = async (accessToken: string): Promise<ProviderAccount>
* Validate access token
*/
export const validateToken = async (accessToken: string): Promise<boolean> => {
const bridge = netcattyBridge.get();
if (bridge?.onedriveGetUserInfo) {
try {
await bridge.onedriveGetUserInfo({ accessToken });
return true;
} catch {
return false;
}
}
try {
const response = await fetch(`${SYNC_CONSTANTS.ONEDRIVE_GRAPH_API}/me`, {
headers: { 'Authorization': `Bearer ${accessToken}` },
@@ -255,6 +291,14 @@ const APP_FOLDER_PATH = '/drive/special/approot';
* Ensure app folder exists and find sync file
*/
export const findSyncFile = async (accessToken: string): Promise<string | null> => {
const bridge = netcattyBridge.get();
if (bridge?.onedriveFindSyncFile) {
const result = await bridge.onedriveFindSyncFile({
accessToken,
fileName: SYNC_CONSTANTS.SYNC_FILE_NAME,
});
return result.fileId || null;
}
try {
const response = await fetch(
`${SYNC_CONSTANTS.ONEDRIVE_GRAPH_API}/me${APP_FOLDER_PATH}:/${SYNC_CONSTANTS.SYNC_FILE_NAME}`,
@@ -287,6 +331,18 @@ export const uploadSyncFile = async (
accessToken: string,
syncedFile: SyncedFile
): Promise<string> => {
const bridge = netcattyBridge.get();
if (bridge?.onedriveUploadSyncFile) {
const result = await bridge.onedriveUploadSyncFile({
accessToken,
fileName: SYNC_CONSTANTS.SYNC_FILE_NAME,
syncedFile,
});
if (!result.fileId) {
throw new Error('Failed to upload sync file');
}
return result.fileId;
}
const content = JSON.stringify(syncedFile, null, 2);
const response = await fetch(
@@ -316,6 +372,15 @@ export const downloadSyncFile = async (
accessToken: string,
fileId?: string
): Promise<SyncedFile | null> => {
const bridge = netcattyBridge.get();
if (bridge?.onedriveDownloadSyncFile) {
const result = await bridge.onedriveDownloadSyncFile({
accessToken,
fileId,
fileName: SYNC_CONSTANTS.SYNC_FILE_NAME,
});
return (result.syncedFile as SyncedFile | null) || null;
}
try {
// Can use either file ID or path
const url = fileId
@@ -349,6 +414,11 @@ export const deleteSyncFile = async (
accessToken: string,
fileId: string
): Promise<void> => {
const bridge = netcattyBridge.get();
if (bridge?.onedriveDeleteSyncFile) {
await bridge.onedriveDeleteSyncFile({ accessToken, fileId });
return;
}
const response = await fetch(
`${SYNC_CONSTANTS.ONEDRIVE_GRAPH_API}/me/drive/items/${fileId}`,
{