From 935f0fd00a6b8cb8c5950c46a1dda4af785bb034 Mon Sep 17 00:00:00 2001 From: clh02467605 Date: Tue, 24 Nov 2026 12:43:21 +0800 Subject: [PATCH 1/5] fix: preserve download symlinks and speech generate recovery info --- .../commands/src/commands/speech/generate.ts | 26 +++++++- .../tests/e2e/speech-generate.e2e.test.ts | 66 +++++++++++++++++++ packages/runtime/src/utils/download.ts | 35 ++++++++-- .../runtime/tests/download-publish.test.ts | 38 +++++++++++ skills/bailian-gen/SKILL.md | 3 +- 5 files changed, 160 insertions(+), 8 deletions(-) diff --git a/packages/commands/src/commands/speech/generate.ts b/packages/commands/src/commands/speech/generate.ts index 17810eec..81c035ee 100644 --- a/packages/commands/src/commands/speech/generate.ts +++ b/packages/commands/src/commands/speech/generate.ts @@ -531,9 +531,29 @@ export default defineCommand({ ); } - await downloadFile(audioUrl, destPath, { - quiet: settings.quiet || settings.output === "json", - }); + try { + await downloadFile(audioUrl, destPath, { + quiet: settings.quiet || settings.output === "json", + }); + } catch (error) { + const originalMessage = error instanceof Error ? error.message : String(error); + const exitCode = error instanceof BailianError ? error.exitCode : ExitCode.GENERAL; + const requestId = response.request_id?.trim(); + const detailParts = [ + requestId ? `request_id=${requestId}` : undefined, + `url=${audioUrl}`, + ].filter((part): part is string => part !== undefined); + throw new BailianError( + `${originalMessage} ${detailParts.join(" ")}`, + exitCode, + ctx.localize({ + "en-US": + "Audio was generated successfully. Re-download with the URL above; do not regenerate.", + "zh-CN": "音频已生成成功。请用上方 URL 重新下载,勿重新生成。", + }), + { cause: error }, + ); + } const result = { ...response, diff --git a/packages/commands/tests/e2e/speech-generate.e2e.test.ts b/packages/commands/tests/e2e/speech-generate.e2e.test.ts index 2d811cc5..36c62fed 100644 --- a/packages/commands/tests/e2e/speech-generate.e2e.test.ts +++ b/packages/commands/tests/e2e/speech-generate.e2e.test.ts @@ -465,6 +465,72 @@ describe("e2e: speech generate dry-run / mock HTTP", () => { await new Promise((resolve) => server.close(() => resolve())); } }); + + test("download HTTP failure keeps request_id and audio URL", async () => { + let synthesizePosts = 0; + const server = createServer((incoming, outgoing) => { + const url = incoming.url ?? ""; + if (url.startsWith("/api/v1/services/audio/tts/SpeechSynthesizer")) { + synthesizePosts += 1; + const address = server.address() as AddressInfo; + outgoing.writeHead(200, { "Content-Type": "application/json" }); + outgoing.end( + JSON.stringify({ + output: { + audio: { + url: `http://127.0.0.1:${address.port}/audio.wav`, + data: "", + id: "audio-1", + expires_at: "2099-01-01T00:00:00Z", + duration: 1.5, + }, + }, + usage: { characters: 10 }, + request_id: "req-gen-dl-fail", + }), + ); + return; + } + if (url.startsWith("/audio.wav")) { + outgoing.writeHead(403, { "Content-Type": "text/plain" }); + outgoing.end("forbidden"); + return; + } + outgoing.writeHead(404); + outgoing.end(); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address() as AddressInfo; + const outDir = makeE2eOutputDir("speech-generate-dl-fail"); + + try { + const failed = await runCommandInProcess(SPEECH_GENERATE_ROUTES, [ + "speech", + "generate", + "--text-prompt", + "短播客", + "--base-url", + `http://127.0.0.1:${address.port}`, + "--api-key", + "sk-e2e", + "--out-dir", + outDir, + "--out-prefix", + "sample", + "--quiet", + ]); + expect(failed.exitCode).not.toBe(0); + expect(synthesizePosts).toBe(1); + expect(failed.stderr).toMatch(/Download failed: HTTP 403/); + expect(failed.stderr).toMatch(/request_id=req-gen-dl-fail/); + expect(failed.stderr).toMatch( + new RegExp(`url=http://127\\.0\\.0\\.1:${address.port}/audio\\.wav`), + ); + expect(failed.stderr).toMatch(/do not regenerate|勿重新生成/i); + } finally { + await new Promise((resolve) => server.close(() => resolve())); + } + }); }); describe.skipIf(!isSpeechGenerateE2EReady())("e2e: speech generate (live)", () => { diff --git a/packages/runtime/src/utils/download.ts b/packages/runtime/src/utils/download.ts index eb2e2e7d..68d74146 100644 --- a/packages/runtime/src/utils/download.ts +++ b/packages/runtime/src/utils/download.ts @@ -4,12 +4,15 @@ import { copyFileSync, createWriteStream, existsSync, + lstatSync, mkdirSync, + readlinkSync, + realpathSync, renameSync, statSync, unlinkSync, } from "fs"; -import { basename, dirname, join } from "path"; +import { basename, dirname, isAbsolute, join } from "path"; import { BailianError, ExitCode } from "bailian-cli-core"; import { createProgressBar } from "../output/progress.ts"; import type { ReadableStreamReadResult } from "stream/web"; @@ -21,6 +24,28 @@ function errnoCode(error: unknown): string | undefined { return undefined; } +/** + * Resolve where bytes should land. Symlink destinations keep the link and + * update the target file (write-through), matching pre-temp-publish behavior. + */ +function resolvePublishPath(destPath: string): string { + let stats; + try { + stats = lstatSync(destPath); + } catch { + return destPath; + } + if (!stats.isSymbolicLink()) { + return destPath; + } + try { + return realpathSync(destPath); + } catch { + const linkTarget = readlinkSync(destPath); + return isAbsolute(linkTarget) ? linkTarget : join(dirname(destPath), linkTarget); + } +} + /** * Publish temp over dest without unlinking dest first. * Existing dest is moved aside and restored if publish fails. @@ -96,11 +121,13 @@ export async function downloadFile( mkdirSync(dirname(destPath), { recursive: true }); + const publishPath = resolvePublishPath(destPath); + let preserveMode: number | undefined; try { - preserveMode = statSync(destPath).mode & 0o7777; + preserveMode = statSync(publishPath).mode & 0o7777; } catch { - // Destination does not exist yet. + // Destination (or symlink target) does not exist yet. } // Same-directory temp so rename stays on one filesystem; never truncate dest until publish. @@ -154,7 +181,7 @@ export async function downloadFile( } try { - publishDownloadedFile(tempPath, destPath, preserveMode); + publishDownloadedFile(tempPath, publishPath, preserveMode); } catch (error) { try { unlinkSync(tempPath); diff --git a/packages/runtime/tests/download-publish.test.ts b/packages/runtime/tests/download-publish.test.ts index 67165c2e..18df3dbf 100644 --- a/packages/runtime/tests/download-publish.test.ts +++ b/packages/runtime/tests/download-publish.test.ts @@ -1,11 +1,13 @@ import { afterEach, beforeEach, expect, test, vi } from "vite-plus/test"; import { chmodSync, + lstatSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, + symlinkSync, writeFileSync, } from "node:fs"; import { tmpdir } from "node:os"; @@ -119,3 +121,39 @@ test("publish rename EPERM falls back to copy and keeps the previous mode", asyn expect(statSync(destination).mode & 0o777).toBe(0o600); expect(readdirSync(directory)).toEqual(["take.wav"]); }); + +test("symlink destination stays a link and the target receives new bytes", async () => { + const targetPath = join(directory, "canonical.wav"); + const linkPath = join(directory, "alias.wav"); + writeFileSync(targetPath, "original-audio", { mode: 0o600 }); + chmodSync(targetPath, 0o600); + symlinkSync(targetPath, linkPath); + + serveBody("new-audio"); + expect(await downloadFile("https://example.invalid/file", linkPath, { quiet: true })).toEqual({ + size: 9, + }); + + expect(lstatSync(linkPath).isSymbolicLink()).toBe(true); + expect(readFileSync(targetPath, "utf-8")).toBe("new-audio"); + expect(readFileSync(linkPath, "utf-8")).toBe("new-audio"); + expect(statSync(targetPath).mode & 0o777).toBe(0o600); +}); + +test("symlink publish failure restores the previous target bytes", async () => { + const targetPath = join(directory, "canonical.wav"); + const linkPath = join(directory, "alias.wav"); + writeFileSync(targetPath, "original-audio", { mode: 0o600 }); + chmodSync(targetPath, 0o600); + symlinkSync(targetPath, linkPath); + + serveBody("new-audio"); + injection.renameCodes = [null, "EIO"]; + await expect( + downloadFile("https://example.invalid/file", linkPath, { quiet: true }), + ).rejects.toThrow("injected EIO"); + + expect(lstatSync(linkPath).isSymbolicLink()).toBe(true); + expect(readFileSync(targetPath, "utf-8")).toBe("original-audio"); + expect(readFileSync(linkPath, "utf-8")).toBe("original-audio"); +}); diff --git a/skills/bailian-gen/SKILL.md b/skills/bailian-gen/SKILL.md index 2234c1c7..79b5ab10 100644 --- a/skills/bailian-gen/SKILL.md +++ b/skills/bailian-gen/SKILL.md @@ -46,7 +46,8 @@ BAILIAN_CALLER_TYPE=agent BAILIAN_CALLER_NAME=codex BAILIAN_SKILL_NAME=bailian-g | Video edit / style transfer | `bl video edit` | `happyhorse-1.0-video-edit` | | Reference-to-video + voice | `bl video ref` | `wan3.0-video` | | Speech synthesis (TTS / voiceover) | `bl speech synthesize` | `cosyvoice-v3-flash` | -| Voice clone / manage | `bl speech voice clone/list/get/update/delete/preview` | CosyVoice/Qwen-Audio: `voice-enrollment` → `speech synthesize --model`. Omni (non-realtime flash/plus only): `qwen-voice-enrollment` create/list/delete → `omni --model --voice` | | Voice design from text | `bl speech voice design` | `voice-enrollment` → preview saved locally; formal listen via `speech synthesize` (not for Omni targets) | +| Voice clone / manage | `bl speech voice clone/list/get/update/delete/preview` | CosyVoice/Qwen-Audio: `voice-enrollment` → `speech synthesize --model`. Omni (non-realtime flash/plus only): `qwen-voice-enrollment` create/list/delete → `omni --model --voice` | +| Voice design from text | `bl speech voice design` | `voice-enrollment` → preview saved locally; formal listen via `speech synthesize` (not for Omni targets) | | Audio content generation (podcast/dialogue) | `bl speech generate` | `qwen-audio-3.1-tts-next` (text_prompt/references; not voice IDs) | | Speech recognition (ASR / transcription) | `bl speech recognize` | `fun-asr` | | Image describe | `bl vision describe` | `qwen3-vl-plus`;宿主能做且未点名 → host-first | From 9e31fd5f14e78704559be409e4753701b0f66bff Mon Sep 17 00:00:00 2001 From: clh02467605 Date: Tue, 24 Nov 2026 13:28:41 +0800 Subject: [PATCH 2/5] fix: keep speech download URLs out of telemetry and write through symlink chains --- .../commands/src/commands/speech/generate.ts | 17 ++- .../tests/e2e/speech-generate.e2e.test.ts | 4 +- packages/runtime/src/utils/download.ts | 100 ++++++++++++------ .../runtime/tests/download-publish.test.ts | 95 ++++++++++++++++- 4 files changed, 170 insertions(+), 46 deletions(-) diff --git a/packages/commands/src/commands/speech/generate.ts b/packages/commands/src/commands/speech/generate.ts index 81c035ee..6bafb2ef 100644 --- a/packages/commands/src/commands/speech/generate.ts +++ b/packages/commands/src/commands/speech/generate.ts @@ -539,19 +539,18 @@ export default defineCommand({ const originalMessage = error instanceof Error ? error.message : String(error); const exitCode = error instanceof BailianError ? error.exitCode : ExitCode.GENERAL; const requestId = response.request_id?.trim(); - const detailParts = [ - requestId ? `request_id=${requestId}` : undefined, - `url=${audioUrl}`, - ].filter((part): part is string => part !== undefined); + // Keep the signed URL in hint only — telemetry records message / api.requestId, not hint. throw new BailianError( - `${originalMessage} ${detailParts.join(" ")}`, + requestId ? `${originalMessage} request_id=${requestId}` : originalMessage, exitCode, ctx.localize({ - "en-US": - "Audio was generated successfully. Re-download with the URL above; do not regenerate.", - "zh-CN": "音频已生成成功。请用上方 URL 重新下载,勿重新生成。", + "en-US": `Audio was generated successfully. Re-download from: ${audioUrl}; do not regenerate.`, + "zh-CN": `音频已生成成功。请从以下地址重新下载,勿重新生成:${audioUrl}`, }), - { cause: error }, + { + cause: error, + ...(requestId ? { api: { requestId } } : {}), + }, ); } diff --git a/packages/commands/tests/e2e/speech-generate.e2e.test.ts b/packages/commands/tests/e2e/speech-generate.e2e.test.ts index 36c62fed..b3fc46ba 100644 --- a/packages/commands/tests/e2e/speech-generate.e2e.test.ts +++ b/packages/commands/tests/e2e/speech-generate.e2e.test.ts @@ -523,9 +523,11 @@ describe("e2e: speech generate dry-run / mock HTTP", () => { expect(synthesizePosts).toBe(1); expect(failed.stderr).toMatch(/Download failed: HTTP 403/); expect(failed.stderr).toMatch(/request_id=req-gen-dl-fail/); + // Signed URL stays in the hint (CLI recovery), not as message `url=` for telemetry. expect(failed.stderr).toMatch( - new RegExp(`url=http://127\\.0\\.0\\.1:${address.port}/audio\\.wav`), + new RegExp(`http://127\\.0\\.0\\.1:${address.port}/audio\\.wav`), ); + expect(failed.stderr).not.toMatch(/url=http:\/\//); expect(failed.stderr).toMatch(/do not regenerate|勿重新生成/i); } finally { await new Promise((resolve) => server.close(() => resolve())); diff --git a/packages/runtime/src/utils/download.ts b/packages/runtime/src/utils/download.ts index 68d74146..611de984 100644 --- a/packages/runtime/src/utils/download.ts +++ b/packages/runtime/src/utils/download.ts @@ -7,7 +7,6 @@ import { lstatSync, mkdirSync, readlinkSync, - realpathSync, renameSync, statSync, unlinkSync, @@ -25,24 +24,70 @@ function errnoCode(error: unknown): string | undefined { } /** - * Resolve where bytes should land. Symlink destinations keep the link and - * update the target file (write-through), matching pre-temp-publish behavior. + * Walk the full symlink chain (including dangling links) so publish writes + * through to the final path and leaves intermediate links intact. */ function resolvePublishPath(destPath: string): string { + let current = destPath; + const seen = new Set(); + for (;;) { + let stats; + try { + stats = lstatSync(current); + } catch { + return current; + } + if (!stats.isSymbolicLink()) { + return current; + } + if (seen.has(current)) { + throw new BailianError( + `Symbolic link cycle detected while resolving download path: ${destPath}`, + ExitCode.GENERAL, + ); + } + seen.add(current); + const linkTarget = readlinkSync(current); + current = isAbsolute(linkTarget) ? linkTarget : join(dirname(current), linkTarget); + } +} + +/** + * Refuse directories and other non-files before publish (matches 2.10.5 EISDIR + * fail-fast; avoids renaming a directory aside and rolling back on unlink). + */ +function assertPublishPathIsFileOrAbsent(publishPath: string): void { let stats; try { - stats = lstatSync(destPath); + stats = lstatSync(publishPath); } catch { - return destPath; + return; } - if (!stats.isSymbolicLink()) { - return destPath; + if (!stats.isFile()) { + throw new BailianError( + `Download destination must be a regular file: ${publishPath}`, + ExitCode.USAGE, + ); } +} + +/** renameSync with copy fallback for Windows / cross-device publishes. */ +function renameOrCopyIntoPlace(tempPath: string, destPath: string): void { try { - return realpathSync(destPath); - } catch { - const linkTarget = readlinkSync(destPath); - return isAbsolute(linkTarget) ? linkTarget : join(dirname(destPath), linkTarget); + renameSync(tempPath, destPath); + } catch (renameError) { + const code = errnoCode(renameError); + // Windows cannot rename onto an existing name; EXDEV needs a copy. + if (code === "EEXIST" || code === "EPERM" || code === "EXDEV") { + copyFileSync(tempPath, destPath); + try { + unlinkSync(tempPath); + } catch { + /* best effort */ + } + return; + } + throw renameError; } } @@ -56,7 +101,7 @@ function publishDownloadedFile( preserveMode: number | undefined, ): void { if (!existsSync(destPath)) { - renameSync(tempPath, destPath); + renameOrCopyIntoPlace(tempPath, destPath); return; } @@ -67,23 +112,7 @@ function publishDownloadedFile( renameSync(destPath, backupPath); try { - try { - renameSync(tempPath, destPath); - } catch (renameError) { - const code = errnoCode(renameError); - // Windows cannot rename onto an existing name; EXDEV needs a copy. - // Never unlink dest first — backup already holds the previous bytes. - if (code === "EEXIST" || code === "EPERM" || code === "EXDEV") { - copyFileSync(tempPath, destPath); - try { - unlinkSync(tempPath); - } catch { - /* best effort */ - } - } else { - throw renameError; - } - } + renameOrCopyIntoPlace(tempPath, destPath); if (preserveMode !== undefined) { chmodSync(destPath, preserveMode); @@ -109,6 +138,9 @@ export async function downloadFile( destPath: string, opts?: { quiet?: boolean }, ): Promise<{ size: number }> { + const publishPath = resolvePublishPath(destPath); + assertPublishPathIsFileOrAbsent(publishPath); + const res = await httpTransport.fetch(url); if (!res.ok) { @@ -119,9 +151,7 @@ export async function downloadFile( const reader = res.body?.getReader(); if (!reader) throw new BailianError("No response body", ExitCode.GENERAL); - mkdirSync(dirname(destPath), { recursive: true }); - - const publishPath = resolvePublishPath(destPath); + mkdirSync(dirname(publishPath), { recursive: true }); let preserveMode: number | undefined; try { @@ -130,10 +160,10 @@ export async function downloadFile( // Destination (or symlink target) does not exist yet. } - // Same-directory temp so rename stays on one filesystem; never truncate dest until publish. + // Temp beside the publish path so rename stays on one filesystem when possible. const tempPath = join( - dirname(destPath), - `.${basename(destPath)}.${process.pid}.${Date.now()}.part`, + dirname(publishPath), + `.${basename(publishPath)}.${process.pid}.${Date.now()}.part`, ); const writer = createWriteStream(tempPath); const progress = diff --git a/packages/runtime/tests/download-publish.test.ts b/packages/runtime/tests/download-publish.test.ts index 18df3dbf..207cb3d7 100644 --- a/packages/runtime/tests/download-publish.test.ts +++ b/packages/runtime/tests/download-publish.test.ts @@ -2,6 +2,7 @@ import { afterEach, beforeEach, expect, test, vi } from "vite-plus/test"; import { chmodSync, lstatSync, + mkdirSync, mkdtempSync, readFileSync, readdirSync, @@ -12,7 +13,7 @@ import { } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { httpTransport } from "bailian-cli-core"; +import { BailianError, ExitCode, httpTransport } from "bailian-cli-core"; import { downloadFile } from "../src/utils/download.ts"; // Publish-path failures (thrown after the body is fully downloaded) must never @@ -157,3 +158,95 @@ test("symlink publish failure restores the previous target bytes", async () => { expect(readFileSync(targetPath, "utf-8")).toBe("original-audio"); expect(readFileSync(linkPath, "utf-8")).toBe("original-audio"); }); + +test("nested dangling symlink chain creates the final target and keeps links", async () => { + const finalPath = join(directory, "final.wav"); + const midPath = join(directory, "mid.wav"); + const linkPath = join(directory, "out.wav"); + symlinkSync(finalPath, midPath); + symlinkSync(midPath, linkPath); + + serveBody("new-audio"); + expect(await downloadFile("https://example.invalid/file", linkPath, { quiet: true })).toEqual({ + size: 9, + }); + + expect(lstatSync(linkPath).isSymbolicLink()).toBe(true); + expect(lstatSync(midPath).isSymbolicLink()).toBe(true); + expect(readFileSync(finalPath, "utf-8")).toBe("new-audio"); + expect(readFileSync(linkPath, "utf-8")).toBe("new-audio"); +}); + +test("dangling symlink to another directory creates the target file", async () => { + const otherDirectory = join(directory, "other"); + mkdirSync(otherDirectory); + const targetPath = join(otherDirectory, "remote.wav"); + const linkPath = join(directory, "alias.wav"); + symlinkSync(targetPath, linkPath); + + serveBody("new-audio"); + expect(await downloadFile("https://example.invalid/file", linkPath, { quiet: true })).toEqual({ + size: 9, + }); + + expect(lstatSync(linkPath).isSymbolicLink()).toBe(true); + expect(readFileSync(targetPath, "utf-8")).toBe("new-audio"); +}); + +test("new publish path EXDEV falls back to copy beside the resolved target", async () => { + const otherDirectory = join(directory, "other"); + mkdirSync(otherDirectory); + const targetPath = join(otherDirectory, "remote.wav"); + const linkPath = join(directory, "alias.wav"); + symlinkSync(targetPath, linkPath); + + serveBody("new-audio"); + // First rename is temp -> publishPath (missing); EXDEV should copy instead of failing. + injection.renameCodes = ["EXDEV"]; + expect(await downloadFile("https://example.invalid/file", linkPath, { quiet: true })).toEqual({ + size: 9, + }); + + expect(lstatSync(linkPath).isSymbolicLink()).toBe(true); + expect(readFileSync(targetPath, "utf-8")).toBe("new-audio"); +}); + +test("refuses a directory destination without moving it aside", async () => { + const targetDirectory = join(directory, "target-dir"); + mkdirSync(targetDirectory); + writeFileSync(join(targetDirectory, "keep.txt"), "keep"); + + const fetchSpy = vi.spyOn(httpTransport, "fetch"); + await expect( + downloadFile("https://example.invalid/file", targetDirectory, { quiet: true }), + ).rejects.toSatisfy((error: unknown) => { + expect(error).toBeInstanceOf(BailianError); + expect((error as BailianError).exitCode).toBe(ExitCode.USAGE); + expect((error as BailianError).message).toMatch(/must be a regular file/); + return true; + }); + + expect(fetchSpy).not.toHaveBeenCalled(); + expect(lstatSync(targetDirectory).isDirectory()).toBe(true); + expect(readFileSync(join(targetDirectory, "keep.txt"), "utf-8")).toBe("keep"); + expect(readdirSync(directory).some((name) => name.includes(".bak"))).toBe(false); +}); + +test("refuses a symlink whose final target is a directory", async () => { + const targetDirectory = join(directory, "target-dir"); + mkdirSync(targetDirectory); + writeFileSync(join(targetDirectory, "keep.txt"), "keep"); + const linkPath = join(directory, "out.wav"); + symlinkSync(targetDirectory, linkPath); + + const fetchSpy = vi.spyOn(httpTransport, "fetch"); + await expect( + downloadFile("https://example.invalid/file", linkPath, { quiet: true }), + ).rejects.toThrow(/must be a regular file/); + + expect(fetchSpy).not.toHaveBeenCalled(); + expect(lstatSync(linkPath).isSymbolicLink()).toBe(true); + expect(lstatSync(targetDirectory).isDirectory()).toBe(true); + expect(readFileSync(join(targetDirectory, "keep.txt"), "utf-8")).toBe("keep"); + expect(readdirSync(directory).some((name) => name.includes(".bak"))).toBe(false); +}); From 6cb9c75036920dcafc4d8882f18bdcf654d0e30c Mon Sep 17 00:00:00 2001 From: clh02467605 Date: Tue, 24 Nov 2026 14:01:49 +0800 Subject: [PATCH 3/5] fix: resolve download symlink paths with OS realpath semantics --- packages/runtime/src/utils/download.ts | 52 +++++++++++++++++-- .../runtime/tests/download-publish.test.ts | 45 ++++++++++++++++ 2 files changed, 94 insertions(+), 3 deletions(-) diff --git a/packages/runtime/src/utils/download.ts b/packages/runtime/src/utils/download.ts index 611de984..d18dfaf2 100644 --- a/packages/runtime/src/utils/download.ts +++ b/packages/runtime/src/utils/download.ts @@ -7,6 +7,7 @@ import { lstatSync, mkdirSync, readlinkSync, + realpathSync, renameSync, statSync, unlinkSync, @@ -23,11 +24,56 @@ function errnoCode(error: unknown): string | undefined { return undefined; } +/** OS physical realpath (same resolution family as 2.10.5 open/createWriteStream). */ +function nativeRealpath(pathToResolve: string): string { + return realpathSync.native(pathToResolve); +} + /** - * Walk the full symlink chain (including dangling links) so publish writes - * through to the final path and leaves intermediate links intact. + * Resolve a relative symlink target against the link location without path.join + * collapsing "dirsymlink/.." before the directory symlink is followed. + */ +function resolveRelativeLinkTarget(linkPath: string, linkTarget: string): string { + let resolvedBase: string; + try { + resolvedBase = nativeRealpath(dirname(linkPath)); + } catch { + resolvedBase = dirname(linkPath); + } + + const segments = linkTarget + .split(/[/\\]+/) + .filter((segment) => segment.length > 0 && segment !== "."); + let resolved = resolvedBase; + for (let index = 0; index < segments.length; index++) { + const segment = segments[index]!; + if (segment === "..") { + resolved = dirname(resolved); + continue; + } + const candidate = join(resolved, segment); + try { + // Follow directory (or file) symlinks the way open(2) does. + resolved = nativeRealpath(candidate); + } catch { + // Remainder is dangling — keep the physical prefix, join only the missing tail. + return join(candidate, ...segments.slice(index + 1)); + } + } + return resolved; +} + +/** + * Resolve where bytes should land. Prefer OS realpath (2.10.5 write-through + * semantics); for dangling links walk the chain without lexical ".." collapse. */ function resolvePublishPath(destPath: string): string { + try { + return nativeRealpath(destPath); + } catch { + // Final path missing or unresolvable — walk links explicitly below. + } + let current = destPath; const seen = new Set(); for (;;) { @@ -48,7 +94,7 @@ function resolvePublishPath(destPath: string): string { } seen.add(current); const linkTarget = readlinkSync(current); - current = isAbsolute(linkTarget) ? linkTarget : join(dirname(current), linkTarget); + current = isAbsolute(linkTarget) ? linkTarget : resolveRelativeLinkTarget(current, linkTarget); } } diff --git a/packages/runtime/tests/download-publish.test.ts b/packages/runtime/tests/download-publish.test.ts index 207cb3d7..6568e99e 100644 --- a/packages/runtime/tests/download-publish.test.ts +++ b/packages/runtime/tests/download-publish.test.ts @@ -211,6 +211,51 @@ test("new publish path EXDEV falls back to copy beside the resolved target", asy expect(readFileSync(targetPath, "utf-8")).toBe("new-audio"); }); +test("relative link through a directory symlink does not overwrite a lexical decoy", async () => { + // portal -> elsewhere/real-home; alias -> portal/../out.wav + // Lexical join would hit root/out.wav; OS resolution hits elsewhere/out.wav. + const elsewhere = join(directory, "elsewhere"); + const realHome = join(elsewhere, "real-home"); + mkdirSync(realHome, { recursive: true }); + const trueTarget = join(elsewhere, "out.wav"); + const decoyPath = join(directory, "out.wav"); + writeFileSync(trueTarget, "true-old"); + writeFileSync(decoyPath, "decoy-old"); + symlinkSync(realHome, join(directory, "portal")); + const linkPath = join(directory, "alias.wav"); + symlinkSync("portal/../out.wav", linkPath); + + serveBody("new-audio"); + expect(await downloadFile("https://example.invalid/file", linkPath, { quiet: true })).toEqual({ + size: 9, + }); + + expect(lstatSync(linkPath).isSymbolicLink()).toBe(true); + expect(readFileSync(trueTarget, "utf-8")).toBe("new-audio"); + expect(readFileSync(decoyPath, "utf-8")).toBe("decoy-old"); +}); + +test("dangling relative link through a directory symlink creates the physical target", async () => { + const elsewhere = join(directory, "elsewhere"); + const realHome = join(elsewhere, "real-home"); + mkdirSync(realHome, { recursive: true }); + const trueTarget = join(elsewhere, "out.wav"); + const decoyPath = join(directory, "out.wav"); + writeFileSync(decoyPath, "decoy-old"); + symlinkSync(realHome, join(directory, "portal")); + const linkPath = join(directory, "alias.wav"); + symlinkSync("portal/../out.wav", linkPath); + + serveBody("new-audio"); + expect(await downloadFile("https://example.invalid/file", linkPath, { quiet: true })).toEqual({ + size: 9, + }); + + expect(lstatSync(linkPath).isSymbolicLink()).toBe(true); + expect(readFileSync(trueTarget, "utf-8")).toBe("new-audio"); + expect(readFileSync(decoyPath, "utf-8")).toBe("decoy-old"); +}); + test("refuses a directory destination without moving it aside", async () => { const targetDirectory = join(directory, "target-dir"); mkdirSync(targetDirectory); From 5d162d9485425c86a13ed5149054a5f3efb975d8 Mon Sep 17 00:00:00 2001 From: clh02467605 Date: Tue, 24 Nov 2026 15:15:27 +0800 Subject: [PATCH 4/5] revert: restore downloadFile to v2.10.5 direct-write semantics --- packages/runtime/src/utils/download.ts | 211 +------------ .../runtime/tests/download-publish.test.ts | 297 ------------------ .../runtime/tests/progress-output.test.ts | 95 +----- 3 files changed, 6 insertions(+), 597 deletions(-) delete mode 100644 packages/runtime/tests/download-publish.test.ts diff --git a/packages/runtime/src/utils/download.ts b/packages/runtime/src/utils/download.ts index d18dfaf2..44ed978e 100644 --- a/packages/runtime/src/utils/download.ts +++ b/packages/runtime/src/utils/download.ts @@ -1,192 +1,15 @@ import { httpTransport } from "bailian-cli-core"; -import { - chmodSync, - copyFileSync, - createWriteStream, - existsSync, - lstatSync, - mkdirSync, - readlinkSync, - realpathSync, - renameSync, - statSync, - unlinkSync, -} from "fs"; -import { basename, dirname, isAbsolute, join } from "path"; +import { createWriteStream, mkdirSync, unlinkSync } from "fs"; +import { dirname } from "path"; import { BailianError, ExitCode } from "bailian-cli-core"; import { createProgressBar } from "../output/progress.ts"; import type { ReadableStreamReadResult } from "stream/web"; -function errnoCode(error: unknown): string | undefined { - if (error !== null && typeof error === "object" && "code" in error) { - return (error as NodeJS.ErrnoException).code; - } - return undefined; -} - -/** OS physical realpath (same resolution family as 2.10.5 open/createWriteStream). */ -function nativeRealpath(pathToResolve: string): string { - return realpathSync.native(pathToResolve); -} - -/** - * Resolve a relative symlink target against the link location without path.join - * collapsing "dirsymlink/.." before the directory symlink is followed. - */ -function resolveRelativeLinkTarget(linkPath: string, linkTarget: string): string { - let resolvedBase: string; - try { - resolvedBase = nativeRealpath(dirname(linkPath)); - } catch { - resolvedBase = dirname(linkPath); - } - - const segments = linkTarget - .split(/[/\\]+/) - .filter((segment) => segment.length > 0 && segment !== "."); - let resolved = resolvedBase; - for (let index = 0; index < segments.length; index++) { - const segment = segments[index]!; - if (segment === "..") { - resolved = dirname(resolved); - continue; - } - const candidate = join(resolved, segment); - try { - // Follow directory (or file) symlinks the way open(2) does. - resolved = nativeRealpath(candidate); - } catch { - // Remainder is dangling — keep the physical prefix, join only the missing tail. - return join(candidate, ...segments.slice(index + 1)); - } - } - return resolved; -} - -/** - * Resolve where bytes should land. Prefer OS realpath (2.10.5 write-through - * semantics); for dangling links walk the chain without lexical ".." collapse. - */ -function resolvePublishPath(destPath: string): string { - try { - return nativeRealpath(destPath); - } catch { - // Final path missing or unresolvable — walk links explicitly below. - } - - let current = destPath; - const seen = new Set(); - for (;;) { - let stats; - try { - stats = lstatSync(current); - } catch { - return current; - } - if (!stats.isSymbolicLink()) { - return current; - } - if (seen.has(current)) { - throw new BailianError( - `Symbolic link cycle detected while resolving download path: ${destPath}`, - ExitCode.GENERAL, - ); - } - seen.add(current); - const linkTarget = readlinkSync(current); - current = isAbsolute(linkTarget) ? linkTarget : resolveRelativeLinkTarget(current, linkTarget); - } -} - -/** - * Refuse directories and other non-files before publish (matches 2.10.5 EISDIR - * fail-fast; avoids renaming a directory aside and rolling back on unlink). - */ -function assertPublishPathIsFileOrAbsent(publishPath: string): void { - let stats; - try { - stats = lstatSync(publishPath); - } catch { - return; - } - if (!stats.isFile()) { - throw new BailianError( - `Download destination must be a regular file: ${publishPath}`, - ExitCode.USAGE, - ); - } -} - -/** renameSync with copy fallback for Windows / cross-device publishes. */ -function renameOrCopyIntoPlace(tempPath: string, destPath: string): void { - try { - renameSync(tempPath, destPath); - } catch (renameError) { - const code = errnoCode(renameError); - // Windows cannot rename onto an existing name; EXDEV needs a copy. - if (code === "EEXIST" || code === "EPERM" || code === "EXDEV") { - copyFileSync(tempPath, destPath); - try { - unlinkSync(tempPath); - } catch { - /* best effort */ - } - return; - } - throw renameError; - } -} - -/** - * Publish temp over dest without unlinking dest first. - * Existing dest is moved aside and restored if publish fails. - */ -function publishDownloadedFile( - tempPath: string, - destPath: string, - preserveMode: number | undefined, -): void { - if (!existsSync(destPath)) { - renameOrCopyIntoPlace(tempPath, destPath); - return; - } - - const backupPath = join( - dirname(destPath), - `.${basename(destPath)}.${process.pid}.${Date.now()}.bak`, - ); - renameSync(destPath, backupPath); - - try { - renameOrCopyIntoPlace(tempPath, destPath); - - if (preserveMode !== undefined) { - chmodSync(destPath, preserveMode); - } - unlinkSync(backupPath); - } catch (error) { - try { - if (existsSync(destPath)) unlinkSync(destPath); - } catch { - /* best effort */ - } - try { - renameSync(backupPath, destPath); - } catch { - /* best effort */ - } - throw error; - } -} - export async function downloadFile( url: string, destPath: string, opts?: { quiet?: boolean }, ): Promise<{ size: number }> { - const publishPath = resolvePublishPath(destPath); - assertPublishPathIsFileOrAbsent(publishPath); - const res = await httpTransport.fetch(url); if (!res.ok) { @@ -197,21 +20,8 @@ export async function downloadFile( const reader = res.body?.getReader(); if (!reader) throw new BailianError("No response body", ExitCode.GENERAL); - mkdirSync(dirname(publishPath), { recursive: true }); - - let preserveMode: number | undefined; - try { - preserveMode = statSync(publishPath).mode & 0o7777; - } catch { - // Destination (or symlink target) does not exist yet. - } - - // Temp beside the publish path so rename stays on one filesystem when possible. - const tempPath = join( - dirname(publishPath), - `.${basename(publishPath)}.${process.pid}.${Date.now()}.part`, - ); - const writer = createWriteStream(tempPath); + mkdirSync(dirname(destPath), { recursive: true }); + const writer = createWriteStream(destPath); const progress = contentLength > 0 && !opts?.quiet ? createProgressBar(contentLength, "Downloading") : null; @@ -249,24 +59,13 @@ export async function downloadFile( if (!completed) { try { - unlinkSync(tempPath); + unlinkSync(destPath); } catch { /* best effort */ } } } - try { - publishDownloadedFile(tempPath, publishPath, preserveMode); - } catch (error) { - try { - unlinkSync(tempPath); - } catch { - /* best effort */ - } - throw error; - } - return { size: received }; } diff --git a/packages/runtime/tests/download-publish.test.ts b/packages/runtime/tests/download-publish.test.ts deleted file mode 100644 index 6568e99e..00000000 --- a/packages/runtime/tests/download-publish.test.ts +++ /dev/null @@ -1,297 +0,0 @@ -import { afterEach, beforeEach, expect, test, vi } from "vite-plus/test"; -import { - chmodSync, - lstatSync, - mkdirSync, - mkdtempSync, - readFileSync, - readdirSync, - rmSync, - statSync, - symlinkSync, - writeFileSync, -} from "node:fs"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { BailianError, ExitCode, httpTransport } from "bailian-cli-core"; -import { downloadFile } from "../src/utils/download.ts"; - -// Publish-path failures (thrown after the body is fully downloaded) must never -// lose the previous destination bytes. renameSync/copyFileSync errnos are -// injected without touching real permissions: `renameCodes` is consumed in call -// order, null lets the real rename run. -const injection = vi.hoisted(() => ({ - renameCodes: [] as Array, - copyErrorCode: undefined as string | undefined, -})); - -vi.mock("fs", async (importOriginal) => { - const actual = await importOriginal(); - const fail = (code: string, action: string): never => { - const error = new Error(`injected ${code}: ${action}`) as NodeJS.ErrnoException; - error.code = code; - throw error; - }; - return { - ...actual, - renameSync: ((from: string, to: string) => { - const code = injection.renameCodes.shift(); - if (code !== undefined && code !== null) fail(code, `rename ${from} -> ${to}`); - return actual.renameSync(from, to); - }) as typeof actual.renameSync, - copyFileSync: ((from: string, to: string) => { - if (injection.copyErrorCode !== undefined) { - fail(injection.copyErrorCode, `copy ${from} -> ${to}`); - } - return actual.copyFileSync(from, to); - }) as typeof actual.copyFileSync, - }; -}); - -function serveBody(text: string): void { - vi.spyOn(httpTransport, "fetch").mockResolvedValue( - new Response( - new ReadableStream({ - start(controller) { - controller.enqueue(new TextEncoder().encode(text)); - controller.close(); - }, - }), - { headers: { "content-length": String(text.length) } }, - ), - ); -} - -let directory = ""; -let destination = ""; - -beforeEach(() => { - injection.renameCodes = []; - injection.copyErrorCode = undefined; - directory = mkdtempSync(join(tmpdir(), "bl-download-publish-")); - destination = join(directory, "take.wav"); - writeFileSync(destination, "original-audio", { mode: 0o600 }); - chmodSync(destination, 0o600); -}); - -afterEach(() => { - vi.restoreAllMocks(); - rmSync(directory, { recursive: true, force: true }); -}); - -test("backup rename EPERM aborts publish with the destination untouched", async () => { - serveBody("new-audio"); - injection.renameCodes = ["EPERM", "EIO"]; - await expect( - downloadFile("https://example.invalid/file", destination, { quiet: true }), - ).rejects.toThrow("injected EPERM"); - expect(readFileSync(destination, "utf-8")).toBe("original-audio"); - expect(statSync(destination).mode & 0o777).toBe(0o600); - expect(readdirSync(directory)).toEqual(["take.wav"]); -}); - -test("publish rename EPERM then copy EIO restores the previous file", async () => { - serveBody("new-audio"); - injection.renameCodes = [null, "EPERM"]; - injection.copyErrorCode = "EIO"; - await expect( - downloadFile("https://example.invalid/file", destination, { quiet: true }), - ).rejects.toThrow("injected EIO"); - expect(readFileSync(destination, "utf-8")).toBe("original-audio"); - expect(statSync(destination).mode & 0o777).toBe(0o600); - expect(readdirSync(directory)).toEqual(["take.wav"]); -}); - -test("publish rename EIO without fallback restores the previous file", async () => { - serveBody("new-audio"); - injection.renameCodes = [null, "EIO"]; - await expect( - downloadFile("https://example.invalid/file", destination, { quiet: true }), - ).rejects.toThrow("injected EIO"); - expect(readFileSync(destination, "utf-8")).toBe("original-audio"); - expect(readdirSync(directory)).toEqual(["take.wav"]); -}); - -test("publish rename EPERM falls back to copy and keeps the previous mode", async () => { - serveBody("new-audio"); - injection.renameCodes = [null, "EPERM"]; - expect(await downloadFile("https://example.invalid/file", destination, { quiet: true })).toEqual({ - size: 9, - }); - expect(readFileSync(destination, "utf-8")).toBe("new-audio"); - expect(statSync(destination).mode & 0o777).toBe(0o600); - expect(readdirSync(directory)).toEqual(["take.wav"]); -}); - -test("symlink destination stays a link and the target receives new bytes", async () => { - const targetPath = join(directory, "canonical.wav"); - const linkPath = join(directory, "alias.wav"); - writeFileSync(targetPath, "original-audio", { mode: 0o600 }); - chmodSync(targetPath, 0o600); - symlinkSync(targetPath, linkPath); - - serveBody("new-audio"); - expect(await downloadFile("https://example.invalid/file", linkPath, { quiet: true })).toEqual({ - size: 9, - }); - - expect(lstatSync(linkPath).isSymbolicLink()).toBe(true); - expect(readFileSync(targetPath, "utf-8")).toBe("new-audio"); - expect(readFileSync(linkPath, "utf-8")).toBe("new-audio"); - expect(statSync(targetPath).mode & 0o777).toBe(0o600); -}); - -test("symlink publish failure restores the previous target bytes", async () => { - const targetPath = join(directory, "canonical.wav"); - const linkPath = join(directory, "alias.wav"); - writeFileSync(targetPath, "original-audio", { mode: 0o600 }); - chmodSync(targetPath, 0o600); - symlinkSync(targetPath, linkPath); - - serveBody("new-audio"); - injection.renameCodes = [null, "EIO"]; - await expect( - downloadFile("https://example.invalid/file", linkPath, { quiet: true }), - ).rejects.toThrow("injected EIO"); - - expect(lstatSync(linkPath).isSymbolicLink()).toBe(true); - expect(readFileSync(targetPath, "utf-8")).toBe("original-audio"); - expect(readFileSync(linkPath, "utf-8")).toBe("original-audio"); -}); - -test("nested dangling symlink chain creates the final target and keeps links", async () => { - const finalPath = join(directory, "final.wav"); - const midPath = join(directory, "mid.wav"); - const linkPath = join(directory, "out.wav"); - symlinkSync(finalPath, midPath); - symlinkSync(midPath, linkPath); - - serveBody("new-audio"); - expect(await downloadFile("https://example.invalid/file", linkPath, { quiet: true })).toEqual({ - size: 9, - }); - - expect(lstatSync(linkPath).isSymbolicLink()).toBe(true); - expect(lstatSync(midPath).isSymbolicLink()).toBe(true); - expect(readFileSync(finalPath, "utf-8")).toBe("new-audio"); - expect(readFileSync(linkPath, "utf-8")).toBe("new-audio"); -}); - -test("dangling symlink to another directory creates the target file", async () => { - const otherDirectory = join(directory, "other"); - mkdirSync(otherDirectory); - const targetPath = join(otherDirectory, "remote.wav"); - const linkPath = join(directory, "alias.wav"); - symlinkSync(targetPath, linkPath); - - serveBody("new-audio"); - expect(await downloadFile("https://example.invalid/file", linkPath, { quiet: true })).toEqual({ - size: 9, - }); - - expect(lstatSync(linkPath).isSymbolicLink()).toBe(true); - expect(readFileSync(targetPath, "utf-8")).toBe("new-audio"); -}); - -test("new publish path EXDEV falls back to copy beside the resolved target", async () => { - const otherDirectory = join(directory, "other"); - mkdirSync(otherDirectory); - const targetPath = join(otherDirectory, "remote.wav"); - const linkPath = join(directory, "alias.wav"); - symlinkSync(targetPath, linkPath); - - serveBody("new-audio"); - // First rename is temp -> publishPath (missing); EXDEV should copy instead of failing. - injection.renameCodes = ["EXDEV"]; - expect(await downloadFile("https://example.invalid/file", linkPath, { quiet: true })).toEqual({ - size: 9, - }); - - expect(lstatSync(linkPath).isSymbolicLink()).toBe(true); - expect(readFileSync(targetPath, "utf-8")).toBe("new-audio"); -}); - -test("relative link through a directory symlink does not overwrite a lexical decoy", async () => { - // portal -> elsewhere/real-home; alias -> portal/../out.wav - // Lexical join would hit root/out.wav; OS resolution hits elsewhere/out.wav. - const elsewhere = join(directory, "elsewhere"); - const realHome = join(elsewhere, "real-home"); - mkdirSync(realHome, { recursive: true }); - const trueTarget = join(elsewhere, "out.wav"); - const decoyPath = join(directory, "out.wav"); - writeFileSync(trueTarget, "true-old"); - writeFileSync(decoyPath, "decoy-old"); - symlinkSync(realHome, join(directory, "portal")); - const linkPath = join(directory, "alias.wav"); - symlinkSync("portal/../out.wav", linkPath); - - serveBody("new-audio"); - expect(await downloadFile("https://example.invalid/file", linkPath, { quiet: true })).toEqual({ - size: 9, - }); - - expect(lstatSync(linkPath).isSymbolicLink()).toBe(true); - expect(readFileSync(trueTarget, "utf-8")).toBe("new-audio"); - expect(readFileSync(decoyPath, "utf-8")).toBe("decoy-old"); -}); - -test("dangling relative link through a directory symlink creates the physical target", async () => { - const elsewhere = join(directory, "elsewhere"); - const realHome = join(elsewhere, "real-home"); - mkdirSync(realHome, { recursive: true }); - const trueTarget = join(elsewhere, "out.wav"); - const decoyPath = join(directory, "out.wav"); - writeFileSync(decoyPath, "decoy-old"); - symlinkSync(realHome, join(directory, "portal")); - const linkPath = join(directory, "alias.wav"); - symlinkSync("portal/../out.wav", linkPath); - - serveBody("new-audio"); - expect(await downloadFile("https://example.invalid/file", linkPath, { quiet: true })).toEqual({ - size: 9, - }); - - expect(lstatSync(linkPath).isSymbolicLink()).toBe(true); - expect(readFileSync(trueTarget, "utf-8")).toBe("new-audio"); - expect(readFileSync(decoyPath, "utf-8")).toBe("decoy-old"); -}); - -test("refuses a directory destination without moving it aside", async () => { - const targetDirectory = join(directory, "target-dir"); - mkdirSync(targetDirectory); - writeFileSync(join(targetDirectory, "keep.txt"), "keep"); - - const fetchSpy = vi.spyOn(httpTransport, "fetch"); - await expect( - downloadFile("https://example.invalid/file", targetDirectory, { quiet: true }), - ).rejects.toSatisfy((error: unknown) => { - expect(error).toBeInstanceOf(BailianError); - expect((error as BailianError).exitCode).toBe(ExitCode.USAGE); - expect((error as BailianError).message).toMatch(/must be a regular file/); - return true; - }); - - expect(fetchSpy).not.toHaveBeenCalled(); - expect(lstatSync(targetDirectory).isDirectory()).toBe(true); - expect(readFileSync(join(targetDirectory, "keep.txt"), "utf-8")).toBe("keep"); - expect(readdirSync(directory).some((name) => name.includes(".bak"))).toBe(false); -}); - -test("refuses a symlink whose final target is a directory", async () => { - const targetDirectory = join(directory, "target-dir"); - mkdirSync(targetDirectory); - writeFileSync(join(targetDirectory, "keep.txt"), "keep"); - const linkPath = join(directory, "out.wav"); - symlinkSync(targetDirectory, linkPath); - - const fetchSpy = vi.spyOn(httpTransport, "fetch"); - await expect( - downloadFile("https://example.invalid/file", linkPath, { quiet: true }), - ).rejects.toThrow(/must be a regular file/); - - expect(fetchSpy).not.toHaveBeenCalled(); - expect(lstatSync(linkPath).isSymbolicLink()).toBe(true); - expect(lstatSync(targetDirectory).isDirectory()).toBe(true); - expect(readFileSync(join(targetDirectory, "keep.txt"), "utf-8")).toBe("keep"); - expect(readdirSync(directory).some((name) => name.includes(".bak"))).toBe(false); -}); diff --git a/packages/runtime/tests/progress-output.test.ts b/packages/runtime/tests/progress-output.test.ts index c838dd23..30ca872c 100644 --- a/packages/runtime/tests/progress-output.test.ts +++ b/packages/runtime/tests/progress-output.test.ts @@ -1,14 +1,5 @@ import { afterEach, expect, test, vi } from "vite-plus/test"; -import { - chmodSync, - existsSync, - mkdtempSync, - readFileSync, - readdirSync, - rmSync, - statSync, - writeFileSync, -} from "node:fs"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { httpTransport, type Client, type Settings } from "bailian-cli-core"; @@ -101,90 +92,6 @@ test.each( }, ); -test("failed download keeps an existing destination file", async () => { - const directory = mkdtempSync(join(tmpdir(), "bl-download-preserve-")); - const destination = join(directory, "take.wav"); - writeFileSync(destination, "original-audio"); - vi.spyOn(httpTransport, "fetch").mockResolvedValue( - new Response( - new ReadableStream({ - start(controller) { - controller.enqueue(new TextEncoder().encode("partial")); - controller.error(new Error("connection reset")); - }, - }), - { headers: { "content-length": "64" } }, - ), - ); - try { - await expect( - downloadFile("https://example.invalid/file", destination, { quiet: true }), - ).rejects.toThrow(/connection reset/); - expect(readFileSync(destination, "utf-8")).toBe("original-audio"); - expect(readdirSync(directory).filter((name) => name.endsWith(".part"))).toEqual([]); - } finally { - rmSync(directory, { recursive: true, force: true }); - } -}); - -test("successful download replaces destination via temp publish", async () => { - const directory = mkdtempSync(join(tmpdir(), "bl-download-replace-")); - const destination = join(directory, "take.wav"); - writeFileSync(destination, "original-audio"); - vi.spyOn(httpTransport, "fetch").mockResolvedValue( - new Response( - new ReadableStream({ - start(controller) { - controller.enqueue(new TextEncoder().encode("new-audio")); - controller.close(); - }, - }), - { headers: { "content-length": "9" } }, - ), - ); - try { - expect( - await downloadFile("https://example.invalid/file", destination, { quiet: true }), - ).toEqual({ - size: 9, - }); - expect(readFileSync(destination, "utf-8")).toBe("new-audio"); - expect(readdirSync(directory).some((name) => name.endsWith(".part"))).toBe(false); - expect(existsSync(destination)).toBe(true); - } finally { - rmSync(directory, { recursive: true, force: true }); - } -}); - -test("successful overwrite preserves the previous destination mode", async () => { - const directory = mkdtempSync(join(tmpdir(), "bl-download-mode-")); - const destination = join(directory, "take.wav"); - writeFileSync(destination, "original-audio", { mode: 0o600 }); - chmodSync(destination, 0o600); - expect(statSync(destination).mode & 0o777).toBe(0o600); - vi.spyOn(httpTransport, "fetch").mockResolvedValue( - new Response( - new ReadableStream({ - start(controller) { - controller.enqueue(new TextEncoder().encode("new-audio")); - controller.close(); - }, - }), - { headers: { "content-length": "9" } }, - ), - ); - try { - expect( - await downloadFile("https://example.invalid/file", destination, { quiet: true }), - ).toEqual({ size: 9 }); - expect(readFileSync(destination, "utf-8")).toBe("new-audio"); - expect(statSync(destination).mode & 0o777).toBe(0o600); - expect(readdirSync(directory).filter((name) => name.endsWith(".bak"))).toEqual([]); - } finally { - rmSync(directory, { recursive: true, force: true }); - } -}); - test("poll uses the complete snapshot loader for completion and failure predicates", async () => { const firstPage = { status: "SUCCEEDED" }; const completeSnapshot = { jobs: [firstPage, { status: "RUNNING" }] }; From 9bcd79d4b270b0fdec259f5ac6d957c1a758bef5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=8B=A5=E9=BA=92?= Date: Tue, 24 Nov 2026 15:23:29 +0800 Subject: [PATCH 5/5] fix(runtime): preserve existing files when downloads fail --- packages/runtime/src/utils/download.ts | 119 +++++---- .../runtime/tests/download-publish.test.ts | 225 ++++++++++++++++++ .../runtime/tests/progress-output.test.ts | 95 +++++++- 3 files changed, 392 insertions(+), 47 deletions(-) create mode 100644 packages/runtime/tests/download-publish.test.ts diff --git a/packages/runtime/src/utils/download.ts b/packages/runtime/src/utils/download.ts index 44ed978e..7ab4bfad 100644 --- a/packages/runtime/src/utils/download.ts +++ b/packages/runtime/src/utils/download.ts @@ -1,69 +1,96 @@ -import { httpTransport } from "bailian-cli-core"; -import { createWriteStream, mkdirSync, unlinkSync } from "fs"; -import { dirname } from "path"; -import { BailianError, ExitCode } from "bailian-cli-core"; +import { BailianError, ExitCode, httpTransport } from "bailian-cli-core"; +import { randomUUID } from "node:crypto"; +import { + chmodSync, + createWriteStream, + lstatSync, + mkdirSync, + openSync, + realpathSync, + renameSync, + statSync, + unlinkSync, +} from "fs"; +import { dirname, join } from "path"; +import { pipeline } from "node:stream/promises"; import { createProgressBar } from "../output/progress.ts"; -import type { ReadableStreamReadResult } from "stream/web"; + +function resolveDownloadTarget(destPath: string): { path: string; mode?: number } { + let entry; + try { + entry = lstatSync(destPath); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return { path: destPath }; + throw error; + } + + // Keep the link itself intact. A dangling link must fail instead of guessing a target. + const targetPath = realpathSync.native(destPath); + const stats = entry.isSymbolicLink() ? statSync(targetPath) : entry; + if (!stats.isFile()) { + throw new BailianError( + `Download destination must be a regular file: ${targetPath}`, + ExitCode.USAGE, + ); + } + return { path: targetPath, mode: stats.mode & 0o7777 }; +} export async function downloadFile( url: string, destPath: string, opts?: { quiet?: boolean }, ): Promise<{ size: number }> { + const target = resolveDownloadTarget(destPath); const res = await httpTransport.fetch(url); if (!res.ok) { throw new BailianError(`Download failed: HTTP ${res.status}`, ExitCode.GENERAL); } + const body = res.body; + if (!body) throw new BailianError("No response body", ExitCode.GENERAL); + const targetDir = dirname(target.path); + mkdirSync(targetDir, { recursive: true }); + const tempPath = join(realpathSync.native(targetDir), `.download-${randomUUID()}.part`); + const descriptor = openSync(tempPath, "wx", target.mode); const contentLength = Number(res.headers.get("content-length") || 0); - const reader = res.body?.getReader(); - if (!reader) throw new BailianError("No response body", ExitCode.GENERAL); - - mkdirSync(dirname(destPath), { recursive: true }); - const writer = createWriteStream(destPath); const progress = contentLength > 0 && !opts?.quiet ? createProgressBar(contentLength, "Downloading") : null; - let received = 0; - let completed = false; try { - const writeError = new Promise((_, reject) => { - writer.on("error", reject); - }); - - while (true) { - const { done, value } = (await Promise.race([ - reader.read(), - writeError, - ])) as ReadableStreamReadResult; - if (done) break; - - const ok = writer.write(value); - if (!ok) await new Promise((resolve) => writer.once("drain", () => resolve())); - - received += value.byteLength; - progress?.update(received); - } - completed = true; - } finally { - reader.releaseLock(); - progress?.finish(); - - await new Promise((resolve, reject) => { - writer.on("finish", resolve); - writer.on("error", reject); - writer.end(); - }); - - if (!completed) { - try { - unlinkSync(destPath); - } catch { - /* best effort */ - } + await pipeline( + async function* ({ signal }: { signal?: AbortSignal } = {}) { + const reader = body.getReader(); + const cancel = () => { + void reader.cancel(signal?.reason).catch(() => {}); + }; + signal?.addEventListener("abort", cancel, { once: true }); + try { + for (;;) { + const { done, value } = await reader.read(); + if (done) return; + received += value.byteLength; + progress?.update(received); + yield value; + } + } finally { + signal?.removeEventListener("abort", cancel); + reader.releaseLock(); + } + }, + createWriteStream(tempPath, { fd: descriptor }), + ).finally(() => progress?.finish()); + if (target.mode !== undefined) chmodSync(tempPath, target.mode); + renameSync(tempPath, target.path); + } catch (error) { + try { + unlinkSync(tempPath); + } catch { + // Best-effort cleanup of the temporary file. } + throw error; } return { size: received }; diff --git a/packages/runtime/tests/download-publish.test.ts b/packages/runtime/tests/download-publish.test.ts new file mode 100644 index 00000000..588b64d8 --- /dev/null +++ b/packages/runtime/tests/download-publish.test.ts @@ -0,0 +1,225 @@ +import { afterEach, beforeEach, expect, test, vi } from "vite-plus/test"; +import { + chmodSync, + lstatSync, + mkdirSync, + mkdtempSync, + readFileSync, + readdirSync, + rmSync, + statSync, + symlinkSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { BailianError, ExitCode, httpTransport } from "bailian-cli-core"; +import { downloadFile } from "../src/utils/download.ts"; + +// Simulate a failed replacement without relying on platform-specific file locks. +const injection = vi.hoisted(() => ({ + publishErrorCode: undefined as string | undefined, +})); + +vi.mock("fs", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + renameSync: ((from: string, to: string) => { + if (from.endsWith(".part") && injection.publishErrorCode !== undefined) { + throw Object.assign(new Error(`injected ${injection.publishErrorCode}`), { + code: injection.publishErrorCode, + }); + } + return actual.renameSync(from, to); + }) as typeof actual.renameSync, + }; +}); + +function serveBody(text: string): void { + vi.spyOn(httpTransport, "fetch").mockResolvedValue( + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode(text)); + controller.close(); + }, + }), + { headers: { "content-length": String(text.length) } }, + ), + ); +} + +let directory = ""; +let destination = ""; + +beforeEach(() => { + injection.publishErrorCode = undefined; + directory = mkdtempSync(join(tmpdir(), "bl-download-publish-")); + destination = join(directory, "take.wav"); + writeFileSync(destination, "original-audio", { mode: 0o600 }); + chmodSync(destination, 0o600); +}); + +afterEach(() => { + vi.restoreAllMocks(); + rmSync(directory, { recursive: true, force: true }); +}); + +test.each(["EPERM", "EEXIST", "EXDEV", "EIO"])( + "replacement failure (%s) leaves the existing file and cleans up the download", + async (code) => { + serveBody("new-audio"); + injection.publishErrorCode = code; + + await expect( + downloadFile("https://example.invalid/file", destination, { quiet: true }), + ).rejects.toMatchObject({ code }); + expect(readFileSync(destination, "utf-8")).toBe("original-audio"); + expect(statSync(destination).mode & 0o777).toBe(0o600); + expect(readdirSync(directory)).toEqual(["take.wav"]); + }, +); + +test("rejects a broken link without overwriting the file with the same name", async () => { + const linkPath = join(directory, "alias.wav"); + symlinkSync("missing-dir/../take.wav", linkPath); + const fetchSpy = vi.spyOn(httpTransport, "fetch").mockResolvedValue(new Response("new-audio")); + + await expect( + downloadFile("https://example.invalid/file", linkPath, { quiet: true }), + ).rejects.toMatchObject({ code: "ENOENT" }); + expect(fetchSpy).not.toHaveBeenCalled(); + expect(lstatSync(linkPath).isSymbolicLink()).toBe(true); + expect(readFileSync(destination, "utf-8")).toBe("original-audio"); + expect(readdirSync(directory).sort()).toEqual(["alias.wav", "take.wav"]); +}); + +test("symlink destination stays a link and the target receives new bytes", async () => { + const targetPath = join(directory, "canonical.wav"); + const linkPath = join(directory, "alias.wav"); + writeFileSync(targetPath, "original-audio", { mode: 0o600 }); + chmodSync(targetPath, 0o600); + symlinkSync(targetPath, linkPath); + + serveBody("new-audio"); + expect(await downloadFile("https://example.invalid/file", linkPath, { quiet: true })).toEqual({ + size: 9, + }); + + expect(lstatSync(linkPath).isSymbolicLink()).toBe(true); + expect(readFileSync(targetPath, "utf-8")).toBe("new-audio"); + expect(readFileSync(linkPath, "utf-8")).toBe("new-audio"); + expect(statSync(targetPath).mode & 0o777).toBe(0o600); +}); + +test("failed replacement leaves a symlink and its target untouched", async () => { + const targetPath = join(directory, "canonical.wav"); + const linkPath = join(directory, "alias.wav"); + writeFileSync(targetPath, "original-audio", { mode: 0o600 }); + chmodSync(targetPath, 0o600); + symlinkSync(targetPath, linkPath); + + serveBody("new-audio"); + injection.publishErrorCode = "EIO"; + await expect( + downloadFile("https://example.invalid/file", linkPath, { quiet: true }), + ).rejects.toThrow("injected EIO"); + + expect(lstatSync(linkPath).isSymbolicLink()).toBe(true); + expect(readFileSync(targetPath, "utf-8")).toBe("original-audio"); + expect(readFileSync(linkPath, "utf-8")).toBe("original-audio"); + expect(readdirSync(directory).sort()).toEqual(["alias.wav", "canonical.wav", "take.wav"]); +}); + +test("rejects a chain of dangling symlinks without creating a target", async () => { + const finalPath = join(directory, "final.wav"); + const midPath = join(directory, "mid.wav"); + const linkPath = join(directory, "out.wav"); + symlinkSync(finalPath, midPath); + symlinkSync(midPath, linkPath); + + await expect( + downloadFile("https://example.invalid/file", linkPath, { quiet: true }), + ).rejects.toMatchObject({ code: "ENOENT" }); + expect(lstatSync(linkPath).isSymbolicLink()).toBe(true); + expect(lstatSync(midPath).isSymbolicLink()).toBe(true); + expect(readdirSync(directory).sort()).toEqual(["mid.wav", "out.wav", "take.wav"]); +}); + +test("creates a new file in an ordinary output directory", async () => { + const otherDirectory = join(directory, "other"); + const targetPath = join(otherDirectory, "new.wav"); + + serveBody("new-audio"); + expect(await downloadFile("https://example.invalid/file", targetPath, { quiet: true })).toEqual({ + size: 9, + }); + + expect(readFileSync(targetPath, "utf-8")).toBe("new-audio"); + expect(readdirSync(otherDirectory)).toEqual(["new.wav"]); +}); + +test("relative link through a directory symlink does not overwrite a lexical decoy", async () => { + // portal -> elsewhere/real-home; alias -> portal/../out.wav + // Lexical join would hit root/out.wav; OS resolution hits elsewhere/out.wav. + const elsewhere = join(directory, "elsewhere"); + const realHome = join(elsewhere, "real-home"); + mkdirSync(realHome, { recursive: true }); + const trueTarget = join(elsewhere, "out.wav"); + const decoyPath = join(directory, "out.wav"); + writeFileSync(trueTarget, "true-old"); + writeFileSync(decoyPath, "decoy-old"); + symlinkSync(realHome, join(directory, "portal")); + const linkPath = join(directory, "alias.wav"); + symlinkSync("portal/../out.wav", linkPath); + + serveBody("new-audio"); + expect(await downloadFile("https://example.invalid/file", linkPath, { quiet: true })).toEqual({ + size: 9, + }); + + expect(lstatSync(linkPath).isSymbolicLink()).toBe(true); + expect(readFileSync(trueTarget, "utf-8")).toBe("new-audio"); + expect(readFileSync(decoyPath, "utf-8")).toBe("decoy-old"); +}); + +test("refuses a directory destination without moving it aside", async () => { + const targetDirectory = join(directory, "target-dir"); + mkdirSync(targetDirectory); + writeFileSync(join(targetDirectory, "keep.txt"), "keep"); + + const fetchSpy = vi.spyOn(httpTransport, "fetch"); + await expect( + downloadFile("https://example.invalid/file", targetDirectory, { quiet: true }), + ).rejects.toSatisfy((error: unknown) => { + expect(error).toBeInstanceOf(BailianError); + expect((error as BailianError).exitCode).toBe(ExitCode.USAGE); + expect((error as BailianError).message).toMatch(/must be a regular file/); + return true; + }); + + expect(fetchSpy).not.toHaveBeenCalled(); + expect(lstatSync(targetDirectory).isDirectory()).toBe(true); + expect(readFileSync(join(targetDirectory, "keep.txt"), "utf-8")).toBe("keep"); + expect(readdirSync(directory).some((name) => name.includes(".bak"))).toBe(false); +}); + +test("refuses a symlink whose final target is a directory", async () => { + const targetDirectory = join(directory, "target-dir"); + mkdirSync(targetDirectory); + writeFileSync(join(targetDirectory, "keep.txt"), "keep"); + const linkPath = join(directory, "out.wav"); + symlinkSync(targetDirectory, linkPath); + + const fetchSpy = vi.spyOn(httpTransport, "fetch"); + await expect( + downloadFile("https://example.invalid/file", linkPath, { quiet: true }), + ).rejects.toThrow(/must be a regular file/); + + expect(fetchSpy).not.toHaveBeenCalled(); + expect(lstatSync(linkPath).isSymbolicLink()).toBe(true); + expect(lstatSync(targetDirectory).isDirectory()).toBe(true); + expect(readFileSync(join(targetDirectory, "keep.txt"), "utf-8")).toBe("keep"); + expect(readdirSync(directory).some((name) => name.includes(".bak"))).toBe(false); +}); diff --git a/packages/runtime/tests/progress-output.test.ts b/packages/runtime/tests/progress-output.test.ts index 30ca872c..c838dd23 100644 --- a/packages/runtime/tests/progress-output.test.ts +++ b/packages/runtime/tests/progress-output.test.ts @@ -1,5 +1,14 @@ import { afterEach, expect, test, vi } from "vite-plus/test"; -import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { + chmodSync, + existsSync, + mkdtempSync, + readFileSync, + readdirSync, + rmSync, + statSync, + writeFileSync, +} from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { httpTransport, type Client, type Settings } from "bailian-cli-core"; @@ -92,6 +101,90 @@ test.each( }, ); +test("failed download keeps an existing destination file", async () => { + const directory = mkdtempSync(join(tmpdir(), "bl-download-preserve-")); + const destination = join(directory, "take.wav"); + writeFileSync(destination, "original-audio"); + vi.spyOn(httpTransport, "fetch").mockResolvedValue( + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode("partial")); + controller.error(new Error("connection reset")); + }, + }), + { headers: { "content-length": "64" } }, + ), + ); + try { + await expect( + downloadFile("https://example.invalid/file", destination, { quiet: true }), + ).rejects.toThrow(/connection reset/); + expect(readFileSync(destination, "utf-8")).toBe("original-audio"); + expect(readdirSync(directory).filter((name) => name.endsWith(".part"))).toEqual([]); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +}); + +test("successful download replaces destination via temp publish", async () => { + const directory = mkdtempSync(join(tmpdir(), "bl-download-replace-")); + const destination = join(directory, "take.wav"); + writeFileSync(destination, "original-audio"); + vi.spyOn(httpTransport, "fetch").mockResolvedValue( + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode("new-audio")); + controller.close(); + }, + }), + { headers: { "content-length": "9" } }, + ), + ); + try { + expect( + await downloadFile("https://example.invalid/file", destination, { quiet: true }), + ).toEqual({ + size: 9, + }); + expect(readFileSync(destination, "utf-8")).toBe("new-audio"); + expect(readdirSync(directory).some((name) => name.endsWith(".part"))).toBe(false); + expect(existsSync(destination)).toBe(true); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +}); + +test("successful overwrite preserves the previous destination mode", async () => { + const directory = mkdtempSync(join(tmpdir(), "bl-download-mode-")); + const destination = join(directory, "take.wav"); + writeFileSync(destination, "original-audio", { mode: 0o600 }); + chmodSync(destination, 0o600); + expect(statSync(destination).mode & 0o777).toBe(0o600); + vi.spyOn(httpTransport, "fetch").mockResolvedValue( + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode("new-audio")); + controller.close(); + }, + }), + { headers: { "content-length": "9" } }, + ), + ); + try { + expect( + await downloadFile("https://example.invalid/file", destination, { quiet: true }), + ).toEqual({ size: 9 }); + expect(readFileSync(destination, "utf-8")).toBe("new-audio"); + expect(statSync(destination).mode & 0o777).toBe(0o600); + expect(readdirSync(directory).filter((name) => name.endsWith(".bak"))).toEqual([]); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +}); + test("poll uses the complete snapshot loader for completion and failure predicates", async () => { const firstPage = { status: "SUCCEEDED" }; const completeSnapshot = { jobs: [firstPage, { status: "RUNNING" }] };