aptunnel 1.0.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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Uruba Software
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,249 @@
1
+ # aptunnel
2
+
3
+ Cross-platform Aptible tunnel manager. Open, close, and monitor multiple database tunnels with short aliases instead of long Aptible handles.
4
+
5
+ ```
6
+ aptunnel dev-db # open tunnel to dev database
7
+ aptunnel all # open all configured tunnels
8
+ aptunnel status # see what's running
9
+ ```
10
+
11
+ ---
12
+
13
+ ## Requirements
14
+
15
+ - **Node.js** 18+
16
+ - **[Aptible CLI](https://www.aptible.com/docs/cli)** installed and in your PATH
17
+
18
+ ---
19
+
20
+ ## Install
21
+
22
+ ```bash
23
+ npm install -g aptunnel
24
+ ```
25
+
26
+ ---
27
+
28
+ ## Quick Start
29
+
30
+ ```bash
31
+ aptunnel init
32
+ ```
33
+
34
+ The wizard will:
35
+ 1. Verify aptible CLI is installed
36
+ 2. Log you in (supports 2FA)
37
+ 3. Discover all your environments and databases
38
+ 4. Auto-assign ports starting at `55550`
39
+ 5. Let you set short aliases (e.g. `dev-db`, `dev-redis`)
40
+ 6. Write `~/.aptunnel/config.yaml`
41
+
42
+ ---
43
+
44
+ ## Commands
45
+
46
+ ### Open a tunnel
47
+
48
+ ```bash
49
+ aptunnel dev-db # open by alias
50
+ aptunnel dev-db --port=5432 # override port for this session
51
+ aptunnel dev-db --env=staging # target a different environment
52
+ ```
53
+
54
+ Output:
55
+ ```
56
+ ✔ dev-db tunnel opened
57
+ Port: 55554
58
+ Host: localhost.aptible.in
59
+ User: aptible
60
+ Password: xxxxxxxxxx
61
+ URL: postgresql://aptible:xxxxxxxxxx@localhost.aptible.in:55554/db
62
+ PID: 12345
63
+ ```
64
+
65
+ ### Close a tunnel
66
+
67
+ ```bash
68
+ aptunnel dev-db --close
69
+ aptunnel all --close # close all
70
+ aptunnel all --close --env=staging # close all in staging
71
+ ```
72
+
73
+ ### Open all tunnels for an environment
74
+
75
+ ```bash
76
+ aptunnel all # uses default environment
77
+ aptunnel all --env=staging
78
+ ```
79
+
80
+ ### Status
81
+
82
+ ```bash
83
+ aptunnel status
84
+ ```
85
+
86
+ ```
87
+ LOGIN STATUS
88
+ User: you@company.com
89
+ Token: valid (expires in 6d 12h)
90
+
91
+ TUNNELS
92
+
93
+ ENVIRONMENT DATABASE ALIAS PORT STATUS UPTIME PID CONNECTION URL
94
+ ──────────── ─────────────── ─────────── ────── ─────── ──────────── ────── ──────────────────────────────────────────
95
+ dev ekaredb-dev dev-db 55554 UP 02h15m30s 12345 postgresql://aptible:xxx@localhost.aptible.in:55554/db
96
+ dev ekaredb-redis dev-redis 55555 DOWN - - -
97
+ ```
98
+
99
+ ### Login
100
+
101
+ ```bash
102
+ aptunnel login # uses saved credentials, supports 2FA
103
+ aptunnel login --email=x@y.com --password=secret
104
+ aptunnel login --lifetime=14d # custom token lifetime
105
+ aptunnel login --status # show token info only
106
+ ```
107
+
108
+ ### Config
109
+
110
+ ```bash
111
+ aptunnel config # print config (password masked)
112
+ aptunnel config --raw # include password
113
+ aptunnel config --set-port dev-db 5433
114
+ aptunnel config --set-default staging
115
+ aptunnel config --refresh # re-discover environments/databases
116
+ aptunnel config --path # print config file path
117
+ ```
118
+
119
+ ---
120
+
121
+ ## Configuration
122
+
123
+ Config lives at `~/.aptunnel/config.yaml`. Password is stored separately in `~/.aptunnel/.credentials` (mode 600).
124
+
125
+ ```yaml
126
+ version: 1
127
+
128
+ credentials:
129
+ email: you@company.com
130
+
131
+ defaults:
132
+ environment: ekare-inc-development-gfpkcova
133
+ lifetime: 7d
134
+
135
+ environments:
136
+ ekare-inc-development-gfpkcova:
137
+ alias: dev
138
+ databases:
139
+ ekaredb-dev:
140
+ alias: dev-db
141
+ port: 55554
142
+ type: postgresql
143
+ ekaredb-dev-redis:
144
+ alias: dev-redis
145
+ port: 55555
146
+ type: redis
147
+
148
+ tunnel_defaults:
149
+ start_port: 55550
150
+ port_increment: 1
151
+ ```
152
+
153
+ ---
154
+
155
+ ## Shell Completions
156
+
157
+ ### Auto-install (detects your shell)
158
+
159
+ ```bash
160
+ aptunnel completions install
161
+ ```
162
+
163
+ ### Manual
164
+
165
+ **Bash** — add to `~/.bashrc`:
166
+ ```bash
167
+ source <(aptunnel completions bash)
168
+ ```
169
+
170
+ **Zsh** — add to `~/.zshrc`:
171
+ ```bash
172
+ source <(aptunnel completions zsh)
173
+ ```
174
+
175
+ **Fish** — copy to completions directory:
176
+ ```bash
177
+ aptunnel completions fish > ~/.config/fish/completions/aptunnel.fish
178
+ ```
179
+
180
+ Completions are dynamic — they read your config at runtime so your actual database aliases appear in tab-completion.
181
+
182
+ ---
183
+
184
+ ## Platform Notes
185
+
186
+ ### macOS
187
+ Full support. Install Aptible CLI via Homebrew:
188
+ ```bash
189
+ brew install aptible/aptible/aptible
190
+ ```
191
+
192
+ ### Linux
193
+ Full support. Install Aptible CLI:
194
+ ```bash
195
+ curl -s https://toolbelt.aptible.com/install.sh | bash
196
+ ```
197
+
198
+ ### Windows
199
+ Supported with some limitations:
200
+ - Process management uses `taskkill` and `wmic` instead of Unix signals
201
+ - Port detection uses `netstat` instead of `lsof`
202
+ - File permissions use `icacls` for the credentials file
203
+ - Requires Node.js 18+ for Windows
204
+
205
+ ### WSL (Windows Subsystem for Linux)
206
+ Treated as Linux. Browser opening uses `wslview` if available, otherwise falls back to `cmd.exe /c start`.
207
+
208
+ ---
209
+
210
+ ## How Tunnels Work
211
+
212
+ `aptible db:tunnel` is a blocking foreground process. aptunnel spawns it **detached** with `stdio` redirected to a log file (`/tmp/aptunnel-<alias>.log`), then saves the PID to `/tmp/aptunnel-<alias>.pid`.
213
+
214
+ On `aptunnel status`, each PID file is checked to determine if the process is still alive.
215
+
216
+ When you close a tunnel (`aptunnel dev-db --close`), aptunnel kills the process and cleans up the PID file.
217
+
218
+ Pressing **Ctrl+C** while aptunnel is running closes all open tunnels before exiting.
219
+
220
+ ---
221
+
222
+ ## Troubleshooting
223
+
224
+ **"Aptible CLI not found"** — Install aptible and make sure it's in your PATH. Run `aptible version` to verify.
225
+
226
+ **"Token expired"** — Run `aptunnel login`. aptunnel will attempt auto-relogin on tunnel failures, but a fresh login is the cleanest fix.
227
+
228
+ **"Port already in use"** — Another process is on that port. Use `--force` to kill it or `--port=<N>` to use a different port.
229
+
230
+ **"Config file is corrupted"** — Delete `~/.aptunnel/config.yaml` and re-run `aptunnel init`.
231
+
232
+ **Tunnel fails silently** — Check the log file: `cat /tmp/aptunnel-<alias>.log`. Set `DEBUG=1` for verbose output from aptunnel.
233
+
234
+ ---
235
+
236
+ ## Contributing
237
+
238
+ 1. Fork the repo
239
+ 2. Create a branch: `git checkout -b my-feature`
240
+ 3. Make your changes
241
+ 4. Open a pull request against `main`
242
+
243
+ Please keep PRs focused. One feature or fix per PR.
244
+
245
+ ---
246
+
247
+ ## License
248
+
249
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,23 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { fileURLToPath, pathToFileURL } from 'url';
4
+ import { dirname, resolve } from 'path';
5
+
6
+ const __dirname = dirname(fileURLToPath(import.meta.url));
7
+
8
+ // Verify minimum Node.js version
9
+ const [major] = process.versions.node.split('.').map(Number);
10
+ if (major < 18) {
11
+ process.stderr.write(
12
+ `aptunnel requires Node.js 18 or higher. You are running ${process.version}.\n`
13
+ );
14
+ process.exit(1);
15
+ }
16
+
17
+ // Launch the CLI router
18
+ // Use pathToFileURL so Windows absolute paths (D:\...) are valid ESM specifiers.
19
+ const entryUrl = pathToFileURL(resolve(__dirname, '../src/index.js')).href;
20
+ import(entryUrl).catch((err) => {
21
+ process.stderr.write(`Fatal error: ${err.message}\n`);
22
+ process.exit(1);
23
+ });
package/package.json ADDED
@@ -0,0 +1,38 @@
1
+ {
2
+ "name": "aptunnel",
3
+ "version": "1.0.0",
4
+ "description": "Cross-platform Aptible tunnel manager — multi-tunnel, auto-discovery, background process management",
5
+ "type": "module",
6
+ "bin": {
7
+ "aptunnel": "./bin/aptunnel.js"
8
+ },
9
+ "main": "./src/index.js",
10
+ "engines": {
11
+ "node": ">=18.0.0"
12
+ },
13
+ "scripts": {
14
+ "start": "node bin/aptunnel.js",
15
+ "test": "node --test test/lib/platform.test.js test/lib/config-manager.test.js test/lib/process-manager.test.js test/lib/aptible.test.js test/lib/completions.test.js test/commands/config.test.js test/commands/help.test.js test/commands/status.test.js",
16
+ "test:integration": "node --test test/integration/cli.test.js",
17
+ "test:all": "node --test test/lib/platform.test.js test/lib/config-manager.test.js test/lib/process-manager.test.js test/lib/aptible.test.js test/lib/completions.test.js test/commands/config.test.js test/commands/help.test.js test/commands/status.test.js test/integration/cli.test.js",
18
+ "test:watch": "node --test --watch test/lib/platform.test.js test/lib/config-manager.test.js test/lib/process-manager.test.js test/lib/aptible.test.js test/lib/completions.test.js test/commands/config.test.js test/commands/help.test.js test/commands/status.test.js"
19
+ },
20
+ "files": [
21
+ "bin/",
22
+ "src/"
23
+ ],
24
+ "keywords": [
25
+ "aptible",
26
+ "tunnel",
27
+ "database",
28
+ "devtools",
29
+ "cli"
30
+ ],
31
+ "author": "Uruba Software",
32
+ "license": "MIT",
33
+ "dependencies": {
34
+ "chalk": "^5.3.0",
35
+ "js-yaml": "^4.1.0",
36
+ "ora": "^8.0.1"
37
+ }
38
+ }
@@ -0,0 +1,24 @@
1
+ import { logger } from '../lib/logger.js';
2
+ import { bashScript, zshScript, fishScript, installCompletions } from '../lib/completions.js';
3
+
4
+ export async function runCompletions(args) {
5
+ const sub = args[0];
6
+
7
+ switch (sub) {
8
+ case 'bash':
9
+ process.stdout.write(bashScript());
10
+ break;
11
+ case 'zsh':
12
+ process.stdout.write(zshScript());
13
+ break;
14
+ case 'fish':
15
+ process.stdout.write(fishScript());
16
+ break;
17
+ case 'install':
18
+ installCompletions();
19
+ break;
20
+ default:
21
+ logger.error(`Unknown shell: "${sub ?? ''}". Use: bash, zsh, fish, install`);
22
+ process.exit(1);
23
+ }
24
+ }
@@ -0,0 +1,119 @@
1
+ import chalk from 'chalk';
2
+ import yaml from 'js-yaml';
3
+ import { logger } from '../lib/logger.js';
4
+ import {
5
+ exists, load, save, getConfigPath, setPort, getDefaultEnv, getAllTunnelTargets,
6
+ } from '../lib/config-manager.js';
7
+ import { listEnvironments, listDatabases } from '../lib/aptible.js';
8
+
9
+ export async function runConfig(args) {
10
+ if (!exists() && !args.includes('--path')) {
11
+ logger.warn('No config found. Run `aptunnel init` to set up.');
12
+ return;
13
+ }
14
+
15
+ if (args.includes('--path')) {
16
+ console.log(getConfigPath());
17
+ return;
18
+ }
19
+
20
+ if (args.includes('--refresh')) {
21
+ await refreshConfig();
22
+ return;
23
+ }
24
+
25
+ const setPortArg = args.indexOf('--set-port');
26
+ if (setPortArg !== -1) {
27
+ const alias = args[setPortArg + 1];
28
+ const port = parseInt(args[setPortArg + 2], 10);
29
+ if (!alias || isNaN(port)) {
30
+ logger.error('Usage: aptunnel config --set-port <alias> <port>');
31
+ process.exit(1);
32
+ }
33
+ setPort(alias, port);
34
+ logger.success(`Port for "${alias}" set to ${port}.`);
35
+ return;
36
+ }
37
+
38
+ const setDefaultArg = args.indexOf('--set-default');
39
+ if (setDefaultArg !== -1) {
40
+ const envAlias = args[setDefaultArg + 1];
41
+ if (!envAlias) {
42
+ logger.error('Usage: aptunnel config --set-default <env-alias>');
43
+ process.exit(1);
44
+ }
45
+ const config = load();
46
+ // Resolve alias or handle
47
+ const { getEnvironment } = await import('../lib/config-manager.js');
48
+ const handle = getEnvironment(envAlias) ?? envAlias;
49
+ config.defaults = config.defaults ?? {};
50
+ config.defaults.environment = handle;
51
+ save(config);
52
+ logger.success(`Default environment set to "${handle}".`);
53
+ return;
54
+ }
55
+
56
+ // Default: print config (mask password by default)
57
+ const showRaw = args.includes('--raw');
58
+ const config = load();
59
+
60
+ // Deep-clone and mask password unless --raw
61
+ let display = JSON.parse(JSON.stringify(config));
62
+ if (!showRaw) {
63
+ if (display.credentials?.password) {
64
+ display.credentials.password = '***masked***';
65
+ }
66
+ }
67
+
68
+ const raw = yaml.dump(display, { lineWidth: 120, noRefs: true });
69
+ console.log('');
70
+ console.log(chalk.dim(`# ${getConfigPath()}`));
71
+ console.log(raw);
72
+ }
73
+
74
+ // ─── Refresh: re-discover environments and databases ─────────────────────────
75
+
76
+ async function refreshConfig() {
77
+ const ora = (await import('ora')).default;
78
+ const config = load();
79
+
80
+ const spinner = ora('Fetching environments from Aptible…').start();
81
+ const envs = listEnvironments();
82
+ spinner.succeed(`Found ${envs.length} environment(s).`);
83
+
84
+ let added = 0;
85
+
86
+ for (const env of envs) {
87
+ if (!config.environments) config.environments = {};
88
+ if (!config.environments[env.handle]) {
89
+ config.environments[env.handle] = { alias: env.handle, databases: {} };
90
+ }
91
+
92
+ const dbSpinner = ora(`Fetching databases for ${env.handle}…`).start();
93
+ const dbs = listDatabases(env.handle);
94
+ dbSpinner.succeed(` ${dbs.length} database(s) in ${env.handle}`);
95
+
96
+ for (const db of dbs) {
97
+ if (!config.environments[env.handle].databases[db.handle]) {
98
+ // Find next unused port
99
+ const usedPorts = new Set(
100
+ Object.values(config.environments).flatMap(e =>
101
+ Object.values(e.databases ?? {}).map(d => d.port)
102
+ ).filter(Boolean)
103
+ );
104
+ let port = config.tunnel_defaults?.start_port ?? 55550;
105
+ while (usedPorts.has(port)) port++;
106
+
107
+ config.environments[env.handle].databases[db.handle] = {
108
+ alias: db.handle,
109
+ port,
110
+ type: db.type,
111
+ };
112
+ added++;
113
+ }
114
+ }
115
+ }
116
+
117
+ save(config);
118
+ logger.success(`Config refreshed. ${added} new database(s) added.`);
119
+ }
@@ -0,0 +1,106 @@
1
+ import chalk from 'chalk';
2
+ import { createRequire } from 'module';
3
+ import { fileURLToPath } from 'url';
4
+ import { dirname, resolve } from 'path';
5
+ import { exists, load, getDefaultEnv, getAllDatabases } from '../lib/config-manager.js';
6
+
7
+ const __dirname = dirname(fileURLToPath(import.meta.url));
8
+ const require = createRequire(import.meta.url);
9
+ const pkg = require(resolve(__dirname, '../../package.json'));
10
+
11
+ export function runHelp() {
12
+ const hasConfig = exists();
13
+ let config = null;
14
+ let databases = [];
15
+ let defaultEnv = null;
16
+
17
+ if (hasConfig) {
18
+ try {
19
+ config = load();
20
+ databases = getAllDatabases();
21
+ defaultEnv = getDefaultEnv();
22
+ } catch {
23
+ // Corrupted config — show generic help
24
+ }
25
+ }
26
+
27
+ console.log('');
28
+ console.log(chalk.bold(`aptunnel`) + chalk.dim(` — Aptible Tunnel Manager v${pkg.version}`));
29
+ console.log('');
30
+
31
+ section('USAGE');
32
+ console.log(' aptunnel <command> [options]');
33
+ console.log('');
34
+
35
+ section('COMMANDS');
36
+ cmd('aptunnel init', 'Setup wizard (login, discover environments & databases)');
37
+ cmd('aptunnel login [--status]', 'Login to Aptible or show token status');
38
+ cmd('aptunnel status', 'Show all tunnel statuses and login info');
39
+ cmd('aptunnel config', 'View or modify configuration');
40
+ cmd('aptunnel completions <bash|zsh|fish>', 'Print shell completion script');
41
+ cmd('aptunnel <db-alias> [--port=N]', 'Open a tunnel to a database');
42
+ cmd('aptunnel <db-alias> --close', 'Close a tunnel');
43
+ cmd('aptunnel all [--env=ALIAS]', 'Open all tunnels for an environment');
44
+ cmd('aptunnel all --close [--env=ALIAS]', 'Close all tunnels');
45
+ console.log('');
46
+
47
+ if (hasConfig && databases.length > 0) {
48
+ // Resolve default env alias
49
+ let defaultAlias = defaultEnv;
50
+ if (defaultEnv && config?.environments?.[defaultEnv]?.alias) {
51
+ defaultAlias = config.environments[defaultEnv].alias;
52
+ }
53
+
54
+ section(`YOUR DATABASES (default env: ${chalk.cyan(defaultAlias ?? '(none)')})`);
55
+
56
+ // Show databases for default environment first
57
+ const defaultDbs = databases.filter(d => d.environment === defaultEnv);
58
+ const otherDbs = databases.filter(d => d.environment !== defaultEnv);
59
+
60
+ for (const db of defaultDbs) {
61
+ cmd(`aptunnel ${db.alias}`, `→ ${db.handle} ${chalk.dim(`(port ${db.port})`)}`);
62
+ }
63
+
64
+ if (otherDbs.length > 0) {
65
+ console.log('');
66
+ section('OTHER ENVIRONMENTS');
67
+ for (const db of otherDbs) {
68
+ cmd(`aptunnel ${db.alias} --env=${db.envAlias}`, `→ ${db.handle} ${chalk.dim(`(port ${db.port})`)}`);
69
+ }
70
+ }
71
+ console.log('');
72
+ } else {
73
+ console.log(chalk.dim(' (no config found — run `aptunnel init` to get started)'));
74
+ console.log('');
75
+ }
76
+
77
+ section('OPTIONS');
78
+ opt('--port=N', 'Override port for this session');
79
+ opt('--env=ALIAS', 'Target a specific environment');
80
+ opt('--close', 'Close tunnel(s)');
81
+ opt('--force', 'Kill existing process on port conflict');
82
+ opt('--help, -h', 'Show this help');
83
+ opt('--version, -v', 'Show version');
84
+ console.log('');
85
+
86
+ section('CONFIG SUBCOMMANDS');
87
+ cmd('aptunnel config', 'Print full config (password masked)');
88
+ cmd('aptunnel config --raw', 'Print full config including password');
89
+ cmd('aptunnel config --set-port <alias> <N>', 'Update port for a database');
90
+ cmd('aptunnel config --set-default <env>', 'Change default environment');
91
+ cmd('aptunnel config --refresh', 'Re-discover envs/dbs from Aptible');
92
+ cmd('aptunnel config --path', 'Print config file path');
93
+ console.log('');
94
+ }
95
+
96
+ function section(title) {
97
+ console.log(chalk.bold(title));
98
+ }
99
+
100
+ function cmd(name, description) {
101
+ console.log(` ${chalk.cyan(name.padEnd(48))} ${chalk.dim(description)}`);
102
+ }
103
+
104
+ function opt(name, description) {
105
+ console.log(` ${chalk.yellow(name.padEnd(20))} ${description}`);
106
+ }