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
@@ -0,0 +1,230 @@
1
+ // Shared JWT verifier using JWKS for assignment token validation
2
+ // Used by TCP/HTTP/UDP tunnels to verify assignment JWTs before opening WebSocket
3
+ // AC1.4/AC5.1: Enforces "no JWKS → no tunnel" policy
4
+ import { createRemoteJWKSet, jwtVerify } from 'jose';
5
+ import logger from './logger.js';
6
+ // JWKS URL configuration (environment-specific)
7
+ const JWKS_URL_PROD = 'https://auth.asyx.ai/.well-known/jwks.json';
8
+ const JWKS_URL_DEV = 'https://auth.dev.asyx.ai/.well-known/jwks.json';
9
+ // Expected issuer and audience
10
+ const EXPECTED_ISSUER = 'https://auth.asyx.ai';
11
+ const EXPECTED_AUDIENCE = 'tunnel-relay';
12
+ // Singleton JWKS cache (shared across all tunnel instances)
13
+ let jwksCache = null;
14
+ let jwksInitialized = false;
15
+ let jwksInitPromise = null;
16
+ /**
17
+ * Initialize JWKS cache (lazy, on first use)
18
+ * @returns {Promise<void>}
19
+ */
20
+ async function initializeJWKS() {
21
+ if (jwksInitialized) {
22
+ return;
23
+ }
24
+ if (jwksInitPromise) {
25
+ return jwksInitPromise;
26
+ }
27
+ jwksInitPromise = (async () => {
28
+ try {
29
+ // Determine JWKS URL from environment
30
+ const env = process.env.ASYX_ENV || process.env.NODE_ENV || 'prod';
31
+ const jwksUrl = env === 'dev' || env === 'development' ? JWKS_URL_DEV : JWKS_URL_PROD;
32
+ // Allow override via environment variable
33
+ const jwksUrlOverride = process.env.ASYX_JWKS_URL;
34
+ const finalJwksUrl = jwksUrlOverride || jwksUrl;
35
+ logger.debug('jwt.jwks.initializing', { jwksUrl: finalJwksUrl, env });
36
+ // Create remote JWKS set (jose handles caching and refresh)
37
+ jwksCache = createRemoteJWKSet(new URL(finalJwksUrl));
38
+ // Test fetch to ensure JWKS is available (fail fast if not)
39
+ // jose's createRemoteJWKSet doesn't fetch immediately, so we need to trigger a fetch
40
+ // We'll do this on first verification attempt
41
+ jwksInitialized = true;
42
+ logger.info('jwt.jwks.initialized', { jwksUrl: finalJwksUrl });
43
+ }
44
+ catch (error) {
45
+ jwksInitPromise = null;
46
+ logger.error('jwt.jwks.init_failed', { error: error.message });
47
+ throw error;
48
+ }
49
+ })();
50
+ return jwksInitPromise;
51
+ }
52
+ /**
53
+ * Verify assignment JWT with JWKS signature verification
54
+ * AC1.4/AC5.1: Validates signature, iss, aud, exp, relayId, protocol, tunnelMode, leaseId
55
+ * @param {string} token - JWT token to verify
56
+ * @param {Object} expectedClaims - Expected claim values
57
+ * @param {string} expectedClaims.relayId - Expected relayId
58
+ * @param {string} expectedClaims.protocol - Expected protocol ('udp' | 'tcp')
59
+ * @param {string} expectedClaims.tunnelMode - Expected tunnelMode ('udpWs-v1' | 'tcpWs-v1')
60
+ * @param {string} [expectedClaims.leaseId] - Expected leaseId (optional)
61
+ * @returns {Promise<Object>} Verified JWT payload
62
+ * @throws {Error} If JWT verification fails (signature, claims, or JWKS unavailable)
63
+ */
64
+ export async function verifyAssignmentJWT(token, expectedClaims = /** @type {any} */ ({})) {
65
+ // Initialize JWKS if not already done
66
+ if (!jwksInitialized) {
67
+ await initializeJWKS();
68
+ }
69
+ // AC1.4/AC5.1: Fail fast if JWKS is not available
70
+ if (!jwksCache) {
71
+ const error = /** @type {Error & { code?: string, cause?: unknown, closeCode?: number, originalError?: unknown }} */ (new Error('JWKS not available - cannot verify assignment JWT'));
72
+ error.code = 'JWKS_UNAVAILABLE';
73
+ logger.error('jwt.verification.jwks_unavailable', {
74
+ tokenLength: token?.length || 0,
75
+ expectedRelayId: expectedClaims.relayId
76
+ });
77
+ throw error;
78
+ }
79
+ try {
80
+ // Verify JWT signature and decode payload using JWKS
81
+ // jwtVerify automatically:
82
+ // - Fetches JWKS if not cached
83
+ // - Verifies signature using the key identified by 'kid' in JWT header
84
+ // - Validates exp, nbf, iat if present
85
+ const { payload, protectedHeader } = await jwtVerify(token, jwksCache, {
86
+ issuer: EXPECTED_ISSUER,
87
+ audience: EXPECTED_AUDIENCE,
88
+ // jose validates exp automatically with clock skew tolerance
89
+ // We'll get ERR_JWT_EXPIRED if expired, which we handle below
90
+ });
91
+ logger.debug('jwt.verification.signature_verified', {
92
+ kid: protectedHeader.kid,
93
+ alg: protectedHeader.alg,
94
+ relayId: payload.relayId,
95
+ protocol: payload.protocol,
96
+ tunnelMode: payload.tunnelMode
97
+ });
98
+ // AC5.1: Validate relayId matches expected
99
+ if (expectedClaims.relayId && payload.relayId !== expectedClaims.relayId) {
100
+ const error = /** @type {Error & { code?: string, cause?: unknown, closeCode?: number, originalError?: unknown }} */ (new Error(`JWT relayId mismatch: ${payload.relayId} !== ${expectedClaims.relayId}`));
101
+ error.code = 'JWT_RELAYID_MISMATCH';
102
+ logger.error('jwt.verification.relayid_mismatch', {
103
+ expected: expectedClaims.relayId,
104
+ actual: payload.relayId,
105
+ leaseId: payload.leaseId
106
+ });
107
+ throw error;
108
+ }
109
+ // AC1.4: Validate protocol
110
+ if (expectedClaims.protocol && payload.protocol !== expectedClaims.protocol) {
111
+ const error = /** @type {Error & { code?: string, cause?: unknown, closeCode?: number, originalError?: unknown }} */ (new Error(`JWT protocol mismatch: ${payload.protocol} !== ${expectedClaims.protocol}`));
112
+ error.code = 'JWT_PROTOCOL_MISMATCH';
113
+ logger.error('jwt.verification.protocol_mismatch', {
114
+ expected: expectedClaims.protocol,
115
+ actual: payload.protocol
116
+ });
117
+ throw error;
118
+ }
119
+ // AC1.4: Validate tunnelMode
120
+ if (expectedClaims.tunnelMode && payload.tunnelMode !== expectedClaims.tunnelMode) {
121
+ const error = /** @type {Error & { code?: string, cause?: unknown, closeCode?: number, originalError?: unknown }} */ (new Error(`JWT tunnelMode mismatch: ${payload.tunnelMode} !== ${expectedClaims.tunnelMode}`));
122
+ error.code = 'JWT_TUNNELMODE_MISMATCH';
123
+ logger.error('jwt.verification.tunnelmode_mismatch', {
124
+ expected: expectedClaims.tunnelMode,
125
+ actual: payload.tunnelMode
126
+ });
127
+ throw error;
128
+ }
129
+ // AC5.1: Validate leaseId if provided
130
+ if (expectedClaims.leaseId && payload.leaseId && payload.leaseId !== expectedClaims.leaseId) {
131
+ const error = /** @type {Error & { code?: string, cause?: unknown, closeCode?: number, originalError?: unknown }} */ (new Error(`JWT leaseId mismatch: ${payload.leaseId} !== ${expectedClaims.leaseId}`));
132
+ error.code = 'JWT_LEASEID_MISMATCH';
133
+ logger.error('jwt.verification.leaseid_mismatch', {
134
+ expected: expectedClaims.leaseId,
135
+ actual: payload.leaseId
136
+ });
137
+ throw error;
138
+ }
139
+ // AC1.4: Validate required claims are present
140
+ if (!payload.relayId) {
141
+ const error = /** @type {Error & { code?: string, cause?: unknown, closeCode?: number, originalError?: unknown }} */ (new Error('Missing relayId in JWT payload'));
142
+ error.code = 'JWT_MISSING_RELAYID';
143
+ throw error;
144
+ }
145
+ if (!payload.protocol) {
146
+ const error = /** @type {Error & { code?: string, cause?: unknown, closeCode?: number, originalError?: unknown }} */ (new Error('Missing protocol in JWT payload'));
147
+ error.code = 'JWT_MISSING_PROTOCOL';
148
+ throw error;
149
+ }
150
+ if (!payload.tunnelMode) {
151
+ const error = /** @type {Error & { code?: string, cause?: unknown, closeCode?: number, originalError?: unknown }} */ (new Error('Missing tunnelMode in JWT payload'));
152
+ error.code = 'JWT_MISSING_TUNNELMODE';
153
+ throw error;
154
+ }
155
+ logger.debug('jwt.verification.success', {
156
+ relayId: payload.relayId,
157
+ protocol: payload.protocol,
158
+ tunnelMode: payload.tunnelMode,
159
+ leaseId: payload.leaseId
160
+ });
161
+ return payload;
162
+ }
163
+ catch (error) {
164
+ // Map jose errors to our error codes
165
+ if (error.code === 'ERR_JWKS_TIMEOUT' || error.code === 'ERR_JWKS_MULTIPLE_MATCHING_KEYS') {
166
+ const jwksError = /** @type {Error & { code?: string, cause?: unknown, closeCode?: number, originalError?: unknown }} */ (new Error(`JWKS error: ${error.message}`));
167
+ jwksError.code = 'JWKS_ERROR';
168
+ logger.error('jwt.verification.jwks_error', {
169
+ error: error.message,
170
+ code: error.code
171
+ });
172
+ throw jwksError;
173
+ }
174
+ if (error.code === 'ERR_JWT_EXPIRED') {
175
+ const expiredError = /** @type {Error & { code?: string, cause?: unknown, closeCode?: number, originalError?: unknown }} */ (new Error('JWT expired'));
176
+ expiredError.code = 'JWT_EXPIRED';
177
+ logger.error('jwt.verification.expired', {
178
+ exp: error.claims?.exp,
179
+ now: Math.floor(Date.now() / 1000)
180
+ });
181
+ throw expiredError;
182
+ }
183
+ if (error.code === 'ERR_JWT_CLAIM_VALIDATION_FAILED') {
184
+ // This could be issuer or audience mismatch
185
+ const claimError = /** @type {Error & { code?: string, cause?: unknown, closeCode?: number, originalError?: unknown }} */ (new Error(`JWT claim validation failed: ${error.message}`));
186
+ claimError.code = 'JWT_CLAIM_INVALID';
187
+ logger.error('jwt.verification.claim_failed', {
188
+ error: error.message,
189
+ claim: error.claim
190
+ });
191
+ throw claimError;
192
+ }
193
+ if (error.code === 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED') {
194
+ const sigError = /** @type {Error & { code?: string, cause?: unknown, closeCode?: number, originalError?: unknown }} */ (new Error('JWT signature verification failed'));
195
+ sigError.code = 'JWT_SIGNATURE_INVALID';
196
+ logger.error('jwt.verification.signature_failed', {
197
+ error: error.message
198
+ });
199
+ throw sigError;
200
+ }
201
+ // Re-throw our custom errors
202
+ if (error.code && error.code.startsWith('JWT_') || error.code === 'JWKS_UNAVAILABLE' || error.code === 'JWKS_ERROR') {
203
+ throw error;
204
+ }
205
+ // Unknown error - wrap it
206
+ const unknownError = /** @type {Error & { code?: string, cause?: unknown, closeCode?: number, originalError?: unknown }} */ (new Error(`JWT verification failed: ${error.message}`));
207
+ unknownError.code = 'JWT_VERIFICATION_FAILED';
208
+ unknownError.originalError = error;
209
+ logger.error('jwt.verification.unknown_error', {
210
+ error: error.message,
211
+ code: error.code
212
+ });
213
+ throw unknownError;
214
+ }
215
+ }
216
+ /**
217
+ * Check if JWKS is available (for health checks)
218
+ * @returns {boolean} True if JWKS is initialized
219
+ */
220
+ export function isJWKSAvailable() {
221
+ return jwksInitialized && jwksCache !== null;
222
+ }
223
+ /**
224
+ * Reset JWKS cache (for testing or re-initialization)
225
+ */
226
+ export function resetJWKS() {
227
+ jwksCache = null;
228
+ jwksInitialized = false;
229
+ jwksInitPromise = null;
230
+ }
@@ -0,0 +1,9 @@
1
+ export function log(level: any, msg: any, fields?: {}): void;
2
+ export namespace logger {
3
+ export function debug(msg: any, fields: any): void;
4
+ export function info(msg: any, fields: any): void;
5
+ export function warn(msg: any, fields: any): void;
6
+ export function error(msg: any, fields: any): void;
7
+ export { log };
8
+ }
9
+ export default logger;
@@ -0,0 +1,58 @@
1
+ function isoNow() {
2
+ return new Date().toISOString();
3
+ }
4
+ // Parse env log level once at module load
5
+ const LEVEL_ORDER = { error: 40, warn: 30, info: 20, debug: 10 };
6
+ function normalizeLevel(value) {
7
+ const v = String(value || '').trim().toLowerCase();
8
+ if (v in LEVEL_ORDER)
9
+ return v;
10
+ // QPA-CLI-10: Default to warn for quiet mode (suppress info/debug telemetry, show warn/error)
11
+ // Users can set LOG_LEVEL=info to see structured telemetry logs
12
+ return 'warn';
13
+ }
14
+ // QPA-CLI-10: Support both ASYX_LOG_LEVEL and LOG_LEVEL env vars
15
+ const ENV_LEVEL = normalizeLevel(process.env.ASYX_LOG_LEVEL || process.env.LOG_LEVEL);
16
+ function shouldEmit(level) {
17
+ // QPA-CLI-10: Default to warn level (quiet mode - suppress info/debug telemetry)
18
+ const desired = LEVEL_ORDER[ENV_LEVEL] ?? LEVEL_ORDER.warn;
19
+ const actual = LEVEL_ORDER[normalizeLevel(level)] ?? LEVEL_ORDER.error; // Default actual to error if invalid
20
+ return actual >= desired;
21
+ }
22
+ function emit(level, msg, fields = {}) {
23
+ const entry = {
24
+ ts: isoNow(),
25
+ lvl: level,
26
+ msg,
27
+ fields: fields && typeof fields === 'object' ? fields : {},
28
+ };
29
+ // Ensure single-line JSON output
30
+ const line = JSON.stringify(entry);
31
+ // Level gating: suppress messages below configured level
32
+ if (!shouldEmit(level))
33
+ return;
34
+ // Route by level to preserve severity semantics if needed
35
+ if (level === 'error') {
36
+ console.error(line);
37
+ }
38
+ else if (level === 'warn') {
39
+ console.warn(line);
40
+ }
41
+ else if (level === 'debug') {
42
+ console.debug(line);
43
+ }
44
+ else {
45
+ console.log(line);
46
+ }
47
+ }
48
+ export function log(level, msg, fields = {}) {
49
+ emit(level, msg, fields);
50
+ }
51
+ export const logger = {
52
+ debug: (msg, fields) => emit('debug', msg, fields),
53
+ info: (msg, fields) => emit('info', msg, fields),
54
+ warn: (msg, fields) => emit('warn', msg, fields),
55
+ error: (msg, fields) => emit('error', msg, fields),
56
+ log,
57
+ };
58
+ export default logger;
@@ -0,0 +1,16 @@
1
+ import type { Logger, Publisher } from '../types.js';
2
+ /**
3
+ * QPA-CLI-09: Publish refresh request with ECONNRESET error handling.
4
+ * Catches connection reset errors during publish and returns a sentinel value
5
+ * instead of throwing, so the CLI doesn't exit with "Unexpected error".
6
+ *
7
+ * @param coordinatorCore - MQTT core client with publish method
8
+ * @param topic - MQTT topic to publish to
9
+ * @param payload - Refresh payload object (will be JSON stringified)
10
+ * @param refreshRequestId - Request ID for logging
11
+ * @param logger - Logger instance
12
+ * @returns Returns true on success, false on ECONNRESET (buffered), throws on other errors
13
+ */
14
+ export declare function publishRefreshRequestWithErrorHandling(coordinatorCore: Publisher, topic: string, payload: unknown, refreshRequestId: string, logger: Logger): Promise<boolean>;
15
+ /** Expiry (seconds since epoch) of a JWT, or null; no signature check. */
16
+ export declare function jwtExpOf(jwt: unknown): number | null;
@@ -0,0 +1,66 @@
1
+ /**
2
+ * QPA-CLI-09: Publish refresh request with ECONNRESET error handling.
3
+ * Catches connection reset errors during publish and returns a sentinel value
4
+ * instead of throwing, so the CLI doesn't exit with "Unexpected error".
5
+ *
6
+ * @param coordinatorCore - MQTT core client with publish method
7
+ * @param topic - MQTT topic to publish to
8
+ * @param payload - Refresh payload object (will be JSON stringified)
9
+ * @param refreshRequestId - Request ID for logging
10
+ * @param logger - Logger instance
11
+ * @returns Returns true on success, false on ECONNRESET (buffered), throws on other errors
12
+ */
13
+ export async function publishRefreshRequestWithErrorHandling(coordinatorCore, topic, payload, refreshRequestId, logger) {
14
+ try {
15
+ await coordinatorCore.publish({
16
+ topic,
17
+ payload: JSON.stringify(payload),
18
+ qos: 1,
19
+ retain: false
20
+ });
21
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
22
+ logger.debug('jwt.refresh.request.sent', { refreshRequestId });
23
+ return true;
24
+ }
25
+ catch (caught) {
26
+ const publishError = caught;
27
+ // Check if this is a connection reset error (transient condition)
28
+ const isConnectionError = publishError?.code === 'ECONNRESET' ||
29
+ publishError?.errno === -54 || // macOS/Linux ECONNRESET errno
30
+ publishError?.message?.includes('ECONNRESET') ||
31
+ publishError?.message?.includes('Connection closed') ||
32
+ publishError?.message?.includes('connection closed');
33
+ if (isConnectionError) {
34
+ // QPA-CLI-09: Return false instead of throwing - refresh is buffered, CLI stays alive
35
+ // The MqttControlPlaneClient will detect the disconnect and set refreshPending=true
36
+ // The re-arm logic will retry after reconnect
37
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
38
+ logger.debug('jwt.refresh.publish.econnreset', {
39
+ refreshRequestId,
40
+ error: publishError?.message || String(publishError),
41
+ code: publishError?.code,
42
+ action: 'buffered_for_retry'
43
+ });
44
+ // Return false to indicate buffered (don't throw - prevents "Unexpected error" log)
45
+ return false;
46
+ }
47
+ // For non-connection errors (e.g., JSON parse, invalid payload), rethrow
48
+ logger.error('jwt.refresh.publish.error', {
49
+ refreshRequestId,
50
+ error: publishError?.message || String(publishError),
51
+ code: publishError?.code
52
+ });
53
+ throw caught;
54
+ }
55
+ }
56
+ /** Expiry (seconds since epoch) of a JWT, or null; no signature check. */
57
+ export function jwtExpOf(jwt) {
58
+ try {
59
+ const part = String(jwt).split('.')[1];
60
+ const payload = JSON.parse(Buffer.from(part.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'));
61
+ return typeof payload.exp === 'number' ? payload.exp : null;
62
+ }
63
+ catch {
64
+ return null;
65
+ }
66
+ }
@@ -0,0 +1,24 @@
1
+ import { EventEmitter } from 'node:events';
2
+ import type { TunnelError } from './errors.js';
3
+ export declare const STATES: readonly ["opening", "live", "reconnecting", "renewed", "closed"];
4
+ export type TunnelState = (typeof STATES)[number];
5
+ /** Extra facts sent with a state change; `error` is set on a 'closed' that was not asked for. */
6
+ export interface StateDetail {
7
+ error?: TunnelError;
8
+ [key: string]: unknown;
9
+ }
10
+ export interface StateEvent extends StateDetail {
11
+ state: TunnelState;
12
+ }
13
+ export interface WarningEvent {
14
+ code: string;
15
+ [key: string]: unknown;
16
+ }
17
+ export declare class LifecycleEmitter extends EventEmitter {
18
+ state: TunnelState | null;
19
+ emit(name: string | symbol, ...args: unknown[]): boolean;
20
+ /** Change state and tell listeners. `detail` may carry `error` (on 'closed'), relay ids, etc. */
21
+ setState(state: TunnelState, detail?: StateDetail): void;
22
+ /** A non-fatal problem the caller may want to show (the core never prints). */
23
+ warn(code: string, detail?: Record<string, unknown>): void;
24
+ }
@@ -0,0 +1,29 @@
1
+ // Story 12.1 (step 2b; TypeScript in r3): lifecycle events for tunnels opened through @asyx/tunnel-core.
2
+ // Operations (connect, open, close) are promises; what happens after a tunnel is open is events.
3
+ // A Node EventEmitter crashes the process when 'error' is emitted with no listener, which c2
4
+ // forbids, so this emitter refuses that event name: a tunnel that ends for good emits a final
5
+ // 'state' event with state 'closed' and the typed error instead.
6
+ import { EventEmitter } from 'node:events';
7
+ export const STATES = Object.freeze(['opening', 'live', 'reconnecting', 'renewed', 'closed']);
8
+ export class LifecycleEmitter extends EventEmitter {
9
+ state = null;
10
+ emit(name, ...args) {
11
+ if (name === 'error')
12
+ throw new TypeError("LifecycleEmitter never emits 'error'; use setState('closed', { error })");
13
+ return super.emit(name, ...args);
14
+ }
15
+ /** Change state and tell listeners. `detail` may carry `error` (on 'closed'), relay ids, etc. */
16
+ setState(state, detail = {}) {
17
+ if (!STATES.includes(state))
18
+ throw new TypeError(`unknown tunnel state: ${state}`);
19
+ if (this.state === 'closed')
20
+ return; // closed is final
21
+ this.state = state;
22
+ super.emit('state', { state, ...detail });
23
+ super.emit(state, detail);
24
+ }
25
+ /** A non-fatal problem the caller may want to show (the core never prints). */
26
+ warn(code, detail = {}) {
27
+ super.emit('warning', { code, ...detail });
28
+ }
29
+ }
@@ -0,0 +1,56 @@
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
+ /**
10
+ * Create a criteria function for session ID matching (backward compatibility)
11
+ * @param {string} sessionId - Session ID to match
12
+ * @param {string} expectedTopic - Expected topic pattern
13
+ * @returns {Function} Criteria function
14
+ */
15
+ static createSessionIdCriteria(sessionId: string, expectedTopic: string): Function;
16
+ /**
17
+ * Create a criteria function for correlation ID matching (future use)
18
+ * @param {string} correlationId - Correlation ID to match
19
+ * @param {string} expectedTopic - Expected topic pattern
20
+ * @returns {Function} Criteria function
21
+ */
22
+ static createCorrelationIdCriteria(correlationId: string, expectedTopic: string): Function;
23
+ constructor(maxSize?: number, logger?: any);
24
+ maxSize: number;
25
+ awaiters: Map<any, any>;
26
+ nextId: number;
27
+ logger: any;
28
+ /**
29
+ * Register an awaiter that will be resolved when a message matches the criteria
30
+ * @param {Function} criteria - Function that returns true if message matches
31
+ * @param {number} timeoutMs - Timeout in milliseconds
32
+ * @returns {Promise} Promise that resolves with the matching message
33
+ */
34
+ register(criteria: Function, timeoutMs?: number): Promise<any>;
35
+ /**
36
+ * Process an incoming message against all registered awaiters
37
+ * @param {Object} message - Message object with topic and payload
38
+ * @returns {boolean} True if any awaiter was resolved
39
+ */
40
+ processMessage(message: any): boolean;
41
+ /**
42
+ * Get current statistics about the awaiter map
43
+ * @returns {Object} Statistics object
44
+ */
45
+ getStats(): any;
46
+ /**
47
+ * Cancel awaiters that match a test criteria
48
+ * @param {Function} testCriteria - Function that returns true if an awaiter should be cancelled
49
+ * @returns {number} Number of awaiters cancelled
50
+ */
51
+ cancelByCriteria(testCriteria: Function): number;
52
+ /**
53
+ * Clear all awaiters (for cleanup)
54
+ */
55
+ clear(): void;
56
+ }