asyx 0.5.9 → 0.6.1

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.
Files changed (88) hide show
  1. package/README.md +73 -9
  2. package/SECURITY.md +5 -3
  3. package/package.json +13 -23
  4. package/src/commands/name.js +23 -0
  5. package/src/commands/reject-messages.js +54 -0
  6. package/src/commands/setup.js +98 -102
  7. package/src/commands/tunnel.js +279 -2425
  8. package/src/lib/naming.js +81 -0
  9. package/src/main.js +9 -1
  10. package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneClient.d.ts +260 -0
  11. package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneClient.js +1088 -0
  12. package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneTransport.d.ts +79 -0
  13. package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneTransport.js +138 -0
  14. package/vendor/tunnel-core/dist/control-plane/session.d.ts +50 -0
  15. package/vendor/tunnel-core/dist/control-plane/session.js +115 -0
  16. package/vendor/tunnel-core/dist/errors.d.ts +49 -0
  17. package/vendor/tunnel-core/dist/errors.js +53 -0
  18. package/vendor/tunnel-core/dist/flows/http.d.ts +50 -0
  19. package/vendor/tunnel-core/dist/flows/http.js +585 -0
  20. package/vendor/tunnel-core/dist/flows/tcp.d.ts +60 -0
  21. package/vendor/tunnel-core/dist/flows/tcp.js +546 -0
  22. package/vendor/tunnel-core/dist/flows/udp.d.ts +41 -0
  23. package/vendor/tunnel-core/dist/flows/udp.js +376 -0
  24. package/vendor/tunnel-core/dist/lib/adapt-logger.d.ts +2 -0
  25. package/vendor/tunnel-core/dist/lib/adapt-logger.js +6 -0
  26. package/vendor/tunnel-core/dist/lib/fingerprint.d.ts +13 -0
  27. package/vendor/tunnel-core/dist/lib/fingerprint.js +95 -0
  28. package/vendor/tunnel-core/dist/lib/jwt-verifier.d.ts +27 -0
  29. package/vendor/tunnel-core/dist/lib/jwt-verifier.js +230 -0
  30. package/vendor/tunnel-core/dist/lib/logger.d.ts +9 -0
  31. package/vendor/tunnel-core/dist/lib/logger.js +58 -0
  32. package/vendor/tunnel-core/dist/lib/refresh-helpers.d.ts +16 -0
  33. package/vendor/tunnel-core/dist/lib/refresh-helpers.js +66 -0
  34. package/vendor/tunnel-core/dist/lifecycle.d.ts +24 -0
  35. package/vendor/tunnel-core/dist/lifecycle.js +29 -0
  36. package/vendor/tunnel-core/dist/mqtt/awaiter-map.d.ts +56 -0
  37. package/vendor/tunnel-core/dist/mqtt/awaiter-map.js +227 -0
  38. package/vendor/tunnel-core/dist/mqtt/events/handlers.d.ts +58 -0
  39. package/vendor/tunnel-core/dist/mqtt/events/handlers.js +250 -0
  40. package/vendor/tunnel-core/dist/mqtt/events/index.d.ts +1 -0
  41. package/vendor/tunnel-core/dist/mqtt/events/index.js +191 -0
  42. package/vendor/tunnel-core/dist/mqtt/events/schemas.d.ts +498 -0
  43. package/vendor/tunnel-core/dist/mqtt/events/schemas.js +51 -0
  44. package/vendor/tunnel-core/dist/mqtt/ingress.d.ts +63 -0
  45. package/vendor/tunnel-core/dist/mqtt/ingress.js +170 -0
  46. package/vendor/tunnel-core/dist/state/assignment.d.ts +122 -0
  47. package/vendor/tunnel-core/dist/state/assignment.js +322 -0
  48. package/vendor/tunnel-core/dist/state/instance-registry.d.ts +88 -0
  49. package/{src → vendor/tunnel-core/dist}/state/instance-registry.js +38 -53
  50. package/vendor/tunnel-core/dist/tcp-v1/framing.d.ts +43 -0
  51. package/vendor/tunnel-core/dist/tcp-v1/framing.js +157 -0
  52. package/vendor/tunnel-core/dist/tunnel/http-tunnel.d.ts +137 -0
  53. package/vendor/tunnel-core/dist/tunnel/http-tunnel.js +1591 -0
  54. package/vendor/tunnel-core/dist/tunnel/httpws-constants.d.ts +13 -0
  55. package/{src → vendor/tunnel-core/dist}/tunnel/httpws-constants.js +5 -7
  56. package/vendor/tunnel-core/dist/tunnel/reconnect.d.ts +76 -0
  57. package/vendor/tunnel-core/dist/tunnel/reconnect.js +183 -0
  58. package/vendor/tunnel-core/dist/tunnel/request-sink.d.ts +40 -0
  59. package/vendor/tunnel-core/dist/tunnel/request-sink.js +39 -0
  60. package/vendor/tunnel-core/dist/tunnel/tcp-tunnel.d.ts +89 -0
  61. package/vendor/tunnel-core/dist/tunnel/tcp-tunnel.js +838 -0
  62. package/vendor/tunnel-core/dist/tunnel/udp-tunnel.d.ts +90 -0
  63. package/vendor/tunnel-core/dist/tunnel/udp-tunnel.js +737 -0
  64. package/vendor/tunnel-core/dist/tunnel/ws-control.d.ts +22 -0
  65. package/vendor/tunnel-core/dist/tunnel/ws-control.js +124 -0
  66. package/vendor/tunnel-core/dist/types.d.ts +24 -0
  67. package/vendor/tunnel-core/dist/types.js +2 -0
  68. package/vendor/tunnel-core/dist/udp-v1/framing.d.ts +41 -0
  69. package/vendor/tunnel-core/dist/udp-v1/framing.js +158 -0
  70. package/vendor/tunnel-core/package.json +34 -0
  71. package/src/control-plane/MqttControlPlaneClient.js +0 -1196
  72. package/src/control-plane/MqttControlPlaneTransport.js +0 -150
  73. package/src/lib/fingerprint.js +0 -115
  74. package/src/lib/jwt-verifier.js +0 -260
  75. package/src/lib/logger.js +0 -62
  76. package/src/mqtt/awaiter-map.js +0 -247
  77. package/src/mqtt/events/handlers.js +0 -300
  78. package/src/mqtt/events/index.js +0 -222
  79. package/src/mqtt/events/schemas.js +0 -58
  80. package/src/mqtt/ingress.js +0 -182
  81. package/src/state/assignment.js +0 -333
  82. package/src/tcp-v1/framing.js +0 -203
  83. package/src/tunnel/http-tunnel.js +0 -1738
  84. package/src/tunnel/reconnect.js +0 -182
  85. package/src/tunnel/tcp-tunnel.js +0 -944
  86. package/src/tunnel/udp-tunnel.js +0 -813
  87. package/src/tunnel/ws-control.js +0 -135
  88. package/src/udp-v1/framing.js +0 -203
