|
1 | 1 | import { existsSync, readFileSync } from 'node:fs' |
| 2 | +import { isIP } from 'node:net' |
| 3 | +import { networkInterfaces } from 'node:os' |
2 | 4 | import { styleText } from 'node:util' |
3 | 5 |
|
4 | 6 | import { join, resolve } from 'pathe' |
@@ -51,11 +53,35 @@ export async function findDevServer(cwd: string, buildDir?: string): Promise<Run |
51 | 53 | const dir = buildDir ? resolve(cwd, buildDir) : await resolveLockDir(cwd) |
52 | 54 |
|
53 | 55 | const lock = readActiveLock(dir) |
54 | | - if (lock?.command === 'dev' && lock.url) { |
| 56 | + if (lock?.command === 'dev' && lock.url && isOwnAddress(lock.url)) { |
55 | 57 | return { url: toLoopback(lock.url), pid: lock.pid, cwd: lock.cwd } |
56 | 58 | } |
57 | 59 | } |
58 | 60 |
|
| 61 | +/** |
| 62 | + * Whether `url` names this machine. A dev server records the address it bound, |
| 63 | + * which is always local, but the lock file it is read from lives in the project |
| 64 | + * and so may have been written by someone else. Requests carrying the user's |
| 65 | + * headers and payloads are only sent to an origin this machine could have bound. |
| 66 | + */ |
| 67 | +function isOwnAddress(url: string): boolean { |
| 68 | + let hostname: string |
| 69 | + try { |
| 70 | + hostname = new URL(url).hostname |
| 71 | + } |
| 72 | + catch { |
| 73 | + return false |
| 74 | + } |
| 75 | + if (isLocalHost(hostname)) { |
| 76 | + return true |
| 77 | + } |
| 78 | + const address = hostname.startsWith('[') ? hostname.slice(1, -1) : hostname |
| 79 | + if (!isIP(address)) { |
| 80 | + return false |
| 81 | + } |
| 82 | + return Object.values(networkInterfaces()).flat().some(info => info?.address === address) |
| 83 | +} |
| 84 | + |
59 | 85 | /** |
60 | 86 | * A dev server bound to every interface records the wildcard it was given, but |
61 | 87 | * that is not an address to connect to: Windows refuses `0.0.0.0` outright, and |
|
0 commit comments