asyx 0.1.1 → 0.1.3

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.
@@ -0,0 +1,150 @@
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
+
9
+ import { MqttControlPlaneClient } from './MqttControlPlaneClient.js';
10
+
11
+ /**
12
+ * Transport adapter that wraps MqttControlPlaneClient.
13
+ * Implements the Transport interface from @asyx/mqtt-core.
14
+ */
15
+ export class MqttControlPlaneTransport {
16
+ /**
17
+ * @param {MqttControlPlaneClient} client
18
+ */
19
+ constructor(client) {
20
+ this.client = client;
21
+ this._messageHandler = null;
22
+ this._connectHandler = null;
23
+ this._disconnectHandler = null;
24
+
25
+ // Store original callbacks to preserve them
26
+ const originalOnConnected = this.client.onConnected;
27
+ const originalOnOffline = this.client.onOffline;
28
+
29
+ // Wire up handlers when client connects (chain with existing callbacks)
30
+ this.client.onConnected = async (mqttClient) => {
31
+ // Wire up message handler (setMessageHandler ensures it's wired on reconnect)
32
+ if (this._messageHandler) {
33
+ this.client.setMessageHandler(this._messageHandler);
34
+ }
35
+
36
+ // Call original callback (set by tunnel.js)
37
+ if (originalOnConnected) {
38
+ await originalOnConnected(mqttClient);
39
+ }
40
+
41
+ // Call Transport connect handler (for MqttCore)
42
+ if (this._connectHandler) {
43
+ this._connectHandler();
44
+ }
45
+ };
46
+
47
+ // Wire up disconnect handler (chain with existing callbacks)
48
+ this.client.onOffline = (reason) => {
49
+ // Call original callback (set by tunnel.js)
50
+ if (originalOnOffline) {
51
+ originalOnOffline(reason);
52
+ }
53
+
54
+ // Call Transport disconnect handler (for MqttCore)
55
+ if (this._disconnectHandler) {
56
+ this._disconnectHandler(new Error(reason));
57
+ }
58
+ };
59
+ }
60
+
61
+ /**
62
+ * Transport interface: connect
63
+ * @param {any} opts - ConnectOptions (ignored, client manages its own connection)
64
+ * @returns {Promise<void>}
65
+ */
66
+ async connect(opts) {
67
+ // Client manages its own connection, just ensure it's connected
68
+ if (!this.client.isOnline()) {
69
+ await this.client.connect();
70
+ }
71
+ }
72
+
73
+ /**
74
+ * Transport interface: end
75
+ * @returns {Promise<void>}
76
+ */
77
+ async end() {
78
+ return this.client.disconnect();
79
+ }
80
+
81
+ /**
82
+ * Transport interface: publish
83
+ * @param {{topic: string, payload: string | Buffer | Uint8Array, qos?: 0 | 1, retain?: boolean}} p
84
+ * @returns {Promise<void>}
85
+ */
86
+ async publish(p) {
87
+ const payload = p.payload instanceof Uint8Array
88
+ ? Buffer.from(p.payload)
89
+ : (typeof p.payload === 'string' ? p.payload : p.payload);
90
+ return this.client.publish(p.topic, payload, { qos: p.qos ?? 0, retain: p.retain ?? false });
91
+ }
92
+
93
+ /**
94
+ * Transport interface: subscribe
95
+ * @param {string} topic
96
+ * @param {0 | 1} [qos=0]
97
+ * @returns {Promise<{topic: string, qos: 0 | 1}>}
98
+ */
99
+ async subscribe(topic, qos = 0) {
100
+ return this.client.subscribe(topic, qos);
101
+ }
102
+
103
+ /**
104
+ * Transport interface: unsubscribe
105
+ * @param {string} topic
106
+ * @returns {Promise<void>}
107
+ */
108
+ async unsubscribe(topic) {
109
+ return this.client.unsubscribe(topic);
110
+ }
111
+
112
+ /**
113
+ * Transport interface: onMessage
114
+ * @param {(message: {topic: string, payload: Uint8Array}) => void} cb
115
+ */
116
+ onMessage(cb) {
117
+ this._messageHandler = cb;
118
+ // Set message handler on client (will be wired on connect/reconnect)
119
+ this.client.setMessageHandler(cb);
120
+ }
121
+
122
+ /**
123
+ * Transport interface: onConnect
124
+ * @param {() => void} cb
125
+ */
126
+ onConnect(cb) {
127
+ this._connectHandler = cb;
128
+ // If already connected, call immediately
129
+ if (this.client.isOnline()) {
130
+ cb();
131
+ }
132
+ }
133
+
134
+ /**
135
+ * Transport interface: onDisconnect
136
+ * @param {(err?: unknown) => void} cb
137
+ */
138
+ onDisconnect(cb) {
139
+ this._disconnectHandler = cb;
140
+ }
141
+
142
+ /**
143
+ * Expose client for helpers that need direct access
144
+ * @returns {MqttControlPlaneClient}
145
+ */
146
+ getClient() {
147
+ return this.client;
148
+ }
149
+ }
150
+
package/src/lib/csr.js CHANGED
@@ -127,12 +127,23 @@ export async function ensureKeyAndCsr(clientId, options = {}) {
127
127
  // Generate new key pair
128
128
  keyPair = await crypto.subtle.generateKey(alg, true, ['sign', 'verify']);
129
129
 
130
- // Export private key in PKCS8 format
130
+ // Export private key in PKCS#8 format (for CSR operations)
131
131
  const pkcs8 = await crypto.subtle.exportKey('pkcs8', keyPair.privateKey);
132
- const pem = bufferToPem(pkcs8, 'PRIVATE KEY');
133
-
134
- // Write private key file
135
- await fs.writeFile(keyPath, pem, { encoding: 'utf8', mode: 0o600 });
132
+ const pkcs8Pem = bufferToPem(pkcs8, 'PRIVATE KEY');
133
+
134
+ // Convert PKCS#8 to PKCS#1 using Node.js crypto (required for Windows TLS compatibility)
135
+ // Node's TLS stack on Windows requires PKCS#1 format (BEGIN RSA PRIVATE KEY)
136
+ const nodePrivateKey = nodeCrypto.createPrivateKey({
137
+ key: pkcs8Pem,
138
+ format: 'pem'
139
+ });
140
+ const pkcs1Pem = nodePrivateKey.export({
141
+ type: 'pkcs1',
142
+ format: 'pem'
143
+ });
144
+
145
+ // Write private key file in PKCS#1 format (for TLS compatibility)
146
+ await fs.writeFile(keyPath, pkcs1Pem, { encoding: 'utf8', mode: 0o600 });
136
147
  } else {
137
148
  // Import existing private key
138
149
  const keyPem = await fs.readFile(keyPath, 'utf8');
@@ -141,24 +152,33 @@ export async function ensureKeyAndCsr(clientId, options = {}) {
141
152
  const isPkcs1 = keyPem.includes('BEGIN RSA PRIVATE KEY');
142
153
 
143
154
  let pkcs8Bytes;
155
+
144
156
  if (isPkcs1) {
145
- // Convert PKCS#1 to PKCS#8 using Node.js crypto (supports both formats)
146
- // Import as PKCS#1, then export as PKCS#8
157
+ // Key is already PKCS#1 - keep it as is (don't convert to PKCS#8)
158
+ // Convert PKCS#1 to PKCS#8 bytes in memory for webcrypto import
147
159
  const nodePrivateKey = nodeCrypto.createPrivateKey({
148
160
  key: keyPem,
149
161
  format: 'pem'
150
162
  });
151
- // Export in PKCS#8 format
152
163
  const pkcs8Pem = nodePrivateKey.export({
153
164
  type: 'pkcs8',
154
165
  format: 'pem'
155
166
  });
156
167
  pkcs8Bytes = pemToBuffer(pkcs8Pem);
157
- // Optionally update the file to PKCS#8 format for future runs
158
- await fs.writeFile(keyPath, pkcs8Pem, { encoding: 'utf8', mode: 0o600 });
168
+ // Keep file as PKCS#1 (no write needed)
159
169
  } else {
160
- // Already PKCS#8 format
161
- pkcs8Bytes = pemToBuffer(keyPem);
170
+ // Key is PKCS#8 - convert to PKCS#1 for Windows TLS compatibility
171
+ const nodePrivateKey = nodeCrypto.createPrivateKey({
172
+ key: keyPem,
173
+ format: 'pem'
174
+ });
175
+ const pkcs1Pem = nodePrivateKey.export({
176
+ type: 'pkcs1',
177
+ format: 'pem'
178
+ });
179
+ pkcs8Bytes = pemToBuffer(keyPem); // Use original PKCS#8 for webcrypto
180
+ // Update the file to PKCS#1 format for future runs
181
+ await fs.writeFile(keyPath, pkcs1Pem, { encoding: 'utf8', mode: 0o600 });
162
182
  }
163
183
 
164
184
  keyPair = await importPrivateKey(pkcs8Bytes);
package/src/lib/logger.js CHANGED
@@ -8,14 +8,18 @@ const LEVEL_ORDER = { error: 40, warn: 30, info: 20, debug: 10 };
8
8
  function normalizeLevel(value) {
9
9
  const v = String(value || '').trim().toLowerCase();
10
10
  if (v in LEVEL_ORDER) return v;
11
- return 'info';
11
+ // QPA-CLI-10: Default to warn for quiet mode (suppress info/debug telemetry, show warn/error)
12
+ // Users can set LOG_LEVEL=info to see structured telemetry logs
13
+ return 'warn';
12
14
  }
13
15
 
14
- const ENV_LEVEL = normalizeLevel(process.env.ASYX_LOG_LEVEL);
16
+ // QPA-CLI-10: Support both ASYX_LOG_LEVEL and LOG_LEVEL env vars
17
+ const ENV_LEVEL = normalizeLevel(process.env.ASYX_LOG_LEVEL || process.env.LOG_LEVEL);
15
18
 
16
19
  function shouldEmit(level) {
17
- const desired = LEVEL_ORDER[ENV_LEVEL] ?? LEVEL_ORDER.info;
18
- const actual = LEVEL_ORDER[normalizeLevel(level)] ?? LEVEL_ORDER.info;
20
+ // QPA-CLI-10: Default to warn level (quiet mode - suppress info/debug telemetry)
21
+ const desired = LEVEL_ORDER[ENV_LEVEL] ?? LEVEL_ORDER.warn;
22
+ const actual = LEVEL_ORDER[normalizeLevel(level)] ?? LEVEL_ORDER.error; // Default actual to error if invalid
19
23
  return actual >= desired;
20
24
  }
21
25
 
@@ -7,10 +7,11 @@
7
7
  */
8
8
 
9
9
  export class AwaiterMap {
10
- constructor(maxSize = 100) {
10
+ constructor(maxSize = 100, logger = null) {
11
11
  this.maxSize = maxSize;
12
12
  this.awaiters = new Map();
13
13
  this.nextId = 1;
14
+ this.logger = logger; // QPA-CLI-10: Optional logger for quiet mode
14
15
  }
15
16
 
16
17
  /**
@@ -58,14 +59,55 @@ export class AwaiterMap {
58
59
  processMessage(message) {
59
60
  let resolved = false;
60
61
 
62
+ // Log open_ack messages for debugging awaiter matching
63
+ const isOpenAck = message.payload?.type === 'open_ack';
64
+ const requestId = message.payload?.requestId;
65
+
66
+ if (isOpenAck && requestId) {
67
+ // QPA-CLI-10: Use logger at debug level for quiet mode
68
+ if (this.logger) {
69
+ this.logger.debug('awaiter.open_ack.received', {
70
+ requestId,
71
+ topic: message.topic,
72
+ pendingAwaiters: this.awaiters.size,
73
+ awaiterIds: Array.from(this.awaiters.keys())
74
+ });
75
+ }
76
+ }
77
+
61
78
  for (const [id, awaiter] of this.awaiters) {
62
79
  try {
63
- if (awaiter.criteria(message)) {
80
+ const matched = awaiter.criteria(message);
81
+
82
+ if (isOpenAck && requestId) {
83
+ // QPA-CLI-10: Use logger at debug level for quiet mode
84
+ if (this.logger) {
85
+ this.logger.debug('awaiter.open_ack.checked', {
86
+ requestId,
87
+ awaiterId: id,
88
+ matched,
89
+ topic: message.topic
90
+ });
91
+ }
92
+ }
93
+
94
+ if (matched) {
64
95
  // Clear timeout and resolve
65
96
  clearTimeout(awaiter.timeoutId);
66
97
  this.awaiters.delete(id);
67
98
  awaiter.resolve(message);
68
99
  resolved = true;
100
+
101
+ if (isOpenAck && requestId) {
102
+ // QPA-CLI-10: Use logger at debug level for quiet mode
103
+ if (this.logger) {
104
+ this.logger.debug('awaiter.open_ack.resolved', {
105
+ requestId,
106
+ awaiterId: id,
107
+ topic: message.topic
108
+ });
109
+ }
110
+ }
69
111
  }
70
112
  } catch (error) {
71
113
  // Criteria function threw an error - reject and clean up
@@ -73,6 +115,31 @@ export class AwaiterMap {
73
115
  this.awaiters.delete(id);
74
116
  awaiter.reject(error);
75
117
  resolved = true;
118
+
119
+ if (isOpenAck && requestId) {
120
+ // QPA-CLI-10: Use logger at debug level for quiet mode
121
+ if (this.logger) {
122
+ this.logger.debug('awaiter.open_ack.criteria_error', {
123
+ requestId,
124
+ awaiterId: id,
125
+ error: error.message,
126
+ topic: message.topic
127
+ });
128
+ }
129
+ }
130
+ }
131
+ }
132
+
133
+ if (isOpenAck && requestId && !resolved) {
134
+ // QPA-CLI-10: Use logger at debug level for quiet mode (no_match is expected when awaiter already resolved)
135
+ if (this.logger) {
136
+ this.logger.debug('awaiter.open_ack.no_match', {
137
+ requestId,
138
+ topic: message.topic,
139
+ pendingAwaiters: this.awaiters.size,
140
+ payloadType: message.payload?.type,
141
+ payloadRequestId: message.payload?.requestId
142
+ });
76
143
  }
77
144
  }
78
145
 
@@ -96,6 +163,29 @@ export class AwaiterMap {
96
163
  };
97
164
  }
98
165
 
166
+ /**
167
+ * Cancel awaiters that match a test criteria
168
+ * @param {Function} testCriteria - Function that returns true if an awaiter should be cancelled
169
+ * @returns {number} Number of awaiters cancelled
170
+ */
171
+ cancelByCriteria(testCriteria) {
172
+ let cancelled = 0;
173
+ for (const [id, awaiter] of this.awaiters) {
174
+ try {
175
+ if (testCriteria(awaiter)) {
176
+ clearTimeout(awaiter.timeoutId);
177
+ this.awaiters.delete(id);
178
+ awaiter.reject(new Error(`Awaiter ${id} cancelled by criteria`));
179
+ cancelled++;
180
+ }
181
+ } catch (error) {
182
+ // Test criteria threw an error - skip this awaiter
183
+ continue;
184
+ }
185
+ }
186
+ return cancelled;
187
+ }
188
+
99
189
  /**
100
190
  * Clear all awaiters (for cleanup)
101
191
  */
@@ -1,5 +1,25 @@
1
1
  import { AnyEvt as AnyEvtSchema } from "./schemas.js";
2
- import { setAssignment } from "../../state/assignment.js";
2
+ import { setAssignment, getAssignment } from "../../state/assignment.js";
3
+ import logger from "../../lib/logger.js";
4
+
5
+ /**
6
+ * Format milliseconds to human-readable hours:minutes
7
+ * @param {number} ms - Milliseconds
8
+ * @returns {string} Formatted string like "1h 30m" or "45m"
9
+ */
10
+ function formatLeaseDuration(ms) {
11
+ const totalMinutes = Math.floor(ms / 60000);
12
+ const hours = Math.floor(totalMinutes / 60);
13
+ const minutes = totalMinutes % 60;
14
+
15
+ if (hours > 0 && minutes > 0) {
16
+ return `${hours}h ${minutes}m`;
17
+ } else if (hours > 0) {
18
+ return `${hours}h`;
19
+ } else {
20
+ return `${minutes}m`;
21
+ }
22
+ }
3
23
 
4
24
  const registry = {
5
25
  async setup_required(e) {
@@ -12,7 +32,6 @@ const registry = {
12
32
  },
13
33
 
14
34
  async open_ack(e) {
15
- console.log(`🔍 open_ack handler called with requestId: ${e.requestId}`);
16
35
  // Normalize legacy format to canonical format
17
36
  let data = e.data;
18
37
 
@@ -32,34 +51,56 @@ const registry = {
32
51
  };
33
52
  }
34
53
 
54
+ // QPA-CLI-11: Store QuickPass info in assignment for vault UX messaging
55
+ // Suppress QP: enabled and Ack received messages - they'll be consolidated in final tunnel.active message
56
+ const quickpassSlug = data.quickpass?.slug || null;
57
+ if (quickpassSlug) {
58
+ logger.info("qp.enabled", { group: quickpassSlug });
59
+ }
60
+
35
61
  // Build relay URL
36
62
  const url = `${data.assignment.proto}://${data.assignment.fqdn}${data.assignment.path}`;
37
63
 
38
64
  // Store assignment in memory (never to disk)
39
65
  const leaseId = e.correlationId || data.leaseId || data.assignment?.leaseId || null;
40
- console.log('🔍 leaseId from ack:', leaseId);
66
+ logger.debug("open_ack.lease_id", { requestId: e.requestId, leaseId });
41
67
 
68
+ // Check if this is a refresh (existing assignment) or initial connection
69
+ const existingAssignment = getAssignment();
70
+ const isRefresh = existingAssignment !== null;
71
+
42
72
  setAssignment({
43
73
  requestId: e.requestId,
44
74
  relayId: data.relayId,
45
75
  relayUrl: url,
46
76
  jwt: data.assignment.jwt, // Stored in memory only
47
77
  leaseMs: data.leaseMs,
48
- leaseId
78
+ leaseId,
79
+ quickpassSlug // QPA-CLI-11: Store QuickPass slug for vault UX messaging
49
80
  });
50
81
 
51
- console.log(`🔍 Assignment stored for requestId: ${e.requestId}`);
82
+ logger.debug("open_ack.assignment_stored", { requestId: e.requestId, isRefresh, quickpassSlug });
52
83
 
53
- // Print concise success message (no JWT logging)
54
- process.stdout.write(
55
- `✅ Ack received — relay=${data.relayId} leaseMs=${data.leaseMs}\n`
56
- );
84
+ // QPA-CLI-11: Suppress all intermediate messages (QP: enabled, Ack received)
85
+ // These will be consolidated into the final vault UX sequence
57
86
  },
58
87
 
59
88
  async open_reject(e) {
60
89
  // Print rejection reason and keep process alive.
61
90
  const d = e.data;
62
91
  const reason = d.reason ? ` (${d.reason})` : "";
92
+
93
+ // QPA-04: Handle invalid_secgroup rejection
94
+ if (d.reason === 'invalid_secgroup' || d.reason === 'INVALID_SECGROUP') {
95
+ // Extract slug from requestId context or data if available
96
+ // Note: The slug was sent in the cmd/open payload, but we don't have direct access here
97
+ // The coordinator should include it in the rejection message, but for now we'll use a generic message
98
+ const slug = d.slug || d.secGroupSlug || 'unknown';
99
+ process.stderr.write(`QuickPass group "${slug}" not found. Re-run \`asyx tunnel\` with a valid group.\n`);
100
+ // Exit with code 1 before opening tunnel
101
+ process.exit(1);
102
+ }
103
+
63
104
  process.stdout.write(
64
105
  `❌ Connection rejected${reason}\n`
65
106
  );
@@ -14,7 +14,8 @@ import { AwaiterMap } from './awaiter-map.js';
14
14
 
15
15
  export class MessageIngress {
16
16
  constructor(options = {}) {
17
- this.awaiterMap = new AwaiterMap(options.maxAwaiters || 100);
17
+ // QPA-CLI-10: Pass logger to AwaiterMap for quiet mode
18
+ this.awaiterMap = new AwaiterMap(options.maxAwaiters || 100, options.logger || null);
18
19
  this.dispatcher = null;
19
20
  this.observability = options.observability || false;
20
21
  this.messageCounter = 0;
@@ -38,6 +39,15 @@ export class MessageIngress {
38
39
  return this.awaiterMap.register(criteria, timeoutMs);
39
40
  }
40
41
 
42
+ /**
43
+ * Cancel awaiters that match a test criteria
44
+ * @param {Function} testCriteria - Function that returns true if an awaiter should be cancelled
45
+ * @returns {number} Number of awaiters cancelled
46
+ */
47
+ cancelAwaitersByCriteria(testCriteria) {
48
+ return this.awaiterMap.cancelByCriteria(testCriteria);
49
+ }
50
+
41
51
  /**
42
52
  * Main ingress handler - processes all incoming MQTT messages
43
53
  * @param {Object} message - Raw MQTT message from transport
@@ -22,6 +22,7 @@ export function setAssignment(assignment) {
22
22
  jwt: assignment.jwt, // Stored in memory only
23
23
  leaseMs: assignment.leaseMs,
24
24
  leaseId: assignment.leaseId, // CLI-IMG-WSReconnect: Store leaseId for JWT refresh
25
+ quickpassSlug: assignment.quickpassSlug || null, // QPA-CLI-11: Store QuickPass slug for vault UX messaging
25
26
  timestamp: Date.now(),
26
27
  lastRefreshMs: undefined,
27
28
  lastRefreshIso: undefined,