asyx 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/AGENTS.md +42 -0
  2. package/bin/asyx.js +1 -1
  3. package/package.json +6 -3
  4. package/src/commands/account.js +80 -71
  5. package/src/commands/app.js +317 -151
  6. package/src/commands/in-use-messages.js +47 -48
  7. package/src/commands/mqtt-broker.js +36 -49
  8. package/src/commands/mqtt.js +111 -149
  9. package/src/commands/name.js +24 -22
  10. package/src/commands/reject-messages.js +123 -123
  11. package/src/commands/setup.js +107 -131
  12. package/src/commands/sts.js +45 -61
  13. package/src/commands/tunnel.js +853 -931
  14. package/src/commands/validate-target-host.js +36 -59
  15. package/src/lib/aws-iot-config.js +30 -0
  16. package/src/lib/certs.js +15 -18
  17. package/src/lib/csr.js +107 -182
  18. package/src/lib/device.js +26 -37
  19. package/src/lib/ids.js +1 -2
  20. package/src/lib/naming.js +74 -68
  21. package/src/lib/pairing.js +10 -11
  22. package/src/lib/shared-transport.js +5 -9
  23. package/src/main.js +63 -53
  24. package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneClient.js +25 -287
  25. package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneTransport.js +0 -72
  26. package/vendor/tunnel-core/dist/control-plane/session.js +0 -20
  27. package/vendor/tunnel-core/dist/errors.js +0 -19
  28. package/vendor/tunnel-core/dist/flows/account.js +1 -6
  29. package/vendor/tunnel-core/dist/flows/goodbye.js +0 -4
  30. package/vendor/tunnel-core/dist/flows/http.js +24 -112
  31. package/vendor/tunnel-core/dist/flows/identity.js +11 -10
  32. package/vendor/tunnel-core/dist/flows/in-use.js +0 -6
  33. package/vendor/tunnel-core/dist/flows/reopen.js +0 -4
  34. package/vendor/tunnel-core/dist/flows/tcp.js +18 -84
  35. package/vendor/tunnel-core/dist/flows/udp.js +15 -52
  36. package/vendor/tunnel-core/dist/lib/fingerprint.js +38 -42
  37. package/vendor/tunnel-core/dist/lib/jwt-verifier.js +14 -67
  38. package/vendor/tunnel-core/dist/lib/logger.js +1 -9
  39. package/vendor/tunnel-core/dist/lib/refresh-helpers.js +1 -22
  40. package/vendor/tunnel-core/dist/lifecycle.js +1 -8
  41. package/vendor/tunnel-core/dist/mqtt/awaiter-map.js +1 -53
  42. package/vendor/tunnel-core/dist/mqtt/events/handlers.js +10 -64
  43. package/vendor/tunnel-core/dist/mqtt/events/index.js +3 -36
  44. package/vendor/tunnel-core/dist/mqtt/events/schemas.js +0 -1
  45. package/vendor/tunnel-core/dist/mqtt/ingress.js +0 -60
  46. package/vendor/tunnel-core/dist/state/assignment.js +6 -122
  47. package/vendor/tunnel-core/dist/state/instance-registry.js +0 -63
  48. package/vendor/tunnel-core/dist/tcp-v1/framing.js +2 -64
  49. package/vendor/tunnel-core/dist/tunnel/http-tunnel.js +64 -331
  50. package/vendor/tunnel-core/dist/tunnel/httpws-constants.js +5 -14
  51. package/vendor/tunnel-core/dist/tunnel/reconnect.js +10 -50
  52. package/vendor/tunnel-core/dist/tunnel/request-sink.js +0 -16
  53. package/vendor/tunnel-core/dist/tunnel/tcp-tunnel.js +32 -195
  54. package/vendor/tunnel-core/dist/tunnel/udp-tunnel.js +28 -153
  55. package/vendor/tunnel-core/dist/tunnel/ws-control.js +4 -39
  56. package/vendor/tunnel-core/dist/types.js +0 -2
  57. package/vendor/tunnel-core/dist/udp-v1/framing.js +2 -64
  58. package/vendor/tunnel-core/package.json +0 -25
  59. package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneClient.d.ts +0 -273
  60. package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneTransport.d.ts +0 -79
  61. package/vendor/tunnel-core/dist/control-plane/session.d.ts +0 -55
  62. package/vendor/tunnel-core/dist/errors.d.ts +0 -49
  63. package/vendor/tunnel-core/dist/flows/account.d.ts +0 -24
  64. package/vendor/tunnel-core/dist/flows/goodbye.d.ts +0 -10
  65. package/vendor/tunnel-core/dist/flows/http.d.ts +0 -61
  66. package/vendor/tunnel-core/dist/flows/identity.d.ts +0 -23
  67. package/vendor/tunnel-core/dist/flows/in-use.d.ts +0 -27
  68. package/vendor/tunnel-core/dist/flows/reopen.d.ts +0 -9
  69. package/vendor/tunnel-core/dist/flows/tcp.d.ts +0 -85
  70. package/vendor/tunnel-core/dist/flows/udp.d.ts +0 -52
  71. package/vendor/tunnel-core/dist/lib/adapt-logger.d.ts +0 -2
  72. package/vendor/tunnel-core/dist/lib/fingerprint.d.ts +0 -145
  73. package/vendor/tunnel-core/dist/lib/jwt-verifier.d.ts +0 -27
  74. package/vendor/tunnel-core/dist/lib/logger.d.ts +0 -9
  75. package/vendor/tunnel-core/dist/lib/refresh-helpers.d.ts +0 -16
  76. package/vendor/tunnel-core/dist/lifecycle.d.ts +0 -24
  77. package/vendor/tunnel-core/dist/mqtt/awaiter-map.d.ts +0 -56
  78. package/vendor/tunnel-core/dist/mqtt/events/handlers.d.ts +0 -60
  79. package/vendor/tunnel-core/dist/mqtt/events/index.d.ts +0 -1
  80. package/vendor/tunnel-core/dist/mqtt/events/schemas.d.ts +0 -498
  81. package/vendor/tunnel-core/dist/mqtt/ingress.d.ts +0 -63
  82. package/vendor/tunnel-core/dist/state/assignment.d.ts +0 -136
  83. package/vendor/tunnel-core/dist/state/instance-registry.d.ts +0 -88
  84. package/vendor/tunnel-core/dist/tcp-v1/framing.d.ts +0 -43
  85. package/vendor/tunnel-core/dist/tunnel/http-tunnel.d.ts +0 -140
  86. package/vendor/tunnel-core/dist/tunnel/httpws-constants.d.ts +0 -13
  87. package/vendor/tunnel-core/dist/tunnel/reconnect.d.ts +0 -76
  88. package/vendor/tunnel-core/dist/tunnel/request-sink.d.ts +0 -40
  89. package/vendor/tunnel-core/dist/tunnel/tcp-tunnel.d.ts +0 -92
  90. package/vendor/tunnel-core/dist/tunnel/udp-tunnel.d.ts +0 -93
  91. package/vendor/tunnel-core/dist/tunnel/ws-control.d.ts +0 -22
  92. package/vendor/tunnel-core/dist/types.d.ts +0 -24
  93. package/vendor/tunnel-core/dist/udp-v1/framing.d.ts +0 -41
