fix: harden URL-decoded image paths

Co-authored-by: zcqqq <10296164+zcqqq@users.noreply.github.com>
This commit is contained in:
Jim Liu 宝玉
2026-05-27 21:34:59 -05:00
parent 876f01ac19
commit 84cefc2784
6 changed files with 130 additions and 13 deletions
@@ -0,0 +1,37 @@
import assert from "node:assert/strict";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import test from "node:test";
import { parseMarkdown } from "./md-to-html.ts";
async function makeTempDir(prefix: string): Promise<string> {
return fs.mkdtemp(path.join(os.tmpdir(), prefix));
}
test("parseMarkdown resolves encoded spaces and literal percent image paths", async (t) => {
const root = await makeTempDir("baoyu-post-to-x-images-");
t.after(() => fs.rm(root, { recursive: true, force: true }));
const articlePath = path.join(root, "article.md");
const tempDir = path.join(root, "tmp");
await fs.mkdir(tempDir, { recursive: true });
await fs.writeFile(path.join(root, "Pasted image.png"), "png");
await fs.writeFile(path.join(root, "100%.png"), "png");
await fs.writeFile(
articlePath,
[
"# Title",
"",
"![encoded](Pasted%20image.png)",
"",
"![literal](100%.png)",
].join("\n"),
);
const result = await parseMarkdown(articlePath, { tempDir });
assert.equal(result.contentImages[0]?.localPath, path.join(root, "Pasted image.png"));
assert.equal(result.contentImages[1]?.localPath, path.join(root, "100%.png"));
});
+21 -4
View File
@@ -181,12 +181,29 @@ async function resolveImagePath(imagePath: string, baseDir: string, tempDir: str
return localPath;
}
const decoded = decodeURIComponent(imagePath);
if (path.isAbsolute(decoded)) {
return decoded;
return resolveLocalImagePath(imagePath, baseDir);
}
function resolveLocalImagePath(imagePath: string, baseDir: string): string {
const decoded = safeDecodeImagePath(imagePath);
const resolved = resolveAgainstBaseDir(decoded, baseDir);
if (decoded === imagePath || fs.existsSync(resolved)) {
return resolved;
}
return path.resolve(baseDir, decoded);
return resolveAgainstBaseDir(imagePath, baseDir);
}
function safeDecodeImagePath(imagePath: string): string {
try {
return decodeURIComponent(imagePath);
} catch {
return imagePath;
}
}
function resolveAgainstBaseDir(imagePath: string, baseDir: string): string {
return path.isAbsolute(imagePath) ? imagePath : path.resolve(baseDir, imagePath);
}
function escapeHtml(text: string): string {