fix: harden CLI parsing, MCP startup and release integrity
This commit is contained in:
1 parent
f0902f5f20
commit
103ead0fe5
53 files changed
+3713
-1945
No files matched your search
@@ -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 {
|
||||
|
||||
Reference in new issue
Block a user