485 lines
17 KiB
TypeScript
485 lines
17 KiB
TypeScript
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";
|
|
|
|
export const DEFAULT_GITHUB_REPO = "yunyingk/hose-use";
|
|
export const GITHUB_REPO_ENV = "HOSE_USE_GITHUB_REPO";
|
|
|
|
export type UpdateSourcePreference = "auto" | "github" | "gitea";
|
|
|
|
export function normalizeRepo(raw: string): string {
|
|
let repo = raw.trim();
|
|
repo = repo.replace(/^(https?:\/\/)?(www\.)?github\.com\//i, "");
|
|
repo = repo.replace(/\.git$/i, "").replace(/\/+$/, "");
|
|
return repo;
|
|
}
|
|
|
|
export function isValidRepo(repo: string): boolean {
|
|
return /^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(repo);
|
|
}
|
|
|
|
export function detectPlatform(): "darwin" | "linux" | "windows" {
|
|
if (process.platform === "darwin") return "darwin";
|
|
if (process.platform === "win32") return "windows";
|
|
return "linux";
|
|
}
|
|
|
|
export function detectArch(): "arm64" | "x64" {
|
|
return process.arch === "arm64" ? "arm64" : "x64";
|
|
}
|
|
|
|
export type GitHubAsset = {
|
|
name: string;
|
|
downloadUrl: string;
|
|
size: number;
|
|
};
|
|
|
|
export type GitHubRelease = {
|
|
version: string;
|
|
tagName: string;
|
|
name?: string;
|
|
publishedAt?: string;
|
|
author?: string;
|
|
notes: string;
|
|
htmlUrl: string;
|
|
assets: GitHubAsset[];
|
|
};
|
|
|
|
export async function fetchGitHubReleases(
|
|
repo: string,
|
|
limit = 20,
|
|
sourcePreference: UpdateSourcePreference = "auto"
|
|
): Promise<GitHubRelease[]> {
|
|
const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
|
|
const headers: Record<string, string> = {
|
|
"User-Agent": `hose-use/${VERSION}`,
|
|
Accept: "application/vnd.github.v3+json",
|
|
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
|
};
|
|
|
|
const isDefaultRepo = repo.toLowerCase() === DEFAULT_GITHUB_REPO.toLowerCase();
|
|
const allowGitea = isDefaultRepo && sourcePreference !== "github";
|
|
|
|
const urls: string[] = [];
|
|
if (sourcePreference === "github") {
|
|
urls.push(`https://api.github.com/repos/${repo}/releases?per_page=${limit}`);
|
|
} else if (sourcePreference === "gitea") {
|
|
if (allowGitea) {
|
|
urls.push(`https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases?per_page=${limit}`);
|
|
}
|
|
urls.push(`https://api.github.com/repos/${repo}/releases?per_page=${limit}`);
|
|
} else {
|
|
if (allowGitea) {
|
|
urls.push(`https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases?per_page=${limit}`);
|
|
}
|
|
urls.push(`https://api.github.com/repos/${repo}/releases?per_page=${limit}`);
|
|
}
|
|
|
|
let fallbackList: GitHubRelease[] = [];
|
|
|
|
for (const url of urls) {
|
|
try {
|
|
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;
|
|
name?: string;
|
|
body?: string;
|
|
html_url?: string;
|
|
published_at?: string;
|
|
author?: { login?: string };
|
|
assets?: Array<{ name: string; browser_download_url: string; size?: number }>;
|
|
}>;
|
|
|
|
if (!Array.isArray(json) || json.length === 0) continue;
|
|
|
|
const list: GitHubRelease[] = [];
|
|
for (const item of json) {
|
|
const tagName = item.tag_name ?? "";
|
|
const version = tagName.replace(/^v/, "");
|
|
if (!version) continue;
|
|
const assets: GitHubAsset[] = (item.assets ?? []).map((a) => ({
|
|
name: a.name,
|
|
downloadUrl: a.browser_download_url,
|
|
size: a.size ?? 0,
|
|
}));
|
|
list.push({
|
|
version,
|
|
tagName,
|
|
name: item.name ?? tagName,
|
|
publishedAt: item.published_at,
|
|
author: item.author?.login,
|
|
notes: item.body ?? "",
|
|
htmlUrl: item.html_url ?? "",
|
|
assets,
|
|
});
|
|
}
|
|
if (list.length > 0) {
|
|
if (list.some((r) => r.assets.length > 0)) {
|
|
return list;
|
|
}
|
|
if (fallbackList.length === 0) {
|
|
fallbackList = list;
|
|
}
|
|
}
|
|
} catch {
|
|
// try next source
|
|
}
|
|
}
|
|
|
|
return fallbackList;
|
|
}
|
|
|
|
export async function fetchGitHubRelease(
|
|
repo: string,
|
|
targetVersion?: string,
|
|
sourcePreference: UpdateSourcePreference = "auto"
|
|
): Promise<GitHubRelease | undefined> {
|
|
const tag = targetVersion ? (targetVersion.startsWith("v") ? targetVersion : `v${targetVersion}`) : undefined;
|
|
const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
|
|
const headers: Record<string, string> = {
|
|
"User-Agent": `hose-use/${VERSION}`,
|
|
Accept: "application/vnd.github.v3+json",
|
|
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
|
};
|
|
|
|
const isDefaultRepo = repo.toLowerCase() === DEFAULT_GITHUB_REPO.toLowerCase();
|
|
const allowGitea = isDefaultRepo && sourcePreference !== "github";
|
|
|
|
const urls: string[] = [];
|
|
const giteaTagUrl = tag
|
|
? `https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases/tags/${tag}`
|
|
: `https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases/latest`;
|
|
const githubTagUrl = tag
|
|
? `https://api.github.com/repos/${repo}/releases/tags/${tag}`
|
|
: `https://api.github.com/repos/${repo}/releases/latest`;
|
|
|
|
if (sourcePreference === "github") {
|
|
urls.push(githubTagUrl);
|
|
} else if (sourcePreference === "gitea") {
|
|
if (allowGitea) urls.push(giteaTagUrl);
|
|
urls.push(githubTagUrl);
|
|
} else {
|
|
if (allowGitea) urls.push(giteaTagUrl);
|
|
urls.push(githubTagUrl);
|
|
}
|
|
|
|
let fallbackRelease: GitHubRelease | undefined;
|
|
|
|
for (const url of urls) {
|
|
try {
|
|
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;
|
|
name?: string;
|
|
body?: string;
|
|
html_url?: string;
|
|
published_at?: string;
|
|
author?: { login?: string };
|
|
assets?: Array<{ name: string; browser_download_url: string; size?: number }>;
|
|
};
|
|
|
|
const tagName = json.tag_name ?? "";
|
|
if (tag && tagName !== tag) continue;
|
|
const version = tagName.replace(/^v/, "");
|
|
if (!version) continue;
|
|
|
|
const assets: GitHubAsset[] = (json.assets ?? []).map((item) => ({
|
|
name: item.name,
|
|
downloadUrl: item.browser_download_url,
|
|
size: item.size ?? 0,
|
|
}));
|
|
|
|
const candidateRelease: GitHubRelease = {
|
|
version,
|
|
tagName,
|
|
name: json.name ?? tagName,
|
|
publishedAt: json.published_at,
|
|
author: json.author?.login,
|
|
notes: json.body ?? "",
|
|
htmlUrl: json.html_url ?? "",
|
|
assets,
|
|
};
|
|
|
|
if (assets.length > 0) {
|
|
return candidateRelease;
|
|
}
|
|
|
|
if (!fallbackRelease) {
|
|
fallbackRelease = candidateRelease;
|
|
}
|
|
} catch {
|
|
// try next source
|
|
}
|
|
}
|
|
|
|
return fallbackRelease;
|
|
}
|
|
|
|
export function matchAssetForPlatform(
|
|
assets: GitHubAsset[],
|
|
platform: "darwin" | "linux" | "windows",
|
|
arch: "arm64" | "x64"
|
|
): GitHubAsset | undefined {
|
|
const platformKeywords: Record<string, string[]> = {
|
|
darwin: ["darwin", "macos", "osx", "apple"],
|
|
linux: ["linux"],
|
|
windows: ["windows", "win32", "win64", ".exe"],
|
|
};
|
|
const archKeywords: Record<string, string[]> = {
|
|
arm64: ["arm64", "aarch64"],
|
|
x64: ["x64", "x86_64", "amd64"],
|
|
};
|
|
|
|
const pKeys = platformKeywords[platform] || [];
|
|
const aKeys = archKeywords[arch] || [];
|
|
|
|
const matched = assets.filter((asset) => {
|
|
const lower = asset.name.toLowerCase();
|
|
const matchesP = pKeys.some((k) => lower.includes(k));
|
|
const matchesA = aKeys.some((k) => lower.includes(k));
|
|
return matchesP && matchesA;
|
|
});
|
|
|
|
// Prefer compressed archives (.tar.gz / .zip) over raw binary for faster downloads (25MB vs 65MB+)
|
|
const archive = matched.find(
|
|
(asset) =>
|
|
asset.name.endsWith(".tar.gz") ||
|
|
asset.name.endsWith(".tgz") ||
|
|
asset.name.endsWith(".zip")
|
|
);
|
|
if (archive) return archive;
|
|
|
|
// Fallback to direct raw binary if available
|
|
const directBinary = matched.find(
|
|
(asset) =>
|
|
!asset.name.endsWith(".tar.gz") &&
|
|
!asset.name.endsWith(".tgz") &&
|
|
!asset.name.endsWith(".zip") &&
|
|
!asset.name.endsWith(".sha256")
|
|
);
|
|
return directBinary || matched[0];
|
|
}
|
|
|
|
function logProgress(msg: string) {
|
|
try {
|
|
process.stderr.write(`${msg}\n`);
|
|
} catch {
|
|
// ignore
|
|
}
|
|
}
|
|
|
|
/** 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",
|
|
minimumBytes = 1000
|
|
) {
|
|
const candidates: string[] = [];
|
|
const tag = tagName ? (tagName.startsWith("v") ? tagName : `v${tagName}`) : undefined;
|
|
const fileName = assetName || url.split("/").pop() || "";
|
|
const isDefaultRepo = repo.toLowerCase() === DEFAULT_GITHUB_REPO.toLowerCase();
|
|
const allowGitea = isDefaultRepo && sourcePreference !== "github";
|
|
|
|
// 1. High-speed Gitea direct mirror first (only for default official repo)
|
|
if (allowGitea) {
|
|
if (tag && fileName) {
|
|
candidates.push(`https://git.ying-qing.cn/gitea/hose-use/releases/download/${tag}/${fileName}`);
|
|
}
|
|
if (url.startsWith("https://git.ying-qing.cn")) {
|
|
candidates.push(url);
|
|
}
|
|
}
|
|
|
|
// 2. Fast GitHub CDN proxies and direct GitHub fallback (dynamic repo)
|
|
if (tag && fileName) {
|
|
const ghDirectUrl = `https://github.com/${repo}/releases/download/${tag}/${fileName}`;
|
|
if (sourcePreference !== "gitea") {
|
|
candidates.push(`https://ghfast.top/${ghDirectUrl}`);
|
|
candidates.push(`https://ghproxy.net/${ghDirectUrl}`);
|
|
candidates.push(`https://gh.ddlc.top/${ghDirectUrl}`);
|
|
candidates.push(`https://mirror.ghproxy.com/${ghDirectUrl}`);
|
|
}
|
|
candidates.push(ghDirectUrl);
|
|
} else if (url.includes("github.com")) {
|
|
if (sourcePreference !== "gitea") {
|
|
candidates.push(`https://ghfast.top/${url}`);
|
|
candidates.push(`https://ghproxy.net/${url}`);
|
|
candidates.push(`https://gh.ddlc.top/${url}`);
|
|
candidates.push(`https://mirror.ghproxy.com/${url}`);
|
|
}
|
|
candidates.push(url);
|
|
} else {
|
|
candidates.push(url);
|
|
}
|
|
|
|
const uniqueCandidates = Array.from(new Set(candidates));
|
|
|
|
let lastError: Error | undefined;
|
|
for (let i = 0; i < uniqueCandidates.length; i++) {
|
|
const candidate = uniqueCandidates[i]!;
|
|
try {
|
|
logProgress(`==> [${i + 1}/${uniqueCandidates.length}] 正在下载更新: ${candidate}`);
|
|
const reqHeaders: Record<string, string> = {
|
|
"User-Agent": `hose-use/${VERSION}`,
|
|
};
|
|
const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
|
|
if (token && ["github.com", "api.github.com"].includes(new URL(candidate).hostname)) {
|
|
reqHeaders["Authorization"] = `Bearer ${token}`;
|
|
}
|
|
const res = await fetch(candidate, {
|
|
headers: reqHeaders,
|
|
signal: AbortSignal.timeout(600_000), // 放宽至 600 秒(10 分钟),保障大体积二进制完整下载
|
|
});
|
|
if (!res.ok) {
|
|
throw new Error(`HTTP ${res.status} ${res.statusText}`);
|
|
}
|
|
|
|
const totalBytes = Number(res.headers.get("content-length")) || 0;
|
|
const reader = res.body?.getReader();
|
|
if (!reader) {
|
|
const buffer = Buffer.from(await res.arrayBuffer());
|
|
if (buffer.length < minimumBytes) {
|
|
throw new Error(`下载文件异常(大小仅 ${buffer.length} 字节)`);
|
|
}
|
|
writeFileSync(destPath, buffer);
|
|
logProgress(`✓ 下载完成 (${(buffer.length / 1024 / 1024).toFixed(1)} MB)`);
|
|
return;
|
|
}
|
|
|
|
const chunks: Uint8Array[] = [];
|
|
let receivedBytes = 0;
|
|
let lastReport = 0;
|
|
|
|
while (true) {
|
|
const { done, value } = await reader.read();
|
|
if (done) break;
|
|
if (value) {
|
|
chunks.push(value);
|
|
receivedBytes += value.length;
|
|
const now = Date.now();
|
|
if (now - lastReport > 200) {
|
|
lastReport = now;
|
|
const percent = totalBytes ? Math.round((receivedBytes / totalBytes) * 100) : 0;
|
|
const receivedMb = (receivedBytes / (1024 * 1024)).toFixed(1);
|
|
const totalMb = totalBytes ? (totalBytes / (1024 * 1024)).toFixed(1) : "?";
|
|
try {
|
|
process.stderr.write(`\r ↳ 进度: ${percent}% (${receivedMb} / ${totalMb} MB)...`);
|
|
} catch {
|
|
// ignore
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
try {
|
|
process.stderr.write("\n");
|
|
} catch {
|
|
// ignore
|
|
}
|
|
|
|
const completeBuffer = Buffer.concat(chunks);
|
|
if (completeBuffer.length < minimumBytes) {
|
|
throw new Error(`下载文件异常(大小仅 ${completeBuffer.length} 字节)`);
|
|
}
|
|
writeFileSync(destPath, completeBuffer);
|
|
logProgress(`✓ 下载完成 (${(completeBuffer.length / 1024 / 1024).toFixed(1)} MB)`);
|
|
return;
|
|
} catch (err) {
|
|
lastError = err instanceof Error ? err : new Error(String(err));
|
|
logProgress(` ↳ 节点失败: ${lastError.message}`);
|
|
}
|
|
}
|
|
|
|
throw new Error(`所有下载镜像均失败: ${lastError?.message}`);
|
|
}
|
|
|
|
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 (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 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;
|
|
}
|
|
|
|
export function extractTarGz(archivePath: string, targetDir: string, platform: string, arch = detectArch()): string {
|
|
return extractReleaseBinary(archivePath, targetDir, platform, arch, "tar");
|
|
}
|
|
|
|
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 {
|
|
const p1 = v1.replace(/^v/, "").split(".").map((n) => Number.parseInt(n, 10) || 0);
|
|
const p2 = v2.replace(/^v/, "").split(".").map((n) => Number.parseInt(n, 10) || 0);
|
|
for (let i = 0; i < Math.max(p1.length, p2.length); i++) {
|
|
const a = p1[i] ?? 0;
|
|
const b = p2[i] ?? 0;
|
|
if (a > b) return 1;
|
|
if (a < b) return -1;
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
export function isNewerVersion(latest: string, current: string): boolean {
|
|
return compareSemVer(latest, current) > 0;
|
|
}
|