From 20cf7394e5c167b59ce1648f171c21bc49c1451c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=89=8B=E7=93=9C=E4=B8=80=E5=8D=81=E9=9B=AA?= Date: Sun, 18 Oct 2026 19:41:02 +0800 Subject: [PATCH] fix(update): recover from GitHub rate limits with configurable mirrors --- packages/common/package.json | 4 + packages/common/src/runtime.ts | 8 +- packages/common/src/update-source.ts | 60 ++++ packages/common/tests/update-source.test.ts | 54 ++++ packages/core/src/update/README.md | 19 ++ packages/core/src/update/check.ts | 72 +++-- packages/core/src/update/download.ts | 157 ++++++---- packages/core/src/update/release.ts | 196 +++++++++++++ packages/core/src/update/sources.ts | 125 ++++++++ packages/core/src/webui/update-routes.ts | 42 +++ packages/core/tests/update-download.test.ts | 105 ++++++- packages/core/tests/update-release.test.ts | 126 +++++++++ .../core/tests/update-source-routes.test.ts | 105 +++++++ packages/core/tests/update-sources.test.ts | 81 ++++++ .../core/tests/webui-update-check.test.ts | 32 ++- .../src/components/pages/settings-page.tsx | 7 + .../components/settings/update-sources.tsx | 267 ++++++++++++++++++ packages/webui/src/lib/api/client.ts | 8 + packages/webui/src/lib/api/types.ts | 6 + packages/webui/src/types.ts | 18 ++ packages/webui/tests/update-api.test.ts | 24 ++ 21 files changed, 1423 insertions(+), 93 deletions(-) create mode 100644 packages/common/src/update-source.ts create mode 100644 packages/common/tests/update-source.test.ts create mode 100644 packages/core/src/update/README.md create mode 100644 packages/core/src/update/release.ts create mode 100644 packages/core/src/update/sources.ts create mode 100644 packages/core/tests/update-release.test.ts create mode 100644 packages/core/tests/update-source-routes.test.ts create mode 100644 packages/core/tests/update-sources.test.ts create mode 100644 packages/webui/src/components/settings/update-sources.tsx diff --git a/packages/common/package.json b/packages/common/package.json index 5dcc8056..7bac666a 100644 --- a/packages/common/package.json +++ b/packages/common/package.json @@ -8,6 +8,10 @@ "main": "./src/index.ts", "types": "./src/index.ts", "exports": { + "./update-source": { + "types": "./src/update-source.ts", + "default": "./src/update-source.ts" + }, "./semver": { "types": "./src/semver.ts", "default": "./src/semver.ts" diff --git a/packages/common/src/runtime.ts b/packages/common/src/runtime.ts index 035723f0..0d2b01b1 100644 --- a/packages/common/src/runtime.ts +++ b/packages/common/src/runtime.ts @@ -1,8 +1,10 @@ import fs from 'fs'; import path from 'path'; import { isObject } from './coerce'; +import { normalizeUpdateSourceConfig, type UpdateSourceConfig } from './update-source'; export interface RuntimeConfig { + updateSource?: UpdateSourceConfig; webuiPort?: number; /** When true, every newly-discovered QQ process gets auto-injected by * the HookManager. Also overridable at runtime via SNOWLUMA_HOOK_AUTOLOAD. @@ -43,6 +45,9 @@ export const MAX_LOG_RETAIN_DAYS = Math.floor(Number.MAX_SAFE_INTEGER / (24 * 60 export function normalizeRuntimeConfig(parsed: unknown): RuntimeConfig { const obj = isObject(parsed) ? parsed : {}; return { + ...(obj.updateSource === undefined + ? {} + : { updateSource: normalizeUpdateSourceConfig(obj.updateSource) }), webuiPort: normalizePort(obj.webuiPort ?? DEFAULT_WEBUI_PORT, DEFAULT_WEBUI_PORT), hookAutoLoad: normalizeBool(obj.hookAutoLoad, false), webuiHost: normalizeHost(obj.webuiHost), @@ -217,7 +222,8 @@ function sameRuntimeConfig(parsed: Record, n: RuntimeConfig): b parsed.trustProxy === n.trustProxy && parsed.logMaxTotalMb === n.logMaxTotalMb && parsed.logRetainDays === n.logRetainDays && - parsed.logPerUin === n.logPerUin + parsed.logPerUin === n.logPerUin && + JSON.stringify(parsed.updateSource) === JSON.stringify(n.updateSource) ); } diff --git a/packages/common/src/update-source.ts b/packages/common/src/update-source.ts new file mode 100644 index 00000000..20956d8d --- /dev/null +++ b/packages/common/src/update-source.ts @@ -0,0 +1,60 @@ +export interface UpdateSourceConfig { + mode: 'auto' | 'direct' | 'mirror'; + mirror: string; + mirrors: string[]; +} + +export function normalizeMirrorUrl(value: unknown): string { + if (typeof value !== 'string' || value.length > 2048) { + throw new Error('镜像地址必须是 HTTP(S) URL'); + } + + let url: URL; + + try { + url = new URL(value.trim()); + } catch { + throw new Error('镜像地址必须是 HTTP(S) URL'); + } + + if ( + !['http:', 'https:'].includes(url.protocol) || + url.username || + url.password || + url.search || + url.hash + ) { + throw new Error('镜像地址仅支持 HTTP(S),不能包含账号、密码、查询参数或片段'); + } + + return url.href.replace(/\/+$/, ''); +} + +export function normalizeUpdateSourceConfig(value: unknown): UpdateSourceConfig { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + throw new Error('更新来源必须是对象'); + } + + if ( + !('mode' in value) || + (value.mode !== 'auto' && value.mode !== 'direct' && value.mode !== 'mirror') + ) { + throw new Error('更新来源模式无效'); + } + + if (!('mirrors' in value) || !Array.isArray(value.mirrors) || value.mirrors.length > 16) { + throw new Error('自动筛选最多支持 16 个镜像'); + } + + const mirror = 'mirror' in value && value.mirror !== '' ? normalizeMirrorUrl(value.mirror) : ''; + + if (value.mode === 'mirror' && !mirror) { + throw new Error('请指定镜像地址'); + } + + return { + mode: value.mode, + mirror, + mirrors: [...new Set(value.mirrors.map(normalizeMirrorUrl))], + }; +} diff --git a/packages/common/tests/update-source.test.ts b/packages/common/tests/update-source.test.ts new file mode 100644 index 00000000..1d18f530 --- /dev/null +++ b/packages/common/tests/update-source.test.ts @@ -0,0 +1,54 @@ +import { describe, expect, it } from 'vitest'; +import { normalizeMirrorUrl, normalizeUpdateSourceConfig } from '../src/update-source'; +import { normalizeRuntimeConfig } from '../src/runtime'; + +describe('update source configuration', () => { + it('normalizes proxy prefixes, deduplicates mirrors and retains order', () => { + expect( + normalizeUpdateSourceConfig({ + mode: 'auto', + mirror: '', + mirrors: [ + ' https://EXAMPLE.com/proxy/ ', + 'https://example.com/proxy', + 'https://other.example', + ], + }), + ).toEqual({ + mode: 'auto', + mirror: '', + mirrors: ['https://example.com/proxy', 'https://other.example'], + }); + }); + + it.each([ + '', + 'file:///tmp/x', + 'ftp://example.com', + 'https://user:secret@example.com', + 'https://example.com/?token=a', + 'https://example.com/#a', + null, + ])('rejects invalid mirror %s', (url) => { + expect(() => normalizeMirrorUrl(url)).toThrow(); + }); + + it.each([ + null, + [], + { mode: ['auto'], mirrors: [] }, + { mode: 'mirror', mirror: '', mirrors: [] }, + { mode: 'auto', mirrors: Array(17).fill('https://example.com') }, + ])('rejects invalid configuration %j', (config) => { + expect(() => normalizeUpdateSourceConfig(config)).toThrow(); + }); + + it('retains configured update sources when normalizing runtime settings', () => { + const updateSource = { mode: 'direct', mirror: '', mirrors: [] }; + expect(normalizeRuntimeConfig({ updateSource, webuiPort: 7777 })).toMatchObject({ + updateSource, + webuiPort: 7777, + }); + expect(normalizeRuntimeConfig({})).not.toHaveProperty('updateSource'); + }); +}); diff --git a/packages/core/src/update/README.md b/packages/core/src/update/README.md new file mode 100644 index 00000000..f0cd9e04 --- /dev/null +++ b/packages/core/src/update/README.md @@ -0,0 +1,19 @@ +# 在线更新与镜像 + +在 WebUI「设置 → 关于 → 软件更新 → 更新来源」中选择: + +- **自动切换**:先尝试 GitHub,下载失败后按候选列表顺序切换。 +- **GitHub 直连**:只访问 GitHub。 +- **指定镜像**:更新包只从指定镜像下载;版本和校验值查询仍会尝试 GitHub。 + +内置 10 个候选镜像:`ghfast.top`、`ghproxy.net`、`gh-proxy.com`、`github.chenc.dev`、`fastgit.cc`、`gh.noki.icu`、`cors.isteed.cc`、`gh-proxy.org`、`githubproxy.gohj99.site`、`github.xxlab.tech`。 + +「检测可用性」从 SnowLuma 所在服务器请求当前版本更新包的前几个字节,检查 ZIP/Gzip 文件特征,并按可用性和响应延迟排序。它会取消剩余响应体,避免检测时下载完整文件。检测延迟不代表下载速度;镜像可用性也会随网络环境变化。 + +可以选用检测通过的来源、仅保留可用镜像,或编辑候选列表(每行一个,最多 16 个)。地址是追加完整 GitHub URL 的 HTTP(S) 代理前缀,可包含路径,不能包含账号、密码、查询参数或片段。修改后点击「保存来源」,下次检查和下载生效。设置保存在 `config/runtime.json` 的 `updateSource` 字段中,不影响正在下载的任务。 + +GitHub API 返回 403、超时或不可用时,更新器读取已有的正式版发布页面获取版本,从已有附件列表读取对应文件的 SHA-256。无需额外发布 metadata 文件,也支持已发布的发行包。页面格式变化或缺少校验值时会报错,不会跳过校验。 + +所有更新包都须通过 SHA-256 校验后才能解包。API 提供的精确大小会继续校验;网页回退时使用响应的 Content-Length,缺少该头时限制最大下载量为 256 MiB 并验证完整摘要。下载中断或校验失败后,自动模式会清理该次下载的临时文件,再尝试下一个来源。解包仍检查目录边界、版本和目标平台。 + +更新先暂存,下次重启时替换运行文件,配置、日志和消息数据保留。源码运行和容器部署不启用文件替换;容器应更新镜像。 diff --git a/packages/core/src/update/check.ts b/packages/core/src/update/check.ts index 6c1f59bf..4f3b6d91 100644 --- a/packages/core/src/update/check.ts +++ b/packages/core/src/update/check.ts @@ -2,10 +2,12 @@ import { APP_VERSION } from '@snowluma/common/version'; import { compareVersions, parseVersion } from '@snowluma/common/semver'; import { createLogger } from '@snowluma/common/logger'; import { createSingleFlightCache } from '@snowluma/common/single-flight-cache'; +import type { UpdateSourceConfig } from '@snowluma/common/update-source'; +import { fetchRelease } from './release'; +import { readUpdateSource } from './sources'; const log = createLogger('Update'); -const LATEST_RELEASE_URL = 'https://api.github.com/repos/SnowLuma/SnowLuma/releases/latest'; const CACHE_TTL_MS = 6 * 60 * 60 * 1000; // 6h — comfortably under the rate limit const FETCH_TIMEOUT_MS = 8_000; const NOTES_MAX = 4_000; // cap the release-body we hand back to the client @@ -29,13 +31,6 @@ export interface UpdateCheckResult { error?: string; } -interface GithubRelease { - tag_name?: string; - html_url?: string; - body?: string; - published_at?: string; -} - function isEnabled(): boolean { const v = (process.env.SNOWLUMA_UPDATE_CHECK ?? '').trim().toLowerCase(); return v !== '0' && v !== 'false' && v !== 'off' && v !== 'no'; @@ -47,8 +42,10 @@ function isEnabled(): boolean { const updateCache = createSingleFlightCache({ ttlMs: CACHE_TTL_MS, shouldCache: (r) => !r.error, - load: async (current) => { - const result = await fetchLatest(current); + load: async (key) => { + // This key is constructed below from our version and normalized settings. + const [current, source] = JSON.parse(key) as [string, UpdateSourceConfig]; + const result = await fetchLatest(current, source); if (result.error) { log.debug('update check failed: %s', result.error); @@ -60,7 +57,10 @@ const updateCache = createSingleFlightCache({ }, }); -async function fetchLatest(current: string): Promise { +async function fetchLatest( + current: string, + source: UpdateSourceConfig, +): Promise { const base: UpdateCheckResult = { current, latest: null, @@ -74,21 +74,19 @@ async function fetchLatest(current: string): Promise { try { // `/releases/latest` already excludes drafts and prereleases, so this is // stable-channel by construction. - const res = await fetch(LATEST_RELEASE_URL, { - headers: { - Accept: 'application/vnd.github+json', - 'User-Agent': `SnowLuma/${current}`, - 'X-GitHub-Api-Version': '2022-11-28', - }, - signal: AbortSignal.timeout(FETCH_TIMEOUT_MS), - }); + const { data: rel } = await fetchRelease( + undefined, + source, + `SnowLuma/${current}`, + FETCH_TIMEOUT_MS, + ); - if (!res.ok) { - return { ...base, error: `github ${res.status}` }; + if (!rel || typeof rel !== 'object' || Array.isArray(rel)) { + return { ...base, error: 'invalid release info' }; } - const rel = (await res.json()) as GithubRelease; - const tag = typeof rel.tag_name === 'string' ? rel.tag_name.trim() : ''; + const tag = + 'tag_name' in rel && typeof rel.tag_name === 'string' ? rel.tag_name.trim() : ''; if (!tag) { return { ...base, error: 'no tag' }; @@ -104,9 +102,15 @@ async function fetchLatest(current: string): Promise { current, latest, hasUpdate: compareVersions(latest, current) > 0, - htmlUrl: rel.html_url ?? null, - notes: rel.body ? rel.body.slice(0, NOTES_MAX) : null, - publishedAt: rel.published_at ?? null, + htmlUrl: 'html_url' in rel && typeof rel.html_url === 'string' ? rel.html_url : null, + notes: + 'body' in rel && typeof rel.body === 'string' && rel.body + ? rel.body.slice(0, NOTES_MAX) + : null, + publishedAt: + 'published_at' in rel && typeof rel.published_at === 'string' + ? rel.published_at + : null, checkedAt: Date.now(), }; } catch (e) { @@ -120,14 +124,26 @@ async function fetchLatest(current: string): Promise { * failures come back as a result with `error` set and `hasUpdate: false`, and * are not cached so the next check retries. */ -export async function getUpdateInfo(force = false): Promise { +export async function getUpdateInfo( + force = false, + source?: UpdateSourceConfig, +): Promise { const current = APP_VERSION; if (!isEnabled()) { return { ...emptyResult(current), error: 'disabled' }; } - return updateCache.get(current, { force }); + try { + return await updateCache.get(JSON.stringify([current, source ?? readUpdateSource()]), { + force, + }); + } catch (error) { + return { + ...emptyResult(current), + error: error instanceof Error ? error.message : String(error), + }; + } } function emptyResult(current: string): UpdateCheckResult { diff --git a/packages/core/src/update/download.ts b/packages/core/src/update/download.ts index 97b19c92..ecabd4ab 100644 --- a/packages/core/src/update/download.ts +++ b/packages/core/src/update/download.ts @@ -1,43 +1,30 @@ import { createHash } from 'node:crypto'; import { createWriteStream } from 'node:fs'; -import { mkdir, readFile, writeFile } from 'node:fs/promises'; +import { mkdir, readFile, writeFile, rm } from 'node:fs/promises'; import path from 'node:path'; import { Readable, Transform } from 'node:stream'; import { pipeline } from 'node:stream/promises'; import { unzipSync } from 'fflate'; import { x as extractTar } from 'tar'; import { isRuntimeEntry, readManifest } from './files'; +import { assetName, fetchRelease } from './release'; +export { assetName } from './release'; +import { readUpdateSource, sourceUrls } from './sources'; +import type { UpdateSourceConfig } from '@snowluma/common/update-source'; interface ReleaseAsset { url: string; - size: number; + size: number | null; digest: string; } -export function assetName(version: string, target: string): string { - const platform = target.replace('win32', 'win'); - return `SnowLuma-v${version}-${platform}-lite.${target.startsWith('win32') ? 'zip' : 'tar.gz'}`; -} - -async function releaseAsset(version: string, target: string): Promise { +async function releaseAsset( + version: string, + target: string, + source: UpdateSourceConfig, +): Promise { const name = assetName(version, target); - const response = await fetch( - `https://api.github.com/repos/SnowLuma/SnowLuma/releases/tags/v${version}`, - { - headers: { - Accept: 'application/vnd.github+json', - 'User-Agent': 'SnowLuma', - 'X-GitHub-Api-Version': '2022-11-28', - }, - signal: AbortSignal.timeout(15_000), - }, - ); - - if (!response.ok) { - throw new Error(`获取更新失败: GitHub ${response.status}`); - } - - const release: unknown = await response.json(); + const { data: release, fromPage } = await fetchRelease(version, source); if ( !release || @@ -58,9 +45,10 @@ async function releaseAsset(version: string, target: string): Promise 0) + ) || !('digest' in asset) || typeof asset.digest !== 'string' || !/^sha256:[a-f0-9]{64}$/.test(asset.digest) @@ -94,37 +82,98 @@ export async function downloadUpdate( directory: string, version: string, target: string, + source = readUpdateSource(), ): Promise { - const asset = await releaseAsset(version, target); - const response = await fetch(asset.url, { signal: AbortSignal.timeout(10 * 60_000) }); - - if (!response.ok || !response.body) { - throw new Error(`下载更新失败: HTTP ${response.status}`); - } - + const asset = await releaseAsset(version, target, source); const archive = path.join(directory, 'archive'); - const hash = createHash('sha256'); - let received = 0; - await pipeline( - Readable.fromWeb(response.body), - new Transform({ - transform(chunk: Buffer, _encoding, callback) { - received += chunk.length; + const urls = sourceUrls(asset.url, source); + const failures: string[] = []; - if (received > asset.size) { - callback(new Error('更新包大小不匹配')); - return; - } + for (const [index, url] of urls.entries()) { + let created = false; - hash.update(chunk); - callback(null, chunk); - }, - }), - createWriteStream(archive, { flags: 'wx' }), - ); + try { + const headersTimeout = new AbortController(); + const timer = setTimeout(() => headersTimeout.abort(), 8_000); + let response: Response; - if (received !== asset.size || `sha256:${hash.digest('hex')}` !== asset.digest) { - throw new Error('更新包校验失败'); + try { + response = await fetch(url, { + signal: AbortSignal.any([ + headersTimeout.signal, + AbortSignal.timeout(10 * 60_000), + ]), + }); + } finally { + clearTimeout(timer); + } + + if (!response.ok || !response.body) { + await response.body?.cancel(); + throw new Error(`下载更新失败: HTTP ${response.status}`); + } + + if (/text\/html/i.test(response.headers.get('content-type') ?? '')) { + await response.body.cancel(); + throw new Error('下载源返回了 HTML 页面,而不是更新包'); + } + + const hash = createHash('sha256'); + const length = response.headers.get('content-length'); + const size = + asset.size ?? (length === null ? null : /^\d+$/.test(length) ? Number(length) : 0); + + if (size !== null && (!Number.isSafeInteger(size) || size <= 0)) { + await response.body.cancel(); + throw new Error('下载源返回了无效的更新包大小'); + } + + let received = 0; + const output = createWriteStream(archive, { flags: 'wx' }); + output.once('open', () => { + created = true; + }); + await pipeline( + Readable.fromWeb(response.body), + new Transform({ + transform(chunk: Buffer, _encoding, callback) { + received += chunk.length; + + if (received > (size ?? 256 * 1024 * 1024)) { + callback(new Error('更新包大小不匹配')); + return; + } + + hash.update(chunk); + callback(null, chunk); + }, + }), + output, + ); + + if ( + (size !== null && received !== size) || + `sha256:${hash.digest('hex')}` !== asset.digest + ) { + throw new Error('更新包校验失败'); + } + + break; + } catch (error) { + if (error && typeof error === 'object' && 'code' in error && error.code === 'EEXIST') { + throw error; + } + + failures.push(error instanceof Error ? error.message : String(error)); + + if (index === urls.length - 1) { + throw new Error([...new Set(failures)].join(';')); + } + + if (created) { + await rm(archive); + } + } } const payload = path.join(directory, 'payload'); diff --git a/packages/core/src/update/release.ts b/packages/core/src/update/release.ts new file mode 100644 index 00000000..5fe50242 --- /dev/null +++ b/packages/core/src/update/release.ts @@ -0,0 +1,196 @@ +import { parseVersion } from '@snowluma/common/semver'; +import type { UpdateSourceConfig } from '@snowluma/common/update-source'; +import { RELEASE_ROOT, sourceUrls } from './sources'; + +export function assetName(version: string, target: string): string { + const platform = target.replace('win32', 'win'); + return `SnowLuma-v${version}-${platform}-lite.${target.startsWith('win32') ? 'zip' : 'tar.gz'}`; +} + +async function readText(response: Response, limit: number): Promise { + if (!response.body) { + throw new Error('发布信息为空'); + } + + const reader = response.body.getReader(); + const chunks: Uint8Array[] = []; + let size = 0; + + try { + for (;;) { + const { value, done } = await reader.read(); + + if (done) { + break; + } + + size += value.length; + + if (size > limit) { + await reader.cancel(); + throw new Error('发布信息过大'); + } + + chunks.push(value); + } + } finally { + reader.releaseLock(); + } + + return Buffer.concat(chunks).toString('utf8'); +} + +function attribute(tag: string, name: string): string | undefined { + return new RegExp(`\\s${name}\\s*=\\s*(["'])(.*?)\\1`, 'i') + .exec(tag)?.[2] + .replaceAll('&', '&') + .replaceAll(''', "'") + .replaceAll('"', '"'); +} + +export function parseLatestReleasePage(html: string) { + const meta = html + .match(/]*>/gi) + ?.find((tag) => attribute(tag, 'property') === 'og:url'); + const canonical = meta && attribute(meta, 'content'); + + if (!canonical) { + throw new Error('发布页面缺少版本信息'); + } + + const url = new URL(canonical, 'https://github.com'); + const tag = /^\/SnowLuma\/SnowLuma\/releases\/tag\/([^/]+)$/.exec(url.pathname)?.[1]; + const decoded = tag && decodeURIComponent(tag); + const version = decoded?.startsWith('v') ? decoded.slice(1) : undefined; + const parsed = parseVersion(version); + + if (url.origin !== 'https://github.com' || !parsed || parsed.prerelease.length) { + throw new Error('发布页面不是 SnowLuma 正式版本'); + } + + return { tag_name: `v${parsed.raw}`, html_url: `${RELEASE_ROOT}/tag/v${parsed.raw}` }; +} + +/** Match the digest in the same asset row; never borrow a neighbouring asset's hash. */ +export function parseReleaseAssetsPage(html: string, version: string) { + const assets: { name: string; size: null; digest: string }[] = []; + const expected = ['win32-x64', 'linux-x64', 'linux-arm64'].map((target) => + assetName(version, target), + ); + + for (const row of html.match(/]*>[\s\S]*?<\/li>/gi) ?? []) { + const links = row.match(/]*>/gi) ?? []; + const name = expected.find((candidate) => + links.some((link) => { + const href = attribute(link, 'href'); + return ( + href === `/SnowLuma/SnowLuma/releases/download/v${version}/${candidate}` || + href === `${RELEASE_ROOT}/download/v${version}/${candidate}` + ); + }), + ); + + if (!name) { + continue; + } + + const digests = (row.match(/]*>/gi) ?? []) + .map((tag) => attribute(tag, 'value')) + .filter((value): value is string => + Boolean(value && /^sha256:[a-f0-9]{64}$/.test(value)), + ); + + if (digests.length !== 1 || assets.some((asset) => asset.name === name)) { + throw new Error('发布页面缺少唯一的文件校验信息'); + } + + // GitHub renders a rounded size in HTML. Verify the exact digest even + // when a proxy streams the asset without Content-Length. + assets.push({ name, size: null, digest: digests[0]! }); + } + + if (!assets.length) { + throw new Error('发布页面没有可验证的更新包'); + } + + return { tag_name: `v${version}`, assets }; +} + +export interface ReleaseResult { + data: unknown; + fromPage: boolean; +} + +export async function fetchRelease( + version: string | undefined, + source: UpdateSourceConfig, + userAgent = 'SnowLuma', + timeoutMs = 8_000, +): Promise { + const apiUrl = `https://api.github.com/repos/SnowLuma/SnowLuma/releases/${version ? `tags/v${version}` : 'latest'}`; + let primaryError: unknown; + + try { + const response = await fetch(apiUrl, { + headers: { + Accept: 'application/vnd.github+json', + 'User-Agent': userAgent, + 'X-GitHub-Api-Version': '2022-11-28', + }, + signal: AbortSignal.timeout(timeoutMs), + }); + + if (!response.ok) { + await response.body?.cancel(); + throw new Error(`GitHub ${response.status}`); + } + + return { + data: JSON.parse(await readText(response, 256 * 1024)) as unknown, + fromPage: false, + }; + } catch (error) { + primaryError = error; + } + + const originalUrl = version + ? `${RELEASE_ROOT}/expanded_assets/v${version}` + : `${RELEASE_ROOT}/latest`; + const controller = new AbortController(); + + try { + // Only a parsed release page can win. Fast errors and HTML interstitials + // cannot cancel a slower working source. + // Download proxies often only support assets. Always retain GitHub's + // release page for version/digest lookup, even with a pinned download mirror. + const urls = [...new Set([originalUrl, ...sourceUrls(originalUrl, source)])]; + const data = await Promise.any( + urls.map(async (url) => { + const response = await fetch(url, { + signal: AbortSignal.any([controller.signal, AbortSignal.timeout(timeoutMs)]), + }); + + if (!response.ok) { + await response.body?.cancel(); + throw new Error(`HTTP ${response.status}`); + } + + const html = await readText(response, 1024 * 1024); + return version + ? parseReleaseAssetsPage(html, version) + : parseLatestReleasePage(html); + }), + ); + return { data, fromPage: true }; + } catch (error) { + const failures = error instanceof AggregateError ? error.errors : [error]; + const details = [primaryError, ...failures] + .filter(Boolean) + .map((failure: unknown) => + failure instanceof Error ? failure.message : String(failure), + ); + throw new Error(`${[...new Set(details)].join(';')};请在更新来源中检测或指定可用镜像`); + } finally { + controller.abort(); + } +} diff --git a/packages/core/src/update/sources.ts b/packages/core/src/update/sources.ts new file mode 100644 index 00000000..20252fa1 --- /dev/null +++ b/packages/core/src/update/sources.ts @@ -0,0 +1,125 @@ +import { APP_VERSION } from '@snowluma/common/version'; +import { readRuntimeConfig, updateRuntimeConfig } from '@snowluma/common/runtime'; +import { + normalizeUpdateSourceConfig, + type UpdateSourceConfig, +} from '@snowluma/common/update-source'; + +export const RELEASE_ROOT = 'https://github.com/SnowLuma/SnowLuma/releases'; +export const DEFAULT_UPDATE_SOURCE: UpdateSourceConfig = { + mode: 'auto', + mirror: '', + mirrors: [ + 'https://ghfast.top', + 'https://ghproxy.net', + 'https://gh-proxy.com', + 'https://github.chenc.dev', + 'https://fastgit.cc', + 'https://gh.noki.icu', + 'https://cors.isteed.cc', + 'https://gh-proxy.org', + 'https://githubproxy.gohj99.site', + 'https://github.xxlab.tech', + ], +}; + +export function readUpdateSource(): UpdateSourceConfig { + return normalizeUpdateSourceConfig(readRuntimeConfig().updateSource ?? DEFAULT_UPDATE_SOURCE); +} + +export function saveUpdateSource(value: unknown): UpdateSourceConfig { + const config = normalizeUpdateSourceConfig(value); + updateRuntimeConfig({ updateSource: config }); + return config; +} + +export function sourceUrls(url: string, config: UpdateSourceConfig): string[] { + if (config.mode === 'direct') { + return [url]; + } + + if (config.mode === 'mirror') { + return [`${config.mirror}/${url}`]; + } + + return [url, ...config.mirrors.map((mirror) => `${mirror}/${url}`)]; +} + +export interface MirrorProbeResult { + mirror: string; + available: boolean; + latencyMs: number; + error?: string; +} + +export async function testUpdateSources(value: unknown): Promise { + const config = normalizeUpdateSourceConfig(value); + const mirrors = [ + ...new Set(['', ...config.mirrors, ...(config.mirror ? [config.mirror] : [])]), + ]; + const target = process.platform === 'win32' ? 'win-x64' : `linux-${process.arch}`; + const extension = process.platform === 'win32' ? 'zip' : 'tar.gz'; + const probeUrl = `${RELEASE_ROOT}/download/v${APP_VERSION}/SnowLuma-v${APP_VERSION}-${target}-lite.${extension}`; + const results = await Promise.all( + mirrors.map(async (mirror): Promise => { + const start = performance.now(); + + try { + const response = await fetch(mirror ? `${mirror}/${probeUrl}` : probeUrl, { + headers: { Range: 'bytes=0-3' }, + signal: AbortSignal.timeout(5_000), + }); + + if (!response.ok || !response.body) { + await response.body?.cancel(); + throw new Error(`HTTP ${response.status}`); + } + + if (/text\/html/i.test(response.headers.get('content-type') ?? '')) { + await response.body.cancel(); + throw new Error('返回了 HTML 页面,而不是更新包'); + } + + const reader = response.body.getReader(); + const prefix: number[] = []; + + try { + while (prefix.length < 4) { + const { value, done } = await reader.read(); + + if (done) { + break; + } + + prefix.push(...value.subarray(0, 4 - prefix.length)); + } + } finally { + await reader.cancel(); + reader.releaseLock(); + } + + const signature = extension === 'zip' ? [0x50, 0x4b, 0x03, 0x04] : [0x1f, 0x8b]; + + if (!signature.every((byte, index) => prefix[index] === byte)) { + throw new Error('返回内容不是有效的更新包'); + } + + return { + mirror, + available: true, + latencyMs: Math.round(performance.now() - start), + }; + } catch (error) { + return { + mirror, + available: false, + latencyMs: Math.round(performance.now() - start), + error: error instanceof Error ? error.message : String(error), + }; + } + }), + ); + return results.sort( + (a, b) => Number(b.available) - Number(a.available) || a.latencyMs - b.latencyMs, + ); +} diff --git a/packages/core/src/webui/update-routes.ts b/packages/core/src/webui/update-routes.ts index 984bb8cf..255d8d0f 100644 --- a/packages/core/src/webui/update-routes.ts +++ b/packages/core/src/webui/update-routes.ts @@ -1,10 +1,52 @@ import { Hono } from 'hono'; import type { HttpBindings } from '@hono/node-server'; import type { UpdateService } from '../update/service'; +import { readUpdateSource, saveUpdateSource, testUpdateSources } from '../update/sources'; +import { + normalizeUpdateSourceConfig, + type UpdateSourceConfig, +} from '@snowluma/common/update-source'; export function updateRoutes(service: UpdateService, restart: () => void) { const app = new Hono<{ Bindings: HttpBindings }>(); app.get('/status', (c) => c.json(service.status())); + app.get('/sources', (c) => { + try { + return c.json({ config: readUpdateSource() }); + } catch (error) { + return c.json({ message: error instanceof Error ? error.message : String(error) }, 500); + } + }); + app.post('/sources', async (c) => { + let config: UpdateSourceConfig; + + try { + config = normalizeUpdateSourceConfig(await c.req.json()); + } catch (error) { + return c.json({ message: error instanceof Error ? error.message : String(error) }, 400); + } + + try { + saveUpdateSource(config); + return c.json({ + config, + saved: true, + applied: true, + online: true, + errors: [], + message: '更新来源已保存', + }); + } catch (error) { + return c.json({ message: error instanceof Error ? error.message : String(error) }, 500); + } + }); + app.post('/sources/test', async (c) => { + try { + return c.json({ results: await testUpdateSources(await c.req.json()) }); + } catch (error) { + return c.json({ message: error instanceof Error ? error.message : String(error) }, 400); + } + }); app.post('/download', async (c) => { let body: unknown; diff --git a/packages/core/tests/update-download.test.ts b/packages/core/tests/update-download.test.ts index 7243abbb..f7237f6f 100644 --- a/packages/core/tests/update-download.test.ts +++ b/packages/core/tests/update-download.test.ts @@ -5,10 +5,14 @@ import path from 'node:path'; import { zipSync } from 'fflate'; import { c as createTar } from 'tar'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { archivePath, assetName, downloadUpdate } from '../src/update/download'; +import { archivePath, assetName, downloadUpdate as download } from '../src/update/download'; import { readManifest } from '../src/update/files'; import { releaseFixture } from './helpers/update-fixture'; +const direct = { mode: 'direct', mirror: '', mirrors: [] } as const; +const downloadUpdate = (directory: string, version: string, target: string) => + download(directory, version, target, { ...direct, mirrors: [] }); + let root: string; beforeEach(async () => { root = await mkdtemp(path.join(os.tmpdir(), 'snowluma-download-test-')); @@ -43,6 +47,105 @@ function mockRelease(bytes: Uint8Array, target: string, digest?: string) { } describe('release downloads', () => { + it.each(['403', 'html', 'corrupt', 'interrupted'])( + 'cleans and retries a %s response through a mirror using HTML release checksums', + async (failure) => { + const manifest = await releaseFixture(path.join(root, 'source'), '2.0.0', 'win32-x64'); + const bytes = zipSync({ + 'release.json': new TextEncoder().encode(JSON.stringify(manifest)), + 'app.mjs': new TextEncoder().encode('verified payload'), + }); + const name = assetName('2.0.0', 'win32-x64'); + const digest = createHash('sha256').update(bytes).digest('hex'); + const fetchMock = vi.fn(async (input) => { + const url = String(input); + + if (url.includes('api.github.com')) { + return new Response('rate limited', { status: 403 }); + } + + if (url.includes('/expanded_assets/')) { + return new Response( + `
  • asset
  • `, + ); + } + + if (url.startsWith('https://working.example/')) { + // Mirrors may stream a verified archive without Content-Length. + return new Response(new Uint8Array(bytes)); + } + + if (failure === '403') { + return new Response('blocked', { status: 403 }); + } + + if (failure === 'html') { + return new Response('challenge', { + headers: { 'Content-Type': 'text/html' }, + }); + } + + if (failure === 'interrupted') { + let sent = false; + return new Response( + new ReadableStream({ + pull(controller) { + if (sent) { + controller.error(new Error('connection reset')); + } else { + controller.enqueue(new Uint8Array([1, 2, 3])); + sent = true; + } + }, + }), + ); + } + + return new Response('corrupt archive'); + }); + vi.stubGlobal('fetch', fetchMock); + await download(root, '2.0.0', 'win32-x64', { + mode: 'auto', + mirror: '', + mirrors: ['https://working.example'], + }); + expect(await readFile(path.join(root, 'archive'))).toEqual(Buffer.from(bytes)); + expect(await readFile(path.join(root, 'payload/app.mjs'), 'utf8')).toBe( + 'verified payload', + ); + expect( + fetchMock.mock.calls + .filter(([url]) => String(url).includes('/download/')) + .map(([url]) => String(url)), + ).toEqual([ + `https://github.com/SnowLuma/SnowLuma/releases/download/v2.0.0/${name}`, + `https://working.example/https://github.com/SnowLuma/SnowLuma/releases/download/v2.0.0/${name}`, + ]); + }, + ); + + it('does not try other download sources in pinned mode', async () => { + const bytes = new Uint8Array([1, 2, 3]); + const fetchMock = mockRelease(bytes, 'win32-x64'); + const original = fetchMock.getMockImplementation()!; + fetchMock.mockImplementation(async (input) => + String(input).includes('api.github.com') + ? original(input) + : new Response('blocked', { status: 403 }), + ); + await expect( + download(root, '2.0.0', 'win32-x64', { + mode: 'mirror', + mirror: 'https://pinned.example', + mirrors: ['https://other.example'], + }), + ).rejects.toThrow('HTTP 403'); + expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([ + 'https://api.github.com/repos/SnowLuma/SnowLuma/releases/tags/v2.0.0', + `https://pinned.example/https://github.com/SnowLuma/SnowLuma/releases/download/v2.0.0/${assetName('2.0.0', 'win32-x64')}`, + ]); + expect(await readdir(root)).toEqual([]); + }); it.each(['win32-x64', 'linux-x64', 'linux-arm64'])( 'downloads and validates the %s lite package', async (target) => { diff --git a/packages/core/tests/update-release.test.ts b/packages/core/tests/update-release.test.ts new file mode 100644 index 00000000..4d926b2f --- /dev/null +++ b/packages/core/tests/update-release.test.ts @@ -0,0 +1,126 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import type { UpdateSourceConfig } from '@snowluma/common/update-source'; +import { + assetName, + fetchRelease, + parseLatestReleasePage, + parseReleaseAssetsPage, +} from '../src/update/release'; + +const direct: UpdateSourceConfig = { mode: 'direct', mirror: '', mirrors: [] }; +const latest = + ''; +const digest = `sha256:${'a'.repeat(64)}`; +const name = assetName('2.0.1', 'win32-x64'); +const row = `
  • ${name}
  • `; + +afterEach(() => vi.unstubAllGlobals()); + +describe('existing GitHub release pages', () => { + it('reads the canonical stable release without a new metadata asset', () => { + expect(parseLatestReleasePage(latest)).toEqual({ + tag_name: 'v2.0.1', + html_url: 'https://github.com/SnowLuma/SnowLuma/releases/tag/v2.0.1', + }); + expect(parseLatestReleasePage(latest.replace('https://github.com', '')).tag_name).toBe( + 'v2.0.1', + ); + }); + + it.each([ + 'please sign in', + latest.replace('github.com', 'unrelated.example'), + latest.replace('/SnowLuma/SnowLuma/', '/other/project/'), + latest.replace('v2.0.1', 'v02.0.1'), + latest.replace('v2.0.1', 'v2.0.1-rc.1'), + ])('rejects non-release or invalid version pages', (html) => { + expect(() => parseLatestReleasePage(html)).toThrow(); + }); + + it('matches an asset with its own digest, ignoring rounded HTML sizes', () => { + expect(parseReleaseAssetsPage(row, '2.0.1')).toEqual({ + tag_name: 'v2.0.1', + assets: [{ name, size: null, digest }], + }); + }); + + it.each([ + row.replace('v2.0.1/', 'v2.0.0/'), + row.replace(digest, 'unavailable'), + row + row, + row.replace(``, '') + + `
  • `, + ])('rejects absent, ambiguous or neighbouring checksum data', (html) => { + expect(() => parseReleaseAssetsPage(html, '2.0.1')).toThrow(); + }); + + it('falls back from API 403 to the existing release page', async () => { + const fetchMock = vi.fn(async (url) => + String(url).includes('api.github.com') + ? new Response('rate limited', { status: 403 }) + : new Response(latest), + ); + vi.stubGlobal('fetch', fetchMock); + expect(await fetchRelease(undefined, direct)).toMatchObject({ + fromPage: true, + data: { tag_name: 'v2.0.1' }, + }); + expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([ + 'https://api.github.com/repos/SnowLuma/SnowLuma/releases/latest', + 'https://github.com/SnowLuma/SnowLuma/releases/latest', + ]); + }); + + it('waits for a valid mirror page after fast invalid responses and cancels other requests', async () => { + let finish!: (response: Response) => void; + const pending = new Promise((resolve) => { + finish = resolve; + }); + const fetchMock = vi.fn(async (url) => { + if (String(url).startsWith('https://working.example/')) { + return pending; + } + + return new Response('HTML challenge'); + }); + vi.stubGlobal('fetch', fetchMock); + const result = fetchRelease('2.0.1', { + ...direct, + mode: 'auto', + mirrors: ['https://bad.example', 'https://working.example'], + }); + await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(4)); + finish(new Response(row)); + expect(await result).toMatchObject({ + fromPage: true, + data: { assets: [{ name, digest }] }, + }); + expect(fetchMock.mock.calls.slice(1).every(([, options]) => options?.signal?.aborted)).toBe( + true, + ); + }); + + it('keeps direct release lookup when the pinned download mirror cannot serve pages', async () => { + const fetchMock = vi.fn(async (url) => + String(url) === 'https://github.com/SnowLuma/SnowLuma/releases/latest' + ? new Response(latest) + : new Response('blocked', { status: 403 }), + ); + vi.stubGlobal('fetch', fetchMock); + expect( + await fetchRelease(undefined, { + ...direct, + mode: 'mirror', + mirror: 'https://files.example', + }), + ).toMatchObject({ data: { tag_name: 'v2.0.1' } }); + }); + + it('rejects oversized release responses', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response('x'.repeat(1024 * 1024 + 1))), + ); + await expect(fetchRelease(undefined, direct)).rejects.toThrow('发布信息过大'); + }); +}); diff --git a/packages/core/tests/update-source-routes.test.ts b/packages/core/tests/update-source-routes.test.ts new file mode 100644 index 00000000..bc727297 --- /dev/null +++ b/packages/core/tests/update-source-routes.test.ts @@ -0,0 +1,105 @@ +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { readRuntimeConfig, updateRuntimeConfig } from '@snowluma/common/runtime'; +import { createUpdateService } from '../src/update/service'; +import { updateRoutes } from '../src/webui/update-routes'; + +let directory: string; +let previous: string; +beforeEach(() => { + directory = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-update-sources-')); + previous = process.cwd(); + process.chdir(directory); +}); +afterEach(() => { + process.chdir(previous); + vi.restoreAllMocks(); + vi.unstubAllGlobals(); + fs.rmSync(directory, { recursive: true, force: true }); +}); + +async function routes() { + return updateRoutes(await createUpdateService(undefined, '2.0.1'), vi.fn()); +} + +describe('update source routes', () => { + it('returns a JSON error when persisted source settings are invalid', async () => { + fs.mkdirSync('config'); + fs.writeFileSync( + 'config/runtime.json', + JSON.stringify({ updateSource: { mode: 'invalid' } }), + ); + const response = await (await routes()).request('/sources'); + expect(response.status).toBe(500); + expect(response.headers.get('content-type')).toContain('application/json'); + expect(await response.json()).toMatchObject({ + message: expect.stringContaining('模式无效'), + }); + }); + it('persists settings for subsequent reads without changing other runtime values', async () => { + updateRuntimeConfig({ webuiPort: 6789, webuiHost: '127.0.0.2' }); + const app = await routes(); + const config = { + mode: 'mirror', + mirror: 'https://example.com/proxy/', + mirrors: ['https://second.example/'], + }; + const response = await app.request('/sources', { + method: 'POST', + body: JSON.stringify(config), + }); + expect(response.status).toBe(200); + const normalized = { + ...config, + mirror: 'https://example.com/proxy', + mirrors: ['https://second.example'], + }; + expect(await response.json()).toMatchObject({ + config: normalized, + saved: true, + applied: true, + errors: [], + }); + expect(readRuntimeConfig()).toMatchObject({ + updateSource: normalized, + webuiPort: 6789, + webuiHost: '127.0.0.2', + }); + expect(await (await app.request('/sources')).json()).toEqual({ config: normalized }); + }); + + it.each(['not json', '{}', '[]', '{"mode":"mirror","mirrors":[]}'])( + 'rejects malformed input without saving or fetching: %s', + async (body) => { + const fetchMock = vi.fn(); + vi.stubGlobal('fetch', fetchMock); + const app = await routes(); + + for (const endpoint of ['/sources', '/sources/test']) { + expect((await app.request(endpoint, { method: 'POST', body })).status).toBe(400); + } + + expect(fetchMock).not.toHaveBeenCalled(); + expect(fs.existsSync('config/runtime.json')).toBe(false); + }, + ); + + it('reports a persistence failure without claiming the config was saved', async () => { + updateRuntimeConfig({ webuiPort: 6789 }); + const before = fs.readFileSync('config/runtime.json', 'utf8'); + vi.spyOn(fs, 'renameSync').mockImplementationOnce(() => { + throw new Error('disk replacement failed'); + }); + const response = await ( + await routes() + ).request('/sources', { + method: 'POST', + body: JSON.stringify({ mode: 'direct', mirror: '', mirrors: [] }), + }); + expect(response.status).toBe(500); + expect(await response.json()).toEqual({ message: 'disk replacement failed' }); + expect(fs.readFileSync('config/runtime.json', 'utf8')).toBe(before); + }); +}); diff --git a/packages/core/tests/update-sources.test.ts b/packages/core/tests/update-sources.test.ts new file mode 100644 index 00000000..e5629bd9 --- /dev/null +++ b/packages/core/tests/update-sources.test.ts @@ -0,0 +1,81 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { DEFAULT_UPDATE_SOURCE, sourceUrls, testUpdateSources } from '../src/update/sources'; +import type { UpdateSourceConfig } from '@snowluma/common/update-source'; + +const config: UpdateSourceConfig = { + mode: 'auto', + mirror: '', + mirrors: [ + 'https://good.example', + 'https://html.example', + 'https://fake.example', + 'https://failed.example', + ], +}; +afterEach(() => vi.unstubAllGlobals()); + +describe('update mirror selection', () => { + it('uses direct, ordered fallback or only the pinned mirror for downloads', () => { + const url = 'https://github.com/project/asset'; + expect(sourceUrls(url, config)).toEqual([ + url, + ...config.mirrors.map((mirror) => `${mirror}/${url}`), + ]); + expect(sourceUrls(url, { ...config, mode: 'direct' })).toEqual([url]); + expect( + sourceUrls(url, { ...config, mode: 'mirror', mirror: 'https://pinned.example/proxy' }), + ).toEqual([`https://pinned.example/proxy/${url}`]); + expect(DEFAULT_UPDATE_SOURCE.mirrors.length).toBeGreaterThanOrEqual(7); + }); + + it('probes actual archive prefixes, rejects HTML even with a binary content type, and cancels bodies', async () => { + const cancelled = vi.fn(); + const signature = + process.platform === 'win32' ? [0x50, 0x4b, 0x03, 0x04] : [0x1f, 0x8b, 0x08, 0]; + const fetchMock = vi.fn(async (url) => { + if (String(url).startsWith('https://html.example')) { + return new Response('blocked', { + headers: { 'Content-Type': 'text/html' }, + }); + } + + if (String(url).startsWith('https://fake.example')) { + return new Response('blocked', { + headers: { 'Content-Type': 'application/octet-stream' }, + }); + } + + if (String(url).startsWith('https://failed.example')) { + return new Response('blocked', { status: 403 }); + } + + return new Response( + new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array(signature)); + }, + cancel: cancelled, + }), + ); + }); + vi.stubGlobal('fetch', fetchMock); + const results = await testUpdateSources(config); + expect( + results + .filter((result) => result.available) + .map((result) => result.mirror) + .sort(), + ).toEqual(['', 'https://good.example']); + expect(results.filter((result) => !result.available)).toHaveLength(3); + expect(results.at(-1)?.available).toBe(false); + expect(cancelled).toHaveBeenCalledTimes(2); + expect( + fetchMock.mock.calls.every( + ([, options]) => + options?.headers && + 'Range' in options.headers && + options.headers.Range === 'bytes=0-3', + ), + ).toBe(true); + }); +}); diff --git a/packages/core/tests/webui-update-check.test.ts b/packages/core/tests/webui-update-check.test.ts index e6ae1c98..5785a1ef 100644 --- a/packages/core/tests/webui-update-check.test.ts +++ b/packages/core/tests/webui-update-check.test.ts @@ -1,5 +1,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { getUpdateInfo } from '../src/update/check'; +import { getUpdateInfo as checkUpdate } from '../src/update/check'; + +const getUpdateInfo = (force = false) => + checkUpdate(force, { mode: 'direct', mirror: '', mirrors: [] }); const LATEST_RELEASE_URL = 'https://api.github.com/repos/SnowLuma/SnowLuma/releases/latest'; const NOTES_MAX = 4_000; @@ -85,7 +88,7 @@ describe('getUpdateInfo', () => { htmlUrl: null, notes: null, publishedAt: null, - error: 'ECONNRESET', + error: expect.stringContaining('ECONNRESET'), }); fetchMock.mockImplementation(async () => jsonResponse({ tag_name: 'v1.0.0' })); @@ -93,7 +96,7 @@ describe('getUpdateInfo', () => { expect(ok.latest).toBe('1.0.0'); expect(ok.hasUpdate).toBe(true); expect(ok.error).toBeUndefined(); - expect(fetchMock).toHaveBeenCalledTimes(2); + expect(fetchMock).toHaveBeenCalledTimes(3); }); it.each(['', '1', 'true', 'yes', 'on', ' '] as const)( @@ -190,7 +193,7 @@ describe('getUpdateInfo', () => { htmlUrl: null, notes: null, publishedAt: null, - error: 'github 403', + error: expect.stringContaining('GitHub 403'), }); }); @@ -230,7 +233,7 @@ describe('getUpdateInfo', () => { throw new Error('getaddrinfo ENOTFOUND'); }); const result = await getUpdateInfo(true); - expect(result.error).toBe('getaddrinfo ENOTFOUND'); + expect(result.error).toContain('getaddrinfo ENOTFOUND'); expect(result.hasUpdate).toBe(false); }); @@ -239,7 +242,7 @@ describe('getUpdateInfo', () => { throw 'timeout'; }); const result = await getUpdateInfo(true); - expect(result.error).toBe('network error'); + expect(result.error).toContain('timeout'); expect(result.hasUpdate).toBe(false); }); @@ -257,7 +260,7 @@ describe('getUpdateInfo', () => { throw new Error('boom'); }); await expect(getUpdateInfo(true)).resolves.toMatchObject({ - error: 'boom', + error: expect.stringContaining('boom'), hasUpdate: false, }); }); @@ -298,12 +301,12 @@ describe('getUpdateInfo', () => { throw new Error('boom'); }); const bad = await getUpdateInfo(true); - expect(bad.error).toBe('boom'); + expect(bad.error).toContain('boom'); const cached = await getUpdateInfo(); expect(cached).toBe(good); expect(cached.error).toBeUndefined(); - expect(fetchMock).toHaveBeenCalledTimes(2); + expect(fetchMock).toHaveBeenCalledTimes(3); }); it('collapses concurrent checks onto one fetch', async () => { @@ -332,4 +335,15 @@ describe('getUpdateInfo', () => { }); expect(fetchMock).toHaveBeenCalledTimes(1); }); + + it('does not reuse the previous source configuration cache after a mirror change', async () => { + const source = { mode: 'auto', mirror: '', mirrors: ['https://first.example'] } as const; + const fetchMock = mockFetch(async () => jsonResponse({ tag_name: 'v3.0.0' })); + const first = await checkUpdate(false, { ...source, mirrors: [...source.mirrors] }); + fetchMock.mockImplementation(async () => jsonResponse({ tag_name: 'v3.0.1' })); + const second = await checkUpdate(false, { ...source, mirrors: ['https://second.example'] }); + expect(first.latest).toBe('3.0.0'); + expect(second.latest).toBe('3.0.1'); + expect(fetchMock).toHaveBeenCalledTimes(2); + }); }); diff --git a/packages/webui/src/components/pages/settings-page.tsx b/packages/webui/src/components/pages/settings-page.tsx index a6728559..b643403a 100644 --- a/packages/webui/src/components/pages/settings-page.tsx +++ b/packages/webui/src/components/pages/settings-page.tsx @@ -95,6 +95,7 @@ import { NotificationsPanel } from '@/components/settings/notifications-panel'; import { GlobalConfigPanel } from '@/components/settings/global-config-panel'; import { SystemPanel } from '@/components/settings/system-panel'; import { UpdateInstaller } from '@/components/settings/update-installer'; +import { UpdateSources } from '@/components/settings/update-sources'; import { StoragePanel } from '@/components/settings/storage-panel'; import { DeveloperCrashProbe, developerCrashReducer } from '@/components/settings/developer-tools'; @@ -2000,6 +2001,12 @@ function UpdateGroup() { {detail} + {updateInfo?.error && !disabledCheck && ( +

    + {updateInfo.error} +

    + )} + ); diff --git a/packages/webui/src/components/settings/update-sources.tsx b/packages/webui/src/components/settings/update-sources.tsx new file mode 100644 index 00000000..f16793dc --- /dev/null +++ b/packages/webui/src/components/settings/update-sources.tsx @@ -0,0 +1,267 @@ +import { useEffect, useId, useState } from 'react'; +import { normalizeUpdateSourceConfig } from '@snowluma/common/update-source'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Textarea } from '@/components/ui/textarea'; +import { DropdownSelect } from '@/components/ui/dropdown-select'; +import { SkeletonSwap } from '@/components/interior/skeleton-swap'; +import { useActionFeedback } from '@/contexts/ActionFeedbackContext'; +import { useApi } from '@/lib/api'; +import type { UpdateSourceConfig, UpdateSourceProbe } from '@/types'; + +export function UpdateSources() { + const api = useApi(); + const { runAction } = useActionFeedback(); + const id = useId(); + const [config, setConfig] = useState(null); + const [mirrors, setMirrors] = useState(''); + const [results, setResults] = useState([]); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(false); + const [ready, setReady] = useState(false); + const [reload, setReload] = useState(0); + + useEffect(() => { + let disposed = false; + setReady(false); + void api.update + .sources() + .then(({ config: next }) => { + if (!disposed) { + setConfig(next); + setMirrors(next.mirrors.join('\n')); + setError(null); + } + }) + .catch((caught: unknown) => { + if (!disposed) { + setError(caught instanceof Error ? caught.message : String(caught)); + } + }) + .finally(() => { + if (!disposed) { + setReady(true); + } + }); + + return () => { + disposed = true; + }; + }, [api, reload]); + + const act = async (testing: boolean) => { + setBusy(true); + setError(null); + + try { + await runAction( + { + title: testing ? '正在检测更新来源' : '正在保存更新来源', + successTitle: testing ? '来源检测完成' : '更新来源已保存', + successDetail: testing + ? '检测从 SnowLuma 所在服务器发起' + : '下次检查和下载时生效', + errorTitle: testing ? '来源检测失败' : '保存失败', + }, + async () => { + const next = normalizeUpdateSourceConfig({ + ...config, + mirrors: mirrors + .split(/\r?\n/) + .map((line) => line.trim()) + .filter(Boolean), + }); + + if (testing) { + setResults((await api.update.testSources(next)).results); + } else { + const saved = await api.update.saveSources(next); + + if (!saved.saved || !saved.applied) { + throw new Error(saved.errors.join(';') || saved.message); + } + + setConfig(saved.config); + setMirrors(saved.config.mirrors.join('\n')); + setResults([]); + } + }, + ); + } catch (caught) { + setError(caught instanceof Error ? caught.message : String(caught)); + } finally { + setBusy(false); + } + }; + + return ( +
    +

    更新来源

    + {error && ( +

    + {error} +

    + )} + + {config ? ( +
    + { + setConfig({ ...config, mode }); + setResults([]); + }} + /> +

    + 自动模式先尝试 + GitHub,失败后按列表顺序切换。镜像用于文件下载,版本查询也会尝试 GitHub + 发布页面。 +

    + {config.mode === 'mirror' && ( +
    + + { + setConfig({ ...config, mirror: event.target.value }); + setResults([]); + }} + /> +
    + )} +
    + + 编辑候选镜像(每行一个地址) + +