@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,515 @@
|
|
|
1
|
+
// Shared helpers for the server modes (plan / install / cert / verify / revert / check / status).
|
|
2
|
+
// Everything that touches the system goes through a context object, so tests can
|
|
3
|
+
// run the modes against a temp directory with a fake command runner:
|
|
4
|
+
// - paths in the code are the real Ubuntu paths ("canonical"); ctx.disk(p) maps
|
|
5
|
+
// them under ctx.root (BESTGATE_ROOT) for every file operation;
|
|
6
|
+
// - every external command runs through ctx.run (read-only) or ctx.change
|
|
7
|
+
// (changes the system; printed instead of run with --dry-run), always with an
|
|
8
|
+
// argument array and never through a shell.
|
|
9
|
+
import { spawnSync } from 'node:child_process';
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
import http from 'node:http';
|
|
13
|
+
import https from 'node:https';
|
|
14
|
+
import { isIPv6 } from 'node:net';
|
|
15
|
+
import { X509Certificate, randomBytes } from 'node:crypto';
|
|
16
|
+
import { Resolver } from 'node:dns/promises';
|
|
17
|
+
import { fileURLToPath } from 'node:url';
|
|
18
|
+
import { CliError } from '../util.js';
|
|
19
|
+
|
|
20
|
+
const posix = path.posix;
|
|
21
|
+
|
|
22
|
+
export const DAEMON_USER = 'bestgate';
|
|
23
|
+
export const SITE_NAME = 'zy-bestgate'; // sorts after ordinary site names, before "zz-" ones
|
|
24
|
+
export const MOTD_NAME = '97-bestgate';
|
|
25
|
+
export const UNITS = Object.freeze({
|
|
26
|
+
auth: 'bestgate-auth.service',
|
|
27
|
+
frps: 'frps.service',
|
|
28
|
+
check: 'bestgate-check.service',
|
|
29
|
+
timer: 'bestgate-check.timer',
|
|
30
|
+
});
|
|
31
|
+
export const MIN_NODE = '22.13.0';
|
|
32
|
+
|
|
33
|
+
// Real paths on the server. Kept in line with PATHS in config.js (which adds BESTGATE_ROOT).
|
|
34
|
+
export const P = Object.freeze({
|
|
35
|
+
etcDir: '/etc/bestgate',
|
|
36
|
+
configFile: '/etc/bestgate/config.json',
|
|
37
|
+
// root 0600: FRP_AUTH_TOKEN + FRP_DASHBOARD_PASSWORD + BESTGATE_PLUGIN_SECRET, for frps and `server user add`
|
|
38
|
+
envFile: '/etc/bestgate/frps.env',
|
|
39
|
+
daemonEnvFile: '/etc/bestgate/daemon.env', // root 0600: FRP_DASHBOARD_PASSWORD + BESTGATE_PLUGIN_SECRET, for the daemon
|
|
40
|
+
frpsToml: '/etc/bestgate/frps.toml',
|
|
41
|
+
stateDir: '/var/lib/bestgate', // root:bestgate 1770 (sticky): the daemon's database lives here
|
|
42
|
+
dbFile: '/var/lib/bestgate/bestgate.db',
|
|
43
|
+
// root 0700: manifest + saved originals. Not inside stateDir: root never works in a
|
|
44
|
+
// directory the daemon user can write.
|
|
45
|
+
origDir: '/var/lib/bestgate-orig',
|
|
46
|
+
manifestFile: '/var/lib/bestgate-orig/manifest.json',
|
|
47
|
+
logDir: '/var/log/bestgate', // root 0750
|
|
48
|
+
checkFile: '/var/log/bestgate/check.txt', // written by `server check`, printed by the motd snippet
|
|
49
|
+
cacheDir: '/var/cache/bestgate', // root 0700: frp download cache (never writable by the daemon)
|
|
50
|
+
systemdDir: '/etc/systemd/system',
|
|
51
|
+
nginxDir: '/etc/nginx',
|
|
52
|
+
nginxLogDir: '/var/log/nginx',
|
|
53
|
+
frpsBin: '/usr/local/bin/frps',
|
|
54
|
+
motdDir: '/etc/update-motd.d',
|
|
55
|
+
letsencryptDir: '/etc/letsencrypt',
|
|
56
|
+
unprivPortSysctl: '/proc/sys/net/ipv4/ip_unprivileged_port_start',
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
export const SAFE_PATH_RE = /^\/(?!.*\/\.\.?(\/|$))[A-Za-z0-9._@+/-]+$/;
|
|
60
|
+
|
|
61
|
+
export function certFiles(baseDomain) {
|
|
62
|
+
const dir = `${P.letsencryptDir}/live/${baseDomain}`;
|
|
63
|
+
return { dir, fullchain: `${dir}/fullchain.pem`, privkey: `${dir}/privkey.pem`, renewal: `${P.letsencryptDir}/renewal/${baseDomain}.conf` };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// ---- commands ----
|
|
67
|
+
|
|
68
|
+
function realExec(cmd, args, opts = {}) {
|
|
69
|
+
const r = spawnSync(cmd, args, {
|
|
70
|
+
input: opts.input,
|
|
71
|
+
env: opts.env ? { ...process.env, ...opts.env } : process.env,
|
|
72
|
+
encoding: 'utf8',
|
|
73
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
74
|
+
timeout: opts.timeoutMs || 120000,
|
|
75
|
+
stdio: opts.inherit ? 'inherit' : 'pipe',
|
|
76
|
+
});
|
|
77
|
+
if (r.error) return { code: r.error.code === 'ENOENT' ? 127 : 1, stdout: '', stderr: r.error.message };
|
|
78
|
+
return { code: r.status === null ? 1 : r.status, stdout: r.stdout || '', stderr: r.stderr || '' };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function showCommand(cmd, args) {
|
|
82
|
+
return [cmd, ...args].map((a) => (/^[A-Za-z0-9_./:=@%+,-]+$/.test(a) ? a : `'${String(a).replace(/'/g, "'\\''")}'`)).join(' ');
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function lastLines(s, n = 15) {
|
|
86
|
+
return String(s || '').trim().split('\n').slice(-n).join('\n');
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// ---- network probes ----
|
|
90
|
+
|
|
91
|
+
// HTTP(S) request to `url` but connected to `address` (like curl --resolve): SNI and
|
|
92
|
+
// Host stay the URL's host name. Never follows redirects. Never throws.
|
|
93
|
+
export function realProbe({ url, address, verifyTls = false, timeoutMs = 10000, maxBody = 65536, headers = {}, method = 'GET', body }) {
|
|
94
|
+
return new Promise((resolve) => {
|
|
95
|
+
let u;
|
|
96
|
+
try { u = new URL(url); } catch { resolve({ error: 'bad url' }); return; }
|
|
97
|
+
const mod = u.protocol === 'https:' ? https : http;
|
|
98
|
+
const family = isIPv6(address) ? 6 : 4;
|
|
99
|
+
const lookup = (h, o, cb) => (o && o.all ? cb(null, [{ address, family }]) : cb(null, address, family));
|
|
100
|
+
const h = { 'user-agent': 'bestgate-check', ...headers };
|
|
101
|
+
if (body !== undefined) { h['content-type'] = 'application/json'; h['content-length'] = Buffer.byteLength(body); }
|
|
102
|
+
const req = mod.request(u, {
|
|
103
|
+
method, agent: false, lookup, rejectUnauthorized: verifyTls, timeout: timeoutMs, headers: h,
|
|
104
|
+
}, (res) => {
|
|
105
|
+
let cert = null;
|
|
106
|
+
if (res.socket && typeof res.socket.getPeerCertificate === 'function') {
|
|
107
|
+
const c = res.socket.getPeerCertificate();
|
|
108
|
+
if (c && c.valid_to) cert = { san: c.subjectaltname || '', validTo: c.valid_to };
|
|
109
|
+
}
|
|
110
|
+
const chunks = [];
|
|
111
|
+
let size = 0;
|
|
112
|
+
res.on('data', (d) => { if (size < maxBody) { chunks.push(d); size += d.length; } });
|
|
113
|
+
res.on('end', () => resolve({ status: res.statusCode, body: Buffer.concat(chunks).toString('utf8'), cert }));
|
|
114
|
+
res.on('error', (e) => resolve({ status: res.statusCode, error: e.code || e.message, cert }));
|
|
115
|
+
});
|
|
116
|
+
req.on('timeout', () => req.destroy(new Error('timeout')));
|
|
117
|
+
req.on('error', (e) => resolve({ error: e.code || e.message }));
|
|
118
|
+
req.end(body);
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async function realResolve(name) {
|
|
123
|
+
const r = new Resolver({ timeout: 5000, tries: 2 });
|
|
124
|
+
const out = [];
|
|
125
|
+
for (const fn of ['resolve4', 'resolve6']) {
|
|
126
|
+
try { out.push(...(await r[fn](name))); } catch { /* no records of that type */ }
|
|
127
|
+
}
|
|
128
|
+
return out;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
async function realResolveNs(name) {
|
|
132
|
+
try { return await new Resolver({ timeout: 5000, tries: 2 }).resolveNs(name); } catch { return []; }
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function findInPath(name, envPath = process.env.PATH || '') {
|
|
136
|
+
const dirs = [...envPath.split(path.delimiter), '/usr/sbin', '/usr/bin', '/sbin', '/bin', '/snap/bin'];
|
|
137
|
+
for (const d of dirs) {
|
|
138
|
+
if (!d) continue;
|
|
139
|
+
const f = path.join(d, name);
|
|
140
|
+
try { if (fs.statSync(f).isFile()) return f; } catch { /* next */ }
|
|
141
|
+
}
|
|
142
|
+
return null;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const realLinks = {
|
|
146
|
+
symlink: (target, p) => fs.symlinkSync(target, p),
|
|
147
|
+
readlink: (p) => fs.readlinkSync(p),
|
|
148
|
+
isLink: (p) => { try { return fs.lstatSync(p).isSymbolicLink(); } catch { return false; } },
|
|
149
|
+
};
|
|
150
|
+
|
|
151
|
+
// ---- context ----
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Options (all optional; tests override most of them):
|
|
155
|
+
* root, dryRun, exec(cmd,args,opts)->{code,stdout,stderr}, uid, nodeVersion, nodePath, binScript,
|
|
156
|
+
* resolve(name)->[addr], resolveNs(name)->[ns], probe(opts)->{status,body,cert,error},
|
|
157
|
+
* ensureFrp(binary, opts)->path, now()->ms, out(line), wait(ms), which(name)->path|null,
|
|
158
|
+
* links {symlink, readlink, isLink}, chownSupported (false on Windows), isTTY, confirm(message)->bool
|
|
159
|
+
*/
|
|
160
|
+
export function createContext(o = {}) {
|
|
161
|
+
const root = o.root ?? (process.env.BESTGATE_ROOT || '');
|
|
162
|
+
const ctx = {
|
|
163
|
+
root,
|
|
164
|
+
dryRun: !!o.dryRun,
|
|
165
|
+
exec: o.exec || realExec,
|
|
166
|
+
uid: o.uid ?? (typeof process.getuid === 'function' ? process.getuid() : -1),
|
|
167
|
+
nodeVersion: o.nodeVersion || process.versions.node,
|
|
168
|
+
nodePath: o.nodePath || process.execPath,
|
|
169
|
+
binScript: o.binScript || fileURLToPath(new URL('../../bin/bestgate.js', import.meta.url)),
|
|
170
|
+
resolve: o.resolve || realResolve,
|
|
171
|
+
resolveNs: o.resolveNs || realResolveNs,
|
|
172
|
+
probe: o.probe || realProbe,
|
|
173
|
+
ensureFrp: o.ensureFrp || (async (b, opts) => (await import('../frp.js')).ensureFrp(b, opts)),
|
|
174
|
+
now: o.now || Date.now,
|
|
175
|
+
out: o.out || ((line) => process.stdout.write(line + '\n')),
|
|
176
|
+
wait: o.wait || ((ms) => new Promise((r) => setTimeout(r, ms))),
|
|
177
|
+
which: o.which || ((name) => findInPath(name)),
|
|
178
|
+
links: o.links || realLinks,
|
|
179
|
+
isTTY: o.isTTY ?? !!(process.stdin.isTTY && process.stdout.isTTY),
|
|
180
|
+
confirm: o.confirm || null,
|
|
181
|
+
posixModes: o.posixModes ?? process.platform !== 'win32',
|
|
182
|
+
// lstat/realpath of real paths (never under root): node and the package itself.
|
|
183
|
+
lstatReal: o.lstatReal || ((p) => fs.lstatSync(p)),
|
|
184
|
+
realpath: o.realpath || ((p) => fs.realpathSync(p)),
|
|
185
|
+
readdirReal: o.readdirReal || ((p) => fs.readdirSync(p)),
|
|
186
|
+
dryDirs: new Set(),
|
|
187
|
+
journal: [], // every change, in order: {op, path|cmd, ...}
|
|
188
|
+
logFile: null,
|
|
189
|
+
};
|
|
190
|
+
|
|
191
|
+
ctx.disk = (p) => (root ? path.join(root, p) : p);
|
|
192
|
+
ctx.exists = (p) => { try { fs.lstatSync(ctx.disk(p)); return true; } catch { return false; } };
|
|
193
|
+
ctx.isLink = (p) => ctx.links.isLink(ctx.disk(p));
|
|
194
|
+
ctx.read = (p) => fs.readFileSync(ctx.disk(p), 'utf8');
|
|
195
|
+
ctx.readOrNull = (p) => { try { return fs.readFileSync(ctx.disk(p), 'utf8'); } catch { return null; } };
|
|
196
|
+
ctx.list = (p) => { try { return fs.readdirSync(ctx.disk(p)).sort(); } catch { return null; } };
|
|
197
|
+
|
|
198
|
+
ctx.say = (line = '') => {
|
|
199
|
+
ctx.out(line);
|
|
200
|
+
if (ctx.logFile) {
|
|
201
|
+
try { fs.appendFileSync(ctx.logFile, line + '\n', { mode: 0o640 }); } catch { /* logging never breaks a run */ }
|
|
202
|
+
}
|
|
203
|
+
};
|
|
204
|
+
|
|
205
|
+
// Read-only command: always runs, also with --dry-run.
|
|
206
|
+
ctx.run = (cmd, args, opts = {}) => {
|
|
207
|
+
const r = ctx.exec(cmd, args, opts);
|
|
208
|
+
if (r.code !== 0 && opts.must) {
|
|
209
|
+
throw new CliError(`${showCommand(cmd, args)} failed (exit ${r.code}):\n${lastLines(r.stderr || r.stdout)}`);
|
|
210
|
+
}
|
|
211
|
+
return r;
|
|
212
|
+
};
|
|
213
|
+
|
|
214
|
+
// Command that changes the system. Throws on a non-zero exit unless opts.allowFail.
|
|
215
|
+
ctx.change = (cmd, args, opts = {}) => {
|
|
216
|
+
ctx.journal.push({ op: 'exec', cmd, args });
|
|
217
|
+
if (ctx.dryRun) {
|
|
218
|
+
ctx.say(` would run: ${showCommand(cmd, args)}`);
|
|
219
|
+
return { code: 0, stdout: '', stderr: '' };
|
|
220
|
+
}
|
|
221
|
+
ctx.say(` $ ${showCommand(cmd, args)}`);
|
|
222
|
+
const r = ctx.exec(cmd, args, opts);
|
|
223
|
+
if (r.code !== 0 && !opts.allowFail) {
|
|
224
|
+
throw new CliError(`${showCommand(cmd, args)} failed (exit ${r.code}):\n${lastLines(r.stderr || r.stdout)}`);
|
|
225
|
+
}
|
|
226
|
+
return r;
|
|
227
|
+
};
|
|
228
|
+
|
|
229
|
+
// Write a file atomically with an exact mode and owner. Returns true if anything changed.
|
|
230
|
+
// opts: mode, owner ('root:root' default), secret (never print the content), show (print content on dry run).
|
|
231
|
+
ctx.writeFile = (p, content, opts = {}) => {
|
|
232
|
+
const mode = opts.mode ?? 0o644;
|
|
233
|
+
const owner = opts.owner || 'root:root';
|
|
234
|
+
const d = ctx.disk(p);
|
|
235
|
+
let same = false;
|
|
236
|
+
try {
|
|
237
|
+
const st = fs.lstatSync(d);
|
|
238
|
+
same = st.isFile() && fs.readFileSync(d, 'utf8') === content && (!ctx.posixModes || (st.mode & 0o7777) === mode);
|
|
239
|
+
} catch { /* new file */ }
|
|
240
|
+
if (same && !opts.forceOwner) return false;
|
|
241
|
+
ctx.journal.push({ op: 'write', path: p, mode, owner });
|
|
242
|
+
const head = ` ${ctx.dryRun ? 'would write' : 'write'} ${p} (${mode.toString(8).padStart(4, '0')} ${owner})`;
|
|
243
|
+
if (ctx.dryRun) {
|
|
244
|
+
if (opts.quiet) return true;
|
|
245
|
+
if (opts.secret) ctx.say(`${head}: secret content, generated on the server, never shown`);
|
|
246
|
+
else {
|
|
247
|
+
ctx.say(`${head}:`);
|
|
248
|
+
ctx.say(content.replace(/\n$/, '').split('\n').map((l) => ` | ${l}`).join('\n'));
|
|
249
|
+
}
|
|
250
|
+
return true;
|
|
251
|
+
}
|
|
252
|
+
if (!opts.quiet) ctx.say(head);
|
|
253
|
+
const tmp = `${d}.bestgate-tmp`;
|
|
254
|
+
fs.rmSync(tmp, { force: true });
|
|
255
|
+
fs.writeFileSync(tmp, content, { mode, flag: 'wx' });
|
|
256
|
+
fs.chmodSync(tmp, mode);
|
|
257
|
+
if (owner !== 'root:root') chownPath(tmp, owner);
|
|
258
|
+
fs.renameSync(tmp, d);
|
|
259
|
+
return true;
|
|
260
|
+
};
|
|
261
|
+
|
|
262
|
+
function chownPath(diskPath, owner) {
|
|
263
|
+
// chown takes the real path; under a test root the fake runner just records it.
|
|
264
|
+
ctx.journal.push({ op: 'chown', path: diskPath, owner });
|
|
265
|
+
const r = ctx.exec('chown', ['--no-dereference', owner, diskPath], {});
|
|
266
|
+
if (r.code !== 0) throw new CliError(`chown ${owner} ${diskPath} failed:\n${lastLines(r.stderr)}`);
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
ctx.chown = (p, owner) => {
|
|
270
|
+
if (ctx.dryRun) {
|
|
271
|
+
ctx.journal.push({ op: 'chown', path: p, owner });
|
|
272
|
+
ctx.say(` would run: chown ${owner} ${p}`);
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
chownPath(ctx.disk(p), owner);
|
|
276
|
+
};
|
|
277
|
+
|
|
278
|
+
ctx.mkdir = (p, opts = {}) => {
|
|
279
|
+
const mode = opts.mode ?? 0o755;
|
|
280
|
+
const owner = opts.owner || 'root:root';
|
|
281
|
+
const d = ctx.disk(p);
|
|
282
|
+
let st = null;
|
|
283
|
+
try { st = fs.lstatSync(d); } catch { /* new */ }
|
|
284
|
+
// lstat: a symlink is "not a directory" here, so it is refused, never followed.
|
|
285
|
+
if (st && !st.isDirectory()) throw new CliError(`${p} exists and is not a directory (a symlink is refused too)`);
|
|
286
|
+
// Every directory bestgate manages is owned by root (the one running this). One owned
|
|
287
|
+
// by anybody else may have been prepared by them: refuse instead of writing into it.
|
|
288
|
+
const me = typeof process.getuid === 'function' ? process.getuid() : null;
|
|
289
|
+
if (st && ctx.posixModes && me !== null && st.uid !== me) {
|
|
290
|
+
throw new CliError(`${p} exists but is owned by uid ${st.uid}, not by ${me === 0 ? 'root' : `uid ${me}`}: check who made it, then fix or remove it by hand`);
|
|
291
|
+
}
|
|
292
|
+
const sameMode = st && (!ctx.posixModes || (st.mode & 0o7777) === mode);
|
|
293
|
+
const sameGroup = st && (!ctx.posixModes || owner !== 'root:root' || st.gid === 0 || me !== 0);
|
|
294
|
+
if (st && sameMode && sameGroup && !opts.forceOwner) return false;
|
|
295
|
+
ctx.journal.push({ op: 'mkdir', path: p, mode, owner });
|
|
296
|
+
if (ctx.dryRun) {
|
|
297
|
+
const seen = ctx.dryDirs.has(p);
|
|
298
|
+
ctx.dryDirs.add(p);
|
|
299
|
+
ctx.say(` would ${st || seen ? 'set' : 'create'} directory ${p} (${mode.toString(8).padStart(4, '0')} ${owner})`);
|
|
300
|
+
return true;
|
|
301
|
+
}
|
|
302
|
+
ctx.say(` directory ${p} (${mode.toString(8).padStart(4, '0')} ${owner})`);
|
|
303
|
+
if (!st) fs.mkdirSync(d, { mode });
|
|
304
|
+
fs.chmodSync(d, mode);
|
|
305
|
+
if (owner !== 'root:root' || opts.forceOwner || (st && !sameGroup)) chownPath(d, owner);
|
|
306
|
+
return true;
|
|
307
|
+
};
|
|
308
|
+
|
|
309
|
+
ctx.symlink = (target, p) => {
|
|
310
|
+
const d = ctx.disk(p);
|
|
311
|
+
const t = ctx.disk(target);
|
|
312
|
+
if (ctx.isLink(p) && ctx.links.readlink(d) === t) return false;
|
|
313
|
+
ctx.journal.push({ op: 'symlink', path: p, target });
|
|
314
|
+
if (ctx.dryRun) { ctx.say(` would link ${p} -> ${target}`); return true; }
|
|
315
|
+
ctx.say(` link ${p} -> ${target}`);
|
|
316
|
+
if (ctx.exists(p)) {
|
|
317
|
+
if (!ctx.isLink(p)) throw new CliError(`${p} exists and is not a symlink`);
|
|
318
|
+
fs.rmSync(d);
|
|
319
|
+
}
|
|
320
|
+
ctx.links.symlink(t, d);
|
|
321
|
+
return true;
|
|
322
|
+
};
|
|
323
|
+
|
|
324
|
+
// Remove one file or symlink (never a directory, never recursive).
|
|
325
|
+
ctx.removeFile = (p) => {
|
|
326
|
+
if (!ctx.exists(p)) return false;
|
|
327
|
+
const d = ctx.disk(p);
|
|
328
|
+
if (!ctx.isLink(p) && fs.lstatSync(d).isDirectory()) throw new CliError(`refusing to remove directory ${p} as a file`);
|
|
329
|
+
ctx.journal.push({ op: 'remove', path: p });
|
|
330
|
+
if (ctx.dryRun) { ctx.say(` would remove ${p}`); return true; }
|
|
331
|
+
ctx.say(` remove ${p}`);
|
|
332
|
+
fs.rmSync(d);
|
|
333
|
+
return true;
|
|
334
|
+
};
|
|
335
|
+
|
|
336
|
+
// Remove an empty directory; a directory that still has files is kept and reported.
|
|
337
|
+
ctx.removeDir = (p) => {
|
|
338
|
+
const d = ctx.disk(p);
|
|
339
|
+
let entries;
|
|
340
|
+
try { entries = fs.readdirSync(d); } catch { return false; }
|
|
341
|
+
if (entries.length) { ctx.say(` kept ${p}: not empty`); return false; }
|
|
342
|
+
ctx.journal.push({ op: 'rmdir', path: p });
|
|
343
|
+
if (ctx.dryRun) { ctx.say(` would remove directory ${p}`); return true; }
|
|
344
|
+
ctx.say(` remove directory ${p}`);
|
|
345
|
+
fs.rmdirSync(d);
|
|
346
|
+
return true;
|
|
347
|
+
};
|
|
348
|
+
|
|
349
|
+
// Copy a file byte for byte (used to keep and restore originals).
|
|
350
|
+
ctx.copyFile = (from, to, mode) => {
|
|
351
|
+
ctx.journal.push({ op: 'copy', from, to, mode });
|
|
352
|
+
if (ctx.dryRun) { ctx.say(` would copy ${from} -> ${to}`); return; }
|
|
353
|
+
const tmp = `${ctx.disk(to)}.bestgate-tmp`;
|
|
354
|
+
fs.rmSync(tmp, { force: true });
|
|
355
|
+
fs.copyFileSync(ctx.disk(from), tmp);
|
|
356
|
+
if (mode !== undefined) fs.chmodSync(tmp, mode);
|
|
357
|
+
fs.renameSync(tmp, ctx.disk(to));
|
|
358
|
+
};
|
|
359
|
+
|
|
360
|
+
ctx.fileMode = (p) => { try { return fs.statSync(ctx.disk(p)).mode & 0o7777; } catch { return null; } };
|
|
361
|
+
|
|
362
|
+
return ctx;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
// Append everything said from now on to <logDir>/server.log, if that directory exists.
|
|
366
|
+
export function openLog(ctx, mode) {
|
|
367
|
+
if (ctx.dryRun) return;
|
|
368
|
+
const dir = ctx.disk(P.logDir);
|
|
369
|
+
try {
|
|
370
|
+
if (!fs.statSync(dir).isDirectory()) return;
|
|
371
|
+
} catch { return; }
|
|
372
|
+
ctx.logFile = path.join(dir, 'server.log');
|
|
373
|
+
try {
|
|
374
|
+
fs.appendFileSync(ctx.logFile, `\n== bestgate server ${mode} ${new Date(ctx.now()).toISOString()}\n`, { mode: 0o640 });
|
|
375
|
+
} catch { ctx.logFile = null; }
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
// ---- checks shared by several modes ----
|
|
379
|
+
|
|
380
|
+
export function versionAtLeast(have, want) {
|
|
381
|
+
const a = String(have).replace(/^v/, '').split('.').map((n) => parseInt(n, 10) || 0);
|
|
382
|
+
const b = String(want).split('.').map((n) => parseInt(n, 10) || 0);
|
|
383
|
+
for (let i = 0; i < 3; i++) {
|
|
384
|
+
if ((a[i] || 0) !== (b[i] || 0)) return (a[i] || 0) > (b[i] || 0);
|
|
385
|
+
}
|
|
386
|
+
return true;
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
export function requireRoot(ctx) {
|
|
390
|
+
if (ctx.uid !== 0) throw new CliError('Run this as root (sudo bestgate server ...).');
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
export function requireNode(ctx) {
|
|
394
|
+
if (!versionAtLeast(ctx.nodeVersion, MIN_NODE)) {
|
|
395
|
+
throw new CliError(`The server side needs Node.js >= ${MIN_NODE} (node:sqlite); this is ${ctx.nodeVersion}. Install Node 24 LTS.`);
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
export function randomLabel() {
|
|
400
|
+
return 'bgcheck-' + randomBytes(5).toString('hex');
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
// DNS check: a random name and the control name under the base must resolve to publicIp.
|
|
404
|
+
export async function checkDns(ctx, cfg) {
|
|
405
|
+
const names = [`${randomLabel()}.${cfg.baseDomain}`, `${cfg.controlLabel}.${cfg.baseDomain}`];
|
|
406
|
+
const out = [];
|
|
407
|
+
for (const name of names) {
|
|
408
|
+
const addresses = await ctx.resolve(name);
|
|
409
|
+
out.push({ name, addresses, ok: addresses.includes(cfg.publicIp) });
|
|
410
|
+
}
|
|
411
|
+
return out;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
// The wildcard certificate of the lineage named after baseDomain.
|
|
415
|
+
export function certInfo(ctx, cfg) {
|
|
416
|
+
const f = certFiles(cfg.baseDomain);
|
|
417
|
+
const pem = ctx.readOrNull(f.fullchain);
|
|
418
|
+
if (pem === null) return { present: false, file: f.fullchain };
|
|
419
|
+
try {
|
|
420
|
+
const x = new X509Certificate(pem);
|
|
421
|
+
const validTo = new Date(x.validTo).getTime();
|
|
422
|
+
const san = x.subjectAltName || '';
|
|
423
|
+
return {
|
|
424
|
+
present: true,
|
|
425
|
+
file: f.fullchain,
|
|
426
|
+
validTo: new Date(validTo).toISOString(),
|
|
427
|
+
daysLeft: Math.floor((validTo - ctx.now()) / 86400000),
|
|
428
|
+
coversWildcard: san.split(/,\s*/).includes(`DNS:*.${cfg.baseDomain}`),
|
|
429
|
+
};
|
|
430
|
+
} catch (e) {
|
|
431
|
+
return { present: true, file: f.fullchain, error: `cannot parse: ${e.message}` };
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
// `ss -Hltnp` → [{addr, port, process}]
|
|
436
|
+
export function parseSs(text) {
|
|
437
|
+
const out = [];
|
|
438
|
+
for (const line of String(text).split('\n')) {
|
|
439
|
+
const f = line.trim().split(/\s+/);
|
|
440
|
+
if (f.length < 5) continue;
|
|
441
|
+
const local = f[3];
|
|
442
|
+
const i = local.lastIndexOf(':');
|
|
443
|
+
if (i < 0) continue;
|
|
444
|
+
const port = parseInt(local.slice(i + 1), 10);
|
|
445
|
+
if (!Number.isInteger(port)) continue;
|
|
446
|
+
let addr = local.slice(0, i).replace(/^\[|\]$/g, '').replace(/%.*$/, '');
|
|
447
|
+
const m = /users:\(\("([^"]+)"/.exec(line);
|
|
448
|
+
out.push({ addr, port, process: m ? m[1] : '' });
|
|
449
|
+
}
|
|
450
|
+
return out;
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
export function listeningPorts(ctx) {
|
|
454
|
+
const r = ctx.run('ss', ['-Hltnp']);
|
|
455
|
+
if (r.code !== 0) throw new CliError(`ss failed: ${lastLines(r.stderr)}`);
|
|
456
|
+
return parseSs(r.stdout);
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
export const isLoopback = (a) => a === '127.0.0.1' || a === '::1';
|
|
460
|
+
|
|
461
|
+
// Status of a systemd unit name as far as files go: where a unit file with that name exists.
|
|
462
|
+
export function unitFileLocations(ctx, name) {
|
|
463
|
+
return ['/etc/systemd/system', '/run/systemd/system', '/lib/systemd/system', '/usr/lib/systemd/system']
|
|
464
|
+
.map((d) => `${d}/${name}`)
|
|
465
|
+
.filter((f) => ctx.exists(f));
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
// The address nginx answers on, for probing without outside DNS (like curl --resolve).
|
|
469
|
+
export const probeAddress = (cfg) => cfg.listenIp || '127.0.0.1';
|
|
470
|
+
|
|
471
|
+
// checkUrls (other sites on this nginx) → { url: '200' | 'error:ECONNREFUSED' }, probed through probeAddress.
|
|
472
|
+
export async function probeCheckUrls(ctx, cfg) {
|
|
473
|
+
const out = {};
|
|
474
|
+
for (const url of cfg.checkUrls) {
|
|
475
|
+
const r = await ctx.probe({ url, address: probeAddress(cfg), verifyTls: false, maxBody: 0 });
|
|
476
|
+
out[url] = r.status ? String(r.status) : `error:${r.error || 'unknown'}`;
|
|
477
|
+
}
|
|
478
|
+
return out;
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
// Print OK/WARN/FAIL lines; returns counts.
|
|
482
|
+
export function report(ctx, checks) {
|
|
483
|
+
let fail = 0;
|
|
484
|
+
let warn = 0;
|
|
485
|
+
for (const c of checks) {
|
|
486
|
+
if (c.level === 'FAIL') fail++;
|
|
487
|
+
if (c.level === 'WARN') warn++;
|
|
488
|
+
ctx.say(`${c.level.padEnd(4)} ${c.msg}`);
|
|
489
|
+
}
|
|
490
|
+
return { fail, warn };
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
export async function askConfirm(ctx, message) {
|
|
494
|
+
if (ctx.confirm) return ctx.confirm(message);
|
|
495
|
+
if (!ctx.isTTY) throw new CliError('No terminal to ask for confirmation: run again with --yes.');
|
|
496
|
+
const { confirm } = await import('@inquirer/prompts');
|
|
497
|
+
return confirm({ message, default: false });
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
export function parseFlags(argv, known) {
|
|
501
|
+
const flags = {};
|
|
502
|
+
for (let i = 0; i < argv.length; i++) {
|
|
503
|
+
const a = argv[i];
|
|
504
|
+
const spec = known[a];
|
|
505
|
+
if (spec === undefined) throw new CliError(`Unknown option ${a}. Known: ${Object.keys(known).join(' ')}`);
|
|
506
|
+
const key = a.replace(/^--/, '').replace(/-([a-z])/g, (_, c) => c.toUpperCase());
|
|
507
|
+
if (spec === 'value') {
|
|
508
|
+
if (!argv[i + 1] || argv[i + 1].startsWith('--')) throw new CliError(`${a} needs a value`);
|
|
509
|
+
flags[key] = argv[++i];
|
|
510
|
+
} else flags[key] = true;
|
|
511
|
+
}
|
|
512
|
+
return flags;
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
export { posix };
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
# bestgate: auth daemon, the frps HTTP plugin. Written by `bestgate server install`.
|
|
2
|
+
# frps refuses every login while this is down, so it restarts always and quickly.
|
|
3
|
+
[Unit]
|
|
4
|
+
Description=bestgate auth daemon (frps plugin)
|
|
5
|
+
Documentation=https://github.com/bestapps-ua/best-gate
|
|
6
|
+
After=network.target
|
|
7
|
+
Before=__FRPS_UNIT__
|
|
8
|
+
|
|
9
|
+
[Service]
|
|
10
|
+
Type=simple
|
|
11
|
+
User=__DAEMON_USER__
|
|
12
|
+
Group=__DAEMON_USER__
|
|
13
|
+
# The dashboard password and the plugin secret; the frps auth token is not given to the daemon.
|
|
14
|
+
EnvironmentFile=__DAEMON_ENV_FILE__
|
|
15
|
+
ExecStart=__NODE__ --disable-warning=ExperimentalWarning __BIN_SCRIPT__ server daemon --config __CONFIG_FILE__
|
|
16
|
+
WorkingDirectory=__STATE_DIR__
|
|
17
|
+
Restart=always
|
|
18
|
+
RestartSec=2s
|
|
19
|
+
MemoryMax=256M
|
|
20
|
+
TasksMax=256
|
|
21
|
+
UMask=0027
|
|
22
|
+
|
|
23
|
+
ReadWritePaths=__STATE_DIR__
|
|
24
|
+
InaccessiblePaths=-__ORIG_DIR__
|
|
25
|
+
NoNewPrivileges=yes
|
|
26
|
+
# Only to bind its privileged loopback ports (see ports in config.json); nothing else.
|
|
27
|
+
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
|
|
28
|
+
AmbientCapabilities=CAP_NET_BIND_SERVICE
|
|
29
|
+
ProtectSystem=strict
|
|
30
|
+
ProtectHome=yes
|
|
31
|
+
PrivateTmp=yes
|
|
32
|
+
PrivateDevices=yes
|
|
33
|
+
ProtectKernelTunables=yes
|
|
34
|
+
ProtectKernelModules=yes
|
|
35
|
+
ProtectKernelLogs=yes
|
|
36
|
+
ProtectControlGroups=yes
|
|
37
|
+
ProtectClock=yes
|
|
38
|
+
ProtectHostname=yes
|
|
39
|
+
ProtectProc=invisible
|
|
40
|
+
ProcSubset=pid
|
|
41
|
+
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
|
|
42
|
+
RestrictNamespaces=yes
|
|
43
|
+
RestrictRealtime=yes
|
|
44
|
+
RestrictSUIDSGID=yes
|
|
45
|
+
LockPersonality=yes
|
|
46
|
+
RemoveIPC=yes
|
|
47
|
+
SystemCallArchitectures=native
|
|
48
|
+
SystemCallFilter=@system-service
|
|
49
|
+
SystemCallFilter=~@privileged
|
|
50
|
+
SystemCallErrorNumber=EPERM
|
|
51
|
+
# The daemon talks only to frps (plugin calls, dashboard API) on loopback.
|
|
52
|
+
IPAddressAllow=localhost
|
|
53
|
+
IPAddressDeny=any
|
|
54
|
+
|
|
55
|
+
[Install]
|
|
56
|
+
WantedBy=multi-user.target
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# bestgate: daily check (DNS, certificate days left). Written by `bestgate server install`.
|
|
2
|
+
# Runs as root to read the certificate; it may write only its own log directory, and
|
|
3
|
+
# has no capabilities, no secrets and no access to the daemon's state directory.
|
|
4
|
+
[Unit]
|
|
5
|
+
Description=bestgate daily check (DNS and certificate)
|
|
6
|
+
Documentation=https://github.com/bestapps-ua/best-gate
|
|
7
|
+
After=network-online.target
|
|
8
|
+
Wants=network-online.target
|
|
9
|
+
|
|
10
|
+
[Service]
|
|
11
|
+
Type=oneshot
|
|
12
|
+
ExecStart=__NODE__ --disable-warning=ExperimentalWarning __BIN_SCRIPT__ server check
|
|
13
|
+
TimeoutStartSec=120
|
|
14
|
+
UMask=0027
|
|
15
|
+
|
|
16
|
+
ReadWritePaths=__LOG_DIR__
|
|
17
|
+
InaccessiblePaths=-__STATE_DIR__ -__ORIG_DIR__ -__ENV_FILE__ -__DAEMON_ENV_FILE__
|
|
18
|
+
NoNewPrivileges=yes
|
|
19
|
+
CapabilityBoundingSet=
|
|
20
|
+
AmbientCapabilities=
|
|
21
|
+
ProtectSystem=strict
|
|
22
|
+
ProtectHome=yes
|
|
23
|
+
PrivateTmp=yes
|
|
24
|
+
PrivateDevices=yes
|
|
25
|
+
ProtectKernelTunables=yes
|
|
26
|
+
ProtectKernelModules=yes
|
|
27
|
+
ProtectKernelLogs=yes
|
|
28
|
+
ProtectControlGroups=yes
|
|
29
|
+
ProtectClock=yes
|
|
30
|
+
ProtectHostname=yes
|
|
31
|
+
ProtectProc=invisible
|
|
32
|
+
ProcSubset=pid
|
|
33
|
+
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX AF_NETLINK
|
|
34
|
+
RestrictNamespaces=yes
|
|
35
|
+
RestrictRealtime=yes
|
|
36
|
+
RestrictSUIDSGID=yes
|
|
37
|
+
LockPersonality=yes
|
|
38
|
+
RemoveIPC=yes
|
|
39
|
+
SystemCallArchitectures=native
|
|
40
|
+
SystemCallFilter=@system-service
|
|
41
|
+
SystemCallFilter=~@privileged
|
|
42
|
+
SystemCallErrorNumber=EPERM
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# bestgate: runs the daily check. Written by `bestgate server install`.
|
|
2
|
+
[Unit]
|
|
3
|
+
Description=bestgate daily check (DNS and certificate)
|
|
4
|
+
|
|
5
|
+
[Timer]
|
|
6
|
+
OnActiveSec=2min
|
|
7
|
+
OnCalendar=daily
|
|
8
|
+
RandomizedDelaySec=1h
|
|
9
|
+
Persistent=true
|
|
10
|
+
Unit=__CHECK_UNIT__
|
|
11
|
+
|
|
12
|
+
[Install]
|
|
13
|
+
WantedBy=timers.target
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
# bestgate: frps, the tunnel server. Written by `bestgate server install`.
|
|
2
|
+
[Unit]
|
|
3
|
+
Description=bestgate frps (dev tunnels)
|
|
4
|
+
Documentation=https://github.com/bestapps-ua/best-gate
|
|
5
|
+
After=network.target __AUTH_UNIT__
|
|
6
|
+
Wants=__AUTH_UNIT__
|
|
7
|
+
|
|
8
|
+
[Service]
|
|
9
|
+
Type=simple
|
|
10
|
+
DynamicUser=yes
|
|
11
|
+
EnvironmentFile=__ENV_FILE__
|
|
12
|
+
ExecStart=__FRPS_BIN__ -c __FRPS_TOML__
|
|
13
|
+
Restart=on-failure
|
|
14
|
+
RestartSec=5s
|
|
15
|
+
MemoryMax=512M
|
|
16
|
+
TasksMax=1024
|
|
17
|
+
LimitNOFILE=65536
|
|
18
|
+
UMask=0077
|
|
19
|
+
|
|
20
|
+
NoNewPrivileges=yes
|
|
21
|
+
# Only to bind its privileged loopback ports (see ports in config.json); nothing else.
|
|
22
|
+
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
|
|
23
|
+
AmbientCapabilities=CAP_NET_BIND_SERVICE
|
|
24
|
+
ProtectSystem=strict
|
|
25
|
+
ProtectHome=yes
|
|
26
|
+
PrivateTmp=yes
|
|
27
|
+
PrivateDevices=yes
|
|
28
|
+
ProtectKernelTunables=yes
|
|
29
|
+
ProtectKernelModules=yes
|
|
30
|
+
ProtectKernelLogs=yes
|
|
31
|
+
ProtectControlGroups=yes
|
|
32
|
+
ProtectClock=yes
|
|
33
|
+
ProtectHostname=yes
|
|
34
|
+
ProtectProc=invisible
|
|
35
|
+
ProcSubset=pid
|
|
36
|
+
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
|
|
37
|
+
RestrictNamespaces=yes
|
|
38
|
+
RestrictRealtime=yes
|
|
39
|
+
RestrictSUIDSGID=yes
|
|
40
|
+
LockPersonality=yes
|
|
41
|
+
MemoryDenyWriteExecute=yes
|
|
42
|
+
RemoveIPC=yes
|
|
43
|
+
SystemCallArchitectures=native
|
|
44
|
+
SystemCallFilter=@system-service
|
|
45
|
+
SystemCallFilter=~@privileged
|
|
46
|
+
SystemCallErrorNumber=EPERM
|
|
47
|
+
# frps only talks to nginx, the daemon and itself, all on loopback.
|
|
48
|
+
IPAddressAllow=localhost
|
|
49
|
+
IPAddressDeny=any
|
|
50
|
+
|
|
51
|
+
[Install]
|
|
52
|
+
WantedBy=multi-user.target
|