From c0176f92b93360390eba8e7e642b253d27a5129a Mon Sep 17 00:00:00 2001 From: fairy <3054158379@qq.com> Date: Wed, 2 Dec 2026 22:16:52 +0800 Subject: [PATCH] =?UTF-8?q?=E8=AE=A9=E6=89=8B=E6=9C=BA=E9=A2=84=E8=A7=88?= =?UTF-8?q?=E5=B7=A5=E4=BD=9C=E5=8C=BA=E9=87=8C=E7=9A=84=E7=94=9F=E6=88=90?= =?UTF-8?q?=E5=9B=BE=E7=89=87=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 会话列表没有工作目录,所以从已归属该会话的工作区读取,并拒绝越出工作区的路径。 Co-authored-by: Cursor --- .../desktop/mobile/mobile-rpc.ts | 23 +++++ .../desktop/mobile/mobile-session-image.ts | 92 +++++++++++++++++++ test/enterprise-mobile-rpc.test.ts | 50 ++++++++++ 3 files changed, 165 insertions(+) create mode 100644 packages/dsh-desktop-enterprise/desktop/mobile/mobile-session-image.ts diff --git a/packages/dsh-desktop-enterprise/desktop/mobile/mobile-rpc.ts b/packages/dsh-desktop-enterprise/desktop/mobile/mobile-rpc.ts index 4caf0d40..15d26f50 100644 --- a/packages/dsh-desktop-enterprise/desktop/mobile/mobile-rpc.ts +++ b/packages/dsh-desktop-enterprise/desktop/mobile/mobile-rpc.ts @@ -1,6 +1,7 @@ import { randomUUID } from 'node:crypto' import type { MobileProductTransport, MobileRpcResult } from '../../../../src/main/mobile/product-extension' import { isWorkRpcMethod, MobileWorkUploads, parseWorkDispatch, readUploadResult, readWorkEnvelope, readWorkJson } from './mobile-work-rpc' +import { readWorkspaceImage, workspaceDirectoryForSession } from './mobile-session-image' import { projectChangesSummary, projectMobileOfficeCatalog, projectMobilePpt, projectSessionList, projectSessionRow, projectLiveAssistantFrame, projectTranscriptFrame, projectTranscriptHistory } from './mobile-phone-view' const PERMISSION_PRESET_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/ @@ -16,6 +17,7 @@ export class EnterpriseMobileRpc { if (typeof input.method !== 'string' || input.method.startsWith('interaction.')) return undefined if (isWorkRpcMethod(input.method)) return this.forwardWork(input.method, input.payload ?? {}) if (input.method === 'session.changes') return this.forwardChanges(input.payload ?? {}) + if (input.method === 'session.image') return this.forwardSessionImage(input.payload ?? {}) if (['workspace.list','session.listPage','session.history','permission.current','permission.select','permission.catalog','session.list'].includes(input.method)) return this.forwardRpc(input.method, input.payload ?? {}, true) return undefined } @@ -362,6 +364,27 @@ private async forwardPermissionSelect( } return { ok: true, value: { preset } } } + + // session/list rows do not carry a workspace directory, so the image is read + // from the workspace snapshot path that already owns this session. + private async forwardSessionImage(payload: unknown): Promise { + const fields = isRecord(payload) ? payload : {} + const sessionId = typeof fields.sessionId === 'string' ? fields.sessionId.trim() : '' + const filePath = typeof fields.path === 'string' ? fields.path : '' + if (sessionId.length === 0 || filePath.trim().length === 0) { + return { ok: false, error: 'Image preview was not available.' } + } + const ready = await this.readyWorkspaceSnapshot() + if (!ready.ok) return ready + const root = workspaceDirectoryForSession(ready.value, sessionId) + if (root === undefined) return { ok: false, error: 'Image preview was not available.' } + try { + const image = await readWorkspaceImage(root, filePath) + return { ok: true, value: { image } } + } catch { + return { ok: false, error: 'Image preview was not available.' } + } + } } export function transcriptFollowValue( diff --git a/packages/dsh-desktop-enterprise/desktop/mobile/mobile-session-image.ts b/packages/dsh-desktop-enterprise/desktop/mobile/mobile-session-image.ts new file mode 100644 index 00000000..759d1961 --- /dev/null +++ b/packages/dsh-desktop-enterprise/desktop/mobile/mobile-session-image.ts @@ -0,0 +1,92 @@ +import { lstat, readFile, realpath } from 'node:fs/promises' +import path from 'node:path' + +const IMAGE_EXTENSIONS = new Set(['png', 'jpg', 'jpeg', 'gif', 'webp']) +const MAX_SOURCE_BYTES = 20 * 1024 * 1024 +const MAX_DATA_URL_CHARS = 600 * 1024 + +const SHRINK_STEPS = [ + { width: 1280, quality: 75 }, + { width: 960, quality: 60 }, + { width: 720, quality: 45 }, + { width: 480, quality: 30 } +] as const + +/** + * Workspace directory that owns [sessionId]. + * + * `session/list` does not include this directory. A row without a path, or a + * session that is not listed, cannot be read from disk. + */ +export function workspaceDirectoryForSession(snapshot: unknown, sessionId: string): string | undefined { + if (typeof snapshot !== 'object' || snapshot === null || Array.isArray(snapshot)) return undefined + const items = (snapshot as { items?: unknown }).items + if (!Array.isArray(items)) return undefined + for (const item of items) { + if (typeof item !== 'object' || item === null || Array.isArray(item)) continue + const row = item as { path?: unknown; sessionIds?: unknown } + if (typeof row.path !== 'string' || row.path.length === 0) continue + if (!Array.isArray(row.sessionIds) || !row.sessionIds.includes(sessionId)) continue + return row.path + } + return undefined +} + +/** Relative image path, or undefined when it leaves the workspace or is not an image. */ +export function relativeImagePath(value: unknown): string | undefined { + if (typeof value !== 'string') return undefined + const trimmed = value.trim() + if (trimmed.length === 0 || trimmed.length > 1024) return undefined + if (trimmed.includes('\0') || trimmed.includes(':')) return undefined + if (trimmed.startsWith('/') || trimmed.startsWith('\\') || trimmed.startsWith('~')) return undefined + const parts = trimmed.split(/[/\\]+/) + if (parts.some((part) => part.length === 0 || part === '.' || part === '..')) return undefined + const name = parts[parts.length - 1] + if (name === undefined) return undefined + const dot = name.lastIndexOf('.') + if (dot <= 0 || dot === name.length - 1) return undefined + const extension = name.slice(dot + 1).toLowerCase() + if (!IMAGE_EXTENSIONS.has(extension)) return undefined + return parts.join('/') +} + +/** + * One jpeg data URL for a file inside [root]. + * + * `..` and a symlink that resolves outside [root] are refused before the bytes + * are encoded. The result stays small enough for one gateway frame. + */ +export async function readWorkspaceImage(root: string, requested: string): Promise { + const relative = relativeImagePath(requested) + if (relative === undefined) throw new Error('Image path is not in the session workspace.') + const directory = await realpath(root) + const rootStat = await lstat(directory) + if (!rootStat.isDirectory()) throw new Error('Image path is not in the session workspace.') + const target = path.join(directory, ...relative.split('/')) + const resolved = await realpath(target) + const prefix = directory.endsWith(path.sep) ? directory : directory + path.sep + if (!resolved.startsWith(prefix)) throw new Error('Image path is not in the session workspace.') + const stat = await lstat(resolved) + if (!stat.isFile() || stat.size <= 0 || stat.size > MAX_SOURCE_BYTES) { + throw new Error('Image path is not in the session workspace.') + } + return shrinkSessionImage(await readFile(resolved)) +} + +async function shrinkSessionImage(bytes: Buffer): Promise { + const sharp = (await import('sharp')).default + for (const step of SHRINK_STEPS) { + const jpeg = await sharp(bytes, { + limitInputPixels: 64_000_000, + animated: false, + failOn: 'none' + }) + .rotate() + .resize({ width: step.width, height: step.width, fit: 'inside', withoutEnlargement: true }) + .jpeg({ quality: step.quality }) + .toBuffer() + const url = `data:image/jpeg;base64,${jpeg.toString('base64')}` + if (url.length <= MAX_DATA_URL_CHARS) return url + } + throw new Error('Image preview is too large.') +} diff --git a/test/enterprise-mobile-rpc.test.ts b/test/enterprise-mobile-rpc.test.ts index ad546d19..87f8e589 100644 --- a/test/enterprise-mobile-rpc.test.ts +++ b/test/enterprise-mobile-rpc.test.ts @@ -1,3 +1,6 @@ +import { mkdtemp, rm, symlink, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import path from 'node:path' import { expect, it, vi } from 'vitest' import { EnterpriseMobileRpc, pageMobileSessions, transcriptFollowValue } from '../packages/dsh-desktop-enterprise/desktop/mobile/mobile-rpc' @@ -149,3 +152,50 @@ it('forwards open/pinned ordering and pages ungrouped sessions independently', a expect(invalidCursor.items[0]?.sessionId).toBe('blank') adapter.dispose() }) + +it('returns one workspace image and refuses a document or a path that leaves the workspace', async () => { + const root = await mkdtemp(path.join(tmpdir(), 'session-image-')) + const outside = await mkdtemp(path.join(tmpdir(), 'session-image-out-')) + const jpeg = Buffer.from( + '/9j/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAABAAEDASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAj/xAAUEAEAAAAAAAAAAAAAAAAAAAAA/8QAFQEBAQAAAAAAAAAAAAAAAAAABAX/xAAUEQEAAAAAAAAAAAAAAAAAAAAA/9oADAMBAAIRAxEAPwCfAFEB/9k=', + 'base64' + ) + try { + await writeFile(path.join(root, 'photo.jpg'), jpeg) + await writeFile(path.join(outside, 'secret.png'), jpeg) + await symlink(path.join(outside, 'secret.png'), path.join(root, 'link.png')) + const invoke = vi.fn() + const adapter = new EnterpriseMobileRpc({ + port: () => 0, + channelToken: () => '', + request: vi.fn(), + invoke, + forward: vi.fn(async () => ({ + ok: true, + value: { items: [{ workspaceId: 'work', path: root, sessionIds: ['s1'] }] } + })) + }) + const opened = await adapter.dispatch({ + method: 'session.image', + payload: { sessionId: 's1', path: 'photo.jpg' } + }) + const image = (opened?.value as { image?: string } | undefined)?.image + expect(opened?.ok).toBe(true) + expect(image?.startsWith('data:image/jpeg;base64,')).toBe(true) + expect(invoke).not.toHaveBeenCalled() + for (const filePath of ['../secret.png', 'notes/a.docx', 'link.png', '/etc/photo.png']) { + expect((await adapter.dispatch({ + method: 'session.image', + payload: { sessionId: 's1', path: filePath } + }))?.ok).toBe(false) + } + expect((await adapter.dispatch({ + method: 'session.image', + payload: { sessionId: 'other', path: 'photo.jpg' } + }))?.ok).toBe(false) + adapter.dispose() + } finally { + await rm(root, { recursive: true, force: true }) + await rm(outside, { recursive: true, force: true }) + } +})