dongsik22 Claude Opus 4.8 (1M context) commited on
Commit
6a3dbdb
·
1 Parent(s): 5a3ed3f

fix(tvchak): CDP 창 무한 깜빡임 + 탭 폭증 제거 — 도메인 추종/창 띄우기 루프 걷어냄

Browse files

운영자가 콘텐츠 도메인 번호를 207→...→213→.live로 수시 변경하는 상황에서
announceFollower(5분 주기 재탐색) + cfClearanceMonitor(2분 주기 cf 창 띄우기)가
맞물려 robots 헬퍼 탭이 폭증(213개+)하고 CDP Chrome 창이 활성화↔최소화를
무한 반복하는 사고 발생.

- announceFollower / cfClearanceMonitor / triggerCfChallengeUi 전부 제거.
주기적 재탐색 + 창 foreground 복원이 깜빡임/탭폭증의 근원이었음.
- findLiveDomain을 단순화: tvchak.org announce를 읽어 그 도메인 그대로 채택.
±5 인접번호 polling, 후보 12개 probe, KNOWN_CONTENT_DOMAINS/stale 후보 제거
(probe가 매번 robots 탭을 만들어 폭증을 유발했음). 캐시는 10분 신뢰(probe 안 함).
- FORCE_DOMAIN 환경변수 추가 — announce/캐시 무시하고 고정 도메인 사용.
현재 announce(tvchak208.com)가 이 PC 공인 IP에 차단(유지보수중 위장)돼,
사용자가 cf challenge 통과시킨 tvchak.live로 고정 운영 중.
- /api/diag/cf-monitor는 창 띄우기 없이 fetch 결과만 보고하도록 축소.

검증: idle 8~12초 창 화면 밖 고정(깜빡임 0), CDP 탭 2개로 수렴,
.live 고정 후 /api/play mp4 정상, 검색·랭킹 정상.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TwvJyPvTeaxcGDJUni8JB8

Files changed (1) hide show
  1. server.js +44 -255
