asyx 0.1.0 → 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "asyx",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Asyx Command Line Interface",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -20,7 +20,7 @@
20
20
  "relay"
21
21
  ],
22
22
  "bin": {
23
- "asyx": "bin/asyx.js"
23
+ "asyx": "./bin/asyx.js"
24
24
  },
25
25
  "engines": {
26
26
  "node": ">=18.17"
@@ -29,7 +29,30 @@
29
29
  "private": false,
30
30
  "files": [
31
31
  "bin/",
32
- "src/",
32
+ "src/commands/.gitkeep",
33
+ "src/commands/mqtt-broker.js",
34
+ "src/commands/mqtt.js",
35
+ "src/commands/setup.js",
36
+ "src/commands/sts.js",
37
+ "src/commands/tunnel.js",
38
+ "src/lib/.gitkeep",
39
+ "src/lib/certs.js",
40
+ "src/lib/csr.js",
41
+ "src/lib/device.js",
42
+ "src/lib/fingerprint.js",
43
+ "src/lib/ids.js",
44
+ "src/lib/logger.js",
45
+ "src/lib/pairing.js",
46
+ "src/lib/shared-transport.js",
47
+ "src/main.js",
48
+ "src/mqtt/awaiter-map.js",
49
+ "src/mqtt/events/handlers.js",
50
+ "src/mqtt/events/index.js",
51
+ "src/mqtt/events/schemas.js",
52
+ "src/mqtt/ingress.js",
53
+ "src/state/assignment.js",
54
+ "src/tunnel/http-tunnel.js",
55
+ "src/tunnel/ws-control.js",
33
56
  "LICENSE",
34
57
  "README.md",
35
58
  "SECURITY.md"
@@ -37,6 +60,8 @@
37
60
  "dependencies": {
38
61
  "@asyx/mqtt-broker-aws": "^0.1.0",
39
62
  "@asyx/mqtt-client": "^0.1.0",
63
+ "@peculiar/webcrypto": "^1.5.0",
64
+ "@peculiar/x509": "^1.14.0",
40
65
  "chalk": "^5.3.0",
41
66
  "hw-fingerprint": "^3.2.0",
42
67
  "node-fetch": "^3.3.2",
@@ -49,10 +74,12 @@
49
74
  "check": "node ./src/main.js --version",
50
75
  "test": "NODE_OPTIONS=--experimental-vm-modules jest --runInBand",
51
76
  "pack:verify": "node scripts/pack-verify.mjs",
52
- "prepublishOnly": "npm test && npm run pack:verify"
77
+ "prepublishOnly": "npm test && npm run pack:verify",
78
+ "prepack": "node scripts/prepack.mjs",
79
+ "postpack": "node scripts/postpack.mjs"
53
80
  },
54
81
  "devDependencies": {
55
82
  "@jest/globals": "^30.2.0",
56
83
  "jest": "^30.2.0"
57
84
  }
58
- }
85
+ }
package/src/lib/csr.js CHANGED
@@ -1,13 +1,49 @@
1
- import { execFile } from 'node:child_process';
2
- import { promisify } from 'node:util';
3
1
  import fs from 'node:fs/promises';
4
2
  import fssync from 'node:fs';
5
3
  import path from 'node:path';
6
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';
7
8
 
8
- const pexec = promisify(execFile);
9
+ const crypto = new Crypto();
10
+ cryptoProvider.set(crypto); // Set provider before using generator
9
11
 
10
- function certsDirFor(clientId) {
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
+ }
11
47
  const home = os.homedir();
12
48
  return path.join(home, '.asyx', 'certs', clientId);
13
49
  }
@@ -17,29 +53,133 @@ async function ensureDir(p) {
17
53
  }
18
54
 
19
55
  async function chmodIfExists(p, mode) {
20
- try { await fs.chmod(p, mode); } catch {}
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 };
21
107
  }
22
108
 
23
- export async function ensureKeyAndCsr(clientId) {
24
- const dir = certsDirFor(clientId);
109
+ export async function ensureKeyAndCsr(clientId, options = {}) {
110
+ const { baseDir } = options;
111
+ const dir = certsDirFor(clientId, baseDir);
25
112
  await ensureDir(dir);
26
113
  const keyPath = path.join(dir, 'private.pem.key');
27
114
  const csrPath = path.join(dir, 'device.csr.pem');
28
115
 
29
- // Generate key if missing
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
30
126
  if (!fssync.existsSync(keyPath)) {
31
- await pexec('openssl', ['genrsa', '-out', keyPath, '2048']);
32
- await chmodIfExists(keyPath, 0o600);
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);
33
165
  }
34
166
 
35
- // Always (re)generate CSR to match current key
36
- const subj = `/CN=${clientId}/O=Asyx`;
37
- await pexec('openssl', ['req', '-new', '-key', keyPath, '-subj', subj, '-out', csrPath]);
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
+ });
38
173
 
39
- const csrPem = await fs.readFile(csrPath, 'utf8');
174
+ const csrPem = csr.toString('pem');
175
+
176
+ // Ensure CSR is properly formatted
40
177
  if (!/^-----BEGIN CERTIFICATE REQUEST-----[\s\S]*-----END CERTIFICATE REQUEST-----\s*$/.test(csrPem)) {
41
178
  throw new Error('csr_generation_failed');
42
179
  }
43
180
 
