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(device): let members operate public workspace devices (#20814)

Rdmclin24c5ae4db15e8
diff --git a/apps/server/src/routers/lambda/__tests__/deviceAppUpdate.test.ts b/apps/server/src/routers/lambda/__tests__/deviceAppUpdate.test.ts
index 6b6a96b0691..63424008513 100644
--- a/apps/server/src/routers/lambda/__tests__/deviceAppUpdate.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/deviceAppUpdate.test.ts
@@ -100,7 +100,11 @@ describe('remote app update', () => {
beforeEach(() => {
vi.clearAllMocks();
- mocks.findWorkspaceDeviceById.mockResolvedValue({ deviceId: 'device', userId: 'enroller' });
+ mocks.findWorkspaceDeviceById.mockResolvedValue({
+ deviceId: 'device',
+ userId: 'enroller',
+ visibility: 'private',
+ });
mocks.installAppUpdate.mockResolvedValue({ status: 'ok', targetVersion: '2.2.0' });
});
diff --git a/apps/server/src/routers/lambda/__tests__/deviceOperate.test.ts b/apps/server/src/routers/lambda/__tests__/deviceOperate.test.ts
new file mode 100644
index 00000000000..60c684dfb5e
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/deviceOperate.test.ts
@@ -0,0 +1,101 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { deviceRouter } from '../device';
+
+const mocks = vi.hoisted(() => ({
+ browseDirectory: vi.fn(),
+ createTerminalSession: vi.fn(),
+ findWorkspaceDeviceById: vi.fn(),
+}));
+
+vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn() }));
+vi.mock('@/database/models/device', () => ({
+ DeviceModel: class {
+ findWorkspaceDeviceById = mocks.findWorkspaceDeviceById;
+ },
+}));
+vi.mock('@/server/services/deviceGateway', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ deviceGateway: {
+ browseDirectory: mocks.browseDirectory,
+ createTerminalSession: mocks.createTerminalSession,
+ },
+}));
+
+type Role = 'member' | 'owner' | 'viewer';
+
+const workspaceCaller = (userId: string, workspaceRole: Role) =>
+ deviceRouter.createCaller({ userId, workspaceId: 'workspace', workspaceRole } as never);
+
+const withDevice = (visibility: 'private' | 'public') =>
+ mocks.findWorkspaceDeviceById.mockResolvedValue({
+ deviceId: 'device',
+ userId: 'enroller',
+ visibility,
+ });
+
+const operate = {
+ browseDirectory: (userId: string, role: Role) =>
+ workspaceCaller(userId, role).browseDirectory({ deviceId: 'device', path: '/home' }),
+ createTerminalSession: (userId: string, role: Role) =>
+ workspaceCaller(userId, role).createTerminalSession({ cols: 80, deviceId: 'device', rows: 24 }),
+};
+
+describe('operating a workspace device', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.browseDirectory.mockResolvedValue({ entries: [] });
+ mocks.createTerminalSession.mockResolvedValue({ sessionId: 'session' });
+ });
+
+ it.each(Object.keys(operate) as (keyof typeof operate)[])(
+ 'lets any member %s on a public device',
+ async (procedure) => {
+ withDevice('public');
+ await expect(operate[procedure]('member', 'member')).resolves.toBeTruthy();
+ expect(mocks[procedure]).toHaveBeenCalledWith(
+ expect.objectContaining({ deviceId: 'device', userId: 'member', workspaceId: 'workspace' }),
+ );
+ },
+ );
+
+ it.each(Object.keys(operate) as (keyof typeof operate)[])(
+ "rejects %s from a member on someone else's private device",
+ async (procedure) => {
+ withDevice('private');
+ await expect(operate[procedure]('member', 'member')).rejects.toMatchObject({
+ code: 'FORBIDDEN',
+ });
+ expect(mocks[procedure]).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each(Object.keys(operate) as (keyof typeof operate)[])(
+ 'rejects %s from a read-only viewer even on a public device',
+ async (procedure) => {
+ withDevice('public');
+ await expect(operate[procedure]('viewer', 'viewer')).rejects.toMatchObject({
+ code: 'FORBIDDEN',
+ message: expect.stringContaining('Workspace viewers cannot'),
+ });
+ expect(mocks[procedure]).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each([
+ ['enroller', 'member'],
+ ['owner', 'owner'],
+ ] as const)('lets the %s browse a private device', async (userId, role) => {
+ withDevice('private');
+ await expect(operate.browseDirectory(userId, role)).resolves.toEqual({ entries: [] });
+ });
+
+ it('keeps hiding devices the caller cannot see', async () => {
+ mocks.findWorkspaceDeviceById.mockResolvedValue(undefined);
+ await expect(operate.browseDirectory('member', 'member')).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
+ expect(mocks.browseDirectory).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/routers/lambda/device.ts b/apps/server/src/routers/lambda/device.ts
index 6e793bdc3d6..c76295332da 100644
--- a/apps/server/src/routers/lambda/device.ts
+++ b/apps/server/src/routers/lambda/device.ts
@@ -64,9 +64,10 @@ const SCAN_TIMEOUT_MS = 10_000;
* else's enrollment, while shared cleanup remains an owner action.
*/
/**
- * Gate an action that operates the machine itself β€” exposing a port, updating
- * its app β€” the same way `browseDirectory` gates new paths: on a workspace
- * device, only the enrolling member or a workspace owner.
+ * Gate an action that operates the machine itself β€” browsing folders, a
+ * terminal, exposing a port, updating its app. A public workspace device is
+ * shared infra every member works on, so any member may operate it; a private
+ * one stays limited to the enrolling member or a workspace owner.
*/
const assertDeviceOperable = async (
ctx: {
@@ -82,10 +83,13 @@ const assertDeviceOperable = async (
const row = await ctx.deviceModel.findWorkspaceDeviceById(deviceId);
if (!row) throw new TRPCError({ code: 'NOT_FOUND', message: 'Workspace device not found.' });
- if (!canEditWorkspaceDevice(ctx.workspaceRole, ctx.userId, row.userId)) {
+ if (!canOperateWorkspaceDevice(ctx.workspaceRole, ctx.userId, row)) {
throw new TRPCError({
code: 'FORBIDDEN',
- message: `Only the enrolling member or a workspace owner can ${action} on this device.`,
+ message:
+ row.visibility === 'public'
+ ? `Workspace viewers cannot ${action} on this device.`
+ : `Only the enrolling member or a workspace owner can ${action} on this private device.`,
});
}
};
@@ -139,6 +143,19 @@ const canEditWorkspaceDevice = (
enrollerUserId: string,
): boolean => role === 'owner' || enrollerUserId === actorUserId;
+/**
+ * Using a workspace device (as opposed to editing its registration) is open to
+ * every member once it is public; read-only viewers never operate a machine.
+ * See {@link assertDeviceOperable}.
+ */
+const canOperateWorkspaceDevice = (
+ role: WorkspaceRole | undefined,
+ actorUserId: string,
+ row: { userId: string; visibility: 'private' | 'public' },
+): boolean =>
+ (row.visibility === 'public' && !!role && role !== 'viewer') ||
+ canEditWorkspaceDevice(role, actorUserId, row.userId);
+
/**
* Fixed workspace agents promise every member the same execution device. Keep
* that promise intact until an editor changes the agent back to member choice
@@ -817,8 +834,7 @@ export const deviceRouter = router({
/**
* Browse one directory level on a remote device. Personal devices belong to
- * the caller. A workspace device may expose new paths only to its enroller or
- * a workspace owner; other members continue to use its approved recents.
+ * the caller; workspace devices follow {@link assertDeviceOperable}.
*/
browseDirectory: deviceProcedure
.input(
@@ -830,19 +846,7 @@ export const deviceRouter = router({
}),
)
.query(async ({ ctx, input }) => {
- if (ctx.workspaceId) {
- const row = await ctx.deviceModel.findWorkspaceDeviceById(input.deviceId);
- if (!row) {
- throw new TRPCError({ code: 'NOT_FOUND', message: 'Workspace device not found.' });
- }
- const role = (ctx as { workspaceRole?: WorkspaceRole }).workspaceRole;
- if (!canEditWorkspaceDevice(role, ctx.userId, row.userId)) {
- throw new TRPCError({
- code: 'FORBIDDEN',
- message: 'Only the enrolling member or a workspace owner can browse this device.',
- });
- }
- }
+ await assertDeviceOperable(ctx, input.deviceId, 'browse folders');
const result = await deviceGateway.browseDirectory({
cursor: input.cursor,
diff --git a/src/features/DeviceManager/DeviceDetailPanel.tsx b/src/features/DeviceManager/DeviceDetailPanel.tsx
index 75733f7caef..3387b02e60c 100644
--- a/src/features/DeviceManager/DeviceDetailPanel.tsx
+++ b/src/features/DeviceManager/DeviceDetailPanel.tsx
@@ -33,7 +33,7 @@ import DeviceHealth, { HealthLegend } from './DeviceHealth';
import FieldLabel from './FieldLabel';
import { getDeviceIcon } from './getDeviceIcon';
import PresenceDot from './PresenceDot';
-import { useCanEditDevice } from './useCanEditDevice';
+import { useCanEditDevice, useCanOperateDevice } from './useCanEditDevice';
const styles = createStaticStyles(({ css }) => ({
// Fills whatever host it lands in: inside a page-level rail the height is
@@ -106,6 +106,7 @@ interface DeviceDetailPanelProps {
const DeviceDetailPanel = memo<DeviceDetailPanelProps>(({ device, isCurrent, onClose }) => {
const { t } = useTranslation(['setting', 'device']);
const canEdit = useCanEditDevice()(device);
+ const canOperate = useCanOperateDevice()(device);
// Health monitoring and the directory settings are separate jobs; a tab each
// keeps the charts from pushing the directories below the fold.
const [tab, setTab] = useState<DetailTab>('overview');
@@ -365,7 +366,7 @@ const DeviceDetailPanel = memo<DeviceDetailPanelProps>(({ device, isCurrent, onC
)}
{/* ─── Connections, each with its client version; desktop carries the update ─── */}
- <Connections canEdit={canEdit} device={device} />
+ <Connections canEdit={canOperate} device={device} />
{/* ─── Machine health ─── */}
<Flexbox gap={8}>
diff --git a/src/features/DeviceManager/useCanEditDevice.test.ts b/src/features/DeviceManager/useCanEditDevice.test.ts
index a985daf22aa..cfcd22a42f8 100644
--- a/src/features/DeviceManager/useCanEditDevice.test.ts
+++ b/src/features/DeviceManager/useCanEditDevice.test.ts
@@ -5,20 +5,25 @@ import type { DeviceEnroller, DeviceListItem, DeviceScope } from '@lobechat/type
import { renderHook } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { useCanEditDevice } from './useCanEditDevice';
+import { useCanEditDevice, useCanOperateDevice } from './useCanEditDevice';
// Mocks live inside `hoisted` so the `vi.mock` factories below can reach
// them β€” vi.mock is hoisted above imports, and only `vi.hoisted` survives that.
const mocks = vi.hoisted(() => {
const userState = { userId: 'current-user-id' as string | undefined };
const isOwner = { current: false };
- return { isOwner, userState };
+ const isViewer = { current: false };
+ return { isOwner, isViewer, userState };
});
vi.mock('@/business/client/hooks/useIsWorkspaceOwner', () => ({
useIsWorkspaceOwner: () => mocks.isOwner.current,
}));
+vi.mock('@/business/client/hooks/useIsWorkspaceViewer', () => ({
+ useIsWorkspaceViewer: () => mocks.isViewer.current,
+}));
+
vi.mock('@/store/user', () => ({
useUserStore: <T>(selector: (state: typeof mocks.userState) => T): T => selector(mocks.userState),
}));
@@ -38,7 +43,9 @@ const buildEnroller = (userId: string): DeviceEnroller => ({
const buildDevice = (overrides: {
enroller?: DeviceEnroller | null;
+ registered?: boolean;
scope: DeviceScope;
+ visibility?: 'private' | 'public';
}): DeviceListItem => ({
channels: [],
defaultCwd: null,
@@ -50,9 +57,9 @@ const buildDevice = (overrides: {
lastSeen: new Date(0).toISOString(),
online: false,
platform: null,
- registered: true,
+ registered: overrides.registered ?? true,
scope: overrides.scope,
- visibility: overrides.scope === 'workspace' ? 'public' : null,
+ visibility: overrides.scope === 'workspace' ? (overrides.visibility ?? 'public') : null,
workingDirs: [],
});
@@ -132,3 +139,64 @@ describe('useCanEditDevice', () => {
});
});
});
+
+describe('useCanOperateDevice', () => {
+ beforeEach(() => {
+ mocks.userState.userId = 'current-user-id';
+ mocks.isOwner.current = false;
+ mocks.isViewer.current = false;
+ });
+
+ it('keeps a read-only viewer off a public workspace device', () => {
+ mocks.isViewer.current = true;
+ const { result } = renderHook(() => useCanOperateDevice());
+ expect(
+ result.current(
+ buildDevice({ enroller: buildEnroller('other-member-id'), scope: 'workspace' }),
+ ),
+ ).toBe(false);
+ });
+
+ it('lets any member operate a public workspace device', () => {
+ const { result } = renderHook(() => useCanOperateDevice());
+ expect(
+ result.current(
+ buildDevice({ enroller: buildEnroller('other-member-id'), scope: 'workspace' }),
+ ),
+ ).toBe(true);
+ });
+
+ it('keeps another member’s private device off-limits', () => {
+ const { result } = renderHook(() => useCanOperateDevice());
+ expect(
+ result.current(
+ buildDevice({
+ enroller: buildEnroller('other-member-id'),
+ scope: 'workspace',
+ visibility: 'private',
+ }),
+ ),
+ ).toBe(false);
+ });
+
+ it('is fail-closed on an unregistered public row', () => {
+ const { result } = renderHook(() => useCanOperateDevice());
+ expect(
+ result.current(buildDevice({ enroller: null, registered: false, scope: 'workspace' })),
+ ).toBe(false);
+ });
+
+ it('falls back to edit rights for the enroller and personal devices', () => {
+ const { result } = renderHook(() => useCanOperateDevice());
+ expect(result.current(buildDevice({ scope: 'personal' }))).toBe(true);
+ expect(
+ result.current(
+ buildDevice({
+ enroller: buildEnroller('current-user-id'),
+ scope: 'workspace',
+ visibility: 'private',
+ }),
+ ),
+ ).toBe(true);
+ });
+});
diff --git a/src/features/DeviceManager/useCanEditDevice.ts b/src/features/DeviceManager/useCanEditDevice.ts
index c2c497000d3..96dc97a090b 100644
--- a/src/features/DeviceManager/useCanEditDevice.ts
+++ b/src/features/DeviceManager/useCanEditDevice.ts
@@ -2,6 +2,7 @@ import type { DeviceListItem } from '@lobechat/types';
import { useCallback } from 'react';
import { useIsWorkspaceOwner } from '@/business/client/hooks/useIsWorkspaceOwner';
+import { useIsWorkspaceViewer } from '@/business/client/hooks/useIsWorkspaceViewer';
import { useUserStore } from '@/store/user';
import { userProfileSelectors } from '@/store/user/selectors';
@@ -37,3 +38,25 @@ export const useCanEditDevice = () => {
[isOwner, currentUserId],
);
};
+
+/**
+ * Predicate for "can the current user operate this machine?" β€” update its app
+ * or CLI, open a terminal, browse folders. Mirrors the server-side
+ * `canOperateWorkspaceDevice` gate: a public workspace device is shared infra
+ * every member works on, so any non-viewer member may operate it; otherwise it
+ * falls back to {@link useCanEditDevice}.
+ */
+export const useCanOperateDevice = () => {
+ const canEdit = useCanEditDevice();
+ const isViewer = useIsWorkspaceViewer();
+
+ return useCallback(
+ (device: DeviceListItem): boolean =>
+ (!isViewer &&
+ device.scope === 'workspace' &&
+ device.registered &&
+ device.visibility === 'public') ||
+ canEdit(device),
+ [canEdit, isViewer],
+ );
+};