server.js CHANGED
@@ -579,6 +579,8 @@ function nasFetch(fullUrl, timeoutMs = 15000) {
579
  // SNI 풀리면 USE_LOCAL_CDP 환경변수만 빼면 기존 NAS/Playwright 경로로 자동 원복.
580
  const USE_LOCAL_CDP = process.env.USE_LOCAL_CDP === '1';
581
  const LOCAL_CDP_URL = process.env.LOCAL_CDP_URL || 'http://127.0.0.1:9222';
 
 
582
  let _cdpBrowser = null;
583
  let _cdpCtx = null;
584
  let _cdpPage = null;
@@ -614,131 +616,11 @@ function minimizeCdpChromeWindow() {
614
  return _minimizeInFlight;
615
  }
616
 
617
- // cf_clearance 만료 감지 시 사용자가 cf challenge 통과할 수 있도록 CDP Chrome 창을 foreground로 띄움.
618
- // 1) /json/new PUT으로 announce 도메인 메인 페이지 새 탭 (이미 있으면 그 탭 activate)
619
- // 2) Win32 SW_RESTORE + 화면 안쪽 위치 + SetForegroundWindow
620
- // 쿨다운(_cfChallengeLastTriggerAt)으로 5분 안엔 재호출 금지 — 사용자가 짜증나지 않게.
621
- let _cfChallengeLastTriggerAt = 0;
622
- const CF_CHALLENGE_COOLDOWN_MS = 5 * 60 * 1000;
623
- async function triggerCfChallengeUi(domain) {
624
- const now = Date.now();
625
- if (now - _cfChallengeLastTriggerAt < CF_CHALLENGE_COOLDOWN_MS) return false;
626
- _cfChallengeLastTriggerAt = now;
627
- console.warn(`[cf-monitor] cf challenge detected on ${domain} — bringing CDP Chrome to foreground`);
628
-
629
- // 1) 새 탭 띄우거나 기존 탭 activate
630
- try {
631
- const u = new URL('/json/list', LOCAL_CDP_URL);
632
- const listResp = await new Promise((resolve, reject) => {
633
- const req = http.get({ hostname: u.hostname, port: u.port || 9222, path: u.pathname, timeout: 3000 }, (res) => {
634
- let buf = '';
635
- res.on('data', (d) => buf += d);
636
- res.on('end', () => resolve(buf));
637
- });
638
- req.on('error', reject);
639
- req.on('timeout', () => { req.destroy(); reject(new Error('list timeout')); });
640
- });
641
- const targets = JSON.parse(listResp);
642
- const targetUrl = `https://${domain}/`;
643
- let tab = targets.find((t) => t.type === 'page' && t.url === targetUrl);
644
- if (!tab) {
645
- // PUT /json/new?<url>
646
- const newPath = `/json/new?${encodeURIComponent(targetUrl)}`;
647
- const newResp = await new Promise((resolve, reject) => {
648
- const req = http.request({ hostname: u.hostname, port: u.port || 9222, path: newPath, method: 'PUT', timeout: 5000 }, (res) => {
649
- let buf = '';
650
- res.on('data', (d) => buf += d);
651
- res.on('end', () => resolve(buf));
652
- });
653
- req.on('error', reject);
654
- req.on('timeout', () => { req.destroy(); reject(new Error('new timeout')); });
655
- req.end();
656
- });
657
- tab = JSON.parse(newResp);
658
- }
659
- // activate
660
- await new Promise((resolve) => {
661
- const req = http.get({ hostname: u.hostname, port: u.port || 9222, path: `/json/activate/${tab.id}`, timeout: 3000 }, (res) => {
662
- res.resume(); res.on('end', resolve);
663
- });
664
- req.on('error', () => resolve());
665
- req.on('timeout', () => { req.destroy(); resolve(); });
666
- });
667
- } catch (e) {
668
- console.warn('[cf-monitor] tab activate failed:', e.message);
669
- }
670
-
671
- // 2) Win32 창 복원 + foreground. PowerShell oneshot.
672
- const restoreScript = "$ErrorActionPreference='SilentlyContinue';" +
673
- "if(-not('CFR.Win'-as[Type])){Add-Type -Namespace CFR -Name Win -MemberDefinition '" +
674
- "[DllImport(\"user32.dll\")]public static extern bool ShowWindow(System.IntPtr hWnd,int nCmdShow);" +
675
- "[DllImport(\"user32.dll\")]public static extern bool MoveWindow(System.IntPtr hWnd,int X,int Y,int nWidth,int nHeight,bool bRepaint);" +
676
- "[DllImport(\"user32.dll\")]public static extern bool SetForegroundWindow(System.IntPtr hWnd);'};" +
677
- "Get-CimInstance Win32_Process -Filter \"Name='chrome.exe'\"|" +
678
- "?{$_.CommandLine -like '*--remote-debugging-port=9222*'}|" +
679
- "%{Get-Process -Id $_.ProcessId -EA SilentlyContinue}|" +
680
- "?{$_.MainWindowHandle -ne 0}|Select-Object -First 1|%{" +
681
- "[CFR.Win]::ShowWindow($_.MainWindowHandle,9)|Out-Null;" +
682
- "[CFR.Win]::MoveWindow($_.MainWindowHandle,100,100,1400,900,$true)|Out-Null;" +
683
- "[CFR.Win]::SetForegroundWindow($_.MainWindowHandle)|Out-Null}";
684
- const { spawn } = require('child_process');
685
- await new Promise((resolve) => {
686
- const p = spawn('powershell.exe', ['-NoProfile', '-WindowStyle', 'Hidden', '-Command', restoreScript], { windowsHide: true });
687
- p.on('exit', resolve);
688
- p.on('error', resolve);
689
- });
690
- return true;
691
- }
692
-
693
- // announce 도메인이 cf challenge에 막혔는지 5분마다 점검.
694
- // 막혔으면 triggerCfChallengeUi로 사용자에게 Chrome 창 띄워줌.
695
- async function cfClearanceMonitor() {
696
- try {
697
- const cached = readCachePermanent('domain.json');
698
- const domain = cached && cached.announced;
699
- if (!domain) return;
700
- const r = await tvFetchCDP(domain, '/index.php/vod/play/id/122862/sid/1/nid/1.html');
701
- if (r.ok) return; // 정상 — cf 통과 상태
702
- // 403이면 cf challenge로 간주 (announce된 도메인은 운영 중이므로 403 = 인증 부족).
703
- // body 패턴 매치는 보조 — Turnstile JS challenge는 raw fetch body에 패턴이 안 보일 수 있음.
704
- const looksLikeCf =
705
- r.status === 403 ||
706
- /challenge-platform|cf-chl|turnstile|cf_chl_|Just a moment|잠시만 기다리/i.test(r.body || '');
707
- if (looksLikeCf) {
708
- console.warn(`[cf-monitor] suspect cf challenge on ${domain} (status=${r.status}) — triggering UI`);
709
- await triggerCfChallengeUi(domain);
710
- }
711
- } catch (e) {
712
- console.warn('[cf-monitor] check failed:', e.message);
713
- }
714
- }
715
-
716
- // 선제적 도메인 추종 (2026-06-30): tvchak.org가 안내하는 활성 주소가 바뀌면,
717
- // 기존 도메인이 죽기를 기다리지 않고 미리 새 도메인으로 갈아탄다.
718
- // 기존 동작은 "캐시 도메인이 probe 실패할 때만" 재탐색 → 전환 순간 끊김 발생.
719
- // 여기서 주기적으로 announce를 읽어 현재 채택 도메인과 다르면 domain.json 캐시를
720
- // 무효화 → 다음 findLiveDomain 호출이 새 도메인을 채택하게 한다.
721
- // 안전장치: announce를 못 읽으면(네트워크 실패/빈 본문) 아무것도 안 함 — 오판으로
722
- // 멀쩡한 도메인을 버리지 않도록. announce가 challenge HTML이면 도메인 파싱이 안 되어 null → skip.
723
- async function announceFollower() {
724
- try {
725
- const cached = readCachePermanent('domain.json');
726
- const current = cached && (cached.announced || cached.domain);
727
- const html = await fetchAnnounceHtml(8000);
728
- if (!html) return; // 못 읽음 — 현 상태 유지
729
- const { announced } = parseAnnouncedDomain(html);
730
- if (!announced) return; // 파싱 실패(랜딩 구조 변경/challenge 등) — 현 상태 유지
731
- if (current && announced !== current) {
732
- console.warn(`[announce-follow] 활성 주소 변경 감지: ${current} → ${announced} — 도메인 캐시 무효화`);
733
- // 캐시 무효화 → 다음 findLiveDomain이 새 도메인 probe + 채택.
734
- try { fs.unlinkSync(path.join(CACHE_DIR, 'domain.json')); } catch {}
735
- // 즉시 재탐색해서 새 도메인을 캐시에 채워둠 (다음 사용자 요청이 바로 새 도메인 쓰게).
736
- try { await findLiveDomain(); } catch (e) { console.warn('[announce-follow] rediscover failed:', e.message); }
737
- }
738
- } catch (e) {
739
- console.warn('[announce-follow] check failed:', e.message);
740
- }
741
- }
742
 
743
  // 9222 CDP 응답 여부 가벼운 체크. 200/json/version이 응답하면 alive.
744
  function checkCdpAlive(timeoutMs = 2000) {
@@ -772,7 +654,7 @@ function spawnCdpChrome() {
772
  '--no-first-run',
773
  '--no-default-browser-check',
774
  // 화면 밖 좌표로 기동 — navigate가 창을 활성화시켜도 사용자 화면에 안 뜨고 포커스 거슬림 없음.
775
- // cf challenge 통과 필요 시 triggerCfChallengeUi가 화면 안으로 끌어옴.
776
  '--window-position=-32000,-32000',
777
  '--window-size=1200,800',
778
  'https://tvchak.org/',
@@ -1816,33 +1698,17 @@ async function aniPlayMaybeFallback(uniqueId) {
1816
 
1817
  // ───── 도메인 탐지 ─────
1818
  async function findLiveDomain() {
1819
- // 살아있는 도메인 캐시는 1시간 유지. 단, 캐시된 도메인이 실제로 죽었을 수 있으므로 가벼운 probe로 검증.
1820
- const cached = readCache('domain.json', 3600);
1821
- if (cached && cached.domain) {
1822
- try {
1823
- // 캐시된 도메인 검증 — 실제 play 경로로 (껍데기 도메인 캐시 오판 방지).
1824
- // CDP 모드면 헬퍼 페이지 navigate, 아니면 NAS 프록시.
1825
- const probeUrl = `https://${cached.domain}/index.php/vod/play/id/122862/sid/1/nid/1.html`;
1826
- const r = USE_LOCAL_CDP
1827
- ? await cdpFetchPage(probeUrl, 6000)
1828
- : await nasFetch(probeUrl, 6000);
1829
- const body = r.body || '';
1830
- const hasPlayer = /player_aaaa/i.test(body);
1831
- if (r.ok && hasPlayer) return cached;
1832
- // (P4) challenge ≠ dead 구분. cf challenge면 도메인은 살아있는 것 → 재탐색하지 말고 캐시 유지.
1833
- // (재탐색 폭주 + 탭 폭증의 주원인이 challenge를 dead로 오판한 것이었음)
1834
- const isCfChallenge = r.status === 403
1835
- || /challenge-platform|cf-chl|turnstile|cf_chl_|__cf_chl|Just a moment|잠시만 기다리/i.test(body);
1836
- if (isCfChallenge) {
1837
- console.warn(`[findLiveDomain] cached ${cached.domain} cf challenge (status=${r.status}) — 도메인 살아있음, 캐시 유지`);
1838
- return cached;
1839
- }
1840
- console.warn(`[findLiveDomain] cached ${cached.domain} dead/fake (ok=${r.ok} status=${r.status} player=${hasPlayer}) — rediscovering`);
1841
- } catch (e) {
1842
- console.warn(`[findLiveDomain] cached ${cached.domain} probe error — rediscovering: ${e.message}`);
1843
- }
1844
- // 캐시된 도메인이 죽었으면 새로 탐색하도록 fall-through
1845
- }
1846
 
1847
  // stale (이전에 받았던 도메인) — 새 시도 실패해도 최후 fallback으로 사용
1848
  const stale = readCachePermanent('domain.json');
@@ -1862,9 +1728,9 @@ async function findLiveDomain() {
1862
  }
1863
  }
1864
 
1865
- // tvchak.org 랜딩 HTML에서 현재 announce된 콘텐츠 도메인 + 등장 번호 카운트를 추출.
1866
- // _findLiveDomainImpl(최초 탐색)와 announceFollower(선제 추종) 양쪽이 공유.
1867
- // counts: 옛 번호 도메인 체계용 ({번호: 등장횟수}). announced: 채택 도메인.
1868
  function parseAnnouncedDomain(html) {
1869
  html = html || '';
1870
  let announced = null;
@@ -1908,77 +1774,23 @@ async function fetchAnnounceHtml(timeoutMs = 10000) {
1908
  }
1909
 
1910
  async function _findLiveDomainImpl(stale) {
 
 
 
 
1911
  const html = await fetchAnnounceHtml(10000);
1912
- const { announced, counts } = parseAnnouncedDomain(html);
1913
-
1914
- // announce된 도메인 + 인접 번호를 후보군으로 만들어 실제 살아있는 도메인 선택.
1915
- // tvchak.org가 한 번호만 announce해도 그 번호가 우리 IP에 차단됐을 수 있으므로 ±5 범위 polling.
1916
- // (단일 도메인 체계에서는 announced가 tvchak.live처럼 번호가 없어 baseNum=null → ±5 polling 스킵, announce 그대로 채택)
1917
- const baseNum = announced && /\d/.test(announced) ? parseInt(announced.replace(/\D/g, ''), 10) : null;
1918
- const candidates = [];
1919
- if (announced) candidates.push(announced);
1920
- // 페이지에 등장한 다른 번호도 후보에 추가 (announce된 best가 아닌 것들)
1921
- for (const [n] of Object.entries(counts).sort((a, b) => b[1] - a[1])) {
1922
- const d = `tvchak${n}.com`;
1923
- if (!candidates.includes(d)) candidates.push(d);
1924
- }
1925
- // 인접 번호 ±5
1926
- if (baseNum) {
1927
- for (let off = 1; off <= 5; off++) {
1928
- for (const sign of [1, -1]) {
1929
- const n = baseNum + sign * off;
1930
- if (n <= 0) continue;
1931
- const d = `tvchak${n}.com`;
1932
- if (!candidates.includes(d)) candidates.push(d);
1933
- }
1934
- }
1935
- }
1936
- // (P3) announce가 불안정(번호 ↔ flat 도메인 오감)하므로, 알려진 콘텐츠 도메인과
1937
- // 직전 캐시 도메인도 항상 후보에 포함 → announce가 막혀도 실제 살아있는 도메인을 채택.
1938
- for (const d of KNOWN_CONTENT_DOMAINS) if (!candidates.includes(d)) candidates.push(d);
1939
- if (stale && stale.domain && !candidates.includes(stale.domain)) candidates.push(stale.domain);
1940
-
1941
- // 후보들을 차례로 probe — context.request.get으로 본문까지 확인.
1942
- // tvchak.org가 인접 번호에 가짜 lander 도메인을 깔아두는 패턴 발견 → 단순 200 판정 금지.
1943
- // 진짜 tvchak는 본문에 maccms 마커("player_aaaa" or "vodlist" 등) 또는 사이트 navbar 존재.
1944
- // probe도 NAS fetch 프록시로 (SOCKS5 raw TLS 병목 회피, KT SNI는 NAS zapret이 처리).
1945
- // 껍데기 도메인(메인엔 tvchak 단어만 ���고 실제 콘텐츠 없는 인접 번호) 오판 방지:
1946
- // 메인이 아니라 실제 play html 경로를 probe해서 player_aaaa가 나오는 도메인만 채택.
1947
- let domain = null;
1948
- let probeTrace = [];
1949
- for (const cand of candidates.slice(0, 12)) {
1950
- try {
1951
- const probeUrl = `https://${cand}/index.php/vod/play/id/122862/sid/1/nid/1.html`;
1952
- const r = USE_LOCAL_CDP
1953
- ? await cdpFetchPage(probeUrl, 6000)
1954
- : await nasFetch(probeUrl, 6000);
1955
- const body = r.body || '';
1956
- const hasPlayer = /player_aaaa/i.test(body);
1957
- // announce된 도메인이 Cloudflare challenge에 막혔어도(403 + challenge HTML), 그 도메인은 운영 중인 것 ⇒ 채택.
1958
- // 이유: BunnyCDN(mp4) hotlink는 announce된 정식 도메인의 Referer만 허용. probe로 발견한 인접 번호는
1959
- // 살아있어도 mp4 단계에서 403 — 사용자 측 cf_clearance가 들어오면 announce 도메인은 정상 작동함.
1960
- const isCfChallenge = r.status === 403 && /challenge-platform|cf-chl|turnstile|cf_chl_/i.test(body);
1961
- const isAnnounce = (cand === announced);
1962
- probeTrace.push(`${cand}=${r.status}${hasPlayer ? ':player' : isCfChallenge ? ':cf' : ''}`);
1963
- if (r.ok && hasPlayer) {
1964
- domain = cand;
1965
- break;
1966
- }
1967
- if (isAnnounce && isCfChallenge) {
1968
- // announce 도메인이 cf challenge로 막힌 경우 — 운영 중인 도메인 확정. 이 도메인 채택.
1969
- domain = cand;
1970
- break;
1971
- }
1972
- } catch (e) {
1973
- probeTrace.push(`${cand}=err`);
1974
- }
1975
- }
1976
- console.log(`[findLiveDomain] announced=${announced} chosen=${domain} probes=${probeTrace.join(',')}`);
1977
 
1978
- // 모든 후보가 죽었으면 announce 그대로 반환 (기존 동작 유지, stale fallback도 가능)
1979
  if (!domain) {
1980
- if (announced) domain = announced;
1981
- else if (stale && stale.domain) return { ...stale, stale: true };
 
 
 
 
 
 
1982
  }
1983
 
1984
  const result = {
@@ -3283,25 +3095,18 @@ async function handleApi(req, res, parsed) {
3283
  }
3284
  }
3285
  else if (p === '/api/diag/cf-monitor') {
3286
- // 디버그/관리용: cf_clearance 모니터를 즉시 1회 실행. CDP 모드 전용.
3287
- // q.force=1이면 cooldown 무시하고 triggerCfChallengeUi까지 강제 호출 (UX 검증용).
3288
  if (!USE_LOCAL_CDP) {
3289
  out = { ok: false, error: 'CDP 모드 아님 (USE_LOCAL_CDP=1 필요)' };
3290
- } else if (q.force === '1') {
3291
- const cached = readCachePermanent('domain.json');
3292
- const dom = cached && cached.announced;
3293
- _cfChallengeLastTriggerAt = 0;
3294
- const triggered = dom ? await triggerCfChallengeUi(dom) : false;
3295
- out = { ok: true, force: true, domain: dom, triggered };
3296
  } else {
3297
  const cached = readCachePermanent('domain.json');
3298
- const dom = cached && cached.announced;
3299
  if (!dom) {
3300
  out = { ok: false, error: 'no announce domain' };
3301
  } else {
3302
  const r = await tvFetchCDP(dom, '/index.php/vod/play/id/122862/sid/1/nid/1.html');
3303
- const isCf = r.status === 403 && /challenge-platform|cf-chl|turnstile|cf_chl_/i.test(r.body || '');
3304
- out = { ok: true, domain: dom, fetchOk: !!r.ok, status: r.status, isCfChallenge: isCf, lastTrigger: _cfChallengeLastTriggerAt };
3305
  }
3306
  }
3307
  }
@@ -3566,26 +3371,10 @@ server.listen(PORT, () => {
3566
  warmup().catch((e) => console.warn('[warmup] failed:', e.message));
3567
  }, 30 * 60 * 1000);
3568
 
3569
- // cf_clearance 만료 점검 — CDP 모드 전용. 부팅 직후 1회(warmup 끝나길 잠시 대기) + 이후 2분 주기.
3570
- // 부팅 직후 호출이 중요 — 재부팅했는데 cf 만료 상태로 부팅된 케이스에서 사용자가 시청 시도 전에
3571
- // 미리 Chrome 창을 띄워줘서 안정적으로 사용 시작 가능.
3572
- if (USE_LOCAL_CDP) {
3573
- setTimeout(() => {
3574
- cfClearanceMonitor().catch((e) => console.warn('[cf-monitor] boot tick failed:', e.message));
3575
- }, 15 * 1000);
3576
- setInterval(() => {
3577
- cfClearanceMonitor().catch((e) => console.warn('[cf-monitor] tick failed:', e.message));
3578
- }, 2 * 60 * 1000);
3579
- }
3580
-
3581
- // 선제��� 도메인 추종 — tvchak.org 활성 주소 변경 시 미리 갈아탐. (CDP/NAS 양쪽)
3582
- // 부팅 직후 1회(warmup 뒤) + 5분 주기. cf-monitor보다 느슨하게(전환은 자주 안 일어남).
3583
- setTimeout(() => {
3584
- announceFollower().catch((e) => console.warn('[announce-follow] boot tick failed:', e.message));
3585
- }, 40 * 1000);
3586
- setInterval(() => {
3587
- announceFollower().catch((e) => console.warn('[announce-follow] tick failed:', e.message));
3588
- }, 5 * 60 * 1000);
3589
 
3590
  // 1시간마다 랭킹 prefetch 재시도 — 날짜/주/월이 넘어가면 자동으로 새 데이터 가져옴.
3591
  setInterval(() => {
 
579
  // SNI 풀리면 USE_LOCAL_CDP 환경변수만 빼면 기존 NAS/Playwright 경로로 자동 원복.
580
  const USE_LOCAL_CDP = process.env.USE_LOCAL_CDP === '1';
581
  const LOCAL_CDP_URL = process.env.LOCAL_CDP_URL || 'http://127.0.0.1:9222';
582
+ // 도메인 강제 고정 — announce/캐시 무시하고 이 도메인만 사용. 빈 값이면 평소대로 announce 추종.
583
+ const FORCE_DOMAIN = process.env.FORCE_DOMAIN || '';
584
  let _cdpBrowser = null;
585
  let _cdpCtx = null;
586
  let _cdpPage = null;
 
616
  return _minimizeInFlight;
617
  }
618
 
619
+ // (제거됨 2026-06-30) triggerCfChallengeUi / cfClearanceMonitor / announceFollower.
620
+ // 창 foreground 복원 + 주기적 재탐색이 운영자의 잦은 도메인 번호 변경과 맞물려
621
+ // robots 탭 폭증 + 창 활성화↔최소화 무한 깜빡임을 일으킴. 도메인 결정은 findLiveDomain이
622
+ // tvchak.org announce를 읽어 그대로 채택하는 단순 경로로 일원화. cf challenge가 필요하면
623
+ // 사용자가 CDP Chrome 창에서 직접 통과(navigator.webdriver=false라 사람 클릭 가능).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
624
 
625
  // 9222 CDP 응답 여부 가벼운 체크. 200/json/version이 응답하면 alive.
626
  function checkCdpAlive(timeoutMs = 2000) {
 
654
  '--no-first-run',
655
  '--no-default-browser-check',
656
  // 화면 밖 좌표로 기동 — navigate가 창을 활성화시켜도 사용자 화면에 안 뜨고 포커스 거슬림 없음.
657
+ // cf challenge 통과가 필요하면 사용자가 작업표시줄에서 직접 창을 열어 통과.
658
  '--window-position=-32000,-32000',
659
  '--window-size=1200,800',
660
  'https://tvchak.org/',
 
1698
 
1699
  // ───── 도메인 탐지 ─────
1700
  async function findLiveDomain() {
1701
+ // 도메인 강제 고정 (2026-06-30): FORCE_DOMAIN 환경변수가 있으면 announce/캐시 무시하고 그대로 사용.
1702
+ // 현재 announce(tvchak208.com)가 이 PC 공인 IP에 차단(유지보수중 위장)돼, 사용자가 cf challenge를
1703
+ // 직접 통과시킨 tvchak.live로 고정 운영. 208 차단 풀리거나 .live가 죽으면 이 환경변수만 제거.
1704
+ if (FORCE_DOMAIN) {
1705
+ return { domain: FORCE_DOMAIN, announced: FORCE_DOMAIN, source: 'forced', checked_at: new Date().toISOString() };
1706
+ }
1707
+ // 도메인 캐시는 10분 신뢰 (probe 안 함 — probe가 robots 탭을 만들어 탭 폭증을 유발했음).
1708
+ // announce를 그때그때 읽는 단순 모델이므로, 만료되면 _findLiveDomainImpl이 tvchak.org를
1709
+ // 다시 읽어 현재 활성 주소로 갱신한다. announce가 208↔.live로 바뀌어도 10분 내 자동 추종.
1710
+ const cached = readCache('domain.json', 600);
1711
+ if (cached && cached.domain) return cached;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1712
 
1713
  // stale (이전에 받았던 도메인) — 새 시도 실패해도 최후 fallback으로 사용
1714
  const stale = readCachePermanent('domain.json');
 
1728
  }
1729
  }
1730
 
1731
+ // tvchak.org 랜딩 HTML에서 현재 announce된 콘텐츠 도메인을 추출. _findLiveDomainImpl이 그대로 채택.
1732
+ // 번호 체계(tvchakNNN.com)면 가장 많이 등장한 번호, 단일 도메인 체계(2026-06-30~)면 flat 도메인(tvchak.live 등).
1733
+ // counts는 내부 best 계산용. announced: 채택 도메인.
1734
  function parseAnnouncedDomain(html) {
1735
  html = html || '';
1736
  let announced = null;
 
1774
  }
1775
 
1776
  async function _findLiveDomainImpl(stale) {
1777
+ // 단순 모델 (2026-06-30): tvchak.org가 안내하는 현재 활성 주소를 그대로 채택.
1778
+ // announce가 208이면 tvchak208.com, .live면 tvchak.live. ±5 인접번호 polling/probe 없음
1779
+ // (그게 매번 새 robots 탭을 만들어 탭 폭증 + 깜빡임의 원인이었음).
1780
+ // announce를 못 읽으면 직전 캐시(stale) 도메인으로 폴백 — 빈 화면 방지.
1781
  const html = await fetchAnnounceHtml(10000);
1782
+ const { announced } = parseAnnouncedDomain(html);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1783
 
1784
+ let domain = announced;
1785
  if (!domain) {
1786
+ // announce 파싱 실패(랜딩 구조 변경/네트워크 실패 등) → 직전 도메인 유지.
1787
+ if (stale && stale.domain) {
1788
+ console.warn(`[findLiveDomain] announce 파싱 실패 — stale ${stale.domain} 유지`);
1789
+ return { ...stale, stale: true };
1790
+ }
1791
+ console.warn('[findLiveDomain] announce 파싱 실패 + stale 없음 — domain=null');
1792
+ } else {
1793
+ console.log(`[findLiveDomain] announced=${announced} chosen=${domain}`);
1794
  }
1795
 
1796
  const result = {
 
3095
  }
3096
  }
3097
  else if (p === '/api/diag/cf-monitor') {
3098
+ // 디버그/관리용: 현재 announce 도메인으로 play 경로 fetch 결과 확인. (창 띄우기 로직은 제거됨 2026-06-30)
 
3099
  if (!USE_LOCAL_CDP) {
3100
  out = { ok: false, error: 'CDP 모드 아님 (USE_LOCAL_CDP=1 필요)' };
 
 
 
 
 
 
3101
  } else {
3102
  const cached = readCachePermanent('domain.json');
3103
+ const dom = cached && (cached.announced || cached.domain);
3104
  if (!dom) {
3105
  out = { ok: false, error: 'no announce domain' };
3106
  } else {
3107
  const r = await tvFetchCDP(dom, '/index.php/vod/play/id/122862/sid/1/nid/1.html');
3108
+ const isCf = /challenge-platform|cf-chl|turnstile|cf_chl_/i.test(r.body || '');
3109
+ out = { ok: true, domain: dom, fetchOk: !!r.ok, status: r.status, isCfChallenge: isCf };
3110
  }
3111
  }
3112
  }
 
3371
  warmup().catch((e) => console.warn('[warmup] failed:', e.message));
3372
  }, 30 * 60 * 1000);
3373
 
3374
+ // (제거됨 2026-06-30) cfClearanceMonitor(2분 주기 창 띄우기) + announceFollower(5분 주기 선제 재탐색).
3375
+ // 운영자가 도메인 번호를 208→...→213→.live로 수시 변경 → 추종 루프가 매번 재탐색 + 새 robots 탭 생성
3376
+ // → 탭 폭증 + cf 창 활성화↔최소화 무한 깜빡임 사고. 추종/창 띄우기를 전부 걷어내고,
3377
+ // findLiveDomain이 tvchak.org announce를 그때그때 읽어 그 도메인으로 CDP 연결하는 단순 모델로 회귀.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3378
 
3379
  // 1시간마다 랭킹 prefetch 재시도 — 날짜/주/월이 넘어가면 자동으로 새 데이터 가져옴.
3380
  setInterval(() => {