@bestapps/bestgate 0.1.0 → 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/README.md CHANGED
@@ -120,7 +120,7 @@ Defaults are 60 minutes and 30 days. Change `idleMinutes` and `accessExpiryDays`
120
120
 
121
121
  ## Limits and security
122
122
 
123
- - nginx limits per client IP: requests per second with a burst, simultaneous connections, control-channel logins per minute, open control connections, and the largest request body. The defaults are 20 requests/s (burst 100), 50 connections, 10 logins/min, 20 control connections and 100m. All bestgate connections together are capped too (`nginx.maxConnections`, 200 by default), because the nginx connection pool is shared with every other site on the server. Request headers must arrive within 10 s and the body must keep moving (30 s).
123
+ - nginx limits per client IP: requests per second with a burst, simultaneous connections, control-channel logins per minute, open control connections, and the largest request body. The defaults are 200 requests/s, 300 connections, 10 logins/min, 20 control connections and 100m. They are sized for a dev server that serves unbundled modules: one Vite page is 800 requests and more within a few seconds, and a reload repeats them. Above the rate, 3000 more requests (`nginx.reqBurst`) are served at once; after that requests are held and let through at the rate, so a heavy page gets slower and does not break. A client gets `429` only with 300 requests (`nginx.connPerIp`) already waiting, or over the connection limit. They are the `nginx.*` fields of the config; to change them, edit the answers file and run `install` again. All bestgate connections together are capped too (`nginx.maxConnections`, 400 by default), because the nginx connection pool is shared with every other site on the server: keep twice that number well below nginx's `worker_connections`. A tunnel connection is kept for 100000 requests (nginx closes one after 1000 by default, in the middle of a large page load). nginx must be 1.15.7 or newer. Request headers must arrive within 10 s and the body must keep moving (30 s).
124
124
  - Per developer: a maximum number of tunnels (3), of running clients (`maxClientsPerUser`, 5), a bandwidth cap per tunnel (10MB per second), HTTP tunnels only, and subdomains of the form `a-z0-9-` that are not the control label. A tunnel cannot claim paths (`locations`), Basic-auth users (`routeByHTTPUser`) or custom domains, and its frp proxy name must start with the developer's own name, so one developer cannot route part of a colleague's traffic to themselves.
125
125
  - These limits bound abuse that goes through tunnels. They cannot stop a volumetric attack on the server's IP address; that has to be handled by the network in front of the server.
126
126
  - Tunnels are public by default. Use `--auth <user>` when the app should not be open, and run tunnels only for development machines with test data.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bestapps/bestgate",
