@bestapps/bestgate 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,49 @@
1
+ # bestgate: frps configuration, written by `bestgate server install`. Local edits are overwritten.
2
+ #
3
+ # frps renders this whole file as a Go template before parsing it, comments included.
4
+ # The only three template expressions are the secrets below (auth token, dashboard
5
+ # password, plugin secret). They are filled from the environment, which systemd loads
6
+ # from /etc/bestgate/frps.env (root, 0600), so no secret is ever stored in this file.
7
+
8
+ # Everything listens on loopback only; nginx is the only way in from outside.
9
+ bindAddr = "127.0.0.1"
10
+ bindPort = __CONTROL_PORT__
11
+ proxyBindAddr = "127.0.0.1"
12
+ vhostHTTPPort = __VHOST_PORT__
13
+ subDomainHost = "__BASE_DOMAIN__"
14
+
15
+ # KCP, QUIC, HTTPS vhost, tcpmux and the SSH gateway stay off: their ports are not set.
16
+ # No TCP/UDP proxy can bind a port: the only allowed port is one frps itself already uses.
17
+ allowPorts = [{ single = __VHOST_PORT__ }]
18
+
19
+ auth.method = "token"
20
+ auth.token = "{{ .Envs.FRP_AUTH_TOKEN }}"
21
+ # Heartbeats and work connections must carry the token too. Without NewWorkConns anyone
22
+ # who knows a client's run_id could join its work-connection pool and receive visitors'
23
+ # requests. frpc must list the same scopes (bestgate's client does).
24
+ auth.additionalScopes = ["HeartBeats", "NewWorkConns"]
25
+
26
+ # Dashboard API, used by the bestgate daemon to see traffic and open connections.
27
+ webServer.addr = "127.0.0.1"
28
+ webServer.port = __DASHBOARD_PORT__
29
+ webServer.user = "admin"
30
+ webServer.password = "{{ .Envs.FRP_DASHBOARD_PASSWORD }}"
31
+
32
+ transport.maxPoolCount = 5
33
+ # Explicit, so every client must Ping: with tcpMux the default would be no timeout,
34
+ # and then idle sessions and revoked keys could never be cut off at the next Ping.
35
+ transport.heartbeatTimeout = 90
36
+
37
+ log.to = "console"
38
+ log.level = "info"
39
+ log.disablePrintColor = true
40
+
41
+ # The bestgate daemon decides every login and every new tunnel. If it is down or
42
+ # answers anything but 200, frps refuses the login or tunnel (fails closed).
43
+ # frps authenticates to it with Basic auth taken from the user:password part of addr;
44
+ # Go's HTTP client redacts that password in the errors frps logs.
45
+ [[httpPlugins]]
46
+ name = "bestgate"
47
+ addr = "bestgate:{{ .Envs.BESTGATE_PLUGIN_SECRET }}@127.0.0.1:__DAEMON_PORT__"
48
+ path = "/handler"
49
+ ops = ["Login", "NewProxy", "CloseProxy", "Ping"]
@@ -0,0 +1,12 @@
1
+ #!/bin/sh
2
+ # bestgate: shows at SSH login what the daily check found wrong (nothing when all is well).
3
+ # Written by `bestgate server install`; the check itself is `bestgate server check`.
4
+ f='__CHECK_FILE__'
5
+ [ -e "$f" ] || exit 0
6
+ if [ -n "$(find "$f" -mmin +2880 2>/dev/null)" ]; then
7
+ echo "bestgate: the daily check has not run for 2 days (systemctl status __TIMER_UNIT__)"
8
+ fi
9
+ if [ -s "$f" ]; then
10
+ tr -cd '\11\12\40-\176' < "$f" | head -n 20
11
+ fi
12
+ exit 0
@@ -0,0 +1,105 @@
1
+ # bestgate: dev tunnels for __BASE_DOMAIN__, written by `bestgate server install`.
2
+ # Local edits are overwritten; `bestgate server revert` removes this file.
3
+ # Everything here is named bestgate_* or answers only names under __BASE_DOMAIN__.
4
+ # No default_server and no port 80: unknown names keep going to the server's own default.
5
+
6
+ map $http_upgrade $bestgate_connection {
7
+ default upgrade;
8
+ '' close;
9
+ }
10
+
11
+ limit_req_zone $binary_remote_addr zone=bestgate_req:10m rate=__REQ_PER_SEC__r/s;
12
+ limit_req_zone $binary_remote_addr zone=bestgate_login:1m rate=__LOGIN_PER_MIN__r/m;
13
+ limit_conn_zone $binary_remote_addr zone=bestgate_conn:10m;
14
+ # One counter for both bestgate server blocks: caps what tunnels can hold of the nginx
15
+ # connection pool that every site on this server shares.
16
+ map $server_port $bestgate_total_key {
17
+ default bestgate;
18
+ }
19
+ limit_conn_zone $bestgate_total_key zone=bestgate_total:1m;
20
+
21
+ # Control channel: frpc connects over WebSocket to /~!frp. Nothing else is served here.
22
+ server {
23
+ listen __LISTEN_ADDR__:443 ssl;
24
+ __HTTP2__
25
+ server_name __CONTROL_HOST__;
26
+
27
+ ssl_certificate __CERT_FULLCHAIN__;
28
+ ssl_certificate_key __CERT_PRIVKEY__;
29
+
30
+ access_log __NGINX_LOG_DIR__/bestgate-control.access.log;
31
+ error_log __NGINX_LOG_DIR__/bestgate-control.error.log;
32
+
33
+ client_header_timeout 10s;
34
+ client_body_timeout 30s;
35
+
36
+ location = /~!frp {
37
+ limit_req zone=bestgate_login burst=__LOGIN_PER_MIN__ nodelay;
38
+ limit_req_status 429;
39
+ # limit_conn set here replaces the server level, so both limits are listed.
40
+ limit_conn bestgate_conn __CONTROL_CONN_PER_IP__;
41
+ limit_conn bestgate_total __MAX_CONNECTIONS__;
42
+ limit_conn_status 429;
43
+
44
+ proxy_pass http://127.0.0.1:__CONTROL_PORT__;
45
+ proxy_http_version 1.1;
46
+ proxy_set_header Host $host;
47
+ proxy_set_header Upgrade $http_upgrade;
48
+ proxy_set_header Connection $bestgate_connection;
49
+ proxy_set_header X-Forwarded-For $remote_addr;
50
+ proxy_buffering off;
51
+ proxy_request_buffering off;
52
+ proxy_connect_timeout 10s;
53
+ proxy_read_timeout 3600s;
54
+ proxy_send_timeout 3600s;
55
+ }
56
+
57
+ location / {
58
+ return 404;
59
+ }
60
+ }
61
+
62
+ # Tunnels: <name>.__BASE_DOMAIN__ goes to frps, which routes by Host to the dev's frpc.
63
+ server {
64
+ listen __LISTEN_ADDR__:443 ssl;
65
+ __HTTP2__
66
+ server_name ~^[a-z0-9-]+\.__BASE_REGEX__$;
67
+
68
+ ssl_certificate __CERT_FULLCHAIN__;
69
+ ssl_certificate_key __CERT_PRIVKEY__;
70
+
71
+ access_log __NGINX_LOG_DIR__/bestgate-tunnels.access.log;
72
+ error_log __NGINX_LOG_DIR__/bestgate-tunnels.error.log;
73
+
74
+ client_max_body_size __MAX_BODY__;
75
+ client_header_timeout 10s;
76
+ client_body_timeout 30s;
77
+ limit_req zone=bestgate_req burst=__REQ_BURST__ nodelay;
78
+ limit_conn bestgate_conn __CONN_PER_IP__;
79
+ limit_conn bestgate_total __MAX_CONNECTIONS__;
80
+ limit_req_status 429;
81
+ limit_conn_status 429;
82
+
83
+ location / {
84
+ add_header X-Robots-Tag "noindex, nofollow" always;
85
+
86
+ proxy_pass http://127.0.0.1:__VHOST_PORT__;
87
+ proxy_http_version 1.1;
88
+ proxy_set_header Host $host;
89
+ proxy_set_header Upgrade $http_upgrade;
90
+ proxy_set_header Connection $bestgate_connection;
91
+ proxy_set_header X-Real-IP $remote_addr;
92
+ proxy_set_header X-Forwarded-For $remote_addr;
93
+ proxy_set_header X-Forwarded-Proto https;
94
+ proxy_set_header X-Forwarded-Host $host;
95
+ proxy_buffering off;
96
+ proxy_request_buffering off;
97
+ proxy_max_temp_file_size 0;
98
+ proxy_connect_timeout 10s;
99
+ # Long, for WebSockets (HMR) that sit idle. A plain request still waits at most
100
+ # 60 s for the app's response headers (frps vhostHTTPTimeout); bestgate_total
101
+ # bounds how many connections can be held this long.
102
+ proxy_read_timeout 3600s;
103
+ proxy_send_timeout 3600s;
104
+ }
105
+ }
@@ -0,0 +1,170 @@
1
+ // `bestgate server user add|list|renew|rekey|revoke|remove`. Root only.
2
+ // The database is shared with the auth daemon, which runs as DAEMON_USER, so this
3
+ // process gives up root BEFORE it opens the database: the db and its -wal/-shm files
4
+ // must never be owned by root. Secrets (config, frps.env) are read before that.
5
+ import { CliError } from '../util.js';
6
+ import { NAME_RE, TOKEN_RE, encodeKey, newSecret, hashSecret } from '../key.js';
7
+ import { loadEnvFile } from './config.js';
8
+ import { openDb } from './db.js';
9
+ import { DAY_MS } from './policy.js';
10
+ import { P, DAEMON_USER, createContext, requireRoot, requireNode, askConfirm, parseFlags } from './sys.js';
11
+ import { loadServerConfig } from './plan.js';
12
+
13
+ const USAGE = 'Usage: bestgate server user add <name> | list | renew <name> | rekey <name> | revoke <name> | remove <name> [--yes]';
14
+
15
+ // Drops root to the daemon user (supplementary groups first, then gid, then uid).
16
+ // Does nothing when not running as root (or on Windows); as root it drops or throws, so
17
+ // the database is never opened as root.
18
+ export function dropPrivileges(user = DAEMON_USER) {
19
+ if (typeof process.getuid !== 'function' || process.getuid() !== 0) return false;
20
+ try {
21
+ process.setgroups([]);
22
+ process.setgid(user);
23
+ process.setuid(user);
24
+ } catch (e) {
25
+ throw new CliError(`Cannot switch to the ${user} user (${e.code || e.message}). Is bestgate installed? Run \`bestgate server install\`.`);
26
+ }
27
+ return true;
28
+ }
29
+
30
+ // Drop privileges, then open the database. opts: dropPrivileges(user), openDb(file).
31
+ export function openUserDb(ctx, opts = {}) {
32
+ (opts.dropPrivileges || dropPrivileges)(DAEMON_USER);
33
+ return (opts.openDb || openDb)(ctx.disk(P.dbFile));
34
+ }
35
+
36
+ // 'active' | 'expired' | 'revoked', same rule as the daemon (policy.userProblem).
37
+ export function userState(u, now, cfg) {
38
+ if (u.revoked_at != null) return 'revoked';
39
+ return now - u.last_used_at > cfg.accessExpiryDays * DAY_MS ? 'expired' : 'active';
40
+ }
41
+
42
+ const stamp = (ms) => new Date(ms).toISOString().slice(0, 16).replace('T', ' ');
43
+
44
+ function daysLeft(u, now, cfg) {
45
+ if (u.revoked_at != null) return '-';
46
+ return String(Math.max(0, Math.ceil((u.last_used_at + cfg.accessExpiryDays * DAY_MS - now) / DAY_MS)));
47
+ }
48
+
49
+ export function formatUserTable(users, now, cfg) {
50
+ const head = ['NAME', 'CREATED (UTC)', 'LAST USED (UTC)', 'DAYS LEFT', 'STATE'];
51
+ const rows = users.map((u) => [u.name, stamp(u.created_at), stamp(u.last_used_at), daysLeft(u, now, cfg), userState(u, now, cfg)]);
52
+ const widths = head.map((h, i) => Math.max(h.length, ...rows.map((r) => r[i].length)));
53
+ return [head, ...rows].map((r) => r.map((c, i) => c.padEnd(widths[i])).join(' ').trimEnd());
54
+ }
55
+
56
+ function requireName(name) {
57
+ if (!name || !NAME_RE.test(name)) {
58
+ throw new CliError('Give a user name: 2-31 characters a-z, 0-9 and "-", starting with a letter or digit.');
59
+ }
60
+ return name;
61
+ }
62
+
63
+ function readToken(ctx) {
64
+ let env;
65
+ try {
66
+ env = loadEnvFile(ctx.disk(P.envFile));
67
+ } catch (e) {
68
+ throw new CliError(`${e.message}. Has \`bestgate server install\` run?`);
69
+ }
70
+ if (!TOKEN_RE.test(env.FRP_AUTH_TOKEN || '')) throw new CliError(`FRP_AUTH_TOKEN in ${P.envFile} is missing or malformed.`);
71
+ return env.FRP_AUTH_TOKEN;
72
+ }
73
+
74
+ // The key goes to the terminal through ctx.out only: never into the log file.
75
+ function showKey(ctx, cfg, name, key, what) {
76
+ ctx.say(`${what} for ${name}. It is shown only once and is not stored on the server:`);
77
+ ctx.say('');
78
+ ctx.out(` ${key}`);
79
+ ctx.say('');
80
+ ctx.say(`Send it to ${name} over a private channel. ${name} then runs:`);
81
+ ctx.say(' npm i -g @bestapps/bestgate');
82
+ ctx.say(` bestgate login (host: ${cfg.baseDomain}, then paste the key)`);
83
+ ctx.say(' bestgate 3000 (the port of the local app)');
84
+ }
85
+
86
+ function mustExist(db, name) {
87
+ const u = db.getUser(name);
88
+ if (!u) throw new CliError(`No such user: ${name}. See \`bestgate server user list\`.`);
89
+ return u;
90
+ }
91
+
92
+ const COMMANDS = {
93
+ add(ctx, db, { name, cfg, token, now }) {
94
+ if (name === cfg.controlLabel) throw new CliError(`"${name}" is the control label and cannot be a user name.`);
95
+ const secret = newSecret();
96
+ try {
97
+ db.addUser(name, hashSecret(secret), now);
98
+ } catch (e) {
99
+ throw new CliError(e.message);
100
+ }
101
+ showKey(ctx, cfg, name, encodeKey({ user: name, secret, token, control: cfg.controlLabel }), 'Access key created');
102
+ },
103
+
104
+ list(ctx, db, { cfg, now }) {
105
+ const users = db.listUsers();
106
+ if (!users.length) return ctx.say('No users yet. Add one with: bestgate server user add <name>');
107
+ for (const l of formatUserTable(users, now, cfg)) ctx.say(l);
108
+ },
109
+
110
+ renew(ctx, db, { name, cfg, now }) {
111
+ const u = mustExist(db, name);
112
+ db.renewUser(name, now);
113
+ if (u.revoked_at != null) {
114
+ ctx.say(`${name} is revoked; renewing restarts the expiry clock but does not undo the revoke.`);
115
+ ctx.say(`To let ${name} in again, issue a new key: bestgate server user rekey ${name}`);
116
+ return;
117
+ }
118
+ ctx.say(`${name}: access renewed, valid for ${cfg.accessExpiryDays} days from now (counted from last use).`);
119
+ },
120
+
121
+ rekey(ctx, db, { name, cfg, token, now }) {
122
+ mustExist(db, name);
123
+ const secret = newSecret();
124
+ db.setKeyHash(name, hashSecret(secret), now);
125
+ showKey(ctx, cfg, name, encodeKey({ user: name, secret, token, control: cfg.controlLabel }), 'New access key created');
126
+ ctx.say('');
127
+ ctx.say(`The old key no longer works; a client connected with it is dropped at its next heartbeat (about 30 seconds). The user is active again.`);
128
+ },
129
+
130
+ async revoke(ctx, db, { name, yes, now }) {
131
+ const u = mustExist(db, name);
132
+ if (u.revoked_at != null) return ctx.say(`${name} is already revoked.`);
133
+ if (!yes && !(await askConfirm(ctx, `Revoke ${name}? Their key stops working.`))) return ctx.say('Nothing changed.');
134
+ db.revokeUser(name, now);
135
+ ctx.say(`${name} revoked. A connected client is dropped at its next heartbeat (about 30 seconds).`);
136
+ ctx.say(`To let ${name} in again: bestgate server user rekey ${name}`);
137
+ },
138
+
139
+ async remove(ctx, db, { name, yes }) {
140
+ mustExist(db, name);
141
+ if (!yes && !(await askConfirm(ctx, `Remove ${name} for good?`))) return ctx.say('Nothing changed.');
142
+ db.removeUser(name);
143
+ ctx.say(`${name} removed. A connected client is dropped at its next heartbeat (about 30 seconds).`);
144
+ },
145
+ };
146
+
147
+ const NEEDS_NAME = new Set(['add', 'renew', 'rekey', 'revoke', 'remove']);
148
+ const NEEDS_TOKEN = new Set(['add', 'rekey']);
149
+
150
+ // opts (tests): ctx, dropPrivileges(user), openDb(file)
151
+ export async function run(argv = [], opts = {}) {
152
+ const [sub, ...rest] = argv;
153
+ if (!Object.hasOwn(COMMANDS, sub)) throw new CliError(USAGE);
154
+ const name = NEEDS_NAME.has(sub) && rest[0] && !rest[0].startsWith('--') ? rest.shift() : undefined;
155
+ const flags = parseFlags(rest, { '--yes': 'flag' });
156
+ if (NEEDS_NAME.has(sub)) requireName(name);
157
+
158
+ const ctx = opts.ctx || createContext();
159
+ requireRoot(ctx);
160
+ requireNode(ctx);
161
+ const cfg = loadServerConfig(ctx);
162
+ const token = NEEDS_TOKEN.has(sub) ? readToken(ctx) : undefined;
163
+
164
+ const db = openUserDb(ctx, opts);
165
+ try {
166
+ await COMMANDS[sub](ctx, db, { name, cfg, token, yes: !!flags.yes, now: ctx.now() });
167
+ } finally {
168
+ db.close();
169
+ }
170
+ }
@@ -0,0 +1,127 @@
1
+ // `bestgate server verify`: is the installed service working, and are the other sites
2
+ // still fine? Read-only. Probes go to nginx's own address (cfg.listenIp) with the host
3
+ // name forced, like curl --resolve, so they do not depend on outside DNS or NAT hairpin.
4
+ // Ends with one "RESULT: OK|FAIL" line.
5
+ import { CliError } from '../util.js';
6
+ import { loadConfig, loadEnvFile } from './config.js';
7
+ import {
8
+ P, UNITS, createContext, openLog, requireRoot, checkDns, certInfo, listeningPorts, isLoopback,
9
+ probeAddress, probeCheckUrls, randomLabel, report, parseFlags,
10
+ } from './sys.js';
11
+ import { parseDump, detectLayout, analyzeNginx } from './nginx.js';
12
+ import { loadServerConfig } from './plan.js';
13
+
14
+ const FRPS_404 = 'Faithfully yours, frp.';
15
+
16
+ export async function verifyAll(ctx, cfg) {
17
+ const checks = [];
18
+ const add = (level, msg) => checks.push({ level, msg });
19
+ const addr = probeAddress(cfg);
20
+
21
+ for (const u of [UNITS.auth, UNITS.frps]) {
22
+ const s = ctx.run('systemctl', ['is-active', u]).stdout.trim();
23
+ add(s === 'active' ? 'OK' : 'FAIL', `${u} is ${s || 'unknown'}${s === 'active' ? '' : ` (journalctl -u ${u} -n 50)`}`);
24
+ }
25
+ const t = ctx.run('systemctl', ['is-enabled', UNITS.timer]).stdout.trim();
26
+ add(t === 'enabled' ? 'OK' : 'WARN', `${UNITS.timer} is ${t || 'unknown'}`);
27
+
28
+ try {
29
+ const l = listeningPorts(ctx);
30
+ for (const [k, port] of Object.entries(cfg.ports)) {
31
+ const on = l.filter((x) => x.port === port);
32
+ if (!on.length) add('FAIL', `nothing listens on port ${port} (${k})`);
33
+ else if (on.every((x) => isLoopback(x.addr))) add('OK', `port ${port} (${k}) listens on loopback only`);
34
+ else add('FAIL', `port ${port} (${k}) listens on ${on.map((x) => x.addr).join(', ')}: must be 127.0.0.1 only`);
35
+ }
36
+ } catch (e) { add('FAIL', e.message); }
37
+
38
+ const host = `${randomLabel()}.${cfg.baseDomain}`;
39
+ const r = await ctx.probe({ url: `https://${host}/`, address: addr, verifyTls: true });
40
+ if (r.error && !r.status) add('FAIL', `https://${host}/ via ${addr}: ${r.error}`);
41
+ else {
42
+ const certOk = r.cert && r.cert.san.split(/,\s*/).includes(`DNS:*.${cfg.baseDomain}`);
43
+ add(certOk ? 'OK' : 'FAIL', `https://${host}/ via ${addr} presents ${certOk ? `the certificate for *.${cfg.baseDomain} (valid chain)` : `another certificate (${r.cert ? r.cert.san : 'none'})`}`);
44
+ const frps = r.status === 404 && (r.body || '').includes(FRPS_404);
45
+ add(frps ? 'OK' : 'FAIL', `https://${host}/ answers ${r.status}${frps ? ' from frps (no such tunnel)' : ', expected frps\'s 404 page'}`);
46
+ }
47
+
48
+ const ctl = `${cfg.controlLabel}.${cfg.baseDomain}`;
49
+ const c1 = await ctx.probe({ url: `https://${ctl}/`, address: addr, verifyTls: true });
50
+ add(c1.status === 404 ? 'OK' : 'FAIL', `https://${ctl}/ answers ${c1.status || c1.error} (expected 404: only /~!frp is served)`);
51
+ const c2 = await ctx.probe({ url: `https://${ctl}/~!frp`, address: addr, verifyTls: true });
52
+ const reaches = c2.status && c2.status !== 404 && c2.status < 500;
53
+ add(reaches ? 'OK' : 'FAIL', `https://${ctl}/~!frp without WebSocket answers ${c2.status || c2.error}${reaches ? ' (reaches frps)' : ', expected frps to refuse the plain request'}`);
54
+
55
+ // Only frps (with the plugin secret) may call the daemon, and the daemon must refuse a
56
+ // login without a valid key. A real frpc login with a valid auth.token but no key is
57
+ // part of the end-to-end test.
58
+ const daemonUrl = `http://127.0.0.1:${cfg.ports.daemon}/handler?version=0.1.0&op=Login`;
59
+ const body = JSON.stringify({ version: '0.1.0', op: 'Login', content: { user: randomLabel().slice(0, 30), metas: {}, run_id: '' } });
60
+ const anon = await ctx.probe({ url: daemonUrl, address: '127.0.0.1', method: 'POST', body });
61
+ add(anon.status === 401 ? 'OK' : 'FAIL', `daemon refuses plugin calls without the plugin secret (${anon.status || anon.error}, expected 401)`);
62
+ let secret = null;
63
+ try { secret = loadEnvFile(ctx.disk(P.envFile)).BESTGATE_PLUGIN_SECRET || null; } catch { /* reported below */ }
64
+ if (!secret) add('FAIL', `no BESTGATE_PLUGIN_SECRET in ${P.envFile}: run \`bestgate server install\``);
65
+ else {
66
+ const authorization = 'Basic ' + Buffer.from(`bestgate:${secret}`).toString('base64');
67
+ const d = await ctx.probe({ url: daemonUrl, address: '127.0.0.1', method: 'POST', body, headers: { authorization } });
68
+ let refused = false;
69
+ try { refused = d.status === 200 && JSON.parse(d.body).reject === true; } catch { /* not JSON */ }
70
+ add(refused ? 'OK' : 'FAIL', `daemon refuses a login without a valid key (${d.status || d.error})`);
71
+ }
72
+
73
+ for (const x of await checkDns(ctx, cfg)) {
74
+ add(x.ok ? 'OK' : 'FAIL', `DNS: ${x.name} → ${x.addresses.join(', ') || 'nothing'}${x.ok ? '' : `, expected ${cfg.publicIp}`}`);
75
+ }
76
+
77
+ const urls = await probeCheckUrls(ctx, cfg);
78
+ for (const [u, s] of Object.entries(urls)) {
79
+ const ok = /^\d+$/.test(s) && +s < 500;
80
+ add(ok ? 'OK' : 'FAIL', `other site ${u} via ${addr} answers ${s}`);
81
+ }
82
+ if (!cfg.checkUrls.length) add('WARN', 'no checkUrls configured: other sites were not probed');
83
+
84
+ const dump = ctx.run('nginx', ['-T']);
85
+ if (dump.code !== 0) add('FAIL', 'nginx -t fails');
86
+ else {
87
+ try {
88
+ const parsed = parseDump(dump.stdout);
89
+ const layout = detectLayout(parsed, P.nginxDir);
90
+ if (!layout || !parsed.files.includes(layout.siteFile)) add('FAIL', `our nginx site is not loaded (${layout ? layout.siteFile : 'no site layout found'})`);
91
+ else {
92
+ const a = analyzeNginx(parsed, { listenIp: cfg.listenIp, siteFile: layout.siteFile, baseDomain: cfg.baseDomain, controlLabel: cfg.controlLabel });
93
+ add(a.wouldBeFirst === false ? 'OK' : 'FAIL', `${layout.siteFile} is ${a.wouldBeFirst === false ? 'not ' : ''}the first server on ${cfg.listenIp}:443`);
94
+ if (a.after.length) add('WARN', `loads after ours: ${a.after.join(', ')}`);
95
+ else add('OK', `${layout.siteFile} sorts last among the enabled sites`);
96
+ for (const x of a.conflicts) add('FAIL', `${x.file}: server_name ${x.name} matches ${x.host}`);
97
+ }
98
+ } catch (e) { add('FAIL', `cannot read nginx -T: ${e.message}`); }
99
+ }
100
+
101
+ const ci = certInfo(ctx, cfg);
102
+ if (!ci.present || ci.error) add('FAIL', `certificate ${ci.file}: ${ci.error || 'missing'}`);
103
+ else if (ci.daysLeft < 0) add('FAIL', `certificate expired ${ci.validTo}`);
104
+ else add(ci.daysLeft < 14 ? 'WARN' : 'OK', `certificate: ${ci.daysLeft} days left (renew with \`bestgate server cert\`)`);
105
+
106
+ return { checks, ok: !checks.some((x) => x.level === 'FAIL') };
107
+ }
108
+
109
+ export async function runVerify(ctx, cfg) {
110
+ ctx.say(`verify (probes go to ${probeAddress(cfg)}:443 with the host name forced; outside DNS is checked separately)`);
111
+ const res = await verifyAll(ctx, cfg);
112
+ report(ctx, res.checks);
113
+ ctx.say(`RESULT: ${res.ok ? 'OK' : 'FAIL'}`);
114
+ return res;
115
+ }
116
+
117
+ // `bestgate server verify [--config <file>]`
118
+ export async function run(argv = [], opts = {}) {
119
+ const flags = parseFlags(argv, { '--config': 'value' });
120
+ const ctx = opts.ctx || createContext();
121
+ requireRoot(ctx);
122
+ const cfg = flags.config ? loadConfig(flags.config) : loadServerConfig(ctx);
123
+ openLog(ctx, 'verify');
124
+ const res = await runVerify(ctx, cfg);
125
+ if (!res.ok) throw new CliError('verify: some checks failed, see FAIL above');
126
+ return res;
127
+ }
@@ -0,0 +1,198 @@
1
+ // `bestgate server wizard` and the questions `server install` asks on a first run.
2
+ // Every answer is checked with validateConfig (the same rules the installer uses),
3
+ // so nothing invalid can be typed; with --answers <file> there are no questions at all.
4
+ import fs from 'node:fs';
5
+ import { isIP } from 'node:net';
6
+ import { CliError } from '../util.js';
7
+ import { DEFAULTS, validateConfig, saveConfig, loadConfig } from './config.js';
8
+ import { P, createContext, requireRoot, parseFlags } from './sys.js';
9
+ import { parseDump } from './nginx.js';
10
+
11
+ // Stand-ins so one field can be validated before the others are answered.
12
+ const PLACEHOLDER = { baseDomain: 'placeholder.example.com', publicIp: '203.0.113.1' };
13
+
14
+ function stripEmpty(a) {
15
+ const out = { ...a };
16
+ if (!out.baseDomain) delete out.baseDomain;
17
+ if (!out.publicIp) delete out.publicIp;
18
+ return out;
19
+ }
20
+
21
+ // The error for one field, or null. `answers` holds what was typed so far.
22
+ export function fieldError(field, value, answers = {}) {
23
+ const cand = { ...PLACEHOLDER, ...stripEmpty(answers), nginx: { ...(answers.nginx || {}) } };
24
+ if (field.startsWith('nginx.')) cand.nginx[field.slice(6)] = value;
25
+ else cand[field] = value;
26
+ try {
27
+ validateConfig(cand);
28
+ return null;
29
+ } catch (e) {
30
+ const lines = e.message.split('\n').slice(1).map((l) => l.replace(/^\s*-\s*/, ''));
31
+ // idleMinutes also decides whether pollSeconds is acceptable
32
+ const mine = lines.filter((l) => l.startsWith(field) || (field === 'idleMinutes' && l.startsWith('pollSeconds')));
33
+ return mine[0] || null;
34
+ }
35
+ }
36
+
37
+ // IPv4/IPv6 addresses nginx already listens on for port 443 (best effort, [] when unknown).
38
+ export function nginxListenIps(ctx) {
39
+ try {
40
+ const r = ctx.run('nginx', ['-T']);
41
+ if (r.code !== 0) return [];
42
+ const ips = new Set();
43
+ for (const s of parseDump(r.stdout || r.stderr).servers) {
44
+ for (const l of s.listens) if (l.port === 443 && isIP(l.addr)) ips.add(l.addr);
45
+ }
46
+ return [...ips].sort();
47
+ } catch {
48
+ return [];
49
+ }
50
+ }
51
+
52
+ function readAnswers(file) {
53
+ let obj;
54
+ try {
55
+ obj = JSON.parse(fs.readFileSync(file, 'utf8'));
56
+ } catch (e) {
57
+ throw new CliError(`Cannot read answers file ${file}: ${e instanceof SyntaxError ? 'not valid JSON' : e.code || e.message}`);
58
+ }
59
+ try {
60
+ return validateConfig(obj);
61
+ } catch (e) {
62
+ throw new CliError(`Answers file ${file}: ${e.message}`);
63
+ }
64
+ }
65
+
66
+ function startingPoint(configFile) {
67
+ if (configFile && fs.existsSync(configFile)) {
68
+ try { return loadConfig(configFile); } catch { /* start from the defaults */ }
69
+ }
70
+ return { ...DEFAULTS, ports: { ...DEFAULTS.ports }, nginx: { ...DEFAULTS.nginx }, checkUrls: [] };
71
+ }
72
+
73
+ const intOr = (v) => (/^\d+$/.test(v) ? Number(v) : v);
74
+ const lower = (v) => v.toLowerCase();
75
+
76
+ export function summary(cfg) {
77
+ return [
78
+ `base domain ${cfg.baseDomain} (tunnels: <name>.${cfg.baseDomain})`,
79
+ `control host ${cfg.controlLabel}.${cfg.baseDomain}`,
80
+ `nginx listen IP ${cfg.listenIp || '(not set)'}`,
81
+ `public IP ${cfg.publicIp}`,
82
+ `certbot account ${cfg.certbotAccount || '(default)'}`,
83
+ `idle timeout ${cfg.idleMinutes} min`,
84
+ `access expiry ${cfg.accessExpiryDays} days after last use`,
85
+ `tunnels per dev ${cfg.maxTunnelsPerUser} (at most ${cfg.maxClientsPerUser} running clients)`,
86
+ `bandwidth limit ${cfg.bandwidthLimit} per second per tunnel`,
87
+ `nginx limits ${cfg.nginx.reqPerSec} req/s (burst ${cfg.nginx.reqBurst}), ${cfg.nginx.connPerIp} connections per IP, ` +
88
+ `${cfg.nginx.loginPerMin} logins/min, body ${cfg.nginx.maxBody}, ${cfg.nginx.controlConnPerIp} control connections per IP, ` +
89
+ `${cfg.nginx.maxConnections} connections in all`,
90
+ `check URLs ${cfg.checkUrls.length ? cfg.checkUrls.join(', ') : '(none)'}`,
91
+ ];
92
+ }
93
+
94
+ /**
95
+ * -> the validated config. Writes it with saveConfig only when `save` is true.
96
+ * Options: answersFile, save, configFile (default PATHS.configFile),
97
+ * ctx (for detecting nginx addresses), prompts (the @inquirer/prompts API; tests inject a fake).
98
+ */
99
+ export async function runWizard({ answersFile = null, save = false, configFile, ctx, prompts } = {}) {
100
+ let cfg;
101
+ if (answersFile) cfg = readAnswers(answersFile);
102
+ else {
103
+ const p = prompts || (await import('@inquirer/prompts'));
104
+ cfg = await interview(p, startingPoint(configFile), ctx || createContext());
105
+ }
106
+ if (save) saveConfig(cfg, configFile);
107
+ return cfg;
108
+ }
109
+
110
+ async function interview(p, start, ctx) {
111
+ const a = { ...start, nginx: { ...start.nginx }, checkUrls: [...start.checkUrls] };
112
+ const getField = (field) => (field.startsWith('nginx.') ? a.nginx[field.slice(6)] : a[field]);
113
+ const setField = (field, value) => {
114
+ if (field.startsWith('nginx.')) a.nginx[field.slice(6)] = value;
115
+ else a[field] = value;
116
+ };
117
+
118
+ const ask = async (field, message, parse = (v) => v) => {
119
+ const cur = getField(field);
120
+ const text = await p.input({
121
+ message,
122
+ default: cur === undefined || cur === '' ? undefined : String(cur),
123
+ validate: (v) => fieldError(field, parse(v.trim()), a) || true,
124
+ });
125
+ const value = parse(text.trim());
126
+ setField(field, value);
127
+ return value;
128
+ };
129
+
130
+ console.log('Answer the questions; press Enter to accept the value in brackets.\n');
131
+ await ask('baseDomain', 'Base domain for tunnels (a wildcard DNS record *.<this> must point at the server):', lower);
132
+ await ask('controlLabel', 'Label of the control host (the client connects to <label>.<base domain>):');
133
+
134
+ const ips = nginxListenIps(ctx);
135
+ const listenQuestion = 'nginx listen IP for port 443 (empty = nginx listens on all addresses):';
136
+ if (ips.length) {
137
+ const pick = await p.select({
138
+ message: 'Address nginx listens on for HTTPS (port 443):',
139
+ default: ips.includes(a.listenIp) ? a.listenIp : undefined,
140
+ choices: [...ips.map((ip) => ({ name: ip, value: ip })), { name: 'Other (type it)', value: '' }],
141
+ });
142
+ if (pick) a.listenIp = pick;
143
+ else await ask('listenIp', listenQuestion, lower);
144
+ } else {
145
+ await ask('listenIp', listenQuestion, lower);
146
+ }
147
+
148
+ await ask('publicIp', 'Public IP address of this server (what the DNS records must resolve to):', lower);
149
+ await ask('certbotAccount', 'Existing certbot account id, 32 hex characters (empty = certbot decides):', lower);
150
+ await ask('idleMinutes', 'Close a tunnel after this many idle minutes:', intOr);
151
+ await ask('accessExpiryDays', 'A developer key expires after this many days without use:', intOr);
152
+ await ask('maxTunnelsPerUser', 'Maximum tunnels per developer:', intOr);
153
+ await ask('maxClientsPerUser', 'Maximum running clients (bestgate commands) per developer:', intOr);
154
+ await ask('bandwidthLimit', 'Bandwidth limit per tunnel, like 10MB or 500KB (per second):');
155
+
156
+ const d = DEFAULTS.nginx;
157
+ const useDefaults = await p.confirm({
158
+ message: `Use the default nginx limits (${d.reqPerSec} req/s, burst ${d.reqBurst}, ${d.connPerIp} connections per IP, ` +
159
+ `${d.loginPerMin} logins/min, body ${d.maxBody}, ${d.controlConnPerIp} control connections per IP, ${d.maxConnections} connections in all)?`,
160
+ default: Object.keys(d).every((k) => a.nginx[k] === d[k]),
161
+ });
162
+ if (useDefaults) a.nginx = { ...d };
163
+ else {
164
+ await ask('nginx.reqPerSec', 'Requests per second per client IP:', intOr);
165
+ await ask('nginx.reqBurst', 'Burst size of extra requests:', intOr);
166
+ await ask('nginx.connPerIp', 'Simultaneous connections per client IP:', intOr);
167
+ await ask('nginx.loginPerMin', 'Control-channel logins per minute per client IP:', intOr);
168
+ await ask('nginx.maxBody', 'Largest request body, like 100m, 512k or 1g:', lower);
169
+ await ask('nginx.controlConnPerIp', 'Open control connections (running clients) per client IP:', intOr);
170
+ await ask('nginx.maxConnections', 'Connections to all tunnels together (the nginx pool is shared with the other sites):', intOr);
171
+ }
172
+
173
+ const list = (v) => v.split(',').map((s) => s.trim()).filter(Boolean);
174
+ const text = await p.input({
175
+ message: 'Other sites on this server that must keep answering, https URLs separated by commas (optional):',
176
+ default: a.checkUrls.length ? a.checkUrls.join(', ') : undefined,
177
+ validate: (v) => fieldError('checkUrls', list(v), a) || true,
178
+ });
179
+ a.checkUrls = list(text);
180
+
181
+ const cfg = validateConfig(a);
182
+ console.log('\nThis is what will be configured:\n');
183
+ for (const l of summary(cfg)) console.log(` ${l}`);
184
+ console.log('');
185
+ if (!(await p.confirm({ message: 'Is this right?', default: true }))) throw new CliError('Cancelled. Nothing was saved.');
186
+ return cfg;
187
+ }
188
+
189
+ // `bestgate server wizard [--answers <file>]`
190
+ export async function run(argv = [], opts = {}) {
191
+ const flags = parseFlags(argv, { '--answers': 'value' });
192
+ const ctx = opts.ctx || createContext();
193
+ requireRoot(ctx);
194
+ const cfg = await runWizard({ answersFile: flags.answers || null, save: true, configFile: ctx.disk(P.configFile), ctx, prompts: opts.prompts });
195
+ ctx.say(`Saved ${P.configFile} for ${cfg.baseDomain}.`);
196
+ ctx.say('Next: `bestgate server cert`, then `bestgate server install`.');
197
+ return cfg;
198
+ }