asyx 0.10.1 → 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 +3 -2
  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 -932
  14. package/src/commands/validate-target-host.js +36 -59
  15. package/src/lib/aws-iot-config.js +26 -24
  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,947 +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 { AwsIotTransport } = await import("@asyx/mqtt-broker-aws");
384
- const { loadAwsIotConfig } = await import("../lib/aws-iot-config.js"); // Story 12.2: apps too
385
- const { MqttCore } = await import("@asyx/mqtt-core");
386
- // policy module path may vary between dev/prod builds; fall back to permissive in dev
387
- const { default: clientPolicyFactory } =
388
- (await import("@asyx/mqtt-client/dist/policy.js").catch(() => ({ default: null })));
389
-
390
- // 1) Load IoT config (throws with clear messages if misconfigured)
391
- let cfg;
392
- try {
393
- cfg = loadAwsIotConfig();
394
- } catch (e) {
395
- logger.error("config.error", { error: e?.message || String(e) });
396
- process.exit(1);
397
- }
398
- logger.info("mqtt.connect.start", {});
399
-
400
- // Preflight endpoint sanity check
401
- if (/^\d{12}-ats\.iot\./.test(cfg.endpoint)) {
402
- logger.error("mqtt.endpoint.invalid", { endpoint: cfg.endpoint });
403
- process.exit(1);
404
- }
405
-
406
- // DNS check for clearer error
407
- try {
408
- const { promises: dns } = await import("node:dns");
409
- await dns.lookup(cfg.endpoint);
410
- } catch {
411
- logger.error("mqtt.endpoint.unresolved", { endpoint: cfg.endpoint });
412
- process.exit(1);
413
- }
414
-
415
- // 2) Build transport + core with policy guard
416
- const t = new AwsIotTransport(logger);
417
- const policy =
418
- clientPolicyFactory ? clientPolicyFactory(cfg.clientId) : { canPublish: () => true, canSubscribe: () => true };
419
- const core = new MqttCore(t, policy);
420
-
421
- // Utility: topic helpers - v4.1 client topics only
422
- const evtWildcard = `asyx/tunnel/clients/${cfg.clientId}/evt/#`;
423
- const cmdOpenTopic = `asyx/tunnel/clients/${cfg.clientId}/cmd/open`;
424
- const registrationTopic = `asyx/tunnel/clients/${cfg.clientId}/cmd/open`;
425
- const acknowledgmentTopic = `asyx/tunnel/clients/${cfg.clientId}/evt/ack`;
426
-
427
- async function performSessionRegistration(ingress) {
428
- const sessionId = crypto.randomUUID();
429
- const manifestVersion = Date.now().toString();
430
- const issuedAt = new Date().toISOString();
431
-
432
- // CP-3C: Collect hardware fingerprint
433
- const { getFpHash } = await import("#tunnel-core/lib/fingerprint.js");
434
- const fingerprint = await getFpHash(cfg.clientId);
435
-
436
- // Warn if fingerprint unavailable
437
- if (fingerprint.fph === 'unavailable') {
438
- logger.warn("fingerprint.unavailable", { clientId: cfg.clientId });
439
- 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);
440
364
  }
441
-
442
- const registrationPayload = {
443
- clientId: cfg.clientId,
444
- sessionId,
445
- manifestVersion,
446
- issuedAt,
447
- ...fingerprint
448
- };
449
-
450
- // Use AwaiterMap to wait for matching ack; timeout after 5s.
451
- const ackPromise = ingress.awaitSessionId(sessionId, acknowledgmentTopic, 5000);
452
-
453
- // Publish once; no retries.
454
- await core.publish({
455
- topic: registrationTopic,
456
- payload: JSON.stringify(registrationPayload),
457
- qos: 1,
458
- retain: false
459
- });
460
-
461
365
  try {
462
- await ackPromise; // Ignore result for now; coordinator may not be running yet.
463
- } catch (error) {
464
- // Timeout or other error - ignore for now as coordinator may not be running
465
- 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
+ }
466
410
  }
