505 lines
16 KiB
TypeScript
505 lines
16 KiB
TypeScript
import crypto from 'node:crypto'
|
|
import fs from 'node:fs'
|
|
import path from 'node:path'
|
|
|
|
import { extractTarGzSafely } from './tar-gz'
|
|
|
|
export interface ClientShellUpdateInfo {
|
|
version: string
|
|
minRequired?: string | null
|
|
downloadUrl: string
|
|
releaseNotes?: string | null
|
|
}
|
|
|
|
export interface ClientBundleUpdateInfo {
|
|
version: string
|
|
minShellVersion: string
|
|
url: string
|
|
sha256: string
|
|
size?: number
|
|
releaseNotes?: string | null
|
|
}
|
|
|
|
export interface ClientUpdateManifest {
|
|
shell?: ClientShellUpdateInfo | null
|
|
bundle?: ClientBundleUpdateInfo | null
|
|
}
|
|
|
|
export interface HotfixState {
|
|
activeVersion: string | null
|
|
previousVerifiedVersion: string | null
|
|
status: 'verified' | 'pending'
|
|
pendingAttempts: number
|
|
blacklistedVersions: string[]
|
|
installedAt?: string
|
|
}
|
|
|
|
export interface ActiveOverlayResolution {
|
|
overlayRoot: string | null
|
|
activeBundleVersion: string
|
|
pendingVerification: boolean
|
|
rolledBackFrom: string | null
|
|
}
|
|
|
|
export type UpdateDecision =
|
|
| { kind: 'up-to-date' }
|
|
| { kind: 'hotfix-update'; bundle: ClientBundleUpdateInfo }
|
|
| { kind: 'shell-update'; shell: ClientShellUpdateInfo; mandatory: boolean }
|
|
|
|
const SEMVER_PATTERN = /^[vV]?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/
|
|
const STRICT_VERSION_PATTERN = /^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][0-9A-Za-z.-]+)?$/
|
|
const SHA256_PATTERN = /^[0-9a-f]{64}$/i
|
|
const MAX_PENDING_ATTEMPTS = 2
|
|
|
|
interface ParsedSemver {
|
|
major: number
|
|
minor: number
|
|
patch: number
|
|
prerelease: string[]
|
|
}
|
|
|
|
function parseSemver(raw: string): ParsedSemver | null {
|
|
const match = SEMVER_PATTERN.exec(String(raw || '').trim())
|
|
if (!match) return null
|
|
return {
|
|
major: Number(match[1] ?? 0),
|
|
minor: Number(match[2] ?? 0),
|
|
patch: Number(match[3] ?? 0),
|
|
prerelease: match[4] ? match[4].split('.') : [],
|
|
}
|
|
}
|
|
|
|
export function compareSemver(a: string, b: string): number {
|
|
const pa = parseSemver(a)
|
|
const pb = parseSemver(b)
|
|
if (!pa || !pb) {
|
|
return String(a).localeCompare(String(b))
|
|
}
|
|
for (const [va, vb] of [
|
|
[pa.major, pb.major],
|
|
[pa.minor, pb.minor],
|
|
[pa.patch, pb.patch],
|
|
]) {
|
|
if (va !== vb) return va > vb ? 1 : -1
|
|
}
|
|
if (pa.prerelease.length === 0 && pb.prerelease.length === 0) return 0
|
|
if (pa.prerelease.length === 0) return 1
|
|
if (pb.prerelease.length === 0) return -1
|
|
|
|
const maxLen = Math.max(pa.prerelease.length, pb.prerelease.length)
|
|
for (let i = 0; i < maxLen; i += 1) {
|
|
const ia = pa.prerelease[i]
|
|
const ib = pb.prerelease[i]
|
|
if (ia === undefined) return -1
|
|
if (ib === undefined) return 1
|
|
const na = /^\d+$/.test(ia) ? Number(ia) : null
|
|
const nb = /^\d+$/.test(ib) ? Number(ib) : null
|
|
if (na !== null && nb !== null) {
|
|
if (na !== nb) return na > nb ? 1 : -1
|
|
} else if (na !== null) {
|
|
return -1
|
|
} else if (nb !== null) {
|
|
return 1
|
|
} else if (ia !== ib) {
|
|
return ia > ib ? 1 : -1
|
|
}
|
|
}
|
|
return 0
|
|
}
|
|
|
|
export function getHotfixRootDir(userDataDir: string): string {
|
|
return path.join(userDataDir, 'earth-hotfix')
|
|
}
|
|
|
|
export function getHotfixBundlesDir(userDataDir: string): string {
|
|
return path.join(getHotfixRootDir(userDataDir), 'bundles')
|
|
}
|
|
|
|
export function getHotfixBundleDir(userDataDir: string, version: string): string {
|
|
return path.join(getHotfixBundlesDir(userDataDir), version)
|
|
}
|
|
|
|
function getHotfixStatePath(userDataDir: string): string {
|
|
return path.join(getHotfixRootDir(userDataDir), 'state.json')
|
|
}
|
|
|
|
function defaultHotfixState(): HotfixState {
|
|
return {
|
|
activeVersion: null,
|
|
previousVerifiedVersion: null,
|
|
status: 'verified',
|
|
pendingAttempts: 0,
|
|
blacklistedVersions: [],
|
|
}
|
|
}
|
|
|
|
export function readHotfixState(userDataDir: string): HotfixState {
|
|
const statePath = getHotfixStatePath(userDataDir)
|
|
try {
|
|
if (!fs.existsSync(statePath)) return defaultHotfixState()
|
|
const raw = JSON.parse(fs.readFileSync(statePath, 'utf8')) as Partial<HotfixState>
|
|
return {
|
|
activeVersion: typeof raw.activeVersion === 'string' && STRICT_VERSION_PATTERN.test(raw.activeVersion)
|
|
? raw.activeVersion
|
|
: null,
|
|
previousVerifiedVersion: typeof raw.previousVerifiedVersion === 'string' && STRICT_VERSION_PATTERN.test(raw.previousVerifiedVersion)
|
|
? raw.previousVerifiedVersion
|
|
: null,
|
|
status: raw.status === 'pending' ? 'pending' : 'verified',
|
|
pendingAttempts: Number.isInteger(raw.pendingAttempts) && Number(raw.pendingAttempts) >= 0
|
|
? Number(raw.pendingAttempts)
|
|
: 0,
|
|
blacklistedVersions: Array.isArray(raw.blacklistedVersions)
|
|
? raw.blacklistedVersions.filter((item): item is string => typeof item === 'string' && STRICT_VERSION_PATTERN.test(item))
|
|
: [],
|
|
installedAt: typeof raw.installedAt === 'string' ? raw.installedAt : undefined,
|
|
}
|
|
} catch {
|
|
return defaultHotfixState()
|
|
}
|
|
}
|
|
|
|
export function writeHotfixStateAtomic(userDataDir: string, state: HotfixState): void {
|
|
const rootDir = getHotfixRootDir(userDataDir)
|
|
const statePath = getHotfixStatePath(userDataDir)
|
|
const tmpPath = `${statePath}.${process.pid}.tmp`
|
|
fs.mkdirSync(rootDir, { recursive: true })
|
|
fs.writeFileSync(tmpPath, `${JSON.stringify(state, null, 2)}\n`, 'utf8')
|
|
fs.renameSync(tmpPath, statePath)
|
|
}
|
|
|
|
function hasValidBundleIndex(bundleDir: string): boolean {
|
|
try {
|
|
return fs.statSync(path.join(bundleDir, 'index.html')).isFile()
|
|
} catch {
|
|
return false
|
|
}
|
|
}
|
|
|
|
function resolveFallbackVersion(state: HotfixState, shellVersion: string, userDataDir: string): string | null {
|
|
const candidate = state.previousVerifiedVersion
|
|
if (!candidate) return null
|
|
if (candidate === state.activeVersion) return null
|
|
if (state.blacklistedVersions.includes(candidate)) return null
|
|
if (compareSemver(candidate, shellVersion) <= 0) return null
|
|
if (!hasValidBundleIndex(getHotfixBundleDir(userDataDir, candidate))) return null
|
|
return candidate
|
|
}
|
|
|
|
function pruneObsoleteBundles(userDataDir: string, keepVersions: Set<string>): void {
|
|
const bundlesDir = getHotfixBundlesDir(userDataDir)
|
|
try {
|
|
if (!fs.existsSync(bundlesDir)) return
|
|
for (const entry of fs.readdirSync(bundlesDir, { withFileTypes: true })) {
|
|
if (!entry.isDirectory()) continue
|
|
if (keepVersions.has(entry.name)) continue
|
|
fs.rmSync(path.join(bundlesDir, entry.name), { recursive: true, force: true })
|
|
}
|
|
} catch {
|
|
// Non-fatal cleanup best-effort.
|
|
}
|
|
}
|
|
|
|
export function resolveActiveEarthOverlay(options: {
|
|
userDataDir: string
|
|
shellVersion: string
|
|
}): ActiveOverlayResolution {
|
|
const { userDataDir, shellVersion } = options
|
|
const state = readHotfixState(userDataDir)
|
|
|
|
if (!state.activeVersion || compareSemver(state.activeVersion, shellVersion) <= 0) {
|
|
return {
|
|
overlayRoot: null,
|
|
activeBundleVersion: shellVersion,
|
|
pendingVerification: false,
|
|
rolledBackFrom: null,
|
|
}
|
|
}
|
|
|
|
const activeDir = getHotfixBundleDir(userDataDir, state.activeVersion)
|
|
const activeUsable =
|
|
!state.blacklistedVersions.includes(state.activeVersion) && hasValidBundleIndex(activeDir)
|
|
|
|
if (!activeUsable) {
|
|
const badVersion = state.activeVersion
|
|
const fallbackVer = resolveFallbackVersion(state, shellVersion, userDataDir)
|
|
const nextState: HotfixState = {
|
|
...state,
|
|
activeVersion: fallbackVer,
|
|
previousVerifiedVersion: fallbackVer,
|
|
status: 'verified',
|
|
pendingAttempts: 0,
|
|
}
|
|
writeHotfixStateAtomic(userDataDir, nextState)
|
|
return {
|
|
overlayRoot: fallbackVer ? getHotfixBundleDir(userDataDir, fallbackVer) : null,
|
|
activeBundleVersion: fallbackVer ?? shellVersion,
|
|
pendingVerification: false,
|
|
rolledBackFrom: badVersion,
|
|
}
|
|
}
|
|
|
|
if (state.status === 'pending') {
|
|
if (state.pendingAttempts >= MAX_PENDING_ATTEMPTS) {
|
|
const rolledBackFrom = state.activeVersion
|
|
const blacklist = state.blacklistedVersions.includes(rolledBackFrom)
|
|
? state.blacklistedVersions
|
|
: [...state.blacklistedVersions, rolledBackFrom]
|
|
const fallbackVer = resolveFallbackVersion(
|
|
{ ...state, blacklistedVersions: blacklist },
|
|
shellVersion,
|
|
userDataDir,
|
|
)
|
|
const nextState: HotfixState = {
|
|
activeVersion: fallbackVer,
|
|
previousVerifiedVersion: fallbackVer,
|
|
status: 'verified',
|
|
pendingAttempts: 0,
|
|
blacklistedVersions: blacklist,
|
|
}
|
|
writeHotfixStateAtomic(userDataDir, nextState)
|
|
fs.rmSync(activeDir, { recursive: true, force: true })
|
|
return {
|
|
overlayRoot: fallbackVer ? getHotfixBundleDir(userDataDir, fallbackVer) : null,
|
|
activeBundleVersion: fallbackVer ?? shellVersion,
|
|
pendingVerification: false,
|
|
rolledBackFrom,
|
|
}
|
|
}
|
|
|
|
const nextState: HotfixState = {
|
|
...state,
|
|
pendingAttempts: state.pendingAttempts + 1,
|
|
}
|
|
writeHotfixStateAtomic(userDataDir, nextState)
|
|
return {
|
|
overlayRoot: activeDir,
|
|
activeBundleVersion: state.activeVersion,
|
|
pendingVerification: true,
|
|
rolledBackFrom: null,
|
|
}
|
|
}
|
|
|
|
return {
|
|
overlayRoot: activeDir,
|
|
activeBundleVersion: state.activeVersion,
|
|
pendingVerification: false,
|
|
rolledBackFrom: null,
|
|
}
|
|
}
|
|
|
|
export function markHotfixVerified(userDataDir: string): HotfixState {
|
|
const state = readHotfixState(userDataDir)
|
|
if (!state.activeVersion) {
|
|
return state
|
|
}
|
|
const nextState: HotfixState = {
|
|
...state,
|
|
previousVerifiedVersion: state.activeVersion,
|
|
status: 'verified',
|
|
pendingAttempts: 0,
|
|
}
|
|
writeHotfixStateAtomic(userDataDir, nextState)
|
|
const keep = new Set<string>([state.activeVersion])
|
|
if (nextState.previousVerifiedVersion) {
|
|
keep.add(nextState.previousVerifiedVersion)
|
|
}
|
|
pruneObsoleteBundles(userDataDir, keep)
|
|
return nextState
|
|
}
|
|
|
|
export function rollbackPendingHotfix(userDataDir: string, shellVersion: string): {
|
|
rolledBackFrom: string | null
|
|
overlayRoot: string | null
|
|
activeBundleVersion: string
|
|
} {
|
|
const state = readHotfixState(userDataDir)
|
|
if (!state.activeVersion || state.status !== 'pending') {
|
|
const activeDir = state.activeVersion ? getHotfixBundleDir(userDataDir, state.activeVersion) : null
|
|
const valid = Boolean(
|
|
activeDir &&
|
|
state.activeVersion &&
|
|
compareSemver(state.activeVersion, shellVersion) > 0 &&
|
|
hasValidBundleIndex(activeDir),
|
|
)
|
|
return {
|
|
rolledBackFrom: null,
|
|
overlayRoot: valid ? activeDir : null,
|
|
activeBundleVersion: valid && state.activeVersion ? state.activeVersion : shellVersion,
|
|
}
|
|
}
|
|
|
|
const rolledBackFrom = state.activeVersion
|
|
const blacklist = state.blacklistedVersions.includes(rolledBackFrom)
|
|
? state.blacklistedVersions
|
|
: [...state.blacklistedVersions, rolledBackFrom]
|
|
const fallbackVer = resolveFallbackVersion(
|
|
{ ...state, blacklistedVersions: blacklist },
|
|
shellVersion,
|
|
userDataDir,
|
|
)
|
|
const nextState: HotfixState = {
|
|
activeVersion: fallbackVer,
|
|
previousVerifiedVersion: fallbackVer,
|
|
status: 'verified',
|
|
pendingAttempts: 0,
|
|
blacklistedVersions: blacklist,
|
|
}
|
|
writeHotfixStateAtomic(userDataDir, nextState)
|
|
fs.rmSync(getHotfixBundleDir(userDataDir, rolledBackFrom), { recursive: true, force: true })
|
|
|
|
return {
|
|
rolledBackFrom,
|
|
overlayRoot: fallbackVer ? getHotfixBundleDir(userDataDir, fallbackVer) : null,
|
|
activeBundleVersion: fallbackVer ?? shellVersion,
|
|
}
|
|
}
|
|
|
|
export function evaluateUpdateDecision(input: {
|
|
shellVersion: string
|
|
activeBundleVersion: string
|
|
blacklistedVersions: string[]
|
|
manifest: ClientUpdateManifest | null | undefined
|
|
}): UpdateDecision {
|
|
const manifest = input.manifest
|
|
if (!manifest || typeof manifest !== 'object') {
|
|
return { kind: 'up-to-date' }
|
|
}
|
|
|
|
const shell = manifest.shell
|
|
const hasShellDownload = Boolean(shell?.downloadUrl && typeof shell.downloadUrl === 'string')
|
|
const shellMandatory = Boolean(
|
|
hasShellDownload && shell?.minRequired && compareSemver(shell.minRequired, input.shellVersion) > 0,
|
|
)
|
|
const shellNewer = Boolean(
|
|
hasShellDownload && shell?.version && compareSemver(shell.version, input.shellVersion) > 0,
|
|
)
|
|
if (shell && shellMandatory) {
|
|
return { kind: 'shell-update', shell, mandatory: true }
|
|
}
|
|
|
|
const bundle = manifest.bundle
|
|
if (
|
|
bundle &&
|
|
typeof bundle.version === 'string' &&
|
|
STRICT_VERSION_PATTERN.test(bundle.version) &&
|
|
typeof bundle.url === 'string' &&
|
|
bundle.url.trim().length > 0 &&
|
|
typeof bundle.sha256 === 'string' &&
|
|
SHA256_PATTERN.test(bundle.sha256.trim()) &&
|
|
compareSemver(bundle.version, input.activeBundleVersion) > 0 &&
|
|
compareSemver(input.shellVersion, bundle.minShellVersion || '0.0.0') >= 0 &&
|
|
!input.blacklistedVersions.includes(bundle.version)
|
|
) {
|
|
return { kind: 'hotfix-update', bundle }
|
|
}
|
|
|
|
if (shell && shellNewer) {
|
|
return { kind: 'shell-update', shell, mandatory: false }
|
|
}
|
|
|
|
return { kind: 'up-to-date' }
|
|
}
|
|
|
|
export const PERIODIC_UPDATE_CHECK_INTERVAL_MS = 12 * 60 * 60 * 1000
|
|
|
|
export function getUpdatePromptKey(decision: UpdateDecision): string | null {
|
|
if (decision.kind === 'hotfix-update') {
|
|
return `hotfix:${decision.bundle.version}`
|
|
}
|
|
if (decision.kind === 'shell-update') {
|
|
return `shell:${decision.shell.version}`
|
|
}
|
|
return null
|
|
}
|
|
|
|
export function shouldSuppressUpdatePrompt(
|
|
decision: UpdateDecision,
|
|
options: { manual: boolean; dismissedKeys: ReadonlySet<string> },
|
|
): boolean {
|
|
if (options.manual || decision.kind === 'up-to-date') {
|
|
return false
|
|
}
|
|
const key = getUpdatePromptKey(decision)
|
|
return Boolean(key && options.dismissedKeys.has(key))
|
|
}
|
|
|
|
export function resolveUpdateAssetUrl(rawUrl: string, backendUrl: string): string {
|
|
const trimmed = String(rawUrl || '').trim()
|
|
if (!trimmed) {
|
|
throw new Error('Empty update asset URL')
|
|
}
|
|
if (trimmed.startsWith('/')) {
|
|
const base = new URL(backendUrl)
|
|
return new URL(trimmed, `${base.origin}`).toString()
|
|
}
|
|
const parsed = new URL(trimmed)
|
|
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
|
throw new Error(`Unsupported update asset URL protocol: ${parsed.protocol}`)
|
|
}
|
|
return parsed.toString()
|
|
}
|
|
|
|
export function installHotfixArchive(input: {
|
|
userDataDir: string
|
|
version: string
|
|
archiveBuffer: Buffer
|
|
expectedSha256: string
|
|
}): { overlayRoot: string; filesCount: number } {
|
|
const version = String(input.version || '').trim()
|
|
if (!STRICT_VERSION_PATTERN.test(version)) {
|
|
throw new Error(`Invalid hotfix bundle version: ${version}`)
|
|
}
|
|
const expected = String(input.expectedSha256 || '').trim().toLowerCase()
|
|
if (!SHA256_PATTERN.test(expected)) {
|
|
throw new Error('Invalid expected SHA-256 checksum')
|
|
}
|
|
|
|
const actual = crypto.createHash('sha256').update(input.archiveBuffer).digest('hex').toLowerCase()
|
|
if (actual !== expected) {
|
|
throw new Error(`Hotfix SHA-256 mismatch (expected ${expected}, got ${actual})`)
|
|
}
|
|
|
|
const rootDir = getHotfixRootDir(input.userDataDir)
|
|
const bundlesDir = getHotfixBundlesDir(input.userDataDir)
|
|
const targetDir = getHotfixBundleDir(input.userDataDir, version)
|
|
const stagingDir = path.join(rootDir, `staging-${version}-${Date.now()}`)
|
|
|
|
try {
|
|
const extracted = extractTarGzSafely(input.archiveBuffer, stagingDir)
|
|
if (!hasValidBundleIndex(stagingDir)) {
|
|
throw new Error('Hotfix archive is missing required index.html entry')
|
|
}
|
|
|
|
fs.mkdirSync(bundlesDir, { recursive: true })
|
|
fs.rmSync(targetDir, { recursive: true, force: true })
|
|
fs.renameSync(stagingDir, targetDir)
|
|
|
|
const previousState = readHotfixState(input.userDataDir)
|
|
const preservedVerified =
|
|
previousState.status === 'verified' && previousState.activeVersion && previousState.activeVersion !== version
|
|
? previousState.activeVersion
|
|
: previousState.previousVerifiedVersion && previousState.previousVerifiedVersion !== version
|
|
? previousState.previousVerifiedVersion
|
|
: null
|
|
|
|
const nextState: HotfixState = {
|
|
activeVersion: version,
|
|
previousVerifiedVersion: preservedVerified,
|
|
status: 'pending',
|
|
pendingAttempts: 0,
|
|
blacklistedVersions: previousState.blacklistedVersions.filter((item) => item !== version),
|
|
installedAt: new Date().toISOString(),
|
|
}
|
|
writeHotfixStateAtomic(input.userDataDir, nextState)
|
|
|
|
return {
|
|
overlayRoot: targetDir,
|
|
filesCount: extracted.files.length,
|
|
}
|
|
} catch (error) {
|
|
fs.rmSync(stagingDir, { recursive: true, force: true })
|
|
throw error
|
|
}
|
|
}
|