@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,284 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { randomBytes } from 'node:crypto';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import readline from 'node:readline';
7
+ import { parseArgs } from 'node:util';
8
+ import { ensureFrp } from '../frp.js';
9
+ import { decodeKey } from '../key.js';
10
+ import { REASONS } from '../reasons.js';
11
+ import { CliError, resolves } from '../util.js';
12
+ import { loadLogin } from './store.js';
13
+
14
+ const NAME_RE = /^[a-z0-9-]{3,32}$/;
15
+
16
+ // ---- arguments -------------------------------------------------------------
17
+
18
+ export function validateName(name) {
19
+ if (!NAME_RE.test(name) || name.startsWith('-') || name.endsWith('-')) {
20
+ throw new CliError(`Invalid name "${name}": use 3-32 characters a-z, 0-9 and hyphen, not starting or ending with a hyphen.`);
21
+ }
22
+ return name;
23
+ }
24
+
25
+ export function validatePort(text) {
26
+ const port = Number(text);
27
+ if (!/^\d+$/.test(String(text)) || port < 1 || port > 65535) {
28
+ throw new CliError(`Invalid port "${text}": use a number from 1 to 65535.`);
29
+ }
30
+ return port;
31
+ }
32
+
33
+ // The default subdomain: a fresh UUIDv7 (RFC 9562) without hyphens, 32 lowercase hex
34
+ // characters. New on every run, so the address cannot be guessed from the user name.
35
+ export function uuidv7Hex(now = Date.now(), rand = randomBytes(10)) {
36
+ const b = Buffer.alloc(16);
37
+ b.writeUIntBE(now, 0, 6); // 48-bit Unix time in ms
38
+ rand.copy(b, 6);
39
+ b[6] = 0x70 | (b[6] & 0x0f); // version 7
40
+ b[8] = 0x80 | (b[8] & 0x3f); // variant 10
41
+ return b.toString('hex');
42
+ }
43
+
44
+ const LOOPBACK = new Set(['127.0.0.1', 'localhost', '::1']);
45
+
46
+ // Where frpc connects. The BESTGATE_SERVER_* / BESTGATE_PROTOCOL overrides exist for local
47
+ // tests only; a protocol other than wss has no certificate check, so it is refused for
48
+ // anything but a loopback server address.
49
+ export function connectionSettings(env, key, login) {
50
+ const serverAddr = env.BESTGATE_SERVER_ADDR || `${key.control}.${login.host}`;
51
+ const serverPort = env.BESTGATE_SERVER_PORT ? validatePort(env.BESTGATE_SERVER_PORT) : 443;
52
+ const protocol = env.BESTGATE_PROTOCOL || 'wss';
53
+ if (env.BESTGATE_PROTOCOL && !LOOPBACK.has(serverAddr)) {
54
+ throw new CliError('BESTGATE_PROTOCOL is only for local tests: it needs BESTGATE_SERVER_ADDR=127.0.0.1 (or localhost, ::1).');
55
+ }
56
+ return { serverAddr, serverPort, protocol };
57
+ }
58
+
59
+ // → { port, name|undefined, auth: {user, password|undefined}|undefined, hostHeader|undefined, verbose }
60
+ // "--auth user" leaves the password undefined: run() asks for it, so it never shows in
61
+ // the process list.
62
+ export function parseTunnelArgs(argv) {
63
+ let parsed;
64
+ try {
65
+ parsed = parseArgs({
66
+ args: argv,
67
+ allowPositionals: true,
68
+ options: {
69
+ name: { type: 'string' },
70
+ auth: { type: 'string' },
71
+ 'host-header': { type: 'string' },
72
+ verbose: { type: 'boolean' },
73
+ },
74
+ });
75
+ } catch (e) {
76
+ throw new CliError(`${e.message}\nRun "bestgate --help" for usage.`);
77
+ }
78
+ const { values, positionals } = parsed;
79
+ if (positionals.length !== 1) throw new CliError('Usage: bestgate <port> [--name <sub>] [--auth user[:pass]] [--host-header <h>]');
80
+ const out = { port: validatePort(positionals[0]), verbose: !!values.verbose };
81
+ if (values.name !== undefined) out.name = validateName(values.name);
82
+ if (values.auth !== undefined) {
83
+ const i = values.auth.indexOf(':');
84
+ if (i < 0 && values.auth) out.auth = { user: values.auth, password: undefined };
85
+ else if (i < 1 || i === values.auth.length - 1) throw new CliError('--auth must look like user (you are then asked for the password) or user:pass.');
86
+ else out.auth = { user: values.auth.slice(0, i), password: values.auth.slice(i + 1) };
87
+ }
88
+ if (values['host-header'] !== undefined) {
89
+ if (!values['host-header'] || /\s/.test(values['host-header'])) throw new CliError('--host-header must be a host name without spaces.');
90
+ out.hostHeader = values['host-header'];
91
+ }
92
+ return out;
93
+ }
94
+
95
+ // ---- frpc config -----------------------------------------------------------
96
+
97
+ // A TOML basic string. frp renders the whole file as a Go template, so "{{" is refused.
98
+ export function tomlString(s) {
99
+ if (typeof s !== 'string' || !s.isWellFormed()) throw new CliError('A value contains characters that cannot be used in the tunnel config.');
100
+ if (s.includes('{{')) throw new CliError('The characters {{ are not allowed in tunnel options.');
101
+ return JSON.stringify(s).replace(/\u007f/g, '\\u007f');
102
+ }
103
+
104
+ /**
105
+ * The frpc TOML. Secrets are not in it: the token and the key secret come from the
106
+ * environment of the frpc process (BESTGATE_TOKEN, BESTGATE_SECRET) through frp templates.
107
+ */
108
+ export function buildConfig({ serverAddr, serverPort = 443, protocol = 'wss', user, name, port, auth, hostHeader }) {
109
+ const lines = [
110
+ '# generated by bestgate, removed when the tunnel stops',
111
+ `serverAddr = ${tomlString(serverAddr)}`,
112
+ `serverPort = ${Number(serverPort)}`,
113
+ `user = ${tomlString(user)}`,
114
+ 'loginFailExit = true',
115
+ 'auth.method = "token"',
116
+ 'auth.token = "{{ .Envs.BESTGATE_TOKEN }}"',
117
+ 'metadatas.key = "{{ .Envs.BESTGATE_SECRET }}"',
118
+ // Must match frps: work connections and heartbeats carry the token too.
119
+ 'auth.additionalScopes = ["HeartBeats", "NewWorkConns"]',
120
+ `transport.protocol = ${tomlString(protocol)}`,
121
+ ];
122
+ if (protocol === 'wss') lines.push('transport.tls.useSystemCa = true');
123
+ lines.push(
124
+ 'transport.heartbeatInterval = 30',
125
+ 'transport.heartbeatTimeout = 90',
126
+ '',
127
+ '[[proxies]]',
128
+ `name = ${tomlString(name)}`,
129
+ 'type = "http"',
130
+ `localPort = ${Number(port)}`,
131
+ `subdomain = ${tomlString(name)}`,
132
+ );
133
+ if (auth) lines.push(`httpUser = ${tomlString(auth.user)}`, `httpPassword = ${tomlString(auth.password)}`);
134
+ if (hostHeader) lines.push(`hostHeaderRewrite = ${tomlString(hostHeader)}`);
135
+ return lines.join('\n') + '\n';
136
+ }
137
+
138
+ // ---- frpc log lines --------------------------------------------------------
139
+ // Patterns come from frp v0.72.0:
140
+ // client/control.go:174 "[%s] start proxy success"
141
+ // client/control.go:172 "[%s] start error: %v" (v = error text sent by the server)
142
+ // pkg/util/vhost/router.go:11 "router config conflict"; server/proxy/proxy.go:586 "... is already in use"
143
+ // client/proxy/proxy.go:240 "connect to local service [ip:port] error: ..."
144
+ // client/service.go:314 "login to the server failed: <server reason>..."
145
+
146
+ const REASON_MESSAGES = {
147
+ IDLE: 'Tunnel closed after being idle. Run the same command again.',
148
+ EXPIRED: 'Your access has expired. Ask the server owner to renew it.',
149
+ REVOKED: 'Your access was revoked by the server owner.',
150
+ INVALID_KEY: 'The server did not accept your access key. Run "bestgate login" with a valid key.',
151
+ TUNNEL_LIMIT: 'You have reached the maximum number of tunnels on this server. Stop another tunnel first.',
152
+ BAD_SUBDOMAIN: 'The server did not accept this name. Choose another with --name.',
153
+ HTTP_ONLY: 'The server only allows http tunnels.',
154
+ };
155
+
156
+ const ANSI = /\u001b\[[0-9;]*m/g;
157
+
158
+ /**
159
+ * Classify one frpc output line.
160
+ * → { kind: 'reason', key, message } | { kind: 'conflict' } | { kind: 'ready' }
161
+ * | { kind: 'localdown' } | { kind: 'error' } | { kind: 'chatter' }
162
+ */
163
+ export function classifyLine(raw) {
164
+ const line = raw.replace(ANSI, '');
165
+ for (const [key, text] of Object.entries(REASONS)) {
166
+ if (line.includes(text)) return { kind: 'reason', key, message: REASON_MESSAGES[key] || text };
167
+ }
168
+ if (/start error:.*(router config conflict|already in use|already exists)/.test(line)) return { kind: 'conflict' };
169
+ if (line.includes('start proxy success')) return { kind: 'ready' };
170
+ if (line.includes('connect to local service')) return { kind: 'localdown' };
171
+ if (/\[(W|E)\]/.test(line)) return { kind: 'error' };
172
+ return { kind: 'chatter' };
173
+ }
174
+
175
+ // ---- start errors -----------------------------------------------------------
176
+
177
+ // Message for a failed frpc start. On Windows, EPERM/EACCES usually means security
178
+ // software (commonly Microsoft Defender, which classifies frp as a potentially unwanted
179
+ // app) blocked the binary.
180
+ export function spawnErrorMessage(err, frpcPath, platform = process.platform) {
181
+ if (platform === 'win32' && (err.code === 'EPERM' || err.code === 'EACCES')) {
182
+ return `Windows security software (commonly Microsoft Defender, which classifies frp as a potentially unwanted app) blocked frpc at ${frpcPath}.
183
+ ` +
184
+ 'See the "Windows" note in the README of @bestapps/bestgate.';
185
+ }
186
+ return `Could not start frpc: ${err.message}`;
187
+ }
188
+
189
+ // ---- run -------------------------------------------------------------------
190
+
191
+ export async function run(argv) {
192
+ const opts = parseTunnelArgs(argv);
193
+ const login = loadLogin();
194
+ if (!login) throw new CliError('You are not logged in. Run "bestgate login" first.');
195
+ let key;
196
+ try {
197
+ key = decodeKey(login.key);
198
+ } catch {
199
+ throw new CliError('The saved access key is not valid. Run "bestgate login" again.');
200
+ }
201
+ const name = opts.name ?? uuidv7Hex();
202
+ if (name === key.control) throw new CliError(`"${name}" is reserved by the server. Choose another with --name.`);
203
+
204
+ const env = process.env;
205
+ const { serverAddr, serverPort, protocol } = connectionSettings(env, key, login);
206
+ if (opts.auth && opts.auth.password === undefined) {
207
+ if (!process.stdin.isTTY) throw new CliError('--auth user asks for the password, but there is no terminal: use --auth user:pass.');
208
+ const { password } = await import('@inquirer/prompts');
209
+ opts.auth.password = await password({ message: `Password for ${opts.auth.user} on the tunnel:`, mask: '*', validate: (v) => v.length > 0 || 'Enter a password.' });
210
+ }
211
+
212
+ if (!(await resolves(serverAddr))) {
213
+ throw new CliError(`${serverAddr} does not resolve in DNS. Check the host with "bestgate login", or ask the server owner whether the DNS records exist.`);
214
+ }
215
+
216
+ const frpc = await ensureFrp('frpc');
217
+ const toml = buildConfig({ serverAddr, serverPort, protocol, user: key.user, name, port: opts.port, auth: opts.auth, hostHeader: opts.hostHeader });
218
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'bestgate-'));
219
+ const confPath = path.join(dir, 'frpc.toml');
220
+ fs.writeFileSync(confPath, toml, { mode: 0o600 });
221
+ const cleanup = () => fs.rmSync(dir, { recursive: true, force: true });
222
+
223
+ const url = `https://${name}.${login.host}`;
224
+ const child = spawn(frpc, ['-c', confPath], {
225
+ stdio: ['ignore', 'pipe', 'pipe'],
226
+ windowsHide: true,
227
+ env: { ...env, BESTGATE_TOKEN: key.token, BESTGATE_SECRET: key.secret },
228
+ });
229
+
230
+ let exitCode = null; // set when we decide to exit
231
+ let childClosed = false;
232
+ const closed = new Promise((resolve) => {
233
+ child.on('close', (code) => { childClosed = true; resolve(code); });
234
+ child.on('error', (e) => {
235
+ childClosed = true;
236
+ console.error(spawnErrorMessage(e, frpc));
237
+ exitCode = 1;
238
+ resolve(1);
239
+ });
240
+ });
241
+
242
+ const stop = (code) => {
243
+ if (exitCode === null) exitCode = code;
244
+ if (!childClosed) child.kill();
245
+ };
246
+ process.on('SIGINT', () => stop(0));
247
+ process.on('SIGTERM', () => stop(0));
248
+
249
+ let warnedLocal = false;
250
+ const onLine = (line) => {
251
+ if (!line.trim() || exitCode !== null) return;
252
+ const c = classifyLine(line);
253
+ switch (c.kind) {
254
+ case 'reason':
255
+ console.error(c.message);
256
+ return stop(1);
257
+ case 'conflict':
258
+ console.error(`The name "${name}" is already used by another tunnel. Choose another with --name.`);
259
+ return stop(1);
260
+ case 'ready':
261
+ console.log(`${url} → http://localhost:${opts.port}`);
262
+ if (!opts.auth) console.log('Note: this URL is public. Use --auth <user> to protect it with a password.');
263
+ console.log('Ctrl-C to stop');
264
+ return;
265
+ case 'localdown':
266
+ if (!warnedLocal) {
267
+ warnedLocal = true;
268
+ console.warn(`Nothing is answering on localhost:${opts.port} yet. Start your app; the tunnel keeps running.`);
269
+ }
270
+ if (opts.verbose) console.log(line);
271
+ return;
272
+ case 'error':
273
+ console.error(line.replace(ANSI, ''));
274
+ return;
275
+ default:
276
+ if (opts.verbose) console.log(line);
277
+ }
278
+ };
279
+ for (const stream of [child.stdout, child.stderr]) readline.createInterface({ input: stream }).on('line', onLine);
280
+
281
+ const code = await closed;
282
+ cleanup();
283
+ process.exit(exitCode !== null ? exitCode : code ?? 1);
284
+ }
package/src/frp.js ADDED
@@ -0,0 +1,133 @@
1
+ // The one place for the frp version and the per-platform checksums.
2
+ import { createHash } from 'node:crypto';
3
+ import { spawn } from 'node:child_process';
4
+ import fs from 'node:fs';
5
+ import os from 'node:os';
6
+ import path from 'node:path';
7
+ import { CliError } from './util.js';
8
+
9
+ export const FRP_VERSION = '0.72.0';
10
+
11
+ // sha256 of the release archives, from frp_sha256_checksums.txt of v0.72.0.
12
+ export const FRP_SHA256 = {
13
+ 'darwin_amd64.tar.gz': '60439dc6bf794c4182a1a4cac147d642f839d55201607208979eb23aecd09be9',
14
+ 'darwin_arm64.tar.gz': '6e8576c5b6b9914a86850f6ff4fb81c5a09e706f91f70f64d5f398558bdc9db8',
15
+ 'linux_amd64.tar.gz': 'daf719b32ca2778770bb92955e231a07414d754378b9af328aa2642862479804',
16
+ 'linux_arm64.tar.gz': '02180b857480302fd934e9ddbd50fe2f73229f99062f88756abc6de9df5e95cf',
17
+ 'windows_amd64.zip': '5197c1b69564089cdc229fc1260a0e25db1e722b1b7db45fe1542c3c43edf9ae',
18
+ 'windows_arm64.zip': 'e4b83b66c4045971dd9a47cdef16dd02af471aaa6667dd303e63b1a669162927',
19
+ };
20
+
21
+ export const RELEASE_BASE = `https://github.com/fatedier/frp/releases/download/v${FRP_VERSION}`;
22
+
23
+ const OS = { win32: 'windows', darwin: 'darwin', linux: 'linux' };
24
+ const sha256 = (buf) => createHash('sha256').update(buf).digest('hex');
25
+
26
+ // The release has no checksums of the binaries themselves, only of the archives. So the
27
+ // sha256 of each binary is recorded next to it at extraction (right after the archive
28
+ // matched its pinned hash) and checked again on every later use.
29
+ export const hashFile = (exe) => `${exe}.sha256`;
30
+
31
+ // Throws unless `buf` is the binary that was extracted to `exe` from a verified archive.
32
+ export function checkBinary(exe, buf) {
33
+ let want = null;
34
+ try { want = fs.readFileSync(hashFile(exe), 'utf8').trim(); } catch { /* missing */ }
35
+ if (!/^[0-9a-f]{64}$/.test(want || '') || sha256(buf) !== want) {
36
+ throw new CliError(`${exe} does not match the hash recorded when it was extracted from the verified frp archive. Remove ${path.dirname(exe)} and run again.`);
37
+ }
38
+ return true;
39
+ }
40
+
41
+ function cachedOk(exe) {
42
+ try { return checkBinary(exe, fs.readFileSync(exe)); } catch { return false; }
43
+ }
44
+ const ARCH = { x64: 'amd64', arm64: 'arm64' };
45
+
46
+ // → { platform: 'linux_amd64', ext: 'tar.gz', suffix: 'linux_amd64.tar.gz', archive: 'frp_0.72.0_linux_amd64.tar.gz' }
47
+ export function platformInfo(platform = process.platform, arch = process.arch) {
48
+ const o = OS[platform];
49
+ const a = ARCH[arch];
50
+ if (!o || !a) throw new CliError(`Unsupported platform ${platform}/${arch}. frp has builds for Windows, macOS and Linux on x64 and arm64.`);
51
+ const ext = o === 'windows' ? 'zip' : 'tar.gz';
52
+ const suffix = `${o}_${a}.${ext}`;
53
+ if (!FRP_SHA256[suffix]) throw new CliError(`No frp build is pinned for ${suffix}.`);
54
+ return { platform: `${o}_${a}`, ext, suffix, archive: `frp_${FRP_VERSION}_${suffix}` };
55
+ }
56
+
57
+ export function defaultCacheDir(env = process.env, platform = process.platform, home = os.homedir()) {
58
+ if (platform === 'win32') return path.join(env.LOCALAPPDATA || path.join(home, 'AppData', 'Local'), 'bestgate');
59
+ if (platform === 'darwin') return path.join(home, 'Library', 'Caches', 'bestgate');
60
+ return path.join(env.XDG_CACHE_HOME || path.join(home, '.cache'), 'bestgate');
61
+ }
62
+
63
+ function run(cmd, args) {
64
+ return new Promise((resolve, reject) => {
65
+ const child = spawn(cmd, args, { stdio: ['ignore', 'ignore', 'pipe'], windowsHide: true });
66
+ let err = '';
67
+ child.stderr.on('data', (d) => { err += d; });
68
+ child.on('error', reject);
69
+ child.on('close', (code) => (code === 0 ? resolve() : reject(new Error(err.trim() || `${cmd} exited with ${code}`))));
70
+ });
71
+ }
72
+
73
+ // On Windows use the system bsdtar (it reads .zip); a GNU tar from Git Bash cannot.
74
+ function tarCommand(platform) {
75
+ if (platform === 'win32') return path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'tar.exe');
76
+ return 'tar';
77
+ }
78
+
79
+ /**
80
+ * Make sure frpc or frps of the pinned version is on disk; return its absolute path.
81
+ * Options (the last four are for tests): cacheDir, fetch, baseUrl, platform, arch.
82
+ */
83
+ export async function ensureFrp(binary, opts = {}) {
84
+ if (binary !== 'frpc' && binary !== 'frps') throw new Error(`unknown binary ${binary}`);
85
+ const platform = opts.platform || process.platform;
86
+ const info = platformInfo(platform, opts.arch || process.arch);
87
+ const cacheDir = path.resolve(opts.cacheDir || defaultCacheDir());
88
+ const finalDir = path.join(cacheDir, `frp-${FRP_VERSION}-${info.platform}`);
89
+ const exe = path.join(finalDir, binary + (platform === 'win32' ? '.exe' : ''));
90
+ if (fs.existsSync(exe) && cachedOk(exe)) return exe;
91
+
92
+ const doFetch = opts.fetch || globalThis.fetch;
93
+ const url = `${opts.baseUrl || RELEASE_BASE}/${info.archive}`;
94
+ fs.mkdirSync(cacheDir, { recursive: true });
95
+ console.error(`Downloading frp ${FRP_VERSION} (${info.platform}), one time only...`);
96
+ let buf;
97
+ try {
98
+ const res = await doFetch(url, { redirect: 'follow' });
99
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
100
+ buf = Buffer.from(await res.arrayBuffer());
101
+ } catch (e) {
102
+ throw new CliError(`Could not download ${url}: ${e.message}`);
103
+ }
104
+ const got = sha256(buf);
105
+ if (got !== FRP_SHA256[info.suffix]) {
106
+ throw new CliError(`Checksum mismatch for ${info.archive}: expected ${FRP_SHA256[info.suffix]}, got ${got}. The download was discarded.`);
107
+ }
108
+
109
+ // Archive and extraction use temp names; the final folder appears only when complete.
110
+ const tmp = `${finalDir}.part-${process.pid}`;
111
+ const archive = `${tmp}.${info.ext}`;
112
+ fs.rmSync(tmp, { recursive: true, force: true });
113
+ fs.mkdirSync(tmp, { recursive: true });
114
+ try {
115
+ fs.writeFileSync(archive, buf);
116
+ try {
117
+ await run(tarCommand(platform), ['-xf', archive, '-C', tmp, '--strip-components=1']);
118
+ } catch (e) {
119
+ throw new CliError(`Could not extract the frp archive with tar: ${e.message}`);
120
+ }
121
+ if (!fs.existsSync(path.join(tmp, path.basename(exe)))) throw new CliError(`${path.basename(exe)} is not in the frp archive.`);
122
+ if (platform !== 'win32') for (const b of ['frpc', 'frps']) fs.chmodSync(path.join(tmp, b), 0o755);
123
+ for (const b of fs.readdirSync(tmp).filter((n) => /^frp[cs](\.exe)?$/.test(n))) {
124
+ fs.writeFileSync(hashFile(path.join(tmp, b)), sha256(fs.readFileSync(path.join(tmp, b))) + '\n', { mode: 0o644 });
125
+ }
126
+ fs.rmSync(finalDir, { recursive: true, force: true });
127
+ fs.renameSync(tmp, finalDir);
128
+ } finally {
129
+ fs.rmSync(archive, { force: true });
130
+ fs.rmSync(tmp, { recursive: true, force: true });
131
+ }
132
+ return exe;
133
+ }
package/src/key.js ADDED
@@ -0,0 +1,56 @@
1
+ // Access key: 'bg_' + base64url(JSON {v:1, u:user, s:secret, t:frps token, c:control label}).
2
+ // Shared by the client (Node >= 20) and the server, so only node:crypto is used.
3
+ import { createHash, randomBytes } from 'node:crypto';
4
+
5
+ export const NAME_RE = /^[a-z0-9][a-z0-9-]{1,30}$/;
6
+ export const LABEL_RE = /^[a-z0-9]([a-z0-9-]{0,30}[a-z0-9])?$/;
7
+ export const SECRET_RE = /^[A-Za-z0-9_-]{43}$/; // 32 bytes, base64url, no padding
8
+ // The token ends up in frpc's toml and frps.env, so only characters that need no quoting anywhere.
9
+ export const TOKEN_RE = /^[A-Za-z0-9._~+/=-]{16,256}$/;
10
+
11
+ const MAX_KEY_LENGTH = 2048;
12
+
13
+ function checkFields({ user, secret, token, control }) {
14
+ const bad = [];
15
+ if (typeof user !== 'string' || !NAME_RE.test(user)) bad.push('user');
16
+ if (typeof secret !== 'string' || !SECRET_RE.test(secret)) bad.push('secret');
17
+ if (typeof token !== 'string' || !TOKEN_RE.test(token)) bad.push('token');
18
+ if (typeof control !== 'string' || !LABEL_RE.test(control)) bad.push('control label');
19
+ return bad;
20
+ }
21
+
22
+ export function encodeKey({ user, secret, token, control }) {
23
+ const bad = checkFields({ user, secret, token, control });
24
+ if (bad.length) throw new Error(`cannot build access key: invalid ${bad.join(', ')}`);
25
+ const json = JSON.stringify({ v: 1, u: user, s: secret, t: token, c: control });
26
+ return 'bg_' + Buffer.from(json, 'utf8').toString('base64url');
27
+ }
28
+
29
+ export function decodeKey(str) {
30
+ if (typeof str !== 'string') throw new Error('access key must be a string');
31
+ const s = str.trim();
32
+ if (!s.startsWith('bg_')) throw new Error('access key must start with "bg_"');
33
+ if (s.length > MAX_KEY_LENGTH) throw new Error('access key is too long');
34
+ const body = s.slice(3);
35
+ if (!/^[A-Za-z0-9_-]+$/.test(body)) throw new Error('access key contains invalid characters');
36
+ let obj;
37
+ try {
38
+ obj = JSON.parse(Buffer.from(body, 'base64url').toString('utf8'));
39
+ } catch {
40
+ throw new Error('access key is damaged (cannot decode)');
41
+ }
42
+ if (!obj || typeof obj !== 'object' || Array.isArray(obj)) throw new Error('access key is damaged (not an object)');
43
+ if (obj.v !== 1) throw new Error('access key has an unsupported version');
44
+ const out = { user: obj.u, secret: obj.s, token: obj.t, control: obj.c };
45
+ const bad = checkFields(out);
46
+ if (bad.length) throw new Error(`access key is damaged (invalid ${bad.join(', ')})`);
47
+ return out;
48
+ }
49
+
50
+ export function newSecret() {
51
+ return randomBytes(32).toString('base64url');
52
+ }
53
+
54
+ export function hashSecret(secret) {
55
+ return createHash('sha256').update(String(secret), 'utf8').digest('hex');
56
+ }
package/src/reasons.js ADDED
@@ -0,0 +1,11 @@
1
+ // Reject reasons sent by the auth daemon to frps and shown to frpc.
2
+ // The client matches on these prefixes, so change them only together.
3
+ export const REASONS = Object.freeze({
4
+ IDLE: 'bestgate: idle timeout',
5
+ EXPIRED: 'bestgate: access expired',
6
+ REVOKED: 'bestgate: access revoked',
7
+ INVALID_KEY: 'bestgate: invalid key',
8
+ TUNNEL_LIMIT: 'bestgate: tunnel limit reached',
9
+ BAD_SUBDOMAIN: 'bestgate: invalid subdomain',
10
+ HTTP_ONLY: 'bestgate: only http tunnels are allowed',
11
+ });
@@ -0,0 +1,72 @@
1
+ // `bestgate server cert`: get or renew the wildcard certificate *.<baseDomain> with
2
+ // certbot's manual DNS-01 challenge, with the terminal attached (you add a TXT record
3
+ // when certbot asks). The same command renews. --no-autorenew keeps `certbot renew`
4
+ // (which runs for every other certificate) away from this manual lineage.
5
+ import { CliError } from '../util.js';
6
+ import { loadConfig } from './config.js';
7
+ import { P, createContext, openLog, requireRoot, certInfo, certFiles, parseFlags } from './sys.js';
8
+ import { loadServerConfig } from './plan.js';
9
+ import { loadManifest } from './manifest.js';
10
+
11
+ export function certbotArgs(cfg) {
12
+ const args = ['certonly', '--manual', '--preferred-challenges', 'dns', '--no-autorenew', '--cert-name', cfg.baseDomain, '-d', `*.${cfg.baseDomain}`];
13
+ if (cfg.certbotAccount) args.push('--account', cfg.certbotAccount);
14
+ return args;
15
+ }
16
+
17
+ // The zone's authoritative name servers: walk up from _acme-challenge.<base>.
18
+ export async function authoritativeNs(ctx, baseDomain) {
19
+ const labels = baseDomain.split('.');
20
+ for (let i = 0; i < labels.length - 1; i++) {
21
+ const zone = labels.slice(i).join('.');
22
+ const ns = await ctx.resolveNs(zone);
23
+ if (ns.length) return { zone, ns: ns.map((n) => n.toLowerCase()).sort() };
24
+ }
25
+ return { zone: null, ns: [] };
26
+ }
27
+
28
+ export async function run(argv = [], opts = {}) {
29
+ const flags = parseFlags(argv, { '--config': 'value' });
30
+ const ctx = opts.ctx || createContext();
31
+ requireRoot(ctx);
32
+ const cfg = flags.config ? loadConfig(flags.config) : loadServerConfig(ctx);
33
+ if (!ctx.isTTY) throw new CliError('`bestgate server cert` is interactive (certbot asks you to add a DNS record): run it in a terminal.');
34
+ if (!ctx.which('certbot')) throw new CliError('certbot is not installed (snap install --classic certbot).');
35
+ openLog(ctx, 'cert');
36
+
37
+ const name = `_acme-challenge.${cfg.baseDomain}`;
38
+ const before = certInfo(ctx, cfg);
39
+ const { zone, ns } = await authoritativeNs(ctx, cfg.baseDomain);
40
+ ctx.say(`Certificate for *.${cfg.baseDomain} (certbot lineage "${cfg.baseDomain}").`);
41
+ if (before.present && !before.error) ctx.say(`Current one: ${before.daysLeft} days left (until ${before.validTo}).`);
42
+ ctx.say('');
43
+ ctx.say('certbot will show a value and ask you to create this DNS record:');
44
+ ctx.say(` ${name}. TXT "<value certbot shows>"`);
45
+ ctx.say('Before you press Enter in certbot, check that the authoritative server already answers it:');
46
+ if (ns.length) ctx.say(` dig +short TXT ${name} @${ns[0]}`);
47
+ else ctx.say(` dig +short NS <your zone> then dig +short TXT ${name} @<one of those servers>`);
48
+ if (zone) ctx.say(`(zone ${zone}, name servers: ${ns.join(', ')})`);
49
+ ctx.say('Remove the TXT record afterwards if you like; it is needed again at the next renewal.');
50
+ ctx.say('');
51
+
52
+ const args = certbotArgs(cfg);
53
+ ctx.say(`$ certbot ${args.join(' ')}`);
54
+ const r = ctx.exec('certbot', args, { inherit: true, timeoutMs: 3 * 3600 * 1000 });
55
+ if (r.code !== 0) throw new CliError(`certbot exited with ${r.code}; nothing else was changed.`);
56
+
57
+ const after = certInfo(ctx, cfg);
58
+ if (!after.present || after.error || !after.coversWildcard) throw new CliError(`certbot finished but ${after.file} is missing or does not cover *.${cfg.baseDomain}.`);
59
+ ctx.say(`OK certificate for *.${cfg.baseDomain}: ${after.daysLeft} days left (until ${after.validTo})`);
60
+ const renewal = ctx.readOrNull(certFiles(cfg.baseDomain).renewal);
61
+ if (renewal !== null && /^\s*autorenew\s*=\s*False\s*$/m.test(renewal)) ctx.say('OK automatic renewal is off for this lineage (renew with this command)');
62
+ else ctx.say(`WARN ${certFiles(cfg.baseDomain).renewal} does not say autorenew = False: \`certbot renew\` would try this manual lineage and fail`);
63
+
64
+ // If the site is installed, nginx must load the new certificate.
65
+ let m = null;
66
+ try { m = loadManifest(ctx); } catch { /* reported by plan */ }
67
+ if (m && m.entries.some((e) => e.path.startsWith(`${P.nginxDir}/`))) {
68
+ const t = ctx.run('nginx', ['-t']);
69
+ if (t.code === 0) ctx.change('systemctl', ['reload', 'nginx']);
70
+ else ctx.say(`WARN nginx -t fails, so nginx was not reloaded:\n${t.stderr.trim()}`);
71
+ } else ctx.say('Next: sudo bestgate server install');
72
+ }
@@ -0,0 +1,47 @@
1
+ // `bestgate server check`: what the daily timer runs, as root. It does not open the
2
+ // database. It writes P.checkFile for the login message (motd snippet):
3
+ // empty file = all well; otherwise up to 20 lines of printable ASCII, each "bestgate: ...".
4
+ // Exit code 0 even when problems were found (they are reported in the file);
5
+ // non-zero only when the check itself could not run.
6
+ import { P, createContext, requireRoot, checkDns, certInfo } from './sys.js';
7
+ import { loadServerConfig } from './plan.js';
8
+
9
+ export const MAX_LINES = 20;
10
+ export const CERT_WARN_DAYS = 30;
11
+
12
+ const ascii = (s) => String(s).replace(/[^\x20-\x7e]/g, '?');
13
+
14
+ // -> array of "bestgate: ..." lines; empty when all is well.
15
+ export async function checkProblems(ctx, cfg) {
16
+ const lines = [];
17
+ for (const x of await checkDns(ctx, cfg)) {
18
+ if (!x.ok) {
19
+ const got = x.addresses.length ? x.addresses.join(', ') : 'nothing';
20
+ lines.push(`bestgate: DNS ${x.name} resolves to ${got}, expected ${cfg.publicIp}. Tunnels will not work until the record is fixed.`);
21
+ }
22
+ }
23
+
24
+ const c = certInfo(ctx, cfg);
25
+ if (!c.present) {
26
+ lines.push(`bestgate: certificate for *.${cfg.baseDomain} is missing. Run \`bestgate server cert\`.`);
27
+ } else if (c.error) {
28
+ lines.push(`bestgate: certificate for *.${cfg.baseDomain} cannot be read. Run \`bestgate server cert\`.`);
29
+ } else if (c.daysLeft < 0) {
30
+ lines.push(`bestgate: certificate expired ${-c.daysLeft} days ago. \`bestgate server cert\` renews it.`);
31
+ } else if (c.daysLeft < CERT_WARN_DAYS) {
32
+ lines.push(`bestgate: certificate has ${c.daysLeft} days left. \`bestgate server cert\` renews it.`);
33
+ } else if (!c.coversWildcard) {
34
+ lines.push(`bestgate: certificate does not cover *.${cfg.baseDomain}. Run \`bestgate server cert\`.`);
35
+ }
36
+ return lines.map(ascii).slice(0, MAX_LINES);
37
+ }
38
+
39
+ export async function run(argv = [], opts = {}) {
40
+ const ctx = opts.ctx || createContext();
41
+ requireRoot(ctx);
42
+ const cfg = loadServerConfig(ctx);
43
+ const lines = await checkProblems(ctx, cfg);
44
+ ctx.writeFile(P.checkFile, lines.length ? lines.join('\n') + '\n' : '', { mode: 0o640, quiet: true });
45
+ ctx.say(lines.length ? `check: ${lines.length} problem(s) written to ${P.checkFile}` : 'check: all well');
46
+ return lines;
47
+ }