fix(update): recover from GitHub rate limits with configurable mirrors
This commit is contained in:
1 parent
68deb48811
commit
20cf7394e5
21 files changed
+1423
-93
No files matched your search
@@ -8,6 +8,10 @@
|
|||||||
"main": "./src/index.ts",
|
"main": "./src/index.ts",
|
||||||
"types": "./src/index.ts",
|
"types": "./src/index.ts",
|
||||||
"exports": {
|
"exports": {
|
||||||
|
"./update-source": {
|
||||||
|
"types": "./src/update-source.ts",
|
||||||
|
"default": "./src/update-source.ts"
|
||||||
|
},
|
||||||
"./semver": {
|
"./semver": {
|
||||||
"types": "./src/semver.ts",
|
"types": "./src/semver.ts",
|
||||||
"default": "./src/semver.ts"
|
"default": "./src/semver.ts"
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
import { isObject } from './coerce';
|
import { isObject } from './coerce';
|
||||||
|
import { normalizeUpdateSourceConfig, type UpdateSourceConfig } from './update-source';
|
||||||
|
|
||||||
export interface RuntimeConfig {
|
export interface RuntimeConfig {
|
||||||
|
updateSource?: UpdateSourceConfig;
|
||||||
webuiPort?: number;
|
webuiPort?: number;
|
||||||
/** When true, every newly-discovered QQ process gets auto-injected by
|
/** When true, every newly-discovered QQ process gets auto-injected by
|
||||||
* the HookManager. Also overridable at runtime via SNOWLUMA_HOOK_AUTOLOAD.
|
* 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 {
|
export function normalizeRuntimeConfig(parsed: unknown): RuntimeConfig {
|
||||||
const obj = isObject(parsed) ? parsed : {};
|
const obj = isObject(parsed) ? parsed : {};
|
||||||
return {
|
return {
|
||||||
|
...(obj.updateSource === undefined
|
||||||
|
? {}
|
||||||
|
: { updateSource: normalizeUpdateSourceConfig(obj.updateSource) }),
|
||||||
webuiPort: normalizePort(obj.webuiPort ?? DEFAULT_WEBUI_PORT, DEFAULT_WEBUI_PORT),
|
webuiPort: normalizePort(obj.webuiPort ?? DEFAULT_WEBUI_PORT, DEFAULT_WEBUI_PORT),
|
||||||
hookAutoLoad: normalizeBool(obj.hookAutoLoad, false),
|
hookAutoLoad: normalizeBool(obj.hookAutoLoad, false),
|
||||||
webuiHost: normalizeHost(obj.webuiHost),
|
webuiHost: normalizeHost(obj.webuiHost),
|
||||||
@@ -217,7 +222,8 @@ function sameRuntimeConfig(parsed: Record<string, unknown>, n: RuntimeConfig): b
|
|||||||
parsed.trustProxy === n.trustProxy &&
|
parsed.trustProxy === n.trustProxy &&
|
||||||
parsed.logMaxTotalMb === n.logMaxTotalMb &&
|
parsed.logMaxTotalMb === n.logMaxTotalMb &&
|
||||||
parsed.logRetainDays === n.logRetainDays &&
|
parsed.logRetainDays === n.logRetainDays &&
|
||||||
parsed.logPerUin === n.logPerUin
|
parsed.logPerUin === n.logPerUin &&
|
||||||
|
JSON.stringify(parsed.updateSource) === JSON.stringify(n.updateSource)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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))],
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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:[email protected]',
|
||||||
|
'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');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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 并验证完整摘要。下载中断或校验失败后,自动模式会清理该次下载的临时文件,再尝试下一个来源。解包仍检查目录边界、版本和目标平台。
|
||||||
|
|
||||||
|
更新先暂存,下次重启时替换运行文件,配置、日志和消息数据保留。源码运行和容器部署不启用文件替换;容器应更新镜像。
|
||||||
@@ -2,10 +2,12 @@ import { APP_VERSION } from '@snowluma/common/version';
|
|||||||
import { compareVersions, parseVersion } from '@snowluma/common/semver';
|
import { compareVersions, parseVersion } from '@snowluma/common/semver';
|
||||||
import { createLogger } from '@snowluma/common/logger';
|
import { createLogger } from '@snowluma/common/logger';
|
||||||
import { createSingleFlightCache } from '@snowluma/common/single-flight-cache';
|
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 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 CACHE_TTL_MS = 6 * 60 * 60 * 1000; // 6h — comfortably under the rate limit
|
||||||
const FETCH_TIMEOUT_MS = 8_000;
|
const FETCH_TIMEOUT_MS = 8_000;
|
||||||
const NOTES_MAX = 4_000; // cap the release-body we hand back to the client
|
const NOTES_MAX = 4_000; // cap the release-body we hand back to the client
|
||||||
@@ -29,13 +31,6 @@ export interface UpdateCheckResult {
|
|||||||
error?: string;
|
error?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface GithubRelease {
|
|
||||||
tag_name?: string;
|
|
||||||
html_url?: string;
|
|
||||||
body?: string;
|
|
||||||
published_at?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
function isEnabled(): boolean {
|
function isEnabled(): boolean {
|
||||||
const v = (process.env.SNOWLUMA_UPDATE_CHECK ?? '').trim().toLowerCase();
|
const v = (process.env.SNOWLUMA_UPDATE_CHECK ?? '').trim().toLowerCase();
|
||||||
return v !== '0' && v !== 'false' && v !== 'off' && v !== 'no';
|
return v !== '0' && v !== 'false' && v !== 'off' && v !== 'no';
|
||||||
@@ -47,8 +42,10 @@ function isEnabled(): boolean {
|
|||||||
const updateCache = createSingleFlightCache<string, UpdateCheckResult>({
|
const updateCache = createSingleFlightCache<string, UpdateCheckResult>({
|
||||||
ttlMs: CACHE_TTL_MS,
|
ttlMs: CACHE_TTL_MS,
|
||||||
shouldCache: (r) => !r.error,
|
shouldCache: (r) => !r.error,
|
||||||
load: async (current) => {
|
load: async (key) => {
|
||||||
const result = await fetchLatest(current);
|
// 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) {
|
if (result.error) {
|
||||||
log.debug('update check failed: %s', 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 = {
|
const base: UpdateCheckResult = {
|
||||||
current,
|
current,
|
||||||
latest: null,
|
latest: null,
|
||||||
@@ -74,21 +74,19 @@ async function fetchLatest(current: string): Promise<UpdateCheckResult> {
|
|||||||
try {
|
try {
|
||||||
// `/releases/latest` already excludes drafts and prereleases, so this is
|
// `/releases/latest` already excludes drafts and prereleases, so this is
|
||||||
// stable-channel by construction.
|
// stable-channel by construction.
|
||||||
const res = await fetch(LATEST_RELEASE_URL, {
|
const { data: rel } = await fetchRelease(
|
||||||
headers: {
|
undefined,
|
||||||
Accept: 'application/vnd.github+json',
|
source,
|
||||||
'User-Agent': `SnowLuma/${current}`,
|
`SnowLuma/${current}`,
|
||||||
'X-GitHub-Api-Version': '2022-11-28',
|
FETCH_TIMEOUT_MS,
|
||||||
},
|
);
|
||||||
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!res.ok) {
|
if (!rel || typeof rel !== 'object' || Array.isArray(rel)) {
|
||||||
return { ...base, error: `github ${res.status}` };
|
return { ...base, error: 'invalid release info' };
|
||||||
}
|
}
|
||||||
|
|
||||||
const rel = (await res.json()) as GithubRelease;
|
const tag =
|
||||||
const tag = typeof rel.tag_name === 'string' ? rel.tag_name.trim() : '';
|
'tag_name' in rel && typeof rel.tag_name === 'string' ? rel.tag_name.trim() : '';
|
||||||
|
|
||||||
if (!tag) {
|
if (!tag) {
|
||||||
return { ...base, error: 'no tag' };
|
return { ...base, error: 'no tag' };
|
||||||
@@ -104,9 +102,15 @@ async function fetchLatest(current: string): Promise<UpdateCheckResult> {
|
|||||||
current,
|
current,
|
||||||
latest,
|
latest,
|
||||||
hasUpdate: compareVersions(latest, current) > 0,
|
hasUpdate: compareVersions(latest, current) > 0,
|
||||||
htmlUrl: rel.html_url ?? null,
|
htmlUrl: 'html_url' in rel && typeof rel.html_url === 'string' ? rel.html_url : null,
|
||||||
notes: rel.body ? rel.body.slice(0, NOTES_MAX) : null,
|
notes:
|
||||||
publishedAt: rel.published_at ?? null,
|
'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(),
|
checkedAt: Date.now(),
|
||||||
};
|
};
|
||||||
} catch (e) {
|
} 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
|
* failures come back as a result with `error` set and `hasUpdate: false`, and
|
||||||
* are not cached so the next check retries.
|
* 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;
|
const current = APP_VERSION;
|
||||||
|
|
||||||
if (!isEnabled()) {
|
if (!isEnabled()) {
|
||||||
return { ...emptyResult(current), error: 'disabled' };
|
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 {
|
function emptyResult(current: string): UpdateCheckResult {
|
||||||
|
|||||||
@@ -1,43 +1,30 @@
|
|||||||
import { createHash } from 'node:crypto';
|
import { createHash } from 'node:crypto';
|
||||||
import { createWriteStream } from 'node:fs';
|
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 path from 'node:path';
|
||||||
import { Readable, Transform } from 'node:stream';
|
import { Readable, Transform } from 'node:stream';
|
||||||
import { pipeline } from 'node:stream/promises';
|
import { pipeline } from 'node:stream/promises';
|
||||||
import { unzipSync } from 'fflate';
|
import { unzipSync } from 'fflate';
|
||||||
import { x as extractTar } from 'tar';
|
import { x as extractTar } from 'tar';
|
||||||
import { isRuntimeEntry, readManifest } from './files';
|
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 {
|
interface ReleaseAsset {
|
||||||
url: string;
|
url: string;
|
||||||
size: number;
|
size: number | null;
|
||||||
digest: string;
|
digest: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function assetName(version: string, target: string): string {
|
async function releaseAsset(
|
||||||
const platform = target.replace('win32', 'win');
|
version: string,
|
||||||
return `SnowLuma-v${version}-${platform}-lite.${target.startsWith('win32') ? 'zip' : 'tar.gz'}`;
|
target: string,
|
||||||
}
|
source: UpdateSourceConfig,
|
||||||
|
): Promise<ReleaseAsset> {
|
||||||
async function releaseAsset(version: string, target: string): Promise<ReleaseAsset> {
|
|
||||||
const name = assetName(version, target);
|
const name = assetName(version, target);
|
||||||
const response = await fetch(
|
const { data: release, fromPage } = await fetchRelease(version, source);
|
||||||
`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();
|
|
||||||
|
|
||||||
if (
|
if (
|
||||||
!release ||
|
!release ||
|
||||||
@@ -58,9 +45,10 @@ async function releaseAsset(version: string, target: string): Promise<ReleaseAss
|
|||||||
!asset ||
|
!asset ||
|
||||||
typeof asset !== 'object' ||
|
typeof asset !== 'object' ||
|
||||||
!('size' in asset) ||
|
!('size' in asset) ||
|
||||||
typeof asset.size !== 'number' ||
|
!(
|
||||||
!Number.isSafeInteger(asset.size) ||
|
(fromPage && asset.size === null) ||
|
||||||
asset.size <= 0 ||
|
(typeof asset.size === 'number' && Number.isSafeInteger(asset.size) && asset.size > 0)
|
||||||
|
) ||
|
||||||
!('digest' in asset) ||
|
!('digest' in asset) ||
|
||||||
typeof asset.digest !== 'string' ||
|
typeof asset.digest !== 'string' ||
|
||||||
!/^sha256:[a-f0-9]{64}$/.test(asset.digest)
|
!/^sha256:[a-f0-9]{64}$/.test(asset.digest)
|
||||||
@@ -94,37 +82,98 @@ export async function downloadUpdate(
|
|||||||
directory: string,
|
directory: string,
|
||||||
version: string,
|
version: string,
|
||||||
target: string,
|
target: string,
|
||||||
|
source = readUpdateSource(),
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const asset = await releaseAsset(version, target);
|
const asset = await releaseAsset(version, target, source);
|
||||||
const response = await fetch(asset.url, { signal: AbortSignal.timeout(10 * 60_000) });
|
|
||||||
|
|
||||||
if (!response.ok || !response.body) {
|
|
||||||
throw new Error(`下载更新失败: HTTP ${response.status}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const archive = path.join(directory, 'archive');
|
const archive = path.join(directory, 'archive');
|
||||||
const hash = createHash('sha256');
|
const urls = sourceUrls(asset.url, source);
|
||||||
let received = 0;
|
const failures: string[] = [];
|
||||||
await pipeline(
|
|
||||||
Readable.fromWeb(response.body),
|
|
||||||
new Transform({
|
|
||||||
transform(chunk: Buffer, _encoding, callback) {
|
|
||||||
received += chunk.length;
|
|
||||||
|
|
||||||
if (received > asset.size) {
|
for (const [index, url] of urls.entries()) {
|
||||||
callback(new Error('更新包大小不匹配'));
|
let created = false;
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
hash.update(chunk);
|
try {
|
||||||
callback(null, chunk);
|
const headersTimeout = new AbortController();
|
||||||
},
|
const timer = setTimeout(() => headersTimeout.abort(), 8_000);
|
||||||
}),
|
let response: Response;
|
||||||
createWriteStream(archive, { flags: 'wx' }),
|
|
||||||
);
|
|
||||||
|
|
||||||
if (received !== asset.size || `sha256:${hash.digest('hex')}` !== asset.digest) {
|
try {
|
||||||
throw new Error('更新包校验失败');
|
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');
|
const payload = path.join(directory, 'payload');
|
||||||
|
|||||||
@@ -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('&', '&')
|
||||||
|
.replaceAll(''', "'")
|
||||||
|
.replaceAll('"', '"');
|
||||||
|
}
|
||||||
|
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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,
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,10 +1,52 @@
|
|||||||
import { Hono } from 'hono';
|
import { Hono } from 'hono';
|
||||||
import type { HttpBindings } from '@hono/node-server';
|
import type { HttpBindings } from '@hono/node-server';
|
||||||
import type { UpdateService } from '../update/service';
|
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) {
|
export function updateRoutes(service: UpdateService, restart: () => void) {
|
||||||
const app = new Hono<{ Bindings: HttpBindings }>();
|
const app = new Hono<{ Bindings: HttpBindings }>();
|
||||||
app.get('/status', (c) => c.json(service.status()));
|
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) => {
|
app.post('/download', async (c) => {
|
||||||
let body: unknown;
|
let body: unknown;
|
||||||
|
|
||||||
|
|||||||
@@ -5,10 +5,14 @@ import path from 'node:path';
|
|||||||
import { zipSync } from 'fflate';
|
import { zipSync } from 'fflate';
|
||||||
import { c as createTar } from 'tar';
|
import { c as createTar } from 'tar';
|
||||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
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 { readManifest } from '../src/update/files';
|
||||||
import { releaseFixture } from './helpers/update-fixture';
|
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;
|
let root: string;
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
root = await mkdtemp(path.join(os.tmpdir(), 'snowluma-download-test-'));
|
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', () => {
|
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<typeof fetch>(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(
|
||||||
|
`<li><a href="/SnowLuma/SnowLuma/releases/download/v2.0.0/${name}">asset</a><clipboard-copy value="sha256:${digest}"></clipboard-copy></li>`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
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('<html>challenge</html>', {
|
||||||
|
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'])(
|
it.each(['win32-x64', 'linux-x64', 'linux-arm64'])(
|
||||||
'downloads and validates the %s lite package',
|
'downloads and validates the %s lite package',
|
||||||
async (target) => {
|
async (target) => {
|
||||||
|
|||||||
@@ -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 =
|
||||||
|
'<meta property="og:url" content="https://github.com/SnowLuma/SnowLuma/releases/tag/v2.0.1">';
|
||||||
|
const digest = `sha256:${'a'.repeat(64)}`;
|
||||||
|
const name = assetName('2.0.1', 'win32-x64');
|
||||||
|
const row = `<li><a href="/SnowLuma/SnowLuma/releases/download/v2.0.1/${name}">${name}</a><clipboard-copy value="${digest}"></clipboard-copy></li>`;
|
||||||
|
|
||||||
|
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([
|
||||||
|
'<html>please sign in</html>',
|
||||||
|
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(`<clipboard-copy value="${digest}"></clipboard-copy>`, '') +
|
||||||
|
`<li><clipboard-copy value="${digest}"></clipboard-copy></li>`,
|
||||||
|
])('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<typeof fetch>(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<Response>((resolve) => {
|
||||||
|
finish = resolve;
|
||||||
|
});
|
||||||
|
const fetchMock = vi.fn<typeof fetch>(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<typeof fetch>(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('发布信息过大');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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<typeof fetch>(async (url) => {
|
||||||
|
if (String(url).startsWith('https://html.example')) {
|
||||||
|
return new Response('<html>blocked</html>', {
|
||||||
|
headers: { 'Content-Type': 'text/html' },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (String(url).startsWith('https://fake.example')) {
|
||||||
|
return new Response('<html>blocked</html>', {
|
||||||
|
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);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,5 +1,8 @@
|
|||||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
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 LATEST_RELEASE_URL = 'https://api.github.com/repos/SnowLuma/SnowLuma/releases/latest';
|
||||||
const NOTES_MAX = 4_000;
|
const NOTES_MAX = 4_000;
|
||||||
@@ -85,7 +88,7 @@ describe('getUpdateInfo', () => {
|
|||||||
htmlUrl: null,
|
htmlUrl: null,
|
||||||
notes: null,
|
notes: null,
|
||||||
publishedAt: null,
|
publishedAt: null,
|
||||||
error: 'ECONNRESET',
|
error: expect.stringContaining('ECONNRESET'),
|
||||||
});
|
});
|
||||||
|
|
||||||
fetchMock.mockImplementation(async () => jsonResponse({ tag_name: 'v1.0.0' }));
|
fetchMock.mockImplementation(async () => jsonResponse({ tag_name: 'v1.0.0' }));
|
||||||
@@ -93,7 +96,7 @@ describe('getUpdateInfo', () => {
|
|||||||
expect(ok.latest).toBe('1.0.0');
|
expect(ok.latest).toBe('1.0.0');
|
||||||
expect(ok.hasUpdate).toBe(true);
|
expect(ok.hasUpdate).toBe(true);
|
||||||
expect(ok.error).toBeUndefined();
|
expect(ok.error).toBeUndefined();
|
||||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
expect(fetchMock).toHaveBeenCalledTimes(3);
|
||||||
});
|
});
|
||||||
|
|
||||||
it.each(['', '1', 'true', 'yes', 'on', ' '] as const)(
|
it.each(['', '1', 'true', 'yes', 'on', ' '] as const)(
|
||||||
@@ -190,7 +193,7 @@ describe('getUpdateInfo', () => {
|
|||||||
htmlUrl: null,
|
htmlUrl: null,
|
||||||
notes: null,
|
notes: null,
|
||||||
publishedAt: null,
|
publishedAt: null,
|
||||||
error: 'github 403',
|
error: expect.stringContaining('GitHub 403'),
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -230,7 +233,7 @@ describe('getUpdateInfo', () => {
|
|||||||
throw new Error('getaddrinfo ENOTFOUND');
|
throw new Error('getaddrinfo ENOTFOUND');
|
||||||
});
|
});
|
||||||
const result = await getUpdateInfo(true);
|
const result = await getUpdateInfo(true);
|
||||||
expect(result.error).toBe('getaddrinfo ENOTFOUND');
|
expect(result.error).toContain('getaddrinfo ENOTFOUND');
|
||||||
expect(result.hasUpdate).toBe(false);
|
expect(result.hasUpdate).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -239,7 +242,7 @@ describe('getUpdateInfo', () => {
|
|||||||
throw 'timeout';
|
throw 'timeout';
|
||||||
});
|
});
|
||||||
const result = await getUpdateInfo(true);
|
const result = await getUpdateInfo(true);
|
||||||
expect(result.error).toBe('network error');
|
expect(result.error).toContain('timeout');
|
||||||
expect(result.hasUpdate).toBe(false);
|
expect(result.hasUpdate).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -257,7 +260,7 @@ describe('getUpdateInfo', () => {
|
|||||||
throw new Error('boom');
|
throw new Error('boom');
|
||||||
});
|
});
|
||||||
await expect(getUpdateInfo(true)).resolves.toMatchObject({
|
await expect(getUpdateInfo(true)).resolves.toMatchObject({
|
||||||
error: 'boom',
|
error: expect.stringContaining('boom'),
|
||||||
hasUpdate: false,
|
hasUpdate: false,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -298,12 +301,12 @@ describe('getUpdateInfo', () => {
|
|||||||
throw new Error('boom');
|
throw new Error('boom');
|
||||||
});
|
});
|
||||||
const bad = await getUpdateInfo(true);
|
const bad = await getUpdateInfo(true);
|
||||||
expect(bad.error).toBe('boom');
|
expect(bad.error).toContain('boom');
|
||||||
|
|
||||||
const cached = await getUpdateInfo();
|
const cached = await getUpdateInfo();
|
||||||
expect(cached).toBe(good);
|
expect(cached).toBe(good);
|
||||||
expect(cached.error).toBeUndefined();
|
expect(cached.error).toBeUndefined();
|
||||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
expect(fetchMock).toHaveBeenCalledTimes(3);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('collapses concurrent checks onto one fetch', async () => {
|
it('collapses concurrent checks onto one fetch', async () => {
|
||||||
@@ -332,4 +335,15 @@ describe('getUpdateInfo', () => {
|
|||||||
});
|
});
|
||||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
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);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -95,6 +95,7 @@ import { NotificationsPanel } from '@/components/settings/notifications-panel';
|
|||||||
import { GlobalConfigPanel } from '@/components/settings/global-config-panel';
|
import { GlobalConfigPanel } from '@/components/settings/global-config-panel';
|
||||||
import { SystemPanel } from '@/components/settings/system-panel';
|
import { SystemPanel } from '@/components/settings/system-panel';
|
||||||
import { UpdateInstaller } from '@/components/settings/update-installer';
|
import { UpdateInstaller } from '@/components/settings/update-installer';
|
||||||
|
import { UpdateSources } from '@/components/settings/update-sources';
|
||||||
import { StoragePanel } from '@/components/settings/storage-panel';
|
import { StoragePanel } from '@/components/settings/storage-panel';
|
||||||
import { DeveloperCrashProbe, developerCrashReducer } from '@/components/settings/developer-tools';
|
import { DeveloperCrashProbe, developerCrashReducer } from '@/components/settings/developer-tools';
|
||||||
|
|
||||||
@@ -2000,6 +2001,12 @@ function UpdateGroup() {
|
|||||||
</div>
|
</div>
|
||||||
</SettingRow>
|
</SettingRow>
|
||||||
{detail}
|
{detail}
|
||||||
|
{updateInfo?.error && !disabledCheck && (
|
||||||
|
<p role="alert" className="px-5 py-3 text-xs text-destructive">
|
||||||
|
{updateInfo.error}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<UpdateSources />
|
||||||
<UpdateInstaller version={updateInfo?.hasUpdate ? updateInfo.latest : null} />
|
<UpdateInstaller version={updateInfo?.hasUpdate ? updateInfo.latest : null} />
|
||||||
</Group>
|
</Group>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -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<UpdateSourceConfig | null>(null);
|
||||||
|
const [mirrors, setMirrors] = useState('');
|
||||||
|
const [results, setResults] = useState<UpdateSourceProbe[]>([]);
|
||||||
|
const [error, setError] = useState<string | null>(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 (
|
||||||
|
<div className="flex flex-col gap-3 px-5 py-4">
|
||||||
|
<p className="text-sm font-medium">更新来源</p>
|
||||||
|
{error && (
|
||||||
|
<p role="alert" className="break-words text-xs text-destructive">
|
||||||
|
{error}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<SkeletonSwap ready={ready} reserve={100} lines={3} label="更新来源">
|
||||||
|
{config ? (
|
||||||
|
<fieldset
|
||||||
|
disabled={busy}
|
||||||
|
className="flex min-w-0 flex-col gap-3 disabled:opacity-60"
|
||||||
|
>
|
||||||
|
<DropdownSelect
|
||||||
|
value={config.mode}
|
||||||
|
ariaLabel="下载来源模式"
|
||||||
|
options={[
|
||||||
|
{ value: 'auto', label: '自动切换' },
|
||||||
|
{ value: 'direct', label: 'GitHub 直连' },
|
||||||
|
{ value: 'mirror', label: '指定镜像' },
|
||||||
|
]}
|
||||||
|
onChange={(mode) => {
|
||||||
|
setConfig({ ...config, mode });
|
||||||
|
setResults([]);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
自动模式先尝试
|
||||||
|
GitHub,失败后按列表顺序切换。镜像用于文件下载,版本查询也会尝试 GitHub
|
||||||
|
发布页面。
|
||||||
|
</p>
|
||||||
|
{config.mode === 'mirror' && (
|
||||||
|
<div className="flex flex-col gap-1.5">
|
||||||
|
<label htmlFor={`${id}-mirror`} className="text-xs">
|
||||||
|
指定镜像地址
|
||||||
|
</label>
|
||||||
|
<Input
|
||||||
|
id={`${id}-mirror`}
|
||||||
|
value={config.mirror}
|
||||||
|
placeholder="https://ghfast.top"
|
||||||
|
onChange={(event) => {
|
||||||
|
setConfig({ ...config, mirror: event.target.value });
|
||||||
|
setResults([]);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<details>
|
||||||
|
<summary className="cursor-pointer text-xs">
|
||||||
|
编辑候选镜像(每行一个地址)
|
||||||
|
</summary>
|
||||||
|
<Textarea
|
||||||
|
aria-label="候选镜像地址"
|
||||||
|
className="mt-2 min-h-32 font-mono text-xs"
|
||||||
|
value={mirrors}
|
||||||
|
onChange={(event) => {
|
||||||
|
setMirrors(event.target.value);
|
||||||
|
setResults([]);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<p className="mt-1 text-xs text-muted-foreground">
|
||||||
|
地址后会追加完整 GitHub 链接;支持带路径的代理前缀。
|
||||||
|
</p>
|
||||||
|
</details>
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => {
|
||||||
|
void act(true);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
检测可用性
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
onClick={() => {
|
||||||
|
void act(false);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
保存来源
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
{results.length > 0 && (
|
||||||
|
<div className="flex flex-col gap-2">
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
按可用性和响应延迟排序;检测结果不代表下载速度。
|
||||||
|
</p>
|
||||||
|
<ul className="flex max-h-64 flex-col gap-2 overflow-auto">
|
||||||
|
{results.map((result) => (
|
||||||
|
<li
|
||||||
|
key={result.mirror}
|
||||||
|
className="flex items-center gap-2 text-xs"
|
||||||
|
>
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<p className="break-all">
|
||||||
|
{result.mirror || 'GitHub 直连'}
|
||||||
|
</p>
|
||||||
|
<p
|
||||||
|
className={
|
||||||
|
result.available
|
||||||
|
? 'text-success'
|
||||||
|
: 'text-destructive'
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{result.available
|
||||||
|
? `可用 · ${result.latencyMs} ms`
|
||||||
|
: result.error || '不可用'}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
{result.available && (
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => {
|
||||||
|
setConfig({
|
||||||
|
...config,
|
||||||
|
mode: result.mirror
|
||||||
|
? 'mirror'
|
||||||
|
: 'direct',
|
||||||
|
mirror: result.mirror,
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
选用
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
className="self-start"
|
||||||
|
onClick={() => {
|
||||||
|
setMirrors(
|
||||||
|
results
|
||||||
|
.filter(
|
||||||
|
(result) => result.available && result.mirror,
|
||||||
|
)
|
||||||
|
.map((result) => result.mirror)
|
||||||
|
.join('\n'),
|
||||||
|
);
|
||||||
|
setConfig({ ...config, mode: 'auto' });
|
||||||
|
setResults([]);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
仅保留可用镜像
|
||||||
|
</Button>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
选用或筛选后,点击「保存来源」生效。
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</fieldset>
|
||||||
|
) : (
|
||||||
|
ready && (
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => setReload((value) => value + 1)}
|
||||||
|
>
|
||||||
|
重试
|
||||||
|
</Button>
|
||||||
|
)
|
||||||
|
)}
|
||||||
|
</SkeletonSwap>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -24,6 +24,9 @@ import type {
|
|||||||
UiConfig,
|
UiConfig,
|
||||||
UpdateInfo,
|
UpdateInfo,
|
||||||
UpdateStatus,
|
UpdateStatus,
|
||||||
|
UpdateSourceConfig,
|
||||||
|
UpdateSourceProbe,
|
||||||
|
UpdateSourceSaveResult,
|
||||||
} from '@/types';
|
} from '@/types';
|
||||||
import type { PasswordRule } from '@/components/pages/change-password-form';
|
import type { PasswordRule } from '@/components/pages/change-password-form';
|
||||||
import { normalizeOneBotConfig } from '@/lib/onebot-config';
|
import { normalizeOneBotConfig } from '@/lib/onebot-config';
|
||||||
@@ -175,6 +178,11 @@ class HttpApiClient implements ApiClient {
|
|||||||
check: (force) =>
|
check: (force) =>
|
||||||
this.getJson<UpdateInfo>(`/api/update/check${force ? '?force=true' : ''}`),
|
this.getJson<UpdateInfo>(`/api/update/check${force ? '?force=true' : ''}`),
|
||||||
status: () => this.getJson<UpdateStatus>('/api/update/status'),
|
status: () => this.getJson<UpdateStatus>('/api/update/status'),
|
||||||
|
sources: () => this.getJson<{ config: UpdateSourceConfig }>('/api/update/sources'),
|
||||||
|
saveSources: (config) =>
|
||||||
|
this.postJson<UpdateSourceSaveResult>('/api/update/sources', config),
|
||||||
|
testSources: (config) =>
|
||||||
|
this.postJson<{ results: UpdateSourceProbe[] }>('/api/update/sources/test', config),
|
||||||
download: (version) => this.postJson<UpdateStatus>('/api/update/download', { version }),
|
download: (version) => this.postJson<UpdateStatus>('/api/update/download', { version }),
|
||||||
restart: () => this.postJson<UpdateStatus>('/api/update/restart'),
|
restart: () => this.postJson<UpdateStatus>('/api/update/restart'),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -28,6 +28,9 @@ import type {
|
|||||||
UiConfig,
|
UiConfig,
|
||||||
UpdateInfo,
|
UpdateInfo,
|
||||||
UpdateStatus,
|
UpdateStatus,
|
||||||
|
UpdateSourceConfig,
|
||||||
|
UpdateSourceProbe,
|
||||||
|
UpdateSourceSaveResult,
|
||||||
} from '@/types';
|
} from '@/types';
|
||||||
import type { PasswordRule } from '@/components/pages/change-password-form';
|
import type { PasswordRule } from '@/components/pages/change-password-form';
|
||||||
|
|
||||||
@@ -277,6 +280,9 @@ export interface ApiClient {
|
|||||||
/** Advisory check for a newer stable release. Read-only — never downloads. */
|
/** Advisory check for a newer stable release. Read-only — never downloads. */
|
||||||
check(force?: boolean): Promise<UpdateInfo>;
|
check(force?: boolean): Promise<UpdateInfo>;
|
||||||
status(): Promise<UpdateStatus>;
|
status(): Promise<UpdateStatus>;
|
||||||
|
sources(): Promise<{ config: UpdateSourceConfig }>;
|
||||||
|
saveSources(config: UpdateSourceConfig): Promise<UpdateSourceSaveResult>;
|
||||||
|
testSources(config: UpdateSourceConfig): Promise<{ results: UpdateSourceProbe[] }>;
|
||||||
download(version: string): Promise<UpdateStatus>;
|
download(version: string): Promise<UpdateStatus>;
|
||||||
restart(): Promise<UpdateStatus>;
|
restart(): Promise<UpdateStatus>;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,6 +1,24 @@
|
|||||||
export const APP_NAME = 'SnowLuma';
|
export const APP_NAME = 'SnowLuma';
|
||||||
// Injected at build time by Vite from the monorepo root package.json.
|
// Injected at build time by Vite from the monorepo root package.json.
|
||||||
export { APP_VERSION } from '@snowluma/common/version';
|
export { APP_VERSION } from '@snowluma/common/version';
|
||||||
|
import type { UpdateSourceConfig } from '@snowluma/common/update-source';
|
||||||
|
export type { UpdateSourceConfig } from '@snowluma/common/update-source';
|
||||||
|
|
||||||
|
export interface UpdateSourceProbe {
|
||||||
|
mirror: string;
|
||||||
|
available: boolean;
|
||||||
|
latencyMs: number;
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UpdateSourceSaveResult {
|
||||||
|
config: UpdateSourceConfig;
|
||||||
|
saved: boolean;
|
||||||
|
applied: boolean;
|
||||||
|
online: boolean;
|
||||||
|
errors: string[];
|
||||||
|
message: string;
|
||||||
|
}
|
||||||
|
|
||||||
export type UpdateStatus = { current: string } & (
|
export type UpdateStatus = { current: string } & (
|
||||||
| { phase: 'unavailable' | 'error'; message: string }
|
| { phase: 'unavailable' | 'error'; message: string }
|
||||||
|
|||||||
@@ -4,6 +4,30 @@ import { createApiClient } from '../src/lib/api/client';
|
|||||||
afterEach(() => vi.unstubAllGlobals());
|
afterEach(() => vi.unstubAllGlobals());
|
||||||
|
|
||||||
describe('update API', () => {
|
describe('update API', () => {
|
||||||
|
it('loads, tests and saves mirror selection through authenticated object endpoints', async () => {
|
||||||
|
const config = { mode: 'auto', mirror: '', mirrors: ['https://example.com'] } as const;
|
||||||
|
const payload = { ...config, mirrors: [...config.mirrors] };
|
||||||
|
const fetchMock = vi.fn<typeof fetch>(async () =>
|
||||||
|
Response.json({ config: payload, results: [] }),
|
||||||
|
);
|
||||||
|
vi.stubGlobal('fetch', fetchMock);
|
||||||
|
const api = createApiClient({ tokenStore: { load: () => 'token', save: () => undefined } });
|
||||||
|
await api.update.sources();
|
||||||
|
await api.update.testSources(payload);
|
||||||
|
await api.update.saveSources(payload);
|
||||||
|
expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([
|
||||||
|
'/api/update/sources',
|
||||||
|
'/api/update/sources/test',
|
||||||
|
'/api/update/sources',
|
||||||
|
]);
|
||||||
|
|
||||||
|
for (const [, options] of fetchMock.mock.calls) {
|
||||||
|
expect(new Headers(options?.headers).get('X-SnowLuma-Token')).toBe('token');
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(fetchMock.mock.calls[1]?.[1]?.body).toBe(JSON.stringify(payload));
|
||||||
|
expect(fetchMock.mock.calls[2]?.[1]?.method).toBe('POST');
|
||||||
|
});
|
||||||
it('sends authenticated download and restart requests', async () => {
|
it('sends authenticated download and restart requests', async () => {
|
||||||
const fetchMock = vi.fn<typeof fetch>(async () =>
|
const fetchMock = vi.fn<typeof fetch>(async () =>
|
||||||
Response.json({ current: '1.0.0', phase: 'ready', version: '2.0.0' }),
|
Response.json({ current: '1.0.0', phase: 'ready', version: '2.0.0' }),
|
||||||
|
|||||||
Reference in new issue
Block a user