Skip to content
Open
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
2 changes: 1 addition & 1 deletion apps/ui-tars/src/main/window/ScreenMarker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ class ScreenMarker {
webPreferences: {
preload: path.join(__dirname, '../preload/index.js'),
sandbox: false,
webSecurity: !!env.isDev,
webSecurity: true,
},
});

Expand Down
2 changes: 1 addition & 1 deletion apps/ui-tars/src/main/window/createWindow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export function createWindow({
webPreferences: {
preload: path.join(__dirname, '../preload/index.js'),
sandbox: false,
webSecurity: !!env.isDev,
webSecurity: true,
},
};

Expand Down
42 changes: 39 additions & 3 deletions apps/ui-tars/src/preload/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,40 @@ import type { AppState, LocalStore } from '@main/store/types';

export type Channels = '';

const ipcRouteChannels = new Set([
'getScreenSize',
'showMainWindow',
'checkForUpdatesDetail',
'getEnsurePermissions',
'runAgent',
'pauseRun',
'resumeRun',
'stopRun',
'setInstructions',
'setMessages',
'setSessionHistoryMessages',
'clearHistory',
'allocRemoteResource',
'getRemoteResourceRDPUrl',
'releaseRemoteResource',
'getTimeBalance',
'checkBrowserAvailability',
'checkVLMResponseApiSupport',
'checkModelAvailability',
]);

function assertIpcRouteChannel(channel: string): void {
if (!ipcRouteChannels.has(channel)) {
throw new Error(`IPC channel is not allowed: ${channel}`);
}
}

const electronHandler = {
ipcRenderer: {
invoke: (channel: string, ...args: unknown[]) =>
ipcRenderer.invoke(channel, ...args),
invoke: (channel: string, ...args: unknown[]) => {
assertIpcRouteChannel(channel);
return ipcRenderer.invoke(channel, ...args);
},
sendMessage(channel: Channels, ...args: unknown[]) {
ipcRenderer.send(channel, ...args);
},
Expand Down Expand Up @@ -48,7 +78,13 @@ const electronHandler = {
ipcRenderer.invoke('setting:updatePresetFromRemote'),
resetPreset: () => ipcRenderer.invoke('setting:resetPreset'),
onUpdate: (callback: (setting: LocalStore) => void) => {
ipcRenderer.on('setting-updated', (_, state) => callback(state));
const subscription = (_: IpcRendererEvent, state: LocalStore) =>
callback(state);
ipcRenderer.on('setting-updated', subscription);

return () => {
ipcRenderer.removeListener('setting-updated', subscription);
};
},
},
};
Expand Down
4 changes: 3 additions & 1 deletion apps/ui-tars/src/renderer/src/hooks/useRunAgent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,10 @@ export const useRunAgent = () => {
callback: () => void = () => {},
) => {
const operator = settings.operator;
const needsLocalPermissions =
operator === Operator.LocalBrowser || operator === Operator.LocalComputer;
if (
(operator === Operator.LocalBrowser || Operator.LocalComputer) &&
needsLocalPermissions &&
!(ensurePermissions?.accessibility && ensurePermissions?.screenCapture)
) {
const permissionsText = [
Expand Down
4 changes: 2 additions & 2 deletions apps/ui-tars/src/renderer/src/hooks/useSetting.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@ export function useSetting() {
setSettings(currentSetting);
};

settingRpc.onUpdate((newState) => {
const unsubscribe = settingRpc.onUpdate((newState) => {
setSettings(newState);
});

initSetting();

// FIXME: clear setting update listener
return unsubscribe;
}, []);

const {
Expand Down
17 changes: 15 additions & 2 deletions multimodal/tarko/agent-server-next/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,15 @@ import {
import { createUserConfigRoutes } from './routes/user';
import { HookManager, BuiltInPriorities, type HookRegistrationOptions } from './hooks';
import { config } from 'dotenv';
import { ContextStorageHook, ErroHandlingHook, RequestIdHook } from './hooks/builtInHooks';
import {
AuthHook,
ContextStorageHook,
ErroHandlingHook,
RequestIdHook,
SecurityHeadersHook,
createCorsHook,
createCsrfProtectionHook,
} from './hooks/builtInHooks';
import { resetLogger } from './utils/logger';
import chalk from 'chalk';

Expand Down Expand Up @@ -130,8 +138,13 @@ export class AgentServer<T extends AgentAppConfig = AgentAppConfig> {
},
});

this.hookManager.register(SecurityHeadersHook);
this.hookManager.register(createCorsHook(this.port));
this.hookManager.register(ContextStorageHook);
this.hookManager.register(ErroHandlingHook);
this.hookManager.register(RequestIdHook);
this.hookManager.register(AuthHook);
this.hookManager.register(createCsrfProtectionHook());
}


Expand Down Expand Up @@ -488,4 +501,4 @@ export class AgentServer<T extends AgentAppConfig = AgentAppConfig> {
setLogger(logger: ILogger) {
resetLogger(logger);
}
}
}
15 changes: 13 additions & 2 deletions multimodal/tarko/agent-server/src/api/controllers/sessions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,14 @@ import { getDefaultModel } from '../../utils/model-utils';
import * as path from 'path';
import * as fs from 'fs';

function isPathInsideOrEqual(parentPath: string, childPath: string): boolean {
const relative = path.relative(parentPath, childPath);
return (
relative === '' ||
(!!relative && !relative.startsWith('..') && !path.isAbsolute(relative))
);
}

/**
* Get all sessions
*/
Expand Down Expand Up @@ -464,7 +472,10 @@ export async function getSessionWorkspaceFiles(req: Request, res: Response) {
const normalizedWorkspace = path.resolve(baseWorkspacePath);

// Security check
if (normalizedPath.startsWith(normalizedWorkspace) && fs.existsSync(normalizedPath)) {
if (
isPathInsideOrEqual(normalizedWorkspace, normalizedPath) &&
fs.existsSync(normalizedPath)
) {
targetPath = normalizedPath;
break;
}
Expand Down Expand Up @@ -757,7 +768,7 @@ export async function validateWorkspacePaths(req: Request, res: Response) {
const normalizedWorkspace = path.resolve(baseWorkspacePath);

// Security check
if (!normalizedPath.startsWith(normalizedWorkspace)) {
if (!isPathInsideOrEqual(normalizedWorkspace, normalizedPath)) {
return { path: relativePath, exists: false, error: 'Path outside workspace' };
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,14 @@ import express from 'express';
import path from 'path';
import fs from 'fs';

function isPathInsideOrEqual(parentPath: string, childPath: string): boolean {
const relative = path.relative(parentPath, childPath);
return (
relative === '' ||
(!!relative && !relative.startsWith('..') && !path.isAbsolute(relative))
);
}

/**
* Extract session ID from referer URL
* @param referer The referer header value
Expand Down Expand Up @@ -83,7 +91,7 @@ export class WorkspaceFileResolver {
const resolvedPath = path.resolve(filePath);
const resolvedWorkspace = path.resolve(this.baseWorkspacePath);

return resolvedPath.startsWith(resolvedWorkspace);
return isPathInsideOrEqual(resolvedWorkspace, resolvedPath);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,14 @@ import path from 'path';
import type { ChatCompletionContentPart } from '@tarko/agent-interface';
import { WorkspacePack } from './workspace-pack';

function isPathInsideOrEqual(parentPath: string, childPath: string): boolean {
const relative = path.relative(parentPath, childPath);
return (
relative === '' ||
(!!relative && !relative.startsWith('..') && !path.isAbsolute(relative))
);
}

/**
* ContextReferenceProcessor - Processes contextual references in agent queries
*
Expand Down Expand Up @@ -106,7 +114,7 @@ export class ContextReferenceProcessor {
const normalizedWorkspace = path.resolve(workspacePath);
const normalizedTarget = path.resolve(absolutePath);

if (!normalizedTarget.startsWith(normalizedWorkspace)) {
if (!isPathInsideOrEqual(normalizedWorkspace, normalizedTarget)) {
console.warn(`File reference outside workspace: ${fileRef}`);
expandedContents.push(
`<file path="${fileRef}">\nError: File reference outside workspace\n</file>`,
Expand Down Expand Up @@ -150,7 +158,7 @@ export class ContextReferenceProcessor {
const normalizedWorkspace = path.resolve(workspacePath);
const normalizedTarget = path.resolve(absolutePath);

if (!normalizedTarget.startsWith(normalizedWorkspace)) {
if (!isPathInsideOrEqual(normalizedWorkspace, normalizedTarget)) {
console.warn(`Directory reference outside workspace: ${dirRef}`);
return null;
}
Expand Down
10 changes: 7 additions & 3 deletions packages/agent-infra/browser/src/local-browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,13 @@ export class LocalBrowser extends BaseBrowser {
'--disable-window-activation',
'--disable-focus-on-load',
'--no-default-browser-check', // disable default browser check
'--disable-web-security', // disable CORS
'--disable-features=IsolateOrigins,site-per-process',
'--disable-site-isolation-trials',
...(options.disableWebSecurity
? [
'--disable-web-security',
'--disable-features=IsolateOrigins,site-per-process',
'--disable-site-isolation-trials',
]
: []),
`--window-size=${viewportWidth},${viewportHeight + 90}`,
options?.proxy ? `--proxy-server=${options.proxy}` : '',
options?.proxyBypassList
Expand Down
7 changes: 7 additions & 0 deletions packages/agent-infra/browser/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,13 @@ export interface LaunchOptions {
* for more info.
*/
userDataDir?: string;

/**
* Disable browser web security. This weakens origin isolation and should only
* be enabled for controlled automation environments that explicitly need it.
* @default false
*/
disableWebSecurity?: boolean;
}

/**
Expand Down
7 changes: 4 additions & 3 deletions packages/agent-infra/mcp-servers/filesystem/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
expandHome,
applyFileEdits,
getFileStats,
isPathInsideOrEqual,
} from './utils.js';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';

Expand Down Expand Up @@ -73,7 +74,7 @@ async function validatePath(requestedPath: string): Promise<string> {

// Check if path is within allowed directories
const isAllowed = allowedDirectories.some((dir) =>
normalizedRequested.startsWith(dir),
isPathInsideOrEqual(dir, normalizedRequested),
);
if (!isAllowed) {
throw new Error(
Expand All @@ -86,7 +87,7 @@ async function validatePath(requestedPath: string): Promise<string> {
const realPath = await fs.realpath(absolute);
const normalizedReal = normalizePath(realPath);
const isRealPathAllowed = allowedDirectories.some((dir) =>
normalizedReal.startsWith(dir),
isPathInsideOrEqual(dir, normalizedReal),
);
if (!isRealPathAllowed) {
throw new Error(
Expand All @@ -103,7 +104,7 @@ async function validatePath(requestedPath: string): Promise<string> {
const realParentPath = await fs.realpath(parentDir);
const normalizedParent = normalizePath(realParentPath);
const isParentAllowed = allowedDirectories.some((dir) =>
normalizedParent.startsWith(dir),
isPathInsideOrEqual(dir, normalizedParent),
);
if (!isParentAllowed) {
throw new Error(
Expand Down
8 changes: 8 additions & 0 deletions packages/agent-infra/mcp-servers/filesystem/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,14 @@ export function expandHome(filepath: string): string {
return filepath;
}

export function isPathInsideOrEqual(parentPath: string, childPath: string): boolean {
const relative = path.relative(parentPath, childPath);
return (
relative === '' ||
(!!relative && !relative.startsWith('..') && !path.isAbsolute(relative))
);
}

// file editing and diffing utilities
function normalizeLineEndings(text: string): string {
return text.replace(/\r\n/g, '\n');
Expand Down
6 changes: 5 additions & 1 deletion packages/ui-tars/electron-ipc/src/main/createServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,11 @@ export const createServer = <Router extends RouterType>(router: Router) => {
get: (_, prop: string) => {
const route = router[prop];
return (input: any, sender?: WebContents) => {
return route.handle({ context: { sender: sender || null }, input });
const parsedInput = route.schema ? route.schema.parse(input) : input;
return route.handle({
context: { sender: sender || null },
input: parsedInput,
});
};
},
});
Expand Down
8 changes: 4 additions & 4 deletions packages/ui-tars/electron-ipc/src/main/initIpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@
*/
import { HandleFunction, RouterType, ZodSchema } from '../types';

const createChainProdure = <TInput>() => {
const createChainProdure = <TInput>(schema?: ZodSchema<TInput>) => {
const chain = {
input<TInput>(_schema?: ZodSchema<TInput>) {
return createChainProdure<TInput>();
input<TNextInput>(_schema?: ZodSchema<TNextInput>) {
return createChainProdure<TNextInput>(_schema);
},

handle: <TResult>(handle: HandleFunction<TInput, TResult>) => {
return { handle };
return { handle, schema };
},
};

Expand Down
3 changes: 2 additions & 1 deletion packages/ui-tars/electron-ipc/src/main/registerIpcMain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ import { RouterType } from '../types';
export const registerIpcMain = (router: RouterType) => {
for (const [name, route] of Object.entries(router)) {
ipcMain.handle(name, (e, payload) => {
return route.handle({ context: { sender: e.sender }, input: payload });
const input = route.schema ? route.schema.parse(payload) : payload;
return route.handle({ context: { sender: e.sender }, input });
});
}
};
7 changes: 6 additions & 1 deletion packages/ui-tars/electron-ipc/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,12 @@ export type HandleFunction<TInput = any, TResult = any> = (args: {

export type HandleContext = { sender: WebContents | null };

export type RouterType = Record<string, { handle: HandleFunction }>;
export type Procedure<TInput = any, TResult = any> = {
handle: HandleFunction<TInput, TResult>;
schema?: ZodSchema<TInput>;
};

export type RouterType = Record<string, Procedure>;

export type ClientFromRouter<Router extends RouterType> = {
[K in keyof Router]: Router[K]['handle'] extends (options: {
Expand Down
14 changes: 14 additions & 0 deletions packages/ui-tars/electron-ipc/test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,4 +77,18 @@ describe('@ui-tars/electron-ipc', () => {

expect(result).toBe('Hello Server');
});

it('should reject invalid Zod input on server-side calls', () => {
const t = initIpc.create();

const router = t.router({
greet: t.procedure
.input(z.object({ name: z.string() }))
.handle(async ({ input }) => `Hello ${input.name}`),
});

const server = createServer(router);

expect(() => server.greet({ name: 123 } as any)).toThrow();
});
});
Loading