feat(release): one-command desktop release with Ed25519-signed update metadata

The installer is unsigned, so latest.yml is now signed with an Ed25519 key and the
app verifies the downloaded installer against it before installing.
npm run release -- patch|minor bumps, gates, tags, builds, signs, publishes,
re-verifies the public feed and pushes; --resume continues after a failure.
The retired GitLab registry publisher is removed.
This commit is contained in:
Yun Chan 2026-10-18 07:06:55 +09:00
parent f5ae4c8c04
commit fd9c97b7cc
21 changed files with 986 additions and 144 deletions

View file

@ -0,0 +1,73 @@
// scripts/ci/build-desktop-installer.mjs
// 데스크톱 NSIS 설치본(+ blockmap + latest.yml)을 apps/desktop/release/<version>/ 에 만든다.
// 로컬 릴리스(release-desktop.mjs)와 CI(release.yml)가 같은 빌드를 쓴다.
//
// 순서: electron-vite 빌드 → unpacked 트리 → 네이티브 ABI 보정·검증 → app-update.yml 보장
// → --prepackaged 로 설치본 (재빌드 없이 검증된 트리 그대로 포장)
//
// 로컬 AI 런타임(사이드카/ffmpeg)은 설치본에 넣지 않는다 — Cloudflare 업로드 한도(100MiB) 때문.
// 앱이 처음 필요할 때 runtime-latest 에서 받는다(RuntimeProvisioner, `npm run release:portable`).
//
// WIN_CSC_LINK 가 있으면 electron-builder 가 Authenticode 서명을 한다. 없으면 무서명 — 그 대신
// 게시 단계가 latest.yml 을 Ed25519 로 서명하고 앱이 검증한다(update-manifest-signature.mjs).
import { spawnSync } from 'node:child_process'
import { existsSync, readFileSync, readdirSync, rmSync, statSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
const root = join(dirname(fileURLToPath(import.meta.url)), '..', '..')
const desktopDir = join(root, 'apps', 'desktop')
/** Cloudflare 업로드 본문 한도 (실측: 110MiB → 413) */
const MAX_UPLOAD_BYTES = 100 * 1024 * 1024
const version = JSON.parse(readFileSync(join(root, 'release', 'product-version.json'), 'utf8')).version
const releaseDir = join(desktopDir, 'release', version)
const appDir = join(releaseDir, 'win-unpacked')
const builderFlags = ['--config', 'electron-builder.yml', '--publish', 'never', '-c.win.forceCodeSigning=false', '-c.npmRebuild=false']
// 같은 버전을 다시 빌드할 때 이전 산출물(휴대용 zip 등)이 섞여 게시되지 않게 비운다.
rmSync(releaseDir, { recursive: true, force: true })
run('npm', ['run', 'build', '--workspace=@d3ro/desktop'], root)
run('npx', ['electron-builder', '--win', 'dir', '--x64', ...builderFlags], desktopDir)
runNode('scripts/ci/fix-native-abi.mjs', ['--dir', appDir])
runNode('scripts/ci/verify-native-abi.mjs', ['--dir', appDir])
// app-update.yml 이 없으면 설치된 앱의 electron-updater 가 설정을 못 읽어 자동 업데이트가 죽는다.
runNode('scripts/ci/write-app-update-yml.mjs', ['--dir', appDir])
run('npx', ['electron-builder', '--prepackaged', appDir, '--win', 'nsis', '--x64', ...builderFlags], desktopDir)
const installer = readdirSync(releaseDir).find((name) => /-Setup-.*\.exe$/.test(name))
if (!installer) fail(`설치본이 없습니다: ${releaseDir}`)
for (const required of [`${installer}.blockmap`, 'latest.yml']) {
if (!existsSync(join(releaseDir, required))) fail(`${required} 가 없습니다: ${releaseDir}`)
}
if (!existsSync(join(appDir, 'resources', 'app-update.yml'))) fail('app-update.yml 누락')
if (!readFileSync(join(releaseDir, 'latest.yml'), 'utf8').includes(`version: ${version}`)) {
fail('latest.yml 의 버전이 product-version.json 과 다릅니다.')
}
const size = statSync(join(releaseDir, installer)).size
if (size > MAX_UPLOAD_BYTES) {
fail(
`설치본 ${(size / 1048576).toFixed(1)}MiB 가 업로드 한도 100MiB 를 넘습니다 — ` +
'런타임(사이드카/ffmpeg)을 electron-builder.yml 의 extraResources/files 에 다시 넣지 않았는지 확인하세요.',
)
}
process.stdout.write(`[build] ${installer} (${(size / 1048576).toFixed(1)}MiB) 준비 완료 — ${releaseDir}\n`)
function run(command, args, cwd) {
process.stdout.write(`[build] $ ${command} ${args.join(' ')}\n`)
const result = spawnSync(command, args, { cwd, stdio: 'inherit', shell: process.platform === 'win32' })
if (result.status !== 0) fail(`${command} ${args[0]} 실패 (exit ${result.status ?? 'null'})`)
}
function runNode(relativePath, args) {
process.stdout.write(`[build] $ node ${relativePath} ${args.join(' ')}\n`)
const result = spawnSync(process.execPath, [join(root, relativePath), ...args], { cwd: root, stdio: 'inherit' })
if (result.status !== 0) fail(`${relativePath} 실패 (exit ${result.status ?? 'null'})`)
}
function fail(message) {
process.stderr.write(`[build] ${message}\n`)
process.exit(1)
}

View file

@ -0,0 +1,46 @@
// scripts/ci/create-update-signing-key.mjs
// 업데이트 메타데이터 서명용 Ed25519 키를 한 번 만든다.
// - 비밀키 → 루트 .env 의 D3RO_UPDATE_SIGNING_KEY (이미 있으면 중단 — 키를 바꾸면 기존 앱이 새 릴리스를 거부한다)
// - 공개키 → release/desktop-update-public.pem
// 그 다음 공개키를 apps/desktop/src/main/update-signature.ts 의 UPDATE_SIGNING_PUBLIC_KEY 에 넣고,
// `npm run release:secrets` 로 Forgejo 시크릿에 동기화한다.
//
// 키를 잃어버리면 이 공개키를 내장한 설치본은 새 릴리스를 더는 받지 못한다(수동 재설치 필요).
// .env 백업이 유일한 복구 수단이다.
import { generateKeyPairSync } from 'node:crypto'
import { appendFileSync, existsSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { SIGNING_KEY_ENV, signManifest, verifyManifest } from './lib/update-manifest-signature.mjs'
const root = join(dirname(fileURLToPath(import.meta.url)), '..', '..')
const envPath = join(root, '.env')
const publicPath = join(root, 'release', 'desktop-update-public.pem')
const envText = existsSync(envPath) ? readFileSync(envPath, 'utf8') : ''
if (new RegExp(`^${SIGNING_KEY_ENV}=`, 'm').test(envText)) {
process.stderr.write(`[update-key] .env 에 ${SIGNING_KEY_ENV} 가 이미 있습니다 — 덮어쓰지 않습니다.\n`)
process.exit(1)
}
if (existsSync(publicPath)) {
process.stderr.write(`[update-key] ${publicPath} 가 이미 있습니다 — 덮어쓰지 않습니다.\n`)
process.exit(1)
}
const { privateKey, publicKey } = generateKeyPairSync('ed25519')
const publicPem = publicKey.export({ type: 'spki', format: 'pem' }).toString()
const probe = 'version: 0.0.0\n'
if (!verifyManifest(probe, signManifest(probe, privateKey), publicPem)) {
process.stderr.write('[update-key] 생성한 키 자체 검사 실패\n')
process.exit(1)
}
const privateB64 = privateKey.export({ type: 'pkcs8', format: 'der' }).toString('base64')
const separator = envText && !envText.endsWith('\n') ? '\n' : ''
appendFileSync(
envPath,
`${separator}\n# 데스크톱 업데이트 메타데이터 서명 키 (Ed25519, 잃어버리면 기존 앱이 새 릴리스를 거부)\n${SIGNING_KEY_ENV}=${privateB64}\n`,
)
writeFileSync(publicPath, publicPem, { flag: 'wx' })
process.stdout.write(`[update-key] 비밀키 → .env ${SIGNING_KEY_ENV}\n[update-key] 공개키 → ${publicPath}\n${publicPem}`)

View file

@ -0,0 +1,44 @@
// scripts/ci/lib/update-manifest-signature.mjs
// 업데이트 메타데이터(latest.yml) Ed25519 서명 — 게시 스크립트와 사후 검증이 같이 쓴다.
//
// 설치본에 Authenticode 서명이 없으면 electron-updater 는 서명 검증을 건너뛴다. 그래서 피드가
// 털리면 아무 설치 파일이나 배포될 수 있다. 대신 latest.yml 을 오프라인 키로 서명하고, 앱은 내장
// 공개키로 서명을 확인한 뒤 받은 설치 파일의 sha512 를 그 latest.yml 과 대조한다
// (apps/desktop/src/main/update-signature.ts).
//
// 비밀키: 환경변수 D3RO_UPDATE_SIGNING_KEY = PKCS8 DER 의 base64 한 줄 (.env 정본, Forgejo 시크릿 동기화).
// 공개키: release/desktop-update-public.pem (앱 내장 사본과 verify-release-metadata 가 대조).
import { createPrivateKey, createPublicKey, sign, verify } from 'node:crypto'
export const SIGNING_KEY_ENV = 'D3RO_UPDATE_SIGNING_KEY'
export const SIGNATURE_SUFFIX = '.sig'
export function loadSigningKey(env = process.env) {
const raw = env[SIGNING_KEY_ENV]?.trim()
if (!raw) {
throw new Error(
`${SIGNING_KEY_ENV} 가 없습니다 — 업데이트 메타데이터를 서명할 수 없습니다. ` +
'루트 .env 에 있는지 확인하세요 (처음이면 node scripts/ci/create-update-signing-key.mjs).',
)
}
const key = createPrivateKey({ key: Buffer.from(raw, 'base64'), format: 'der', type: 'pkcs8' })
if (key.asymmetricKeyType !== 'ed25519') throw new Error(`${SIGNING_KEY_ENV} 는 Ed25519 키여야 합니다.`)
return key
}
/** latest.yml 바이트에 대한 서명(base64 한 줄) */
export function signManifest(manifest, privateKey) {
return `${sign(null, Buffer.from(manifest), privateKey).toString('base64')}\n`
}
export function verifyManifest(manifest, signatureText, publicKeyPem) {
const signature = Buffer.from(String(signatureText).trim(), 'base64')
if (signature.length !== 64) return false
return verify(null, Buffer.from(manifest), createPublicKey(publicKeyPem), signature)
}
/** 비밀키에서 공개키 PEM — 게시 전에 저장소 공개키와 짝이 맞는지 확인할 때 쓴다 */
export function publicPemOf(privateKey) {
return createPublicKey(privateKey).export({ type: 'spki', format: 'pem' }).toString()
}

View file

@ -7,6 +7,10 @@
// - latest 경로: /api/packages/<owner>/generic/d3ro-voice/latest/<file> (electron-updater feed)
// 2) release/update-policy.json을 latest feed에 게시 (원격 정책/킬 스위치)
// 3) Forgejo Release 생성/갱신 + 설치 자산 첨부 (admin·site 다운로드 허브)
// 4) 공개 URL 에서 서명된 latest.yml 을 다시 받아 서명·설치본 해시를 검증 (기존 앱이 받을 그대로)
//
// latest.yml 은 Ed25519 로 서명해 latest.yml.sig 를 함께 올린다 (D3RO_UPDATE_SIGNING_KEY 필수).
// 무서명 설치본이라도 앱이 이 서명으로 설치 파일을 검증한다 — apps/desktop/src/main/update-signature.ts.
//
// 배포 순서 보장: 설치파일/blockmap을 먼저 올리고 update metadata(latest.yml)를
// 마지막에 게시한다. 기존 설치본이 배포 도중 404를 받지 않는다.
@ -19,7 +23,7 @@
import { createHash } from "node:crypto";
import { createReadStream, readFileSync } from "node:fs";
import { readFile, readdir, stat } from "node:fs/promises";
import { readFile, readdir, stat, writeFile } from "node:fs/promises";
import { basename, join } from "node:path";
import process from "node:process";
import { fileURLToPath, URL } from "node:url";
@ -38,6 +42,13 @@ import {
parseRuntimeMinVersions,
} from "./lib/runtime-feed-gate.mjs";
import { assertValidUpdatePolicy } from "./lib/update-policy-schema.mjs";
import {
SIGNATURE_SUFFIX,
loadSigningKey,
publicPemOf,
signManifest,
verifyManifest,
} from "./lib/update-manifest-signature.mjs";
const { forgejoAuthorization } = credentialHelpers;
@ -81,7 +92,25 @@ assertValidUpdatePolicy(readFileSync(policyPath), "release/update-policy.json");
const releaseDirectory = process.env.FORGEJO_RELEASE_DIR?.trim()
? process.env.FORGEJO_RELEASE_DIR.trim()
: fileURLToPath(new URL(`../../apps/desktop/release/${version}/`, import.meta.url));
const ASSET_PATTERN = /(\.exe|\.dmg|\.zip|\.blockmap|^(latest|beta|alpha)(-mac|-linux)?\.yml)$/;
// 같은 폴더에 휴대용 zip/7z·__uninstaller exe 가 섞일 수 있다 — 업데이트 자산만 고른다.
const ASSET_PATTERN = /(-Setup-[^/]*\.exe(\.blockmap)?|\.dmg|-mac\.zip(\.blockmap)?|^(latest|beta|alpha)(-mac|-linux)?\.yml(\.sig)?)$/;
// latest.yml 서명 — 키가 저장소 공개키와 짝이 아니면 앱이 거부할 릴리스이므로 아무것도 올리지 않는다.
const repoPublicKeyPem = readFileSync(
fileURLToPath(new URL("../../release/desktop-update-public.pem", import.meta.url)),
"utf8",
);
if (!dryRun || process.env.D3RO_UPDATE_SIGNING_KEY) {
const signingKey = loadSigningKey();
if (publicPemOf(signingKey).trim() !== repoPublicKeyPem.trim()) {
throw new Error("D3RO_UPDATE_SIGNING_KEY 가 release/desktop-update-public.pem 과 짝이 아닙니다.");
}
for (const name of await readdir(releaseDirectory)) {
if (!/^(latest|beta|alpha)(-mac|-linux)?\.yml$/.test(name)) continue;
const manifest = await readFile(join(releaseDirectory, name));
await writeFile(join(releaseDirectory, `${name}${SIGNATURE_SUFFIX}`), signManifest(manifest, signingKey));
}
}
const files = [];
for (const name of await readdir(releaseDirectory)) {
@ -96,6 +125,9 @@ if (!files.some((file) => file.name.endsWith(".exe"))) {
if (!files.some((file) => file.name === "latest.yml")) {
throw new Error(`latest.yml is missing for ${tag} — check electron-builder.yml publish config.`);
}
if (!dryRun && !files.some((file) => file.name === `latest.yml${SIGNATURE_SUFFIX}`)) {
throw new Error(`latest.yml${SIGNATURE_SUFFIX} is missing for ${tag}.`);
}
if (!files.some((file) => file.name.endsWith(".dmg"))) {
process.stdout.write(`WARNING: macOS artifacts missing for ${tag} — Windows-only release.\n`);
}
@ -195,7 +227,10 @@ if (latestFeed.update) {
await verifyPublicFile(`${packageVersionedUrl}/latest.yml`);
}
// 4) Forgejo Release 생성/갱신 + 자산 첨부
// 4) 기존 앱이 받을 그대로 검증 — 공개(무인증) 버전별 경로의 latest.yml + 서명 + 설치본 해시
await verifySignedPublicManifest();
// 5) Forgejo Release 생성/갱신 + 자산 첨부
const description = await buildReleaseDescription();
const releaseId = await upsertRelease(description);
for (const file of sorted) {
@ -236,7 +271,7 @@ function safeAssetName(name) {
}
function isUpdateMetadata(name) {
return /(?:\.blockmap$|^(?:latest|beta|alpha)(?:-mac|-linux)?\.yml$|^update-policy\.json$)/.test(name);
return /(?:\.blockmap$|^(?:latest|beta|alpha)(?:-mac|-linux)?\.yml(?:\.sig)?$|^update-policy\.json$)/.test(name);
}
function isYamlUpdateMetadata(name) {
@ -333,6 +368,31 @@ async function verifyPublicFile(url) {
if (!body.trim()) throw new Error(`Public updater file is empty: ${url}`);
}
async function verifySignedPublicManifest() {
const url = `${packageVersionedUrl}/latest.yml`;
const [manifestResponse, signatureResponse] = await Promise.all([
fetch(url, { cache: "no-store" }),
fetch(`${url}${SIGNATURE_SUFFIX}`, { cache: "no-store" }),
]);
if (!manifestResponse.ok || !signatureResponse.ok) {
throw new Error(
`Public signed manifest unreachable: latest.yml HTTP ${manifestResponse.status}, .sig HTTP ${signatureResponse.status}`,
);
}
const manifest = await manifestResponse.text();
if (!verifyManifest(manifest, await signatureResponse.text(), repoPublicKeyPem)) {
throw new Error(`Public ${url} signature does not verify with release/desktop-update-public.pem.`);
}
const signedSha512 = manifest.match(/^sha512:\s*(\S+)\s*$/m)?.[1];
const installer = sorted.find((file) => /-Setup-.*\.exe$/.test(file.name));
const localSha512 = createHash("sha512").update(await readFile(installer.path)).digest("base64");
if (signedSha512 !== localSha512) {
throw new Error(`Signed latest.yml sha512 does not match ${installer.name}.`);
}
process.stdout.write(` verified public signed manifest ${url}
`);
}
async function buildReleaseDescription() {
const changelog = await readFile(
fileURLToPath(new URL("../../CHANGELOG.md", import.meta.url)),

View file

@ -0,0 +1,283 @@
// scripts/ci/release-desktop.mjs
// 데스크톱 릴리스 한 줄 명령 — 버전 올리기부터 기존 사용자 자동 업데이트까지.
//
// npm run release -- patch # 1.9.0 → 1.9.1 (fix)
// npm run release -- minor # 1.9.0 → 1.10.0 (feat)
// npm run release -- 2.0.0 # 직접 지정
// npm run release -- minor --dry-run # 무엇을 할지만 출력
// npm run release -- --resume # 빌드/게시/푸시 중 실패했을 때 같은 버전으로 이어서
//
// 단계 (실패하면 거기서 멈추고, --resume 으로 이어 간다):
// 1. 점검 main 브랜치 · 깨끗한 작업 트리 · Forgejo 토큰 · 서명 키 짝 · 태그 미사용
// 2. 버전 product-version.json + sync-version --write + CHANGELOG 섹션(없으면 커밋 제목으로 초안)
// 3. 게이트 typecheck · version:check · release:metadata
// 4. 커밋 + annotated 태그 (로컬만 — 게시가 끝나야 푸시한다)
// 5. 빌드 build-desktop-installer.mjs
// 6. 게시 publish-forgejo-release.mjs (latest.yml Ed25519 서명 · 불변 버전 경로 · latest 피드 · 공개 URL 재검증)
// 7. 푸시 chanpaca main + 태그 (origin 미러는 실패해도 경고만)
//
// 태그는 불변이다. 게시된 버전에 문제가 있으면 더 높은 patch 로 다시 낸다.
import { spawnSync } from 'node:child_process'
import { existsSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { loadSigningKey, publicPemOf } from './lib/update-manifest-signature.mjs'
const root = join(dirname(fileURLToPath(import.meta.url)), '..', '..')
const args = process.argv.slice(2)
const dryRun = args.includes('--dry-run')
const resume = args.includes('--resume')
const bumpArg = args.find((arg) => !arg.startsWith('--'))
const CANONICAL_REMOTE = 'chanpaca'
const MIRROR_REMOTES = ['origin']
const FEED = 'https://git.chanpaca.net/api/packages/yunchan/generic/d3ro-voice'
const versionPath = join(root, 'release', 'product-version.json')
const changelogPath = join(root, 'CHANGELOG.md')
if (!resume && !bumpArg) {
fail('사용법: npm run release -- <patch|minor|major|X.Y.Z> [--dry-run] 또는 npm run release -- --resume')
}
// ── 1. 점검 ──
step('점검')
const branch = git(['rev-parse', '--abbrev-ref', 'HEAD'])
if (branch !== 'main') fail(`main 브랜치에서만 릴리스합니다 (현재 ${branch}).`)
if (!process.env.FORGEJO_TOKEN && !(process.env.FORGEJO_USERNAME && process.env.FORGEJO_PASSWORD)) {
fail('FORGEJO_TOKEN 이 없습니다 — 루트 .env 를 확인하세요.')
}
const repoPublicKey = readFileSync(join(root, 'release', 'desktop-update-public.pem'), 'utf8')
if (publicPemOf(loadSigningKey()).trim() !== repoPublicKey.trim()) {
fail('D3RO_UPDATE_SIGNING_KEY 가 release/desktop-update-public.pem 과 짝이 아닙니다.')
}
const dirty = git(['status', '--porcelain'])
if (dirty && !dryRun) fail(`작업 트리가 깨끗하지 않습니다 — 먼저 커밋하세요:\n${dirty}`)
const current = readJson(versionPath)
let version = current.version
if (resume) {
const tag = `v${version}`
if (!git(['tag', '--list', tag])) fail(`${tag} 태그가 없습니다 — 이어 갈 릴리스가 없습니다.`)
if (git(['rev-parse', `${tag}^{commit}`]) !== git(['rev-parse', 'HEAD'])) {
fail(`HEAD 가 ${tag} 가 아닙니다 — 태그 이후 커밋이 있으면 새 버전으로 릴리스하세요.`)
}
info(`${tag} 이어서 진행 (빌드 → 게시 → 푸시)`)
} else {
version = nextVersion(current.version, bumpArg)
const tag = `v${version}`
if (git(['tag', '--list', tag])) fail(`${tag} 태그가 이미 있습니다. 실패한 릴리스를 이어 가려면 --resume.`)
if (spawnGit(['ls-remote', '--exit-code', '--tags', CANONICAL_REMOTE, tag]).status === 0) {
fail(`${CANONICAL_REMOTE} 에 ${tag} 가 이미 있습니다.`)
}
if (await feedHasVersion(version)) fail(`피드에 ${version} 가 이미 게시돼 있습니다.`)
// ── 2. 버전 ──
step(`버전 ${current.version} → ${version}`)
const changelog = readFileSync(changelogPath, 'utf8')
const releaseDate = todayKst()
const notes = changelog.includes(`## [${version}] - `) ? null : draftNotes(current.version)
if (dryRun) {
info(notes ? `CHANGELOG 초안:\n${notes}` : 'CHANGELOG 섹션 있음')
info('단계: 커밋·태그 → 빌드 → 게시(서명) → 공개 URL 검증 → 푸시')
info('dry-run — 아무것도 바꾸지 않았습니다.')
process.exit(0)
}
writeFileSync(
versionPath,
`${JSON.stringify({ ...current, version, ...mobileBuildNumbers(version), releaseDate }, null, 2)}\n`,
)
if (notes) {
insertChangelogSection(version, releaseDate, notes)
} else {
// 손으로 쓴 섹션의 날짜만 오늘로 맞춘다.
writeFileSync(
changelogPath,
changelog.replace(new RegExp(`## \\[${escapeRegExp(version)}\\] - \\d{4}-\\d{2}-\\d{2}`), `## [${version}] - ${releaseDate}`),
)
}
ensurePlayChangelogs(mobileBuildNumbers(version).androidVersionCode)
runNode('scripts/ci/sync-version.mjs', ['--write'])
// ── 3. 게이트 ──
step('게이트')
runNpm(['run', 'version:check'])
runNpm(['run', 'release:metadata'])
runNpm(['run', 'typecheck'])
// 여기까지 실패하면 버전 파일만 바뀐 상태다 — git checkout -- . 로 되돌리고 다시 실행.
// ── 4. 커밋 + 태그 ──
step(`커밋 + 태그 ${tag}`)
gitInherit(['add', '-u'])
gitInherit(['commit', '-m', `chore(release): ${tag}`])
runNode('scripts/ci/create-release-tag.mjs', [])
}
const tag = `v${version}`
// 태그가 생긴 뒤의 실패는 --resume 으로 이어 간다.
const resumeHint = '\n고친 뒤 이어 가기: npm run release -- --resume'
// 이미 게시가 끝난 버전을 다시 빌드하면 바이트가 달라 불변 경로와 충돌한다 — 푸시만 남은 경우다.
if (resume && (await feedHasVersion(version))) {
info(`피드에 ${version} 가 이미 있습니다 — 빌드·게시를 건너뜁니다.`)
} else {
// ── 5. 빌드 ──
step('빌드')
runNode('scripts/ci/build-desktop-installer.mjs', [], {}, resumeHint)
// ── 6. 게시 ──
step('게시')
runNode('scripts/ci/publish-forgejo-release.mjs', [], { FORGEJO_RELEASE_TAG: tag }, resumeHint)
}
// ── 7. 푸시 ──
step('푸시')
// 게시는 끝났다 — 푸시 실패는 사용자 업데이트에 영향이 없고, 손으로 다시 밀면 된다.
const pushed = spawnSync('git', ['push', CANONICAL_REMOTE, 'main', tag], { cwd: root, stdio: 'inherit' })
if (pushed.status !== 0) warn(`${CANONICAL_REMOTE} 푸시 실패 — git push ${CANONICAL_REMOTE} main ${tag}`)
for (const remote of MIRROR_REMOTES) {
const result = spawnSync('git', ['push', remote, 'main', tag], { cwd: root, stdio: 'inherit' })
if (result.status !== 0) warn(`${remote} 미러 푸시 실패 — 나중에 git push ${remote} main ${tag}`)
}
step('완료')
info(`${tag} 게시 완료. 기존 설치본은 다음 업데이트 확인(시작 15초 뒤, 이후 4시간마다)에 받습니다.`)
info(`피드: ${FEED}/latest/latest.yml`)
// ── helpers ──
function nextVersion(from, bump) {
const [major, minor, patch] = from.split('.').map(Number)
if (bump === 'patch') return `${major}.${minor}.${patch + 1}`
if (bump === 'minor') return `${major}.${minor + 1}.0`
if (bump === 'major') return `${major + 1}.0.0`
if (/^\d+\.\d+\.\d+$/.test(bump)) {
const [a, b, c] = bump.split('.').map(Number)
if (a * 1e8 + b * 1e4 + c <= major * 1e8 + minor * 1e4 + patch) fail(`${bump} 는 ${from} 보다 높아야 합니다.`)
return bump
}
fail(`알 수 없는 버전 지정: ${bump} (patch|minor|major|X.Y.Z)`)
}
/** 1.9.0 → 1090000 (기존 규칙: major*1e6 + minor*1e4 + patch*1e2) */
function mobileBuildNumbers(next) {
const [major, minor, patch] = next.split('.').map(Number)
const code = major * 1_000_000 + minor * 10_000 + patch * 100
return { androidVersionCode: code, iosBuildNumber: code }
}
function draftNotes(previous) {
const subjects = git(['log', '--no-merges', '--format=%s', `v${previous}..HEAD`]).split('\n').filter(Boolean)
const groups = { Added: [], Fixed: [], Changed: [] }
for (const subject of subjects) {
const match = subject.match(/^(\w+)(?:\([^)]*\))?!?:\s*(.+)$/)
const type = match?.[1]
const text = match?.[2] ?? subject
if (type === 'feat') groups.Added.push(text)
else if (type === 'fix') groups.Fixed.push(text)
else if (type === 'perf' || type === 'refactor') groups.Changed.push(text)
}
const body = Object.entries(groups)
.filter(([, items]) => items.length > 0)
.map(([heading, items]) => `### ${heading}\n${items.map((item) => `- ${item}`).join('\n')}`)
.join('\n\n')
return body || '### Changed\n- Maintenance release.'
}
function insertChangelogSection(next, date, notes) {
const text = readFileSync(changelogPath, 'utf8')
const anchor = text.search(/\n## \[\d+\.\d+\.\d+\]/)
const section =
`\n## [${next}] - ${date}\n\n` +
'> Published from an annotated tag. Installer and update metadata are served by the\n' +
'> canonical Forgejo feed; no binaries are committed to this repository.\n\n' +
`${notes}\n`
writeFileSync(changelogPath, anchor === -1 ? `${text.trimEnd()}\n${section}` : `${text.slice(0, anchor)}\n${section}${text.slice(anchor)}`)
}
/**
* 모바일과 버전을 같이 쓰므로 release:metadata 가 새 versionCode 의 Play '새 기능' 문구를 요구한다.
* 데스크톱만 내는 릴리스면 일반 문구로 채운다 — 모바일을 실제로 낼 때 고쳐 쓴다.
*/
function ensurePlayChangelogs(versionCode) {
const texts = {
'ko-KR': '안정성과 성능을 개선했습니다.',
'en-US': 'Stability and performance improvements.',
}
for (const [locale, text] of Object.entries(texts)) {
const path = join(root, 'apps', 'mobile-rn', 'metadata', 'android', locale, 'changelogs', `${versionCode}.txt`)
if (!existsSync(path)) {
writeFileSync(path, `${text}\n`)
gitInherit(['add', path])
}
}
}
async function feedHasVersion(next) {
const response = await fetch(`${FEED}/${next}/latest.yml`, { cache: 'no-store' }).catch(() => null)
return Boolean(response?.ok)
}
function todayKst() {
return new Date(Date.now() + 9 * 3600_000).toISOString().slice(0, 10)
}
function escapeRegExp(value) {
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}
function readJson(path) {
return JSON.parse(readFileSync(path, 'utf8'))
}
function spawnGit(commandArgs) {
return spawnSync('git', commandArgs, { cwd: root, encoding: 'utf8' })
}
function git(commandArgs) {
const result = spawnGit(commandArgs)
if (result.status !== 0 && !(commandArgs[0] === 'tag' && commandArgs[1] === '--list')) {
fail(`git ${commandArgs.join(' ')} 실패: ${result.stderr?.trim() || `exit ${result.status}`}`)
}
return (result.stdout ?? '').trim()
}
function gitInherit(commandArgs) {
const result = spawnSync('git', commandArgs, { cwd: root, stdio: 'inherit' })
if (result.status !== 0) fail(`git ${commandArgs.join(' ')} 실패 (exit ${result.status ?? 'null'})`)
}
function runNpm(commandArgs) {
info(`$ npm ${commandArgs.join(' ')}`)
const result = spawnSync('npm', commandArgs, { cwd: root, stdio: 'inherit', shell: process.platform === 'win32' })
if (result.status !== 0) fail(`npm ${commandArgs.join(' ')} 실패 (exit ${result.status ?? 'null'})`)
}
function runNode(relativePath, scriptArgs, env = {}, hint = '') {
info(`$ node ${relativePath} ${scriptArgs.join(' ')}`)
const result = spawnSync(process.execPath, [join(root, relativePath), ...scriptArgs], {
cwd: root,
stdio: 'inherit',
env: { ...process.env, ...env },
})
if (result.status !== 0) fail(`${relativePath} 실패 (exit ${result.status ?? 'null'})${hint}`)
}
function step(name) {
process.stdout.write(`\n[release] ── ${name} ──\n`)
}
function info(message) {
process.stdout.write(`[release] ${message}\n`)
}
function warn(message) {
process.stdout.write(`[release] 경고: ${message}\n`)
}
function fail(message) {
process.stderr.write(`[release] ${message}\n`)
process.exit(1)
}

View file

@ -30,7 +30,7 @@ const SECRETS = [
{ name: 'FORGEJO_TOKEN', envKey: 'FORGEJO_TOKEN', required: true, usedBy: 'release.yml, portable.yml' },
{ name: 'WIN_CSC_LINK', envKey: 'WIN_CSC_LINK', required: false, usedBy: 'release.yml' },
{ name: 'WIN_CSC_KEY_PASSWORD', envKey: 'WIN_CSC_KEY_PASSWORD', required: false, usedBy: 'release.yml' },
{ name: 'WIN_CSC_EXPECTED_SIGNER_SUBJECT', envKey: 'WIN_CSC_EXPECTED_SIGNER_SUBJECT', required: false, usedBy: 'release.yml' },
{ name: 'D3RO_UPDATE_SIGNING_KEY', envKey: 'D3RO_UPDATE_SIGNING_KEY', required: true, usedBy: 'release.yml' },
]
const LOCAL_HOST = /^(https?:\/\/)?(localhost|127\.|0\.0\.0\.0|\[::1\]|host\.docker\.internal)/i

View file

@ -0,0 +1,46 @@
#!/usr/bin/env bash
# scripts/ci/setup-nas-cron-runner.sh
# NAS 에 d3ro-voice 저장소 전용 Forgejo 러너(라벨 `nas`)를 띄운다.
#
# 왜: linux-builder 러너는 노트북 한 대뿐이라 노트북이 꺼지면 payple-renew 크론도
# 멈춘다(GAP-CI-02). 상시 켜진 NAS 에서 크론을 돌린다. 기존 NAS 러너
# (forgejo-runner, 다른 저장소 전용)는 건드리지 않는다.
#
# 사용 (루트에서): bash scripts/ci/setup-nas-cron-runner.sh
# 필요: 루트 .env 의 FORGEJO_TOKEN, ssh 별칭 yunchan-nas.
# 되돌리기: ssh yunchan-nas 'docker rm -f d3ro-nas-runner && rm -rf /volume1/docker/d3ro-nas-runner'
# 후 Forgejo 저장소 설정 > Actions > Runners 에서 d3ro-nas 삭제.
set -euo pipefail
cd "$(dirname "$0")/../.."
token=$(grep '^FORGEJO_TOKEN=' .env | cut -d= -f2- | tr -d '"')
[ -n "$token" ] || { echo "FORGEJO_TOKEN 이 .env 에 없습니다." >&2; exit 1; }
reg=$(curl -fsS -m 15 -H "Authorization: token $token" \
"https://git.chanpaca.net/api/v1/repos/yunchan/d3ro-voice/actions/runners/registration-token" |
node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>process.stdout.write(JSON.parse(s).token))')
# 등록 토큰은 명령줄에 남기지 않고 stdin 으로 넘긴다.
printf '%s\n' "$reg" | ssh -o BatchMode=yes yunchan-nas '
export PATH=$PATH:/usr/local/bin
set -e
read -r RT
D=/volume1/docker/d3ro-nas-runner
IMG=code.forgejo.org/forgejo/runner:6
# 기존 forgejo-runner 와 같이 root 로 돈다. 기본 사용자(1000)는 Synology ACL 에 막혀 .runner 를 못 쓴다.
if docker ps -a --format "{{.Names}}" | grep -qx d3ro-nas-runner; then
echo "d3ro-nas-runner 가 이미 있습니다."; docker ps --filter name=d3ro-nas-runner; exit 0
fi
mkdir -p "$D"
[ -f "$D/config.yml" ] || grep -v A_TEST_ENV /volume1/docker/forgejo-runner/config.yml > "$D/config.yml"
[ -f "$D/.runner" ] || docker run --rm -u 0:0 -v "$D:/data" -w /data "$IMG" forgejo-runner register \
--no-interactive --config /data/config.yml --instance http://192.168.0.39:3000 \
--token "$RT" --name d3ro-nas --labels "nas:docker://node:22-bookworm"
docker run -d --name d3ro-nas-runner --restart unless-stopped -u 0:0 \
-v "$D:/data" -v /var/run/docker.sock:/var/run/docker.sock -w /data -e HOME=/data \
"$IMG" forgejo-runner daemon --config /data/config.yml >/dev/null
sleep 6
docker ps --filter name=d3ro-nas-runner --format "{{.Names}} {{.Status}}"
docker logs --tail 4 d3ro-nas-runner 2>&1
'

View file

@ -7,9 +7,6 @@ const root = join(dirname(fileURLToPath(import.meta.url)), '..', '..')
// canonical updater feed: Forgejo Generic Package Registry
const CANONICAL_UPDATE_FEED =
'https://git.chanpaca.net/api/packages/yunchan/generic/d3ro-voice/latest'
// legacy mirror: GitLab Generic Registry (pre-Forgejo installs still poll this)
const LEGACY_UPDATE_FEED =
'https://gitlab.twentyoz.kr:8443/api/v4/projects/1172/packages/generic/d3ro-voice/latest'
function read(path) {
return readFileSync(join(root, path), 'utf8')
@ -31,7 +28,9 @@ function loadSurfaces(readSurface = read) {
updatePolicySource: readSurface('apps/desktop/src/main/update-policy.ts'),
updateService: readSurface('apps/desktop/src/main/services/UpdateService.ts'),
updateAdapters: readSurface('apps/desktop/src/main/services/update-adapters.ts'),
publisher: readSurface('scripts/ci/publish-gitlab-release.mjs'),
updateSignature: readSurface('apps/desktop/src/main/update-signature.ts'),
updatePublicKey: readSurface('release/desktop-update-public.pem'),
releaseCommand: readSurface('scripts/ci/release-desktop.mjs'),
forgejoPublisher: readSurface('scripts/ci/publish-forgejo-release.mjs'),
gitlab: readSurface('.gitlab-ci.yml'),
forgejoRelease: readSurface('.forgejo/workflows/release.yml'),
@ -128,12 +127,35 @@ function validate(surfaces) {
// ── canonical feed contract: runtime == builder == Forgejo canonical ──
const sourceFeed = surfaces.updateFeed.match(/UPDATE_FEED_URL\s*=\s*\n?\s*['"]([^'"]+)['"]/)?.[1]
const legacyFeed = surfaces.updateFeed.match(/LEGACY_UPDATE_FEED_URL\s*=\s*\n?\s*['"]([^'"]+)['"]/)?.[1]
const builderFeed = surfaces.builder.match(/publish:\s*[\s\S]*?\n\s+url:\s*["']([^"']+)["']/)?.[1]
fail(sourceFeed === CANONICAL_UPDATE_FEED, 'desktop_runtime_update_feed_drift')
fail(builderFeed === CANONICAL_UPDATE_FEED, 'desktop_builder_update_feed_drift')
fail(!/\/releases\/\d+\.\d+\.\d+/.test(sourceFeed ?? ''), 'desktop_update_feed_version_pinned')
fail(legacyFeed === LEGACY_UPDATE_FEED, 'desktop_legacy_mirror_feed_missing')
fail(!surfaces.updateFeed.includes('gitlab'), 'desktop_legacy_gitlab_feed_reintroduced')
// ── 업데이트 메타데이터 Ed25519 서명: 앱 내장 공개키 == 저장소 공개키, 앱이 실제로 검증 ──
const embeddedKey = surfaces.updateSignature.match(/UPDATE_SIGNING_PUBLIC_KEY = `([^`]+)`/)?.[1]?.trim()
let updateKeyValid = false
try {
updateKeyValid = createPublicKey(surfaces.updatePublicKey).asymmetricKeyType === 'ed25519'
} catch {
updateKeyValid = false
}
fail(updateKeyValid, 'update_signing_public_key_invalid')
fail(embeddedKey === surfaces.updatePublicKey.trim(), 'update_signing_public_key_drift')
fail(surfaces.updateAdapters.includes('verifyDownloadedUpdate('), 'update_signature_verification_missing')
fail(
surfaces.forgejoPublisher.includes('signManifest(') && surfaces.forgejoPublisher.includes('verifySignedPublicManifest()'),
'forgejo_publisher_manifest_signing_missing',
)
fail(surfaces.forgejoRelease.includes('D3RO_UPDATE_SIGNING_KEY'), 'forgejo_release_signing_key_missing')
// 로컬 한 줄 명령과 CI 예비 경로가 같은 빌드·게시 스크립트를 써야 한다
fail(
surfaces.releaseCommand.includes('build-desktop-installer.mjs') &&
surfaces.releaseCommand.includes('publish-forgejo-release.mjs') &&
surfaces.forgejoRelease.includes('build-desktop-installer.mjs'),
'release_paths_diverged',
)
// ── update policy SSOT ──
const policy = surfaces.updatePolicy
@ -183,12 +205,6 @@ function validate(surfaces) {
'update_service_differential_control_missing',
)
// ── legacy GitLab publisher (mirror) ──
fail(surfaces.publisher.includes('const latestFiles = [...sortedFiles].sort'), 'publisher_asset_first_order_missing')
fail(!surfaces.publisher.includes('deletePackagesForVersion("latest")'), 'publisher_deletes_live_feed_first')
fail(surfaces.publisher.includes('verifyPublicLatestFile'), 'publisher_public_metadata_verification_missing')
fail(surfaces.publisher.includes('release/product-version.json'), 'publisher_product_version_gate_missing')
// ── canonical Forgejo publisher contract ──
fail(!/1\.0\.0/.test(surfaces.forgejoPublisher), 'forgejo_publisher_hardcoded_version')
fail(surfaces.forgejoPublisher.includes('release/product-version.json'), 'forgejo_publisher_version_gate_missing')
@ -243,7 +259,6 @@ function validate(surfaces) {
androidVersionCode: metadata.androidVersionCode,
iosBuildNumber: metadata.iosBuildNumber,
updateFeed: sourceFeed,
legacyUpdateFeed: legacyFeed,
updateChannel: policy.defaultChannel,
minimumSupportedVersion: policy.minimumSupportedVersion,
electronVersion: lockedElectron,
@ -282,9 +297,16 @@ if (process.argv.includes('--self-test')) {
expectRejected(
surfaces,
(candidate) => {
candidate.updateFeed = candidate.updateFeed.replace(LEGACY_UPDATE_FEED, 'https://example.invalid/legacy')
candidate.updatePublicKey = candidate.desktopLicensePublicKey
},
'desktop_legacy_mirror_feed_missing',
'update_signing_public_key_drift',
)
expectRejected(
surfaces,
(candidate) => {
candidate.updateAdapters = candidate.updateAdapters.replaceAll('verifyDownloadedUpdate(', 'skipVerification(')
},
'update_signature_verification_missing',
)
expectRejected(
surfaces,
@ -345,9 +367,9 @@ if (process.argv.includes('--self-test')) {
expectRejected(
surfaces,
(candidate) => {
candidate.publisher = candidate.publisher.replace('const latestFiles = [...sortedFiles].sort', 'const latestFiles = sortedFiles.sort')
candidate.forgejoPublisher = candidate.forgejoPublisher.replaceAll('signManifest(', 'noSign(')
},
'publisher_asset_first_order_missing',
'forgejo_publisher_manifest_signing_missing',
)
expectRejected(
surfaces,
@ -385,7 +407,7 @@ if (process.argv.includes('--self-test')) {
if (!missingDesktopKeyRejected) {
throw new Error('release_metadata_self_test_failed:desktop_license_public_key_missing')
}
result.negativeCases = 14
result.negativeCases = 16
}
process.stdout.write(`${JSON.stringify(result, null, 2)}\n`)