DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat(desktop): GitHub Release 下载源增加多个代理镜像兜底 (#138) (#946)
iuuuuuuuu3b13119e1e41
diff --git a/packages/dsh-tauri-ssh/src/host/service/bootstrap.test.ts b/packages/dsh-tauri-ssh/src/host/service/bootstrap.test.tsindex 98eaf6c1..fb69f7d4 100644--- a/packages/dsh-tauri-ssh/src/host/service/bootstrap.test.ts+++ b/packages/dsh-tauri-ssh/src/host/service/bootstrap.test.ts@@ -10,6 +10,7 @@ import { join } from 'pathe'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { REMOTE_ROOT } from '../config/constants'import { MachineId } from '../types/index'+import { DSH_MIRROR_PREFIXES } from '../utils/assets'import { FALLBACK_DSH_TAG, RECOMMENDED_DSH_VERSION } from '../utils/version'import {buildInstallScript,@@ -72,7 +73,7 @@ const LINUX_ASSETS = [/** The default injected fetchers (no network): a healthy metadata view. */function healthyFetchers(overrides: Partial<{listReleases: () => Promise<typeof RELEASES>- listAssets: () => Promise<typeof LINUX_ASSETS>+ listAssets: () => Promise<Array<{ name: string, url: string, digest?: string }>>npmDist: () => Promise<{ url: string, mirrorUrl: string, integrity?: string }>}> = {}) {return {@@ -232,7 +233,7 @@ describe('planRemoteInstall', () => {expect(plan.dsh.tag).toBe(DSH_TAG)expect(plan.dsh.digest).toBe(LINUX_ASSETS[0]?.digest)expect(plan.dsh.urls[0]).toBe(LINUX_ASSETS[0]?.url)- expect(plan.dsh.urls[1]).toContain('ghfast.top/')+ expect(plan.dsh.urls.slice(1).map(url => new URL(url).host)).toEqual([...DSH_MIRROR_PREFIXES].map(prefix => new URL(prefix).host))expect(plan.dshEntry).toBe('node_modules/@deepseek-ai/dsh/lib/bin.js')expect(plan.dshVersion).toBe(DSH_VERSION)expect(plan.notes).toEqual([])@@ -255,6 +256,19 @@ describe('planRemoteInstall', () => {expect(plan.node.version).toBe('v22.22.0')})+ it('drops every mirror when the release digest is unavailable', async () => {+ const plan = await planRemoteInstall('Linux 6.8 x86_64', {}, healthyFetchers({+ // The asset exists but the release carries no digest, so nothing can be verified.+ listAssets: () => Promise.resolve(LINUX_ASSETS.map(asset => ({ name: asset.name, url: asset.url }))),+ }))+ if (plan.dsh.kind !== 'pkg-zip')+ throw new Error('expected pkg-zip')+ expect(plan.dsh.digest).toBeUndefined()+ // An unverifiable download must not gain extra writable sources.+ expect(plan.dsh.urls).toEqual([LINUX_ASSETS[0]?.url])+ expect(plan.notes.join('\n')).toContain('未取得')+ })+it('derives deterministic URLs and notes skipped verification when metadata fails', async () => {const plan = await planRemoteInstall('Linux 6.8 x86_64', {}, healthyFetchers({listAssets: () => Promise.reject(new Error('rate limited')),@@ -367,6 +381,16 @@ describe('buildInstallScript', () => {throw new Error('expected npm-tgz')expect(plan.dsh.urls).toEqual([mirrorOnly])})+ it('verifies each candidate inside the fallback loop, never after it', async () => {+ const pkgScript = buildInstallScript(await planRemoteInstall('Linux 6.8 x86_64', {}, healthyFetchers()))+ expect(pkgScript).toContain('fetch_verified "$TMP/node.tar.gz"')+ expect(pkgScript).toContain('fetch_verified "$TMP/pnpm.tgz"')+ expect(pkgScript).toContain('fetch_verified "$TMP/dsh-pkg.zip"')+ // 校验必须留在逐个候选的循环里:循环外的一次性 verify 会让坏镜像中断兜底+ expect(pkgScript).not.toContain('verify "$TMP/')+ const npmScript = buildInstallScript(await planRemoteInstall('Linux 5.15 aarch64', {}, healthyFetchers()))+ expect(npmScript).toContain('fetch_verified "$TMP/dsh.tgz"')+ })})describe('install script execution (real POSIX sh)', () => {@@ -565,6 +589,86 @@ describe('install script execution (real POSIX sh)', () => {expect(existsSync(join(root, 'runtime', 'bin', 'node'))).toBe(true)expect(existsSync(join(root, 'dependencies', 'pnpm', 'bin', 'pnpm.cjs'))).toBe(true)})+ /**+ * Same as runScriptServing, but the fake curl serves tampered bytes for the+ * FIRST mirror of every artifact (the official host) and real bytes from+ * `servedDir` for the fallback mirror, so a script that verifies only once+ * after the whole fallback loop cannot recover.+ */+ function runScriptWithBrokenFirstSource(script: string, sandbox: string, servedDir: string): Promise<{ code: number, stdout: string, stderr: string }> {+ const binDir = join(sandbox, 'fake-bin')+ mkdirSync(binDir, { recursive: true })+ const fakeCurl = join(binDir, 'curl')+ writeFileSync(fakeCurl, [+ '#!/bin/sh',+ 'dst=""',+ 'prev=""',+ 'for arg in "$@"; do',+ ' if [ "$prev" = "-o" ]; then dst="$arg"; fi',+ ' prev="$arg"',+ 'done',+ 'url=""',+ 'for arg in "$@"; do url="$arg"; done',+ 'case "$url" in',+ ' *SHASUMS256.txt) cat "$SERVED/SHASUMS256.txt" > "$dst"; exit 0 ;;',+ ' *nodejs.org*) printf \'tampered-download-bytes\' > "$dst"; exit 0 ;;',+ 'esac',+ 'if [ -f "$SERVED/$(basename "$url")" ]; then cp "$SERVED/$(basename "$url")" "$dst"; exit 0; fi',+ 'echo "fake curl: no artifact for $url" >&2',+ 'exit 22',+ ].join('\n'))+ chmodSync(fakeCurl, 0o755)+ const scriptPath = join(sandbox, 'install.sh')+ writeFileSync(scriptPath, script)+ const run = promisify(execFile)+ return run('sh', [scriptPath], {+ env: { ...process.env, HOME: sandbox, SERVED: servedDir, PATH: `${binDir}:${process.env.PATH ?? ''}` },+ }).then(+ ({ stdout, stderr }) => ({ code: 0, stdout, stderr }),+ (error: { code?: number, stdout?: string, stderr?: string }) =>+ ({ code: error.code ?? -1, stdout: error.stdout ?? '', stderr: error.stderr ?? '' }),+ )+ }++ it('keeps trying the next source when a mirror serves bytes that fail the digest (real POSIX sh)', async () => {+ const work = tempDir()+ const served = join(work, 'served')+ mkdirSync(served, { recursive: true })++ const nodeDir = join(work, 'node-v22.22.0-linux-x64')+ mkdirSync(join(nodeDir, 'bin'), { recursive: true })+ mkdirSync(join(nodeDir, 'include'), { recursive: true })+ writeFileSync(join(nodeDir, 'bin', 'node'), '#!/bin/sh\nexec sh "$@"\n')+ writeFileSync(join(nodeDir, 'include', 'node'), 'headers\n')+ const nodeTgz = join(served, 'node-v22.22.0-linux-x64.tar.gz')+ await promisify(execFile)('tar', ['-czf', nodeTgz, '-C', work, 'node-v22.22.0-linux-x64'])+ writeFileSync(+ join(served, 'SHASUMS256.txt'),+ `${createHash('sha256').update(readFileSync(nodeTgz)).digest('hex')} node-v22.22.0-linux-x64.tar.gz\n`,+ )++ const plan = await planRemoteInstall('Linux 6.8 x86_64', {}, healthyFetchers())+ expect(plan.node.urls[0]).toContain('nodejs.org')++ const sandbox = tempDir()+ // pnpm and dsh are pre-installed so the run exercises the node section,+ // whose official source is the broken mirror.+ const root = join(sandbox, REMOTE_ROOT)+ mkdirSync(join(root, 'dependencies', 'pnpm', 'bin'), { recursive: true })+ writeFileSync(join(root, 'dependencies', 'pnpm', 'bin', 'pnpm.cjs'), 'placeholder')+ mkdirSync(join(root, 'dependencies', 'dsh', 'node_modules', '@deepseek-ai', 'dsh', 'lib'), { recursive: true })+ writeFileSync(join(root, 'dependencies', 'dsh', 'node_modules', '@deepseek-ai', 'dsh', 'lib', 'bin.js'), 'placeholder')++ const outcome = await runScriptWithBrokenFirstSource(buildInstallScript(plan), sandbox, served)+ expect(outcome.stderr).toBe('')+ expect(outcome.code).toBe(0)+ // The broken official source is reported, but the fallback mirror installs.+ expect(outcome.stdout).toContain('改用下一个下载源')+ expect(outcome.stdout).not.toContain('::dsh failed')+ expect(outcome.stdout).toContain('node 安装完成')+ expect(outcome.stdout).toContain('远端初始化完成')+ expect(existsSync(join(root, 'runtime', 'bin', 'node'))).toBe(true)+ })})describe('remote pnpm shim (real POSIX sh)', () => {diff --git a/packages/dsh-tauri-ssh/src/host/service/bootstrap.utils.ts b/packages/dsh-tauri-ssh/src/host/service/bootstrap.utils.tsindex 2902e135..b697bf65 100644--- a/packages/dsh-tauri-ssh/src/host/service/bootstrap.utils.ts+++ b/packages/dsh-tauri-ssh/src/host/service/bootstrap.utils.ts@@ -130,7 +130,8 @@ export async function planRemoteInstall(notes.push(`release 资产元数据获取失败(${messageOf(error)})`)}if (digest === undefined)- notes.push(`未取得 ${zipName} 的可信摘要,将跳过 SHA-256 校验`)+ notes.push(`未取得 ${zipName} 的可信摘要,将跳过 SHA-256 校验;校验不了就不启用镜像`)+ const dshUrls = urls ?? dshZipDownloadUrls(repo, resolved.tag, zipName)return {os,arch,@@ -139,7 +140,8 @@ export async function planRemoteInstall(dshEntry: DSH_ZIP_ENTRY,dshVersion: resolved.version,node,- dsh: { kind: 'pkg-zip', urls: urls ?? dshZipDownloadUrls(repo, resolved.tag, zipName), ...digest === undefined ? {} : { digest }, zipName, tag: resolved.tag },+ // 摘要缺失时脚本会跳过 SHA-256 校验:此时只留官方源,绝不额外放大可写入口。+ dsh: { kind: 'pkg-zip', urls: digest === undefined ? dshUrls.slice(0, 1) : dshUrls, ...digest === undefined ? {} : { digest }, zipName, tag: resolved.tag },pnpm,notes,}@@ -184,8 +186,7 @@ export function buildInstallScript(plan: RemoteInstallPlan): string {` log install "dsh 已就绪"`,`else`,` log download "dsh ${plan.dsh.tag}"`,- ` fetch "$TMP/dsh-pkg.zip" ${quoteUrls(plan.dsh.urls)}`,- ` verify "$TMP/dsh-pkg.zip" "${plan.dsh.digest ?? ''}" "${plan.dsh.zipName}"`,+ ` fetch_verified "$TMP/dsh-pkg.zip" "${plan.dsh.digest ?? ''}" "${plan.dsh.zipName}" ${quoteUrls(plan.dsh.urls)}`,` extract_zip "$TMP/dsh-pkg.zip" "$ROOT/dependencies/dsh.new"`,` flatten_move "$ROOT/dependencies/dsh.new" "$ROOT/dependencies/dsh"`,` log install "dsh 安装完成 (${plan.dsh.tag})"`,@@ -206,8 +207,7 @@ export function buildInstallScript(plan: RemoteInstallPlan): string {` log install "dsh 已就绪"`,`else`,` log download "dsh ${plan.dsh.packageName}@${plan.dsh.version} (npm)"`,- ` fetch "$TMP/dsh.tgz" ${quoteUrls(plan.dsh.urls)}`,- ` verify "$TMP/dsh.tgz" "${plan.dsh.integrity ?? ''}" "${plan.dsh.packageName}-${plan.dsh.version}.tgz"`,+ ` fetch_verified "$TMP/dsh.tgz" "${plan.dsh.integrity ?? ''}" "${plan.dsh.packageName}-${plan.dsh.version}.tgz" ${quoteUrls(plan.dsh.urls)}`,` rm -rf "$ROOT/dependencies/dsh.new"`,` mkdir -p "$ROOT/dependencies/dsh.new"`,` tar -xzf "$TMP/dsh.tgz" -C "$ROOT/dependencies/dsh.new" --strip-components=1`,@@ -224,26 +224,50 @@ export function buildInstallScript(plan: RemoteInstallPlan): string {'cleanup() { rm -rf "$TMP" "$ROOT/runtime.new" "$ROOT/dependencies/pnpm.new" "$ROOT/dependencies/dsh.new"; }','trap cleanup EXIT',`log() { printf '${BOOTSTRAP_LOG_PREFIX}%s %s\\n' "$1" "$2"; }`,+ 'fetch_one() {',+ ' _dst="$1"; _url="$2"',+ ' if command -v curl >/dev/null 2>&1; then',+ ' log download "$_url"',+ ' if curl -fsSL --retry 3 --connect-timeout 15 -o "$_dst" "$_url" 2>"$TMP/fetch.err"; then return 0; fi',+ ' _errs="$_errs | $_url: $(head -n 1 "$TMP/fetch.err" 2>/dev/null || echo download failed)"',+ ' return 1',+ ' fi',+ ' if command -v wget >/dev/null 2>&1; then',+ ' log download "$_url"',+ ' if wget -q --tries=3 -O "$_dst" "$_url" 2>/dev/null; then return 0; fi',+ ' _errs="$_errs | $_url: wget download failed"',+ ' return 1',+ ' fi',+ ' log failed "REMOTE_INSTALL_NO_DOWNLOADER: 远端缺少 curl 或 wget,请先安装其一"',+ ' exit 9',+ '}','fetch() {',' _dst="$1"; shift',' _errs=""',' for _url in "$@"; do',- ' if command -v curl >/dev/null 2>&1; then',- ' log download "$_url"',- ' if curl -fsSL --retry 3 --connect-timeout 15 -o "$_dst" "$_url" 2>"$TMP/fetch.err"; then return 0; fi',- ' _errs="$_errs | $_url: $(head -n 1 "$TMP/fetch.err" 2>/dev/null || echo download failed)"',- ' elif command -v wget >/dev/null 2>&1; then',- ' log download "$_url"',- ' if wget -q --tries=3 -O "$_dst" "$_url" 2>/dev/null; then return 0; fi',- ' _errs="$_errs | $_url: wget download failed"',- ' else',- ' log failed "REMOTE_INSTALL_NO_DOWNLOADER: 远端缺少 curl 或 wget,请先安装其一"',- ' exit 9',- ' fi',+ ' if fetch_one "$_dst" "$_url"; then return 0; fi',' done',' log failed "所有下载源均失败:$_errs"',' exit 10','}',+ 'fetch_verified() {',+ ' _dst="$1"; _want="$2"; _name="$3"; shift 3',+ ' _errs=""',+ ' _mismatch=0',+ ' for _url in "$@"; do',+ ' if fetch_one "$_dst" "$_url"; then',+ ' if verify "$_dst" "$_want" "$_name"; then return 0; fi',+ ' _mismatch=1',+ ' log verify "改用下一个下载源: $_url"',+ ' fi',+ ' done',+ ' if [ "$_mismatch" = 0 ]; then',+ ' log failed "所有下载源均失败:$_errs"',+ ' exit 10',+ ' fi',+ ' log failed "checksum mismatch: $_name (want sha$_algo:$_hex, got $_got)"',+ ' exit 11',+ '}','verify() {',' _file="$1"; _want="$2"; _name="$3"',' case "$_want" in',@@ -267,8 +291,8 @@ export function buildInstallScript(plan: RemoteInstallPlan): string {' return 0',' fi',' if [ "$_got" != "$_hex" ]; then',- ' log failed "checksum mismatch: $_name (want sha$_algo:$_hex, got $_got)"',- ' exit 11',+ ' log verify "校验不通过: $_name (want sha$_algo:$_hex, got $_got)"',+ ' return 1',' fi',` log verify "$_name 校验通过 (sha$_algo)"`,'}',@@ -304,10 +328,9 @@ export function buildInstallScript(plan: RemoteInstallPlan): string {' log install "node 已就绪: $("$ROOT/runtime/bin/node" --version 2>/dev/null || echo installed)"','else',` log download "node ${plan.node.version}"`,- ` fetch "$TMP/node.tar.gz" ${quoteUrls(plan.node.urls)}`,` fetch "$TMP/SHASUMS256.txt" ${quoteUrls(plan.node.shasumUrls)}`,` _want="$(grep " ${plan.node.filename}\$" "$TMP/SHASUMS256.txt" | head -n 1 | tr -d '\\r' | sed 's/^ *//' | cut -d' ' -f1)"`,- ` verify "$TMP/node.tar.gz" "\$_want" "${plan.node.filename}"`,+ ` fetch_verified "$TMP/node.tar.gz" "\$_want" "${plan.node.filename}" ${quoteUrls(plan.node.urls)}`,' rm -rf "$ROOT/runtime.new"',' mkdir -p "$ROOT/runtime.new"',' tar -xzf "$TMP/node.tar.gz" -C "$ROOT/runtime.new" --strip-components=1',@@ -318,8 +341,7 @@ export function buildInstallScript(plan: RemoteInstallPlan): string {' log install "pnpm 已就绪"','else',` log download "pnpm ${plan.pnpm.version}"`,- ` fetch "$TMP/pnpm.tgz" ${quoteUrls(plan.pnpm.urls)}`,- ` verify "$TMP/pnpm.tgz" "sha256:${plan.pnpm.sha256}" "pnpm-${plan.pnpm.version}.tgz"`,+ ` fetch_verified "$TMP/pnpm.tgz" "sha256:${plan.pnpm.sha256}" "pnpm-${plan.pnpm.version}.tgz" ${quoteUrls(plan.pnpm.urls)}`,' rm -rf "$ROOT/dependencies/pnpm.new"',' mkdir -p "$ROOT/dependencies/pnpm.new"',' tar -xzf "$TMP/pnpm.tgz" -C "$ROOT/dependencies/pnpm.new" --strip-components=1',diff --git a/packages/dsh-tauri-ssh/src/host/utils/assets.test.ts b/packages/dsh-tauri-ssh/src/host/utils/assets.test.tsindex 65077d0d..2eb68668 100644--- a/packages/dsh-tauri-ssh/src/host/utils/assets.test.ts+++ b/packages/dsh-tauri-ssh/src/host/utils/assets.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from 'vitest'import {assetMatrixFor,+ DSH_MIRROR_PREFIXES,dshNpmTarballUrls,dshZipDownloadUrls,nodeDownloadUrls,@@ -91,10 +92,11 @@ describe('download URL builders', () => {])})- it('builds the packaged zip URL pair (GitHub official → ghfast.top mirror)', () => {+ it('builds the packaged zip URL list (GitHub official → every proxy mirror)', () => {+ const asset = 'https://github.com/dsh-tauri-desk/deepseek-harness-pkg/releases/download/dsh-0.1.2-rc.1-1/deepseek-harness-pkg-linux.zip'expect(dshZipDownloadUrls('dsh-tauri-desk/deepseek-harness-pkg', 'dsh-0.1.2-rc.1-1', 'deepseek-harness-pkg-linux.zip')).toEqual([- 'https://github.com/dsh-tauri-desk/deepseek-harness-pkg/releases/download/dsh-0.1.2-rc.1-1/deepseek-harness-pkg-linux.zip',- 'https://ghfast.top/https://github.com/dsh-tauri-desk/deepseek-harness-pkg/releases/download/dsh-0.1.2-rc.1-1/deepseek-harness-pkg-linux.zip',+ asset,+ ...DSH_MIRROR_PREFIXES.map(prefix => `${prefix}${asset}`),])})diff --git a/packages/dsh-tauri-ssh/src/host/utils/assets.ts b/packages/dsh-tauri-ssh/src/host/utils/assets.tsindex 6e198602..9c2162e6 100644--- a/packages/dsh-tauri-ssh/src/host/utils/assets.ts+++ b/packages/dsh-tauri-ssh/src/host/utils/assets.ts@@ -104,9 +104,17 @@ export function pnpmDownloadUrls(): string[] {]}+/** GitHub Release 代理镜像前缀(与桌面端 config::DSH_MIRROR_PREFIXES 保持同一份清单) */+export const DSH_MIRROR_PREFIXES = [+ 'https://gh-proxy.com/',+ 'https://gh.llkk.cc/',+ 'https://ghfast.top/',+ 'https://ghproxy.net/',+] as const+export function dshZipDownloadUrls(repo: string, tag: string, assetName: string): string[] {const official = `https://github.com/${repo}/releases/download/${tag}/${assetName}`- return [official, `https://ghfast.top/${official}`]+ return [official, ...DSH_MIRROR_PREFIXES.map(prefix => `${prefix}${official}`)]}export function dshNpmTarballUrls(packageName: string, version: string): string[] {diff --git a/src-tauri/src/config/constants.rs b/src-tauri/src/config/constants.rsindex 840167b5..e98ef701 100644--- a/src-tauri/src/config/constants.rs+++ b/src-tauri/src/config/constants.rs@@ -13,9 +13,14 @@ pub const NODE_MIRROR_BASE_URL: &str = "https://npmmirror.com/mirrors/node/";pub const DSH_CORE_URL: &str ="https://github.com/dsh-tauri-desk/deepseek-harness-pkg/releases/latest/download/";-/// GitHub Release 的 ghfast.top 中转前缀(透传官方 URL,下载内容一致、-/// 仍可做 SHA-256 完整性校验),用作官方直连失败时的兜底镜像。-pub const DSH_MIRROR_PREFIX: &str = "https://ghfast.top/";+/// GitHub Release 的代理镜像前缀列表(透传官方 URL,下载内容一致、+/// 仍可做 SHA-256 完整性校验),按实测延迟从低到高排列,官方直连失败时依次兜底。+pub const DSH_MIRROR_PREFIXES: &[&str] = &[+ "https://gh-proxy.com/",+ "https://gh.llkk.cc/",+ "https://ghfast.top/",+ "https://ghproxy.net/",+];/// 捆绑的 pnpm 版本(与 deepseek-harness-pkg 的 packageManager: [email protected] 对齐)pub const PNPM_VERSION: &str = "11.7.0";diff --git a/src-tauri/src/config/region.rs b/src-tauri/src/config/region.rsindex 86dfb5a5..e3a0bb77 100644--- a/src-tauri/src/config/region.rs+++ b/src-tauri/src/config/region.rs@@ -1,4 +1,4 @@-//! 下载地域检测:中国大陆用户自动切换镜像加速源(npmmirror / ghfast.top 中转),+//! 下载地域检测:中国大陆用户自动切换镜像加速源(npmmirror / GitHub 代理镜像),//! 避免直连 GitHub / nodejs.org 大文件下载缓慢。use std::sync::OnceLock;@@ -6,7 +6,7 @@ use std::sync::OnceLock;/// 下载源地域#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Region {- /// 中国大陆:走镜像(npmmirror / ghfast.top 中转)+ /// 中国大陆:走镜像(npmmirror / GitHub 代理镜像)Domestic,/// 其他地区:直连官方源(nodejs.org / GitHub)Overseas,diff --git a/src-tauri/src/config/runtime.rs b/src-tauri/src/config/runtime.rsindex a8d4c7ba..37e6e4fe 100644--- a/src-tauri/src/config/runtime.rs+++ b/src-tauri/src/config/runtime.rs@@ -88,10 +88,13 @@ pub fn get_dsh_download_url() -> Result<String, String> {Ok(format!("{}{}", DSH_CORE_URL, dsh_pkg_asset_filename()?))}-/// 为任意 GitHub Release 资产 URL 生成 ghfast.top 镜像兜底地址+/// 为任意 GitHub Release 资产 URL 生成全部镜像兜底地址/// (透传原 URL,下载内容一致,仍可做 SHA-256 完整性校验)。-pub fn mirror_download_url(asset_url: &str) -> String {- format!("{DSH_MIRROR_PREFIX}{asset_url}")+pub fn mirror_download_urls(asset_url: &str) -> Vec<String> {+ DSH_MIRROR_PREFIXES+ .iter()+ .map(|prefix| format!("{prefix}{asset_url}"))+ .collect()}/// 指定 tag 的 DeepSeek Harness 发行版下载地址。@@ -681,12 +684,13 @@ mod tests {}#[test]- fn mirror_url_prepends_ghfast_prefix() {+ fn mirror_urls_expand_every_prefix() {let asset = "https://github.com/dsh-tauri-desk/deepseek-harness-pkg/releases/download/v1.0.0/deepseek-harness-pkg-windows.zip";- assert_eq!(- mirror_download_url(asset),- format!("{DSH_MIRROR_PREFIX}{asset}")- );+ let urls = mirror_download_urls(asset);+ assert_eq!(urls.len(), DSH_MIRROR_PREFIXES.len());+ for (url, prefix) in urls.iter().zip(DSH_MIRROR_PREFIXES) {+ assert_eq!(url, &format!("{prefix}{asset}"));+ }}#[test]diff --git a/src-tauri/src/service/core/version.rs b/src-tauri/src/service/core/version.rsindex 6850ab49..d68ed477 100644--- a/src-tauri/src/service/core/version.rs+++ b/src-tauri/src/service/core/version.rs@@ -701,16 +701,14 @@ pub async fn download_version(app_handle: &AppHandle, tag: &str) -> Result<Harne})?;// 2. 下载 + 校验 + 原子解压到历史槽位(两阶段进度:下载 0-50,解压 50-100)- // 下载默认走 GitHub 官方直连,失败自动切换 ghfast.top 镜像兜底。+ // 下载默认走 GitHub 官方直连,失败自动切换代理镜像兜底。let window = app_handle.get_webview_window("main").ok_or("WINDOW_NOT_FOUND: main window missing")?;let mut tracker = download::ProgressTracker::new(&window, 2);tracker.start_phase("download", &format!("正在下载核心版本 {tag}"));- let urls = vec![- info.asset_url.clone(),- config::mirror_download_url(&info.asset_url),- ];+ let mut urls = vec![info.asset_url.clone()];+ urls.extend(config::mirror_download_urls(&info.asset_url));let buffer = download::download_file_from_sources(&tracker, urls).await.map_err(|e| format!("CORE_DOWNLOAD_FAILED: {e}"))?;diff --git a/src-tauri/src/service/download/core.rs b/src-tauri/src/service/download/core.rsindex 456b801f..b86931f3 100644--- a/src-tauri/src/service/download/core.rs+++ b/src-tauri/src/service/download/core.rs@@ -25,13 +25,13 @@ pub async fn download_file<'a, R: Runtime>(download_file_from_sources(tracker, vec![url]).await}-/// 按顺序依次尝试多个下载源(如 GitHub 官方直连 → ghfast.top 镜像兜底),+/// 按顺序依次尝试多个下载源(GitHub 官方直连 → 多个 GitHub 代理镜像兜底),/// 某个源全部重试失败后自动切换下一个源,并通过 `tracker` 在界面上告知用户/// 当前使用的下载源;全部源均失败时返回最后一个源的错误并注明尝试过的源数。///-/// 每个源内部仍走 `download_with_retry` 的断点续传重试;切换源时保留已下载-/// 的字节续传(镜像透传同一文件,内容一致,且最终有 SHA-256 完整性校验兜底;-/// 服务端不支持 Range 时 `download_attempt` 会自动清空从头下载)。+/// 断点续传只在单个源内部生效(`download_with_retry` 的字节缓冲按源独立):+/// 换源必然从头下载,避免把不同来源的半成品拼成一个文件;镜像只是原样透传+/// 官方资产,最终内容仍由 SHA-256 校验兜底。pub async fn download_file_from_sources<'a, R: Runtime>(tracker: &'a ProgressTracker<'a, R>,urls: Vec<String>,@@ -258,11 +258,14 @@ fn validate_download_url(url: &str) -> Result<(), String> {| "release-assets.githubusercontent.com"| "objects.githubusercontent.com"// 国内镜像:npmmirror 系列(node dist 会 302 到 cdn.npmmirror.com)- // 与 ghfast.top 中转(GitHub Release 内容原样透传)+ // 与 GitHub Release 代理(原样透传,重定向后仍落在镜像自身域名)| "npmmirror.com"| "cdn.npmmirror.com"| "registry.npmmirror.com"+ | "gh-proxy.com"+ | "gh.llkk.cc"| "ghfast.top"+ | "ghproxy.net"));if parsed.scheme() != "https" || !trusted_host {@@ -601,10 +604,15 @@ mod tests {validate_download_url("https://cdn.npmmirror.com/binaries/node/v22/file.zip").is_ok());assert!(validate_download_url("https://registry.npmmirror.com/pnpm/-/pnpm.tgz").is_ok());- assert!(validate_download_url(- "https://ghfast.top/https://github.com/dsh-tauri-desk/deepseek-harness-pkg/releases/latest/download/deepseek-harness-pkg-windows.zip"- )- .is_ok());+ for prefix in crate::config::DSH_MIRROR_PREFIXES {+ assert!(+ validate_download_url(&format!(+ "{prefix}https://github.com/dsh-tauri-desk/deepseek-harness-pkg/releases/latest/download/deepseek-harness-pkg-windows.zip"+ ))+ .is_ok(),+ "镜像前缀应被放行: {prefix}"+ );+ }}#[tokio::test]diff --git a/src-tauri/src/service/update/install.rs b/src-tauri/src/service/update/install.rsindex d3731d74..44c0fe50 100644--- a/src-tauri/src/service/update/install.rs+++ b/src-tauri/src/service/update/install.rs@@ -1,7 +1,7 @@//! 安装包下载、完整性校验与交付系统处理器打开。//!//! 下载源策略:先取 `expanded_assets` 页面的 SHA-256 摘要作为完整性凭据,再选择-//! 下载源——镜像兜底(ghfast.top)仅在已取得可信摘要时才可使用,否则宁可失败,+//! 下载源——镜像兜底(GitHub 代理镜像)仅在已取得可信摘要时才可使用,否则宁可失败,//! 防止第三方镜像投毒未被察觉;官方 GitHub 直连在摘要缺失时仍可按旧行为下载,//! 下载后若有摘要则强制校验。@@ -141,14 +141,14 @@ fn download_client(app_handle: &AppHandle) -> Result<reqwest::Client, String> {.map_err(|e| format!("UPDATE_CLIENT: {e}"))}-/// 组装安装包下载源列表:官方 GitHub 直连 + (存在可信摘要时)ghfast.top 镜像。+/// 组装安装包下载源列表:官方 GitHub 直连 + (存在可信摘要时)代理镜像。////// 安全策略:第三方镜像没有独立信任根,仅在其内容可被 SHA-256 校验(摘要已取得)/// 时才提供兜底;否则只允许官方直连,宁可在官方不可用时失败,也不冒投毒风险。fn download_sources(release: &LatestRelease) -> Vec<String> {let mut urls = vec![release.url.clone()];if release.digest.is_some() {- urls.push(config::mirror_download_url(&release.url));+ urls.extend(config::mirror_download_urls(&release.url));}urls}@@ -213,7 +213,7 @@ fn verify_installer_sha256(path: &std::path::Path, expected: &str) -> Result<(),/// `DesktopUpdateInfo`(path/downloaded 已更新)。////// 下载源策略:先取 `expanded_assets` 页面的 SHA-256 摘要作为完整性凭据,再-/// 选择下载源——**镜像兜底(ghfast.top)仅在已取得可信摘要时才可使用**,否则+/// 选择下载源——**镜像兜底(GitHub 代理镜像)仅在已取得可信摘要时才可使用**,否则/// 宁可失败,防止第三方镜像投毒未被察觉;官方 GitHub 直连在摘要缺失时仍可/// 按旧行为下载(兼容早期未填摘要的发布),下载后若有摘要则强制校验。pub async fn download(app_handle: &AppHandle) -> Result<DesktopUpdateInfo, String> {@@ -234,7 +234,7 @@ pub async fn download(app_handle: &AppHandle) -> Result<DesktopUpdateInfo, Strinlet client = download_client(app_handle)?;- // 官方直连 → (可选)ghfast.top 镜像兜底。安装包无 SHA-256 元数据,切换源时+ // 官方直连 → (可选)多个 GitHub 代理镜像兜底。安装包无 SHA-256 元数据,切换源时// 丢弃上一源的部分字节从头下载,避免混用两个源的字节流。// 安全策略:镜像兜底要求已有可信摘要,否则不提供镜像(宁可失败)。let urls = download_sources(&release);@@ -788,17 +788,17 @@ mod tests {..base.clone()};let sources = download_sources(&with_digest);- assert_eq!(sources.len(), 2);- assert!(- sources[1].contains("ghfast.top"),- "镜像应为 ghfast.top 前缀: {}",- sources[1]- );- assert!(- sources[1].ends_with("/releases/download/v0.7.4/x.dmg"),- "镜像保留完整资产路径: {}",- sources[1]- );+ assert_eq!(sources.len(), 1 + crate::config::DSH_MIRROR_PREFIXES.len());+ for (source, prefix) in sources[1..].iter().zip(crate::config::DSH_MIRROR_PREFIXES) {+ assert!(+ source.starts_with(prefix),+ "镜像应为 {prefix} 前缀: {source}"+ );+ assert!(+ source.ends_with("/releases/download/v0.7.4/x.dmg"),+ "镜像保留完整资产路径: {source}"+ );+ }}/// 流式校验:正确的文件通过、错误的摘要拒绝,且不把整个文件读进内存。diff --git a/src-tauri/src/service/workflow/install.rs b/src-tauri/src/service/workflow/install.rsindex 817a4e0f..f4d3b0b6 100644--- a/src-tauri/src/service/workflow/install.rs+++ b/src-tauri/src/service/workflow/install.rs@@ -144,7 +144,7 @@ pub async fn install(// 下载 URL 对 dsh 也是完全确定可算的(DSH_CORE_URL + 平台文件名),// 无需依赖 GitHub API 元数据;api.github.com 限流/被代理拦截时// (mac 首次启动常见)仍能拿到真实下载地址,避免整次安装被瞬时失败卡死。- // dsh 核心默认先走 GitHub 官方直连,失败自动切换 ghfast.top 镜像兜底+ // dsh 核心默认先走 GitHub 官方直连,失败依次切换代理镜像兜底// (下载层会在界面上告知用户);其余任务保持单一官方源。let (urls, name) = if kind == download::InstallKind::Dsh {// 摘要与资产必须来自同一个 release。若前面已取得 release 元数据,@@ -156,7 +156,8 @@ pub async fn install(.filter(|url| !url.is_empty()).unwrap_or(config::get_dsh_download_url()?);let name = primary.rsplit('/').next().unwrap_or("").to_string();- let urls = vec![primary.clone(), config::mirror_download_url(&primary)];+ let mut urls = vec![primary.clone()];+ urls.extend(config::mirror_download_urls(&primary));(urls, name)} else {let url = task.get_download_url()?;diff --git a/src/components/logs.utils.ts b/src/components/logs.utils.tsindex aa922550..161dbd38 100644--- a/src/components/logs.utils.ts+++ b/src/components/logs.utils.ts@@ -1,7 +1,12 @@/** DSH 发行版 GitHub Release 下载 URL 前缀:日志展示时剥离,避免整段长 URL 占满一行 */const DSH_RELEASE_URL_PREFIX = 'https://github.com/dsh-tauri-desk/deepseek-harness-pkg/releases/download/'-/** ghfast.top 镜像透传包装前缀(与官方 URL 拼接),同样剥离 */-const DSH_MIRROR_URL_PREFIX = 'https://ghfast.top/'+/** GitHub 代理镜像的透传包装前缀(与官方 URL 拼接),同样剥离 */+const DSH_MIRROR_URL_PREFIXES = [+ 'https://gh-proxy.com/',+ 'https://gh.llkk.cc/',+ 'https://ghfast.top/',+ 'https://ghproxy.net/',+]/** 日志中认定为「错误行」的标记(大小写不敏感) */const ERROR_LINE_MARKERS = /error|duplicate|fatal|panic|throw|✖|exception|failed/i@@ -12,10 +17,9 @@ const ERROR_LINE_MARKERS = /error|duplicate|fatal|panic|throw|✖|exception|fail* 用 split/join 代替 replaceAll 以保证各构建目标下行为一致。*/export function formatLogLine(line: string): string {- return line- .split(DSH_RELEASE_URL_PREFIX)- .join('')- .replace(DSH_MIRROR_URL_PREFIX, '')+ let formatted = line.split(DSH_RELEASE_URL_PREFIX).join('')+ for (const prefix of DSH_MIRROR_URL_PREFIXES) formatted = formatted.split(prefix).join('')+ return formatted}/**diff --git a/test/index.test.ts b/test/index.test.tsindex 1fb587b0..84670f3b 100644--- a/test/index.test.ts+++ b/test/index.test.ts@@ -9,10 +9,12 @@ describe('formatLogLine', () => {)})- it('strips the ghfast.top mirror wrapper prefix', () => {- const url = 'https://ghfast.top/https://github.com/dsh-tauri-desk/deepseek-harness-pkg/releases/download/dsh-0.1.x-x/deepseek-harness-pkg-linux.zip'- expect(formatLogLine(`Download ${url}`)).toContain('deepseek-harness-pkg-linux.zip')- expect(formatLogLine(`Download ${url}`)).not.toContain('ghfast.top')+ it('strips every mirror wrapper prefix', () => {+ const asset = 'https://github.com/dsh-tauri-desk/deepseek-harness-pkg/releases/download/dsh-0.1.x-x/deepseek-harness-pkg-linux.zip'+ for (const prefix of ['https://gh-proxy.com/', 'https://gh.llkk.cc/', 'https://ghfast.top/', 'https://ghproxy.net/']) {+ const formatted = formatLogLine(`Download ${prefix}${asset}`)+ expect(formatted).toBe('Download dsh-0.1.x-x/deepseek-harness-pkg-linux.zip')+ }})it('leaves ordinary log lines untouched', () => {