The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(webapp): keep the session token out of a failed image's link
dokterdokaf8882d4ec94
diff --git a/apps/desktop/src/components/chat/generated-image-open.test.tsx b/apps/desktop/src/components/chat/generated-image-open.test.tsxindex 76949054e5e..07ccdc14d4a 100644--- a/apps/desktop/src/components/chat/generated-image-open.test.tsx+++ b/apps/desktop/src/components/chat/generated-image-open.test.tsx@@ -3,13 +3,24 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest'import type { HermesConnection } from '@/global'import { I18nProvider } from '@/i18n'-import { $connection } from '@/store/session'+import { createBrowserFilesBridge } from '@/lib/browser-files'+import type { BrowserBootstrap } from '@/lib/browser-transport'+import { $notifications } from '@/store/notifications'+import { $connection, $selectedStoredSessionId, $sessions } from '@/store/session'+import type { SessionInfo } from '@/types/hermes'import { GeneratedImage } from './generated-image-result'-// The image never loads, so the card collapses to its "Open image" link.+// The image never loads, so the card collapses to its "Open image" link. An inline source stays its+// own src, as in the real hook.vi.mock('@/hooks/use-media-image', () => ({- useMediaImage: () => ({ failed: true, frameStyle: {}, key: 'k', loaded: false, src: '' })+ useMediaImage: (path: string) => ({+ failed: true,+ frameStyle: {},+ key: 'k',+ loaded: false,+ src: /^(?:https?|data):/i.test(path) ? path : ''+ })}))const openExternal = vi.fn()@@ -24,6 +35,10 @@ afterEach(() => {cleanup()vi.clearAllMocks()$connection.set(null)+ $sessions.set([])+ $selectedStoredSessionId.set(null)+ $notifications.set([])+ window.document.documentElement.removeAttribute('data-hermes-desktop-host')delete (window as unknown as { hermesDesktop?: unknown }).hermesDesktop})@@ -38,9 +53,29 @@ function openImageLink(image: string) {}// A remote gateway's file URL carries the connection token. Handed to the-// system browser it would sit in that browser's history, so native Desktop-// saves the file through the bridge's save dialog instead.-it('saves a remote gateway image through the save dialog in native Desktop, never opening its tokened URL', async () => {+// system browser it would sit in that browser's history, so the image saves+// through the bridge instead (native Desktop's save dialog). A relative path+// saves there too, on both hosts, from the chat's own working directory: this+// gateway runs from /srv/gateway, and the chat ran on its `work` profile in+// /srv/project.+const SESSION_CWDS: Record<string, string> = { 'work/origin-session': '/srv/project' }++it.each([+ ['electron', '/srv/hermes/images/cat.png', 'cat.png', '/srv/hermes/images/cat.png'],+ ['electron', 'renders/out.png', 'out.png', '/srv/project/renders/out.png'],+ ['browser', 'renders/out.png', 'out.png', '/srv/project/renders/out.png']+])('saves a gateway image through the %s bridge (%s), never opening its tokened URL', async (host, image, name, saved) => {+ // Resolves like /api/fs/download: in the named session's cwd, else in the gateway's own.+ saveGatewayFile.mockImplementation(async ({ path, profile, sessionId }) => {+ const cwd = sessionId ? SESSION_CWDS[`${profile}/${sessionId}`] : '/srv/gateway'++ if (!cwd) {+ throw new Error('404: Session not found')+ }++ return { path: path.startsWith('/') ? path : `${cwd}/${path}`, saved: true }+ })+ window.document.documentElement.dataset.hermesDesktopHost = host$connection.set({baseUrl: 'https://gateway.example',connectionId: 'remote-1',@@ -48,15 +83,20 @@ it('saves a remote gateway image through the save dialog in native Desktop, neveprofile: 'default',token: 'secret-token'} as unknown as HermesConnection)+ $sessions.set([{ id: 'origin-session', profile: 'work' } as SessionInfo])+ $selectedStoredSessionId.set('origin-session')- const link = openImageLink('/srv/hermes/images/cat.png')+ const link = openImageLink(image)await act(async () => {fireEvent.click(link)})- expect(saveGatewayFile).toHaveBeenCalledWith(- expect.objectContaining({ connectionId: 'remote-1', path: '/srv/hermes/images/cat.png', suggestedName: 'cat.png' })+ await vi.waitFor(() =>+ expect(saveGatewayFile).toHaveBeenCalledWith(+ expect.objectContaining({ connectionId: 'remote-1', path: image, suggestedName: name })+ ))+ await expect(saveGatewayFile.mock.results[0]!.value).resolves.toEqual({ path: saved, saved: true })expect(JSON.stringify(saveGatewayFile.mock.calls)).not.toContain('secret-token')expect(openExternal).not.toHaveBeenCalled()})@@ -73,3 +113,38 @@ it('opens a web image\'s URL with the system handler in native Desktop', async (expect(openExternal).toHaveBeenCalledWith('https://images.example/cat.png')expect(saveGatewayFile).not.toHaveBeenCalled()})++// A data: image (a plugin backend's HEIC, say, that this renderer cannot decode) carries its own+// bytes: it saves them, on both hosts. As a gateway link it would hand the connection token to the+// system browser, and the Webapp cannot open one at all.+it.each(['electron', 'browser'])('saves a data: image that will not decode in %s, never opening a link', async host => {+ const image = 'data:image/png;base64,AAAA'+ const clicked: string[] = []+ vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (this: HTMLAnchorElement) {+ clicked.push(this.href)+ })++ const saveImageFromUrl =+ host === 'browser'+ ? vi.fn(+ createBrowserFilesBridge({ api: vi.fn(), bootstrap: {} as BrowserBootstrap, currentProfile: () => null })+ .saveImageFromUrl+ )+ : vi.fn().mockResolvedValue(true)++ ;(window as unknown as { hermesDesktop: object }).hermesDesktop = { openExternal, saveGatewayFile, saveImageFromUrl }+ window.document.documentElement.dataset.hermesDesktopHost = host+ $connection.set({ baseUrl: 'https://gateway.example', mode: 'remote', token: 'secret-token' } as unknown as HermesConnection)++ const link = openImageLink(image)+ await act(async () => {+ fireEvent.click(link)+ })++ expect(JSON.stringify(openExternal.mock.calls)).not.toContain('secret-token')+ expect(openExternal).not.toHaveBeenCalled()+ await vi.waitFor(() => expect(saveImageFromUrl).toHaveBeenCalledWith(image))+ expect(saveGatewayFile).not.toHaveBeenCalled()+ await vi.waitFor(() => expect($notifications.get().map(({ title }) => title)).toContain('Image saved'))+ expect(clicked).toEqual(host === 'browser' ? [image] : [])+})diff --git a/apps/desktop/src/components/chat/generated-image-result.tsx b/apps/desktop/src/components/chat/generated-image-result.tsxindex 0aeca92b7ed..6fac1db33f4 100644--- a/apps/desktop/src/components/chat/generated-image-result.tsx+++ b/apps/desktop/src/components/chat/generated-image-result.tsx@@ -1,7 +1,10 @@'use client'+import { useStore } from '@nanostores/react'import { type FC, useState } from 'react'+import { useSessionView } from '@/app/chat/session-view'+import { resolveSessionOwner } from '@/app/session/hooks/use-session-actions/utils'import { DiffusionCanvas } from '@/components/chat/image-generation-placeholder'import { ImageActionButton, ImageLightbox } from '@/components/chat/zoomable-image'import { useImageDownload } from '@/hooks/use-image-download'@@ -10,13 +13,16 @@ import { useI18n } from '@/i18n'import { generatedImageDimensionsFromResult, generatedImageFromResult } from '@/lib/generated-images'import {downloadGatewayMediaFile,+ type GatewayFileOrigin,isFileMediaPath,+ isInlineMediaSrc,isRemoteGateway,mediaExternalUrl,mediaName} from '@/lib/media'import { cn } from '@/lib/utils'import { notifyError } from '@/store/notifications'+import { profileScopeForSessionOwner } from '@/store/session-request-router'// A hint is only a placeholder shape, not a promise about the delivered image.const ASPECT_HINTS: Record<string, number> = {@@ -35,6 +41,21 @@ function hintedRatio(aspectRatio?: string): number {)}+/** A relative path names a file in the producing session's working directory, on its profile. The+ * gateway resolves it there only for a save that names that session, and in its own cwd otherwise. */+async function sessionFileOrigin(storedSessionId: null | string): Promise<GatewayFileOrigin> {+ if (!storedSessionId) {+ throw new Error('No session to resolve a relative image path in')+ }++ const scope = profileScopeForSessionOwner(await resolveSessionOwner(storedSessionId))++ return {+ sessionId: storedSessionId,+ ...(typeof scope === 'string' ? { profile: scope } : scope ? { owner: scope } : {})+ }+}+export const GeneratedImage: FC<{ aspectRatio?: string; result?: unknown }> = ({ aspectRatio, result }) => {const { t } = useI18n()const copy = t.desktop@@ -49,6 +70,7 @@ export const GeneratedImage: FC<{ aspectRatio?: string; result?: unknown }> = ({const [canvasGone, setCanvasGone] = useState<string | null>(null)const [lightboxOpen, setLightboxOpen] = useState<string | null>(null)const { download, saving } = useImageDownload(src)+ const storedSessionId = useStore(useSessionView().$storedId)// Completed but no usable image (generation failed): the agent's prose carries// the explanation, so render nothing here.@@ -67,9 +89,18 @@ export const GeneratedImage: FC<{ aspectRatio?: string; result?: unknown }> = ({// A gateway file saves through the host bridge, like every other// remote media open: its URL form carries the connection token,- // which must never land in a browser's history.- if (isRemoteGateway() && isFileMediaPath(image)) {+ // which must never land in a browser's history. A relative path+ // saves through it too, from the chat's own working directory,+ // which only a save naming that session resolves it in. A data:+ // image carries its own bytes and saves them, as its download button does.+ if (/^data:/i.test(image)) {+ void download()+ } else if (isRemoteGateway() && isFileMediaPath(image)) {void downloadGatewayMediaFile(image).catch(error => notifyError(error, copy.imageDownloadFailed))+ } else if (isRemoteGateway() && !isInlineMediaSrc(image)) {+ void sessionFileOrigin(storedSessionId)+ .then(origin => downloadGatewayMediaFile(image, origin))+ .catch(error => notifyError(error, copy.imageDownloadFailed))} else {void window.hermesDesktop?.openExternal(mediaExternalUrl(image))}diff --git a/apps/desktop/src/lib/media.remote.test.ts b/apps/desktop/src/lib/media.remote.test.tsindex ddbe284237d..cc044733ec9 100644--- a/apps/desktop/src/lib/media.remote.test.ts+++ b/apps/desktop/src/lib/media.remote.test.ts@@ -47,6 +47,15 @@ describe('mediaExternalUrl', () => {expect(mediaExternalUrl('https://example.com/a.png')).toBe('https://example.com/a.png')})+ // Their bytes are in the URL itself, never a gateway path, so none of them gets a tokened link.+ it('passes through data: and blob: URLs untouched', () => {+ $connection.set({ mode: 'remote', baseUrl: 'https://gw', token: 'SECRET' } as never)++ for (const url of ['data:image/png;base64,AAAA', 'blob:https://app.example/3f1c']) {+ expect(mediaExternalUrl(url)).toBe(url)+ }+ })+it('keeps file:// form in local mode', () => {$connection.set({ mode: 'local' } as never)expect(mediaExternalUrl('/tmp/a.png')).toBe('file:///tmp/a.png')@@ -72,6 +81,21 @@ describe('mediaExternalUrl', () => {expect(new URL(mediaExternalUrl('file://nas/share/a.png')).searchParams.get('path')).toBe('\\\\nas\\share\\a.png')})+ // #93508 item 5: the browser-hosted Desktop's session token grants host shells. Its gateway files+ // save through the ticketed bridge, so no URL built here may carry that token.+ it('never puts the browser-hosted Desktop session token into a URL', () => {+ document.documentElement.dataset.hermesDesktopHost = 'browser'+ $connection.set({ mode: 'remote', baseUrl: 'http://127.0.0.1:9119', token: 'SECRET' } as never)++ try {+ for (const path of ['/home/me/report.pdf', 'file:///tmp/a.png', 'out/render.png']) {+ expect(mediaExternalUrl(path)).not.toContain('SECRET')+ }+ } finally {+ document.documentElement.removeAttribute('data-hermes-desktop-host')+ }+ })+it('falls back to file:// when remote connection lacks a token', () => {$connection.set({ mode: 'remote', baseUrl: 'https://gw' } as never)expect(mediaExternalUrl('/tmp/a.png')).toBe('file:///tmp/a.png')diff --git a/apps/desktop/src/lib/media.ts b/apps/desktop/src/lib/media.tsindex 642b5d5b8a7..a72cd7c9121 100644--- a/apps/desktop/src/lib/media.ts+++ b/apps/desktop/src/lib/media.ts@@ -271,15 +271,19 @@ export async function resolveMediaPlaybackSrc(path: string, owner?: OwnerScope,// Resolve a media path to a URL the shell can open. Remote mode rewrites// gateway-local paths to an authenticated /api/files/download URL (the file// lives on the gateway, not this disk); local mode keeps the file:// form.+// The browser-hosted Desktop's token grants host shells and never enters a+// URL: its gateway files save through the ticketed bridge+// (downloadGatewayMediaFile) instead. A data: or blob: URL is no gateway+// path: it stays as it is, on every host.export function mediaExternalUrl(path: string): string {- if (/^https?:/i.test(path)) {+ if (/^(?:https?|data|blob):/i.test(path)) {return path}if (isRemoteGateway()) {const conn = $connection.get()- if (conn?.baseUrl && conn.token) {+ if (conn?.baseUrl && conn.token && !isBrowserHostedDesktop()) {const file = encodeURIComponent(filePathFromMediaPath(path))return `${conn.baseUrl}/api/files/download?path=${file}&token=${encodeURIComponent(conn.token)}`