467
- }
468
-
469
- // initial connect (single attempt; no debug/retry noise)
470
- try {
471
- await core.connect({ protocol: "tls", keepalive: 30, clean: true });
472
- } catch (e) {
473
- logger.error("mqtt.connect.failed", { error: e?.message || String(e) });
474
- process.exit(1);
475
- }
476
- await core.subscribe(evtWildcard, 0);
477
-
478
- // CP-3G: Single ingress with awaiters + dispatcher (fix multiple onMessage handlers)
479
- const ingress = new MessageIngress({
480
- maxAwaiters: 100,
481
- observability: process.env.ASYX_DEBUG === '1',
482
- logger // QPA-CLI-10: Pass logger for quiet mode
483
- });
484
-
485
- // Set up the CP-3F dispatcher
486
- ingress.setDispatcher(dispatchEvt);
487
-
488
- // Single onMessage handler that processes all messages
489
- core.onMessage(async (m) => {
490
411
  try {
491
- await ingress.handleMessage(m);
492
- } catch (e) {
493
- // Map handler decisions to exit codes (business logic only)
494
- if (e && e.code === "SETUP_REQUIRED") {
495
- process.stderr.write(`❌ ${e.message}\n`);
496
- // Ensure clean connection end, then exit 2
497
- try { await core.end(); } catch {}
498
- process.exit(2);
499
- }
500
- if (e && typeof e.code === "string" && e.code.startsWith("ERROR_")) {
501
- process.stderr.write(`❌ ${e.message}\n`);
502
- 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) });
503
416
  process.exit(1);
504
- }
505
- // Unknown exceptions — hard fail
506
- process.stderr.write(`❌ Unexpected: ${e?.message || String(e)}\n`);
507
- try { await core.end(); } catch {}
508
- process.exit(1);
509
417
  }
510
- });
511
-
512
-
513
- // CP-2: Session Registration (single publish; optional ack wait)
514
- await performSessionRegistration(ingress);
515
-
516
- // 6) Keep alive & auto-reconnect on failures seen at call sites
517
- // In this CP-1 minimal pass, we rely on publish/subscribe errors to trigger reconnects if needed.
518
- // For now, we simply keep the process alive until SIGINT/SIGTERM.
519
-
520
- // 6) Graceful shutdown
521
- let shuttingDown = false;
522
- const onSig = async (sig) => {
523
- if (shuttingDown) return;
524
- shuttingDown = true;
525
- logger.info("cli.shutdown", { sig });
526
- const killer = setTimeout(() => {
527
- logger.error("cli.shutdown.timeout", {});
528
- process.exit(0);
529
- }, 3000);
530
- try { await core.end(); } catch (e) { /* ignore */ }
531
- clearTimeout(killer);
532
- process.exit(0);
533
- };
534
- process.once("SIGINT", onSig);
535
- process.once("SIGTERM", onSig);
536
-
537
- // park the process (no interval spam; just a pending promise)
538
- 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(() => { });
539
475
  }
