From a1c08b71287257d7e279e08765cbbc2d1c025fc6 Mon Sep 17 00:00:00 2001 From: hsien wei Date: Mon, 2 Nov 2026 15:41:34 +0800 Subject: [PATCH 1/2] fix(markdown): decode local image and link paths before reading disk - Decode each Markdown URL path segment exactly once before resolving workspace paths - Share the decoder between local images and relative Markdown links - Refuse malformed escapes and encoded separators without falling back to the raw path - Treat a leading slash in Markdown links as the workspace root, matching images - Judge disk paths by their real file name so `#` and `?` stay part of the name - Stamp image MIME from the disk file name instead of the full absolute path - Restrict image MIME lookup to the table's own extension keys - Settle synchronous image read failures into the visible error state - Show localized chip notes when a local image source is refused - Cover parser output, same-name collisions, and disk MIME cases in tests --- src/main/fs.ts | 4 +- src/renderer/src/hooks/useWorkspaceImage.ts | 23 +- src/renderer/src/i18n/locales/ar.json | 8 + src/renderer/src/i18n/locales/de.json | 8 + src/renderer/src/i18n/locales/en.json | 8 + src/renderer/src/i18n/locales/es.json | 8 + src/renderer/src/i18n/locales/fr.json | 8 + src/renderer/src/i18n/locales/it.json | 8 + src/renderer/src/i18n/locales/ja.json | 8 + src/renderer/src/i18n/locales/ko.json | 8 + src/renderer/src/i18n/locales/pt-BR.json | 8 + src/renderer/src/i18n/locales/tr.json | 8 + src/renderer/src/i18n/locales/zh-CN.json | 8 + src/renderer/src/ide/IdePanel.tsx | 8 +- src/renderer/src/ide/ImagePreview.tsx | 2 +- src/renderer/src/markdown/MarkdownPreview.tsx | 43 +++- src/renderer/src/markdown/mdLinks.ts | 136 +++++++++- src/shared/imageTypes.ts | 91 ++++++- test/ide-image.test.cjs | 242 +++++++++++++++++- 19 files changed, 588 insertions(+), 49 deletions(-) diff --git a/src/main/fs.ts b/src/main/fs.ts index 84a2ec24f3..d065fe207d 100644 --- a/src/main/fs.ts +++ b/src/main/fs.ts @@ -3,7 +3,7 @@ import type { FileHandle } from 'node:fs/promises'; import { constants } from 'node:fs'; import { basename, dirname, isAbsolute, join, normalize, relative, resolve, sep } from 'node:path'; import { homedir } from 'node:os'; -import { imageMimeForPath } from '../shared/imageTypes'; +import { imageMimeForDiskPath } from '../shared/imageTypes'; /** * Lexical containment — pure string math, no filesystem access. @@ -261,7 +261,7 @@ export async function readFileBinary(root: string, rel: string, maxBytes = MAX_B return { ok: true, bytes, - mime: imageMimeForPath(abs) ?? 'application/octet-stream', + mime: imageMimeForDiskPath(abs) ?? 'application/octet-stream', path: abs, size: s.size }; diff --git a/src/renderer/src/hooks/useWorkspaceImage.ts b/src/renderer/src/hooks/useWorkspaceImage.ts index 677e117866..3ef5b24c59 100644 --- a/src/renderer/src/hooks/useWorkspaceImage.ts +++ b/src/renderer/src/hooks/useWorkspaceImage.ts @@ -31,6 +31,27 @@ export type WorkspaceImageState = | { status: 'ready'; url: string; mime: string; size: number } | { status: 'error'; error: string }; +/** What one `fs:readBinary` round trip settles to. */ +export type WorkspaceImageRead = Awaited>; + +/** + * Run one image read so that EVERY failure comes back as `{ ok: false, error }` + * — never as a throw. + * + * A trailing `.catch()` only sees a REJECTED promise. A read that throws while + * being CALLED (the preload bridge missing, or throwing before it returns a + * promise) escapes it, and inside an effect that exception unmounts the whole + * preview through the error boundary instead of turning one image into a chip. + * Taking a thunk puts the call itself inside the `try`. + */ +export async function settleImageRead(read: () => Promise): Promise { + try { + return await read(); + } catch (e) { + return { ok: false, error: e instanceof Error ? e.message : String(e) }; + } +} + export function useWorkspaceImage( root: string | null | undefined, rel: string | null | undefined @@ -46,7 +67,7 @@ export function useWorkspaceImage( let created: string | null = null; setState({ status: 'loading' }); - void window.cth.readBinary(root, rel).then((res) => { + void settleImageRead(() => window.cth.readBinary(root, rel)).then((res) => { // Bail BEFORE creating the URL when the consumer already unmounted — a URL // created after cleanup has run would never be revoked by anyone. if (!alive) return; diff --git a/src/renderer/src/i18n/locales/ar.json b/src/renderer/src/i18n/locales/ar.json index f4ba06cde1..6976044297 100644 --- a/src/renderer/src/i18n/locales/ar.json +++ b/src/renderer/src/i18n/locales/ar.json @@ -2437,5 +2437,13 @@ "usageNotice": { "telemetryOff": "تم إيقافه لأن عدّ الرموز الخاص به متوقف. احذف CLAUDE_CODE_ENABLE_TELEMETRY وأي إعدادات OTEL_ من قسم env في ‎~/.claude/settings.json ومن الأمر الذي يشغّله، ثم شغّله مرة أخرى. إذا كانت مؤسستك تدير إعدادات Claude Code لديك، فاسأل المسؤول.", "engineNotCounted": "في الخطة المجانية لا يمكن تشغيل هذا المحرك بعد، لأن التطبيق لا يستطيع عدّ رموزه. تعمل Claude وCodex وAntigravity وGrok وQwen وCrush، وتفتح Pro أو Max كل المحركات." + }, + "markdownImage": { + "untitled": "صورة", + "notImage": "ليس نوع صورة مدعومًا", + "malformedEncoding": "يحتوي المسار على ترميز % غير صالح", + "unsafeSegment": "يُرمّز المسار فاصلًا أو ..", + "loading": "جارٍ التحميل", + "decodeFailed": "تعذّر فك الترميز" } } diff --git a/src/renderer/src/i18n/locales/de.json b/src/renderer/src/i18n/locales/de.json index bb650afcdd..53003cae9d 100644 --- a/src/renderer/src/i18n/locales/de.json +++ b/src/renderer/src/i18n/locales/de.json @@ -2437,5 +2437,13 @@ "usageNotice": { "telemetryOff": "Er wurde gestoppt, weil seine Token Zählung ausgeschaltet ist. Entferne CLAUDE_CODE_ENABLE_TELEMETRY und alle OTEL_ Einstellungen aus dem env Block von ~/.claude/settings.json und aus dem Befehl, der ihn startet, und starte ihn dann neu. Wenn deine Organisation deine Claude Code Einstellungen verwaltet, frag deine Administration.", "engineNotCounted": "Im kostenlosen Plan kann diese Engine noch nicht starten, weil die App ihre Tokens nicht zählen kann. Claude, Codex, Antigravity, Grok, Qwen und Crush funktionieren, und Pro oder Max schaltet jede Engine frei." + }, + "markdownImage": { + "untitled": "Bild", + "notImage": "kein unterstütztes Bildformat", + "malformedEncoding": "der Pfad enthält eine ungültige %-Kodierung", + "unsafeSegment": "der Pfad kodiert ein Trennzeichen oder ..", + "loading": "wird geladen", + "decodeFailed": "konnte nicht dekodiert werden" } } diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index cdd56eb749..f5aefcc5ea 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -2437,5 +2437,13 @@ "usageNotice": { "telemetryOff": "It was stopped because its token count is switched off. Remove CLAUDE_CODE_ENABLE_TELEMETRY and any OTEL_ settings from the env block of ~/.claude/settings.json and from the command that starts it, then start it again. If your organization manages your Claude Code settings, ask your administrator.", "engineNotCounted": "On the free plan this engine cannot start yet, because the app cannot count its tokens. Claude, Codex, Antigravity, Grok, Qwen and Crush work, and Pro or Max unlocks every engine." + }, + "markdownImage": { + "untitled": "image", + "notImage": "not a supported image type", + "malformedEncoding": "the path has an invalid % escape", + "unsafeSegment": "the path encodes a separator or ..", + "loading": "loading", + "decodeFailed": "could not decode" } } diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index 6933fd0fc7..8737cd8c7d 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -2437,5 +2437,13 @@ "usageNotice": { "telemetryOff": "Se detuvo porque su conteo de tokens está desactivado. Quita CLAUDE_CODE_ENABLE_TELEMETRY y cualquier ajuste OTEL_ del bloque env de ~/.claude/settings.json y del comando que lo inicia, y vuelve a iniciarlo. Si tu organización gestiona tus ajustes de Claude Code, pregunta a tu administrador.", "engineNotCounted": "En el plan gratuito este motor todavía no puede iniciarse, porque la app no puede contar sus tokens. Claude, Codex, Antigravity, Grok, Qwen y Crush funcionan, y Pro o Max desbloquea todos los motores." + }, + "markdownImage": { + "untitled": "imagen", + "notImage": "no es un tipo de imagen compatible", + "malformedEncoding": "la ruta tiene un escape % no válido", + "unsafeSegment": "la ruta codifica un separador o ..", + "loading": "cargando", + "decodeFailed": "no se pudo decodificar" } } diff --git a/src/renderer/src/i18n/locales/fr.json b/src/renderer/src/i18n/locales/fr.json index e4a58c7579..43922be08a 100644 --- a/src/renderer/src/i18n/locales/fr.json +++ b/src/renderer/src/i18n/locales/fr.json @@ -2437,5 +2437,13 @@ "usageNotice": { "telemetryOff": "Il a été arrêté car son comptage de tokens est désactivé. Retire CLAUDE_CODE_ENABLE_TELEMETRY et tout réglage OTEL_ du bloc env de ~/.claude/settings.json et de la commande qui le lance, puis relance-le. Si ton organisation gère tes réglages Claude Code, demande à ton administrateur.", "engineNotCounted": "Avec l'offre gratuite, ce moteur ne peut pas encore démarrer, car l'app ne peut pas compter ses tokens. Claude, Codex, Antigravity, Grok, Qwen et Crush fonctionnent, et Pro ou Max débloque tous les moteurs." + }, + "markdownImage": { + "untitled": "image", + "notImage": "type d’image non pris en charge", + "malformedEncoding": "le chemin contient un échappement % invalide", + "unsafeSegment": "le chemin encode un séparateur ou ..", + "loading": "chargement", + "decodeFailed": "décodage impossible" } } diff --git a/src/renderer/src/i18n/locales/it.json b/src/renderer/src/i18n/locales/it.json index 3184d9867d..7a2defa82f 100644 --- a/src/renderer/src/i18n/locales/it.json +++ b/src/renderer/src/i18n/locales/it.json @@ -2437,5 +2437,13 @@ "usageNotice": { "telemetryOff": "È stato fermato perché il suo conteggio dei token è disattivato. Rimuovi CLAUDE_CODE_ENABLE_TELEMETRY e ogni impostazione OTEL_ dal blocco env di ~/.claude/settings.json e dal comando che lo avvia, poi avvialo di nuovo. Se la tua organizzazione gestisce le tue impostazioni di Claude Code, chiedi al tuo amministratore.", "engineNotCounted": "Con il piano gratuito questo motore non può ancora avviarsi, perché l'app non può contare i suoi token. Claude, Codex, Antigravity, Grok, Qwen e Crush funzionano, e Pro o Max sblocca tutti i motori." + }, + "markdownImage": { + "untitled": "immagine", + "notImage": "tipo di immagine non supportato", + "malformedEncoding": "il percorso contiene un escape % non valido", + "unsafeSegment": "il percorso codifica un separatore o ..", + "loading": "caricamento", + "decodeFailed": "impossibile decodificare" } } diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index 1381f3c0df..1680b59149 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -2437,5 +2437,13 @@ "usageNotice": { "telemetryOff": "トークンの計測がオフになっているため停止しました。~/.claude/settings.json の env ブロックと、起動するコマンドから CLAUDE_CODE_ENABLE_TELEMETRY と OTEL_ の設定をすべて削除してから、もう一度起動してください。組織が Claude Code の設定を管理している場合は、管理者に確認してください。", "engineNotCounted": "無料プランでは、このエンジンはまだ起動できません。アプリがトークンを計測できないためです。Claude、Codex、Antigravity、Grok、Qwen、Crush は使えます。Pro または Max ではすべてのエンジンが使えます。" + }, + "markdownImage": { + "untitled": "画像", + "notImage": "対応していない画像形式です", + "malformedEncoding": "パスに無効な % エスケープが含まれています", + "unsafeSegment": "パスに区切り文字または .. がエンコードされています", + "loading": "読み込み中", + "decodeFailed": "デコードできませんでした" } } diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index aacd52da99..ac298e8277 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -2437,5 +2437,13 @@ "usageNotice": { "telemetryOff": "토큰 집계가 꺼져 있어 중지되었습니다. ~/.claude/settings.json의 env 블록과 이를 시작하는 명령에서 CLAUDE_CODE_ENABLE_TELEMETRY와 모든 OTEL_ 설정을 지운 뒤 다시 시작하세요. 조직에서 Claude Code 설정을 관리한다면 관리자에게 문의하세요.", "engineNotCounted": "무료 플랜에서는 앱이 이 엔진의 토큰을 집계할 수 없어 아직 시작할 수 없습니다. Claude, Codex, Antigravity, Grok, Qwen, Crush는 사용할 수 있으며, Pro 또는 Max에서는 모든 엔진을 사용할 수 있습니다." + }, + "markdownImage": { + "untitled": "이미지", + "notImage": "지원하지 않는 이미지 형식입니다", + "malformedEncoding": "경로에 잘못된 % 이스케이프가 있습니다", + "unsafeSegment": "경로에 구분자 또는 ..가 인코딩되어 있습니다", + "loading": "불러오는 중", + "decodeFailed": "디코딩할 수 없습니다" } } diff --git a/src/renderer/src/i18n/locales/pt-BR.json b/src/renderer/src/i18n/locales/pt-BR.json index c0aabb5793..c87f19b43b 100644 --- a/src/renderer/src/i18n/locales/pt-BR.json +++ b/src/renderer/src/i18n/locales/pt-BR.json @@ -2437,5 +2437,13 @@ "usageNotice": { "telemetryOff": "Ele foi parado porque a contagem de tokens dele está desligada. Remova CLAUDE_CODE_ENABLE_TELEMETRY e qualquer configuração OTEL_ do bloco env de ~/.claude/settings.json e do comando que o inicia, e inicie de novo. Se a sua organização gerencia suas configurações do Claude Code, fale com o administrador.", "engineNotCounted": "No plano gratuito este motor ainda não pode iniciar, porque o app não consegue contar os tokens dele. Claude, Codex, Antigravity, Grok, Qwen e Crush funcionam, e o Pro ou o Max libera todos os motores." + }, + "markdownImage": { + "untitled": "imagem", + "notImage": "tipo de imagem não suportado", + "malformedEncoding": "o caminho tem um escape % inválido", + "unsafeSegment": "o caminho codifica um separador ou ..", + "loading": "carregando", + "decodeFailed": "não foi possível decodificar" } } diff --git a/src/renderer/src/i18n/locales/tr.json b/src/renderer/src/i18n/locales/tr.json index 4556f6baa0..d5bd2217be 100644 --- a/src/renderer/src/i18n/locales/tr.json +++ b/src/renderer/src/i18n/locales/tr.json @@ -2437,5 +2437,13 @@ "usageNotice": { "telemetryOff": "Token sayımı kapalı olduğu için durduruldu. ~/.claude/settings.json dosyasındaki env bloğundan ve onu başlatan komuttan CLAUDE_CODE_ENABLE_TELEMETRY ve tüm OTEL_ ayarlarını kaldır, sonra yeniden başlat. Claude Code ayarlarını kuruluşun yönetiyorsa yöneticine sor.", "engineNotCounted": "Ücretsiz planda bu motor henüz başlayamaz, çünkü uygulama tokenlarını sayamıyor. Claude, Codex, Antigravity, Grok, Qwen ve Crush çalışır; Pro veya Max tüm motorların kilidini açar." + }, + "markdownImage": { + "untitled": "görsel", + "notImage": "desteklenen bir görsel türü değil", + "malformedEncoding": "yolda geçersiz bir % kaçış dizisi var", + "unsafeSegment": "yol bir ayırıcı veya .. kodluyor", + "loading": "yükleniyor", + "decodeFailed": "çözülemedi" } } diff --git a/src/renderer/src/i18n/locales/zh-CN.json b/src/renderer/src/i18n/locales/zh-CN.json index 5308bf372f..9a0149e8b9 100644 --- a/src/renderer/src/i18n/locales/zh-CN.json +++ b/src/renderer/src/i18n/locales/zh-CN.json @@ -2437,5 +2437,13 @@ "usageNotice": { "telemetryOff": "它已被停止,因为它的 token 计数已关闭。请从 ~/.claude/settings.json 的 env 部分以及启动它的命令中删除 CLAUDE_CODE_ENABLE_TELEMETRY 和所有 OTEL_ 设置,然后重新启动它。如果你的组织管理你的 Claude Code 设置,请联系管理员。", "engineNotCounted": "在免费计划中,此引擎暂时无法启动,因为应用无法统计它的 token。Claude、Codex、Antigravity、Grok、Qwen 和 Crush 可以使用,Pro 或 Max 可解锁所有引擎。" + }, + "markdownImage": { + "untitled": "图片", + "notImage": "不是支持的图片格式", + "malformedEncoding": "路径含有无效的 % 编码", + "unsafeSegment": "路径中编码了分隔符或 ..", + "loading": "加载中", + "decodeFailed": "无法解码" } } diff --git a/src/renderer/src/ide/IdePanel.tsx b/src/renderer/src/ide/IdePanel.tsx index cf896cd751..a8e0283100 100644 --- a/src/renderer/src/ide/IdePanel.tsx +++ b/src/renderer/src/ide/IdePanel.tsx @@ -56,7 +56,7 @@ import { UnsavedDialog } from './UnsavedDialog'; import { MarkdownBody, OutlinePane, type OutlineJump } from './MarkdownReview'; import { Breadcrumb, EditorStatusBar, SaveChip, ShortcutSheet } from './EditorChrome'; import { IdeIcon, IDE_YELLOW } from './ideIcons'; -import { isImagePath, isSvgPath } from '@shared/imageTypes'; +import { isImageDiskPath, isSvgDiskPath } from '@shared/imageTypes'; import { markdownOutline } from '@shared/markdownOutline'; import { languageForPath } from './monaco'; import { parentOfRel } from '@shared/ideNewFile'; @@ -349,7 +349,7 @@ export function IdePanel() { * reader rejects anything with a null byte. SVG is a picture first here * too, with view source one click away. */ const openEdit = useCallback((rel: string) => { - if (isImagePath(rel)) { openTab('image', rel); touchRecent(rel); return; } + if (isImageDiskPath(rel)) { openTab('image', rel); touchRecent(rel); return; } openSource(rel); }, [openSource, openTab, touchRecent]); @@ -1156,7 +1156,7 @@ export function IdePanel() { root={root} rel={activeTab.rel} onCopyPath={() => copyAbs(activeTab.rel)} - onViewSource={isSvgPath(activeTab.rel) ? () => openSource(activeTab.rel) : undefined} + onViewSource={isSvgDiskPath(activeTab.rel) ? () => openSource(activeTab.rel) : undefined} /> )} @@ -1195,7 +1195,7 @@ export function IdePanel() { )} - {isImagePath(activeTab.rel) && ( + {isImageDiskPath(activeTab.rel) && ( )} diff --git a/src/renderer/src/ide/ImagePreview.tsx b/src/renderer/src/ide/ImagePreview.tsx index e0ffe297cf..9dda17b28c 100644 --- a/src/renderer/src/ide/ImagePreview.tsx +++ b/src/renderer/src/ide/ImagePreview.tsx @@ -17,7 +17,7 @@ import { useState } from 'react'; import { useTranslation } from 'react-i18next'; import { useWorkspaceImage } from '@/hooks/useWorkspaceImage'; -import { formatBytes, isSvgPath } from '@shared/imageTypes'; +import { formatBytes } from '@shared/imageTypes'; import { ideBarStyle, ideIconBtn, ideTextBtn } from './chrome'; import { FileIcon, IdeIcon } from './ideIcons'; diff --git a/src/renderer/src/markdown/MarkdownPreview.tsx b/src/renderer/src/markdown/MarkdownPreview.tsx index d858222521..f008bdfcb4 100644 --- a/src/renderer/src/markdown/MarkdownPreview.tsx +++ b/src/renderer/src/markdown/MarkdownPreview.tsx @@ -14,10 +14,11 @@ * (IDE tab / overlay) opens them in context; everything else is inert. */ import { memo, useState } from 'react'; +import { useTranslation } from 'react-i18next'; import ReactMarkdown from 'react-markdown'; import remarkGfm from 'remark-gfm'; import { useWorkspaceImage } from '@/hooks/useWorkspaceImage'; -import { isExternal, isRelativeMd, resolveLocalImageRel, resolveRel } from './mdLinks'; +import { isExternal, resolveLocalImageSource, resolveMdLinkRel, type LocalImageRejectReason } from './mdLinks'; import { remarkSoftBreaks } from './remarkSoftBreaks'; import { rehypeAutoDir } from './rehypeAutoDir'; import { useRtl } from '@/i18n/useDirection'; @@ -40,6 +41,18 @@ const CARD_PLUGINS = [remarkGfm, remarkSoftBreaks]; const AUTO_DIR_PLUGINS = [rehypeAutoDir]; const NO_PLUGINS: never[] = []; +/** Chip note (i18n key) for each reason a local image was not loaded. `null` + * keeps the chip as quiet as it always was: a remote URL is not a mistake the + * author made, it is a policy. A Record, so a new reason fails the typecheck + * here until someone decides what the user should see for it. */ +const IMAGE_REJECT_NOTE_KEY: Readonly> = { + empty: null, + remote: null, + 'not-image': 'markdownImage.notImage', + 'malformed-encoding': 'markdownImage.malformedEncoding', + 'unsafe-segment': 'markdownImage.unsafeSegment' +}; + export interface MarkdownPreviewProps { source: string; /** Repo-relative path of the file being previewed (for resolving relative links). */ @@ -67,6 +80,7 @@ export const MarkdownPreview = memo(function MarkdownPreview({ // means an English user's markdown renders through exactly the pipeline it // rendered through before this existed, whatever the agent writes into it. const rtl = useRtl(); + const { t } = useTranslation(); return (
{ const h = href ?? ''; + // Decoded like an image src, so `[x]()` opens + // `my notes.md`; a malformed escape resolves to null and stays inert. + const mdRel = onOpenMarkdownLink ? resolveMdLinkRel(baseRel, h) : null; const onClick = (e: React.MouseEvent) => { e.preventDefault(); if (isExternal(h)) { void window.cth.openExternal?.(h); return; } - if (isRelativeMd(h) && onOpenMarkdownLink) { - onOpenMarkdownLink(resolveRel(baseRel, h.replace(/#.*$/, ''))); - } + if (mdRel && onOpenMarkdownLink) onOpenMarkdownLink(mdRel); // anything else (file:, anchors into self, unknown schemes): inert }; - const clickable = isExternal(h) || (isRelativeMd(h) && !!onOpenMarkdownLink); + const clickable = isExternal(h) || mdRel !== null; return ( { const s = typeof src === 'string' ? src : undefined; - const rel = root ? resolveLocalImageRel(baseRel, s) : null; - if (!root || !rel) return ; - return ; + if (!root) return ; + const source = resolveLocalImageSource(baseRel, s); + if (!source.ok) { + const noteKey = IMAGE_REJECT_NOTE_KEY[source.reason]; + return ; + } + return ; } }} > @@ -117,9 +136,10 @@ export const MarkdownPreview = memo(function MarkdownPreview({ /** Fallback for anything we won't (or can't) load: remote URLs, non-images, * and local files that turned out to be missing or undecodable. */ function ImageChip({ alt, src, note }: { alt?: string; src?: string; note?: string }) { + const { t } = useTranslation(); return ( - 🖼 {alt || 'image'}{note ? ` — ${note}` : ''} + 🖼 {alt || t('markdownImage.untitled')}{note ? ` — ${note}` : ''} ); } @@ -128,11 +148,12 @@ function ImageChip({ alt, src, note }: { alt?: string; src?: string; note?: stri * failure so a stale path in a report degrades to the old behaviour instead of * a broken-image glyph. Blob lifetime (create AND revoke) belongs to the hook. */ function MdImage({ root, rel, alt, src }: { root: string; rel: string; alt?: string; src?: string }) { + const { t } = useTranslation(); const img = useWorkspaceImage(root, rel); const [decodeFailed, setDecodeFailed] = useState(false); - if (img.status === 'loading') return ; + if (img.status === 'loading') return ; if (img.status === 'error') return ; - if (decodeFailed) return ; + if (decodeFailed) return ; return ( ` is not loaded from the workspace. */ +export type LocalImageRejectReason = + | 'empty' + /** Any URI scheme — http(s):, data:, file:, javascript: — none of them is a workspace path. */ + | 'remote' + | 'not-image' + | HrefRejectReason; + +export type DecodedHrefPath = + | { ok: true; rooted: boolean; segments: string[] } + | { ok: false; reason: HrefRejectReason }; + +export type LocalImageSource = + | { ok: true; rel: string } + | { ok: false; reason: LocalImageRejectReason }; /** Resolve `href` against the directory of `baseRel` ('' when unknown). * @@ -39,9 +62,86 @@ export function isRelativeMd(href: string): boolean { return !hasScheme(href) && /\.(md|markdown)(#.*)?$/i.test(href); } +/** Raw path STRUCTURE — handed to `resolveRel` as-is, never decoded. */ +function isStructuralSegment(encodedSegment: string): boolean { + return encodedSegment === '' || encodedSegment === '.' || encodedSegment === '..'; +} + +/** True when a decoded segment would change the path's shape instead of naming a file. */ +function isUnsafeDecodedSegment(decodedSegment: string): boolean { + return decodedSegment === '.' || decodedSegment === '..' || /[/\\\0]/.test(decodedSegment); +} + +/** + * Split a markdown URL path into the DISK names it refers to, decoding each + * segment exactly once. + * + * WHY: react-markdown never hands over what the author typed — it hands over + * the URL after `normalizeUri`, which percent-encodes spaces, backslashes and + * every non-ASCII character. `![QA]()` arrives as `QA%20Shot.png`, + * and passing that to the filesystem opened a file literally named + * `QA%20Shot.png` (or, worse, a DIFFERENT file by that name). + * + * The rules, in order: + * - the URL suffix goes first: everything from the first LITERAL `?` or `#`. + * An encoded `%23` is still file-name data at this point. + * - raw `''`, `.` and `..` are structure and are left for `resolveRel`. + * - every other segment is decoded once (`%2520` → `%20`, never a space); `+` + * stays a plus — this is a path, not a form body. + * - a decoded segment that is `.`/`..` or contains a separator or NUL is + * refused: encoding must not be a way to smuggle in path structure. The rule + * is applied to EVERY segment, encoded or not, so `img\shot.png` and + * `img%5Cshot.png` get the same answer on every OS. `:` is deliberately + * allowed — it is a legal name on macOS/Linux, and on Windows the + * containment of drive/stream forms is `safeResolve`'s job in main. + * + * Never falls back to the raw string on failure: with both `QA Shot.png` and + * `QA%20Shot.png` on disk, a fallback is exactly how the wrong image gets read. + */ +export function decodeHrefPath(href: string): DecodedHrefPath { + const suffixAt = href.search(/[?#]/); + const sourcePath = suffixAt < 0 ? href : href.slice(0, suffixAt); + const segments: string[] = []; + for (const encodedSegment of sourcePath.split('/')) { + if (isStructuralSegment(encodedSegment)) { segments.push(encodedSegment); continue; } + let decodedSegment: string; + try { + decodedSegment = decodeURIComponent(encodedSegment); + } catch (e) { + if (e instanceof URIError) return { ok: false, reason: 'malformed-encoding' }; + throw e; + } + if (isUnsafeDecodedSegment(decodedSegment)) return { ok: false, reason: 'unsafe-segment' }; + segments.push(decodedSegment); + } + return { ok: true, rooted: sourcePath.startsWith('/'), segments }; +} + +/** Workspace-relative path for already-decoded segments. Safe to re-join on `/`: + * `decodeHrefPath` has refused every segment that contains one. A leading `/` + * means the WORKSPACE root (see `resolveLocalImageSource`). */ +function resolveDecodedRel(baseRel: string | undefined, decoded: { rooted: boolean; segments: string[] }): string { + return resolveRel(decoded.rooted ? undefined : baseRel, decoded.segments.join('/')); +} + /** - * Workspace-relative path for a markdown ``, or null when the source is - * not a local image we may load. + * Workspace-relative path for a relative markdown link, or null when it is not + * one the host should open. Decodes exactly like images do, so + * `[x]()` opens `my notes.md` rather than a literal + * `my%20notes.md`. + */ +export function resolveMdLinkRel(baseRel: string | undefined, href: string): string | null { + if (!isRelativeMd(href)) return null; + const decoded = decodeHrefPath(href); + if (!decoded.ok) return null; + return resolveDecodedRel(baseRel, decoded) || null; +} + +/** + * Workspace-relative path for a markdown ``, or the reason it is not a + * local image we may load. The reason exists so the preview can tell "you wrote + * this path wrong" apart from "this is a remote URL" instead of showing the + * same silent chip for both. * * WHY THIS EXISTS: the preview used to replace EVERY image with a placeholder * chip, so an agent-written report containing screenshots rendered as a row of @@ -56,22 +156,30 @@ export function isRelativeMd(href: string): boolean { * document into a network beacon that leaks "this user opened this file" to * whoever authored the markdown. Agent-generated markdown is untrusted. * - anything whose extension is not a known image type — there is no reason for - * an to pull an arbitrary file's bytes into the renderer. + * an to pull an arbitrary file's bytes into the renderer. Judged on the + * DECODED file name, so the answer is about the file that would be opened. + * - malformed or shape-changing percent-encoding (see `decodeHrefPath`). * * A leading `/` is read as workspace-root-relative rather than as a filesystem * absolute path; the leading slashes are stripped and the rest resolves from the * root, so `/etc/passwd` becomes the (harmless, nonexistent) `etc/passwd` inside * the workspace instead of escaping to the real one. */ +export function resolveLocalImageSource(baseRel: string | undefined, src: string | undefined): LocalImageSource { + if (typeof src !== 'string') return { ok: false, reason: 'empty' }; + const sourcePath = src.trim(); + if (!sourcePath) return { ok: false, reason: 'empty' }; + if (hasScheme(sourcePath)) return { ok: false, reason: 'remote' }; + const decoded = decodeHrefPath(sourcePath); + if (!decoded.ok) return decoded; + const fileName = decoded.segments[decoded.segments.length - 1] ?? ''; + if (!imageMimeForFileName(fileName)) return { ok: false, reason: 'not-image' }; + const resolvedRel = resolveDecodedRel(baseRel, decoded); + return resolvedRel ? { ok: true, rel: resolvedRel } : { ok: false, reason: 'empty' }; +} + +/** `resolveLocalImageSource` for callers that only need the path: null when refused. */ export function resolveLocalImageRel(baseRel: string | undefined, src: string | undefined): string | null { - if (typeof src !== 'string') return null; - const raw = src.trim(); - if (!raw) return null; - if (hasScheme(raw)) return null; - if (!isImagePath(raw)) return null; - // Strip the query/hash before resolving — they are cache-busters, not path. - const clean = raw.split('#')[0].split('?')[0]; - const rooted = clean.startsWith('/'); - const rel = resolveRel(rooted ? undefined : baseRel, clean); - return rel || null; + const source = resolveLocalImageSource(baseRel, src); + return source.ok ? source.rel : null; } diff --git a/src/shared/imageTypes.ts b/src/shared/imageTypes.ts index fe69e88f9f..df0a3496dc 100644 --- a/src/shared/imageTypes.ts +++ b/src/shared/imageTypes.ts @@ -17,6 +17,14 @@ * only ever used to label a `blob:` URL for the platform's own image decoder — * a mislabelled file simply fails to decode and shows the preview's error state, * it never becomes a script or a navigation. + * + * TWO KINDS OF INPUT, two families of functions. A markdown `src` is a URL: + * `?v=2` and `#fig` are cache-busters and fragments, not part of the name + * (`imageMimeForPath`, `isImagePath`, `isSvgPath`). A path from the file tree or + * from `fs` is a DISK path: `QA#1.png` is a perfectly good file name and a + * workspace can live under `C:\Users\me\C#work\` (`imageMimeForDiskPath`, + * `isImageDiskPath`, `isSvgDiskPath`). Feeding one kind to the other's API + * truncates the name at the `#` and silently loses the extension. */ /** Extension (lower-case, no dot) → mime type. */ @@ -33,29 +41,56 @@ const MIME_BY_EXT: Readonly> = { }; /** - * Lower-cased extension of `p` without the dot, or '' when there is none. + * The mime for a bare lower-case extension, or null. + * + * OWN keys only. The table is a plain object literal, so an unguarded + * `MIME_BY_EXT['constructor']` hands back Object itself: `x.constructor` became + * an "image", and the "mime" the main process stamped onto it was a function + * that cannot cross IPC. + */ +function mimeForExtension(ext: string): string | null { + return Object.hasOwn(MIME_BY_EXT, ext) ? MIME_BY_EXT[ext] : null; +} + +/** Lower-cased extension of a single file NAME (no separators), or ''. */ +function extensionOfFileName(fileName: string): string { + const dot = fileName.lastIndexOf('.'); + if (dot < 0 || dot === fileName.length - 1) return ''; + return fileName.slice(dot + 1).toLowerCase(); +} + +/** + * Last component of a disk path. Splits on BOTH separators: the main process + * hands over native Windows paths, the renderer uses `/`, and the answer has to + * be the same either way. + */ +function fileNameOfDiskPath(diskPath: string): string { + return diskPath.split(/[\\/]/).pop() ?? ''; +} + +/** + * Lower-cased extension of the URL path `p` without the dot, or '' when there + * is none. * - * Strips a `?query` / `#hash` first: markdown authored by an agent routinely - * carries cache-busting suffixes (`./shot.png?v=2`), and treating `png?v=2` as - * the extension would silently drop exactly the screenshots we want to render. - * Only the LAST path segment is considered, so a dotted directory name - * (`v1.2/report`) can never masquerade as an extension. + * URL semantics: strips a `?query` / `#hash` first. Markdown authored by an + * agent routinely carries cache-busting suffixes (`./shot.png?v=2`), and + * treating `png?v=2` as the extension would silently drop exactly the + * screenshots we want to render. Only the LAST path segment is considered, so a + * dotted directory name (`v1.2/report`) can never masquerade as an extension. + * For a path from disk use the `*DiskPath` functions instead. */ export function extensionOf(p: string): string { if (typeof p !== 'string') return ''; const clean = p.split('#')[0].split('?')[0]; - const base = clean.split('/').pop() ?? ''; - const dot = base.lastIndexOf('.'); - if (dot < 0 || dot === base.length - 1) return ''; - return base.slice(dot + 1).toLowerCase(); + return extensionOfFileName(clean.split('/').pop() ?? ''); } -/** The image mime for `p`, or null when the extension isn't a known image. */ +/** The image mime for the URL path `p`, or null when the extension isn't a known image. */ export function imageMimeForPath(p: string): string | null { - return MIME_BY_EXT[extensionOf(p)] ?? null; + return mimeForExtension(extensionOf(p)); } -/** True when `p` names a raster or vector image we can render. */ +/** True when the URL path `p` names a raster or vector image we can render. */ export function isImagePath(p: string): boolean { return imageMimeForPath(p) !== null; } @@ -65,12 +100,40 @@ export function isImagePath(p: string): boolean { * Callers use this to keep a "view source" escape hatch: an .svg opens as a * picture (that's what you want 95% of the time) but must never become * un-editable, which is what routing every image straight to a read-only - * preview would have done. + * preview would have done. URL semantics; see `isSvgDiskPath` for disk paths. */ export function isSvgPath(p: string): boolean { return extensionOf(p) === 'svg'; } +/** + * The image mime for a single file NAME exactly as it is on disk — `#` and `?` + * included — or null. The markdown resolver calls this on the DECODED last + * segment, so `QA%231.png` is judged as `QA#1.png` and `cover.png%23notes.txt` + * by its real `.txt`. + */ +export function imageMimeForFileName(fileName: string): string | null { + if (typeof fileName !== 'string') return null; + return mimeForExtension(extensionOfFileName(fileName)); +} + +/** The image mime for a disk path (workspace-relative or absolute, either separator), or null. */ +export function imageMimeForDiskPath(diskPath: string): string | null { + if (typeof diskPath !== 'string') return null; + return imageMimeForFileName(fileNameOfDiskPath(diskPath)); +} + +/** True when the disk path names an image we can render. */ +export function isImageDiskPath(diskPath: string): boolean { + return imageMimeForDiskPath(diskPath) !== null; +} + +/** `isSvgPath` for a disk path. */ +export function isSvgDiskPath(diskPath: string): boolean { + if (typeof diskPath !== 'string') return false; + return extensionOfFileName(fileNameOfDiskPath(diskPath)) === 'svg'; +} + /** Human byte size for a status line: "864 B", "1.4 MB". */ export function formatBytes(n: number): string { if (!Number.isFinite(n) || n < 0) return '—'; diff --git a/test/ide-image.test.cjs b/test/ide-image.test.cjs index 2ce9836a90..d37f23154b 100644 --- a/test/ide-image.test.cjs +++ b/test/ide-image.test.cjs @@ -21,9 +21,15 @@ const os = require('node:os'); const path = require('node:path'); const loadTs = require('./load-ts.cjs'); -const { extensionOf, imageMimeForPath, isImagePath, isSvgPath, formatBytes } = loadTs('src/shared/imageTypes.ts'); +const { + extensionOf, imageMimeForPath, isImagePath, isSvgPath, formatBytes, + imageMimeForFileName, imageMimeForDiskPath, isImageDiskPath, isSvgDiskPath +} = loadTs('src/shared/imageTypes.ts'); const { readFileBinary } = loadTs('src/main/fs.ts'); -const { resolveLocalImageRel, resolveRel } = loadTs('src/renderer/src/markdown/mdLinks.ts'); +const { + resolveLocalImageRel, resolveLocalImageSource, resolveMdLinkRel, decodeHrefPath, resolveRel +} = loadTs('src/renderer/src/markdown/mdLinks.ts'); +const { settleImageRead } = loadTs('src/renderer/src/hooks/useWorkspaceImage.ts'); // ─── extension → mime ─────────────────────────────────────────────────────── @@ -72,6 +78,37 @@ test('svg is flagged separately — it is the one image that is also source', () assert.equal(isSvgPath('logo.png'), false); }); +test('Object.prototype keys are not image extensions', () => { + // MIME_BY_EXT is a plain object literal, so an unguarded lookup of + // `constructor` hands back Object itself — `x.constructor` became an "image", + // and the mime the main process then stamped was a function that cannot cross + // IPC. Lower-casing means these two are the reachable ones. + for (const name of ['x.constructor', 'x.__proto__', 'x.hasownproperty']) { + assert.equal(imageMimeForPath(name), null, `${name} via the URL API`); + assert.equal(imageMimeForFileName(name), null, `${name} via the file-name API`); + assert.equal(isImagePath(name), false); + assert.equal(isImageDiskPath(name), false); + } +}); + +test('DISK paths keep `#` and `?` as part of the file name', () => { + // The URL API strips them as fragment/query; on disk they are just + // characters. A screenshot called `QA#1.png`, or any image under a `notes#1/` + // directory, must still open as an image in the IDE. + assert.equal(imageMimeForFileName('QA#1.png'), 'image/png'); + assert.equal(imageMimeForFileName('cover.png?v=1'), null, 'its real extension is `png?v=1`'); + assert.ok(isImageDiskPath('docs/QA#1.png')); + assert.ok(isImageDiskPath('notes#1/shot.png')); + assert.ok(isSvgDiskPath('notes#1\\logo.svg'), 'Windows separators count too'); + assert.equal(isSvgDiskPath('notes#1/logo.png'), false); + // A workspace that lives under a `#` directory: the WHOLE absolute path is + // what the main process sees. + assert.equal(imageMimeForDiskPath('C:\\Users\\me\\C#work\\docs\\logo.svg'), 'image/svg+xml'); + assert.equal(imageMimeForDiskPath('/home/me/C#work/docs/shot.PNG'), 'image/png'); + assert.equal(imageMimeForDiskPath('C:\\v1.2\\report'), null, 'a dotted directory is not an extension'); + assert.equal(imageMimeForDiskPath(''), null); +}); + test('formatBytes reads like a status line', () => { assert.equal(formatBytes(0), '0 B'); assert.equal(formatBytes(864), '864 B'); @@ -122,6 +159,116 @@ test('`..` can never climb above the workspace root textually', () => { assert.equal(resolveLocalImageRel('a/b.md', '../../../../x.png'), 'x.png'); }); +// ─── percent-encoded sources ──────────────────────────────────────────────── +// +// The resolver never sees what the author typed: react-markdown hands it the +// URL AFTER `normalizeUri`, which percent-encodes spaces, backslashes and every +// non-ASCII character, and turns a `%` that is not followed by two +// alphanumerics into `%25`. So the inputs below come in two kinds — PARSER +// OUTPUT (what the product actually receives) and DIRECT input (only reachable +// by calling the resolver yourself, kept to pin the defensive edges). + +/** The `src` react-markdown passes to the `img` component for `markdown`. */ +async function srcOfMarkdownImage(markdown) { + const { default: ReactMarkdown } = await import('react-markdown'); + const React = require('react'); + const { renderToStaticMarkup } = require('react-dom/server'); + let captured; + renderToStaticMarkup(React.createElement(ReactMarkdown, { + components: { img: ({ src }) => { captured = src; return null; } } + }, markdown)); + return captured; +} + +test('what the parser actually hands the resolver', async () => { + assert.equal(await srcOfMarkdownImage('![QA]()'), 'QA%20Shot.png'); + assert.equal(await srcOfMarkdownImage('![QA](QA%20Shot.png)'), 'QA%20Shot.png'); + assert.equal(await srcOfMarkdownImage('![x](bad%2.png)'), 'bad%252.png', 'a lone `%` is re-encoded'); + assert.equal(await srcOfMarkdownImage('![x](100%.png)'), '100%25.png'); + assert.equal(await srcOfMarkdownImage('![x](bad%zz.png)'), 'bad%zz.png', 'kept: it LOOKS like an escape'); + assert.equal(await srcOfMarkdownImage('![x]()'), 'img%5Cshot.png'); + // A colon BEFORE the first `/` reads as a scheme and react-markdown's + // urlTransform blanks the whole URL; after a `/` it survives untouched. + assert.equal(await srcOfMarkdownImage('![x](a:b.png)'), ''); + assert.equal(await srcOfMarkdownImage('![x](shots/a:b.png)'), 'shots/a:b.png'); +}); + +test('each URL segment is decoded exactly once', () => { + const base = 'docs/report.md'; + assert.equal(resolveLocalImageRel(base, 'QA%20Shot.png'), 'docs/QA Shot.png'); + assert.equal(resolveLocalImageRel(base, 'QA%2520Shot.png'), 'docs/QA%20Shot.png', 'never twice'); + assert.equal(resolveLocalImageRel(base, '%E6%B8%AC%E8%A9%A6.png'), 'docs/測試.png'); + assert.equal(resolveLocalImageRel(base, '100%25.png'), 'docs/100%.png'); + assert.equal(resolveLocalImageRel(base, 'bad%252.png'), 'docs/bad%2.png'); + assert.equal(resolveLocalImageRel(base, 'C++.png'), 'docs/C++.png', '`+` is not a form-encoded space'); + assert.equal(resolveLocalImageRel(base, 'QA%20Shot.png?v=2#fig'), 'docs/QA Shot.png'); + assert.equal(resolveLocalImageRel(base, '/docs/QA%20Shot.png'), 'docs/QA Shot.png'); + assert.equal(resolveLocalImageRel(base, 'folder%20one/../QA%20Shot.png'), 'docs/QA Shot.png'); +}); + +test('an encoded `#` is file-name data, judged by the DECODED extension', () => { + const base = 'docs/report.md'; + assert.equal(resolveLocalImageRel(base, 'QA%231.png'), 'docs/QA#1.png'); + assert.equal(resolveLocalImageRel(base, 'folder%23one/pic.png'), 'docs/folder#one/pic.png'); + assert.deepEqual(resolveLocalImageSource(base, 'cover.png%23notes.txt'), { ok: false, reason: 'not-image' }); + assert.deepEqual(resolveLocalImageSource(base, 'x.constructor'), { ok: false, reason: 'not-image' }); +}); + +test('the document directory is a disk path and is never decoded', () => { + assert.equal(resolveLocalImageRel('notes%20literal/report.md', 'shot.png'), 'notes%20literal/shot.png'); + assert.equal(resolveLocalImageRel('notes#1/report.md', 'QA%20Shot.png'), 'notes#1/QA Shot.png'); +}); + +test('malformed encodings and shape-changing segments are refused with a reason', () => { + const base = 'docs/report.md'; + for (const src of ['bad%zz.png', 'bad%FF.png', 'bad%E6%B8.png', 'bad%2.png' /* direct */]) { + assert.deepEqual(resolveLocalImageSource(base, src), { ok: false, reason: 'malformed-encoding' }, src); + assert.equal(resolveLocalImageRel(base, src), null); + } + for (const src of [ + 'x%2Fy.png', 'x%5Cy.png', '%2e%2e/outside.png', 'a/%2E/b.png', 'a%00b.png', + 'img\\shot.png', '\\\\server\\share\\x.png' // direct: the parser encodes `\` + ]) { + assert.deepEqual(resolveLocalImageSource(base, src), { ok: false, reason: 'unsafe-segment' }, src); + } +}); + +test('a colon names the same file whether or not it was encoded', () => { + // Legal on macOS/Linux and readable there today; Windows drive and stream + // forms are confined by safeResolve in the main process, not here. + assert.equal(resolveLocalImageRel('docs/report.md', 'shots/a:b.png'), 'docs/shots/a:b.png'); + assert.equal(resolveLocalImageRel('docs/report.md', 'shots/a%3Ab.png'), 'docs/shots/a:b.png'); + // …while a leading `name:` is a scheme, encoded or not it never gets that far. + assert.deepEqual(resolveLocalImageSource('docs/report.md', 'a:b.png'), { ok: false, reason: 'remote' }); +}); + +test('every refusal carries a reason the preview can show', () => { + const base = 'docs/report.md'; + assert.deepEqual(resolveLocalImageSource(base, undefined), { ok: false, reason: 'empty' }); + assert.deepEqual(resolveLocalImageSource(base, ' '), { ok: false, reason: 'empty' }); + assert.deepEqual(resolveLocalImageSource(base, 'https://evil.example/t.png'), { ok: false, reason: 'remote' }); + assert.deepEqual(resolveLocalImageSource(base, 'data:image/png;base64,AAAA'), { ok: false, reason: 'remote' }); + assert.deepEqual(resolveLocalImageSource(base, './secrets.env'), { ok: false, reason: 'not-image' }); + assert.deepEqual(resolveLocalImageSource(base, 'shot.png'), { ok: true, rel: 'docs/shot.png' }); +}); + +test('decodeHrefPath keeps raw structure apart from decoded names', () => { + assert.deepEqual(decodeHrefPath('/a%20b/../c.png?x#y'), { ok: true, rooted: true, segments: ['', 'a b', '..', 'c.png'] }); + assert.deepEqual(decodeHrefPath('%zz'), { ok: false, reason: 'malformed-encoding' }); +}); + +test('relative markdown links decode the same way images do', () => { + const base = 'docs/report.md'; + assert.equal(resolveMdLinkRel(base, 'my%20notes.md'), 'docs/my notes.md'); + assert.equal(resolveMdLinkRel(base, 'my%20notes.md#intro'), 'docs/my notes.md'); + assert.equal(resolveMdLinkRel(base, '../README.md'), 'README.md'); + assert.equal(resolveMdLinkRel(base, '/guide/start.md'), 'guide/start.md', 'leading `/` is the workspace root, as for images'); + assert.equal(resolveMdLinkRel(base, 'bad%zz.md'), null); + assert.equal(resolveMdLinkRel(base, 'x%2Fy.md'), null); + assert.equal(resolveMdLinkRel(base, 'https://example.com/a.md'), null); + assert.equal(resolveMdLinkRel(base, 'shot.png'), null, 'only markdown files open as markdown'); +}); + // ─── the binary read itself ───────────────────────────────────────────────── /** A 1×1 PNG — a real file with a null byte in its header, i.e. exactly what the @@ -240,3 +387,94 @@ test('unknown binary types still read, labelled octet-stream', async () => { fs.rmSync(dir, { recursive: true, force: true }); } }); + +// ─── encoded sources, end to end ──────────────────────────────────────────── + +/** A second, distinguishable "image": same PNG header, different trailing + * bytes, so a test can tell WHICH file a read actually returned. */ +const OTHER_PNG = Buffer.concat([ONE_PIXEL_PNG, Buffer.from('other')]); + +test('a space-named image and its literal-%20 twin each read their OWN bytes', async () => { + // The collision is the whole point: before the fix `QA%20Shot.png` read the + // file literally named `QA%20Shot.png`, which `ok: true` alone cannot catch. + const { dir, root } = makeWorkspace(); + try { + fs.writeFileSync(path.join(root, 'docs', 'QA Shot.png'), ONE_PIXEL_PNG); + fs.writeFileSync(path.join(root, 'docs', 'QA%20Shot.png'), OTHER_PNG); + for (const [src, expected] of [ + ['QA%20Shot.png', ONE_PIXEL_PNG], + ['QA%2520Shot.png', OTHER_PNG], + ['QA%20Shot.png?v=2#fig', ONE_PIXEL_PNG], + ['/docs/QA%20Shot.png', ONE_PIXEL_PNG] + ]) { + const rel = resolveLocalImageRel('docs/report.md', src); + const res = await readFileBinary(root, rel); + assert.equal(res.ok, true, `${src}: ${res.ok ? '' : res.error}`); + assert.ok(Buffer.from(res.bytes).equals(expected), `${src} read the wrong file`); + assert.equal(res.mime, 'image/png'); + } + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +test('names with `#`, `%`, `+` and CJK read back with an image mime', async () => { + const { dir, root } = makeWorkspace(); + try { + for (const name of ['QA#1.png', '100%.png', 'C++.png', '測試截圖.png']) { + fs.writeFileSync(path.join(root, 'docs', name), ONE_PIXEL_PNG); + } + fs.mkdirSync(path.join(root, 'docs', 'folder#one')); + fs.writeFileSync(path.join(root, 'docs', 'folder#one', 'pic.png'), ONE_PIXEL_PNG); + for (const src of [ + 'QA%231.png', '100%25.png', 'C++.png', + '%E6%B8%AC%E8%A9%A6%E6%88%AA%E5%9C%96.png', 'folder%23one/pic.png' + ]) { + const res = await readFileBinary(root, resolveLocalImageRel('docs/report.md', src)); + assert.equal(res.ok, true, `${src}: ${res.ok ? '' : res.error}`); + assert.equal(res.mime, 'image/png', `${src} must not fall back to octet-stream`); + } + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +test('a workspace under a `#` directory still gets image mimes (svg included)', async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cth-img-')); + const root = path.join(dir, 'C#work'); + try { + fs.mkdirSync(path.join(root, 'docs'), { recursive: true }); + fs.writeFileSync(path.join(root, 'docs', 'shot.png'), ONE_PIXEL_PNG); + fs.writeFileSync(path.join(root, 'docs', 'logo.svg'), ''); + const png = await readFileBinary(root, 'docs/shot.png'); + const svg = await readFileBinary(root, 'docs/logo.svg'); + assert.equal(png.ok && png.mime, 'image/png'); + // SVG is the one format the decoder will NOT sniff — a wrong mime here is a + // broken image, not a cosmetic label. + assert.equal(svg.ok && svg.mime, 'image/svg+xml'); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +// ─── the renderer side of the read ────────────────────────────────────────── + +test('settleImageRead turns every failure into a result, never a throw', async () => { + const ok = { ok: true, bytes: new Uint8Array([1]), mime: 'image/png', path: '/x.png', size: 1 }; + assert.deepEqual(await settleImageRead(() => Promise.resolve(ok)), ok); + assert.deepEqual( + await settleImageRead(() => Promise.resolve({ ok: false, error: 'ENOENT' })), + { ok: false, error: 'ENOENT' } + ); + // Rejected IPC (e.g. a reply that could not be structured-cloned). + assert.deepEqual( + await settleImageRead(() => Promise.reject(new Error('could not be cloned'))), + { ok: false, error: 'could not be cloned' } + ); + // SYNCHRONOUS throw — a missing bridge or a preload that throws on call. A + // trailing `.catch()` never sees this; inside an effect it would unmount the + // whole preview through the error boundary instead of showing a chip. + const missingBridge = await settleImageRead(() => { throw new TypeError('readBinary is not a function'); }); + assert.deepEqual(missingBridge, { ok: false, error: 'readBinary is not a function' }); + assert.deepEqual(await settleImageRead(() => { throw 'plain string'; }), { ok: false, error: 'plain string' }); +}); From 77a40c00000710db56b11ee83a6700fc1d5ab9a2 Mon Sep 17 00:00:00 2001 From: hsien wei Date: Fri, 4 Dec 2026 15:12:28 +0800 Subject: [PATCH 2/2] fix(markdown): judge link extension on the decoded file name - check .md/.markdown on the decoded last segment, the name that is opened - `secrets.env?.md` and `secrets.env#.md` no longer open secrets.env - a query after a real .md (`notes.md?v=2`) now opens notes.md, as for images - drop isRelativeMd, which no longer has a caller - add a regression test for links whose href and opened path disagree --- src/renderer/src/markdown/mdLinks.ts | 16 +++++++++++----- test/ide-image.test.cjs | 14 ++++++++++++++ 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/src/renderer/src/markdown/mdLinks.ts b/src/renderer/src/markdown/mdLinks.ts index 4a0683c997..030d5508e1 100644 --- a/src/renderer/src/markdown/mdLinks.ts +++ b/src/renderer/src/markdown/mdLinks.ts @@ -58,10 +58,6 @@ function hasScheme(href: string): boolean { return /^[a-z][a-z0-9+.-]*:/i.test(href); } -export function isRelativeMd(href: string): boolean { - return !hasScheme(href) && /\.(md|markdown)(#.*)?$/i.test(href); -} - /** Raw path STRUCTURE — handed to `resolveRel` as-is, never decoded. */ function isStructuralSegment(encodedSegment: string): boolean { return encodedSegment === '' || encodedSegment === '.' || encodedSegment === '..'; @@ -124,16 +120,26 @@ function resolveDecodedRel(baseRel: string | undefined, decoded: { rooted: boole return resolveRel(decoded.rooted ? undefined : baseRel, decoded.segments.join('/')); } +/** A file NAME (already decoded, no URL suffix) that opens as markdown. */ +const MARKDOWN_FILE_NAME = /\.(md|markdown)$/i; + /** * Workspace-relative path for a relative markdown link, or null when it is not * one the host should open. Decodes exactly like images do, so * `[x]()` opens `my notes.md` rather than a literal * `my%20notes.md`. + * + * The `.md` check is made on the DECODED last segment, the same name that will + * be opened, as `resolveLocalImageSource` does for images. Checking the raw href + * instead let `secrets.env?.md` pass as markdown and then open `secrets.env`, + * because the decoder cuts the URL suffix at the first literal `?` or `#`. */ export function resolveMdLinkRel(baseRel: string | undefined, href: string): string | null { - if (!isRelativeMd(href)) return null; + if (typeof href !== 'string' || hasScheme(href)) return null; const decoded = decodeHrefPath(href); if (!decoded.ok) return null; + const fileName = decoded.segments[decoded.segments.length - 1] ?? ''; + if (!MARKDOWN_FILE_NAME.test(fileName)) return null; return resolveDecodedRel(baseRel, decoded) || null; } diff --git a/test/ide-image.test.cjs b/test/ide-image.test.cjs index d37f23154b..1564eda3ea 100644 --- a/test/ide-image.test.cjs +++ b/test/ide-image.test.cjs @@ -269,6 +269,20 @@ test('relative markdown links decode the same way images do', () => { assert.equal(resolveMdLinkRel(base, 'shot.png'), null, 'only markdown files open as markdown'); }); +test('a markdown link is judged by the file it would OPEN, not by how its href ends', () => { + // The extension check and the opened path must look at the same string. A + // literal `?` or `#` starts the URL suffix, so `.md` after it names nothing. + const base = 'docs/report.md'; + assert.equal(resolveMdLinkRel(base, 'secrets.env?.md'), null, 'a `?.md` suffix must not open secrets.env'); + assert.equal(resolveMdLinkRel(base, 'secrets.env#.md'), null, 'a `#.md` fragment must not open secrets.env'); + assert.equal(resolveMdLinkRel(base, 'what?-notes.md'), null, 'the path is `what`, which is not markdown'); + assert.equal(resolveMdLinkRel(base, 'what%3F-notes.md'), 'docs/what?-notes.md', 'an encoded `?` is file-name data'); + assert.equal(resolveMdLinkRel(base, 'notes.md?v=2'), 'docs/notes.md', 'a query after a real .md is dropped, as for images'); + assert.equal(resolveMdLinkRel(base, 'NOTES.MARKDOWN'), 'docs/NOTES.MARKDOWN'); + assert.equal(resolveMdLinkRel(base, '#intro'), null, 'an anchor into the same document stays inert'); + assert.equal(resolveMdLinkRel(base, 'mailto:a@b.md'), null); +}); + // ─── the binary read itself ───────────────────────────────────────────────── /** A 1×1 PNG — a real file with a null byte in its header, i.e. exactly what the