The tree carried uncommitted work from several areas (web push, mobile screens, admin charts, test-hygiene cleanup, CI and map docs). It is landed as one commit so the release pipeline can start from a clean tree; the desktop transcript-correction behaviour shipped in the previous commit and is unchanged here.
271 lines
11 KiB
TypeScript
271 lines
11 KiB
TypeScript
// 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 { getMainWindow, getPopupTranslator } from '../windows/WindowManager'
|
|
import { UPDATE_FEED_URL, UPDATE_POLICY_URL, versionedManifestUrl } from '../update-feed'
|
|
import { verifyDownloadedUpdate } from '../update-signature'
|
|
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
|
|
/** 서명된 latest.yml fetch 타임아웃 */
|
|
const MANIFEST_FETCH_TIMEOUT_MS = 15_000
|
|
|
|
async function fetchText(url: string): Promise<string> {
|
|
const response = await fetch(url, { cache: 'no-store', signal: AbortSignal.timeout(MANIFEST_FETCH_TIMEOUT_MS) })
|
|
if (!response.ok) throw new Error(`HTTP ${response.status} ${url}`)
|
|
return response.text()
|
|
}
|
|
|
|
/**
|
|
* NsisUpdater 는 받은 파일을 넘기기 전에 `verifySignature(path)` 를 부르고, 문자열을 돌려받으면
|
|
* 파일을 지우고 ERR_UPDATER_INVALID_SIGNATURE 로 실패한다. 무서명 앱에선 이 단계가 아무것도 안 하므로
|
|
* 우리 Ed25519 검증으로 바꿔 끼운다. 라이브러리가 이 지점을 없애면 업데이트를 받지 않는다(fail-closed).
|
|
*/
|
|
function installManifestVerifier(
|
|
updater: import('electron-updater').AppUpdater,
|
|
offeredVersion: () => string | null,
|
|
): boolean {
|
|
const target = updater as unknown as { verifySignature?: (path: string) => Promise<string | null> }
|
|
if (typeof target.verifySignature !== 'function') return false
|
|
target.verifySignature = async (installerPath: string): Promise<string | null> => {
|
|
const version = offeredVersion()
|
|
if (!version) return '받으려던 버전을 알 수 없음'
|
|
const rejection = await verifyDownloadedUpdate({
|
|
version,
|
|
installerPath,
|
|
fetchText,
|
|
manifestUrl: versionedManifestUrl(version),
|
|
})
|
|
if (rejection) logger.error(`업데이트 v${version} 설치 거부 — ${rejection}`)
|
|
else logger.info(`업데이트 v${version} 서명 확인 완료`)
|
|
return rejection
|
|
}
|
|
return true
|
|
}
|
|
|
|
/** 실행 중인 설치본의 형태를 파일 시스템에서 읽는다 (판단은 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
|
|
}
|
|
|
|
let offeredVersion: string | null = null
|
|
// macOS 는 Squirrel.Mac 이 앱 코드 서명을 직접 요구하므로 이 검증은 Windows(NSIS) 전용이다.
|
|
if (process.platform === 'win32' && !installManifestVerifier(updater, () => offeredVersion)) {
|
|
logger.error('electron-updater 에 설치 파일 검증 지점(verifySignature)이 없음 — 자동 업데이트 비활성')
|
|
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) => {
|
|
offeredVersion = info.version
|
|
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 기반 프롬프터. 문구는 현재 앱 로케일의 update.dialog.* 키에서 가져온다. */
|
|
export function createDialogPrompter(): UpdatePrompter {
|
|
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 t = getPopupTranslator()
|
|
const notesText =
|
|
typeof releaseNotes === 'string'
|
|
? `\n\n${t('update.dialog.releaseNotesHeading')}\n${releaseNotes}`
|
|
: ''
|
|
const mandatoryNote = mandatory ? `\n\n${t('update.dialog.mandatoryNote')}` : ''
|
|
|
|
if (mandatory) {
|
|
const response = await show({
|
|
type: 'info',
|
|
title: t('update.dialog.requiredTitle'),
|
|
message: `${t('update.dialog.requiredMessage', { version })}${mandatoryNote}${notesText}`,
|
|
buttons: [t('update.dialog.updateNow')],
|
|
defaultId: 0,
|
|
cancelId: -1,
|
|
})
|
|
return response === 0 ? 'download' : 'later'
|
|
}
|
|
|
|
const response = await show({
|
|
type: 'info',
|
|
title: t('update.dialog.availableTitle'),
|
|
message: `${t('update.dialog.availableMessage', { version })}${notesText}`,
|
|
buttons: [
|
|
t('update.dialog.downloadNow'),
|
|
t('update.dialog.later'),
|
|
t('update.dialog.skipVersion'),
|
|
],
|
|
defaultId: 0,
|
|
cancelId: 1,
|
|
})
|
|
if (response === 0) return 'download'
|
|
if (response === 2) return 'skip'
|
|
return 'later'
|
|
},
|
|
|
|
async askRestart(version, { mandatory }): Promise<RestartAnswer> {
|
|
const t = getPopupTranslator()
|
|
if (mandatory) {
|
|
// 필수 업데이트는 미룰 수 없다 — 작업을 마칠 시간만 주고, 닫아도 재시작한다.
|
|
await show({
|
|
type: 'warning',
|
|
title: t('update.dialog.requiredInstallTitle'),
|
|
message: t('update.dialog.requiredRestartMessage', { version }),
|
|
buttons: [t('update.dialog.restartInstallNow')],
|
|
defaultId: 0,
|
|
cancelId: 0,
|
|
})
|
|
return 'restart'
|
|
}
|
|
const response = await show({
|
|
type: 'info',
|
|
title: t('update.dialog.readyTitle'),
|
|
message: t('update.dialog.readyMessage', { version }),
|
|
buttons: [t('update.dialog.restartInstallNow'), t('update.dialog.installOnExit')],
|
|
defaultId: 0,
|
|
cancelId: 1,
|
|
})
|
|
return response === 0 ? 'restart' : 'later'
|
|
},
|
|
}
|
|
}
|