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.
- package/AGENTS.md +42 -0
- package/bin/asyx.js +1 -1
- package/package.json +6 -3
- package/src/commands/account.js +80 -71
- package/src/commands/app.js +317 -151
- package/src/commands/in-use-messages.js +47 -48
- package/src/commands/mqtt-broker.js +36 -49
- package/src/commands/mqtt.js +111 -149
- package/src/commands/name.js +24 -22
- package/src/commands/reject-messages.js +123 -123
- package/src/commands/setup.js +107 -131
- package/src/commands/sts.js +45 -61
- package/src/commands/tunnel.js +853 -931
- package/src/commands/validate-target-host.js +36 -59
- package/src/lib/aws-iot-config.js +30 -0
- package/src/lib/certs.js +15 -18
- package/src/lib/csr.js +107 -182
- package/src/lib/device.js +26 -37
- package/src/lib/ids.js +1 -2
- package/src/lib/naming.js +74 -68
- package/src/lib/pairing.js +10 -11
- package/src/lib/shared-transport.js +5 -9
- package/src/main.js +63 -53
- package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneClient.js +25 -287
- package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneTransport.js +0 -72
- package/vendor/tunnel-core/dist/control-plane/session.js +0 -20
- package/vendor/tunnel-core/dist/errors.js +0 -19
- package/vendor/tunnel-core/dist/flows/account.js +1 -6
- package/vendor/tunnel-core/dist/flows/goodbye.js +0 -4
- package/vendor/tunnel-core/dist/flows/http.js +24 -112
- package/vendor/tunnel-core/dist/flows/identity.js +11 -10
- package/vendor/tunnel-core/dist/flows/in-use.js +0 -6
- package/vendor/tunnel-core/dist/flows/reopen.js +0 -4
- package/vendor/tunnel-core/dist/flows/tcp.js +18 -84
- package/vendor/tunnel-core/dist/flows/udp.js +15 -52
- package/vendor/tunnel-core/dist/lib/fingerprint.js +38 -42
- package/vendor/tunnel-core/dist/lib/jwt-verifier.js +14 -67
- package/vendor/tunnel-core/dist/lib/logger.js +1 -9
- package/vendor/tunnel-core/dist/lib/refresh-helpers.js +1 -22
- package/vendor/tunnel-core/dist/lifecycle.js +1 -8
- package/vendor/tunnel-core/dist/mqtt/awaiter-map.js +1 -53
- package/vendor/tunnel-core/dist/mqtt/events/handlers.js +10 -64
- package/vendor/tunnel-core/dist/mqtt/events/index.js +3 -36
- package/vendor/tunnel-core/dist/mqtt/events/schemas.js +0 -1
- package/vendor/tunnel-core/dist/mqtt/ingress.js +0 -60
- package/vendor/tunnel-core/dist/state/assignment.js +6 -122
- package/vendor/tunnel-core/dist/state/instance-registry.js +0 -63
- package/vendor/tunnel-core/dist/tcp-v1/framing.js +2 -64
- package/vendor/tunnel-core/dist/tunnel/http-tunnel.js +64 -331
- package/vendor/tunnel-core/dist/tunnel/httpws-constants.js +5 -14
- package/vendor/tunnel-core/dist/tunnel/reconnect.js +10 -50
- package/vendor/tunnel-core/dist/tunnel/request-sink.js +0 -16
- package/vendor/tunnel-core/dist/tunnel/tcp-tunnel.js +32 -195
- package/vendor/tunnel-core/dist/tunnel/udp-tunnel.js +28 -153
- package/vendor/tunnel-core/dist/tunnel/ws-control.js +4 -39
- package/vendor/tunnel-core/dist/types.js +0 -2
- package/vendor/tunnel-core/dist/udp-v1/framing.js +2 -64
- package/vendor/tunnel-core/package.json +0 -25
- package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneClient.d.ts +0 -273
- package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneTransport.d.ts +0 -79
- package/vendor/tunnel-core/dist/control-plane/session.d.ts +0 -55
- package/vendor/tunnel-core/dist/errors.d.ts +0 -49
- package/vendor/tunnel-core/dist/flows/account.d.ts +0 -24
- package/vendor/tunnel-core/dist/flows/goodbye.d.ts +0 -10
- package/vendor/tunnel-core/dist/flows/http.d.ts +0 -61
- package/vendor/tunnel-core/dist/flows/identity.d.ts +0 -23
- package/vendor/tunnel-core/dist/flows/in-use.d.ts +0 -27
- package/vendor/tunnel-core/dist/flows/reopen.d.ts +0 -9
- package/vendor/tunnel-core/dist/flows/tcp.d.ts +0 -85
- package/vendor/tunnel-core/dist/flows/udp.d.ts +0 -52
- package/vendor/tunnel-core/dist/lib/adapt-logger.d.ts +0 -2
- package/vendor/tunnel-core/dist/lib/fingerprint.d.ts +0 -145
- package/vendor/tunnel-core/dist/lib/jwt-verifier.d.ts +0 -27
- package/vendor/tunnel-core/dist/lib/logger.d.ts +0 -9
- package/vendor/tunnel-core/dist/lib/refresh-helpers.d.ts +0 -16
- package/vendor/tunnel-core/dist/lifecycle.d.ts +0 -24
- package/vendor/tunnel-core/dist/mqtt/awaiter-map.d.ts +0 -56
- package/vendor/tunnel-core/dist/mqtt/events/handlers.d.ts +0 -60
- package/vendor/tunnel-core/dist/mqtt/events/index.d.ts +0 -1
- package/vendor/tunnel-core/dist/mqtt/events/schemas.d.ts +0 -498
- package/vendor/tunnel-core/dist/mqtt/ingress.d.ts +0 -63
- package/vendor/tunnel-core/dist/state/assignment.d.ts +0 -136
- package/vendor/tunnel-core/dist/state/instance-registry.d.ts +0 -88
- package/vendor/tunnel-core/dist/tcp-v1/framing.d.ts +0 -43
- package/vendor/tunnel-core/dist/tunnel/http-tunnel.d.ts +0 -140
- package/vendor/tunnel-core/dist/tunnel/httpws-constants.d.ts +0 -13
- package/vendor/tunnel-core/dist/tunnel/reconnect.d.ts +0 -76
- package/vendor/tunnel-core/dist/tunnel/request-sink.d.ts +0 -40
- package/vendor/tunnel-core/dist/tunnel/tcp-tunnel.d.ts +0 -92
- package/vendor/tunnel-core/dist/tunnel/udp-tunnel.d.ts +0 -93
- package/vendor/tunnel-core/dist/tunnel/ws-control.d.ts +0 -22
- package/vendor/tunnel-core/dist/types.d.ts +0 -24
- package/vendor/tunnel-core/dist/udp-v1/framing.d.ts +0 -41
|
@@ -1,14 +1,6 @@
|
|
|
1
|
-
// Story 12.1 (step 2b, sub-step 3; TypeScript in r3): the HTTP tunnel flow, moved from httpTunnel() and
|
|
2
|
-
// connectToRelay() in clients/asyx/src/commands/tunnel.js. Behaviour is unchanged; what the CLI
|
|
3
|
-
// printed or exited on is now an event or a typed error, and the CLI maps both to its old wording:
|
|
4
|
-
// 'control-connected' / 'control-offline' { reason } / 'control-fatal' { reason, error }
|
|
5
|
-
// state events: 'opening', 'live', and a final 'closed' { error } when a reply ends the tunnel
|
|
6
|
-
// after it opened (SetupRequiredError, RefusedError, InternalError).
|
|
7
|
-
// open() rejects with ConnectionError control_plane_connect_failed | assignment_failed |
|
|
8
|
-
// tunnel_connect_failed. The renewal callback (in-band reauth, reconnect fallback) is unchanged.
|
|
9
1
|
import { randomUUID } from 'node:crypto';
|
|
10
|
-
import { sayGoodbye } from './goodbye.js';
|
|
11
|
-
import { ReopenLimiter, reopenPayload } from './reopen.js';
|
|
2
|
+
import { sayGoodbye } from './goodbye.js';
|
|
3
|
+
import { ReopenLimiter, reopenPayload } from './reopen.js';
|
|
12
4
|
import { LifecycleEmitter } from '../lifecycle.js';
|
|
13
5
|
import { ConnectionError, SetupRequiredError, RefusedError, InternalError } from '../errors.js';
|
|
14
6
|
import { createControlPlaneSession } from '../control-plane/session.js';
|
|
@@ -42,9 +34,7 @@ export class HttpTunnelHandle extends LifecycleEmitter {
|
|
|
42
34
|
opts;
|
|
43
35
|
tunnel = null;
|
|
44
36
|
mqttClient = null;
|
|
45
|
-
/** Story 1.9: one id for this tunnel across its opens (a re-open is never "another tunnel"). */
|
|
46
37
|
tunnelSession = randomUUID();
|
|
47
|
-
/** Story 3.13: reopens after a closed lease, at most 3 in 10 minutes. */
|
|
48
38
|
reopenLimiter = new ReopenLimiter();
|
|
49
39
|
core = null;
|
|
50
40
|
assignment = null;
|
|
@@ -52,11 +42,9 @@ export class HttpTunnelHandle extends LifecycleEmitter {
|
|
|
52
42
|
super();
|
|
53
43
|
this.opts = { secGroupSlug: null, ...o };
|
|
54
44
|
}
|
|
55
|
-
/** Story 3.13: tell the cloud this tunnel stops on purpose (closes its lease at once); waits at most 2 s. */
|
|
56
45
|
async goodbye(timeoutMs = 2000) {
|
|
57
46
|
return sayGoodbye(this, timeoutMs);
|
|
58
47
|
}
|
|
59
|
-
/** Connect the control plane, get a lease and open the data plane; rejects with a ConnectionError. */
|
|
60
48
|
async open() {
|
|
61
49
|
const { credentials, localPort, secGroupSlug, logger } = this.opts;
|
|
62
50
|
this.setState('opening');
|
|
@@ -65,11 +53,9 @@ export class HttpTunnelHandle extends LifecycleEmitter {
|
|
|
65
53
|
const { MqttControlPlaneTransport } = await import('../control-plane/MqttControlPlaneTransport.js');
|
|
66
54
|
const { MessageIngress } = await import('../mqtt/ingress.js');
|
|
67
55
|
const { dispatch: dispatchEvt } = await import('../mqtt/events/index.js');
|
|
68
|
-
// CLI-IMG-ControlPlane-Watchdog: Add configurable timeout
|
|
69
56
|
const CONTROL_PLANE_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_TIMEOUT_MS || '60000', 10);
|
|
70
57
|
const baseClientId = credentials.clientId;
|
|
71
58
|
const instanceIdRef = { instanceId: null };
|
|
72
|
-
// QPA-CLI-01: tunnel reference for the reconnect hook and the renewal callback
|
|
73
59
|
const tunnelInstanceRef = { tunnel: null };
|
|
74
60
|
let coordinatorCoreRef = null;
|
|
75
61
|
let coordinatorIngressRef = null;
|
|
@@ -82,11 +68,9 @@ export class HttpTunnelHandle extends LifecycleEmitter {
|
|
|
82
68
|
if (!coordinatorCoreRef || !coordinatorIngressRef) {
|
|
83
69
|
throw new Error("Coordinator not available for refresh");
|
|
84
70
|
}
|
|
85
|
-
// TPB-12: Get instanceId from mqttClient (captured in closure)
|
|
86
71
|
const refreshInstanceId = mqttClient.getClientId();
|
|
87
72
|
const { getAssignment, readRefreshAssignment } = await import('../state/assignment.js');
|
|
88
73
|
const { getFpHash } = await import('../lib/fingerprint.js');
|
|
89
|
-
// TPB-12: Get assignment for this specific instance
|
|
90
74
|
const currentAssignment = getAssignment(refreshInstanceId);
|
|
91
75
|
if (!currentAssignment) {
|
|
92
76
|
throw new Error(`No current assignment for refresh (instanceId: ${refreshInstanceId})`);
|
|
@@ -95,36 +79,28 @@ export class HttpTunnelHandle extends LifecycleEmitter {
|
|
|
95
79
|
if (!leaseId) {
|
|
96
80
|
throw new Error("No leaseId in current assignment");
|
|
97
81
|
}
|
|
98
|
-
|
|
99
|
-
const refreshRequestId = `refresh-${randomUUID()}` /* Defect 11.27: unique across processes (was Date.now()) */;
|
|
82
|
+
const refreshRequestId = `refresh-${randomUUID()}`;
|
|
100
83
|
const fingerprint = await getFpHash(deviceIdRef);
|
|
101
|
-
// TPB-12: Include instanceId in refresh payload
|
|
102
84
|
const refreshPayload = {
|
|
103
85
|
requestId: refreshRequestId,
|
|
104
|
-
instanceId: refreshInstanceId,
|
|
86
|
+
instanceId: refreshInstanceId,
|
|
105
87
|
refreshOf: leaseId,
|
|
106
88
|
proto: 'http',
|
|
107
89
|
localPort: localPortRef,
|
|
108
90
|
clientId: deviceIdRef,
|
|
109
91
|
...fingerprint
|
|
110
92
|
};
|
|
111
|
-
// QPA-04: Include secGroupSlug in refresh payload if provided
|
|
112
93
|
if (secGroupSlugRef) {
|
|
113
94
|
refreshPayload.secGroupSlug = secGroupSlugRef;
|
|
114
95
|
}
|
|
115
|
-
// Cancel any existing awaiters for this leaseId before starting a new refresh
|
|
116
|
-
// This prevents duplicate awaiters from accumulating when multiple refresh attempts happen
|
|
117
96
|
const ackTopic = `asyx/tunnel/clients/${deviceIdRef}/evt/ack`;
|
|
118
97
|
const cancelled = coordinatorIngressRef.cancelAwaitersByCriteria((awaiter) => {
|
|
119
|
-
// Test if this awaiter matches open_ack messages (likely a stale refresh awaiter)
|
|
120
98
|
try {
|
|
121
99
|
const testMessage = {
|
|
122
100
|
topic: ackTopic,
|
|
123
101
|
payload: { type: 'open_ack', requestId: 'test' }
|
|
124
102
|
};
|
|
125
|
-
// If the criteria matches open_ack messages, it's likely a refresh awaiter
|
|
126
103
|
const matches = awaiter.criteria(testMessage);
|
|
127
|
-
// Only cancel if it matches open_ack (we don't want to cancel other awaiters)
|
|
128
104
|
return matches;
|
|
129
105
|
}
|
|
130
106
|
catch {
|
|
@@ -138,28 +114,22 @@ export class HttpTunnelHandle extends LifecycleEmitter {
|
|
|
138
114
|
reason: 'new_refresh_starting'
|
|
139
115
|
});
|
|
140
116
|
}
|
|
141
|
-
// Wait for subscription to be ready before publishing (prevents race where ack is published before subscription is active)
|
|
142
|
-
// Only wait if subscription is not ready (e.g., after reconnect before resubscription completes)
|
|
143
117
|
if (!subscriptionReadyRef.ready) {
|
|
144
118
|
logger.debug('jwt.refresh.waiting_for_subscription', { refreshRequestId });
|
|
145
|
-
// Wait up to 2 seconds for subscription to be ready (should be immediate after subscribe() resolves)
|
|
146
119
|
const maxWait = 2000;
|
|
147
120
|
const startWait = Date.now();
|
|
148
121
|
while (!subscriptionReadyRef.ready && (Date.now() - startWait) < maxWait) {
|
|
149
122
|
await new Promise(resolve => setTimeout(resolve, 50));
|
|
150
123
|
}
|
|
151
124
|
if (!subscriptionReadyRef.ready) {
|
|
152
|
-
// QPA-CLI-10: Telemetry logs default to debug for quiet mode
|
|
153
125
|
logger.debug('jwt.refresh.subscription_not_ready', { refreshRequestId, waited: Date.now() - startWait });
|
|
154
126
|
}
|
|
155
127
|
else {
|
|
156
128
|
logger.debug('jwt.refresh.subscription_ready', { refreshRequestId, waited: Date.now() - startWait });
|
|
157
129
|
}
|
|
158
130
|
}
|
|
159
|
-
// Set up topic and wait for ack
|
|
160
131
|
const cmdOpenTopic = `asyx/tunnel/clients/${deviceIdRef}/cmd/open`;
|
|
161
132
|
const ACK_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_ACK_TIMEOUT_MS || "20000", 10);
|
|
162
|
-
// Log awaiter registration for debugging
|
|
163
133
|
logger.debug('jwt.refresh.awaiter.registered', {
|
|
164
134
|
refreshRequestId,
|
|
165
135
|
instanceId: refreshInstanceId,
|
|
@@ -172,7 +142,6 @@ export class HttpTunnelHandle extends LifecycleEmitter {
|
|
|
172
142
|
const parsed = message.payload;
|
|
173
143
|
const isAck = parsed && parsed.type === 'open_ack' && parsed.requestId === refreshRequestId;
|
|
174
144
|
const isReject = parsed && parsed.type === 'open_reject' && parsed.requestId === refreshRequestId;
|
|
175
|
-
// Log matching attempts for debugging
|
|
176
145
|
if (parsed?.type === 'open_ack' || parsed?.type === 'open_reject') {
|
|
177
146
|
logger.debug('jwt.refresh.awaiter.checking', {
|
|
178
147
|
refreshRequestId,
|
|
@@ -183,7 +152,6 @@ export class HttpTunnelHandle extends LifecycleEmitter {
|
|
|
183
152
|
topic: message.topic
|
|
184
153
|
});
|
|
185
154
|
}
|
|
186
|
-
// If we get a reject, throw an error so the awaiter rejects the promise
|
|
187
155
|
if (isReject) {
|
|
188
156
|
const reason = parsed.data?.reason || 'unknown';
|
|
189
157
|
if (reason === 'lease_closed' || reason === 'LEASE_CLOSED') {
|
|
@@ -192,7 +160,6 @@ export class HttpTunnelHandle extends LifecycleEmitter {
|
|
|
192
160
|
leaseClosedError.reason = reason;
|
|
193
161
|
throw leaseClosedError;
|
|
194
162
|
}
|
|
195
|
-
// For other reject reasons, also throw but with different code
|
|
196
163
|
const rejectError = new Error(`Refresh rejected: ${reason}`);
|
|
197
164
|
rejectError.code = 'REFRESH_REJECTED';
|
|
198
165
|
rejectError.reason = reason;
|
|
@@ -201,7 +168,6 @@ export class HttpTunnelHandle extends LifecycleEmitter {
|
|
|
201
168
|
return isAck;
|
|
202
169
|
}
|
|
203
170
|
catch (e) {
|
|
204
|
-
// If it's a lease_closed or refresh_rejected error, rethrow it
|
|
205
171
|
if (e.code === 'LEASE_CLOSED' || e.code === 'REFRESH_REJECTED') {
|
|
206
172
|
throw e;
|
|
207
173
|
}
|
|
@@ -212,25 +178,17 @@ export class HttpTunnelHandle extends LifecycleEmitter {
|
|
|
212
178
|
return false;
|
|
213
179
|
}
|
|
214
180
|
}, ACK_TIMEOUT_MS);
|
|
215
|
-
// Publish refresh request
|
|
216
|
-
// QPA-CLI-09: Catch ECONNRESET during publish to prevent fatal exit
|
|
217
181
|
const publishSuccess = await publishRefreshRequestWithErrorHandling(coordinatorCoreRef, cmdOpenTopic, refreshPayload, refreshRequestId, logger);
|
|
218
|
-
// If publish returned false, ECONNRESET was caught and buffered
|
|
219
|
-
// Throw an error that MqttControlPlaneClient recognizes as offline error
|
|
220
|
-
// This ensures refreshPending stays true and re-arm logic knows refresh is needed
|
|
221
|
-
// The error will be caught by MqttControlPlaneClient and buffered (not bubbled up)
|
|
222
182
|
if (publishSuccess === false) {
|
|
223
183
|
const bufferedError = new Error('Connection closed during refresh publish');
|
|
224
184
|
bufferedError.code = 'ECONNRESET';
|
|
225
185
|
throw bufferedError;
|
|
226
186
|
}
|
|
227
|
-
// Wait for ack with reconnect retry on timeout
|
|
228
187
|
let ackResult;
|
|
229
188
|
try {
|
|
230
189
|
ackResult = await ackPromise;
|
|
231
190
|
}
|
|
232
191
|
catch (error) {
|
|
233
|
-
// Check if this is a lease_closed error - don't retry, treat as fatal
|
|
234
192
|
if (error.code === 'LEASE_CLOSED' || error.code === 'REFRESH_REJECTED') {
|
|
235
193
|
logger.error('jwt.refresh.rejected', {
|
|
236
194
|
reason: error.reason || 'unknown',
|
|
@@ -239,22 +197,14 @@ export class HttpTunnelHandle extends LifecycleEmitter {
|
|
|
239
197
|
});
|
|
240
198
|
throw new Error(`Cannot refresh closed lease: ${error.reason || 'lease_closed'}`);
|
|
241
199
|
}
|
|
242
|
-
// Otherwise treat as timeout and retry
|
|
243
200
|
const timeoutError = error;
|
|
244
|
-
// QPA-CLI-07: On timeout, reconnect control-plane and retry once
|
|
245
|
-
// QPA-CLI-10: Telemetry logs default to debug for quiet mode
|
|
246
201
|
logger.debug('jwt.refresh.timeout', {
|
|
247
202
|
error: timeoutError.message,
|
|
248
203
|
action: 'reconnect_and_retry',
|
|
249
204
|
requestId: refreshRequestId
|
|
250
205
|
});
|
|
251
|
-
// Cancel any existing awaiters for this requestId before retrying
|
|
252
|
-
// This prevents duplicate awaiters from accumulating when retrying
|
|
253
206
|
const cancelled = coordinatorIngressRef.cancelAwaitersByCriteria((awaiter) => {
|
|
254
|
-
// Test if this awaiter matches the same requestId
|
|
255
207
|
try {
|
|
256
|
-
// Create a test message to see if the awaiter's criteria would match
|
|
257
|
-
// We can't directly inspect the criteria, so we test it with a mock message
|
|
258
208
|
const testMessage = {
|
|
259
209
|
topic: `asyx/tunnel/clients/${deviceIdRef}/evt/ack`,
|
|
260
210
|
payload: { type: 'open_ack', requestId: refreshRequestId }
|
|
@@ -271,9 +221,7 @@ export class HttpTunnelHandle extends LifecycleEmitter {
|
|
|
271
221
|
cancelledCount: cancelled
|
|
272
222
|
});
|
|
273
223
|
}
|
|
274
|
-
// Force reconnect to get fresh MQTT session
|
|
275
224
|
await mqttClient.forceReconnect('ack_timeout');
|
|
276
|
-
// Re-register awaiter with same timeout after reconnect; ack might already be queued
|
|
277
225
|
logger.debug('jwt.refresh.awaiter.retry_registered', {
|
|
278
226
|
refreshRequestId,
|
|
279
227
|
timeoutMs: ACK_TIMEOUT_MS
|
|
@@ -283,7 +231,6 @@ export class HttpTunnelHandle extends LifecycleEmitter {
|
|
|
283
231
|
const parsed = message.payload;
|
|
284
232
|
const isAck = parsed && parsed.type === 'open_ack' && parsed.requestId === refreshRequestId;
|
|
285
233
|
const isReject = parsed && parsed.type === 'open_reject' && parsed.requestId === refreshRequestId;
|
|
286
|
-
// Log matching attempts for debugging
|
|
287
234
|
if (parsed?.type === 'open_ack' || parsed?.type === 'open_reject') {
|
|
288
235
|
logger.debug('jwt.refresh.awaiter.retry_checking', {
|
|
289
236
|
refreshRequestId,
|
|
@@ -294,7 +241,6 @@ export class HttpTunnelHandle extends LifecycleEmitter {
|
|
|
294
241
|
topic: message.topic
|
|
295
242
|
});
|
|
296
243
|
}
|
|
297
|
-
// If we get a reject, throw an error so the awaiter rejects the promise
|
|
298
244
|
if (isReject) {
|
|
299
245
|
const reason = parsed.data?.reason || 'unknown';
|
|
300
246
|
if (reason === 'lease_closed' || reason === 'LEASE_CLOSED') {
|
|
@@ -303,7 +249,6 @@ export class HttpTunnelHandle extends LifecycleEmitter {
|
|
|
303
249
|
leaseClosedError.reason = reason;
|
|
304
250
|
throw leaseClosedError;
|
|
305
251
|
}
|
|
306
|
-
// For other reject reasons, also throw but with different code
|
|
307
252
|
const rejectError = new Error(`Refresh rejected: ${reason}`);
|
|
308
253
|
rejectError.code = 'REFRESH_REJECTED';
|
|
309
254
|
rejectError.reason = reason;
|
|
@@ -312,7 +257,6 @@ export class HttpTunnelHandle extends LifecycleEmitter {
|
|
|
312
257
|
return isAck;
|
|
313
258
|
}
|
|
314
259
|
catch (e) {
|
|
315
|
-
// If it's a lease_closed or refresh_rejected error, rethrow it
|
|
316
260
|
if (e.code === 'LEASE_CLOSED' || e.code === 'REFRESH_REJECTED') {
|
|
317
261
|
throw e;
|
|
318
262
|
}
|
|
@@ -325,11 +269,9 @@ export class HttpTunnelHandle extends LifecycleEmitter {
|
|
|
325
269
|
}, ACK_TIMEOUT_MS);
|
|
326
270
|
try {
|
|
327
271
|
ackResult = await retryAckPromise;
|
|
328
|
-
// QPA-CLI-10: Telemetry logs default to debug for quiet mode
|
|
329
272
|
logger.debug('jwt.refresh.timeout.retry_success', { requestId: refreshRequestId });
|
|
330
273
|
}
|
|
331
274
|
catch (retryError) {
|
|
332
|
-
// Check if this is a lease_closed error - don't retry, treat as fatal
|
|
333
275
|
if (retryError.code === 'LEASE_CLOSED' || retryError.code === 'REFRESH_REJECTED') {
|
|
334
276
|
logger.error('jwt.refresh.rejected.retry', {
|
|
335
277
|
reason: retryError.reason || 'unknown',
|
|
@@ -346,14 +288,9 @@ export class HttpTunnelHandle extends LifecycleEmitter {
|
|
|
346
288
|
throw new Error(`Refresh timeout after reconnect: ${retryError.message}`);
|
|
347
289
|
}
|
|
348
290
|
}
|
|
349
|
-
// Get new assignment for this client id. An unkeyed read is null once
|
|
350
|
-
// rotation has left more than one map entry.
|
|
351
291
|
const { assignment: newAssignment, expMs } = readRefreshAssignment(refreshInstanceId);
|
|
352
292
|
const newJwt = newAssignment.jwt;
|
|
353
|
-
// QPA-CLI-05: Notify HttpTunnel that new JWT is available
|
|
354
|
-
// HttpTunnel will handle WebSocket update (in-band reauth or reconnect)
|
|
355
293
|
if (tunnelInstanceRef.tunnel) {
|
|
356
|
-
// Update HttpTunnel with new JWT and assignment
|
|
357
294
|
tunnelInstanceRef.tunnel.jwt = newJwt;
|
|
358
295
|
tunnelInstanceRef.tunnel.requestId = newAssignment.requestId;
|
|
359
296
|
tunnelInstanceRef.tunnel.relayUrl = newAssignment.relayUrl;
|
|
@@ -362,11 +299,7 @@ export class HttpTunnelHandle extends LifecycleEmitter {
|
|
|
362
299
|
'X-Asyx-DeviceId': deviceIdRef,
|
|
363
300
|
'X-Asyx-RequestId': newAssignment.requestId
|
|
364
301
|
};
|
|
365
|
-
// Update jwtMeta for HttpTunnel
|
|
366
302
|
tunnelInstanceRef.tunnel.jwtMeta = { token: newJwt, expMs };
|
|
367
|
-
// Note: recordRefresh is called in http-tunnel.js after in-band reauth succeeds
|
|
368
|
-
// to avoid double-counting when refresh happens via in-band reauth
|
|
369
|
-
// Try in-band reauth if WebSocket is open
|
|
370
303
|
if (tunnelInstanceRef.tunnel.ws && tunnelInstanceRef.tunnel.ws.readyState === 1) {
|
|
371
304
|
const prevJti = tunnelInstanceRef.tunnel.jwtMeta?.token
|
|
372
305
|
? tunnelInstanceRef.tunnel._extractJti(tunnelInstanceRef.tunnel.jwtMeta.token)
|
|
@@ -374,26 +307,20 @@ export class HttpTunnelHandle extends LifecycleEmitter {
|
|
|
374
307
|
try {
|
|
375
308
|
const reauthSuccess = await tunnelInstanceRef.tunnel.reauthInBand(newJwt, prevJti, 'timer');
|
|
376
309
|
if (reauthSuccess) {
|
|
377
|
-
// QPA-CLI-10: Telemetry logs default to debug for quiet mode
|
|
378
310
|
logger.debug('jwt.refresh.success', { method: 'in_band', leaseId: newAssignment.leaseId });
|
|
379
311
|
return expMs;
|
|
380
312
|
}
|
|
381
313
|
}
|
|
382
314
|
catch (reauthError) {
|
|
383
|
-
// QPA-CLI-10: Telemetry logs default to debug for quiet mode
|
|
384
315
|
logger.debug('jwt.reauth.exception', { error: reauthError.message });
|
|
385
316
|
}
|
|
386
317
|
}
|
|
387
|
-
// Fallback to reconnect
|
|
388
|
-
// QPA-CLI-10: Telemetry logs default to debug for quiet mode
|
|
389
318
|
logger.debug('jwt.refresh.reconnect', { leaseId: newAssignment.leaseId });
|
|
390
319
|
await tunnelInstanceRef.tunnel._attemptConnect();
|
|
391
320
|
}
|
|
392
|
-
// QPA-CLI-10: Telemetry logs default to debug for quiet mode
|
|
393
321
|
logger.debug('jwt.refresh.success', { method: 'reconnect', leaseId: newAssignment.leaseId });
|
|
394
322
|
return expMs;
|
|
395
323
|
};
|
|
396
|
-
// Story 3.13: set once the open request exists (below); used by the control plane and the tunnel.
|
|
397
324
|
const reopenRef = { fn: null };
|
|
398
325
|
const cpSession = createControlPlaneSession({
|
|
399
326
|
credentials,
|
|
@@ -408,8 +335,11 @@ export class HttpTunnelHandle extends LifecycleEmitter {
|
|
|
408
335
|
}
|
|
409
336
|
return r;
|
|
410
337
|
},
|
|
411
|
-
onLeaseClosed: async () => {
|
|
412
|
-
|
|
338
|
+
onLeaseClosed: async () => {
|
|
339
|
+
if (!reopenRef.fn)
|
|
340
|
+
throw new Error('reopen unavailable');
|
|
341
|
+
return reopenRef.fn();
|
|
342
|
+
},
|
|
413
343
|
instanceIdRef,
|
|
414
344
|
subscriptionReadyRef,
|
|
415
345
|
getTunnel: () => tunnelInstanceRef.tunnel,
|
|
@@ -422,7 +352,6 @@ export class HttpTunnelHandle extends LifecycleEmitter {
|
|
|
422
352
|
const transport = new MqttControlPlaneTransport(mqttClient);
|
|
423
353
|
const core = new MqttCore(transport, { canPublish: () => true, canSubscribe: () => true });
|
|
424
354
|
this.core = core;
|
|
425
|
-
// CLI-IMG-ControlPlane-Watchdog: helpers for HttpTunnel
|
|
426
355
|
const isControlPlaneConnected = () => mqttClient.isOnline();
|
|
427
356
|
const waitForControlPlane = () => {
|
|
428
357
|
if (mqttClient.isOnline())
|
|
@@ -448,7 +377,6 @@ export class HttpTunnelHandle extends LifecycleEmitter {
|
|
|
448
377
|
await mqttClient.connect();
|
|
449
378
|
}
|
|
450
379
|
};
|
|
451
|
-
// 3) Connect to control plane
|
|
452
380
|
try {
|
|
453
381
|
await mqttClient.connect();
|
|
454
382
|
}
|
|
@@ -456,17 +384,13 @@ export class HttpTunnelHandle extends LifecycleEmitter {
|
|
|
456
384
|
logger.error('mqtt.connect.failed', { error: e?.message || String(e) });
|
|
457
385
|
throw new ConnectionError('control_plane_connect_failed', e?.message || String(e), { cause: e });
|
|
458
386
|
}
|
|
459
|
-
// TPB-12: instanceId is the full MQTT clientId after connection
|
|
460
387
|
instanceIdRef.instanceId = mqttClient.getClientId();
|
|
461
388
|
const instanceId = instanceIdRef.instanceId;
|
|
462
389
|
logger.debug('cli.instance.registered', { instanceId, tunnelType: 'http', baseClientId });
|
|
463
|
-
// 4) Topics (baseClientId, not the session client id, keeps topics stable)
|
|
464
390
|
const evtWildcard = `asyx/tunnel/clients/${baseClientId}/evt/#`;
|
|
465
391
|
const cmdOpenTopic = `asyx/tunnel/clients/${baseClientId}/cmd/open`;
|
|
466
392
|
await core.subscribe(evtWildcard, 0);
|
|
467
|
-
// subscribe() resolves only after the broker acknowledges
|
|
468
393
|
subscriptionReadyRef.ready = true;
|
|
469
|
-
// 5) Message ingress and dispatcher
|
|
470
394
|
const ingress = new MessageIngress({ maxAwaiters: 100, observability: process.env.ASYX_DEBUG === '1', logger, onObserve: this.opts.onObserve });
|
|
471
395
|
ingress.setDispatcher(dispatchEvt);
|
|
472
396
|
const { registerInstance, setExpectedRequestId } = await import('../state/instance-registry.js');
|
|
@@ -477,10 +401,8 @@ export class HttpTunnelHandle extends LifecycleEmitter {
|
|
|
477
401
|
getAssignment: getAssignmentFn,
|
|
478
402
|
metadata: { baseClientId, localPort, secGroupSlug },
|
|
479
403
|
});
|
|
480
|
-
// QPA-CLI-05: coordinator references for the renewal callback
|
|
481
404
|
coordinatorCoreRef = core;
|
|
482
405
|
coordinatorIngressRef = ingress;
|
|
483
|
-
// A reply that ends the tunnel closes it with a typed error (the CLI used to print and exit here).
|
|
484
406
|
core.onMessage(async (m) => {
|
|
485
407
|
try {
|
|
486
408
|
await ingress.handleMessage(m);
|
|
@@ -500,24 +422,21 @@ export class HttpTunnelHandle extends LifecycleEmitter {
|
|
|
500
422
|
this.setState('closed', { error });
|
|
501
423
|
}
|
|
502
424
|
});
|
|
503
|
-
// 6) Publish cmd/open request (Story 1.9: asked again while the address is in use, see in-use.ts)
|
|
504
425
|
let requestId = '';
|
|
505
426
|
const { getFpHash } = await import('../lib/fingerprint.js');
|
|
506
427
|
const fingerprint = await getFpHash(credentials.clientId);
|
|
507
428
|
const openPayload = {
|
|
508
|
-
instanceId,
|
|
429
|
+
instanceId,
|
|
509
430
|
proto: 'http',
|
|
510
431
|
localPort,
|
|
511
432
|
clientId: credentials.clientId,
|
|
512
|
-
tunnelSession: this.tunnelSession,
|
|
433
|
+
tunnelSession: this.tunnelSession,
|
|
513
434
|
...fingerprint,
|
|
514
435
|
};
|
|
515
436
|
if (this.opts.replace === true)
|
|
516
|
-
openPayload.replace = true;
|
|
517
|
-
// QPA-04: Include secGroupSlug in cmd/open payload if provided
|
|
437
|
+
openPayload.replace = true;
|
|
518
438
|
if (secGroupSlug)
|
|
519
439
|
openPayload.secGroupSlug = secGroupSlug;
|
|
520
|
-
// 7) Wait for ack
|
|
521
440
|
const ACK_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_ACK_TIMEOUT_MS || '20000', 10);
|
|
522
441
|
let assignment;
|
|
523
442
|
try {
|
|
@@ -525,7 +444,6 @@ export class HttpTunnelHandle extends LifecycleEmitter {
|
|
|
525
444
|
const opened = await openUntilFree({
|
|
526
445
|
send: async (rid) => {
|
|
527
446
|
requestId = rid;
|
|
528
|
-
// TPB-12: Track expected requestId for pre-assignment routing
|
|
529
447
|
setExpectedRequestId(instanceId, rid);
|
|
530
448
|
await core.publish({ topic: cmdOpenTopic, payload: JSON.stringify({ requestId: rid, ...openPayload }), qos: 1, retain: false });
|
|
531
449
|
logger.info('cli.cmd.open.sent', { requestId: rid, instanceId, tunnelType: 'http' });
|
|
@@ -538,7 +456,6 @@ export class HttpTunnelHandle extends LifecycleEmitter {
|
|
|
538
456
|
assignment = opened.assignment;
|
|
539
457
|
logger.info('cli.ack.wait.resolved', { requestId, instanceId, tunnelType: 'http' });
|
|
540
458
|
logger.info('cli.assignment.received', { relayId: assignment.relayId, instanceId, tunnelType: 'http' });
|
|
541
|
-
// TPB-12: Persist assignment using per-instance store
|
|
542
459
|
try {
|
|
543
460
|
const { setAssignment } = await import('../state/assignment.js');
|
|
544
461
|
const { clearExpectedRequestId } = await import('../state/instance-registry.js');
|
|
@@ -559,13 +476,10 @@ export class HttpTunnelHandle extends LifecycleEmitter {
|
|
|
559
476
|
}
|
|
560
477
|
catch { }
|
|
561
478
|
if (error?.code === 'address_in_use')
|
|
562
|
-
throw error;
|
|
479
|
+
throw error;
|
|
563
480
|
throw new ConnectionError('assignment_failed', error.message, { cause: error });
|
|
564
481
|
}
|
|
565
|
-
// 8) Connect to the relay (was connectToRelay)
|
|
566
482
|
const { HttpTunnel } = await import('../tunnel/http-tunnel.js');
|
|
567
|
-
// Story 3.13: a fresh open for the same address (same session, never --replace), then the tunnel takes
|
|
568
|
-
// the new token and relay and reconnects, as the renewal fallback does.
|
|
569
483
|
reopenRef.fn = async () => {
|
|
570
484
|
if (!this.reopenLimiter.allow()) {
|
|
571
485
|
this.emit('reopen_refused', { code: 'reopen_limit', details: { limit: 3, windowMin: 10 } });
|
|
@@ -607,7 +521,7 @@ export class HttpTunnelHandle extends LifecycleEmitter {
|
|
|
607
521
|
};
|
|
608
522
|
const tunnel = new HttpTunnel({
|
|
609
523
|
relayUrl: assignment.relayUrl,
|
|
610
|
-
jwt: assignment.jwt,
|
|
524
|
+
jwt: assignment.jwt,
|
|
611
525
|
deviceId: credentials.clientId,
|
|
612
526
|
requestId: assignment.requestId,
|
|
613
527
|
localPort,
|
|
@@ -620,19 +534,19 @@ export class HttpTunnelHandle extends LifecycleEmitter {
|
|
|
620
534
|
controlPlaneTimeoutMs: CONTROL_PLANE_TIMEOUT_MS,
|
|
621
535
|
secGroupSlug,
|
|
622
536
|
instanceId,
|
|
623
|
-
requestSink: this.opts.requestSink,
|
|
537
|
+
requestSink: this.opts.requestSink,
|
|
624
538
|
log: adaptLogger(logger),
|
|
625
|
-
// Story 12.1 (c2): where the tunnel used to exit(1) it now ends with a typed error, and what it
|
|
626
|
-
// used to print is a notice; the CLI keeps the exit code and the wording.
|
|
627
539
|
onFatal: (code) => this.setState('closed', { error: new ConnectionError(code, `http tunnel ended: ${code}`, { details: { exitCode: 1 } }) }),
|
|
628
540
|
onNotice: (code, details) => this.emit('notice', { code, ...details }),
|
|
629
|
-
onLeaseClosed: async () => {
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
541
|
+
onLeaseClosed: async () => {
|
|
542
|
+
try {
|
|
543
|
+
await reopenRef.fn?.();
|
|
544
|
+
return true;
|
|
545
|
+
}
|
|
546
|
+
catch {
|
|
547
|
+
return false;
|
|
548
|
+
}
|
|
549
|
+
},
|
|
636
550
|
});
|
|
637
551
|
tunnelInstanceRef.tunnel = tunnel;
|
|
638
552
|
this.tunnel = tunnel;
|
|
@@ -642,7 +556,6 @@ export class HttpTunnelHandle extends LifecycleEmitter {
|
|
|
642
556
|
logger.info('tunnel.active', { url: `http://localhost:${localPort}`, relayId: assignment.relayId, leaseMs: assignment.leaseMs });
|
|
643
557
|
}
|
|
644
558
|
catch (error) {
|
|
645
|
-
// As before: no cleanup here; the caller reports and exits.
|
|
646
559
|
logger.error('cli.tunnel.failed', { error: error.message });
|
|
647
560
|
throw new ConnectionError('tunnel_connect_failed', error.message, { cause: error });
|
|
648
561
|
}
|
|
@@ -651,7 +564,6 @@ export class HttpTunnelHandle extends LifecycleEmitter {
|
|
|
651
564
|
this.setState('live', info);
|
|
652
565
|
return info;
|
|
653
566
|
}
|
|
654
|
-
/** Ask for a renewal now (SIGUSR2 in the CLI). */
|
|
655
567
|
attemptJwtRefresh() { return this.tunnel?.attemptJwtRefresh(); }
|
|
656
568
|
}
|
|
657
569
|
export function createHttpTunnel(opts) {
|
|
@@ -1,17 +1,18 @@
|
|
|
1
|
-
// Story 12.2: an identity command (app create) sent over the device's own certificate connection on
|
|
2
|
-
// asyx/tunnel/clients/<deviceId>/cmd/identity/create. A separate IoT rule routes that topic to the
|
|
3
|
-
// identity command function, which answers on the device's ack topic with
|
|
4
|
-
// { type: 'identity_ack', requestId, data }. One connection per command; it ends after the answer.
|
|
5
1
|
import { randomUUID } from 'node:crypto';
|
|
6
|
-
|
|
7
|
-
|
|
2
|
+
export function sendAppCreate(o) {
|
|
3
|
+
return sendIdentityCommand('create', 'app_create', o);
|
|
4
|
+
}
|
|
5
|
+
export function sendAppStatus(o) {
|
|
6
|
+
return sendIdentityCommand('status', 'app_status', { timeoutMs: 20000, ...o });
|
|
7
|
+
}
|
|
8
|
+
async function sendIdentityCommand(topicOp, op, o) {
|
|
8
9
|
const { credentials, command, logger, timeoutMs = 45000 } = o;
|
|
9
10
|
const { MqttCore } = await import('@asyx/mqtt-core');
|
|
10
11
|
const { createControlPlaneSession } = await import('../control-plane/session.js');
|
|
11
12
|
const { MqttControlPlaneTransport } = await import('../control-plane/MqttControlPlaneTransport.js');
|
|
12
13
|
const base = credentials.clientId;
|
|
13
14
|
const session = createControlPlaneSession({
|
|
14
|
-
credentials, tunnelType: 'identity', metadata: { op
|
|
15
|
+
credentials, tunnelType: 'identity', metadata: { op }, logger,
|
|
15
16
|
onRefreshLease: async () => null, trackSubscriptionReady: false, reportOffline: false, verboseRotationLogs: false,
|
|
16
17
|
});
|
|
17
18
|
const mqttClient = session.mqttClient;
|
|
@@ -36,8 +37,8 @@ export async function sendAppCreate(o) {
|
|
|
36
37
|
});
|
|
37
38
|
await core.subscribe(`asyx/tunnel/clients/${base}/evt/#`, 0);
|
|
38
39
|
const instanceId = mqttClient.getClientId();
|
|
39
|
-
await core.publish({ topic: `asyx/tunnel/clients/${base}/cmd/identity
|
|
40
|
-
logger.debug('identity.command.sent', { op
|
|
40
|
+
await core.publish({ topic: `asyx/tunnel/clients/${base}/cmd/identity/${topicOp}`, payload: JSON.stringify({ ...command, requestId, clientId: base, instanceId }), qos: 1, retain: false });
|
|
41
|
+
logger.debug('identity.command.sent', { op, requestId });
|
|
41
42
|
return await answer;
|
|
42
43
|
}
|
|
43
44
|
finally {
|
|
@@ -46,6 +47,6 @@ export async function sendAppCreate(o) {
|
|
|
46
47
|
try {
|
|
47
48
|
await mqttClient.disconnect();
|
|
48
49
|
}
|
|
49
|
-
catch {
|
|
50
|
+
catch { }
|
|
50
51
|
}
|
|
51
52
|
}
|
|
@@ -1,13 +1,7 @@
|
|
|
1
|
-
// Story 1.9: an address runs one tunnel of each kind. When the coordinator answers address_in_use,
|
|
2
|
-
// the open fails with RefusedError('address_in_use', { details }). On the same computer (a restart
|
|
3
|
-
// that beat the old connection's offline notice) the open asks again every 3 s for up to 15 s; with
|
|
4
|
-
// waitIfInUse (`asyx tunnel --wait`) it asks again every 30 s until the address is free. Every retry
|
|
5
|
-
// travels over the same MQTT connection; nothing new is opened.
|
|
6
1
|
import { randomUUID } from 'node:crypto';
|
|
7
2
|
export const SAME_COMPUTER_WAIT_MS = 15_000;
|
|
8
3
|
export const SAME_COMPUTER_STEP_MS = 3_000;
|
|
9
4
|
export const WAIT_STEP_MS = 30_000;
|
|
10
|
-
/** How long to wait before asking again, or null to give up (the caller reports the refusal). */
|
|
11
5
|
export function inUseDelay(details, firstAt, now, waitIfInUse) {
|
|
12
6
|
if (details?.sameComputer === true && now - firstAt < SAME_COMPUTER_WAIT_MS)
|
|
13
7
|
return SAME_COMPUTER_STEP_MS;
|
|
@@ -1,6 +1,3 @@
|
|
|
1
|
-
// Story 3.13: a tunnel whose lease was closed while it is still meant to run opens a fresh tunnel on the
|
|
2
|
-
// same address (and TCP/UDP port), at most 3 times in 10 minutes; a reopen never carries --replace, so a
|
|
3
|
-
// tunnel that a newer one replaced is refused (address_in_use) instead of taking the address back.
|
|
4
1
|
export class ReopenLimiter {
|
|
5
2
|
max;
|
|
6
3
|
windowMs;
|
|
@@ -17,7 +14,6 @@ export class ReopenLimiter {
|
|
|
17
14
|
return true;
|
|
18
15
|
}
|
|
19
16
|
}
|
|
20
|
-
/** The open request for a reopen: same address, port and session, never `replace`. */
|
|
21
17
|
export function reopenPayload(openPayload, requestId, publicPort) {
|
|
22
18
|
const { replace, ...rest } = openPayload;
|
|
23
19
|
const again = { ...rest, requestId, reopen: true };
|