package/README.md CHANGED
@@ -30,7 +30,7 @@ Enrollment is human-gated (browser verification) so prompts alone cannot open tu
30
30
 
31
31
  ```bash
32
32
  npm install -g asyx # 1. install (Node 18.17+)
33
- asyx setup # 2. enroll once — browser opens, pick your subdomain
33
+ asyx setup # 2. enroll once — approve in the browser with the code shown
34
34
  npm run dev # 3. start your app (note the port, often 3000 or 5173)
35
35
  asyx tunnel --http --port 3000 # 4. second terminal — copy the printed URL
36
36
  ```
@@ -54,7 +54,9 @@ PUBLISHING CONTRACT — Asyx tunnel
54
54
 
55
55
  Prerequisites (human completes once per machine):
56
56
  - asyx CLI installed (npm install -g asyx)
57
- - asyx setup completed (browser enrollment)
57
+ - asyx setup completed (browser enrollment). An agent may start it with
58
+ `asyx setup --json` (add --hostname NAME or --random to pick the name) and
59
+ show the approval link to the human; the human approves with the code shown.
58
60
 
59
61
  When a local HTTP server is running on PORT:
60
62
  1. Run: asyx tunnel --http --port PORT
@@ -99,11 +101,44 @@ Node.js **18.17+** recommended.
99
101
  asyx setup
100
102
  ```
101
103
 
102
- - Opens your browser for passwordless approval; you choose `<subdomain>.tunnel.asyx.ai`.
103
- - Provisions a device certificate and client ID under `~/.asyx/certs/<clientId>/`.
104
+ - Prints an approval link and a short code, and opens your browser. Sign in, check the code matches your terminal, and press **Approve**. Only approve a setup you started yourself—never a link someone sent you.
105
+ - The terminal never asks questions; it waits up to 10 minutes for the approval, then reports the device's hostname.
106
+ - Provisions a device certificate and client ID under `~/.asyx/certs/<clientId>/`. The private key never leaves the machine.
104
107
  - Hardware fingerprint is hashed locally; raw attributes never leave the device.
108
+ - Running `asyx setup` again on the same machine keeps the same device and hostname (it renews the certificate).
105
109
  - Run `asyx setup` on each host you want to trust—certificates are single-device.
106
110
 
111
+ ### Device names and several devices
112
+
113
+ Each device on your account has its own hostname under `tunnel.asyx.ai`. Your first device uses your account's name; each further device gets its own:
114
+
115
+ ```bash
116
+ asyx name check orders-api # is orders-api.tunnel.asyx.ai available? (no setup needed)
117
+ asyx setup --hostname orders-api # enroll this machine with that name
118
+ asyx setup --random # or a generated name such as quiet-otter-482
119
+ asyx setup # or choose on the approval page (it proposes <machine>-<account>)
120
+ ```
121
+
122
+ Names use 3–30 characters: lowercase letters, digits and hyphens, starting and ending with a letter or digit. Some names are reserved. How many devices an account can have depends on its plan.
123
+
124
+ ### For agents and scripts: `--json` and exit codes
125
+
126
+ With `--json`, `asyx setup` prints one JSON object per line on stdout and nothing else:
127
+
128
+ ```text
129
+ {"event":"approval_required","url":"https://www.asyx.ai/console/tunnel?...","code":"ABC-123","clientId":"cli_…","expiresInSeconds":600}
130
+ {"event":"enrolled","clientId":"cli_…","hostname":"orders-api.tunnel.asyx.ai"}
131
+ ```
132
+
133
+ On failure the last line is `{"event":"error","error":"<code>",…}` (with `suggestions` when a `--hostname` is not available). `asyx name check --json` prints `{"label","hostname","status","suggestions"}`, where `status` is `available`, `hostname_taken`, `hostname_reserved`, `hostname_cooling_down` or `hostname_invalid`.
134
+
135
+ | Exit code | `asyx setup` | `asyx name check` |
136
+ | --- | --- | --- |
137
+ | 0 | Enrolled | Available |
138
+ | 1 | Not approved in time, expired, signed out, or another failure | Could not check (network, rate limit) |
139
+ | 2 | Invalid options | Invalid usage |
140
+ | 3 | The `--hostname` name is not available (nothing was started) | Not available |
141
+
107
142
  ---
108
143
 
109
144
  ## HTTP tunnels (most common)
@@ -112,8 +147,9 @@ asyx setup
112
147
  asyx tunnel --http --port 3000
113
148
  ```