3
- "version": "0.1.0",
3
+ "version": "0.1.3",
4
4
  "description": "ngrok-style dev tunnels on your own server, built on frp: `bestgate 3000` gives https://<name>.<your domain>",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -121,8 +121,12 @@ export function buildConfig({ serverAddr, serverPort = 443, protocol = 'wss', us
121
121
  ];
122
122
  if (protocol === 'wss') lines.push('transport.tls.useSystemCa = true');
123
123
  lines.push(
124
- 'transport.heartbeatInterval = 30',
125
- 'transport.heartbeatTimeout = 90',
124
+ // A dead connection is noticed after 30 s. frps keeps its own, longer timeout.
125
+ 'transport.heartbeatInterval = 10',
126
+ 'transport.heartbeatTimeout = 30',
127
+ // Work connections kept ready on the server, so a page that asks for hundreds of files
128
+ // at once does not wait a round trip for each. frps caps it (transport.maxPoolCount).
129
+ 'transport.poolCount = 64',
126
130
  '',
127
131
  '[[proxies]]',
128
132
  `name = ${tomlString(name)}`,
@@ -132,6 +136,9 @@ export function buildConfig({ serverAddr, serverPort = 443, protocol = 'wss', us
132
136
  );
133
137
  if (auth) lines.push(`httpUser = ${tomlString(auth.user)}`, `httpPassword = ${tomlString(auth.password)}`);
134
138
  if (hostHeader) lines.push(`hostHeaderRewrite = ${tomlString(hostHeader)}`);
139
+ // frps overwrites X-Forwarded-Proto with "http", because nginx reaches it without TLS.
140
+ // With wss the public side is always https, so say so to the app.
141
+ if (protocol === 'wss') lines.push('requestHeaders.set.x-forwarded-proto = "https"');
135
142
  return lines.join('\n') + '\n';
136
143
  }
137
144
 
@@ -142,6 +149,10 @@ export function buildConfig({ serverAddr, serverPort = 443, protocol = 'wss', us
142
149
  // pkg/util/vhost/router.go:11 "router config conflict"; server/proxy/proxy.go:586 "... is already in use"
143
150
  // client/proxy/proxy.go:240 "connect to local service [ip:port] error: ..."
144
151
  // client/service.go:314 "login to the server failed: <server reason>..."
152
+ // client/control.go:153 "StartWorkConn contains error: work connection pool is full, discarding"
153
+ // client/control.go:272 "heartbeat timeout"
154
+ // client/service.go:369 "try to connect to server..." (the start and every reconnect)
155
+ // client/service.go:380 "connect to server error: ..." (each failed reconnect)
145
156
 
146
157
  const REASON_MESSAGES = {
147
158
  IDLE: 'Tunnel closed after being idle. Run the same command again.',
@@ -158,7 +169,7 @@ const ANSI = /\u001b\[[0-9;]*m/g;
158
169
  /**
159
170
  * Classify one frpc output line.
160
171
  * → { kind: 'reason', key, message } | { kind: 'conflict' } | { kind: 'ready' }
161
- * | { kind: 'localdown' } | { kind: 'error' } | { kind: 'chatter' }
172
+ * | { kind: 'localdown' } | { kind: 'dropped' } | { kind: 'error' } | { kind: 'chatter' }
162
173
  */
163
174
  export function classifyLine(raw) {
164
175
  const line = raw.replace(ANSI, '');
@@ -168,6 +179,10 @@ export function classifyLine(raw) {
168
179
  if (/start error:.*(router config conflict|already in use|already exists)/.test(line)) return { kind: 'conflict' };
169
180
  if (line.includes('start proxy success')) return { kind: 'ready' };
170
181
  if (line.includes('connect to local service')) return { kind: 'localdown' };
182
+ if (/heartbeat timeout|connect to server error|try to connect to server/.test(line)) return { kind: 'dropped' };
183
+ // Not an error: frps asks for a spare work connection with every request and sends back
184
+ // the ones its pool has no room for (server/control.go:336).
185
+ if (line.includes('work connection pool is full')) return { kind: 'chatter' };
171
186
  if (/\[(W|E)\]/.test(line)) return { kind: 'error' };
172
187
  return { kind: 'chatter' };
173
188
  }
@@ -247,6 +262,9 @@ export async function run(argv) {
247
262
  process.on('SIGTERM', () => stop(0));
248
263
 
249
264
  let warnedLocal = false;
265
+ let wasReady = false;
266
+ let droppedAt = null; // time the connection to the server was lost, while it is down
267
+ let reasonShown = false; // frpc's own warning was printed for this outage
250
268
  const onLine = (line) => {
251
269
  if (!line.trim() || exitCode !== null) return;
252
270
  const c = classifyLine(line);
@@ -258,6 +276,13 @@ export async function run(argv) {
258
276
  console.error(`The name "${name}" is already used by another tunnel. Choose another with --name.`);
259
277
  return stop(1);
260
278
  case 'ready':
279
+ if (droppedAt !== null) {
280
+ console.log(`Tunnel is back after ${Math.round((Date.now() - droppedAt) / 1000)} s: ${url}`);
281
+ droppedAt = null;
282
+ reasonShown = false;
283
+ return;
284
+ }
285
+ wasReady = true;
261
286
  console.log(`${url} → http://localhost:${opts.port}`);
262
287
  if (!opts.auth) console.log('Note: this URL is public. Use --auth <user> to protect it with a password.');
263
288
  console.log('Ctrl-C to stop');
@@ -269,6 +294,23 @@ export async function run(argv) {
269
294
  }
270
295
  if (opts.verbose) console.log(line);
271
296
  return;
297
+ case 'dropped':
298
+ // Before the first "ready" this is the start: show frpc's own warnings.
299
+ if (!wasReady) {
300
+ if (/\[(W|E)\]/.test(line)) console.error(line.replace(ANSI, ''));
301
+ else if (opts.verbose) console.log(line);
302
+ return;
303
+ }
304
+ if (droppedAt === null) {
305
+ droppedAt = Date.now();
306
+ console.warn(`Connection to the server lost at ${new Date().toLocaleTimeString()}. Requests to ${url} fail until it is back; reconnecting...`);
307
+ }
308
+ // frpc's first warning of an outage says why (heartbeat timeout, DNS, refused...).
309
+ if (!reasonShown && /\[(W|E)\]/.test(line)) {
310
+ reasonShown = true;
311
+ console.warn(line.replace(ANSI, ''));
312
+ } else if (opts.verbose) console.log(line);
313
+ return;
272
314
  case 'error':
273
315
  console.error(line.replace(ANSI, ''));
274
316
  return;
@@ -39,9 +39,15 @@ export const DEFAULTS = Object.freeze({
39
39
  bandwidthLimit: '10MB',
40
40
  pollSeconds: 30,
41
41
  nginx: Object.freeze({
42
- reqPerSec: 20, reqBurst: 100, connPerIp: 50, loginPerMin: 10, maxBody: '100m',
42
+ // Sized for a dev server that serves unbundled modules: one Vite page is 800 requests
43
+ // and more within a few seconds, and a reload repeats them.
44
+ // reqBurst requests above reqPerSec are served at once; more are held and let through
45
+ // at the rate; a client is refused only with connPerIp requests already waiting.
46
+ // With HTTP/2 nginx counts every request in flight as a connection, and a browser has
47
+ // up to 128 per connection: connPerIp leaves room for two (a reconnect during a load).
48
+ reqPerSec: 200, reqBurst: 3000, connPerIp: 300, loginPerMin: 10, maxBody: '100m',
43
49
  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
50
+ maxConnections: 400, // all bestgate connections together, per server block: the nginx pool is shared
45
51
  }),
46
52
  checkUrls: Object.freeze([]),
47
53
  });
@@ -17,7 +17,9 @@ export function loadServerConfig(ctx, file = P.configFile) {
17
17
  }
18
18
 
19
19
  // Which process name each of our ports should show in `ss -p`.
20
- const PORT_OWNERS = { control: 'frps', vhost: 'frps', dashboard: 'frps', daemon: 'node' };
20
+ // Process names as ss prints them. Node 24 names its main thread MainThread, so ss shows
21
+ // that for the daemon instead of node.
22
+ const PORT_OWNERS = { control: ['frps'], vhost: ['frps'], dashboard: ['frps'], daemon: ['node', 'MainThread'] };
21
23
  const MAX_WALK = 50000;
22
24
 
23
25
  /**
@@ -124,6 +126,9 @@ export async function collectPlan(ctx, cfg) {
124
126
  facts.nginxVersion = nginxVersion(v.stderr + v.stdout);
125
127
  add(facts.nginxVersion ? 'OK' : 'WARN', `nginx version ${facts.nginxVersion || 'unknown'}` +
126
128
  (facts.nginxVersion && versionAtLeast(facts.nginxVersion, '1.25.1') ? ' (per-server "http2 on;")' : ' (http2 left to the listen socket)'));
129
+ if (facts.nginxVersion && !versionAtLeast(facts.nginxVersion, '1.15.7')) {
130
+ add('FAIL', `nginx ${facts.nginxVersion} is too old: the request limit uses "limit_req ... delay=", which needs 1.15.7 or newer`);
131
+ }
127
132
  const dump = ctx.run('nginx', ['-T']);
128
133
  if (dump.code !== 0) {
129
134
  add('FAIL', `nginx -t fails right now, fix that first:\n${(dump.stderr || '').trim().split('\n').slice(-5).join('\n')}`);
@@ -186,7 +191,7 @@ export async function collectPlan(ctx, cfg) {
186
191
  const l = listening.filter((x) => x.port === port);
187
192
  if (port >= 1024) add('FAIL', `port ${port} (${k}) is not privileged: any local user could bind it while frps or the daemon restarts; use 1-1023`);
188
193
  else if (!l.length) add('OK', `port ${port} (${k}) is free`);
189
- else if (frpsOurs && l.every((x) => x.process === PORT_OWNERS[k] && isLoopback(x.addr))) add('OK', `port ${port} (${k}) is used by our ${PORT_OWNERS[k]}`);
194
+ else if (frpsOurs && l.every((x) => PORT_OWNERS[k].includes(x.process) && isLoopback(x.addr))) add('OK', `port ${port} (${k}) is used by our ${PORT_OWNERS[k][0]}`);
190
195
  else add('FAIL', `port ${port} (${k}) is already used by ${l.map((x) => `${x.process || '?'} on ${x.addr}`).join(', ')}`);
191
196
  }
192
197
 
@@ -118,6 +118,8 @@ export function templateVars(cfg, facts) {
118
118
  VHOST_PORT: c.ports.vhost,
119
119
  REQ_PER_SEC: c.nginx.reqPerSec,
120
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,
121
123
  CONN_PER_IP: c.nginx.connPerIp,
122
124
  CONTROL_CONN_PER_IP: c.nginx.controlConnPerIp,
123
125
  MAX_CONNECTIONS: c.nginx.maxConnections,
@@ -29,7 +29,9 @@ webServer.port = __DASHBOARD_PORT__
29
29
  webServer.user = "admin"
30
30
  webServer.password = "{{ .Envs.FRP_DASHBOARD_PASSWORD }}"
31
31
 
32
- transport.maxPoolCount = 5
32
+ # Work connections a client may keep ready (bestgate's client asks for 64). A page that
33
+ # loads hundreds of files at once then finds connections waiting, not one round trip each.
34
+ transport.maxPoolCount = 64
33
35
  # Explicit, so every client must Ping: with tcpMux the default would be no timeout,
34
36
  # and then idle sessions and revoked keys could never be cut off at the next Ping.
35
37
  transport.heartbeatTimeout = 90
@@ -74,7 +74,13 @@ server {
74
74
  client_max_body_size __MAX_BODY__;
75
75
  client_header_timeout 10s;
76
76
  client_body_timeout 30s;
77
- limit_req zone=bestgate_req burst=__REQ_BURST__ nodelay;
77
+ # nginx closes a connection after 1000 requests by default. An unbundled dev page is
78
+ # that many in one load, and the browser then loses requests that were in flight.
79
+ keepalive_requests 100000;
80
+ # Per client IP: __REQ_BURST__ requests above the rate are served at once. The next ones
81
+ # are held and let through at the rate: a heavy page gets slower, it does not break.
82
+ # 429 only when more than __CONN_PER_IP__ requests of one IP are already waiting.
83
+ limit_req zone=bestgate_req burst=__REQ_BURST_TOTAL__ delay=__REQ_BURST__;
78
84
  limit_conn bestgate_conn __CONN_PER_IP__;
79
85
  limit_conn bestgate_total __MAX_CONNECTIONS__;
80
86
  limit_req_status 429;
@@ -84,7 +84,7 @@ export function summary(cfg) {
84
84
  `access expiry ${cfg.accessExpiryDays} days after last use`,
85
85
  `tunnels per dev ${cfg.maxTunnelsPerUser} (at most ${cfg.maxClientsPerUser} running clients)`,
86
86
  `bandwidth limit ${cfg.bandwidthLimit} per second per tunnel`,
87
- `nginx limits ${cfg.nginx.reqPerSec} req/s (burst ${cfg.nginx.reqBurst}), ${cfg.nginx.connPerIp} connections per IP, ` +
87
+ `nginx limits ${cfg.nginx.reqPerSec} req/s (${cfg.nginx.reqBurst} more at once, then slowed), ${cfg.nginx.connPerIp} connections per IP, ` +
88
88
  `${cfg.nginx.loginPerMin} logins/min, body ${cfg.nginx.maxBody}, ${cfg.nginx.controlConnPerIp} control connections per IP, ` +
89
89
  `${cfg.nginx.maxConnections} connections in all`,
90
90
  `check URLs ${cfg.checkUrls.length ? cfg.checkUrls.join(', ') : '(none)'}`,
@@ -155,14 +155,14 @@ async function interview(p, start, ctx) {
155
155
 
156
156
  const d = DEFAULTS.nginx;
157
157
  const useDefaults = await p.confirm({
158
- message: `Use the default nginx limits (${d.reqPerSec} req/s, burst ${d.reqBurst}, ${d.connPerIp} connections per IP, ` +
158
+ message: `Use the default nginx limits (${d.reqPerSec} req/s, ${d.reqBurst} more at once and then slowed, ${d.connPerIp} connections per IP, ` +
159
159
  `${d.loginPerMin} logins/min, body ${d.maxBody}, ${d.controlConnPerIp} control connections per IP, ${d.maxConnections} connections in all)?`,
160
160
  default: Object.keys(d).every((k) => a.nginx[k] === d[k]),
161
161
  });
162
162
  if (useDefaults) a.nginx = { ...d };
163
163
  else {
164
164
  await ask('nginx.reqPerSec', 'Requests per second per client IP:', intOr);
165
- await ask('nginx.reqBurst', 'Burst size of extra requests:', intOr);
165
+ await ask('nginx.reqBurst', 'Requests above that rate served at once (more are slowed down, not refused):', intOr);
166
166
  await ask('nginx.connPerIp', 'Simultaneous connections per client IP:', intOr);
167
167
  await ask('nginx.loginPerMin', 'Control-channel logins per minute per client IP:', intOr);
168
168
  await ask('nginx.maxBody', 'Largest request body, like 100m, 512k or 1g:', lower);