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
23 changes: 23 additions & 0 deletions packages/dsh-desktop-enterprise/desktop/mobile/mobile-rpc.ts
Original file line number Diff line number Diff line change
@@ -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]+)*$/

Expand All @@ -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
}
Expand Down Expand Up @@ -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<MobileRpcResult> {
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(
Expand Down
Original file line number Diff line number Diff line change
@@ -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<string> {
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<string> {
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.')
}
50 changes: 50 additions & 0 deletions test/enterprise-mobile-rpc.test.ts
Original file line number Diff line number Diff line change
@@ -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'

Expand Down Expand Up @@ -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 })
}
})
Loading