asyx 0.0.2 → 0.1.1
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/LICENSE +67 -0
- package/README.md +125 -17
- package/SECURITY.md +40 -0
- package/bin/asyx.js +2 -0
- package/package.json +75 -18
- package/src/commands/.gitkeep +0 -0
- package/src/commands/mqtt-broker.js +56 -0
- package/src/commands/mqtt.js +164 -0
- package/src/commands/setup.js +137 -0
- package/src/commands/sts.js +73 -0
- package/src/commands/tunnel.js +540 -0
- package/src/lib/.gitkeep +0 -0
- package/src/lib/certs.js +25 -0
- package/src/lib/csr.js +185 -0
- package/src/lib/device.js +18 -0
- package/src/lib/fingerprint.js +115 -0
- package/src/lib/ids.js +5 -0
- package/src/lib/logger.js +58 -0
- package/src/lib/pairing.js +15 -0
- package/src/lib/shared-transport.js +15 -0
- package/src/main.js +57 -0
- package/src/mqtt/awaiter-map.js +157 -0
- package/src/mqtt/events/handlers.js +90 -0
- package/src/mqtt/events/index.js +14 -0
- package/src/mqtt/events/schemas.js +58 -0
- package/src/mqtt/ingress.js +172 -0
- package/src/state/assignment.js +156 -0
- package/src/tunnel/http-tunnel.js +1131 -0
- package/src/tunnel/ws-control.js +135 -0
- package/index.js +0 -13
package/src/lib/csr.js
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import fssync from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import nodeCrypto from 'node:crypto';
|
|
6
|
+
import { Crypto } from '@peculiar/webcrypto';
|
|
7
|
+
import { cryptoProvider, Pkcs10CertificateRequestGenerator } from '@peculiar/x509';
|
|
8
|
+
|
|
9
|
+
const crypto = new Crypto();
|
|
10
|
+
cryptoProvider.set(crypto); // Set provider before using generator
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Convert ArrayBuffer to PEM format
|
|
14
|
+
* @param {ArrayBuffer} arrayBuffer - The binary data
|
|
15
|
+
* @param {string} header - PEM header (e.g., 'PRIVATE KEY')
|
|
16
|
+
* @returns {string} PEM formatted string
|
|
17
|
+
*/
|
|
18
|
+
function bufferToPem(arrayBuffer, header) {
|
|
19
|
+
const base64 = Buffer.from(arrayBuffer).toString('base64');
|
|
20
|
+
const chunks = base64.match(/.{1,64}/g) || [];
|
|
21
|
+
const pem = [
|
|
22
|
+
`-----BEGIN ${header}-----`,
|
|
23
|
+
...chunks,
|
|
24
|
+
`-----END ${header}-----`
|
|
25
|
+
].join('\n');
|
|
26
|
+
return pem + '\n';
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Convert PEM string to ArrayBuffer
|
|
31
|
+
* @param {string} pem - PEM formatted string
|
|
32
|
+
* @returns {ArrayBuffer} Binary data
|
|
33
|
+
*/
|
|
34
|
+
function pemToBuffer(pem) {
|
|
35
|
+
const base64 = pem
|
|
36
|
+
.replace(/-----BEGIN [\s\S]+?-----/, '')
|
|
37
|
+
.replace(/-----END [\s\S]+?-----/, '')
|
|
38
|
+
.replace(/\s/g, '');
|
|
39
|
+
const buffer = Buffer.from(base64, 'base64');
|
|
40
|
+
return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function certsDirFor(clientId, baseDir) {
|
|
44
|
+
if (baseDir) {
|
|
45
|
+
return path.join(baseDir, 'certs', clientId);
|
|
46
|
+
}
|
|
47
|
+
const home = os.homedir();
|
|
48
|
+
return path.join(home, '.asyx', 'certs', clientId);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function ensureDir(p) {
|
|
52
|
+
await fs.mkdir(p, { recursive: true, mode: 0o700 });
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async function chmodIfExists(p, mode) {
|
|
56
|
+
try {
|
|
57
|
+
await fs.chmod(p, mode);
|
|
58
|
+
} catch {
|
|
59
|
+
// Ignore errors (file might not exist)
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Import private key from PEM file and extract public key
|
|
65
|
+
* @param {ArrayBuffer} pkcs8Bytes - PKCS8 formatted key bytes
|
|
66
|
+
* @returns {Promise<CryptoKeyPair>} Key pair with private and public keys
|
|
67
|
+
*/
|
|
68
|
+
async function importPrivateKey(pkcs8Bytes) {
|
|
69
|
+
const alg = {
|
|
70
|
+
name: 'RSASSA-PKCS1-v1_5',
|
|
71
|
+
modulusLength: 2048,
|
|
72
|
+
publicExponent: new Uint8Array([1, 0, 1]),
|
|
73
|
+
hash: 'SHA-256'
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
// Import private key (can be used for both sign and verify operations)
|
|
77
|
+
const privateKey = await crypto.subtle.importKey(
|
|
78
|
+
'pkcs8',
|
|
79
|
+
pkcs8Bytes,
|
|
80
|
+
alg,
|
|
81
|
+
true,
|
|
82
|
+
['sign']
|
|
83
|
+
);
|
|
84
|
+
|
|
85
|
+
// Export as JWK to extract public key components
|
|
86
|
+
const jwk = await crypto.subtle.exportKey('jwk', privateKey);
|
|
87
|
+
|
|
88
|
+
// Create public key JWK by removing private components
|
|
89
|
+
const publicJwk = {
|
|
90
|
+
kty: jwk.kty,
|
|
91
|
+
n: jwk.n,
|
|
92
|
+
e: jwk.e,
|
|
93
|
+
alg: jwk.alg,
|
|
94
|
+
key_ops: ['verify']
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
// Import as public key
|
|
98
|
+
const publicKey = await crypto.subtle.importKey(
|
|
99
|
+
'jwk',
|
|
100
|
+
publicJwk,
|
|
101
|
+
alg,
|
|
102
|
+
true,
|
|
103
|
+
['verify']
|
|
104
|
+
);
|
|
105
|
+
|
|
106
|
+
return { privateKey, publicKey };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export async function ensureKeyAndCsr(clientId, options = {}) {
|
|
110
|
+
const { baseDir } = options;
|
|
111
|
+
const dir = certsDirFor(clientId, baseDir);
|
|
112
|
+
await ensureDir(dir);
|
|
113
|
+
const keyPath = path.join(dir, 'private.pem.key');
|
|
114
|
+
const csrPath = path.join(dir, 'device.csr.pem');
|
|
115
|
+
|
|
116
|
+
const alg = {
|
|
117
|
+
name: 'RSASSA-PKCS1-v1_5',
|
|
118
|
+
modulusLength: 2048,
|
|
119
|
+
publicExponent: new Uint8Array([1, 0, 1]),
|
|
120
|
+
hash: 'SHA-256'
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
let keyPair;
|
|
124
|
+
|
|
125
|
+
// Generate key if missing, otherwise import existing key
|
|
126
|
+
if (!fssync.existsSync(keyPath)) {
|
|
127
|
+
// Generate new key pair
|
|
128
|
+
keyPair = await crypto.subtle.generateKey(alg, true, ['sign', 'verify']);
|
|
129
|
+
|
|
130
|
+
// Export private key in PKCS8 format
|
|
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 });
|
|
136
|
+
} else {
|
|
137
|
+
// Import existing private key
|
|
138
|
+
const keyPem = await fs.readFile(keyPath, 'utf8');
|
|
139
|
+
|
|
140
|
+
// Check if key is PKCS#1 (RSA PRIVATE KEY) or PKCS#8 (PRIVATE KEY)
|
|
141
|
+
const isPkcs1 = keyPem.includes('BEGIN RSA PRIVATE KEY');
|
|
142
|
+
|
|
143
|
+
let pkcs8Bytes;
|
|
144
|
+
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
|
|
147
|
+
const nodePrivateKey = nodeCrypto.createPrivateKey({
|
|
148
|
+
key: keyPem,
|
|
149
|
+
format: 'pem'
|
|
150
|
+
});
|
|
151
|
+
// Export in PKCS#8 format
|
|
152
|
+
const pkcs8Pem = nodePrivateKey.export({
|
|
153
|
+
type: 'pkcs8',
|
|
154
|
+
format: 'pem'
|
|
155
|
+
});
|
|
156
|
+
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 });
|
|
159
|
+
} else {
|
|
160
|
+
// Already PKCS#8 format
|
|
161
|
+
pkcs8Bytes = pemToBuffer(keyPem);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
keyPair = await importPrivateKey(pkcs8Bytes);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// Build CSR using static factory method
|
|
168
|
+
const csr = await Pkcs10CertificateRequestGenerator.create({
|
|
169
|
+
name: `CN=${clientId}, O=Asyx`,
|
|
170
|
+
keys: keyPair, // { publicKey, privateKey }
|
|
171
|
+
signingAlgorithm: alg // same object used for generateKey
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
const csrPem = csr.toString('pem');
|
|
175
|
+
|
|
176
|
+
// Ensure CSR is properly formatted
|
|
177
|
+
if (!/^-----BEGIN CERTIFICATE REQUEST-----[\s\S]*-----END CERTIFICATE REQUEST-----\s*$/.test(csrPem)) {
|
|
178
|
+
throw new Error('csr_generation_failed');
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// Write CSR file
|
|
182
|
+
await fs.writeFile(csrPath, csrPem, { encoding: 'utf8' });
|
|
183
|
+
|
|
184
|
+
return { keyPath, csrPath, csrPem, dir };
|
|
185
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import crypto from "node:crypto";
|
|
5
|
+
|
|
6
|
+
const DIR = join(homedir(), ".asyx");
|
|
7
|
+
const FILE = join(DIR, "device.json");
|
|
8
|
+
|
|
9
|
+
export function loadOrCreateClientId() {
|
|
10
|
+
if (!existsSync(DIR)) mkdirSync(DIR, { recursive: true });
|
|
11
|
+
if (existsSync(FILE)) {
|
|
12
|
+
const raw = JSON.parse(readFileSync(FILE, "utf8"));
|
|
13
|
+
if (raw?.clientId) return raw.clientId;
|
|
14
|
+
}
|
|
15
|
+
const clientId = "cli_" + crypto.randomUUID().replace(/-/g, "").slice(0, 12).toUpperCase();
|
|
16
|
+
writeFileSync(FILE, JSON.stringify({ clientId }, null, 2));
|
|
17
|
+
return clientId;
|
|
18
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CP-3C: Safe Hardware Fingerprint Collection (macOS Privacy Compliant)
|
|
3
|
+
*
|
|
4
|
+
* Privacy-preserving hardware fingerprinting that avoids macOS privacy warnings.
|
|
5
|
+
* Uses only safe fields that don't trigger system permission requests.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { getFingerprintingInfo } from 'hw-fingerprint';
|
|
9
|
+
import { createHash } from 'node:crypto';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Safe hardware attributes that don't trigger macOS privacy warnings.
|
|
13
|
+
* Based on analysis of hw-fingerprint library behavior.
|
|
14
|
+
*/
|
|
15
|
+
const SAFE_FIELDS = [
|
|
16
|
+
'platform', // OS platform (darwin, linux, win32)
|
|
17
|
+
'arch', // CPU architecture (arm64, x64)
|
|
18
|
+
'cores', // Number of CPU cores
|
|
19
|
+
'manufacturer', // Hardware manufacturer
|
|
20
|
+
'vendor', // System vendor
|
|
21
|
+
'model' // Hardware model (Mac16,11, etc.)
|
|
22
|
+
];
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Collect safe hardware fingerprint using only non-sensitive fields.
|
|
26
|
+
* Returns canonical JSON string with stable ordering.
|
|
27
|
+
*/
|
|
28
|
+
async function collectSafeHardwareFingerprint() {
|
|
29
|
+
try {
|
|
30
|
+
const fingerprint = await getFingerprintingInfo();
|
|
31
|
+
|
|
32
|
+
// Extract only safe fields, dropping empties
|
|
33
|
+
const safeData = {};
|
|
34
|
+
|
|
35
|
+
for (const field of SAFE_FIELDS) {
|
|
36
|
+
const value = fingerprint[field];
|
|
37
|
+
if (value !== undefined && value !== null && value !== '') {
|
|
38
|
+
safeData[field] = value;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Create canonical JSON with stable ordering
|
|
43
|
+
const canonical = {
|
|
44
|
+
version: 'fpv1-safe',
|
|
45
|
+
fields: safeData
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
return JSON.stringify(canonical, Object.keys(canonical).sort());
|
|
49
|
+
} catch (error) {
|
|
50
|
+
// Return empty canonical structure on failure
|
|
51
|
+
return JSON.stringify({ version: 'fpv1-safe', fields: {} }, Object.keys({ version: 'fpv1-safe', fields: {} }).sort());
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Hash fingerprint using SHA-256 with public salt.
|
|
57
|
+
* Returns hex string.
|
|
58
|
+
*/
|
|
59
|
+
function hashFingerprint(canonical, clientId) {
|
|
60
|
+
const publicSalt = `asyx|${clientId}`;
|
|
61
|
+
const preimage = publicSalt + canonical;
|
|
62
|
+
|
|
63
|
+
return createHash('sha256')
|
|
64
|
+
.update(preimage, 'utf8')
|
|
65
|
+
.digest('hex');
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Get safe hardware fingerprint hash with version metadata.
|
|
70
|
+
* Returns structured object for cmd/open payload.
|
|
71
|
+
*
|
|
72
|
+
* This version avoids macOS privacy warnings by using only safe fields.
|
|
73
|
+
*/
|
|
74
|
+
export async function getFpHash(clientId) {
|
|
75
|
+
try {
|
|
76
|
+
const canonical = await collectSafeHardwareFingerprint();
|
|
77
|
+
const clientHash = hashFingerprint(canonical, clientId);
|
|
78
|
+
|
|
79
|
+
return {
|
|
80
|
+
fpv: '1-safe',
|
|
81
|
+
fph: clientHash,
|
|
82
|
+
alg: 'sha256',
|
|
83
|
+
lib: 'hw-fingerprint@3.2.0-safe'
|
|
84
|
+
};
|
|
85
|
+
} catch (error) {
|
|
86
|
+
// Return unavailable fingerprint on any failure
|
|
87
|
+
return {
|
|
88
|
+
fpv: '1-safe',
|
|
89
|
+
fph: 'unavailable',
|
|
90
|
+
alg: 'sha256',
|
|
91
|
+
lib: 'hw-fingerprint@3.2.0-safe'
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Test function to verify safe fingerprinting works without warnings
|
|
98
|
+
*/
|
|
99
|
+
export async function testSafeFingerprint() {
|
|
100
|
+
console.log('🧪 Testing safe hardware fingerprint...');
|
|
101
|
+
|
|
102
|
+
try {
|
|
103
|
+
const result = await getFpHash('test-client');
|
|
104
|
+
console.log('✅ Safe fingerprint result:', JSON.stringify(result, null, 2));
|
|
105
|
+
|
|
106
|
+
// Test deterministic behavior
|
|
107
|
+
const result2 = await getFpHash('test-client');
|
|
108
|
+
console.log('✅ Deterministic test - same result:', result.fph === result2.fph);
|
|
109
|
+
|
|
110
|
+
return result;
|
|
111
|
+
} catch (error) {
|
|
112
|
+
console.error('❌ Safe fingerprint test failed:', error.message);
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
}
|
package/src/lib/ids.js
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
function isoNow() {
|
|
2
|
+
return new Date().toISOString();
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
// Parse env log level once at module load
|
|
6
|
+
const LEVEL_ORDER = { error: 40, warn: 30, info: 20, debug: 10 };
|
|
7
|
+
|
|
8
|
+
function normalizeLevel(value) {
|
|
9
|
+
const v = String(value || '').trim().toLowerCase();
|
|
10
|
+
if (v in LEVEL_ORDER) return v;
|
|
11
|
+
return 'info';
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const ENV_LEVEL = normalizeLevel(process.env.ASYX_LOG_LEVEL);
|
|
15
|
+
|
|
16
|
+
function shouldEmit(level) {
|
|
17
|
+
const desired = LEVEL_ORDER[ENV_LEVEL] ?? LEVEL_ORDER.info;
|
|
18
|
+
const actual = LEVEL_ORDER[normalizeLevel(level)] ?? LEVEL_ORDER.info;
|
|
19
|
+
return actual >= desired;
|
|
20
|
+
}
|
|
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)) return;
|
|
33
|
+
// Route by level to preserve severity semantics if needed
|
|
34
|
+
if (level === 'error') {
|
|
35
|
+
console.error(line);
|
|
36
|
+
} else if (level === 'warn') {
|
|
37
|
+
console.warn(line);
|
|
38
|
+
} else if (level === 'debug') {
|
|
39
|
+
console.debug(line);
|
|
40
|
+
} else {
|
|
41
|
+
console.log(line);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function log(level, msg, fields = {}) {
|
|
46
|
+
emit(level, msg, fields);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export const logger = {
|
|
50
|
+
debug: (msg, fields) => emit('debug', msg, fields),
|
|
51
|
+
info: (msg, fields) => emit('info', msg, fields),
|
|
52
|
+
warn: (msg, fields) => emit('warn', msg, fields),
|
|
53
|
+
error: (msg, fields) => emit('error', msg, fields),
|
|
54
|
+
log,
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
export default logger;
|
|
58
|
+
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import open from "open";
|
|
2
|
+
import chalk from "chalk";
|
|
3
|
+
|
|
4
|
+
export async function startPairing(deviceCode) {
|
|
5
|
+
const claimUrl = `https://www.asyx.ai/console/tunnel?code=${encodeURIComponent(deviceCode)}`;
|
|
6
|
+
console.log(chalk.gray(`Preparing browser for pairing...`));
|
|
7
|
+
|
|
8
|
+
try {
|
|
9
|
+
await open(claimUrl);
|
|
10
|
+
console.log(chalk.green("✅ Opening your default browser to complete pairing..."));
|
|
11
|
+
} catch (err) {
|
|
12
|
+
console.log(chalk.yellow("⚠️ Could not open your browser automatically."));
|
|
13
|
+
console.log(`Please visit:\n${chalk.cyan(claimUrl)}`);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { MemoryTransport } from "@asyx/mqtt-client";
|
|
2
|
+
|
|
3
|
+
// Simple singleton pattern for shared transport in dev mode
|
|
4
|
+
let sharedTransport = null;
|
|
5
|
+
|
|
6
|
+
export function getSharedTransport() {
|
|
7
|
+
if (!sharedTransport) {
|
|
8
|
+
sharedTransport = new MemoryTransport();
|
|
9
|
+
}
|
|
10
|
+
return sharedTransport;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function resetSharedTransport() {
|
|
14
|
+
sharedTransport = null;
|
|
15
|
+
}
|
package/src/main.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire } from 'node:module';
|
|
3
|
+
import cmdSetup from "./commands/setup.js";
|
|
4
|
+
import cmdSts from "./commands/sts.js";
|
|
5
|
+
|
|
6
|
+
const require = createRequire(import.meta.url);
|
|
7
|
+
const pkg = require("../package.json");
|
|
8
|
+
|
|
9
|
+
export const CLI_VERSION = pkg.version;
|
|
10
|
+
export const CLI_DESCRIPTION = pkg.description;
|
|
11
|
+
|
|
12
|
+
// Unified error handling
|
|
13
|
+
process.on('unhandledRejection', (err) => {
|
|
14
|
+
console.error('Unexpected error:', err?.message ?? err);
|
|
15
|
+
process.exit(1);
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
const handleFailure = (label) => (err) => {
|
|
19
|
+
console.error(`${label} failed:`, err?.message ?? err);
|
|
20
|
+
process.exit(1);
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
async function run() {
|
|
24
|
+
const cmd = process.argv[2];
|
|
25
|
+
if (!cmd || cmd === "help") {
|
|
26
|
+
console.log(`asyx <command>
|
|
27
|
+
|
|
28
|
+
Commands:
|
|
29
|
+
help Show this help
|
|
30
|
+
setup Set up this client by provisioning its device certificate
|
|
31
|
+
mqtt MQTT utilities (dev)
|
|
32
|
+
tunnel Connect to control plane (CP-1)
|
|
33
|
+
`);
|
|
34
|
+
process.exit(0);
|
|
35
|
+
}
|
|
36
|
+
if (cmd === "--version" || cmd === "-v") {
|
|
37
|
+
console.log(`asyx ${CLI_VERSION}`);
|
|
38
|
+
process.exit(0);
|
|
39
|
+
}
|
|
40
|
+
if (cmd === "setup") {
|
|
41
|
+
cmdSetup(process.argv.slice(2)).catch(handleFailure('Setup'));
|
|
42
|
+
} else if (cmd === "sts") {
|
|
43
|
+
cmdSts(process.argv.slice(2)).catch(handleFailure('STS'));
|
|
44
|
+
} else if (cmd === "mqtt") {
|
|
45
|
+
// Import and execute mqtt command
|
|
46
|
+
const { default: mqttCommand } = await import("./commands/mqtt.js");
|
|
47
|
+
mqttCommand().catch(handleFailure('MQTT'));
|
|
48
|
+
} else if (cmd === "tunnel") {
|
|
49
|
+
const { default: tunnelCommand } = await import("./commands/tunnel.js");
|
|
50
|
+
tunnelCommand(process.argv.slice(3)).catch(handleFailure('Tunnel'));
|
|
51
|
+
} else {
|
|
52
|
+
console.log(`Unknown command: ${cmd}`);
|
|
53
|
+
process.exit(1);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
run();
|
|
@@ -0,0 +1,157 @@
|
|
|
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
|
+
|
|
9
|
+
export class AwaiterMap {
|
|
10
|
+
constructor(maxSize = 100) {
|
|
11
|
+
this.maxSize = maxSize;
|
|
12
|
+
this.awaiters = new Map();
|
|
13
|
+
this.nextId = 1;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Register an awaiter that will be resolved when a message matches the criteria
|
|
18
|
+
* @param {Function} criteria - Function that returns true if message matches
|
|
19
|
+
* @param {number} timeoutMs - Timeout in milliseconds
|
|
20
|
+
* @returns {Promise} Promise that resolves with the matching message
|
|
21
|
+
*/
|
|
22
|
+
register(criteria, timeoutMs = 5000) {
|
|
23
|
+
if (this.awaiters.size >= this.maxSize) {
|
|
24
|
+
throw new Error(`AwaiterMap is at capacity (${this.maxSize}). Cannot register more awaiters.`);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const id = this.nextId++;
|
|
28
|
+
const awaiter = {
|
|
29
|
+
id,
|
|
30
|
+
criteria,
|
|
31
|
+
timeoutMs,
|
|
32
|
+
resolve: null,
|
|
33
|
+
reject: null,
|
|
34
|
+
timeoutId: null,
|
|
35
|
+
createdAt: Date.now()
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const promise = new Promise((resolve, reject) => {
|
|
39
|
+
awaiter.resolve = resolve;
|
|
40
|
+
awaiter.reject = reject;
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
// Set up timeout
|
|
44
|
+
awaiter.timeoutId = setTimeout(() => {
|
|
45
|
+
this.awaiters.delete(id);
|
|
46
|
+
awaiter.reject(new Error(`Awaiter ${id} timed out after ${timeoutMs}ms`));
|
|
47
|
+
}, timeoutMs);
|
|
48
|
+
|
|
49
|
+
this.awaiters.set(id, awaiter);
|
|
50
|
+
return promise;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Process an incoming message against all registered awaiters
|
|
55
|
+
* @param {Object} message - Message object with topic and payload
|
|
56
|
+
* @returns {boolean} True if any awaiter was resolved
|
|
57
|
+
*/
|
|
58
|
+
processMessage(message) {
|
|
59
|
+
let resolved = false;
|
|
60
|
+
|
|
61
|
+
for (const [id, awaiter] of this.awaiters) {
|
|
62
|
+
try {
|
|
63
|
+
if (awaiter.criteria(message)) {
|
|
64
|
+
// Clear timeout and resolve
|
|
65
|
+
clearTimeout(awaiter.timeoutId);
|
|
66
|
+
this.awaiters.delete(id);
|
|
67
|
+
awaiter.resolve(message);
|
|
68
|
+
resolved = true;
|
|
69
|
+
}
|
|
70
|
+
} catch (error) {
|
|
71
|
+
// Criteria function threw an error - reject and clean up
|
|
72
|
+
clearTimeout(awaiter.timeoutId);
|
|
73
|
+
this.awaiters.delete(id);
|
|
74
|
+
awaiter.reject(error);
|
|
75
|
+
resolved = true;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
return resolved;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Get current statistics about the awaiter map
|
|
84
|
+
* @returns {Object} Statistics object
|
|
85
|
+
*/
|
|
86
|
+
getStats() {
|
|
87
|
+
const now = Date.now();
|
|
88
|
+
const ages = Array.from(this.awaiters.values()).map(a => now - a.createdAt);
|
|
89
|
+
|
|
90
|
+
return {
|
|
91
|
+
count: this.awaiters.size,
|
|
92
|
+
maxSize: this.maxSize,
|
|
93
|
+
utilization: this.awaiters.size / this.maxSize,
|
|
94
|
+
oldestAge: ages.length > 0 ? Math.max(...ages) : 0,
|
|
95
|
+
averageAge: ages.length > 0 ? ages.reduce((a, b) => a + b, 0) / ages.length : 0
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Clear all awaiters (for cleanup)
|
|
101
|
+
*/
|
|
102
|
+
clear() {
|
|
103
|
+
for (const [id, awaiter] of this.awaiters) {
|
|
104
|
+
clearTimeout(awaiter.timeoutId);
|
|
105
|
+
awaiter.reject(new Error(`AwaiterMap cleared - awaiter ${id} cancelled`));
|
|
106
|
+
}
|
|
107
|
+
this.awaiters.clear();
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Create a criteria function for session ID matching (backward compatibility)
|
|
112
|
+
* @param {string} sessionId - Session ID to match
|
|
113
|
+
* @param {string} expectedTopic - Expected topic pattern
|
|
114
|
+
* @returns {Function} Criteria function
|
|
115
|
+
*/
|
|
116
|
+
static createSessionIdCriteria(sessionId, expectedTopic) {
|
|
117
|
+
return (message) => {
|
|
118
|
+
if (message.topic !== expectedTopic) {
|
|
119
|
+
return false;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
try {
|
|
123
|
+
const raw = message.payload;
|
|
124
|
+
const payload = typeof raw === 'object' && raw !== null && !Buffer.isBuffer(raw)
|
|
125
|
+
? raw
|
|
126
|
+
: JSON.parse(Buffer.isBuffer(raw) ? raw.toString() : String(raw));
|
|
127
|
+
return payload.sessionId === sessionId;
|
|
128
|
+
} catch {
|
|
129
|
+
return false;
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Create a criteria function for correlation ID matching (future use)
|
|
136
|
+
* @param {string} correlationId - Correlation ID to match
|
|
137
|
+
* @param {string} expectedTopic - Expected topic pattern
|
|
138
|
+
* @returns {Function} Criteria function
|
|
139
|
+
*/
|
|
140
|
+
static createCorrelationIdCriteria(correlationId, expectedTopic) {
|
|
141
|
+
return (message) => {
|
|
142
|
+
if (message.topic !== expectedTopic) {
|
|
143
|
+
return false;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
try {
|
|
147
|
+
const raw = message.payload;
|
|
148
|
+
const payload = typeof raw === 'object' && raw !== null && !Buffer.isBuffer(raw)
|
|
149
|
+
? raw
|
|
150
|
+
: JSON.parse(Buffer.isBuffer(raw) ? raw.toString() : String(raw));
|
|
151
|
+
return payload.correlationId === correlationId;
|
|
152
|
+
} catch {
|
|
153
|
+
return false;
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
}
|