@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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,139 @@
1
- # Temporary Holding Version
1
+ # bestgate
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ bestgate gives you a public HTTPS address for an app on your own computer, on a server you control. It is built on [frp](https://github.com/fatedier/frp) and runs behind the nginx that is already on the server, with a wildcard certificate for your tunnel domain.
4
+
5
+ You install a small client on a developer PC and run one command:
6
+
7
+ ```
8
+ bestgate 3000 # https://<random name>.t.example.com now reaches localhost:3000
9
+ bestgate 3000 --name shop # https://shop.t.example.com
10
+ ```
11
+
12
+ ## Quick start for developers
13
+
14
+ You need Node.js 20.17 or newer, the server's base domain (for example `t.example.com`) and an access key from the server owner (it starts with `bg_`).
15
+
16
+ ```
17
+ npm i -g @bestapps/bestgate
18
+ bestgate login
19
+ bestgate 3000
20
+ ```
21
+
22
+ `bestgate login` asks for the host (the base domain) and the access key, saves them in your user configuration folder (file mode 0600) and checks that the host resolves. `bestgate logout` forgets them. For CI, set `BESTGATE_HOST` and `BESTGATE_KEY` instead.
23
+
24
+ `bestgate <port>` downloads the frp client once, checks it against a pinned sha256, and prints the address, `https://<name>.<base domain>`. Press Ctrl-C to stop.
25
+
26
+ Without `--name` the name is new on every run: a UUIDv7 without hyphens, 32 hex characters such as `019abc12def37a4c8e0f1234567890ab`. Nobody can guess it from your user name, but the address is still public: anyone who sees it (a shared link, a browser history, a log) can open it.
27
+
28
+ Options:
29
+
30
+ - `--name <sub>`: a fixed subdomain (3-32 characters: a-z, 0-9, hyphen). Names are first come, first served: while your tunnel is not running, any other key holder on the server can take the same name and receive the requests meant for you.
31
+ - `--auth <user>`: protect the address with HTTP basic auth; bestgate asks for the password, so it does not show in the process list. `--auth user:pass` also works, but then the password is visible to other users of your PC (`ps`). Without `--auth` the address is public.
32
+ - `--host-header <h>`: replace the Host header sent to your app.
33
+ - `--verbose`: show the frp client's own output.
34
+
35
+ Messages you may see:
36
+
37
+ - `Tunnel closed after being idle. Run the same command again.` The tunnel had no traffic and no open connection for the server's idle timeout (60 minutes by default).
38
+ - `Your access has expired. Ask the server owner to renew it.` You did not use the server for longer than the access expiry (30 days by default). The owner runs `bestgate server user renew <name>`.
39
+ - `Your access was revoked by the server owner.` The owner ran `revoke`; they can issue a new key with `rekey`.
40
+ - `You have reached the maximum number of tunnels on this server.` Stop another tunnel first. The server also limits how many `bestgate` commands one developer can run at the same time (5 by default); a client that just stopped counts for up to 90 seconds.
41
+ - `The name "x" is already used by another tunnel.` Choose another with `--name`.
42
+
43
+ ### Frameworks
44
+
45
+ Dev servers often refuse requests whose Host header they do not know. For Vite or Nuxt add the tunnel domain to the allowed hosts, for example in `vite.config.js`:
46
+
47
+ ```js
48
+ server: { allowedHosts: ['.t.example.com'] }
49
+ ```
50
+
51
+ Or send a header your app accepts: `bestgate 3000 --host-header localhost`.
52
+
53
+ ### Windows
54
+
55
+ Microsoft Defender flags frp binaries as a potentially unwanted app (`PUA:Win32/FRProxy`), so frpc may be blocked and bestgate shows "Access is denied" or a message that Windows security software blocked frpc. The binary is downloaded from the official frp release on GitHub and checked against a pinned sha256 before it is used. Whether to allow it is your decision, or your administrator's. The usual fix is an exclusion for the bestgate cache folder (`%LOCALAPPDATA%\bestgate`).
56
+
57
+ ## Server setup
58
+
59
+ Requirements on the server:
60
+
61
+ - Ubuntu (Debian should work), run as root.
62
+ - nginx already serving HTTPS. bestgate adds one site file and reloads nginx only after `nginx -t` passes.
63
+ - A wildcard DNS record `*.<base domain>` that resolves to the server's public IP (a CNAME to a name that resolves there is fine).
64
+ - Node.js 22.13 or newer, installed system-wide (not under `/home` or `/root`), because systemd runs it.
65
+ - certbot, for the wildcard certificate.
66
+
67
+ `install.sh` checks these, offers to install Node.js 24 LTS from NodeSource (it asks first; `--yes` skips the question), installs the package and starts `bestgate setup`. Or do it by hand:
68
+
69
+ ```
70
+ npm i -g @bestapps/bestgate
71
+ sudo bestgate server wizard # questions, then saves /etc/bestgate/config.json
72
+ sudo bestgate server cert # wildcard certificate, interactive
73
+ sudo bestgate server install # shows the plan, asks, installs
74
+ sudo bestgate server verify # probes the result and the other sites
75
+ ```
76
+
77
+ `wizard` asks for the base domain, the control label, the nginx address, the public IP, the idle timeout, the access expiry, the limits and a list of other sites on the server that must keep answering. For a repeatable, non-interactive run use `--answers <file>` (a JSON file with the same fields) with `wizard` or `install`. `sudo bestgate server plan` shows the read-only checks and what `install` would change; `install --dry-run` changes nothing.
78
+
79
+ Developers:
80
+
81
+ ```
82
+ sudo bestgate server user add alice # prints the access key once
83
+ sudo bestgate server user list
84
+ sudo bestgate server user renew alice
85
+ sudo bestgate server user rekey alice # new key; also lets a revoked user in again
86
+ sudo bestgate server user revoke alice
87
+ sudo bestgate server user remove alice
88
+ sudo bestgate server rotate-token # new frps token: every key stops working, rekey who should stay
89
+ ```
90
+
91
+ Send the key over a private channel. The server stores only a hash of it, so a lost key cannot be shown again: use `rekey`.
92
+
93
+ Overview and removal:
94
+
95
+ ```
96
+ sudo bestgate server status # services, ports, DNS, certificate, users, online tunnels
97
+ sudo bestgate server revert # removes the services and the nginx site; keeps config and database
98
+ sudo bestgate server revert --purge
99
+ ```
100
+
101
+ A daily timer runs `bestgate server check`. It records a wrong DNS answer, a missing certificate or a certificate with fewer than 30 days left, and the message appears when you log in over SSH.
102
+
103
+ ## How it works
104
+
105
+ ```
106
+ browser -> https://shop.<base> -> nginx (rate limits, wildcard cert) -> frps 127.0.0.1:722 -> frpc -> localhost:3000
107
+ frpc -> wss://frp.<base>/~!frp -> nginx -> frps 127.0.0.1:721
108
+ frps -> HTTP plugin -> bestgate daemon 127.0.0.1:724 (Login / NewProxy / Ping / CloseProxy)
109
+ daemon -> frps dashboard API 127.0.0.1:723 every 30 s (traffic, open connections)
110
+ ```
111
+
112
+ The client connects over port 443 as a WebSocket, so only HTTPS has to be open to the server. Everything frps opens listens on 127.0.0.1, on privileged ports (below 1024), so no other account on the server can take one of them over while frps or the daemon restarts; the two services get only the capability to bind such a port. The default ports 721-724 are in a block IANA leaves unassigned; `server plan` checks that they are free and that `net.ipv4.ip_unprivileged_port_start` has not been lowered. The access key holds the developer name, a per-developer secret and the frps token. frps checks the token on every login, heartbeat and work connection; the daemon checks the secret, the expiry and the limits. frps authenticates to the daemon with a secret of its own (`BESTGATE_PLUGIN_SECRET` in `/etc/bestgate/frps.env` and `daemon.env`), so local users cannot send it fake plugin calls.
113
+
114
+ ## Expiry
115
+
116
+ - Idle tunnels: the daemon polls frps. A tunnel with no open connections and no traffic for the idle timeout is closed, and the client says so. An open browser tab with a live WebSocket counts as use.
117
+ - Access: every login and every poll with an online tunnel counts as use. A login more than the access expiry after the last use is refused until the owner runs `user renew`.
118
+
119
+ Defaults are 60 minutes and 30 days. Change `idleMinutes` and `accessExpiryDays` through `sudo bestgate server wizard` (it starts from the saved values) and run `sudo bestgate server install` to apply them.
120
+
121
+ ## Limits and security
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).
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
+ - 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
+ - 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.
127
+ - Subdomains are first come, first served. A fixed `--name` can be taken by any key holder while your tunnel is not running; the default random name avoids that.
128
+ - The tunnel access log on the server (`/var/log/nginx/bestgate-tunnels.access.log`) records every request with its full URL, query string included. Do not put secrets in URLs, and tell developers that the server owner can read them.
129
+ - Every access key contains the shared frps token. Revoking a key stops that developer at the daemon, but they still know the token. After revoking someone you do not trust, run `sudo bestgate server rotate-token` (a new token in `frps.env`, frps restarts, every connected client is dropped) and then `sudo bestgate server user rekey <name>` for every developer who should keep access: their old keys no longer work.
130
+ - Cookies: tunnel apps run on `<name>.<base domain>`. A tunnel can set cookies for the parent domains of the base domain (for example a base domain `t.example.com` can set cookies for `example.com`) and can read cookies other sites set for those parent domains. Use a separate registrable domain for the tunnels, or one where no site relies on cookies scoped to a parent domain.
131
+ - The daily check (`bestgate-check.service`) runs node and this package as root, so `server plan` refuses to install unless node, the package and every directory above them are owned by root and not writable by group or others (install the package as root, `sudo npm i -g`).
132
+
133
+ ## Certificate renewal
134
+
135
+ The wildcard certificate comes from Let's Encrypt over the DNS-01 challenge and is renewed by hand. Run `sudo bestgate server cert` again before it expires (about every 60 days for a 90-day certificate). certbot asks you to create a TXT record `_acme-challenge.<base domain>`; the command prints where to check that the record is visible first. certbot's own renewal skips this certificate (`--no-autorenew`). Let's Encrypt no longer sends expiry emails, so the daily check and the login message are your reminder. When the nginx site is installed, the command reloads nginx after `nginx -t` passes.
136
+
137
+ ## Licence
138
+
139
+ Apache-2.0, see `LICENSE`. frp is Apache-2.0, by fatedier: https://github.com/fatedier/frp
@@ -0,0 +1,107 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync } from 'node:fs';
3
+ import { CliError } from '../src/util.js';
4
+
5
+ const HELP = `bestgate - share a local port at https://<name>.<your tunnel domain>
6
+
7
+ Usage:
8
+ bestgate <port> [--name <sub>] [--auth <user>] [--host-header <h>] [--verbose]
9
+ Open a tunnel to localhost:<port>. Without --name the subdomain is a new random
10
+ 32-character name on every run (hard to guess, but still public).
11
+ --name a fixed subdomain; any other key holder can take it while it is free
12
+ --auth <user> protect the URL with HTTP basic auth; asks for the password, so it does
13
+ not show in the process list (--auth user:pass also works)
14
+ --host-header rewrite the Host header sent to your app
15
+ bestgate login Save the server host and your access key
16
+ bestgate logout Forget them
17
+ bestgate setup Guided setup: developer PC or tunnel server
18
+ bestgate server <install|plan|cert|verify|status|revert|wizard>
19
+ Server commands (Ubuntu, run as root); install asks the questions first
20
+ bestgate server user add <name> Create a developer and print the access key once
21
+ bestgate server user list Show developers, last use and days until expiry
22
+ bestgate server user renew <name> Restart the access expiry clock
23
+ bestgate server user rekey <name> Issue a new key (also lets a revoked user in again)
24
+ bestgate server user revoke <name> Stop the key from working (--yes skips the question)
25
+ bestgate server user remove <name> Delete the developer (--yes skips the question)
26
+ bestgate server rotate-token New frps token: every key stops working until \`user rekey\`
27
+ (also run by systemd: bestgate server check, bestgate server daemon)
28
+ bestgate --version
29
+ bestgate --help
30
+
31
+ Environment: BESTGATE_HOST and BESTGATE_KEY override the saved login (for CI).
32
+ `;
33
+
34
+ const SERVER_MODES = ['install', 'plan', 'cert', 'verify', 'status', 'revert', 'check', 'daemon', 'wizard', 'rotate-token'];
35
+
36
+ async function loadModule(rel, what) {
37
+ try {
38
+ return await import(rel);
39
+ } catch (e) {
40
+ if (e.code === 'ERR_MODULE_NOT_FOUND' && e.message.includes(rel.split('/').pop())) {
41
+ throw new CliError(`${what} is not available in this installation.`);
42
+ }
43
+ throw e;
44
+ }
45
+ }
46
+
47
+ async function server(args) {
48
+ const [mode, ...rest] = args;
49
+ if (mode === 'user') return (await loadModule('../src/server/users.js', '"bestgate server user"')).run(rest);
50
+ if (!SERVER_MODES.includes(mode)) {
51
+ throw new CliError(`Usage: bestgate server <${SERVER_MODES.join('|')}> or bestgate server user <add|list|renew|rekey|revoke|remove>`);
52
+ }
53
+ return (await loadModule(`../src/server/${mode}.js`, `"bestgate server ${mode}"`)).run(rest);
54
+ }
55
+
56
+ async function setup() {
57
+ const { select } = await import('@inquirer/prompts');
58
+ const where = await select({
59
+ message: 'What are you setting up?',
60
+ choices: [
61
+ { name: 'This is a developer PC', value: 'dev' },
62
+ { name: 'This is the tunnel server', value: 'server' },
63
+ ],
64
+ });
65
+ if (where === 'dev') return (await import('../src/client/login.js')).run([]);
66
+ return server(['install']);
67
+ }
68
+
69
+ async function main(argv) {
70
+ const [first, ...rest] = argv;
71
+ if (!first || first === '--help' || first === '-h' || first === 'help') {
72
+ process.stdout.write(HELP);
73
+ return;
74
+ }
75
+ if (first === '--version' || first === '-v') {
76
+ const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
77
+ console.log(pkg.version);
78
+ return;
79
+ }
80
+ switch (first) {
81
+ case 'login':
82
+ return (await import('../src/client/login.js')).run(rest);
83
+ case 'logout': {
84
+ const { clearLogin } = await import('../src/client/store.js');
85
+ console.log(clearLogin() ? 'Logged out.' : 'You were not logged in.');
86
+ return;
87
+ }
88
+ case 'setup':
89
+ return setup();
90
+ case 'server':
91
+ return server(rest);
92
+ default:
93
+ return (await import('../src/client/tunnel.js')).run(argv);
94
+ }
95
+ }
96
+
97
+ try {
98
+ await main(process.argv.slice(2));
99
+ } catch (e) {
100
+ if (e?.name === 'ExitPromptError') process.exit(130);
101
+ if (e instanceof CliError) {
102
+ console.error(e.message);
103
+ process.exit(1);
104
+ }
105
+ console.error(e?.stack || e);
106
+ process.exit(1);
107
+ }
package/install.sh ADDED
@@ -0,0 +1,82 @@
1
+ #!/usr/bin/env bash
2
+ # bestgate bootstrap for Ubuntu/Debian: makes sure Node.js >= 22.13 is installed,
3
+ # installs the package globally and starts `bestgate setup`.
4
+ # Run as root on a tunnel server. Options: --yes (do not ask before installing Node.js).
5
+ set -euo pipefail
6
+
7
+ MIN_NODE="22.13.0"
8
+ NODE_MAJOR="24"
9
+ PACKAGE="@bestapps/bestgate"
10
+
11
+ assume_yes=0
12
+ for arg in "$@"; do
13
+ case "$arg" in
14
+ --yes|-y) assume_yes=1 ;;
15
+ -h|--help) echo "Usage: install.sh [--yes]"; exit 0 ;;
16
+ *) echo "Unknown option: $arg" >&2; exit 2 ;;
17
+ esac
18
+ done
19
+
20
+ die() { echo "install.sh: $*" >&2; exit 1; }
21
+
22
+ [ "$(id -u)" -eq 0 ] || die "run this as root (sudo ./install.sh)"
23
+
24
+ [ -r /etc/os-release ] || die "cannot read /etc/os-release"
25
+ # shellcheck disable=SC1091
26
+ . /etc/os-release
27
+ case "${ID:-}:${ID_LIKE:-}" in
28
+ ubuntu:*|debian:*|*:*ubuntu*|*:*debian*) ;;
29
+ *) die "this script supports Ubuntu and Debian only (found: ${PRETTY_NAME:-unknown})" ;;
30
+ esac
31
+
32
+ # true when "$1" >= "$2" (dotted versions)
33
+ version_ge() { [ "$(printf '%s\n%s\n' "$2" "$1" | sort -V | head -n 1)" = "$2" ]; }
34
+
35
+ node_ok() {
36
+ command -v node >/dev/null 2>&1 || return 1
37
+ version_ge "$(node -p 'process.versions.node')" "$MIN_NODE"
38
+ }
39
+
40
+ if node_ok; then
41
+ echo "Node.js $(node -p 'process.versions.node') found."
42
+ else
43
+ if command -v node >/dev/null 2>&1; then
44
+ echo "Node.js $(node -p 'process.versions.node') is older than the required $MIN_NODE."
45
+ else
46
+ echo "Node.js is not installed. bestgate needs $MIN_NODE or newer."
47
+ fi
48
+ echo
49
+ echo "This script can install Node.js ${NODE_MAJOR} LTS system-wide. It will:"
50
+ echo " 1. download the NodeSource setup script from https://deb.nodesource.com/setup_${NODE_MAJOR}.x"
51
+ echo " and run it as root (it adds the NodeSource apt repository)"
52
+ echo " 2. run: apt-get install -y nodejs"
53
+ if [ "$assume_yes" -ne 1 ]; then
54
+ printf 'Install Node.js %s now? [y/N] ' "$NODE_MAJOR"
55
+ read -r answer </dev/tty || answer=""
56
+ case "$answer" in
57
+ y|Y|yes|YES) ;;
58
+ *) die "Node.js not installed; install Node ${NODE_MAJOR} LTS yourself and run this script again" ;;
59
+ esac
60
+ fi
61
+ command -v curl >/dev/null 2>&1 || { apt-get update && apt-get install -y curl ca-certificates; }
62
+ setup_script="$(mktemp)"
63
+ trap 'rm -f "$setup_script"' EXIT
64
+ curl -fsSL "https://deb.nodesource.com/setup_${NODE_MAJOR}.x" -o "$setup_script"
65
+ bash "$setup_script"
66
+ rm -f "$setup_script"
67
+ apt-get install -y nodejs
68
+ node_ok || die "Node.js is still missing or too old after the installation"
69
+ fi
70
+
71
+ # The server side must not depend on a Node under /home or /root (systemd units run it).
72
+ node_path="$(command -v node)"
73
+ case "$(readlink -f "$node_path")" in
74
+ /home/*|/root/*) die "node is installed under a home directory ($node_path); install it system-wide (for example /usr/bin/node)" ;;
75
+ esac
76
+
77
+ echo
78
+ echo "Installing $PACKAGE (npm install -g $PACKAGE)"
79
+ npm install -g "$PACKAGE"
80
+
81
+ echo
82
+ exec bestgate setup
package/package.json CHANGED
@@ -1,6 +1,40 @@
1
1
  {
2
2
  "name": "@bestapps/bestgate",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "ngrok-style dev tunnels on your own server, built on frp: `bestgate 3000` gives https://<name>.<your domain>",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "bin": {
8
+ "bestgate": "bin/bestgate.js"
9
+ },
10
+ "files": [
11
+ "bin",
12
+ "src",
13
+ "install.sh",
14
+ "README.md",
15
+ "LICENSE"
16
+ ],
17
+ "engines": {
18
+ "node": ">=20.17"
19
+ },
20
+ "scripts": {
21
+ "test": "node --test"
22
+ },
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "git+https://github.com/bestapps-ua/best-gate.git"
26
+ },
27
+ "publishConfig": {
28
+ "access": "public"
29
+ },
30
+ "keywords": [
31
+ "tunnel",
32
+ "frp",
33
+ "ngrok",
34
+ "localhost",
35
+ "dev"
36
+ ],
37
+ "dependencies": {
38
+ "@inquirer/prompts": "^8.8.1"
39
+ }
40
+ }
@@ -0,0 +1,41 @@
1
+ import { input, password } from '@inquirer/prompts';
2
+ import { decodeKey } from '../key.js';
3
+ import { CliError, isDomain, resolves } from '../util.js';
4
+ import { loadLogin, saveLogin } from './store.js';
5
+
6
+ export async function run() {
7
+ const old = loadLogin();
8
+ const host = await input({
9
+ message: 'Tunnel server host (base domain, e.g. t.example.com):',
10
+ default: old?.host,
11
+ validate: (v) => isDomain(v.trim()) || 'Enter a plain lowercase domain name, without https:// or a path.',
12
+ });
13
+ const keyText = await password({
14
+ message: 'Access key:',
15
+ mask: '*',
16
+ validate: (v) => {
17
+ try {
18
+ decodeKey(v.trim());
19
+ return true;
20
+ } catch {
21
+ return 'That is not a valid access key (it starts with bg_).';
22
+ }
23
+ },
24
+ });
25
+
26
+ let key;
27
+ try {
28
+ key = decodeKey(keyText.trim());
29
+ } catch (e) {
30
+ throw new CliError(`Invalid access key: ${e.message}`);
31
+ }
32
+ const h = host.trim();
33
+ saveLogin({ host: h, key: keyText.trim() });
34
+ console.log(`Logged in as ${key.user}`);
35
+
36
+ const control = `${key.control}.${h}`;
37
+ if (!(await resolves(control))) {
38
+ console.warn(`Warning: ${control} does not resolve in DNS. The login is saved, but tunnels will not start until it does.`);
39
+ console.warn('Check the host you typed, or ask the server owner whether the DNS records exist.');
40
+ }
41
+ }
@@ -0,0 +1,41 @@
1
+ // Where login data lives: <config dir>/login.json = { host, key }, mode 0600.
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+
6
+ export function configDir(env = process.env, platform = process.platform, home = os.homedir()) {
7
+ if (platform === 'win32') return path.join(env.APPDATA || path.join(home, 'AppData', 'Roaming'), 'bestgate');
8
+ return path.join(env.XDG_CONFIG_HOME || path.join(home, '.config'), 'bestgate');
9
+ }
10
+
11
+ const file = (dir) => path.join(dir, 'login.json');
12
+
13
+ // → { host, key } or null. BESTGATE_HOST + BESTGATE_KEY (both) override the file.
14
+ export function loadLogin(dir = configDir(), env = process.env) {
15
+ if (env.BESTGATE_HOST && env.BESTGATE_KEY) return { host: env.BESTGATE_HOST, key: env.BESTGATE_KEY };
16
+ try {
17
+ const { host, key } = JSON.parse(fs.readFileSync(file(dir), 'utf8'));
18
+ return host && key ? { host, key } : null;
19
+ } catch {
20
+ return null;
21
+ }
22
+ }
23
+
24
+ export function saveLogin({ host, key }, dir = configDir()) {
25
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
26
+ const f = file(dir);
27
+ const tmp = `${f}.${process.pid}.tmp`;
28
+ fs.writeFileSync(tmp, JSON.stringify({ host, key }, null, 2) + '\n', { mode: 0o600 });
29
+ fs.renameSync(tmp, f);
30
+ return f;
31
+ }
32
+
33
+ // → true if a file was removed
34
+ export function clearLogin(dir = configDir()) {
35
+ try {
36
+ fs.rmSync(file(dir));
37
+ return true;
38
+ } catch {
39
+ return false;
40
+ }
41
+ }