asyx 0.0.2 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +67 -0
- package/README.md +125 -17
- package/SECURITY.md +40 -0
- package/bin/asyx.js +2 -0
- package/package.json +47 -17
- 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 +45 -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/logger.level.spec.js +81 -0
- package/src/lib/logger.test.js +42 -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/__test_utils__/testUtils.js +76 -0
- package/src/tunnel/__tests__/jwt-refresh.spec.js +948 -0
- package/src/tunnel/__tests__/ws-control.spec.js +164 -0
- package/src/tunnel/http-tunnel.js +1131 -0
- package/src/tunnel/ws-control.js +144 -0
- package/index.js +0 -13
|
@@ -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,81 @@
|
|
|
1
|
+
import { jest, describe, test, expect, beforeEach, afterEach } from '@jest/globals';
|
|
2
|
+
|
|
3
|
+
async function loadLogger() {
|
|
4
|
+
jest.resetModules();
|
|
5
|
+
const mod = await import('./logger.js');
|
|
6
|
+
return mod.logger;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
describe('logger level gating via ASYX_LOG_LEVEL', () => {
|
|
10
|
+
let spyLog, spyWarn, spyError, spyDebug;
|
|
11
|
+
const origEnv = process.env.ASYX_LOG_LEVEL;
|
|
12
|
+
|
|
13
|
+
beforeEach(() => {
|
|
14
|
+
spyLog = jest.spyOn(console, 'log').mockImplementation(() => {});
|
|
15
|
+
spyWarn = jest.spyOn(console, 'warn').mockImplementation(() => {});
|
|
16
|
+
spyError = jest.spyOn(console, 'error').mockImplementation(() => {});
|
|
17
|
+
spyDebug = jest.spyOn(console, 'debug').mockImplementation(() => {});
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
afterEach(() => {
|
|
21
|
+
jest.restoreAllMocks();
|
|
22
|
+
process.env.ASYX_LOG_LEVEL = origEnv;
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
test('default (unset) => info; debug suppressed', async () => {
|
|
26
|
+
delete process.env.ASYX_LOG_LEVEL;
|
|
27
|
+
const logger = await loadLogger();
|
|
28
|
+
logger.debug('d');
|
|
29
|
+
logger.info('i');
|
|
30
|
+
expect(spyDebug).not.toHaveBeenCalled();
|
|
31
|
+
expect(spyLog).toHaveBeenCalledTimes(1);
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
test('invalid value falls back to info', async () => {
|
|
35
|
+
process.env.ASYX_LOG_LEVEL = 'nope';
|
|
36
|
+
const logger = await loadLogger();
|
|
37
|
+
logger.debug('d');
|
|
38
|
+
logger.info('i');
|
|
39
|
+
expect(spyDebug).not.toHaveBeenCalled();
|
|
40
|
+
expect(spyLog).toHaveBeenCalledTimes(1);
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
test('warn level: info suppressed, warn+ visible', async () => {
|
|
44
|
+
process.env.ASYX_LOG_LEVEL = 'WaRn';
|
|
45
|
+
const logger = await loadLogger();
|
|
46
|
+
logger.info('i');
|
|
47
|
+
logger.warn('w');
|
|
48
|
+
logger.error('e');
|
|
49
|
+
expect(spyLog).not.toHaveBeenCalled();
|
|
50
|
+
expect(spyWarn).toHaveBeenCalledTimes(1);
|
|
51
|
+
expect(spyError).toHaveBeenCalledTimes(1);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
test('error level: only errors visible', async () => {
|
|
55
|
+
process.env.ASYX_LOG_LEVEL = 'error';
|
|
56
|
+
const logger = await loadLogger();
|
|
57
|
+
logger.debug('d');
|
|
58
|
+
logger.info('i');
|
|
59
|
+
logger.warn('w');
|
|
60
|
+
logger.error('e');
|
|
61
|
+
expect(spyDebug).not.toHaveBeenCalled();
|
|
62
|
+
expect(spyLog).not.toHaveBeenCalled();
|
|
63
|
+
expect(spyWarn).not.toHaveBeenCalled();
|
|
64
|
+
expect(spyError).toHaveBeenCalledTimes(1);
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
test('debug level: all visible', async () => {
|
|
68
|
+
process.env.ASYX_LOG_LEVEL = 'debug';
|
|
69
|
+
const logger = await loadLogger();
|
|
70
|
+
logger.debug('d');
|
|
71
|
+
logger.info('i');
|
|
72
|
+
logger.warn('w');
|
|
73
|
+
logger.error('e');
|
|
74
|
+
expect(spyDebug).toHaveBeenCalledTimes(1);
|
|
75
|
+
expect(spyLog).toHaveBeenCalledTimes(1);
|
|
76
|
+
expect(spyWarn).toHaveBeenCalledTimes(1);
|
|
77
|
+
expect(spyError).toHaveBeenCalledTimes(1);
|
|
78
|
+
});
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { jest, describe, test, expect, beforeEach, afterEach } from '@jest/globals';
|
|
2
|
+
import { logger } from './logger.js';
|
|
3
|
+
|
|
4
|
+
describe('logger', () => {
|
|
5
|
+
let spyLog, spyWarn, spyError, spyDebug;
|
|
6
|
+
beforeEach(() => {
|
|
7
|
+
spyLog = jest.spyOn(console, 'log').mockImplementation(() => {});
|
|
8
|
+
spyWarn = jest.spyOn(console, 'warn').mockImplementation(() => {});
|
|
9
|
+
spyError = jest.spyOn(console, 'error').mockImplementation(() => {});
|
|
10
|
+
spyDebug = jest.spyOn(console, 'debug').mockImplementation(() => {});
|
|
11
|
+
});
|
|
12
|
+
afterEach(() => {
|
|
13
|
+
jest.restoreAllMocks();
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
test('info emits single-line JSON with required keys', () => {
|
|
17
|
+
logger.info('mqtt.connect', { clientId: 'cli', retryCount: 0 });
|
|
18
|
+
expect(spyLog).toHaveBeenCalledTimes(1);
|
|
19
|
+
const [line] = spyLog.mock.calls[0];
|
|
20
|
+
expect(typeof line).toBe('string');
|
|
21
|
+
expect(line.includes('\n')).toBe(false);
|
|
22
|
+
const parsed = JSON.parse(line);
|
|
23
|
+
expect(parsed).toHaveProperty('ts');
|
|
24
|
+
expect(parsed).toHaveProperty('lvl', 'info');
|
|
25
|
+
expect(parsed).toHaveProperty('msg', 'mqtt.connect');
|
|
26
|
+
expect(parsed).toHaveProperty('fields');
|
|
27
|
+
expect(parsed.fields).toMatchObject({ clientId: 'cli', retryCount: 0 });
|
|
28
|
+
// ISO timestamp
|
|
29
|
+
expect(() => new Date(parsed.ts)).not.toThrow();
|
|
30
|
+
expect(Number.isNaN(Date.parse(parsed.ts))).toBe(false);
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
test('warn/error route to respective consoles (debug may be gated)', () => {
|
|
34
|
+
logger.warn('warned');
|
|
35
|
+
logger.error('failed');
|
|
36
|
+
logger.debug('trace');
|
|
37
|
+
expect(spyWarn).toHaveBeenCalledTimes(1);
|
|
38
|
+
expect(spyError).toHaveBeenCalledTimes(1);
|
|
39
|
+
// debug emission is covered in logger.level.spec.js
|
|
40
|
+
});
|
|
41
|
+
});
|
|
42
|
+
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { AnyEvt as AnyEvtSchema } from "./schemas.js";
|
|
2
|
+
import { setAssignment } from "../../state/assignment.js";
|
|
3
|
+
|
|
4
|
+
const registry = {
|
|
5
|
+
async setup_required(e) {
|
|
6
|
+
// Minimal user-facing message; CLI should exit(2)
|
|
7
|
+
// Do not add logs; leave control to caller via thrown Error with code.
|
|
8
|
+
const reason = e.data?.reason ? ` (${e.data.reason})` : "";
|
|
9
|
+
const err = new Error(`Please run "asyx setup"${reason}`);
|
|
10
|
+
err.code = "SETUP_REQUIRED";
|
|
11
|
+
throw err;
|
|
12
|
+
},
|
|
13
|
+
|
|
14
|
+
async open_ack(e) {
|
|
15
|
+
console.log(`🔍 open_ack handler called with requestId: ${e.requestId}`);
|
|
16
|
+
// Normalize legacy format to canonical format
|
|
17
|
+
let data = e.data;
|
|
18
|
+
|
|
19
|
+
// Legacy format: { data: { jwt, relayId, leaseMs } }
|
|
20
|
+
// Canonical format: { data: { relayId, leaseMs, assignment: { jwt, fqdn, proto, path, ... } } }
|
|
21
|
+
if (data.jwt && !data.assignment) {
|
|
22
|
+
// Transform legacy to canonical
|
|
23
|
+
data = {
|
|
24
|
+
relayId: data.relayId,
|
|
25
|
+
leaseMs: data.leaseMs,
|
|
26
|
+
assignment: {
|
|
27
|
+
jwt: data.jwt,
|
|
28
|
+
fqdn: 'relay.customer.example', // Default fallback
|
|
29
|
+
proto: 'wss',
|
|
30
|
+
path: '/agent'
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Build relay URL
|
|
36
|
+
const url = `${data.assignment.proto}://${data.assignment.fqdn}${data.assignment.path}`;
|
|
37
|
+
|
|
38
|
+
// Store assignment in memory (never to disk)
|
|
39
|
+
const leaseId = e.correlationId || data.leaseId || data.assignment?.leaseId || null;
|
|
40
|
+
console.log('🔍 leaseId from ack:', leaseId);
|
|
41
|
+
|
|
42
|
+
setAssignment({
|
|
43
|
+
requestId: e.requestId,
|
|
44
|
+
relayId: data.relayId,
|
|
45
|
+
relayUrl: url,
|
|
46
|
+
jwt: data.assignment.jwt, // Stored in memory only
|
|
47
|
+
leaseMs: data.leaseMs,
|
|
48
|
+
leaseId
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
console.log(`🔍 Assignment stored for requestId: ${e.requestId}`);
|
|
52
|
+
|
|
53
|
+
// Print concise success message (no JWT logging)
|
|
54
|
+
process.stdout.write(
|
|
55
|
+
`✅ Ack received — relay=${data.relayId} leaseMs=${data.leaseMs}\n`
|
|
56
|
+
);
|
|
57
|
+
},
|
|
58
|
+
|
|
59
|
+
async open_reject(e) {
|
|
60
|
+
// Print rejection reason and keep process alive.
|
|
61
|
+
const d = e.data;
|
|
62
|
+
const reason = d.reason ? ` (${d.reason})` : "";
|
|
63
|
+
process.stdout.write(
|
|
64
|
+
`❌ Connection rejected${reason}\n`
|
|
65
|
+
);
|
|
66
|
+
},
|
|
67
|
+
|
|
68
|
+
async error(e) {
|
|
69
|
+
const d = e.data || {};
|
|
70
|
+
const err = new Error(d.msg || "Command failed");
|
|
71
|
+
err.code = `ERROR_${String(d.code || "UNKNOWN").toUpperCase()}`;
|
|
72
|
+
throw err;
|
|
73
|
+
},
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
export function getHandler(type) {
|
|
77
|
+
return registry[type];
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// Safe parse helper the caller can reuse if needed
|
|
81
|
+
export function parseAny(raw) {
|
|
82
|
+
try {
|
|
83
|
+
const txt = typeof raw === "string" ? raw : new TextDecoder().decode(raw);
|
|
84
|
+
const json = JSON.parse(txt);
|
|
85
|
+
const parsed = AnyEvtSchema.safeParse(json);
|
|
86
|
+
return parsed.success ? parsed.data : null;
|
|
87
|
+
} catch (e) {
|
|
88
|
+
return null;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { parseAny, getHandler } from "./handlers.js";
|
|
2
|
+
|
|
3
|
+
export async function dispatch(parsedMessage) {
|
|
4
|
+
// Extract the parsed payload from the message object
|
|
5
|
+
const payload = parsedMessage.payload;
|
|
6
|
+
if (!payload) return; // No payload — ignore
|
|
7
|
+
|
|
8
|
+
// The payload is already parsed JSON, so we can use it directly
|
|
9
|
+
const evt = payload;
|
|
10
|
+
if (!evt.type) return; // No type — ignore
|
|
11
|
+
const handler = getHandler(evt.type);
|
|
12
|
+
if (!handler) return; // Unknown type — ignore
|
|
13
|
+
return handler(evt);
|
|
14
|
+
}
|