fix: harden CLI parsing, MCP startup and release integrity

This commit is contained in:
gitea committed 2026-10-17 20:32:36 +08:00
1 parent f0902f5f20
commit 103ead0fe5
53 files changed
+3713 -1945

No files matched your search

+7 -15
View File
@@ -1,24 +1,16 @@
import { spawn } from "child_process";
import { join } from "path";
import { usageError } from "../errors.js";
import type { CliParsedArgs, CliResult, CliRunOptions } from "../types.js";
export async function handleMcpCommand(
parsed: CliParsedArgs,
options: CliRunOptions
): Promise<CliResult> {
const appRoot = options.appRoot || process.cwd();
const serverPath = join(appRoot, "src", "server.ts");
console.error("启动 MCP Server on stdio...");
const child = spawn("bun", ["run", serverPath], {
stdio: "inherit",
cwd: appRoot,
env: process.env,
});
await new Promise<void>((resolve) => {
child.on("exit", () => resolve());
});
if (parsed.action && parsed.action !== "serve") {
throw usageError(`未知 mcp 子命令: ${parsed.action}。用法: hose-use mcp [serve]`);
}
// Lazy loading avoids a runner -> registry -> server -> runner startup cycle.
const { startServer } = await import("../../server.js");
await startServer(options);
return { stdout: "", stderr: "", exitCode: 0 };
}
+1 -1
View File
@@ -99,7 +99,7 @@ export async function handleSkillCommand(
});
return {
stdout: `====== Agent Skill 状态 ======\n${output}\n\n提示: 运行 hose-use skill install 进行全局安装\n`,
stdout: `====== Agent Skill 状态 ======\n${output}\n\n提示: 运行 hose-use skill install --yes 进行全局安装\n`,
stderr: "",
exitCode: 0,
};
+4 -4
View File
@@ -13,6 +13,7 @@ import {
detectArch,
detectPlatform,
downloadFile,
downloadVerifiedReleaseAsset,
extractTarGz,
extractZip,
fetchGitHubRelease,
@@ -447,14 +448,13 @@ export async function handleUpdateCommand(
mkdirSync(tmpDir, { recursive: true });
try {
const downloadedFile = join(tmpDir, asset.name);
await downloadFile(asset.downloadUrl, downloadedFile, release.tagName, asset.name, repo, options.sourcePreference);
const downloadedFile = await downloadVerifiedReleaseAsset(release, asset, tmpDir, repo, options.sourcePreference);
let newBinaryPath = downloadedFile;
if (asset.name.endsWith(".tar.gz") || asset.name.endsWith(".tgz")) {
newBinaryPath = extractTarGz(downloadedFile, tmpDir, platform);
newBinaryPath = extractTarGz(downloadedFile, tmpDir, platform, arch);
} else if (asset.name.endsWith(".zip")) {
newBinaryPath = extractZip(downloadedFile, tmpDir, platform);
newBinaryPath = extractZip(downloadedFile, tmpDir, platform, arch);
}
chmodSync(newBinaryPath, 0o755);
+108
View File
@@ -0,0 +1,108 @@
import { afterEach, describe, expect, test } from "bun:test";
import { createHash } from "node:crypto";
import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { spawnSync } from "node:child_process";
import { downloadVerifiedReleaseAsset, extractTarGz, extractZip, fetchGitHubRelease, verifyAssetChecksum, type GitHubRelease } from "./releases.js";
const roots: string[] = [];
afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });
const temp = () => { const root = mkdtempSync(join(tmpdir(), "hose-update-test-")); roots.push(root); return root; };
const payload = Buffer.alloc(2048, 42);
const assetName = "hose-use-linux-x64.tar.gz";
const digest = createHash("sha256").update(payload).digest("hex");
const asset = { name: assetName, downloadUrl: `https://github.com/test/repo/releases/download/v9.9.9/${assetName}`, size: payload.length };
const release: GitHubRelease = { version: "9.9.9", tagName: "v9.9.9", notes: "", htmlUrl: "", assets: [asset, { name: "checksums.txt", downloadUrl: "https://github.com/test/repo/releases/download/v9.9.9/checksums.txt", size: 100 }] };
describe("verified self-update assets", () => {
test("rejects missing, duplicate and mismatched checksums", () => {
const file = join(temp(), "asset"); writeFileSync(file, payload);
expect(() => verifyAssetChecksum(file, assetName, `${digest} ${assetName}\n`)).not.toThrow();
expect(() => verifyAssetChecksum(file, assetName, `${digest} *${assetName}\r\n`)).not.toThrow();
for (const manifest of ["", `${digest} unrelated\n`, `${digest} ${assetName}\n${digest} ${assetName}\n`, `${digest} ${assetName}\ninvalid ${assetName}\n`, `${"0".repeat(64)} ${assetName}\n`]) {
expect(() => verifyAssetChecksum(file, assetName, manifest)).toThrow();
}
});
test("pins manifest and binary to the release tag and never sends GitHub credentials to proxies", async () => {
const fetchBefore = globalThis.fetch;
const tokenBefore = process.env.GITHUB_TOKEN;
process.env.GITHUB_TOKEN = "fixture-token";
const requests: Array<{ url: string; authorization?: string }> = [];
globalThis.fetch = (async (input: string | URL | Request, options?: RequestInit) => {
const url = String(input);
requests.push({ url, authorization: new Headers(options?.headers).get("Authorization") || undefined });
return new Response(url.endsWith("checksums.txt") ? `${digest} ${assetName}\n` : payload);
}) as typeof fetch;
try {
const path = await downloadVerifiedReleaseAsset(release, asset, temp(), "test/repo", "github");
expect(readFileSync(path)).toEqual(payload);
expect(requests).toHaveLength(2);
for (const request of requests) {
expect(request.url).toContain("/download/v9.9.9/");
if (new URL(request.url).hostname !== "github.com") expect(request.authorization).toBeUndefined();
}
} finally {
globalThis.fetch = fetchBefore;
if (tokenBefore === undefined) delete process.env.GITHUB_TOKEN; else process.env.GITHUB_TOKEN = tokenBefore;
}
});
test("does not start downloading a release without a checksum manifest", async () => {
const fetchBefore = globalThis.fetch;
let requests = 0;
globalThis.fetch = (async () => { requests++; throw new Error("must not fetch"); }) as unknown as typeof fetch;
try {
await expect(downloadVerifiedReleaseAsset({ ...release, assets: [asset] }, asset, temp())).rejects.toThrow("checksums.txt");
expect(requests).toBe(0);
} finally { globalThis.fetch = fetchBefore; }
});
test("GitHub API credentials are also excluded from mirror metadata requests", async () => {
const fetchBefore = globalThis.fetch;
const tokenBefore = process.env.GITHUB_TOKEN;
process.env.GITHUB_TOKEN = "fixture-token";
let authorization: string | null = "not-called";
globalThis.fetch = (async (_input: string | URL | Request, options?: RequestInit) => {
authorization = new Headers(options?.headers).get("Authorization");
return Response.json({ tag_name: "v9.9.9", assets: [{ name: "checksums.txt", browser_download_url: "https://example.test/checksums.txt" }] });
}) as typeof fetch;
try {
expect((await fetchGitHubRelease("yunyingk/hose-use", "9.9.9", "gitea"))?.tagName).toBe("v9.9.9");
expect(authorization).toBeNull();
} finally {
globalThis.fetch = fetchBefore;
if (tokenBefore === undefined) delete process.env.GITHUB_TOKEN; else process.env.GITHUB_TOKEN = tokenBefore;
}
});
test("extracts only a known binary and rejects archives containing no expected member", () => {
const root = temp(), source = join(root, "source"), target = join(root, "target");
mkdirSync(source); mkdirSync(target);
const platform = process.platform === "darwin" ? "darwin" : "linux";
const name = `hose-use-${platform}-${process.arch === "arm64" ? "arm64" : "x64"}`;
writeFileSync(join(source, name), payload);
writeFileSync(join(source, "unrelated.txt"), "not a binary");
const archive = join(target, "release.tar.gz");
expect(spawnSync("tar", ["-czf", archive, "-C", source, name, "unrelated.txt"]).status).toBe(0);
const extracted = extractTarGz(archive, target, platform);
expect(readFileSync(extracted)).toEqual(payload);
expect(existsSync(join(target, "unrelated.txt"))).toBe(false);
expect(spawnSync("tar", ["-czf", archive, "-C", source, "unrelated.txt"]).status).toBe(0);
expect(() => extractTarGz(archive, target, platform)).toThrow("目标平台二进制");
});
test("extracts the selected Windows ZIP binary without materializing wrappers or extra files", () => {
const root = temp(), source = join(root, "source"), target = join(root, "target");
mkdirSync(source); mkdirSync(target);
const name = "hose-use-windows-x64.exe";
writeFileSync(join(source, name), payload);
writeFileSync(join(source, "hose-aipro.cmd"), "fixture wrapper");
const archive = join(target, "release.zip");
expect(spawnSync("zip", ["-q", archive, name, "hose-aipro.cmd"], { cwd: source }).status).toBe(0);
const extracted = extractZip(archive, target, "windows", "x64");
expect(readFileSync(extracted)).toEqual(payload);
expect(existsSync(join(target, "hose-aipro.cmd"))).toBe(false);
});
});
+69 -50
View File
@@ -1,4 +1,6 @@
import { unlinkSync, writeFileSync } from "node:fs";
import { closeSync, mkdtempSync, openSync, readFileSync, statSync, unlinkSync, writeFileSync } from "node:fs";
import { createHash } from "node:crypto";
import { basename, join } from "node:path";
import { spawnSync } from "node:child_process";
import { VERSION } from "../../../version.js";
@@ -79,7 +81,7 @@ export async function fetchGitHubReleases(
for (const url of urls) {
try {
const res = await fetch(url, { headers, signal: AbortSignal.timeout(5000) });
const res = await fetch(url, { headers: scopedHeaders(headers, url), signal: AbortSignal.timeout(5000) });
if (!res.ok) continue;
const json = (await res.json()) as Array<{
tag_name?: string;
@@ -168,7 +170,7 @@ export async function fetchGitHubRelease(
for (const url of urls) {
try {
const res = await fetch(url, { headers, signal: AbortSignal.timeout(5000) });
const res = await fetch(url, { headers: scopedHeaders(headers, url), signal: AbortSignal.timeout(5000) });
if (!res.ok) continue;
const json = (await res.json()) as {
tag_name?: string;
@@ -181,6 +183,7 @@ export async function fetchGitHubRelease(
};
const tagName = json.tag_name ?? "";
if (tag && tagName !== tag) continue;
const version = tagName.replace(/^v/, "");
if (!version) continue;
@@ -269,13 +272,22 @@ function logProgress(msg: string) {
}
}
/** Credentials for GitHub must never be forwarded to a CDN or the Gitea mirror. */
function scopedHeaders(headers: Record<string, string>, url: string): Record<string, string> {
const hostname = new URL(url).hostname;
if (hostname === "github.com" || hostname === "api.github.com") return headers;
const { Authorization: _authorization, ...publicHeaders } = headers;
return publicHeaders;
}
export async function downloadFile(
url: string,
destPath: string,
tagName?: string,
assetName?: string,
repo: string = DEFAULT_GITHUB_REPO,
sourcePreference: UpdateSourcePreference = "auto"
sourcePreference: UpdateSourcePreference = "auto",
minimumBytes = 1000
) {
const candidates: string[] = [];
const tag = tagName ? (tagName.startsWith("v") ? tagName : `v${tagName}`) : undefined;
@@ -326,7 +338,7 @@ export async function downloadFile(
"User-Agent": `hose-use/${VERSION}`,
};
const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
if (token && candidate.includes("github.com")) {
if (token && ["github.com", "api.github.com"].includes(new URL(candidate).hostname)) {
reqHeaders["Authorization"] = `Bearer ${token}`;
}
const res = await fetch(candidate, {
@@ -341,7 +353,7 @@ export async function downloadFile(
const reader = res.body?.getReader();
if (!reader) {
const buffer = Buffer.from(await res.arrayBuffer());
if (buffer.length < 1000) {
if (buffer.length < minimumBytes) {
throw new Error(`下载文件异常(大小仅 ${buffer.length} 字节)`);
}
writeFileSync(destPath, buffer);
@@ -381,7 +393,7 @@ export async function downloadFile(
}
const completeBuffer = Buffer.concat(chunks);
if (completeBuffer.length < 1000) {
if (completeBuffer.length < minimumBytes) {
throw new Error(`下载文件异常(大小仅 ${completeBuffer.length} 字节)`);
}
writeFileSync(destPath, completeBuffer);
@@ -396,56 +408,63 @@ export async function downloadFile(
throw new Error(`所有下载镜像均失败: ${lastError?.message}`);
}
export function extractTarGz(archivePath: string, targetDir: string, platform: string): string {
const result = spawnSync("tar", ["-xzf", archivePath, "-C", targetDir], { stdio: "pipe" });
if (result.status !== 0) {
throw new Error(`解压 tar 归档失败: ${result.stderr.toString()}`);
}
unlinkSync(archivePath);
const files = spawnSync("find", [targetDir, "-type", "f"], { encoding: "utf8" })
.stdout.trim()
.split("\n")
.filter(Boolean);
// Exact match for hose-use or hose-use.exe
const expectedName = platform === "windows" ? "hose-use.exe" : "hose-use";
const exact = files.find((f) => f.endsWith(`/${expectedName}`) || f.endsWith(expectedName));
if (exact) return exact;
// Next match for hose-use-darwin-arm64 etc., excluding hose-aipro
const platformBinary = files.find((f) => {
const base = f.split("/").pop() || "";
return base.startsWith("hose-use-") && !base.endsWith(".cmd") && !base.endsWith(".json");
export function verifyAssetChecksum(assetPath: string, assetName: string, manifest: string): void {
const matches = manifest.split(/\r?\n/).flatMap(line => {
const match = line.match(/^(\S+)\s+\*?(.+)$/);
return match?.[2] === assetName ? [match[1].toLowerCase()] : [];
});
if (platformBinary) return platformBinary;
return files.find((f) => !f.endsWith("hose-aipro")) || files[0] || archivePath;
if (matches.length !== 1 || !/^[a-f0-9]{64}$/.test(matches[0])) throw new Error(`checksums.txt 缺少、重复或错误列出 ${assetName},拒绝未经校验的更新`);
const actual = createHash("sha256").update(readFileSync(assetPath)).digest("hex");
if (actual !== matches[0]) throw new Error(`SHA-256 校验失败: ${assetName};现有安装未替换`);
}
export function extractZip(archivePath: string, targetDir: string, platform: string): string {
const result = spawnSync("unzip", ["-q", "-o", archivePath, "-d", targetDir], { stdio: "pipe" });
if (result.status !== 0) {
throw new Error(`解压 zip 归档失败: ${result.stderr.toString()}`);
export async function downloadVerifiedReleaseAsset(
release: GitHubRelease,
asset: GitHubAsset,
targetDir: string,
repo = DEFAULT_GITHUB_REPO,
sourcePreference: UpdateSourcePreference = "auto"
): Promise<string> {
if (basename(asset.name) !== asset.name || /[\\/]/.test(asset.name)) throw new Error("非法 Release 资产文件名");
if (!/^v\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(release.tagName)) throw new Error("非法 Release tag");
const manifest = release.assets.find(item => item.name === "checksums.txt");
if (!manifest) throw new Error(`Release ${release.tagName} 缺少 checksums.txt,拒绝未经校验的更新`);
const manifestPath = join(targetDir, "checksums.txt");
await downloadFile(manifest.downloadUrl, manifestPath, release.tagName, manifest.name, repo, sourcePreference, 1);
const assetPath = join(targetDir, asset.name);
await downloadFile(asset.downloadUrl, assetPath, release.tagName, asset.name, repo, sourcePreference);
verifyAssetChecksum(assetPath, asset.name, readFileSync(manifestPath, "utf8"));
return assetPath;
}
/** Extract only a known binary member; never materialize archive paths or aliases. */
function extractReleaseBinary(archivePath: string, targetDir: string, platform: string, arch: string, format: "tar" | "zip"): string {
const listing = spawnSync(format === "tar" ? "tar" : "unzip", format === "tar" ? ["-tzf", archivePath] : ["-Z1", archivePath], { encoding: "utf8" });
if (listing.status !== 0) throw new Error(`无法读取 Release 归档: ${listing.stderr}`);
const names = listing.stdout.split(/\r?\n/);
const suffix = platform === "windows" ? ".exe" : "";
const expected = [`hose-use-${platform}-${arch}${suffix}`, `hose-use${suffix}`];
const member = expected.flatMap(name => [name, `./${name}`]).find(name => names.filter(item => item === name).length === 1);
if (!member) throw new Error("Release 归档中没有唯一的目标平台二进制");
const output = join(mkdtempSync(join(targetDir, ".extract-")), `hose-use${suffix}`);
const fd = openSync(output, "wx", 0o700);
try {
const extraction = spawnSync(format === "tar" ? "tar" : "unzip", format === "tar" ? ["-xOzf", archivePath, member] : ["-p", archivePath, member], { stdio: ["ignore", fd, "pipe"] });
if (extraction.status !== 0) throw new Error(`解压 Release 二进制失败: ${extraction.stderr}`);
} finally {
closeSync(fd);
}
if (!statSync(output).size) throw new Error("Release 二进制为空");
unlinkSync(archivePath);
return output;
}
const files = spawnSync("find", [targetDir, "-type", "f"], { encoding: "utf8" })
.stdout.trim()
.split("\n")
.filter(Boolean);
export function extractTarGz(archivePath: string, targetDir: string, platform: string, arch = detectArch()): string {
return extractReleaseBinary(archivePath, targetDir, platform, arch, "tar");
}
const expectedName = platform === "windows" ? "hose-use.exe" : "hose-use";
const exact = files.find((f) => f.endsWith(`/${expectedName}`) || f.endsWith(expectedName));
if (exact) return exact;
const platformBinary = files.find((f) => {
const base = f.split("/").pop() || "";
return base.startsWith("hose-use-") && !base.endsWith(".cmd") && !base.endsWith(".json");
});
if (platformBinary) return platformBinary;
return files.find((f) => !f.endsWith("hose-aipro")) || files[0] || archivePath;
export function extractZip(archivePath: string, targetDir: string, platform: string, arch = detectArch()): string {
return extractReleaseBinary(archivePath, targetDir, platform, arch, "zip");
}
export function compareSemVer(v1: string, v2: string): number {
+1 -1
View File
@@ -3,7 +3,7 @@ import {
analyzeWorkflow,
extractWorkflowSpecificationIds,
type WorkflowFormSpecLike,
} from "../../../domains/platform/analysis.js";
} from "../../../domains/platform/workflow/analysis/index.js";
import { getFormSpecification } from "../../../domains/bill/tools.js";
import { stringOption } from "../../parser.js";
import { printJson, printTable, printKeyValue } from "../../printer.js";
+1 -1
View File
@@ -1,5 +1,5 @@
import { listAllWorkflows, listWorkflowLogs } from "../../../domains/platform/services.js";
import { WorkflowAlertStore } from "../../../domains/platform/workflow-alert-store.js";
import { WorkflowAlertStore } from "../../../domains/platform/workflow/alert/index.js";
import { stringOption, numberOption, booleanOption } from "../../parser.js";
import { createClientsForCorp, createPiperClientForCorp } from "../../helpers.js";
import { printJson, printTable } from "../../printer.js";
+1 -1
View File
@@ -8,7 +8,7 @@ import {
createWorkflowDraft,
failWorkflowSave,
hasWorkflowVersionConflict,
} from "../../../domains/platform/workflow-state.js";
} from "../../../domains/platform/workflow/state/index.js";
import { stringOption, booleanOption } from "../../parser.js";
import { createClientsForCorp, createPiperClientForCorp } from "../../helpers.js";
import { printJson } from "../../printer.js";
+1 -1
View File
@@ -367,7 +367,7 @@ export async function handleWorkflowEvalScript(
}
function formatEvalCliResult(
evalResult: import("../../../domains/platform/workflow-script.js").ScriptEvalResult,
evalResult: import("../../../domains/platform/workflow/script/index.js").ScriptEvalResult,
targetDesc: string
): CliResult {
const lines: string[] = [];