fix(update): recover from GitHub rate limits with configurable mirrors

This commit is contained in:
手瓜一十雪 committed 2026-10-18 19:41:02 +08:00
1 parent 68deb48811
commit 20cf7394e5
21 files changed
+1423 -93

No files matched your search

+19
View File
@@ -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 并验证完整摘要。下载中断或校验失败后,自动模式会清理该次下载的临时文件,再尝试下一个来源。解包仍检查目录边界、版本和目标平台。
更新先暂存,下次重启时替换运行文件,配置、日志和消息数据保留。源码运行和容器部署不启用文件替换;容器应更新镜像。
+44 -28
View File
@@ -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<string, UpdateCheckResult>({
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<string, UpdateCheckResult>({
},
});
async function fetchLatest(current: string): Promise<UpdateCheckResult> {
async function fetchLatest(
current: string,
source: UpdateSourceConfig,
): Promise<UpdateCheckResult> {
const base: UpdateCheckResult = {
current,
latest: null,
@@ -74,21 +74,19 @@ async function fetchLatest(current: string): Promise<UpdateCheckResult> {
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<UpdateCheckResult> {
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<UpdateCheckResult> {
* 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<UpdateCheckResult> {
export async function getUpdateInfo(
force = false,
source?: UpdateSourceConfig,
): Promise<UpdateCheckResult> {
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 {
+103 -54
View File
@@ -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<ReleaseAsset> {
async function releaseAsset(
version: string,
target: string,
source: UpdateSourceConfig,
): Promise<ReleaseAsset> {
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<ReleaseAss
!asset ||
typeof asset !== 'object' ||
!('size' in asset) ||
typeof asset.size !== 'number' ||
!Number.isSafeInteger(asset.size) ||
asset.size <= 0 ||
!(
(fromPage && asset.size === null) ||
(typeof asset.size === 'number' && Number.isSafeInteger(asset.size) && asset.size > 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<void> {
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');
+196
View File
@@ -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<string> {
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('&amp;', '&')
.replaceAll('&#39;', "'")
.replaceAll('&quot;', '"');
}
export function parseLatestReleasePage(html: string) {
const meta = html
.match(/<meta\b[^>]*>/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(/<li\b[^>]*>[\s\S]*?<\/li>/gi) ?? []) {
const links = row.match(/<a\b[^>]*>/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(/<clipboard-copy\b[^>]*>/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<ReleaseResult> {
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();
}
}
+125
View File
@@ -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<MirrorProbeResult[]> {
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<MirrorProbeResult> => {
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,
);
}