// scripts/ci/verify-desktop-installer-smoke.mjs // GAP-QA-06 / TDD v2.0 Phase 5 — 데스크톱 NSIS 설치본 · win-unpacked · latest.yml · Ed25519 서명 무결성 스모크 게이트. // // 사용법: // node scripts/ci/verify-desktop-installer-smoke.mjs [--dir apps/desktop/release/] [--verify-signature] // node scripts/ci/verify-desktop-installer-smoke.mjs --self-test // // 검증 항목: // 1. *-Setup-*.exe 존재, 크기(4KiB ~ 100MiB), DOS MZ + PE\0\0 헤더 정합성 // 2. *.exe.blockmap 존재 및 gzip 매직 바이트(0x1f 0x8b) // 3. latest.yml 버전 일치, 설치본 파일명 참조 일치, 실제 설치본 SHA-512 재계산 일치 // 4. win-unpacked/*.exe x86_64 PE64(0x8664) 헤더, resources/app-update.yml 정본 피드 URL, // resources/app.asar Chromium Pickle JSON("files") 헤더 정합성 // 5. (--verify-signature 또는 latest.yml.sig 존재 시) Ed25519 공개키 서명 검증 import { createHash, createPublicKey, generateKeyPairSync, sign, verify } from 'node:crypto' import { closeSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' import { fileURLToPath } from 'node:url' import { gzipSync } from 'node:zlib' const root = join(dirname(fileURLToPath(import.meta.url)), '..', '..') const CANONICAL_UPDATE_FEED = 'https://git.chanpaca.net/api/packages/yunchan/generic/d3ro-voice/latest' const MAX_UPLOAD_BYTES = 100 * 1024 * 1024 const MIN_INSTALLER_BYTES = 4096 const MAX_ASAR_HEADER_BYTES = 32 * 1024 * 1024 function readPeMachine(buffer) { if (buffer.length < 0x44) return null if (buffer[0] !== 0x4d || buffer[1] !== 0x5a) return null // 'MZ' const peOffset = buffer.readUInt32LE(0x3c) if (peOffset < 0x40 || peOffset + 6 > buffer.length) return null if ( buffer[peOffset] !== 0x50 || buffer[peOffset + 1] !== 0x45 || buffer[peOffset + 2] !== 0x00 || buffer[peOffset + 3] !== 0x00 ) { return null } return buffer.readUInt16LE(peOffset + 4) } function readExact(fd, buffer, length, position) { let offset = 0 while (offset < length) { const bytesRead = readSync(fd, buffer, offset, length - offset, position + offset) if (bytesRead <= 0) return false offset += bytesRead } return true } function hasValidAsarFileHeader(asarPath) { let fd try { const fileSize = statSync(asarPath).size if (fileSize < 20) return false fd = openSync(asarPath, 'r') const preamble = Buffer.allocUnsafe(16) if (!readExact(fd, preamble, 16, 0)) return false const picklePayloadSize = preamble.readUInt32LE(0) if (picklePayloadSize !== 4) return false const jsonByteLength = preamble.readUInt32LE(12) if (jsonByteLength < 2 || jsonByteLength > MAX_ASAR_HEADER_BYTES || 16 + jsonByteLength > fileSize) { return false } const headerBuf = Buffer.allocUnsafe(jsonByteLength) if (!readExact(fd, headerBuf, jsonByteLength, 16)) return false const headerText = headerBuf.toString('utf8').replace(/\0+$/g, '') const parsed = JSON.parse(headerText) return Boolean(parsed && typeof parsed === 'object' && parsed.files && typeof parsed.files === 'object') } catch { return false } finally { if (fd !== undefined) closeSync(fd) } } function sha512Base64(buffer) { return createHash('sha512').update(buffer).digest('base64') } export function verifyInstallerReleaseDir({ releaseDir, expectedVersion, publicKeyPem, requireSignature = false }) { const errors = [] const fail = (cond, code) => { if (!cond) errors.push(code) } if (!existsSync(releaseDir)) { throw new Error('installer_smoke_invalid:release_dir_missing') } const entries = readdirSync(releaseDir) const installerName = entries.find((name) => /-Setup-.*\.exe$/.test(name)) if (!installerName) { throw new Error('installer_smoke_invalid:installer_missing') } const installerPath = join(releaseDir, installerName) const installerStat = statSync(installerPath) fail(installerStat.size >= MIN_INSTALLER_BYTES, 'installer_too_small') fail(installerStat.size <= MAX_UPLOAD_BYTES, 'installer_size_exceeded') const installerBytes = readFileSync(installerPath) const installerMachine = readPeMachine(installerBytes) fail(installerMachine !== null, 'installer_pe_invalid') const blockmapPath = join(releaseDir, `${installerName}.blockmap`) if (!existsSync(blockmapPath)) { errors.push('blockmap_missing') } else { const blockmapBytes = readFileSync(blockmapPath) fail( blockmapBytes.length >= 10 && blockmapBytes[0] === 0x1f && blockmapBytes[1] === 0x8b, 'blockmap_not_gzip' ) } const latestYmlPath = join(releaseDir, 'latest.yml') let manifestText = '' if (!existsSync(latestYmlPath)) { errors.push('latest_yml_missing') } else { manifestText = readFileSync(latestYmlPath, 'utf8') const versionMatch = manifestText.match(/^version:\s*['"]?([^'"\s]+)['"]?\s*$/m)?.[1] const sha512Match = manifestText.match(/^sha512:\s*['"]?([^'"\s]+)['"]?\s*$/m)?.[1] const pathMatch = manifestText.match(/^path:\s*['"]?(.+?)['"]?\s*$/m)?.[1] fail(versionMatch === expectedVersion, 'latest_yml_version_drift') fail(pathMatch === installerName, 'latest_yml_path_drift') const actualSha512 = sha512Base64(installerBytes) fail(sha512Match === actualSha512, 'latest_yml_sha512_mismatch') } const sigPath = join(releaseDir, 'latest.yml.sig') if (requireSignature || existsSync(sigPath)) { if (!existsSync(sigPath)) { errors.push('manifest_signature_missing') } else { const sigBytes = Buffer.from(readFileSync(sigPath, 'utf8').trim(), 'base64') let sigOk = false if (sigBytes.length === 64 && manifestText.length > 0 && publicKeyPem) { try { sigOk = verify(null, Buffer.from(manifestText, 'utf8'), createPublicKey(publicKeyPem), sigBytes) } catch { sigOk = false } } fail(sigOk, 'manifest_signature_invalid') } } const unpackedDir = join(releaseDir, 'win-unpacked') if (!existsSync(unpackedDir)) { errors.push('unpacked_dir_missing') } else { const unpackedExe = readdirSync(unpackedDir).find((name) => name.toLowerCase().endsWith('.exe')) if (!unpackedExe) { errors.push('unpacked_exe_missing') } else { const exeHeader = readFileSync(join(unpackedDir, unpackedExe)).subarray(0, 4096) fail(readPeMachine(exeHeader) === 0x8664, 'unpacked_exe_pe64_invalid') } const appUpdatePath = join(unpackedDir, 'resources', 'app-update.yml') if (!existsSync(appUpdatePath)) { errors.push('app_update_yml_missing') } else { const appUpdateText = readFileSync(appUpdatePath, 'utf8') fail(appUpdateText.includes(CANONICAL_UPDATE_FEED), 'app_update_yml_feed_drift') } const asarPath = join(unpackedDir, 'resources', 'app.asar') if (!existsSync(asarPath)) { errors.push('app_asar_missing') } else { fail(hasValidAsarFileHeader(asarPath), 'app_asar_header_invalid') } } if (errors.length > 0) { throw new Error(`installer_smoke_invalid:${errors.join(',')}`) } return { ok: true, version: expectedVersion, installer: installerName, sizeBytes: installerStat.size } } function buildSyntheticPe(machine, totalBytes = 8192) { const buf = Buffer.alloc(totalBytes, 0) buf[0] = 0x4d // 'M' buf[1] = 0x5a // 'Z' buf.writeUInt32LE(0x80, 0x3c) buf[0x80] = 0x50 // 'P' buf[0x81] = 0x45 // 'E' buf[0x82] = 0x00 buf[0x83] = 0x00 buf.writeUInt16LE(machine, 0x84) return buf } function buildSyntheticAsar(jsonObj) { const jsonBytes = Buffer.from(JSON.stringify(jsonObj), 'utf8') const alignedLen = Math.ceil(jsonBytes.length / 4) * 4 const header = Buffer.alloc(16 + alignedLen, 0) header.writeUInt32LE(4, 0) header.writeUInt32LE(8 + alignedLen, 4) header.writeUInt32LE(4 + alignedLen, 8) header.writeUInt32LE(jsonBytes.length, 12) jsonBytes.copy(header, 16) return header } function runSelfTest() { const sandbox = mkdtempSync(join(tmpdir(), 'd3ro-installer-smoke-')) try { const { publicKey, privateKey } = generateKeyPairSync('ed25519') const publicKeyPem = publicKey.export({ type: 'spki', format: 'pem' }).toString() const version = '9.9.9' const installerName = `D3RO-Voice-Setup-${version}.exe` const createValidFixture = (subName) => { const dir = join(sandbox, subName) mkdirSync(join(dir, 'win-unpacked', 'resources'), { recursive: true }) const installerBytes = buildSyntheticPe(0x014c, 8192) writeFileSync(join(dir, installerName), installerBytes) writeFileSync(join(dir, `${installerName}.blockmap`), gzipSync(Buffer.from('{"version":2}'))) const sha512 = sha512Base64(installerBytes) const manifest = [ `version: ${version}`, 'files:', ` - url: ${installerName}`, ` sha512: ${sha512}`, ` size: ${installerBytes.length}`, `path: ${installerName}`, `sha512: ${sha512}`, "releaseDate: '2026-11-13T00:00:00.000Z'", '' ].join('\n') writeFileSync(join(dir, 'latest.yml'), manifest) const sig = sign(null, Buffer.from(manifest, 'utf8'), privateKey).toString('base64') writeFileSync(join(dir, 'latest.yml.sig'), `${sig}\n`) writeFileSync(join(dir, 'win-unpacked', 'D3RO Voice.exe'), buildSyntheticPe(0x8664, 4096)) writeFileSync( join(dir, 'win-unpacked', 'resources', 'app-update.yml'), `provider: generic\nurl: "${CANONICAL_UPDATE_FEED}"\n` ) writeFileSync( join(dir, 'win-unpacked', 'resources', 'app.asar'), buildSyntheticAsar({ files: { 'package.json': { size: 42, offset: '0' } } }) ) return dir } const validDir = createValidFixture('valid') const okResult = verifyInstallerReleaseDir({ releaseDir: validDir, expectedVersion: version, publicKeyPem, requireSignature: true }) if (!okResult.ok) throw new Error('self_test_valid_case_failed') // Regression: real Electron app.asar headers exceed 64 KiB (often several MiB). const largeHeaderDir = createValidFixture('valid-large-asar') const manyFiles = {} for (let i = 0; i < 3000; i += 1) { manyFiles[`node_modules/pkg-${i}/dist/index.js`] = { size: 128, offset: String(i * 128) } } writeFileSync( join(largeHeaderDir, 'win-unpacked', 'resources', 'app.asar'), buildSyntheticAsar({ files: manyFiles }) ) const largeResult = verifyInstallerReleaseDir({ releaseDir: largeHeaderDir, expectedVersion: version, publicKeyPem, requireSignature: true }) if (!largeResult.ok) throw new Error('self_test_large_asar_failed') const expectCaseError = (name, tamper, expectedCode) => { const dir = createValidFixture(name) tamper(dir) try { verifyInstallerReleaseDir({ releaseDir: dir, expectedVersion: version, publicKeyPem, requireSignature: true }) } catch (err) { if (err instanceof Error && err.message.includes(expectedCode)) return throw err } throw new Error(`installer_smoke_self_test_failed:${expectedCode}`) } expectCaseError( 'bad-pe', (dir) => writeFileSync(join(dir, installerName), Buffer.alloc(8192, 0x20)), 'installer_pe_invalid' ) expectCaseError( 'bad-sha512', (dir) => { const tampered = buildSyntheticPe(0x014c, 8192) tampered[500] = 0xff writeFileSync(join(dir, installerName), tampered) }, 'latest_yml_sha512_mismatch' ) expectCaseError( 'bad-version', (dir) => { const yml = readFileSync(join(dir, 'latest.yml'), 'utf8').replace(`version: ${version}`, 'version: 9.9.8') writeFileSync(join(dir, 'latest.yml'), yml) const sig = sign(null, Buffer.from(yml, 'utf8'), privateKey).toString('base64') writeFileSync(join(dir, 'latest.yml.sig'), `${sig}\n`) }, 'latest_yml_version_drift' ) expectCaseError( 'bad-blockmap', (dir) => writeFileSync(join(dir, `${installerName}.blockmap`), Buffer.from('not-a-gzip-stream')), 'blockmap_not_gzip' ) expectCaseError( 'bad-feed', (dir) => writeFileSync( join(dir, 'win-unpacked', 'resources', 'app-update.yml'), 'provider: generic\nurl: "https://evil.invalid/feed"\n' ), 'app_update_yml_feed_drift' ) expectCaseError( 'bad-asar', (dir) => writeFileSync(join(dir, 'win-unpacked', 'resources', 'app.asar'), Buffer.alloc(128, 0x7f)), 'app_asar_header_invalid' ) expectCaseError( 'bad-unpacked-arch', (dir) => writeFileSync(join(dir, 'win-unpacked', 'D3RO Voice.exe'), buildSyntheticPe(0x014c, 4096)), 'unpacked_exe_pe64_invalid' ) expectCaseError( 'bad-sig', (dir) => writeFileSync(join(dir, 'latest.yml.sig'), `${Buffer.alloc(64, 1).toString('base64')}\n`), 'manifest_signature_invalid' ) process.stdout.write('[release:installer:smoke] self-test GREEN (2 valid + 8 negative cases)\n') } finally { rmSync(sandbox, { recursive: true, force: true }) } } const args = process.argv.slice(2) if (args.includes('--self-test')) { runSelfTest() process.exit(0) } const dirIdx = args.indexOf('--dir') const productVersion = JSON.parse(readFileSync(join(root, 'release', 'product-version.json'), 'utf8')).version const targetDir = dirIdx !== -1 && args[dirIdx + 1] ? join(root, args[dirIdx + 1]) : join(root, 'apps', 'desktop', 'release', productVersion) const publicKeyPem = readFileSync(join(root, 'release', 'desktop-update-public.pem'), 'utf8') const summary = verifyInstallerReleaseDir({ releaseDir: targetDir, expectedVersion: productVersion, publicKeyPem, requireSignature: args.includes('--verify-signature') }) process.stdout.write(`${JSON.stringify(summary, null, 2)}\n`)