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 interface H2SessionRecord { session: ClientHttp2Session id: string remoteIp: string streamCount: number goaway: boolean } let transportMode: KeyescapeTransportMode = 'http1' let h2Session: H2SessionRecord | undefined let h2Connecting: Promise | 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' export interface EdgeHeaderOptions { accept?: string referer?: string navigation?: boolean xhr?: boolean } export function edgeBrowserHeaders(options: EdgeHeaderOptions = {}): Record { const headers: Record = { 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' headers.Origin = ORIGIN headers.Priority = 'u=1, i' } 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: ResponseHeaders body: Buffer sentAtMs: number receivedAtMs: number sentMonoMs: number receivedMonoMs: number rttMs: number remoteIp: string reusedSocket: boolean protocol: 'http/1.1' | 'h2' connectionId: string } export interface KeyescapeRequestOptions { method: 'GET' | 'HEAD' | 'POST' path: string headers?: Record body?: Buffer timeoutMs?: number } 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 { return new Promise((resolve, reject) => { const sentAtMs = Date.now() const sentMonoMs = performance.now() let remoteIp = '' let connectionId = '' 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, protocol: 'http/1.1', connectionId, }) }) }) request.setTimeout(options.timeoutMs ?? 12_000, () => { request.destroy(new Error('예약 서버 응답 시간이 초과되었습니다.')) }) request.on('socket', (socket) => { 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() }) request.on('error', reject) if (options.body) request.write(options.body) request.end() }) } function createHttp2Session(): Promise { if (h2Session && !h2Session.goaway && !h2Session.session.closed && !h2Session.session.destroyed) { return Promise.resolve(h2Session) } if (h2Connecting) return h2Connecting const pending = new Promise((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 { 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 { return transportMode === 'http2' ? requestKeyescapeHttp2(options) : requestKeyescapeHttp1(options) } export function encodeMultipart(fields: Record) { 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) } }