540
-
541
476
  async function httpTunnel(localPort, secGroupSlug) {
542
- logger.info("cli.http.start", { localPort, secGroupSlug });
543
- process.stdout.write(`⚙️ Initializing tunnel on port ${localPort}…\n`);
544
-
545
- const { loadAwsIotConfig } = await import("../lib/aws-iot-config.js"); // Story 12.2: apps too
546
- const { readFileSync } = await import("node:fs");
547
-
548
- // 1) Load IoT config (throws with clear messages if misconfigured)
549
- let cfg;
550
- try {
551
- cfg = loadAwsIotConfig();
552
- } catch (e) {
553
- logger.error("config.error", { error: e?.message || String(e) });
554
- process.stderr.write(`Config error: ${e?.message || e}\n`);
555
- process.exit(1);
556
- }
557
-
558
- logger.info("cli.http.control_plane.establish", {});
559
- // QPA-CLI-11: Vault UX messaging - Negotiating control-plane security
560
- process.stdout.write(`🔐 Negotiating control-plane security…\n`);
561
-
562
- // Story 12.1 (step 2b): the HTTP flow lives in @asyx/tunnel-core; the CLI prints its events and
563
- // maps its error codes to the same messages and exit codes as before.
564
- const { createHttpTunnel } = await import("#tunnel-core/flows/http.js");
565
- const handle = createHttpTunnel({
566
- waitIfInUse: tunnelOutput.wait === true, // Story 1.9
567
- credentials: { endpoint: cfg.endpoint, clientId: cfg.clientId, ca: readFileSync(cfg.caPath), cert: readFileSync(cfg.certPath), key: readFileSync(cfg.keyPath) },
568
- localPort,
569
- secGroupSlug,
570
- logger,
571
- onObserve: (line) => console.log(line), // ASYX_DEBUG=1 ingress lines, printed as before
572
- });
573
- handle.on('notice', (n) => { if (n?.code === 'address_in_use_waiting') printWaiting(n); }); // Story 1.9
574
- // Story 3.13: one line when a closed lease is reopened by itself, and why when it cannot be
575
- handle.on('reopened', (r) => process.stdout.write(`↻ The tunnel's lease was closed; reopened it${r?.publicPort ? ` on the same port ${r.publicPort}` : ''}.\n`));
576
- 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`));
577
- // QPA-CLI-11: Vault UX messaging - Control-plane sealed
578
- handle.on('control-connected', () => process.stdout.write("✅ Control-plane sealed\n"));
579
- handle.on('control-offline', ({ reason }) => process.stderr.write(`[mqtt] Control-plane connection lost: ${reason}\n`));
580
- handle.on('control-fatal', ({ reason }) => {
581
- process.stderr.write(`❌ Fatal control-plane error: ${reason}\n`);
582
- process.exit(1);
583
- });
584
- // Story 12.1: messages the HTTP tunnel used to print itself
585
- handle.on('notice', ({ code, reason, mqttReason, retry, port }) => {
586
- const mqttSuffix = (mqttReason && mqttReason !== 'unknown') ? `. MQTT reason: ${mqttReason}` : '';
587
- if (code === 'control_plane_offline') process.stdout.write(`⚠️ Control-plane offline (${reason})${mqttSuffix}. Waiting for reconnect…\n`);
588
- else if (code === 'control_plane_timeout') process.stdout.write(`⚠️ Control-plane offline (timeout)${mqttSuffix}. Waiting for reconnect…\n`);
589
- else if (code === 'jwt_expired_offline') process.stdout.write(`❌ JWT expired while control-plane was offline. Exiting.\n`);
590
- else if (code === 'quickpass_refresh_delayed') process.stdout.write(`⚠️ QuickPass token refresh delayed – reconnecting control plane… (retry ${retry})\n`);
591
- // Story 3.8: the tunnel stays up while the local service is down; visitors get a 502 page.
592
- 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`);
593
- else if (code === 'local_service_back') process.stdout.write(`✅ Your app on localhost:${port} is answering again.\n`);
594
- });
595
- handle.on('closed', ({ error }) => {
596
- if (!error) return;
597
- if (error.code === 'setup_required') { process.stderr.write(`❌ ${error.message}\n`); process.exit(2); }
598
- // Story 12.1: the tunnel ended where it used to call process.exit; same code, no message
599
- if (error.details?.exitCode !== undefined) process.exit(error.details.exitCode);
600
- if (error.name === 'RefusedError') { process.stderr.write(`❌ ${error.message}\n`); process.exit(1); }
601
- process.stderr.write(`❌ Unexpected: ${error.message}\n`);
602
- process.exit(1);
603
- });
604
-
605
- try {
606
- await handle.open();
607
- } catch (error) {
608
- if (error.code === 'address_in_use') exitInUse(error.details); // Story 1.9
609
- switch (error.code) {
610
- case 'control_plane_connect_failed': process.stderr.write(`Tunnel command failed: ${error.message}\n`); break;
611
- case 'assignment_failed': break; // HTTP has always exited here without a message
612
- case 'tunnel_connect_failed': process.stderr.write(`❌ Tunnel connection failed: ${error.message}\n`); break;
613
- default: process.stderr.write(`❌ Unexpected: ${error?.message || String(error)}\n`);
614
- }
615
- process.exit(1);
616
- }
617
- const assignment = handle.assignment;
618
- const leaseMinutes = Math.floor(assignment.leaseMs / 60000);
619
-
620
- // QPA-CLI-11: QuickPass line only when a group was requested and the coordinator confirmed it
621
- if (secGroupSlug && assignment.quickpassSlug) {
622
- process.stdout.write(`🛡️ QuickPass secured (group=${assignment.quickpassSlug})\n`);
623
- }
624
- process.stdout.write(httpLiveLines(assignment, localPort));
625
- // QPA-CLI-12: Lease and relay info only shown with LOG_LEVEL=info or higher
626
- const logLevel = (process.env.ASYX_LOG_LEVEL || process.env.LOG_LEVEL || 'warn').toLowerCase();
627
- if (logLevel === 'info' || logLevel === 'debug') {
628
- process.stdout.write(` Relay: ${assignment.relayId}\n`);
629
- process.stdout.write(` Lease window: ${leaseMinutes} minutes (auto-renews while active)\n`);
630
- }
631
- process.stdout.write(` Press Ctrl+C to stop\n`);
632
-
633
- let shuttingDown = false;
634
- const onSig = async (sig) => {
635
- if (shuttingDown) return;
636
- shuttingDown = true;
637
- logger.info("cli.signal.shutdown", { sig });
638
- process.stdout.write(`signal ${sig} — shutting down…\n`);
639
- const killer = setTimeout(() => {
640
- logger.error("tunnel.close.timeout", {});
641
- process.stderr.write("tunnel.close() timed out; forcing exit\n");
642
- process.exit(0);
643
- }, 3000);
644
- // Story 3.13: say goodbye first (the lease closes at once); never waits more than 2 s
645
- 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;
646
482
  try {
647
- handle.tunnel.close();
648
- } catch (e) {
649
- logger.error('tunnel.close.error', { error: e.message });
650
- process.stderr.write(`Error closing tunnel: ${e.message}\n`);
483
+ cfg = loadAwsIotConfig();
651
484
  }
652
- try {
653
- await handle.mqttClient.disconnect();
654
- } catch (e) {
655
- logger.debug('mqtt.control_plane.disconnect.error', { error: e.message });
656
- }
657
- clearTimeout(killer);
658
- process.exit(0);
659
- };
660
- process.once("SIGINT", onSig);
661
- process.once("SIGTERM", onSig);
662
-
663
- // Manual renewal for troubleshooting
664
- try {
665
- process.once('SIGUSR2', () => {
666
- logger.debug('jwt.refresh.trigger', { source: 'signal', sig: 'SIGUSR2' });
667
- try { handle.attemptJwtRefresh(); } catch (e) {
668
- logger.error('jwt.refresh.trigger.error', { error: e?.message || String(e) });
669
- }
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),
670
500
  });
