@bestapps/bestgate 0.0.0-stage → 0.1.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/LICENSE +201 -0
- package/README.md +138 -2
- package/bin/bestgate.js +107 -0
- package/install.sh +82 -0
- package/package.json +38 -4
- package/src/client/login.js +41 -0
- package/src/client/store.js +41 -0
- package/src/client/tunnel.js +326 -0
- package/src/frp.js +133 -0
- package/src/key.js +56 -0
- package/src/reasons.js +11 -0
- package/src/server/cert.js +72 -0
- package/src/server/check.js +47 -0
- package/src/server/config.js +193 -0
- package/src/server/daemon.js +351 -0
- package/src/server/db.js +170 -0
- package/src/server/install.js +321 -0
- package/src/server/manifest.js +57 -0
- package/src/server/nginx.js +243 -0
- package/src/server/plan.js +316 -0
- package/src/server/policy.js +237 -0
- package/src/server/render.js +141 -0
- package/src/server/revert.js +128 -0
- package/src/server/rotate-token.js +34 -0
- package/src/server/status.js +114 -0
- package/src/server/sys.js +515 -0
- package/src/server/templates/bestgate-auth.service +56 -0
- package/src/server/templates/bestgate-check.service +42 -0
- package/src/server/templates/bestgate-check.timer +13 -0
- package/src/server/templates/frps.service +52 -0
- package/src/server/templates/frps.toml +51 -0
- package/src/server/templates/motd.sh +12 -0
- package/src/server/templates/nginx.conf.template +111 -0
- package/src/server/users.js +170 -0
- package/src/server/verify.js +127 -0
- package/src/server/wizard.js +198 -0
- package/src/util.js +26 -0
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
// Reading the running nginx configuration (`nginx -T`) to decide whether our site can
|
|
2
|
+
// join it safely: which layout it uses, which servers listen on our address, whether
|
|
3
|
+
// ours would become the default server, and whether any existing name would capture
|
|
4
|
+
// (or be captured by) the tunnel names. Pure functions; the caller runs nginx.
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { SITE_NAME } from './sys.js';
|
|
7
|
+
|
|
8
|
+
const posix = path.posix;
|
|
9
|
+
|
|
10
|
+
// "# configuration file /etc/nginx/nginx.conf:" lines separate the files in `nginx -T`.
|
|
11
|
+
export function splitDump(dump) {
|
|
12
|
+
const files = [];
|
|
13
|
+
let cur = null;
|
|
14
|
+
for (const line of String(dump).split('\n')) {
|
|
15
|
+
const m = /^# configuration file (.+):\s*$/.exec(line);
|
|
16
|
+
if (m) {
|
|
17
|
+
cur = { file: m[1], lines: [] };
|
|
18
|
+
files.push(cur);
|
|
19
|
+
} else if (cur) cur.lines.push(line);
|
|
20
|
+
}
|
|
21
|
+
return files.map((f) => ({ file: f.file, text: f.lines.join('\n') }));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// nginx tokens: words (quotes removed), "{", "}", ";". '#' starts a comment only where
|
|
25
|
+
// a token could start, as in nginx itself.
|
|
26
|
+
export function tokenize(text) {
|
|
27
|
+
const out = [];
|
|
28
|
+
let i = 0;
|
|
29
|
+
const n = text.length;
|
|
30
|
+
while (i < n) {
|
|
31
|
+
const ch = text[i];
|
|
32
|
+
if (/\s/.test(ch)) { i++; continue; }
|
|
33
|
+
if (ch === '#') { while (i < n && text[i] !== '\n') i++; continue; }
|
|
34
|
+
if (ch === '{' || ch === '}' || ch === ';') { out.push(ch); i++; continue; }
|
|
35
|
+
if (ch === '"' || ch === "'") {
|
|
36
|
+
let v = '';
|
|
37
|
+
i++;
|
|
38
|
+
while (i < n && text[i] !== ch) {
|
|
39
|
+
if (text[i] === '\\' && i + 1 < n) { v += text[i + 1]; i += 2; continue; }
|
|
40
|
+
v += text[i++];
|
|
41
|
+
}
|
|
42
|
+
if (i >= n) throw new Error('unterminated quote');
|
|
43
|
+
i++;
|
|
44
|
+
out.push({ w: v });
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
let v = '';
|
|
48
|
+
while (i < n && !/\s/.test(text[i]) && text[i] !== ';' && text[i] !== '{' && text[i] !== '}') {
|
|
49
|
+
if (text[i] === '\\' && i + 1 < n) { v += text[i] + text[i + 1]; i += 2; continue; }
|
|
50
|
+
if (text[i] === '$' && text[i + 1] === '{') { // ${var} inside a word
|
|
51
|
+
const j = text.indexOf('}', i);
|
|
52
|
+
if (j < 0) throw new Error('unterminated ${');
|
|
53
|
+
v += text.slice(i, j + 1);
|
|
54
|
+
i = j + 1;
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
v += text[i++];
|
|
58
|
+
}
|
|
59
|
+
out.push({ w: v });
|
|
60
|
+
}
|
|
61
|
+
return out;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// "443", "*:443", "1.2.3.4:443", "[::1]:443", "unix:/x" → {addr, port}
|
|
65
|
+
export function parseListenAddr(s) {
|
|
66
|
+
if (s.startsWith('unix:')) return { addr: s, port: null };
|
|
67
|
+
let m = /^\[([^\]]+)\](?::(\d+))?$/.exec(s);
|
|
68
|
+
if (m) return { addr: m[1].toLowerCase(), port: m[2] ? +m[2] : 80 };
|
|
69
|
+
if (/^\d+$/.test(s)) return { addr: '*', port: +s };
|
|
70
|
+
m = /^(.*):(\d+)$/.exec(s);
|
|
71
|
+
if (m) return { addr: m[1] === '0.0.0.0' ? '*' : m[1].toLowerCase(), port: +m[2] };
|
|
72
|
+
return { addr: s.toLowerCase(), port: 80 };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* → { files: [path...] in dump order, servers: [{file, listens:[{addr,port,flags}], names:[]}],
|
|
77
|
+
* includes: [{file, arg}], tokensByFile: Map(file → words) }
|
|
78
|
+
* Throws on unbalanced braces (fail closed: the caller reports it as FAIL).
|
|
79
|
+
*/
|
|
80
|
+
export function parseDump(dump) {
|
|
81
|
+
const parts = splitDump(dump);
|
|
82
|
+
if (!parts.length) throw new Error('no "# configuration file" sections in nginx -T output');
|
|
83
|
+
const files = [];
|
|
84
|
+
const servers = [];
|
|
85
|
+
const includes = [];
|
|
86
|
+
const words = new Map();
|
|
87
|
+
for (const { file, text } of parts) {
|
|
88
|
+
files.push(file);
|
|
89
|
+
const toks = tokenize(text);
|
|
90
|
+
words.set(file, toks.filter((t) => typeof t === 'object').map((t) => t.w));
|
|
91
|
+
const stack = [];
|
|
92
|
+
let stmt = [];
|
|
93
|
+
let server = null;
|
|
94
|
+
for (const t of toks) {
|
|
95
|
+
if (typeof t === 'object') { stmt.push(t.w); continue; }
|
|
96
|
+
if (t === '{') {
|
|
97
|
+
const name = stmt[0] || '';
|
|
98
|
+
const inOther = stack.some((s) => s === 'stream' || s === 'mail');
|
|
99
|
+
if (name === 'server' && !inOther && !stack.includes('server')) {
|
|
100
|
+
server = { file, listens: [], names: [], depth: stack.length + 1 };
|
|
101
|
+
}
|
|
102
|
+
stack.push(name);
|
|
103
|
+
stmt = [];
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
if (t === '}') {
|
|
107
|
+
if (!stack.length) throw new Error(`unbalanced "}" in ${file}`);
|
|
108
|
+
stack.pop();
|
|
109
|
+
if (server && stack.length < server.depth) {
|
|
110
|
+
servers.push({ file: server.file, listens: server.listens, names: server.names });
|
|
111
|
+
server = null;
|
|
112
|
+
}
|
|
113
|
+
stmt = [];
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
// ';'
|
|
117
|
+
const [d, ...args] = stmt;
|
|
118
|
+
if (d === 'include' && args[0]) includes.push({ file, arg: args[0] });
|
|
119
|
+
if (server && stack.length === server.depth) {
|
|
120
|
+
if (d === 'listen' && args[0]) {
|
|
121
|
+
const a = parseListenAddr(args[0]);
|
|
122
|
+
server.listens.push({ ...a, flags: args.slice(1) });
|
|
123
|
+
} else if (d === 'server_name') server.names.push(...args.map((x) => x.toLowerCase()));
|
|
124
|
+
}
|
|
125
|
+
stmt = [];
|
|
126
|
+
}
|
|
127
|
+
if (stack.length) throw new Error(`unbalanced "{" in ${file}`);
|
|
128
|
+
}
|
|
129
|
+
return { files, servers, includes, words };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export function nginxVersion(text) {
|
|
133
|
+
const m = /nginx\/(\d+\.\d+\.\d+)/.exec(String(text));
|
|
134
|
+
return m ? m[1] : null;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// Where site files go: "sites" (sites-available + symlink in sites-enabled) or "confd".
|
|
138
|
+
export function detectLayout(parsed, nginxDir = '/etc/nginx') {
|
|
139
|
+
const abs = (a) => (a.startsWith('/') ? a : posix.join(nginxDir, a));
|
|
140
|
+
const args = parsed.includes.map((i) => abs(i.arg));
|
|
141
|
+
const find = (dirName) => args.map((a) => new RegExp(`^${nginxDir.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&')}/${dirName}/\\*(\\.conf)?$`).exec(a)).find(Boolean);
|
|
142
|
+
let m = find('sites-enabled');
|
|
143
|
+
if (m) {
|
|
144
|
+
const name = SITE_NAME + (m[1] || '');
|
|
145
|
+
return {
|
|
146
|
+
mode: 'sites',
|
|
147
|
+
dir: `${nginxDir}/sites-enabled`,
|
|
148
|
+
enabledFile: `${nginxDir}/sites-enabled/${name}`,
|
|
149
|
+
availableFile: `${nginxDir}/sites-available/${name}`,
|
|
150
|
+
siteFile: `${nginxDir}/sites-enabled/${name}`,
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
m = find('conf\\.d');
|
|
154
|
+
if (m) {
|
|
155
|
+
const name = `${SITE_NAME}.conf`;
|
|
156
|
+
return { mode: 'confd', dir: `${nginxDir}/conf.d`, siteFile: `${nginxDir}/conf.d/${name}`, enabledFile: null, availableFile: null };
|
|
157
|
+
}
|
|
158
|
+
return null;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const listensOn = (l, ip, port) => l.port === port && l.addr === ip.toLowerCase();
|
|
162
|
+
|
|
163
|
+
// nginx server_name → does it match host h? null = cannot tell (regex JS cannot compile).
|
|
164
|
+
export function nameMatches(name, h) {
|
|
165
|
+
if (!name) return false;
|
|
166
|
+
if (name.startsWith('~')) {
|
|
167
|
+
let src = name.slice(1);
|
|
168
|
+
let flags = '';
|
|
169
|
+
if (src.startsWith('(?i)')) { src = src.slice(4); flags = 'i'; }
|
|
170
|
+
try { return new RegExp(src, flags).test(h); } catch { return null; }
|
|
171
|
+
}
|
|
172
|
+
if (name.startsWith('.')) return h === name.slice(1) || h.endsWith(name);
|
|
173
|
+
if (name.startsWith('*.')) return h.endsWith(name.slice(1));
|
|
174
|
+
if (name.endsWith('.*')) return h.startsWith(name.slice(0, -1));
|
|
175
|
+
return h === name;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* opts: listenIp, siteFile (our file, real path), baseDomain, controlLabel, sampleLabel
|
|
180
|
+
* → { listeners, defaultServer, wouldBeFirst (true/false/null=unknown), after: [files], conflicts, unsure,
|
|
181
|
+
* underBase, foreignZones, wildcardOnly, proxyProtocol, realIpFiles }
|
|
182
|
+
*/
|
|
183
|
+
export function analyzeNginx(parsed, { listenIp, siteFile, baseDomain, controlLabel, sampleLabel = 'bgcheck-x1' }) {
|
|
184
|
+
const ours = (f) => f === siteFile;
|
|
185
|
+
const group = parsed.servers.filter((s) => !ours(s.file) && s.listens.some((l) => listensOn(l, listenIp, 443)));
|
|
186
|
+
const defaultServer = group.find((s) => s.listens.some((l) => listensOn(l, listenIp, 443) && (l.flags.includes('default_server') || l.flags.includes('default')))) || null;
|
|
187
|
+
|
|
188
|
+
// Position of our file in load order: files of the same directory load sorted by name.
|
|
189
|
+
const files = parsed.files.filter((f) => !ours(f));
|
|
190
|
+
const dir = posix.dirname(siteFile);
|
|
191
|
+
const base = posix.basename(siteFile);
|
|
192
|
+
const sameDir = files.filter((f) => posix.dirname(f) === dir);
|
|
193
|
+
const after = sameDir.filter((f) => posix.basename(f) > base);
|
|
194
|
+
let insertAt = null; // index in `files` our file loads at; null = cannot tell
|
|
195
|
+
if (parsed.files.includes(siteFile)) insertAt = parsed.files.indexOf(siteFile); // already loaded (nothing before it is ours)
|
|
196
|
+
else if (after.length) insertAt = files.indexOf(after[0]);
|
|
197
|
+
else if (sameDir.length) insertAt = files.indexOf(sameDir.at(-1)) + 1;
|
|
198
|
+
let wouldBeFirst = null;
|
|
199
|
+
if (defaultServer) wouldBeFirst = false;
|
|
200
|
+
else if (insertAt !== null) {
|
|
201
|
+
const before = group.filter((s) => files.indexOf(s.file) < insertAt);
|
|
202
|
+
wouldBeFirst = before.length === 0;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const hosts = [`${controlLabel}.${baseDomain}`, `${sampleLabel}.${baseDomain}`, `a1.${baseDomain}`];
|
|
206
|
+
const conflicts = [];
|
|
207
|
+
const unsure = [];
|
|
208
|
+
const underBase = [];
|
|
209
|
+
for (const s of group) {
|
|
210
|
+
for (const name of s.names) {
|
|
211
|
+
const plainExact = !name.startsWith('~') && !name.includes('*') && !name.startsWith('.');
|
|
212
|
+
for (const h of hosts) {
|
|
213
|
+
const m = nameMatches(name, h);
|
|
214
|
+
if (m === null) { unsure.push({ file: s.file, name }); break; }
|
|
215
|
+
if (m) { conflicts.push({ file: s.file, name, host: h }); break; }
|
|
216
|
+
}
|
|
217
|
+
if (plainExact && name.endsWith(`.${baseDomain}`) && !conflicts.some((c) => c.file === s.file && c.name === name)) {
|
|
218
|
+
underBase.push({ file: s.file, name });
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
const foreignZones = [];
|
|
224
|
+
for (const [file, ws] of parsed.words) {
|
|
225
|
+
if (ours(file)) continue;
|
|
226
|
+
for (const w of ws) if (/(^|[=$])bestgate_/.test(w)) foreignZones.push({ file, token: w });
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const wildcardOnly = parsed.servers.filter((s) => !ours(s.file) && s.listens.some((l) => l.port === 443 && l.addr === '*')).length;
|
|
230
|
+
|
|
231
|
+
// PROXY protocol on our address:port: $remote_addr is then the balancer, unless real-IP
|
|
232
|
+
// takes the client address from the PROXY header ("real_ip_header proxy_protocol").
|
|
233
|
+
const proxyProtocol = group.some((s) => s.listens.some((l) => listensOn(l, listenIp, 443) && l.flags.includes('proxy_protocol')));
|
|
234
|
+
const realIpFiles = [];
|
|
235
|
+
for (const [file, ws] of parsed.words) {
|
|
236
|
+
if (ws.some((w, i) => w === 'real_ip_header' && ws[i + 1] === 'proxy_protocol')) realIpFiles.push(file);
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
return {
|
|
240
|
+
listeners: group, defaultServer, wouldBeFirst, after, conflicts, unsure, underBase, foreignZones, wildcardOnly,
|
|
241
|
+
proxyProtocol, realIpFiles,
|
|
242
|
+
};
|
|
243
|
+
}
|
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
// `bestgate server plan`: read-only checks, safe to run any time. Prints OK/WARN/FAIL
|
|
2
|
+
// lines and what `install` would create or change; exits non-zero on any FAIL.
|
|
3
|
+
import { CliError } from '../util.js';
|
|
4
|
+
import { loadConfig } from './config.js';
|
|
5
|
+
import {
|
|
6
|
+
P, UNITS, DAEMON_USER, MOTD_NAME, SAFE_PATH_RE, MIN_NODE, createContext, openLog, versionAtLeast,
|
|
7
|
+
checkDns, certInfo, certFiles, listeningPorts, isLoopback, unitFileLocations, report, randomLabel, parseFlags, posix,
|
|
8
|
+
} from './sys.js';
|
|
9
|
+
import { parseDump, detectLayout, analyzeNginx, nginxVersion } from './nginx.js';
|
|
10
|
+
import { loadManifest, entryFor } from './manifest.js';
|
|
11
|
+
import { renderAll } from './render.js';
|
|
12
|
+
|
|
13
|
+
export const motdFile = `${P.motdDir}/${MOTD_NAME}`;
|
|
14
|
+
|
|
15
|
+
export function loadServerConfig(ctx, file = P.configFile) {
|
|
16
|
+
return loadConfig(ctx.disk(file));
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// Which process name each of our ports should show in `ss -p`.
|
|
20
|
+
// Process names as ss prints them. Node 24 names its main thread MainThread, so ss shows
|
|
21
|
+
// that for the daemon instead of node.
|
|
22
|
+
const PORT_OWNERS = { control: ['frps'], vhost: ['frps'], dashboard: ['frps'], daemon: ['node', 'MainThread'] };
|
|
23
|
+
const MAX_WALK = 50000;
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* The daily check runs node + this package as root, and the daemon runs them too: anyone
|
|
27
|
+
* who can change one of those files, or a directory above them, runs code as root.
|
|
28
|
+
* → list of problems (empty = node, the package tree and every directory above them are
|
|
29
|
+
* owned by root and not writable by group or others). Symlinks are checked, not followed.
|
|
30
|
+
*/
|
|
31
|
+
export function ownershipProblems(ctx) {
|
|
32
|
+
const problems = [];
|
|
33
|
+
const seen = new Map(); // path -> lstat result (null when it could not be read)
|
|
34
|
+
const check = (p) => {
|
|
35
|
+
if (seen.has(p)) return seen.get(p);
|
|
36
|
+
seen.set(p, null);
|
|
37
|
+
let st;
|
|
38
|
+
try { st = ctx.lstatReal(p); } catch (e) { problems.push(`cannot check ${p}: ${e.code || e.message}`); return null; }
|
|
39
|
+
if (st.uid !== 0) problems.push(`${p} is owned by uid ${st.uid}, not root`);
|
|
40
|
+
else if (!st.isSymbolicLink() && (st.mode & 0o022)) {
|
|
41
|
+
problems.push(`${p} is writable by ${st.mode & 0o020 ? 'its group' : 'others'} (mode ${(st.mode & 0o7777).toString(8)})`);
|
|
42
|
+
}
|
|
43
|
+
seen.set(p, st);
|
|
44
|
+
return st;
|
|
45
|
+
};
|
|
46
|
+
const up = (p) => {
|
|
47
|
+
for (let d = posix.dirname(p); ; d = posix.dirname(d)) {
|
|
48
|
+
check(d);
|
|
49
|
+
if (d === '/') break;
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
const real = (p) => { try { return ctx.realpath(p); } catch (e) { problems.push(`cannot resolve ${p}: ${e.code || e.message}`); return null; } };
|
|
53
|
+
|
|
54
|
+
for (const p of [ctx.nodePath, real(ctx.nodePath)]) if (p) { check(p); up(p); }
|
|
55
|
+
const given = posix.dirname(posix.dirname(ctx.binScript)); // <package>/bin/bestgate.js
|
|
56
|
+
check(ctx.binScript);
|
|
57
|
+
up(ctx.binScript);
|
|
58
|
+
const pkg = real(given);
|
|
59
|
+
if (pkg) {
|
|
60
|
+
up(pkg);
|
|
61
|
+
const stack = [pkg];
|
|
62
|
+
let n = 0;
|
|
63
|
+
while (stack.length) {
|
|
64
|
+
const p = stack.pop();
|
|
65
|
+
if (++n > MAX_WALK) { problems.push(`${pkg} has more than ${MAX_WALK} entries: not checked to the end`); break; }
|
|
66
|
+
const st = check(p);
|
|
67
|
+
if (st && st.isDirectory() && !st.isSymbolicLink()) {
|
|
68
|
+
let names = [];
|
|
69
|
+
try { names = ctx.readdirReal(p); } catch (e) { problems.push(`cannot list ${p}: ${e.code || e.message}`); }
|
|
70
|
+
for (const name of names) stack.push(posix.join(p, name));
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return problems;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* All read-only checks. → { checks: [{level, msg}], facts }
|
|
79
|
+
* facts: nginxVersion, layout, analysis, cert, manifest, userExists
|
|
80
|
+
*/
|
|
81
|
+
export async function collectPlan(ctx, cfg) {
|
|
82
|
+
const checks = [];
|
|
83
|
+
const add = (level, msg) => checks.push({ level, msg });
|
|
84
|
+
const facts = { manifest: null, layout: null, nginxVersion: null, cert: null, userExists: false };
|
|
85
|
+
|
|
86
|
+
if (ctx.uid !== 0) {
|
|
87
|
+
add('FAIL', 'not running as root (sudo bestgate server ...): the checks need to read the nginx configuration');
|
|
88
|
+
return { checks, facts };
|
|
89
|
+
}
|
|
90
|
+
add('OK', 'running as root');
|
|
91
|
+
try {
|
|
92
|
+
facts.manifest = loadManifest(ctx);
|
|
93
|
+
} catch (e) {
|
|
94
|
+
add('FAIL', e.message);
|
|
95
|
+
return { checks, facts };
|
|
96
|
+
}
|
|
97
|
+
add('OK', facts.manifest ? `bestgate is installed here (manifest ${P.manifestFile}); install would update it in place` : 'no earlier bestgate install found');
|
|
98
|
+
|
|
99
|
+
if (versionAtLeast(ctx.nodeVersion, MIN_NODE)) add('OK', `Node.js ${ctx.nodeVersion} (>= ${MIN_NODE})`);
|
|
100
|
+
else add('FAIL', `Node.js ${ctx.nodeVersion} is too old: the server side needs >= ${MIN_NODE} (install Node 24 LTS)`);
|
|
101
|
+
for (const [what, p] of [['node', ctx.nodePath], ['bestgate script', ctx.binScript]]) {
|
|
102
|
+
if (!SAFE_PATH_RE.test(p)) add('FAIL', `${what} path ${JSON.stringify(p)} has characters a systemd unit cannot take safely`);
|
|
103
|
+
else if (/^\/(home|root|tmp|var\/tmp|run\/user)\//.test(p)) add('FAIL', `${what} is at ${p}: the hardened units cannot see home or temp directories (install Node and bestgate system-wide)`);
|
|
104
|
+
}
|
|
105
|
+
if (!ctx.posixModes) add('WARN', 'cannot check file ownership on this platform (node and the bestgate package must be root-owned)');
|
|
106
|
+
else {
|
|
107
|
+
const own = ownershipProblems(ctx);
|
|
108
|
+
if (!own.length) add('OK', 'node and the bestgate package are owned by root and not writable by others');
|
|
109
|
+
else {
|
|
110
|
+
add('FAIL', `the daily check runs node and the bestgate package as root, so they must be root's alone (reinstall them as root, e.g. sudo npm i -g):\n ` +
|
|
111
|
+
own.slice(0, 10).join('\n ') + (own.length > 10 ? `\n ... and ${own.length - 10} more` : ''));
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const missing = ['nginx', 'systemctl', 'ss', 'useradd', 'getent', 'chown'].filter((t) => !ctx.which(t));
|
|
116
|
+
if (missing.length) {
|
|
117
|
+
add('FAIL', `missing commands: ${missing.join(', ')}`);
|
|
118
|
+
return { checks, facts };
|
|
119
|
+
}
|
|
120
|
+
add('OK', 'nginx, systemctl, ss, useradd, getent present');
|
|
121
|
+
if (ctx.which('certbot')) add('OK', 'certbot present');
|
|
122
|
+
else add('WARN', 'certbot not found: `bestgate server cert` needs it');
|
|
123
|
+
|
|
124
|
+
// nginx
|
|
125
|
+
const v = ctx.run('nginx', ['-v']);
|
|
126
|
+
facts.nginxVersion = nginxVersion(v.stderr + v.stdout);
|
|
127
|
+
add(facts.nginxVersion ? 'OK' : 'WARN', `nginx version ${facts.nginxVersion || 'unknown'}` +
|
|
128
|
+
(facts.nginxVersion && versionAtLeast(facts.nginxVersion, '1.25.1') ? ' (per-server "http2 on;")' : ' (http2 left to the listen socket)'));
|
|
129
|
+
if (facts.nginxVersion && !versionAtLeast(facts.nginxVersion, '1.15.7')) {
|
|
130
|
+
add('FAIL', `nginx ${facts.nginxVersion} is too old: the request limit uses "limit_req ... delay=", which needs 1.15.7 or newer`);
|
|
131
|
+
}
|
|
132
|
+
const dump = ctx.run('nginx', ['-T']);
|
|
133
|
+
if (dump.code !== 0) {
|
|
134
|
+
add('FAIL', `nginx -t fails right now, fix that first:\n${(dump.stderr || '').trim().split('\n').slice(-5).join('\n')}`);
|
|
135
|
+
return { checks, facts };
|
|
136
|
+
}
|
|
137
|
+
add('OK', 'nginx configuration is valid now (nginx -T)');
|
|
138
|
+
let parsed;
|
|
139
|
+
try {
|
|
140
|
+
parsed = parseDump(dump.stdout);
|
|
141
|
+
} catch (e) {
|
|
142
|
+
add('FAIL', `cannot read the nginx -T output: ${e.message}`);
|
|
143
|
+
return { checks, facts };
|
|
144
|
+
}
|
|
145
|
+
facts.layout = detectLayout(parsed, P.nginxDir);
|
|
146
|
+
if (!facts.layout) {
|
|
147
|
+
add('FAIL', `nginx includes neither ${P.nginxDir}/sites-enabled/* nor ${P.nginxDir}/conf.d/*.conf at http level`);
|
|
148
|
+
return { checks, facts };
|
|
149
|
+
}
|
|
150
|
+
add('OK', `site layout: ${facts.layout.mode === 'sites' ? `${facts.layout.availableFile} + link in sites-enabled` : facts.layout.siteFile}`);
|
|
151
|
+
|
|
152
|
+
if (!cfg.listenIp) {
|
|
153
|
+
add('FAIL', 'listenIp is empty: set it to the address nginx listens on for 443 (e.g. "listen 192.0.2.10:443 ssl")');
|
|
154
|
+
return { checks, facts };
|
|
155
|
+
}
|
|
156
|
+
const a = analyzeNginx(parsed, {
|
|
157
|
+
listenIp: cfg.listenIp, siteFile: facts.layout.siteFile, baseDomain: cfg.baseDomain,
|
|
158
|
+
controlLabel: cfg.controlLabel, sampleLabel: randomLabel(),
|
|
159
|
+
});
|
|
160
|
+
facts.analysis = a;
|
|
161
|
+
if (!a.listeners.length) {
|
|
162
|
+
add('FAIL', `no nginx server listens on ${cfg.listenIp}:443 now. A first server on a new address would ` +
|
|
163
|
+
`take that address over for all sites: use the address the other sites listen on`);
|
|
164
|
+
} else add('OK', `${a.listeners.length} nginx servers already listen on ${cfg.listenIp}:443`);
|
|
165
|
+
if (a.defaultServer) add('OK', `default_server on ${cfg.listenIp}:443 is in ${a.defaultServer.file}; our names are explicit, so it does not capture them`);
|
|
166
|
+
if (a.wouldBeFirst === true) add('FAIL', `${facts.layout.siteFile} would be the first server on ${cfg.listenIp}:443 and so the default for unknown names`);
|
|
167
|
+
else if (a.wouldBeFirst === null) add('FAIL', `cannot tell where ${facts.layout.siteFile} would load among the other servers`);
|
|
168
|
+
else add('OK', `${facts.layout.siteFile} is not the first server on ${cfg.listenIp}:443 (unknown names keep their current default)`);
|
|
169
|
+
if (a.after.length) add('WARN', `loads after ${facts.layout.siteFile}: ${a.after.join(', ')} (fine if those are meant to be last)`);
|
|
170
|
+
else add('OK', `${facts.layout.siteFile} sorts last among the enabled sites`);
|
|
171
|
+
if (a.proxyProtocol && !a.realIpFiles.length) {
|
|
172
|
+
add('FAIL', `servers on ${cfg.listenIp}:443 accept the PROXY protocol, so nginx sees every visitor as the balancer's address ` +
|
|
173
|
+
'and the per-IP limits (bestgate_req, bestgate_conn, bestgate_login) would be one limit shared by everybody. ' +
|
|
174
|
+
'Configure set_real_ip_from <balancer> and real_ip_header proxy_protocol at http level first.');
|
|
175
|
+
} else if (a.proxyProtocol) {
|
|
176
|
+
add('WARN', `servers on ${cfg.listenIp}:443 accept the PROXY protocol; real_ip_header proxy_protocol is set in ${a.realIpFiles.join(', ')}: ` +
|
|
177
|
+
'make sure it is at http level, or the per-IP limits apply to the balancer\'s address');
|
|
178
|
+
}
|
|
179
|
+
for (const c of a.conflicts) add('FAIL', `${c.file}: server_name ${c.name} matches ${c.host} and would capture tunnel traffic`);
|
|
180
|
+
for (const u of a.unsure) add('WARN', `${u.file}: cannot evaluate regex server_name ${u.name}; check by hand that it cannot match *.${cfg.baseDomain}`);
|
|
181
|
+
for (const u of a.underBase) add('WARN', `${u.file}: ${u.name} is under the tunnel domain; that name keeps going to its own site`);
|
|
182
|
+
if (!a.conflicts.length) add('OK', `no existing server name on ${cfg.listenIp}:443 matches ${cfg.controlLabel}.${cfg.baseDomain} or <name>.${cfg.baseDomain}`);
|
|
183
|
+
if (a.foreignZones.length) for (const z of a.foreignZones) add('FAIL', `${z.file} already defines ${z.token}: the bestgate_ names must be ours alone`);
|
|
184
|
+
else add('OK', 'no bestgate_* map or zone defined elsewhere');
|
|
185
|
+
|
|
186
|
+
// Ports
|
|
187
|
+
let listening = [];
|
|
188
|
+
try { listening = listeningPorts(ctx); } catch (e) { add('FAIL', e.message); }
|
|
189
|
+
const frpsOurs = !!entryFor(facts.manifest, `${P.systemdDir}/${UNITS.frps}`);
|
|
190
|
+
for (const [k, port] of Object.entries(cfg.ports)) {
|
|
191
|
+
const l = listening.filter((x) => x.port === port);
|
|
192
|
+
if (port >= 1024) add('FAIL', `port ${port} (${k}) is not privileged: any local user could bind it while frps or the daemon restarts; use 1-1023`);
|
|
193
|
+
else if (!l.length) add('OK', `port ${port} (${k}) is free`);
|
|
194
|
+
else if (frpsOurs && l.every((x) => PORT_OWNERS[k].includes(x.process) && isLoopback(x.addr))) add('OK', `port ${port} (${k}) is used by our ${PORT_OWNERS[k][0]}`);
|
|
195
|
+
else add('FAIL', `port ${port} (${k}) is already used by ${l.map((x) => `${x.process || '?'} on ${x.addr}`).join(', ')}`);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// Our ports are safe only while unprivileged users cannot bind them.
|
|
199
|
+
const maxPort = Math.max(...Object.values(cfg.ports));
|
|
200
|
+
const raw = ctx.readOrNull(P.unprivPortSysctl); // missing: a kernel before 4.11, where it is fixed at 1024
|
|
201
|
+
const start = raw === null ? 1024 : /^\s*\d+\s*$/.test(raw) ? parseInt(raw, 10) : NaN;
|
|
202
|
+
if (!Number.isInteger(start)) add('FAIL', `cannot read ${P.unprivPortSysctl}`);
|
|
203
|
+
else if (start <= maxPort) {
|
|
204
|
+
add('FAIL', `net.ipv4.ip_unprivileged_port_start is ${start}: any local user may bind ports from ${start} up, ` +
|
|
205
|
+
`including ours (up to ${maxPort}). Set it back to 1024 (sysctl -w net.ipv4.ip_unprivileged_port_start=1024, and in /etc/sysctl.d) ` +
|
|
206
|
+
`or choose ports below ${start}`);
|
|
207
|
+
} else add('OK', `net.ipv4.ip_unprivileged_port_start is ${start}: only root can bind our ports`);
|
|
208
|
+
|
|
209
|
+
// Names that must be ours or free
|
|
210
|
+
for (const u of Object.values(UNITS)) {
|
|
211
|
+
const locs = unitFileLocations(ctx, u).filter((f) => !entryFor(facts.manifest, f));
|
|
212
|
+
if (locs.length) add('FAIL', `a unit named ${u} already exists (${locs.join(', ')}) and is not ours`);
|
|
213
|
+
}
|
|
214
|
+
const files = [P.frpsBin, motdFile, facts.layout.siteFile, facts.layout.availableFile].filter(Boolean);
|
|
215
|
+
for (const f of files) {
|
|
216
|
+
if (ctx.exists(f) && !entryFor(facts.manifest, f)) add('FAIL', `${f} already exists and is not ours`);
|
|
217
|
+
}
|
|
218
|
+
if (!ctx.exists(P.motdDir)) add('WARN', `${P.motdDir} does not exist: no login message for failed daily checks`);
|
|
219
|
+
const pw = ctx.run('getent', ['passwd', DAEMON_USER]);
|
|
220
|
+
if (pw.code === 0) {
|
|
221
|
+
facts.userExists = true;
|
|
222
|
+
const f = pw.stdout.trim().split(':');
|
|
223
|
+
const uid = parseInt(f[2], 10);
|
|
224
|
+
if (entryFor(facts.manifest, DAEMON_USER)) add('OK', `system user ${DAEMON_USER} exists (ours)`);
|
|
225
|
+
else if (uid < 1000 && /(nologin|false)$/.test(f[6] || '')) add('WARN', `system user ${DAEMON_USER} already exists (uid ${uid}, no login); it will be used for the daemon`);
|
|
226
|
+
else add('FAIL', `user ${DAEMON_USER} already exists (uid ${uid}) and is not a no-login system user`);
|
|
227
|
+
} else add('OK', `system user ${DAEMON_USER} will be created`);
|
|
228
|
+
|
|
229
|
+
// DNS
|
|
230
|
+
for (const d of await checkDns(ctx, cfg)) {
|
|
231
|
+
if (d.ok) add('OK', `DNS: ${d.name} → ${cfg.publicIp}`);
|
|
232
|
+
else add('FAIL', `DNS: ${d.name} → ${d.addresses.join(', ') || 'nothing'}, expected ${cfg.publicIp} (add *.${cfg.baseDomain} pointing to this server)`);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// Certificate
|
|
236
|
+
facts.cert = certInfo(ctx, cfg);
|
|
237
|
+
const c = facts.cert;
|
|
238
|
+
if (!c.present) add('WARN', `no certificate at ${c.file} yet: run \`bestgate server cert\` (install refuses until then)`);
|
|
239
|
+
else if (c.error) add('FAIL', `${c.file}: ${c.error}`);
|
|
240
|
+
else if (!c.coversWildcard) add('FAIL', `${c.file} does not cover *.${cfg.baseDomain}`);
|
|
241
|
+
else if (c.daysLeft < 0) add('FAIL', `certificate expired on ${c.validTo}: run \`bestgate server cert\``);
|
|
242
|
+
else if (c.daysLeft < 14) add('WARN', `certificate for *.${cfg.baseDomain} expires in ${c.daysLeft} days: run \`bestgate server cert\``);
|
|
243
|
+
else add('OK', `certificate for *.${cfg.baseDomain}, ${c.daysLeft} days left`);
|
|
244
|
+
const renewal = ctx.readOrNull(certFiles(cfg.baseDomain).renewal);
|
|
245
|
+
if (renewal !== null && !/^\s*autorenew\s*=\s*False\s*$/m.test(renewal)) {
|
|
246
|
+
add('WARN', `${certFiles(cfg.baseDomain).renewal} does not say autorenew = False: certbot renew would try (and fail) the manual lineage`);
|
|
247
|
+
}
|
|
248
|
+
return { checks, facts };
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* The files install manages, in the order it writes them.
|
|
253
|
+
* → [{ path, kind: 'dir'|'file'|'link'|'bin'|'secret', mode, owner, content?, target?, keep? }]
|
|
254
|
+
*/
|
|
255
|
+
export function buildTargets(ctx, cfg, facts) {
|
|
256
|
+
const r = renderAll(cfg, { nginxVersion: facts.nginxVersion, nodePath: ctx.nodePath, binScript: ctx.binScript });
|
|
257
|
+
const t = [
|
|
258
|
+
{ path: P.frpsToml, kind: 'file', mode: 0o644, content: r['frps.toml'] },
|
|
259
|
+
{ path: `${P.systemdDir}/${UNITS.auth}`, kind: 'file', mode: 0o644, content: r['bestgate-auth.service'] },
|
|
260
|
+
{ path: `${P.systemdDir}/${UNITS.frps}`, kind: 'file', mode: 0o644, content: r['frps.service'] },
|
|
261
|
+
{ path: `${P.systemdDir}/${UNITS.check}`, kind: 'file', mode: 0o644, content: r['bestgate-check.service'] },
|
|
262
|
+
{ path: `${P.systemdDir}/${UNITS.timer}`, kind: 'file', mode: 0o644, content: r['bestgate-check.timer'] },
|
|
263
|
+
];
|
|
264
|
+
if (ctx.exists(P.motdDir)) t.push({ path: motdFile, kind: 'file', mode: 0o755, content: r['motd.sh'] });
|
|
265
|
+
const nginx = r['nginx.conf.template'];
|
|
266
|
+
const L = facts.layout;
|
|
267
|
+
if (L.mode === 'sites') t.push({ path: L.availableFile, kind: 'file', mode: 0o644, content: nginx, nginx: true }, { path: L.enabledFile, kind: 'link', target: L.availableFile, nginx: true });
|
|
268
|
+
else t.push({ path: L.siteFile, kind: 'file', mode: 0o644, content: nginx, nginx: true });
|
|
269
|
+
return t;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
export function describeInstall(ctx, cfg, facts) {
|
|
273
|
+
const lines = [];
|
|
274
|
+
if (!facts.layout) return lines;
|
|
275
|
+
let targets;
|
|
276
|
+
try { targets = buildTargets(ctx, cfg, facts); } catch (e) { return [`(cannot render the files: ${e.message})`]; }
|
|
277
|
+
const state = (x) => {
|
|
278
|
+
if (x.kind === 'link') return ctx.exists(x.path) ? 'present' : 'create';
|
|
279
|
+
const cur = ctx.readOrNull(x.path);
|
|
280
|
+
return cur === null ? 'create' : cur === x.content ? 'unchanged' : 'update';
|
|
281
|
+
};
|
|
282
|
+
if (!facts.userExists) lines.push(`create system user ${DAEMON_USER} (no login, no home)`);
|
|
283
|
+
lines.push(`directories ${P.etcDir}, ${P.stateDir} (root:${DAEMON_USER} 1770), ${P.origDir}, ${P.logDir}, ${P.cacheDir}`);
|
|
284
|
+
lines.push(ctx.exists(P.envFile) ? `${P.envFile}: present, kept as is (a missing plugin secret is added)` : `${P.envFile}: generate the frps token, dashboard password and plugin secret (root 0600, never shown)`);
|
|
285
|
+
lines.push(`${P.daemonEnvFile}: dashboard password and plugin secret, for the daemon (root 0600)`);
|
|
286
|
+
lines.push(`${P.frpsBin}: frps from the pinned frp release (sha256 checked)`);
|
|
287
|
+
for (const x of targets) lines.push(`${x.path}: ${state(x)}`);
|
|
288
|
+
lines.push(`systemctl daemon-reload; enable and (re)start ${UNITS.auth}, ${UNITS.frps}, ${UNITS.timer}`);
|
|
289
|
+
lines.push('nginx -t, then systemctl reload nginx (rolled back if nginx -t fails or a check URL changes)');
|
|
290
|
+
return lines;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// `bestgate server plan [--config <file>]`
|
|
294
|
+
export async function run(argv = [], opts = {}) {
|
|
295
|
+
const flags = parseFlags(argv, { '--config': 'value' });
|
|
296
|
+
const ctx = opts.ctx || createContext();
|
|
297
|
+
const configFile = flags.config || P.configFile;
|
|
298
|
+
if (!ctx.exists(configFile) && !flags.config) {
|
|
299
|
+
throw new CliError(`No config at ${configFile} yet: run \`sudo bestgate server install\` (it asks the questions first).`);
|
|
300
|
+
}
|
|
301
|
+
const cfg = flags.config ? loadConfig(flags.config) : loadServerConfig(ctx);
|
|
302
|
+
openLog(ctx, 'plan');
|
|
303
|
+
ctx.say(`bestgate server plan: ${cfg.baseDomain} (control ${cfg.controlLabel}.${cfg.baseDomain}, nginx ${cfg.listenIp || '?'}:443)`);
|
|
304
|
+
const { checks, facts } = await collectPlan(ctx, cfg);
|
|
305
|
+
const { fail, warn } = report(ctx, checks);
|
|
306
|
+
const lines = describeInstall(ctx, cfg, facts);
|
|
307
|
+
if (lines.length) {
|
|
308
|
+
ctx.say('');
|
|
309
|
+
ctx.say('install would:');
|
|
310
|
+
for (const l of lines) ctx.say(` - ${l}`);
|
|
311
|
+
}
|
|
312
|
+
ctx.say('');
|
|
313
|
+
ctx.say(`RESULT: ${fail ? 'FAIL' : 'OK'} (${fail} fail, ${warn} warn)`);
|
|
314
|
+
if (fail) throw new CliError(`plan: ${fail} check(s) failed, see FAIL above`);
|
|
315
|
+
return { checks, facts, fail, warn };
|
|
316
|
+
}
|