Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(server): guard device file mutations against unapproved workspace roots (#15967)

Arvin Xu7ea84a269532
diff --git a/apps/server/src/routers/lambda/__tests__/deviceWorkspaceGuard.test.ts b/apps/server/src/routers/lambda/__tests__/deviceWorkspaceGuard.test.ts
new file mode 100644
index 00000000000..4a75b9afbd2
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/deviceWorkspaceGuard.test.ts
@@ -0,0 +1,70 @@
+import { TRPCError } from '@trpc/server';
+import { describe, expect, it, vi } from 'vitest';
+
+import type { DeviceModel } from '@/database/models/device';
+
+import { assertWorkspaceRootApproved } from '../deviceWorkspaceGuard';
+
+const mockModel = (row: { defaultCwd?: string | null; workingDirs?: { path: string }[] } | null) =>
+ ({
+ findByDeviceId: vi.fn().mockResolvedValue(row),
+ }) as unknown as DeviceModel;
+
+describe('assertWorkspaceRootApproved', () => {
+ it('allows a root that exactly matches a bound workingDir', async () => {
+ const model = mockModel({ workingDirs: [{ path: '/Users/me/proj' }] });
+ await expect(
+ assertWorkspaceRootApproved(model, 'dev-1', '/Users/me/proj'),
+ ).resolves.toBeUndefined();
+ });
+
+ it('allows a root nested inside a bound workingDir', async () => {
+ const model = mockModel({ workingDirs: [{ path: '/Users/me/proj' }] });
+ await expect(
+ assertWorkspaceRootApproved(model, 'dev-1', '/Users/me/proj/packages/app'),
+ ).resolves.toBeUndefined();
+ });
+
+ it('allows a root matching defaultCwd when no workingDirs match', async () => {
+ const model = mockModel({ defaultCwd: '/Users/me/default', workingDirs: [] });
+ await expect(
+ assertWorkspaceRootApproved(model, 'dev-1', '/Users/me/default'),
+ ).resolves.toBeUndefined();
+ });
+
+ it('rejects a root that escapes the approved roots (filesystem root)', async () => {
+ const model = mockModel({ workingDirs: [{ path: '/Users/me/proj' }] });
+ await expect(assertWorkspaceRootApproved(model, 'dev-1', '/')).rejects.toMatchObject({
+ code: 'FORBIDDEN',
+ });
+ });
+
+ it('rejects a sibling directory that shares a path prefix but is not contained', async () => {
+ const model = mockModel({ workingDirs: [{ path: '/Users/me/proj' }] });
+ await expect(
+ assertWorkspaceRootApproved(model, 'dev-1', '/Users/me/proj-evil'),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ });
+
+ it('rejects when the device has no approved roots at all', async () => {
+ const model = mockModel({ workingDirs: [] });
+ await expect(
+ assertWorkspaceRootApproved(model, 'dev-1', '/Users/me/proj'),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ });
+
+ it('rejects when the device row is missing', async () => {
+ const model = mockModel(null);
+ await expect(
+ assertWorkspaceRootApproved(model, 'dev-1', '/Users/me/proj'),
+ ).rejects.toBeInstanceOf(TRPCError);
+ });
+
+ it('rejects an empty workspace root with BAD_REQUEST before hitting the DB', async () => {
+ const model = mockModel({ workingDirs: [{ path: '/Users/me/proj' }] });
+ await expect(assertWorkspaceRootApproved(model, 'dev-1', '')).rejects.toMatchObject({
+ code: 'BAD_REQUEST',
+ });
+ expect(model.findByDeviceId).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/routers/lambda/device.ts b/apps/server/src/routers/lambda/device.ts
index f61e3fec042..b8a24a5382d 100644
--- a/apps/server/src/routers/lambda/device.ts
+++ b/apps/server/src/routers/lambda/device.ts
@@ -8,6 +8,7 @@ import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { deviceGateway } from '@/server/services/deviceGateway';
import { preserveWorkspaceCache } from './deviceWorkingDirs';
+import { assertWorkspaceRootApproved } from './deviceWorkspaceGuard';
// Derive the zod enum from the canonical config so new platforms are
// automatically covered without touching this file.
@@ -29,6 +30,23 @@ const deviceProcedure = authedProcedure.use(serverDatabase).use(async (opts) =>
});
});
+const workspaceFileInput = z.object({
+ deviceId: z.string(),
+ workingDirectory: z.string(),
+});
+
+/**
+ * `deviceProcedure` that additionally requires `workingDirectory` to be an
+ * approved workspace root for the device. Builds the guard into the procedure
+ * so every file-mutating route inherits it and can never forget the check β€”
+ * see {@link assertWorkspaceRootApproved} for why the check is necessary.
+ */
+const workspaceFileProcedure = deviceProcedure.input(workspaceFileInput).use(async (opts) => {
+ const { deviceId, workingDirectory } = workspaceFileInput.parse(await opts.getRawInput());
+ await assertWorkspaceRootApproved(opts.ctx.deviceModel, deviceId, workingDirectory);
+ return opts.next();
+});
+
export const deviceRouter = router({
/**
* Probe whether a specific agent platform (openclaw / hermes) is available
@@ -334,24 +352,22 @@ export const deviceRouter = router({
* Read-only local file preview for a file on a remote device. The web client
* receives render data, not a `localfile://` URL; saving remains unsupported.
*/
- getLocalFilePreview: deviceProcedure
+ getLocalFilePreview: workspaceFileProcedure
.input(
z.object({
accept: z.enum(['image']).optional(),
- deviceId: z.string(),
path: z.string(),
- workingDirectory: z.string(),
}),
)
- .query(async ({ ctx, input }) =>
- deviceGateway.getLocalFilePreview({
+ .query(async ({ ctx, input }) => {
+ return deviceGateway.getLocalFilePreview({
accept: input.accept,
deviceId: input.deviceId,
path: input.path,
userId: ctx.userId,
workingDirectory: input.workingDirectory,
- }),
- ),
+ });
+ }),
/**
* Project skills (`.agents/skills` / `.claude/skills`) for a directory on a
@@ -388,68 +404,62 @@ export const deviceRouter = router({
* Move files/folders within a directory on a remote device, via the device's
* `moveLocalFiles` RPC. Powers the Files tree's drag-to-move in device mode.
*/
- moveProjectFiles: deviceProcedure
+ moveProjectFiles: workspaceFileProcedure
.input(
z.object({
- deviceId: z.string(),
items: z.array(z.object({ newPath: z.string(), oldPath: z.string() })),
- workingDirectory: z.string(),
}),
)
- .mutation(async ({ ctx, input }) =>
- deviceGateway.moveProjectFiles({
+ .mutation(async ({ ctx, input }) => {
+ return deviceGateway.moveProjectFiles({
deviceId: input.deviceId,
items: input.items,
userId: ctx.userId,
workingDirectory: input.workingDirectory,
- }),
- ),
+ });
+ }),
/**
* Rename a single file/folder in a directory on a remote device, via the
* device's `renameLocalFile` RPC.
*/
- renameProjectFile: deviceProcedure
+ renameProjectFile: workspaceFileProcedure
.input(
z.object({
- deviceId: z.string(),
newName: z.string(),
path: z.string(),
- workingDirectory: z.string(),
}),
)
- .mutation(async ({ ctx, input }) =>
- deviceGateway.renameProjectFile({
+ .mutation(async ({ ctx, input }) => {
+ return deviceGateway.renameProjectFile({
deviceId: input.deviceId,
newName: input.newName,
path: input.path,
userId: ctx.userId,
workingDirectory: input.workingDirectory,
- }),
- ),
+ });
+ }),
/**
* Save edited content back to a file on a remote device, via the device's
* `writeLocalFile` RPC. Powers remote save in the LocalFile editor.
*/
- writeProjectFile: deviceProcedure
+ writeProjectFile: workspaceFileProcedure
.input(
z.object({
content: z.string(),
- deviceId: z.string(),
path: z.string(),
- workingDirectory: z.string(),
}),
)
- .mutation(async ({ ctx, input }) =>
- deviceGateway.writeProjectFile({
+ .mutation(async ({ ctx, input }) => {
+ return deviceGateway.writeProjectFile({
content: input.content,
deviceId: input.deviceId,
path: input.path,
userId: ctx.userId,
workingDirectory: input.workingDirectory,
- }),
- ),
+ });
+ }),
/**
* Check whether a path exists on a remote device and is a directory, via the
diff --git a/apps/server/src/routers/lambda/deviceWorkspaceGuard.ts b/apps/server/src/routers/lambda/deviceWorkspaceGuard.ts
new file mode 100644
index 00000000000..7cac680ddbe
--- /dev/null
+++ b/apps/server/src/routers/lambda/deviceWorkspaceGuard.ts
@@ -0,0 +1,52 @@
+import { TRPCError } from '@trpc/server';
+
+import type { DeviceModel } from '@/database/models/device';
+import { isPathWithinRoot } from '@/server/services/deviceGateway';
+
+/**
+ * Validate that a client-supplied workspace root is actually one the user has
+ * bound to this device.
+ *
+ * The file routes (move / rename / write / preview) receive `workingDirectory`
+ * from the same untrusted browser session that supplies the file paths. The
+ * gateway's `assertPathsWithinWorkspace` only proves the paths sit *inside that
+ * directory* β€” it never proves the directory itself is legitimate. So a caller
+ * could set `workingDirectory` to `/` (or `C:\`), pass that containment check
+ * trivially, and reach any path on the device.
+ *
+ * To close that hole we re-derive the approved roots from the *server-owned*
+ * device row β€” the `workingDirs` recent list and `defaultCwd`, both written only
+ * via `device.updateDevice` / the run path, never trusted from this request β€”
+ * and require the requested root to equal or nest inside one of them before any
+ * RPC is forwarded. The picker upserts every chosen directory into `workingDirs`
+ * (see `useCommitWorkingDirectory`) and run start upserts the bound cwd, so a
+ * legitimately-selected workspace is always present here.
+ */
+export const assertWorkspaceRootApproved = async (
+ deviceModel: DeviceModel,
+ deviceId: string,
+ workingDirectory: string,
+): Promise<void> => {
+ if (!workingDirectory) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'A workspace root is required for file operations',
+ });
+ }
+
+ const device = await deviceModel.findByDeviceId(deviceId);
+
+ const approvedRoots = [
+ ...(device?.workingDirs ?? []).map((dir) => dir.path),
+ ...(device?.defaultCwd ? [device.defaultCwd] : []),
+ ].filter((root): root is string => Boolean(root));
+
+ const approved = approvedRoots.some((root) => isPathWithinRoot(root, workingDirectory));
+
+ if (!approved) {
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message: 'Working directory is not an approved workspace for this device',
+ });
+ }
+};
diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.ts
index a7e8cafc9cb..f1aa132e83d 100644
--- a/apps/server/src/services/deviceGateway/index.ts
+++ b/apps/server/src/services/deviceGateway/index.ts
@@ -50,7 +50,7 @@ const log = debug('lobe-server:device-gateway');
* path flavour from the root's shape so a Windows device path is still resolved
* with Windows semantics rather than being mangled by `path.posix`.
*/
-const isPathWithinRoot = (root: string, target: string): boolean => {
+export const isPathWithinRoot = (root: string, target: string): boolean => {
const p = /^[A-Z]:[/\\]/i.test(root) ? path.win32 : path.posix;
if (!p.isAbsolute(root) || !p.isAbsolute(target)) return false;
const relative = p.relative(p.resolve(root), p.resolve(target));