114
149
 
115
- - Forwards to `127.0.0.1:3000` (loopback only).
116
- - Prints your stable `https://<subdomain>.tunnel.asyx.ai` URL.
150
+ - Forwards to your app on localhost (loopback only; works whether it listens on IPv4 `127.0.0.1` or IPv6 `::1`).
151
+ - Prints your device's stable `https://<hostname>.tunnel.asyx.ai` URL.
152
+ - If your app stops answering, the tunnel stays up: the terminal says so, visitors see a "not reachable" page, and the terminal tells you when the app is answering again.
117
153
  - TLS and token refresh handled automatically; your app keeps its port.
118
154
  - If the connection drops (network loss, laptop wake, Asyx server maintenance), the CLI reconnects on its own and the same URL comes back.
119
155
 
@@ -168,7 +204,8 @@ If the connection of a TCP or UDP tunnel drops (network loss, Asyx server mainte
168
204
  ```bash
169
205
  asyx help # commands; asyx tunnel --help for tunnel options
170
206
  asyx --version
171
- asyx setup
207
+ asyx setup [--hostname <name> | --random] [--json]
208
+ asyx name check <name> [--json]
172
209
  asyx tunnel --http --port <n> [--secgroup <slug>]
173
210
  asyx tunnel --tcp --port <n> [--name <alias>] [--external-port <p>]
174
211
  asyx tunnel --udp --port <n> [--external-port <p>]
@@ -177,7 +214,29 @@ asyx tunnel --minecraft [--port <n>] [--name <alias>]
177
214
 
178
215
  ---
179
216
 
180
- ## What's new in 0.5.9
217
+ ## What's new in 0.6.1
218
+
219
+ 0.6.1 is the 0.6 release; 0.6.0 was published with a packaging error and could not be installed.
220
+
221
+ **Several devices, each with its own name** — every device on your account gets its own hostname. Pick it with `asyx setup --hostname <name>`, get a generated one with `--random`, or choose it on the approval page, which proposes `<machine>-<account>` and checks names as you type.
222
+
223
+ **`asyx name check`** — ask whether `<name>.tunnel.asyx.ai` is available, before setup and without signing in. Answers say why a name is not available and suggest alternatives.
224
+
225
+ **Built for agents** — `asyx setup --json` and `asyx name check --json` print machine-readable output with documented exit codes. The terminal never prompts.
226
+
227
+ **Safer approval** — nothing is approved until you press **Approve**; the page asks for the short code printed in your terminal and shows which computer and account the device joins.
228
+
229
+ **Re-running setup keeps your device** — setting up the same machine again keeps its device and hostname instead of creating a new device.
230
+
231
+ **"Your app isn't answering" instead of silence** — when nothing listens on your port, the HTTP tunnel stays up, tells you in the terminal, and shows visitors a "not reachable" page until your app is back.
232
+
233
+ **localhost on IPv6** — apps that listen only on `::1` (common with recent Node.js and some dev servers) are reached correctly.
234
+
235
+ **More reliable with several tunnels running** — tunnels running at the same time, on one machine or several, no longer interfere with each other's token refresh.
236
+
237
+ **Windows** — tested on Windows 11 (ARM64), including setup and tunnels.
238
+
239
+ ## Earlier: 0.5.9
181
240
 
182
241
  **TCP and UDP tunnels reconnect on their own** — after a network drop or Asyx server maintenance, TCP and UDP tunnels come back with the same hostname and public port, without rerunning the CLI. Previously they ended and had to be started again. See [Other tunnel types](#other-tunnel-types) for the settings.
183
242
 
@@ -245,7 +304,11 @@ Levels: `error` | `warn` | `info` | `debug` (default `info`).
245
304
  | Issue | Fix |
246
305
  | --- | --- |
247
306
  | `asyx: command not found` | `npm install -g asyx` or `npx asyx@latest` |
248
- | Setup browser did not open | Run `asyx setup` again; open the printed URL manually |
307
+ | Setup browser did not open | Open the link `asyx setup` printed; it waits up to 10 minutes |
308
+ | Approval page says the code does not match | Type the code from the terminal that printed the link (codes change on every `asyx setup`) |
309
+ | `asyx setup --hostname` exits with code 3 | The name is taken or reserved; pick one of the suggestions or run `asyx name check` |
310
+ | Windows PowerShell: "running scripts is disabled on this system" | Run `asyx.cmd` instead of `asyx` (or use Command Prompt), or allow local scripts once: `Set-ExecutionPolicy -Scope CurrentUser RemoteSigned` |
311
+ | Tunnel stops right after starting with `jwt_expired_before_refresh` | Your computer's clock is wrong; turn on automatic time and try again |
249
312
  | Tunnel URL 502 / unreachable | Dev server not running on the same port |
250
313
  | Link dies overnight | Expected—the tunnel lives only while the CLI runs and the machine is awake |
251
314
  | TCP/UDP tunnel ended after an outage | It retries for 15 minutes, then exits; run the same command again (raise `ASYX_TUNNEL_RECONNECT_MAX_MS` for longer outages) |
@@ -257,6 +320,7 @@ Levels: `error` | `warn` | `info` | `debug` (default `info`).
257
320
  ## Security
258
321
 
259
322
  - Device-bound identity per host; hardware fingerprint hashed locally.
323
+ - Human approval for every new device, confirmed with a one-time code from your terminal.
260
324
  - Mutual TLS with a per-device certificate; short-lived signed tunnel tokens.
261
325
  - Forward-only proxy—your app stays isolated; no direct inbound to your host.
262
326
  - Report issues: [security@asyx.ai](mailto:security@asyx.ai)
package/SECURITY.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Security Policy
2
2
 
3
- Last updated: 2025-10-23
3
+ Last updated: 2026-11-25
4
4
 
5
5
  ## Reporting a Vulnerability
6
6
 
@@ -11,11 +11,13 @@ Last updated: 2025-10-23
11
11
  ## Supported Builds
12
12
 
13
13
  - The Asyx CLI is in public beta. Only the latest published npm package receives security updates.
14
- - Create an account at https://www.asyx.ai/register (email + magic link; no invite code). Subdomains are reserved during `asyx setup`.
14
+ - Create an account at https://www.asyx.ai/register (email + magic link; no invite code). Each device gets its own hostname, chosen at `asyx setup`.
15
15
 
16
16
  ## Device-Bound Credentials
17
17
 
18
- - `asyx setup` issues a unique device certificate and UUID, stored under `~/.asyx/certs/<clientId>/`.
18
+ - `asyx setup` issues a unique device certificate, stored under `~/.asyx/certs/<clientId>/`. The private key is generated on the machine and never leaves it.
19
+ - A device is added only after a signed-in person presses **Approve** on www.asyx.ai and enters the short code printed in the terminal that started the setup. Never approve a setup link someone else sent you.
20
+ - Re-running `asyx setup` on the same machine keeps its device id and renews its certificate.
19
21
  - Certificates cannot be reused on other machines; copying the directory fails policy checks. Re-run `asyx setup` on each host instead.
20
22
  - Remove local material by deleting the cert directory (`rm -rf ~/.asyx/certs/<clientId>`). The next setup reinstates access.
21
23
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "asyx",
3
- "version": "0.5.9",
3
+ "version": "0.6.1",
4
4
  "description": "Asyx tunnel CLI — secure localhost exposure (HTTP, TCP, UDP)",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -31,41 +31,25 @@
31
31
  "src/commands/.gitkeep",
32
32
  "src/commands/mqtt-broker.js",
33
33
  "src/commands/mqtt.js",
34
+ "src/commands/name.js",
35
+ "src/commands/reject-messages.js",
34
36
  "src/commands/setup.js",
35
37
  "src/commands/sts.js",
36
38
  "src/commands/tunnel.js",
37
39
  "src/commands/validate-target-host.js",
38
- "src/control-plane/MqttControlPlaneClient.js",
39
- "src/control-plane/MqttControlPlaneTransport.js",
40
40
  "src/lib/.gitkeep",
41
41
  "src/lib/certs.js",
42
42
  "src/lib/csr.js",
43
43
  "src/lib/device.js",
44
- "src/lib/fingerprint.js",
45
44
  "src/lib/ids.js",
46
- "src/lib/jwt-verifier.js",
47
- "src/lib/logger.js",
45
+ "src/lib/naming.js",
48
46
  "src/lib/pairing.js",
49
47
  "src/lib/shared-transport.js",
50
48
  "src/main.js",
51
- "src/mqtt/awaiter-map.js",
52
- "src/mqtt/events/handlers.js",
53
- "src/mqtt/events/index.js",
54
- "src/mqtt/events/schemas.js",
55
- "src/mqtt/ingress.js",
56
- "src/state/assignment.js",
57
- "src/state/instance-registry.js",
58
- "src/tcp-v1/framing.js",
59
- "src/tunnel/http-tunnel.js",
60
- "src/tunnel/httpws-constants.js",
61
- "src/tunnel/reconnect.js",
62
- "src/tunnel/tcp-tunnel.js",
63
- "src/tunnel/udp-tunnel.js",
64
- "src/tunnel/ws-control.js",
65
- "src/udp-v1/framing.js",
66
49
  "LICENSE",
67
50
  "README.md",
68
- "SECURITY.md"
51
+ "SECURITY.md",
52
+ "vendor/"
69
53
  ],
70
54
  "dependencies": {
71
55
  "@asyx/mqtt-broker-aws": "^0.1.0",
@@ -85,16 +69,22 @@
85
69
  "build": "npm install",
86
70
  "postinstall": "node -e \"console.log('✅ asyx installed')\"",
87
71
  "check": "node ./src/main.js --version",
72
+ "pretest": "npm --prefix ../../packages/tunnel-core run build && npm --prefix ../../packages/mqtt-client run build >/dev/null && npm --prefix ../../packages/mqtt-broker-aws run build >/dev/null",
88
73
  "test": "NODE_OPTIONS=\"--experimental-vm-modules --max-old-space-size=8192\" jest --runInBand",
74
+ "pretest:ci": "npm --prefix ../../packages/tunnel-core run build && npm --prefix ../../packages/mqtt-client run build >/dev/null && npm --prefix ../../packages/mqtt-broker-aws run build >/dev/null",
89
75
  "test:ci": "NODE_OPTIONS=\"--experimental-vm-modules --max-old-space-size=8192\" jest --runInBand --forceExit",
90
76
  "test:e2e:httpwsv2": "NODE_OPTIONS=\"--experimental-vm-modules --max-old-space-size=8192\" jest --runInBand --testPathIgnorePatterns=/node_modules/ --testMatch='**/test/e2e/**/*.e2e.test.js'",
91
77
  "pack:verify": "node scripts/pack-verify.mjs",
92
78
  "prepublishOnly": "npm run test:ci && npm run pack:verify",
93
79
  "prepack": "node scripts/prepack.mjs",
94
- "postpack": "node scripts/postpack.mjs"
80
+ "postpack": "node scripts/postpack.mjs",
81
+ "test:characterization": "NODE_OPTIONS=\"--experimental-vm-modules --max-old-space-size=8192\" jest --runInBand test/characterization"
95
82
  },
96
83
  "devDependencies": {
97
84
  "@jest/globals": "^30.2.0",
98
85
  "jest": "^30.2.0"
86
+ },
87
+ "imports": {
88
+ "#tunnel-core/*": "./vendor/tunnel-core/dist/*"
99
89
  }
100
90
  }
@@ -0,0 +1,23 @@
1
+ // Story 2.1 r3: `asyx name check <name> [--json]` — can <name>.tunnel.asyx.ai be claimed?
2
+ // Works without setup or sign-in. Exit 0 available, 3 not available, 2 usage, 1 could not check.
3
+ import { checkName, describeAnswer, normalizeLabel, EXIT } from '../lib/naming.js';
4
+
5
+ export default async function cmdName(argv, { fetchImpl = fetch, out = console.log, err = console.error } = {}) {
6
+ const json = argv.includes('--json');
7
+ const args = argv.filter((a) => a !== '--json');
8
+ if (args[0] !== 'check' || !args[1] || args.length > 2) {
9
+ err('Usage: asyx name check <name> [--json]');
10
+ return EXIT.USAGE;
11
+ }
12
+ const raw = args[1];
13
+ const label = normalizeLabel(raw) || String(raw).trim().toLowerCase();
14
+ try {
15
+ const answer = await checkName(label, { fetchImpl });
16
+ out(json ? JSON.stringify(answer) : describeAnswer(answer));
17
+ return answer.status === 'available' ? EXIT.OK : EXIT.NAME_UNAVAILABLE;
18
+ } catch (e) {
19
+ if (json) out(JSON.stringify({ label, status: 'error', error: e.code || 'network_error', message: e.message }));
20
+ else err(`Could not check the name: ${e.message}`);
21
+ return EXIT.FAILED;
22
+ }
23
+ }
@@ -0,0 +1,54 @@
1
+ // Story 12.1 (step 2b): the CLI's wording for coordinator refusals. The core (@asyx/tunnel-core)
2
+ // reports the coordinator's reason and data; this module prints exactly what the CLI has always
3
+ // printed and exits where it always has (code 1 for refusals that end the open; others keep running).
4
+ // Importing this module registers it with the core.
5
+ import { setOpenRejectReporter } from '#tunnel-core/mqtt/events/handlers.js';
6
+
7
+ export function printOpenReject({ code, reason, data }) {
8
+ const d = data || {};
9
+ switch (code) {
10
+ case 'invalid_secgroup': {
11
+ const slug = d.slug || d.secGroupSlug || 'unknown';
12
+ process.stderr.write(`QuickPass group "${slug}" not found. Re-run \`asyx tunnel\` with a valid group.\n`);
13
+ process.exit(1);
14
+ return;
15
+ }
16
+ case 'tcp_port_out_of_block': {
17
+ const requestedPort = d.requestedPort || d.requestedExternalPort || 'X';
18
+ const blockStart = d.blockStart || 'A';
19
+ const blockEnd = d.blockEnd || 'B';
20
+ process.stderr.write(`Requested external port ${requestedPort} is outside your assigned block ${blockStart}–${blockEnd}.\n`);
21
+ process.exit(1);
22
+ return;
23
+ }
24
+ case 'tcp_port_already_in_use': {
25
+ const requestedPort = d.requestedPort || d.requestedExternalPort || 'X';
26
+ process.stderr.write(`External port ${requestedPort} is already in use by another active tunnel.\n`);
27
+ process.exit(1);
28
+ return;
29
+ }
30
+ case 'tcp_port_block_exhausted_for_tenant':
31
+ case 'tcp_port_block_exhausted': {
32
+ const blockStart = d.blockStart || 'A';
33
+ const blockEnd = d.blockEnd || 'B';
34
+ process.stderr.write(`All 10 ports in your block ${blockStart}–${blockEnd} are currently in use.\n`);
35
+ process.exit(1);
36
+ return;
37
+ }
38
+ case 'tcp_port_capacity_exhausted':
39
+ process.stderr.write(`Relay TCP port capacity exhausted. Please retry later.\n`);
40
+ process.exit(1);
41
+ return;
42
+ case 'tenant_tcp_lease_limit_reached': {
43
+ const relayId = d.relayId || 'unknown';
44
+ process.stderr.write(`Tenant TCP lease limit reached on relay ${relayId}\n`);
45
+ process.exit(1);
46
+ return;
47
+ }
48
+ default:
49
+ // Not fatal: print and keep running (e.g. a refused renewal).
50
+ process.stdout.write(`❌ Connection rejected${reason ? ` (${reason})` : ''}\n`);
51
+ }
52
+ }
53
+
54
+ setOpenRejectReporter(printOpenReject);
@@ -4,10 +4,13 @@ import path from 'node:path';
4
4
  import os from 'node:os';
