-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.js
66 lines (57 loc) · 1.75 KB
/
config.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
const { mkdir, readdir, writeFile, readFile } = require('fs/promises');
const { networkInterfaces } = require('os');
const { homedir } = require('os');
const { join } = require('path');
const configDir =
process.env.PROXY_CONFIG_DIR || join(homedir(), '.virtual-host-proxy');
async function ensureResolversConfig(rootDomain) {
try {
const exists = await checkIfRootDomainResolverExists(rootDomain);
if (!exists) {
await writeFile(`/etc/resolver/${rootDomain}`, 'nameserver 127.0.0.1');
}
} catch (err) {
if (err.code === 'EACCES') {
console.log('Resolver config not found, add it yourself:');
console.log(
`sudo -- sh -c 'mkdir -p /etc/resolver && echo nameserver 127.0.0.1 > /etc/resolver/${rootDomain}'`,
);
} else throw err;
}
}
async function checkIfRootDomainResolverExists(rootDomain) {
try {
const files = await readdir('/etc/resolver');
return files.includes(rootDomain);
} catch (err) {
if (err.code === 'ENOENT') {
await mkdir('/etc/resolver', { recursive: true });
return false;
}
throw err;
}
}
function getInterfaces() {
return Object.values(networkInterfaces()).flatMap((interfaces) => {
return interfaces.filter((x) => x.family === 'IPv4' && !x.internal);
});
}
async function getNameserver() {
try {
const resolvConf = await readFile('/etc/resolv.conf', 'utf8');
const match = resolvConf.match(/nameserver\s([\d.]+)/);
if (!match) {
return '8.8.8.8';
}
return match[1];
} catch (err) {
if (err.code === 'ENOENT') {
return '8.8.8.8';
}
throw err;
}
}
exports.configDir = configDir;
exports.ensureResolversConfig = ensureResolversConfig;
exports.getInterfaces = getInterfaces;
exports.getNameserver = getNameserver;