671
- } catch {}
672
-
673
- // Keep process alive until SIGINT/SIGTERM
674
- 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(() => { });
675
623
  }
676
-
677
- /**
678
- * Build TCP target string from port.
679
- * Defaults to 127.0.0.1 (localhost-only in v4.1).
680
- * @param {number} port - Port number
681
- * @returns {string} Target string in format "127.0.0.1:port"
682
- */
683
624
  function buildTcpTarget(port) {
684
- return `127.0.0.1:${port}`;
625
+ return `127.0.0.1:${port}`;
685
626
  }
686
-
687
- /**
688
- * Validate that target is localhost-only (127.0.0.1, ::1, or localhost).
689
- * @param {string} target - Target string in format "host:port"
690
- * @returns {boolean} True if target is localhost-only
691
- */
692
627
  function isLocalhostTarget(target) {
693
- // Extract host part (before the colon)
694
- const host = target.split(':')[0];
695
-
696
- // Normalize hostname to lowercase for comparison
697
- const normalizedHost = host.toLowerCase();
698
-
699
- // Allowed localhost values
700
- const allowedHosts = ['127.0.0.1', '::1', 'localhost'];
701
-
702
- 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);
703
632
  }
704
-
705
- /**
706
- * TCP tunnel implementation (TCP-S2: cmd/open Payload + Compatibility).
707
- * Builds and sends MQTT cmd/open payload with protocol:"tcp" and target.
708
- * Reuses existing MQTT control-plane infrastructure.
709
- * @param {number} localPort - Local port number
710
- * @param {string} [serviceName] - Optional service name
711
- * @param {string} [kind] - Optional service kind
712
- * @param {number} [requestedExternalPort] - Optional requested external port (TPB-03B)
713
- */
714
633
  async function tcpTunnel(localPort, serviceName, kind = null, requestedExternalPort = null) {
715
- logger.info('cli.tcp.start', { localPort, serviceName });
716
- process.stdout.write(`⚙️ Initializing TCP tunnel on port ${localPort}…\n`);
717
-
718
- // TCP-S1: Validation complete, target constructed
719
- const target = buildTcpTarget(localPort);
720
- logger.info('cli.tcp.target', { target });
721
-
722
- const { loadAwsIotConfig } = await import("../lib/aws-iot-config.js"); // Story 12.2: apps too
723
- const { readFileSync } = await import("node:fs");
724
-
725
- // 1) Load IoT config (throws with clear messages if misconfigured)
726
- let cfg;
727
- try {
728
- cfg = loadAwsIotConfig();
729
- } catch (e) {
730
- logger.error("config.error", { error: e?.message || String(e) });
731
- process.stderr.write(`Config error: ${e?.message || e}\n`);
732
- process.exit(1);
733
- }
734
-
735
- logger.info("cli.tcp.control_plane.establish", {});
736
- process.stdout.write(`🔐 Negotiating control-plane security…\n`);
737
-
738
- // Story 12.1 (step 2b): the TCP flow lives in @asyx/tunnel-core; the CLI prints its events and
739
- // maps its error codes to the same messages and exit codes as before.
740
- const { createTcpTunnel } = await import("#tunnel-core/flows/tcp.js");
741
- const handle = createTcpTunnel({
742
- waitIfInUse: tunnelOutput.wait === true, // Story 1.9
743
- credentials: { endpoint: cfg.endpoint, clientId: cfg.clientId, ca: readFileSync(cfg.caPath), cert: readFileSync(cfg.certPath), key: readFileSync(cfg.keyPath) },
744
- localPort,
745
- target,
746
- serviceName,
747
- kind,
748
- requestedExternalPort,
749
- logger,
750
- onObserve: (line) => console.log(line), // ASYX_DEBUG=1 ingress lines, printed as before
751
- });
752
- handle.on('notice', (n) => { if (n?.code === 'address_in_use_waiting') printWaiting(n); }); // Story 1.9
753
- // Story 3.13: one line when a closed lease is reopened by itself, and why when it cannot be
754
- handle.on('reopened', (r) => process.stdout.write(`↻ The tunnel's lease was closed; reopened it${r?.publicPort ? ` on the same port ${r.publicPort}` : ''}.\n`));
755
- 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`));
756
- // QPA-CLI-11: Vault UX messaging - Control-plane sealed
757
- handle.on('control-connected', () => process.stdout.write("✅ Control-plane sealed\n"));
758
- handle.on('control-fatal', ({ reason }) => {
759
- process.stderr.write(`❌ Fatal control-plane error: ${reason}\n`);
760
- process.exit(1);
761
- });
762
- handle.on('closed', ({ error }) => {
763
- if (!error) return;
764
- if (error.code === 'setup_required') { process.stderr.write(`❌ ${error.message}\n`); process.exit(2); }
765
- // Story 12.1: the tunnel ended where it used to call process.exit; same code, no message
766
- if (error.details?.exitCode !== undefined) process.exit(error.details.exitCode);
767
- if (error.name === 'RefusedError') { process.stderr.write(`❌ ${error.message}\n`); process.exit(1); }
768
- process.stderr.write(`❌ Unexpected: ${error.message}\n`);
769
- process.exit(1);
770
- });
771
- // TCP-S3 / E3-S8: where the server is reachable, printed when the assignment arrives
772
- handle.on('assigned', ({ tcpAliasFqdn, srvProvisioned, srvFqdn, fqdn, publicPort, aliasRequestedButFailed, portMoved }) => {
773
- // Story 2.11 c3: naming a port labelled for another address moved its label here
774
- if (portMoved?.from) process.stdout.write(`Port ${portMoved.port} moved from ${portMoved.from} to ${portMoved.to}.\n`);
775
- const mc = minecraftMoveLine(portMoved); // Story 1.7 r8
776
- if (mc) process.stdout.write(mc);
777
- if (tcpAliasFqdn) {
778
- process.stdout.write(`Your TCP server is available at:\n\n`);
779
- process.stdout.write(` ${tcpAliasFqdn}\n`);
780
- process.stdout.write(` or\n`);
781
- process.stdout.write(` ${fqdn}:${publicPort}\n`);
782
- if (srvProvisioned && srvFqdn) {
783
- process.stdout.write(`\n Minecraft clients can connect to: ${srvFqdn.replace('_minecraft._tcp.', '')} (SRV record)\n`);
784
- }
785
- } else if (srvProvisioned && srvFqdn) {
786
- process.stdout.write(`Your TCP server is available at:\n\n`);
787
- process.stdout.write(` ${fqdn}:${publicPort}\n`);
788
- process.stdout.write(`\n Minecraft clients can connect to: ${srvFqdn.replace('_minecraft._tcp.', '')} (SRV record, no port needed)\n`);
789
- } else if (aliasRequestedButFailed) {
790
- process.stdout.write(`Your TCP server is available at:\n\n`);
791
- process.stdout.write(` ${fqdn}:${publicPort}\n`);
792
- process.stdout.write(` (alias unavailable; using host:port only)\n`);
793
- } else {
794
- process.stdout.write(`Your TCP server is available at:\n\n`);
795
- process.stdout.write(` ${fqdn}:${publicPort}\n`);
796
- }
797
- });
798
-
799
- try {
800
- await handle.open();
801
- } catch (error) {
802
- if (error.code === 'address_in_use') exitInUse(error.details); // Story 1.9
803
- const d = error.details || {};
804
- switch (error.code) {
805
- case 'control_plane_connect_failed': process.stderr.write(`Tunnel command failed: ${error.message}\n`); break;
806
- 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;
807
- case 'tcp_port_already_in_use': process.stderr.write(`External port ${d.requestedPort} is already in use by another active tunnel.\n`); break;
808
- case 'tcp_port_block_exhausted_for_tenant':
809
- case 'tcp_port_block_exhausted': process.stderr.write(`All 10 ports in your block ${d.blockStart}–${d.blockEnd} are currently in use.\n`); break;
810
- case 'tcp_port_capacity_exhausted': process.stderr.write(`Relay TCP port capacity exhausted. Please retry later.\n`); break;
811
- case 'tenant_tcp_lease_limit_reached': process.stderr.write(`Tenant TCP lease limit reached on relay ${d.relayId}\n`); break;
812
- case 'assignment_failed': process.stderr.write(`❌ Tunnel assignment failed: ${error.message}\n`); break;
813
- case 'tunnel_connect_failed': break; // TCP has always exited here without a message
814
- default: process.stderr.write(`❌ Unexpected: ${error?.message || String(error)}\n`);
815
- }
816
- process.exit(1);
817
- }
818
- const assignment = handle.assignment;
819
-
820
- process.stdout.write(`🔌 TCP tunnel active (ready for connections)\n`);
821
- process.stdout.write(` Target: 127.0.0.1:${localPort}\n`);
822
- // QPA-CLI-12: Lease and relay info only shown with LOG_LEVEL=info or higher
823
- const logLevel = (process.env.ASYX_LOG_LEVEL || process.env.LOG_LEVEL || 'warn').toLowerCase();
824
- if (logLevel === 'info' || logLevel === 'debug') {
825
- process.stdout.write(` Relay: ${assignment.relayId}\n`);
826
- const leaseMinutes = Math.floor(assignment.leaseMs / 60000);
827
- process.stdout.write(` Lease window: ${leaseMinutes} minutes\n`);
828
- }
829
- process.stdout.write(` Press Ctrl+C to stop\n`);
830
-
831
- // CLI-IMG-WSReconnect: Set up graceful shutdown
832
- let shuttingDown = false;
833
- const onSig = async (sig) => {
834
- if (shuttingDown) return;
835
- shuttingDown = true;
836
- logger.info("cli.signal.shutdown", { sig });
837
- process.stdout.write(`\nsignal ${sig} — shutting down…\n`);
838
- const killer = setTimeout(() => {
839
- logger.error("tunnel.close.timeout", {});
840
- process.stderr.write("tunnel.close() timed out; forcing exit\n");
841
- process.exit(0);
842
- }, 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;
843
641
  try {
844
- await handle.close();
845
- } catch (e) {
846
- logger.debug('tunnel.shutdown.error', { error: e.message });
847
- }
848
- clearTimeout(killer);
849
- process.exit(0);
850
- };
851
- process.once("SIGINT", onSig);
852
- process.once("SIGTERM", onSig);
853
-
854
- // Keep process alive until SIGINT/SIGTERM
855
- 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(() => { });
856
788
  }
857
-
858
- /**
859
- * UDP tunnel implementation (UDP-S1: CLI – UDP entrypoint & WS connect).
860
- * Builds and sends MQTT cmd/open payload with protocol:"udp" and tunnelMode:"udpWs-v1".
861
- * Reuses existing MQTT control-plane infrastructure.
862
- * UDP-S13: --port is the app's listening port (targetPort), CLI never binds it.
863
- * @param {number} targetPort - Target port of the local UDP app (from --port)
864
- * @param {number} [requestedExternalPort] - Optional requested external port
865
- * @param {string} [targetHost] - Target host (defaults to 127.0.0.1, must be loopback)
866
- */
867
789
  async function udpTunnel(targetPort, requestedExternalPort = null, targetHost = '127.0.0.1') {
868
- logger.info('cli.udp.start', { targetPort, requestedExternalPort, targetHost });
869
- process.stdout.write(`⚙️ Initializing UDP tunnel to ${targetHost}:${targetPort}…\n`);
870
-
871
- // UDP-S13: --port is targetPort, not a port we bind to
872
- logger.info('cli.udp.target', { target: `${targetHost}:${targetPort}` });
873
-
874
- const { loadAwsIotConfig } = await import("../lib/aws-iot-config.js"); // Story 12.2: apps too
875
- const { readFileSync } = await import("node:fs");
876
-
877
- // 1) Load IoT config (throws with clear messages if misconfigured)
878
- let cfg;
879
- try {
880
- cfg = loadAwsIotConfig();
881
- } catch (e) {
882
- logger.error("config.error", { error: e?.message || String(e) });
883
- process.stderr.write(`Config error: ${e?.message || e}\n`);
884
- process.exit(1);
885
- }
886
-
887
- logger.info("cli.udp.control_plane.establish", {});
888
- process.stdout.write(`🔐 Negotiating control-plane security…\n`);
889
-
890
- // Story 12.1 (step 2b): the UDP flow lives in @asyx/tunnel-core; the CLI prints its events and
891
- // maps its error codes to the same messages and exit codes as before.
892
- const { createUdpTunnel } = await import("#tunnel-core/flows/udp.js");
893
- const handle = createUdpTunnel({
894
- waitIfInUse: tunnelOutput.wait === true, // Story 1.9
895
- credentials: { endpoint: cfg.endpoint, clientId: cfg.clientId, ca: readFileSync(cfg.caPath), cert: readFileSync(cfg.certPath), key: readFileSync(cfg.keyPath) },
896
- targetPort,
897
- targetHost,
898
- requestedExternalPort,
899
- logger,
900
- onObserve: (line) => console.log(line), // ASYX_DEBUG=1 ingress lines, printed as before
901
- });
902
- handle.on('notice', (n) => { if (n?.code === 'address_in_use_waiting') printWaiting(n); }); // Story 1.9
903
- // Story 3.13: one line when a closed lease is reopened by itself, and why when it cannot be
904
- handle.on('reopened', (r) => process.stdout.write(`↻ The tunnel's lease was closed; reopened it${r?.publicPort ? ` on the same port ${r.publicPort}` : ''}.\n`));
905
- 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`));
906
- // QPA-CLI-11: Vault UX messaging - Control-plane sealed
907
- handle.on('control-connected', () => process.stdout.write("✅ Control-plane sealed\n"));
908
- handle.on('control-offline', ({ reason }) => process.stderr.write(`[mqtt] Control-plane connection lost: ${reason}\n`));
909
- handle.on('control-fatal', ({ reason }) => {
910
- process.stderr.write(`❌ Fatal control-plane error: ${reason}\n`);
911
- process.exit(1);
912
- });
913
- handle.on('closed', ({ error }) => {
914
- if (!error) return;
915
- if (error.code === 'setup_required') { process.stderr.write(`❌ ${error.message}\n`); process.exit(2); }
916
- // Story 12.1: the tunnel ended where it used to call process.exit; same code, no message
917
- if (error.details?.exitCode !== undefined) process.exit(error.details.exitCode);
918
- if (error.name === 'RefusedError') { process.stderr.write(`❌ ${error.message}\n`); process.exit(1); }
919
- process.stderr.write(`❌ Unexpected: ${error.message}\n`);
920
- process.exit(1);
921
- });
922
-
923
- try {
924
- await handle.open();
925
- } catch (error) {
926
- if (error.code === 'address_in_use') exitInUse(error.details); // Story 1.9
927
- switch (error.code) {
928
- case 'control_plane_connect_failed': process.stderr.write(`Tunnel command failed: ${error.message}\n`); break;
929
- case 'udp_relay_unavailable': process.stderr.write(`❌ ${error.message}\n`); break;
930
- case 'assignment_failed': process.stderr.write(`❌ Tunnel assignment failed: ${error.message}\n`); break;
931
- case 'tunnel_connect_failed': process.stderr.write(`❌ Tunnel connection failed: ${error.message}\n`); break;
932
- default: process.stderr.write(`❌ Unexpected: ${error?.message || String(error)}\n`);
933
- }
934
- process.exit(1);
935
- }
936
- const assignment = handle.assignment;
937
-
938
- // Tunnel live message (UDP-S13: both fqdn and fqdn:publicPort; the CLI does not bind the service port)
939
- 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
940
- process.stdout.write(`🔌 UDP tunnel active (ready for datagrams)\n`);
941
- process.stdout.write(` App target: ${targetHost}:${targetPort}\n`);
942
- if (assignment.fqdn) {
943
- process.stdout.write(` Your UDP server is available at:\n`);
944
- process.stdout.write(` ${assignment.fqdn}\n`);
945
- if (assignment.publicPort) {
946
- process.stdout.write(` ${assignment.fqdn}:${assignment.publicPort}\n`);
947
- }
948
- } else if (assignment.publicPort) {
949
- process.stdout.write(` Public port: ${assignment.publicPort}\n`);
950
- }
951
- // QPA-CLI-12: Lease and relay info only shown with LOG_LEVEL=info or higher
952
- const logLevel = (process.env.ASYX_LOG_LEVEL || process.env.LOG_LEVEL || 'warn').toLowerCase();
953
- if (logLevel === 'info' || logLevel === 'debug') {
954
- process.stdout.write(` Relay: ${assignment.relayId}\n`);
955
- const leaseMinutes = Math.floor(assignment.leaseMs / 60000);
956
- process.stdout.write(` Lease window: ${leaseMinutes} minutes\n`);
957
- }
958
- process.stdout.write(` Press Ctrl+C to stop\n`);
959
-
960
- // CLI-IMG-WSReconnect: Set up graceful shutdown
961
- let shuttingDown = false;
962
- const onSig = async (sig) => {
963
- if (shuttingDown) return;
964
- shuttingDown = true;
965
- logger.info("cli.signal.shutdown", { sig });
966
- process.stdout.write(`\nsignal ${sig} — shutting down…\n`);
967
- const killer = setTimeout(() => {
968
- logger.error("tunnel.close.timeout", {});
969
- process.stderr.write("tunnel.close() timed out; forcing exit\n");
970
- process.exit(0);
971
- }, 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;
972
796
  try {
973
- await handle.close();
974
- } catch (e) {
975
- logger.debug('tunnel.shutdown.error', { error: e.message });
976
- }
977
- clearTimeout(killer);
978
- process.exit(0);
979
- };
980
- process.once("SIGINT", onSig);
981
- process.once("SIGTERM", onSig);
982
-
983
- // Keep process alive until SIGINT/SIGTERM
984
- 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(() => { });
985
912
  }
986
-
987
913
  function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }
988
-
989
- // Story 11.2: exp claim (seconds) of an assignment token, or null
990
-
991
- /** Defect 11.47: the HTTP live line names the public address visitors use, then the local port. */
992
914
  export function httpLiveLines(assignment, localPort) {
993
- const publicHost = typeof assignment?.fqdn === 'string' && assignment.fqdn.trim() ? assignment.fqdn.trim() : null;
994
- return publicHost
995
- ? `🌐 Tunnel live at https://${publicHost}\n Forwarding to http://localhost:${localPort}\n`
996
- : `🌐 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`;
997
919
  }
998
-
999
- /** Story 1.7 r8: what happened to the port's Minecraft record when its label moved (TCP). */
1000
920
  export function minecraftMoveLine(portMoved) {
1001
- const m = portMoved?.minecraft;
1002
- if (!portMoved?.from || !m) return '';
1003
- const to = portMoved.toHostname || portMoved.to;
1004
- const from = portMoved.fromHostname || portMoved.from;
1005
- switch (m.status) {
1006
- case 'moved': return `Minecraft players now find it at ${to}. For a few minutes ${from} may still lead there.\n`;
1007
- 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`;
1008
- case 'pending': return `The Minecraft record is not updated yet; it follows within a few minutes.\n`;
1009
- 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`;
1010
- default: return '';
1011
- }
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
+ }
1012
933
  }