import { BrowserWindow, ipcMain } from 'electron' import { CLOCK_CALIBRATION_DEFAULTS, type ClockCalibrationSettings, type ClockEstimate, type ClockSample, type TimingTestRequest, type TimingTestResult, } from '../../src/type/reservation' import { disposeKeyescapeTransport, edgeBrowserHeaders, requestKeyescape, setKeyescapeTransportMode, } from './keyescape-http' import { appendClockSample, computePlannedSendAtMs, estimateClock, observationToSample } from './server-clock-core' const CLOCK_EVENT = 'reservation:clock-state' const BASE_INTERVAL_MS = 5_000 const NEAR_INTERVAL_MS = 1_000 const FINAL_INTERVAL_MS = 250 function headerValue(value: string | string[] | undefined) { return Array.isArray(value) ? value.join(', ') : value } function broadcast(channel: string, value: unknown) { for (const window of BrowserWindow.getAllWindows()) { if (!window.isDestroyed()) window.webContents.send(channel, value) } } export class ServerClockService { private samples: ClockSample[] = [] private sequence = 0 private timer?: NodeJS.Timeout private inFlight?: Promise private userMonitoring = false private autoTargetServerTimeMs?: number private lastError?: string private settings: ClockCalibrationSettings = { ...CLOCK_CALIBRATION_DEFAULTS } private precisionBoundaryServerMs?: number private quietUntilMs = 0 getEstimate(): ClockEstimate { const estimate = estimateClock(this.samples, Date.now(), this.isRunning(), this.settings) if (this.lastError && estimate.quality !== 'unavailable') { estimate.warning = this.lastError if (estimate.quality === 'good') estimate.quality = 'fair' } return estimate } configure(input: ClockCalibrationSettings) { const integer = (value: number, minimum: number, maximum: number, fallback: number) => Number.isFinite(value) ? Math.round(Math.min(maximum, Math.max(minimum, value))) : fallback const requiredBoundaryCount = integer(input.requiredBoundaryCount, 3, 12, CLOCK_CALIBRATION_DEFAULTS.requiredBoundaryCount) const transportMode = input.transportMode === 'http2' ? 'http2' : 'http1' const transportChanged = setKeyescapeTransportMode(transportMode) this.settings = { transportMode, enabled: Boolean(input.enabled), autoApply: Boolean(input.autoApply), scanWindowMs: integer(input.scanWindowMs, 100, 450, CLOCK_CALIBRATION_DEFAULTS.scanWindowMs), probeIntervalMs: integer(input.probeIntervalMs, 25, 200, CLOCK_CALIBRATION_DEFAULTS.probeIntervalMs), initialBoundarySpacingSec: integer(input.initialBoundarySpacingSec, 1, 10, CLOCK_CALIBRATION_DEFAULTS.initialBoundarySpacingSec), requiredBoundaryCount, historySize: integer(input.historySize, requiredBoundaryCount, 30, Math.max(requiredBoundaryCount, CLOCK_CALIBRATION_DEFAULTS.historySize)), maxBoundarySpreadMs: integer(input.maxBoundarySpreadMs, 30, 500, CLOCK_CALIBRATION_DEFAULTS.maxBoundarySpreadMs), maxProbeRttMs: integer(input.maxProbeRttMs, 100, 1_500, CLOCK_CALIBRATION_DEFAULTS.maxProbeRttMs), maintenanceIntervalSec: integer(input.maintenanceIntervalSec, 5, 120, CLOCK_CALIBRATION_DEFAULTS.maintenanceIntervalSec), sampleWindowSize: integer(input.sampleWindowSize, 60, 600, CLOCK_CALIBRATION_DEFAULTS.sampleWindowSize), } this.samples = transportChanged ? [] : this.samples.slice(-this.settings.sampleWindowSize) this.precisionBoundaryServerMs = undefined if (transportChanged) this.lastError = `${transportMode === 'http2' ? 'HTTP/2 단일 세션' : 'HTTP/1.1 keep-alive'} 모드로 전환해 시간을 다시 보정합니다.` this.emit() this.scheduleNext() return this.getEstimate() } async start() { this.userMonitoring = true await this.probeNow().catch(() => undefined) this.scheduleNext() return this.getEstimate() } stop() { this.userMonitoring = false this.scheduleNext() this.emit() return this.getEstimate() } setAutoTarget(targetServerTimeMs?: number) { if (this.autoTargetServerTimeMs !== undefined && targetServerTimeMs === undefined) { this.quietUntilMs = Date.now() + 500 } this.autoTargetServerTimeMs = targetServerTimeMs if (targetServerTimeMs) void this.probeNow().catch(() => undefined) this.scheduleNext() } async ensureSample() { if (this.getEstimate().acceptedSamples === 0) await this.probeNow() return this.getEstimate() } async probeNow(): Promise { if (this.inFlight) return this.inFlight this.inFlight = this.performProbe().finally(() => { this.inFlight = undefined }) return this.inFlight } private async performProbe(): Promise { try { const response = await requestKeyescape({ method: 'HEAD', path: `/?clock_probe=${Date.now()}-${this.sequence + 1}`, headers: { ...edgeBrowserHeaders({ referer: 'https://www.keyescape.com/' }), 'Cache-Control': 'no-cache, no-store, max-age=0', Pragma: 'no-cache', }, timeoutMs: 5_000, }) const sample = observationToSample({ id: ++this.sequence, sentAtMs: response.sentAtMs, receivedAtMs: response.receivedAtMs, rttMs: response.rttMs, serverDateHeader: headerValue(response.headers.date), remoteIp: response.remoteIp, reusedSocket: response.reusedSocket, protocol: response.protocol, connectionId: response.connectionId, ageHeader: headerValue(response.headers.age), viaHeader: headerValue(response.headers.via), cacheHeader: headerValue(response.headers['x-cache']), statusCode: response.statusCode, }) if (sample.accepted && sample.rttMs > this.settings.maxProbeRttMs) { sample.accepted = false sample.rejectionReason = `설정된 최대 RTT ${this.settings.maxProbeRttMs}ms 초과` } const previousEstimate = this.getEstimate() const previousIp = previousEstimate.remoteIp const previousConnectionId = previousEstimate.connectionId this.samples = appendClockSample(this.samples, sample, this.settings.sampleWindowSize) if (sample.accepted && previousIp && sample.remoteIp !== previousIp) this.precisionBoundaryServerMs = undefined else if (sample.accepted && response.protocol === 'h2' && previousConnectionId && response.connectionId !== previousConnectionId) { this.precisionBoundaryServerMs = undefined this.lastError = `HTTP/2 세션이 ${previousConnectionId}에서 ${response.connectionId}로 교체되어 같은 경로에서 재검증 중입니다.` } else this.lastError = undefined this.emit() return sample } catch (error) { this.lastError = error instanceof Error ? error.message : '서버시간 측정에 실패했습니다.' this.emit() throw error } finally { this.scheduleNext() } } async runTimingTest(request: TimingTestRequest): Promise { if (!Number.isFinite(request.targetServerTimeMs)) throw new Error('테스트 목표 시각이 올바르지 않습니다.') if (!Number.isFinite(request.userOffsetMs) || Math.abs(request.userOffsetMs) > 5_000) { throw new Error('오프셋은 -5000ms에서 +5000ms 사이여야 합니다.') } const estimate = await this.ensureSample() const plannedSendAtMs = computePlannedSendAtMs(request.targetServerTimeMs, request.userOffsetMs, estimate) const delay = plannedSendAtMs - Date.now() if (delay < 150 || delay > 60_000) throw new Error('시간 테스트는 0.15초에서 60초 이내의 미래 시각만 사용할 수 있습니다.') await new Promise((resolve) => setTimeout(resolve, delay)) const estimateAtSend = this.getEstimate() const sample = await this.probeNow() const estimatedArrivalServerMs = sample.sentAtMs + estimateAtSend.offsetMs + sample.rttMs / 2 const effectiveTarget = request.targetServerTimeMs + request.userOffsetMs return { targetServerTimeMs: request.targetServerTimeMs, plannedSendAtMs, actualSendAtMs: sample.sentAtMs, estimatedArrivalServerMs, arrivalErrorMs: estimatedArrivalServerMs - effectiveTarget, schedulerJitterMs: sample.sentAtMs - plannedSendAtMs, rttMs: sample.rttMs, uncertaintyMs: estimateAtSend.uncertaintyMs, remoteIp: sample.remoteIp, reusedSocket: sample.reusedSocket, protocol: sample.protocol, connectionId: sample.connectionId, } } dispose() { this.userMonitoring = false this.autoTargetServerTimeMs = undefined if (this.timer) clearTimeout(this.timer) this.timer = undefined this.samples = [] this.precisionBoundaryServerMs = undefined disposeKeyescapeTransport() } private isRunning() { return this.userMonitoring || this.autoTargetServerTimeMs !== undefined } private regularInterval() { if (!this.autoTargetServerTimeMs) return BASE_INTERVAL_MS const estimate = this.getEstimate() const remaining = this.autoTargetServerTimeMs - estimate.estimatedServerTimeMs if (remaining <= 2_000) return FINAL_INTERVAL_MS if (remaining <= 15_000) return NEAR_INTERVAL_MS return BASE_INTERVAL_MS } private precisionInterval() { if (!this.settings.enabled || this.getEstimate().acceptedSamples === 0) return Number.POSITIVE_INFINITY const now = Date.now() let estimate = this.getEstimate() // The first Date sample has an unknown phase within its one-second bucket. // Scan continuously only until one transition is found, then probe narrowly // around predicted boundaries to avoid permanent high request rates. if (estimate.boundaryCount === 0) return Math.max(75, this.settings.probeIntervalMs) if (this.precisionBoundaryServerMs === undefined) { const boundaryBasedServerNow = now + (estimate.boundaryOffsetMs ?? estimate.offsetMs) this.precisionBoundaryServerMs = Math.ceil((boundaryBasedServerNow + this.settings.scanWindowMs + 25) / 1_000) * 1_000 } let localBoundary = this.precisionBoundaryServerMs - (estimate.boundaryOffsetMs ?? estimate.offsetMs) while (now > localBoundary + this.settings.scanWindowMs) { const spacingSec = estimate.calibrationReady ? this.settings.maintenanceIntervalSec : this.settings.initialBoundarySpacingSec this.precisionBoundaryServerMs += spacingSec * 1_000 estimate = this.getEstimate() localBoundary = this.precisionBoundaryServerMs - (estimate.boundaryOffsetMs ?? estimate.offsetMs) } const scanStartsAt = localBoundary - this.settings.scanWindowMs if (now < scanStartsAt) return Math.max(10, scanStartsAt - now) return this.settings.probeIntervalMs } private nextInterval() { if (this.quietUntilMs > Date.now()) return this.quietUntilMs - Date.now() return Math.min(this.regularInterval(), this.precisionInterval()) } private scheduleNext() { if (this.timer) clearTimeout(this.timer) this.timer = undefined if (!this.isRunning()) return this.timer = setTimeout(() => void this.probeNow().catch(() => undefined), this.nextInterval()) } private emit() { broadcast(CLOCK_EVENT, this.getEstimate()) } } export const serverClock = new ServerClockService() export function registerClockHandlers() { const safe = async (task: () => T | Promise) => { try { return { ok: true, data: await task() } } catch (error) { return { ok: false, error: error instanceof Error ? error.message : '시간 기능 오류가 발생했습니다.' } } } ipcMain.handle('reservation:clock-start', () => safe(() => serverClock.start())) ipcMain.handle('reservation:clock-stop', () => safe(() => serverClock.stop())) ipcMain.handle('reservation:clock-get', () => safe(() => serverClock.getEstimate())) ipcMain.handle('reservation:clock-configure', (_event, settings: ClockCalibrationSettings) => safe(() => serverClock.configure(settings))) ipcMain.handle('reservation:clock-test', (_event, request: TimingTestRequest) => safe(() => serverClock.runTimingTest(request))) }