This commit is contained in:
dahyeon committed 2026-08-13 01:34:54 +09:00
1 parent d2c03d155d
commit db60190e19
13 files changed
+505 -38

No files matched your search

+214 -4
View File
@@ -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[] = []