asyx 0.5.8 → 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 (87) hide show
  1. package/README.md +103 -17
  2. package/SECURITY.md +5 -3
  3. package/package.json +15 -22
  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 +304 -2316
  8. package/src/lib/naming.js +81 -0
  9. package/src/main.js +24 -6
  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 -1694
  84. package/src/tunnel/tcp-tunnel.js +0 -862
  85. package/src/tunnel/udp-tunnel.js +0 -708
  86. package/src/tunnel/ws-control.js +0 -135
  87. package/src/udp-v1/framing.js +0 -203
@@ -1,222 +0,0 @@
1
- import { parseAny, getHandler } from "./handlers.js";
2
- import { getInstance, getAllInstances, resolveInstanceByRequestId } from "../../state/instance-registry.js";
3
- import { resolveInstanceByLease, getAssignment } from "../../state/assignment.js";
4
- import logger from "../../lib/logger.js";
5
-
6
- // TPB-12: Track unmatched events to avoid log spam
7
- let unmatchedEventLogged = false;
8
-
9
- export async function dispatch(parsedMessage) {
10
- // Extract the parsed payload from the message object
11
- const payload = parsedMessage.payload;
12
- if (!payload) return; // No payload — ignore
13
-
14
- // The payload is already parsed JSON, so we can use it directly
15
- const evt = payload;
16
- if (!evt.type) return; // No type — ignore
17
-
18
- // TPB-12: Route by instanceId/leaseId
19
- const instanceId = evt.instanceId || evt.data?.instanceId || null;
20
- const leaseId = evt.correlationId || evt.data?.leaseId || evt.data?.assignment?.leaseId || null;
21
-
22
- let targetInstanceId = null;
23
- let instanceContext = null;
24
-
25
- // Routing logic:
26
- // 1. If instanceId present: lookup instance registry
27
- // 2. If instanceId unknown but leaseId present: try leaseId resolution (resilience for rotated clientIds)
28
- // 3. If both present but mismatch: log mismatch, prefer instanceId if both resolve
29
- // 4. If neither: try other fallbacks, then drop
30
-
31
- if (instanceId) {
32
- instanceContext = getInstance(instanceId);
33
- if (instanceContext) {
34
- targetInstanceId = instanceId;
35
- } else {
36
- // TPB-12: Don't early-drop on unknown instanceId - try multiple fallbacks
37
- // This preserves resilience for rotated clientIds and initial connections
38
-
39
- // Fallback 1: Try leaseId resolution (for rotated clientIds with existing assignments)
40
- if (leaseId) {
41
- const resolvedInstanceId = resolveInstanceByLease(leaseId);
42
- if (resolvedInstanceId) {
43
- instanceContext = getInstance(resolvedInstanceId);
44
- if (instanceContext) {
45
- targetInstanceId = resolvedInstanceId;
46
- logger.debug('evt.routed.leaseid_fallback', {
47
- unknownInstanceId: instanceId,
48
- resolvedInstanceId,
49
- leaseId,
50
- eventType: evt.type,
51
- requestId: evt.requestId,
52
- note: 'Unknown instanceId; routed via leaseId (likely rotated clientId)'
53
- });
54
- }
55
- }
56
- }
57
-
58
- // Fallback 2: Try requestId resolution (for initial open_ack before assignment exists)
59
- if (!targetInstanceId && evt.requestId) {
60
- const preAssignmentInstanceId = resolveInstanceByRequestId(evt.requestId);
61
- if (preAssignmentInstanceId) {
62
- instanceContext = getInstance(preAssignmentInstanceId);
63
- if (instanceContext) {
64
- targetInstanceId = preAssignmentInstanceId;
65
- logger.debug('evt.routed.requestid_fallback_unknown_instance', {
66
- unknownInstanceId: instanceId,
67
- resolvedInstanceId: targetInstanceId,
68
- requestId: evt.requestId,
69
- leaseId,
70
- eventType: evt.type,
71
- note: 'Unknown instanceId; routed via requestId (initial connection or rotated clientId)'
72
- });
73
- }
74
- }
75
- }
76
-
77
- // Fallback 3: Try matching requestId in existing assignments (for refresh/reconnect)
78
- if (!targetInstanceId && evt.requestId) {
79
- const allInstances = getAllInstances();
80
- for (const inst of allInstances) {
81
- const assignment = getAssignment(inst.instanceId);
82
- if (assignment && assignment.requestId === evt.requestId) {
83
- instanceContext = inst;
84
- targetInstanceId = inst.instanceId;
85
- logger.debug('evt.routed.assignment_requestid_fallback', {
86
- unknownInstanceId: instanceId,
87
- resolvedInstanceId: targetInstanceId,
88
- requestId: evt.requestId,
89
- leaseId,
90
- eventType: evt.type,
91
- note: 'Unknown instanceId; routed via requestId match in assignment'
92
- });
93
- break;
94
- }
95
- }
96
- }
97
-
98
- // Only log/drop if all fallbacks failed
99
- if (!targetInstanceId) {
100
- logger.warn('evt.instance.unknown', {
101
- instanceId,
102
- leaseId,
103
- eventType: evt.type,
104
- requestId: evt.requestId,
105
- note: 'Event dropped - unknown instanceId and all fallbacks failed'
106
- });
107
- return;
108
- }
109
- }
110
- }
111
-
112
- if (leaseId && !targetInstanceId) {
113
- // Fallback to leaseId resolution when instanceId not present
114
- const resolvedInstanceId = resolveInstanceByLease(leaseId);
115
- if (resolvedInstanceId) {
116
- instanceContext = getInstance(resolvedInstanceId);
117
- if (instanceContext) {
118
- targetInstanceId = resolvedInstanceId;
119
- }
120
- }
121
- }
122
-
123
- // Check for mismatch
124
- if (instanceId && leaseId && targetInstanceId) {
125
- const leaseResolvedInstanceId = resolveInstanceByLease(leaseId);
126
- if (leaseResolvedInstanceId && leaseResolvedInstanceId !== instanceId) {
127
- logger.warn('evt.instance.lease_mismatch', {
128
- instanceId,
129
- leaseId,
130
- leaseResolvedInstanceId,
131
- preferredInstanceId: instanceId,
132
- eventType: evt.type,
133
- requestId: evt.requestId
134
- });
135
- // Prefer instanceId (already set above)
136
- }
137
- }
138
-
139
- // TPB-12: Backcompat fallback - if no instanceId/leaseId, try pre-assignment requestId, then assignment requestId, then single-instance
140
- if (!targetInstanceId) {
141
- const allInstances = getAllInstances();
142
-
143
- // Fallback 1: Pre-assignment requestId matching (for initial open_ack before assignment exists)
144
- if (evt.requestId) {
145
- const preAssignmentInstanceId = resolveInstanceByRequestId(evt.requestId);
146
- if (preAssignmentInstanceId) {
147
- instanceContext = getInstance(preAssignmentInstanceId);
148
- if (instanceContext) {
149
- targetInstanceId = preAssignmentInstanceId;
150
- logger.debug('evt.routed.pre_assignment_requestid', {
151
- instanceId: targetInstanceId,
152
- eventType: evt.type,
153
- requestId: evt.requestId,
154
- note: 'No instanceId in event; routed by pre-assignment requestId (backcompat)'
155
- });
156
- }
157
- }
158
- }
159
-
160
- // Fallback 2: Match by requestId in existing assignment (for refresh/reconnect)
161
- if (!targetInstanceId && evt.requestId && allInstances.length > 0) {
162
- // Try to find instance with matching requestId in assignment
163
- for (const inst of allInstances) {
164
- const assignment = getAssignment(inst.instanceId);
165
- if (assignment && assignment.requestId === evt.requestId) {
166
- instanceContext = inst;
167
- targetInstanceId = inst.instanceId;
168
- logger.debug('evt.routed.requestid_match', {
169
- instanceId: targetInstanceId,
170
- eventType: evt.type,
171
- requestId: evt.requestId,
172
- note: 'No instanceId in event; routed by requestId match in assignment (backcompat)'
173
- });
174
- break;
175
- }
176
- }
177
- }
178
-
179
- // Fallback 3: Single registered instance (backcompat for TPB-13)
180
- if (!targetInstanceId && allInstances.length === 1) {
181
- instanceContext = allInstances[0];
182
- targetInstanceId = instanceContext.instanceId;
183
- logger.debug('evt.routed.single_instance_fallback', {
184
- instanceId: targetInstanceId,
185
- eventType: evt.type,
186
- requestId: evt.requestId,
187
- note: 'No instanceId in event; routed to single registered instance (backcompat)'
188
- });
189
- }
190
-
191
- // If still no target, drop event
192
- if (!targetInstanceId) {
193
- if (!unmatchedEventLogged) {
194
- logger.warn('evt.unmatched', {
195
- instanceId,
196
- leaseId,
197
- eventType: evt.type,
198
- requestId: evt.requestId,
199
- registeredInstances: allInstances.length,
200
- note: 'Event dropped - no matching instance. This may be normal for late/unknown events.'
201
- });
202
- unmatchedEventLogged = true;
203
- // Reset after 60 seconds to allow occasional logging
204
- // Store timeout handle for potential cleanup (though module-level cleanup is rare)
205
- const timeoutHandle = setTimeout(() => { unmatchedEventLogged = false; }, 60000);
206
- // In test mode, unref the timeout so it doesn't keep the process alive
207
- if (process.env.JEST_WORKER_ID !== undefined || process.env.NODE_ENV === 'test') {
208
- timeoutHandle.unref();
209
- }
210
- }
211
- return;
212
- }
213
- }
214
-
215
- // Attach instance context to event for handlers
216
- evt._instanceId = targetInstanceId;
217
- evt._instanceContext = instanceContext;
218
-
219
- const handler = getHandler(evt.type);
220
- if (!handler) return; // Unknown type — ignore
221
- return handler(evt);
222
- }
@@ -1,58 +0,0 @@
1
- import { z } from "zod";
2
-
3
- export const Envelope = z.object({
4
- type: z.enum(["setup_required","open_ack","open_reject","error"]),
5
- v: z.literal(1),
6
- requestId: z.string().min(1),
7
- ts: z.number().int().positive(),
8
- data: z.unknown(),
9
- });
10
-
11
- export const SetupRequired = Envelope.extend({
12
- type: z.literal("setup_required"),
13
- data: z.object({ reason: z.string().optional() }),
14
- });
15
-
16
- export const OpenAck = Envelope.extend({
17
- type: z.literal("open_ack"),
18
- data: z.object({
19
- relayId: z.string().min(1),
20
- leaseMs: z.number().int().positive(),
21
- assignment: z.object({
22
- jwt: z.string().min(10),
23
- fqdn: z.string().min(1),
24
- proto: z.string().min(1),
25
- path: z.string().min(1),
26
- kid: z.string().optional(),
27
- alg: z.string().optional(),
28
- exp: z.number().optional(),
29
- }),
30
- }),
31
- });
32
-
33
- // Legacy OpenAck schema for backward compatibility
34
- export const OpenAckLegacy = Envelope.extend({
35
- type: z.literal("open_ack"),
36
- data: z.object({
37
- relayId: z.string().min(1),
38
- jwt: z.string().min(10),
39
- leaseMs: z.number().int().positive(),
40
- }),
41
- });
42
-
43
- export const OpenReject = Envelope.extend({
44
- type: z.literal("open_reject"),
45
- data: z.object({
46
- reason: z.string().min(1),
47
- }),
48
- });
49
-
50
- export const ErrorEvt = Envelope.extend({
51
- type: z.enum(["error"]),
52
- data: z.object({
53
- code: z.string().min(1),
54
- msg: z.string().optional(),
55
- }),
56
- });
57
-
58
- export const AnyEvt = z.union([SetupRequired, OpenAck, OpenAckLegacy, OpenReject, ErrorEvt]);
@@ -1,182 +0,0 @@
1
- /**
2
- * Single Ingress Message Handler
3
- *
4
- * Provides a single point of entry for all MQTT messages that:
5
- * 1. Parses messages once
6
- * 2. Resolves awaiters for request/response flows
7
- * 3. Always forwards messages to the CP-3F dispatcher
8
- *
9
- * This eliminates the handler-order race that prevents CP-3F envelopes
10
- * from being processed and establishes the pattern for future stories.
11
- */
12
-
13
- import { AwaiterMap } from './awaiter-map.js';
14
-
15
- export class MessageIngress {
16
- constructor(options = {}) {
17
- // QPA-CLI-10: Pass logger to AwaiterMap for quiet mode
18
- this.awaiterMap = new AwaiterMap(options.maxAwaiters || 100, options.logger || null);
19
- this.dispatcher = null;
20
- this.observability = options.observability || false;
21
- this.messageCounter = 0;
22
- }
23
-
24
- /**
25
- * Set the CP-3F event dispatcher
26
- * @param {Function} dispatcher - The dispatchEvt function
27
- */
28
- setDispatcher(dispatcher) {
29
- this.dispatcher = dispatcher;
30
- }
31
-
32
- /**
33
- * Register an awaiter for request/response correlation
34
- * @param {Function} criteria - Function that returns true if message matches
35
- * @param {number} timeoutMs - Timeout in milliseconds
36
- * @returns {Promise} Promise that resolves with the matching message
37
- */
38
- registerAwaiter(criteria, timeoutMs = 5000) {
39
- return this.awaiterMap.register(criteria, timeoutMs);
40
- }
41
-
42
- /**
43
- * Cancel awaiters that match a test criteria
44
- * @param {Function} testCriteria - Function that returns true if an awaiter should be cancelled
45
- * @returns {number} Number of awaiters cancelled
46
- */
47
- cancelAwaitersByCriteria(testCriteria) {
48
- return this.awaiterMap.cancelByCriteria(testCriteria);
49
- }
50
-
51
- /**
52
- * Main ingress handler - processes all incoming MQTT messages
53
- * @param {Object} message - Raw MQTT message from transport
54
- */
55
- async handleMessage(message) {
56
- const msgId = ++this.messageCounter;
57
- const ts = Date.now();
58
- const sizeBytes = message.payload ? message.payload.length : 0;
59
-
60
- // Parse message once
61
- let parsedMessage;
62
- let parseStatus = 'success';
63
-
64
- try {
65
- const raw = message.payload;
66
- const buffer =
67
- typeof raw === 'string' ? Buffer.from(raw, 'utf8')
68
- : Buffer.isBuffer(raw) ? raw
69
- : ArrayBuffer.isView(raw) ? Buffer.from(raw.buffer, raw.byteOffset, raw.byteLength)
70
- : raw instanceof ArrayBuffer ? Buffer.from(raw)
71
- : null;
72
-
73
- let parsedPayload;
74
- if (buffer) {
75
- try {
76
- parsedPayload = JSON.parse(buffer.toString('utf8'));
77
- } catch {
78
- parseStatus = 'json_parse_error';
79
- }
80
- }
81
-
82
- parsedMessage = {
83
- topic: message.topic,
84
- payload: parsedPayload,
85
- raw: buffer,
86
- sizeBytes,
87
- msgId,
88
- ts
89
- };
90
- } catch (error) {
91
- parseStatus = 'parse_error';
92
- parsedMessage = {
93
- topic: message.topic,
94
- payload: undefined,
95
- raw: message.payload,
96
- sizeBytes,
97
- msgId,
98
- ts,
99
- error: error.message
100
- };
101
- }
102
-
103
- // Log ingress (CP-5 ready)
104
- if (this.observability) {
105
- console.log(`[ingress] ts=${ts} msgId=${msgId} topic=${parsedMessage.topic} parseStatus=${parseStatus} sizeBytes=${sizeBytes}`);
106
- }
107
-
108
- // Check awaiters and resolve any matching promises
109
- const awaiterResolved = this.awaiterMap.processMessage(parsedMessage);
110
-
111
- // Always dispatch to CP-3F dispatcher (non-exclusive broadcast)
112
- if (this.dispatcher) {
113
- try {
114
- await this.dispatcher(parsedMessage);
115
-
116
- // Log dispatch completion (CP-5 ready)
117
- if (this.observability) {
118
- console.log(`[dispatch] ts=${Date.now()} msgId=${msgId} dispatched=true`);
119
- }
120
- } catch (error) {
121
- // Log dispatch error but don't crash
122
- if (this.observability) {
123
- console.log(`[dispatch] ts=${Date.now()} msgId=${msgId} dispatched=false error=${error.message}`);
124
- }
125
-
126
- // Re-throw dispatcher errors (they contain business logic like exit codes)
127
- throw error;
128
- }
129
- }
130
-
131
- return {
132
- msgId,
133
- awaiterResolved,
134
- parseStatus,
135
- sizeBytes
136
- };
137
- }
138
-
139
- /**
140
- * Get statistics about the ingress system
141
- * @returns {Object} Statistics object
142
- */
143
- getStats() {
144
- return {
145
- messageCounter: this.messageCounter,
146
- awaiterStats: this.awaiterMap.getStats(),
147
- hasDispatcher: !!this.dispatcher,
148
- observabilityEnabled: this.observability
149
- };
150
- }
151
-
152
- /**
153
- * Clear all awaiters (for cleanup)
154
- */
155
- clear() {
156
- this.awaiterMap.clear();
157
- }
158
-
159
- /**
160
- * Create a session ID awaiter (backward compatibility)
161
- * @param {string} sessionId - Session ID to match
162
- * @param {string} expectedTopic - Expected topic pattern
163
- * @param {number} timeoutMs - Timeout in milliseconds
164
- * @returns {Promise} Promise that resolves with the matching message
165
- */
166
- awaitSessionId(sessionId, expectedTopic, timeoutMs = 5000) {
167
- const criteria = AwaiterMap.createSessionIdCriteria(sessionId, expectedTopic);
168
- return this.registerAwaiter(criteria, timeoutMs);
169
- }
170
-
171
- /**
172
- * Create a correlation ID awaiter (future use)
173
- * @param {string} correlationId - Correlation ID to match
174
- * @param {string} expectedTopic - Expected topic pattern
175
- * @param {number} timeoutMs - Timeout in milliseconds
176
- * @returns {Promise} Promise that resolves with the matching message
177
- */
178
- awaitCorrelationId(correlationId, expectedTopic, timeoutMs = 5000) {
179
- const criteria = AwaiterMap.createCorrelationIdCriteria(correlationId, expectedTopic);
180
- return this.registerAwaiter(criteria, timeoutMs);
181
- }
182
- }