Files
test-project-161/electron/main/captcha-window.ts
T
2026-08-13 01:34:54 +09:00

166 lines
5.7 KiB
TypeScript

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 페이지를 열지 못했습니다.'))
})
}