asyx 0.10.0 → 0.11.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.
Files changed (93) hide show
  1. package/AGENTS.md +42 -0
  2. package/bin/asyx.js +1 -1
  3. package/package.json +6 -3
  4. package/src/commands/account.js +80 -71
  5. package/src/commands/app.js +317 -151
  6. package/src/commands/in-use-messages.js +47 -48
  7. package/src/commands/mqtt-broker.js +36 -49
  8. package/src/commands/mqtt.js +111 -149
  9. package/src/commands/name.js +24 -22
  10. package/src/commands/reject-messages.js +123 -123
  11. package/src/commands/setup.js +107 -131
  12. package/src/commands/sts.js +45 -61
  13. package/src/commands/tunnel.js +853 -931
  14. package/src/commands/validate-target-host.js +36 -59
  15. package/src/lib/aws-iot-config.js +30 -0
  16. package/src/lib/certs.js +15 -18
  17. package/src/lib/csr.js +107 -182
  18. package/src/lib/device.js +26 -37
  19. package/src/lib/ids.js +1 -2
  20. package/src/lib/naming.js +74 -68
  21. package/src/lib/pairing.js +10 -11
  22. package/src/lib/shared-transport.js +5 -9
  23. package/src/main.js +63 -53
  24. package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneClient.js +25 -287
  25. package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneTransport.js +0 -72
  26. package/vendor/tunnel-core/dist/control-plane/session.js +0 -20
  27. package/vendor/tunnel-core/dist/errors.js +0 -19
  28. package/vendor/tunnel-core/dist/flows/account.js +1 -6
  29. package/vendor/tunnel-core/dist/flows/goodbye.js +0 -4
  30. package/vendor/tunnel-core/dist/flows/http.js +24 -112
  31. package/vendor/tunnel-core/dist/flows/identity.js +11 -10
  32. package/vendor/tunnel-core/dist/flows/in-use.js +0 -6
  33. package/vendor/tunnel-core/dist/flows/reopen.js +0 -4
  34. package/vendor/tunnel-core/dist/flows/tcp.js +18 -84
  35. package/vendor/tunnel-core/dist/flows/udp.js +15 -52
  36. package/vendor/tunnel-core/dist/lib/fingerprint.js +38 -42
  37. package/vendor/tunnel-core/dist/lib/jwt-verifier.js +14 -67
  38. package/vendor/tunnel-core/dist/lib/logger.js +1 -9
  39. package/vendor/tunnel-core/dist/lib/refresh-helpers.js +1 -22
  40. package/vendor/tunnel-core/dist/lifecycle.js +1 -8
  41. package/vendor/tunnel-core/dist/mqtt/awaiter-map.js +1 -53
  42. package/vendor/tunnel-core/dist/mqtt/events/handlers.js +10 -64
  43. package/vendor/tunnel-core/dist/mqtt/events/index.js +3 -36
  44. package/vendor/tunnel-core/dist/mqtt/events/schemas.js +0 -1
  45. package/vendor/tunnel-core/dist/mqtt/ingress.js +0 -60
  46. package/vendor/tunnel-core/dist/state/assignment.js +6 -122
  47. package/vendor/tunnel-core/dist/state/instance-registry.js +0 -63
  48. package/vendor/tunnel-core/dist/tcp-v1/framing.js +2 -64
  49. package/vendor/tunnel-core/dist/tunnel/http-tunnel.js +64 -331
  50. package/vendor/tunnel-core/dist/tunnel/httpws-constants.js +5 -14
  51. package/vendor/tunnel-core/dist/tunnel/reconnect.js +10 -50
  52. package/vendor/tunnel-core/dist/tunnel/request-sink.js +0 -16
  53. package/vendor/tunnel-core/dist/tunnel/tcp-tunnel.js +32 -195
  54. package/vendor/tunnel-core/dist/tunnel/udp-tunnel.js +28 -153
  55. package/vendor/tunnel-core/dist/tunnel/ws-control.js +4 -39
  56. package/vendor/tunnel-core/dist/types.js +0 -2
  57. package/vendor/tunnel-core/dist/udp-v1/framing.js +2 -64
  58. package/vendor/tunnel-core/package.json +0 -25
  59. package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneClient.d.ts +0 -273
  60. package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneTransport.d.ts +0 -79
  61. package/vendor/tunnel-core/dist/control-plane/session.d.ts +0 -55
  62. package/vendor/tunnel-core/dist/errors.d.ts +0 -49
  63. package/vendor/tunnel-core/dist/flows/account.d.ts +0 -24
  64. package/vendor/tunnel-core/dist/flows/goodbye.d.ts +0 -10
  65. package/vendor/tunnel-core/dist/flows/http.d.ts +0 -61
  66. package/vendor/tunnel-core/dist/flows/identity.d.ts +0 -23
  67. package/vendor/tunnel-core/dist/flows/in-use.d.ts +0 -27
  68. package/vendor/tunnel-core/dist/flows/reopen.d.ts +0 -9
  69. package/vendor/tunnel-core/dist/flows/tcp.d.ts +0 -85
  70. package/vendor/tunnel-core/dist/flows/udp.d.ts +0 -52
  71. package/vendor/tunnel-core/dist/lib/adapt-logger.d.ts +0 -2
  72. package/vendor/tunnel-core/dist/lib/fingerprint.d.ts +0 -145
  73. package/vendor/tunnel-core/dist/lib/jwt-verifier.d.ts +0 -27
  74. package/vendor/tunnel-core/dist/lib/logger.d.ts +0 -9
  75. package/vendor/tunnel-core/dist/lib/refresh-helpers.d.ts +0 -16
  76. package/vendor/tunnel-core/dist/lifecycle.d.ts +0 -24
  77. package/vendor/tunnel-core/dist/mqtt/awaiter-map.d.ts +0 -56
  78. package/vendor/tunnel-core/dist/mqtt/events/handlers.d.ts +0 -60
  79. package/vendor/tunnel-core/dist/mqtt/events/index.d.ts +0 -1
  80. package/vendor/tunnel-core/dist/mqtt/events/schemas.d.ts +0 -498
  81. package/vendor/tunnel-core/dist/mqtt/ingress.d.ts +0 -63
  82. package/vendor/tunnel-core/dist/state/assignment.d.ts +0 -136
  83. package/vendor/tunnel-core/dist/state/instance-registry.d.ts +0 -88
  84. package/vendor/tunnel-core/dist/tcp-v1/framing.d.ts +0 -43
  85. package/vendor/tunnel-core/dist/tunnel/http-tunnel.d.ts +0 -140
  86. package/vendor/tunnel-core/dist/tunnel/httpws-constants.d.ts +0 -13
  87. package/vendor/tunnel-core/dist/tunnel/reconnect.d.ts +0 -76
  88. package/vendor/tunnel-core/dist/tunnel/request-sink.d.ts +0 -40
  89. package/vendor/tunnel-core/dist/tunnel/tcp-tunnel.d.ts +0 -92
  90. package/vendor/tunnel-core/dist/tunnel/udp-tunnel.d.ts +0 -93
  91. package/vendor/tunnel-core/dist/tunnel/ws-control.d.ts +0 -22
  92. package/vendor/tunnel-core/dist/types.d.ts +0 -24
  93. package/vendor/tunnel-core/dist/udp-v1/framing.d.ts +0 -41
@@ -1,7 +1,3 @@
1
- // CP-1: Control-plane connect (TLS 8883) with bounded reconnect & graceful shutdown.
2
- // CP-2: Session negotiation and registration with coordinator.
3
- // CP-3F: Event envelope & dispatcher for control-plane responses.
4
- // CP-3G: Single ingress with awaiters + dispatcher (fix multiple onMessage handlers).
5
1
  import { constants as fsConstants } from 'node:fs';
6
2
  import { access } from 'node:fs/promises';
7
3
  import { join } from 'node:path';
@@ -10,30 +6,35 @@ import logger from "#tunnel-core/lib/logger.js";
10
6
  import { dispatch as dispatchEvt } from "#tunnel-core/mqtt/events/index.js";
11
7
  import { MessageIngress } from "#tunnel-core/mqtt/ingress.js";
12
8
  import { getDeviceJsonPath } from "../lib/device.js";
13
- import './reject-messages.js'; // Story 12.1: the CLI's wording for coordinator refusals
14
- import { exitInUse, printWaiting, tunnelOutput } from './in-use-messages.js'; // Story 1.9
9
+ import './reject-messages.js';
10
+ async function explainAppStop(error) {
11
+ const appId = process.env.ASYX_APP_ID;
12
+ const why = error?.code === 'control_plane_connect_failed' || /identity_inactive/.test(`${error?.code} ${error?.details?.reason} ${error?.message}`) || error?.name === 'RefusedError';
13
+ if (!appId || !why)
14
+ return;
15
+ try {
16
+ const { explainAppFailure } = await import('./app.js');
17
+ if (await explainAppFailure(appId))
18
+ process.exit(1);
19
+ }
20
+ catch { }
21
+ }
22
+ import { exitInUse, printWaiting, tunnelOutput } from './in-use-messages.js';
15
23
  import { createControlPlaneSession } from '#tunnel-core/control-plane/session.js';
16
24
  import { publishRefreshRequestWithErrorHandling, jwtExpOf } from '#tunnel-core/lib/refresh-helpers.js';
17
- // Re-exported for existing tests that import it from here.
18
25
  export { publishRefreshRequestWithErrorHandling };
