@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
package/src/server/db.js
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
// The only module that touches node:sqlite (Node >= 22.13). Two processes write
|
|
2
|
+
// this database: the auth daemon and the root `bestgate server user ...` commands.
|
|
3
|
+
// All times are integer milliseconds passed in by the caller.
|
|
4
|
+
//
|
|
5
|
+
// User lifecycle:
|
|
6
|
+
// addUser - new user; last_used_at = created_at, so a never-used key is not expired.
|
|
7
|
+
// touchUser - successful login / active tunnel; ignored for revoked users.
|
|
8
|
+
// renewUser - restarts the expiry clock (last_used_at = now). Does NOT un-revoke.
|
|
9
|
+
// setKeyHash - re-issues a key: new hash, last_used_at = now, revoked_at cleared.
|
|
10
|
+
// Sessions using the old key are kicked at their next Ping.
|
|
11
|
+
// revokeUser - sets revoked_at; connected clients are kicked at their next Ping.
|
|
12
|
+
// removeUser - deletes the row; connected clients are kicked at their next Ping.
|
|
13
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
14
|
+
import { PATHS } from './config.js';
|
|
15
|
+
import { NAME_RE } from '../key.js';
|
|
16
|
+
|
|
17
|
+
const SCHEMA_VERSION = 1;
|
|
18
|
+
const HASH_RE = /^[0-9a-f]{64}$/;
|
|
19
|
+
|
|
20
|
+
const SCHEMA = `
|
|
21
|
+
CREATE TABLE IF NOT EXISTS users (
|
|
22
|
+
name TEXT PRIMARY KEY,
|
|
23
|
+
key_hash TEXT NOT NULL,
|
|
24
|
+
created_at INTEGER NOT NULL,
|
|
25
|
+
last_used_at INTEGER NOT NULL,
|
|
26
|
+
revoked_at INTEGER
|
|
27
|
+
);
|
|
28
|
+
CREATE TABLE IF NOT EXISTS sessions (
|
|
29
|
+
run_id TEXT PRIMARY KEY,
|
|
30
|
+
user TEXT NOT NULL,
|
|
31
|
+
created_at INTEGER NOT NULL,
|
|
32
|
+
last_activity_at INTEGER NOT NULL,
|
|
33
|
+
last_seen_at INTEGER NOT NULL,
|
|
34
|
+
traffic TEXT NOT NULL DEFAULT '{}',
|
|
35
|
+
closed_reason TEXT,
|
|
36
|
+
closed_at INTEGER
|
|
37
|
+
);
|
|
38
|
+
CREATE INDEX IF NOT EXISTS sessions_user ON sessions(user);
|
|
39
|
+
CREATE TABLE IF NOT EXISTS meta (
|
|
40
|
+
key TEXT PRIMARY KEY,
|
|
41
|
+
value INTEGER
|
|
42
|
+
);
|
|
43
|
+
`;
|
|
44
|
+
|
|
45
|
+
function checkName(name) {
|
|
46
|
+
if (typeof name !== 'string' || !NAME_RE.test(name)) {
|
|
47
|
+
throw new Error('invalid user name: use 2-31 chars a-z, 0-9, "-", starting with a letter or digit');
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
function checkHash(h) {
|
|
51
|
+
if (typeof h !== 'string' || !HASH_RE.test(h)) throw new Error('invalid key hash');
|
|
52
|
+
}
|
|
53
|
+
function checkTime(t) {
|
|
54
|
+
if (!Number.isSafeInteger(t) || t < 0) throw new Error('invalid time');
|
|
55
|
+
}
|
|
56
|
+
const plain = (row) => (row ? { ...row } : null);
|
|
57
|
+
|
|
58
|
+
export function openDb(file = PATHS.dbFile) {
|
|
59
|
+
const db = new DatabaseSync(file);
|
|
60
|
+
db.exec('PRAGMA busy_timeout = 5000');
|
|
61
|
+
db.exec('PRAGMA journal_mode = WAL');
|
|
62
|
+
db.exec('PRAGMA foreign_keys = ON');
|
|
63
|
+
const version = db.prepare('PRAGMA user_version').get().user_version;
|
|
64
|
+
if (version > SCHEMA_VERSION) {
|
|
65
|
+
db.close();
|
|
66
|
+
throw new Error(`database ${file} has schema version ${version}, this bestgate knows ${SCHEMA_VERSION}; upgrade bestgate`);
|
|
67
|
+
}
|
|
68
|
+
if (version < SCHEMA_VERSION) {
|
|
69
|
+
db.exec('BEGIN IMMEDIATE');
|
|
70
|
+
try {
|
|
71
|
+
db.exec(SCHEMA);
|
|
72
|
+
db.exec(`PRAGMA user_version = ${SCHEMA_VERSION}`);
|
|
73
|
+
db.exec('COMMIT');
|
|
74
|
+
} catch (e) {
|
|
75
|
+
db.exec('ROLLBACK');
|
|
76
|
+
db.close();
|
|
77
|
+
throw e;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const st = {
|
|
82
|
+
addUser: db.prepare('INSERT INTO users (name, key_hash, created_at, last_used_at) VALUES (?, ?, ?, ?)'),
|
|
83
|
+
getUser: db.prepare('SELECT * FROM users WHERE name = ?'),
|
|
84
|
+
listUsers: db.prepare('SELECT * FROM users ORDER BY name'),
|
|
85
|
+
touchUser: db.prepare('UPDATE users SET last_used_at = MAX(last_used_at, ?) WHERE name = ? AND revoked_at IS NULL'),
|
|
86
|
+
renewUser: db.prepare('UPDATE users SET last_used_at = ? WHERE name = ?'),
|
|
87
|
+
setKeyHash: db.prepare('UPDATE users SET key_hash = ?, last_used_at = ?, revoked_at = NULL WHERE name = ?'),
|
|
88
|
+
revokeUser: db.prepare('UPDATE users SET revoked_at = ? WHERE name = ? AND revoked_at IS NULL'),
|
|
89
|
+
removeUser: db.prepare('DELETE FROM users WHERE name = ?'),
|
|
90
|
+
getSession: db.prepare('SELECT * FROM sessions WHERE run_id = ?'),
|
|
91
|
+
listSessions: db.prepare('SELECT * FROM sessions ORDER BY created_at'),
|
|
92
|
+
ensureSession: db.prepare(`INSERT INTO sessions (run_id, user, created_at, last_activity_at, last_seen_at)
|
|
93
|
+
VALUES (?, ?, ?, ?, ?) ON CONFLICT(run_id) DO NOTHING`),
|
|
94
|
+
seenSession: db.prepare('UPDATE sessions SET last_seen_at = MAX(last_seen_at, ?) WHERE run_id = ?'),
|
|
95
|
+
setTraffic: db.prepare('UPDATE sessions SET traffic = ? WHERE run_id = ? AND closed_reason IS NULL'),
|
|
96
|
+
setActivity: db.prepare(`UPDATE sessions SET traffic = ?, last_activity_at = MAX(last_activity_at, ?)
|
|
97
|
+
WHERE run_id = ? AND closed_reason IS NULL`),
|
|
98
|
+
closeSession: db.prepare(`UPDATE sessions SET closed_reason = ?, closed_at = ?, last_seen_at = MAX(last_seen_at, ?)
|
|
99
|
+
WHERE run_id = ? AND closed_reason IS NULL`),
|
|
100
|
+
shiftOpen: db.prepare('UPDATE sessions SET last_activity_at = last_activity_at + ? WHERE closed_reason IS NULL'),
|
|
101
|
+
gc: db.prepare('DELETE FROM sessions WHERE closed_reason IS NOT NULL AND last_seen_at < ?'),
|
|
102
|
+
getMeta: db.prepare('SELECT value FROM meta WHERE key = ?'),
|
|
103
|
+
setMeta: db.prepare('INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value'),
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
return {
|
|
107
|
+
// users
|
|
108
|
+
addUser(name, keyHash, now) {
|
|
109
|
+
checkName(name); checkHash(keyHash); checkTime(now);
|
|
110
|
+
try {
|
|
111
|
+
st.addUser.run(name, keyHash, now, now);
|
|
112
|
+
} catch (e) {
|
|
113
|
+
if (/UNIQUE|PRIMARY KEY/.test(e.message)) throw new Error(`user ${name} already exists`);
|
|
114
|
+
throw e;
|
|
115
|
+
}
|
|
116
|
+
},
|
|
117
|
+
getUser(name) {
|
|
118
|
+
if (typeof name !== 'string' || !NAME_RE.test(name)) return null;
|
|
119
|
+
return plain(st.getUser.get(name));
|
|
120
|
+
},
|
|
121
|
+
listUsers() { return st.listUsers.all().map(plain); },
|
|
122
|
+
touchUser(name, now) { checkTime(now); return st.touchUser.run(now, name).changes > 0; },
|
|
123
|
+
renewUser(name, now) { checkName(name); checkTime(now); return st.renewUser.run(now, name).changes > 0; },
|
|
124
|
+
setKeyHash(name, keyHash, now) {
|
|
125
|
+
checkName(name); checkHash(keyHash); checkTime(now);
|
|
126
|
+
return st.setKeyHash.run(keyHash, now, name).changes > 0;
|
|
127
|
+
},
|
|
128
|
+
revokeUser(name, now) { checkName(name); checkTime(now); return st.revokeUser.run(now, name).changes > 0; },
|
|
129
|
+
removeUser(name) { checkName(name); return st.removeUser.run(name).changes > 0; },
|
|
130
|
+
|
|
131
|
+
// sessions (one per frpc run_id)
|
|
132
|
+
getSession(runId) { return plain(st.getSession.get(String(runId))); },
|
|
133
|
+
listSessions() { return st.listSessions.all().map(plain); },
|
|
134
|
+
// Creates the session if missing; returns the stored row (which may belong to another user).
|
|
135
|
+
ensureSession(runId, user, now) {
|
|
136
|
+
checkTime(now);
|
|
137
|
+
st.ensureSession.run(String(runId), String(user), now, now, now);
|
|
138
|
+
return plain(st.getSession.get(String(runId)));
|
|
139
|
+
},
|
|
140
|
+
seenSession(runId, now) { checkTime(now); st.seenSession.run(now, String(runId)); },
|
|
141
|
+
setSessionTraffic(runId, traffic) { st.setTraffic.run(String(traffic), String(runId)); },
|
|
142
|
+
setSessionActivity(runId, traffic, now) { checkTime(now); st.setActivity.run(String(traffic), now, String(runId)); },
|
|
143
|
+
closeSession(runId, reason, now) {
|
|
144
|
+
checkTime(now);
|
|
145
|
+
return st.closeSession.run(String(reason), now, now, String(runId)).changes > 0;
|
|
146
|
+
},
|
|
147
|
+
// Moves idle clocks forward, so time the daemon could not watch does not count as idle.
|
|
148
|
+
shiftOpenSessions(deltaMs) { if (Number.isSafeInteger(deltaMs) && deltaMs > 0) st.shiftOpen.run(deltaMs); },
|
|
149
|
+
// Drops closed sessions whose frpc has not retried since `before`. Open sessions are
|
|
150
|
+
// never dropped here: the poller idle-closes them first (offline ones show no activity).
|
|
151
|
+
gcSessions(before) { checkTime(before); return st.gc.run(before).changes; },
|
|
152
|
+
|
|
153
|
+
// meta
|
|
154
|
+
getMeta(key) { const r = st.getMeta.get(String(key)); return r ? r.value : null; },
|
|
155
|
+
setMeta(key, value) { st.setMeta.run(String(key), value); },
|
|
156
|
+
|
|
157
|
+
transaction(fn) {
|
|
158
|
+
db.exec('BEGIN IMMEDIATE');
|
|
159
|
+
try {
|
|
160
|
+
const r = fn();
|
|
161
|
+
db.exec('COMMIT');
|
|
162
|
+
return r;
|
|
163
|
+
} catch (e) {
|
|
164
|
+
try { db.exec('ROLLBACK'); } catch { /* already rolled back */ }
|
|
165
|
+
throw e;
|
|
166
|
+
}
|
|
167
|
+
},
|
|
168
|
+
close() { db.close(); },
|
|
169
|
+
};
|
|
170
|
+
}
|
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
// `bestgate server install [--dry-run] [--yes] [--answers <file>]`
|
|
2
|
+
// Installs or updates frps, the auth daemon, the systemd units, the motd snippet and
|
|
3
|
+
// the nginx site. Safe to run again: unchanged files are left alone and nothing is
|
|
4
|
+
// restarted or reloaded without a reason. nginx is reloaded only after `nginx -t`
|
|
5
|
+
// passed, and the site is rolled back if another site answers differently afterwards.
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
8
|
+
import { CliError } from '../util.js';
|
|
9
|
+
import { TOKEN_RE } from '../key.js';
|
|
10
|
+
import { FRP_VERSION, checkBinary } from '../frp.js';
|
|
11
|
+
import { PLUGIN_SECRET_RE, validateConfig, loadEnvFile } from './config.js';
|
|
12
|
+
import {
|
|
13
|
+
P, UNITS, DAEMON_USER, createContext, openLog, requireRoot, requireNode, report, askConfirm, parseFlags,
|
|
14
|
+
probeCheckUrls, listeningPorts, showCommand,
|
|
15
|
+
} from './sys.js';
|
|
16
|
+
import { collectPlan, buildTargets, describeInstall, loadServerConfig } from './plan.js';
|
|
17
|
+
import { loadManifest, newManifest, saveManifest, track } from './manifest.js';
|
|
18
|
+
import { runVerify } from './verify.js';
|
|
19
|
+
|
|
20
|
+
const newSecret = () => randomBytes(32).toString('base64url');
|
|
21
|
+
const newPluginSecret = () => randomBytes(32).toString('hex');
|
|
22
|
+
|
|
23
|
+
function packageVersion() {
|
|
24
|
+
try { return JSON.parse(fs.readFileSync(new URL('../../package.json', import.meta.url), 'utf8')).version; } catch { return '?'; }
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// Changes to any of these restart the services even if no file they read changed.
|
|
28
|
+
function fingerprint(cfg) {
|
|
29
|
+
return createHash('sha256').update(JSON.stringify({ cfg, pkg: packageVersion(), frp: FRP_VERSION })).digest('hex');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async function getConfig(ctx, flags, opts) {
|
|
33
|
+
if (flags.answers || !ctx.exists(P.configFile)) {
|
|
34
|
+
const runWizard = opts.wizard || (await import('./wizard.js')).runWizard;
|
|
35
|
+
if (typeof runWizard !== 'function') throw new CliError('The setup wizard is not available in this installation.');
|
|
36
|
+
const cfg = await runWizard({ answersFile: flags.answers || null, save: !ctx.dryRun, configFile: ctx.disk(P.configFile) });
|
|
37
|
+
return validateConfig(cfg);
|
|
38
|
+
}
|
|
39
|
+
return loadServerConfig(ctx);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// frps.env: generated once, never regenerated or printed. A plugin secret missing from an
|
|
43
|
+
// older file is added (it is not part of any access key). → { token, password, plugin, changed }
|
|
44
|
+
function ensureSecrets(ctx, m) {
|
|
45
|
+
if (ctx.exists(P.envFile)) {
|
|
46
|
+
if (ctx.dryRun) {
|
|
47
|
+
ctx.say(` ${P.envFile}: present, kept as is (BESTGATE_PLUGIN_SECRET is added if it is missing)`);
|
|
48
|
+
return { token: 'x'.repeat(43), password: 'x'.repeat(43), plugin: '0'.repeat(64) };
|
|
49
|
+
}
|
|
50
|
+
const env = loadEnvFile(ctx.disk(P.envFile));
|
|
51
|
+
const token = env.FRP_AUTH_TOKEN;
|
|
52
|
+
const password = env.FRP_DASHBOARD_PASSWORD;
|
|
53
|
+
if (!TOKEN_RE.test(token || '') || !TOKEN_RE.test(password || '')) {
|
|
54
|
+
throw new CliError(`${P.envFile} must hold FRP_AUTH_TOKEN and FRP_DASHBOARD_PASSWORD (16-256 chars of A-Z a-z 0-9 . _ ~ + / = -). ` +
|
|
55
|
+
'It is never regenerated, because every access key contains the token: fix it by hand.');
|
|
56
|
+
}
|
|
57
|
+
let plugin = env.BESTGATE_PLUGIN_SECRET;
|
|
58
|
+
let changed = false;
|
|
59
|
+
if (plugin === undefined) {
|
|
60
|
+
plugin = newPluginSecret();
|
|
61
|
+
const raw = ctx.read(P.envFile);
|
|
62
|
+
ctx.writeFile(P.envFile, `${raw}${raw.endsWith('\n') || raw === '' ? '' : '\n'}BESTGATE_PLUGIN_SECRET=${plugin}\n`, { mode: 0o600, secret: true });
|
|
63
|
+
changed = true;
|
|
64
|
+
} else if (!PLUGIN_SECRET_RE.test(plugin)) {
|
|
65
|
+
throw new CliError(`BESTGATE_PLUGIN_SECRET in ${P.envFile} must be 64 hex characters: fix it by hand, or delete that line and run install again.`);
|
|
66
|
+
}
|
|
67
|
+
const mode = ctx.fileMode(P.envFile);
|
|
68
|
+
if (ctx.posixModes && mode !== 0o600) ctx.change('chmod', ['0600', ctx.disk(P.envFile)]);
|
|
69
|
+
return { token, password, plugin, changed };
|
|
70
|
+
}
|
|
71
|
+
const s = { token: newSecret(), password: newSecret(), plugin: newPluginSecret(), created: true, changed: true };
|
|
72
|
+
track(ctx, m, P.envFile, 'file', { keep: true });
|
|
73
|
+
ctx.writeFile(P.envFile, `FRP_AUTH_TOKEN=${s.token}\nFRP_DASHBOARD_PASSWORD=${s.password}\nBESTGATE_PLUGIN_SECRET=${s.plugin}\n`,
|
|
74
|
+
{ mode: 0o600, secret: true });
|
|
75
|
+
return s;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async function installFrps(ctx, m) {
|
|
79
|
+
if (ctx.dryRun) {
|
|
80
|
+
ctx.say(` would download frp ${FRP_VERSION} (sha256 pinned in src/frp.js) to ${P.cacheDir} and install frps as ${P.frpsBin} (0755 root:root)`);
|
|
81
|
+
return true;
|
|
82
|
+
}
|
|
83
|
+
const src = await ctx.ensureFrp('frps', { cacheDir: ctx.disk(P.cacheDir) });
|
|
84
|
+
const buf = fs.readFileSync(src);
|
|
85
|
+
// These exact bytes are what gets installed: check them, not the file, against the hash
|
|
86
|
+
// recorded when the verified archive was extracted into the root-only cache.
|
|
87
|
+
checkBinary(src, buf);
|
|
88
|
+
const dest = ctx.disk(P.frpsBin);
|
|
89
|
+
let cur = null;
|
|
90
|
+
try { cur = fs.readFileSync(dest); } catch { /* new */ }
|
|
91
|
+
if (cur && cur.equals(buf)) return false;
|
|
92
|
+
track(ctx, m, P.frpsBin, 'file');
|
|
93
|
+
ctx.journal.push({ op: 'write', path: P.frpsBin, mode: 0o755, owner: 'root:root' });
|
|
94
|
+
ctx.say(` install ${P.frpsBin} (frp ${FRP_VERSION}, 0755 root:root)`);
|
|
95
|
+
const tmp = `${dest}.bestgate-tmp`;
|
|
96
|
+
fs.rmSync(tmp, { force: true });
|
|
97
|
+
fs.writeFileSync(tmp, buf, { mode: 0o755, flag: 'wx' });
|
|
98
|
+
fs.chmodSync(tmp, 0o755);
|
|
99
|
+
fs.renameSync(tmp, dest);
|
|
100
|
+
return true;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// Only a database file root itself left behind (an older bestgate opened it as root) is
|
|
104
|
+
// handed to the daemon user: a plain file with one link, owned by root. A symlink, a hard
|
|
105
|
+
// link or a file the daemon user already owns is left alone (chown --no-dereference too).
|
|
106
|
+
function rootOwnedPlainFile(ctx, p) {
|
|
107
|
+
let st;
|
|
108
|
+
try { st = fs.lstatSync(ctx.disk(p)); } catch { return false; }
|
|
109
|
+
if (!st.isFile() || st.nlink !== 1) return false;
|
|
110
|
+
return !ctx.posixModes || st.uid === 0;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function writeTarget(ctx, m, x) {
|
|
114
|
+
track(ctx, m, x.path, x.kind === 'link' ? 'link' : 'file');
|
|
115
|
+
if (x.kind === 'link') return ctx.symlink(x.target, x.path);
|
|
116
|
+
return ctx.writeFile(x.path, x.content, { mode: x.mode });
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const isActive = (ctx, unit) => ctx.run('systemctl', ['is-active', unit]).stdout.trim() === 'active';
|
|
120
|
+
const isEnabled = (ctx, unit) => ctx.run('systemctl', ['is-enabled', unit]).stdout.trim() === 'enabled';
|
|
121
|
+
|
|
122
|
+
async function startUnit(ctx, unit, restart, port) {
|
|
123
|
+
if (!isEnabled(ctx, unit)) ctx.change('systemctl', ['enable', unit]);
|
|
124
|
+
if (!restart && isActive(ctx, unit)) {
|
|
125
|
+
ctx.say(` ${unit}: unchanged and running`);
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
ctx.change('systemctl', ['restart', unit]);
|
|
129
|
+
if (ctx.dryRun) return;
|
|
130
|
+
for (let i = 0; i < 20; i++) {
|
|
131
|
+
await ctx.wait(500);
|
|
132
|
+
const up = isActive(ctx, unit) && (!port || listeningPorts(ctx).some((l) => l.port === port));
|
|
133
|
+
if (up) { ctx.say(` ${unit}: running`); return; }
|
|
134
|
+
}
|
|
135
|
+
const j = ctx.run('journalctl', ['-u', unit, '-n', '20', '--no-pager']);
|
|
136
|
+
throw new CliError(`${unit} did not come up. Last log lines:\n${j.stdout.trim()}\n(the nginx site was not changed yet; \`bestgate server revert\` undoes the rest)`);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function sameStatus(before, after) {
|
|
140
|
+
const changed = [];
|
|
141
|
+
for (const [url, s] of Object.entries(before)) {
|
|
142
|
+
if (!/^\d+$/.test(s)) continue; // it did not answer before; nothing to compare
|
|
143
|
+
if (after[url] !== s) changed.push(`${url}: ${s} before, ${after[url]} after`);
|
|
144
|
+
}
|
|
145
|
+
return changed;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// The nginx step: write → nginx -t → reload → compare the other sites → keep or roll back.
|
|
149
|
+
async function applyNginx(ctx, cfg, m, targets, before) {
|
|
150
|
+
const site = targets.filter((x) => x.nginx);
|
|
151
|
+
const file = site.find((x) => x.kind === 'file');
|
|
152
|
+
const link = site.find((x) => x.kind === 'link');
|
|
153
|
+
const prev = ctx.readOrNull(file.path);
|
|
154
|
+
const hadLink = link ? ctx.exists(link.path) : true;
|
|
155
|
+
const undo = () => {
|
|
156
|
+
if (link && !hadLink) ctx.removeFile(link.path);
|
|
157
|
+
if (prev === null) ctx.removeFile(file.path);
|
|
158
|
+
else ctx.writeFile(file.path, prev, { mode: file.mode });
|
|
159
|
+
};
|
|
160
|
+
let changed = false;
|
|
161
|
+
for (const x of site) changed = writeTarget(ctx, m, x) || changed;
|
|
162
|
+
if (!changed) {
|
|
163
|
+
ctx.say(' nginx site unchanged: no reload');
|
|
164
|
+
return false;
|
|
165
|
+
}
|
|
166
|
+
if (ctx.dryRun) {
|
|
167
|
+
ctx.say(' would run: nginx -t, then systemctl reload nginx; then compare checkUrls with their earlier answers');
|
|
168
|
+
return true;
|
|
169
|
+
}
|
|
170
|
+
const t = ctx.run('nginx', ['-t']);
|
|
171
|
+
if (t.code !== 0) {
|
|
172
|
+
undo();
|
|
173
|
+
const t2 = ctx.run('nginx', ['-t']);
|
|
174
|
+
throw new CliError(`nginx -t failed with the bestgate site. The previous state is back and nginx was not reloaded.\n` +
|
|
175
|
+
`${t.stderr.trim()}${t2.code !== 0 ? '\nWARNING: nginx -t still fails after the rollback: look at it now.' : ''}`);
|
|
176
|
+
}
|
|
177
|
+
let after;
|
|
178
|
+
try {
|
|
179
|
+
ctx.change('systemctl', ['reload', 'nginx']);
|
|
180
|
+
await ctx.wait(2000);
|
|
181
|
+
after = await probeCheckUrls(ctx, cfg);
|
|
182
|
+
} catch (e) {
|
|
183
|
+
undo();
|
|
184
|
+
const t4 = ctx.run('nginx', ['-t']);
|
|
185
|
+
let state;
|
|
186
|
+
if (t4.code !== 0) state = 'nginx -t now FAILS without it too: NOT reloaded, look at nginx now';
|
|
187
|
+
else if (ctx.change('systemctl', ['reload', 'nginx'], { allowFail: true }).code === 0) state = 'nginx -t passes and nginx was reloaded without it';
|
|
188
|
+
else state = 'nginx -t passes, but reloading failed again: look at nginx now (systemctl status nginx)';
|
|
189
|
+
throw new CliError(`Reloading nginx with the bestgate site failed, so the site was removed again; ${state}.\n${e.message}`);
|
|
190
|
+
}
|
|
191
|
+
const diff = sameStatus(before, after);
|
|
192
|
+
if (diff.length) {
|
|
193
|
+
undo();
|
|
194
|
+
const t3 = ctx.run('nginx', ['-t']);
|
|
195
|
+
if (t3.code === 0) ctx.change('systemctl', ['reload', 'nginx']);
|
|
196
|
+
throw new CliError(`Other sites answered differently after the reload, so the bestgate site was rolled back` +
|
|
197
|
+
`${t3.code === 0 ? ' and nginx reloaded' : ' (nginx -t now fails: NOT reloaded, look at it now)'}:\n ${diff.join('\n ')}`);
|
|
198
|
+
}
|
|
199
|
+
for (const [u, s] of Object.entries(after)) ctx.say(` ${u}: ${s} (same as before)`);
|
|
200
|
+
return true;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
export async function install(ctx, cfg, facts) {
|
|
204
|
+
const m = facts.manifest || newManifest();
|
|
205
|
+
const before = ctx.dryRun ? {} : await probeCheckUrls(ctx, cfg);
|
|
206
|
+
if (!ctx.dryRun) {
|
|
207
|
+
if (!/^active$/.test(ctx.run('systemctl', ['is-active', 'nginx']).stdout.trim())) throw new CliError('nginx is not active: nothing changed.');
|
|
208
|
+
for (const [u, s] of Object.entries(before)) ctx.say(` before: ${u} → ${s}`);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
ctx.say('directories');
|
|
212
|
+
const dirs = [
|
|
213
|
+
[P.etcDir, 0o755], [P.stateDir, 0o755], [P.origDir, 0o700], [P.logDir, 0o750], [P.cacheDir, 0o700],
|
|
214
|
+
];
|
|
215
|
+
const created = dirs.filter(([d]) => !ctx.exists(d)).map(([d]) => d);
|
|
216
|
+
for (const [d, mode] of dirs) {
|
|
217
|
+
if (d === P.stateDir && !created.includes(d)) continue; // its final mode is set below
|
|
218
|
+
ctx.mkdir(d, { mode });
|
|
219
|
+
}
|
|
220
|
+
for (const d of created) track(ctx, m, d, 'dir', { keep: d !== P.cacheDir });
|
|
221
|
+
if (!ctx.logFile) openLog(ctx, 'install');
|
|
222
|
+
|
|
223
|
+
ctx.say('daemon user');
|
|
224
|
+
if (!facts.userExists) {
|
|
225
|
+
track(ctx, m, DAEMON_USER, 'user', { keep: true });
|
|
226
|
+
ctx.change('useradd', ['--system', '--user-group', '--no-create-home', '--home-dir', '/nonexistent', '--shell', '/usr/sbin/nologin', DAEMON_USER]);
|
|
227
|
+
} else ctx.say(` ${DAEMON_USER} exists`);
|
|
228
|
+
// The daemon creates its database here. Root (this process) never reads or writes
|
|
229
|
+
// anything inside it: the saved originals and the manifest live in P.origDir.
|
|
230
|
+
ctx.mkdir(P.stateDir, { mode: 0o1770, owner: `root:${DAEMON_USER}`, forceOwner: true });
|
|
231
|
+
for (const f of [P.dbFile, `${P.dbFile}-wal`, `${P.dbFile}-shm`]) {
|
|
232
|
+
if (rootOwnedPlainFile(ctx, f)) ctx.chown(f, `${DAEMON_USER}:${DAEMON_USER}`);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
ctx.say('secrets');
|
|
236
|
+
const secrets = ensureSecrets(ctx, m);
|
|
237
|
+
track(ctx, m, P.daemonEnvFile, 'file');
|
|
238
|
+
const daemonEnvChanged = ctx.writeFile(P.daemonEnvFile,
|
|
239
|
+
`FRP_DASHBOARD_PASSWORD=${secrets.password}\nBESTGATE_PLUGIN_SECRET=${secrets.plugin}\n`, { mode: 0o600, secret: true });
|
|
240
|
+
const envChanged = !!secrets.changed;
|
|
241
|
+
|
|
242
|
+
ctx.say('frps');
|
|
243
|
+
const binChanged = await installFrps(ctx, m);
|
|
244
|
+
|
|
245
|
+
ctx.say('configuration and units');
|
|
246
|
+
const targets = buildTargets(ctx, cfg, facts);
|
|
247
|
+
const changed = {};
|
|
248
|
+
for (const x of targets.filter((y) => !y.nginx)) changed[x.path] = writeTarget(ctx, m, x);
|
|
249
|
+
const unitPath = (u) => `${P.systemdDir}/${u}`;
|
|
250
|
+
if (!ctx.dryRun) {
|
|
251
|
+
const env = { FRP_AUTH_TOKEN: secrets.token, FRP_DASHBOARD_PASSWORD: secrets.password, BESTGATE_PLUGIN_SECRET: secrets.plugin };
|
|
252
|
+
const v = ctx.run(ctx.disk(P.frpsBin), ['verify', '-c', ctx.disk(P.frpsToml)], { env });
|
|
253
|
+
if (v.code !== 0) {
|
|
254
|
+
let out = `${v.stdout}\n${v.stderr}`;
|
|
255
|
+
for (const x of Object.values(env)) out = out.split(x).join('***');
|
|
256
|
+
out = out.trim();
|
|
257
|
+
throw new CliError(`frps rejects ${P.frpsToml}:\n${out}`);
|
|
258
|
+
}
|
|
259
|
+
} else ctx.say(` would run: ${showCommand(P.frpsBin, ['verify', '-c', P.frpsToml])} (with the secrets in its environment)`);
|
|
260
|
+
if (Object.values(UNITS).some((u) => changed[unitPath(u)])) ctx.change('systemctl', ['daemon-reload']);
|
|
261
|
+
|
|
262
|
+
const fp = fingerprint(cfg);
|
|
263
|
+
const fpChanged = m.fingerprint !== fp;
|
|
264
|
+
ctx.say('services');
|
|
265
|
+
await startUnit(ctx, UNITS.auth, fpChanged || daemonEnvChanged || changed[unitPath(UNITS.auth)], cfg.ports.daemon);
|
|
266
|
+
await startUnit(ctx, UNITS.frps, fpChanged || binChanged || envChanged || changed[P.frpsToml] || changed[unitPath(UNITS.frps)], cfg.ports.control);
|
|
267
|
+
const timerChanged = changed[unitPath(UNITS.timer)] || changed[unitPath(UNITS.check)];
|
|
268
|
+
if (!isEnabled(ctx, UNITS.timer)) ctx.change('systemctl', ['enable', UNITS.timer]);
|
|
269
|
+
if (timerChanged || !isActive(ctx, UNITS.timer)) ctx.change('systemctl', ['restart', UNITS.timer]);
|
|
270
|
+
|
|
271
|
+
ctx.say('nginx');
|
|
272
|
+
await applyNginx(ctx, cfg, m, targets, before);
|
|
273
|
+
|
|
274
|
+
m.fingerprint = fp;
|
|
275
|
+
m.installedAt = new Date(ctx.now()).toISOString();
|
|
276
|
+
saveManifest(ctx, m);
|
|
277
|
+
return m;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
export async function run(argv = [], opts = {}) {
|
|
281
|
+
const flags = parseFlags(argv, { '--dry-run': 'flag', '--yes': 'flag', '--answers': 'value' });
|
|
282
|
+
const ctx = opts.ctx || createContext({ dryRun: flags.dryRun });
|
|
283
|
+
ctx.dryRun = !!flags.dryRun;
|
|
284
|
+
requireRoot(ctx);
|
|
285
|
+
requireNode(ctx);
|
|
286
|
+
const cfg = await getConfig(ctx, flags, opts);
|
|
287
|
+
openLog(ctx, 'install');
|
|
288
|
+
ctx.say(`bestgate server install${ctx.dryRun ? ' --dry-run (nothing will be changed)' : ''}: ${cfg.baseDomain}`);
|
|
289
|
+
|
|
290
|
+
const { checks, facts } = await collectPlan(ctx, cfg);
|
|
291
|
+
const { fail } = report(ctx, checks);
|
|
292
|
+
const c = facts.cert;
|
|
293
|
+
const certOk = c && c.present && !c.error && c.coversWildcard && c.daysLeft >= 0;
|
|
294
|
+
if (fail || !certOk) {
|
|
295
|
+
const why = fail ? `plan found ${fail} problem(s), see FAIL above` : 'there is no valid certificate yet: run `sudo bestgate server cert` first';
|
|
296
|
+
if (!ctx.dryRun || !facts.layout) throw new CliError(`Install refused: ${why}. Nothing was changed.`);
|
|
297
|
+
ctx.say(`\nNOTE: a real install would refuse: ${why}. Showing what it would do anyway.`);
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
ctx.say('');
|
|
301
|
+
ctx.say('install will:');
|
|
302
|
+
for (const l of describeInstall(ctx, cfg, facts)) ctx.say(` - ${l}`);
|
|
303
|
+
ctx.say('');
|
|
304
|
+
if (!ctx.dryRun && !flags.yes && !(await askConfirm(ctx, 'Go ahead?'))) {
|
|
305
|
+
ctx.say('Nothing changed.');
|
|
306
|
+
return { cancelled: true };
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
await install(ctx, cfg, facts);
|
|
310
|
+
if (ctx.dryRun) {
|
|
311
|
+
ctx.say('\nRESULT: DRY RUN (nothing was changed)');
|
|
312
|
+
return { dryRun: true, journal: ctx.journal };
|
|
313
|
+
}
|
|
314
|
+
ctx.say('');
|
|
315
|
+
const res = await runVerify(ctx, cfg);
|
|
316
|
+
if (!res.ok) throw new CliError('Installed, but verify found problems (see FAIL above). `bestgate server revert` undoes the install.');
|
|
317
|
+
ctx.say(`\nDone. Add a developer with: sudo bestgate server user add <name>`);
|
|
318
|
+
return { ok: true, journal: ctx.journal };
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
export { loadManifest };
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// What install created or replaced, so revert can undo exactly that and nothing else.
|
|
2
|
+
// /var/lib/bestgate/orig/manifest.json (root 0600), next to the saved originals.
|
|
3
|
+
// An entry is written BEFORE the change it describes, so a crash leaves nothing unrecorded.
|
|
4
|
+
// { path, kind: 'file'|'link'|'dir'|'user', orig: <saved copy>|null, origMode, keep }
|
|
5
|
+
// orig null → install created it; revert removes it (unless keep and no --purge)
|
|
6
|
+
// orig set → it existed before; revert puts the saved copy back
|
|
7
|
+
import { P, posix } from './sys.js';
|
|
8
|
+
|
|
9
|
+
export function loadManifest(ctx) {
|
|
10
|
+
const raw = ctx.readOrNull(P.manifestFile);
|
|
11
|
+
if (raw === null) return null;
|
|
12
|
+
let m;
|
|
13
|
+
try { m = JSON.parse(raw); } catch { throw new Error(`${P.manifestFile} is not valid JSON: fix or remove it by hand`); }
|
|
14
|
+
if (!m || m.version !== 1 || !Array.isArray(m.entries)) throw new Error(`${P.manifestFile} has an unknown format`);
|
|
15
|
+
for (const e of m.entries) {
|
|
16
|
+
if (!e || typeof e.path !== 'string' || !['file', 'link', 'dir', 'user'].includes(e.kind)) {
|
|
17
|
+
throw new Error(`${P.manifestFile} has a bad entry`);
|
|
18
|
+
}
|
|
19
|
+
if (e.kind !== 'user' && !e.path.startsWith('/')) throw new Error(`${P.manifestFile} has a relative path`);
|
|
20
|
+
if (e.orig !== null && e.orig !== undefined && !(typeof e.orig === 'string' && e.orig.startsWith(`${P.origDir}/`))) {
|
|
21
|
+
throw new Error(`${P.manifestFile}: a saved original is outside ${P.origDir}`);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
return m;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function newManifest() {
|
|
28
|
+
return { version: 1, entries: [] };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function saveManifest(ctx, m) {
|
|
32
|
+
if (ctx.dryRun) return;
|
|
33
|
+
ctx.writeFile(P.manifestFile, JSON.stringify(m, null, 2) + '\n', { mode: 0o600, quiet: true });
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export const entryFor = (m, p) => (m ? m.entries.find((e) => e.path === p) : undefined);
|
|
37
|
+
|
|
38
|
+
// Record p before install writes it. A file that exists and is not ours yet is copied first.
|
|
39
|
+
export function track(ctx, m, p, kind, { keep = false } = {}) {
|
|
40
|
+
const have = entryFor(m, p);
|
|
41
|
+
if (have) return have;
|
|
42
|
+
const e = { path: p, kind, orig: null, keep };
|
|
43
|
+
if (kind === 'file' && ctx.exists(p) && !ctx.isLink(p)) {
|
|
44
|
+
const stamp = new Date(ctx.now()).toISOString().replace(/[-:]/g, '').replace(/\..*$/, '');
|
|
45
|
+
e.orig = `${P.origDir}/${stamp}${p.replace(/\//g, '_')}`;
|
|
46
|
+
e.origMode = ctx.fileMode(p) ?? 0o644;
|
|
47
|
+
ctx.say(` ${ctx.dryRun ? 'would keep' : 'keep'} the original ${p} as ${e.orig}`);
|
|
48
|
+
ctx.copyFile(p, e.orig, 0o600);
|
|
49
|
+
} else if (kind === 'link' && ctx.exists(p)) {
|
|
50
|
+
throw new Error(`${p} exists and is not ours: refusing to replace it`);
|
|
51
|
+
}
|
|
52
|
+
m.entries.push(e);
|
|
53
|
+
saveManifest(ctx, m);
|
|
54
|
+
return e;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export { posix };
|