328 lines
13 KiB
TypeScript
328 lines
13 KiB
TypeScript
import { chmod, mkdir, rename, writeFile } from "node:fs/promises";
|
|
import path from "node:path";
|
|
import { createPublicKey, randomUUID, verify as verifySignature } from "node:crypto";
|
|
import type Database from "better-sqlite3";
|
|
import { AppError } from "./errors.js";
|
|
import type { AppConfig } from "./config.js";
|
|
import {
|
|
detectPlatform,
|
|
fetchReleaseBytes,
|
|
fetchReleaseMetadata,
|
|
fetchReleaseText,
|
|
isNewerVersion,
|
|
parseSemver,
|
|
sanitizeAssetName,
|
|
selectReleaseAsset,
|
|
validateHttpsUrl,
|
|
type ReleaseAsset,
|
|
type ReleaseMetadata,
|
|
} from "./update.js";
|
|
import type { UpdateJobStatus } from "../shared/contracts.js";
|
|
|
|
export const UPDATE_CACHE_KEY = "update.release.v1";
|
|
export const ACTIVE_UPDATE_STATUSES: readonly UpdateJobStatus[] = [
|
|
"queued",
|
|
"downloading",
|
|
"verifying",
|
|
"staged",
|
|
"backing_up",
|
|
"applying",
|
|
];
|
|
|
|
export type CachedRelease = {
|
|
checkedAt: number;
|
|
metadataUrl: string;
|
|
version: string;
|
|
tagName?: string;
|
|
publishedAt?: string;
|
|
platform: string;
|
|
signatureVerified?: boolean;
|
|
asset?: {
|
|
name: string;
|
|
url: string;
|
|
size?: number;
|
|
sha256?: string;
|
|
};
|
|
};
|
|
|
|
export type UpdateCheckResult = {
|
|
configured: boolean;
|
|
currentVersion: string;
|
|
platform: ReturnType<typeof detectPlatform>;
|
|
checkedAt: number;
|
|
latest: {
|
|
version: string;
|
|
tagName?: string;
|
|
publishedAt?: string;
|
|
compatible: boolean;
|
|
integrityReady: boolean;
|
|
signatureReady: boolean;
|
|
isNewer: boolean;
|
|
assetName?: string;
|
|
assetSize?: number;
|
|
} | null;
|
|
};
|
|
|
|
export type UpdateRequest = {
|
|
jobId: string;
|
|
version: string;
|
|
metadataUrl: string;
|
|
assetUrl: string;
|
|
assetName: string;
|
|
expectedSha256: string;
|
|
requestedAt: number;
|
|
// These paths are derived from the server config and are included so the
|
|
// privileged runner does not need to infer a working directory from input.
|
|
currentLink: string;
|
|
releasesDir: string;
|
|
dataDir: string;
|
|
};
|
|
|
|
function setting(database: Database.Database, key: string): string | undefined {
|
|
return (database.prepare("SELECT value FROM system_settings WHERE key=?").get(key) as { value: string } | undefined)?.value;
|
|
}
|
|
|
|
function saveSetting(database: Database.Database, key: string, value: unknown): void {
|
|
database.prepare(`
|
|
INSERT INTO system_settings(key, value, updated_at) VALUES (?, ?, ?)
|
|
ON CONFLICT(key) DO UPDATE SET value=excluded.value, updated_at=excluded.updated_at
|
|
`).run(key, JSON.stringify(value), Date.now());
|
|
}
|
|
|
|
function sha256FromSums(text: string, assetName: string): string | undefined {
|
|
const wanted = sanitizeAssetName(assetName);
|
|
for (const line of text.split(/\r?\n/)) {
|
|
const match = /^\s*([a-f0-9]{64})\s+[* ]?(.+?)\s*$/.exec(line);
|
|
if (!match) continue;
|
|
const name = match[2]!.replaceAll("\\", "/").split("/").pop() ?? "";
|
|
if (name === wanted) return match[1]!.toLowerCase();
|
|
}
|
|
return undefined;
|
|
}
|
|
|
|
/** Verify an Ed25519 detached signature over the exact SHA256SUMS bytes.
|
|
* The signature sidecar is accepted as either base64 or a 64-byte hex value.
|
|
*/
|
|
export function verifyReleaseSignature(payload: string, encodedSignature: string | Uint8Array, publicKey: string): boolean {
|
|
try {
|
|
const signature = (() => {
|
|
if (encodedSignature instanceof Uint8Array) {
|
|
const bytes = Buffer.from(encodedSignature);
|
|
if (bytes.length === 64) return bytes;
|
|
encodedSignature = bytes.toString("utf8");
|
|
}
|
|
const compact = encodedSignature.trim().replace(/\s+/g, "");
|
|
return /^[a-f0-9]{128}$/i.test(compact)
|
|
? Buffer.from(compact, "hex")
|
|
: Buffer.from(compact, "base64");
|
|
})();
|
|
if (signature.length !== 64) return false;
|
|
return verifySignature(null, Buffer.from(payload, "utf8"), createPublicKey(publicKey), signature);
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
function signatureAssetFor(metadata: ReleaseMetadata, sums: ReleaseAsset): ReleaseAsset | undefined {
|
|
const sumsName = sums.name.toLowerCase();
|
|
return metadata.assets.find((candidate) => {
|
|
const name = candidate.name.toLowerCase();
|
|
return name === `${sumsName}.sig` || name === `${sumsName}.asc`;
|
|
});
|
|
}
|
|
|
|
export async function attachSidecarHash(
|
|
metadata: ReleaseMetadata,
|
|
asset: ReleaseAsset,
|
|
options: { allowedHosts: readonly string[]; baseUrl: string; maxBytes: number; publicKey?: string | undefined; requireSignature?: boolean | undefined },
|
|
): Promise<{ asset: ReleaseAsset; signatureVerified: boolean }> {
|
|
let signatureVerified = false;
|
|
if (asset.sha256 && (!options.publicKey || !options.requireSignature)) return { asset, signatureVerified };
|
|
const sums = metadata.assets.find((candidate) => /^(?:sha256sums?|checksums?)(?:\.txt)?$/i.test(path.basename(candidate.name)));
|
|
if (!sums) return { asset, signatureVerified };
|
|
try {
|
|
const content = await fetchReleaseText(sums.url, { allowedHosts: options.allowedHosts, baseUrl: options.baseUrl, maxBytes: Math.min(options.maxBytes, 2 * 1024 * 1024) });
|
|
const sha256 = sha256FromSums(content, asset.name);
|
|
if (options.publicKey) {
|
|
const signatureAsset = signatureAssetFor(metadata, sums);
|
|
if (signatureAsset) {
|
|
const signature = await fetchReleaseBytes(signatureAsset.url, { allowedHosts: options.allowedHosts, baseUrl: options.baseUrl, maxBytes: 64 * 1024 });
|
|
signatureVerified = verifyReleaseSignature(content, signature, options.publicKey);
|
|
}
|
|
}
|
|
return { asset: sha256 ? { ...asset, sha256 } : asset, signatureVerified };
|
|
} catch {
|
|
// A missing/unreadable sidecar makes the update unavailable; it must not
|
|
// turn into an unverified download.
|
|
return { asset, signatureVerified };
|
|
}
|
|
}
|
|
|
|
function policy(config: AppConfig) {
|
|
return {
|
|
allowedHosts: config.updateAllowedHosts,
|
|
baseUrl: config.updateMetadataUrl,
|
|
maxRedirects: 3,
|
|
} as const;
|
|
}
|
|
|
|
function safeMetadataUrl(config: AppConfig): string {
|
|
try {
|
|
return validateHttpsUrl(config.updateMetadataUrl, policy(config)).toString();
|
|
} catch {
|
|
throw new AppError(503, "UPDATE_NOT_CONFIGURED", "更新源地址配置无效");
|
|
}
|
|
}
|
|
|
|
export async function checkForUpdate(database: Database.Database, config: AppConfig): Promise<UpdateCheckResult> {
|
|
const platform = detectPlatform();
|
|
const checkedAt = Date.now();
|
|
if (config.updateStrategy === "disabled" || !config.updateMetadataUrl) {
|
|
return { configured: false, currentVersion: config.appVersion, platform, checkedAt, latest: null };
|
|
}
|
|
const metadataUrl = safeMetadataUrl(config);
|
|
let metadata: ReleaseMetadata;
|
|
try {
|
|
metadata = await fetchReleaseMetadata(metadataUrl, policy(config));
|
|
} catch {
|
|
throw new AppError(502, "UPDATE_CHECK_FAILED", "暂时无法获取最新版本,请稍后重试");
|
|
}
|
|
let asset = selectReleaseAsset(metadata, platform);
|
|
let signatureVerified = false;
|
|
if (asset) {
|
|
const integrity = await attachSidecarHash(metadata, asset, {
|
|
allowedHosts: config.updateAllowedHosts,
|
|
baseUrl: metadataUrl,
|
|
maxBytes: config.updateMaxBytes,
|
|
publicKey: config.updatePublicKey,
|
|
requireSignature: config.updateRequireSignature,
|
|
});
|
|
asset = integrity.asset;
|
|
signatureVerified = integrity.signatureVerified;
|
|
}
|
|
const safeVersion = metadata.version;
|
|
const cached: CachedRelease = {
|
|
checkedAt,
|
|
metadataUrl,
|
|
version: safeVersion,
|
|
...(metadata.tagName ? { tagName: metadata.tagName } : {}),
|
|
...(metadata.publishedAt ? { publishedAt: metadata.publishedAt } : {}),
|
|
platform: platform.target,
|
|
signatureVerified,
|
|
...(asset ? {
|
|
asset: {
|
|
name: sanitizeAssetName(asset.name),
|
|
url: validateHttpsUrl(asset.url, policy(config)).toString(),
|
|
...(asset.size === undefined ? {} : { size: asset.size }),
|
|
...(asset.sha256 ? { sha256: asset.sha256 } : {}),
|
|
},
|
|
} : {}),
|
|
};
|
|
saveSetting(database, UPDATE_CACHE_KEY, cached);
|
|
return {
|
|
configured: true,
|
|
currentVersion: config.appVersion,
|
|
platform,
|
|
checkedAt,
|
|
latest: {
|
|
version: safeVersion,
|
|
...(metadata.tagName ? { tagName: metadata.tagName } : {}),
|
|
...(metadata.publishedAt ? { publishedAt: metadata.publishedAt } : {}),
|
|
compatible: Boolean(asset),
|
|
integrityReady: Boolean(asset?.sha256 && (!config.updateRequireSignature || signatureVerified)),
|
|
signatureReady: !config.updateRequireSignature || signatureVerified,
|
|
isNewer: isNewerVersion(config.appVersion, safeVersion),
|
|
...(asset ? { assetName: asset.name, ...(asset.size === undefined ? {} : { assetSize: asset.size }) } : {}),
|
|
},
|
|
};
|
|
}
|
|
|
|
export function readCachedRelease(database: Database.Database, config: AppConfig): CachedRelease | null {
|
|
const raw = setting(database, UPDATE_CACHE_KEY);
|
|
if (!raw) return null;
|
|
try {
|
|
const value = JSON.parse(raw) as CachedRelease;
|
|
if (!value || typeof value !== "object" || typeof value.version !== "string" || typeof value.metadataUrl !== "string" || typeof value.platform !== "string") return null;
|
|
parseSemver(value.version);
|
|
const metadataUrl = validateHttpsUrl(value.metadataUrl, policy(config)).toString();
|
|
if (value.signatureVerified !== undefined && typeof value.signatureVerified !== "boolean") return null;
|
|
if (value.asset) {
|
|
if (typeof value.asset.name !== "string" || typeof value.asset.url !== "string") return null;
|
|
sanitizeAssetName(value.asset.name);
|
|
validateHttpsUrl(value.asset.url, policy(config));
|
|
if (value.asset.sha256 !== undefined && !/^[a-f0-9]{64}$/i.test(value.asset.sha256)) return null;
|
|
}
|
|
return { ...value, metadataUrl };
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export function publicCheckFromCache(database: Database.Database, config: AppConfig): UpdateCheckResult {
|
|
const platform = detectPlatform();
|
|
const cached = readCachedRelease(database, config);
|
|
if (!cached || cached.platform !== platform.target) {
|
|
const compatible = Boolean(cached && cached.platform === platform.target && cached.asset);
|
|
return { configured: config.updateStrategy !== "disabled", currentVersion: config.appVersion, platform, checkedAt: cached?.checkedAt ?? 0, latest: cached ? {
|
|
version: cached.version,
|
|
...(cached.tagName ? { tagName: cached.tagName } : {}),
|
|
...(cached.publishedAt ? { publishedAt: cached.publishedAt } : {}),
|
|
compatible,
|
|
integrityReady: compatible && Boolean(cached.asset?.sha256) && (!config.updateRequireSignature || cached.signatureVerified === true),
|
|
signatureReady: !config.updateRequireSignature || cached.signatureVerified === true,
|
|
isNewer: isNewerVersion(config.appVersion, cached.version),
|
|
...(cached.asset ? { assetName: cached.asset.name, ...(cached.asset.size === undefined ? {} : { assetSize: cached.asset.size }) } : {}),
|
|
} : null };
|
|
}
|
|
return {
|
|
configured: config.updateStrategy !== "disabled",
|
|
currentVersion: config.appVersion,
|
|
platform,
|
|
checkedAt: cached.checkedAt,
|
|
latest: {
|
|
version: cached.version,
|
|
...(cached.tagName ? { tagName: cached.tagName } : {}),
|
|
...(cached.publishedAt ? { publishedAt: cached.publishedAt } : {}),
|
|
compatible: Boolean(cached.asset),
|
|
integrityReady: Boolean(cached.asset?.sha256) && (!config.updateRequireSignature || cached.signatureVerified === true),
|
|
signatureReady: !config.updateRequireSignature || cached.signatureVerified === true,
|
|
isNewer: isNewerVersion(config.appVersion, cached.version),
|
|
...(cached.asset ? { assetName: cached.asset.name, ...(cached.asset.size === undefined ? {} : { assetSize: cached.asset.size }) } : {}),
|
|
},
|
|
};
|
|
}
|
|
|
|
export async function writeUpdateRequest(config: AppConfig, request: UpdateRequest): Promise<void> {
|
|
const parent = path.dirname(config.updateRequestPath);
|
|
await mkdir(parent, { recursive: true, mode: 0o700 });
|
|
const temporary = `${config.updateRequestPath}.tmp-${randomUUID()}`;
|
|
await writeFile(temporary, JSON.stringify(request), { encoding: "utf8", mode: 0o600, flag: "wx" });
|
|
try {
|
|
await chmod(temporary, 0o600);
|
|
await rename(temporary, config.updateRequestPath);
|
|
} catch (error) {
|
|
await import("node:fs/promises").then(({ rm }) => rm(temporary, { force: true })).catch(() => undefined);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
export function publicUpdateJob(row: Record<string, unknown> | undefined): Record<string, unknown> | null {
|
|
if (!row) return null;
|
|
const hasError = typeof row.errorMessage === "string" && row.errorMessage.length > 0;
|
|
return {
|
|
id: row.id,
|
|
status: row.status,
|
|
version: row.version,
|
|
platform: row.platform,
|
|
assetName: row.assetName ?? null,
|
|
sizeBytes: row.sizeBytes ?? null,
|
|
// Do not expose filesystem paths, command output, or upstream response
|
|
// text through the authenticated status endpoint. Detailed diagnostics
|
|
// remain in the server journal for operators.
|
|
errorMessage: hasError ? "更新失败,请查看服务器日志或重试" : null,
|
|
createdAt: row.createdAt,
|
|
updatedAt: row.updatedAt,
|
|
completedAt: row.completedAt ?? null,
|
|
};
|
|
}
|