asyx 0.5.9 → 0.6.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 (88) hide show
  1. package/README.md +71 -9
  2. package/SECURITY.md +5 -3
  3. package/package.json +13 -23
  4. package/src/commands/name.js +23 -0
  5. package/src/commands/reject-messages.js +54 -0
  6. package/src/commands/setup.js +98 -102
  7. package/src/commands/tunnel.js +279 -2425
  8. package/src/lib/naming.js +81 -0
  9. package/src/main.js +9 -1
  10. package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneClient.d.ts +260 -0
  11. package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneClient.js +1088 -0
  12. package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneTransport.d.ts +79 -0
  13. package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneTransport.js +138 -0
  14. package/vendor/tunnel-core/dist/control-plane/session.d.ts +50 -0
  15. package/vendor/tunnel-core/dist/control-plane/session.js +115 -0
  16. package/vendor/tunnel-core/dist/errors.d.ts +49 -0
  17. package/vendor/tunnel-core/dist/errors.js +53 -0
  18. package/vendor/tunnel-core/dist/flows/http.d.ts +50 -0
  19. package/vendor/tunnel-core/dist/flows/http.js +585 -0
  20. package/vendor/tunnel-core/dist/flows/tcp.d.ts +60 -0
  21. package/vendor/tunnel-core/dist/flows/tcp.js +546 -0
  22. package/vendor/tunnel-core/dist/flows/udp.d.ts +41 -0
  23. package/vendor/tunnel-core/dist/flows/udp.js +376 -0
  24. package/vendor/tunnel-core/dist/lib/adapt-logger.d.ts +2 -0
  25. package/vendor/tunnel-core/dist/lib/adapt-logger.js +6 -0
  26. package/vendor/tunnel-core/dist/lib/fingerprint.d.ts +13 -0
  27. package/vendor/tunnel-core/dist/lib/fingerprint.js +95 -0
  28. package/vendor/tunnel-core/dist/lib/jwt-verifier.d.ts +27 -0
  29. package/vendor/tunnel-core/dist/lib/jwt-verifier.js +230 -0
  30. package/vendor/tunnel-core/dist/lib/logger.d.ts +9 -0
  31. package/vendor/tunnel-core/dist/lib/logger.js +58 -0
  32. package/vendor/tunnel-core/dist/lib/refresh-helpers.d.ts +16 -0
  33. package/vendor/tunnel-core/dist/lib/refresh-helpers.js +66 -0
  34. package/vendor/tunnel-core/dist/lifecycle.d.ts +24 -0
  35. package/vendor/tunnel-core/dist/lifecycle.js +29 -0
  36. package/vendor/tunnel-core/dist/mqtt/awaiter-map.d.ts +56 -0
  37. package/vendor/tunnel-core/dist/mqtt/awaiter-map.js +227 -0
  38. package/vendor/tunnel-core/dist/mqtt/events/handlers.d.ts +58 -0
  39. package/vendor/tunnel-core/dist/mqtt/events/handlers.js +250 -0
  40. package/vendor/tunnel-core/dist/mqtt/events/index.d.ts +1 -0
  41. package/vendor/tunnel-core/dist/mqtt/events/index.js +191 -0
  42. package/vendor/tunnel-core/dist/mqtt/events/schemas.d.ts +498 -0
  43. package/vendor/tunnel-core/dist/mqtt/events/schemas.js +51 -0
  44. package/vendor/tunnel-core/dist/mqtt/ingress.d.ts +63 -0
  45. package/vendor/tunnel-core/dist/mqtt/ingress.js +170 -0
  46. package/vendor/tunnel-core/dist/state/assignment.d.ts +122 -0
  47. package/vendor/tunnel-core/dist/state/assignment.js +322 -0
  48. package/vendor/tunnel-core/dist/state/instance-registry.d.ts +88 -0
  49. package/{src → vendor/tunnel-core/dist}/state/instance-registry.js +38 -53
  50. package/vendor/tunnel-core/dist/tcp-v1/framing.d.ts +43 -0
  51. package/vendor/tunnel-core/dist/tcp-v1/framing.js +157 -0
  52. package/vendor/tunnel-core/dist/tunnel/http-tunnel.d.ts +137 -0
  53. package/vendor/tunnel-core/dist/tunnel/http-tunnel.js +1591 -0
  54. package/vendor/tunnel-core/dist/tunnel/httpws-constants.d.ts +13 -0
  55. package/{src → vendor/tunnel-core/dist}/tunnel/httpws-constants.js +5 -7
  56. package/vendor/tunnel-core/dist/tunnel/reconnect.d.ts +76 -0
  57. package/vendor/tunnel-core/dist/tunnel/reconnect.js +183 -0
  58. package/vendor/tunnel-core/dist/tunnel/request-sink.d.ts +40 -0
  59. package/vendor/tunnel-core/dist/tunnel/request-sink.js +39 -0
  60. package/vendor/tunnel-core/dist/tunnel/tcp-tunnel.d.ts +89 -0
  61. package/vendor/tunnel-core/dist/tunnel/tcp-tunnel.js +838 -0
  62. package/vendor/tunnel-core/dist/tunnel/udp-tunnel.d.ts +90 -0
  63. package/vendor/tunnel-core/dist/tunnel/udp-tunnel.js +737 -0
  64. package/vendor/tunnel-core/dist/tunnel/ws-control.d.ts +22 -0
  65. package/vendor/tunnel-core/dist/tunnel/ws-control.js +124 -0
  66. package/vendor/tunnel-core/dist/types.d.ts +24 -0
  67. package/vendor/tunnel-core/dist/types.js +2 -0
  68. package/vendor/tunnel-core/dist/udp-v1/framing.d.ts +41 -0
  69. package/vendor/tunnel-core/dist/udp-v1/framing.js +158 -0
  70. package/vendor/tunnel-core/package.json +34 -0
  71. package/src/control-plane/MqttControlPlaneClient.js +0 -1196
  72. package/src/control-plane/MqttControlPlaneTransport.js +0 -150
  73. package/src/lib/fingerprint.js +0 -115
  74. package/src/lib/jwt-verifier.js +0 -260
  75. package/src/lib/logger.js +0 -62
  76. package/src/mqtt/awaiter-map.js +0 -247
  77. package/src/mqtt/events/handlers.js +0 -300
  78. package/src/mqtt/events/index.js +0 -222
  79. package/src/mqtt/events/schemas.js +0 -58
  80. package/src/mqtt/ingress.js +0 -182
  81. package/src/state/assignment.js +0 -333
  82. package/src/tcp-v1/framing.js +0 -203
  83. package/src/tunnel/http-tunnel.js +0 -1738
  84. package/src/tunnel/reconnect.js +0 -182
  85. package/src/tunnel/tcp-tunnel.js +0 -944
  86. package/src/tunnel/udp-tunnel.js +0 -813
  87. package/src/tunnel/ws-control.js +0 -135
  88. package/src/udp-v1/framing.js +0 -203
