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.
- package/README.md +103 -17
- package/SECURITY.md +5 -3
- package/package.json +15 -22
- package/src/commands/name.js +23 -0
- package/src/commands/reject-messages.js +54 -0
- package/src/commands/setup.js +98 -102
- package/src/commands/tunnel.js +304 -2316
- package/src/lib/naming.js +81 -0
- package/src/main.js +24 -6
- package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneClient.d.ts +260 -0
- package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneClient.js +1088 -0
- package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneTransport.d.ts +79 -0
- package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneTransport.js +138 -0
- package/vendor/tunnel-core/dist/control-plane/session.d.ts +50 -0
- package/vendor/tunnel-core/dist/control-plane/session.js +115 -0
- package/vendor/tunnel-core/dist/errors.d.ts +49 -0
- package/vendor/tunnel-core/dist/errors.js +53 -0
- package/vendor/tunnel-core/dist/flows/http.d.ts +50 -0
- package/vendor/tunnel-core/dist/flows/http.js +585 -0
- package/vendor/tunnel-core/dist/flows/tcp.d.ts +60 -0
- package/vendor/tunnel-core/dist/flows/tcp.js +546 -0
- package/vendor/tunnel-core/dist/flows/udp.d.ts +41 -0
- package/vendor/tunnel-core/dist/flows/udp.js +376 -0
- package/vendor/tunnel-core/dist/lib/adapt-logger.d.ts +2 -0
- package/vendor/tunnel-core/dist/lib/adapt-logger.js +6 -0
- package/vendor/tunnel-core/dist/lib/fingerprint.d.ts +13 -0
- package/vendor/tunnel-core/dist/lib/fingerprint.js +95 -0
- package/vendor/tunnel-core/dist/lib/jwt-verifier.d.ts +27 -0
- package/vendor/tunnel-core/dist/lib/jwt-verifier.js +230 -0
- package/vendor/tunnel-core/dist/lib/logger.d.ts +9 -0
- package/vendor/tunnel-core/dist/lib/logger.js +58 -0
- package/vendor/tunnel-core/dist/lib/refresh-helpers.d.ts +16 -0
- package/vendor/tunnel-core/dist/lib/refresh-helpers.js +66 -0
- package/vendor/tunnel-core/dist/lifecycle.d.ts +24 -0
- package/vendor/tunnel-core/dist/lifecycle.js +29 -0
- package/vendor/tunnel-core/dist/mqtt/awaiter-map.d.ts +56 -0
- package/vendor/tunnel-core/dist/mqtt/awaiter-map.js +227 -0
- package/vendor/tunnel-core/dist/mqtt/events/handlers.d.ts +58 -0
- package/vendor/tunnel-core/dist/mqtt/events/handlers.js +250 -0
- package/vendor/tunnel-core/dist/mqtt/events/index.d.ts +1 -0
- package/vendor/tunnel-core/dist/mqtt/events/index.js +191 -0
- package/vendor/tunnel-core/dist/mqtt/events/schemas.d.ts +498 -0
- package/vendor/tunnel-core/dist/mqtt/events/schemas.js +51 -0
- package/vendor/tunnel-core/dist/mqtt/ingress.d.ts +63 -0
- package/vendor/tunnel-core/dist/mqtt/ingress.js +170 -0
- package/vendor/tunnel-core/dist/state/assignment.d.ts +122 -0
- package/vendor/tunnel-core/dist/state/assignment.js +322 -0
- package/vendor/tunnel-core/dist/state/instance-registry.d.ts +88 -0
- package/{src → vendor/tunnel-core/dist}/state/instance-registry.js +38 -53
- package/vendor/tunnel-core/dist/tcp-v1/framing.d.ts +43 -0
- package/vendor/tunnel-core/dist/tcp-v1/framing.js +157 -0
- package/vendor/tunnel-core/dist/tunnel/http-tunnel.d.ts +137 -0
- package/vendor/tunnel-core/dist/tunnel/http-tunnel.js +1591 -0
- package/vendor/tunnel-core/dist/tunnel/httpws-constants.d.ts +13 -0
- package/{src → vendor/tunnel-core/dist}/tunnel/httpws-constants.js +5 -7
- package/vendor/tunnel-core/dist/tunnel/reconnect.d.ts +76 -0
- package/vendor/tunnel-core/dist/tunnel/reconnect.js +183 -0
- package/vendor/tunnel-core/dist/tunnel/request-sink.d.ts +40 -0
- package/vendor/tunnel-core/dist/tunnel/request-sink.js +39 -0
- package/vendor/tunnel-core/dist/tunnel/tcp-tunnel.d.ts +89 -0
- package/vendor/tunnel-core/dist/tunnel/tcp-tunnel.js +838 -0
- package/vendor/tunnel-core/dist/tunnel/udp-tunnel.d.ts +90 -0
- package/vendor/tunnel-core/dist/tunnel/udp-tunnel.js +737 -0
- package/vendor/tunnel-core/dist/tunnel/ws-control.d.ts +22 -0
- package/vendor/tunnel-core/dist/tunnel/ws-control.js +124 -0
- package/vendor/tunnel-core/dist/types.d.ts +24 -0
- package/vendor/tunnel-core/dist/types.js +2 -0
- package/vendor/tunnel-core/dist/udp-v1/framing.d.ts +41 -0
- package/vendor/tunnel-core/dist/udp-v1/framing.js +158 -0
- package/vendor/tunnel-core/package.json +34 -0
- package/src/control-plane/MqttControlPlaneClient.js +0 -1196
- package/src/control-plane/MqttControlPlaneTransport.js +0 -150
- package/src/lib/fingerprint.js +0 -115
- package/src/lib/jwt-verifier.js +0 -260
- package/src/lib/logger.js +0 -62
- package/src/mqtt/awaiter-map.js +0 -247
- package/src/mqtt/events/handlers.js +0 -300
- package/src/mqtt/events/index.js +0 -222
- package/src/mqtt/events/schemas.js +0 -58
- package/src/mqtt/ingress.js +0 -182
- package/src/state/assignment.js +0 -333
- package/src/tcp-v1/framing.js +0 -203
- package/src/tunnel/http-tunnel.js +0 -1694
- package/src/tunnel/tcp-tunnel.js +0 -862
- package/src/tunnel/udp-tunnel.js +0 -708
- package/src/tunnel/ws-control.js +0 -135
- package/src/udp-v1/framing.js +0 -203
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AwaiterMap - Manages request/response correlation for MQTT messages
|
|
3
|
+
*
|
|
4
|
+
* Provides a bounded map of awaiters that can be resolved by incoming messages.
|
|
5
|
+
* Each awaiter has a criteria function and timeout, and will be automatically
|
|
6
|
+
* cleaned up on resolve, reject, or timeout.
|
|
7
|
+
*/
|
|
8
|
+
export class AwaiterMap {
|
|
9
|
+
constructor(maxSize = 100, logger = null) {
|
|
10
|
+
this.maxSize = maxSize;
|
|
11
|
+
this.awaiters = new Map();
|
|
12
|
+
this.nextId = 1;
|
|
13
|
+
this.logger = logger; // QPA-CLI-10: Optional logger for quiet mode
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Register an awaiter that will be resolved when a message matches the criteria
|
|
17
|
+
* @param {Function} criteria - Function that returns true if message matches
|
|
18
|
+
* @param {number} timeoutMs - Timeout in milliseconds
|
|
19
|
+
* @returns {Promise} Promise that resolves with the matching message
|
|
20
|
+
*/
|
|
21
|
+
register(criteria, timeoutMs = 5000) {
|
|
22
|
+
if (this.awaiters.size >= this.maxSize) {
|
|
23
|
+
throw new Error(`AwaiterMap is at capacity (${this.maxSize}). Cannot register more awaiters.`);
|
|
24
|
+
}
|
|
25
|
+
const id = this.nextId++;
|
|
26
|
+
const awaiter = {
|
|
27
|
+
id,
|
|
28
|
+
criteria,
|
|
29
|
+
timeoutMs,
|
|
30
|
+
resolve: null,
|
|
31
|
+
reject: null,
|
|
32
|
+
timeoutId: null,
|
|
33
|
+
createdAt: Date.now()
|
|
34
|
+
};
|
|
35
|
+
const promise = new Promise((resolve, reject) => {
|
|
36
|
+
awaiter.resolve = resolve;
|
|
37
|
+
awaiter.reject = reject;
|
|
38
|
+
});
|
|
39
|
+
// Set up timeout
|
|
40
|
+
awaiter.timeoutId = setTimeout(() => {
|
|
41
|
+
this.awaiters.delete(id);
|
|
42
|
+
awaiter.reject(new Error(`Awaiter ${id} timed out after ${timeoutMs}ms`));
|
|
43
|
+
}, timeoutMs);
|
|
44
|
+
this.awaiters.set(id, awaiter);
|
|
45
|
+
return promise;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Process an incoming message against all registered awaiters
|
|
49
|
+
* @param {Object} message - Message object with topic and payload
|
|
50
|
+
* @returns {boolean} True if any awaiter was resolved
|
|
51
|
+
*/
|
|
52
|
+
processMessage(message) {
|
|
53
|
+
let resolved = false;
|
|
54
|
+
// Log open_ack messages for debugging awaiter matching
|
|
55
|
+
const isOpenAck = message.payload?.type === 'open_ack';
|
|
56
|
+
const requestId = message.payload?.requestId;
|
|
57
|
+
if (isOpenAck && requestId) {
|
|
58
|
+
// QPA-CLI-10: Use logger at debug level for quiet mode
|
|
59
|
+
if (this.logger) {
|
|
60
|
+
this.logger.debug('awaiter.open_ack.received', {
|
|
61
|
+
requestId,
|
|
62
|
+
topic: message.topic,
|
|
63
|
+
pendingAwaiters: this.awaiters.size,
|
|
64
|
+
awaiterIds: Array.from(this.awaiters.keys())
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
for (const [id, awaiter] of this.awaiters) {
|
|
69
|
+
try {
|
|
70
|
+
const matched = awaiter.criteria(message);
|
|
71
|
+
if (isOpenAck && requestId) {
|
|
72
|
+
// QPA-CLI-10: Use logger at debug level for quiet mode
|
|
73
|
+
if (this.logger) {
|
|
74
|
+
this.logger.debug('awaiter.open_ack.checked', {
|
|
75
|
+
requestId,
|
|
76
|
+
awaiterId: id,
|
|
77
|
+
matched,
|
|
78
|
+
topic: message.topic
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
if (matched) {
|
|
83
|
+
// Clear timeout and resolve
|
|
84
|
+
clearTimeout(awaiter.timeoutId);
|
|
85
|
+
this.awaiters.delete(id);
|
|
86
|
+
awaiter.resolve(message);
|
|
87
|
+
resolved = true;
|
|
88
|
+
if (isOpenAck && requestId) {
|
|
89
|
+
// QPA-CLI-10: Use logger at debug level for quiet mode
|
|
90
|
+
if (this.logger) {
|
|
91
|
+
this.logger.debug('awaiter.open_ack.resolved', {
|
|
92
|
+
requestId,
|
|
93
|
+
awaiterId: id,
|
|
94
|
+
topic: message.topic
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
catch (error) {
|
|
101
|
+
// Criteria function threw an error - reject and clean up
|
|
102
|
+
clearTimeout(awaiter.timeoutId);
|
|
103
|
+
this.awaiters.delete(id);
|
|
104
|
+
awaiter.reject(error);
|
|
105
|
+
resolved = true;
|
|
106
|
+
if (isOpenAck && requestId) {
|
|
107
|
+
// QPA-CLI-10: Use logger at debug level for quiet mode
|
|
108
|
+
if (this.logger) {
|
|
109
|
+
this.logger.debug('awaiter.open_ack.criteria_error', {
|
|
110
|
+
requestId,
|
|
111
|
+
awaiterId: id,
|
|
112
|
+
error: error.message,
|
|
113
|
+
topic: message.topic
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
if (isOpenAck && requestId && !resolved) {
|
|
120
|
+
// QPA-CLI-10: Use logger at debug level for quiet mode (no_match is expected when awaiter already resolved)
|
|
121
|
+
if (this.logger) {
|
|
122
|
+
this.logger.debug('awaiter.open_ack.no_match', {
|
|
123
|
+
requestId,
|
|
124
|
+
topic: message.topic,
|
|
125
|
+
pendingAwaiters: this.awaiters.size,
|
|
126
|
+
payloadType: message.payload?.type,
|
|
127
|
+
payloadRequestId: message.payload?.requestId
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return resolved;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Get current statistics about the awaiter map
|
|
135
|
+
* @returns {Object} Statistics object
|
|
136
|
+
*/
|
|
137
|
+
getStats() {
|
|
138
|
+
const now = Date.now();
|
|
139
|
+
const ages = Array.from(this.awaiters.values()).map(a => now - a.createdAt);
|
|
140
|
+
return {
|
|
141
|
+
count: this.awaiters.size,
|
|
142
|
+
maxSize: this.maxSize,
|
|
143
|
+
utilization: this.awaiters.size / this.maxSize,
|
|
144
|
+
oldestAge: ages.length > 0 ? Math.max(...ages) : 0,
|
|
145
|
+
averageAge: ages.length > 0 ? ages.reduce((a, b) => a + b, 0) / ages.length : 0
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Cancel awaiters that match a test criteria
|
|
150
|
+
* @param {Function} testCriteria - Function that returns true if an awaiter should be cancelled
|
|
151
|
+
* @returns {number} Number of awaiters cancelled
|
|
152
|
+
*/
|
|
153
|
+
cancelByCriteria(testCriteria) {
|
|
154
|
+
let cancelled = 0;
|
|
155
|
+
for (const [id, awaiter] of this.awaiters) {
|
|
156
|
+
try {
|
|
157
|
+
if (testCriteria(awaiter)) {
|
|
158
|
+
clearTimeout(awaiter.timeoutId);
|
|
159
|
+
this.awaiters.delete(id);
|
|
160
|
+
awaiter.reject(new Error(`Awaiter ${id} cancelled by criteria`));
|
|
161
|
+
cancelled++;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
catch (error) {
|
|
165
|
+
// Test criteria threw an error - skip this awaiter
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
return cancelled;
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Clear all awaiters (for cleanup)
|
|
173
|
+
*/
|
|
174
|
+
clear() {
|
|
175
|
+
for (const [id, awaiter] of this.awaiters) {
|
|
176
|
+
clearTimeout(awaiter.timeoutId);
|
|
177
|
+
awaiter.reject(new Error(`AwaiterMap cleared - awaiter ${id} cancelled`));
|
|
178
|
+
}
|
|
179
|
+
this.awaiters.clear();
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Create a criteria function for session ID matching (backward compatibility)
|
|
183
|
+
* @param {string} sessionId - Session ID to match
|
|
184
|
+
* @param {string} expectedTopic - Expected topic pattern
|
|
185
|
+
* @returns {Function} Criteria function
|
|
186
|
+
*/
|
|
187
|
+
static createSessionIdCriteria(sessionId, expectedTopic) {
|
|
188
|
+
return (message) => {
|
|
189
|
+
if (message.topic !== expectedTopic) {
|
|
190
|
+
return false;
|
|
191
|
+
}
|
|
192
|
+
try {
|
|
193
|
+
const raw = message.payload;
|
|
194
|
+
const payload = typeof raw === 'object' && raw !== null && !Buffer.isBuffer(raw)
|
|
195
|
+
? raw
|
|
196
|
+
: JSON.parse(Buffer.isBuffer(raw) ? raw.toString() : String(raw));
|
|
197
|
+
return payload.sessionId === sessionId;
|
|
198
|
+
}
|
|
199
|
+
catch {
|
|
200
|
+
return false;
|
|
201
|
+
}
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Create a criteria function for correlation ID matching (future use)
|
|
206
|
+
* @param {string} correlationId - Correlation ID to match
|
|
207
|
+
* @param {string} expectedTopic - Expected topic pattern
|
|
208
|
+
* @returns {Function} Criteria function
|
|
209
|
+
*/
|
|
210
|
+
static createCorrelationIdCriteria(correlationId, expectedTopic) {
|
|
211
|
+
return (message) => {
|
|
212
|
+
if (message.topic !== expectedTopic) {
|
|
213
|
+
return false;
|
|
214
|
+
}
|
|
215
|
+
try {
|
|
216
|
+
const raw = message.payload;
|
|
217
|
+
const payload = typeof raw === 'object' && raw !== null && !Buffer.isBuffer(raw)
|
|
218
|
+
? raw
|
|
219
|
+
: JSON.parse(Buffer.isBuffer(raw) ? raw.toString() : String(raw));
|
|
220
|
+
return payload.correlationId === correlationId;
|
|
221
|
+
}
|
|
222
|
+
catch {
|
|
223
|
+
return false;
|
|
224
|
+
}
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/** Register how open rejections are reported to the user (the CLI does; the SDK uses errors). */
|
|
2
|
+
export function setOpenRejectReporter(fn: any): void;
|
|
3
|
+
export function getHandler(type: any): any;
|
|
4
|
+
export function parseAny(raw: any): {
|
|
5
|
+
requestId?: string;
|
|
6
|
+
type?: "setup_required";
|
|
7
|
+
v?: 1;
|
|
8
|
+
ts?: number;
|
|
9
|
+
data?: {
|
|
10
|
+
reason?: string;
|
|
11
|
+
};
|
|
12
|
+
} | {
|
|
13
|
+
requestId?: string;
|
|
14
|
+
type?: "open_ack";
|
|
15
|
+
v?: 1;
|
|
16
|
+
ts?: number;
|
|
17
|
+
data?: {
|
|
18
|
+
assignment?: {
|
|
19
|
+
path?: string;
|
|
20
|
+
jwt?: string;
|
|
21
|
+
fqdn?: string;
|
|
22
|
+
proto?: string;
|
|
23
|
+
kid?: string;
|
|
24
|
+
alg?: string;
|
|
25
|
+
exp?: number;
|
|
26
|
+
};
|
|
27
|
+
relayId?: string;
|
|
28
|
+
leaseMs?: number;
|
|
29
|
+
};
|
|
30
|
+
} | {
|
|
31
|
+
requestId?: string;
|
|
32
|
+
type?: "open_ack";
|
|
33
|
+
v?: 1;
|
|
34
|
+
ts?: number;
|
|
35
|
+
data?: {
|
|
36
|
+
relayId?: string;
|
|
37
|
+
leaseMs?: number;
|
|
38
|
+
jwt?: string;
|
|
39
|
+
};
|
|
40
|
+
} | {
|
|
41
|
+
requestId?: string;
|
|
42
|
+
type?: "open_reject";
|
|
43
|
+
v?: 1;
|
|
44
|
+
ts?: number;
|
|
45
|
+
data?: {
|
|
46
|
+
reason?: string;
|
|
47
|
+
};
|
|
48
|
+
} | {
|
|
49
|
+
requestId?: string;
|
|
50
|
+
type?: "error";
|
|
51
|
+
v?: 1;
|
|
52
|
+
ts?: number;
|
|
53
|
+
data?: {
|
|
54
|
+
code?: string;
|
|
55
|
+
msg?: string;
|
|
56
|
+
};
|
|
57
|
+
};
|
|
58
|
+
export const FATAL_REJECT_CODES: Set<string>;
|
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
import { AnyEvt as AnyEvtSchema } from "./schemas.js";
|
|
2
|
+
import { setAssignment, getAssignment } from "../../state/assignment.js";
|
|
3
|
+
import logger from "../../lib/logger.js";
|
|
4
|
+
import { RefusedError } from "../../errors.js";
|
|
5
|
+
// Story 12.1 (step 2b): refusals that end the open (QPA-04, TCP-S3, TPB-03B). Codes are the
|
|
6
|
+
// coordinator's reasons, lower-cased.
|
|
7
|
+
export const FATAL_REJECT_CODES = new Set([
|
|
8
|
+
'invalid_secgroup', 'tcp_port_out_of_block', 'tcp_port_already_in_use', 'tcp_port_block_exhausted_for_tenant',
|
|
9
|
+
'tcp_port_block_exhausted', 'tcp_port_capacity_exhausted', 'tenant_tcp_lease_limit_reached',
|
|
10
|
+
]);
|
|
11
|
+
let openRejectReporter = null;
|
|
12
|
+
/** Register how open rejections are reported to the user (the CLI does; the SDK uses errors). */
|
|
13
|
+
export function setOpenRejectReporter(fn) { openRejectReporter = fn; }
|
|
14
|
+
/**
|
|
15
|
+
* Format milliseconds to human-readable hours:minutes
|
|
16
|
+
* @param {number} ms - Milliseconds
|
|
17
|
+
* @returns {string} Formatted string like "1h 30m" or "45m"
|
|
18
|
+
*/
|
|
19
|
+
function formatLeaseDuration(ms) {
|
|
20
|
+
const totalMinutes = Math.floor(ms / 60000);
|
|
21
|
+
const hours = Math.floor(totalMinutes / 60);
|
|
22
|
+
const minutes = totalMinutes % 60;
|
|
23
|
+
if (hours > 0 && minutes > 0) {
|
|
24
|
+
return `${hours}h ${minutes}m`;
|
|
25
|
+
}
|
|
26
|
+
else if (hours > 0) {
|
|
27
|
+
return `${hours}h`;
|
|
28
|
+
}
|
|
29
|
+
else {
|
|
30
|
+
return `${minutes}m`;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
const registry = {
|
|
34
|
+
async setup_required(e) {
|
|
35
|
+
// Minimal user-facing message; CLI should exit(2)
|
|
36
|
+
// Do not add logs; leave control to caller via thrown Error with code.
|
|
37
|
+
const reason = e.data?.reason ? ` (${e.data.reason})` : "";
|
|
38
|
+
const err = /** @type {Error & { code?: string, cause?: unknown, closeCode?: number, originalError?: unknown }} */ (new Error(`Please run "asyx setup"${reason}`));
|
|
39
|
+
err.code = "SETUP_REQUIRED";
|
|
40
|
+
throw err;
|
|
41
|
+
},
|
|
42
|
+
async open_ack(e) {
|
|
43
|
+
// TPB-12: Route by instanceId - get instance context from dispatcher
|
|
44
|
+
const instanceId = e._instanceId;
|
|
45
|
+
const instanceContext = e._instanceContext;
|
|
46
|
+
if (!instanceId || !instanceContext) {
|
|
47
|
+
logger.warn('open_ack.unknown_instance', {
|
|
48
|
+
requestId: e.requestId,
|
|
49
|
+
instanceId: e.instanceId || e.data?.instanceId || null,
|
|
50
|
+
leaseId: e.correlationId || e.data?.leaseId || null,
|
|
51
|
+
note: 'Event dropped - no matching instance context'
|
|
52
|
+
});
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
// Normalize legacy format to canonical format
|
|
56
|
+
let data = e.data;
|
|
57
|
+
// Legacy format: { data: { jwt, relayId, leaseMs } }
|
|
58
|
+
// Canonical format: { data: { relayId, leaseMs, assignment: { jwt, fqdn, proto, path, ... } } }
|
|
59
|
+
if (data.jwt && !data.assignment) {
|
|
60
|
+
// Transform legacy to canonical
|
|
61
|
+
data = {
|
|
62
|
+
relayId: data.relayId,
|
|
63
|
+
leaseMs: data.leaseMs,
|
|
64
|
+
assignment: {
|
|
65
|
+
jwt: data.jwt,
|
|
66
|
+
fqdn: 'relay.customer.example', // Default fallback
|
|
67
|
+
proto: 'wss',
|
|
68
|
+
path: '/agent'
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
// QPA-CLI-11: Store QuickPass info in assignment for vault UX messaging
|
|
73
|
+
// Suppress QP: enabled and Ack received messages - they'll be consolidated in final tunnel.active message
|
|
74
|
+
const quickpassSlug = data.quickpass?.slug || null;
|
|
75
|
+
if (quickpassSlug) {
|
|
76
|
+
logger.info("qp.enabled", {
|
|
77
|
+
group: quickpassSlug,
|
|
78
|
+
instanceId,
|
|
79
|
+
tunnelType: instanceContext.tunnelType
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
// Build relay URL with fallbacks for missing fields
|
|
83
|
+
// TCP-S4: Add fallbacks to prevent malformed URLs if TCP assignments omit fields
|
|
84
|
+
// UDP-S1: Add UDP support
|
|
85
|
+
const proto = data.assignment?.proto || 'wss';
|
|
86
|
+
const fqdn = data.assignment?.fqdn || data.fqdn || 'relay.unknown';
|
|
87
|
+
// TCP-S4: Always use /tcp for TCP tunnels, /agent for HTTP tunnels
|
|
88
|
+
// UDP-S1: Always use /udp for UDP tunnels
|
|
89
|
+
// Detect tunnel type by checking for publicPort (TCP/UDP-specific) or proto/tunnelMode
|
|
90
|
+
const isTcpTunnel = (data.assignment?.publicPort !== undefined ||
|
|
91
|
+
data.assignment?.proto === 'tcp' ||
|
|
92
|
+
data.publicPort !== undefined) &&
|
|
93
|
+
data.assignment?.tunnelMode !== 'udpWs-v1' &&
|
|
94
|
+
data.assignment?.protocol !== 'udp';
|
|
95
|
+
const isUdpTunnel = data.assignment?.tunnelMode === 'udpWs-v1' ||
|
|
96
|
+
data.assignment?.protocol === 'udp' ||
|
|
97
|
+
instanceContext.tunnelType === 'udp';
|
|
98
|
+
// Always override path for TCP/UDP tunnels, regardless of what the control plane returns
|
|
99
|
+
let path;
|
|
100
|
+
if (isUdpTunnel) {
|
|
101
|
+
path = '/udp';
|
|
102
|
+
}
|
|
103
|
+
else if (isTcpTunnel) {
|
|
104
|
+
path = '/tcp';
|
|
105
|
+
}
|
|
106
|
+
else {
|
|
107
|
+
path = data.assignment?.path || '/agent';
|
|
108
|
+
}
|
|
109
|
+
const url = `${proto}://${fqdn}${path}`;
|
|
110
|
+
// Log warning if fallbacks were used
|
|
111
|
+
if (!data.assignment?.proto || !data.assignment?.fqdn || !data.assignment?.path) {
|
|
112
|
+
logger.warn('open_ack.relay_url_fallback', {
|
|
113
|
+
requestId: e.requestId,
|
|
114
|
+
instanceId,
|
|
115
|
+
tunnelType: instanceContext.tunnelType,
|
|
116
|
+
proto: data.assignment?.proto || 'missing',
|
|
117
|
+
fqdn: data.assignment?.fqdn || 'missing',
|
|
118
|
+
path: data.assignment?.path || 'missing',
|
|
119
|
+
constructedUrl: url
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
// Store assignment in memory (never to disk)
|
|
123
|
+
const leaseId = e.correlationId || data.leaseId || data.assignment?.leaseId || null;
|
|
124
|
+
logger.debug("open_ack.lease_id", {
|
|
125
|
+
requestId: e.requestId,
|
|
126
|
+
instanceId,
|
|
127
|
+
leaseId,
|
|
128
|
+
tunnelType: instanceContext.tunnelType
|
|
129
|
+
});
|
|
130
|
+
// Check if this is a refresh (existing assignment) or initial connection
|
|
131
|
+
const existingAssignment = instanceContext.getAssignment(instanceId);
|
|
132
|
+
const isRefresh = existingAssignment !== null;
|
|
133
|
+
// TCP-S3: Extract TCP-specific fields from assignment
|
|
134
|
+
// E3-S8: Extract SRV status for Minecraft tunnels
|
|
135
|
+
// Reuse fqdn from above (already declared for relayUrl construction)
|
|
136
|
+
const tcpAliasFqdn = data.assignment?.tcpAliasFqdn || data.tcpAliasFqdn || null;
|
|
137
|
+
const publicPort = data.assignment?.publicPort || data.publicPort || null;
|
|
138
|
+
const srvProvisioned = data.assignment?.srvProvisioned === true;
|
|
139
|
+
const srvFqdn = data.assignment?.srvFqdn || null;
|
|
140
|
+
const warnings = data.warnings || data.assignment?.warnings || [];
|
|
141
|
+
// Extract JWT with null safety (required for tunnel authentication)
|
|
142
|
+
const jwt = data.assignment?.jwt || data.jwt || null;
|
|
143
|
+
if (!jwt) {
|
|
144
|
+
logger.error('open_ack.missing_jwt', {
|
|
145
|
+
requestId: e.requestId,
|
|
146
|
+
instanceId,
|
|
147
|
+
tunnelType: instanceContext.tunnelType,
|
|
148
|
+
hasAssignment: !!data.assignment,
|
|
149
|
+
hasDataJwt: !!data.jwt
|
|
150
|
+
});
|
|
151
|
+
throw new Error('Missing JWT in assignment');
|
|
152
|
+
}
|
|
153
|
+
// UDP-S1: Extract UDP-specific fields from assignment
|
|
154
|
+
const tunnelMode = data.assignment?.tunnelMode || data.tunnelMode || null;
|
|
155
|
+
const protocol = data.assignment?.protocol || data.protocol || null;
|
|
156
|
+
const assignmentJwt = data.assignment?.assignmentJwt || data.assignmentJwt || jwt; // UDP-S1: Use assignmentJwt if available
|
|
157
|
+
// TPB-12: Use per-instance setAssignment
|
|
158
|
+
instanceContext.setAssignment(instanceId, {
|
|
159
|
+
requestId: e.requestId,
|
|
160
|
+
relayId: data.relayId,
|
|
161
|
+
relayUrl: url,
|
|
162
|
+
jwt: assignmentJwt, // UDP-S1: Use assignmentJwt if available, fallback to jwt
|
|
163
|
+
assignmentJwt: assignmentJwt, // UDP-S1: Store assignmentJwt separately
|
|
164
|
+
leaseMs: data.leaseMs,
|
|
165
|
+
leaseId,
|
|
166
|
+
quickpassSlug, // QPA-CLI-11: Store QuickPass slug for vault UX messaging
|
|
167
|
+
// TCP-S3: Store TCP-specific fields
|
|
168
|
+
tcpAliasFqdn,
|
|
169
|
+
publicPort,
|
|
170
|
+
fqdn,
|
|
171
|
+
// E3-S8: Store SRV provisioning status
|
|
172
|
+
srvProvisioned,
|
|
173
|
+
srvFqdn,
|
|
174
|
+
warnings,
|
|
175
|
+
// UDP-S1: Store UDP-specific fields
|
|
176
|
+
tunnelMode,
|
|
177
|
+
protocol
|
|
178
|
+
});
|
|
179
|
+
logger.debug("open_ack.assignment_stored", {
|
|
180
|
+
requestId: e.requestId,
|
|
181
|
+
instanceId,
|
|
182
|
+
leaseId,
|
|
183
|
+
tunnelType: instanceContext.tunnelType,
|
|
184
|
+
isRefresh,
|
|
185
|
+
quickpassSlug,
|
|
186
|
+
tcpAliasFqdn,
|
|
187
|
+
publicPort,
|
|
188
|
+
hasWarnings: warnings.length > 0
|
|
189
|
+
});
|
|
190
|
+
// TCP-S3: Handle TCP_ALIAS_UNAVAILABLE warning (warn-only, don't fail)
|
|
191
|
+
if (warnings.includes('TCP_ALIAS_UNAVAILABLE') || warnings.some(w => w.code === 'TCP_ALIAS_UNAVAILABLE')) {
|
|
192
|
+
logger.warn('tcp.alias.unavailable', {
|
|
193
|
+
requestId: e.requestId,
|
|
194
|
+
instanceId,
|
|
195
|
+
tunnelType: instanceContext.tunnelType,
|
|
196
|
+
fqdn,
|
|
197
|
+
publicPort
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
// QPA-CLI-11: Suppress all intermediate messages (QP: enabled, Ack received)
|
|
201
|
+
// These will be consolidated into the final vault UX sequence
|
|
202
|
+
},
|
|
203
|
+
async open_reject(e) {
|
|
204
|
+
// Story 12.1 (step 2b): the core holds no user-facing text and never exits. It works out the
|
|
205
|
+
// coordinator's reason and hands it to the reporter the caller registered (the CLI prints the
|
|
206
|
+
// same messages and exits where it always has). Without a reporter (SDK use), a refusal that
|
|
207
|
+
// ends the tunnel throws a RefusedError carrying the coordinator's reason as its code.
|
|
208
|
+
const d = e.data || {};
|
|
209
|
+
// TPB-12: Clean up expected requestId on rejection (prevents map leak)
|
|
210
|
+
const instanceId = e._instanceId || null;
|
|
211
|
+
if (instanceId) {
|
|
212
|
+
try {
|
|
213
|
+
const { clearExpectedRequestId } = await import("../../state/instance-registry.js");
|
|
214
|
+
clearExpectedRequestId(instanceId);
|
|
215
|
+
}
|
|
216
|
+
catch (err) {
|
|
217
|
+
// Ignore cleanup errors (module may not be available in all contexts)
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
const code = String(d.reason || 'refused').toLowerCase();
|
|
221
|
+
const report = { code, reason: d.reason, fatal: FATAL_REJECT_CODES.has(code), data: d, instanceId };
|
|
222
|
+
if (openRejectReporter) {
|
|
223
|
+
await openRejectReporter(report);
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
if (report.fatal)
|
|
227
|
+
throw new RefusedError(code, `coordinator refused the open: ${d.reason}`, { details: d });
|
|
228
|
+
},
|
|
229
|
+
async error(e) {
|
|
230
|
+
const d = e.data || {};
|
|
231
|
+
const err = /** @type {Error & { code?: string, cause?: unknown, closeCode?: number, originalError?: unknown }} */ (new Error(d.msg || "Command failed"));
|
|
232
|
+
err.code = `ERROR_${String(d.code || "UNKNOWN").toUpperCase()}`;
|
|
233
|
+
throw err;
|
|
234
|
+
},
|
|
235
|
+
};
|
|
236
|
+
export function getHandler(type) {
|
|
237
|
+
return registry[type];
|
|
238
|
+
}
|
|
239
|
+
// Safe parse helper the caller can reuse if needed
|
|
240
|
+
export function parseAny(raw) {
|
|
241
|
+
try {
|
|
242
|
+
const txt = typeof raw === "string" ? raw : new TextDecoder().decode(raw);
|
|
243
|
+
const json = JSON.parse(txt);
|
|
244
|
+
const parsed = AnyEvtSchema.safeParse(json);
|
|
245
|
+
return parsed.success ? parsed.data : null;
|
|
246
|
+
}
|
|
247
|
+
catch (e) {
|
|
248
|
+
return null;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export function dispatch(parsedMessage: any): Promise<any>;
|