Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions src/main/bootstrap/app-bootstrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,18 @@ import { SessionResolver } from "../pipeline/session-resolver";
import { ExchangeQueryService } from "../queries/exchange-query-service";
import { SessionQueryService } from "../queries/session-query-service";
import { ExchangeRepository } from "../storage/exchange-repository";
import { AppDataService } from "../storage/app-data-service";
import { HistoryMaintenanceService } from "../storage/history-maintenance-service";
import { ProfileStore } from "../storage/profile-store";
import { SessionRepository } from "../storage/session-repository";
import { createSqliteDatabase } from "../storage/sqlite";
import { forwardRequest } from "../transport/forwarder";
import { createProxyManager, type ProxyManager } from "../transport/proxy-manager";
import type { AppDataTransferResult } from "../../shared/app-data";

export interface AppBootstrapDependencies {
userDataPath: string;
appVersion?: string;
onTraceCaptured?: (payload: TraceCapturedEvent) => void;
onProfileStatusChanged?: (payload: ProfileStatusChangedEvent) => void;
onProfileError?: (message: string) => void;
Expand All @@ -39,6 +42,8 @@ export interface AppBootstrap {
proxyManager: ProxyManager;
sessionQueryService: SessionQueryService;
exchangeQueryService: ExchangeQueryService;
exportData(filePath: string): AppDataTransferResult;
importData(filePath: string): Promise<AppDataTransferResult>;
getProfiles(): ConnectionProfile[];
saveProfiles(profiles: ConnectionProfile[]): ConnectionProfile[];
clearHistory(): void;
Expand Down Expand Up @@ -253,13 +258,27 @@ export function createAppBootstrap(
},
});

const appDataService = new AppDataService({
appVersion: deps.appVersion ?? "0.0.0",
profileStore,
sessionRepository,
exchangeRepository,
proxyManager,
});