19
-
20
-
21
26
  export default async function tunnel(args = []) {
22
- // Device credential guard - use same path resolution as device.js
23
- // (help works before enrollment)
24
- const deviceJsonPath = getDeviceJsonPath();
25
- const wantsHelp = args.includes('--help') || args.includes('-h');
26
- if (!wantsHelp) await access(deviceJsonPath, fsConstants.F_OK).catch(() => {
27
- console.error('This machine is not set up yet. Run "asyx setup" first (it opens your browser once), then run this command again.');
28
- process.exit(2);
29
- });
30
-
31
- // Parse arguments using minimist-like approach
32
- const parsed = parseArgs(args);
33
-
34
- if (parsed.help || args.length === 0) {
35
- logger.info("cli.help", {});
36
- process.stdout.write(`Usage:
27
+ const deviceJsonPath = getDeviceJsonPath();
28
+ const wantsHelp = args.includes('--help') || args.includes('-h');
29
+ if (!wantsHelp)
30
+ await access(deviceJsonPath, fsConstants.F_OK).catch(() => {
31
+ console.error('This machine is not set up yet. Run "asyx setup" first (it opens your browser once), then run this command again.');
32
+ process.exit(2);
33
+ });
34
+ const parsed = parseArgs(args);
35
+ if (parsed.help || args.length === 0) {
36
+ logger.info("cli.help", {});
37
+ process.stdout.write(`Usage:
37
38
  asyx tunnel --http --port <n> --to <hostname> [--secgroup <slug>]
38
39
  HTTP tunnel: a public HTTPS URL for a web app on localhost:<n>.
39
40
  --secgroup <slug> QuickPass security group; only its members can open the URL
@@ -66,946 +67,867 @@ taken over by --replace), so a service manager can be told not to restart on it.
66
67
  Tunnels forward to 127.0.0.1 only and reconnect on their own after a network or
67
68
  server interruption. Press Ctrl+C to stop. Docs: https://www.asyx.ai/docs
68
69
  `);
69
- return;
70
- }
71
-
72
- // Story 4.10 r3: every open and refresh request carries the target (see tunnel-core requestFields).
73
- if (parsed.to) process.env.ASYX_TUNNEL_TO = parsed.to;
74
- // Story 1.9: --replace takes over a live tunnel of this kind for the address; --wait keeps trying.
75
- if (parsed.replace) process.env.ASYX_TUNNEL_REPLACE = '1';
76
- tunnelOutput.json = parsed.json === true;
77
- tunnelOutput.wait = parsed.wait === true;
78
- tunnelOutput.rerun = parsed.replace ? null : `asyx ${['tunnel', ...args.filter((a) => a !== '--wait' && a !== '--json')].join(' ')}`;
79
-
80
- // Handle legacy connect command
81
- if (args[0] === "connect") return connect();
82
-
83
- // E3-S8: Handle --minecraft flag (expands to --tcp --port 25565 --kind minecraft)
84
- if (parsed.minecraft) {
85
- parsed.tcp = true;
86
- if (!parsed.port) {
87
- parsed.port = 25565; // Default Minecraft port
88
- }
89
- parsed.kind = 'minecraft';
90
- }
91
-
92
- // Validation: Mutual exclusion check MUST happen before dispatch to handlers
93
- if (parsed.tcp && parsed.http) {
94
- logger.error("cli.args.invalid", { reason: "--tcp and --http are mutually exclusive" });
95
- process.stderr.write("Error: --tcp and --http are mutually exclusive\n");
96
- process.exit(2);
97
- }
98
-
99
- if (parsed.tcp && parsed.udp) {
100
- logger.error("cli.args.invalid", { reason: "--tcp and --udp are mutually exclusive" });
101
- process.stderr.write("Error: --tcp and --udp are mutually exclusive\n");
102
- process.exit(2);
103
- }
104
-
105
- if (parsed.udp && parsed.http) {
106
- logger.error("cli.args.invalid", { reason: "--udp and --http are mutually exclusive" });
107
- process.stderr.write("Error: --udp and --http are mutually exclusive\n");
108
- process.exit(2);
109
- }
110
-
111
- // Validation: Fail fast on unsupported combinations
112
- if (parsed.http && !parsed.port) {
113
- logger.error("cli.args.invalid", { reason: "--http requires --port" });
114
- process.exit(2);
115
- }
116
-
117
- if (parsed.tcp && !parsed.port) {
118
- logger.error("cli.args.invalid", { reason: "--tcp requires --port" });
119
- process.stderr.write("Error: --tcp requires --port\n");
120
- process.exit(2);
121
- }
122
-
123
- if (parsed.udp && !parsed.port) {
124
- logger.error("cli.args.invalid", { reason: "--udp requires --port" });
125
- process.stderr.write("Error: --udp requires --port\n");
126
- process.exit(2);
127
- }
128
-
129
- if (parsed.port && !parsed.http && !parsed.tcp && !parsed.udp) {
130
- logger.error("cli.args.invalid", { reason: "--port requires --http, --tcp, or --udp" });
131
- process.stderr.write("Error: --port requires --http, --tcp, or --udp\n");
70
+ return;
71
+ }
72
+ if (parsed.to)
73
+ process.env.ASYX_TUNNEL_TO = parsed.to;
74
+ if (parsed.replace)
75
+ process.env.ASYX_TUNNEL_REPLACE = '1';
76
+ tunnelOutput.json = parsed.json === true;
77
+ tunnelOutput.wait = parsed.wait === true;
78
+ tunnelOutput.rerun = parsed.replace ? null : `asyx ${['tunnel', ...args.filter((a) => a !== '--wait' && a !== '--json')].join(' ')}`;
79
+ if (args[0] === "connect")
80
+ return connect();
81
+ if (parsed.minecraft) {
82
+ parsed.tcp = true;
83
+ if (!parsed.port) {
84
+ parsed.port = 25565;
85
+ }
86
+ parsed.kind = 'minecraft';
87
+ }
88
+ if (parsed.tcp && parsed.http) {
89
+ logger.error("cli.args.invalid", { reason: "--tcp and --http are mutually exclusive" });
90
+ process.stderr.write("Error: --tcp and --http are mutually exclusive\n");
91
+ process.exit(2);
92
+ }
93
+ if (parsed.tcp && parsed.udp) {
94
+ logger.error("cli.args.invalid", { reason: "--tcp and --udp are mutually exclusive" });
95
+ process.stderr.write("Error: --tcp and --udp are mutually exclusive\n");
96
+ process.exit(2);
97
+ }
98
+ if (parsed.udp && parsed.http) {
99
+ logger.error("cli.args.invalid", { reason: "--udp and --http are mutually exclusive" });
100
+ process.stderr.write("Error: --udp and --http are mutually exclusive\n");
101
+ process.exit(2);
102
+ }
103
+ if (parsed.http && !parsed.port) {
104
+ logger.error("cli.args.invalid", { reason: "--http requires --port" });
105
+ process.exit(2);
106
+ }
107
+ if (parsed.tcp && !parsed.port) {
108
+ logger.error("cli.args.invalid", { reason: "--tcp requires --port" });
109
+ process.stderr.write("Error: --tcp requires --port\n");
110
+ process.exit(2);
111
+ }
112
+ if (parsed.udp && !parsed.port) {
113
+ logger.error("cli.args.invalid", { reason: "--udp requires --port" });
114
+ process.stderr.write("Error: --udp requires --port\n");
115
+ process.exit(2);
116
+ }
117
+ if (parsed.port && !parsed.http && !parsed.tcp && !parsed.udp) {
118
+ logger.error("cli.args.invalid", { reason: "--port requires --http, --tcp, or --udp" });
119
+ process.stderr.write("Error: --port requires --http, --tcp, or --udp\n");
120
+ process.exit(2);
121
+ }
122
+ if (parsed.http && parsed.port) {
123
+ if (parsed.secGroupSlug) {
124
+ logger.info("qp.requested", { group: parsed.secGroupSlug });
125
+ }
126
+ return httpTunnel(parsed.port, parsed.secGroupSlug);
127
+ }
128
+ if (parsed.tcp && parsed.port) {
129
+ const target = buildTcpTarget(parsed.port);
130
+ if (!isLocalhostTarget(target)) {
131
+ logger.error("cli.args.invalid", {
132
+ reason: `TCP tunnels in v4.1 can only target localhost (127.0.0.1 / ::1 / localhost). Got: ${target}`
133
+ });
134
+ process.stderr.write(`Error: TCP tunnels in v4.1 can only target localhost (127.0.0.1 / ::1 / localhost).\n`);
135
+ process.exit(2);
136
+ }
137
+ return tcpTunnel(parsed.port, parsed.serviceName, parsed.kind, parsed.externalPort);
138
+ }
139
+ if (parsed.udp && parsed.port) {
140
+ const targetHost = parsed.targetHost || '127.0.0.1';
141
+ const targetPort = parsed.port;
142
+ if (targetPort < 1 || targetPort > 65535) {
143
+ logger.error("cli.args.invalid", {
144
+ reason: `Invalid targetPort: ${targetPort} (must be 1-65535)`
145
+ });
146
+ process.stderr.write(`Error: --port must be between 1 and 65535. Got: ${targetPort}\n`);
147
+ process.exit(2);
148
+ }
149
+ const { validateTargetHost } = await import('./validate-target-host.js');
150
+ let validationResult;
151
+ try {
152
+ validationResult = await validateTargetHost(targetHost);
153
+ }
154
+ catch (error) {
155
+ logger.error("cli.args.invalid", {
156
+ reason: `Failed to resolve --target-host: ${error.message}`
157
+ });
158
+ process.stderr.write(`Error: Failed to resolve --target-host "${targetHost}": ${error.message}\n`);
159
+ process.exit(2);
160
+ }
161
+ if (!validationResult.isLoopback) {
162
+ logger.error("cli.args.invalid", {
163
+ reason: `UDP tunnels in v4.1 can only target localhost. Got: ${targetHost} (resolved to: ${validationResult.resolvedIPs.join(', ')})`
164
+ });
165
+ process.stderr.write(`Error: --target-host must resolve to loopback addresses only (127.0.0.1 / ::1).\n`);
166
+ process.stderr.write(` Target: ${targetHost}\n`);
167
+ process.stderr.write(` Resolved IPs: ${validationResult.resolvedIPs.join(', ')}\n`);
168
+ process.exit(2);
169
+ }
170
+ return udpTunnel(targetPort, parsed.externalPort, targetHost);
171
+ }
172
+ logger.error("cli.args.unknown", { args: args.join(' ') });
173
+ process.stderr.write(`Unknown subcommand or invalid flags: ${args.join(' ')}\n`);
132
174
  process.exit(2);
133
- }
134
-
135
- // Handle new --http --port flags
136
- if (parsed.http && parsed.port) {
137
- // QPA-CLI-11: Track QuickPass request for vault UX messaging
138
- if (parsed.secGroupSlug) {
139
- logger.info("qp.requested", { group: parsed.secGroupSlug });
140
- }
141
- return httpTunnel(parsed.port, parsed.secGroupSlug);
142
- }
143
-
144
- // Handle new --tcp --port flags
145
- if (parsed.tcp && parsed.port) {
146
- // Validate target is localhost-only (defaults to 127.0.0.1)
147
- const target = buildTcpTarget(parsed.port);
148
- if (!isLocalhostTarget(target)) {
149
- logger.error("cli.args.invalid", {
150
- reason: `TCP tunnels in v4.1 can only target localhost (127.0.0.1 / ::1 / localhost). Got: ${target}`
151
- });
152
- process.stderr.write(`Error: TCP tunnels in v4.1 can only target localhost (127.0.0.1 / ::1 / localhost).\n`);
153
- process.exit(2);
154
- }
155
- return tcpTunnel(parsed.port, parsed.serviceName, parsed.kind, parsed.externalPort);
156
- }
157
-
158
- // Handle new --udp --port flags
159
- if (parsed.udp && parsed.port) {
160
- // UDP-S13: --target-host defaults to 127.0.0.1
161
- const targetHost = parsed.targetHost || '127.0.0.1';
162
- const targetPort = parsed.port;
163
-
164
- // UDP-S13: Validate targetPort (must be 1-65535)
165
- if (targetPort < 1 || targetPort > 65535) {
166
- logger.error("cli.args.invalid", {
167
- reason: `Invalid targetPort: ${targetPort} (must be 1-65535)`
168
- });
169
- process.stderr.write(`Error: --port must be between 1 and 65535. Got: ${targetPort}\n`);
170
- process.exit(2);
171
- }
172
-
173
- // UDP-S13: Validate target-host is loopback-only (resolve DNS if needed)
174
- const { validateTargetHost } = await import('./validate-target-host.js');
175
- let validationResult;
176
- try {
177
- validationResult = await validateTargetHost(targetHost);
178
- } catch (error) {
179
- logger.error("cli.args.invalid", {
180
- reason: `Failed to resolve --target-host: ${error.message}`
181
- });
182
- process.stderr.write(`Error: Failed to resolve --target-host "${targetHost}": ${error.message}\n`);
183
- process.exit(2);
184
- }
185
-
186
- if (!validationResult.isLoopback) {
187
- logger.error("cli.args.invalid", {
188
- reason: `UDP tunnels in v4.1 can only target localhost. Got: ${targetHost} (resolved to: ${validationResult.resolvedIPs.join(', ')})`
189
- });
190
- process.stderr.write(`Error: --target-host must resolve to loopback addresses only (127.0.0.1 / ::1).\n`);
191
- process.stderr.write(` Target: ${targetHost}\n`);
192
- process.stderr.write(` Resolved IPs: ${validationResult.resolvedIPs.join(', ')}\n`);
193
- process.exit(2);
194
- }
195
-
196
- return udpTunnel(targetPort, parsed.externalPort, targetHost);
197
- }
198
-
199
- logger.error("cli.args.unknown", { args: args.join(' ') });
200
- process.stderr.write(`Unknown subcommand or invalid flags: ${args.join(' ')}\n`);
201
- process.exit(2);
202
175
  }
203
-
204
- // UDP-S16: Helper to find closest matching flag for "did you mean" suggestions
205
176
  function findClosestFlag(unknownFlag, knownFlags) {
206
- // Normalize: convert underscores to dashes and lowercase
207
- const normalize = (str) => str.replace(/_/g, '-').toLowerCase();
208
- const normalizedUnknown = normalize(unknownFlag);
209
-
210
- // Find exact match after normalization
211
- for (const known of knownFlags) {
212
- if (normalize(known) === normalizedUnknown) {
213
- return known;
214
- }
215
- }
216
-
217
- // Find close match (contains normalized unknown or vice versa)
218
- let closest = null;
219
- for (const known of knownFlags) {
220
- const normalizedKnown = normalize(known);
221
- if (normalizedKnown.includes(normalizedUnknown) || normalizedUnknown.includes(normalizedKnown)) {
222
- if (!closest || Math.abs(normalizedKnown.length - normalizedUnknown.length) < Math.abs(normalize(closest).length - normalizedUnknown.length)) {
223
- closest = known;
224
- }
225
- }
226
- }
227
-
228
- return closest;
177
+ const normalize = (str) => str.replace(/_/g, '-').toLowerCase();
178
+ const normalizedUnknown = normalize(unknownFlag);
179
+ for (const known of knownFlags) {
180
+ if (normalize(known) === normalizedUnknown) {
181
+ return known;
182
+ }
183
+ }
184
+ let closest = null;
185
+ for (const known of knownFlags) {
186
+ const normalizedKnown = normalize(known);
187
+ if (normalizedKnown.includes(normalizedUnknown) || normalizedUnknown.includes(normalizedKnown)) {
188
+ if (!closest || Math.abs(normalizedKnown.length - normalizedUnknown.length) < Math.abs(normalize(closest).length - normalizedUnknown.length)) {
189
+ closest = known;
190
+ }
191
+ }
192
+ }
193
+ return closest;
229
194
  }
230
-
231
- // UDP-S16: List of known flags for tunnel command
232
195
  const KNOWN_TUNNEL_FLAGS = [
233
- '--http',
234
- '--tcp',
235
- '--udp',
236
- '--minecraft',
237
- '--port',
238
- '--name',
239
- '--secgroup',
240
- '--to',
241
- '--replace',
242
- '--wait',
243
- '--json',
244
- '--target-host',
245
- '--external-port',
246
- '--ext-port',
247
- '--help',
248
- '-h'
196
+ '--http',
197
+ '--tcp',
198
+ '--udp',
199
+ '--minecraft',
200
+ '--port',
201
+ '--name',
202
+ '--secgroup',
203
+ '--to',
204
+ '--replace',
205
+ '--wait',
206
+ '--json',
207
+ '--target-host',
208
+ '--external-port',
209
+ '--ext-port',
210
+ '--help',
211
+ '-h'
249
212
  ];
250
-
251
- // Simple argument parser (minimist-like)
252
- // UDP-S16: Enhanced with unknown flag detection
253
213
  function parseArgs(args) {
254
- const parsed = {};
255
- const consumed = new Set(); // Track consumed argument indices
256
-
257
- for (let i = 0; i < args.length; i++) {
258
- if (consumed.has(i)) continue; // Skip already consumed arguments
259
-
260
- const arg = args[i];
261
- if (arg === '--http') {
262
- parsed.http = true;
263
- consumed.add(i);
264
- } else if (arg === '--tcp') {
265
- parsed.tcp = true;
266
- consumed.add(i);
267
- } else if (arg === '--udp') {
268
- parsed.udp = true;
269
- consumed.add(i);
270
- } else if (arg === '--minecraft') {
271
- parsed.minecraft = true;
272
- consumed.add(i);
273
- } else if (arg === '--port') {
274
- if (i + 1 < args.length) {
275
- const port = parseInt(args[i + 1], 10);
276
- if (isNaN(port) || port < 1 || port > 65535) {
277
- logger.error("cli.args.port_invalid", { value: args[i + 1] });
278
- process.stderr.write(`Error: Invalid port number: ${args[i + 1]}\n`);
279
- process.exit(2);
280
- }
281
- parsed.port = port;
282
- consumed.add(i);
283
- consumed.add(i + 1);
284
- i++; // Skip next argument as it's the port value
285
- } else {
286
- logger.error("cli.args.port_missing", {});
287
- process.stderr.write("Error: --port requires a port number\n");
288
- process.exit(2);
289
- }
290
- } else if (arg === '--name') {
291
- // Optional service name for TCP mode
292
- if (i + 1 < args.length) {
293
- parsed.serviceName = args[i + 1];
294
- consumed.add(i);
295
- consumed.add(i + 1);
296
- i++; // Skip next argument as it's the service name value
297
- } else {
298
- logger.error("cli.args.name_missing", {});
299
- process.stderr.write("Error: --name requires a service name\n");
300
- process.exit(2);
301
- }
302
- } else if (arg === '--replace' || arg === '--wait' || arg === '--json') {
303
- // Story 1.9: take over a live tunnel of this kind / keep trying while the address is in use / JSON errors
304
- parsed[arg.slice(2)] = true;
305
- consumed.add(i);
306
- } else if (arg === '--to') {
307
- // Story 4.10 r3: the address this tunnel serves (must be this computer's address).
308
- const v = args[i + 1];
309
- const host = v ? String(v).trim().toLowerCase().replace(/^[a-z]+:\/\//, '').replace(/[/?#].*$/, '').replace(/\.$/, '') : '';
310
- if (!host || !/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/.test(host)) {
311
- logger.error("cli.args.to_invalid", {});
312
- process.stderr.write("Error: --to needs a hostname, for example --to orders-api.tunnel.asyx.ai\n");
313
- process.exit(2);
314
- }
315
- parsed.to = host;
316
- consumed.add(i);
317
- consumed.add(i + 1);
318
- i++;
319
- } else if (arg === '--secgroup') {
320
- // QPA-04: Parse --secgroup flag
321
- if (i + 1 < args.length) {
322
- parsed.secGroupSlug = args[i + 1];
323
- consumed.add(i);
324
- consumed.add(i + 1);
325
- i++; // Skip next argument as it's the slug value
326
- } else {
327
- logger.error("cli.args.secgroup_missing", {});
328
- process.stderr.write("Error: --secgroup requires a slug\n");
329
- process.exit(2);
330
- }
331
- } else if (arg === '--target-host') {
332
- // UDP-S13: Parse --target-host flag (defaults to 127.0.0.1)
333
- if (i + 1 < args.length) {
334
- parsed.targetHost = args[i + 1];
335
- consumed.add(i);
336
- consumed.add(i + 1);
337
- i++; // Skip next argument as it's the target host value
338
- } else {
339
- logger.error("cli.args.target_host_missing", {});
340
- process.stderr.write("Error: --target-host requires a host value\n");
341
- process.exit(2);
342
- }
343
- } else if (arg === '--external-port' || arg === '--ext-port') {
344
- // TPB-03B: Parse --external-port flag (alias --ext-port)
345
- if (i + 1 < args.length) {
346
- const externalPort = parseInt(args[i + 1], 10);
347
- if (isNaN(externalPort) || externalPort < 1 || externalPort > 65535) {
348
- logger.error("cli.args.external_port_invalid", { value: args[i + 1] });
349
- process.stderr.write(`Error: Invalid external port number: ${args[i + 1]}\n`);
350
- process.exit(2);
351
- }
352
- parsed.externalPort = externalPort;
353
- consumed.add(i);
354
- consumed.add(i + 1);
355
- i++; // Skip next argument as it's the external port value
356
- } else {
357
- logger.error("cli.args.external_port_missing", {});
358
- process.stderr.write("Error: --external-port requires a port number\n");
359
- process.exit(2);
360
- }
361
- } else if (arg === '--help' || arg === '-h') {
362
- parsed.help = true;
363
- consumed.add(i);
364
- } else if (arg.startsWith('--')) {
365
- // UDP-S16: Unknown flag detected
366
- const closest = findClosestFlag(arg, KNOWN_TUNNEL_FLAGS);
367
- if (closest) {
368
- // User-friendly error message only (no structured logging for user-facing errors)
369
- process.stderr.write(`Error: Unknown option: ${arg}. Did you mean: ${closest}?\n`);
370
- } else {
371
- // User-friendly error message only (no structured logging for user-facing errors)
372
- process.stderr.write(`Error: Unknown option: ${arg}\n`);
373
- }
374
- process.exit(1);
375
- }
376
- // Non-flag arguments (like "connect") are not consumed here and will be handled by the caller
377
- }
378
- return parsed;
214
+ const parsed = {};
215
+ const consumed = new Set();
216
+ for (let i = 0; i < args.length; i++) {
217
+ if (consumed.has(i))
218
+ continue;
219
+ const arg = args[i];
220
+ if (arg === '--http') {
221
+ parsed.http = true;
222
+ consumed.add(i);
223
+ }
224
+ else if (arg === '--tcp') {
225
+ parsed.tcp = true;
226
+ consumed.add(i);
227
+ }
228
+ else if (arg === '--udp') {
229
+ parsed.udp = true;
230
+ consumed.add(i);
231
+ }
232
+ else if (arg === '--minecraft') {
233
+ parsed.minecraft = true;
234
+ consumed.add(i);
235
+ }
236
+ else if (arg === '--port') {
237
+ if (i + 1 < args.length) {
238
+ const port = parseInt(args[i + 1], 10);
239
+ if (isNaN(port) || port < 1 || port > 65535) {
240
+ logger.error("cli.args.port_invalid", { value: args[i + 1] });
241
+ process.stderr.write(`Error: Invalid port number: ${args[i + 1]}\n`);
242
+ process.exit(2);
243
+ }
244
+ parsed.port = port;
245
+ consumed.add(i);
246
+ consumed.add(i + 1);
247
+ i++;
248
+ }
249
+ else {
250
+ logger.error("cli.args.port_missing", {});
251
+ process.stderr.write("Error: --port requires a port number\n");
252
+ process.exit(2);
253
+ }
254
+ }
255
+ else if (arg === '--name') {
256
+ if (i + 1 < args.length) {
257
+ parsed.serviceName = args[i + 1];
258
+ consumed.add(i);
259
+ consumed.add(i + 1);
260
+ i++;
261
+ }
262
+ else {
263
+ logger.error("cli.args.name_missing", {});
264
+ process.stderr.write("Error: --name requires a service name\n");
265
+ process.exit(2);
266
+ }
267
+ }
268
+ else if (arg === '--replace' || arg === '--wait' || arg === '--json') {
269
+ parsed[arg.slice(2)] = true;
270
+ consumed.add(i);
271
+ }
272
+ else if (arg === '--to') {
273
+ const v = args[i + 1];
274
+ const host = v ? String(v).trim().toLowerCase().replace(/^[a-z]+:\/\//, '').replace(/[/?#].*$/, '').replace(/\.$/, '') : '';
275
+ if (!host || !/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/.test(host)) {
276
+ logger.error("cli.args.to_invalid", {});
277
+ process.stderr.write("Error: --to needs a hostname, for example --to orders-api.tunnel.asyx.ai\n");
278
+ process.exit(2);
279
+ }
280
+ parsed.to = host;
281
+ consumed.add(i);
282
+ consumed.add(i + 1);
283
+ i++;
284
+ }
285
+ else if (arg === '--secgroup') {
286
+ if (i + 1 < args.length) {
287
+ parsed.secGroupSlug = args[i + 1];
288
+ consumed.add(i);
289
+ consumed.add(i + 1);
290
+ i++;
291
+ }
292
+ else {
293
+ logger.error("cli.args.secgroup_missing", {});
294
+ process.stderr.write("Error: --secgroup requires a slug\n");
295
+ process.exit(2);
296
+ }
297
+ }
298
+ else if (arg === '--target-host') {
299
+ if (i + 1 < args.length) {
300
+ parsed.targetHost = args[i + 1];
301
+ consumed.add(i);
302
+ consumed.add(i + 1);
303
+ i++;
304
+ }
305
+ else {
306
+ logger.error("cli.args.target_host_missing", {});
307
+ process.stderr.write("Error: --target-host requires a host value\n");
308
+ process.exit(2);
309
+ }
310
+ }
311
+ else if (arg === '--external-port' || arg === '--ext-port') {
312
+ if (i + 1 < args.length) {
313
+ const externalPort = parseInt(args[i + 1], 10);
314
+ if (isNaN(externalPort) || externalPort < 1 || externalPort > 65535) {
315
+ logger.error("cli.args.external_port_invalid", { value: args[i + 1] });
316
+ process.stderr.write(`Error: Invalid external port number: ${args[i + 1]}\n`);
317
+ process.exit(2);
318
+ }
319
+ parsed.externalPort = externalPort;
320
+ consumed.add(i);
321
+ consumed.add(i + 1);
322
+ i++;
323
+ }
324
+ else {
325
+ logger.error("cli.args.external_port_missing", {});
326
+ process.stderr.write("Error: --external-port requires a port number\n");
327
+ process.exit(2);
328
+ }
329
+ }
330
+ else if (arg === '--help' || arg === '-h') {
331
+ parsed.help = true;
332
+ consumed.add(i);
333
+ }
334
+ else if (arg.startsWith('--')) {
335
+ const closest = findClosestFlag(arg, KNOWN_TUNNEL_FLAGS);
336
+ if (closest) {
337
+ process.stderr.write(`Error: Unknown option: ${arg}. Did you mean: ${closest}?\n`);
338
+ }
339
+ else {
340
+ process.stderr.write(`Error: Unknown option: ${arg}\n`);
341
+ }
342
+ process.exit(1);
343
+ }
344
+ }
345
+ return parsed;
379
346
  }
380
-
381
347
  async function connect() {
382
- // 0) Imports (kept local to this command to avoid global side-effects)
383
- const { loadAwsIotConfig, AwsIotTransport } = await import("@asyx/mqtt-broker-aws");
384
- const { MqttCore } = await import("@asyx/mqtt-core");
385
- // policy module path may vary between dev/prod builds; fall back to permissive in dev
386
- const { default: clientPolicyFactory } =
387
- (await import("@asyx/mqtt-client/dist/policy.js").catch(() => ({ default: null })));
388
-
389
- // 1) Load IoT config (throws with clear messages if misconfigured)
390
- let cfg;
391
- try {
392
- cfg = loadAwsIotConfig();
393
- } catch (e) {
394
- logger.error("config.error", { error: e?.message || String(e) });
395
- process.exit(1);
396
- }
397
- logger.info("mqtt.connect.start", {});
398
-
399
- // Preflight endpoint sanity check
400
- if (/^\d{12}-ats\.iot\./.test(cfg.endpoint)) {
401
- logger.error("mqtt.endpoint.invalid", { endpoint: cfg.endpoint });
402
- process.exit(1);
403
- }
404
-
405
- // DNS check for clearer error
406
- try {
407
- const { promises: dns } = await import("node:dns");
408
- await dns.lookup(cfg.endpoint);
409
- } catch {
410
- logger.error("mqtt.endpoint.unresolved", { endpoint: cfg.endpoint });
411
- process.exit(1);
412
- }
413
-
414
- // 2) Build transport + core with policy guard
415
- const t = new AwsIotTransport(logger);
416
- const policy =
417
- clientPolicyFactory ? clientPolicyFactory(cfg.clientId) : { canPublish: () => true, canSubscribe: () => true };
418
- const core = new MqttCore(t, policy);
419
-
420
- // Utility: topic helpers - v4.1 client topics only
421
- const evtWildcard = `asyx/tunnel/clients/${cfg.clientId}/evt/#`;
422
- const cmdOpenTopic = `asyx/tunnel/clients/${cfg.clientId}/cmd/open`;
423
- const registrationTopic = `asyx/tunnel/clients/${cfg.clientId}/cmd/open`;
424
- const acknowledgmentTopic = `asyx/tunnel/clients/${cfg.clientId}/evt/ack`;
425
-
426
- async function performSessionRegistration(ingress) {
427
- const sessionId = crypto.randomUUID();
428
- const manifestVersion = Date.now().toString();
429
- const issuedAt = new Date().toISOString();
430
-
431
- // CP-3C: Collect hardware fingerprint
432
- const { getFpHash } = await import("#tunnel-core/lib/fingerprint.js");
433
- const fingerprint = await getFpHash(cfg.clientId);
434
-
435
- // Warn if fingerprint unavailable
436
- if (fingerprint.fph === 'unavailable') {
437
- logger.warn("fingerprint.unavailable", { clientId: cfg.clientId });
438
- process.stderr.write('⚠️ hardware fingerprint unavailable; coordinator may require setup.\n');
348
+ const { AwsIotTransport } = await import("@asyx/mqtt-broker-aws");
349
+ const { loadAwsIotConfig } = await import("../lib/aws-iot-config.js");
350
+ const { MqttCore } = await import("@asyx/mqtt-core");
351
+ const { default: clientPolicyFactory } = (await import("@asyx/mqtt-client/dist/policy.js").catch(() => ({ default: null })));
352
+ let cfg;
353
+ try {
354
+ cfg = loadAwsIotConfig();
355
+ }
356
+ catch (e) {
357
+ logger.error("config.error", { error: e?.message || String(e) });
358
+ process.exit(1);
359
+ }
360
+ logger.info("mqtt.connect.start", {});
361
+ if (/^\d{12}-ats\.iot\./.test(cfg.endpoint)) {
362
+ logger.error("mqtt.endpoint.invalid", { endpoint: cfg.endpoint });
363
+ process.exit(1);
439
364
  }
440
-
441
- const registrationPayload = {
442
- clientId: cfg.clientId,
443
- sessionId,
444
- manifestVersion,
445
- issuedAt,
446
- ...fingerprint
447
- };
448
-
449
- // Use AwaiterMap to wait for matching ack; timeout after 5s.
450
- const ackPromise = ingress.awaitSessionId(sessionId, acknowledgmentTopic, 5000);
451
-
452
- // Publish once; no retries.
453
- await core.publish({
454
- topic: registrationTopic,
455
- payload: JSON.stringify(registrationPayload),
456
- qos: 1,
457
- retain: false
458
- });
459
-
460
365
  try {
461
- await ackPromise; // Ignore result for now; coordinator may not be running yet.
462
- } catch (error) {
463
- // Timeout or other error - ignore for now as coordinator may not be running
464
- logger.warn("cp.registration.timeout", { error: error.message });
366
+ const { promises: dns } = await import("node:dns");
367
+ await dns.lookup(cfg.endpoint);
368
+ }
369
+ catch {
370
+ logger.error("mqtt.endpoint.unresolved", { endpoint: cfg.endpoint });
371
+ process.exit(1);
372
+ }
373
+ const t = new AwsIotTransport(logger);
374
+ const policy = clientPolicyFactory ? clientPolicyFactory(cfg.clientId) : { canPublish: () => true, canSubscribe: () => true };
375
+ const core = new MqttCore(t, policy);
376
+ const evtWildcard = `asyx/tunnel/clients/${cfg.clientId}/evt/#`;
377
+ const cmdOpenTopic = `asyx/tunnel/clients/${cfg.clientId}/cmd/open`;
378
+ const registrationTopic = `asyx/tunnel/clients/${cfg.clientId}/cmd/open`;
379
+ const acknowledgmentTopic = `asyx/tunnel/clients/${cfg.clientId}/evt/ack`;
380
+ async function performSessionRegistration(ingress) {
381
+ const sessionId = crypto.randomUUID();
382
+ const manifestVersion = Date.now().toString();
383
+ const issuedAt = new Date().toISOString();
384
+ const { getFpHash } = await import("#tunnel-core/lib/fingerprint.js");
385
+ const fingerprint = await getFpHash(cfg.clientId);
386
+ if (fingerprint.fph === 'unavailable') {
387
+ logger.warn("fingerprint.unavailable", { clientId: cfg.clientId });
388
+ process.stderr.write('⚠️ hardware fingerprint unavailable; coordinator may require setup.\n');
389
+ }
390
+ const registrationPayload = {
391
+ clientId: cfg.clientId,
392
+ sessionId,
393
+ manifestVersion,
394
+ issuedAt,
395
+ ...fingerprint
396
+ };
397
+ const ackPromise = ingress.awaitSessionId(sessionId, acknowledgmentTopic, 5000);
398
+ await core.publish({
399
+ topic: registrationTopic,
400
+ payload: JSON.stringify(registrationPayload),
401
+ qos: 1,
402
+ retain: false
403
+ });
404
+ try {
405
+ await ackPromise;
406
+ }
407
+ catch (error) {
408
+ logger.warn("cp.registration.timeout", { error: error.message });
409
+ }
465
410
  }
466
- }
467
-
468
- // initial connect (single attempt; no debug/retry noise)
469
- try {
470
- await core.connect({ protocol: "tls", keepalive: 30, clean: true });
471
- } catch (e) {
472
- logger.error("mqtt.connect.failed", { error: e?.message || String(e) });
473
- process.exit(1);
474
- }
475
- await core.subscribe(evtWildcard, 0);
476
-
477
- // CP-3G: Single ingress with awaiters + dispatcher (fix multiple onMessage handlers)
478
- const ingress = new MessageIngress({
479
- maxAwaiters: 100,
480
- observability: process.env.ASYX_DEBUG === '1',
481
- logger // QPA-CLI-10: Pass logger for quiet mode
482
- });
483
-
484
- // Set up the CP-3F dispatcher
485
- ingress.setDispatcher(dispatchEvt);
486
-
487
- // Single onMessage handler that processes all messages
488
- core.onMessage(async (m) => {
489
411
  try {
490
- await ingress.handleMessage(m);
491
- } catch (e) {
492
- // Map handler decisions to exit codes (business logic only)
493
- if (e && e.code === "SETUP_REQUIRED") {
494
- process.stderr.write(`❌ ${e.message}\n`);
495
- // Ensure clean connection end, then exit 2
496
- try { await core.end(); } catch {}
497
- process.exit(2);
498
- }
499
- if (e && typeof e.code === "string" && e.code.startsWith("ERROR_")) {
500
- process.stderr.write(`❌ ${e.message}\n`);
501
- try { await core.end(); } catch {}
412
+ await core.connect({ protocol: "tls", keepalive: 30, clean: true });
413
+ }
414
+ catch (e) {
415
+ logger.error("mqtt.connect.failed", { error: e?.message || String(e) });
502
416
  process.exit(1);
503
- }
504
- // Unknown exceptions — hard fail
505
- process.stderr.write(`❌ Unexpected: ${e?.message || String(e)}\n`);
506
- try { await core.end(); } catch {}
507
- process.exit(1);
508
417
  }
509
- });
510
-
511
-
512
- // CP-2: Session Registration (single publish; optional ack wait)
513
- await performSessionRegistration(ingress);
514
-
515
- // 6) Keep alive & auto-reconnect on failures seen at call sites
516
- // In this CP-1 minimal pass, we rely on publish/subscribe errors to trigger reconnects if needed.
517
- // For now, we simply keep the process alive until SIGINT/SIGTERM.
518
-
519
- // 6) Graceful shutdown
520
- let shuttingDown = false;
521
- const onSig = async (sig) => {
522
- if (shuttingDown) return;
523
- shuttingDown = true;
524
- logger.info("cli.shutdown", { sig });
525
- const killer = setTimeout(() => {
526
- logger.error("cli.shutdown.timeout", {});
527
- process.exit(0);
528
- }, 3000);
529
- try { await core.end(); } catch (e) { /* ignore */ }
530
- clearTimeout(killer);
531
- process.exit(0);
532
- };
533
- process.once("SIGINT", onSig);
534
- process.once("SIGTERM", onSig);
535
-
536
- // park the process (no interval spam; just a pending promise)
537
- await new Promise(() => {}); // eslint-disable-line no-new
418
+ await core.subscribe(evtWildcard, 0);
419
+ const ingress = new MessageIngress({
420
+ maxAwaiters: 100,
421
+ observability: process.env.ASYX_DEBUG === '1',
422
+ logger
423
+ });
424
+ ingress.setDispatcher(dispatchEvt);
425
+ core.onMessage(async (m) => {
426
+ try {
427
+ await ingress.handleMessage(m);
428
+ }
429
+ catch (e) {
430
+ if (e && e.code === "SETUP_REQUIRED") {
431
+ process.stderr.write(`❌ ${e.message}\n`);
432
+ try {
433
+ await core.end();
434
+ }
435
+ catch { }
436
+ process.exit(2);
437
+ }
438
+ if (e && typeof e.code === "string" && e.code.startsWith("ERROR_")) {
439
+ process.stderr.write(`❌ ${e.message}\n`);
440
+ try {
441
+ await core.end();
442
+ }
443
+ catch { }
444
+ process.exit(1);
445
+ }
446
+ process.stderr.write(`❌ Unexpected: ${e?.message || String(e)}\n`);
447
+ try {
448
+ await core.end();
449
+ }
450
+ catch { }
451
+ process.exit(1);
452
+ }
453
+ });
454
+ await performSessionRegistration(ingress);
455
+ let shuttingDown = false;
456
+ const onSig = async (sig) => {
457
+ if (shuttingDown)
458
+ return;
459
+ shuttingDown = true;
460
+ logger.info("cli.shutdown", { sig });
461
+ const killer = setTimeout(() => {
462
+ logger.error("cli.shutdown.timeout", {});
463
+ process.exit(0);
464
+ }, 3000);
465
+ try {
466
+ await core.end();
467
+ }
468
+ catch (e) { }
469
+ clearTimeout(killer);
470
+ process.exit(0);
471
+ };
472
+ process.once("SIGINT", onSig);
473
+ process.once("SIGTERM", onSig);
474
+ await new Promise(() => { });
538
475
  }
539
-
540
476
  async function httpTunnel(localPort, secGroupSlug) {
541
- logger.info("cli.http.start", { localPort, secGroupSlug });
542
- process.stdout.write(`⚙️ Initializing tunnel on port ${localPort}…\n`);
543
-
544
- const { loadAwsIotConfig } = await import("@asyx/mqtt-broker-aws");
545
- const { readFileSync } = await import("node:fs");
546
-
547
- // 1) Load IoT config (throws with clear messages if misconfigured)
548
- let cfg;
549
- try {
550
- cfg = loadAwsIotConfig();
551
- } catch (e) {
552
- logger.error("config.error", { error: e?.message || String(e) });
553
- process.stderr.write(`Config error: ${e?.message || e}\n`);
554
- process.exit(1);
555
- }
556
-
557
- logger.info("cli.http.control_plane.establish", {});
558
- // QPA-CLI-11: Vault UX messaging - Negotiating control-plane security
559
- process.stdout.write(`🔐 Negotiating control-plane security…\n`);
560
-
561
- // Story 12.1 (step 2b): the HTTP flow lives in @asyx/tunnel-core; the CLI prints its events and
562
- // maps its error codes to the same messages and exit codes as before.
563
- const { createHttpTunnel } = await import("#tunnel-core/flows/http.js");
564
- const handle = createHttpTunnel({
565
- waitIfInUse: tunnelOutput.wait === true, // Story 1.9
566
- credentials: { endpoint: cfg.endpoint, clientId: cfg.clientId, ca: readFileSync(cfg.caPath), cert: readFileSync(cfg.certPath), key: readFileSync(cfg.keyPath) },
567
- localPort,
568
- secGroupSlug,
569
- logger,
570
- onObserve: (line) => console.log(line), // ASYX_DEBUG=1 ingress lines, printed as before
571
- });
572
- handle.on('notice', (n) => { if (n?.code === 'address_in_use_waiting') printWaiting(n); }); // Story 1.9
573
- // Story 3.13: one line when a closed lease is reopened by itself, and why when it cannot be
574
- handle.on('reopened', (r) => process.stdout.write(`↻ The tunnel's lease was closed; reopened it${r?.publicPort ? ` on the same port ${r.publicPort}` : ''}.\n`));
575
- handle.on('reopen_refused', (r) => process.stderr.write(r?.code === 'reopen_limit' ? 'The tunnel was closed 3 times in 10 minutes; not reopening again. Start it again when you are ready.\n' : `The tunnel's lease was closed and reopening it was refused (${r?.code || 'refused'}).\n`));
576
- // QPA-CLI-11: Vault UX messaging - Control-plane sealed
577
- handle.on('control-connected', () => process.stdout.write("✅ Control-plane sealed\n"));
578
- handle.on('control-offline', ({ reason }) => process.stderr.write(`[mqtt] Control-plane connection lost: ${reason}\n`));
579
- handle.on('control-fatal', ({ reason }) => {
580
- process.stderr.write(`❌ Fatal control-plane error: ${reason}\n`);
581
- process.exit(1);
582
- });
583
- // Story 12.1: messages the HTTP tunnel used to print itself
584
- handle.on('notice', ({ code, reason, mqttReason, retry, port }) => {
585
- const mqttSuffix = (mqttReason && mqttReason !== 'unknown') ? `. MQTT reason: ${mqttReason}` : '';
586
- if (code === 'control_plane_offline') process.stdout.write(`⚠️ Control-plane offline (${reason})${mqttSuffix}. Waiting for reconnect…\n`);
587
- else if (code === 'control_plane_timeout') process.stdout.write(`⚠️ Control-plane offline (timeout)${mqttSuffix}. Waiting for reconnect…\n`);
588
- else if (code === 'jwt_expired_offline') process.stdout.write(`❌ JWT expired while control-plane was offline. Exiting.\n`);
589
- else if (code === 'quickpass_refresh_delayed') process.stdout.write(`⚠️ QuickPass token refresh delayed – reconnecting control plane… (retry ${retry})\n`);
590
- // Story 3.8: the tunnel stays up while the local service is down; visitors get a 502 page.
591
- else if (code === 'local_service_unreachable') process.stdout.write(`⚠️ Nothing is answering on localhost:${port}. The tunnel stays up; visitors see a "not reachable" page until your app is back.\n`);
592
- else if (code === 'local_service_back') process.stdout.write(`✅ Your app on localhost:${port} is answering again.\n`);
593
- });
594
- handle.on('closed', ({ error }) => {
595
- if (!error) return;
596
- if (error.code === 'setup_required') { process.stderr.write(`❌ ${error.message}\n`); process.exit(2); }
597
- // Story 12.1: the tunnel ended where it used to call process.exit; same code, no message
598
- if (error.details?.exitCode !== undefined) process.exit(error.details.exitCode);
599
- if (error.name === 'RefusedError') { process.stderr.write(`❌ ${error.message}\n`); process.exit(1); }
600
- process.stderr.write(`❌ Unexpected: ${error.message}\n`);
601
- process.exit(1);
602
- });
603
-
604
- try {
605
- await handle.open();
606
- } catch (error) {
607
- if (error.code === 'address_in_use') exitInUse(error.details); // Story 1.9
608
- switch (error.code) {
609
- case 'control_plane_connect_failed': process.stderr.write(`Tunnel command failed: ${error.message}\n`); break;
610
- case 'assignment_failed': break; // HTTP has always exited here without a message
611
- case 'tunnel_connect_failed': process.stderr.write(`❌ Tunnel connection failed: ${error.message}\n`); break;
612
- default: process.stderr.write(`❌ Unexpected: ${error?.message || String(error)}\n`);
613
- }
614
- process.exit(1);
615
- }
616
- const assignment = handle.assignment;
617
- const leaseMinutes = Math.floor(assignment.leaseMs / 60000);
618
-
619
- // QPA-CLI-11: QuickPass line only when a group was requested and the coordinator confirmed it
620
- if (secGroupSlug && assignment.quickpassSlug) {
621
- process.stdout.write(`🛡️ QuickPass secured (group=${assignment.quickpassSlug})\n`);
622
- }
623
- process.stdout.write(httpLiveLines(assignment, localPort));
624
- // QPA-CLI-12: Lease and relay info only shown with LOG_LEVEL=info or higher
625
- const logLevel = (process.env.ASYX_LOG_LEVEL || process.env.LOG_LEVEL || 'warn').toLowerCase();
626
- if (logLevel === 'info' || logLevel === 'debug') {
627
- process.stdout.write(` Relay: ${assignment.relayId}\n`);
628
- process.stdout.write(` Lease window: ${leaseMinutes} minutes (auto-renews while active)\n`);
629
- }
630
- process.stdout.write(` Press Ctrl+C to stop\n`);
631
-
632
- let shuttingDown = false;
633
- const onSig = async (sig) => {
634
- if (shuttingDown) return;
635
- shuttingDown = true;
636
- logger.info("cli.signal.shutdown", { sig });
637
- process.stdout.write(`signal ${sig} — shutting down…\n`);
638
- const killer = setTimeout(() => {
639
- logger.error("tunnel.close.timeout", {});
640
- process.stderr.write("tunnel.close() timed out; forcing exit\n");
641
- process.exit(0);
642
- }, 3000);
643
- // Story 3.13: say goodbye first (the lease closes at once); never waits more than 2 s
644
- try { const bye = await handle.goodbye?.(2000); logger.debug('tunnel.goodbye', { result: bye }); } catch (e) { logger.debug('tunnel.goodbye.error', { error: e?.message }); }
477
+ logger.info("cli.http.start", { localPort, secGroupSlug });
478
+ process.stdout.write(`⚙️ Initializing tunnel on port ${localPort}…\n`);
479
+ const { loadAwsIotConfig } = await import("../lib/aws-iot-config.js");
480
+ const { readFileSync } = await import("node:fs");
481
+ let cfg;
645
482
  try {
646
- handle.tunnel.close();
647
- } catch (e) {
648
- logger.error('tunnel.close.error', { error: e.message });
649
- process.stderr.write(`Error closing tunnel: ${e.message}\n`);
483
+ cfg = loadAwsIotConfig();
650
484
  }
651
- try {
652
- await handle.mqttClient.disconnect();
653
- } catch (e) {
654
- logger.debug('mqtt.control_plane.disconnect.error', { error: e.message });
655
- }
656
- clearTimeout(killer);
657
- process.exit(0);
658
- };
659
- process.once("SIGINT", onSig);
660
- process.once("SIGTERM", onSig);
661
-
662
- // Manual renewal for troubleshooting
663
- try {
664
- process.once('SIGUSR2', () => {
665
- logger.debug('jwt.refresh.trigger', { source: 'signal', sig: 'SIGUSR2' });
666
- try { handle.attemptJwtRefresh(); } catch (e) {
667
- logger.error('jwt.refresh.trigger.error', { error: e?.message || String(e) });
668
- }
485
+ catch (e) {
486
+ logger.error("config.error", { error: e?.message || String(e) });
487
+ process.stderr.write(`Config error: ${e?.message || e}\n`);
488
+ process.exit(1);
489
+ }
490
+ logger.info("cli.http.control_plane.establish", {});
491
+ process.stdout.write(`🔐 Negotiating control-plane security…\n`);
492
+ const { createHttpTunnel } = await import("#tunnel-core/flows/http.js");
493
+ const handle = createHttpTunnel({
494
+ waitIfInUse: tunnelOutput.wait === true,
495
+ credentials: { endpoint: cfg.endpoint, clientId: cfg.clientId, ca: readFileSync(cfg.caPath), cert: readFileSync(cfg.certPath), key: readFileSync(cfg.keyPath) },
496
+ localPort,
497
+ secGroupSlug,
498
+ logger,
499
+ onObserve: (line) => console.log(line),
669
500
  });
670
- } catch {}
671
-
672
- // Keep process alive until SIGINT/SIGTERM
673
- await new Promise(() => {});
501
+ handle.on('notice', (n) => { if (n?.code === 'address_in_use_waiting')
502
+ printWaiting(n); });
503
+ handle.on('reopened', (r) => process.stdout.write(`↻ The tunnel's lease was closed; reopened it${r?.publicPort ? ` on the same port ${r.publicPort}` : ''}.\n`));
504
+ handle.on('reopen_refused', (r) => process.stderr.write(r?.code === 'reopen_limit' ? 'The tunnel was closed 3 times in 10 minutes; not reopening again. Start it again when you are ready.\n' : `The tunnel's lease was closed and reopening it was refused (${r?.code || 'refused'}).\n`));
505
+ handle.on('control-connected', () => process.stdout.write("✅ Control-plane sealed\n"));
506
+ handle.on('control-offline', ({ reason }) => process.stderr.write(`[mqtt] Control-plane connection lost: ${reason}\n`));
507
+ handle.on('control-fatal', ({ reason }) => {
508
+ process.stderr.write(`❌ Fatal control-plane error: ${reason}\n`);
509
+ process.exit(1);
510
+ });
511
+ handle.on('notice', ({ code, reason, mqttReason, retry, port }) => {
512
+ const mqttSuffix = (mqttReason && mqttReason !== 'unknown') ? `. MQTT reason: ${mqttReason}` : '';
513
+ if (code === 'control_plane_offline')
514
+ process.stdout.write(`⚠️ Control-plane offline (${reason})${mqttSuffix}. Waiting for reconnect…\n`);
515
+ else if (code === 'control_plane_timeout')
516
+ process.stdout.write(`⚠️ Control-plane offline (timeout)${mqttSuffix}. Waiting for reconnect…\n`);
517
+ else if (code === 'jwt_expired_offline')
518
+ process.stdout.write(`❌ JWT expired while control-plane was offline. Exiting.\n`);
519
+ else if (code === 'quickpass_refresh_delayed')
520
+ process.stdout.write(`⚠️ QuickPass token refresh delayed – reconnecting control plane… (retry ${retry})\n`);
521
+ else if (code === 'local_service_unreachable')
522
+ process.stdout.write(`⚠️ Nothing is answering on localhost:${port}. The tunnel stays up; visitors see a "not reachable" page until your app is back.\n`);
523
+ else if (code === 'local_service_back')
524
+ process.stdout.write(`✅ Your app on localhost:${port} is answering again.\n`);
525
+ });
526
+ handle.on('closed', ({ error }) => {
527
+ if (!error)
528
+ return;
529
+ if (error.code === 'setup_required') {
530
+ process.stderr.write(`❌ ${error.message}\n`);
531
+ process.exit(2);
532
+ }
533
+ if (error.details?.exitCode !== undefined)
534
+ process.exit(error.details.exitCode);
535
+ if (error.name === 'RefusedError') {
536
+ explainAppStop(error).then(() => { process.stderr.write(`❌ ${error.message}\n`); process.exit(1); });
537
+ return;
538
+ }
539
+ process.stderr.write(`❌ Unexpected: ${error.message}\n`);
540
+ process.exit(1);
541
+ });
542
+ try {
543
+ await handle.open();
544
+ }
545
+ catch (error) {
546
+ await explainAppStop(error);
547
+ if (error.code === 'address_in_use')
548
+ exitInUse(error.details);
549
+ switch (error.code) {
550
+ case 'control_plane_connect_failed':
551
+ process.stderr.write(`Tunnel command failed: ${error.message}\n`);
552
+ break;
553
+ case 'assignment_failed': break;
554
+ case 'tunnel_connect_failed':
555
+ process.stderr.write(`❌ Tunnel connection failed: ${error.message}\n`);
556
+ break;
557
+ default: process.stderr.write(`❌ Unexpected: ${error?.message || String(error)}\n`);
558
+ }
559
+ process.exit(1);
560
+ }
561
+ const assignment = handle.assignment;
562
+ const leaseMinutes = Math.floor(assignment.leaseMs / 60000);
563
+ if (secGroupSlug && assignment.quickpassSlug) {
564
+ process.stdout.write(`🛡️ QuickPass secured (group=${assignment.quickpassSlug})\n`);
565
+ }
566
+ process.stdout.write(httpLiveLines(assignment, localPort));
567
+ const logLevel = (process.env.ASYX_LOG_LEVEL || process.env.LOG_LEVEL || 'warn').toLowerCase();
568
+ if (logLevel === 'info' || logLevel === 'debug') {
569
+ process.stdout.write(` Relay: ${assignment.relayId}\n`);
570
+ process.stdout.write(` Lease window: ${leaseMinutes} minutes (auto-renews while active)\n`);
571
+ }
572
+ process.stdout.write(` Press Ctrl+C to stop\n`);
573
+ let shuttingDown = false;
574
+ const onSig = async (sig) => {
575
+ if (shuttingDown)
576
+ return;
577
+ shuttingDown = true;
578
+ logger.info("cli.signal.shutdown", { sig });
579
+ process.stdout.write(`signal ${sig} — shutting down…\n`);
580
+ const killer = setTimeout(() => {
581
+ logger.error("tunnel.close.timeout", {});
582
+ process.stderr.write("tunnel.close() timed out; forcing exit\n");
583
+ process.exit(0);
584
+ }, 3000);
585
+ try {
586
+ const bye = await handle.goodbye?.(2000);
587
+ logger.debug('tunnel.goodbye', { result: bye });
588
+ }
589
+ catch (e) {
590
+ logger.debug('tunnel.goodbye.error', { error: e?.message });
591
+ }
592
+ try {
593
+ handle.tunnel.close();
594
+ }
595
+ catch (e) {
596
+ logger.error('tunnel.close.error', { error: e.message });
597
+ process.stderr.write(`Error closing tunnel: ${e.message}\n`);
598
+ }
599
+ try {
600
+ await handle.mqttClient.disconnect();
601
+ }
602
+ catch (e) {
603
+ logger.debug('mqtt.control_plane.disconnect.error', { error: e.message });
604
+ }
605
+ clearTimeout(killer);
606
+ process.exit(0);
607
+ };
608
+ process.once("SIGINT", onSig);
609
+ process.once("SIGTERM", onSig);
610
+ try {
611
+ process.once('SIGUSR2', () => {
612
+ logger.debug('jwt.refresh.trigger', { source: 'signal', sig: 'SIGUSR2' });
613
+ try {
614
+ handle.attemptJwtRefresh();
615
+ }
616
+ catch (e) {
617
+ logger.error('jwt.refresh.trigger.error', { error: e?.message || String(e) });
618
+ }
619
+ });
620
+ }
621
+ catch { }
622
+ await new Promise(() => { });
674
623
  }
675
-
676
- /**
677
- * Build TCP target string from port.
678
- * Defaults to 127.0.0.1 (localhost-only in v4.1).
679
- * @param {number} port - Port number
680
- * @returns {string} Target string in format "127.0.0.1:port"
681
- */
682
624
  function buildTcpTarget(port) {
683
- return `127.0.0.1:${port}`;
625
+ return `127.0.0.1:${port}`;
684
626
  }
685
-
686
- /**
687
- * Validate that target is localhost-only (127.0.0.1, ::1, or localhost).
688
- * @param {string} target - Target string in format "host:port"
689
- * @returns {boolean} True if target is localhost-only
690
- */
691
627
  function isLocalhostTarget(target) {
692
- // Extract host part (before the colon)
693
- const host = target.split(':')[0];
694
-
695
- // Normalize hostname to lowercase for comparison
696
- const normalizedHost = host.toLowerCase();
697
-
698
- // Allowed localhost values
699
- const allowedHosts = ['127.0.0.1', '::1', 'localhost'];
700
-
701
- return allowedHosts.includes(normalizedHost);
628
+ const host = target.split(':')[0];
629
+ const normalizedHost = host.toLowerCase();
630
+ const allowedHosts = ['127.0.0.1', '::1', 'localhost'];
631
+ return allowedHosts.includes(normalizedHost);
702
632
  }
703
-
704
- /**
705
- * TCP tunnel implementation (TCP-S2: cmd/open Payload + Compatibility).
706
- * Builds and sends MQTT cmd/open payload with protocol:"tcp" and target.
707
- * Reuses existing MQTT control-plane infrastructure.
708
- * @param {number} localPort - Local port number
709
- * @param {string} [serviceName] - Optional service name
710
- * @param {string} [kind] - Optional service kind
711
- * @param {number} [requestedExternalPort] - Optional requested external port (TPB-03B)
712
- */
713
633
  async function tcpTunnel(localPort, serviceName, kind = null, requestedExternalPort = null) {
714
- logger.info('cli.tcp.start', { localPort, serviceName });
715
- process.stdout.write(`⚙️ Initializing TCP tunnel on port ${localPort}…\n`);
716
-
717
- // TCP-S1: Validation complete, target constructed
718
- const target = buildTcpTarget(localPort);
719
- logger.info('cli.tcp.target', { target });
720
-
721
- const { loadAwsIotConfig } = await import("@asyx/mqtt-broker-aws");
722
- const { readFileSync } = await import("node:fs");
723
-
724
- // 1) Load IoT config (throws with clear messages if misconfigured)
725
- let cfg;
726
- try {
727
- cfg = loadAwsIotConfig();
728
- } catch (e) {
729
- logger.error("config.error", { error: e?.message || String(e) });
730
- process.stderr.write(`Config error: ${e?.message || e}\n`);
731
- process.exit(1);
732
- }
733
-
734
- logger.info("cli.tcp.control_plane.establish", {});
735
- process.stdout.write(`🔐 Negotiating control-plane security…\n`);
736
-
737
- // Story 12.1 (step 2b): the TCP flow lives in @asyx/tunnel-core; the CLI prints its events and
738
- // maps its error codes to the same messages and exit codes as before.
739
- const { createTcpTunnel } = await import("#tunnel-core/flows/tcp.js");
740
- const handle = createTcpTunnel({
741
- waitIfInUse: tunnelOutput.wait === true, // Story 1.9
742
- credentials: { endpoint: cfg.endpoint, clientId: cfg.clientId, ca: readFileSync(cfg.caPath), cert: readFileSync(cfg.certPath), key: readFileSync(cfg.keyPath) },
743
- localPort,
744
- target,
745
- serviceName,
746
- kind,
747
- requestedExternalPort,
748
- logger,
749
- onObserve: (line) => console.log(line), // ASYX_DEBUG=1 ingress lines, printed as before
750
- });
751
- handle.on('notice', (n) => { if (n?.code === 'address_in_use_waiting') printWaiting(n); }); // Story 1.9
752
- // Story 3.13: one line when a closed lease is reopened by itself, and why when it cannot be
753
- handle.on('reopened', (r) => process.stdout.write(`↻ The tunnel's lease was closed; reopened it${r?.publicPort ? ` on the same port ${r.publicPort}` : ''}.\n`));
754
- handle.on('reopen_refused', (r) => process.stderr.write(r?.code === 'reopen_limit' ? 'The tunnel was closed 3 times in 10 minutes; not reopening again. Start it again when you are ready.\n' : `The tunnel's lease was closed and reopening it was refused (${r?.code || 'refused'}).\n`));
755
- // QPA-CLI-11: Vault UX messaging - Control-plane sealed
756
- handle.on('control-connected', () => process.stdout.write("✅ Control-plane sealed\n"));
757
- handle.on('control-fatal', ({ reason }) => {
758
- process.stderr.write(`❌ Fatal control-plane error: ${reason}\n`);
759
- process.exit(1);
760
- });
761
- handle.on('closed', ({ error }) => {
762
- if (!error) return;
763
- if (error.code === 'setup_required') { process.stderr.write(`❌ ${error.message}\n`); process.exit(2); }
764
- // Story 12.1: the tunnel ended where it used to call process.exit; same code, no message
765
- if (error.details?.exitCode !== undefined) process.exit(error.details.exitCode);
766
- if (error.name === 'RefusedError') { process.stderr.write(`❌ ${error.message}\n`); process.exit(1); }
767
- process.stderr.write(`❌ Unexpected: ${error.message}\n`);
768
- process.exit(1);
769
- });
770
- // TCP-S3 / E3-S8: where the server is reachable, printed when the assignment arrives
771
- handle.on('assigned', ({ tcpAliasFqdn, srvProvisioned, srvFqdn, fqdn, publicPort, aliasRequestedButFailed, portMoved }) => {
772
- // Story 2.11 c3: naming a port labelled for another address moved its label here
773
- if (portMoved?.from) process.stdout.write(`Port ${portMoved.port} moved from ${portMoved.from} to ${portMoved.to}.\n`);
774
- const mc = minecraftMoveLine(portMoved); // Story 1.7 r8
775
- if (mc) process.stdout.write(mc);
776
- if (tcpAliasFqdn) {
777
- process.stdout.write(`Your TCP server is available at:\n\n`);
778
- process.stdout.write(` ${tcpAliasFqdn}\n`);
779
- process.stdout.write(` or\n`);
780
- process.stdout.write(` ${fqdn}:${publicPort}\n`);
781
- if (srvProvisioned && srvFqdn) {
782
- process.stdout.write(`\n Minecraft clients can connect to: ${srvFqdn.replace('_minecraft._tcp.', '')} (SRV record)\n`);
783
- }
784
- } else if (srvProvisioned && srvFqdn) {
785
- process.stdout.write(`Your TCP server is available at:\n\n`);
786
- process.stdout.write(` ${fqdn}:${publicPort}\n`);
787
- process.stdout.write(`\n Minecraft clients can connect to: ${srvFqdn.replace('_minecraft._tcp.', '')} (SRV record, no port needed)\n`);
788
- } else if (aliasRequestedButFailed) {
789
- process.stdout.write(`Your TCP server is available at:\n\n`);
790
- process.stdout.write(` ${fqdn}:${publicPort}\n`);
791
- process.stdout.write(` (alias unavailable; using host:port only)\n`);
792
- } else {
793
- process.stdout.write(`Your TCP server is available at:\n\n`);
794
- process.stdout.write(` ${fqdn}:${publicPort}\n`);
795
- }
796
- });
797
-
798
- try {
799
- await handle.open();
800
- } catch (error) {
801
- if (error.code === 'address_in_use') exitInUse(error.details); // Story 1.9
802
- const d = error.details || {};
803
- switch (error.code) {
804
- case 'control_plane_connect_failed': process.stderr.write(`Tunnel command failed: ${error.message}\n`); break;
805
- case 'tcp_port_out_of_block': process.stderr.write(`Requested external port ${d.requestedPort} is outside your assigned block ${d.blockStart}–${d.blockEnd}.\n`); break;
806
- case 'tcp_port_already_in_use': process.stderr.write(`External port ${d.requestedPort} is already in use by another active tunnel.\n`); break;
807
- case 'tcp_port_block_exhausted_for_tenant':
808
- case 'tcp_port_block_exhausted': process.stderr.write(`All 10 ports in your block ${d.blockStart}–${d.blockEnd} are currently in use.\n`); break;
809
- case 'tcp_port_capacity_exhausted': process.stderr.write(`Relay TCP port capacity exhausted. Please retry later.\n`); break;
810
- case 'tenant_tcp_lease_limit_reached': process.stderr.write(`Tenant TCP lease limit reached on relay ${d.relayId}\n`); break;
811
- case 'assignment_failed': process.stderr.write(`❌ Tunnel assignment failed: ${error.message}\n`); break;
812
- case 'tunnel_connect_failed': break; // TCP has always exited here without a message
813
- default: process.stderr.write(`❌ Unexpected: ${error?.message || String(error)}\n`);
814
- }
815
- process.exit(1);
816
- }
817
- const assignment = handle.assignment;
818
-
819
- process.stdout.write(`🔌 TCP tunnel active (ready for connections)\n`);
820
- process.stdout.write(` Target: 127.0.0.1:${localPort}\n`);
821
- // QPA-CLI-12: Lease and relay info only shown with LOG_LEVEL=info or higher
822
- const logLevel = (process.env.ASYX_LOG_LEVEL || process.env.LOG_LEVEL || 'warn').toLowerCase();
823
- if (logLevel === 'info' || logLevel === 'debug') {
824
- process.stdout.write(` Relay: ${assignment.relayId}\n`);
825
- const leaseMinutes = Math.floor(assignment.leaseMs / 60000);
826
- process.stdout.write(` Lease window: ${leaseMinutes} minutes\n`);
827
- }
828
- process.stdout.write(` Press Ctrl+C to stop\n`);
829
-
830
- // CLI-IMG-WSReconnect: Set up graceful shutdown
831
- let shuttingDown = false;
832
- const onSig = async (sig) => {
833
- if (shuttingDown) return;
834
- shuttingDown = true;
835
- logger.info("cli.signal.shutdown", { sig });
836
- process.stdout.write(`\nsignal ${sig} — shutting down…\n`);
837
- const killer = setTimeout(() => {
838
- logger.error("tunnel.close.timeout", {});
839
- process.stderr.write("tunnel.close() timed out; forcing exit\n");
840
- process.exit(0);
841
- }, 3000);
634
+ logger.info('cli.tcp.start', { localPort, serviceName });
635
+ process.stdout.write(`⚙️ Initializing TCP tunnel on port ${localPort}…\n`);
636
+ const target = buildTcpTarget(localPort);
637
+ logger.info('cli.tcp.target', { target });
638
+ const { loadAwsIotConfig } = await import("../lib/aws-iot-config.js");
639
+ const { readFileSync } = await import("node:fs");
640
+ let cfg;
842
641
  try {
843
- await handle.close();
844
- } catch (e) {
845
- logger.debug('tunnel.shutdown.error', { error: e.message });
846
- }
847
- clearTimeout(killer);
848
- process.exit(0);
849
- };
850
- process.once("SIGINT", onSig);
851
- process.once("SIGTERM", onSig);
852
-
853
- // Keep process alive until SIGINT/SIGTERM
854
- await new Promise(() => {});
642
+ cfg = loadAwsIotConfig();
643
+ }
644
+ catch (e) {
645
+ logger.error("config.error", { error: e?.message || String(e) });
646
+ process.stderr.write(`Config error: ${e?.message || e}\n`);
647
+ process.exit(1);
648
+ }
649
+ logger.info("cli.tcp.control_plane.establish", {});
650
+ process.stdout.write(`🔐 Negotiating control-plane security…\n`);
651
+ const { createTcpTunnel } = await import("#tunnel-core/flows/tcp.js");
652
+ const handle = createTcpTunnel({
653
+ waitIfInUse: tunnelOutput.wait === true,
654
+ credentials: { endpoint: cfg.endpoint, clientId: cfg.clientId, ca: readFileSync(cfg.caPath), cert: readFileSync(cfg.certPath), key: readFileSync(cfg.keyPath) },
655
+ localPort,
656
+ target,
657
+ serviceName,
658
+ kind,
659
+ requestedExternalPort,
660
+ logger,
661
+ onObserve: (line) => console.log(line),
662
+ });
663
+ handle.on('notice', (n) => { if (n?.code === 'address_in_use_waiting')
664
+ printWaiting(n); });
665
+ handle.on('reopened', (r) => process.stdout.write(`↻ The tunnel's lease was closed; reopened it${r?.publicPort ? ` on the same port ${r.publicPort}` : ''}.\n`));
666
+ handle.on('reopen_refused', (r) => process.stderr.write(r?.code === 'reopen_limit' ? 'The tunnel was closed 3 times in 10 minutes; not reopening again. Start it again when you are ready.\n' : `The tunnel's lease was closed and reopening it was refused (${r?.code || 'refused'}).\n`));
667
+ handle.on('control-connected', () => process.stdout.write("✅ Control-plane sealed\n"));
668
+ handle.on('control-fatal', ({ reason }) => {
669
+ process.stderr.write(`❌ Fatal control-plane error: ${reason}\n`);
670
+ process.exit(1);
671
+ });
672
+ handle.on('closed', ({ error }) => {
673
+ if (!error)
674
+ return;
675
+ if (error.code === 'setup_required') {
676
+ process.stderr.write(`❌ ${error.message}\n`);
677
+ process.exit(2);
678
+ }
679
+ if (error.details?.exitCode !== undefined)
680
+ process.exit(error.details.exitCode);
681
+ if (error.name === 'RefusedError') {
682
+ process.stderr.write(`❌ ${error.message}\n`);
683
+ process.exit(1);
684
+ }
685
+ process.stderr.write(`❌ Unexpected: ${error.message}\n`);
686
+ process.exit(1);
687
+ });
688
+ handle.on('assigned', ({ tcpAliasFqdn, srvProvisioned, srvFqdn, fqdn, publicPort, aliasRequestedButFailed, portMoved }) => {
689
+ if (portMoved?.from)
690
+ process.stdout.write(`Port ${portMoved.port} moved from ${portMoved.from} to ${portMoved.to}.\n`);
691
+ const mc = minecraftMoveLine(portMoved);
692
+ if (mc)
693
+ process.stdout.write(mc);
694
+ if (tcpAliasFqdn) {
695
+ process.stdout.write(`Your TCP server is available at:\n\n`);
696
+ process.stdout.write(` ${tcpAliasFqdn}\n`);
697
+ process.stdout.write(` or\n`);
698
+ process.stdout.write(` ${fqdn}:${publicPort}\n`);
699
+ if (srvProvisioned && srvFqdn) {
700
+ process.stdout.write(`\n Minecraft clients can connect to: ${srvFqdn.replace('_minecraft._tcp.', '')} (SRV record)\n`);
701
+ }
702
+ }
703
+ else if (srvProvisioned && srvFqdn) {
704
+ process.stdout.write(`Your TCP server is available at:\n\n`);
705
+ process.stdout.write(` ${fqdn}:${publicPort}\n`);
706
+ process.stdout.write(`\n Minecraft clients can connect to: ${srvFqdn.replace('_minecraft._tcp.', '')} (SRV record, no port needed)\n`);
707
+ }
708
+ else if (aliasRequestedButFailed) {
709
+ process.stdout.write(`Your TCP server is available at:\n\n`);
710
+ process.stdout.write(` ${fqdn}:${publicPort}\n`);
711
+ process.stdout.write(` (alias unavailable; using host:port only)\n`);
712
+ }
713
+ else {
714
+ process.stdout.write(`Your TCP server is available at:\n\n`);
715
+ process.stdout.write(` ${fqdn}:${publicPort}\n`);
716
+ }
717
+ });
718
+ try {
719
+ await handle.open();
720
+ }
721
+ catch (error) {
722
+ await explainAppStop(error);
723
+ if (error.code === 'address_in_use')
724
+ exitInUse(error.details);
725
+ const d = error.details || {};
726
+ switch (error.code) {
727
+ case 'control_plane_connect_failed':
728
+ process.stderr.write(`Tunnel command failed: ${error.message}\n`);
729
+ break;
730
+ case 'tcp_port_out_of_block':
731
+ process.stderr.write(`Requested external port ${d.requestedPort} is outside your assigned block ${d.blockStart}–${d.blockEnd}.\n`);
732
+ break;
733
+ case 'tcp_port_already_in_use':
734
+ process.stderr.write(`External port ${d.requestedPort} is already in use by another active tunnel.\n`);
735
+ break;
736
+ case 'tcp_port_block_exhausted_for_tenant':
737
+ case 'tcp_port_block_exhausted':
738
+ process.stderr.write(`All 10 ports in your block ${d.blockStart}–${d.blockEnd} are currently in use.\n`);
739
+ break;
740
+ case 'tcp_port_capacity_exhausted':
741
+ process.stderr.write(`Relay TCP port capacity exhausted. Please retry later.\n`);
742
+ break;
743
+ case 'tenant_tcp_lease_limit_reached':
744
+ process.stderr.write(`Tenant TCP lease limit reached on relay ${d.relayId}\n`);
745
+ break;
746
+ case 'assignment_failed':
747
+ process.stderr.write(`❌ Tunnel assignment failed: ${error.message}\n`);
748
+ break;
749
+ case 'tunnel_connect_failed': break;
750
+ default: process.stderr.write(`❌ Unexpected: ${error?.message || String(error)}\n`);
751
+ }
752
+ process.exit(1);
753
+ }
754
+ const assignment = handle.assignment;
755
+ process.stdout.write(`🔌 TCP tunnel active (ready for connections)\n`);
756
+ process.stdout.write(` Target: 127.0.0.1:${localPort}\n`);
757
+ const logLevel = (process.env.ASYX_LOG_LEVEL || process.env.LOG_LEVEL || 'warn').toLowerCase();
758
+ if (logLevel === 'info' || logLevel === 'debug') {
759
+ process.stdout.write(` Relay: ${assignment.relayId}\n`);
760
+ const leaseMinutes = Math.floor(assignment.leaseMs / 60000);
761
+ process.stdout.write(` Lease window: ${leaseMinutes} minutes\n`);
762
+ }
763
+ process.stdout.write(` Press Ctrl+C to stop\n`);
764
+ let shuttingDown = false;
765
+ const onSig = async (sig) => {
766
+ if (shuttingDown)
767
+ return;
768
+ shuttingDown = true;
769
+ logger.info("cli.signal.shutdown", { sig });
770
+ process.stdout.write(`\nsignal ${sig} — shutting down…\n`);
771
+ const killer = setTimeout(() => {
772
+ logger.error("tunnel.close.timeout", {});
773
+ process.stderr.write("tunnel.close() timed out; forcing exit\n");
774
+ process.exit(0);
775
+ }, 3000);
776
+ try {
777
+ await handle.close();
778
+ }
779
+ catch (e) {
780
+ logger.debug('tunnel.shutdown.error', { error: e.message });
781
+ }
782
+ clearTimeout(killer);
783
+ process.exit(0);
784
+ };
785
+ process.once("SIGINT", onSig);
786
+ process.once("SIGTERM", onSig);
787
+ await new Promise(() => { });
855
788
  }
856
-
857
- /**
858
- * UDP tunnel implementation (UDP-S1: CLI – UDP entrypoint & WS connect).
859
- * Builds and sends MQTT cmd/open payload with protocol:"udp" and tunnelMode:"udpWs-v1".
860
- * Reuses existing MQTT control-plane infrastructure.
861
- * UDP-S13: --port is the app's listening port (targetPort), CLI never binds it.
862
- * @param {number} targetPort - Target port of the local UDP app (from --port)
863
- * @param {number} [requestedExternalPort] - Optional requested external port
864
- * @param {string} [targetHost] - Target host (defaults to 127.0.0.1, must be loopback)
865
- */
866
789
  async function udpTunnel(targetPort, requestedExternalPort = null, targetHost = '127.0.0.1') {
867
- logger.info('cli.udp.start', { targetPort, requestedExternalPort, targetHost });
868
- process.stdout.write(`⚙️ Initializing UDP tunnel to ${targetHost}:${targetPort}…\n`);
869
-
870
- // UDP-S13: --port is targetPort, not a port we bind to
871
- logger.info('cli.udp.target', { target: `${targetHost}:${targetPort}` });
872
-
873
- const { loadAwsIotConfig } = await import("@asyx/mqtt-broker-aws");
874
- const { readFileSync } = await import("node:fs");
875
-
876
- // 1) Load IoT config (throws with clear messages if misconfigured)
877
- let cfg;
878
- try {
879
- cfg = loadAwsIotConfig();
880
- } catch (e) {
881
- logger.error("config.error", { error: e?.message || String(e) });
882
- process.stderr.write(`Config error: ${e?.message || e}\n`);
883
- process.exit(1);
884
- }
885
-
886
- logger.info("cli.udp.control_plane.establish", {});
887
- process.stdout.write(`🔐 Negotiating control-plane security…\n`);
888
-
889
- // Story 12.1 (step 2b): the UDP flow lives in @asyx/tunnel-core; the CLI prints its events and
890
- // maps its error codes to the same messages and exit codes as before.
891
- const { createUdpTunnel } = await import("#tunnel-core/flows/udp.js");
892
- const handle = createUdpTunnel({
893
- waitIfInUse: tunnelOutput.wait === true, // Story 1.9
894
- credentials: { endpoint: cfg.endpoint, clientId: cfg.clientId, ca: readFileSync(cfg.caPath), cert: readFileSync(cfg.certPath), key: readFileSync(cfg.keyPath) },
895
- targetPort,
896
- targetHost,
897
- requestedExternalPort,
898
- logger,
899
- onObserve: (line) => console.log(line), // ASYX_DEBUG=1 ingress lines, printed as before
900
- });
901
- handle.on('notice', (n) => { if (n?.code === 'address_in_use_waiting') printWaiting(n); }); // Story 1.9
902
- // Story 3.13: one line when a closed lease is reopened by itself, and why when it cannot be
903
- handle.on('reopened', (r) => process.stdout.write(`↻ The tunnel's lease was closed; reopened it${r?.publicPort ? ` on the same port ${r.publicPort}` : ''}.\n`));
904
- handle.on('reopen_refused', (r) => process.stderr.write(r?.code === 'reopen_limit' ? 'The tunnel was closed 3 times in 10 minutes; not reopening again. Start it again when you are ready.\n' : `The tunnel's lease was closed and reopening it was refused (${r?.code || 'refused'}).\n`));
905
- // QPA-CLI-11: Vault UX messaging - Control-plane sealed
906
- handle.on('control-connected', () => process.stdout.write("✅ Control-plane sealed\n"));
907
- handle.on('control-offline', ({ reason }) => process.stderr.write(`[mqtt] Control-plane connection lost: ${reason}\n`));
908
- handle.on('control-fatal', ({ reason }) => {
909
- process.stderr.write(`❌ Fatal control-plane error: ${reason}\n`);
910
- process.exit(1);
911
- });
912
- handle.on('closed', ({ error }) => {
913
- if (!error) return;
914
- if (error.code === 'setup_required') { process.stderr.write(`❌ ${error.message}\n`); process.exit(2); }
915
- // Story 12.1: the tunnel ended where it used to call process.exit; same code, no message
916
- if (error.details?.exitCode !== undefined) process.exit(error.details.exitCode);
917
- if (error.name === 'RefusedError') { process.stderr.write(`❌ ${error.message}\n`); process.exit(1); }
918
- process.stderr.write(`❌ Unexpected: ${error.message}\n`);
919
- process.exit(1);
920
- });
921
-
922
- try {
923
- await handle.open();
924
- } catch (error) {
925
- if (error.code === 'address_in_use') exitInUse(error.details); // Story 1.9
926
- switch (error.code) {
927
- case 'control_plane_connect_failed': process.stderr.write(`Tunnel command failed: ${error.message}\n`); break;
928
- case 'udp_relay_unavailable': process.stderr.write(`❌ ${error.message}\n`); break;
929
- case 'assignment_failed': process.stderr.write(`❌ Tunnel assignment failed: ${error.message}\n`); break;
930
- case 'tunnel_connect_failed': process.stderr.write(`❌ Tunnel connection failed: ${error.message}\n`); break;
931
- default: process.stderr.write(`❌ Unexpected: ${error?.message || String(error)}\n`);
932
- }
933
- process.exit(1);
934
- }
935
- const assignment = handle.assignment;
936
-
937
- // Tunnel live message (UDP-S13: both fqdn and fqdn:publicPort; the CLI does not bind the service port)
938
- if (assignment.portMoved?.from) process.stdout.write(`Port ${assignment.portMoved.port} moved from ${assignment.portMoved.from} to ${assignment.portMoved.to}.\n`); // Story 2.11 c3
939
- process.stdout.write(`🔌 UDP tunnel active (ready for datagrams)\n`);
940
- process.stdout.write(` App target: ${targetHost}:${targetPort}\n`);
941
- if (assignment.fqdn) {
942
- process.stdout.write(` Your UDP server is available at:\n`);
943
- process.stdout.write(` ${assignment.fqdn}\n`);
944
- if (assignment.publicPort) {
945
- process.stdout.write(` ${assignment.fqdn}:${assignment.publicPort}\n`);
946
- }
947
- } else if (assignment.publicPort) {
948
- process.stdout.write(` Public port: ${assignment.publicPort}\n`);
949
- }
950
- // QPA-CLI-12: Lease and relay info only shown with LOG_LEVEL=info or higher
951
- const logLevel = (process.env.ASYX_LOG_LEVEL || process.env.LOG_LEVEL || 'warn').toLowerCase();
952
- if (logLevel === 'info' || logLevel === 'debug') {
953
- process.stdout.write(` Relay: ${assignment.relayId}\n`);
954
- const leaseMinutes = Math.floor(assignment.leaseMs / 60000);
955
- process.stdout.write(` Lease window: ${leaseMinutes} minutes\n`);
956
- }
957
- process.stdout.write(` Press Ctrl+C to stop\n`);
958
-
959
- // CLI-IMG-WSReconnect: Set up graceful shutdown
960
- let shuttingDown = false;
961
- const onSig = async (sig) => {
962
- if (shuttingDown) return;
963
- shuttingDown = true;
964
- logger.info("cli.signal.shutdown", { sig });
965
- process.stdout.write(`\nsignal ${sig} — shutting down…\n`);
966
- const killer = setTimeout(() => {
967
- logger.error("tunnel.close.timeout", {});
968
- process.stderr.write("tunnel.close() timed out; forcing exit\n");
969
- process.exit(0);
970
- }, 3000);
790
+ logger.info('cli.udp.start', { targetPort, requestedExternalPort, targetHost });
791
+ process.stdout.write(`⚙️ Initializing UDP tunnel to ${targetHost}:${targetPort}…\n`);
792
+ logger.info('cli.udp.target', { target: `${targetHost}:${targetPort}` });
793
+ const { loadAwsIotConfig } = await import("../lib/aws-iot-config.js");
794
+ const { readFileSync } = await import("node:fs");
795
+ let cfg;
971
796
  try {
972
- await handle.close();
973
- } catch (e) {
974
- logger.debug('tunnel.shutdown.error', { error: e.message });
975
- }
976
- clearTimeout(killer);
977
- process.exit(0);
978
- };
979
- process.once("SIGINT", onSig);
980
- process.once("SIGTERM", onSig);
981
-
982
- // Keep process alive until SIGINT/SIGTERM
983
- await new Promise(() => {});
797
+ cfg = loadAwsIotConfig();
798
+ }
799
+ catch (e) {
800
+ logger.error("config.error", { error: e?.message || String(e) });
801
+ process.stderr.write(`Config error: ${e?.message || e}\n`);
802
+ process.exit(1);
803
+ }
804
+ logger.info("cli.udp.control_plane.establish", {});
805
+ process.stdout.write(`🔐 Negotiating control-plane security…\n`);
806
+ const { createUdpTunnel } = await import("#tunnel-core/flows/udp.js");
807
+ const handle = createUdpTunnel({
808
+ waitIfInUse: tunnelOutput.wait === true,
809
+ credentials: { endpoint: cfg.endpoint, clientId: cfg.clientId, ca: readFileSync(cfg.caPath), cert: readFileSync(cfg.certPath), key: readFileSync(cfg.keyPath) },
810
+ targetPort,
811
+ targetHost,
812
+ requestedExternalPort,
813
+ logger,
814
+ onObserve: (line) => console.log(line),
815
+ });
816
+ handle.on('notice', (n) => { if (n?.code === 'address_in_use_waiting')
817
+ printWaiting(n); });
818
+ handle.on('reopened', (r) => process.stdout.write(`↻ The tunnel's lease was closed; reopened it${r?.publicPort ? ` on the same port ${r.publicPort}` : ''}.\n`));
819
+ handle.on('reopen_refused', (r) => process.stderr.write(r?.code === 'reopen_limit' ? 'The tunnel was closed 3 times in 10 minutes; not reopening again. Start it again when you are ready.\n' : `The tunnel's lease was closed and reopening it was refused (${r?.code || 'refused'}).\n`));
820
+ handle.on('control-connected', () => process.stdout.write("✅ Control-plane sealed\n"));
821
+ handle.on('control-offline', ({ reason }) => process.stderr.write(`[mqtt] Control-plane connection lost: ${reason}\n`));
822
+ handle.on('control-fatal', ({ reason }) => {
823
+ process.stderr.write(`❌ Fatal control-plane error: ${reason}\n`);
824
+ process.exit(1);
825
+ });
826
+ handle.on('closed', ({ error }) => {
827
+ if (!error)
828
+ return;
829
+ if (error.code === 'setup_required') {
830
+ process.stderr.write(`❌ ${error.message}\n`);
831
+ process.exit(2);
832
+ }
833
+ if (error.details?.exitCode !== undefined)
834
+ process.exit(error.details.exitCode);
835
+ if (error.name === 'RefusedError') {
836
+ process.stderr.write(`❌ ${error.message}\n`);
837
+ process.exit(1);
838
+ }
839
+ process.stderr.write(`❌ Unexpected: ${error.message}\n`);
840
+ process.exit(1);
841
+ });
842
+ try {
843
+ await handle.open();
844
+ }
845
+ catch (error) {
846
+ await explainAppStop(error);
847
+ if (error.code === 'address_in_use')
848
+ exitInUse(error.details);
849
+ switch (error.code) {
850
+ case 'control_plane_connect_failed':
851
+ process.stderr.write(`Tunnel command failed: ${error.message}\n`);
852
+ break;
853
+ case 'udp_relay_unavailable':
854
+ process.stderr.write(`❌ ${error.message}\n`);
855
+ break;
856
+ case 'assignment_failed':
857
+ process.stderr.write(`❌ Tunnel assignment failed: ${error.message}\n`);
858
+ break;
859
+ case 'tunnel_connect_failed':
860
+ process.stderr.write(`❌ Tunnel connection failed: ${error.message}\n`);
861
+ break;
862
+ default: process.stderr.write(`❌ Unexpected: ${error?.message || String(error)}\n`);
863
+ }
864
+ process.exit(1);
865
+ }
866
+ const assignment = handle.assignment;
867
+ if (assignment.portMoved?.from)
868
+ process.stdout.write(`Port ${assignment.portMoved.port} moved from ${assignment.portMoved.from} to ${assignment.portMoved.to}.\n`);
869
+ process.stdout.write(`🔌 UDP tunnel active (ready for datagrams)\n`);
870
+ process.stdout.write(` App target: ${targetHost}:${targetPort}\n`);
871
+ if (assignment.fqdn) {
872
+ process.stdout.write(` Your UDP server is available at:\n`);
873
+ process.stdout.write(` ${assignment.fqdn}\n`);
874
+ if (assignment.publicPort) {
875
+ process.stdout.write(` ${assignment.fqdn}:${assignment.publicPort}\n`);
876
+ }
877
+ }
878
+ else if (assignment.publicPort) {
879
+ process.stdout.write(` Public port: ${assignment.publicPort}\n`);
880
+ }
881
+ const logLevel = (process.env.ASYX_LOG_LEVEL || process.env.LOG_LEVEL || 'warn').toLowerCase();
882
+ if (logLevel === 'info' || logLevel === 'debug') {
883
+ process.stdout.write(` Relay: ${assignment.relayId}\n`);
884
+ const leaseMinutes = Math.floor(assignment.leaseMs / 60000);
885
+ process.stdout.write(` Lease window: ${leaseMinutes} minutes\n`);
886
+ }
887
+ process.stdout.write(` Press Ctrl+C to stop\n`);
888
+ let shuttingDown = false;
889
+ const onSig = async (sig) => {
890
+ if (shuttingDown)
891
+ return;
892
+ shuttingDown = true;
893
+ logger.info("cli.signal.shutdown", { sig });
894
+ process.stdout.write(`\nsignal ${sig} — shutting down…\n`);
895
+ const killer = setTimeout(() => {
896
+ logger.error("tunnel.close.timeout", {});
897
+ process.stderr.write("tunnel.close() timed out; forcing exit\n");
898
+ process.exit(0);
899
+ }, 3000);
900
+ try {
901
+ await handle.close();
902
+ }
903
+ catch (e) {
904
+ logger.debug('tunnel.shutdown.error', { error: e.message });
905
+ }
906
+ clearTimeout(killer);
907
+ process.exit(0);
908
+ };
909
+ process.once("SIGINT", onSig);
910
+ process.once("SIGTERM", onSig);
911
+ await new Promise(() => { });
984
912
  }
985
-
986
913
  function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }
987
-
988
- // Story 11.2: exp claim (seconds) of an assignment token, or null
989
-
990
- /** Defect 11.47: the HTTP live line names the public address visitors use, then the local port. */
991
914
  export function httpLiveLines(assignment, localPort) {
992
- const publicHost = typeof assignment?.fqdn === 'string' && assignment.fqdn.trim() ? assignment.fqdn.trim() : null;
993
- return publicHost
994
- ? `🌐 Tunnel live at https://${publicHost}\n Forwarding to http://localhost:${localPort}\n`
995
- : `🌐 Tunnel live at http://localhost:${localPort}\n`;
915
+ const publicHost = typeof assignment?.fqdn === 'string' && assignment.fqdn.trim() ? assignment.fqdn.trim() : null;
916
+ return publicHost
917
+ ? `🌐 Tunnel live at https://${publicHost}\n Forwarding to http://localhost:${localPort}\n`
918
+ : `🌐 Tunnel live at http://localhost:${localPort}\n`;
996
919
  }
997
-
998
- /** Story 1.7 r8: what happened to the port's Minecraft record when its label moved (TCP). */
999
920
  export function minecraftMoveLine(portMoved) {
1000
- const m = portMoved?.minecraft;
1001
- if (!portMoved?.from || !m) return '';
1002
- const to = portMoved.toHostname || portMoved.to;
1003
- const from = portMoved.fromHostname || portMoved.from;
1004
- switch (m.status) {
1005
- case 'moved': return `Minecraft players now find it at ${to}. For a few minutes ${from} may still lead there.\n`;
1006
- case 'kept_existing': return `${to} already points Minecraft players at port ${m.existingPort}, so that stays. The Minecraft record for port ${portMoved.port} under ${from} was removed.\n`;
1007
- case 'pending': return `The Minecraft record is not updated yet; it follows within a few minutes.\n`;
1008
- case 'not_updated': return `The Minecraft record for port ${portMoved.port} could not be moved to ${to}. Players can still connect with ${to}:${portMoved.port}.\n`;
1009
- default: return '';
1010
- }
921
+ const m = portMoved?.minecraft;
922
+ if (!portMoved?.from || !m)
923
+ return '';
924
+ const to = portMoved.toHostname || portMoved.to;
925
+ const from = portMoved.fromHostname || portMoved.from;
926
+ switch (m.status) {
927
+ case 'moved': return `Minecraft players now find it at ${to}. For a few minutes ${from} may still lead there.\n`;
928
+ case 'kept_existing': return `${to} already points Minecraft players at port ${m.existingPort}, so that stays. The Minecraft record for port ${portMoved.port} under ${from} was removed.\n`;
929
+ case 'pending': return `The Minecraft record is not updated yet; it follows within a few minutes.\n`;
930
+ case 'not_updated': return `The Minecraft record for port ${portMoved.port} could not be moved to ${to}. Players can still connect with ${to}:${portMoved.port}.\n`;
931
+ default: return '';
932
+ }
1011
933
  }