first commit
This commit is contained in:
1 parent
18d31d5dcf
commit
77a5f5248c
31 files changed
+6637
-30
No files matched your search
@@ -0,0 +1,274 @@
|
||||
import { app, BrowserWindow, ipcMain } from 'electron'
|
||||
import type {
|
||||
AutoReservationConfig,
|
||||
AutoReservationSnapshot,
|
||||
AutoReservationState,
|
||||
ReservationRequest,
|
||||
} from '../../src/type/reservation'
|
||||
import { executeReservation } from './reservation'
|
||||
import { serverClock } from './server-clock'
|
||||
import { computePlannedSendAtMs } from './server-clock-core'
|
||||
import type { ClockEstimate } from '../../src/type/reservation'
|
||||
|
||||
const AUTO_EVENT = 'reservation:auto-state'
|
||||
const MAX_TOKEN_TARGET_AGE_MS = 90_000
|
||||
const MAX_LATE_FIRE_MS = 1_000
|
||||
|
||||
function broadcast(value: AutoReservationState) {
|
||||
for (const window of BrowserWindow.getAllWindows()) {
|
||||
if (!window.isDestroyed()) window.webContents.send(AUTO_EVENT, value)
|
||||
}
|
||||
}
|
||||
|
||||
function snapshot(request: ReservationRequest): AutoReservationSnapshot {
|
||||
return {
|
||||
branchNum: request.branchNum,
|
||||
themeNum: request.themeNum,
|
||||
themeInfoNum: request.themeInfoNum,
|
||||
date: request.date,
|
||||
timeNum: request.timeNum,
|
||||
timeLabel: request.timeLabel,
|
||||
themeName: request.themeName,
|
||||
totalPrice: request.totalPrice,
|
||||
person: request.person,
|
||||
}
|
||||
}
|
||||
|
||||
function cloneRequest(request: ReservationRequest): ReservationRequest {
|
||||
return {
|
||||
branchNum: request.branchNum,
|
||||
themeNum: request.themeNum,
|
||||
themeInfoNum: request.themeInfoNum,
|
||||
date: request.date,
|
||||
timeNum: request.timeNum,
|
||||
timeLabel: request.timeLabel,
|
||||
themeName: request.themeName,
|
||||
totalPrice: request.totalPrice,
|
||||
person: request.person,
|
||||
name: request.name,
|
||||
phone: request.phone,
|
||||
captchaToken: request.captchaToken,
|
||||
}
|
||||
}
|
||||
|
||||
export class AutoReservationService {
|
||||
private config?: AutoReservationConfig
|
||||
private timer?: NodeJS.Timeout
|
||||
private expectedTickAtMs = 0
|
||||
private frozenTiming?: { plannedSendAtMs: number; offsetMs: number; oneWayMs: number }
|
||||
private state: AutoReservationState = { status: 'idle', tokenStatus: 'empty' }
|
||||
|
||||
constructor(
|
||||
private readonly clock: {
|
||||
ensureSample(): Promise<ClockEstimate>
|
||||
getEstimate(): ClockEstimate
|
||||
setAutoTarget(targetServerTimeMs?: number): void
|
||||
} = serverClock,
|
||||
private readonly execute: (request: ReservationRequest) => Promise<Awaited<ReturnType<typeof executeReservation>>> = executeReservation,
|
||||
private readonly emitState: (state: AutoReservationState) => void = broadcast,
|
||||
) {}
|
||||
|
||||
getState() {
|
||||
return this.state
|
||||
}
|
||||
|
||||
async arm(input: AutoReservationConfig) {
|
||||
if (this.state.status === 'armed' || this.state.status === 'firing') {
|
||||
throw new Error('이미 자동 예약이 무장되어 있습니다.')
|
||||
}
|
||||
if (!Number.isFinite(input.targetServerTimeMs)) throw new Error('실행 시각이 올바르지 않습니다.')
|
||||
if (!Number.isFinite(input.userOffsetMs) || input.userOffsetMs < -5_000 || input.userOffsetMs > 5_000) {
|
||||
throw new Error('사용자 오프셋은 -5000ms에서 +5000ms 사이여야 합니다.')
|
||||
}
|
||||
if (!Number.isFinite(input.captchaPastedAtMs) || input.captchaPastedAtMs > Date.now()) {
|
||||
throw new Error('캡차 토큰 입력 시각이 올바르지 않습니다.')
|
||||
}
|
||||
if (input.request.captchaToken.trim().length < 30) throw new Error('캡차 토큰을 입력해주세요.')
|
||||
const estimate = await this.clock.ensureSample()
|
||||
if (estimate.acceptedSamples === 0) throw new Error('유효한 서버시간 표본이 없어 자동 예약을 무장할 수 없습니다.')
|
||||
if (input.targetServerTimeMs <= estimate.estimatedServerTimeMs + 150) {
|
||||
throw new Error('실행 시각은 현재 관측 서버시각보다 최소 0.15초 이후여야 합니다.')
|
||||
}
|
||||
const targetLocalTimeMs = input.targetServerTimeMs - estimate.offsetMs
|
||||
const tokenAgeAtTargetMs = targetLocalTimeMs - input.captchaPastedAtMs
|
||||
if (tokenAgeAtTargetMs < 0 || tokenAgeAtTargetMs > MAX_TOKEN_TARGET_AGE_MS) {
|
||||
throw new Error('캡차 토큰 입력 후 90초 이내의 실행 시각만 무장할 수 있습니다.')
|
||||
}
|
||||
|
||||
this.config = {
|
||||
request: cloneRequest(input.request),
|
||||
targetServerTimeMs: input.targetServerTimeMs,
|
||||
userOffsetMs: input.userOffsetMs,
|
||||
captchaPastedAtMs: input.captchaPastedAtMs,
|
||||
}
|
||||
this.frozenTiming = undefined
|
||||
this.state = {
|
||||
status: 'armed',
|
||||
targetServerTimeMs: input.targetServerTimeMs,
|
||||
userOffsetMs: input.userOffsetMs,
|
||||
armedAtMs: Date.now(),
|
||||
captchaPastedAtMs: input.captchaPastedAtMs,
|
||||
tokenStatus: 'ready',
|
||||
snapshot: snapshot(input.request),
|
||||
warning: estimate.quality === 'poor' || (estimate.calibrationSettings.enabled && !estimate.calibrationReady) ? estimate.warning : undefined,
|
||||
}
|
||||
this.clock.setAutoTarget(input.targetServerTimeMs)
|
||||
this.emit()
|
||||
this.scheduleTick(0)
|
||||
return this.state
|
||||
}
|
||||
|
||||
disarm(message = '자동 예약이 해제되었습니다.') {
|
||||
if (this.state.status === 'firing') return this.state
|
||||
if (this.timer) clearTimeout(this.timer)
|
||||
this.timer = undefined
|
||||
this.frozenTiming = undefined
|
||||
this.config = undefined
|
||||
this.clock.setAutoTarget(undefined)
|
||||
this.state = { status: 'cancelled', tokenStatus: 'empty', message }
|
||||
this.emit()
|
||||
return this.state
|
||||
}
|
||||
|
||||
reset() {
|
||||
if (this.timer) clearTimeout(this.timer)
|
||||
this.timer = undefined
|
||||
this.frozenTiming = undefined
|
||||
this.config = undefined
|
||||
this.clock.setAutoTarget(undefined)
|
||||
this.state = { status: 'idle', tokenStatus: 'empty' }
|
||||
this.emit()
|
||||
}
|
||||
|
||||
private scheduleTick(delayMs: number) {
|
||||
if (this.timer) clearTimeout(this.timer)
|
||||
const normalizedDelay = Math.max(0, delayMs)
|
||||
this.expectedTickAtMs = Date.now() + normalizedDelay
|
||||
this.timer = setTimeout(() => void this.tick(), normalizedDelay)
|
||||
}
|
||||
|
||||
private tick() {
|
||||
if (this.state.status !== 'armed' || !this.config) return
|
||||
const tickLateMs = Math.max(0, Date.now() - this.expectedTickAtMs)
|
||||
const estimate = this.clock.getEstimate()
|
||||
if (estimate.acceptedSamples === 0) {
|
||||
this.failBeforeSend('유효한 서버시간 표본이 없어 제출하지 않았습니다.', 'empty')
|
||||
return
|
||||
}
|
||||
|
||||
const plannedSendAtMs = this.frozenTiming?.plannedSendAtMs ?? computePlannedSendAtMs(
|
||||
this.config.targetServerTimeMs, this.config.userOffsetMs, estimate,
|
||||
)
|
||||
const remainingMs = plannedSendAtMs - Date.now()
|
||||
const effectiveTarget = this.config.targetServerTimeMs + this.config.userOffsetMs
|
||||
if (estimate.estimatedServerTimeMs > effectiveTarget + MAX_LATE_FIRE_MS) {
|
||||
this.failBeforeSend('절전 또는 지연으로 목표 시각이 지나 제출하지 않았습니다.', 'ready')
|
||||
return
|
||||
}
|
||||
if (remainingMs < 0 && tickLateMs > 250) {
|
||||
this.failBeforeSend('절전 또는 스케줄러 정지 후 목표 시각이 지나 제출하지 않았습니다.', 'ready')
|
||||
return
|
||||
}
|
||||
|
||||
this.state = {
|
||||
...this.state,
|
||||
warning: estimate.quality === 'poor' || (estimate.calibrationSettings.enabled && !estimate.calibrationReady) ? estimate.warning : undefined,
|
||||
timeline: { ...this.state.timeline, plannedSendAtMs },
|
||||
}
|
||||
this.emit()
|
||||
|
||||
if (remainingMs > 100) {
|
||||
this.scheduleTick(Math.min(1_000, Math.max(10, remainingMs - 100)))
|
||||
return
|
||||
}
|
||||
if (!this.frozenTiming) {
|
||||
this.frozenTiming = { plannedSendAtMs, offsetMs: estimate.offsetMs, oneWayMs: estimate.oneWayMs }
|
||||
this.clock.setAutoTarget(undefined)
|
||||
}
|
||||
if (remainingMs > 0) {
|
||||
this.scheduleTick(remainingMs)
|
||||
return
|
||||
}
|
||||
if (remainingMs >= -MAX_LATE_FIRE_MS) void this.fire(this.frozenTiming.offsetMs, this.frozenTiming.oneWayMs)
|
||||
else this.failBeforeSend('스케줄러 지연으로 목표 시각을 놓쳐 제출하지 않았습니다.', 'ready')
|
||||
}
|
||||
|
||||
private async fire(offsetMs: number, oneWayMs: number) {
|
||||
if (this.state.status !== 'armed' || !this.config) return
|
||||
const config = this.config
|
||||
this.config = undefined
|
||||
if (this.timer) clearTimeout(this.timer)
|
||||
this.timer = undefined
|
||||
this.frozenTiming = undefined
|
||||
this.state = { ...this.state, status: 'firing', tokenStatus: 'consumed' }
|
||||
this.emit()
|
||||
|
||||
try {
|
||||
const result = await this.execute(config.request)
|
||||
const transport = result.transport
|
||||
const estimatedArrivalServerMs = transport
|
||||
? transport.sentAtMs + offsetMs + oneWayMs
|
||||
: undefined
|
||||
const effectiveTarget = config.targetServerTimeMs + config.userOffsetMs
|
||||
this.state = {
|
||||
...this.state,
|
||||
status: result.success ? 'succeeded' : 'failed',
|
||||
message: result.message,
|
||||
result,
|
||||
timeline: {
|
||||
...this.state.timeline,
|
||||
actualSendAtMs: transport?.sentAtMs,
|
||||
estimatedArrivalServerMs,
|
||||
arrivalErrorMs: estimatedArrivalServerMs === undefined ? undefined : estimatedArrivalServerMs - effectiveTarget,
|
||||
rttMs: transport?.rttMs,
|
||||
httpStatus: transport?.httpStatus,
|
||||
remoteIp: transport?.remoteIp,
|
||||
reusedSocket: transport?.reusedSocket,
|
||||
},
|
||||
}
|
||||
} catch (error) {
|
||||
this.state = {
|
||||
...this.state,
|
||||
status: 'failed',
|
||||
message: error instanceof Error ? error.message : '자동 예약 요청에 실패했습니다.',
|
||||
}
|
||||
} finally {
|
||||
this.clock.setAutoTarget(undefined)
|
||||
this.emit()
|
||||
}
|
||||
}
|
||||
|
||||
private failBeforeSend(message: string, tokenStatus: AutoReservationState['tokenStatus']) {
|
||||
if (this.timer) clearTimeout(this.timer)
|
||||
this.timer = undefined
|
||||
this.frozenTiming = undefined
|
||||
this.config = undefined
|
||||
this.clock.setAutoTarget(undefined)
|
||||
this.state = { ...this.state, status: 'failed', tokenStatus, message }
|
||||
this.emit()
|
||||
}
|
||||
|
||||
private emit() {
|
||||
this.emitState(this.state)
|
||||
}
|
||||
}
|
||||
|
||||
export const autoReservation = new AutoReservationService()
|
||||
|
||||
export function registerAutoReservationHandlers() {
|
||||
const safe = async <T>(task: () => T | Promise<T>) => {
|
||||
try {
|
||||
return { ok: true, data: await task() }
|
||||
} catch (error) {
|
||||
return { ok: false, error: error instanceof Error ? error.message : '자동 예약 오류가 발생했습니다.' }
|
||||
}
|
||||
}
|
||||
ipcMain.handle('reservation:auto-arm', (_event, config: AutoReservationConfig) => safe(() => autoReservation.arm(config)))
|
||||
ipcMain.handle('reservation:auto-disarm', () => safe(() => autoReservation.disarm()))
|
||||
ipcMain.handle('reservation:auto-get', () => safe(() => autoReservation.getState()))
|
||||
ipcMain.on('reservation:renderer-unload', () => autoReservation.reset())
|
||||
app.once('before-quit', () => {
|
||||
autoReservation.reset()
|
||||
serverClock.dispose()
|
||||
})
|
||||
}
|
||||
+10
-1
@@ -4,6 +4,7 @@ import { fileURLToPath } from 'node:url'
|
||||
import path from 'node:path'
|
||||
import os from 'node:os'
|
||||
import { update } from './update'
|
||||
import './reservation-register'
|
||||
|
||||
const require = createRequire(import.meta.url)
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url))
|
||||
@@ -45,7 +46,13 @@ const indexHtml = path.join(RENDERER_DIST, 'index.html')
|
||||
|
||||
async function createWindow() {
|
||||
win = new BrowserWindow({
|
||||
title: 'Main window',
|
||||
title: 'ESCAPE / RESERVE',
|
||||
width: 1280,
|
||||
height: 860,
|
||||
minWidth: 960,
|
||||
minHeight: 720,
|
||||
backgroundColor: '#090909',
|
||||
show: false,
|
||||
icon: path.join(process.env.VITE_PUBLIC, 'favicon.ico'),
|
||||
webPreferences: {
|
||||
preload,
|
||||
@@ -66,6 +73,8 @@ async function createWindow() {
|
||||
win.loadFile(indexHtml)
|
||||
}
|
||||
|
||||
win.once('ready-to-show', () => win?.show())
|
||||
|
||||
// Test actively push message to the Electron-Renderer
|
||||
win.webContents.on('did-finish-load', () => {
|
||||
win?.webContents.send('main-process-message', new Date().toLocaleString())
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
import https from 'node:https'
|
||||
import { performance } from 'node:perf_hooks'
|
||||
import { randomBytes } from 'node:crypto'
|
||||
|
||||
const HOSTNAME = 'www.keyescape.com'
|
||||
|
||||
export const EDGE_USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/151.0.0.0 Safari/537.36 Edg/151.0.0.0'
|
||||
|
||||
export interface EdgeHeaderOptions {
|
||||
accept?: string
|
||||
referer?: string
|
||||
navigation?: boolean
|
||||
xhr?: boolean
|
||||
}
|
||||
|
||||
export function edgeBrowserHeaders(options: EdgeHeaderOptions = {}): Record<string, string> {
|
||||
const headers: Record<string, string> = {
|
||||
Accept: options.accept ?? (options.navigation
|
||||
? 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8'
|
||||
: '*/*'),
|
||||
'Accept-Language': 'ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7',
|
||||
'User-Agent': EDGE_USER_AGENT,
|
||||
'Sec-CH-UA': '"Not=A?Brand";v="99", "Microsoft Edge";v="151", "Chromium";v="151"',
|
||||
'Sec-CH-UA-Mobile': '?0',
|
||||
'Sec-CH-UA-Platform': '"Windows"',
|
||||
'Sec-Fetch-Site': 'same-origin',
|
||||
'Sec-Fetch-Mode': options.navigation ? 'navigate' : 'cors',
|
||||
'Sec-Fetch-Dest': options.navigation ? 'document' : 'empty',
|
||||
}
|
||||
if (options.navigation) {
|
||||
headers['Sec-Fetch-User'] = '?1'
|
||||
headers['Upgrade-Insecure-Requests'] = '1'
|
||||
}
|
||||
if (options.xhr) headers['X-Requested-With'] = 'XMLHttpRequest'
|
||||
if (options.referer) headers.Referer = options.referer
|
||||
return headers
|
||||
}
|
||||
|
||||
export const keyescapeAgent = new https.Agent({
|
||||
keepAlive: true,
|
||||
keepAliveMsecs: 15_000,
|
||||
maxSockets: 2,
|
||||
maxFreeSockets: 2,
|
||||
scheduling: 'lifo',
|
||||
})
|
||||
|
||||
export interface KeyescapeResponse {
|
||||
statusCode: number
|
||||
headers: https.IncomingHttpHeaders
|
||||
body: Buffer
|
||||
sentAtMs: number
|
||||
receivedAtMs: number
|
||||
sentMonoMs: number
|
||||
receivedMonoMs: number
|
||||
rttMs: number
|
||||
remoteIp: string
|
||||
reusedSocket: boolean
|
||||
}
|
||||
|
||||
export interface KeyescapeRequestOptions {
|
||||
method: 'GET' | 'HEAD' | 'POST'
|
||||
path: string
|
||||
headers?: Record<string, string>
|
||||
body?: Buffer
|
||||
timeoutMs?: number
|
||||
}
|
||||
|
||||
export function requestKeyescape(options: KeyescapeRequestOptions): Promise<KeyescapeResponse> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const sentAtMs = Date.now()
|
||||
const sentMonoMs = performance.now()
|
||||
let remoteIp = ''
|
||||
|
||||
const request = https.request({
|
||||
hostname: HOSTNAME,
|
||||
port: 443,
|
||||
method: options.method,
|
||||
path: options.path,
|
||||
agent: keyescapeAgent,
|
||||
headers: {
|
||||
...edgeBrowserHeaders(),
|
||||
Connection: 'keep-alive',
|
||||
...options.headers,
|
||||
},
|
||||
}, (response) => {
|
||||
const receivedAtMs = Date.now()
|
||||
const receivedMonoMs = performance.now()
|
||||
const chunks: Buffer[] = []
|
||||
response.on('data', (chunk: Buffer) => chunks.push(Buffer.from(chunk)))
|
||||
response.on('end', () => {
|
||||
resolve({
|
||||
statusCode: response.statusCode ?? 0,
|
||||
headers: response.headers,
|
||||
body: Buffer.concat(chunks),
|
||||
sentAtMs,
|
||||
receivedAtMs,
|
||||
sentMonoMs,
|
||||
receivedMonoMs,
|
||||
rttMs: receivedMonoMs - sentMonoMs,
|
||||
remoteIp,
|
||||
reusedSocket: request.reusedSocket,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
request.setTimeout(options.timeoutMs ?? 12_000, () => {
|
||||
request.destroy(new Error('예약 서버 응답 시간이 초과되었습니다.'))
|
||||
})
|
||||
request.on('socket', (socket) => {
|
||||
const captureAddress = () => { remoteIp = socket.remoteAddress ?? remoteIp }
|
||||
socket.once('connect', captureAddress)
|
||||
socket.once('secureConnect', captureAddress)
|
||||
if (socket.remoteAddress) captureAddress()
|
||||
})
|
||||
request.on('error', reject)
|
||||
if (options.body) request.write(options.body)
|
||||
request.end()
|
||||
})
|
||||
}
|
||||
|
||||
export function encodeMultipart(fields: Record<string, string>) {
|
||||
const boundary = `----WebKitFormBoundary${randomBytes(12).toString('base64url').slice(0, 16)}`
|
||||
const chunks: Buffer[] = []
|
||||
for (const [name, value] of Object.entries(fields)) {
|
||||
chunks.push(Buffer.from(
|
||||
`--${boundary}\r\nContent-Disposition: form-data; name="${name.replaceAll('"', '')}"\r\n\r\n${value}\r\n`,
|
||||
'utf8',
|
||||
))
|
||||
}
|
||||
chunks.push(Buffer.from(`--${boundary}--\r\n`, 'utf8'))
|
||||
return { boundary, body: Buffer.concat(chunks) }
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { registerReservationHandlers } from './reservation'
|
||||
import { registerAutoReservationHandlers } from './auto-reservation'
|
||||
import { registerClockHandlers } from './server-clock'
|
||||
|
||||
registerReservationHandlers()
|
||||
registerClockHandlers()
|
||||
registerAutoReservationHandlers()
|
||||
@@ -0,0 +1,370 @@
|
||||
import { ipcMain, shell } from 'electron'
|
||||
import type {
|
||||
Branch,
|
||||
PriceOption,
|
||||
ReservationRequest,
|
||||
ReservationResult,
|
||||
ReservationSelection,
|
||||
Theme,
|
||||
ThemeDetail,
|
||||
TimeSlot,
|
||||
} from '../../src/type/reservation'
|
||||
import { edgeBrowserHeaders, encodeMultipart, requestKeyescape } from './keyescape-http'
|
||||
|
||||
const BASE_URL = 'https://www.keyescape.com'
|
||||
const API_URL = `${BASE_URL}/controller/run_proc.php`
|
||||
const REQUEST_TIMEOUT_MS = 12_000
|
||||
|
||||
interface ApiEnvelope<T> {
|
||||
status?: boolean
|
||||
msg?: string
|
||||
data?: T
|
||||
}
|
||||
|
||||
function asPositiveInteger(value: unknown, label: string): number {
|
||||
const number = Number(value)
|
||||
if (!Number.isSafeInteger(number) || number <= 0) {
|
||||
throw new Error(`${label} 값이 올바르지 않습니다.`)
|
||||
}
|
||||
return number
|
||||
}
|
||||
|
||||
function asDate(value: unknown): string {
|
||||
const date = String(value ?? '')
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) {
|
||||
throw new Error('예약 날짜가 올바르지 않습니다.')
|
||||
}
|
||||
return date
|
||||
}
|
||||
|
||||
function cleanText(value: unknown, maxLength = 200): string {
|
||||
return String(value ?? '').trim().slice(0, maxLength)
|
||||
}
|
||||
|
||||
async function fetchWithTimeout(url: string, init?: RequestInit): Promise<Response> {
|
||||
const controller = new AbortController()
|
||||
const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS)
|
||||
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
...init,
|
||||
signal: controller.signal,
|
||||
headers: {
|
||||
...edgeBrowserHeaders(),
|
||||
...init?.headers,
|
||||
},
|
||||
})
|
||||
if (!response.ok) {
|
||||
throw new Error(`예약 서버가 HTTP ${response.status} 오류를 반환했습니다.`)
|
||||
}
|
||||
return response
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.name === 'AbortError') {
|
||||
throw new Error('예약 서버 응답 시간이 초과되었습니다.')
|
||||
}
|
||||
throw error
|
||||
} finally {
|
||||
clearTimeout(timeout)
|
||||
}
|
||||
}
|
||||
|
||||
async function postApi<T>(body: Record<string, string>, referer: string): Promise<ApiEnvelope<T>> {
|
||||
const response = await fetchWithTimeout(API_URL, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
...edgeBrowserHeaders({
|
||||
accept: 'application/json, text/javascript, */*; q=0.01',
|
||||
referer,
|
||||
xhr: true,
|
||||
}),
|
||||
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
|
||||
},
|
||||
body: new URLSearchParams(body),
|
||||
})
|
||||
|
||||
try {
|
||||
return await response.json() as ApiEnvelope<T>
|
||||
} catch {
|
||||
throw new Error('예약 서버 응답을 해석하지 못했습니다.')
|
||||
}
|
||||
}
|
||||
|
||||
export function parseBranches(html: string): Branch[] {
|
||||
const match = html.match(/const\s+originalZizumData\s*=\s*(\[[\s\S]*?\]);/)
|
||||
if (!match) return []
|
||||
|
||||
try {
|
||||
const values = JSON.parse(match[1]) as Array<Record<string, unknown>>
|
||||
return values
|
||||
.filter((item) => item.category === 'room')
|
||||
.map((item) => ({
|
||||
num: Number(item.num),
|
||||
name: cleanText(item.name, 80),
|
||||
phone: cleanText(item.phone, 30),
|
||||
}))
|
||||
.filter((item) => Number.isSafeInteger(item.num) && item.num > 0 && item.name.length > 0)
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
export function parsePriceOptions(html: string): PriceOption[] {
|
||||
const select = html.match(/<select[^>]+name=["']person["'][^>]*>([\s\S]*?)<\/select>/i)?.[1] ?? ''
|
||||
const options = [...select.matchAll(/<option[^>]+value=["']?(\d+)["']?[^>]+data-rev_price=["']?(\d+)["']?[^>]*>/gi)]
|
||||
return options.map((match) => ({
|
||||
person: Number(match[1]),
|
||||
totalPrice: Number(match[2]),
|
||||
})).filter((option) => option.person > 0 && option.totalPrice >= 0)
|
||||
}
|
||||
|
||||
async function getBranches(): Promise<Branch[]> {
|
||||
const response = await fetchWithTimeout(`${BASE_URL}/reservation.php`, {
|
||||
headers: edgeBrowserHeaders({ referer: `${BASE_URL}/works.php`, navigation: true }),
|
||||
})
|
||||
const branches = parseBranches(await response.text())
|
||||
if (branches.length === 0) {
|
||||
throw new Error('지점 목록을 찾지 못했습니다. 사이트 구조가 변경되었을 수 있습니다.')
|
||||
}
|
||||
return branches
|
||||
}
|
||||
|
||||
async function getThemes(rawBranchNum: unknown): Promise<Theme[]> {
|
||||
const branchNum = asPositiveInteger(rawBranchNum, '지점')
|
||||
const result = await postApi<Array<Record<string, unknown>>>({
|
||||
t: 'get_theme_info_list',
|
||||
zizum_num: String(branchNum),
|
||||
}, `${BASE_URL}/reservation.php`)
|
||||
|
||||
if (!result.status || !Array.isArray(result.data)) {
|
||||
throw new Error(cleanText(result.msg) || '테마 목록을 불러오지 못했습니다.')
|
||||
}
|
||||
|
||||
return result.data.map((item) => ({
|
||||
infoNum: Number(item.info_num),
|
||||
themeNum: Number(item.theme_num),
|
||||
name: cleanText(item.info_name, 100),
|
||||
doing: Number(item.doing) || 1,
|
||||
memo: cleanText(item.memo, 4_000),
|
||||
})).filter((item) => item.infoNum > 0 && item.themeNum > 0 && item.name.length > 0)
|
||||
}
|
||||
|
||||
async function getThemeDetail(rawThemeInfoNum: unknown): Promise<ThemeDetail> {
|
||||
const themeInfoNum = asPositiveInteger(rawThemeInfoNum, '테마')
|
||||
const result = await postApi<Record<string, unknown>>({
|
||||
t: 'get_theme_date',
|
||||
num: String(themeInfoNum),
|
||||
}, `${BASE_URL}/reservation1.php`) as ApiEnvelope<Record<string, unknown>> & {
|
||||
calendarData?: Record<string, unknown>
|
||||
}
|
||||
|
||||
if (!result.status || !result.data) {
|
||||
throw new Error(cleanText(result.msg) || '테마 정보를 불러오지 못했습니다.')
|
||||
}
|
||||
|
||||
return {
|
||||
name: cleanText(result.data.name, 100),
|
||||
imageUrl: cleanText(result.data.image_url, 500),
|
||||
genre: cleanText(result.data.genre, 100),
|
||||
level: cleanText(result.data.level, 20),
|
||||
playTime: cleanText(result.data.play_time, 20),
|
||||
memo: cleanText(result.data.memo, 4_000),
|
||||
serverToday: asDate(result.calendarData?.today),
|
||||
}
|
||||
}
|
||||
|
||||
async function getTimes(rawSelection: Record<string, unknown>): Promise<TimeSlot[]> {
|
||||
const branchNum = asPositiveInteger(rawSelection.branchNum, '지점')
|
||||
const themeNum = asPositiveInteger(rawSelection.themeNum, '테마')
|
||||
const date = asDate(rawSelection.date)
|
||||
const result = await postApi<Array<Record<string, unknown>>>({
|
||||
t: 'get_theme_time',
|
||||
date,
|
||||
zizumNum: String(branchNum),
|
||||
themeNum: String(themeNum),
|
||||
}, `${BASE_URL}/reservation1.php?zizum_num=${branchNum}&theme_num=${themeNum}`)
|
||||
|
||||
if (!result.status || !Array.isArray(result.data)) {
|
||||
throw new Error(cleanText(result.msg) || '시간 목록을 불러오지 못했습니다.')
|
||||
}
|
||||
|
||||
return result.data.map((item) => ({
|
||||
num: Number(item.num),
|
||||
time: `${cleanText(item.hh, 2)}:${cleanText(item.mm, 2)}`,
|
||||
available: item.enable === 'Y',
|
||||
saleText: cleanText(item.sale_txt, 80),
|
||||
})).filter((item) => item.num > 0 && /^\d{2}:\d{2}$/.test(item.time))
|
||||
}
|
||||
|
||||
function normalizeSelection(rawSelection: Record<string, unknown>): ReservationSelection {
|
||||
return {
|
||||
branchNum: asPositiveInteger(rawSelection.branchNum, '지점'),
|
||||
themeNum: asPositiveInteger(rawSelection.themeNum, '테마'),
|
||||
themeInfoNum: asPositiveInteger(rawSelection.themeInfoNum, '테마 정보'),
|
||||
date: asDate(rawSelection.date),
|
||||
timeNum: asPositiveInteger(rawSelection.timeNum, '예약 시간'),
|
||||
timeLabel: cleanText(rawSelection.timeLabel, 20),
|
||||
themeName: cleanText(rawSelection.themeName, 100),
|
||||
}
|
||||
}
|
||||
|
||||
async function prepare(rawSelection: Record<string, unknown>): Promise<PriceOption[]> {
|
||||
const selection = normalizeSelection(rawSelection)
|
||||
const form = new FormData()
|
||||
form.set('zizumNum', String(selection.branchNum))
|
||||
form.set('themeNum', String(selection.themeNum))
|
||||
form.set('themeInfoNum', String(selection.themeInfoNum))
|
||||
form.set('revDays', selection.date)
|
||||
form.set('themeTimeNum', String(selection.timeNum))
|
||||
form.set('revTimes', selection.timeLabel)
|
||||
form.set('themeName', selection.themeName)
|
||||
|
||||
const response = await fetchWithTimeout(`${BASE_URL}/reservation2.php`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
...edgeBrowserHeaders({
|
||||
referer: `${BASE_URL}/reservation1.php?zizum_num=${selection.branchNum}&theme_num=${selection.themeNum}&theme_info_num=${selection.themeInfoNum}`,
|
||||
navigation: true,
|
||||
}),
|
||||
},
|
||||
body: form,
|
||||
})
|
||||
const options = parsePriceOptions(await response.text())
|
||||
if (options.length === 0) {
|
||||
throw new Error('인원별 금액을 불러오지 못했습니다. 선택한 시간이 마감되었을 수 있습니다.')
|
||||
}
|
||||
return options
|
||||
}
|
||||
|
||||
async function openCaptcha(rawSelection: Record<string, unknown>): Promise<void> {
|
||||
const branchNum = asPositiveInteger(rawSelection.branchNum, '지점')
|
||||
const themeNum = asPositiveInteger(rawSelection.themeNum, '테마')
|
||||
const themeInfoNum = asPositiveInteger(rawSelection.themeInfoNum, '테마 정보')
|
||||
await shell.openExternal(
|
||||
`${BASE_URL}/reservation1.php?zizum_num=${branchNum}&theme_num=${themeNum}&theme_info_num=${themeInfoNum}`,
|
||||
)
|
||||
}
|
||||
|
||||
let reservationSubmissionInFlight = false
|
||||
|
||||
async function executeReservationOnce(rawRequest: ReservationRequest): Promise<ReservationResult> {
|
||||
const requestRecord = rawRequest as unknown as Record<string, unknown>
|
||||
const selection = normalizeSelection(requestRecord)
|
||||
const person = asPositiveInteger(rawRequest.person, '인원')
|
||||
const totalPrice = asPositiveInteger(rawRequest.totalPrice, '결제 금액')
|
||||
const name = cleanText(rawRequest.name, 50)
|
||||
const phone = cleanText(rawRequest.phone, 20).replace(/\D/g, '')
|
||||
const captchaToken = cleanText(rawRequest.captchaToken, 8_000)
|
||||
|
||||
if (!name) throw new Error('예약자명을 입력해주세요.')
|
||||
if (!/^01\d{8,9}$/.test(phone)) throw new Error('휴대폰 번호를 올바르게 입력해주세요.')
|
||||
if (captchaToken.length < 30) throw new Error('캡차 토큰을 올바르게 붙여넣어 주세요.')
|
||||
|
||||
const mobile1 = phone.slice(0, 3)
|
||||
const remainder = phone.slice(3)
|
||||
const values: Record<string, string> = {
|
||||
device: 'pc',
|
||||
t: 'ins_rev',
|
||||
theme_info_num: String(selection.themeInfoNum),
|
||||
zizum_num: String(selection.branchNum),
|
||||
theme_num: String(selection.themeNum),
|
||||
rev_days: selection.date,
|
||||
theme_time_num: String(selection.timeNum),
|
||||
rev_price: String(totalPrice),
|
||||
person: String(person),
|
||||
name,
|
||||
mobile1,
|
||||
mobile2: remainder.slice(0, remainder.length - 4),
|
||||
mobile3: remainder.slice(-4),
|
||||
'g-recaptcha-response': captchaToken,
|
||||
payment: 'D',
|
||||
agree_all: 'on',
|
||||
agree_1: 'on',
|
||||
agree_2: 'on',
|
||||
agree_3: 'on',
|
||||
}
|
||||
const multipart = encodeMultipart(values)
|
||||
const response = await requestKeyescape({
|
||||
method: 'POST',
|
||||
path: '/controller/run_proc.php',
|
||||
headers: {
|
||||
...edgeBrowserHeaders({
|
||||
accept: 'application/json, text/javascript, */*; q=0.01',
|
||||
referer: `${BASE_URL}/reservation2.php`,
|
||||
xhr: true,
|
||||
}),
|
||||
'Content-Type': `multipart/form-data; boundary=${multipart.boundary}`,
|
||||
'Content-Length': String(multipart.body.length),
|
||||
},
|
||||
body: multipart.body,
|
||||
timeoutMs: REQUEST_TIMEOUT_MS,
|
||||
})
|
||||
|
||||
if (response.statusCode < 200 || response.statusCode >= 300) {
|
||||
throw new Error(`예약 서버가 HTTP ${response.statusCode} 오류를 반환했습니다.`)
|
||||
}
|
||||
|
||||
let result: ApiEnvelope<Record<string, unknown>>
|
||||
try {
|
||||
result = JSON.parse(response.body.toString('utf8')) as ApiEnvelope<Record<string, unknown>>
|
||||
} catch {
|
||||
throw new Error('예약 서버 응답을 해석하지 못했습니다.')
|
||||
}
|
||||
|
||||
const message = cleanText(result.msg, 500) || (result.status ? '예약이 접수되었습니다.' : '예약에 실패했습니다.')
|
||||
const observedServerDateMs = Date.parse(Array.isArray(response.headers.date)
|
||||
? response.headers.date[0]
|
||||
: response.headers.date ?? '')
|
||||
const transport = {
|
||||
sentAtMs: response.sentAtMs,
|
||||
receivedAtMs: response.receivedAtMs,
|
||||
rttMs: response.rttMs,
|
||||
httpStatus: response.statusCode,
|
||||
remoteIp: response.remoteIp,
|
||||
reusedSocket: response.reusedSocket,
|
||||
observedServerDateMs: Number.isFinite(observedServerDateMs) ? observedServerDateMs : undefined,
|
||||
}
|
||||
if (!result.status || !result.data) return { success: false, message, transport }
|
||||
|
||||
const reservationNum = cleanText(result.data.num, 100)
|
||||
const checkCode = cleanText(result.data.ck_code, 200)
|
||||
const confirmationUrl = reservationNum && checkCode
|
||||
? `${BASE_URL}/reservation3.php?num=${encodeURIComponent(reservationNum)}&ck_code=${encodeURIComponent(checkCode)}`
|
||||
: undefined
|
||||
return { success: true, message, reservationNum, confirmationUrl, transport }
|
||||
}
|
||||
|
||||
export async function executeReservation(rawRequest: ReservationRequest): Promise<ReservationResult> {
|
||||
if (reservationSubmissionInFlight) throw new Error('이미 예약 요청이 진행 중입니다.')
|
||||
reservationSubmissionInFlight = true
|
||||
try {
|
||||
return await executeReservationOnce(rawRequest)
|
||||
} finally {
|
||||
reservationSubmissionInFlight = false
|
||||
}
|
||||
}
|
||||
|
||||
function handle<TArgs extends unknown[], TResult>(
|
||||
channel: string,
|
||||
handler: (...args: TArgs) => Promise<TResult>,
|
||||
) {
|
||||
ipcMain.handle(channel, async (_event, ...args: TArgs) => {
|
||||
try {
|
||||
return { ok: true, data: await handler(...args) }
|
||||
} catch (error) {
|
||||
return {
|
||||
ok: false,
|
||||
error: error instanceof Error ? error.message : '알 수 없는 오류가 발생했습니다.',
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export function registerReservationHandlers() {
|
||||
handle('reservation:get-branches', getBranches)
|
||||
handle('reservation:get-themes', getThemes)
|
||||
handle('reservation:get-theme-detail', getThemeDetail)
|
||||
handle('reservation:get-times', getTimes)
|
||||
handle('reservation:prepare', prepare)
|
||||
handle('reservation:open-captcha', openCaptcha)
|
||||
handle('reservation:submit', executeReservation)
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
import {
|
||||
CLOCK_CALIBRATION_DEFAULTS,
|
||||
type ClockCalibrationSettings,
|
||||
type ClockEstimate,
|
||||
type ClockSample,
|
||||
} from '../../src/type/reservation'
|
||||
|
||||
export interface RawClockObservation {
|
||||
id: number
|
||||
sentAtMs: number
|
||||
receivedAtMs: number
|
||||
rttMs: number
|
||||
serverDateHeader?: string
|
||||
remoteIp: string
|
||||
reusedSocket: boolean
|
||||
ageHeader?: string
|
||||
viaHeader?: string
|
||||
cacheHeader?: string
|
||||
statusCode: number
|
||||
}
|
||||
|
||||
const MAX_ACCEPTED_RTT_MS = 2_000
|
||||
|
||||
function finite(value: number, fallback = 0) {
|
||||
return Number.isFinite(value) ? value : fallback
|
||||
}
|
||||
|
||||
export function observationToSample(observation: RawClockObservation): ClockSample {
|
||||
const serverDateMs = Date.parse(observation.serverDateHeader ?? '')
|
||||
const midpointMs = (observation.sentAtMs + observation.receivedAtMs) / 2
|
||||
const age = Number(observation.ageHeader ?? '0')
|
||||
const cacheHit = /hit/i.test(observation.cacheHeader ?? '')
|
||||
let rejectionReason: string | undefined
|
||||
|
||||
if (observation.statusCode < 200 || observation.statusCode >= 400) rejectionReason = `HTTP ${observation.statusCode}`
|
||||
else if (!Number.isFinite(serverDateMs)) rejectionReason = 'Date 헤더 없음'
|
||||
else if (Number.isFinite(age) && age > 0) rejectionReason = '캐시된 응답'
|
||||
else if (cacheHit || observation.viaHeader) rejectionReason = '프록시 캐시 경로'
|
||||
else if (observation.rttMs <= 0 || observation.rttMs > MAX_ACCEPTED_RTT_MS) rejectionReason = 'RTT 이상치'
|
||||
|
||||
return {
|
||||
id: observation.id,
|
||||
sentAtMs: observation.sentAtMs,
|
||||
receivedAtMs: observation.receivedAtMs,
|
||||
midpointMs,
|
||||
serverDateMs: finite(serverDateMs),
|
||||
rttMs: observation.rttMs,
|
||||
offsetEstimateMs: finite(serverDateMs) + 500 - midpointMs,
|
||||
offsetMinMs: finite(serverDateMs) - observation.receivedAtMs,
|
||||
offsetMaxMs: finite(serverDateMs) + 1_000 - observation.sentAtMs,
|
||||
remoteIp: observation.remoteIp,
|
||||
reusedSocket: observation.reusedSocket,
|
||||
accepted: !rejectionReason,
|
||||
rejectionReason,
|
||||
}
|
||||
}
|
||||
|
||||
export function quantile(values: number[], percentile: number): number {
|
||||
if (values.length === 0) return 0
|
||||
const sorted = [...values].sort((a, b) => a - b)
|
||||
const index = (sorted.length - 1) * Math.min(1, Math.max(0, percentile))
|
||||
const lower = Math.floor(index)
|
||||
const upper = Math.ceil(index)
|
||||
if (lower === upper) return sorted[lower]
|
||||
return sorted[lower] + (sorted[upper] - sorted[lower]) * (index - lower)
|
||||
}
|
||||
|
||||
function weightedMedian(items: Array<{ value: number; weight: number }>): number {
|
||||
if (items.length === 0) return 0
|
||||
const sorted = [...items].sort((a, b) => a.value - b.value)
|
||||
const total = sorted.reduce((sum, item) => sum + item.weight, 0)
|
||||
let accumulated = 0
|
||||
for (const item of sorted) {
|
||||
accumulated += item.weight
|
||||
if (accumulated >= total / 2) return item.value
|
||||
}
|
||||
return sorted.at(-1)?.value ?? 0
|
||||
}
|
||||
|
||||
function estimateDrift(samples: ClockSample[], nowMs: number) {
|
||||
if (samples.length < 6) return { currentOffsetMs: 0, driftPpm: 0, usable: false }
|
||||
const origin = samples[Math.floor(samples.length / 2)].midpointMs
|
||||
let sumWeight = 0
|
||||
let sumX = 0
|
||||
let sumY = 0
|
||||
let sumXX = 0
|
||||
let sumXY = 0
|
||||
|
||||
for (const sample of samples) {
|
||||
const x = sample.midpointMs - origin
|
||||
const y = sample.offsetEstimateMs
|
||||
const weight = 1 / Math.max(sample.rttMs, 1) ** 2
|
||||
sumWeight += weight
|
||||
sumX += weight * x
|
||||
sumY += weight * y
|
||||
sumXX += weight * x * x
|
||||
sumXY += weight * x * y
|
||||
}
|
||||
|
||||
const denominator = sumWeight * sumXX - sumX * sumX
|
||||
if (Math.abs(denominator) < 1e-9) return { currentOffsetMs: 0, driftPpm: 0, usable: false }
|
||||
const rawSlope = (sumWeight * sumXY - sumX * sumY) / denominator
|
||||
const slope = Math.max(-200e-6, Math.min(200e-6, rawSlope))
|
||||
const intercept = (sumY - slope * sumX) / sumWeight
|
||||
return {
|
||||
currentOffsetMs: intercept + slope * (nowMs - origin),
|
||||
driftPpm: slope * 1_000_000,
|
||||
usable: true,
|
||||
}
|
||||
}
|
||||
|
||||
export interface BoundaryEstimate {
|
||||
count: number
|
||||
offsetMs: number
|
||||
uncertaintyMs: number
|
||||
spreadMs: number
|
||||
}
|
||||
|
||||
export function estimateBoundaryOffset(
|
||||
samples: ClockSample[],
|
||||
settings: ClockCalibrationSettings = CLOCK_CALIBRATION_DEFAULTS,
|
||||
): BoundaryEstimate | undefined {
|
||||
const candidates: Array<{ boundaryMs: number; offsetMs: number; uncertaintyMs: number; atMs: number }> = []
|
||||
for (let index = 1; index < samples.length; index += 1) {
|
||||
const previous = samples[index - 1]
|
||||
const current = samples[index]
|
||||
if (!previous.accepted || !current.accepted) continue
|
||||
if (previous.remoteIp !== current.remoteIp) continue
|
||||
if (previous.rttMs > settings.maxProbeRttMs || current.rttMs > settings.maxProbeRttMs) continue
|
||||
if (current.serverDateMs - previous.serverDateMs !== 1_000) continue
|
||||
const gap = current.midpointMs - previous.midpointMs
|
||||
if (gap <= 0 || gap > Math.max(250, settings.probeIntervalMs * 3)) continue
|
||||
const localBoundaryMs = (previous.midpointMs + current.midpointMs) / 2
|
||||
candidates.push({
|
||||
boundaryMs: current.serverDateMs,
|
||||
offsetMs: current.serverDateMs - localBoundaryMs,
|
||||
uncertaintyMs: gap / 2 + Math.max(previous.rttMs, current.rttMs) / 2
|
||||
+ (previous.reusedSocket && current.reusedSocket ? 0 : 25),
|
||||
atMs: current.receivedAtMs,
|
||||
})
|
||||
}
|
||||
|
||||
const uniqueBoundaries = [...candidates.reduce((map, candidate) => {
|
||||
const existing = map.get(candidate.boundaryMs)
|
||||
if (!existing || candidate.uncertaintyMs < existing.uncertaintyMs) map.set(candidate.boundaryMs, candidate)
|
||||
return map
|
||||
}, new Map<number, typeof candidates[number]>()).values()].sort((a, b) => a.atMs - b.atMs)
|
||||
const recent = uniqueBoundaries.slice(-settings.historySize)
|
||||
if (recent.length === 0) return undefined
|
||||
const center = quantile(recent.map((item) => item.offsetMs), 0.5)
|
||||
const absoluteDeviations = recent.map((item) => Math.abs(item.offsetMs - center))
|
||||
const mad = quantile(absoluteDeviations, 0.5)
|
||||
const rejectionLimit = Math.max(settings.maxBoundarySpreadMs, mad * 3 * 1.4826)
|
||||
const filtered = recent.filter((item) => Math.abs(item.offsetMs - center) <= rejectionLimit)
|
||||
if (filtered.length === 0) return undefined
|
||||
|
||||
const offsetMs = weightedMedian(filtered.map((item) => ({
|
||||
value: item.offsetMs,
|
||||
weight: 1 / Math.max(item.uncertaintyMs, 1) ** 2,
|
||||
})))
|
||||
const spreadMs = quantile(filtered.map((item) => Math.abs(item.offsetMs - offsetMs)), 0.9)
|
||||
const typicalMeasurementUncertainty = quantile(filtered.map((item) => item.uncertaintyMs), 0.5)
|
||||
const uncertaintyMs = Math.max(
|
||||
spreadMs,
|
||||
typicalMeasurementUncertainty / Math.sqrt(filtered.length),
|
||||
)
|
||||
return { count: filtered.length, offsetMs, uncertaintyMs, spreadMs }
|
||||
}
|
||||
|
||||
export function estimateClock(
|
||||
samples: ClockSample[],
|
||||
nowMs = Date.now(),
|
||||
monitoring = false,
|
||||
settings: ClockCalibrationSettings = CLOCK_CALIBRATION_DEFAULTS,
|
||||
): ClockEstimate {
|
||||
const allRecent = samples.slice(-settings.sampleWindowSize)
|
||||
const accepted = allRecent.filter((sample) => sample.accepted && sample.rttMs <= settings.maxProbeRttMs)
|
||||
if (accepted.length === 0) {
|
||||
return {
|
||||
monitoring,
|
||||
observedAtMs: nowMs,
|
||||
estimatedServerTimeMs: nowMs,
|
||||
offsetMs: 0,
|
||||
driftPpm: 0,
|
||||
minRttMs: 0,
|
||||
p50RttMs: 0,
|
||||
p95RttMs: 0,
|
||||
oneWayMs: 0,
|
||||
uncertaintyMs: 1_000,
|
||||
sampleAgeMs: Number.POSITIVE_INFINITY,
|
||||
acceptedSamples: 0,
|
||||
rawOffsetMs: 0,
|
||||
boundaryCount: 0,
|
||||
recommendedCorrectionMs: 0,
|
||||
calibrationReady: false,
|
||||
calibrationApplied: false,
|
||||
calibrationSettings: settings,
|
||||
remoteIp: '',
|
||||
quality: 'unavailable',
|
||||
warning: '유효한 서버시간 표본이 없습니다.',
|
||||
samples: allRecent,
|
||||
}
|
||||
}
|
||||
|
||||
const rtts = accepted.map((sample) => sample.rttMs)
|
||||
const minRttMs = Math.min(...rtts)
|
||||
const p50RttMs = quantile(rtts, 0.5)
|
||||
const p95RttMs = quantile(rtts, 0.95)
|
||||
const lowLatencyCutoff = Math.max(minRttMs + 25, p50RttMs)
|
||||
const lowLatency = accepted.filter((sample) => sample.rttMs <= lowLatencyCutoff)
|
||||
const medianOffset = weightedMedian(lowLatency.map((sample) => ({
|
||||
value: sample.offsetEstimateMs,
|
||||
weight: 1 / Math.max(sample.rttMs, 1) ** 2,
|
||||
})))
|
||||
const drift = estimateDrift(lowLatency, nowMs)
|
||||
const boundary = settings.enabled ? estimateBoundaryOffset(accepted, settings) : undefined
|
||||
const rawOffsetMs = drift.usable ? medianOffset * 0.75 + drift.currentOffsetMs * 0.25 : medianOffset
|
||||
const calibrationReady = Boolean(boundary && boundary.count >= settings.requiredBoundaryCount
|
||||
&& boundary.spreadMs <= settings.maxBoundarySpreadMs)
|
||||
const calibrationApplied = Boolean(calibrationReady && settings.autoApply)
|
||||
let offsetMs = calibrationApplied ? boundary!.offsetMs : rawOffsetMs
|
||||
let uncertaintyMs = Math.max(
|
||||
500 + minRttMs / 2,
|
||||
quantile(lowLatency.map((sample) => Math.abs(sample.offsetEstimateMs - medianOffset)), 0.9) + p95RttMs / 2,
|
||||
)
|
||||
|
||||
if (calibrationApplied && boundary) {
|
||||
uncertaintyMs = Math.max(boundary.uncertaintyMs, minRttMs / 2)
|
||||
}
|
||||
|
||||
const latest = accepted.at(-1)!
|
||||
const sampleAgeMs = Math.max(0, nowMs - latest.receivedAtMs)
|
||||
let quality: ClockEstimate['quality'] = 'poor'
|
||||
let warning: string | undefined
|
||||
if (uncertaintyMs <= 300 && p95RttMs <= 250 && sampleAgeMs <= 5_000) quality = 'good'
|
||||
else if (uncertaintyMs <= 700 && sampleAgeMs <= 10_000) quality = 'fair'
|
||||
else warning = sampleAgeMs > 10_000
|
||||
? '마지막 표본이 오래되었습니다. 네트워크 상태를 확인하세요.'
|
||||
: '서버 Date 헤더 해상도 또는 RTT 변동으로 추정 오차가 큽니다.'
|
||||
if (settings.enabled && !calibrationReady) {
|
||||
warning = `초 경계 정밀 보정을 학습 중입니다 (${boundary?.count ?? 0}/${settings.requiredBoundaryCount}).`
|
||||
}
|
||||
|
||||
return {
|
||||
monitoring,
|
||||
observedAtMs: nowMs,
|
||||
estimatedServerTimeMs: nowMs + offsetMs,
|
||||
offsetMs,
|
||||
driftPpm: drift.driftPpm,
|
||||
minRttMs,
|
||||
p50RttMs,
|
||||
p95RttMs,
|
||||
oneWayMs: minRttMs / 2,
|
||||
uncertaintyMs,
|
||||
sampleAgeMs,
|
||||
acceptedSamples: accepted.length,
|
||||
rawOffsetMs,
|
||||
boundaryCount: boundary?.count ?? 0,
|
||||
boundaryOffsetMs: boundary?.offsetMs,
|
||||
boundaryUncertaintyMs: boundary?.uncertaintyMs,
|
||||
boundarySpreadMs: boundary?.spreadMs,
|
||||
recommendedCorrectionMs: boundary ? boundary.offsetMs - rawOffsetMs : 0,
|
||||
calibrationReady,
|
||||
calibrationApplied,
|
||||
calibrationSettings: settings,
|
||||
remoteIp: latest.remoteIp,
|
||||
quality,
|
||||
warning,
|
||||
samples: allRecent,
|
||||
}
|
||||
}
|
||||
|
||||
export function appendClockSample(samples: ClockSample[], sample: ClockSample, maxSamples = CLOCK_CALIBRATION_DEFAULTS.sampleWindowSize) {
|
||||
const previousIp = [...samples].reverse().find((item) => item.accepted)?.remoteIp
|
||||
const routeChanged = sample.accepted && previousIp && sample.remoteIp && previousIp !== sample.remoteIp
|
||||
return [...(routeChanged ? [] : samples), sample].slice(-maxSamples)
|
||||
}
|
||||
|
||||
export function computePlannedSendAtMs(
|
||||
targetServerTimeMs: number,
|
||||
userOffsetMs: number,
|
||||
estimate: Pick<ClockEstimate, 'offsetMs' | 'oneWayMs'>,
|
||||
) {
|
||||
return targetServerTimeMs + userOffsetMs - estimate.offsetMs - estimate.oneWayMs
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
import { BrowserWindow, ipcMain } from 'electron'
|
||||
import {
|
||||
CLOCK_CALIBRATION_DEFAULTS,
|
||||
type ClockCalibrationSettings,
|
||||
type ClockEstimate,
|
||||
type ClockSample,
|
||||
type TimingTestRequest,
|
||||
type TimingTestResult,
|
||||
} from '../../src/type/reservation'
|
||||
import { edgeBrowserHeaders, requestKeyescape } 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<ClockSample>
|
||||
private userMonitoring = false
|
||||
private autoTargetServerTimeMs?: number
|
||||
private lastError?: string
|
||||
private settings: ClockCalibrationSettings = { ...CLOCK_CALIBRATION_DEFAULTS }
|
||||
private precisionBoundaryServerMs?: number
|
||||
|
||||
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)
|
||||
this.settings = {
|
||||
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 = this.samples.slice(-this.settings.sampleWindowSize)
|
||||
this.precisionBoundaryServerMs = undefined
|
||||
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) {
|
||||
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<ClockSample> {
|
||||
if (this.inFlight) return this.inFlight
|
||||
this.inFlight = this.performProbe().finally(() => { this.inFlight = undefined })
|
||||
return this.inFlight
|
||||
}
|
||||
|
||||
private async performProbe(): Promise<ClockSample> {
|
||||
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,
|
||||
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 previousIp = this.getEstimate().remoteIp
|
||||
this.samples = appendClockSample(this.samples, sample, this.settings.sampleWindowSize)
|
||||
if (sample.accepted && previousIp && sample.remoteIp !== previousIp) this.precisionBoundaryServerMs = undefined
|
||||
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<TimingTestResult> {
|
||||
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<void>((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,
|
||||
}
|
||||
}
|
||||
|
||||
dispose() {
|
||||
this.userMonitoring = false
|
||||
this.autoTargetServerTimeMs = undefined
|
||||
if (this.timer) clearTimeout(this.timer)
|
||||
this.timer = undefined
|
||||
this.samples = []
|
||||
this.precisionBoundaryServerMs = undefined
|
||||
}
|
||||
|
||||
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() {
|
||||
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 <T>(task: () => T | Promise<T>) => {
|
||||
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)))
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { ipcRenderer, contextBridge } from 'electron'
|
||||
import './reservation-api'
|
||||
|
||||
// --------- Expose some API to the Renderer process ---------
|
||||
contextBridge.exposeInMainWorld('ipcRenderer', {
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { contextBridge, ipcRenderer } from 'electron'
|
||||
import type { ReservationApi } from '../../src/type/reservation'
|
||||
|
||||
type IpcResult<T> = { ok: true; data: T } | { ok: false; error: string }
|
||||
|
||||
async function invoke<T>(channel: string, ...args: unknown[]): Promise<T> {
|
||||
const result = await ipcRenderer.invoke(channel, ...args) as IpcResult<T>
|
||||
if (!result.ok) throw new Error(result.error)
|
||||
return result.data
|
||||
}
|
||||
|
||||
const reservationApi: ReservationApi = {
|
||||
getBranches: () => invoke('reservation:get-branches'),
|
||||
getThemes: (branchNum) => invoke('reservation:get-themes', branchNum),
|
||||
getThemeDetail: (themeInfoNum) => invoke('reservation:get-theme-detail', themeInfoNum),
|
||||
getTimes: (selection) => invoke('reservation:get-times', selection),
|
||||
prepare: (selection) => invoke('reservation:prepare', selection),
|
||||
openCaptcha: (selection) => invoke('reservation:open-captcha', selection),
|
||||
submit: (request) => invoke('reservation:submit', request),
|
||||
startClockMonitor: () => invoke('reservation:clock-start'),
|
||||
stopClockMonitor: () => invoke('reservation:clock-stop'),
|
||||
getClockState: () => invoke('reservation:clock-get'),
|
||||
configureClock: (settings) => invoke('reservation:clock-configure', settings),
|
||||
subscribeClock: (listener) => {
|
||||
const wrapped = (_event: Electron.IpcRendererEvent, estimate: Parameters<typeof listener>[0]) => listener(estimate)
|
||||
ipcRenderer.on('reservation:clock-state', wrapped)
|
||||
return () => ipcRenderer.off('reservation:clock-state', wrapped)
|
||||
},
|
||||
runTimingTest: (request) => invoke('reservation:clock-test', request),
|
||||
armAutoReservation: (config) => invoke('reservation:auto-arm', config),
|
||||
disarmAutoReservation: () => invoke('reservation:auto-disarm'),
|
||||
getAutoReservationState: () => invoke('reservation:auto-get'),
|
||||
subscribeAutoState: (listener) => {
|
||||
const wrapped = (_event: Electron.IpcRendererEvent, state: Parameters<typeof listener>[0]) => listener(state)
|
||||
ipcRenderer.on('reservation:auto-state', wrapped)
|
||||
return () => ipcRenderer.off('reservation:auto-state', wrapped)
|
||||
},
|
||||
}
|
||||
|
||||
contextBridge.exposeInMainWorld('reservationApi', reservationApi)
|
||||
|
||||
window.addEventListener('beforeunload', () => {
|
||||
ipcRenderer.send('reservation:renderer-unload')
|
||||
})
|
||||
Reference in new issue
Block a user