.
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())
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user