@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,187 @@
1
+ // Server config: schema, defaults, strict validation, paths.
2
+ // Values end up in nginx/toml/systemd files written as root, so validation only
3
+ // accepts the exact expected shape of every field.
4
+ import { readFileSync, writeFileSync, renameSync, mkdirSync } from 'node:fs';
5
+ import { dirname, join } from 'node:path';
6
+ import { isIPv4, isIPv6 } from 'node:net';
7
+ import { LABEL_RE } from '../key.js';
8
+
9
+ const ROOT = process.env.BESTGATE_ROOT || '';
10
+ const p = (rel) => (ROOT ? join(ROOT, rel) : '/' + rel);
11
+
12
+ export const PATHS = Object.freeze({
13
+ configFile: p('etc/bestgate/config.json'),
14
+ envFile: p('etc/bestgate/frps.env'),
15
+ stateDir: p('var/lib/bestgate'),
16
+ dbFile: p('var/lib/bestgate/bestgate.db'),
17
+ origDir: p('var/lib/bestgate-orig'),
18
+ logDir: p('var/log/bestgate'),
19
+ });
20
+
21
+ export const DEFAULTS = Object.freeze({
22
+ baseDomain: '',
23
+ controlLabel: 'frp',
24
+ listenIp: '',
25
+ publicIp: '',
26
+ certbotAccount: '',
27
+ // Privileged (< 1024) on purpose: while frps or the daemon restarts, no unprivileged
28
+ // local account can bind one of these and catch logins, keys or visitor traffic.
29
+ // 721-724 sit in a block IANA leaves unassigned (717-728) and that no common Ubuntu
30
+ // service uses; `server plan` checks that they are free.
31
+ ports: Object.freeze({ control: 721, vhost: 722, dashboard: 723, daemon: 724 }),
32
+ idleMinutes: 60,
33
+ accessExpiryDays: 30,
34
+ maxTunnelsPerUser: 3,
35
+ // Control sessions (running frpc) per developer. One `bestgate <port>` is one frpc, so
36
+ // 5 = the 3 tunnels plus room for 2 restarts while frps still lists the dead frpc
37
+ // (up to its 90 s heartbeat timeout).
38
+ maxClientsPerUser: 5,
39
+ bandwidthLimit: '10MB',
40
+ pollSeconds: 30,
41
+ nginx: Object.freeze({
42
+ reqPerSec: 20, reqBurst: 100, connPerIp: 50, loginPerMin: 10, maxBody: '100m',
43
+ controlConnPerIp: 20, // open control WebSockets per client IP (an office NAT may hold several devs)
44
+ maxConnections: 200, // all bestgate connections together, per server block: the nginx pool is shared
45
+ }),
46
+ checkUrls: Object.freeze([]),
47
+ });
48
+
49
+ // Shared secret frps sends to the daemon (Basic auth); 32 random bytes as hex.
50
+ export const PLUGIN_SECRET_RE = /^[0-9a-f]{64}$/;
51
+
52
+ const DOMAIN_LABEL_RE = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;
53
+ const BANDWIDTH_RE = /^[1-9][0-9]{0,5}(MB|KB)$/; // frp accepts only MB / KB
54
+ const NGINX_SIZE_RE = /^[1-9][0-9]{0,5}[kmg]$/;
55
+ const CERTBOT_ACCOUNT_RE = /^[0-9a-f]{32}$/;
56
+ const CHECK_URL_RE = /^https?:\/\/[a-z0-9.-]+(:[0-9]{1,5})?(\/[A-Za-z0-9._~%/?&=+-]*)?$/;
57
+
58
+ export function isDomain(s) {
59
+ if (typeof s !== 'string' || s.length > 253) return false;
60
+ const labels = s.split('.');
61
+ return labels.length >= 2 && labels.every((l) => DOMAIN_LABEL_RE.test(l)) && !/^[0-9]+$/.test(labels.at(-1));
62
+ }
63
+
64
+ export function isIp(s) {
65
+ return typeof s === 'string' && !s.includes('%') && (isIPv4(s) || isIPv6(s));
66
+ }
67
+
68
+ const isInt = (v, min, max) => Number.isSafeInteger(v) && v >= min && v <= max;
69
+
70
+ const TOP_KEYS = Object.keys(DEFAULTS);
71
+ const PORT_KEYS = Object.keys(DEFAULTS.ports);
72
+ const NGINX_KEYS = Object.keys(DEFAULTS.nginx);
73
+
74
+ // Returns a normalized config (merged over DEFAULTS) or throws listing every problem.
75
+ export function validateConfig(obj) {
76
+ if (!obj || typeof obj !== 'object' || Array.isArray(obj)) throw new Error('invalid config: not an object');
77
+ const errors = [];
78
+ const isObj = (v) => v && typeof v === 'object' && !Array.isArray(v);
79
+ for (const k of Object.keys(obj)) if (!TOP_KEYS.includes(k)) errors.push(`unknown key "${k}"`);
80
+ if (obj.ports !== undefined && !isObj(obj.ports)) errors.push('ports must be an object');
81
+ if (obj.nginx !== undefined && !isObj(obj.nginx)) errors.push('nginx must be an object');
82
+ const ports = isObj(obj.ports) ? obj.ports : {};
83
+ const nginx = isObj(obj.nginx) ? obj.nginx : {};
84
+ for (const k of Object.keys(ports)) if (!PORT_KEYS.includes(k)) errors.push(`unknown key "ports.${k}"`);
85
+ for (const k of Object.keys(nginx)) if (!NGINX_KEYS.includes(k)) errors.push(`unknown key "nginx.${k}"`);
86
+
87
+ const c = {
88
+ ...DEFAULTS,
89
+ ...obj,
90
+ ports: { ...DEFAULTS.ports, ...ports },
91
+ nginx: { ...DEFAULTS.nginx, ...nginx },
92
+ checkUrls: obj.checkUrls === undefined ? [] : obj.checkUrls,
93
+ };
94
+
95
+ if (!isDomain(c.baseDomain)) errors.push('baseDomain must be a lowercase domain name like t.example.com');
96
+ if (typeof c.controlLabel !== 'string' || !LABEL_RE.test(c.controlLabel)) {
97
+ errors.push('controlLabel must be one lowercase DNS label (a-z, 0-9, -), up to 32 chars');
98
+ }
99
+ if (c.listenIp !== '' && !isIp(c.listenIp)) errors.push('listenIp must be an IPv4/IPv6 address or empty');
100
+ if (!isIp(c.publicIp)) errors.push('publicIp must be an IPv4/IPv6 address');
101
+ if (c.certbotAccount !== '' && !(typeof c.certbotAccount === 'string' && CERTBOT_ACCOUNT_RE.test(c.certbotAccount))) {
102
+ errors.push('certbotAccount must be a 32-character hex certbot account id or empty');
103
+ }
104
+ // Below 1024 only root (or CAP_NET_BIND_SERVICE) can bind them; see DEFAULTS.ports.
105
+ for (const k of PORT_KEYS) if (!isInt(c.ports[k], 1, 1023)) errors.push(`ports.${k} must be an integer 1-1023 (a privileged port)`);
106
+ const pv = PORT_KEYS.map((k) => c.ports[k]);
107
+ if (new Set(pv).size !== pv.length) errors.push('ports must all be different');
108
+ if (!isInt(c.idleMinutes, 1, 10080)) errors.push('idleMinutes must be an integer 1-10080');
109
+ if (!isInt(c.accessExpiryDays, 1, 3650)) errors.push('accessExpiryDays must be an integer 1-3650');
110
+ if (!isInt(c.maxTunnelsPerUser, 1, 100)) errors.push('maxTunnelsPerUser must be an integer 1-100');
111
+ if (!isInt(c.maxClientsPerUser, 1, 100)) errors.push('maxClientsPerUser must be an integer 1-100');
112
+ if (typeof c.bandwidthLimit !== 'string' || !BANDWIDTH_RE.test(c.bandwidthLimit)) {
113
+ errors.push('bandwidthLimit must look like 10MB or 500KB');
114
+ }
115
+ if (!isInt(c.pollSeconds, 5, 3600)) errors.push('pollSeconds must be an integer 5-3600');
116
+ if (isInt(c.pollSeconds, 5, 3600) && isInt(c.idleMinutes, 1, 10080) && c.pollSeconds * 2 > c.idleMinutes * 60) {
117
+ errors.push('pollSeconds must be at most half of idleMinutes');
118
+ }
119
+ if (!isInt(c.nginx.reqPerSec, 1, 100000)) errors.push('nginx.reqPerSec must be an integer 1-100000');
120
+ if (!isInt(c.nginx.reqBurst, 0, 100000)) errors.push('nginx.reqBurst must be an integer 0-100000');
121
+ if (!isInt(c.nginx.connPerIp, 1, 100000)) errors.push('nginx.connPerIp must be an integer 1-100000');
122
+ if (!isInt(c.nginx.loginPerMin, 1, 100000)) errors.push('nginx.loginPerMin must be an integer 1-100000');
123
+ if (!isInt(c.nginx.controlConnPerIp, 1, 100000)) errors.push('nginx.controlConnPerIp must be an integer 1-100000');
124
+ if (!isInt(c.nginx.maxConnections, 1, 100000)) errors.push('nginx.maxConnections must be an integer 1-100000');
125
+ if (typeof c.nginx.maxBody !== 'string' || !NGINX_SIZE_RE.test(c.nginx.maxBody)) {
126
+ errors.push('nginx.maxBody must look like 100m, 512k or 1g');
127
+ }
128
+ if (!Array.isArray(c.checkUrls) || c.checkUrls.length > 20) {
129
+ errors.push('checkUrls must be a list of at most 20 URLs');
130
+ } else {
131
+ c.checkUrls.forEach((u, i) => {
132
+ if (typeof u !== 'string' || u.length > 2048 || !CHECK_URL_RE.test(u)) {
133
+ errors.push(`checkUrls[${i}] must be a plain http(s) URL with a lowercase host`);
134
+ }
135
+ });
136
+ c.checkUrls = [...c.checkUrls];
137
+ }
138
+
139
+ if (errors.length) throw new Error('invalid config:\n - ' + errors.join('\n - '));
140
+ return c;
141
+ }
142
+
143
+ export function loadConfig(file = PATHS.configFile) {
144
+ let raw;
145
+ try {
146
+ raw = readFileSync(file, 'utf8');
147
+ } catch (e) {
148
+ throw new Error(`cannot read config ${file}: ${e.code || e.message}`);
149
+ }
150
+ let obj;
151
+ try {
152
+ obj = JSON.parse(raw);
153
+ } catch {
154
+ throw new Error(`config ${file} is not valid JSON`);
155
+ }
156
+ return validateConfig(obj);
157
+ }
158
+
159
+ export function saveConfig(cfg, file = PATHS.configFile) {
160
+ const c = validateConfig(cfg);
161
+ mkdirSync(dirname(file), { recursive: true, mode: 0o755 });
162
+ const tmp = `${file}.tmp-${process.pid}`;
163
+ writeFileSync(tmp, JSON.stringify(c, null, 2) + '\n', { mode: 0o644 });
164
+ renameSync(tmp, file);
165
+ return c;
166
+ }
167
+
168
+ // KEY=VALUE per line (systemd EnvironmentFile subset). Values are never printed.
169
+ export function loadEnvFile(file = PATHS.envFile) {
170
+ let raw;
171
+ try {
172
+ raw = readFileSync(file, 'utf8');
173
+ } catch (e) {
174
+ throw new Error(`cannot read ${file}: ${e.code || e.message}`);
175
+ }
176
+ const out = {};
177
+ raw.split(/\r?\n/).forEach((line, i) => {
178
+ const t = line.trim();
179
+ if (!t || t.startsWith('#')) return;
180
+ const m = /^([A-Z_][A-Z0-9_]*)=(.*)$/.exec(t);
181
+ if (!m) throw new Error(`${file}: line ${i + 1} is not KEY=VALUE`);
182
+ let v = m[2].trim();
183
+ if (v.length >= 2 && (v[0] === '"' || v[0] === "'") && v.at(-1) === v[0]) v = v.slice(1, -1);
184
+ out[m[1]] = v;
185
+ });
186
+ return out;
187
+ }
@@ -0,0 +1,351 @@
1
+ // Auth daemon: frps HTTP server plugin (Login / NewProxy / Ping / CloseProxy) on
2
+ // 127.0.0.1:<ports.daemon>/handler, plus a poller of the frps dashboard API that
3
+ // closes idle sessions. Fails closed: anything unexpected is a reject or a non-200.
4
+ // Never logs keys, secrets, tokens, privilege keys or full run_ids.
5
+ //
6
+ // Only frps may call /handler: it authenticates with HTTP Basic auth, user "bestgate" and
7
+ // the plugin secret (BESTGATE_PLUGIN_SECRET in daemon.env and frps.env). frps puts them in
8
+ // the plugin URL ("bestgate:<secret>@127.0.0.1:<port>"); Go's HTTP client turns that into
9
+ // an Authorization header and redacts the password in the errors frps logs.
10
+ import { createServer } from 'node:http';
11
+ import { timingSafeEqual, createHash } from 'node:crypto';
12
+ import { join } from 'node:path';
13
+ import { NAME_RE } from '../key.js';
14
+ import { REASONS } from '../reasons.js';
15
+ import { PATHS, PLUGIN_SECRET_RE, loadConfig, loadEnvFile } from './config.js';
16
+ import { openDb } from './db.js';
17
+ import {
18
+ DAY_MS, RUN_ID_RE, shortRun, decideLogin, decidePing, decideNewProxy, evaluatePoll, gapShift, countTunnels,
19
+ } from './policy.js';
20
+
21
+ const MAX_BODY = 64 * 1024;
22
+ const PENDING_MS = 15000;
23
+
24
+ const safe = (v) => (typeof v === 'string' && v ? v.replace(/[^A-Za-z0-9._-]/g, '?').slice(0, 64) : '-');
25
+ export const PLUGIN_USER = 'bestgate';
26
+
27
+ // Constant-time check of "Authorization: Basic base64(bestgate:<secret>)".
28
+ export function pluginAuthOk(header, secret) {
29
+ if (typeof secret !== 'string' || !PLUGIN_SECRET_RE.test(secret)) return false;
30
+ if (typeof header !== 'string' || header.length > 512) return false;
31
+ const want = 'Basic ' + Buffer.from(`${PLUGIN_USER}:${secret}`).toString('base64');
32
+ const h = (x) => createHash('sha256').update(x).digest();
33
+ return timingSafeEqual(h(header), h(want));
34
+ }
35
+
36
+ class HttpError extends Error {
37
+ constructor(status, message) { super(message); this.status = status; }
38
+ }
39
+
40
+ function isLoopback(addr) {
41
+ return addr === '127.0.0.1' || addr === '::1' || addr === '::ffff:127.0.0.1';
42
+ }
43
+
44
+ // config: validated config; db: openDb() object; fetchProxies(): /api/proxy/http .proxies;
45
+ // fetchClients(): /api/clients; now(): ms clock; log(line); pluginSecret: what frps must
46
+ // send (without it every HTTP request is refused).
47
+ export function createDaemon({
48
+ config, db, fetchProxies, fetchClients = async () => [], now = Date.now, log = console.log, pluginSecret = null,
49
+ }) {
50
+ const pollMs = config.pollSeconds * 1000;
51
+ let pending = []; // NewProxy grants frps may not list yet: [{name, user, at}]
52
+ let pollTimer = null;
53
+ let pollFailing = false;
54
+ let server = null;
55
+
56
+ const say = (op, d, fields) =>
57
+ log(`${op} ${d.allow ? 'allow' : 'reject'} ${fields}${d.allow ? '' : ` reason="${d.reason}"`}`);
58
+ const respond = (d) => {
59
+ if (!d.allow) return { reject: true, reject_reason: d.reason };
60
+ if (d.content) return { reject: false, unchange: false, content: d.content };
61
+ return { reject: false, unchange: true };
62
+ };
63
+
64
+ // Online control sessions of `name` other than `runId` (a reconnect replaces its own).
65
+ function countClients(clients, name, runId) {
66
+ if (!Array.isArray(clients)) throw new Error('dashboard /api/clients: unexpected answer');
67
+ return clients.filter((c) => c && c.online && c.user === name && c.runID !== runId).length;
68
+ }
69
+
70
+ async function login(content) {
71
+ const name = content && typeof content.user === 'string' && NAME_RE.test(content.user) ? content.user : null;
72
+ const runId = content && typeof content.run_id === 'string' && RUN_ID_RE.test(content.run_id) ? content.run_id : '';
73
+ const read = () => ({ user: name ? db.getUser(name) : null, session: runId ? db.getSession(runId) : null });
74
+ const fields = `user=${safe(content && content.user)} run=${shortRun(content && content.run_id)}`;
75
+ let rows = read();
76
+ let d = decideLogin({ content, ...rows, now: now(), config });
77
+ if (d.allow) {
78
+ // Fail closed: if the dashboard API does not answer, this throws -> 500 -> frps refuses.
79
+ const n = countClients(await fetchClients(), name, runId);
80
+ rows = read();
81
+ d = decideLogin({ content, ...rows, now: now(), config });
82
+ if (d.allow && n >= config.maxClientsPerUser) {
83
+ d = { allow: false, reason: `${REASONS.TUNNEL_LIMIT} (${config.maxClientsPerUser} clients)` };
84
+ }
85
+ }
86
+ const t = now();
87
+ // Never creates a session row: that happens at the first Ping/NewProxy of a login frps accepted.
88
+ if (d.allow) db.touchUser(name, t);
89
+ if (rows.session && rows.session.user === name) db.seenSession(runId, t); // a closed session someone retries is kept a day longer
90
+ say('Login', d, fields);
91
+ return respond(d);
92
+ }
93
+
94
+ // Writes for Ping/NewProxy outcomes on the session of an accepted frps control.
95
+ // A reject never inserts: it only closes an existing row of that same user.
96
+ function recordSession(d, name, runId, session, t) {
97
+ if (!NAME_RE.test(name || '') || typeof runId !== 'string' || !RUN_ID_RE.test(runId)) return;
98
+ if (session && session.user !== name) return;
99
+ if (d.allow) {
100
+ if (!session) db.ensureSession(runId, name, t);
101
+ db.seenSession(runId, t);
102
+ } else if (session && d.close) {
103
+ db.closeSession(runId, d.base, t);
104
+ } else if (session) {
105
+ db.seenSession(runId, t);
106
+ }
107
+ }
108
+
109
+ function ping(content) {
110
+ const t = now();
111
+ const u = (content && content.user) || {};
112
+ const user = typeof u.user === 'string' ? db.getUser(u.user) : null;
113
+ const session = typeof u.run_id === 'string' && RUN_ID_RE.test(u.run_id) ? db.getSession(u.run_id) : null;
114
+ const d = decidePing({ content, user, session, now: t, config });
115
+ recordSession(d, u.user, u.run_id, session, t);
116
+ if (!d.allow) say('Ping', d, `user=${safe(u.user)} run=${shortRun(u.run_id)}`);
117
+ return respond(d);
118
+ }
119
+
120
+ async function newProxy(content) {
121
+ const u = (content && content.user) || {};
122
+ const read = () => ({
123
+ user: typeof u.user === 'string' ? db.getUser(u.user) : null,
124
+ session: typeof u.run_id === 'string' && RUN_ID_RE.test(u.run_id) ? db.getSession(u.run_id) : null,
125
+ });
126
+ const fields = `user=${safe(u.user)} run=${shortRun(u.run_id)} proxy=${safe(content && content.proxy_name)} ` +
127
+ `subdomain=${safe(content && content.subdomain)}`;
128
+ // Cheap checks first, so a bad request never waits for the dashboard API.
129
+ let rows = read();
130
+ let d = decideNewProxy({ content, ...rows, onlineCount: 0, now: now(), config });
131
+ if (d.allow) {
132
+ const proxies = await fetchProxies(); // throws -> 500 -> frps refuses the proxy
133
+ const t = now();
134
+ rows = read();
135
+ pending = pending.filter((g) => t - g.at < PENDING_MS);
136
+ const onlineCount = countTunnels({ proxies, pending, user: u.user, proxyName: content.proxy_name, now: t, graceMs: PENDING_MS });
137
+ d = decideNewProxy({ content, ...rows, onlineCount, now: t, config });
138
+ if (d.allow) pending.push({ name: content.proxy_name, user: u.user, at: t });
139
+ }
140
+ recordSession(d, u.user, u.run_id, rows.session, now());
141
+ say('NewProxy', d, fields);
142
+ return respond(d);
143
+ }
144
+
145
+ function closeProxy(content) {
146
+ const name = content && content.proxy_name;
147
+ const user = content && content.user && content.user.user;
148
+ pending = pending.filter((g) => !(g.name === name && g.user === user));
149
+ log(`CloseProxy user=${safe(user)} proxy=${safe(name)}`);
150
+ return { reject: false, unchange: true };
151
+ }
152
+
153
+ async function handle(op, content) {
154
+ switch (op) {
155
+ case 'Login': return login(content);
156
+ case 'Ping': return ping(content);
157
+ case 'NewProxy': return newProxy(content);
158
+ case 'CloseProxy': return closeProxy(content);
159
+ default: throw new HttpError(400, `unsupported op ${safe(op)}`);
160
+ }
161
+ }
162
+
163
+ async function pollOnce() {
164
+ const t = now();
165
+ let proxies, clients;
166
+ try {
167
+ [proxies, clients] = await Promise.all([fetchProxies(), fetchClients()]);
168
+ } catch (e) {
169
+ if (!pollFailing) log(`poll failed, idle clocks paused: ${e.message}`);
170
+ pollFailing = true;
171
+ return false;
172
+ }
173
+ if (pollFailing) log('poll recovered');
174
+ pollFailing = false;
175
+ db.transaction(() => {
176
+ const shift = gapShift(db.getMeta('last_poll_at'), t, pollMs);
177
+ if (shift > 0) {
178
+ db.shiftOpenSessions(shift);
179
+ log(`idle clocks moved ${Math.round(shift / 1000)}s forward (time the daemon could not watch frps)`);
180
+ }
181
+ const r = evaluatePoll({ sessions: db.listSessions(), proxies, clients, now: t, config });
182
+ for (const a of r.active) db.setSessionActivity(a.run_id, a.traffic, t);
183
+ for (const b of r.baseline) db.setSessionTraffic(b.run_id, b.traffic);
184
+ for (const c of r.create) {
185
+ db.ensureSession(c.run_id, c.user, t);
186
+ db.setSessionActivity(c.run_id, c.traffic, t);
187
+ log(`poll adopted session user=${safe(c.user)} run=${shortRun(c.run_id)}`);
188
+ }
189
+ for (const name of r.touch) db.touchUser(name, t);
190
+ for (const c of r.close) {
191
+ db.closeSession(c.run_id, c.reason, t);
192
+ log(`poll close user=${safe(c.user)} run=${shortRun(c.run_id)} reason="${c.reason}"`);
193
+ }
194
+ db.gcSessions(t - DAY_MS);
195
+ db.setMeta('last_poll_at', t);
196
+ });
197
+ return true;
198
+ }
199
+
200
+ function startPolling() {
201
+ const loop = async () => {
202
+ try { await pollOnce(); } catch (e) { log(`poll error: ${e.message}`); }
203
+ if (pollTimer) pollTimer = setTimeout(loop, pollMs);
204
+ };
205
+ pollTimer = setTimeout(loop, 0);
206
+ }
207
+
208
+ function handler(req, res) {
209
+ const send = (status, obj) => {
210
+ const body = JSON.stringify(obj);
211
+ res.writeHead(status, { 'content-type': 'application/json', 'content-length': Buffer.byteLength(body) });
212
+ res.end(body);
213
+ };
214
+ let url;
215
+ try { url = new URL(req.url, 'http://127.0.0.1'); } catch { return send(400, { error: 'bad url' }); }
216
+ if (!isLoopback(req.socket.remoteAddress)) return send(403, { error: 'forbidden' });
217
+ if (!pluginAuthOk(req.headers.authorization, pluginSecret)) {
218
+ res.setHeader('www-authenticate', 'Basic realm="bestgate"');
219
+ req.resume();
220
+ return send(401, { error: 'unauthorized' });
221
+ }
222
+ if (req.method !== 'POST' || url.pathname !== '/handler') return send(404, { error: 'not found' });
223
+ const chunks = [];
224
+ let size = 0;
225
+ let done = false;
226
+ req.on('data', (c) => {
227
+ if (done) return;
228
+ size += c.length;
229
+ if (size > MAX_BODY) {
230
+ done = true;
231
+ send(413, { error: 'body too large' });
232
+ req.destroy();
233
+ return;
234
+ }
235
+ chunks.push(c);
236
+ });
237
+ req.on('error', () => { done = true; });
238
+ req.on('end', () => {
239
+ if (done) return;
240
+ done = true;
241
+ let body;
242
+ try { body = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { return send(400, { error: 'bad json' }); }
243
+ if (!body || typeof body !== 'object' || typeof body.op !== 'string' || !body.content || typeof body.content !== 'object') {
244
+ return send(400, { error: 'bad request' });
245
+ }
246
+ const qop = url.searchParams.get('op');
247
+ if (qop !== null && qop !== body.op) return send(400, { error: 'op mismatch' });
248
+ handle(body.op, body.content).then(
249
+ (r) => send(200, r),
250
+ (e) => {
251
+ log(`${safe(body.op)} error status=${e.status || 500}: ${e.message}`);
252
+ send(e.status || 500, { error: 'internal error' });
253
+ },
254
+ );
255
+ });
256
+ }
257
+
258
+ function listen(port = config.ports.daemon, host = '127.0.0.1') {
259
+ server = createServer(handler);
260
+ server.requestTimeout = 10000;
261
+ server.headersTimeout = 5000;
262
+ server.keepAliveTimeout = 5000;
263
+ return new Promise((resolve, reject) => {
264
+ server.once('error', reject);
265
+ server.listen(port, host, () => { server.off('error', reject); resolve(server.address()); });
266
+ });
267
+ }
268
+
269
+ async function close() {
270
+ if (pollTimer) clearTimeout(pollTimer);
271
+ pollTimer = null;
272
+ if (server) {
273
+ const closed = new Promise((resolve) => server.close(() => resolve()));
274
+ server.closeAllConnections();
275
+ await closed;
276
+ server = null;
277
+ }
278
+ }
279
+
280
+ return { handle, handler, pollOnce, startPolling, listen, close };
281
+ }
282
+
283
+ function dashboardFetchers(config, password) {
284
+ const base = `http://127.0.0.1:${config.ports.dashboard}`;
285
+ const auth = 'Basic ' + Buffer.from(`admin:${password}`).toString('base64');
286
+ const getJson = async (path) => {
287
+ const r = await fetch(base + path, { headers: { authorization: auth }, signal: AbortSignal.timeout(5000) });
288
+ if (!r.ok) throw new Error(`dashboard ${path}: HTTP ${r.status}`);
289
+ return r.json();
290
+ };
291
+ return {
292
+ fetchProxies: async () => {
293
+ const j = await getJson('/api/proxy/http');
294
+ if (!j || !Array.isArray(j.proxies)) throw new Error('dashboard /api/proxy/http: unexpected answer');
295
+ return j.proxies;
296
+ },
297
+ fetchClients: async () => {
298
+ const j = await getJson('/api/clients');
299
+ if (!Array.isArray(j)) throw new Error('dashboard /api/clients: unexpected answer');
300
+ return j;
301
+ },
302
+ };
303
+ }
304
+
305
+ // `bestgate server daemon [--config <file>]`
306
+ export async function run(argv = []) {
307
+ let configFile = PATHS.configFile;
308
+ const i = argv.indexOf('--config');
309
+ if (i >= 0) {
310
+ if (!argv[i + 1]) throw new Error('--config needs a file');
311
+ configFile = argv[i + 1];
312
+ }
313
+ // The database must never be created or opened by root (see users.js).
314
+ if (typeof process.getuid === 'function' && process.getuid() === 0) {
315
+ throw new Error('the daemon does not run as root: systemd starts it as the bestgate user (systemctl start bestgate-auth)');
316
+ }
317
+ const config = loadConfig(configFile);
318
+ let password = process.env.FRP_DASHBOARD_PASSWORD;
319
+ let pluginSecret = process.env.BESTGATE_PLUGIN_SECRET;
320
+ if (!password || !pluginSecret) {
321
+ try {
322
+ const env = loadEnvFile(join(PATHS.envFile, '..', 'daemon.env'));
323
+ password ||= env.FRP_DASHBOARD_PASSWORD;
324
+ pluginSecret ||= env.BESTGATE_PLUGIN_SECRET;
325
+ } catch { /* reported below */ }
326
+ }
327
+ if (!password) throw new Error('FRP_DASHBOARD_PASSWORD is not set (environment or daemon.env)');
328
+ if (!PLUGIN_SECRET_RE.test(pluginSecret || '')) {
329
+ throw new Error('BESTGATE_PLUGIN_SECRET is missing or malformed (environment or daemon.env): run `bestgate server install`');
330
+ }
331
+
332
+ const db = openDb();
333
+ const daemon = createDaemon({ config, db, pluginSecret, ...dashboardFetchers(config, password) });
334
+ try {
335
+ await daemon.listen();
336
+ } catch (e) {
337
+ db.close();
338
+ throw new Error(`cannot listen on 127.0.0.1:${config.ports.daemon}: ${e.code || e.message}`);
339
+ }
340
+ daemon.startPolling();
341
+ console.log(`bestgate daemon listening on 127.0.0.1:${config.ports.daemon}/handler ` +
342
+ `(idle ${config.idleMinutes} min, expiry ${config.accessExpiryDays} d, ${config.maxTunnelsPerUser} tunnels/user)`);
343
+ await new Promise((resolve) => {
344
+ const stop = (sig) => { console.log(`bestgate daemon stopping (${sig})`); resolve(); };
345
+ process.once('SIGTERM', stop);
346
+ process.once('SIGINT', stop);
347
+ });
348
+ await daemon.close();
349
+ db.close();
350
+ }
351
+