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.
- package/README.md +71 -9
- package/SECURITY.md +5 -3
- package/package.json +13 -23
- 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 +279 -2425
- package/src/lib/naming.js +81 -0
- package/src/main.js +9 -1
- 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 -1738
- package/src/tunnel/reconnect.js +0 -182
- package/src/tunnel/tcp-tunnel.js +0 -944
- package/src/tunnel/udp-tunnel.js +0 -813
- package/src/tunnel/ws-control.js +0 -135
- package/src/udp-v1/framing.js +0 -203
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Transport adapter that wraps MqttControlPlaneClient.
|
|
3
|
+
* Implements the Transport interface from @asyx/mqtt-core.
|
|
4
|
+
*/
|
|
5
|
+
export class MqttControlPlaneTransport {
|
|
6
|
+
/**
|
|
7
|
+
* @param {MqttControlPlaneClient} client
|
|
8
|
+
*/
|
|
9
|
+
constructor(client: MqttControlPlaneClient);
|
|
10
|
+
client: MqttControlPlaneClient;
|
|
11
|
+
_messageHandler: (message: {
|
|
12
|
+
topic: string;
|
|
13
|
+
payload: Uint8Array;
|
|
14
|
+
}) => void;
|
|
15
|
+
_connectHandler: () => void;
|
|
16
|
+
_disconnectHandler: (err?: unknown) => void;
|
|
17
|
+
/**
|
|
18
|
+
* Transport interface: connect
|
|
19
|
+
* @param {any} opts - ConnectOptions (ignored, client manages its own connection)
|
|
20
|
+
* @returns {Promise<void>}
|
|
21
|
+
*/
|
|
22
|
+
connect(opts: any): Promise<void>;
|
|
23
|
+
/**
|
|
24
|
+
* Transport interface: end
|
|
25
|
+
* @returns {Promise<void>}
|
|
26
|
+
*/
|
|
27
|
+
end(): Promise<void>;
|
|
28
|
+
/**
|
|
29
|
+
* Transport interface: publish
|
|
30
|
+
* @param {{topic: string, payload: string | Buffer | Uint8Array, qos?: 0 | 1, retain?: boolean}} p
|
|
31
|
+
* @returns {Promise<void>}
|
|
32
|
+
*/
|
|
33
|
+
publish(p: {
|
|
34
|
+
topic: string;
|
|
35
|
+
payload: string | Buffer | Uint8Array;
|
|
36
|
+
qos?: 0 | 1;
|
|
37
|
+
retain?: boolean;
|
|
38
|
+
}): Promise<void>;
|
|
39
|
+
/**
|
|
40
|
+
* Transport interface: subscribe
|
|
41
|
+
* @param {string} topic
|
|
42
|
+
* @param {0 | 1} [qos=0]
|
|
43
|
+
* @returns {Promise<{topic: string, qos: 0 | 1}>}
|
|
44
|
+
*/
|
|
45
|
+
subscribe(topic: string, qos?: 0 | 1): Promise<{
|
|
46
|
+
topic: string;
|
|
47
|
+
qos: 0 | 1;
|
|
48
|
+
}>;
|
|
49
|
+
/**
|
|
50
|
+
* Transport interface: unsubscribe
|
|
51
|
+
* @param {string} topic
|
|
52
|
+
* @returns {Promise<void>}
|
|
53
|
+
*/
|
|
54
|
+
unsubscribe(topic: string): Promise<void>;
|
|
55
|
+
/**
|
|
56
|
+
* Transport interface: onMessage
|
|
57
|
+
* @param {(message: {topic: string, payload: Uint8Array}) => void} cb
|
|
58
|
+
*/
|
|
59
|
+
onMessage(cb: (message: {
|
|
60
|
+
topic: string;
|
|
61
|
+
payload: Uint8Array;
|
|
62
|
+
}) => void): void;
|
|
63
|
+
/**
|
|
64
|
+
* Transport interface: onConnect
|
|
65
|
+
* @param {() => void} cb
|
|
66
|
+
*/
|
|
67
|
+
onConnect(cb: () => void): void;
|
|
68
|
+
/**
|
|
69
|
+
* Transport interface: onDisconnect
|
|
70
|
+
* @param {(err?: unknown) => void} cb
|
|
71
|
+
*/
|
|
72
|
+
onDisconnect(cb: (err?: unknown) => void): void;
|
|
73
|
+
/**
|
|
74
|
+
* Expose client for helpers that need direct access
|
|
75
|
+
* @returns {MqttControlPlaneClient}
|
|
76
|
+
*/
|
|
77
|
+
getClient(): MqttControlPlaneClient;
|
|
78
|
+
}
|
|
79
|
+
import { MqttControlPlaneClient } from './MqttControlPlaneClient.js';
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MqttControlPlaneTransport
|
|
3
|
+
*
|
|
4
|
+
* Adapter that wraps MqttControlPlaneClient to implement the Transport interface
|
|
5
|
+
* required by MqttCore. This allows us to use MqttControlPlaneClient for connection
|
|
6
|
+
* management while still using MqttCore for the higher-level API.
|
|
7
|
+
*/
|
|
8
|
+
import { MqttControlPlaneClient } from './MqttControlPlaneClient.js';
|
|
9
|
+
/**
|
|
10
|
+
* Transport adapter that wraps MqttControlPlaneClient.
|
|
11
|
+
* Implements the Transport interface from @asyx/mqtt-core.
|
|
12
|
+
*/
|
|
13
|
+
export class MqttControlPlaneTransport {
|
|
14
|
+
/**
|
|
15
|
+
* @param {MqttControlPlaneClient} client
|
|
16
|
+
*/
|
|
17
|
+
constructor(client) {
|
|
18
|
+
this.client = client;
|
|
19
|
+
this._messageHandler = null;
|
|
20
|
+
this._connectHandler = null;
|
|
21
|
+
this._disconnectHandler = null;
|
|
22
|
+
// Store original callbacks to preserve them
|
|
23
|
+
const originalOnConnected = this.client.onConnected;
|
|
24
|
+
const originalOnOffline = this.client.onOffline;
|
|
25
|
+
// Wire up handlers when client connects (chain with existing callbacks)
|
|
26
|
+
this.client.onConnected = async (mqttClient) => {
|
|
27
|
+
// Wire up message handler (setMessageHandler ensures it's wired on reconnect)
|
|
28
|
+
if (this._messageHandler) {
|
|
29
|
+
this.client.setMessageHandler(this._messageHandler);
|
|
30
|
+
}
|
|
31
|
+
// Call original callback (set by tunnel.js)
|
|
32
|
+
if (originalOnConnected) {
|
|
33
|
+
await originalOnConnected(mqttClient);
|
|
34
|
+
}
|
|
35
|
+
// Call Transport connect handler (for MqttCore)
|
|
36
|
+
if (this._connectHandler) {
|
|
37
|
+
this._connectHandler();
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
// Wire up disconnect handler (chain with existing callbacks)
|
|
41
|
+
this.client.onOffline = (reason) => {
|
|
42
|
+
// Call original callback (set by tunnel.js)
|
|
43
|
+
if (originalOnOffline) {
|
|
44
|
+
originalOnOffline(reason);
|
|
45
|
+
}
|
|
46
|
+
// Call Transport disconnect handler (for MqttCore)
|
|
47
|
+
if (this._disconnectHandler) {
|
|
48
|
+
this._disconnectHandler(new Error(reason));
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Transport interface: connect
|
|
54
|
+
* @param {any} opts - ConnectOptions (ignored, client manages its own connection)
|
|
55
|
+
* @returns {Promise<void>}
|
|
56
|
+
*/
|
|
57
|
+
async connect(opts) {
|
|
58
|
+
// Client manages its own connection, just ensure it's connected
|
|
59
|
+
if (!this.client.isOnline()) {
|
|
60
|
+
await this.client.connect();
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Transport interface: end
|
|
65
|
+
* @returns {Promise<void>}
|
|
66
|
+
*/
|
|
67
|
+
async end() {
|
|
68
|
+
return this.client.disconnect();
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Transport interface: publish
|
|
72
|
+
* @param {{topic: string, payload: string | Buffer | Uint8Array, qos?: 0 | 1, retain?: boolean}} p
|
|
73
|
+
* @returns {Promise<void>}
|
|
74
|
+
*/
|
|
75
|
+
async publish(p) {
|
|
76
|
+
const payload = p.payload instanceof Uint8Array
|
|
77
|
+
? Buffer.from(p.payload)
|
|
78
|
+
: (typeof p.payload === 'string' ? p.payload : p.payload);
|
|
79
|
+
return this.client.publish(p.topic, payload, { qos: p.qos ?? 0, retain: p.retain ?? false });
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Transport interface: subscribe
|
|
83
|
+
* @param {string} topic
|
|
84
|
+
* @param {0 | 1} [qos=0]
|
|
85
|
+
* @returns {Promise<{topic: string, qos: 0 | 1}>}
|
|
86
|
+
*/
|
|
87
|
+
async subscribe(topic, qos = 0) {
|
|
88
|
+
// Story 12.1 r3 (type check): the client resolves with nothing, not the {topic, qos} SubAck the
|
|
89
|
+
// mqtt-core Transport interface declares; no caller uses the result today. Kept as is (CLI unchanged).
|
|
90
|
+
// @ts-expect-error see above
|
|
91
|
+
return this.client.subscribe(topic, qos);
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Transport interface: unsubscribe
|
|
95
|
+
* @param {string} topic
|
|
96
|
+
* @returns {Promise<void>}
|
|
97
|
+
*/
|
|
98
|
+
async unsubscribe(topic) {
|
|
99
|
+
// Story 12.1 r3 (type check): MqttControlPlaneClient has no unsubscribe(), so this would throw;
|
|
100
|
+
// nothing calls it today (the tunnel never unsubscribes). Recorded, not changed (CLI unchanged).
|
|
101
|
+
// @ts-expect-error see above
|
|
102
|
+
return this.client.unsubscribe(topic);
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Transport interface: onMessage
|
|
106
|
+
* @param {(message: {topic: string, payload: Uint8Array}) => void} cb
|
|
107
|
+
*/
|
|
108
|
+
onMessage(cb) {
|
|
109
|
+
this._messageHandler = cb;
|
|
110
|
+
// Set message handler on client (will be wired on connect/reconnect)
|
|
111
|
+
this.client.setMessageHandler(cb);
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Transport interface: onConnect
|
|
115
|
+
* @param {() => void} cb
|
|
116
|
+
*/
|
|
117
|
+
onConnect(cb) {
|
|
118
|
+
this._connectHandler = cb;
|
|
119
|
+
// If already connected, call immediately
|
|
120
|
+
if (this.client.isOnline()) {
|
|
121
|
+
cb();
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Transport interface: onDisconnect
|
|
126
|
+
* @param {(err?: unknown) => void} cb
|
|
127
|
+
*/
|
|
128
|
+
onDisconnect(cb) {
|
|
129
|
+
this._disconnectHandler = cb;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Expose client for helpers that need direct access
|
|
133
|
+
* @returns {MqttControlPlaneClient}
|
|
134
|
+
*/
|
|
135
|
+
getClient() {
|
|
136
|
+
return this.client;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { EventEmitter } from 'node:events';
|
|
2
|
+
import { MqttControlPlaneClient } from './MqttControlPlaneClient.js';
|
|
3
|
+
import type { Logger } from '../types.js';
|
|
4
|
+
/** Credentials as values; reading them from disk is the caller's job. */
|
|
5
|
+
export interface ControlPlaneCredentials {
|
|
6
|
+
endpoint: string;
|
|
7
|
+
clientId: string;
|
|
8
|
+
ca: Buffer | string;
|
|
9
|
+
cert: Buffer | string;
|
|
10
|
+
key: Buffer | string;
|
|
11
|
+
}
|
|
12
|
+
export type TunnelType = 'http' | 'tcp' | 'udp';
|
|
13
|
+
export interface ControlPlaneSessionOptions {
|
|
14
|
+
credentials: ControlPlaneCredentials;
|
|
15
|
+
tunnelType: TunnelType;
|
|
16
|
+
/** Instance metadata used when re-registering after a client id rotation. */
|
|
17
|
+
metadata: Record<string, unknown>;
|
|
18
|
+
logger: Logger;
|
|
19
|
+
/** Protocol-specific renewal (stays with the caller for now). */
|
|
20
|
+
onRefreshLease: () => Promise<number | null>;
|
|
21
|
+
/** HTTP passes its tunnel when the assignment moves to a new instance id. */
|
|
22
|
+
getTunnel?: () => unknown;
|
|
23
|
+
/** HTTP and UDP track it; TCP never has. */
|
|
24
|
+
trackSubscriptionReady?: boolean;
|
|
25
|
+
/** HTTP and UDP report it; TCP has no offline handler. */
|
|
26
|
+
reportOffline?: boolean;
|
|
27
|
+
/** UDP never logged requestId migration or re-registration. */
|
|
28
|
+
verboseRotationLogs?: boolean;
|
|
29
|
+
keepaliveSec?: number;
|
|
30
|
+
mode?: 'unique' | 'legacy';
|
|
31
|
+
instanceIdRef?: {
|
|
32
|
+
instanceId: string | null;
|
|
33
|
+
};
|
|
34
|
+
subscriptionReadyRef?: {
|
|
35
|
+
ready: boolean;
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
/** Events: 'connected' { clientId }, 'offline' { reason }, 'fatal' { reason, error }. */
|
|
39
|
+
export interface ControlPlaneSession {
|
|
40
|
+
mqttClient: MqttControlPlaneClient;
|
|
41
|
+
events: EventEmitter;
|
|
42
|
+
baseClientId: string;
|
|
43
|
+
instanceIdRef: {
|
|
44
|
+
instanceId: string | null;
|
|
45
|
+
};
|
|
46
|
+
subscriptionReadyRef: {
|
|
47
|
+
ready: boolean;
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
export declare function createControlPlaneSession(o: ControlPlaneSessionOptions): ControlPlaneSession;
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
// Story 12.1 (step 2b, sub-step 2; TypeScript in r3): the control-plane session shared by the HTTP, TCP and UDP
|
|
2
|
+
// tunnels. Moved from the three copies in clients/asyx/src/commands/tunnel.js with their differences
|
|
3
|
+
// kept as explicit options (12.1 must not change behaviour); the user-facing lines the copies
|
|
4
|
+
// printed are now events the caller prints:
|
|
5
|
+
// 'connected' after each (re)connect and instance re-registration (CLI: "✅ Control-plane sealed")
|
|
6
|
+
// 'offline' { reason } when the connection is lost (CLI: "[mqtt] Control-plane connection lost: …")
|
|
7
|
+
// 'fatal' { reason, error } when the client gives up (CLI: message, exit 1)
|
|
8
|
+
// Credentials are values ({ endpoint, clientId, ca, cert, key }); reading them from disk is the caller's job.
|
|
9
|
+
import { EventEmitter } from 'node:events';
|
|
10
|
+
import { MqttControlPlaneClient } from './MqttControlPlaneClient.js';
|
|
11
|
+
class SessionEvents extends EventEmitter {
|
|
12
|
+
emit(name, ...args) {
|
|
13
|
+
if (name === 'error')
|
|
14
|
+
throw new TypeError("control-plane session never emits 'error'; listen for 'fatal'");
|
|
15
|
+
return super.emit(name, ...args);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
export function createControlPlaneSession(o) {
|
|
19
|
+
const { credentials, tunnelType, metadata, logger, onRefreshLease, getTunnel = () => null, trackSubscriptionReady = true, reportOffline = true, verboseRotationLogs = true, keepaliveSec = parseInt(process.env.ASYX_CONTROL_PLANE_KEEPALIVE_SEC || '60', 10), mode = process.env.ASYX_MQTT_CLIENTID_MODE === 'legacy' ? 'legacy' : 'unique', } = o;
|
|
20
|
+
const events = new SessionEvents();
|
|
21
|
+
const baseClientId = credentials.clientId;
|
|
22
|
+
// TPB-12: instanceId is the full MQTT client id; it changes when the client id rotates on reconnect
|
|
23
|
+
const instanceIdRef = o.instanceIdRef || { instanceId: null };
|
|
24
|
+
// Track subscription state so renewal requests wait for the subscription to be active
|
|
25
|
+
const subscriptionReadyRef = o.subscriptionReadyRef || { ready: false };
|
|
26
|
+
const callbacks = {
|
|
27
|
+
onConnected: async () => {
|
|
28
|
+
const newClientId = mqttClient.getClientId();
|
|
29
|
+
logger.debug('mqtt.control_plane.connected', { clientId: newClientId });
|
|
30
|
+
// TPB-12: Update instance registry if clientId changed on reconnect
|
|
31
|
+
if (instanceIdRef.instanceId && newClientId !== instanceIdRef.instanceId) {
|
|
32
|
+
const oldInstanceId = instanceIdRef.instanceId;
|
|
33
|
+
logger.debug('cli.instance.clientid_rotated', { oldInstanceId, newInstanceId: newClientId, tunnelType });
|
|
34
|
+
// Imported here, as the original code did, so they load only when a rotation happens
|
|
35
|
+
const { unregisterInstance, registerInstance, getInstance, setExpectedRequestId } = await import('../state/instance-registry.js');
|
|
36
|
+
const { setAssignment, getAssignment, migrateInstanceAssignment } = await import('../state/assignment.js');
|
|
37
|
+
const oldContext = getInstance(oldInstanceId);
|
|
38
|
+
if (oldContext) {
|
|
39
|
+
// Preserve expectedRequestId before unregistering (for in-flight refresh/reconnect)
|
|
40
|
+
const preservedRequestId = oldContext.expectedRequestId;
|
|
41
|
+
// Register new instance FIRST (before unregistering old) to ensure routing works
|
|
42
|
+
registerInstance(newClientId, { tunnelType, setAssignment, getAssignment, metadata: oldContext.metadata || metadata });
|
|
43
|
+
if (preservedRequestId) {
|
|
44
|
+
setExpectedRequestId(newClientId, preservedRequestId);
|
|
45
|
+
if (verboseRotationLogs) {
|
|
46
|
+
logger.debug('cli.instance.expected_requestid_migrated', { oldInstanceId, newInstanceId: newClientId, requestId: preservedRequestId, tunnelType });
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
unregisterInstance(oldInstanceId);
|
|
50
|
+
// Move the assignment onto the new id and drop the old key.
|
|
51
|
+
const migration = migrateInstanceAssignment(tunnelType === 'http'
|
|
52
|
+
? { oldId: oldInstanceId, newId: newClientId, tunnel: getTunnel() }
|
|
53
|
+
: { oldId: oldInstanceId, newId: newClientId });
|
|
54
|
+
if (migration.moved) {
|
|
55
|
+
logger.debug('cli.instance.assignment_migrated', { oldInstanceId, newInstanceId: newClientId, leaseId: migration.leaseId, tunnelType, assignmentCount: migration.size });
|
|
56
|
+
}
|
|
57
|
+
if (verboseRotationLogs)
|
|
58
|
+
logger.debug('cli.instance.reregistered', { oldInstanceId, newInstanceId: newClientId, tunnelType });
|
|
59
|
+
}
|
|
60
|
+
instanceIdRef.instanceId = newClientId;
|
|
61
|
+
}
|
|
62
|
+
events.emit('connected', { clientId: newClientId });
|
|
63
|
+
// Resubscribe to topics on reconnect (MqttControlPlaneClient manages subscriptions)
|
|
64
|
+
const evtWildcard = `asyx/tunnel/clients/${baseClientId}/evt/#`;
|
|
65
|
+
if (trackSubscriptionReady)
|
|
66
|
+
subscriptionReadyRef.ready = false;
|
|
67
|
+
try {
|
|
68
|
+
await mqttClient.subscribe(evtWildcard, 0);
|
|
69
|
+
logger.debug('mqtt.control_plane.resubscribed', { topic: evtWildcard });
|
|
70
|
+
// subscribe() resolves only after the broker acknowledges
|
|
71
|
+
if (trackSubscriptionReady)
|
|
72
|
+
subscriptionReadyRef.ready = true;
|
|
73
|
+
}
|
|
74
|
+
catch (e) {
|
|
75
|
+
logger.debug('mqtt.control_plane.resubscribe.failed', { error: e?.message || String(e) });
|
|
76
|
+
// Mark ready even on failure to avoid blocking forever
|
|
77
|
+
if (trackSubscriptionReady)
|
|
78
|
+
subscriptionReadyRef.ready = true;
|
|
79
|
+
}
|
|
80
|
+
},
|
|
81
|
+
onFatalError: (reason, err) => {
|
|
82
|
+
logger.error('mqtt.control_plane.fatal', { reason, error: err?.message || String(err) });
|
|
83
|
+
events.emit('fatal', { reason, error: err });
|
|
84
|
+
},
|
|
85
|
+
onRefreshLease: onRefreshLease,
|
|
86
|
+
};
|
|
87
|
+
if (reportOffline) {
|
|
88
|
+
callbacks.onOffline = (reason) => {
|
|
89
|
+
logger.debug('mqtt.control_plane.disconnected', { reason, clientId: mqttClient.getClientId() });
|
|
90
|
+
events.emit('offline', { reason });
|
|
91
|
+
// Clear the ready flag so renewals wait for resubscription after the reconnect
|
|
92
|
+
subscriptionReadyRef.ready = false;
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
const mqttClient = new MqttControlPlaneClient({
|
|
96
|
+
url: `mqtts://${credentials.endpoint}:443`,
|
|
97
|
+
baseClientId,
|
|
98
|
+
mqttOptions: {
|
|
99
|
+
protocol: 'mqtts',
|
|
100
|
+
port: 443,
|
|
101
|
+
cert: credentials.cert,
|
|
102
|
+
key: credentials.key,
|
|
103
|
+
ca: credentials.ca,
|
|
104
|
+
rejectUnauthorized: true,
|
|
105
|
+
keepalive: keepaliveSec,
|
|
106
|
+
connectTimeout: 8000,
|
|
107
|
+
// ALPN for port 443 (AWS IoT)
|
|
108
|
+
ALPNProtocols: ['x-amzn-mqtt-ca'],
|
|
109
|
+
},
|
|
110
|
+
mode,
|
|
111
|
+
logger,
|
|
112
|
+
...callbacks,
|
|
113
|
+
});
|
|
114
|
+
return { mqttClient, events, baseClientId, instanceIdRef, subscriptionReadyRef };
|
|
115
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
export interface TunnelErrorOptions {
|
|
2
|
+
/** Whether trying the same operation again may succeed. */
|
|
3
|
+
retryable?: boolean;
|
|
4
|
+
/** The underlying error, kept for logs. */
|
|
5
|
+
cause?: unknown;
|
|
6
|
+
/** Structured facts for the caller (e.g. port limits for a refused port, exitCode for the CLI). */
|
|
7
|
+
details?: Record<string, unknown>;
|
|
8
|
+
}
|
|
9
|
+
export declare class TunnelError extends Error {
|
|
10
|
+
/** Stable, machine-readable reason. */
|
|
11
|
+
readonly code: string;
|
|
12
|
+
readonly retryable: boolean;
|
|
13
|
+
details?: Record<string, unknown>;
|
|
14
|
+
/**
|
|
15
|
+
* @param code stable, machine-readable reason
|
|
16
|
+
* @param message developer-facing description (never shown to users as-is by the CLI)
|
|
17
|
+
*/
|
|
18
|
+
constructor(code: string, message?: string, { retryable, cause, details }?: TunnelErrorOptions);
|
|
19
|
+
}
|
|
20
|
+
type SubclassOptions = Omit<TunnelErrorOptions, 'retryable'> & {
|
|
21
|
+
retryable?: boolean;
|
|
22
|
+
};
|
|
23
|
+
/** The machine is not enrolled, or the coordinator wants it to enroll again. */
|
|
24
|
+
export declare class SetupRequiredError extends TunnelError {
|
|
25
|
+
constructor(code?: string, message?: string, opts?: SubclassOptions);
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* The coordinator said no. `code` is the coordinator's own reason, passed through unchanged, so a
|
|
29
|
+
* new reason on the server needs no client release (e.g. port_out_of_block, invalid_secgroup,
|
|
30
|
+
* cap_exceeded, hostname_not_assigned, revoked).
|
|
31
|
+
*/
|
|
32
|
+
export declare class RefusedError extends TunnelError {
|
|
33
|
+
constructor(code?: string, message?: string, opts?: SubclassOptions);
|
|
34
|
+
}
|
|
35
|
+
/** Network or transport failure; usually worth retrying. */
|
|
36
|
+
export declare class ConnectionError extends TunnelError {
|
|
37
|
+
constructor(code?: string, message?: string, opts?: SubclassOptions);
|
|
38
|
+
}
|
|
39
|
+
/** Bad local input (arguments, configuration, credentials on disk). */
|
|
40
|
+
export declare class ConfigError extends TunnelError {
|
|
41
|
+
constructor(code?: string, message?: string, opts?: SubclassOptions);
|
|
42
|
+
}
|
|
43
|
+
/** A bug or an unexpected state inside the core. */
|
|
44
|
+
export declare class InternalError extends TunnelError {
|
|
45
|
+
constructor(code?: string, message?: string, opts?: SubclassOptions);
|
|
46
|
+
}
|
|
47
|
+
/** Wrap anything thrown into a TunnelError without losing it. */
|
|
48
|
+
export declare function toTunnelError(e: unknown, fallbackCode?: string): TunnelError;
|
|
49
|
+
export {};
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// Story 12.1 (step 2b; TypeScript in r3): typed errors for @asyx/tunnel-core.
|
|
2
|
+
// Classes by what the caller should do; the `code` is the contract (docs/proposals/tunnel-core-shape-12.1.md).
|
|
3
|
+
// The core holds no user-facing wording: `message` is for logs and developers, the CLI maps `code`
|
|
4
|
+
// to its own text and exit codes.
|
|
5
|
+
export class TunnelError extends Error {
|
|
6
|
+
/** Stable, machine-readable reason. */
|
|
7
|
+
code;
|
|
8
|
+
retryable;
|
|
9
|
+
details;
|
|
10
|
+
/**
|
|
11
|
+
* @param code stable, machine-readable reason
|
|
12
|
+
* @param message developer-facing description (never shown to users as-is by the CLI)
|
|
13
|
+
*/
|
|
14
|
+
constructor(code, message = code, { retryable = false, cause, details } = {}) {
|
|
15
|
+
super(message, cause === undefined ? undefined : { cause });
|
|
16
|
+
this.name = new.target.name;
|
|
17
|
+
this.code = code;
|
|
18
|
+
this.retryable = retryable;
|
|
19
|
+
if (details !== undefined)
|
|
20
|
+
this.details = details;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
/** The machine is not enrolled, or the coordinator wants it to enroll again. */
|
|
24
|
+
export class SetupRequiredError extends TunnelError {
|
|
25
|
+
constructor(code = 'setup_required', message, opts) { super(code, message, { retryable: false, ...opts }); }
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* The coordinator said no. `code` is the coordinator's own reason, passed through unchanged, so a
|
|
29
|
+
* new reason on the server needs no client release (e.g. port_out_of_block, invalid_secgroup,
|
|
30
|
+
* cap_exceeded, hostname_not_assigned, revoked).
|
|
31
|
+
*/
|
|
32
|
+
export class RefusedError extends TunnelError {
|
|
33
|
+
constructor(code, message, opts) { super(code || 'refused', message, { retryable: false, ...opts }); }
|
|
34
|
+
}
|
|
35
|
+
/** Network or transport failure; usually worth retrying. */
|
|
36
|
+
export class ConnectionError extends TunnelError {
|
|
37
|
+
constructor(code = 'connection_failed', message, opts) { super(code, message, { retryable: true, ...opts }); }
|
|
38
|
+
}
|
|
39
|
+
/** Bad local input (arguments, configuration, credentials on disk). */
|
|
40
|
+
export class ConfigError extends TunnelError {
|
|
41
|
+
constructor(code = 'invalid_config', message, opts) { super(code, message, { retryable: false, ...opts }); }
|
|
42
|
+
}
|
|
43
|
+
/** A bug or an unexpected state inside the core. */
|
|
44
|
+
export class InternalError extends TunnelError {
|
|
45
|
+
constructor(code = 'internal', message, opts) { super(code, message, { retryable: false, ...opts }); }
|
|
46
|
+
}
|
|
47
|
+
/** Wrap anything thrown into a TunnelError without losing it. */
|
|
48
|
+
export function toTunnelError(e, fallbackCode = 'internal') {
|
|
49
|
+
if (e instanceof TunnelError)
|
|
50
|
+
return e;
|
|
51
|
+
const message = e?.message;
|
|
52
|
+
return new InternalError(fallbackCode, typeof message === 'string' && message ? message : String(e), { cause: e });
|
|
53
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { LifecycleEmitter } from '../lifecycle.js';
|
|
2
|
+
import type { ControlPlaneCredentials } from '../control-plane/session.js';
|
|
3
|
+
import type { RequestSink } from '../tunnel/request-sink.js';
|
|
4
|
+
import type { Logger } from '../types.js';
|
|
5
|
+
export declare function scheduleInitialHttpRefresh(mqttClient: {
|
|
6
|
+
scheduleRefresh(expMs: number, leaseId: string): void;
|
|
7
|
+
} | null, assignment: Record<string, any>, logger: Logger): void;
|
|
8
|
+
export interface HttpTunnelOptions {
|
|
9
|
+
credentials: ControlPlaneCredentials;
|
|
10
|
+
/** The local web app's port. */
|
|
11
|
+
localPort: number;
|
|
12
|
+
/** QuickPass security group (QPA-04): only its members can open the URL. */
|
|
13
|
+
secGroupSlug?: string | null;
|
|
14
|
+
/** Where received requests go (default: LocalPortSink(localPort)). */
|
|
15
|
+
requestSink?: RequestSink;
|
|
16
|
+
logger: Logger;
|
|
17
|
+
/** Called with each observability line when ASYX_DEBUG=1 (the CLI prints them). */
|
|
18
|
+
onObserve?: (line: string) => void;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Sent with 'notice': something the user may want to know that does not end the tunnel, e.g.
|
|
22
|
+
* control_plane_offline, control_plane_timeout, jwt_expired_offline, quickpass_refresh_delayed.
|
|
23
|
+
*/
|
|
24
|
+
export type HttpNoticeEvent = {
|
|
25
|
+
code: string;
|
|
26
|
+
[key: string]: unknown;
|
|
27
|
+
};
|
|
28
|
+
/** What open() resolves to and the 'live' state carries. */
|
|
29
|
+
export type HttpTunnelInfo = {
|
|
30
|
+
assignment: Record<string, any>;
|
|
31
|
+
localPort: number;
|
|
32
|
+
relayId: string;
|
|
33
|
+
leaseMs?: number;
|
|
34
|
+
quickpassSlug?: string;
|
|
35
|
+
};
|
|
36
|
+
export declare class HttpTunnelHandle extends LifecycleEmitter {
|
|
37
|
+
readonly opts: HttpTunnelOptions & {
|
|
38
|
+
secGroupSlug: string | null;
|
|
39
|
+
};
|
|
40
|
+
tunnel: any;
|
|
41
|
+
mqttClient: any;
|
|
42
|
+
core: any;
|
|
43
|
+
assignment: Record<string, any> | null;
|
|
44
|
+
constructor(o: HttpTunnelOptions);
|
|
45
|
+
/** Connect the control plane, get a lease and open the data plane; rejects with a ConnectionError. */
|
|
46
|
+
open(): Promise<HttpTunnelInfo>;
|
|
47
|
+
/** Ask for a renewal now (SIGUSR2 in the CLI). */
|
|
48
|
+
attemptJwtRefresh(): Promise<unknown> | undefined;
|
|
49
|
+
}
|
|
50
|
+
export declare function createHttpTunnel(opts: HttpTunnelOptions): HttpTunnelHandle;
|