@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,237 @@
|
|
|
1
|
+
// Pure decision functions: no I/O, time passed in. Every reject reason starts with a REASONS value.
|
|
2
|
+
import { timingSafeEqual } from 'node:crypto';
|
|
3
|
+
import { REASONS } from '../reasons.js';
|
|
4
|
+
import { NAME_RE, SECRET_RE, hashSecret } from '../key.js';
|
|
5
|
+
|
|
6
|
+
export const DAY_MS = 24 * 60 * 60 * 1000;
|
|
7
|
+
const SUBDOMAIN_RE = /^[a-z0-9-]{3,32}$/;
|
|
8
|
+
const HASH_RE = /^[0-9a-f]{64}$/;
|
|
9
|
+
// frps assigns every run_id itself: util.RandID() = 16 lowercase hex characters
|
|
10
|
+
// (frp v0.72.0 pkg/util/util/util.go:31, server/service.go:872). frpc only ever sends
|
|
11
|
+
// back the one it got, so anything else did not come from a real frpc session.
|
|
12
|
+
export const RUN_ID_RE = /^[0-9a-f]{16}$/;
|
|
13
|
+
// Log only a prefix: a full run_id is enough to address that client's control session.
|
|
14
|
+
export const shortRun = (runId) => (typeof runId === 'string' && RUN_ID_RE.test(runId) ? runId.slice(0, 6) : '-');
|
|
15
|
+
|
|
16
|
+
const allow = (extra) => ({ allow: true, ...extra });
|
|
17
|
+
// close: the session must be closed with this reason, so the re-login gets the same answer.
|
|
18
|
+
const reject = (reason, detail = '', close = false) => ({ allow: false, reason: reason + detail, base: reason, close });
|
|
19
|
+
|
|
20
|
+
const isClosed = (session) => Boolean(session && session.closed_reason);
|
|
21
|
+
const closedReason = (session) =>
|
|
22
|
+
Object.values(REASONS).includes(session.closed_reason) ? session.closed_reason : REASONS.REVOKED;
|
|
23
|
+
|
|
24
|
+
function keyMatches(secret, storedHash) {
|
|
25
|
+
if (typeof secret !== 'string' || !SECRET_RE.test(secret)) return false;
|
|
26
|
+
if (typeof storedHash !== 'string' || !HASH_RE.test(storedHash)) return false;
|
|
27
|
+
return timingSafeEqual(Buffer.from(hashSecret(secret), 'hex'), Buffer.from(storedHash, 'hex'));
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// null when the user may use the server, else 'unknown' | 'badkey' | 'revoked' | 'expired'.
|
|
31
|
+
export function userProblem(user, secret, now, config) {
|
|
32
|
+
if (!user) return 'unknown';
|
|
33
|
+
if (!keyMatches(secret, user.key_hash)) return 'badkey';
|
|
34
|
+
if (user.revoked_at != null) return 'revoked';
|
|
35
|
+
if (!(now - user.last_used_at <= config.accessExpiryDays * DAY_MS)) return 'expired';
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const metaKey = (metas) => (metas && typeof metas === 'object' && typeof metas.key === 'string' ? metas.key : null);
|
|
40
|
+
|
|
41
|
+
// Login content: {user, metas:{key}, run_id, ...}. run_id is empty on frpc's first login;
|
|
42
|
+
// a non-empty one is a reconnect and must be a session this daemon already knows for the
|
|
43
|
+
// same user (sessions are created at the first Ping/NewProxy of an accepted login, never
|
|
44
|
+
// at Login). An unknown one (forgotten after a day, or never real) gets the idle answer,
|
|
45
|
+
// so the client stops and says "run the same command again".
|
|
46
|
+
// user/session are DB rows (or null) looked up by the caller for content.user / content.run_id.
|
|
47
|
+
export function decideLogin({ content, user, session, now, config }) {
|
|
48
|
+
if (!content || typeof content !== 'object') return reject(REASONS.INVALID_KEY);
|
|
49
|
+
const name = content.user;
|
|
50
|
+
if (typeof name !== 'string' || !NAME_RE.test(name)) return reject(REASONS.INVALID_KEY);
|
|
51
|
+
const runId = content.run_id ?? '';
|
|
52
|
+
if (runId !== '' && !(typeof runId === 'string' && RUN_ID_RE.test(runId))) return reject(REASONS.INVALID_KEY);
|
|
53
|
+
if (session && (session.user !== name || session.run_id !== runId)) return reject(REASONS.INVALID_KEY);
|
|
54
|
+
if (isClosed(session)) return reject(closedReason(session));
|
|
55
|
+
if (user && user.name !== name) return reject(REASONS.INVALID_KEY);
|
|
56
|
+
switch (userProblem(user, metaKey(content.metas), now, config)) {
|
|
57
|
+
case null: return runId && !session ? reject(REASONS.IDLE, ' (session unknown)') : allow();
|
|
58
|
+
case 'revoked': return reject(REASONS.REVOKED);
|
|
59
|
+
case 'expired': return reject(REASONS.EXPIRED);
|
|
60
|
+
default: return reject(REASONS.INVALID_KEY);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// Checks shared by Ping and NewProxy: content.user = {user, metas, run_id} of a session frps accepted.
|
|
65
|
+
function checkSessionUser({ content, user, session, now, config }) {
|
|
66
|
+
const u = content && content.user;
|
|
67
|
+
if (!u || typeof u !== 'object' || typeof u.user !== 'string' || !NAME_RE.test(u.user)) {
|
|
68
|
+
return reject(REASONS.INVALID_KEY);
|
|
69
|
+
}
|
|
70
|
+
if (typeof u.run_id !== 'string' || !RUN_ID_RE.test(u.run_id)) return reject(REASONS.INVALID_KEY);
|
|
71
|
+
if (session && (session.user !== u.user || session.run_id !== u.run_id)) return reject(REASONS.INVALID_KEY);
|
|
72
|
+
if (isClosed(session)) return reject(closedReason(session));
|
|
73
|
+
if (user && user.name !== u.user) return reject(REASONS.INVALID_KEY);
|
|
74
|
+
// The key passed at Login; a mismatch now means it was re-issued, or the user was removed.
|
|
75
|
+
switch (userProblem(user, metaKey(u.metas), now, config)) {
|
|
76
|
+
case null: return null;
|
|
77
|
+
case 'expired': return reject(REASONS.EXPIRED, '', true);
|
|
78
|
+
default: return reject(REASONS.REVOKED, '', true);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function decidePing(args) {
|
|
83
|
+
return checkSessionUser(args) || allow();
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function checkSubdomain(sub, controlLabel) {
|
|
87
|
+
return typeof sub === 'string' && SUBDOMAIN_RE.test(sub) && !sub.startsWith('-') && !sub.endsWith('-') &&
|
|
88
|
+
sub !== controlLabel;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const emptyList = (v) => v == null || (Array.isArray(v) && v.length === 0);
|
|
92
|
+
const isStringMap = (v) => v && typeof v === 'object' && !Array.isArray(v) &&
|
|
93
|
+
Object.entries(v).every(([k, x]) => typeof k === 'string' && typeof x === 'string');
|
|
94
|
+
|
|
95
|
+
// NewProxy fields a tunnel may set itself. Everything else is fixed by the daemon or left
|
|
96
|
+
// out. frps routes HTTP by (domain, location, httpUser) with the longest location and an
|
|
97
|
+
// exact httpUser winning (pkg/util/vhost/router.go), so locations / route_by_http_user
|
|
98
|
+
// would let one developer take paths or Basic-auth users of another's subdomain.
|
|
99
|
+
const PASS_STRINGS = ['http_user', 'http_pwd', 'host_header_rewrite'];
|
|
100
|
+
const PASS_BOOLS = ['use_encryption', 'use_compression'];
|
|
101
|
+
const PASS_MAPS = ['headers', 'response_headers'];
|
|
102
|
+
|
|
103
|
+
// onlineCount: tunnels this user already has (online in frps plus granted moments ago), excluding this one.
|
|
104
|
+
export function decideNewProxy({ content, user, session, onlineCount, now, config }) {
|
|
105
|
+
const bad = checkSessionUser({ content, user, session, now, config });
|
|
106
|
+
if (bad) return bad;
|
|
107
|
+
const name = content.user.user;
|
|
108
|
+
if (content.proxy_type !== 'http') return reject(REASONS.HTTP_ONLY);
|
|
109
|
+
// frpc builds the wire name as "<user>.<name>" (pkg/naming/names.go), but frps takes
|
|
110
|
+
// whatever name the client sends (pkg/config/v1/proxy.go UnmarshalFromMsg), so a client
|
|
111
|
+
// could otherwise register "alice.web" first and block alice's own tunnel.
|
|
112
|
+
const pn = content.proxy_name;
|
|
113
|
+
if (typeof pn !== 'string' || pn.length > 128 || !pn.startsWith(`${name}.`) || pn.length === name.length + 1) {
|
|
114
|
+
return reject(REASONS.BAD_SUBDOMAIN, ' (bad proxy name)');
|
|
115
|
+
}
|
|
116
|
+
if (!emptyList(content.custom_domains)) return reject(REASONS.BAD_SUBDOMAIN);
|
|
117
|
+
if (!emptyList(content.locations)) return reject(REASONS.BAD_SUBDOMAIN, ' (locations are not allowed)');
|
|
118
|
+
if (!(content.route_by_http_user == null || content.route_by_http_user === '')) {
|
|
119
|
+
return reject(REASONS.BAD_SUBDOMAIN, ' (route by http user is not allowed)');
|
|
120
|
+
}
|
|
121
|
+
if (!checkSubdomain(content.subdomain, config.controlLabel)) return reject(REASONS.BAD_SUBDOMAIN);
|
|
122
|
+
if (!Number.isInteger(onlineCount) || onlineCount >= config.maxTunnelsPerUser) {
|
|
123
|
+
return reject(REASONS.TUNNEL_LIMIT, ` (${config.maxTunnelsPerUser})`);
|
|
124
|
+
}
|
|
125
|
+
// frps replaces the whole NewProxy message with what we return, so it is built from an
|
|
126
|
+
// allow-list: frps reads only the NewProxy part back (server/control.go handleNewProxy).
|
|
127
|
+
const out = {
|
|
128
|
+
proxy_name: pn,
|
|
129
|
+
proxy_type: 'http',
|
|
130
|
+
subdomain: content.subdomain,
|
|
131
|
+
custom_domains: [],
|
|
132
|
+
locations: [],
|
|
133
|
+
route_by_http_user: '',
|
|
134
|
+
bandwidth_limit: config.bandwidthLimit,
|
|
135
|
+
bandwidth_limit_mode: 'server',
|
|
136
|
+
group: '',
|
|
137
|
+
group_key: '',
|
|
138
|
+
};
|
|
139
|
+
for (const k of PASS_STRINGS) if (typeof content[k] === 'string') out[k] = content[k];
|
|
140
|
+
for (const k of PASS_BOOLS) if (typeof content[k] === 'boolean') out[k] = content[k];
|
|
141
|
+
for (const k of PASS_MAPS) if (isStringMap(content[k])) out[k] = { ...content[k] };
|
|
142
|
+
return allow({ content: out });
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// Idle clocks pause while the daemon cannot see frps (daemon down, API failing):
|
|
146
|
+
// returns how far to move open sessions' last_activity_at forward.
|
|
147
|
+
export function gapShift(lastPollAt, now, pollMs) {
|
|
148
|
+
if (!Number.isFinite(lastPollAt) || lastPollAt <= 0) return 0;
|
|
149
|
+
const gap = now - lastPollAt;
|
|
150
|
+
return gap > 3 * pollMs ? Math.round(gap - pollMs) : 0;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const num = (v) => (Number.isFinite(v) && v >= 0 ? v : 0);
|
|
154
|
+
|
|
155
|
+
function parseTraffic(s) {
|
|
156
|
+
try {
|
|
157
|
+
const o = JSON.parse(s);
|
|
158
|
+
return o && typeof o === 'object' && !Array.isArray(o) ? o : {};
|
|
159
|
+
} catch {
|
|
160
|
+
return {};
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// One poll of the frps dashboard API.
|
|
165
|
+
// sessions: all session rows (open and closed)
|
|
166
|
+
// proxies: /api/proxy/http .proxies [{name, user, clientID, todayTrafficIn, todayTrafficOut, curConns, status}]
|
|
167
|
+
// clients: /api/clients [{user, clientID, runID, online}]
|
|
168
|
+
// A proxy's clientID is the frpc clientID, or its run_id when frpc sets none;
|
|
169
|
+
// /api/clients maps user+clientID to the current run_id.
|
|
170
|
+
// A session is active when any of its online tunnels has open connections, is new,
|
|
171
|
+
// or its traffic counters grew. A counter that went down (daily reset, frps restart)
|
|
172
|
+
// only resets the baseline. Returns what the caller should write.
|
|
173
|
+
export function evaluatePoll({ sessions, proxies, clients, now, config }) {
|
|
174
|
+
const idleMs = config.idleMinutes * 60 * 1000;
|
|
175
|
+
const runOf = new Map();
|
|
176
|
+
for (const c of Array.isArray(clients) ? clients : []) {
|
|
177
|
+
if (c && c.online && typeof c.user === 'string' && typeof c.clientID === 'string' && typeof c.runID === 'string' && c.runID) {
|
|
178
|
+
runOf.set(`${c.user}\n${c.clientID}`, c.runID);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
const byRun = new Map();
|
|
182
|
+
for (const p of Array.isArray(proxies) ? proxies : []) {
|
|
183
|
+
if (!p || p.status !== 'online' || typeof p.name !== 'string' || typeof p.user !== 'string') continue;
|
|
184
|
+
if (typeof p.clientID !== 'string' || !p.clientID) continue;
|
|
185
|
+
const runId = runOf.get(`${p.user}\n${p.clientID}`) || p.clientID;
|
|
186
|
+
if (!byRun.has(runId)) byRun.set(runId, { user: p.user, list: [] });
|
|
187
|
+
const entry = byRun.get(runId);
|
|
188
|
+
if (entry.user !== p.user) continue;
|
|
189
|
+
entry.list.push({ name: p.name, in: num(p.todayTrafficIn), out: num(p.todayTrafficOut), conns: num(p.curConns) });
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
const result = { active: [], idle: [], baseline: [], close: [], create: [], touch: new Set() };
|
|
193
|
+
const known = new Set();
|
|
194
|
+
for (const s of Array.isArray(sessions) ? sessions : []) {
|
|
195
|
+
known.add(s.run_id);
|
|
196
|
+
if (s.closed_reason) continue;
|
|
197
|
+
const entry = byRun.get(s.run_id);
|
|
198
|
+
const list = entry && entry.user === s.user ? entry.list : [];
|
|
199
|
+
const prev = parseTraffic(s.traffic);
|
|
200
|
+
const traffic = JSON.stringify(Object.fromEntries(list.map((t) => [t.name, [t.in, t.out]])));
|
|
201
|
+
const isActive = list.some((t) => {
|
|
202
|
+
const was = prev[t.name];
|
|
203
|
+
return t.conns > 0 || !Array.isArray(was) || t.in > was[0] || t.out > was[1];
|
|
204
|
+
});
|
|
205
|
+
if (isActive) {
|
|
206
|
+
result.active.push({ run_id: s.run_id, traffic });
|
|
207
|
+
result.touch.add(s.user);
|
|
208
|
+
} else if (now - s.last_activity_at >= idleMs) {
|
|
209
|
+
result.close.push({ run_id: s.run_id, user: s.user, reason: REASONS.IDLE });
|
|
210
|
+
} else if (traffic !== s.traffic) {
|
|
211
|
+
result.baseline.push({ run_id: s.run_id, traffic });
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
// Online tunnels of a run_id the daemon has never seen (e.g. database restored): adopt them.
|
|
215
|
+
for (const [runId, entry] of byRun) {
|
|
216
|
+
if (known.has(runId) || !NAME_RE.test(entry.user) || !RUN_ID_RE.test(runId)) continue;
|
|
217
|
+
const traffic = JSON.stringify(Object.fromEntries(entry.list.map((t) => [t.name, [t.in, t.out]])));
|
|
218
|
+
result.create.push({ run_id: runId, user: entry.user, traffic });
|
|
219
|
+
result.touch.add(entry.user);
|
|
220
|
+
}
|
|
221
|
+
result.touch = [...result.touch];
|
|
222
|
+
return result;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// Counts a user's tunnels for the limit: online in frps, plus ones granted in the last
|
|
226
|
+
// moments that frps does not list yet. `pending` = [{name, user, at}].
|
|
227
|
+
export function countTunnels({ proxies, pending, user, proxyName, now, graceMs = 15000 }) {
|
|
228
|
+
const online = new Set();
|
|
229
|
+
for (const p of Array.isArray(proxies) ? proxies : []) {
|
|
230
|
+
if (p && p.status === 'online' && p.user === user && p.name !== proxyName) online.add(p.name);
|
|
231
|
+
}
|
|
232
|
+
let n = online.size;
|
|
233
|
+
for (const g of pending) {
|
|
234
|
+
if (g.user === user && g.name !== proxyName && !online.has(g.name) && now - g.at < graceMs) n++;
|
|
235
|
+
}
|
|
236
|
+
return n;
|
|
237
|
+
}
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
// Templates → file contents. Every value comes from validateConfig output or from
|
|
2
|
+
// fixed paths, and is checked again here before it reaches a root-owned file.
|
|
3
|
+
import { readFileSync } from 'node:fs';
|
|
4
|
+
import { isIPv6 } from 'node:net';
|
|
5
|
+
import { validateConfig } from './config.js';
|
|
6
|
+
import { P, UNITS, DAEMON_USER, SAFE_PATH_RE, certFiles, versionAtLeast } from './sys.js';
|
|
7
|
+
|
|
8
|
+
const TEMPLATE_DIR = new URL('./templates/', import.meta.url);
|
|
9
|
+
export const TEMPLATES = Object.freeze([
|
|
10
|
+
'frps.toml', 'frps.service', 'bestgate-auth.service', 'bestgate-check.service', 'bestgate-check.timer',
|
|
11
|
+
'nginx.conf.template', 'motd.sh',
|
|
12
|
+
]);
|
|
13
|
+
|
|
14
|
+
const PLACEHOLDER = /__([A-Z][A-Z0-9_]*)__/g;
|
|
15
|
+
// No control characters (newline would start a new directive), no braces or quotes.
|
|
16
|
+
const BAD_VALUE = /[\x00-\x1f\x7f{}"'`]/;
|
|
17
|
+
|
|
18
|
+
function checkValue(key, v) {
|
|
19
|
+
if (typeof v === 'number') {
|
|
20
|
+
if (!Number.isSafeInteger(v) || v < 0) throw new Error(`template value ${key} is not a non-negative integer`);
|
|
21
|
+
return String(v);
|
|
22
|
+
}
|
|
23
|
+
if (typeof v !== 'string' || v === '') throw new Error(`template value ${key} must be a non-empty string or an integer`);
|
|
24
|
+
if (BAD_VALUE.test(v)) throw new Error(`template value ${key} contains a forbidden character`);
|
|
25
|
+
return v;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// Fill __NAME__ placeholders. Throws if one has no value, or a value is never used.
|
|
29
|
+
export function fillTemplate(text, vars, name = 'template') {
|
|
30
|
+
const missing = new Set();
|
|
31
|
+
const used = new Set();
|
|
32
|
+
const out = text.replace(PLACEHOLDER, (m, k) => {
|
|
33
|
+
if (!Object.hasOwn(vars, k)) { missing.add(k); return m; }
|
|
34
|
+
used.add(k);
|
|
35
|
+
return checkValue(k, vars[k]);
|
|
36
|
+
});
|
|
37
|
+
if (missing.size) throw new Error(`${name}: no value for ${[...missing].join(', ')}`);
|
|
38
|
+
const unused = Object.keys(vars).filter((k) => !used.has(k));
|
|
39
|
+
if (unused.length) throw new Error(`${name}: values not used: ${unused.join(', ')}`);
|
|
40
|
+
return out;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function renderTemplate(name, vars) {
|
|
44
|
+
if (!TEMPLATES.includes(name)) throw new Error(`unknown template ${name}`);
|
|
45
|
+
const text = readFileSync(new URL(name, TEMPLATE_DIR), 'utf8');
|
|
46
|
+
return fillTemplate(text, vars, name);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const safePath = (what, p) => {
|
|
50
|
+
if (typeof p !== 'string' || !SAFE_PATH_RE.test(p)) throw new Error(`${what} path ${JSON.stringify(p)} is not a plain absolute path`);
|
|
51
|
+
return p;
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
// Validated domain → the regex body for nginx: only a-z 0-9 - and escaped dots.
|
|
55
|
+
export function escapeDomainRegex(domain) {
|
|
56
|
+
const out = domain.replace(/\./g, '\\.');
|
|
57
|
+
if (!/^[a-z0-9-]+(\\\.[a-z0-9-]+)+$/.test(out)) throw new Error('cannot escape base domain');
|
|
58
|
+
return out;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// nginx >= 1.25.1 has the per-server `http2 on;`. Older versions only know `listen ... http2`,
|
|
62
|
+
// which switches the whole address:port for every site, so then http2 is left to the others.
|
|
63
|
+
export function http2Line(version) {
|
|
64
|
+
return version && versionAtLeast(version, '1.25.1')
|
|
65
|
+
? 'http2 on;'
|
|
66
|
+
: '# http2 is a listen-socket option before nginx 1.25.1: left to the other sites';
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* cfg: config (validated again here); facts: { nginxVersion, nodePath, binScript }
|
|
71
|
+
* → { [template name]: vars }
|
|
72
|
+
*/
|
|
73
|
+
export function templateVars(cfg, facts) {
|
|
74
|
+
const c = validateConfig(cfg);
|
|
75
|
+
if (!c.listenIp) throw new Error('listenIp is empty: set the address nginx listens on for 443');
|
|
76
|
+
const node = safePath('node', facts.nodePath);
|
|
77
|
+
const bin = safePath('bestgate script', facts.binScript);
|
|
78
|
+
const cert = certFiles(c.baseDomain);
|
|
79
|
+
return {
|
|
80
|
+
'frps.toml': {
|
|
81
|
+
CONTROL_PORT: c.ports.control,
|
|
82
|
+
VHOST_PORT: c.ports.vhost,
|
|
83
|
+
DASHBOARD_PORT: c.ports.dashboard,
|
|
84
|
+
DAEMON_PORT: c.ports.daemon,
|
|
85
|
+
BASE_DOMAIN: c.baseDomain,
|
|
86
|
+
},
|
|
87
|
+
'frps.service': {
|
|
88
|
+
AUTH_UNIT: UNITS.auth,
|
|
89
|
+
ENV_FILE: P.envFile,
|
|
90
|
+
FRPS_BIN: P.frpsBin,
|
|
91
|
+
FRPS_TOML: P.frpsToml,
|
|
92
|
+
},
|
|
93
|
+
'bestgate-auth.service': {
|
|
94
|
+
FRPS_UNIT: UNITS.frps,
|
|
95
|
+
DAEMON_USER,
|
|
96
|
+
DAEMON_ENV_FILE: P.daemonEnvFile,
|
|
97
|
+
NODE: node,
|
|
98
|
+
BIN_SCRIPT: bin,
|
|
99
|
+
CONFIG_FILE: P.configFile,
|
|
100
|
+
STATE_DIR: P.stateDir,
|
|
101
|
+
ORIG_DIR: P.origDir,
|
|
102
|
+
},
|
|
103
|
+
'bestgate-check.service': {
|
|
104
|
+
NODE: node, BIN_SCRIPT: bin, LOG_DIR: P.logDir, STATE_DIR: P.stateDir, ORIG_DIR: P.origDir,
|
|
105
|
+
ENV_FILE: P.envFile, DAEMON_ENV_FILE: P.daemonEnvFile,
|
|
106
|
+
},
|
|
107
|
+
'bestgate-check.timer': { CHECK_UNIT: UNITS.check },
|
|
108
|
+
'nginx.conf.template': {
|
|
109
|
+
BASE_DOMAIN: c.baseDomain,
|
|
110
|
+
BASE_REGEX: escapeDomainRegex(c.baseDomain),
|
|
111
|
+
CONTROL_HOST: `${c.controlLabel}.${c.baseDomain}`,
|
|
112
|
+
LISTEN_ADDR: isIPv6(c.listenIp) ? `[${c.listenIp}]` : c.listenIp,
|
|
113
|
+
HTTP2: http2Line(facts.nginxVersion),
|
|
114
|
+
CERT_FULLCHAIN: cert.fullchain,
|
|
115
|
+
CERT_PRIVKEY: cert.privkey,
|
|
116
|
+
NGINX_LOG_DIR: P.nginxLogDir,
|
|
117
|
+
CONTROL_PORT: c.ports.control,
|
|
118
|
+
VHOST_PORT: c.ports.vhost,
|
|
119
|
+
REQ_PER_SEC: c.nginx.reqPerSec,
|
|
120
|
+
REQ_BURST: c.nginx.reqBurst,
|
|
121
|
+
// burst= is where nginx starts to refuse; delay= (REQ_BURST) is where it starts to hold.
|
|
122
|
+
REQ_BURST_TOTAL: c.nginx.reqBurst + c.nginx.connPerIp,
|
|
123
|
+
CONN_PER_IP: c.nginx.connPerIp,
|
|
124
|
+
CONTROL_CONN_PER_IP: c.nginx.controlConnPerIp,
|
|
125
|
+
MAX_CONNECTIONS: c.nginx.maxConnections,
|
|
126
|
+
LOGIN_PER_MIN: c.nginx.loginPerMin,
|
|
127
|
+
MAX_BODY: c.nginx.maxBody,
|
|
128
|
+
},
|
|
129
|
+
'motd.sh': { CHECK_FILE: P.checkFile, TIMER_UNIT: UNITS.timer },
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function renderAll(cfg, facts) {
|
|
134
|
+
const vars = templateVars(cfg, facts);
|
|
135
|
+
const out = {};
|
|
136
|
+
for (const name of TEMPLATES) out[name] = renderTemplate(name, vars[name]);
|
|
137
|
+
const toml = out['frps.toml'];
|
|
138
|
+
// frps treats "{{" as a Go template anywhere in the file: exactly the three env secrets.
|
|
139
|
+
if ((toml.match(/\{\{/g) || []).length !== 3) throw new Error('frps.toml must contain exactly three template expressions');
|
|
140
|
+
return out;
|
|
141
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
// `bestgate server revert [--dry-run] [--purge] [--yes]`
|
|
2
|
+
// Undoes what the manifest says install did, and nothing else: stops and disables the
|
|
3
|
+
// units, removes the nginx site (nginx -t before the reload, put back if it fails),
|
|
4
|
+
// restores saved originals, removes units, binary and motd snippet.
|
|
5
|
+
// Kept unless --purge: /etc/bestgate (secrets, config), the database, the daemon user.
|
|
6
|
+
// The certificate is never deleted; the certbot command for that is printed.
|
|
7
|
+
import { CliError } from '../util.js';
|
|
8
|
+
import { P, UNITS, DAEMON_USER, createContext, openLog, requireRoot, askConfirm, parseFlags } from './sys.js';
|
|
9
|
+
import { loadManifest, saveManifest } from './manifest.js';
|
|
10
|
+
import { loadServerConfig } from './plan.js';
|
|
11
|
+
|
|
12
|
+
function removeNginxSite(ctx, m) {
|
|
13
|
+
const site = m.entries.filter((e) => e.path.startsWith(`${P.nginxDir}/`) && (e.kind === 'file' || e.kind === 'link'));
|
|
14
|
+
if (!site.length) return;
|
|
15
|
+
ctx.say('nginx');
|
|
16
|
+
const saved = site.map((e) => ({
|
|
17
|
+
e,
|
|
18
|
+
exists: ctx.exists(e.path),
|
|
19
|
+
content: e.kind === 'file' ? ctx.readOrNull(e.path) : null,
|
|
20
|
+
target: e.kind === 'link' && ctx.isLink(e.path) ? ctx.links.readlink(ctx.disk(e.path)) : null,
|
|
21
|
+
}));
|
|
22
|
+
// Links first, so nginx never sees a dangling link.
|
|
23
|
+
const order = [...saved].sort((a, b) => (a.e.kind === 'link' ? -1 : 0) - (b.e.kind === 'link' ? -1 : 0));
|
|
24
|
+
let removed = false;
|
|
25
|
+
for (const s of order) {
|
|
26
|
+
if (s.e.orig) continue; // restored with the other originals below
|
|
27
|
+
removed = ctx.removeFile(s.e.path) || removed;
|
|
28
|
+
}
|
|
29
|
+
if (!removed) { ctx.say(' nginx site already gone'); return; }
|
|
30
|
+
if (ctx.dryRun) { ctx.say(' would run: nginx -t, then systemctl reload nginx'); return; }
|
|
31
|
+
const t = ctx.run('nginx', ['-t']);
|
|
32
|
+
if (t.code !== 0) {
|
|
33
|
+
for (const s of [...order].reverse()) {
|
|
34
|
+
if (!s.exists || s.e.orig) continue;
|
|
35
|
+
if (s.content !== null) ctx.writeFile(s.e.path, s.content, { mode: 0o644 });
|
|
36
|
+
else if (s.target) ctx.links.symlink(s.target, ctx.disk(s.e.path));
|
|
37
|
+
}
|
|
38
|
+
throw new CliError(`nginx -t fails without the bestgate site, so it was put back and nginx was not reloaded:\n${t.stderr.trim()}\n` +
|
|
39
|
+
'The failure is elsewhere in the nginx configuration; fix it, then run revert again.');
|
|
40
|
+
}
|
|
41
|
+
if (ctx.run('systemctl', ['is-active', 'nginx']).stdout.trim() === 'active') ctx.change('systemctl', ['reload', 'nginx']);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// Plain files of one known directory (never recursive beyond one level, never from config).
|
|
45
|
+
function removeFilesIn(ctx, dir) {
|
|
46
|
+
for (const name of ctx.list(dir) || []) {
|
|
47
|
+
const p = `${dir}/${name}`;
|
|
48
|
+
if (!ctx.isLink(p) && ctx.list(p) !== null) {
|
|
49
|
+
for (const sub of ctx.list(p)) ctx.removeFile(`${p}/${sub}`);
|
|
50
|
+
ctx.removeDir(p);
|
|
51
|
+
} else ctx.removeFile(p);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export async function revert(ctx, m, { purge }) {
|
|
56
|
+
ctx.say('services');
|
|
57
|
+
for (const u of [UNITS.timer, UNITS.frps, UNITS.auth, UNITS.check]) {
|
|
58
|
+
if (m.entries.some((e) => e.path === `${P.systemdDir}/${u}`)) ctx.change('systemctl', ['disable', '--now', u], { allowFail: true });
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
removeNginxSite(ctx, m);
|
|
62
|
+
|
|
63
|
+
ctx.say('files');
|
|
64
|
+
const rev = [...m.entries].reverse();
|
|
65
|
+
for (const e of rev.filter((x) => x.kind === 'file' || x.kind === 'link')) {
|
|
66
|
+
if (e.orig) {
|
|
67
|
+
ctx.say(` restore ${e.path} from ${e.orig}`);
|
|
68
|
+
ctx.copyFile(e.orig, e.path, e.origMode ?? 0o644);
|
|
69
|
+
} else if (e.keep && !purge) ctx.say(` kept ${e.path}`);
|
|
70
|
+
else ctx.removeFile(e.path);
|
|
71
|
+
}
|
|
72
|
+
if (rev.some((e) => e.path.startsWith(`${P.systemdDir}/`))) {
|
|
73
|
+
ctx.change('systemctl', ['daemon-reload']);
|
|
74
|
+
ctx.change('systemctl', ['reset-failed', UNITS.frps, UNITS.auth, UNITS.check], { allowFail: true });
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
if (purge) {
|
|
78
|
+
ctx.say('purge');
|
|
79
|
+
for (const f of [P.dbFile, `${P.dbFile}-wal`, `${P.dbFile}-shm`, P.configFile, P.envFile, P.daemonEnvFile]) ctx.removeFile(f);
|
|
80
|
+
removeFilesIn(ctx, P.cacheDir);
|
|
81
|
+
ctx.logFile = null; // the log directory goes too
|
|
82
|
+
for (const f of ctx.list(P.logDir) || []) ctx.removeFile(`${P.logDir}/${f}`);
|
|
83
|
+
for (const e of m.entries) if (e.orig) ctx.removeFile(e.orig);
|
|
84
|
+
ctx.removeFile(P.manifestFile);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
for (const e of rev.filter((x) => x.kind === 'dir')) {
|
|
88
|
+
if (e.keep && !purge) ctx.say(` kept ${e.path}`);
|
|
89
|
+
else ctx.removeDir(e.path);
|
|
90
|
+
}
|
|
91
|
+
if (purge) ctx.removeDir(P.etcDir);
|
|
92
|
+
if (rev.some((e) => e.kind === 'user')) {
|
|
93
|
+
if (purge) ctx.change('userdel', [DAEMON_USER], { allowFail: true });
|
|
94
|
+
else ctx.say(` kept system user ${DAEMON_USER} (it owns the database)`);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
if (!purge) {
|
|
98
|
+
// What is left is still ours: a later install reuses it, a later --purge removes it.
|
|
99
|
+
const left = { ...m, entries: m.entries.filter((e) => !e.orig && e.keep), fingerprint: null, revertedAt: new Date(ctx.now()).toISOString() };
|
|
100
|
+
saveManifest(ctx, left);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export async function run(argv = [], opts = {}) {
|
|
105
|
+
const flags = parseFlags(argv, { '--dry-run': 'flag', '--purge': 'flag', '--yes': 'flag' });
|
|
106
|
+
const ctx = opts.ctx || createContext({ dryRun: flags.dryRun });
|
|
107
|
+
ctx.dryRun = !!flags.dryRun;
|
|
108
|
+
requireRoot(ctx);
|
|
109
|
+
openLog(ctx, 'revert');
|
|
110
|
+
const m = loadManifest(ctx);
|
|
111
|
+
if (!m) {
|
|
112
|
+
ctx.say(`No bestgate install found (${P.manifestFile} is missing): nothing to revert.`);
|
|
113
|
+
return { nothing: true };
|
|
114
|
+
}
|
|
115
|
+
let base = null;
|
|
116
|
+
try { base = loadServerConfig(ctx).baseDomain; } catch { /* config may be gone */ }
|
|
117
|
+
ctx.say(`bestgate server revert${ctx.dryRun ? ' --dry-run (nothing will be changed)' : ''}${flags.purge ? ' --purge' : ''}`);
|
|
118
|
+
if (!ctx.dryRun && !flags.yes) {
|
|
119
|
+
const what = flags.purge ? 'Remove bestgate, its secrets, config and database? Every access key stops working for good.' : 'Remove the bestgate services and nginx site (secrets, config and database are kept)?';
|
|
120
|
+
if (!(await askConfirm(ctx, what))) { ctx.say('Nothing changed.'); return { cancelled: true }; }
|
|
121
|
+
}
|
|
122
|
+
await revert(ctx, m, { purge: !!flags.purge });
|
|
123
|
+
ctx.say('');
|
|
124
|
+
ctx.say(`The certificate is kept. To delete it: certbot delete --cert-name ${base || '<base domain>'}`);
|
|
125
|
+
if (!flags.purge) ctx.say(`Kept: ${P.etcDir} (secrets, config), ${P.stateDir} (database). \`bestgate server revert --purge\` removes them.`);
|
|
126
|
+
ctx.say(`RESULT: ${ctx.dryRun ? 'DRY RUN (nothing was changed)' : 'REVERTED'}`);
|
|
127
|
+
return { ok: true, journal: ctx.journal };
|
|
128
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// `bestgate server rotate-token [--yes]`: a new frps auth token in frps.env, then frps
|
|
2
|
+
// restarts. Every access key contains the token, so every key stops working: re-issue them
|
|
3
|
+
// with `bestgate server user rekey <name>`. Use it after revoking someone you do not trust.
|
|
4
|
+
// The token is never printed. Root only.
|
|
5
|
+
import { randomBytes } from 'node:crypto';
|
|
6
|
+
import { CliError } from '../util.js';
|
|
7
|
+
import { TOKEN_RE } from '../key.js';
|
|
8
|
+
import { loadEnvFile } from './config.js';
|
|
9
|
+
import { P, UNITS, createContext, openLog, requireRoot, askConfirm, parseFlags } from './sys.js';
|
|
10
|
+
|
|
11
|
+
export async function run(argv = [], opts = {}) {
|
|
12
|
+
const flags = parseFlags(argv, { '--yes': 'flag' });
|
|
13
|
+
const ctx = opts.ctx || createContext();
|
|
14
|
+
requireRoot(ctx);
|
|
15
|
+
if (!ctx.exists(P.envFile)) throw new CliError(`${P.envFile} does not exist: run \`bestgate server install\` first.`);
|
|
16
|
+
const raw = ctx.read(P.envFile);
|
|
17
|
+
const lines = raw.split('\n').filter((l) => /^\s*FRP_AUTH_TOKEN\s*=/.test(l));
|
|
18
|
+
if (lines.length !== 1 || !TOKEN_RE.test(loadEnvFile(ctx.disk(P.envFile)).FRP_AUTH_TOKEN || '')) {
|
|
19
|
+
throw new CliError(`${P.envFile} must hold exactly one valid FRP_AUTH_TOKEN line; fix it by hand.`);
|
|
20
|
+
}
|
|
21
|
+
if (!flags.yes && !(await askConfirm(ctx, 'Replace the frps token? Every access key stops working until you re-issue it with `user rekey`.'))) {
|
|
22
|
+
ctx.say('Nothing changed.');
|
|
23
|
+
return { cancelled: true };
|
|
24
|
+
}
|
|
25
|
+
openLog(ctx, 'rotate-token');
|
|
26
|
+
const token = randomBytes(32).toString('base64url');
|
|
27
|
+
const next = raw.split('\n').map((l) => (/^\s*FRP_AUTH_TOKEN\s*=/.test(l) ? `FRP_AUTH_TOKEN=${token}` : l)).join('\n');
|
|
28
|
+
ctx.writeFile(P.envFile, next, { mode: 0o600, secret: true });
|
|
29
|
+
ctx.change('systemctl', ['restart', UNITS.frps]);
|
|
30
|
+
ctx.say('New frps token in place and frps restarted. Every connected client was dropped and every access key is now invalid.');
|
|
31
|
+
ctx.say('Issue a new key to each developer who should keep access (see `bestgate server user list`):');
|
|
32
|
+
ctx.say(' sudo bestgate server user rekey <name>');
|
|
33
|
+
return { ok: true };
|
|
34
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// `bestgate server status`: one screen, read-only. Root only. Prints no secrets.
|
|
2
|
+
// The database is opened only after the same privilege drop as `server user` (see users.js),
|
|
3
|
+
// and the dashboard password is read before that.
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import { loadEnvFile } from './config.js';
|
|
6
|
+
import { P, UNITS, createContext, requireRoot, checkDns, certInfo, listeningPorts, isLoopback } from './sys.js';
|
|
7
|
+
import { loadServerConfig } from './plan.js';
|
|
8
|
+
import { openUserDb, userState } from './users.js';
|
|
9
|
+
|
|
10
|
+
const MAX_TUNNELS_SHOWN = 20;
|
|
11
|
+
const clean = (v) => String(v ?? '').replace(/[^\x20-\x7e]/g, '?').slice(0, 64);
|
|
12
|
+
|
|
13
|
+
// Same call the daemon makes: frps dashboard API on loopback, user "admin".
|
|
14
|
+
export function dashboardProxies(cfg, password) {
|
|
15
|
+
return async () => {
|
|
16
|
+
const auth = 'Basic ' + Buffer.from(`admin:${password}`).toString('base64');
|
|
17
|
+
const r = await fetch(`http://127.0.0.1:${cfg.ports.dashboard}/api/proxy/http`, { headers: { authorization: auth }, signal: AbortSignal.timeout(5000) });
|
|
18
|
+
if (!r.ok) throw new Error(`dashboard answered HTTP ${r.status}`);
|
|
19
|
+
const j = await r.json();
|
|
20
|
+
if (!j || !Array.isArray(j.proxies)) throw new Error('unexpected dashboard answer');
|
|
21
|
+
return j.proxies;
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// -> array of {user, subdomain, conns} for the tunnels online right now.
|
|
26
|
+
export function onlineTunnels(proxies) {
|
|
27
|
+
return proxies
|
|
28
|
+
.filter((p) => p && p.status === 'online')
|
|
29
|
+
.map((p) => ({
|
|
30
|
+
user: clean(p.user),
|
|
31
|
+
subdomain: clean((p.conf && p.conf.subdomain) || p.name),
|
|
32
|
+
conns: Number.isFinite(p.curConns) ? p.curConns : 0,
|
|
33
|
+
}));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function lastCheck(ctx, now) {
|
|
37
|
+
const text = ctx.readOrNull(P.checkFile);
|
|
38
|
+
if (text === null) return ['never ran (systemctl status ' + UNITS.timer + ')'];
|
|
39
|
+
let age = '';
|
|
40
|
+
try {
|
|
41
|
+
const h = Math.floor((now - fs.statSync(ctx.disk(P.checkFile)).mtimeMs) / 3600000);
|
|
42
|
+
age = ` (${h < 1 ? 'less than an hour' : `${h} h`} ago)`;
|
|
43
|
+
} catch { /* age is optional */ }
|
|
44
|
+
const lines = text.split('\n').filter(Boolean).map(clean);
|
|
45
|
+
return lines.length ? [`${lines.length} problem(s)${age}:`, ...lines.map((l) => ` ${l}`)] : [`all well${age}`];
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// opts (tests): ctx, fetchProxies(), dropPrivileges, openDb
|
|
49
|
+
export async function run(argv = [], opts = {}) {
|
|
50
|
+
const ctx = opts.ctx || createContext();
|
|
51
|
+
requireRoot(ctx);
|
|
52
|
+
const cfg = loadServerConfig(ctx);
|
|
53
|
+
const now = ctx.now();
|
|
54
|
+
const say = (l = '') => ctx.out(l);
|
|
55
|
+
const row = (k, v) => say(`${k.padEnd(14)}${v}`);
|
|
56
|
+
|
|
57
|
+
let password = null;
|
|
58
|
+
try { password = loadEnvFile(ctx.disk(P.envFile)).FRP_DASHBOARD_PASSWORD || null; } catch { /* shown below */ }
|
|
59
|
+
|
|
60
|
+
say(`bestgate on ${cfg.baseDomain} (control ${cfg.controlLabel}.${cfg.baseDomain})`);
|
|
61
|
+
say('');
|
|
62
|
+
for (const u of [UNITS.auth, UNITS.frps, UNITS.timer]) {
|
|
63
|
+
const s = ctx.run('systemctl', ['is-active', u]).stdout.trim() || 'unknown';
|
|
64
|
+
row('service', `${u}: ${s}`);
|
|
65
|
+
}
|
|
66
|
+
try {
|
|
67
|
+
const listening = listeningPorts(ctx);
|
|
68
|
+
const parts = Object.entries(cfg.ports).map(([k, port]) => {
|
|
69
|
+
const on = listening.filter((x) => x.port === port);
|
|
70
|
+
return `${port} ${k} ${!on.length ? 'NOT LISTENING' : on.every((x) => isLoopback(x.addr)) ? 'ok' : 'EXPOSED (not loopback)'}`;
|
|
71
|
+
});
|
|
72
|
+
row('ports', parts.join(', '));
|
|
73
|
+
} catch (e) { row('ports', `cannot check: ${clean(e.message)}`); }
|
|
74
|
+
|
|
75
|
+
for (const x of await checkDns(ctx, cfg)) {
|
|
76
|
+
row('dns', `${x.name} -> ${x.addresses.map(clean).join(', ') || 'nothing'}${x.ok ? '' : ` WRONG, expected ${cfg.publicIp}`}`);
|
|
77
|
+
}
|
|
78
|
+
const c = certInfo(ctx, cfg);
|
|
79
|
+
if (!c.present) row('certificate', 'MISSING (run `bestgate server cert`)');
|
|
80
|
+
else if (c.error) row('certificate', clean(c.error));
|
|
81
|
+
else row('certificate', `${c.daysLeft} days left, valid to ${c.validTo.slice(0, 10)}${c.daysLeft < 30 ? ' (renew with `bestgate server cert`)' : ''}`);
|
|
82
|
+
|
|
83
|
+
const check = lastCheck(ctx, now); // read as root, before the privilege drop below
|
|
84
|
+
let tunnels = null;
|
|
85
|
+
say('');
|
|
86
|
+
try {
|
|
87
|
+
const db = openUserDb(ctx, opts);
|
|
88
|
+
try {
|
|
89
|
+
const users = db.listUsers();
|
|
90
|
+
const by = { active: 0, expired: 0, revoked: 0 };
|
|
91
|
+
for (const u of users) by[userState(u, now, cfg)]++;
|
|
92
|
+
row('users', `${users.length} (${by.active} active, ${by.expired} expired, ${by.revoked} revoked)`);
|
|
93
|
+
} finally { db.close(); }
|
|
94
|
+
} catch (e) { row('users', `unavailable: ${clean(e.message)}`); }
|
|
95
|
+
|
|
96
|
+
try {
|
|
97
|
+
const fetchProxies = opts.fetchProxies || dashboardProxies(cfg, password);
|
|
98
|
+
if (!password && !opts.fetchProxies) throw new Error(`no FRP_DASHBOARD_PASSWORD in ${P.envFile}`);
|
|
99
|
+
tunnels = onlineTunnels(await fetchProxies());
|
|
100
|
+
} catch (e) { row('tunnels', `unavailable: ${clean(e.message)}`); }
|
|
101
|
+
if (tunnels) {
|
|
102
|
+
row('tunnels', `${tunnels.length} online`);
|
|
103
|
+
for (const t of tunnels.slice(0, MAX_TUNNELS_SHOWN)) say(`${''.padEnd(14)}${t.user} ${t.subdomain}.${cfg.baseDomain} ${t.conns} open connection(s)`);
|
|
104
|
+
if (tunnels.length > MAX_TUNNELS_SHOWN) say(`${''.padEnd(14)}... and ${tunnels.length - MAX_TUNNELS_SHOWN} more`);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
say('');
|
|
108
|
+
row('idle timeout', `${cfg.idleMinutes} min without traffic or open connections`);
|
|
109
|
+
row('access expiry', `${cfg.accessExpiryDays} days after last use`);
|
|
110
|
+
row('per dev', `${cfg.maxTunnelsPerUser} tunnels, ${cfg.maxClientsPerUser} clients, ${cfg.bandwidthLimit} per second`);
|
|
111
|
+
const [first, ...more] = check;
|
|
112
|
+
row('last check', first);
|
|
113
|
+
for (const l of more) say(`${''.padEnd(14)}${l}`);
|
|
114
|
+
}
|