@@ -0,0 +1,376 @@
1
+ // Story 12.1 (step 2b, sub-step 3; TypeScript in r3): the UDP tunnel flow, moved from udpTunnel() and
2
+ // connectToRelayUdp() 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 from LifecycleEmitter: 'opening', 'live', and a final 'closed' { error } when a
6
+ // reply ends the tunnel after it opened (SetupRequiredError, RefusedError, InternalError).
7
+ // open() rejects with a ConnectionError whose code tells the caller what failed:
8
+ // control_plane_connect_failed, udp_relay_unavailable, assignment_failed, tunnel_connect_failed.
9
+ import { randomUUID } from 'node:crypto';
10
+ import { LifecycleEmitter } from '../lifecycle.js';
11
+ import { ConnectionError, SetupRequiredError, RefusedError, InternalError } from '../errors.js';
12
+ import { createControlPlaneSession } from '../control-plane/session.js';
13
+ import { publishRefreshRequestWithErrorHandling, jwtExpOf } from '../lib/refresh-helpers.js';
14
+ import { adaptLogger } from '../lib/adapt-logger.js';
15
+ const relayUnavailable = (message) => new ConnectionError('udp_relay_unavailable', message);
16
+ export class UdpTunnelHandle extends LifecycleEmitter {
17
+ opts;
18
+ tunnel = null;
19
+ mqttClient = null;
20
+ core = null;
21
+ assignment = null;
22
+ constructor(o) {
23
+ super();
24
+ this.opts = { targetHost: '127.0.0.1', requestedExternalPort: null, ...o };
25
+ }
26
+ /** Connect the control plane, get a lease and open the data plane; rejects with a ConnectionError. */
27
+ async open() {
28
+ const { credentials, targetPort, targetHost, requestedExternalPort, logger } = this.opts;
29
+ this.setState('opening');
30
+ const { MqttCore } = await import('@asyx/mqtt-core');
31
+ const { waitForAssignment } = await import('../state/assignment.js');
32
+ const { MqttControlPlaneTransport } = await import('../control-plane/MqttControlPlaneTransport.js');
33
+ const { MessageIngress } = await import('../mqtt/ingress.js');
34
+ const { dispatch: dispatchEvt } = await import('../mqtt/events/index.js');
35
+ // CLI-IMG-ControlPlane-Watchdog: Add configurable timeout
36
+ const CONTROL_PLANE_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_TIMEOUT_MS || '60000', 10);
37
+ const baseClientId = credentials.clientId;
38
+ const instanceIdRef = { instanceId: null };
39
+ let coordinatorCoreRef = null;
40
+ let coordinatorIngressRef = null;
41
+ const deviceIdRef = credentials.clientId;
42
+ const subscriptionReadyRef = { ready: false };
43
+ let mqttClient;
44
+ // Story 11.2: UDP refresh (control plane UDP-S3), so a reconnect after the first token expires
45
+ // still has a valid token. Same flow as TCP (TPB-17); failures are non-fatal.
46
+ const onRefreshLease = async () => {
47
+ if (!coordinatorCoreRef || !coordinatorIngressRef) {
48
+ throw new Error('Coordinator not available for refresh');
49
+ }
50
+ const refreshInstanceId = mqttClient.getClientId();
51
+ const { getAssignment } = await import('../state/assignment.js');
52
+ const { getFpHash } = await import('../lib/fingerprint.js');
53
+ const currentAssignment = getAssignment(refreshInstanceId);
54
+ if (!currentAssignment?.leaseId) {
55
+ throw new Error(`No current assignment for refresh (instanceId: ${refreshInstanceId})`);
56
+ }
57
+ const refreshRequestId = `refresh-${randomUUID()}` /* Defect 11.27: unique across processes (was Date.now()) */;
58
+ const fingerprint = await getFpHash(deviceIdRef);
59
+ const refreshPayload = {
60
+ requestId: refreshRequestId,
61
+ instanceId: refreshInstanceId,
62
+ refreshOf: currentAssignment.leaseId,
63
+ proto: 'udp',
64
+ protocol: 'udp',
65
+ tunnelMode: 'udpWs-v1',
66
+ targetHost,
67
+ targetPort,
68
+ clientId: deviceIdRef,
69
+ ...fingerprint,
70
+ };
71
+ const cmdOpenTopic = `asyx/tunnel/clients/${deviceIdRef}/cmd/open`;
72
+ const ACK_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_ACK_TIMEOUT_MS || '20000', 10);
73
+ const ackPromise = coordinatorIngressRef.registerAwaiter((message) => {
74
+ const parsed = message.payload;
75
+ if (parsed && parsed.requestId === refreshRequestId && parsed.type === 'open_reject') {
76
+ const rejectError = new Error(`Refresh rejected: ${parsed.data?.reason || 'unknown'}`);
77
+ rejectError.code = 'REFRESH_REJECTED';
78
+ throw rejectError;
79
+ }
80
+ return !!parsed && parsed.type === 'open_ack' && parsed.requestId === refreshRequestId;
81
+ }, ACK_TIMEOUT_MS);
82
+ const publishSuccess = await publishRefreshRequestWithErrorHandling(coordinatorCoreRef, cmdOpenTopic, refreshPayload, refreshRequestId, logger);
83
+ if (publishSuccess === false) {
84
+ const bufferedError = new Error('Connection closed during refresh publish');
85
+ bufferedError.code = 'ECONNRESET';
86
+ throw bufferedError;
87
+ }
88
+ try {
89
+ await ackPromise;
90
+ }
91
+ catch (error) {
92
+ logger.warn('udp.refresh.failed', { error: error.message, requestId: refreshRequestId, action: 'non_fatal_continue' });
93
+ return null;
94
+ }
95
+ const exp = jwtExpOf(getAssignment(refreshInstanceId)?.jwt);
96
+ if (!exp) {
97
+ logger.warn('udp.refresh.no_exp', { requestId: refreshRequestId });
98
+ return null;
99
+ }
100
+ logger.debug('udp.refresh.success', { leaseId: currentAssignment.leaseId, expMs: exp * 1000, requestId: refreshRequestId });
101
+ this.setState('renewed', { leaseId: currentAssignment.leaseId, expMs: exp * 1000 });
102
+ this.setState('live');
103
+ return exp * 1000;
104
+ };
105
+ const cpSession = createControlPlaneSession({
106
+ credentials,
107
+ tunnelType: 'udp',
108
+ metadata: { baseClientId, targetPort, targetHost, requestedExternalPort },
109
+ logger,
110
+ onRefreshLease,
111
+ instanceIdRef,
112
+ subscriptionReadyRef,
113
+ verboseRotationLogs: false,
114
+ });
115
+ mqttClient = cpSession.mqttClient;
116
+ this.mqttClient = mqttClient;
117
+ cpSession.events.on('connected', (e) => this.emit('control-connected', e));
118
+ cpSession.events.on('offline', (e) => this.emit('control-offline', e));
119
+ cpSession.events.on('fatal', (e) => this.emit('control-fatal', e));
120
+ const transport = new MqttControlPlaneTransport(mqttClient);
121
+ const core = new MqttCore(transport, { canPublish: () => true, canSubscribe: () => true });
122
+ this.core = core;
123
+ const isControlPlaneConnected = () => mqttClient.isOnline();
124
+ const waitForControlPlane = () => {
125
+ if (mqttClient.isOnline())
126
+ return Promise.resolve();
127
+ const start = Date.now();
128
+ return new Promise((resolve, reject) => {
129
+ const interval = setInterval(() => {
130
+ if (mqttClient.isOnline()) {
131
+ clearInterval(interval);
132
+ resolve();
133
+ }
134
+ else if (Date.now() - start >= CONTROL_PLANE_TIMEOUT_MS) {
135
+ clearInterval(interval);
136
+ reject(new Error('control_plane_timeout'));
137
+ }
138
+ }, 250);
139
+ });
140
+ };
141
+ const getLastMqttError = () => null;
142
+ const getForceReconnect = () => async () => {
143
+ if (!mqttClient.isOnline()) {
144
+ await mqttClient.disconnect();
145
+ await mqttClient.connect();
146
+ }
147
+ };
148
+ // 3) Connect to control plane
149
+ try {
150
+ await mqttClient.connect();
151
+ }
152
+ catch (e) {
153
+ logger.error('mqtt.connect.failed', { error: e?.message || String(e) });
154
+ throw new ConnectionError('control_plane_connect_failed', e?.message || String(e), { cause: e });
155
+ }
156
+ // TPB-12: instanceId is the full MQTT clientId after connection
157
+ instanceIdRef.instanceId = mqttClient.getClientId();
158
+ const instanceId = instanceIdRef.instanceId;
159
+ logger.debug('cli.instance.registered', { instanceId, tunnelType: 'udp', baseClientId });
160
+ // 4) Topics
161
+ const evtWildcard = `asyx/tunnel/clients/${baseClientId}/evt/#`;
162
+ const cmdOpenTopic = `asyx/tunnel/clients/${baseClientId}/cmd/open`;
163
+ await core.subscribe(evtWildcard, 0);
164
+ subscriptionReadyRef.ready = true;
165
+ // 5) Message ingress and dispatcher
166
+ const ingress = new MessageIngress({ maxAwaiters: 100, observability: process.env.ASYX_DEBUG === '1', logger, onObserve: this.opts.onObserve });
167
+ ingress.setDispatcher(dispatchEvt);
168
+ const { registerInstance, setExpectedRequestId } = await import('../state/instance-registry.js');
169
+ const { setAssignment: setAssignmentFn, getAssignment: getAssignmentFn } = await import('../state/assignment.js');
170
+ registerInstance(instanceId, {
171
+ tunnelType: 'udp',
172
+ setAssignment: setAssignmentFn,
173
+ getAssignment: getAssignmentFn,
174
+ metadata: { baseClientId, targetPort, targetHost, requestedExternalPort },
175
+ });
176
+ coordinatorCoreRef = core;
177
+ coordinatorIngressRef = ingress;
178
+ // A reply that ends the tunnel closes it with a typed error (the CLI used to print and exit here).
179
+ core.onMessage(async (m) => {
180
+ try {
181
+ await ingress.handleMessage(m);
182
+ }
183
+ catch (e) {
184
+ let error;
185
+ if (e && e.code === 'SETUP_REQUIRED')
186
+ error = new SetupRequiredError('setup_required', e.message, { cause: e });
187
+ else if (e && typeof e.code === 'string' && e.code.startsWith('ERROR_'))
188
+ error = new RefusedError(e.code, e.message, { cause: e });
189
+ else
190
+ error = new InternalError('unexpected', e?.message || String(e), { cause: e });
191
+ try {
192
+ await core.end();
193
+ }
194
+ catch { }
195
+ this.setState('closed', { error });
196
+ }
197
+ });
198
+ // 6) Publish cmd/open request with UDP protocol
199
+ const requestId = randomUUID();
200
+ const { getFpHash } = await import('../lib/fingerprint.js');
201
+ const fingerprint = await getFpHash(credentials.clientId);
202
+ setExpectedRequestId(instanceId, requestId);
203
+ const openPayload = {
204
+ requestId,
205
+ instanceId, // TPB-12: Per-instance routing
206
+ protocol: 'udp',
207
+ tunnelMode: 'udpWs-v1',
208
+ port: targetPort, // UDP-S13: the app's listening port
209
+ targetHost,
210
+ targetPort,
211
+ clientId: credentials.clientId,
212
+ tenantId: 'tunnel', // AC1.2: v4.1 validation phase uses literal "tunnel" as tenantId
213
+ ...fingerprint,
214
+ };
215
+ if (requestedExternalPort !== null && requestedExternalPort !== undefined) {
216
+ openPayload.externalPort = requestedExternalPort;
217
+ }
218
+ await core.publish({ topic: cmdOpenTopic, payload: JSON.stringify(openPayload), qos: 1, retain: false });
219
+ logger.info('cli.cmd.open.sent', { requestId, instanceId, tunnelType: 'udp', protocol: 'udp', tunnelMode: 'udpWs-v1' });
220
+ // 7) Wait for ack and assignment
221
+ const ACK_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_ACK_TIMEOUT_MS || '20000', 10);
222
+ let assignment;
223
+ let reassignSamePort;
224
+ try {
225
+ const assignmentPromise = waitForAssignment(requestId, ACK_TIMEOUT_MS);
226
+ logger.info('cli.ack.wait.start', { requestId });
227
+ assignment = await assignmentPromise;
228
+ logger.info('cli.ack.wait.resolved', { requestId, instanceId, tunnelType: 'udp' });
229
+ logger.info('cli.assignment.received', { relayId: assignment.relayId, leaseId: assignment.leaseId, instanceId, tunnelType: 'udp', publicPort: assignment.publicPort });
230
+ // UDP-S1: Validate assignment (AC1.4/AC5.1)
231
+ if (!assignment.relayUrl)
232
+ throw relayUnavailable('UDP_RELAY_UNAVAILABLE: Missing relayUrl in assignment');
233
+ if (!assignment.tunnelMode || assignment.tunnelMode !== 'udpWs-v1') {
234
+ throw relayUnavailable(`UDP_RELAY_UNAVAILABLE: Invalid tunnelMode in assignment: ${assignment.tunnelMode}, expected udpWs-v1`);
235
+ }
236
+ if (!assignment.protocol || assignment.protocol !== 'udp') {
237
+ throw relayUnavailable(`UDP_RELAY_UNAVAILABLE: Invalid protocol in assignment: ${assignment.protocol}, expected udp`);
238
+ }
239
+ if (!assignment.relayId)
240
+ throw relayUnavailable('UDP_RELAY_UNAVAILABLE: Missing relayId in assignment');
241
+ if (!assignment.publicPort)
242
+ throw relayUnavailable('UDP_RELAY_UNAVAILABLE: Missing publicPort in assignment');
243
+ const assignmentJwt = assignment.assignmentJwt || assignment.jwt;
244
+ if (!assignmentJwt)
245
+ throw relayUnavailable('UDP_RELAY_UNAVAILABLE: Missing assignmentJwt in assignment');
246
+ // AC1.4/AC5.1: Verify JWT signature and claims using JWKS
247
+ try {
248
+ const { verifyAssignmentJWT } = await import('../lib/jwt-verifier.js');
249
+ await verifyAssignmentJWT(assignmentJwt, { relayId: assignment.relayId, protocol: 'udp', tunnelMode: 'udpWs-v1', leaseId: assignment.leaseId });
250
+ logger.debug('udp.assignment.jwt_verified', { relayId: assignment.relayId, leaseId: assignment.leaseId });
251
+ }
252
+ catch (jwtError) {
253
+ logger.error('udp.assignment.jwt_verification_failed', { error: jwtError.message, code: jwtError.code, relayId: assignment.relayId, leaseId: assignment.leaseId });
254
+ throw relayUnavailable(`UDP_RELAY_UNAVAILABLE: JWT verification failed: ${jwtError.message}`);
255
+ }
256
+ // TPB-12: Persist assignment using per-instance store
257
+ try {
258
+ const { setAssignment } = await import('../state/assignment.js');
259
+ const { clearExpectedRequestId } = await import('../state/instance-registry.js');
260
+ setAssignment(instanceId, assignment);
261
+ clearExpectedRequestId(instanceId);
262
+ }
263
+ catch { }
264
+ // Story 10.9: if the relay refuses this assignment on a reconnect (the tenant moved), open
265
+ // again for the same public port; the control plane places the lease on the current relay.
266
+ reassignSamePort = async () => {
267
+ const { setAssignment: setA, getAssignment: getA } = await import('../state/assignment.js');
268
+ const cur = getA(instanceIdRef.instanceId) || assignment;
269
+ const rid = randomUUID();
270
+ const again = { ...openPayload, requestId: rid, externalPort: cur.publicPort ?? assignment.publicPort };
271
+ setExpectedRequestId(instanceIdRef.instanceId, rid);
272
+ await core.publish({ topic: cmdOpenTopic, payload: JSON.stringify(again), qos: 1, retain: false });
273
+ const next = await waitForAssignment(rid, ACK_TIMEOUT_MS);
274
+ setA(instanceIdRef.instanceId, next);
275
+ logger.info('udp.reassign.ok', { leaseId: next.leaseId, relayId: next.relayId, publicPort: next.publicPort });
276
+ return { relayUrl: next.relayUrl, jwt: next.jwt, leaseId: next.leaseId, relayId: next.relayId };
277
+ };
278
+ }
279
+ catch (error) {
280
+ logger.error('cli.ack.wait.failed', { error: error.message, errorCode: error.code, instanceId, tunnelType: 'udp' });
281
+ if (error.code === 'udp_relay_unavailable') {
282
+ try {
283
+ await core.end();
284
+ }
285
+ catch { }
286
+ throw error;
287
+ }
288
+ // TPB-12: Clean up expected requestId on timeout/error
289
+ try {
290
+ const { clearExpectedRequestId } = await import('../state/instance-registry.js');
291
+ clearExpectedRequestId(instanceId);
292
+ }
293
+ catch { }
294
+ try {
295
+ await core.end();
296
+ }
297
+ catch { }
298
+ throw new ConnectionError('assignment_failed', error.message, { cause: error });
299
+ }
300
+ // Connect to the relay (was connectToRelayUdp)
301
+ const { UdpTunnel } = await import('../tunnel/udp-tunnel.js');
302
+ const { getAssignment: getStoredAssignment } = await import('../state/assignment.js');
303
+ const tunnel = new UdpTunnel({
304
+ reassign: reassignSamePort,
305
+ relayUrl: assignment.relayUrl,
306
+ jwt: assignment.assignmentJwt || assignment.jwt, // UDP-S1: Use assignmentJwt if available
307
+ // Story 11.2: reconnects use the newest token (kept fresh by the UDP refresh)
308
+ getJwt: () => {
309
+ const stored = instanceId ? getStoredAssignment(instanceId) : null;
310
+ return stored?.assignmentJwt || stored?.jwt || null;
311
+ },
312
+ deviceId: credentials.clientId,
313
+ requestId: assignment.requestId,
314
+ targetHost,
315
+ targetPort,
316
+ leaseId: assignment.leaseId,
317
+ relayId: assignment.relayId, // AC5.1: Pass relayId for JWT validation
318
+ coordinatorCore: core,
319
+ coordinatorIngress: ingress,
320
+ isControlPlaneConnected,
321
+ waitForControlPlane,
322
+ getLastMqttError,
323
+ getForceReconnect,
324
+ controlPlaneTimeoutMs: CONTROL_PLANE_TIMEOUT_MS,
325
+ log: adaptLogger(logger),
326
+ // Story 12.1 (c2): where the tunnel used to exit, it now ends with a typed error; the CLI exits
327
+ // with the same code (silently, as before).
328
+ exit: (code) => this.setState('closed', { error: new ConnectionError('tunnel_ended', `tunnel ended (exit code ${code})`, { details: { exitCode: code } }) }),
329
+ });
330
+ this.tunnel = tunnel;
331
+ try {
332
+ await tunnel.open();
333
+ // Story 11.2: schedule the first proactive token refresh (as TCP, TPB-17)
334
+ const firstExp = jwtExpOf(assignment.assignmentJwt || assignment.jwt);
335
+ if (mqttClient && firstExp && assignment.leaseId) {
336
+ mqttClient.scheduleRefresh(firstExp * 1000, assignment.leaseId);
337
+ logger.debug('udp.refresh.initial_scheduled', { expMs: firstExp * 1000, leaseId: assignment.leaseId });
338
+ }
339
+ logger.info('tunnel.active', { target: `udp://${targetHost}:${targetPort}`, relayId: assignment.relayId, leaseMs: assignment.leaseMs, publicPort: assignment.publicPort });
340
+ }
341
+ catch (error) {
342
+ logger.error('tunnel.open.failed', { error: error.message });
343
+ try {
344
+ tunnel.close();
345
+ }
346
+ catch (e) {
347
+ logger.debug('tunnel.close.error', { error: e.message });
348
+ }
349
+ try {
350
+ await mqttClient.disconnect();
351
+ }
352
+ catch (e) {
353
+ logger.debug('mqtt.control_plane.disconnect.error', { error: e.message });
354
+ }
355
+ if (error.code === 'UDP_RELAY_UNAVAILABLE')
356
+ throw relayUnavailable(error.message);
357
+ throw new ConnectionError('tunnel_connect_failed', error.message, { cause: error });
358
+ }
359
+ this.assignment = assignment;
360
+ const info = { assignment, targetHost, targetPort, relayId: assignment.relayId, publicPort: assignment.publicPort, fqdn: assignment.fqdn, leaseMs: assignment.leaseMs };
361
+ this.setState('live', info);
362
+ return info;
363
+ }
364
+ /** Close the data plane, then the control plane. */
365
+ async close() {
366
+ try {
367
+ this.tunnel?.close();
368
+ }
369
+ finally {
370
+ await this.mqttClient?.disconnect();
371
+ }
372
+ }
373
+ }
374
+ export function createUdpTunnel(opts) {
375
+ return new UdpTunnelHandle(opts);
376
+ }
@@ -0,0 +1,2 @@
1
+ import type { ClassLogger, Logger } from '../types.js';
2
+ export declare function adaptLogger(logger: Logger): ClassLogger;
@@ -0,0 +1,6 @@
1
+ export function adaptLogger(logger) {
2
+ const wrap = (level) => (msgOrFields, maybeFields) => (typeof msgOrFields === 'string'
3
+ ? logger[level](msgOrFields, maybeFields)
4
+ : logger[level](maybeFields, msgOrFields));
5
+ return { info: wrap('info'), warn: wrap('warn'), error: wrap('error'), debug: wrap('debug') };
6
+ }
@@ -0,0 +1,13 @@
1
+ export function getFpHash(clientId: any): Promise<{
2
+ clientVersion: string;
3
+ fpv: string;
4
+ fph: string;
5
+ alg: string;
6
+ lib: string;
7
+ } | {
8
+ clientVersion?: undefined;
9
+ fpv: string;
10
+ fph: string;
11
+ alg: string;
12
+ lib: string;
13
+ }>;
@@ -0,0 +1,95 @@
1
+ /**
2
+ * CP-3C: Safe Hardware Fingerprint Collection (macOS Privacy Compliant)
3
+ *
4
+ * Privacy-preserving hardware fingerprinting that avoids macOS privacy warnings.
5
+ * Uses only safe fields that don't trigger system permission requests.
6
+ */
7
+ import { getFingerprintingInfo } from 'hw-fingerprint';
8
+ import { createHash } from 'node:crypto';
9
+ /**
10
+ * Safe hardware attributes that don't trigger macOS privacy warnings.
11
+ * Based on analysis of hw-fingerprint library behavior.
12
+ */
13
+ const SAFE_FIELDS = [
14
+ 'platform', // OS platform (darwin, linux, win32)
15
+ 'arch', // CPU architecture (arm64, x64)
16
+ 'cores', // Number of CPU cores
17
+ 'manufacturer', // Hardware manufacturer
18
+ 'vendor', // System vendor
19
+ 'model' // Hardware model (Mac16,11, etc.)
20
+ ];
21
+ /**
22
+ * Collect safe hardware fingerprint using only non-sensitive fields.
23
+ * Returns canonical JSON string with stable ordering.
24
+ */
25
+ async function collectSafeHardwareFingerprint() {
26
+ try {
27
+ const fingerprint = await getFingerprintingInfo();
28
+ // Extract only safe fields, dropping empties
29
+ const safeData = {};
30
+ for (const field of SAFE_FIELDS) {
31
+ const value = fingerprint[field];
32
+ if (value !== undefined && value !== null && value !== '') {
33
+ safeData[field] = value;
34
+ }
35
+ }
36
+ // Create canonical JSON with stable ordering
37
+ const canonical = {
38
+ version: 'fpv1-safe',
39
+ fields: safeData
40
+ };
41
+ return JSON.stringify(canonical, Object.keys(canonical).sort());
42
+ }
43
+ catch (error) {
44
+ // Return empty canonical structure on failure
45
+ return JSON.stringify({ version: 'fpv1-safe', fields: {} }, Object.keys({ version: 'fpv1-safe', fields: {} }).sort());
46
+ }
47
+ }
48
+ /**
49
+ * Hash fingerprint using SHA-256 with public salt.
50
+ * Returns hex string.
51
+ */
52
+ function hashFingerprint(canonical, clientId) {
53
+ const publicSalt = `asyx|${clientId}`;
54
+ const preimage = publicSalt + canonical;
55
+ return createHash('sha256')
56
+ .update(preimage, 'utf8')
57
+ .digest('hex');
58
+ }
59
+ /**
60
+ * Get safe hardware fingerprint hash with version metadata.
61
+ * Returns structured object for cmd/open payload.
62
+ *
63
+ * This version avoids macOS privacy warnings by using only safe fields.
64
+ */
65
+ // Story 2.1 c7: every cmd/open (first open, refresh, reconnect) carries the client's version so the
66
+ // coordinator can tell old clients from new ones. The CLI sets ASYX_CLIENT_VERSION at start-up; an
67
+ // embedding app may set it too. Omitted when unknown.
68
+ function versionField() {
69
+ const v = (process.env.ASYX_CLIENT_VERSION || '').trim();
70
+ return /^[0-9A-Za-z.@+-]{1,40}$/.test(v) ? { clientVersion: v } : {};
71
+ }
72
+ export async function getFpHash(clientId) {
73
+ return { ...(await fingerprintFields(clientId)), ...versionField() };
74
+ }
75
+ async function fingerprintFields(clientId) {
76
+ try {
77
+ const canonical = await collectSafeHardwareFingerprint();
78
+ const clientHash = hashFingerprint(canonical, clientId);
79
+ return {
80
+ fpv: '1-safe',
81
+ fph: clientHash,
82
+ alg: 'sha256',
83
+ lib: 'hw-fingerprint@3.2.0-safe'
84
+ };
85
+ }
86
+ catch (error) {
87
+ // Return unavailable fingerprint on any failure
88
+ return {
89
+ fpv: '1-safe',
90
+ fph: 'unavailable',
91
+ alg: 'sha256',
92
+ lib: 'hw-fingerprint@3.2.0-safe'
93
+ };
94
+ }
95
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Verify assignment JWT with JWKS signature verification
3
+ * AC1.4/AC5.1: Validates signature, iss, aud, exp, relayId, protocol, tunnelMode, leaseId
4
+ * @param {string} token - JWT token to verify
5
+ * @param {Object} expectedClaims - Expected claim values
6
+ * @param {string} expectedClaims.relayId - Expected relayId
7
+ * @param {string} expectedClaims.protocol - Expected protocol ('udp' | 'tcp')
8
+ * @param {string} expectedClaims.tunnelMode - Expected tunnelMode ('udpWs-v1' | 'tcpWs-v1')
9
+ * @param {string} [expectedClaims.leaseId] - Expected leaseId (optional)
10
+ * @returns {Promise<Object>} Verified JWT payload
11
+ * @throws {Error} If JWT verification fails (signature, claims, or JWKS unavailable)
12
+ */
13
+ export function verifyAssignmentJWT(token: string, expectedClaims?: {
14
+ relayId: string;
15
+ protocol: string;
16
+ tunnelMode: string;
17
+ leaseId?: string;
18
+ }): Promise<any>;
19
+ /**
20
+ * Check if JWKS is available (for health checks)
21
+ * @returns {boolean} True if JWKS is initialized
22
+ */
23
+ export function isJWKSAvailable(): boolean;
24
+ /**
25
+ * Reset JWKS cache (for testing or re-initialization)
26
+ */
27
+ export function resetJWKS(): void;