viruagent-cli 0.3.2 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,745 @@
1
+ const { chromium } = require('playwright');
2
+ const { execSync, execFileSync } = require('child_process');
3
+ const fs = require('fs');
4
+ const os = require('os');
5
+ const crypto = require('crypto');
6
+ const path = require('path');
7
+ const { pickValue } = require('./browserHelpers');
8
+ const { persistTistorySession } = require('./session');
9
+ const {
10
+ KAKAO_TRIGGER_SELECTORS,
11
+ KAKAO_ACCOUNT_CONFIRM_SELECTORS,
12
+ } = require('./selectors');
13
+
14
+ const decryptChromeCookieMac = (encryptedValue, derivedKey) => {
15
+ if (!encryptedValue || encryptedValue.length < 4) return '';
16
+ const prefix = encryptedValue.slice(0, 3).toString('ascii');
17
+ if (prefix !== 'v10') return encryptedValue.toString('utf-8');
18
+
19
+ const encrypted = encryptedValue.slice(3);
20
+ const iv = Buffer.alloc(16, 0x20);
21
+ const decipher = crypto.createDecipheriv('aes-128-cbc', derivedKey, iv);
22
+ decipher.setAutoPadding(true);
23
+ try {
24
+ const dec = Buffer.concat([decipher.update(encrypted), decipher.final()]);
25
+ // CBC 첫 블록은 IV 불일치로 깨짐 → 끝에서부터 printable ASCII 범위 추출
26
+ let start = dec.length;
27
+ for (let i = dec.length - 1; i >= 0; i--) {
28
+ if (dec[i] >= 0x20 && dec[i] <= 0x7e) { start = i; }
29
+ else { break; }
30
+ }
31
+ return start < dec.length ? dec.slice(start).toString('utf-8') : '';
32
+ } catch {
33
+ return '';
34
+ }
35
+ };
36
+
37
+ const getWindowsChromeMasterKey = (chromeRoot) => {
38
+ const localStatePath = path.join(chromeRoot, 'Local State');
39
+ if (!fs.existsSync(localStatePath)) {
40
+ throw new Error('Chrome Local State 파일을 찾을 수 없습니다.');
41
+ }
42
+ const localState = JSON.parse(fs.readFileSync(localStatePath, 'utf-8'));
43
+ const encryptedKeyB64 = localState.os_crypt && localState.os_crypt.encrypted_key;
44
+ if (!encryptedKeyB64) {
45
+ throw new Error('Chrome Local State에서 암호화 키를 찾을 수 없습니다.');
46
+ }
47
+ const encryptedKeyWithPrefix = Buffer.from(encryptedKeyB64, 'base64');
48
+ // 앞 5바이트 "DPAPI" 접두사 제거
49
+ const encryptedKey = encryptedKeyWithPrefix.slice(5);
50
+ const encHex = encryptedKey.toString('hex');
51
+
52
+ // PowerShell DPAPI로 복호화
53
+ const psScript = `
54
+ Add-Type -AssemblyName System.Security
55
+ $encBytes = [byte[]]::new(${encryptedKey.length})
56
+ $hex = '${encHex}'
57
+ for ($i = 0; $i -lt $encBytes.Length; $i++) {
58
+ $encBytes[$i] = [Convert]::ToByte($hex.Substring($i * 2, 2), 16)
59
+ }
60
+ $decBytes = [System.Security.Cryptography.ProtectedData]::Unprotect($encBytes, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)
61
+ $decHex = -join ($decBytes | ForEach-Object { $_.ToString('x2') })
62
+ Write-Output $decHex
63
+ `.trim().replace(/\n/g, '; ');
64
+
65
+ try {
66
+ const decHex = execSync(
67
+ `powershell -NoProfile -Command "${psScript}"`,
68
+ { encoding: 'utf-8', timeout: 10000 }
69
+ ).trim();
70
+ return Buffer.from(decHex, 'hex');
71
+ } catch {
72
+ throw new Error('Chrome 암호화 키를 DPAPI로 복호화할 수 없습니다.');
73
+ }
74
+ };
75
+
76
+ const decryptChromeCookieWindows = (encryptedValue, masterKey) => {
77
+ if (!encryptedValue || encryptedValue.length < 4) return '';
78
+ const prefix = encryptedValue.slice(0, 3).toString('ascii');
79
+ if (prefix !== 'v10' && prefix !== 'v20') return encryptedValue.toString('utf-8');
80
+
81
+ // AES-256-GCM: nonce(12바이트) + ciphertext + authTag(16바이트)
82
+ const nonce = encryptedValue.slice(3, 3 + 12);
83
+ const authTag = encryptedValue.slice(encryptedValue.length - 16);
84
+ const ciphertext = encryptedValue.slice(3 + 12, encryptedValue.length - 16);
85
+
86
+ try {
87
+ const decipher = crypto.createDecipheriv('aes-256-gcm', masterKey, nonce);
88
+ decipher.setAuthTag(authTag);
89
+ const dec = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
90
+ return dec.toString('utf-8');
91
+ } catch {
92
+ return '';
93
+ }
94
+ };
95
+
96
+ const decryptChromeCookie = (encryptedValue, key) => {
97
+ if (process.platform === 'win32') {
98
+ return decryptChromeCookieWindows(encryptedValue, key);
99
+ }
100
+ return decryptChromeCookieMac(encryptedValue, key);
101
+ };
102
+
103
+ const copyFileViaVSS = (srcPath, destPath) => {
104
+ const scriptPath = path.join(__dirname, '..', '..', 'scripts', 'vss-copy.ps1');
105
+ if (!fs.existsSync(scriptPath)) return false;
106
+ try {
107
+ const result = execSync(
108
+ 'powershell -NoProfile -ExecutionPolicy Bypass -File "' + scriptPath + '" -SourcePath "' + srcPath + '" -DestPath "' + destPath + '"',
109
+ { encoding: 'utf-8', timeout: 30000 }
110
+ ).trim();
111
+ return result.includes('OK');
112
+ } catch {
113
+ return false;
114
+ }
115
+ };
116
+
117
+ const isChromeRunning = () => {
118
+ try {
119
+ if (process.platform === 'win32') {
120
+ const result = execSync('tasklist /FI "IMAGENAME eq chrome.exe" /NH', { encoding: 'utf-8', timeout: 5000 });
121
+ return result.includes('chrome.exe');
122
+ }
123
+ const result = execSync('pgrep -x "Google Chrome" 2>/dev/null || pgrep -x chrome 2>/dev/null', { encoding: 'utf-8', timeout: 5000 });
124
+ return result.trim().length > 0;
125
+ } catch {
126
+ return false;
127
+ }
128
+ };
129
+
130
+ const extractChromeCookies = (cookiesDb, derivedKey, domainPattern) => {
131
+ const tempDb = path.join(os.tmpdir(), `viruagent-cookies-${Date.now()}.db`);
132
+
133
+ // SQLite 온라인 백업 API 사용 (Chrome이 실행 중이어도 동작)
134
+ // execFileSync로 쉘을 거치지 않아 Windows 경로 공백/이스케이핑 문제 없음
135
+ const backupCmd = process.platform === 'win32'
136
+ ? `.backup "${tempDb}"`
137
+ : `.backup '${tempDb.replace(/'/g, "''")}'`;
138
+ try {
139
+ execFileSync('sqlite3', [cookiesDb, backupCmd], { stdio: 'ignore', timeout: 10000 });
140
+ } catch {
141
+ // sqlite3 백업 실패 시 파일 복사 → VSS 순으로 폴백
142
+ let copied = false;
143
+ try {
144
+ fs.copyFileSync(cookiesDb, tempDb);
145
+ copied = true;
146
+ } catch {}
147
+ if (!copied && process.platform === 'win32') {
148
+ // Windows: VSS(Volume Shadow Copy)로 잠긴 파일 복사
149
+ copied = copyFileViaVSS(cookiesDb, tempDb);
150
+ }
151
+ if (!copied) {
152
+ throw new Error('Chrome 쿠키 DB 복사에 실패했습니다. Chrome이 실행 중이면 종료 후 다시 시도해 주세요.');
153
+ }
154
+ }
155
+
156
+ // 백업 후 남은 WAL/SHM 파일 제거 (깨끗한 DB 보장)
157
+ for (const suffix of ['-wal', '-shm', '-journal']) {
158
+ try { fs.unlinkSync(tempDb + suffix); } catch {}
159
+ }
160
+
161
+ try {
162
+ const query = `SELECT host_key, name, value, hex(encrypted_value), path, expires_utc, is_secure, is_httponly, samesite FROM cookies WHERE host_key LIKE '${domainPattern}'`;
163
+ const rows = execFileSync('sqlite3', ['-separator', '||', tempDb, query], {
164
+ encoding: 'utf-8',
165
+ timeout: 5000,
166
+ }).trim();
167
+ if (!rows) return [];
168
+
169
+ const chromeEpochOffset = 11644473600;
170
+ const sameSiteMap = { '-1': 'None', '0': 'None', '1': 'Lax', '2': 'Strict' };
171
+ return rows.split('\n').map(row => {
172
+ const [domain, name, plainValue, encHex, cookiePath, expiresUtc, isSecure, isHttpOnly, sameSite] = row.split('||');
173
+ let value = plainValue || '';
174
+ if (!value && encHex) {
175
+ value = decryptChromeCookie(Buffer.from(encHex, 'hex'), derivedKey);
176
+ }
177
+ if (value && !/^[\x20-\x7E]*$/.test(value)) value = '';
178
+ const expires = expiresUtc === '0' ? -1 : Math.floor(Number(expiresUtc) / 1000000) - chromeEpochOffset;
179
+ return { name, value, domain, path: cookiePath || '/', expires, httpOnly: isHttpOnly === '1', secure: isSecure === '1', sameSite: sameSiteMap[sameSite] || 'None' };
180
+ }).filter(c => c.value);
181
+ } finally {
182
+ try { fs.unlinkSync(tempDb); } catch {}
183
+ }
184
+ };
185
+
186
+ const findWindowsChromePath = () => {
187
+ const candidates = [
188
+ path.join(process.env['PROGRAMFILES(X86)'] || '', 'Google', 'Chrome', 'Application', 'chrome.exe'),
189
+ path.join(process.env['PROGRAMFILES'] || '', 'Google', 'Chrome', 'Application', 'chrome.exe'),
190
+ path.join(process.env['LOCALAPPDATA'] || '', 'Google', 'Chrome', 'Application', 'chrome.exe'),
191
+ ];
192
+ return candidates.find(p => fs.existsSync(p)) || null;
193
+ };
194
+
195
+ const generateSelfSignedCert = (domain) => {
196
+ const tempDir = path.join(os.tmpdir(), `viruagent-cert-${Date.now()}`);
197
+ fs.mkdirSync(tempDir, { recursive: true });
198
+ const keyPath = path.join(tempDir, 'key.pem');
199
+ const certPath = path.join(tempDir, 'cert.pem');
200
+
201
+ // openssl (Git for Windows에 포함)
202
+ const opensslPaths = [
203
+ 'openssl',
204
+ 'C:/Program Files/Git/usr/bin/openssl.exe',
205
+ 'C:/Program Files (x86)/Git/usr/bin/openssl.exe',
206
+ ];
207
+ let generated = false;
208
+ for (const openssl of opensslPaths) {
209
+ try {
210
+ execSync(
211
+ `"${openssl}" req -x509 -newkey rsa:2048 -nodes -keyout "${keyPath}" -out "${certPath}" -days 1 -subj "/CN=${domain}"`,
212
+ { timeout: 10000, stdio: 'pipe' }
213
+ );
214
+ generated = true;
215
+ break;
216
+ } catch {}
217
+ }
218
+ if (!generated) {
219
+ try { fs.rmSync(tempDir, { recursive: true, force: true }); } catch {}
220
+ return null;
221
+ }
222
+ return { keyPath, certPath, tempDir };
223
+ };
224
+
225
+ const CDP_DEBUG_PORT = 9222;
226
+
227
+ const tryConnectCDP = async (port) => {
228
+ const http = require('http');
229
+ return new Promise((resolve) => {
230
+ http.get(`http://127.0.0.1:${port}/json/version`, { timeout: 2000 }, (res) => {
231
+ let data = '';
232
+ res.on('data', c => data += c);
233
+ res.on('end', () => {
234
+ try {
235
+ const info = JSON.parse(data);
236
+ resolve(info.webSocketDebuggerUrl || null);
237
+ } catch { resolve(null); }
238
+ });
239
+ }).on('error', () => resolve(null));
240
+ });
241
+ };
242
+
243
+ const findChromeDebugPort = async () => {
244
+ // 1. 고정 포트 9222 시도
245
+ const ws = await tryConnectCDP(CDP_DEBUG_PORT);
246
+ if (ws) return { port: CDP_DEBUG_PORT, wsUrl: ws };
247
+
248
+ // 2. DevToolsActivePort 파일 확인
249
+ const dtpPath = path.join(
250
+ process.env.LOCALAPPDATA || '',
251
+ 'Google', 'Chrome', 'User Data', 'DevToolsActivePort'
252
+ );
253
+ try {
254
+ const content = fs.readFileSync(dtpPath, 'utf-8').trim();
255
+ const port = parseInt(content.split('\n')[0], 10);
256
+ if (port > 0) {
257
+ const ws2 = await tryConnectCDP(port);
258
+ if (ws2) return { port, wsUrl: ws2 };
259
+ }
260
+ } catch {}
261
+
262
+ return null;
263
+ };
264
+
265
+ const enableChromeDebugPort = () => {
266
+ // Chrome 바로가기에 --remote-debugging-port 추가 (한 번만 실행)
267
+ if (process.platform !== 'win32') return false;
268
+
269
+ const flag = `--remote-debugging-port=${CDP_DEBUG_PORT}`;
270
+ const shortcutPaths = [];
271
+
272
+ // 바탕화면, 시작 메뉴, 작업표시줄 바로가기 검색
273
+ const locations = [
274
+ path.join(os.homedir(), 'Desktop'),
275
+ path.join(os.homedir(), 'AppData', 'Roaming', 'Microsoft', 'Windows', 'Start Menu', 'Programs'),
276
+ path.join(os.homedir(), 'AppData', 'Roaming', 'Microsoft', 'Internet Explorer', 'Quick Launch', 'User Pinned', 'TaskBar'),
277
+ 'C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs',
278
+ ];
279
+ for (const loc of locations) {
280
+ try {
281
+ const files = fs.readdirSync(loc);
282
+ for (const f of files) {
283
+ if (/chrome/i.test(f) && f.endsWith('.lnk')) {
284
+ shortcutPaths.push(path.join(loc, f));
285
+ }
286
+ }
287
+ } catch {}
288
+ }
289
+ // Google Chrome 폴더 내부도 탐색
290
+ for (const loc of locations) {
291
+ try {
292
+ const chromeDir = path.join(loc, 'Google Chrome');
293
+ if (fs.existsSync(chromeDir)) {
294
+ const files = fs.readdirSync(chromeDir);
295
+ for (const f of files) {
296
+ if (/chrome/i.test(f) && f.endsWith('.lnk')) {
297
+ shortcutPaths.push(path.join(chromeDir, f));
298
+ }
299
+ }
300
+ }
301
+ } catch {}
302
+ }
303
+
304
+ let modified = 0;
305
+ for (const lnkPath of shortcutPaths) {
306
+ try {
307
+ const psScript = `
308
+ $shell = New-Object -ComObject WScript.Shell
309
+ $sc = $shell.CreateShortcut('${lnkPath.replace(/'/g, "''")}')
310
+ if ($sc.Arguments -notmatch 'remote-debugging-port') {
311
+ $sc.Arguments = ($sc.Arguments + ' ${flag}').Trim()
312
+ $sc.Save()
313
+ Write-Output 'MODIFIED'
314
+ } else {
315
+ Write-Output 'ALREADY'
316
+ }`;
317
+ const result = execSync(`powershell -Command "${psScript.replace(/"/g, '\\"')}"`, {
318
+ timeout: 5000,
319
+ encoding: 'utf-8',
320
+ }).trim();
321
+ if (result === 'MODIFIED') modified++;
322
+ } catch {}
323
+ }
324
+ return modified > 0;
325
+ };
326
+
327
+ const extractCookiesFromCDP = async (port, targetSessionPath) => {
328
+ const http = require('http');
329
+ const WebSocket = require('ws');
330
+
331
+ // 1. 브라우저 레벨 CDP에 연결하여 tistory 탭 생성/탐색
332
+ const browserWsUrl = await tryConnectCDP(port);
333
+ if (!browserWsUrl) throw new Error('Chrome CDP 연결 실패');
334
+
335
+ // 2. 기존 tistory 탭 찾거나 새로 생성
336
+ const targetsJson = await new Promise((resolve, reject) => {
337
+ http.get(`http://127.0.0.1:${port}/json/list`, { timeout: 3000 }, (res) => {
338
+ let data = '';
339
+ res.on('data', c => data += c);
340
+ res.on('end', () => resolve(data));
341
+ }).on('error', reject);
342
+ });
343
+ const targets = JSON.parse(targetsJson);
344
+ let pageTarget = targets.find(t => t.type === 'page' && t.url && t.url.includes('tistory'));
345
+
346
+ if (!pageTarget) {
347
+ // tistory 탭이 없으면 브라우저 CDP로 새 탭 생성
348
+ const bws = new WebSocket(browserWsUrl);
349
+ const newTargetId = await new Promise((resolve, reject) => {
350
+ const timeout = setTimeout(() => reject(new Error('탭 생성 시간 초과')), 10000);
351
+ bws.on('open', () => {
352
+ bws.send(JSON.stringify({ id: 1, method: 'Target.createTarget', params: { url: 'https://www.tistory.com/' } }));
353
+ });
354
+ bws.on('message', (msg) => {
355
+ const resp = JSON.parse(msg.toString());
356
+ if (resp.id === 1) {
357
+ clearTimeout(timeout);
358
+ resolve(resp.result?.targetId);
359
+ bws.close();
360
+ }
361
+ });
362
+ bws.on('error', (e) => { clearTimeout(timeout); reject(e); });
363
+ });
364
+ // 새 탭의 WebSocket URL 조회
365
+ await new Promise(r => setTimeout(r, 3000));
366
+ const newTargetsJson = await new Promise((resolve, reject) => {
367
+ http.get(`http://127.0.0.1:${port}/json/list`, { timeout: 3000 }, (res) => {
368
+ let data = '';
369
+ res.on('data', c => data += c);
370
+ res.on('end', () => resolve(data));
371
+ }).on('error', reject);
372
+ });
373
+ const newTargets = JSON.parse(newTargetsJson);
374
+ pageTarget = newTargets.find(t => t.id === newTargetId) || newTargets.find(t => t.type === 'page' && t.url && t.url.includes('tistory'));
375
+ }
376
+
377
+ if (!pageTarget || !pageTarget.webSocketDebuggerUrl) {
378
+ throw new Error('tistory 페이지 타겟을 찾을 수 없습니다.');
379
+ }
380
+
381
+ // 3. 페이지 레벨 CDP에서 Network.enable → Network.getAllCookies
382
+ const ws = new WebSocket(pageTarget.webSocketDebuggerUrl);
383
+ const cookies = await new Promise((resolve, reject) => {
384
+ const timeout = setTimeout(() => reject(new Error('CDP 쿠키 추출 시간 초과')), 15000);
385
+ let msgId = 1;
386
+ ws.on('open', () => {
387
+ ws.send(JSON.stringify({ id: msgId++, method: 'Network.enable' }));
388
+ });
389
+ ws.on('message', (msg) => {
390
+ const resp = JSON.parse(msg.toString());
391
+ if (resp.id === 1) {
392
+ // Network enabled → getAllCookies
393
+ ws.send(JSON.stringify({ id: msgId++, method: 'Network.getAllCookies' }));
394
+ }
395
+ if (resp.id === 2) {
396
+ clearTimeout(timeout);
397
+ resolve(resp.result?.cookies || []);
398
+ ws.close();
399
+ }
400
+ });
401
+ ws.on('error', (e) => { clearTimeout(timeout); reject(e); });
402
+ });
403
+
404
+ const tistoryCookies = cookies.filter(c => String(c.domain).includes('tistory'));
405
+ const tssession = tistoryCookies.find(c => c.name === 'TSSESSION');
406
+ if (!tssession || !tssession.value) {
407
+ throw new Error('Chrome에 티스토리 로그인 세션이 없습니다. Chrome에서 먼저 티스토리에 로그인해 주세요.');
408
+ }
409
+
410
+ const payload = {
411
+ cookies: tistoryCookies.map(c => ({
412
+ name: c.name, value: c.value, domain: c.domain,
413
+ path: c.path || '/', expires: c.expires > 0 ? c.expires : -1,
414
+ httpOnly: !!c.httpOnly, secure: !!c.secure,
415
+ sameSite: c.sameSite || 'None',
416
+ })),
417
+ updatedAt: new Date().toISOString(),
418
+ };
419
+ await fs.promises.mkdir(path.dirname(targetSessionPath), { recursive: true });
420
+ await fs.promises.writeFile(targetSessionPath, JSON.stringify(payload, null, 2), 'utf-8');
421
+ return { cookieCount: tistoryCookies.length };
422
+ };
423
+
424
+ const getOrCreateJunctionPath = (chromeRoot) => {
425
+ // Chrome 145+: 기본 user-data-dir에서는 --remote-debugging-port가 작동하지 않음
426
+ // Junction point로 같은 디렉토리를 다른 경로로 가리켜서 우회
427
+ if (process.platform !== 'win32') return chromeRoot;
428
+
429
+ const junctionPath = path.join(path.dirname(chromeRoot), 'ChromeDebug');
430
+ if (!fs.existsSync(junctionPath)) {
431
+ try {
432
+ execSync(`cmd /c "mklink /J "${junctionPath}" "${chromeRoot}""`, {
433
+ timeout: 5000, stdio: 'pipe',
434
+ });
435
+ } catch {
436
+ // Junction 생성 실패 시 원본 경로 사용 (디버그 포트 작동 안 할 수 있음)
437
+ return chromeRoot;
438
+ }
439
+ }
440
+ return junctionPath;
441
+ };
442
+
443
+ const extractCookiesViaCDP = async (targetSessionPath, chromeRoot, profileName) => {
444
+ // Chrome 실행 중: CDP(Chrome DevTools Protocol)로 쿠키 추출
445
+ // 1단계: 이미 디버그 포트가 열려있으면 바로 연결 (크롬 종료 없음)
446
+ // 2단계: 없으면 한 번만 재시작 + 바로가기 수정 (이후 재시작 불필요)
447
+ const { spawn } = require('child_process');
448
+
449
+ // 1. 이미 디버그 포트가 열려있는지 확인
450
+ const existing = await findChromeDebugPort();
451
+ if (existing) {
452
+ console.log(`[chrome-cdp] 기존 Chrome 디버그 포트(${existing.port}) 감지 — 크롬 종료 없이 쿠키 추출`);
453
+ return await extractCookiesFromCDP(existing.port, targetSessionPath);
454
+ }
455
+
456
+ // 2. 디버그 포트 없음 → Chrome 바로가기에 디버그 포트 추가 (이후 재시작 불필요)
457
+ console.log('[chrome-cdp] Chrome 디버그 포트 미감지 — 바로가기에 --remote-debugging-port 추가 중...');
458
+ const shortcutModified = enableChromeDebugPort();
459
+ if (shortcutModified) {
460
+ console.log('[chrome-cdp] Chrome 바로가기 수정 완료 — 다음부터는 크롬 종료 없이 쿠키 추출 가능');
461
+ }
462
+
463
+ // 3. Chrome을 graceful하게 종료하고 디버그 포트로 재시작 (최초 1회만)
464
+ const chromePath = findWindowsChromePath();
465
+ if (!chromePath) throw new Error('Chrome 실행 파일을 찾을 수 없습니다.');
466
+
467
+ console.log('[chrome-cdp] Chrome을 디버그 포트와 함께 재시작합니다 (탭 자동 복원)...');
468
+ try {
469
+ if (process.platform === 'win32') {
470
+ execSync('cmd /c "taskkill /IM chrome.exe"', { stdio: 'ignore', timeout: 10000 });
471
+ }
472
+ } catch {}
473
+ await new Promise(r => setTimeout(r, 2000));
474
+ if (isChromeRunning()) {
475
+ try { execSync('cmd /c "taskkill /F /IM chrome.exe"', { stdio: 'ignore', timeout: 5000 }); } catch {}
476
+ await new Promise(r => setTimeout(r, 1000));
477
+ }
478
+
479
+ // 4. Junction 경로로 디버그 포트 + 세션 복원 재시작
480
+ // Chrome 145+는 기본 user-data-dir에서 디버그 포트를 거부하므로 junction으로 우회
481
+ const junctionRoot = getOrCreateJunctionPath(chromeRoot);
482
+ const chromeProc = spawn(chromePath, [
483
+ `--remote-debugging-port=${CDP_DEBUG_PORT}`,
484
+ '--remote-allow-origins=*',
485
+ '--restore-last-session',
486
+ `--user-data-dir=${junctionRoot}`,
487
+ `--profile-directory=${profileName}`,
488
+ ], { detached: true, stdio: 'ignore' });
489
+ chromeProc.unref();
490
+
491
+ // 5. CDP 연결 대기
492
+ let connected = null;
493
+ const maxWait = 15000;
494
+ const start = Date.now();
495
+ while (Date.now() - start < maxWait) {
496
+ await new Promise(r => setTimeout(r, 500));
497
+ connected = await findChromeDebugPort();
498
+ if (connected) break;
499
+ }
500
+ if (!connected) throw new Error('Chrome 디버그 포트 연결 시간 초과');
501
+
502
+ // 6. 쿠키 추출 (Chrome은 계속 실행 상태 유지 — 종료하지 않음)
503
+ return await extractCookiesFromCDP(connected.port, targetSessionPath);
504
+ };
505
+
506
+ const importSessionViaChromeDirectLaunch = async (targetSessionPath, chromeRoot, profileName) => {
507
+ // Windows Chrome 145+: v20 App Bound Encryption으로 외부에서 쿠키 복호화 불가
508
+ // Chrome 실행 중이면 CDP 방식으로 추출 (잠시 재시작, 탭 자동 복원)
509
+ if (isChromeRunning()) {
510
+ return await extractCookiesViaCDP(targetSessionPath, chromeRoot, profileName);
511
+ }
512
+
513
+ const chromePath = findWindowsChromePath();
514
+ if (!chromePath) {
515
+ throw new Error('Chrome 실행 파일을 찾을 수 없습니다.');
516
+ }
517
+
518
+ // 1. 자체 서명 인증서 생성 (openssl 필요)
519
+ const cert = generateSelfSignedCert('www.tistory.com');
520
+ if (!cert) {
521
+ throw new Error(
522
+ 'openssl을 찾을 수 없습니다. Git for Windows를 설치하면 openssl이 포함됩니다.'
523
+ );
524
+ }
525
+
526
+ const https = require('https');
527
+ const { spawn } = require('child_process');
528
+
529
+ // 2. HTTPS 서버 시작 (포트 443)
530
+ const server = https.createServer({
531
+ key: fs.readFileSync(cert.keyPath),
532
+ cert: fs.readFileSync(cert.certPath),
533
+ });
534
+
535
+ try {
536
+ await new Promise((resolve, reject) => {
537
+ server.on('error', reject);
538
+ server.listen(443, '127.0.0.1', resolve);
539
+ });
540
+ } catch (e) {
541
+ try { fs.rmSync(cert.tempDir, { recursive: true, force: true }); } catch {}
542
+ throw new Error(`포트 443 바인딩 실패: ${e.message}. 관리자 권한으로 실행해 주세요.`);
543
+ }
544
+
545
+ // 3. 쿠키 수신 Promise
546
+ let chromeProc = null;
547
+ const cookiePromise = new Promise((resolve, reject) => {
548
+ const timeout = setTimeout(() => {
549
+ reject(new Error('Chrome 쿠키 추출 시간 초과 (15초)'));
550
+ }, 15000);
551
+
552
+ server.on('request', (req, res) => {
553
+ res.writeHead(200, { 'Content-Type': 'text/html' });
554
+ res.end('<html><body>Session captured. You can close this window.</body></html>');
555
+
556
+ if (req.url === '/' || req.url === '') {
557
+ clearTimeout(timeout);
558
+ const cookieHeader = req.headers.cookie || '';
559
+ resolve(cookieHeader);
560
+ }
561
+ });
562
+ });
563
+
564
+ // 4. Chrome 실행 (Chrome이 꺼진 상태에서만 실행됨 - DNS 리다이렉션, 인증서 오류 무시)
565
+ chromeProc = spawn(chromePath, [
566
+ '--no-first-run',
567
+ '--no-default-browser-check',
568
+ `--profile-directory=${profileName}`,
569
+ '--host-resolver-rules=MAP www.tistory.com 127.0.0.1',
570
+ '--ignore-certificate-errors',
571
+ 'https://www.tistory.com/',
572
+ ], { detached: true, stdio: 'ignore' });
573
+ chromeProc.unref();
574
+
575
+ try {
576
+ const cookieHeader = await cookiePromise;
577
+
578
+ // Cookie 헤더 파싱
579
+ const cookies = cookieHeader.split(';')
580
+ .map(c => c.trim())
581
+ .filter(Boolean)
582
+ .map(c => {
583
+ const eqIdx = c.indexOf('=');
584
+ if (eqIdx < 0) return null;
585
+ return { name: c.slice(0, eqIdx).trim(), value: c.slice(eqIdx + 1).trim() };
586
+ })
587
+ .filter(Boolean);
588
+
589
+ const tssession = cookies.find(c => c.name === 'TSSESSION');
590
+ if (!tssession || !tssession.value) {
591
+ throw new Error(
592
+ 'Chrome에 티스토리 로그인 세션이 없습니다. Chrome에서 먼저 티스토리에 로그인해 주세요.'
593
+ );
594
+ }
595
+
596
+ // Cookie 헤더에는 domain/path/expires 정보가 없으므로 기본값 설정
597
+ const payload = {
598
+ cookies: cookies.map(c => ({
599
+ name: c.name,
600
+ value: c.value,
601
+ domain: '.tistory.com',
602
+ path: '/',
603
+ expires: -1,
604
+ httpOnly: false,
605
+ secure: true,
606
+ sameSite: 'None',
607
+ })),
608
+ updatedAt: new Date().toISOString(),
609
+ };
610
+
611
+ await fs.promises.mkdir(path.dirname(targetSessionPath), { recursive: true });
612
+ await fs.promises.writeFile(targetSessionPath, JSON.stringify(payload, null, 2), 'utf-8');
613
+
614
+ return { cookieCount: cookies.length };
615
+ } finally {
616
+ server.close();
617
+ if (chromeProc) {
618
+ try { execSync(`taskkill /F /PID ${chromeProc.pid} /T`, { stdio: 'ignore', timeout: 5000 }); } catch {}
619
+ }
620
+ try { fs.rmSync(cert.tempDir, { recursive: true, force: true }); } catch {}
621
+ }
622
+ };
623
+
624
+ const importSessionFromChrome = async (targetSessionPath, profileName = 'Default') => {
625
+ let chromeRoot;
626
+ if (process.platform === 'win32') {
627
+ chromeRoot = path.join(process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local'), 'Google', 'Chrome', 'User Data');
628
+ } else {
629
+ chromeRoot = path.join(os.homedir(), 'Library', 'Application Support', 'Google', 'Chrome');
630
+ }
631
+ if (!fs.existsSync(chromeRoot)) {
632
+ throw new Error('Chrome이 설치되어 있지 않습니다.');
633
+ }
634
+
635
+ const profileDir = path.join(chromeRoot, profileName);
636
+ // Windows 최신 Chrome은 Network/Cookies, 이전 버전은 Cookies
637
+ let cookiesDb = path.join(profileDir, 'Network', 'Cookies');
638
+ if (!fs.existsSync(cookiesDb)) {
639
+ cookiesDb = path.join(profileDir, 'Cookies');
640
+ }
641
+ if (!fs.existsSync(cookiesDb)) {
642
+ throw new Error(`Chrome 프로필 "${profileName}"에 쿠키 DB가 없습니다.`);
643
+ }
644
+
645
+ let derivedKey;
646
+ if (process.platform === 'win32') {
647
+ // Windows: Local State → DPAPI로 마스터 키 복호화
648
+ derivedKey = getWindowsChromeMasterKey(chromeRoot);
649
+ } else {
650
+ // macOS: Keychain에서 Chrome 암호화 키 추출
651
+ let keychainPassword;
652
+ try {
653
+ keychainPassword = execSync(
654
+ 'security find-generic-password -s "Chrome Safe Storage" -w',
655
+ { encoding: 'utf-8', timeout: 5000 }
656
+ ).trim();
657
+ } catch {
658
+ throw new Error('Chrome Safe Storage 키를 Keychain에서 읽을 수 없습니다. macOS 권한을 확인해 주세요.');
659
+ }
660
+ derivedKey = crypto.pbkdf2Sync(keychainPassword, 'saltysalt', 1003, 16, 'sha1');
661
+ }
662
+
663
+ // Chrome에서 tistory + kakao 쿠키 복호화 추출
664
+ const tistoryCookies = extractChromeCookies(cookiesDb, derivedKey, '%tistory.com');
665
+ const kakaoCookies = extractChromeCookies(cookiesDb, derivedKey, '%kakao.com');
666
+
667
+ // 이미 TSSESSION 있으면 바로 저장
668
+ const existingSession = tistoryCookies.some(c => c.name === 'TSSESSION' && c.value);
669
+ if (existingSession) {
670
+ const payload = { cookies: tistoryCookies, updatedAt: new Date().toISOString() };
671
+ await fs.promises.mkdir(path.dirname(targetSessionPath), { recursive: true });
672
+ await fs.promises.writeFile(targetSessionPath, JSON.stringify(payload, null, 2), 'utf-8');
673
+ return { cookieCount: tistoryCookies.length };
674
+ }
675
+
676
+ // 3) 카카오 세션 쿠키가 있으면 Playwright에 주입 후 자동 로그인
677
+ const hasKakaoSession = kakaoCookies.some(c => c.domain.includes('kakao.com') && (c.name === '_kawlt' || c.name === '_kawltea' || c.name === '_karmt'));
678
+ if (!hasKakaoSession) {
679
+ // Windows v20 App Bound Encryption: DPAPI만으로 복호화 불가
680
+ // Playwright persistent context (pipe 모드)로 Chrome 기본 프로필에서 직접 추출
681
+ if (process.platform === 'win32') {
682
+ return await importSessionViaChromeDirectLaunch(targetSessionPath, chromeRoot, profileName);
683
+ }
684
+ throw new Error('Chrome에 카카오 로그인 세션이 없습니다. Chrome에서 먼저 카카오 계정에 로그인해 주세요.');
685
+ }
686
+
687
+ const browser = await chromium.launch({ headless: true });
688
+ const context = await browser.newContext();
689
+ try {
690
+ // Playwright 형식으로 변환하여 쿠키 주입
691
+ const allCookies = [...tistoryCookies, ...kakaoCookies].map(c => ({
692
+ ...c,
693
+ domain: c.domain.startsWith('.') ? c.domain : c.domain,
694
+ expires: c.expires > 0 ? c.expires : undefined,
695
+ }));
696
+ await context.addCookies(allCookies);
697
+
698
+ const page = await context.newPage();
699
+ await page.goto('https://www.tistory.com/auth/login', { waitUntil: 'domcontentloaded', timeout: 10000 });
700
+ await page.waitForTimeout(1000);
701
+
702
+ // 카카오 로그인 버튼 클릭
703
+ const kakaoBtn = await pickValue(page, KAKAO_TRIGGER_SELECTORS);
704
+ if (kakaoBtn) {
705
+ await page.locator(kakaoBtn).click({ timeout: 5000 }).catch(() => {});
706
+ await page.waitForLoadState('domcontentloaded').catch(() => {});
707
+ }
708
+
709
+ // 카카오 계정 확인 → 계속하기 클릭
710
+ await page.waitForTimeout(2000);
711
+ const confirmBtn = await pickValue(page, [
712
+ ...KAKAO_ACCOUNT_CONFIRM_SELECTORS.continue,
713
+ 'button[type="submit"]',
714
+ ]);
715
+ if (confirmBtn) {
716
+ await page.locator(confirmBtn).click({ timeout: 3000 }).catch(() => {});
717
+ }
718
+
719
+ // TSSESSION 대기 (최대 15초)
720
+ let hasSession = false;
721
+ const maxWait = 15000;
722
+ const startTime = Date.now();
723
+ while (Date.now() - startTime < maxWait) {
724
+ await page.waitForTimeout(1000);
725
+ const cookies = await context.cookies('https://www.tistory.com');
726
+ hasSession = cookies.some(c => c.name === 'TSSESSION' && c.value);
727
+ if (hasSession) break;
728
+ }
729
+
730
+ if (!hasSession) {
731
+ throw new Error('Chrome 카카오 세션으로 티스토리 자동 로그인에 실패했습니다.');
732
+ }
733
+
734
+ await persistTistorySession(context, targetSessionPath);
735
+ const finalCookies = await context.cookies('https://www.tistory.com');
736
+ return { cookieCount: finalCookies.filter(c => String(c.domain).includes('tistory')).length };
737
+ } finally {
738
+ await context.close().catch(() => {});
739
+ await browser.close().catch(() => {});
740
+ }
741
+ };
742
+
743
+ module.exports = {
744
+ importSessionFromChrome,
745
+ };