|
| 1 | +import { spawn } from 'node:child_process' |
| 2 | +import fs from 'node:fs' |
| 3 | +import os from 'node:os' |
| 4 | +import path from 'node:path' |
| 5 | +import process from 'node:process' |
| 6 | +import { log } from '@stacksjs/cli' |
| 7 | +import { config } from './config' |
| 8 | +import { debugLog } from './utils' |
| 9 | + |
| 10 | +export const hostsFilePath: string = process.platform === 'win32' |
| 11 | + ? path.join(process.env.windir || 'C:\\Windows', 'System32', 'drivers', 'etc', 'hosts') |
| 12 | + : '/etc/hosts' |
| 13 | + |
| 14 | +async function sudoWrite(operation: 'append' | 'write', content: string): Promise<void> { |
| 15 | + return new Promise((resolve, reject) => { |
| 16 | + if (process.platform === 'win32') { |
| 17 | + reject(new Error('Administrator privileges required on Windows')) |
| 18 | + return |
| 19 | + } |
| 20 | + |
| 21 | + const tmpFile = path.join(os.tmpdir(), 'hosts.tmp') |
| 22 | + |
| 23 | + try { |
| 24 | + if (operation === 'append') { |
| 25 | + // For append, read current content first |
| 26 | + const currentContent = fs.readFileSync(hostsFilePath, 'utf8') |
| 27 | + fs.writeFileSync(tmpFile, currentContent + content, 'utf8') |
| 28 | + } |
| 29 | + else { |
| 30 | + // For write, just write the new content |
| 31 | + fs.writeFileSync(tmpFile, content, 'utf8') |
| 32 | + } |
| 33 | + |
| 34 | + const sudo = spawn('sudo', ['cp', tmpFile, hostsFilePath]) |
| 35 | + |
| 36 | + sudo.on('close', (code) => { |
| 37 | + try { |
| 38 | + fs.unlinkSync(tmpFile) |
| 39 | + if (code === 0) |
| 40 | + resolve() |
| 41 | + else |
| 42 | + reject(new Error(`sudo process exited with code ${code}`)) |
| 43 | + } |
| 44 | + catch (err) { |
| 45 | + reject(err) |
| 46 | + } |
| 47 | + }) |
| 48 | + |
| 49 | + sudo.on('error', (err) => { |
| 50 | + try { |
| 51 | + fs.unlinkSync(tmpFile) |
| 52 | + } |
| 53 | + catch { } |
| 54 | + reject(err) |
| 55 | + }) |
| 56 | + } |
| 57 | + catch (err) { |
| 58 | + reject(err) |
| 59 | + } |
| 60 | + }) |
| 61 | +} |
| 62 | + |
| 63 | +export async function addHosts(hosts: string[]): Promise<void> { |
| 64 | + debugLog('hosts', `Adding hosts: ${hosts.join(', ')}`, config.verbose) |
| 65 | + debugLog('hosts', `Using hosts file at: ${hostsFilePath}`, config.verbose) |
| 66 | + |
| 67 | + try { |
| 68 | + // Read existing hosts file content |
| 69 | + const existingContent = await fs.promises.readFile(hostsFilePath, 'utf-8') |
| 70 | + |
| 71 | + // Prepare new entries, only including those that don't exist |
| 72 | + const newEntries = hosts.filter((host) => { |
| 73 | + const ipv4Entry = `127.0.0.1 ${host}` |
| 74 | + const ipv6Entry = `::1 ${host}` |
| 75 | + return !existingContent.includes(ipv4Entry) && !existingContent.includes(ipv6Entry) |
| 76 | + }) |
| 77 | + |
| 78 | + if (newEntries.length === 0) { |
| 79 | + debugLog('hosts', 'All hosts already exist in hosts file', config.verbose) |
| 80 | + log.info('All hosts are already in the hosts file') |
| 81 | + return |
| 82 | + } |
| 83 | + |
| 84 | + // Create content for new entries |
| 85 | + const hostEntries = newEntries.map(host => |
| 86 | + `\n# Added by rpx\n127.0.0.1 ${host}\n::1 ${host}`, |
| 87 | + ).join('\n') |
| 88 | + |
| 89 | + try { |
| 90 | + // Try normal write first |
| 91 | + await fs.promises.appendFile(hostsFilePath, hostEntries, { flag: 'a' }) |
| 92 | + log.success(`Added new hosts: ${newEntries.join(', ')}`) |
| 93 | + } |
| 94 | + catch (writeErr) { |
| 95 | + if ((writeErr as NodeJS.ErrnoException).code === 'EACCES') { |
| 96 | + debugLog('hosts', 'Permission denied, attempting with sudo', config.verbose) |
| 97 | + try { |
| 98 | + await sudoWrite('append', hostEntries) |
| 99 | + log.success(`Added new hosts with sudo: ${newEntries.join(', ')}`) |
| 100 | + } |
| 101 | + // eslint-disable-next-line unused-imports/no-unused-vars |
| 102 | + catch (sudoErr) { |
| 103 | + log.error('Failed to modify hosts file automatically') |
| 104 | + log.warn('Please add these entries to your hosts file manually:') |
| 105 | + hostEntries.split('\n').forEach(entry => log.warn(entry)) |
| 106 | + |
| 107 | + if (process.platform === 'win32') { |
| 108 | + log.warn('\nOn Windows:') |
| 109 | + log.warn('1. Run notepad as administrator') |
| 110 | + log.warn('2. Open C:\\Windows\\System32\\drivers\\etc\\hosts') |
| 111 | + } |
| 112 | + else { |
| 113 | + log.warn('\nOn Unix systems:') |
| 114 | + log.warn(`sudo nano ${hostsFilePath}`) |
| 115 | + } |
| 116 | + |
| 117 | + throw new Error('Failed to modify hosts file: manual intervention required') |
| 118 | + } |
| 119 | + } |
| 120 | + else { |
| 121 | + throw writeErr |
| 122 | + } |
| 123 | + } |
| 124 | + } |
| 125 | + catch (err) { |
| 126 | + const error = err as Error |
| 127 | + log.error(`Failed to manage hosts file: ${error.message}`) |
| 128 | + throw error |
| 129 | + } |
| 130 | +} |
| 131 | + |
| 132 | +export async function removeHosts(hosts: string[]): Promise<void> { |
| 133 | + debugLog('hosts', `Removing hosts: ${hosts.join(', ')}`, config.verbose) |
| 134 | + |
| 135 | + try { |
| 136 | + const content = await fs.promises.readFile(hostsFilePath, 'utf-8') |
| 137 | + const lines = content.split('\n') |
| 138 | + |
| 139 | + // Filter out our added entries and their comments |
| 140 | + const filteredLines = lines.filter((line, index) => { |
| 141 | + // If it's our comment, skip this line and the following IPv4/IPv6 entries |
| 142 | + if (line.trim() === '# Added by rpx') { |
| 143 | + // Skip next two lines (IPv4 and IPv6) |
| 144 | + lines.splice(index + 1, 2) |
| 145 | + return false |
| 146 | + } |
| 147 | + return true |
| 148 | + }) |
| 149 | + |
| 150 | + // Remove empty lines at the end of the file |
| 151 | + while (filteredLines[filteredLines.length - 1]?.trim() === '') |
| 152 | + filteredLines.pop() |
| 153 | + |
| 154 | + // Ensure file ends with a single newline |
| 155 | + const newContent = `${filteredLines.join('\n')}\n` |
| 156 | + |
| 157 | + try { |
| 158 | + await fs.promises.writeFile(hostsFilePath, newContent) |
| 159 | + log.success('Hosts removed successfully') |
| 160 | + } |
| 161 | + catch (writeErr) { |
| 162 | + if ((writeErr as NodeJS.ErrnoException).code === 'EACCES') { |
| 163 | + debugLog('hosts', 'Permission denied, attempting with sudo', config.verbose) |
| 164 | + try { |
| 165 | + await sudoWrite('write', newContent) |
| 166 | + log.success('Hosts removed successfully with sudo') |
| 167 | + } |
| 168 | + // eslint-disable-next-line unused-imports/no-unused-vars |
| 169 | + catch (sudoErr) { |
| 170 | + log.error('Failed to modify hosts file automatically') |
| 171 | + log.warn('Please remove these entries from your hosts file manually:') |
| 172 | + hosts.forEach((host) => { |
| 173 | + log.warn('# Added by rpx') |
| 174 | + log.warn(`127.0.0.1 ${host}`) |
| 175 | + log.warn(`::1 ${host}`) |
| 176 | + }) |
| 177 | + |
| 178 | + if (process.platform === 'win32') { |
| 179 | + log.warn('\nOn Windows:') |
| 180 | + log.warn('1. Run notepad as administrator') |
| 181 | + log.warn('2. Open C:\\Windows\\System32\\drivers\\etc\\hosts') |
| 182 | + } |
| 183 | + else { |
| 184 | + log.warn('\nOn Unix systems:') |
| 185 | + log.warn(`sudo nano ${hostsFilePath}`) |
| 186 | + } |
| 187 | + |
| 188 | + throw new Error('Failed to modify hosts file: manual intervention required') |
| 189 | + } |
| 190 | + } |
| 191 | + else { |
| 192 | + throw writeErr |
| 193 | + } |
| 194 | + } |
| 195 | + } |
| 196 | + catch (err) { |
| 197 | + const error = err as Error |
| 198 | + log.error(`Failed to remove hosts: ${error.message}`) |
| 199 | + throw error |
| 200 | + } |
| 201 | +} |
| 202 | + |
| 203 | +// Helper function to check if hosts exist |
| 204 | +export async function checkHosts(hosts: string[]): Promise<boolean[]> { |
| 205 | + debugLog('hosts', `Checking hosts: ${hosts}`, config.verbose) |
| 206 | + |
| 207 | + const content = await fs.promises.readFile(hostsFilePath, 'utf-8') |
| 208 | + return hosts.map((host) => { |
| 209 | + const ipv4Entry = `127.0.0.1 ${host}` |
| 210 | + const ipv6Entry = `::1 ${host}` |
| 211 | + return content.includes(ipv4Entry) || content.includes(ipv6Entry) |
| 212 | + }) |
| 213 | +} |
0 commit comments