asyx 0.1.0 → 0.1.2
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/README.md +22 -0
- package/package.json +32 -5
- package/src/lib/csr.js +174 -14
- package/src/tunnel/ws-control.js +4 -13
- package/src/lib/logger.level.spec.js +0 -81
- package/src/lib/logger.test.js +0 -42
- package/src/tunnel/__test_utils__/testUtils.js +0 -76
- package/src/tunnel/__tests__/jwt-refresh.spec.js +0 -948
- package/src/tunnel/__tests__/ws-control.spec.js +0 -164
package/README.md
CHANGED
|
@@ -92,6 +92,28 @@ The CLI manages heartbeats automatically to keep idle sessions stable without us
|
|
|
92
92
|
- Heartbeat stops when the tunnel exits or errors.
|
|
93
93
|
- Use `ASYX_DEBUG=1` if you need to trace heartbeat activity for support purposes.
|
|
94
94
|
|
|
95
|
+
## Troubleshooting
|
|
96
|
+
|
|
97
|
+
### MQTT Connection Issues (Windows)
|
|
98
|
+
|
|
99
|
+
If you experience issues where the CLI connects but never receives `open_ack` messages (especially on Windows after running `asyx setup` without OpenSSL), the private key may be in PKCS#8 format which Node's TLS stack on Windows rejects.
|
|
100
|
+
|
|
101
|
+
**Solution**: Rerun `asyx setup` to regenerate keys in the correct format. The CLI will automatically convert existing PKCS#8 keys to PKCS#1 format (required for Windows TLS compatibility).
|
|
102
|
+
|
|
103
|
+
**Manual workaround** (if you cannot rerun setup):
|
|
104
|
+
```javascript
|
|
105
|
+
const crypto = require('crypto');
|
|
106
|
+
const fs = require('fs');
|
|
107
|
+
const keyPath = '~/.asyx/certs/<clientId>/private.pem.key';
|
|
108
|
+
|
|
109
|
+
const keyPem = fs.readFileSync(keyPath, 'utf8');
|
|
110
|
+
const privateKey = crypto.createPrivateKey({ key: keyPem, format: 'pem' });
|
|
111
|
+
const pkcs1Pem = privateKey.export({ type: 'pkcs1', format: 'pem' });
|
|
112
|
+
fs.writeFileSync(keyPath, pkcs1Pem, { mode: 0o600 });
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
This issue is fixed in version 0.1.2+ where keys are automatically generated in PKCS#1 format for Windows compatibility.
|
|
116
|
+
|
|
95
117
|
## Security
|
|
96
118
|
|
|
97
119
|
Asyx tunnels are designed with security-first principles to protect both your local services and the tunnel infrastructure. Every active tunnel operates with **per-tunnel cryptographic isolation**, short-lived JWT credentials, and in-band credential refresh to achieve zero-downtime, zero-trust operation.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "asyx",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2",
|
|
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
|
|
9
|
+
const crypto = new Crypto();
|
|
10
|
+
cryptoProvider.set(crypto); // Set provider before using generator
|
|
9
11
|
|
|
10
|
-
|
|
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,153 @@ async function ensureDir(p) {
|
|
|
17
53
|
}
|
|
18
54
|
|
|
19
55
|
async function chmodIfExists(p, mode) {
|
|
20
|
-
try {
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
32
|
-
await
|
|
127
|
+
// Generate new key pair
|
|
128
|
+
keyPair = await crypto.subtle.generateKey(alg, true, ['sign', 'verify']);
|
|
129
|
+
|
|
130
|
+
// Export private key in PKCS#8 format (for CSR operations)
|
|
131
|
+
const pkcs8 = await crypto.subtle.exportKey('pkcs8', keyPair.privateKey);
|
|
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 });
|
|
147
|
+
} else {
|
|
148
|
+
// Import existing private key
|
|
149
|
+
const keyPem = await fs.readFile(keyPath, 'utf8');
|
|
150
|
+
|
|
151
|
+
// Check if key is PKCS#1 (RSA PRIVATE KEY) or PKCS#8 (PRIVATE KEY)
|
|
152
|
+
const isPkcs1 = keyPem.includes('BEGIN RSA PRIVATE KEY');
|
|
153
|
+
|
|
154
|
+
let pkcs8Bytes;
|
|
155
|
+
|
|
156
|
+
if (isPkcs1) {
|
|
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
|
|
159
|
+
const nodePrivateKey = nodeCrypto.createPrivateKey({
|
|
160
|
+
key: keyPem,
|
|
161
|
+
format: 'pem'
|
|
162
|
+
});
|
|
163
|
+
const pkcs8Pem = nodePrivateKey.export({
|
|
164
|
+
type: 'pkcs8',
|
|
165
|
+
format: 'pem'
|
|
166
|
+
});
|
|
167
|
+
pkcs8Bytes = pemToBuffer(pkcs8Pem);
|
|
168
|
+
// Keep file as PKCS#1 (no write needed)
|
|
169
|
+
} else {
|
|
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 });
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
keyPair = await importPrivateKey(pkcs8Bytes);
|
|
33
185
|
}
|
|
34
186
|
|
|
35
|
-
//
|
|
36
|
-
const
|
|
37
|
-
|
|
187
|
+
// Build CSR using static factory method
|
|
188
|
+
const csr = await Pkcs10CertificateRequestGenerator.create({
|
|
189
|
+
name: `CN=${clientId}, O=Asyx`,
|
|
190
|
+
keys: keyPair, // { publicKey, privateKey }
|
|
191
|
+
signingAlgorithm: alg // same object used for generateKey
|
|
192
|
+
});
|
|
38
193
|
|
|
39
|
-
const csrPem =
|
|
194
|
+
const csrPem = csr.toString('pem');
|
|
195
|
+
|
|
196
|
+
// Ensure CSR is properly formatted
|
|
40
197
|
if (!/^-----BEGIN CERTIFICATE REQUEST-----[\s\S]*-----END CERTIFICATE REQUEST-----\s*$/.test(csrPem)) {
|
|
41
198
|
throw new Error('csr_generation_failed');
|
|
42
199
|
}
|
|
43
200
|
|
|
201
|
+
// Write CSR file
|
|
202
|
+
await fs.writeFile(csrPath, csrPem, { encoding: 'utf8' });
|
|
203
|
+
|
|
44
204
|
return { keyPath, csrPath, csrPem, dir };
|
|
45
205
|
}
|
package/src/tunnel/ws-control.js
CHANGED
|
@@ -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 -
|
|
52
|
-
|
|
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
|
-
|
package/src/lib/logger.test.js
DELETED
|
@@ -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
|
-
|