viruagent-cli 0.3.1 → 0.3.3

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "viruagent-cli",
3
- "version": "0.3.1",
3
+ "version": "0.3.3",
4
4
  "description": "AI-agent-optimized CLI for blog publishing (Tistory, Naver)",
5
5
  "private": false,
6
6
  "type": "commonjs",
@@ -1,5 +1,5 @@
1
1
  const { chromium } = require('playwright');
2
- const { execSync } = require('child_process');
2
+ const { execSync, execFileSync } = require('child_process');
3
3
  const fs = require('fs');
4
4
  const os = require('os');
5
5
  const crypto = require('crypto');
@@ -1734,7 +1734,7 @@ const persistTistorySession = async (context, targetSessionPath) => {
1734
1734
  );
1735
1735
  };
1736
1736
 
1737
- const decryptChromeCookie = (encryptedValue, derivedKey) => {
1737
+ const decryptChromeCookieMac = (encryptedValue, derivedKey) => {
1738
1738
  if (!encryptedValue || encryptedValue.length < 4) return '';
1739
1739
  const prefix = encryptedValue.slice(0, 3).toString('ascii');
1740
1740
  if (prefix !== 'v10') return encryptedValue.toString('utf-8');
@@ -1757,19 +1757,136 @@ const decryptChromeCookie = (encryptedValue, derivedKey) => {
1757
1757
  }
1758
1758
  };
1759
1759
 
1760
+ const getWindowsChromeMasterKey = (chromeRoot) => {
1761
+ const localStatePath = path.join(chromeRoot, 'Local State');
1762
+ if (!fs.existsSync(localStatePath)) {
1763
+ throw new Error('Chrome Local State 파일을 찾을 수 없습니다.');
1764
+ }
1765
+ const localState = JSON.parse(fs.readFileSync(localStatePath, 'utf-8'));
1766
+ const encryptedKeyB64 = localState.os_crypt && localState.os_crypt.encrypted_key;
1767
+ if (!encryptedKeyB64) {
1768
+ throw new Error('Chrome Local State에서 암호화 키를 찾을 수 없습니다.');
1769
+ }
1770
+ const encryptedKeyWithPrefix = Buffer.from(encryptedKeyB64, 'base64');
1771
+ // 앞 5바이트 "DPAPI" 접두사 제거
1772
+ const encryptedKey = encryptedKeyWithPrefix.slice(5);
1773
+ const encHex = encryptedKey.toString('hex');
1774
+
1775
+ // PowerShell DPAPI로 복호화
1776
+ const psScript = `
1777
+ Add-Type -AssemblyName System.Security
1778
+ $encBytes = [byte[]]::new(${encryptedKey.length})
1779
+ $hex = '${encHex}'
1780
+ for ($i = 0; $i -lt $encBytes.Length; $i++) {
1781
+ $encBytes[$i] = [Convert]::ToByte($hex.Substring($i * 2, 2), 16)
1782
+ }
1783
+ $decBytes = [System.Security.Cryptography.ProtectedData]::Unprotect($encBytes, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)
1784
+ $decHex = -join ($decBytes | ForEach-Object { $_.ToString('x2') })
1785
+ Write-Output $decHex
1786
+ `.trim().replace(/\n/g, '; ');
1787
+
1788
+ try {
1789
+ const decHex = execSync(
1790
+ `powershell -NoProfile -Command "${psScript}"`,
1791
+ { encoding: 'utf-8', timeout: 10000 }
1792
+ ).trim();
1793
+ return Buffer.from(decHex, 'hex');
1794
+ } catch {
1795
+ throw new Error('Chrome 암호화 키를 DPAPI로 복호화할 수 없습니다.');
1796
+ }
1797
+ };
1798
+
1799
+ const decryptChromeCookieWindows = (encryptedValue, masterKey) => {
1800
+ if (!encryptedValue || encryptedValue.length < 4) return '';
1801
+ const prefix = encryptedValue.slice(0, 3).toString('ascii');
1802
+ if (prefix !== 'v10' && prefix !== 'v20') return encryptedValue.toString('utf-8');
1803
+
1804
+ // AES-256-GCM: nonce(12바이트) + ciphertext + authTag(16바이트)
1805
+ const nonce = encryptedValue.slice(3, 3 + 12);
1806
+ const authTag = encryptedValue.slice(encryptedValue.length - 16);
1807
+ const ciphertext = encryptedValue.slice(3 + 12, encryptedValue.length - 16);
1808
+
1809
+ try {
1810
+ const decipher = crypto.createDecipheriv('aes-256-gcm', masterKey, nonce);
1811
+ decipher.setAuthTag(authTag);
1812
+ const dec = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
1813
+ return dec.toString('utf-8');
1814
+ } catch {
1815
+ return '';
1816
+ }
1817
+ };
1818
+
1819
+ const decryptChromeCookie = (encryptedValue, key) => {
1820
+ if (process.platform === 'win32') {
1821
+ return decryptChromeCookieWindows(encryptedValue, key);
1822
+ }
1823
+ return decryptChromeCookieMac(encryptedValue, key);
1824
+ };
1825
+
1826
+ const copyFileViaVSS = (srcPath, destPath) => {
1827
+ const scriptPath = path.join(__dirname, '..', 'scripts', 'vss-copy.ps1');
1828
+ if (!fs.existsSync(scriptPath)) return false;
1829
+ try {
1830
+ const result = execSync(
1831
+ 'powershell -NoProfile -ExecutionPolicy Bypass -File "' + scriptPath + '" -SourcePath "' + srcPath + '" -DestPath "' + destPath + '"',
1832
+ { encoding: 'utf-8', timeout: 30000 }
1833
+ ).trim();
1834
+ return result.includes('OK');
1835
+ } catch {
1836
+ return false;
1837
+ }
1838
+ };
1839
+
1840
+ const isChromeRunning = () => {
1841
+ try {
1842
+ if (process.platform === 'win32') {
1843
+ const result = execSync('tasklist /FI "IMAGENAME eq chrome.exe" /NH', { encoding: 'utf-8', timeout: 5000 });
1844
+ return result.includes('chrome.exe');
1845
+ }
1846
+ const result = execSync('pgrep -x "Google Chrome" 2>/dev/null || pgrep -x chrome 2>/dev/null', { encoding: 'utf-8', timeout: 5000 });
1847
+ return result.trim().length > 0;
1848
+ } catch {
1849
+ return false;
1850
+ }
1851
+ };
1852
+
1760
1853
  const extractChromeCookies = (cookiesDb, derivedKey, domainPattern) => {
1761
1854
  const tempDb = path.join(os.tmpdir(), `viruagent-cookies-${Date.now()}.db`);
1855
+
1856
+ // SQLite 온라인 백업 API 사용 (Chrome이 실행 중이어도 동작)
1857
+ // execFileSync로 쉘을 거치지 않아 Windows 경로 공백/이스케이핑 문제 없음
1858
+ const backupCmd = process.platform === 'win32'
1859
+ ? `.backup "${tempDb}"`
1860
+ : `.backup '${tempDb.replace(/'/g, "''")}'`;
1762
1861
  try {
1763
- execSync(`sqlite3 "${cookiesDb}" ".backup '${tempDb}'"`, { timeout: 5000 });
1862
+ execFileSync('sqlite3', [cookiesDb, backupCmd], { stdio: 'ignore', timeout: 10000 });
1764
1863
  } catch {
1765
- throw new Error('Chrome 쿠키 DB 복사에 실패했습니다. Chrome이 실행 중이면 잠시 후 다시 시도해 주세요.');
1864
+ // sqlite3 백업 실패 파일 복사 VSS 순으로 폴백
1865
+ let copied = false;
1866
+ try {
1867
+ fs.copyFileSync(cookiesDb, tempDb);
1868
+ copied = true;
1869
+ } catch {}
1870
+ if (!copied && process.platform === 'win32') {
1871
+ // Windows: VSS(Volume Shadow Copy)로 잠긴 파일 복사
1872
+ copied = copyFileViaVSS(cookiesDb, tempDb);
1873
+ }
1874
+ if (!copied) {
1875
+ throw new Error('Chrome 쿠키 DB 복사에 실패했습니다. Chrome이 실행 중이면 종료 후 다시 시도해 주세요.');
1876
+ }
1877
+ }
1878
+
1879
+ // 백업 후 남은 WAL/SHM 파일 제거 (깨끗한 DB 보장)
1880
+ for (const suffix of ['-wal', '-shm', '-journal']) {
1881
+ try { fs.unlinkSync(tempDb + suffix); } catch {}
1766
1882
  }
1767
1883
 
1768
1884
  try {
1769
- const rows = execSync(
1770
- `sqlite3 -separator '||' "${tempDb}" "SELECT host_key, name, value, hex(encrypted_value), path, expires_utc, is_secure, is_httponly, samesite FROM cookies WHERE host_key LIKE '${domainPattern}'"`,
1771
- { encoding: 'utf-8', timeout: 5000 }
1772
- ).trim();
1885
+ 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}'`;
1886
+ const rows = execFileSync('sqlite3', ['-separator', '||', tempDb, query], {
1887
+ encoding: 'utf-8',
1888
+ timeout: 5000,
1889
+ }).trim();
1773
1890
  if (!rows) return [];
1774
1891
 
1775
1892
  const chromeEpochOffset = 11644473600;
@@ -1789,31 +1906,484 @@ const extractChromeCookies = (cookiesDb, derivedKey, domainPattern) => {
1789
1906
  }
1790
1907
  };
1791
1908
 
1909
+ const findWindowsChromePath = () => {
1910
+ const candidates = [
1911
+ path.join(process.env['PROGRAMFILES(X86)'] || '', 'Google', 'Chrome', 'Application', 'chrome.exe'),
1912
+ path.join(process.env['PROGRAMFILES'] || '', 'Google', 'Chrome', 'Application', 'chrome.exe'),
1913
+ path.join(process.env['LOCALAPPDATA'] || '', 'Google', 'Chrome', 'Application', 'chrome.exe'),
1914
+ ];
1915
+ return candidates.find(p => fs.existsSync(p)) || null;
1916
+ };
1917
+
1918
+ const generateSelfSignedCert = (domain) => {
1919
+ const tempDir = path.join(os.tmpdir(), `viruagent-cert-${Date.now()}`);
1920
+ fs.mkdirSync(tempDir, { recursive: true });
1921
+ const keyPath = path.join(tempDir, 'key.pem');
1922
+ const certPath = path.join(tempDir, 'cert.pem');
1923
+
1924
+ // openssl (Git for Windows에 포함)
1925
+ const opensslPaths = [
1926
+ 'openssl',
1927
+ 'C:/Program Files/Git/usr/bin/openssl.exe',
1928
+ 'C:/Program Files (x86)/Git/usr/bin/openssl.exe',
1929
+ ];
1930
+ let generated = false;
1931
+ for (const openssl of opensslPaths) {
1932
+ try {
1933
+ execSync(
1934
+ `"${openssl}" req -x509 -newkey rsa:2048 -nodes -keyout "${keyPath}" -out "${certPath}" -days 1 -subj "/CN=${domain}"`,
1935
+ { timeout: 10000, stdio: 'pipe' }
1936
+ );
1937
+ generated = true;
1938
+ break;
1939
+ } catch {}
1940
+ }
1941
+ if (!generated) {
1942
+ try { fs.rmSync(tempDir, { recursive: true, force: true }); } catch {}
1943
+ return null;
1944
+ }
1945
+ return { keyPath, certPath, tempDir };
1946
+ };
1947
+
1948
+ const CDP_DEBUG_PORT = 9222;
1949
+
1950
+ const tryConnectCDP = async (port) => {
1951
+ const http = require('http');
1952
+ return new Promise((resolve) => {
1953
+ http.get(`http://127.0.0.1:${port}/json/version`, { timeout: 2000 }, (res) => {
1954
+ let data = '';
1955
+ res.on('data', c => data += c);
1956
+ res.on('end', () => {
1957
+ try {
1958
+ const info = JSON.parse(data);
1959
+ resolve(info.webSocketDebuggerUrl || null);
1960
+ } catch { resolve(null); }
1961
+ });
1962
+ }).on('error', () => resolve(null));
1963
+ });
1964
+ };
1965
+
1966
+ const findChromeDebugPort = async () => {
1967
+ // 1. 고정 포트 9222 시도
1968
+ const ws = await tryConnectCDP(CDP_DEBUG_PORT);
1969
+ if (ws) return { port: CDP_DEBUG_PORT, wsUrl: ws };
1970
+
1971
+ // 2. DevToolsActivePort 파일 확인
1972
+ const dtpPath = path.join(
1973
+ process.env.LOCALAPPDATA || '',
1974
+ 'Google', 'Chrome', 'User Data', 'DevToolsActivePort'
1975
+ );
1976
+ try {
1977
+ const content = fs.readFileSync(dtpPath, 'utf-8').trim();
1978
+ const port = parseInt(content.split('\n')[0], 10);
1979
+ if (port > 0) {
1980
+ const ws2 = await tryConnectCDP(port);
1981
+ if (ws2) return { port, wsUrl: ws2 };
1982
+ }
1983
+ } catch {}
1984
+
1985
+ return null;
1986
+ };
1987
+
1988
+ const enableChromeDebugPort = () => {
1989
+ // Chrome 바로가기에 --remote-debugging-port 추가 (한 번만 실행)
1990
+ if (process.platform !== 'win32') return false;
1991
+
1992
+ const flag = `--remote-debugging-port=${CDP_DEBUG_PORT}`;
1993
+ const shortcutPaths = [];
1994
+
1995
+ // 바탕화면, 시작 메뉴, 작업표시줄 바로가기 검색
1996
+ const locations = [
1997
+ path.join(os.homedir(), 'Desktop'),
1998
+ path.join(os.homedir(), 'AppData', 'Roaming', 'Microsoft', 'Windows', 'Start Menu', 'Programs'),
1999
+ path.join(os.homedir(), 'AppData', 'Roaming', 'Microsoft', 'Internet Explorer', 'Quick Launch', 'User Pinned', 'TaskBar'),
2000
+ 'C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs',
2001
+ ];
2002
+ for (const loc of locations) {
2003
+ try {
2004
+ const files = fs.readdirSync(loc);
2005
+ for (const f of files) {
2006
+ if (/chrome/i.test(f) && f.endsWith('.lnk')) {
2007
+ shortcutPaths.push(path.join(loc, f));
2008
+ }
2009
+ }
2010
+ } catch {}
2011
+ }
2012
+ // Google Chrome 폴더 내부도 탐색
2013
+ for (const loc of locations) {
2014
+ try {
2015
+ const chromeDir = path.join(loc, 'Google Chrome');
2016
+ if (fs.existsSync(chromeDir)) {
2017
+ const files = fs.readdirSync(chromeDir);
2018
+ for (const f of files) {
2019
+ if (/chrome/i.test(f) && f.endsWith('.lnk')) {
2020
+ shortcutPaths.push(path.join(chromeDir, f));
2021
+ }
2022
+ }
2023
+ }
2024
+ } catch {}
2025
+ }
2026
+
2027
+ let modified = 0;
2028
+ for (const lnkPath of shortcutPaths) {
2029
+ try {
2030
+ const psScript = `
2031
+ $shell = New-Object -ComObject WScript.Shell
2032
+ $sc = $shell.CreateShortcut('${lnkPath.replace(/'/g, "''")}')
2033
+ if ($sc.Arguments -notmatch 'remote-debugging-port') {
2034
+ $sc.Arguments = ($sc.Arguments + ' ${flag}').Trim()
2035
+ $sc.Save()
2036
+ Write-Output 'MODIFIED'
2037
+ } else {
2038
+ Write-Output 'ALREADY'
2039
+ }`;
2040
+ const result = execSync(`powershell -Command "${psScript.replace(/"/g, '\\"')}"`, {
2041
+ timeout: 5000,
2042
+ encoding: 'utf-8',
2043
+ }).trim();
2044
+ if (result === 'MODIFIED') modified++;
2045
+ } catch {}
2046
+ }
2047
+ return modified > 0;
2048
+ };
2049
+
2050
+ const extractCookiesFromCDP = async (port, targetSessionPath) => {
2051
+ const http = require('http');
2052
+ const WebSocket = require('ws');
2053
+
2054
+ // 1. 브라우저 레벨 CDP에 연결하여 tistory 탭 생성/탐색
2055
+ const browserWsUrl = await tryConnectCDP(port);
2056
+ if (!browserWsUrl) throw new Error('Chrome CDP 연결 실패');
2057
+
2058
+ // 2. 기존 tistory 탭 찾거나 새로 생성
2059
+ const targetsJson = await new Promise((resolve, reject) => {
2060
+ http.get(`http://127.0.0.1:${port}/json/list`, { timeout: 3000 }, (res) => {
2061
+ let data = '';
2062
+ res.on('data', c => data += c);
2063
+ res.on('end', () => resolve(data));
2064
+ }).on('error', reject);
2065
+ });
2066
+ const targets = JSON.parse(targetsJson);
2067
+ let pageTarget = targets.find(t => t.type === 'page' && t.url && t.url.includes('tistory'));
2068
+
2069
+ if (!pageTarget) {
2070
+ // tistory 탭이 없으면 브라우저 CDP로 새 탭 생성
2071
+ const bws = new WebSocket(browserWsUrl);
2072
+ const newTargetId = await new Promise((resolve, reject) => {
2073
+ const timeout = setTimeout(() => reject(new Error('탭 생성 시간 초과')), 10000);
2074
+ bws.on('open', () => {
2075
+ bws.send(JSON.stringify({ id: 1, method: 'Target.createTarget', params: { url: 'https://www.tistory.com/' } }));
2076
+ });
2077
+ bws.on('message', (msg) => {
2078
+ const resp = JSON.parse(msg.toString());
2079
+ if (resp.id === 1) {
2080
+ clearTimeout(timeout);
2081
+ resolve(resp.result?.targetId);
2082
+ bws.close();
2083
+ }
2084
+ });
2085
+ bws.on('error', (e) => { clearTimeout(timeout); reject(e); });
2086
+ });
2087
+ // 새 탭의 WebSocket URL 조회
2088
+ await new Promise(r => setTimeout(r, 3000));
2089
+ const newTargetsJson = await new Promise((resolve, reject) => {
2090
+ http.get(`http://127.0.0.1:${port}/json/list`, { timeout: 3000 }, (res) => {
2091
+ let data = '';
2092
+ res.on('data', c => data += c);
2093
+ res.on('end', () => resolve(data));
2094
+ }).on('error', reject);
2095
+ });
2096
+ const newTargets = JSON.parse(newTargetsJson);
2097
+ pageTarget = newTargets.find(t => t.id === newTargetId) || newTargets.find(t => t.type === 'page' && t.url && t.url.includes('tistory'));
2098
+ }
2099
+
2100
+ if (!pageTarget || !pageTarget.webSocketDebuggerUrl) {
2101
+ throw new Error('tistory 페이지 타겟을 찾을 수 없습니다.');
2102
+ }
2103
+
2104
+ // 3. 페이지 레벨 CDP에서 Network.enable → Network.getAllCookies
2105
+ const ws = new WebSocket(pageTarget.webSocketDebuggerUrl);
2106
+ const cookies = await new Promise((resolve, reject) => {
2107
+ const timeout = setTimeout(() => reject(new Error('CDP 쿠키 추출 시간 초과')), 15000);
2108
+ let msgId = 1;
2109
+ ws.on('open', () => {
2110
+ ws.send(JSON.stringify({ id: msgId++, method: 'Network.enable' }));
2111
+ });
2112
+ ws.on('message', (msg) => {
2113
+ const resp = JSON.parse(msg.toString());
2114
+ if (resp.id === 1) {
2115
+ // Network enabled → getAllCookies
2116
+ ws.send(JSON.stringify({ id: msgId++, method: 'Network.getAllCookies' }));
2117
+ }
2118
+ if (resp.id === 2) {
2119
+ clearTimeout(timeout);
2120
+ resolve(resp.result?.cookies || []);
2121
+ ws.close();
2122
+ }
2123
+ });
2124
+ ws.on('error', (e) => { clearTimeout(timeout); reject(e); });
2125
+ });
2126
+
2127
+ const tistoryCookies = cookies.filter(c => String(c.domain).includes('tistory'));
2128
+ const tssession = tistoryCookies.find(c => c.name === 'TSSESSION');
2129
+ if (!tssession || !tssession.value) {
2130
+ throw new Error('Chrome에 티스토리 로그인 세션이 없습니다. Chrome에서 먼저 티스토리에 로그인해 주세요.');
2131
+ }
2132
+
2133
+ const payload = {
2134
+ cookies: tistoryCookies.map(c => ({
2135
+ name: c.name, value: c.value, domain: c.domain,
2136
+ path: c.path || '/', expires: c.expires > 0 ? c.expires : -1,
2137
+ httpOnly: !!c.httpOnly, secure: !!c.secure,
2138
+ sameSite: c.sameSite || 'None',
2139
+ })),
2140
+ updatedAt: new Date().toISOString(),
2141
+ };
2142
+ await fs.promises.mkdir(path.dirname(targetSessionPath), { recursive: true });
2143
+ await fs.promises.writeFile(targetSessionPath, JSON.stringify(payload, null, 2), 'utf-8');
2144
+ return { cookieCount: tistoryCookies.length };
2145
+ };
2146
+
2147
+ const getOrCreateJunctionPath = (chromeRoot) => {
2148
+ // Chrome 145+: 기본 user-data-dir에서는 --remote-debugging-port가 작동하지 않음
2149
+ // Junction point로 같은 디렉토리를 다른 경로로 가리켜서 우회
2150
+ if (process.platform !== 'win32') return chromeRoot;
2151
+
2152
+ const junctionPath = path.join(path.dirname(chromeRoot), 'ChromeDebug');
2153
+ if (!fs.existsSync(junctionPath)) {
2154
+ try {
2155
+ execSync(`cmd /c "mklink /J "${junctionPath}" "${chromeRoot}""`, {
2156
+ timeout: 5000, stdio: 'pipe',
2157
+ });
2158
+ } catch {
2159
+ // Junction 생성 실패 시 원본 경로 사용 (디버그 포트 작동 안 할 수 있음)
2160
+ return chromeRoot;
2161
+ }
2162
+ }
2163
+ return junctionPath;
2164
+ };
2165
+
2166
+ const extractCookiesViaCDP = async (targetSessionPath, chromeRoot, profileName) => {
2167
+ // Chrome 실행 중: CDP(Chrome DevTools Protocol)로 쿠키 추출
2168
+ // 1단계: 이미 디버그 포트가 열려있으면 바로 연결 (크롬 종료 없음)
2169
+ // 2단계: 없으면 한 번만 재시작 + 바로가기 수정 (이후 재시작 불필요)
2170
+ const { spawn } = require('child_process');
2171
+
2172
+ // 1. 이미 디버그 포트가 열려있는지 확인
2173
+ const existing = await findChromeDebugPort();
2174
+ if (existing) {
2175
+ console.log(`[chrome-cdp] 기존 Chrome 디버그 포트(${existing.port}) 감지 — 크롬 종료 없이 쿠키 추출`);
2176
+ return await extractCookiesFromCDP(existing.port, targetSessionPath);
2177
+ }
2178
+
2179
+ // 2. 디버그 포트 없음 → Chrome 바로가기에 디버그 포트 추가 (이후 재시작 불필요)
2180
+ console.log('[chrome-cdp] Chrome 디버그 포트 미감지 — 바로가기에 --remote-debugging-port 추가 중...');
2181
+ const shortcutModified = enableChromeDebugPort();
2182
+ if (shortcutModified) {
2183
+ console.log('[chrome-cdp] Chrome 바로가기 수정 완료 — 다음부터는 크롬 종료 없이 쿠키 추출 가능');
2184
+ }
2185
+
2186
+ // 3. Chrome을 graceful하게 종료하고 디버그 포트로 재시작 (최초 1회만)
2187
+ const chromePath = findWindowsChromePath();
2188
+ if (!chromePath) throw new Error('Chrome 실행 파일을 찾을 수 없습니다.');
2189
+
2190
+ console.log('[chrome-cdp] Chrome을 디버그 포트와 함께 재시작합니다 (탭 자동 복원)...');
2191
+ try {
2192
+ if (process.platform === 'win32') {
2193
+ execSync('cmd /c "taskkill /IM chrome.exe"', { stdio: 'ignore', timeout: 10000 });
2194
+ }
2195
+ } catch {}
2196
+ await new Promise(r => setTimeout(r, 2000));
2197
+ if (isChromeRunning()) {
2198
+ try { execSync('cmd /c "taskkill /F /IM chrome.exe"', { stdio: 'ignore', timeout: 5000 }); } catch {}
2199
+ await new Promise(r => setTimeout(r, 1000));
2200
+ }
2201
+
2202
+ // 4. Junction 경로로 디버그 포트 + 세션 복원 재시작
2203
+ // Chrome 145+는 기본 user-data-dir에서 디버그 포트를 거부하므로 junction으로 우회
2204
+ const junctionRoot = getOrCreateJunctionPath(chromeRoot);
2205
+ const chromeProc = spawn(chromePath, [
2206
+ `--remote-debugging-port=${CDP_DEBUG_PORT}`,
2207
+ '--remote-allow-origins=*',
2208
+ '--restore-last-session',
2209
+ `--user-data-dir=${junctionRoot}`,
2210
+ `--profile-directory=${profileName}`,
2211
+ ], { detached: true, stdio: 'ignore' });
2212
+ chromeProc.unref();
2213
+
2214
+ // 5. CDP 연결 대기
2215
+ let connected = null;
2216
+ const maxWait = 15000;
2217
+ const start = Date.now();
2218
+ while (Date.now() - start < maxWait) {
2219
+ await new Promise(r => setTimeout(r, 500));
2220
+ connected = await findChromeDebugPort();
2221
+ if (connected) break;
2222
+ }
2223
+ if (!connected) throw new Error('Chrome 디버그 포트 연결 시간 초과');
2224
+
2225
+ // 6. 쿠키 추출 (Chrome은 계속 실행 상태 유지 — 종료하지 않음)
2226
+ return await extractCookiesFromCDP(connected.port, targetSessionPath);
2227
+ };
2228
+
2229
+ const importSessionViaChromeDirectLaunch = async (targetSessionPath, chromeRoot, profileName) => {
2230
+ // Windows Chrome 145+: v20 App Bound Encryption으로 외부에서 쿠키 복호화 불가
2231
+ // Chrome 실행 중이면 CDP 방식으로 추출 (잠시 재시작, 탭 자동 복원)
2232
+ if (isChromeRunning()) {
2233
+ return await extractCookiesViaCDP(targetSessionPath, chromeRoot, profileName);
2234
+ }
2235
+
2236
+ const chromePath = findWindowsChromePath();
2237
+ if (!chromePath) {
2238
+ throw new Error('Chrome 실행 파일을 찾을 수 없습니다.');
2239
+ }
2240
+
2241
+ // 1. 자체 서명 인증서 생성 (openssl 필요)
2242
+ const cert = generateSelfSignedCert('www.tistory.com');
2243
+ if (!cert) {
2244
+ throw new Error(
2245
+ 'openssl을 찾을 수 없습니다. Git for Windows를 설치하면 openssl이 포함됩니다.'
2246
+ );
2247
+ }
2248
+
2249
+ const https = require('https');
2250
+ const { spawn } = require('child_process');
2251
+
2252
+ // 2. HTTPS 서버 시작 (포트 443)
2253
+ const server = https.createServer({
2254
+ key: fs.readFileSync(cert.keyPath),
2255
+ cert: fs.readFileSync(cert.certPath),
2256
+ });
2257
+
2258
+ try {
2259
+ await new Promise((resolve, reject) => {
2260
+ server.on('error', reject);
2261
+ server.listen(443, '127.0.0.1', resolve);
2262
+ });
2263
+ } catch (e) {
2264
+ try { fs.rmSync(cert.tempDir, { recursive: true, force: true }); } catch {}
2265
+ throw new Error(`포트 443 바인딩 실패: ${e.message}. 관리자 권한으로 실행해 주세요.`);
2266
+ }
2267
+
2268
+ // 3. 쿠키 수신 Promise
2269
+ let chromeProc = null;
2270
+ const cookiePromise = new Promise((resolve, reject) => {
2271
+ const timeout = setTimeout(() => {
2272
+ reject(new Error('Chrome 쿠키 추출 시간 초과 (15초)'));
2273
+ }, 15000);
2274
+
2275
+ server.on('request', (req, res) => {
2276
+ res.writeHead(200, { 'Content-Type': 'text/html' });
2277
+ res.end('<html><body>Session captured. You can close this window.</body></html>');
2278
+
2279
+ if (req.url === '/' || req.url === '') {
2280
+ clearTimeout(timeout);
2281
+ const cookieHeader = req.headers.cookie || '';
2282
+ resolve(cookieHeader);
2283
+ }
2284
+ });
2285
+ });
2286
+
2287
+ // 4. Chrome 실행 (Chrome이 꺼진 상태에서만 실행됨 - DNS 리다이렉션, 인증서 오류 무시)
2288
+ chromeProc = spawn(chromePath, [
2289
+ '--no-first-run',
2290
+ '--no-default-browser-check',
2291
+ `--profile-directory=${profileName}`,
2292
+ '--host-resolver-rules=MAP www.tistory.com 127.0.0.1',
2293
+ '--ignore-certificate-errors',
2294
+ 'https://www.tistory.com/',
2295
+ ], { detached: true, stdio: 'ignore' });
2296
+ chromeProc.unref();
2297
+
2298
+ try {
2299
+ const cookieHeader = await cookiePromise;
2300
+
2301
+ // Cookie 헤더 파싱
2302
+ const cookies = cookieHeader.split(';')
2303
+ .map(c => c.trim())
2304
+ .filter(Boolean)
2305
+ .map(c => {
2306
+ const eqIdx = c.indexOf('=');
2307
+ if (eqIdx < 0) return null;
2308
+ return { name: c.slice(0, eqIdx).trim(), value: c.slice(eqIdx + 1).trim() };
2309
+ })
2310
+ .filter(Boolean);
2311
+
2312
+ const tssession = cookies.find(c => c.name === 'TSSESSION');
2313
+ if (!tssession || !tssession.value) {
2314
+ throw new Error(
2315
+ 'Chrome에 티스토리 로그인 세션이 없습니다. Chrome에서 먼저 티스토리에 로그인해 주세요.'
2316
+ );
2317
+ }
2318
+
2319
+ // Cookie 헤더에는 domain/path/expires 정보가 없으므로 기본값 설정
2320
+ const payload = {
2321
+ cookies: cookies.map(c => ({
2322
+ name: c.name,
2323
+ value: c.value,
2324
+ domain: '.tistory.com',
2325
+ path: '/',
2326
+ expires: -1,
2327
+ httpOnly: false,
2328
+ secure: true,
2329
+ sameSite: 'None',
2330
+ })),
2331
+ updatedAt: new Date().toISOString(),
2332
+ };
2333
+
2334
+ await fs.promises.mkdir(path.dirname(targetSessionPath), { recursive: true });
2335
+ await fs.promises.writeFile(targetSessionPath, JSON.stringify(payload, null, 2), 'utf-8');
2336
+
2337
+ return { cookieCount: cookies.length };
2338
+ } finally {
2339
+ server.close();
2340
+ if (chromeProc) {
2341
+ try { execSync(`taskkill /F /PID ${chromeProc.pid} /T`, { stdio: 'ignore', timeout: 5000 }); } catch {}
2342
+ }
2343
+ try { fs.rmSync(cert.tempDir, { recursive: true, force: true }); } catch {}
2344
+ }
2345
+ };
2346
+
1792
2347
  const importSessionFromChrome = async (targetSessionPath, profileName = 'Default') => {
1793
- const chromeRoot = path.join(os.homedir(), 'Library', 'Application Support', 'Google', 'Chrome');
2348
+ let chromeRoot;
2349
+ if (process.platform === 'win32') {
2350
+ chromeRoot = path.join(process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local'), 'Google', 'Chrome', 'User Data');
2351
+ } else {
2352
+ chromeRoot = path.join(os.homedir(), 'Library', 'Application Support', 'Google', 'Chrome');
2353
+ }
1794
2354
  if (!fs.existsSync(chromeRoot)) {
1795
2355
  throw new Error('Chrome이 설치되어 있지 않습니다.');
1796
2356
  }
1797
2357
 
1798
2358
  const profileDir = path.join(chromeRoot, profileName);
1799
- const cookiesDb = path.join(profileDir, 'Cookies');
2359
+ // Windows 최신 Chrome은 Network/Cookies, 이전 버전은 Cookies
2360
+ let cookiesDb = path.join(profileDir, 'Network', 'Cookies');
2361
+ if (!fs.existsSync(cookiesDb)) {
2362
+ cookiesDb = path.join(profileDir, 'Cookies');
2363
+ }
1800
2364
  if (!fs.existsSync(cookiesDb)) {
1801
2365
  throw new Error(`Chrome 프로필 "${profileName}"에 쿠키 DB가 없습니다.`);
1802
2366
  }
1803
2367
 
1804
- // 1) Keychain에서 Chrome 암호화 키 추출
1805
- let keychainPassword;
1806
- try {
1807
- keychainPassword = execSync(
1808
- 'security find-generic-password -s "Chrome Safe Storage" -w',
1809
- { encoding: 'utf-8', timeout: 5000 }
1810
- ).trim();
1811
- } catch {
1812
- throw new Error('Chrome Safe Storage 키를 Keychain에서 읽을 수 없습니다. macOS 권한을 확인해 주세요.');
2368
+ let derivedKey;
2369
+ if (process.platform === 'win32') {
2370
+ // Windows: Local State → DPAPI로 마스터 키 복호화
2371
+ derivedKey = getWindowsChromeMasterKey(chromeRoot);
2372
+ } else {
2373
+ // macOS: Keychain에서 Chrome 암호화 키 추출
2374
+ let keychainPassword;
2375
+ try {
2376
+ keychainPassword = execSync(
2377
+ 'security find-generic-password -s "Chrome Safe Storage" -w',
2378
+ { encoding: 'utf-8', timeout: 5000 }
2379
+ ).trim();
2380
+ } catch {
2381
+ throw new Error('Chrome Safe Storage 키를 Keychain에서 읽을 수 없습니다. macOS 권한을 확인해 주세요.');
2382
+ }
2383
+ derivedKey = crypto.pbkdf2Sync(keychainPassword, 'saltysalt', 1003, 16, 'sha1');
1813
2384
  }
1814
- const derivedKey = crypto.pbkdf2Sync(keychainPassword, 'saltysalt', 1003, 16, 'sha1');
1815
2385
 
1816
- // 2) Chrome에서 tistory + kakao 쿠키 복호화 추출
2386
+ // Chrome에서 tistory + kakao 쿠키 복호화 추출
1817
2387
  const tistoryCookies = extractChromeCookies(cookiesDb, derivedKey, '%tistory.com');
1818
2388
  const kakaoCookies = extractChromeCookies(cookiesDb, derivedKey, '%kakao.com');
1819
2389
 
@@ -1829,6 +2399,11 @@ const importSessionFromChrome = async (targetSessionPath, profileName = 'Default
1829
2399
  // 3) 카카오 세션 쿠키가 있으면 Playwright에 주입 후 자동 로그인
1830
2400
  const hasKakaoSession = kakaoCookies.some(c => c.domain.includes('kakao.com') && (c.name === '_kawlt' || c.name === '_kawltea' || c.name === '_karmt'));
1831
2401
  if (!hasKakaoSession) {
2402
+ // Windows v20 App Bound Encryption: DPAPI만으로 복호화 불가
2403
+ // Playwright persistent context (pipe 모드)로 Chrome 기본 프로필에서 직접 추출
2404
+ if (process.platform === 'win32') {
2405
+ return await importSessionViaChromeDirectLaunch(targetSessionPath, chromeRoot, profileName);
2406
+ }
1832
2407
  throw new Error('Chrome에 카카오 로그인 세션이 없습니다. Chrome에서 먼저 카카오 계정에 로그인해 주세요.');
1833
2408
  }
1834
2409
 
@@ -0,0 +1,28 @@
1
+ param(
2
+ [Parameter(Mandatory=$true)][string]$SourcePath,
3
+ [Parameter(Mandatory=$true)][string]$DestPath
4
+ )
5
+
6
+ $ErrorActionPreference = 'Stop'
7
+
8
+ $drive = $SourcePath.Substring(0, 2) + '\'
9
+ $relativePath = $SourcePath.Substring(2)
10
+
11
+ try {
12
+ $shadow = (Get-WmiObject -List Win32_ShadowCopy).Create($drive, 'ClientAccessible')
13
+ $shadowObj = Get-WmiObject Win32_ShadowCopy | Where-Object { $_.ID -eq $shadow.ShadowID }
14
+ $shadowPath = $shadowObj.DeviceObject + $relativePath
15
+
16
+ cmd /c "copy `"$shadowPath`" `"$DestPath`" /y" | Out-Null
17
+
18
+ $shadowObj.Delete()
19
+
20
+ if (Test-Path $DestPath) {
21
+ Write-Output 'OK'
22
+ } else {
23
+ Write-Output 'FAIL'
24
+ }
25
+ } catch {
26
+ Write-Error $_
27
+ exit 1
28
+ }