fix(update): re-evaluate policy on every update transition and skip NSIS updater on portable installs

This commit is contained in:
Yun Chan 2026-09-28 02:16:18 +09:00
parent a4acb42573
commit 88f3dbcd69
11 changed files with 1216 additions and 307 deletions

View file

@ -0,0 +1,237 @@
// src/main/services/update-adapters.ts
// UpdateService 포트의 기본 구현 (electron-updater / fetch / electron dialog).
// 게이팅 판단은 여기 두지 않는다 — update-policy.ts · update-session.ts 가 정하고 UpdateService 가 실행한다.
import { existsSync, readdirSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { app, dialog } from 'electron'
import { getLogger } from './LoggerService'
import { configGet } from './ConfigService'
import { getMainWindow } from '../windows/WindowManager'
import { UPDATE_FEED_URL, UPDATE_POLICY_URL } from '../update-feed'
import { DEFAULT_UPDATE_POLICY, parseUpdatePolicy, type UpdatePolicy } from '../update-policy'
import { PORTABLE_INSTALL_MARKER, detectInstallKind, type InstallProbe } from '../install-kind'
import type {
ConsentAnswer,
PolicySource,
RestartAnswer,
UpdatePrompter,
UpdaterEventHandlers,
UpdaterPort,
} from './update-ports'
const logger = getLogger('UpdateService')
/** 원격 정책 fetch 타임아웃 */
const POLICY_FETCH_TIMEOUT_MS = 8_000
/** 실행 중인 설치본의 형태를 파일 시스템에서 읽는다 (판단은 detectInstallKind). */
function probeInstall(): InstallProbe {
const exeDir = dirname(process.execPath)
let exeDirEntries: string[] = []
try {
exeDirEntries = readdirSync(exeDir)
} catch (err) {
logger.warn(`설치 디렉터리 확인 실패(${exeDir}): ${err instanceof Error ? err.message : String(err)}`)
}
return {
platform: process.platform,
exeDirEntries,
hasPortableMarker: existsSync(join(process.resourcesPath, PORTABLE_INSTALL_MARKER)),
portableExecutableDir: process.env.PORTABLE_EXECUTABLE_DIR,
}
}
export function createElectronUpdater(handlers: UpdaterEventHandlers): UpdaterPort | null {
if (!app.isPackaged) {
logger.info('dev 실행 — 자동 업데이트 비활성')
return null
}
if (process.platform !== 'win32' && process.platform !== 'darwin') {
logger.info(`플랫폼 ${process.platform} — 자동 업데이트 미지원`)
return null
}
if (!UPDATE_FEED_URL) {
logger.info('UPDATE_FEED_URL 미설정 — 자동 업데이트 비활성')
return null
}
// Scoop·설치 스크립트·zip 해제본에서 NSIS 설치자를 돌리면 다른 경로에 두 번째 사본이 깔리고
// 실행 중인 사본은 옛 버전으로 남는다. 이런 설치본의 업데이트는 Scoop/설치 스크립트가 맡는다.
const install = detectInstallKind(probeInstall())
if (install.kind === 'portable') {
logger.info(`휴대용 설치본(${install.reason}) — 내장 자동 업데이트 비활성 (Scoop/설치 스크립트로 업데이트)`)
return null
}
let updater: import('electron-updater').AppUpdater
try {
// eslint-disable-next-line @typescript-eslint/no-require-imports
updater = (require('electron-updater') as typeof import('electron-updater')).autoUpdater
} catch (err) {
logger.warn(
`electron-updater 로드 실패 — 자동 업데이트 비활성: ${err instanceof Error ? err.message : String(err)}`,
)
return null
}
updater.setFeedURL({ provider: 'generic', url: UPDATE_FEED_URL })
// 사용자 인가를 위해 자동 다운로드는 비활성화 (동의 시 downloadUpdate 호출)
updater.autoDownload = false
// 받아 둔 설치 파일이 정책상 철회되면 UpdateService 가 setAutoInstallOnQuit(false) 로 내린다.
updater.autoInstallOnAppQuit = true
updater.logger = {
info: (msg: unknown) => logger.info(String(msg)),
warn: (msg: unknown) => logger.warn(String(msg)),
error: (msg: unknown) => logger.error(String(msg)),
debug: (msg: unknown) => logger.debug(String(msg)),
}
updater.on('checking-for-update', () => handlers.onChecking())
updater.on('update-available', (info) => handlers.onAvailable(info))
updater.on('update-not-available', (info) => handlers.onNotAvailable(info.version))
updater.on('download-progress', (progress) =>
handlers.onProgress({
percent: progress.percent,
bytesPerSecond: progress.bytesPerSecond,
transferred: progress.transferred,
total: progress.total,
}),
)
updater.on('update-downloaded', (info) => handlers.onDownloaded(info.version))
updater.on('error', (err) => handlers.onError(err.message))
return {
checkForUpdates: () => updater.checkForUpdates(),
downloadUpdate: () => updater.downloadUpdate(),
quitAndInstall: (isSilent, isForceRunAfter) => updater.quitAndInstall(isSilent, isForceRunAfter),
setChannel: (channel, allowPrerelease) => {
updater.channel = channel
updater.allowPrerelease = allowPrerelease
},
setDifferentialDisabled: (disabled) => {
// NSIS 이외 업데이터는 이 속성을 무시한다
;(updater as unknown as { disableDifferentialDownload?: boolean }).disableDifferentialDownload = disabled
},
setAutoInstallOnQuit: (enabled) => {
updater.autoInstallOnAppQuit = enabled
},
}
}
/** 원격 정책 공급원 — 실패하면 마지막으로 성공한 정책, 그것도 없으면 내장 기본값 */
export function createRemotePolicySource(
url: string | null | undefined = UPDATE_POLICY_URL,
fetchImpl: typeof fetch = (input, init) => fetch(input, init),
): PolicySource {
let lastGood: UpdatePolicy | null = null
return {
async load(): Promise<UpdatePolicy> {
if (!url) return lastGood ?? DEFAULT_UPDATE_POLICY
try {
const response = await fetchImpl(url, {
cache: 'no-store',
signal: AbortSignal.timeout(POLICY_FETCH_TIMEOUT_MS),
})
if (!response.ok) throw new Error(`HTTP ${response.status}`)
lastGood = parseUpdatePolicy(await response.json())
logger.info(
`원격 업데이트 정책 적용 — min=${lastGood.minimumSupportedVersion}, killSwitch=${lastGood.killSwitch}, staging=${lastGood.stagingPercentage}%`,
)
return lastGood
} catch (err) {
// 네트워크 실패 시 마지막 정책(없으면 내장 기본값)으로 fail-open (업데이트 자체는 계속).
logger.debug(
`원격 업데이트 정책 로드 실패 — ${lastGood ? '마지막 정책 유지' : '내장 기본값 사용'}: ${err instanceof Error ? err.message : String(err)}`,
)
return lastGood ?? DEFAULT_UPDATE_POLICY
}
},
}
}
/**
* electron dialog 기반 프롬프터.
* TODO(i18n): 문구가 아직 ko/en 인라인이다 — update.* 키를 locale 파일에 추가한 뒤 t() 로 옮긴다.
*/
export function createDialogPrompter(): UpdatePrompter {
const isKorean = (): boolean => (configGet('language') as string | undefined)?.startsWith('ko') ?? true
const show = async (options: Electron.MessageBoxOptions): Promise<number> => {
const win = getMainWindow()
const { response } =
win && !win.isDestroyed()
? await dialog.showMessageBox(win, options)
: await dialog.showMessageBox(options)
return response
}
return {
async askConsent({ version, releaseNotes, mandatory }): Promise<ConsentAnswer> {
const isKo = isKorean()
const notesText = typeof releaseNotes === 'string' ? `\n\n[주요 변경사항]\n${releaseNotes}` : ''
const mandatoryNote = mandatory
? isKo
? '\n\n이 업데이트는 필수입니다 (지원 종료 버전).'
: '\n\nThis update is required (end of support).'
: ''
if (mandatory) {
const response = await show({
type: 'info',
title: isKo ? '필수 업데이트' : 'Required Update',
message: isKo
? `D3RO Voice v${version} 업데이트가 필요합니다.${mandatoryNote}${notesText}`
: `D3RO Voice v${version} is required.${mandatoryNote}${notesText}`,
buttons: isKo ? ['지금 업데이트'] : ['Update Now'],
defaultId: 0,
cancelId: -1,
})
return response === 0 ? 'download' : 'later'
}
const response = await show({
type: 'info',
title: isKo ? '새 버전 업데이트' : 'Software Update',
message: isKo
? `D3RO Voice v${version} 새 버전이 출시되었습니다. 지금 다운로드할까요?${notesText}`
: `A new version of D3RO Voice (v${version}) is available. Would you like to download it now?${notesText}`,
buttons: isKo
? ['지금 다운로드', '나중에', '이 버전 건너뛰기']
: ['Download Now', 'Later', 'Skip This Version'],
defaultId: 0,
cancelId: 1,
})
if (response === 0) return 'download'
if (response === 2) return 'skip'
return 'later'
},
async askRestart(version, { mandatory }): Promise<RestartAnswer> {
const isKo = isKorean()
if (mandatory) {
// 필수 업데이트는 미룰 수 없다 — 작업을 마칠 시간만 주고, 닫아도 재시작한다.
await show({
type: 'warning',
title: isKo ? '필수 업데이트 설치' : 'Required Update',
message: isKo
? `D3RO Voice v${version} 필수 업데이트가 준비되었습니다. 확인을 누르면 앱을 재시작하여 설치합니다.`
: `Required update D3RO Voice v${version} is ready. The app will restart to install it when you continue.`,
buttons: isKo ? ['지금 재시작 및 설치'] : ['Restart & Install Now'],
defaultId: 0,
cancelId: 0,
})
return 'restart'
}
const response = await show({
type: 'info',
title: isKo ? '업데이트 준비 완료' : 'Update Ready',
message: isKo
? `D3RO Voice v${version} 다운로드가 완료되었습니다. 지금 앱을 재시작하여 설치를 완료할까요?`
: `D3RO Voice v${version} has been downloaded. Restart now to complete installation?`,
buttons: isKo ? ['지금 재시작 및 설치', '종료 시 자동 설치'] : ['Restart & Install Now', 'Install on Exit'],
defaultId: 0,
cancelId: 1,
})
return response === 0 ? 'restart' : 'later'
},
}
}