.
This commit is contained in:
1 parent
d2c03d155d
commit
db60190e19
13 files changed
+505
-38
No files matched your search
@@ -224,6 +224,8 @@ export class AutoReservationService {
|
||||
httpStatus: transport?.httpStatus,
|
||||
remoteIp: transport?.remoteIp,
|
||||
reusedSocket: transport?.reusedSocket,
|
||||
protocol: transport?.protocol,
|
||||
connectionId: transport?.connectionId,
|
||||
},
|
||||
}
|
||||
} catch (error) {
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
import { BrowserWindow, session } from 'electron'
|
||||
import type { CaptchaResult, ReservationSelection } from '../../src/type/reservation'
|
||||
import { EDGE_USER_AGENT, encodeMultipart } from './keyescape-http'
|
||||
|
||||
const BASE_URL = 'https://www.keyescape.com'
|
||||
const CAPTCHA_PARTITION = 'persist:escape-reserve-captcha'
|
||||
const TOKEN_POLL_INTERVAL_MS = 200
|
||||
const MAX_TOKEN_LENGTH = 8_000
|
||||
|
||||
let captchaWindow: BrowserWindow | null = null
|
||||
|
||||
function captchaForm(selection: ReservationSelection) {
|
||||
return encodeMultipart({
|
||||
zizumNum: String(selection.branchNum),
|
||||
themeNum: String(selection.themeNum),
|
||||
themeInfoNum: String(selection.themeInfoNum),
|
||||
revDays: selection.date,
|
||||
themeTimeNum: String(selection.timeNum),
|
||||
revTimes: selection.timeLabel,
|
||||
themeName: selection.themeName,
|
||||
})
|
||||
}
|
||||
|
||||
function isAllowedTopLevelUrl(rawUrl: string) {
|
||||
try {
|
||||
const url = new URL(rawUrl)
|
||||
return url.protocol === 'https:' && url.hostname === 'www.keyescape.com'
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
const AUTH_WINDOW_GUARD = `(() => {
|
||||
if (window.__escapeReserveCaptchaGuard) return
|
||||
window.__escapeReserveCaptchaGuard = true
|
||||
|
||||
document.addEventListener('submit', (event) => {
|
||||
event.preventDefault()
|
||||
event.stopImmediatePropagation()
|
||||
}, true)
|
||||
|
||||
const banner = document.createElement('div')
|
||||
banner.setAttribute('role', 'status')
|
||||
banner.textContent = 'Escape Reserve 보안 인증 창 · CAPTCHA만 인증할 수 있으며 예약 제출은 차단됩니다.'
|
||||
Object.assign(banner.style, {
|
||||
position: 'fixed',
|
||||
zIndex: '2147483647',
|
||||
inset: '0 0 auto 0',
|
||||
padding: '12px 18px',
|
||||
background: '#111111',
|
||||
color: '#ffffff',
|
||||
font: '600 13px/1.4 system-ui, sans-serif',
|
||||
textAlign: 'center',
|
||||
boxShadow: '0 2px 12px rgba(0,0,0,.25)'
|
||||
})
|
||||
document.documentElement.appendChild(banner)
|
||||
document.documentElement.style.scrollPaddingTop = '48px'
|
||||
})()`
|
||||
|
||||
const READ_CAPTCHA_TOKEN = `(() => {
|
||||
const field = document.querySelector('textarea[name="g-recaptcha-response"], #g-recaptcha-response')
|
||||
return field && typeof field.value === 'string' ? field.value : ''
|
||||
})()`
|
||||
|
||||
export async function openCaptchaWindow(selection: ReservationSelection): Promise<CaptchaResult> {
|
||||
if (captchaWindow && !captchaWindow.isDestroyed()) {
|
||||
captchaWindow.focus()
|
||||
throw new Error('CAPTCHA 인증 창이 이미 열려 있습니다.')
|
||||
}
|
||||
|
||||
const parent = BrowserWindow.getFocusedWindow() ?? undefined
|
||||
const captchaSession = session.fromPartition(CAPTCHA_PARTITION, { cache: true })
|
||||
captchaSession.setPermissionRequestHandler((_webContents, _permission, callback) => callback(false))
|
||||
captchaSession.webRequest.onBeforeRequest({
|
||||
urls: [`${BASE_URL}/controller/run_proc.php*`],
|
||||
}, (_details, callback) => callback({ cancel: true }))
|
||||
|
||||
const window = new BrowserWindow({
|
||||
parent,
|
||||
modal: Boolean(parent),
|
||||
title: 'CAPTCHA 인증 · Escape Reserve',
|
||||
width: 1180,
|
||||
height: 820,
|
||||
minWidth: 760,
|
||||
minHeight: 620,
|
||||
show: false,
|
||||
autoHideMenuBar: true,
|
||||
backgroundColor: '#fbf9fb',
|
||||
webPreferences: {
|
||||
partition: CAPTCHA_PARTITION,
|
||||
nodeIntegration: false,
|
||||
contextIsolation: true,
|
||||
sandbox: true,
|
||||
devTools: false,
|
||||
webSecurity: true,
|
||||
},
|
||||
})
|
||||
captchaWindow = window
|
||||
|
||||
window.webContents.setWindowOpenHandler(() => ({ action: 'deny' }))
|
||||
window.webContents.on('will-navigate', (event, url) => {
|
||||
if (!isAllowedTopLevelUrl(url)) event.preventDefault()
|
||||
})
|
||||
|
||||
return new Promise<CaptchaResult>((resolve, reject) => {
|
||||
let settled = false
|
||||
let pollTimer: NodeJS.Timeout | undefined
|
||||
|
||||
const cleanup = () => {
|
||||
if (pollTimer) clearInterval(pollTimer)
|
||||
pollTimer = undefined
|
||||
if (captchaWindow === window) captchaWindow = null
|
||||
}
|
||||
|
||||
const fail = (message: string) => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
cleanup()
|
||||
reject(new Error(message))
|
||||
if (!window.isDestroyed()) window.destroy()
|
||||
}
|
||||
|
||||
const pollToken = async () => {
|
||||
if (settled || window.isDestroyed() || window.webContents.isLoadingMainFrame()) return
|
||||
try {
|
||||
const value = await window.webContents.executeJavaScript(READ_CAPTCHA_TOKEN, true)
|
||||
const token = typeof value === 'string' ? value.trim().slice(0, MAX_TOKEN_LENGTH) : ''
|
||||
if (token.length < 30 || settled) return
|
||||
settled = true
|
||||
cleanup()
|
||||
resolve({ token, solvedAtMs: Date.now() })
|
||||
window.destroy()
|
||||
} catch {
|
||||
// Navigations temporarily destroy the execution context; the next poll retries.
|
||||
}
|
||||
}
|
||||
|
||||
window.once('closed', () => {
|
||||
cleanup()
|
||||
if (!settled) {
|
||||
settled = true
|
||||
reject(new Error('CAPTCHA 인증을 취소했습니다.'))
|
||||
}
|
||||
})
|
||||
window.webContents.on('did-fail-load', (_event, errorCode, errorDescription, _url, isMainFrame) => {
|
||||
if (isMainFrame && errorCode !== -3) fail(`CAPTCHA 페이지를 불러오지 못했습니다: ${errorDescription}`)
|
||||
})
|
||||
window.webContents.on('dom-ready', () => {
|
||||
void window.webContents.executeJavaScript(AUTH_WINDOW_GUARD, true).catch(() => undefined)
|
||||
})
|
||||
window.webContents.once('did-finish-load', () => {
|
||||
window.show()
|
||||
pollTimer = setInterval(() => void pollToken(), TOKEN_POLL_INTERVAL_MS)
|
||||
void pollToken()
|
||||
})
|
||||
|
||||
const multipart = captchaForm(selection)
|
||||
void window.loadURL(`${BASE_URL}/reservation2.php`, {
|
||||
httpReferrer: `${BASE_URL}/reservation1.php?zizum_num=${selection.branchNum}&theme_num=${selection.themeNum}&theme_info_num=${selection.themeInfoNum}`,
|
||||
userAgent: EDGE_USER_AGENT,
|
||||
extraHeaders: `Content-Type: multipart/form-data; boundary=${multipart.boundary}\n`,
|
||||
postData: [{ type: 'rawData', bytes: multipart.body }],
|
||||
}).catch((error) => fail(error instanceof Error ? error.message : 'CAPTCHA 페이지를 열지 못했습니다.'))
|
||||
})
|
||||
}
|
||||
@@ -1,8 +1,27 @@
|
||||
import https from 'node:https'
|
||||
import http2, { constants as http2Constants, type ClientHttp2Session } from 'node:http2'
|
||||
import { performance } from 'node:perf_hooks'
|
||||
import { randomBytes } from 'node:crypto'
|
||||
|
||||
const HOSTNAME = 'www.keyescape.com'
|
||||
const ORIGIN = `https://${HOSTNAME}`
|
||||
|
||||
export type KeyescapeTransportMode = 'http1' | 'http2'
|
||||
type ResponseHeaders = Record<string, string | string[] | undefined>
|
||||
|
||||
interface H2SessionRecord {
|
||||
session: ClientHttp2Session
|
||||
id: string
|
||||
remoteIp: string
|
||||
streamCount: number
|
||||
goaway: boolean
|
||||
}
|
||||
|
||||
let transportMode: KeyescapeTransportMode = 'http1'
|
||||
let h2Session: H2SessionRecord | undefined
|
||||
let h2Connecting: Promise<H2SessionRecord> | undefined
|
||||
let h2ConnectingSession: ClientHttp2Session | undefined
|
||||
let h2Generation = 0
|
||||
|
||||
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'
|
||||
|
||||
@@ -31,7 +50,11 @@ export function edgeBrowserHeaders(options: EdgeHeaderOptions = {}): Record<stri
|
||||
headers['Sec-Fetch-User'] = '?1'
|
||||
headers['Upgrade-Insecure-Requests'] = '1'
|
||||
}
|
||||
if (options.xhr) headers['X-Requested-With'] = 'XMLHttpRequest'
|
||||
if (options.xhr) {
|
||||
headers['X-Requested-With'] = 'XMLHttpRequest'
|
||||
headers.Origin = ORIGIN
|
||||
headers.Priority = 'u=1, i'
|
||||
}
|
||||
if (options.referer) headers.Referer = options.referer
|
||||
return headers
|
||||
}
|
||||
@@ -46,7 +69,7 @@ export const keyescapeAgent = new https.Agent({
|
||||
|
||||
export interface KeyescapeResponse {
|
||||
statusCode: number
|
||||
headers: https.IncomingHttpHeaders
|
||||
headers: ResponseHeaders
|
||||
body: Buffer
|
||||
sentAtMs: number
|
||||
receivedAtMs: number
|
||||
@@ -55,6 +78,8 @@ export interface KeyescapeResponse {
|
||||
rttMs: number
|
||||
remoteIp: string
|
||||
reusedSocket: boolean
|
||||
protocol: 'http/1.1' | 'h2'
|
||||
connectionId: string
|
||||
}
|
||||
|
||||
export interface KeyescapeRequestOptions {
|
||||
@@ -65,11 +90,39 @@ export interface KeyescapeRequestOptions {
|
||||
timeoutMs?: number
|
||||
}
|
||||
|
||||
export function requestKeyescape(options: KeyescapeRequestOptions): Promise<KeyescapeResponse> {
|
||||
export function getKeyescapeTransportMode() {
|
||||
return transportMode
|
||||
}
|
||||
|
||||
export function setKeyescapeTransportMode(mode: KeyescapeTransportMode) {
|
||||
if (mode !== 'http1' && mode !== 'http2') throw new Error('지원하지 않는 HTTP 전송 모드입니다.')
|
||||
if (transportMode === mode) return false
|
||||
transportMode = mode
|
||||
if (mode === 'http1') closeHttp2Session()
|
||||
return true
|
||||
}
|
||||
|
||||
export function closeHttp2Session() {
|
||||
const current = h2Session
|
||||
const connecting = h2ConnectingSession
|
||||
h2Session = undefined
|
||||
h2Connecting = undefined
|
||||
h2ConnectingSession = undefined
|
||||
if (current && !current.session.closed && !current.session.destroyed) current.session.close()
|
||||
if (connecting && !connecting.closed && !connecting.destroyed) connecting.destroy()
|
||||
}
|
||||
|
||||
export function disposeKeyescapeTransport() {
|
||||
closeHttp2Session()
|
||||
keyescapeAgent.destroy()
|
||||
}
|
||||
|
||||
function requestKeyescapeHttp1(options: KeyescapeRequestOptions): Promise<KeyescapeResponse> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const sentAtMs = Date.now()
|
||||
const sentMonoMs = performance.now()
|
||||
let remoteIp = ''
|
||||
let connectionId = ''
|
||||
|
||||
const request = https.request({
|
||||
hostname: HOSTNAME,
|
||||
@@ -99,6 +152,8 @@ export function requestKeyescape(options: KeyescapeRequestOptions): Promise<Keye
|
||||
rttMs: receivedMonoMs - sentMonoMs,
|
||||
remoteIp,
|
||||
reusedSocket: request.reusedSocket,
|
||||
protocol: 'http/1.1',
|
||||
connectionId,
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -107,7 +162,10 @@ export function requestKeyescape(options: KeyescapeRequestOptions): Promise<Keye
|
||||
request.destroy(new Error('예약 서버 응답 시간이 초과되었습니다.'))
|
||||
})
|
||||
request.on('socket', (socket) => {
|
||||
const captureAddress = () => { remoteIp = socket.remoteAddress ?? remoteIp }
|
||||
const captureAddress = () => {
|
||||
remoteIp = socket.remoteAddress ?? remoteIp
|
||||
connectionId = `h1-${socket.localPort ?? 'x'}-${socket.remotePort ?? 443}`
|
||||
}
|
||||
socket.once('connect', captureAddress)
|
||||
socket.once('secureConnect', captureAddress)
|
||||
if (socket.remoteAddress) captureAddress()
|
||||
@@ -118,6 +176,158 @@ export function requestKeyescape(options: KeyescapeRequestOptions): Promise<Keye
|
||||
})
|
||||
}
|
||||
|
||||
function createHttp2Session(): Promise<H2SessionRecord> {
|
||||
if (h2Session && !h2Session.goaway && !h2Session.session.closed && !h2Session.session.destroyed) {
|
||||
return Promise.resolve(h2Session)
|
||||
}
|
||||
if (h2Connecting) return h2Connecting
|
||||
|
||||
const pending = new Promise<H2SessionRecord>((resolve, reject) => {
|
||||
const session = http2.connect(ORIGIN, {
|
||||
settings: { enablePush: false },
|
||||
})
|
||||
h2ConnectingSession = session
|
||||
const record: H2SessionRecord = {
|
||||
session,
|
||||
id: `h2-${++h2Generation}`,
|
||||
remoteIp: '',
|
||||
streamCount: 0,
|
||||
goaway: false,
|
||||
}
|
||||
let connected = false
|
||||
|
||||
const failConnection = (error: Error) => {
|
||||
if (h2Session === record) h2Session = undefined
|
||||
if (!connected) reject(error)
|
||||
}
|
||||
session.on('error', failConnection)
|
||||
session.on('goaway', () => {
|
||||
record.goaway = true
|
||||
if (h2Session === record) h2Session = undefined
|
||||
})
|
||||
session.on('close', () => {
|
||||
record.goaway = true
|
||||
if (h2Session === record) h2Session = undefined
|
||||
if (!connected) reject(new Error('HTTP/2 세션이 연결 전에 종료되었습니다.'))
|
||||
})
|
||||
session.once('connect', () => {
|
||||
connected = true
|
||||
const socket = session.socket
|
||||
if (socket.alpnProtocol !== 'h2') {
|
||||
const error = new Error(`서버가 HTTP/2로 연결되지 않았습니다 (ALPN: ${socket.alpnProtocol || 'none'}).`)
|
||||
session.destroy(error)
|
||||
reject(error)
|
||||
return
|
||||
}
|
||||
record.remoteIp = socket.remoteAddress ?? ''
|
||||
h2Session = record
|
||||
if (h2ConnectingSession === session) h2ConnectingSession = undefined
|
||||
resolve(record)
|
||||
})
|
||||
})
|
||||
h2Connecting = pending
|
||||
pending.then(
|
||||
() => { if (h2Connecting === pending) h2Connecting = undefined },
|
||||
() => {
|
||||
if (h2Connecting === pending) h2Connecting = undefined
|
||||
if (h2ConnectingSession?.destroyed) h2ConnectingSession = undefined
|
||||
},
|
||||
)
|
||||
return pending
|
||||
}
|
||||
|
||||
const HTTP2_FORBIDDEN_HEADERS = new Set([
|
||||
'connection', 'host', 'http2-settings', 'keep-alive', 'proxy-connection', 'transfer-encoding', 'upgrade',
|
||||
])
|
||||
|
||||
function toHttp2Headers(options: KeyescapeRequestOptions): http2.OutgoingHttpHeaders {
|
||||
const headers: http2.OutgoingHttpHeaders = {
|
||||
':authority': HOSTNAME,
|
||||
':method': options.method,
|
||||
':path': options.path,
|
||||
':scheme': 'https',
|
||||
}
|
||||
const merged = { ...edgeBrowserHeaders(), ...options.headers }
|
||||
for (const [name, value] of Object.entries(merged)) {
|
||||
const lowerName = name.toLowerCase()
|
||||
if (!HTTP2_FORBIDDEN_HEADERS.has(lowerName)) headers[lowerName] = value
|
||||
}
|
||||
return headers
|
||||
}
|
||||
|
||||
async function requestKeyescapeHttp2(options: KeyescapeRequestOptions): Promise<KeyescapeResponse> {
|
||||
const record = await createHttp2Session()
|
||||
if (record.goaway || record.session.closed || record.session.destroyed) {
|
||||
if (h2Session === record) h2Session = undefined
|
||||
return requestKeyescapeHttp2(options)
|
||||
}
|
||||
|
||||
const reusedSocket = record.streamCount > 0
|
||||
record.streamCount += 1
|
||||
const sentAtMs = Date.now()
|
||||
const sentMonoMs = performance.now()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
let stream: http2.ClientHttp2Stream
|
||||
try {
|
||||
stream = record.session.request(toHttp2Headers(options), { endStream: !options.body })
|
||||
} catch (error) {
|
||||
reject(error)
|
||||
return
|
||||
}
|
||||
|
||||
let responseHeaders: ResponseHeaders = {}
|
||||
let statusCode = 0
|
||||
let receivedAtMs = sentAtMs
|
||||
let receivedMonoMs = sentMonoMs
|
||||
let settled = false
|
||||
const chunks: Buffer[] = []
|
||||
const finishWithError = (error: Error) => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
reject(error)
|
||||
}
|
||||
|
||||
stream.once('response', (headers) => {
|
||||
receivedAtMs = Date.now()
|
||||
receivedMonoMs = performance.now()
|
||||
statusCode = Number(headers[':status'] ?? 0)
|
||||
responseHeaders = headers as ResponseHeaders
|
||||
})
|
||||
stream.on('data', (chunk: Buffer) => chunks.push(Buffer.from(chunk)))
|
||||
stream.once('end', () => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
resolve({
|
||||
statusCode,
|
||||
headers: responseHeaders,
|
||||
body: Buffer.concat(chunks),
|
||||
sentAtMs,
|
||||
receivedAtMs,
|
||||
sentMonoMs,
|
||||
receivedMonoMs,
|
||||
rttMs: receivedMonoMs - sentMonoMs,
|
||||
remoteIp: record.remoteIp,
|
||||
reusedSocket,
|
||||
protocol: 'h2',
|
||||
connectionId: record.id,
|
||||
})
|
||||
})
|
||||
stream.once('error', finishWithError)
|
||||
stream.setTimeout(options.timeoutMs ?? 12_000, () => {
|
||||
stream.close(http2Constants.NGHTTP2_CANCEL)
|
||||
finishWithError(new Error('예약 서버 HTTP/2 응답 시간이 초과되었습니다.'))
|
||||
})
|
||||
if (options.body) stream.end(options.body)
|
||||
})
|
||||
}
|
||||
|
||||
export function requestKeyescape(options: KeyescapeRequestOptions): Promise<KeyescapeResponse> {
|
||||
return transportMode === 'http2'
|
||||
? requestKeyescapeHttp2(options)
|
||||
: requestKeyescapeHttp1(options)
|
||||
}
|
||||
|
||||
export function encodeMultipart(fields: Record<string, string>) {
|
||||
const boundary = `----WebKitFormBoundary${randomBytes(12).toString('base64url').slice(0, 16)}`
|
||||
const chunks: Buffer[] = []
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ipcMain, shell } from 'electron'
|
||||
import { ipcMain } from 'electron'
|
||||
import type {
|
||||
Branch,
|
||||
PriceOption,
|
||||
@@ -10,6 +10,7 @@ import type {
|
||||
TimeSlot,
|
||||
} from '../../src/type/reservation'
|
||||
import { edgeBrowserHeaders, encodeMultipart, requestKeyescape } from './keyescape-http'
|
||||
import { openCaptchaWindow } from './captcha-window'
|
||||
|
||||
const BASE_URL = 'https://www.keyescape.com'
|
||||
const API_URL = `${BASE_URL}/controller/run_proc.php`
|
||||
@@ -235,13 +236,8 @@ async function prepare(rawSelection: Record<string, unknown>): Promise<PriceOpti
|
||||
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}`,
|
||||
)
|
||||
async function openCaptcha(rawSelection: Record<string, unknown>) {
|
||||
return openCaptchaWindow(normalizeSelection(rawSelection))
|
||||
}
|
||||
|
||||
let reservationSubmissionInFlight = false
|
||||
@@ -321,6 +317,8 @@ async function executeReservationOnce(rawRequest: ReservationRequest): Promise<R
|
||||
httpStatus: response.statusCode,
|
||||
remoteIp: response.remoteIp,
|
||||
reusedSocket: response.reusedSocket,
|
||||
protocol: response.protocol,
|
||||
connectionId: response.connectionId,
|
||||
observedServerDateMs: Number.isFinite(observedServerDateMs) ? observedServerDateMs : undefined,
|
||||
}
|
||||
if (!result.status || !result.data) return { success: false, message, transport }
|
||||
|
||||
@@ -13,6 +13,8 @@ export interface RawClockObservation {
|
||||
serverDateHeader?: string
|
||||
remoteIp: string
|
||||
reusedSocket: boolean
|
||||
protocol?: 'http/1.1' | 'h2'
|
||||
connectionId?: string
|
||||
ageHeader?: string
|
||||
viaHeader?: string
|
||||
cacheHeader?: string
|
||||
@@ -50,6 +52,8 @@ export function observationToSample(observation: RawClockObservation): ClockSamp
|
||||
offsetMaxMs: finite(serverDateMs) + 1_000 - observation.sentAtMs,
|
||||
remoteIp: observation.remoteIp,
|
||||
reusedSocket: observation.reusedSocket,
|
||||
protocol: observation.protocol,
|
||||
connectionId: observation.connectionId,
|
||||
accepted: !rejectionReason,
|
||||
rejectionReason,
|
||||
}
|
||||
@@ -196,6 +200,9 @@ export function estimateClock(
|
||||
calibrationApplied: false,
|
||||
calibrationSettings: settings,
|
||||
remoteIp: '',
|
||||
protocol: undefined,
|
||||
connectionId: undefined,
|
||||
connectionReused: undefined,
|
||||
quality: 'unavailable',
|
||||
warning: '유효한 서버시간 표본이 없습니다.',
|
||||
samples: allRecent,
|
||||
@@ -264,6 +271,9 @@ export function estimateClock(
|
||||
calibrationApplied,
|
||||
calibrationSettings: settings,
|
||||
remoteIp: latest.remoteIp,
|
||||
protocol: latest.protocol,
|
||||
connectionId: latest.connectionId,
|
||||
connectionReused: latest.reusedSocket,
|
||||
quality,
|
||||
warning,
|
||||
samples: allRecent,
|
||||
|
||||
@@ -7,7 +7,12 @@ import {
|
||||
type TimingTestRequest,
|
||||
type TimingTestResult,
|
||||
} from '../../src/type/reservation'
|
||||
import { edgeBrowserHeaders, requestKeyescape } from './keyescape-http'
|
||||
import {
|
||||
disposeKeyescapeTransport,
|
||||
edgeBrowserHeaders,
|
||||
requestKeyescape,
|
||||
setKeyescapeTransportMode,
|
||||
} from './keyescape-http'
|
||||
import { appendClockSample, computePlannedSendAtMs, estimateClock, observationToSample } from './server-clock-core'
|
||||
|
||||
const CLOCK_EVENT = 'reservation:clock-state'
|
||||
@@ -35,6 +40,7 @@ export class ServerClockService {
|
||||
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)
|
||||
@@ -50,7 +56,10 @@ export class ServerClockService {
|
||||
? 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),
|
||||
@@ -63,8 +72,9 @@ export class ServerClockService {
|
||||
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.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()
|
||||
@@ -85,6 +95,9 @@ export class ServerClockService {
|
||||
}
|
||||
|
||||
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()
|
||||
@@ -121,6 +134,8 @@ export class ServerClockService {
|
||||
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']),
|
||||
@@ -131,10 +146,17 @@ export class ServerClockService {
|
||||
sample.rejectionReason = `설정된 최대 RTT ${this.settings.maxProbeRttMs}ms 초과`
|
||||
}
|
||||
|
||||
const previousIp = this.getEstimate().remoteIp
|
||||
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
|
||||
this.lastError = 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) {
|
||||
@@ -172,6 +194,8 @@ export class ServerClockService {
|
||||
uncertaintyMs: estimateAtSend.uncertaintyMs,
|
||||
remoteIp: sample.remoteIp,
|
||||
reusedSocket: sample.reusedSocket,
|
||||
protocol: sample.protocol,
|
||||
connectionId: sample.connectionId,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -182,6 +206,7 @@ export class ServerClockService {
|
||||
this.timer = undefined
|
||||
this.samples = []
|
||||
this.precisionBoundaryServerMs = undefined
|
||||
disposeKeyescapeTransport()
|
||||
}
|
||||
|
||||
private isRunning() {
|
||||
@@ -226,6 +251,7 @@ export class ServerClockService {
|
||||
}
|
||||
|
||||
private nextInterval() {
|
||||
if (this.quietUntilMs > Date.now()) return this.quietUntilMs - Date.now()
|
||||
return Math.min(this.regularInterval(), this.precisionInterval())
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "escape-reserve",
|
||||
"productName": "Escape Reserve",
|
||||
"version": "2.3.0",
|
||||
"version": "2.4.0",
|
||||
"private": true,
|
||||
"description": "A personal Keyescape reservation desk for Electron.",
|
||||
"license": "MIT",
|
||||
|
||||
+11
-10
@@ -13,7 +13,7 @@ import type {
|
||||
} from './type/reservation'
|
||||
import './reservation.css'
|
||||
|
||||
type LoadingKey = 'branches' | 'themes' | 'detail' | 'times' | 'prepare' | 'submit' | null
|
||||
type LoadingKey = 'branches' | 'themes' | 'detail' | 'times' | 'prepare' | 'captcha' | 'submit' | null
|
||||
|
||||
const inputClass = 'field-input'
|
||||
|
||||
@@ -257,16 +257,17 @@ function ReservationApp() {
|
||||
}
|
||||
|
||||
const openCaptcha = async () => {
|
||||
if (!selectedTheme) return
|
||||
if (!selection) return
|
||||
setError('')
|
||||
setLoading('captcha')
|
||||
try {
|
||||
await window.reservationApi.openCaptcha({
|
||||
branchNum,
|
||||
themeNum: selectedTheme.themeNum,
|
||||
themeInfoNum: selectedTheme.infoNum,
|
||||
})
|
||||
const authentication = await window.reservationApi.openCaptcha(selection)
|
||||
setCaptchaToken(authentication.token)
|
||||
setCaptchaPastedAtMs(authentication.solvedAtMs)
|
||||
} catch (reason) {
|
||||
setError(reason instanceof Error ? reason.message : '브라우저를 열지 못했습니다.')
|
||||
setError(reason instanceof Error ? reason.message : 'CAPTCHA 인증 창을 열지 못했습니다.')
|
||||
} finally {
|
||||
setLoading(null)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -441,8 +442,8 @@ function ReservationApp() {
|
||||
</section>
|
||||
|
||||
<section className={`panel-card overflow-hidden transition ${!scheduleDone ? 'opacity-45' : ''}`}>
|
||||
<div className="border-b border-line-soft p-5 sm:p-6"><div className="flex items-center justify-between gap-3"><div className="flex items-center gap-3"><span className="flex h-9 w-9 items-center justify-center rounded-full bg-accent/10 text-accent"><Icon name="shield" className="h-4 w-4" /></span><div><h2 className="text-sm font-semibold text-ink">캡차 인증</h2><p className="mt-0.5 text-[11px] text-ink-muted">브라우저에서 직접 인증 후 토큰을 붙여넣으세요.</p></div></div><button onClick={openCaptcha} disabled={!selectedTheme} className="inline-flex items-center gap-1.5 rounded-full border border-accent/30 px-3 py-2 text-[11px] font-semibold text-accent hover:bg-accent/10 disabled:opacity-30">브라우저 열기 <Icon name="external" className="h-3 w-3" /></button></div></div>
|
||||
<div className="p-5 sm:p-6"><textarea aria-label="캡차 토큰" value={captchaToken} onChange={(event) => { const value = event.target.value; setCaptchaToken(value); setCaptchaPastedAtMs(value.trim() ? Date.now() : null) }} disabled={!scheduleDone} rows={3} placeholder="g-recaptcha-response 토큰을 여기에 붙여넣기" spellCheck={false} className={`${inputClass} resize-none font-mono text-xs leading-5`} /><div className="mt-2 flex items-start justify-between gap-3 text-[10px] leading-4 text-ink-muted"><p>토큰은 짧은 시간 동안만 유효하며 한 번만 사용할 수 있습니다. 브라우저에서도 앱과 같은 날짜·시간을 선택하세요.</p>{captchaToken && <span className="shrink-0 rounded-full bg-success/10 px-2 py-1 font-semibold text-success">메모리 전용</span>}</div></div>
|
||||
<div className="border-b border-line-soft p-5 sm:p-6"><div className="flex items-center justify-between gap-3"><div className="flex items-center gap-3"><span className="flex h-9 w-9 items-center justify-center rounded-full bg-accent/10 text-accent"><Icon name="shield" className="h-4 w-4" /></span><div><h2 className="text-sm font-semibold text-ink">캡차 인증</h2><p className="mt-0.5 text-[11px] text-ink-muted">선택한 시간의 공식 2단계 페이지를 앱 안에서 엽니다.</p></div></div><button onClick={openCaptcha} disabled={!selection || loading === 'captcha'} className="inline-flex items-center gap-1.5 rounded-full border border-accent/30 px-3 py-2 text-[11px] font-semibold text-accent hover:bg-accent/10 disabled:opacity-30">{loading === 'captcha' ? '인증 대기 중…' : captchaToken ? '다시 인증' : '앱에서 인증'} <Icon name={captchaToken ? 'refresh' : 'external'} className="h-3 w-3" /></button></div></div>
|
||||
<div className="p-5 sm:p-6"><textarea aria-label="캡차 토큰" value={captchaToken} onChange={(event) => { const value = event.target.value; setCaptchaToken(value); setCaptchaPastedAtMs(value.trim() ? Date.now() : null) }} disabled={!scheduleDone || loading === 'captcha'} rows={3} placeholder="앱에서 인증하면 토큰이 자동으로 입력됩니다. 필요한 경우 직접 붙여넣을 수도 있습니다." spellCheck={false} className={`${inputClass} resize-none font-mono text-xs leading-5`} /><div className="mt-2 flex items-start justify-between gap-3 text-[10px] leading-4 text-ink-muted"><p>인증 창에서는 실제 예약 제출이 차단됩니다. 인증이 끝나면 창이 자동으로 닫히며 토큰은 메모리에만 보관됩니다.</p>{captchaToken && <span className="shrink-0 rounded-full bg-success/10 px-2 py-1 font-semibold text-success">인증 완료</span>}</div></div>
|
||||
</section>
|
||||
|
||||
{autoMode && <AutomationPanel request={autoRequest} captchaToken={captchaToken} captchaPastedAtMs={captchaPastedAtMs} onTokenConsumed={() => { setCaptchaToken(''); setCaptchaPastedAtMs(null) }} onResult={setResult} />}
|
||||
|
||||
@@ -122,6 +122,7 @@ export default function AutomationPanel({
|
||||
const [clockSettings, setClockSettings] = useState<ClockCalibrationSettings>(loadClockSettings)
|
||||
const previousFingerprint = useRef('')
|
||||
const previousAutoStatus = useRef(autoState.status)
|
||||
const previousCaptchaAt = useRef<number | null>(null)
|
||||
const targetServerTimeMs = parseKstInput(targetInput)
|
||||
const liveServerTimeMs = clock
|
||||
? clock.estimatedServerTimeMs + (nowMs - clock.observedAtMs)
|
||||
@@ -132,6 +133,7 @@ export default function AutomationPanel({
|
||||
? targetServerTimeMs - (captchaPastedAtMs + (clock?.offsetMs ?? 0))
|
||||
: Number.POSITIVE_INFINITY
|
||||
const tokenReady = captchaToken.trim().length >= 30 && tokenAgeAtTargetMs >= 0 && tokenAgeAtTargetMs <= 90_000
|
||||
const armed = autoState.status === 'armed' || autoState.status === 'firing'
|
||||
|
||||
const requestFingerprint = useMemo(() => request ? JSON.stringify({
|
||||
...request,
|
||||
@@ -163,6 +165,17 @@ export default function AutomationPanel({
|
||||
previousFingerprint.current = requestFingerprint
|
||||
}, [requestFingerprint, autoState.status])
|
||||
|
||||
useEffect(() => {
|
||||
if (!captchaPastedAtMs || captchaPastedAtMs === previousCaptchaAt.current || armed) return
|
||||
previousCaptchaAt.current = captchaPastedAtMs
|
||||
const estimatedServerNow = clock
|
||||
? clock.estimatedServerTimeMs + (Date.now() - clock.observedAtMs)
|
||||
: Date.now()
|
||||
if (!Number.isFinite(targetServerTimeMs) || targetServerTimeMs <= estimatedServerNow + 150) {
|
||||
setTargetInput(toKstInput(estimatedServerNow + 30_000))
|
||||
}
|
||||
}, [armed, captchaPastedAtMs, clock, targetServerTimeMs])
|
||||
|
||||
useEffect(() => {
|
||||
if (previousAutoStatus.current !== autoState.status) {
|
||||
if (autoState.status === 'firing') onTokenConsumed()
|
||||
@@ -252,7 +265,6 @@ export default function AutomationPanel({
|
||||
}
|
||||
|
||||
const qualityTone = clock?.quality === 'good' ? 'good' : clock?.quality === 'poor' || clock?.quality === 'unavailable' ? 'warn' : 'normal'
|
||||
const armed = autoState.status === 'armed' || autoState.status === 'firing'
|
||||
|
||||
return (
|
||||
<section className="panel-card overflow-hidden" aria-label="자동 예약 및 서버시간">
|
||||
@@ -279,6 +291,7 @@ export default function AutomationPanel({
|
||||
<Metric label="sample age" value={clock?.acceptedSamples ? formatDuration(clock.sampleAgeMs + (nowMs - clock.observedAtMs)) : '—'} />
|
||||
<Metric label="drift" value={`${(clock?.driftPpm ?? 0).toFixed(2)}ppm`} />
|
||||
<Metric label="remote" value={clock?.remoteIp || '—'} />
|
||||
<Metric label="transport" value={`${clock?.protocol ?? (clockSettings.transportMode === 'http2' ? 'h2' : 'http/1.1')} · ${clock?.connectionId ?? 'not connected'}`} tone={clock?.protocol === 'h2' ? 'good' : 'normal'} />
|
||||
<Metric label="boundaries" value={`${clock?.boundaryCount ?? 0} / ${clock?.calibrationSettings.requiredBoundaryCount ?? CLOCK_CALIBRATION_DEFAULTS.requiredBoundaryCount}`} tone={clock?.calibrationReady ? 'good' : 'warn'} />
|
||||
<Metric label="phase spread" value={clock?.boundarySpreadMs === undefined ? '—' : `${clock.boundarySpreadMs.toFixed(1)}ms`} tone={clock?.calibrationReady ? 'good' : 'warn'} />
|
||||
<Metric label="recommended" value={`${(clock?.recommendedCorrectionMs ?? 0) >= 0 ? '+' : ''}${(clock?.recommendedCorrectionMs ?? 0).toFixed(1)}ms`} />
|
||||
@@ -294,6 +307,7 @@ export default function AutomationPanel({
|
||||
{clock?.warning && <p className="mt-2 text-[10px] leading-4 text-warning">{clock.warning} 품질이 낮아도 마지막 유효 추정값으로 1회 실행합니다.</p>}
|
||||
<div className="mt-3 flex justify-end"><button onClick={() => setSettingsOpen((value) => !value)} disabled={armed} className="rounded-full border border-line px-3 py-2 text-[10px] font-semibold text-ink-muted hover:text-ink disabled:opacity-40">정밀 보정 설정</button></div>
|
||||
{settingsOpen && <div className="mt-3 rounded-xl border border-line-soft bg-canvas p-4">
|
||||
<label className="mb-4 block space-y-1"><span className="text-[9px] font-semibold text-ink-muted">전송 모드</span><select value={clockSettings.transportMode} onChange={(event) => setClockSettings((current) => ({ ...current, transportMode: event.target.value as ClockCalibrationSettings['transportMode'] }))} className="w-full rounded-lg border border-line bg-surface px-3 py-2 font-mono text-xs text-ink outline-none focus:border-accent"><option value="http1">HTTP/1.1 keep-alive (기존)</option><option value="http2">HTTP/2 단일 세션</option></select><span className="block text-[9px] leading-4 text-ink-muted">모드 전환 시 RTT 특성이 달라 기존 시간 보정을 초기화하고 다시 수집합니다.</span></label>
|
||||
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{([
|
||||
['scanWindowMs', '경계 탐색 범위 (ms)', 100, 450],
|
||||
@@ -317,7 +331,7 @@ export default function AutomationPanel({
|
||||
<div><h3 className="text-sm font-semibold text-ink">시간 테스트</h3><p className="mt-1 text-[10px] text-ink-muted">3초 뒤 HEAD 요청으로 스케줄러와 도착 오차를 측정합니다.</p></div>
|
||||
<button onClick={runTimingTest} disabled={busy === 'test' || armed} className="rounded-full border border-line px-3 py-2 text-[11px] font-semibold text-ink-muted hover:border-ink hover:text-ink disabled:opacity-40">{busy === 'test' ? '테스트 중…' : '3초 테스트'}</button>
|
||||
</div>
|
||||
{timingTest && <div className="mt-3 grid grid-cols-2 gap-2 sm:grid-cols-4"><Metric label="arrival error" value={`${timingTest.arrivalErrorMs >= 0 ? '+' : ''}${timingTest.arrivalErrorMs.toFixed(1)}ms`} tone={Math.abs(timingTest.arrivalErrorMs) <= timingTest.uncertaintyMs ? 'good' : 'warn'} /><Metric label="timer jitter" value={`${timingTest.schedulerJitterMs >= 0 ? '+' : ''}${timingTest.schedulerJitterMs.toFixed(1)}ms`} /><Metric label="RTT" value={`${timingTest.rttMs.toFixed(1)}ms`} /><Metric label="socket" value={timingTest.reusedSocket ? 'reused' : 'new'} /></div>}
|
||||
{timingTest && <div className="mt-3 grid grid-cols-2 gap-2 sm:grid-cols-4"><Metric label="arrival error" value={`${timingTest.arrivalErrorMs >= 0 ? '+' : ''}${timingTest.arrivalErrorMs.toFixed(1)}ms`} tone={Math.abs(timingTest.arrivalErrorMs) <= timingTest.uncertaintyMs ? 'good' : 'warn'} /><Metric label="timer jitter" value={`${timingTest.schedulerJitterMs >= 0 ? '+' : ''}${timingTest.schedulerJitterMs.toFixed(1)}ms`} /><Metric label="RTT" value={`${timingTest.rttMs.toFixed(1)}ms`} /><Metric label="connection" value={`${timingTest.protocol ?? '—'} ${timingTest.connectionId ?? ''} · ${timingTest.reusedSocket ? 'reused' : 'new'}`} /></div>}
|
||||
</div>
|
||||
|
||||
<div className="p-5 sm:p-6">
|
||||
@@ -328,9 +342,10 @@ export default function AutomationPanel({
|
||||
</div>
|
||||
<div className="mt-3 grid grid-cols-2 gap-2"><Metric label="countdown" value={formatDuration(countdownMs)} tone={countdownMs > 0 ? 'good' : 'warn'} /><Metric label="token at target" value={Number.isFinite(tokenAgeAtTargetMs) ? formatDuration(tokenAgeAtTargetMs) : '토큰 없음'} tone={tokenReady ? 'good' : 'warn'} /></div>
|
||||
<div className="mt-3 rounded-xl border border-line-soft bg-canvas p-3 text-[10px] leading-5 text-ink-muted"><div className="flex justify-between gap-3"><span>토큰</span><span className={tokenReady ? 'font-semibold text-success' : 'font-semibold text-warning'}>{captchaToken ? `${captchaToken.slice(0, 6)}••••${captchaToken.slice(-4)} · ${formatDuration(tokenAgeMs)}` : '입력되지 않음'}</span></div>{autoState.snapshot && <><div className="flex justify-between gap-3"><span>고정 스냅샷</span><span className="text-right text-ink">{autoState.snapshot.themeName} · {autoState.snapshot.date} {autoState.snapshot.timeLabel} · {autoState.snapshot.person}명</span></div><div className="flex justify-between gap-3"><span>예정 발송</span><span className="font-mono text-ink">{autoState.timeline?.plannedSendAtMs ? formatClock(autoState.timeline.plannedSendAtMs) : '계산 중'}</span></div></>}</div>
|
||||
{autoState.timeline?.actualSendAtMs && <div className="mt-3 grid grid-cols-2 gap-2 sm:grid-cols-4"><Metric label="actual send" value={formatClock(autoState.timeline.actualSendAtMs).split(' ').at(-1) ?? '—'} /><Metric label="arrival error" value={autoState.timeline.arrivalErrorMs === undefined ? '—' : `${autoState.timeline.arrivalErrorMs >= 0 ? '+' : ''}${autoState.timeline.arrivalErrorMs.toFixed(1)}ms`} /><Metric label="response RTT" value={autoState.timeline.rttMs === undefined ? '—' : `${autoState.timeline.rttMs.toFixed(1)}ms`} /><Metric label="HTTP / socket" value={`${autoState.timeline.httpStatus ?? '—'} / ${autoState.timeline.reusedSocket ? 'reused' : 'new'}`} /></div>}
|
||||
{autoState.timeline?.actualSendAtMs && <div className="mt-3 grid grid-cols-2 gap-2 sm:grid-cols-4"><Metric label="actual send" value={formatClock(autoState.timeline.actualSendAtMs).split(' ').at(-1) ?? '—'} /><Metric label="arrival error" value={autoState.timeline.arrivalErrorMs === undefined ? '—' : `${autoState.timeline.arrivalErrorMs >= 0 ? '+' : ''}${autoState.timeline.arrivalErrorMs.toFixed(1)}ms`} /><Metric label="response RTT" value={autoState.timeline.rttMs === undefined ? '—' : `${autoState.timeline.rttMs.toFixed(1)}ms`} /><Metric label="HTTP / connection" value={`${autoState.timeline.httpStatus ?? '—'} · ${autoState.timeline.protocol ?? '—'} ${autoState.timeline.connectionId ?? ''} · ${autoState.timeline.reusedSocket ? 'reused' : 'new'}`} /></div>}
|
||||
{(error || autoState.message) && <p role="alert" className={`mt-3 rounded-xl border px-3 py-2 text-[10px] leading-4 ${error || autoState.status === 'failed' ? 'border-danger/25 bg-danger/8 text-danger' : 'border-success/25 bg-success/8 text-success'}`}>{error || autoState.message}</p>}
|
||||
<div className="mt-4 grid grid-cols-2 gap-2">{armed ? <button onClick={disarm} disabled={autoState.status === 'firing'} className="col-span-2 rounded-xl border border-danger/30 py-3 text-xs font-semibold text-danger hover:bg-danger/8 disabled:opacity-40">자동 예약 해제</button> : <button onClick={arm} disabled={busy === 'arm' || !request || !tokenReady} className="col-span-2 rounded-xl bg-coral py-3 text-xs font-bold text-coral-ink hover:bg-coral-strong disabled:cursor-not-allowed disabled:bg-chrome disabled:text-ink-muted">{busy === 'arm' ? '시작 중…' : '자동 예약 시작'}</button>}</div>
|
||||
{!armed && (!request || !tokenReady) && <p className="mt-3 text-[10px] leading-4 text-warning">{!request ? '예약자 정보·인원·동의와 CAPTCHA 인증을 완료해주세요.' : tokenAgeAtTargetMs < 0 ? '실행 시각이 이미 지났습니다. 미래 시각으로 변경해주세요.' : 'CAPTCHA 인증 후 90초 이내의 실행 시각을 입력해주세요.'}</p>}
|
||||
<div className="mt-4 grid grid-cols-2 gap-2">{armed ? <button onClick={disarm} disabled={autoState.status === 'firing'} className="col-span-2 rounded-xl border border-danger/30 py-3 text-xs font-semibold text-danger hover:bg-danger/8 disabled:opacity-40">자동 예약 해제</button> : <button onClick={arm} disabled={busy === 'arm'} className="col-span-2 rounded-xl bg-coral py-3 text-xs font-bold text-coral-ink hover:bg-coral-strong disabled:cursor-not-allowed disabled:bg-chrome disabled:text-ink-muted">{busy === 'arm' ? '시작 중…' : '자동 예약 시작'}</button>}</div>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
|
||||
+19
-1
@@ -60,6 +60,11 @@ export interface ReservationResult {
|
||||
transport?: ReservationTransport
|
||||
}
|
||||
|
||||
export interface CaptchaResult {
|
||||
token: string
|
||||
solvedAtMs: number
|
||||
}
|
||||
|
||||
export interface ReservationTransport {
|
||||
sentAtMs: number
|
||||
receivedAtMs: number
|
||||
@@ -67,6 +72,8 @@ export interface ReservationTransport {
|
||||
httpStatus: number
|
||||
remoteIp: string
|
||||
reusedSocket: boolean
|
||||
protocol?: 'http/1.1' | 'h2'
|
||||
connectionId?: string
|
||||
observedServerDateMs?: number
|
||||
}
|
||||
|
||||
@@ -82,11 +89,14 @@ export interface ClockSample {
|
||||
offsetMaxMs: number
|
||||
remoteIp: string
|
||||
reusedSocket: boolean
|
||||
protocol?: 'http/1.1' | 'h2'
|
||||
connectionId?: string
|
||||
accepted: boolean
|
||||
rejectionReason?: string
|
||||
}
|
||||
|
||||
export interface ClockCalibrationSettings {
|
||||
transportMode: 'http1' | 'http2'
|
||||
enabled: boolean
|
||||
autoApply: boolean
|
||||
scanWindowMs: number
|
||||
@@ -101,6 +111,7 @@ export interface ClockCalibrationSettings {
|
||||
}
|
||||
|
||||
export const CLOCK_CALIBRATION_DEFAULTS: ClockCalibrationSettings = {
|
||||
transportMode: 'http1',
|
||||
enabled: true,
|
||||
autoApply: true,
|
||||
scanWindowMs: 250,
|
||||
@@ -137,6 +148,9 @@ export interface ClockEstimate {
|
||||
calibrationApplied: boolean
|
||||
calibrationSettings: ClockCalibrationSettings
|
||||
remoteIp: string
|
||||
protocol?: 'http/1.1' | 'h2'
|
||||
connectionId?: string
|
||||
connectionReused?: boolean
|
||||
quality: 'good' | 'fair' | 'poor' | 'unavailable'
|
||||
warning?: string
|
||||
samples: ClockSample[]
|
||||
@@ -158,6 +172,8 @@ export interface TimingTestResult {
|
||||
uncertaintyMs: number
|
||||
remoteIp: string
|
||||
reusedSocket: boolean
|
||||
protocol?: 'http/1.1' | 'h2'
|
||||
connectionId?: string
|
||||
}
|
||||
|
||||
export interface AutoReservationConfig {
|
||||
@@ -188,6 +204,8 @@ export interface AutoReservationTimeline {
|
||||
httpStatus?: number
|
||||
remoteIp?: string
|
||||
reusedSocket?: boolean
|
||||
protocol?: 'http/1.1' | 'h2'
|
||||
connectionId?: string
|
||||
}
|
||||
|
||||
export interface AutoReservationState {
|
||||
@@ -210,7 +228,7 @@ export interface ReservationApi {
|
||||
getThemeDetail(themeInfoNum: number): Promise<ThemeDetail>
|
||||
getTimes(selection: Pick<ReservationSelection, 'date' | 'branchNum' | 'themeNum'>): Promise<TimeSlot[]>
|
||||
prepare(selection: ReservationSelection): Promise<PriceOption[]>
|
||||
openCaptcha(selection: Pick<ReservationSelection, 'branchNum' | 'themeNum' | 'themeInfoNum'>): Promise<void>
|
||||
openCaptcha(selection: ReservationSelection): Promise<CaptchaResult>
|
||||
submit(request: ReservationRequest): Promise<ReservationResult>
|
||||
startClockMonitor(): Promise<ClockEstimate>
|
||||
stopClockMonitor(): Promise<ClockEstimate>
|
||||
|
||||
+11
-5
@@ -101,17 +101,23 @@ test.describe('[escape-reserve] e2e tests', () => {
|
||||
|
||||
test('monitors live server time and runs a safe timing probe', async () => {
|
||||
await page.getByRole('button', { name: '자동 예약' }).click()
|
||||
await page.getByRole('button', { name: '정밀 보정 설정' }).click()
|
||||
await expect(page.getByText('경계 측정 간격 (ms)')).toBeVisible()
|
||||
await page.getByLabel('전송 모드').selectOption('http2')
|
||||
await page.getByRole('button', { name: '설정 적용' }).click()
|
||||
await page.getByRole('button', { name: '모니터 시작' }).click()
|
||||
await expect(page.getByRole('button', { name: '모니터 중지' })).toBeVisible({ timeout: 10_000 })
|
||||
await expect(page.getByLabel('관측 서버시간 값')).toContainText(':')
|
||||
|
||||
await page.getByRole('button', { name: '정밀 보정 설정' }).click()
|
||||
await expect(page.getByText('경계 측정 간격 (ms)')).toBeVisible()
|
||||
await page.getByRole('button', { name: '기본값' }).click()
|
||||
await page.getByRole('button', { name: '설정 적용' }).click()
|
||||
await expect.poll(() => page.evaluate(async () => (await window.reservationApi.getClockState()).protocol), {
|
||||
timeout: 10_000,
|
||||
}).toBe('h2')
|
||||
|
||||
await page.getByRole('button', { name: '3초 테스트' }).click()
|
||||
await expect(page.getByText('arrival error')).toBeVisible({ timeout: 10_000 })
|
||||
const h2State = await page.evaluate(() => window.reservationApi.getClockState())
|
||||
expect(h2State.protocol).toBe('h2')
|
||||
expect(h2State.connectionId).toMatch(/^h2-\d+$/)
|
||||
expect(h2State.connectionReused).toBe(true)
|
||||
})
|
||||
|
||||
test('arms and disarms an automatic reservation without submitting', async () => {
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { EDGE_USER_AGENT, edgeBrowserHeaders, encodeMultipart } from '../electron/main/keyescape-http'
|
||||
import {
|
||||
EDGE_USER_AGENT,
|
||||
edgeBrowserHeaders,
|
||||
encodeMultipart,
|
||||
getKeyescapeTransportMode,
|
||||
setKeyescapeTransportMode,
|
||||
} from '../electron/main/keyescape-http'
|
||||
|
||||
describe('Edge-compatible Keyescape request metadata', () => {
|
||||
it('matches the captured Edge client hints and XHR metadata', () => {
|
||||
@@ -17,6 +23,8 @@ describe('Edge-compatible Keyescape request metadata', () => {
|
||||
expect(headers['Sec-Fetch-Mode']).toBe('cors')
|
||||
expect(headers['Sec-Fetch-Dest']).toBe('empty')
|
||||
expect(headers['X-Requested-With']).toBe('XMLHttpRequest')
|
||||
expect(headers.Origin).toBe('https://www.keyescape.com')
|
||||
expect(headers.Priority).toBe('u=1, i')
|
||||
expect(headers.Referer).toBe('https://www.keyescape.com/reservation2.php')
|
||||
})
|
||||
|
||||
@@ -30,4 +38,12 @@ describe('Edge-compatible Keyescape request metadata', () => {
|
||||
expect(first.body.toString('utf8')).toContain('Content-Disposition: form-data; name="device"')
|
||||
expect(first.body.toString('utf8')).toMatch(/--\r\n$/)
|
||||
})
|
||||
|
||||
it('switches explicitly between the legacy and HTTP/2 transports', () => {
|
||||
setKeyescapeTransportMode('http2')
|
||||
expect(getKeyescapeTransportMode()).toBe('http2')
|
||||
expect(setKeyescapeTransportMode('http2')).toBe(false)
|
||||
expect(setKeyescapeTransportMode('http1')).toBe(true)
|
||||
expect(getKeyescapeTransportMode()).toBe('http1')
|
||||
})
|
||||
})
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 79 KiB After Width: | Height: | Size: 117 KiB |
Reference in new issue
Block a user