5
5
  import crypto from 'node:crypto';
6
6
  import { ensureKeyAndCsr } from '../lib/csr.js';
7
- import { loadOrCreateClientId, resetClientId } from '../lib/device.js';
7
+ import { loadOrCreateClientId } from '../lib/device.js';
8
+ import { parseSetupArgs, approvalUrl, checkName, describeAnswer, setupCode, EXIT } from '../lib/naming.js';
8
9
 
9
10
  const CONSOLE_URL = process.env.ASYX_CONSOLE_URL || 'https://www.asyx.ai/console/tunnel';
10
11
  const STS_URL = process.env.ASYX_STS_URL || 'https://www.asyx.ai/www/sts';
12
+ // A person has to open the link, maybe sign in, and press Approve (4.7): wait up to 10 minutes.
13
+ const APPROVAL_DEADLINE_MS = Number(process.env.ASYX_SETUP_TIMEOUT_MS || 10 * 60_000);
11
14
 
12
15
  function randHex(bytes = 16) {
13
16
  return crypto.randomBytes(bytes).toString('hex');
@@ -18,141 +21,134 @@ function isJsonResponse(res) {
18
21
  return ct.toLowerCase().includes('application/json');
19
22
  }
20
23
 
21
- export default async function cmdSetup(argv = process.argv.slice(2)) {
22
- let clientId = loadOrCreateClientId();
23
-
24
- // Check if there are existing certs that might belong to another user
25
- // On Windows, multiple users can share the same home directory structure,
26
- // so we automatically regenerate clientId if existing certs are found
27
- const certsDir = path.join(os.homedir(), '.asyx', 'certs', clientId);
28
- try {
29
- const manifestPath = path.join(certsDir, 'manifest.json');
30
- if (await fs.access(manifestPath).then(() => true).catch(() => false)) {
31
- // Existing certs found - regenerate clientId to avoid subdomain mismatch
32
- // This fixes the Windows multi-user issue where another user's clientId
33
- // would be reused, causing subdomain mismatch
34
- console.log(`⚠️ Found existing setup for clientId ${clientId}`);
35
- console.log(`🔄 Regenerating clientId to ensure correct subdomain assignment...\n`);
36
- resetClientId();
37
- clientId = loadOrCreateClientId();
38
- console.log(` New clientId: ${clientId}\n`);
24
+ /**
25
+ * `asyx setup [--hostname <name> | --random] [--json]` (Stories 2.1 r3, 4.7).
26
+ * Returns the exit code. The terminal never prompts: it prints the approval link, waits, and reports
27
+ * the approved hostname. With --json, stdout carries one JSON object per line and nothing else.
28
+ *
29
+ * Story 2.1 c6: the machine keeps its device id across setups (a new id only when it has none), so it
30
+ * keeps its hostname; the old certificate is retired by the server when the new one is issued.
31
+ */
32
+ export async function runSetup(argv = [], deps = {}) {
33
+ const {
34
+ fetchImpl = fetch,
35
+ openImpl = open,
36
+ sleep = (ms) => new Promise((r) => setTimeout(r, ms)),
37
+ now = () => Date.now(),
38
+ stdout = (s) => process.stdout.write(s + '\n'),
39
+ stderr = (s) => process.stderr.write(s + '\n'),
40
+ clientIdImpl = loadOrCreateClientId,
41
+ csrImpl = ensureKeyAndCsr,
42
+ writeFiles = writeCertificateFiles,
43
+ deadlineMs = APPROVAL_DEADLINE_MS,
44
+ } = deps;
45
+
46
+ const opts = parseSetupArgs(argv);
47
+ const say = (s) => (opts.json ? stderr(s) : stdout(s));
48
+ const emit = (o) => { if (opts.json) stdout(JSON.stringify(o)); };
49
+ const fail = (code, error, message) => {
50
+ if (opts.json) emit({ event: 'error', error, message });
51
+ else stderr(`❌ ${message}`);
52
+ return code;
53
+ };
54
+
55
+ if (opts.error) return fail(EXIT.USAGE, 'usage', `${opts.error}\nUsage: asyx setup [--hostname <name> | --random] [--json]`);
56
+
57
+ const clientId = clientIdImpl();
58
+ if (!/^cli_[A-F0-9]{12}$/.test(clientId)) return fail(EXIT.FAILED, 'invalid_client_id', 'Invalid clientId format (expected cli_[A-F0-9]{12})');
59
+
60
+ // An early answer for --hostname; the approval itself checks again, so a failed check is not fatal.
61
+ if (opts.hostname) {
62
+ try {
63
+ const answer = await checkName(opts.hostname, { fetchImpl });
64
+ if (answer.status !== 'available') {
65
+ if (opts.json) emit({ event: 'error', error: answer.status, hostname: answer.hostname, suggestions: answer.suggestions || [] });
66
+ else stderr(`❌ ${describeAnswer(answer)}`);
67
+ return EXIT.NAME_UNAVAILABLE;
68
+ }
69
+ } catch (e) {
70
+ say(`⚠️ Could not check the name first (${e.message}); the approval page will check it.`);
39
71
  }
40
- } catch (e) {
41
- // No existing certs, proceed normally
42
- }
43
-
44
- if (!/^cli_[A-F0-9]{12}$/.test(clientId)) {
45
- console.error('Invalid clientId format (expected cli_[A-F0-9]{12})');
46
- process.exit(2);
47
72
  }
48
73
 
49
- // 1) Generate ticket and claim URL
74
+ // 1) Approval link
50
75
  const ticket = randHex(16);
51
- const claimUrl = `${CONSOLE_URL}?clientId=${encodeURIComponent(clientId)}&ticket=${encodeURIComponent(ticket)}`;
52
-
53
- console.log('🌐 Opening browser…');
54
- await open(claimUrl);
55
- console.log('⏳ Waiting for certificate issuance via www.asyx.ai …');
56
-
57
- // 2) Generate CSR (key stays local)
58
- const { csrPem } = await ensureKeyAndCsr(clientId);
59
-
60
- // 3) Poll /www/sts until issued (bounded, resilient)
61
- const pollStart = Date.now();
62
- const deadlineMs = 60_000; // 60s total budget
76
+ const url = approvalUrl(CONSOLE_URL, { clientId, ticket, hostname: opts.hostname, random: opts.random });
77
+ const code = setupCode(ticket);
78
+ emit({ event: 'approval_required', url, code, clientId, expiresInSeconds: Math.round(deadlineMs / 1000) });
79
+ say('Approve this device in your browser:');
80
+ say(` ${url}`);
81
+ say(`The page will ask for this code: ${code}`);
82
+ say('Only approve it if you started this setup yourself.');
83
+ try { await openImpl(url); } catch { /* no browser here: the link above is enough */ }
84
+ say('⏳ Waiting for approval…');
85
+
86
+ // 2) Key and CSR (the key stays on this machine)
87
+ const { csrPem } = await csrImpl(clientId);
88
+
89
+ // 3) Poll until approved
90
+ const start = now();
63
91
  let attempt = 0;
64
92
  let issued = null;
65
-
66
- while (Date.now() - pollStart < deadlineMs) {
93
+ while (now() - start < deadlineMs) {
67
94
  attempt++;
95
+ const backoff = Math.min(1000 + attempt * 250, 2000);
68
96
  let res;
69
97
  try {
70
- res = await fetch(STS_URL, {
98
+ res = await fetchImpl(STS_URL, {
71
99
  method: 'POST',
72
- headers: {
73
- 'content-type': 'application/json',
74
- 'accept': 'application/json',
75
- 'cache-control': 'no-store',
76
- },
100
+ headers: { 'content-type': 'application/json', accept: 'application/json', 'cache-control': 'no-store' },
77
101
  body: JSON.stringify({ ticket, clientId, csrPem }),
78
102
  });
79
- } catch (e) {
80
- // Network hiccup; short backoff and retry
81
- await new Promise(r => setTimeout(r, Math.min(1000 + attempt * 250, 2000)));
82
- continue;
83
- }
84
-
85
- // 202: not ready yet — backoff and retry
86
- if (res.status === 202) {
87
- await new Promise(r => setTimeout(r, Math.min(1000 + attempt * 250, 2000)));
103
+ } catch {
104
+ await sleep(backoff);
88
105
  continue;
89
106
  }
90
-
91
- // Non-JSON (e.g., CloudFront fallback HTML). Ignore and keep polling within budget.
92
- if (res.ok && !isJsonResponse(res)) {
93
- await res.text().catch(() => undefined); // drain
94
- await new Promise(r => setTimeout(r, Math.min(1000 + attempt * 250, 2000)));
107
+ // 202: not approved yet (Defect 11.33). A non-JSON 200 is a CloudFront page: keep waiting.
108
+ if (res.status === 202 || (res.ok && !isJsonResponse(res))) {
109
+ await res.text().catch(() => undefined);
110
+ await sleep(backoff);
95
111
  continue;
96
112
  }
97
-
98
- // Error codes:
99
113
  if (!res.ok) {
100
- // Map specific error codes to user-friendly messages
101
- if (res.status === 401 || res.status === 403) {
102
- console.error('❌ Please sign in first at https://www.asyx.ai and run `asyx setup` again.');
103
- process.exit(1);
104
- }
105
- if (res.status === 404) {
106
- console.error('❌ Setup timed out. Run `asyx setup` again to start over.');
107
- process.exit(1);
108
- }
109
- if (res.status === 409) {
110
- console.error('❌ The certificate request didn\'t match this machine\'s identity. Please re-run asyx setup on the same machine that opened the Console.');
111
- process.exit(1);
112
- }
113
- // Generic error
114
+ if (res.status === 401 || res.status === 403) return fail(EXIT.FAILED, 'unauthorized', 'Please sign in at https://www.asyx.ai and run `asyx setup` again.');
115
+ if (res.status === 404 || res.status === 410) return fail(EXIT.FAILED, 'expired', 'The approval expired. Run `asyx setup` again.');
116
+ if (res.status === 409) return fail(EXIT.FAILED, 'csr_mismatch', "The certificate request didn't match this machine's identity. Run `asyx setup` again on the machine that opened the link.");
114
117
  let payload = '';
115
118
  try { payload = await res.text(); } catch {}
116
- console.error(`❌ Setup failed (HTTP ${res.status}) — ${payload}`);
117
- console.error('❌ Please sign in (or refresh) and run `asyx setup` again.');
118
- process.exit(1);
119
+ return fail(EXIT.FAILED, 'setup_failed', `Setup failed (HTTP ${res.status}) ${payload}`.trim());
119
120
  }
120
-
121
- // Success JSON
122
121
  try {
123
122
  issued = await res.json();
124
123
  break;
125
124
  } catch {
126
- // Malformed JSON — treat as transient and keep polling
127
- await new Promise(r => setTimeout(r, Math.min(1000 + attempt * 250, 2000)));
128
- continue;
125
+ await sleep(backoff);
129
126
  }
130
127
  }
128
+ if (!issued) return fail(EXIT.FAILED, 'timeout', 'Nobody approved the device in time. Run `asyx setup` again.');
129
+
130
+ // 4) Files
131
+ await writeFiles(clientId, issued);
132
+ const hostname = issued.identity?.hostname || null;
133
+ emit({ event: 'enrolled', clientId, hostname });
134
+ say('✅ Certificate issued and stored.');
135
+ if (hostname) say(` Hostname: ${hostname}`);
136
+ return EXIT.OK;
137
+ }
131
138
 
132
- if (!issued) {
133
- console.error('⏳ Setup timed out. Please sign in and run `asyx setup` again.');
134
- process.exit(1);
135
- }
136
-
137
- // 4) Write files
139
+ async function writeCertificateFiles(clientId, issued) {
138
140
  const dir = path.join(os.homedir(), '.asyx', 'certs', clientId);
139
141
  await fs.mkdir(dir, { recursive: true, mode: 0o700 });
140
142
  await fs.writeFile(path.join(dir, 'AmazonRootCA1.pem'), issued.caPem, { mode: 0o644 });
141
143
  await fs.writeFile(path.join(dir, 'device.pem.crt'), issued.certPem, { mode: 0o600 });
142
144
  await fs.writeFile(
143
145
  path.join(dir, 'manifest.json'),
144
- JSON.stringify(
145
- {
146
- clientId,
147
- endpoint: issued.endpoint,
148
- region: issued.region,
149
- issuedAt: Date.now(),
150
- },
151
- null,
152
- 2,
153
- ),
146
+ JSON.stringify({ clientId, endpoint: issued.endpoint, region: issued.region, issuedAt: Date.now(), hostname: issued.identity?.hostname || undefined }, null, 2),
154
147
  { mode: 0o600 },
155
148
  );
149
+ }
156
150
 
157
- console.log('✅ Certificate issued and stored.');
151
+ export default async function cmdSetup(argv = process.argv.slice(2)) {
152
+ const code = await runSetup(argv);
153
+ process.exit(code);
158
154
  }