|
| 1 | +import fs from 'fs'; |
| 2 | +import path from 'path'; |
| 3 | + |
| 4 | +import { log } from '../middleware/logger'; |
| 5 | + |
| 6 | +// ── 타입 ────────────────────────────────────────────────────────── |
| 7 | + |
| 8 | +export type TunnelMode = 'quick' | 'named'; |
| 9 | + |
| 10 | +export interface TunnelConfig { |
| 11 | + mode: TunnelMode; |
| 12 | + token: string; |
| 13 | +} |
| 14 | + |
| 15 | +export interface TunnelStatus { |
| 16 | + running: boolean; |
| 17 | + url: string | null; |
| 18 | + mode: TunnelMode | null; |
| 19 | +} |
| 20 | + |
| 21 | +// ── 설정 파일 경로 ──────────────────────────────────────────────── |
| 22 | + |
| 23 | +const CONFIG_PATH = path.resolve(process.cwd(), 'tunnel.config.json'); |
| 24 | + |
| 25 | +function loadConfig(): TunnelConfig { |
| 26 | + try { |
| 27 | + const raw = fs.readFileSync(CONFIG_PATH, 'utf-8'); |
| 28 | + return JSON.parse(raw) as TunnelConfig; |
| 29 | + } catch { |
| 30 | + return { mode: 'quick', token: '' }; |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +function saveConfig(cfg: TunnelConfig): void { |
| 35 | + fs.writeFileSync(CONFIG_PATH, JSON.stringify(cfg, null, 2), 'utf-8'); |
| 36 | +} |
| 37 | + |
| 38 | +// ── 터널 매니저 (싱글턴) ────────────────────────────────────────── |
| 39 | + |
| 40 | +class CloudflareTunnelManager { |
| 41 | + private _running = false; |
| 42 | + private _url: string | null = null; |
| 43 | + private _mode: TunnelMode | null = null; |
| 44 | + private _tunnelInstance: { stop: () => boolean } | null = null; |
| 45 | + |
| 46 | + get status(): TunnelStatus { |
| 47 | + return { running: this._running, url: this._url, mode: this._mode }; |
| 48 | + } |
| 49 | + |
| 50 | + getConfig(): TunnelConfig { |
| 51 | + return loadConfig(); |
| 52 | + } |
| 53 | + |
| 54 | + setConfig(cfg: TunnelConfig): void { |
| 55 | + saveConfig(cfg); |
| 56 | + } |
| 57 | + |
| 58 | + async start(): Promise<{ url: string }> { |
| 59 | + if (this._running) { |
| 60 | + if (this._url) return { url: this._url }; |
| 61 | + throw new Error('터널이 이미 시작 중입니다.'); |
| 62 | + } |
| 63 | + |
| 64 | + const cfg = loadConfig(); |
| 65 | + |
| 66 | + // cloudflared 패키지 동적 import |
| 67 | + let TunnelClass: typeof import('cloudflared').Tunnel; |
| 68 | + try { |
| 69 | + const mod = await import('cloudflared'); |
| 70 | + TunnelClass = mod.Tunnel; |
| 71 | + } catch { |
| 72 | + throw new Error('cloudflared 패키지가 설치되어 있지 않습니다. pnpm install을 실행해주세요.'); |
| 73 | + } |
| 74 | + |
| 75 | + this._running = true; |
| 76 | + this._mode = cfg.mode; |
| 77 | + |
| 78 | + try { |
| 79 | + // 개발 모드에서는 Vite dev server(5173)로, 프로덕션에서는 API 서버로 연결 |
| 80 | + // localhost 대신 127.0.0.1 사용 — WSL2에서 localhost가 ::1(IPv6)로 해석되어 |
| 81 | + // Vite가 응답하지 못하는 Error 1033 방지 |
| 82 | + const isDev = process.env['NODE_ENV'] !== 'production'; |
| 83 | + const localUrl = isDev |
| 84 | + ? `http://127.0.0.1:${process.env['VITE_PORT'] ?? 5173}` |
| 85 | + : `http://127.0.0.1:${process.env['PORT'] ?? 3000}`; |
| 86 | + |
| 87 | + log.info('tunnel', `starting ${cfg.mode} tunnel → ${localUrl}`); |
| 88 | + |
| 89 | + const tunnelInstance = |
| 90 | + cfg.mode === 'named' |
| 91 | + ? (() => { |
| 92 | + if (!cfg.token) throw new Error('Named Tunnel 토큰이 설정되어 있지 않습니다.'); |
| 93 | + return TunnelClass.withToken(cfg.token); |
| 94 | + })() |
| 95 | + : TunnelClass.quick(localUrl); |
| 96 | + |
| 97 | + this._tunnelInstance = tunnelInstance; |
| 98 | + |
| 99 | + // cloudflared stdout/stderr를 서버 로그로 중계 |
| 100 | + tunnelInstance.on('stdout', (data: string) => { |
| 101 | + for (const line of data.trim().split('\n')) { |
| 102 | + if (line.trim()) log.info('cloudflared', line.trim()); |
| 103 | + } |
| 104 | + }); |
| 105 | + tunnelInstance.on('stderr', (data: string) => { |
| 106 | + for (const line of data.trim().split('\n')) { |
| 107 | + if (line.trim()) log.info('cloudflared', line.trim()); |
| 108 | + } |
| 109 | + }); |
| 110 | + |
| 111 | + const url = await new Promise<string>((resolve, reject) => { |
| 112 | + const timeout = setTimeout(() => { |
| 113 | + reject(new Error('터널 URL을 가져오는 데 시간이 초과되었습니다 (60초).')); |
| 114 | + }, 60_000); |
| 115 | + |
| 116 | + tunnelInstance.once('url', (tunnelUrl: string) => { |
| 117 | + clearTimeout(timeout); |
| 118 | + log.success('tunnel', `tunnel active → ${tunnelUrl}`); |
| 119 | + resolve(tunnelUrl); |
| 120 | + }); |
| 121 | + |
| 122 | + tunnelInstance.once('error', (err: Error) => { |
| 123 | + clearTimeout(timeout); |
| 124 | + log.error('tunnel', `tunnel error: ${err.message}`); |
| 125 | + reject(err); |
| 126 | + }); |
| 127 | + |
| 128 | + tunnelInstance.once('exit', (code: number | null) => { |
| 129 | + clearTimeout(timeout); |
| 130 | + reject(new Error(`cloudflared 프로세스가 예상치 못하게 종료되었습니다 (code: ${code}).`)); |
| 131 | + }); |
| 132 | + }); |
| 133 | + |
| 134 | + this._url = url; |
| 135 | + |
| 136 | + // 프로세스 종료 시 상태 초기화 및 로그 |
| 137 | + tunnelInstance.once('exit', (code: number | null) => { |
| 138 | + log.warn('tunnel', `cloudflared exited (code: ${code ?? 'null'})`); |
| 139 | + this._running = false; |
| 140 | + this._url = null; |
| 141 | + this._mode = null; |
| 142 | + this._tunnelInstance = null; |
| 143 | + }); |
| 144 | + |
| 145 | + return { url }; |
| 146 | + } catch (err) { |
| 147 | + this._running = false; |
| 148 | + this._mode = null; |
| 149 | + this._tunnelInstance = null; |
| 150 | + throw err; |
| 151 | + } |
| 152 | + } |
| 153 | + |
| 154 | + stop(): void { |
| 155 | + if (!this._running || !this._tunnelInstance) throw new Error('실행 중인 터널이 없습니다.'); |
| 156 | + log.info('tunnel', 'stopping tunnel…'); |
| 157 | + this._tunnelInstance.stop(); |
| 158 | + this._running = false; |
| 159 | + this._url = null; |
| 160 | + this._mode = null; |
| 161 | + this._tunnelInstance = null; |
| 162 | + } |
| 163 | +} |
| 164 | + |
| 165 | +export const tunnelManager = new CloudflareTunnelManager(); |
0 commit comments