304 lines
12 KiB
TypeScript
304 lines
12 KiB
TypeScript
import crypto from 'node:crypto'
|
|
import fs from 'node:fs'
|
|
import os from 'node:os'
|
|
import path from 'node:path'
|
|
import zlib from 'node:zlib'
|
|
|
|
import { afterEach, describe, expect, test } from 'bun:test'
|
|
|
|
import {
|
|
PERIODIC_UPDATE_CHECK_INTERVAL_MS,
|
|
compareSemver,
|
|
evaluateUpdateDecision,
|
|
getUpdatePromptKey,
|
|
installHotfixArchive,
|
|
markHotfixVerified,
|
|
readHotfixState,
|
|
resolveActiveEarthOverlay,
|
|
resolveUpdateAssetUrl,
|
|
rollbackPendingHotfix,
|
|
shouldSuppressUpdatePrompt,
|
|
} from '../src/main/hot-update-core'
|
|
import { createEarthProtocolHandler } from '../src/main/protocol-core'
|
|
import { createTarGz, extractTarGzSafely } from '../src/main/tar-gz'
|
|
|
|
const tempRoots: string[] = []
|
|
|
|
function makeTempDir(prefix: string): string {
|
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix))
|
|
tempRoots.push(dir)
|
|
return dir
|
|
}
|
|
|
|
function buildMaliciousTarGz(entryName: string, typeFlag = '0'): Buffer {
|
|
const header = Buffer.alloc(512, 0)
|
|
header.write(entryName, 0, 100, 'utf8')
|
|
header.write('0000644\0', 100, 8, 'ascii')
|
|
header.write('0000000\0', 108, 8, 'ascii')
|
|
header.write('0000000\0', 116, 8, 'ascii')
|
|
header.write('00000000000\0', 124, 12, 'ascii')
|
|
header.write('00000000000\0', 136, 12, 'ascii')
|
|
header.fill(0x20, 148, 156)
|
|
header.write(typeFlag, 156, 1, 'ascii')
|
|
header.write('ustar\0', 257, 6, 'ascii')
|
|
header.write('00', 263, 2, 'ascii')
|
|
let checksum = 0
|
|
for (let i = 0; i < 512; i += 1) checksum += header[i]
|
|
header.write(`${checksum.toString(8).padStart(6, '0')}\0 `, 148, 8, 'ascii')
|
|
return zlib.gzipSync(Buffer.concat([header, Buffer.alloc(1024, 0)]))
|
|
}
|
|
|
|
afterEach(() => {
|
|
while (tempRoots.length > 0) {
|
|
const dir = tempRoots.pop()!
|
|
fs.rmSync(dir, { recursive: true, force: true })
|
|
}
|
|
})
|
|
|
|
describe('tar-gz archive creation and safe extraction', () => {
|
|
test('round-trips files including nested js/css directories and long USTAR paths', () => {
|
|
const outDir = makeTempDir('planet-tar-ok-')
|
|
const longPath =
|
|
'js/submodules/deeply/nested/component/folder/structure/extra-segment/another-segment/runtime-earth-worker-module-bundle.js'
|
|
const archive = createTarGz([
|
|
{ path: 'index.html', data: Buffer.from('<!doctype html><html><body>ok</body></html>') },
|
|
{ path: 'css/theme.css', data: Buffer.from('body { color: #fff; }') },
|
|
{ path: longPath, data: Buffer.from('export const ok = true;') },
|
|
])
|
|
|
|
const result = extractTarGzSafely(archive, outDir)
|
|
expect(result.files).toEqual(['css/theme.css', 'index.html', longPath])
|
|
expect(fs.readFileSync(path.join(outDir, 'index.html'), 'utf8')).toContain('<body>ok</body>')
|
|
expect(fs.readFileSync(path.join(outDir, longPath), 'utf8')).toBe('export const ok = true;')
|
|
})
|
|
|
|
test('rejects path traversal, absolute paths, and symlink entries', () => {
|
|
const outDir = makeTempDir('planet-tar-bad-')
|
|
expect(() => createTarGz([{ path: '../escape.js', data: Buffer.from('x') }])).toThrow()
|
|
expect(() => createTarGz([{ path: '/etc/passwd', data: Buffer.from('x') }])).toThrow()
|
|
|
|
expect(() => extractTarGzSafely(buildMaliciousTarGz('../escape.js', '0'), outDir)).toThrow()
|
|
expect(() => extractTarGzSafely(buildMaliciousTarGz('/abs/path.js', '0'), outDir)).toThrow()
|
|
expect(() => extractTarGzSafely(buildMaliciousTarGz('js/link.js', '2'), outDir)).toThrow()
|
|
})
|
|
})
|
|
|
|
describe('hot-update decision matrix, verification, rollback, and overlay protocol', () => {
|
|
test('compareSemver and evaluateUpdateDecision select the exact right update tier', () => {
|
|
expect(compareSemver('0.78.0', '0.78.0')).toBe(0)
|
|
expect(compareSemver('0.78.1', '0.78.0')).toBe(1)
|
|
expect(compareSemver('0.79.0', '0.78.9')).toBe(1)
|
|
expect(compareSemver('v0.79.0', '0.79.0-beta.1')).toBe(1)
|
|
|
|
const validSha = 'a'.repeat(64)
|
|
|
|
expect(
|
|
evaluateUpdateDecision({
|
|
shellVersion: '0.78.0',
|
|
activeBundleVersion: '0.78.0',
|
|
blacklistedVersions: [],
|
|
manifest: {
|
|
shell: { version: '0.78.0', minRequired: '0.78.0', downloadUrl: 'https://gitea.rclaw.top/r' },
|
|
bundle: null,
|
|
},
|
|
}),
|
|
).toEqual({ kind: 'up-to-date' })
|
|
|
|
expect(
|
|
evaluateUpdateDecision({
|
|
shellVersion: '0.78.0',
|
|
activeBundleVersion: '0.78.0',
|
|
blacklistedVersions: [],
|
|
manifest: {
|
|
shell: { version: '0.78.0', minRequired: '0.78.0', downloadUrl: 'https://gitea.rclaw.top/r' },
|
|
bundle: { version: '0.78.2', minShellVersion: '0.78.0', url: '/api/v1/client/updates/files/b.tar.gz', sha256: validSha },
|
|
},
|
|
}),
|
|
).toMatchObject({ kind: 'hotfix-update', bundle: { version: '0.78.2' } })
|
|
|
|
expect(
|
|
evaluateUpdateDecision({
|
|
shellVersion: '0.78.0',
|
|
activeBundleVersion: '0.78.2',
|
|
blacklistedVersions: ['0.78.3'],
|
|
manifest: {
|
|
shell: { version: '0.79.0', minRequired: '0.79.0', downloadUrl: 'https://gitea.rclaw.top/r' },
|
|
bundle: { version: '0.78.3', minShellVersion: '0.78.0', url: '/b.tar.gz', sha256: validSha },
|
|
},
|
|
}),
|
|
).toEqual({
|
|
kind: 'shell-update',
|
|
mandatory: true,
|
|
shell: { version: '0.79.0', minRequired: '0.79.0', downloadUrl: 'https://gitea.rclaw.top/r' },
|
|
})
|
|
|
|
expect(
|
|
evaluateUpdateDecision({
|
|
shellVersion: '0.78.0',
|
|
activeBundleVersion: '0.78.0',
|
|
blacklistedVersions: [],
|
|
manifest: {
|
|
shell: { version: '0.79.0', minRequired: '0.78.0', downloadUrl: 'https://gitea.rclaw.top/r' },
|
|
bundle: { version: '0.79.1', minShellVersion: '0.79.0', url: '/b.tar.gz', sha256: validSha },
|
|
},
|
|
}),
|
|
).toMatchObject({ kind: 'shell-update', mandatory: false })
|
|
|
|
expect(resolveUpdateAssetUrl('/api/v1/client/updates/files/a.tar.gz', 'https://rclaw.top/sub')).toBe(
|
|
'https://rclaw.top/api/v1/client/updates/files/a.tar.gz',
|
|
)
|
|
})
|
|
|
|
test('verifies SHA-256 on install, marks verified on ready, and auto-rolls back failing pending bundles', () => {
|
|
const userDataDir = makeTempDir('planet-hotfix-state-')
|
|
|
|
const goodV1Archive = createTarGz([
|
|
{ path: 'index.html', data: Buffer.from('<html>v1</html>') },
|
|
{ path: 'js/app.js', data: Buffer.from('console.log("v1")') },
|
|
])
|
|
const goodV1Sha = crypto.createHash('sha256').update(goodV1Archive).digest('hex')
|
|
|
|
expect(() =>
|
|
installHotfixArchive({
|
|
userDataDir,
|
|
version: '0.78.1',
|
|
archiveBuffer: goodV1Archive,
|
|
expectedSha256: '0'.repeat(64),
|
|
}),
|
|
).toThrow(/SHA-256 mismatch/)
|
|
|
|
installHotfixArchive({
|
|
userDataDir,
|
|
version: '0.78.1',
|
|
archiveBuffer: goodV1Archive,
|
|
expectedSha256: goodV1Sha,
|
|
})
|
|
|
|
const boot1 = resolveActiveEarthOverlay({ userDataDir, shellVersion: '0.78.0' })
|
|
expect(boot1.activeBundleVersion).toBe('0.78.1')
|
|
expect(boot1.pendingVerification).toBe(true)
|
|
expect(boot1.overlayRoot).toBeTruthy()
|
|
|
|
const verifiedState = markHotfixVerified(userDataDir)
|
|
expect(verifiedState.status).toBe('verified')
|
|
expect(verifiedState.previousVerifiedVersion).toBe('0.78.1')
|
|
|
|
// Install a bad pending v0.78.2 that fails to mark ready across 2 launch attempts.
|
|
const badV2Archive = createTarGz([
|
|
{ path: 'index.html', data: Buffer.from('<html>broken v2</html>') },
|
|
])
|
|
const badV2Sha = crypto.createHash('sha256').update(badV2Archive).digest('hex')
|
|
installHotfixArchive({
|
|
userDataDir,
|
|
version: '0.78.2',
|
|
archiveBuffer: badV2Archive,
|
|
expectedSha256: badV2Sha,
|
|
})
|
|
|
|
const failBoot1 = resolveActiveEarthOverlay({ userDataDir, shellVersion: '0.78.0' })
|
|
expect(failBoot1.activeBundleVersion).toBe('0.78.2')
|
|
expect(failBoot1.pendingVerification).toBe(true)
|
|
|
|
const failBoot2 = resolveActiveEarthOverlay({ userDataDir, shellVersion: '0.78.0' })
|
|
expect(failBoot2.activeBundleVersion).toBe('0.78.2')
|
|
expect(failBoot2.pendingVerification).toBe(true)
|
|
|
|
// 3rd attempt sees 2 failed unverified boots -> automatically rolls back to verified v0.78.1
|
|
const rolledBack = resolveActiveEarthOverlay({ userDataDir, shellVersion: '0.78.0' })
|
|
expect(rolledBack.rolledBackFrom).toBe('0.78.2')
|
|
expect(rolledBack.activeBundleVersion).toBe('0.78.1')
|
|
expect(rolledBack.pendingVerification).toBe(false)
|
|
expect(readHotfixState(userDataDir).blacklistedVersions).toContain('0.78.2')
|
|
|
|
// Immediate crash rollback also blacklists pending version right away.
|
|
installHotfixArchive({
|
|
userDataDir,
|
|
version: '0.78.3',
|
|
archiveBuffer: badV2Archive,
|
|
expectedSha256: badV2Sha,
|
|
})
|
|
const immediateRollback = rollbackPendingHotfix(userDataDir, '0.78.0')
|
|
expect(immediateRollback.rolledBackFrom).toBe('0.78.3')
|
|
expect(immediateRollback.activeBundleVersion).toBe('0.78.1')
|
|
|
|
// Installing a newer shell (0.79.0) automatically retires older hotfixes (0.78.1).
|
|
const afterShellUpgrade = resolveActiveEarthOverlay({ userDataDir, shellVersion: '0.79.0' })
|
|
expect(afterShellUpgrade.overlayRoot).toBeNull()
|
|
expect(afterShellUpgrade.activeBundleVersion).toBe('0.79.0')
|
|
})
|
|
|
|
test('createEarthProtocolHandler serves overlay files first and falls back to shell assets', async () => {
|
|
const shellRoot = makeTempDir('planet-proto-shell-')
|
|
const overlayRoot = makeTempDir('planet-proto-overlay-')
|
|
|
|
fs.mkdirSync(path.join(shellRoot, 'js'), { recursive: true })
|
|
fs.mkdirSync(path.join(shellRoot, 'assets'), { recursive: true })
|
|
fs.writeFileSync(path.join(shellRoot, 'index.html'), '<html>shell</html>')
|
|
fs.writeFileSync(path.join(shellRoot, 'js', 'main.js'), 'shell-js')
|
|
fs.writeFileSync(path.join(shellRoot, 'assets', '8k_earth_daymap.jpg'), 'heavy-texture-bytes')
|
|
|
|
fs.mkdirSync(path.join(overlayRoot, 'js'), { recursive: true })
|
|
fs.writeFileSync(path.join(overlayRoot, 'index.html'), '<html>hotfix</html>')
|
|
fs.writeFileSync(path.join(overlayRoot, 'js', 'main.js'), 'hotfix-js')
|
|
|
|
let activeOverlay: string | null = overlayRoot
|
|
const handler = createEarthProtocolHandler({
|
|
earthBundleRoot: shellRoot,
|
|
getEarthOverlayRoot: () => activeOverlay,
|
|
getBackendUrl: () => 'https://rclaw.top',
|
|
})
|
|
|
|
const htmlRes = await handler(new Request('planet://earth/earth/index.html'))
|
|
expect(await htmlRes.text()).toBe('<html>hotfix</html>')
|
|
|
|
const jsRes = await handler(new Request('planet://earth/earth/js/main.js'))
|
|
expect(await jsRes.text()).toBe('hotfix-js')
|
|
|
|
const assetRes = await handler(new Request('planet://earth/earth/assets/8k_earth_daymap.jpg'))
|
|
expect(await assetRes.text()).toBe('heavy-texture-bytes')
|
|
|
|
const traversalRes = await handler(new Request('planet://earth/earth/..%2f..%2fsecret.txt'))
|
|
expect(traversalRes.status).toBe(403)
|
|
|
|
activeOverlay = null
|
|
const restoredHtmlRes = await handler(new Request('planet://earth/earth/index.html'))
|
|
expect(await restoredHtmlRes.text()).toBe('<html>shell</html>')
|
|
})
|
|
|
|
test('periodic 12h polling interval and per-session dismissal guard behave cleanly', () => {
|
|
expect(PERIODIC_UPDATE_CHECK_INTERVAL_MS).toBe(12 * 60 * 60 * 1000)
|
|
|
|
const validSha = 'b'.repeat(64)
|
|
const hotfixDecision = evaluateUpdateDecision({
|
|
shellVersion: '0.78.0',
|
|
activeBundleVersion: '0.78.0',
|
|
blacklistedVersions: [],
|
|
manifest: {
|
|
shell: { version: '0.78.0', minRequired: '0.78.0', downloadUrl: 'https://gitea.rclaw.top/r' },
|
|
bundle: { version: '0.78.1', minShellVersion: '0.78.0', url: '/b.tar.gz', sha256: validSha },
|
|
},
|
|
})
|
|
const key = getUpdatePromptKey(hotfixDecision)
|
|
expect(key).toBe('hotfix:0.78.1')
|
|
|
|
const dismissed = new Set<string>()
|
|
expect(shouldSuppressUpdatePrompt(hotfixDecision, { manual: false, dismissedKeys: dismissed })).toBe(false)
|
|
|
|
dismissed.add(key!)
|
|
expect(shouldSuppressUpdatePrompt(hotfixDecision, { manual: false, dismissedKeys: dismissed })).toBe(true)
|
|
expect(shouldSuppressUpdatePrompt(hotfixDecision, { manual: true, dismissedKeys: dismissed })).toBe(false)
|
|
|
|
const newerDecision = evaluateUpdateDecision({
|
|
shellVersion: '0.78.0',
|
|
activeBundleVersion: '0.78.0',
|
|
blacklistedVersions: [],
|
|
manifest: {
|
|
shell: { version: '0.78.0', minRequired: '0.78.0', downloadUrl: 'https://gitea.rclaw.top/r' },
|
|
bundle: { version: '0.78.2', minShellVersion: '0.78.0', url: '/b.tar.gz', sha256: validSha },
|
|
},
|
|
})
|
|
expect(shouldSuppressUpdatePrompt(newerDecision, { manual: false, dismissedKeys: dismissed })).toBe(false)
|
|
expect(getUpdatePromptKey({ kind: 'up-to-date' })).toBeNull()
|
|
})
|
|
})
|