return {
providerCatalog,
protocolAdapters,
profileStore,
proxyManager,
sessionQueryService,
exchangeQueryService,
exportData(filePath) {
return appDataService.exportToFile(filePath);
},
importData(filePath) {
return appDataService.importFromFile(filePath);
},

getProfiles() {
return profileStore.getProfiles();
Expand Down
66 changes: 65 additions & 1 deletion src/main/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { app, BrowserWindow } from "electron";
import { app, BrowserWindow, shell } from "electron";
import { join } from "path";
import { registerIpcHandlers } from "./ipc/register-ipc";
import { IPC } from "../shared/ipc-channels";
Expand All @@ -11,6 +11,41 @@ let disposeIpcHandlers: (() => void) | null = null;
let disposeUpdateService: (() => void) | null = null;
let profilesStarted = false;

function getExternalNavigationTarget(
currentUrl: string,
nextUrl: string,
): string | null {
let target: URL;
try {
target = new URL(nextUrl);
} catch {
return null;
}

if (!["http:", "https:", "mailto:"].includes(target.protocol)) {
return null;
}

if (target.protocol === "mailto:") {
return target.toString();
}

if (!currentUrl) {
return target.toString();
}

try {
const current = new URL(currentUrl);
if (current.origin === target.origin) {
return null;
}
} catch {
return target.toString();
}

return target.toString();
}

function broadcastProfileStatuses(): void {
if (!mainWindow || !appBootstrap) return;
mainWindow.webContents.send(IPC.PROFILE_STATUS_CHANGED, {
Expand Down Expand Up @@ -40,6 +75,32 @@ function createWindow(): void {
broadcastProfileStatuses();
});

mainWindow.webContents.setWindowOpenHandler(({ url }) => {
const target = getExternalNavigationTarget(
mainWindow?.webContents.getURL() ?? "",
url,
);
if (target) {
void shell.openExternal(target);
return { action: "deny" };
}

return { action: "allow" };
});

mainWindow.webContents.on("will-navigate", (event, url) => {
const target = getExternalNavigationTarget(
mainWindow?.webContents.getURL() ?? "",
url,
);
if (!target) {
return;
}

event.preventDefault();
void shell.openExternal(target);
});

if (process.env.ELECTRON_RENDERER_URL) {
void mainWindow.loadURL(process.env.ELECTRON_RENDERER_URL);
} else {
Expand All @@ -59,6 +120,7 @@ app.whenReady().then(async () => {

appBootstrap = createAppBootstrap({
userDataPath,
appVersion: app.getVersion(),
onTraceCaptured: (payload) => {
mainWindow?.webContents.send(IPC.TRACE_CAPTURED, payload);
},
Expand All @@ -75,6 +137,8 @@ app.whenReady().then(async () => {
proxyManager: appBootstrap.proxyManager,
sessionQueryService: appBootstrap.sessionQueryService,
exchangeQueryService: appBootstrap.exchangeQueryService,
exportData: (filePath) => appBootstrap!.exportData(filePath),
importData: (filePath) => appBootstrap!.importData(filePath),
clearHistory: () => {
appBootstrap?.clearHistory();
},
Expand Down
87 changes: 86 additions & 1 deletion src/main/ipc/register-ipc.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { ipcMain, type BrowserWindow } from "electron";
import { homedir } from "node:os";
import { join } from "node:path";
import { dialog, ipcMain, shell, type BrowserWindow } from "electron";
import { IPC } from "../../shared/ipc-channels";
import type { AppDataTransferResult } from "../../shared/app-data";
import type {
ConnectionProfile,
SessionListFilter,
Expand All @@ -18,6 +21,8 @@ export interface IpcDependencies {
"listSessions" | "getSessionTrace"
>;
exchangeQueryService: Pick<ExchangeQueryService, "getExchangeDetail">;
exportData: (filePath: string) => AppDataTransferResult;
importData: (filePath: string) => Promise<AppDataTransferResult>;
clearHistory: () => void | Promise<void>;
getMainWindow: () => BrowserWindow | null;
updateService: UpdateService;
Expand All @@ -35,7 +40,87 @@ function broadcast(
win.webContents.send(channel, payload);
}

function validateExternalUrl(input: string): string {
if (typeof input !== "string") {
throw new Error("Invalid external URL");
}

let parsed: URL;
try {
parsed = new URL(input);
} catch {
throw new Error("Invalid external URL");
}

if (!["http:", "https:", "mailto:"].includes(parsed.protocol)) {
throw new Error("Unsupported external URL protocol");
}

return parsed.toString();
}

export function registerIpcHandlers(deps: IpcDependencies): () => void {
ipcMain.handle(IPC.OPEN_EXTERNAL, async (_event, url: string) => {
await shell.openExternal(validateExternalUrl(url));
});

ipcMain.handle(IPC.EXPORT_APP_DATA, async () => {
const defaultPath = join(
homedir(),
`agent-trace-backup-${new Date().toISOString().slice(0, 10)}.zip`,
);
const window = deps.getMainWindow();
const dialogOptions: Electron.SaveDialogOptions = {
title: "Export Agent Trace Data",
defaultPath,
filters: [
{ name: "Agent Trace Backup Archive", extensions: ["zip"] },
],
};
const result = window
? await dialog.showSaveDialog(window, dialogOptions)
: await dialog.showSaveDialog(dialogOptions);

if (result.canceled || !result.filePath) {
return null;
}

const exported = deps.exportData(result.filePath);
shell.showItemInFolder(result.filePath);
return exported;
});

ipcMain.handle(IPC.IMPORT_APP_DATA, async () => {
const window = deps.getMainWindow();
const dialogOptions: Electron.OpenDialogOptions = {
title: "Import Agent Trace Data",
properties: ["openFile"],
filters: [
{ name: "Agent Trace Backups", extensions: ["zip"] },
],
};
const result = window
? await dialog.showOpenDialog(window, dialogOptions)
: await dialog.showOpenDialog(dialogOptions);

const filePath = result.filePaths[0];
if (result.canceled || !filePath) {
return null;
}

const imported = await deps.importData(filePath);
broadcast(deps.getMainWindow, IPC.PROFILES_CHANGED, {
profiles: deps.profileStore.getProfiles(),
});
broadcast(deps.getMainWindow, IPC.PROFILE_STATUS_CHANGED, {
statuses: deps.proxyManager.getStatuses(),
});
broadcast(deps.getMainWindow, IPC.TRACE_RESET, {
clearedAt: new Date().toISOString(),
});
return imported;
});

ipcMain.handle(IPC.GET_PROFILES, () => {
return deps.profileStore.getProfiles();
});
Expand Down
Loading
Loading