@@ -1,24 +1,12 @@
1
- /**
2
- * CLI-REAUTH: WebSocket Control Frame Helper
3
- * Manages control frame communication with relay for in-band reauth
4
- */
5
- // Global waiter registry: op -> Set<{ resolve, reject, timer }>
6
1
  const controlWaiters = new Map();
7
- /**
8
- * CLI-REAUTH: Dispatch incoming control frames to waiting promises
9
- * Called from WebSocket message handler when a text frame matches control pattern
10
- *
11
- * @param {Object} frame - Parsed JSON control frame (must have 'op' field)
12
- */
13
2
  export function dispatchControlFrame(frame) {
14
3
  if (!frame || typeof frame !== 'object' || !frame.op) {
15
- return false; // Not a control frame
4
+ return false;
16
5
  }
17
6
  const waiters = controlWaiters.get(frame.op);
18
7
  if (!waiters || waiters.size === 0) {
19
- return false; // No waiters for this op
8
+ return false;
20
9
  }
21
- // Resolve all waiters for this op and remove them
22
10
  const resolvedWaiters = Array.from(waiters);
23
11
  controlWaiters.delete(frame.op);
24
12
  for (const waiter of resolvedWaiters) {
@@ -27,43 +15,26 @@ export function dispatchControlFrame(frame) {
27
15
  waiter.resolve(frame);
28
16
  }
29
17
  catch (err) {
30
- // Ignore resolution errors
31
18
  }
32
19
  }
33
- return true; // Frame was dispatched
20
+ return true;
34
21
  }