181
+ // Write CSR file
182
+ await fs.writeFile(csrPath, csrPem, { encoding: 'utf8' });
183
+
44
184
  return { keyPath, csrPath, csrPem, dir };
45
185
  }
@@ -9,7 +9,7 @@ const controlWaiters = new Map();
9
9
  /**
10
10
  * CLI-REAUTH: Dispatch incoming control frames to waiting promises
11
11
  * Called from WebSocket message handler when a text frame matches control pattern
12
- *
12
+ *
13
13
  * @param {Object} frame - Parsed JSON control frame (must have 'op' field)
14
14
  */
15
15
  export function dispatchControlFrame(frame) {
@@ -43,31 +43,23 @@ export function dispatchControlFrame(frame) {
43
43
  * Rejects all pending waiters to ensure promises settle and don't linger in microtask queue
44
44
  */
45
45
  export function clearAllWaiters() {
46
- const rejections = [];
47
46
  for (const [, waiters] of controlWaiters) {
48
47
  for (const waiter of waiters) {
49
48
  clearTimeout(waiter.timer);
50
49
  try {
51
- // Reject the promise - catch any rejections to prevent unhandled rejection warnings
52
- const rejectionPromise = Promise.resolve().then(() => {
53
- waiter.reject(new Error('WebSocket closed before control frame received'));
54
- });
55
- // Suppress unhandled rejection warnings in tests
56
- rejectionPromise.catch(() => {});
57
- rejections.push(rejectionPromise);
50
+ // Reject the promise - tests should await these to prevent unhandled rejections
51
+ waiter.reject(new Error('WebSocket closed before control frame received'));
58
52
  } catch {
59
53
  // Ignore rejection errors (promise already settled)
60
54
  }
61
55
  }
62
56
  }
63
57
  controlWaiters.clear();
64
- // Return promise that settles all rejections (for test cleanup)
65
- return Promise.allSettled(rejections);
66
58
  }
67
59
 
68
60
  /**
69
61
  * CLI-REAUTH: Send control frame and wait for acknowledgment
70
- *
62
+ *
71
63
  * @param {WebSocket} ws - WebSocket connection
72
64
  * @param {string} payloadJson - Serialized JSON payload to send
73
65
  * @param {string} expectedOp - Expected 'op' value in response (e.g., 'reauth_ack')
@@ -141,4 +133,3 @@ export function sendControlAndWaitAck(ws, payloadJson, expectedOp, timeoutMs = 3
141
133
  }
142
134
  });
143
135
  }
144
-
@@ -1,81 +0,0 @@
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
-
@@ -1,42 +0,0 @@
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
-
@@ -1,76 +0,0 @@
1
- import { jest } from '@jest/globals';
2
-
3
- export function createMockLogger() {
4
- return {
5
- info: jest.fn(),
6
- warn: jest.fn(),
7
- error: jest.fn(),
8
- debug: jest.fn(),
9
- };
10
- }
11
-
12
- export function createMockCoordinatorCore() {
13
- return {
14
- publish: jest.fn(async () => undefined),
15
- end: jest.fn(),
16
- };
17
- }
18
-
19
- export function createMockIngress() {
20
- const awaiters = new Set();
21
- return {
22
- registerAwaiter: jest.fn((predicate, _timeoutMs) => {
23
- return new Promise((resolve, reject) => {
24
- awaiters.add({ predicate, resolve, reject });
25
- });
26
- }),
27
- resolve(payload) {
28
- for (const entry of awaiters) {
29
- try {
30
- if (entry.predicate({ payload })) {
31
- entry.resolve({ payload });
32
- awaiters.delete(entry);
33
- return true;
34
- }
35
- } catch {}
36
- }
37
- return false;
38
- },
39
- rejectAll(error) {
40
- for (const entry of awaiters) {
41
- entry.reject(error);
42
- awaiters.delete(entry);
43
- }
44
- },
45
- };
46
- }
47
-
48
- export async function createHttpTunnel(overrides = {}) {
49
- const logger = overrides.logger ?? createMockLogger();
50
- const coordinatorCore = overrides.coordinatorCore ?? createMockCoordinatorCore();
51
- const coordinatorIngress = overrides.coordinatorIngress ?? createMockIngress();
52
-
53
- const module = await import('../http-tunnel.js');
54
- const { HttpTunnel } = module;
55
-
56
- const tunnel = new HttpTunnel({
57
- relayUrl: overrides.relayUrl ?? 'wss://relay.example.com/agent',
58
- jwt: overrides.jwt ?? 'initial.jwt',
59
- deviceId: overrides.deviceId ?? 'cli_123456789ABC',
60
- requestId: overrides.requestId ?? 'initial-request',
61
- localPort: overrides.localPort ?? 3000,
62
- coordinatorCore,
63
- coordinatorIngress,
64
- isControlPlaneConnected: overrides.isControlPlaneConnected ?? (() => true),
65
- waitForControlPlane: overrides.waitForControlPlane ?? (() => Promise.resolve()),
66
- controlPlaneTimeoutMs: overrides.controlPlaneTimeoutMs ?? 100,
67
- log: logger,
68
- });
69
-
70
- // Avoid real WS connects in unit tests
71
- tunnel._attemptConnect = jest.fn(async () => {});
72
-
73
- return { tunnel, logger, coordinatorCore, coordinatorIngress };
74
- }
75
-
76
-