35
- /**
36
- * CLI-REAUTH: Cleanup all waiters (call on socket close to prevent leaks)
37
- * Rejects all pending waiters to ensure promises settle and don't linger in microtask queue
38
- */
39
22
  export function clearAllWaiters() {
40
23
  for (const [, waiters] of controlWaiters) {
41
24
  for (const waiter of waiters) {
42
25
  clearTimeout(waiter.timer);
43
26
  try {
44
- // Reject the promise - tests should await these to prevent unhandled rejections
45
27
  waiter.reject(new Error('WebSocket closed before control frame received'));
46
28
  }
47
29
  catch {
48
- // Ignore rejection errors (promise already settled)
49
30
  }
50
31
  }
51
32
  }
52
33
  controlWaiters.clear();
53
34
  }
54
- /**
55
- * CLI-REAUTH: Send control frame and wait for acknowledgment
56
- *
57
- * @param {import('ws').WebSocket} ws - WebSocket connection
58
- * @param {string} payloadJson - Serialized JSON payload to send
59
- * @param {string} expectedOp - Expected 'op' value in response (e.g., 'reauth_ack')
60
- * @param {number} timeoutMs - Timeout in milliseconds (default 3000)
61
- * @returns {Promise<Object>} Resolves with parsed control frame, or {status:'error', error:'timeout'} on timeout
62
- */
63
35
  export function sendControlAndWaitAck(ws, payloadJson, expectedOp, timeoutMs = 3000) {
64
36
  return new Promise((resolve, reject) => {
65
- // Validate inputs
66
- if (!ws || ws.readyState !== 1) { // WebSocket.OPEN = 1
37
+ if (!ws || ws.readyState !== 1) {
67
38
  resolve({ status: 'error', error: 'socket_not_open' });
68
39
  return;
69
40
  }
@@ -75,9 +46,7 @@ export function sendControlAndWaitAck(ws, payloadJson, expectedOp, timeoutMs = 3
75
46
  resolve({ status: 'error', error: 'invalid_expected_op' });
76
47
  return;
77
48
  }
78
- // Set up timeout
79
49
  const timer = setTimeout(() => {
80
- // Remove from registry
81
50
  const waiters = controlWaiters.get(expectedOp);
82
51
  if (waiters) {
83
52
  waiters.delete(waiter);
@@ -87,7 +56,6 @@ export function sendControlAndWaitAck(ws, payloadJson, expectedOp, timeoutMs = 3
87
56
  }
88
57
  resolve({ status: 'error', error: 'timeout' });
89
58
  }, timeoutMs);
90
- // Create waiter
91
59
  const waiter = {
92
60
  resolve: (frame) => {
93
61
  clearTimeout(timer);
@@ -99,17 +67,14 @@ export function sendControlAndWaitAck(ws, payloadJson, expectedOp, timeoutMs = 3
99
67
  },
100
68
  timer
101
69
  };
102
- // Register waiter
103
70
  if (!controlWaiters.has(expectedOp)) {
104
71
  controlWaiters.set(expectedOp, new Set());
105
72
  }
106
73
  controlWaiters.get(expectedOp).add(waiter);
107
- // Send control frame
108
74
  try {
109
75
  ws.send(payloadJson);
110
76
  }
111
77
  catch (sendError) {
112
- // Clean up waiter on send failure
113
78
  const waiters = controlWaiters.get(expectedOp);
114
79
  if (waiters) {
115
80
  waiters.delete(waiter);
@@ -1,2 +0,0 @@
1
- // Story 12.1 r3: shapes shared by the public surface of @asyx/tunnel-core.
2
- export {};
@@ -1,28 +1,11 @@
1
- /**
2
- * UDP-v1 (udpWs-v1) Framing Protocol
3
- *
4
- * Binary frame format (same as tcpWs-v1):
5
- * [frameType:1 byte][flowId:4 bytes (big-endian)][length:4 bytes (big-endian)][payload:length bytes]
6
- *
7
- * Frame types:
8
- * - 0x10: UDP_DGRAM
9
- * - 0x11: UDP_CLOSE
10
- * - 0x05: PING
11
- * - 0x06: PONG
12
- *
13
- * Max payload size: 64 KiB (65536 bytes)
14
- * FlowId: 32-bit value (big-endian)
15
- *
16
- * Reference: docs/v4.1/v4.1_tcpWs_udpWs_protocol_v1.md
17
- */
18
1
  export const FrameType = {
19
2
  UDP_DGRAM: 0x10,
20
3
  UDP_CLOSE: 0x11,
21
4
  PING: 0x05,
22
5
  PONG: 0x06,
23
6
  };
24
- export const MAX_FRAME_PAYLOAD = 64 * 1024; // 64 KiB
25
- export const FRAME_HEADER_SIZE = 9; // 1 byte type + 4 bytes flowId + 4 bytes length
7
+ export const MAX_FRAME_PAYLOAD = 64 * 1024;
8
+ export const FRAME_HEADER_SIZE = 9;
26
9
  export class UdpV1FramingError extends Error {
27
10
  constructor(message, code) {
28
11
  super(message);
@@ -30,94 +13,58 @@ export class UdpV1FramingError extends Error {
30
13
  this.code = code;
31
14
  }
32
15
  }
33
- /**
34
- * Encode a frame to binary format
35
- * @param {Object} frame - Frame object with type, flowId, and payload
36
- * @param {number} frame.type - Frame type (FrameType constant)
37
- * @param {number} frame.flowId - Flow ID (32-bit, 0 for PING/PONG)
38
- * @param {Buffer|Uint8Array} frame.payload - Frame payload (max 64 KiB)
39
- * @returns {Buffer} Encoded frame
40
- * @throws {UdpV1FramingError} If frame is invalid
41
- */
42
16
  export function encodeFrame(frame) {
43
17
  const { type, flowId = 0, payload = Buffer.alloc(0) } = frame;
44
- // Validate frame type
45
18
  const validTypes = [FrameType.UDP_DGRAM, FrameType.UDP_CLOSE, FrameType.PING, FrameType.PONG];
46
19
  if (!validTypes.includes(type)) {
47
20
  throw new UdpV1FramingError(`Invalid frame type: ${type}`, 'INVALID_FRAME_TYPE');
48
21
  }
49
- // Convert payload to Buffer if needed
50
22
  const payloadBuf = Buffer.isBuffer(payload) ? payload : Buffer.from(payload);
51
- // Validate payload size
52
23
  if (payloadBuf.length > MAX_FRAME_PAYLOAD) {
53
24
  throw new UdpV1FramingError(`Payload size ${payloadBuf.length} exceeds max ${MAX_FRAME_PAYLOAD}`, 'PAYLOAD_TOO_LARGE');
54
25
  }
55
- // FlowID validation (PING/PONG can have 0)
56
26
  if (type !== FrameType.PING && type !== FrameType.PONG) {
57
27
  if (flowId === 0) {
58
28
  throw new UdpV1FramingError('FlowID required for non-PING/PONG frames', 'MISSING_FLOW_ID');
59
29
  }
60
- // Ensure flowId fits in 32 bits
61
30
  if (flowId > 0xFFFFFFFF) {
62
31
  throw new UdpV1FramingError(`FlowID ${flowId} exceeds 32-bit limit`, 'INVALID_FLOW_ID');
63
32
  }
64
33
  }
65
- // Create frame buffer
66
34
  const frameBuf = Buffer.allocUnsafe(FRAME_HEADER_SIZE + payloadBuf.length);
67
- // Write frame type (1 byte)
68
35
  frameBuf[0] = type;
69
- // Write flowId (4 bytes, big-endian)
70
36
  frameBuf.writeUInt32BE(flowId, 1);
71
- // Write payload length (4 bytes, big-endian)
72
37
  frameBuf.writeUInt32BE(payloadBuf.length, 5);
73
- // Write payload
74
38
  if (payloadBuf.length > 0) {
75
39
  payloadBuf.copy(frameBuf, FRAME_HEADER_SIZE);
76
40
  }
77
41
  return frameBuf;
78
42
  }
79
- /**
80
- * Decode a frame from binary format
81
- * @param {Buffer|Uint8Array} data - Binary frame data
82
- * @param {number} [offset=0] - Offset to start reading from
83
- * @returns {Object} Decoded frame object with type, flowId, payload, and consumed bytes
84
- * @throws {UdpV1FramingError} If frame is invalid
85
- */
86
43
  export function decodeFrame(data, offset = 0) {
87
44
  const buf = Buffer.isBuffer(data) ? data : Buffer.from(data);
88
- // Check if we have enough data for header
89
45
  if (buf.length - offset < FRAME_HEADER_SIZE) {
90
46
  throw new UdpV1FramingError(`Insufficient data for frame header: need ${FRAME_HEADER_SIZE} bytes, got ${buf.length - offset}`, 'INCOMPLETE_FRAME');
91
47
  }
92
- // If offset is provided, create a subarray view
93
48
  const view = offset > 0 ? buf.subarray(offset) : buf;
94
- // Read frame type (1 byte)
95
49
  const type = view[0];
96
- // Validate frame type
97
50
  const validTypes = [FrameType.UDP_DGRAM, FrameType.UDP_CLOSE, FrameType.PING, FrameType.PONG];
98
51
  if (!validTypes.includes(type)) {
99
52
  throw new UdpV1FramingError(`Invalid frame type: ${type}`, 'INVALID_FRAME_TYPE');
100
53
  }
101
- // Read flowId (4 bytes, big-endian)
102
54
  const flowId = view.readUInt32BE(1);
103
- // Read payload length (4 bytes, big-endian)
104
55
  const payloadLength = view.readUInt32BE(5);
105
- // Validate payload length
106
56
  if (payloadLength > MAX_FRAME_PAYLOAD) {
107
57
  throw new UdpV1FramingError(`Payload length ${payloadLength} exceeds max ${MAX_FRAME_PAYLOAD}`, 'PAYLOAD_TOO_LARGE');
108
58
  }
109
- // Check if we have enough data for payload
110
59
  const totalFrameSize = FRAME_HEADER_SIZE + payloadLength;
111
60
  if (view.length < totalFrameSize) {
112
61
  throw new UdpV1FramingError(`Insufficient data for frame payload: need ${totalFrameSize} bytes, got ${view.length}`, 'INCOMPLETE_FRAME');
113
62
  }
114
- // FlowID validation (PING/PONG can have 0)
115
63
  if (type !== FrameType.PING && type !== FrameType.PONG) {
116
64
  if (flowId === 0) {
117
65
  throw new UdpV1FramingError('FlowID required for non-PING/PONG frames', 'MISSING_FLOW_ID');
118
66
  }
119
67
  }
120
- // Read payload
121
68
  const payload = payloadLength > 0
122
69
  ? view.subarray(FRAME_HEADER_SIZE, FRAME_HEADER_SIZE + payloadLength)
123
70
  : Buffer.alloc(0);
@@ -128,25 +75,16 @@ export function decodeFrame(data, offset = 0) {
128
75
  consumed: totalFrameSize,
129
76
  };
130
77
  }
131
- /**
132
- * Validate a frame for protocol violations
133
- * @param {Object} frame - Frame object to validate
134
- * @returns {void}
135
- * @throws {UdpV1FramingError} If frame is invalid
136
- */
137
78
  export function validateFrame(frame) {
138
79
  const { type, flowId = 0, payload = Buffer.alloc(0) } = frame;
139
- // Validate frame type
140
80
  const validTypes = [FrameType.UDP_DGRAM, FrameType.UDP_CLOSE, FrameType.PING, FrameType.PONG];
141
81
  if (!validTypes.includes(type)) {
142
82
  throw new UdpV1FramingError(`Invalid frame type: ${type}`, 'INVALID_FRAME_TYPE');
143
83
  }
144
- // Validate payload size
145
84
  const payloadBuf = Buffer.isBuffer(payload) ? payload : Buffer.from(payload);
146
85
  if (payloadBuf.length > MAX_FRAME_PAYLOAD) {
147
86
  throw new UdpV1FramingError(`Payload size ${payloadBuf.length} exceeds max ${MAX_FRAME_PAYLOAD}`, 'PAYLOAD_TOO_LARGE');
148
87
  }
149
- // FlowID validation (PING/PONG can have 0)
150
88
  if (type !== FrameType.PING && type !== FrameType.PONG) {
151
89
  if (flowId === 0) {
152
90
  throw new UdpV1FramingError('FlowID required for non-PING/PONG frames', 'MISSING_FLOW_ID');
@@ -2,33 +2,8 @@
2
2
  "name": "@asyx/tunnel-core",
3
3
  "version": "0.1.0",
4
4
  "private": true,
5
- "description": "Shared tunnel protocol for the Asyx CLI and SDK (Story 12.1). Public surface in TypeScript; internals JavaScript with compiler-generated declarations. Not published yet: the CLI carries the built output inside its package.",
6
5
  "type": "module",
7
- "engines": {
8
- "node": ">=18.17"
9
- },
10
6
  "exports": {
11
7
  "./*": "./dist/*"
12
- },
13
- "files": [
14
- "dist/**"
15
- ],
16
- "scripts": {
17
- "build": "npm --prefix ../mqtt-core run build >/dev/null && rm -rf dist && tsc -p tsconfig.json",
18
- "typecheck": "npm --prefix ../mqtt-core run build >/dev/null && tsc -p tsconfig.json --noEmit",
19
- "test": "NODE_OPTIONS=\"--experimental-vm-modules --max-old-space-size=8192\" jest --runInBand"
20
- },
21
- "dependencies": {
22
- "@asyx/mqtt-core": "^0.1.0",
23
- "hw-fingerprint": "^3.2.0",
24
- "jose": "^5.10.0",
25
- "mqtt": "^5.3.4",
26
- "ulid": "^2.4.0",
27
- "ws": "^8.14.2",
28
- "zod": "3.23.8"
29
- },
30
- "devDependencies": {
31
- "@jest/globals": "^30.2.0",
32
- "jest": "^30.2.0"
33
8
  }
34
9
  }
@@ -1,273 +0,0 @@
1
- /**
2
- * @typedef {'soft' | 'hard' | 'transient'} MqttFaultKind
3
- */
4
- /**
5
- * @typedef {Object} MqttControlPlaneClientOptions
6
- * @property {string} url - MQTT broker URL (e.g., 'wss://...')
7
- * @property {string} baseClientId - Base client ID (e.g., 'cli_F285616B53CE')
8
- * @property {Object} [mqttOptions] - Additional mqtt.js options (cert, key, ca, etc.)
9
- * @property {(client: any) => void | Promise<void>} [onConnected] - Called after successful connect
10
- * @property {(reason: string) => void} [onOffline] - Called when connection goes offline
11
- * @property {(reason: string, err?: unknown) => void} [onFatalError] - Called when we give up due to JWT expiry or unrecoverable error
12
- * @property {() => Promise<{ exp: number | null, leaseId: string } | null>} [onLeaseClosed] - Story 3.13: reopen after a closed lease.
13
- * @property {() => Promise<number>} onRefreshLease - Async refresh function. Must publish the refresh request over MQTT and resolve with new exp (ms since epoch). Throw on hard failure.
14
- * @property {number} [refreshEarlySeconds] - Seconds before exp when we should start refresh (e.g. 0.75 * ttl, default: 675s for 15min TTL)
15
- * @property {number} [maxReconnectDelayMs] - Max reconnect delay in ms (default 5000)
16
- * @property {'unique' | 'legacy'} [mode] - Mode: 'unique' (default) or 'legacy'
17
- * @property {Object} [logger] - Logger for structured logging
18
- * @property {any} [mqttLib] - Optional mqtt library for dependency injection (defaults to real mqtt)
19
- * @property {any} [ulidLib] - Optional ulid library for dependency injection (defaults to real ulid)
20
- */
21
- export class MqttControlPlaneClient {
22
- /**
23
- * @param {MqttControlPlaneClientOptions} opts
24
- */
25
- constructor(opts: MqttControlPlaneClientOptions);
26
- url: string;
27
- baseClientId: string;
28
- mqttOptions: any;
29
- onConnected: (client: any) => void | Promise<void>;
30
- onOffline: (reason: string) => void;
31
- onFatalError: (reason: string, err?: unknown) => void;
32
- onRefreshLease: () => Promise<number>;
33
- /** Story 3.13: called when a renewal finds the lease closed; reopens and resolves { exp, leaseId } or throws. */
34
- onLeaseClosed: () => Promise<{
35
- exp: number | null;
36
- leaseId: string;
37
- } | null>;
38
- refreshEarlySeconds: number;
39
- maxReconnectDelayMs: number;
40
- mode: "unique" | "legacy";
41
- logger: any;
42
- mqtt: any;
43
- ulidLib: any;
44
- currentClientId: string;
45
- client: any;
46
- forceClosing: any;
47
- shuttingDown: boolean;
48
- mqttOnline: boolean;
49
- hardErrorCount: number;
50
- transientErrorCount: number;
51
- reconnectTimer: any;
52
- connectStartTime: number;
53
- reconnectAttempts: number;
54
- maxReconnectAttempts: number;
55
- refreshTimer: any;
56
- refreshPending: boolean;
57
- refreshDeadlineMs: number;
58
- currentLeaseId: string;
59
- rearmTimeout: any;
60
- flushPendingRefreshTimer: any;
61
- watchdogTimer: NodeJS.Timeout;
62
- WATCHDOG_TIMEOUT_MS: number;
63
- _pendingMessageHandler: (topic: any, payload: any, packet: any) => void;
64
- /**
65
- * Connect to MQTT broker (initial connection).
66
- * Returns a promise that resolves when connected or rejects on fatal error.
67
- * @returns {Promise<void>}
68
- */
69
- connect(): Promise<void>;
70
- /**
71
- * Disconnect and clean up all timers.
72
- * @param {Object} [opts] - Options
73
- * @param {boolean} [opts.preserveState] - If true, don't set shuttingDown (for forceReconnect)
74
- * @returns {Promise<void>}
75
- */
76
- disconnect(opts?: {
77
- preserveState?: boolean;
78
- }): Promise<void>;
79
- /**
80
- * Force a manual reconnect (tear down and reconnect).
81
- * Used when we need a fresh MQTT session (e.g., after ack timeout).
82
- * @param {string} reason - Reason for reconnect
83
- * @returns {Promise<void>}
84
- */
85
- forceReconnect(reason?: string): Promise<void>;
86
- /**
87
- * Publish a message.
88
- * @param {string} topic
89
- * @param {string | Buffer} payload
90
- * @param {Object} [opts]
91
- * @returns {Promise<void>}
92
- */
93
- publish(topic: string, payload: string | Buffer, opts?: any): Promise<void>;
94
- /**
95
- * Subscribe to a topic.
96
- * @param {string} topic
97
- * @param {number} qos
98
- * @returns {Promise<void>}
99
- */
100
- subscribe(topic: string, qos?: number): Promise<void>;
101
- /**
102
- * Schedule a JWT refresh based on an expiration timestamp (ms since epoch).
103
- * @param {number} expMs - Expiration timestamp in milliseconds since epoch
104
- * @param {string} [leaseId] - Optional lease ID for correlation
105
- */
106
- scheduleRefresh(expMs: number, leaseId?: string): void;
107
- /**
108
- * Check if MQTT is online.
109
- * @returns {boolean}
110
- */
111
- isOnline(): boolean;
112
- /**
113
- * Get current client ID.
114
- * @returns {string}
115
- */
116
- getClientId(): string;
117
- /**
118
- * Set message handler (for Transport interface).
119
- * Converts mqtt.js format (topic, payload, packet) to MqttCore format {topic, payload: Uint8Array}
120
- * @param {(message: {topic: string, payload: Uint8Array}) => void} handler
121
- */
122
- setMessageHandler(handler: (message: {
123
- topic: string;
124
- payload: Uint8Array;
125
- }) => void): void;
126
- /**
127
- * Generate client ID based on mode.
128
- * @returns {string}
129
- */
130
- makeClientId(): string;
131
- /**
132
- * Connect with a new client (initial or after fault).
133
- * @param {boolean} initial - true for first connect, false for reconnect
134
- * @returns {Promise<void>}
135
- */
136
- connectWithNewClient(initial?: boolean): Promise<void>;
137
- /**
138
- * Classify MQTT fault as hard or soft.
139
- * @param {string} event - Event type: 'error', 'close', 'end'
140
- * @param {any} [err] - Error object
141
- * @param {number} [closeCode] - MQTT close code
142
- * @param {boolean} [beforeConnect] - true if fault occurred before connect event
143
- * @returns {MqttFaultKind}
144
- */
145
- classifyMqttFault(event: string, err?: any, closeCode?: number, beforeConnect?: boolean): MqttFaultKind;
146
- /**
147
- * Handle a fault (soft or hard).
148
- * Hard faults trigger clientId rotation and immediate reconnect.
149
- * @param {MqttFaultKind} kind
150
- * @param {any} [err]
151
- */
152
- handleFault(kind: MqttFaultKind, err?: any): void;
153
- /**
154
- * Force close the current client.
155
- */
156
- forceCloseClient(): void;
157
- /**
158
- * Schedule reconnect with jittered backoff.
159
- * @param {boolean} immediate - true for hard faults (ECONNRESET, etc.), false for soft
160
- * @param {{ transient?: boolean }} [options] - transient resolver failures use a growing delay
161
- */
162
- scheduleReconnect(immediate: boolean, options?: {
163
- transient?: boolean;
164
- }): void;
165
- /**
166
- * Start watchdog timer to detect stuck connections.
167
- */
168
- startWatchdog(): void;
169
- /**
170
- * Clear watchdog timer.
171
- */
172
- clearWatchdog(): void;
173
- /**
174
- * Clear reconnect timer.
175
- */
176
- clearReconnectTimer(): void;
177
- /**
178
- * Clear refresh timer.
179
- */
180
- clearRefreshTimer(): void;
181
- /**
182
- * Clear rearm timeout (QPA-CLI-08).
183
- */
184
- clearRearmTimeout(): void;
185
- /**
186
- * Clear flush pending refresh timer.
187
- */
188
- clearFlushPendingRefreshTimer(): void;
189
- /**
190
- * Attempt to refresh the lease token.
191
- * @param {string} reason - Reason for refresh (e.g., 'scheduled', 'pending_after_reconnect')
192
- */
193
- refreshLeaseToken(reason: string): Promise<void>;
194
- /**
195
- * Check if error is an offline/connection error (should buffer refresh).
196
- * @param {any} err
197
- * @returns {boolean}
198
- */
199
- isOfflineError(err: any): boolean;
200
- /**
201
- * QPA-CLI-08: Ensure a refresh is scheduled after reconnect.
202
- * Checks if refresh is pending or if we need to re-arm a refresh.
203
- */
204
- ensureRefreshScheduled(): void;
205
- /**
206
- * Handle fatal error (JWT expired, max retries, etc.).
207
- * @param {string} reason
208
- * @param {any} [err]
209
- */
210
- handleFatal(reason: string, err?: any): void;
211
- }
212
- export type MqttFaultKind = "soft" | "hard" | "transient";
213
- export type MqttControlPlaneClientOptions = {
214
- /**
215
- * - MQTT broker URL (e.g., 'wss://...')
216
- */
217
- url: string;
218
- /**
219
- * - Base client ID (e.g., 'cli_F285616B53CE')
220
- */
221
- baseClientId: string;
222
- /**
223
- * - Additional mqtt.js options (cert, key, ca, etc.)
224
- */
225
- mqttOptions?: any;
226
- /**
227
- * - Called after successful connect
228
- */
229
- onConnected?: (client: any) => void | Promise<void>;
230
- /**
231
- * - Called when connection goes offline
232
- */
233
- onOffline?: (reason: string) => void;
234
- /**
235
- * - Called when we give up due to JWT expiry or unrecoverable error
236
- */
237
- onFatalError?: (reason: string, err?: unknown) => void;
238
- /**
239
- * - Story 3.13: reopen after a closed lease.
240
- */
241
- onLeaseClosed?: () => Promise<{
242
- exp: number | null;
243
- leaseId: string;
244
- } | null>;
245
- /**
246
- * - Async refresh function. Must publish the refresh request over MQTT and resolve with new exp (ms since epoch). Throw on hard failure.
247
- */
248
- onRefreshLease: () => Promise<number>;
249
- /**
250
- * - Seconds before exp when we should start refresh (e.g. 0.75 * ttl, default: 675s for 15min TTL)
251
- */
252
- refreshEarlySeconds?: number;
253
- /**
254
- * - Max reconnect delay in ms (default 5000)
255
- */
256
- maxReconnectDelayMs?: number;
257
- /**
258
- * - Mode: 'unique' (default) or 'legacy'
259
- */
260
- mode?: "unique" | "legacy";
261
- /**
262
- * - Logger for structured logging
263
- */
264
- logger?: any;
265
- /**
266
- * - Optional mqtt library for dependency injection (defaults to real mqtt)
267
- */
268
- mqttLib?: any;
269
- /**
270
- * - Optional ulid library for dependency injection (defaults to real ulid)
271
- */
272
- ulidLib?: any;
273
- };
@@ -1,79 +0,0 @@
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';