asyx 0.10.1 → 0.11.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.
Files changed (93) hide show
  1. package/AGENTS.md +42 -0
  2. package/bin/asyx.js +1 -1
  3. package/package.json +8 -2
  4. package/src/commands/account.js +80 -71
  5. package/src/commands/app.js +317 -151
  6. package/src/commands/in-use-messages.js +47 -48
  7. package/src/commands/mqtt-broker.js +36 -49
  8. package/src/commands/mqtt.js +111 -149
  9. package/src/commands/name.js +24 -22
  10. package/src/commands/reject-messages.js +123 -123
  11. package/src/commands/setup.js +107 -131
  12. package/src/commands/sts.js +45 -61
  13. package/src/commands/tunnel.js +853 -932
  14. package/src/commands/validate-target-host.js +36 -59
  15. package/src/lib/aws-iot-config.js +26 -24
  16. package/src/lib/certs.js +15 -18
  17. package/src/lib/csr.js +107 -182
  18. package/src/lib/device.js +26 -37
  19. package/src/lib/ids.js +1 -2
  20. package/src/lib/naming.js +74 -68
  21. package/src/lib/pairing.js +10 -11
  22. package/src/lib/shared-transport.js +5 -9
  23. package/src/main.js +63 -53
  24. package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneClient.js +25 -287
  25. package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneTransport.js +0 -72
  26. package/vendor/tunnel-core/dist/control-plane/session.js +0 -20
  27. package/vendor/tunnel-core/dist/errors.js +0 -19
  28. package/vendor/tunnel-core/dist/flows/account.js +1 -6
  29. package/vendor/tunnel-core/dist/flows/goodbye.js +0 -4
  30. package/vendor/tunnel-core/dist/flows/http.js +24 -112
  31. package/vendor/tunnel-core/dist/flows/identity.js +17 -10
  32. package/vendor/tunnel-core/dist/flows/in-use.js +0 -6
  33. package/vendor/tunnel-core/dist/flows/reopen.js +0 -4
  34. package/vendor/tunnel-core/dist/flows/tcp.js +18 -84
  35. package/vendor/tunnel-core/dist/flows/udp.js +15 -52
  36. package/vendor/tunnel-core/dist/lib/fingerprint.js +38 -42
  37. package/vendor/tunnel-core/dist/lib/jwt-verifier.js +22 -74
  38. package/vendor/tunnel-core/dist/lib/logger.js +1 -9
  39. package/vendor/tunnel-core/dist/lib/refresh-helpers.js +1 -22
  40. package/vendor/tunnel-core/dist/lifecycle.js +1 -8
  41. package/vendor/tunnel-core/dist/mqtt/awaiter-map.js +1 -53
  42. package/vendor/tunnel-core/dist/mqtt/events/handlers.js +10 -64
  43. package/vendor/tunnel-core/dist/mqtt/events/index.js +3 -36
  44. package/vendor/tunnel-core/dist/mqtt/events/schemas.js +0 -1
  45. package/vendor/tunnel-core/dist/mqtt/ingress.js +0 -60
  46. package/vendor/tunnel-core/dist/state/assignment.js +6 -122
  47. package/vendor/tunnel-core/dist/state/instance-registry.js +0 -63
  48. package/vendor/tunnel-core/dist/tcp-v1/framing.js +2 -64
  49. package/vendor/tunnel-core/dist/tunnel/http-tunnel.js +64 -331
  50. package/vendor/tunnel-core/dist/tunnel/httpws-constants.js +5 -14
  51. package/vendor/tunnel-core/dist/tunnel/reconnect.js +10 -50
  52. package/vendor/tunnel-core/dist/tunnel/request-sink.js +0 -16
  53. package/vendor/tunnel-core/dist/tunnel/tcp-tunnel.js +32 -195
  54. package/vendor/tunnel-core/dist/tunnel/udp-tunnel.js +28 -153
  55. package/vendor/tunnel-core/dist/tunnel/ws-control.js +4 -39
  56. package/vendor/tunnel-core/dist/types.js +0 -2
  57. package/vendor/tunnel-core/dist/udp-v1/framing.js +2 -64
  58. package/vendor/tunnel-core/package.json +0 -25
  59. package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneClient.d.ts +0 -273
  60. package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneTransport.d.ts +0 -79
  61. package/vendor/tunnel-core/dist/control-plane/session.d.ts +0 -55
  62. package/vendor/tunnel-core/dist/errors.d.ts +0 -49
  63. package/vendor/tunnel-core/dist/flows/account.d.ts +0 -24
  64. package/vendor/tunnel-core/dist/flows/goodbye.d.ts +0 -10
  65. package/vendor/tunnel-core/dist/flows/http.d.ts +0 -61
  66. package/vendor/tunnel-core/dist/flows/identity.d.ts +0 -23
  67. package/vendor/tunnel-core/dist/flows/in-use.d.ts +0 -27
  68. package/vendor/tunnel-core/dist/flows/reopen.d.ts +0 -9
  69. package/vendor/tunnel-core/dist/flows/tcp.d.ts +0 -85
  70. package/vendor/tunnel-core/dist/flows/udp.d.ts +0 -52
  71. package/vendor/tunnel-core/dist/lib/adapt-logger.d.ts +0 -2
  72. package/vendor/tunnel-core/dist/lib/fingerprint.d.ts +0 -145
  73. package/vendor/tunnel-core/dist/lib/jwt-verifier.d.ts +0 -27
  74. package/vendor/tunnel-core/dist/lib/logger.d.ts +0 -9
  75. package/vendor/tunnel-core/dist/lib/refresh-helpers.d.ts +0 -16
  76. package/vendor/tunnel-core/dist/lifecycle.d.ts +0 -24
  77. package/vendor/tunnel-core/dist/mqtt/awaiter-map.d.ts +0 -56
  78. package/vendor/tunnel-core/dist/mqtt/events/handlers.d.ts +0 -60
  79. package/vendor/tunnel-core/dist/mqtt/events/index.d.ts +0 -1
  80. package/vendor/tunnel-core/dist/mqtt/events/schemas.d.ts +0 -498
  81. package/vendor/tunnel-core/dist/mqtt/ingress.d.ts +0 -63
  82. package/vendor/tunnel-core/dist/state/assignment.d.ts +0 -136
  83. package/vendor/tunnel-core/dist/state/instance-registry.d.ts +0 -88
  84. package/vendor/tunnel-core/dist/tcp-v1/framing.d.ts +0 -43
  85. package/vendor/tunnel-core/dist/tunnel/http-tunnel.d.ts +0 -140
  86. package/vendor/tunnel-core/dist/tunnel/httpws-constants.d.ts +0 -13
  87. package/vendor/tunnel-core/dist/tunnel/reconnect.d.ts +0 -76
  88. package/vendor/tunnel-core/dist/tunnel/request-sink.d.ts +0 -40
  89. package/vendor/tunnel-core/dist/tunnel/tcp-tunnel.d.ts +0 -92
  90. package/vendor/tunnel-core/dist/tunnel/udp-tunnel.d.ts +0 -93
  91. package/vendor/tunnel-core/dist/tunnel/ws-control.d.ts +0 -22
  92. package/vendor/tunnel-core/dist/types.d.ts +0 -24
  93. package/vendor/tunnel-core/dist/udp-v1/framing.d.ts +0 -41
@@ -1,32 +1,17 @@
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
1
  import { getFingerprintingInfo } from 'hw-fingerprint';
8
2
  import { createHash } from 'node:crypto';
9
3
  import os from 'node:os';
10
- /**
11
- * Safe hardware attributes that don't trigger macOS privacy warnings.
12
- * Based on analysis of hw-fingerprint library behavior.
13
- */
14
4
  const SAFE_FIELDS = [
15
- 'platform', // OS platform (darwin, linux, win32)
16
- 'arch', // CPU architecture (arm64, x64)
17
- 'cores', // Number of CPU cores
18
- 'manufacturer', // Hardware manufacturer
19
- 'vendor', // System vendor
20
- 'model' // Hardware model (Mac16,11, etc.)
5
+ 'platform',
6
+ 'arch',
7
+ 'cores',
8
+ 'manufacturer',
9
+ 'vendor',
10
+ 'model'
21
11
  ];
22
- /**
23
- * Collect safe hardware fingerprint using only non-sensitive fields.
24
- * Returns canonical JSON string with stable ordering.
25
- */
26
12
  async function collectSafeHardwareFingerprint() {
27
13
  try {
28
14
  const fingerprint = await getFingerprintingInfo();
29
- // Extract only safe fields, dropping empties
30
15
  const safeData = {};
31
16
  for (const field of SAFE_FIELDS) {
32
17
  const value = fingerprint[field];
@@ -34,7 +19,6 @@ async function collectSafeHardwareFingerprint() {
34
19
  safeData[field] = value;
35
20
  }
36
21
  }
37
- // Create canonical JSON with stable ordering
38
22
  const canonical = {
39
23
  version: 'fpv1-safe',
40
24
  fields: safeData
@@ -42,14 +26,9 @@ async function collectSafeHardwareFingerprint() {
42
26
  return JSON.stringify(canonical, Object.keys(canonical).sort());
43
27
  }
44
28
  catch (error) {
45
- // Return empty canonical structure on failure
46
29
  return JSON.stringify({ version: 'fpv1-safe', fields: {} }, Object.keys({ version: 'fpv1-safe', fields: {} }).sort());
47
30
  }
48
31
  }
49
- /**
50
- * Hash fingerprint using SHA-256 with public salt.
51
- * Returns hex string.
52
- */
53
32
  function hashFingerprint(canonical, clientId) {
54
33
  const publicSalt = `asyx|${clientId}`;
55
34
  const preimage = publicSalt + canonical;
@@ -57,27 +36,14 @@ function hashFingerprint(canonical, clientId) {
57
36
  .update(preimage, 'utf8')
58
37
  .digest('hex');
59
38
  }
60
- /**
61
- * Get safe hardware fingerprint hash with version metadata.
62
- * Returns structured object for cmd/open payload.
63
- *
64
- * This version avoids macOS privacy warnings by using only safe fields.
65
- */
66
- // Story 2.1 c7: every cmd/open (first open, refresh, reconnect) carries the client's version so the
67
- // coordinator can tell old clients from new ones. The CLI sets ASYX_CLIENT_VERSION at start-up; an
68
- // embedding app may set it too. Omitted when unknown.
69
39
  function versionField() {
70
40
  const v = (process.env.ASYX_CLIENT_VERSION || '').trim();
71
41
  return /^[0-9A-Za-z.@+-]{1,40}$/.test(v) ? { clientVersion: v } : {};
72
42
  }
73
- // Story 4.10 r3: the address the tunnel serves (`asyx tunnel --to <hostname>`), sent on every
74
- // open/refresh/reconnect so the coordinator can refuse a tunnel for an address this device does not serve.
75
43
  function targetField() {
76
44
  const v = (process.env.ASYX_TUNNEL_TO || '').trim().toLowerCase();
77
45
  return /^[a-z0-9.-]{3,253}$/.test(v) ? { to: v } : {};
78
46
  }
79
- // Story 1.9: the computer's name (so a refusal can say where the running tunnel is; never an IP
80
- // address) and whether this open may take over a live tunnel of the same kind (`--replace`).
81
47
  function hostField() {
82
48
  let h = '';
83
49
  try {
@@ -92,8 +58,39 @@ function hostField() {
92
58
  function replaceField() {
93
59
  return process.env.ASYX_TUNNEL_REPLACE === '1' ? { replace: true } : {};
94
60
  }
61
+ const openFieldsById = new Map();
62
+ export function setOpenFields(clientId, fields) {
63
+ if (!clientId)
64
+ return;
65
+ if (!fields) {
66
+ openFieldsById.delete(clientId);
67
+ return;
68
+ }
69
+ const out = {};
70
+ if (typeof fields.clientVersion === 'string' && /^[0-9A-Za-z.@+-]{1,40}$/.test(fields.clientVersion))
71
+ out.clientVersion = fields.clientVersion;
72
+ if (typeof fields.to === 'string' && /^[a-z0-9.-]{3,253}$/.test(fields.to.trim().toLowerCase()))
73
+ out.to = fields.to.trim().toLowerCase();
74
+ if (fields.replace === true)
75
+ out.replace = true;
76
+ openFieldsById.set(clientId, out);
77
+ }
95
78
  export async function getFpHash(clientId) {
96
- return { ...(await fingerprintFields(clientId)), ...versionField(), ...targetField(), ...hostField(), ...replaceField() };
79
+ const own = openFieldsById.get(clientId);
80
+ const fields = { ...(await fingerprintFields(clientId)), ...versionField(), ...targetField(), ...hostField(), ...replaceField() };
81
+ if (own) {
82
+ if (own.clientVersion)
83
+ fields.clientVersion = own.clientVersion;
84
+ if (own.to)
85
+ fields.to = own.to;
86
+ else
87
+ delete fields.to;
88
+ if (own.replace)
89
+ fields.replace = true;
90
+ else
91
+ delete fields.replace;
92
+ }
93
+ return fields;
97
94
  }
98
95
  async function fingerprintFields(clientId) {
99
96
  try {
@@ -107,7 +104,6 @@ async function fingerprintFields(clientId) {
107
104
  };
108
105
  }
109
106
  catch (error) {
110
- // Return unavailable fingerprint on any failure
111
107
  return {
112
108
  fpv: '1-safe',
113
109
  fph: 'unavailable',
@@ -1,22 +1,12 @@
1
- // Shared JWT verifier using JWKS for assignment token validation
2
- // Used by TCP/HTTP/UDP tunnels to verify assignment JWTs before opening WebSocket
3
- // AC1.4/AC5.1: Enforces "no JWKS → no tunnel" policy
4
1
  import { createRemoteJWKSet, jwtVerify } from 'jose';
5
2
  import logger from './logger.js';
6
- // JWKS URL configuration (environment-specific)
7
- const JWKS_URL_PROD = 'https://auth.asyx.ai/.well-known/jwks.json';
8
- const JWKS_URL_DEV = 'https://auth.dev.asyx.ai/.well-known/jwks.json';
9
- // Expected issuer and audience
3
+ const JWKS_URL = 'https://auth.asyx.ai/.well-known/jwks.json';
4
+ let keySourceForTests = null;
10
5
  const EXPECTED_ISSUER = 'https://auth.asyx.ai';
11
6
  const EXPECTED_AUDIENCE = 'tunnel-relay';
12
- // Singleton JWKS cache (shared across all tunnel instances)
13
7
  let jwksCache = null;
14
8
  let jwksInitialized = false;
15
9
  let jwksInitPromise = null;
16
- /**
17
- * Initialize JWKS cache (lazy, on first use)
18
- * @returns {Promise<void>}
19
- */
20
10
  async function initializeJWKS() {
21
11
  if (jwksInitialized) {
22
12
  return;
@@ -26,18 +16,9 @@ async function initializeJWKS() {
26
16
  }
27
17
  jwksInitPromise = (async () => {
28
18
  try {
29
- // Determine JWKS URL from environment
30
- const env = process.env.ASYX_ENV || process.env.NODE_ENV || 'prod';
31
- const jwksUrl = env === 'dev' || env === 'development' ? JWKS_URL_DEV : JWKS_URL_PROD;
32
- // Allow override via environment variable
33
- const jwksUrlOverride = process.env.ASYX_JWKS_URL;
34
- const finalJwksUrl = jwksUrlOverride || jwksUrl;
35
- logger.debug('jwt.jwks.initializing', { jwksUrl: finalJwksUrl, env });
36
- // Create remote JWKS set (jose handles caching and refresh)
19
+ const finalJwksUrl = keySourceForTests || JWKS_URL;
20
+ logger.debug('jwt.jwks.initializing', { jwksUrl: finalJwksUrl });
37
21
  jwksCache = createRemoteJWKSet(new URL(finalJwksUrl));
38
- // Test fetch to ensure JWKS is available (fail fast if not)
39
- // jose's createRemoteJWKSet doesn't fetch immediately, so we need to trigger a fetch
40
- // We'll do this on first verification attempt
41
22
  jwksInitialized = true;
42
23
  logger.info('jwt.jwks.initialized', { jwksUrl: finalJwksUrl });
43
24
  }
@@ -49,26 +30,12 @@ async function initializeJWKS() {
49
30
  })();
50
31
  return jwksInitPromise;
51
32
  }
52
- /**
53
- * Verify assignment JWT with JWKS signature verification
54
- * AC1.4/AC5.1: Validates signature, iss, aud, exp, relayId, protocol, tunnelMode, leaseId
55
- * @param {string} token - JWT token to verify
56
- * @param {Object} expectedClaims - Expected claim values
57
- * @param {string} expectedClaims.relayId - Expected relayId
58
- * @param {string} expectedClaims.protocol - Expected protocol ('udp' | 'tcp')
59
- * @param {string} expectedClaims.tunnelMode - Expected tunnelMode ('udpWs-v1' | 'tcpWs-v1')
60
- * @param {string} [expectedClaims.leaseId] - Expected leaseId (optional)
61
- * @returns {Promise<Object>} Verified JWT payload
62
- * @throws {Error} If JWT verification fails (signature, claims, or JWKS unavailable)
63
- */
64
- export async function verifyAssignmentJWT(token, expectedClaims = /** @type {any} */ ({})) {
65
- // Initialize JWKS if not already done
33
+ export async function verifyAssignmentJWT(token, expectedClaims = ({})) {
66
34
  if (!jwksInitialized) {
67
35
  await initializeJWKS();
68
36
  }
69
- // AC1.4/AC5.1: Fail fast if JWKS is not available
70
37
  if (!jwksCache) {
71
- const error = /** @type {Error & { code?: string, cause?: unknown, closeCode?: number, originalError?: unknown }} */ (new Error('JWKS not available - cannot verify assignment JWT'));
38
+ const error = (new Error('JWKS not available - cannot verify assignment JWT'));
72
39
  error.code = 'JWKS_UNAVAILABLE';
73
40
  logger.error('jwt.verification.jwks_unavailable', {
74
41
  tokenLength: token?.length || 0,
@@ -77,16 +44,9 @@ export async function verifyAssignmentJWT(token, expectedClaims = /** @type {any
77
44
  throw error;
78
45
  }
79
46
  try {
80
- // Verify JWT signature and decode payload using JWKS
81
- // jwtVerify automatically:
82
- // - Fetches JWKS if not cached
83
- // - Verifies signature using the key identified by 'kid' in JWT header
84
- // - Validates exp, nbf, iat if present
85
47
  const { payload, protectedHeader } = await jwtVerify(token, jwksCache, {
86
48
  issuer: EXPECTED_ISSUER,
87
49
  audience: EXPECTED_AUDIENCE,
88
- // jose validates exp automatically with clock skew tolerance
89
- // We'll get ERR_JWT_EXPIRED if expired, which we handle below
90
50
  });
91
51
  logger.debug('jwt.verification.signature_verified', {
92
52
  kid: protectedHeader.kid,
@@ -95,9 +55,8 @@ export async function verifyAssignmentJWT(token, expectedClaims = /** @type {any
95
55
  protocol: payload.protocol,
96
56
  tunnelMode: payload.tunnelMode
97
57
  });
98
- // AC5.1: Validate relayId matches expected
99
58
  if (expectedClaims.relayId && payload.relayId !== expectedClaims.relayId) {
100
- const error = /** @type {Error & { code?: string, cause?: unknown, closeCode?: number, originalError?: unknown }} */ (new Error(`JWT relayId mismatch: ${payload.relayId} !== ${expectedClaims.relayId}`));
59
+ const error = (new Error(`JWT relayId mismatch: ${payload.relayId} !== ${expectedClaims.relayId}`));
101
60
  error.code = 'JWT_RELAYID_MISMATCH';
102
61
  logger.error('jwt.verification.relayid_mismatch', {
103
62
  expected: expectedClaims.relayId,
@@ -106,9 +65,8 @@ export async function verifyAssignmentJWT(token, expectedClaims = /** @type {any
106
65
  });
107
66
  throw error;
108
67
  }
109
- // AC1.4: Validate protocol
110
68
  if (expectedClaims.protocol && payload.protocol !== expectedClaims.protocol) {
111
- const error = /** @type {Error & { code?: string, cause?: unknown, closeCode?: number, originalError?: unknown }} */ (new Error(`JWT protocol mismatch: ${payload.protocol} !== ${expectedClaims.protocol}`));
69
+ const error = (new Error(`JWT protocol mismatch: ${payload.protocol} !== ${expectedClaims.protocol}`));
112
70
  error.code = 'JWT_PROTOCOL_MISMATCH';
113
71
  logger.error('jwt.verification.protocol_mismatch', {
114
72
  expected: expectedClaims.protocol,
@@ -116,9 +74,8 @@ export async function verifyAssignmentJWT(token, expectedClaims = /** @type {any
116
74
  });
117
75
  throw error;
118
76
  }
119
- // AC1.4: Validate tunnelMode
120
77
  if (expectedClaims.tunnelMode && payload.tunnelMode !== expectedClaims.tunnelMode) {
121
- const error = /** @type {Error & { code?: string, cause?: unknown, closeCode?: number, originalError?: unknown }} */ (new Error(`JWT tunnelMode mismatch: ${payload.tunnelMode} !== ${expectedClaims.tunnelMode}`));
78
+ const error = (new Error(`JWT tunnelMode mismatch: ${payload.tunnelMode} !== ${expectedClaims.tunnelMode}`));
122
79
  error.code = 'JWT_TUNNELMODE_MISMATCH';
123
80
  logger.error('jwt.verification.tunnelmode_mismatch', {
124
81
  expected: expectedClaims.tunnelMode,
@@ -126,9 +83,8 @@ export async function verifyAssignmentJWT(token, expectedClaims = /** @type {any
126
83
  });
127
84
  throw error;
128
85
  }
129
- // AC5.1: Validate leaseId if provided
130
86
  if (expectedClaims.leaseId && payload.leaseId && payload.leaseId !== expectedClaims.leaseId) {
131
- const error = /** @type {Error & { code?: string, cause?: unknown, closeCode?: number, originalError?: unknown }} */ (new Error(`JWT leaseId mismatch: ${payload.leaseId} !== ${expectedClaims.leaseId}`));
87
+ const error = (new Error(`JWT leaseId mismatch: ${payload.leaseId} !== ${expectedClaims.leaseId}`));
132
88
  error.code = 'JWT_LEASEID_MISMATCH';
133
89
  logger.error('jwt.verification.leaseid_mismatch', {
134
90
  expected: expectedClaims.leaseId,
@@ -136,19 +92,18 @@ export async function verifyAssignmentJWT(token, expectedClaims = /** @type {any
136
92
  });
137
93
  throw error;
138
94
  }
139
- // AC1.4: Validate required claims are present
140
95
  if (!payload.relayId) {
141
- const error = /** @type {Error & { code?: string, cause?: unknown, closeCode?: number, originalError?: unknown }} */ (new Error('Missing relayId in JWT payload'));
96
+ const error = (new Error('Missing relayId in JWT payload'));
142
97
  error.code = 'JWT_MISSING_RELAYID';
143
98
  throw error;
144
99
  }
145
100
  if (!payload.protocol) {
146
- const error = /** @type {Error & { code?: string, cause?: unknown, closeCode?: number, originalError?: unknown }} */ (new Error('Missing protocol in JWT payload'));
101
+ const error = (new Error('Missing protocol in JWT payload'));
147
102
  error.code = 'JWT_MISSING_PROTOCOL';
148
103
  throw error;
149
104
  }
150
105
  if (!payload.tunnelMode) {
151
- const error = /** @type {Error & { code?: string, cause?: unknown, closeCode?: number, originalError?: unknown }} */ (new Error('Missing tunnelMode in JWT payload'));
106
+ const error = (new Error('Missing tunnelMode in JWT payload'));
152
107
  error.code = 'JWT_MISSING_TUNNELMODE';
153
108
  throw error;
154
109
  }
@@ -161,9 +116,8 @@ export async function verifyAssignmentJWT(token, expectedClaims = /** @type {any
161
116
  return payload;
162
117
  }
163
118
  catch (error) {
164
- // Map jose errors to our error codes
165
119
  if (error.code === 'ERR_JWKS_TIMEOUT' || error.code === 'ERR_JWKS_MULTIPLE_MATCHING_KEYS') {
166
- const jwksError = /** @type {Error & { code?: string, cause?: unknown, closeCode?: number, originalError?: unknown }} */ (new Error(`JWKS error: ${error.message}`));
120
+ const jwksError = (new Error(`JWKS error: ${error.message}`));
167
121
  jwksError.code = 'JWKS_ERROR';
168
122
  logger.error('jwt.verification.jwks_error', {
169
123
  error: error.message,
@@ -172,7 +126,7 @@ export async function verifyAssignmentJWT(token, expectedClaims = /** @type {any
172
126
  throw jwksError;
173
127
  }
174
128
  if (error.code === 'ERR_JWT_EXPIRED') {
175
- const expiredError = /** @type {Error & { code?: string, cause?: unknown, closeCode?: number, originalError?: unknown }} */ (new Error('JWT expired'));
129
+ const expiredError = (new Error('JWT expired'));
176
130
  expiredError.code = 'JWT_EXPIRED';
177
131
  logger.error('jwt.verification.expired', {
178
132
  exp: error.claims?.exp,
@@ -181,8 +135,7 @@ export async function verifyAssignmentJWT(token, expectedClaims = /** @type {any
181
135
  throw expiredError;
182
136
  }
183
137
  if (error.code === 'ERR_JWT_CLAIM_VALIDATION_FAILED') {
184
- // This could be issuer or audience mismatch
185
- const claimError = /** @type {Error & { code?: string, cause?: unknown, closeCode?: number, originalError?: unknown }} */ (new Error(`JWT claim validation failed: ${error.message}`));
138
+ const claimError = (new Error(`JWT claim validation failed: ${error.message}`));
186
139
  claimError.code = 'JWT_CLAIM_INVALID';
187
140
  logger.error('jwt.verification.claim_failed', {
188
141
  error: error.message,
@@ -191,19 +144,17 @@ export async function verifyAssignmentJWT(token, expectedClaims = /** @type {any
191
144
  throw claimError;
192
145
  }
193
146
  if (error.code === 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED') {
194
- const sigError = /** @type {Error & { code?: string, cause?: unknown, closeCode?: number, originalError?: unknown }} */ (new Error('JWT signature verification failed'));
147
+ const sigError = (new Error('JWT signature verification failed'));
195
148
  sigError.code = 'JWT_SIGNATURE_INVALID';
196
149
  logger.error('jwt.verification.signature_failed', {
197
150
  error: error.message
198
151
  });
199
152
  throw sigError;
200
153
  }
201
- // Re-throw our custom errors
202
154
  if (error.code && error.code.startsWith('JWT_') || error.code === 'JWKS_UNAVAILABLE' || error.code === 'JWKS_ERROR') {
203
155
  throw error;
204
156
  }
205
- // Unknown error - wrap it
206
- const unknownError = /** @type {Error & { code?: string, cause?: unknown, closeCode?: number, originalError?: unknown }} */ (new Error(`JWT verification failed: ${error.message}`));
157
+ const unknownError = (new Error(`JWT verification failed: ${error.message}`));
207
158
  unknownError.code = 'JWT_VERIFICATION_FAILED';
208
159
  unknownError.originalError = error;
209
160
  logger.error('jwt.verification.unknown_error', {
@@ -213,18 +164,15 @@ export async function verifyAssignmentJWT(token, expectedClaims = /** @type {any
213
164
  throw unknownError;
214
165
  }
215
166
  }
216
- /**
217
- * Check if JWKS is available (for health checks)
218
- * @returns {boolean} True if JWKS is initialized
219
- */
220
167
  export function isJWKSAvailable() {
221
168
  return jwksInitialized && jwksCache !== null;
222
169
  }
223
- /**
224
- * Reset JWKS cache (for testing or re-initialization)
225
- */
226
170
  export function resetJWKS() {
227
171
  jwksCache = null;
228
172
  jwksInitialized = false;
229
173
  jwksInitPromise = null;
230
174
  }
175
+ export function setKeySourceForTests(url) {
176
+ keySourceForTests = url || null;
177
+ resetJWKS();
178
+ }
@@ -1,22 +1,17 @@
1
1
  function isoNow() {
2
2
  return new Date().toISOString();
3
3
  }
4
- // Parse env log level once at module load
5
4
  const LEVEL_ORDER = { error: 40, warn: 30, info: 20, debug: 10 };
6
5
  function normalizeLevel(value) {
7
6
  const v = String(value || '').trim().toLowerCase();
8
7
  if (v in LEVEL_ORDER)
9
8
  return v;
10
- // QPA-CLI-10: Default to warn for quiet mode (suppress info/debug telemetry, show warn/error)
11
- // Users can set LOG_LEVEL=info to see structured telemetry logs
12
9
  return 'warn';
13
10
  }
14
- // QPA-CLI-10: Support both ASYX_LOG_LEVEL and LOG_LEVEL env vars
15
11
  const ENV_LEVEL = normalizeLevel(process.env.ASYX_LOG_LEVEL || process.env.LOG_LEVEL);
16
12
  function shouldEmit(level) {
17
- // QPA-CLI-10: Default to warn level (quiet mode - suppress info/debug telemetry)
18
13
  const desired = LEVEL_ORDER[ENV_LEVEL] ?? LEVEL_ORDER.warn;
19
- const actual = LEVEL_ORDER[normalizeLevel(level)] ?? LEVEL_ORDER.error; // Default actual to error if invalid
14
+ const actual = LEVEL_ORDER[normalizeLevel(level)] ?? LEVEL_ORDER.error;
20
15
  return actual >= desired;
21
16
  }
22
17
  function emit(level, msg, fields = {}) {
@@ -26,12 +21,9 @@ function emit(level, msg, fields = {}) {
26
21
  msg,
27
22
  fields: fields && typeof fields === 'object' ? fields : {},
28
23
  };
29
- // Ensure single-line JSON output
30
24
  const line = JSON.stringify(entry);
31
- // Level gating: suppress messages below configured level
32
25
  if (!shouldEmit(level))
33
26
  return;
34
- // Route by level to preserve severity semantics if needed
35
27
  if (level === 'error') {
36
28
  console.error(line);
37
29
  }
@@ -1,15 +1,3 @@
1
- /**
2
- * QPA-CLI-09: Publish refresh request with ECONNRESET error handling.
3
- * Catches connection reset errors during publish and returns a sentinel value
4
- * instead of throwing, so the CLI doesn't exit with "Unexpected error".
5
- *
6
- * @param coordinatorCore - MQTT core client with publish method
7
- * @param topic - MQTT topic to publish to
8
- * @param payload - Refresh payload object (will be JSON stringified)
9
- * @param refreshRequestId - Request ID for logging
10
- * @param logger - Logger instance
11
- * @returns Returns true on success, false on ECONNRESET (buffered), throws on other errors
12
- */
13
1
  export async function publishRefreshRequestWithErrorHandling(coordinatorCore, topic, payload, refreshRequestId, logger) {
14
2
  try {
15
3
  await coordinatorCore.publish({
@@ -18,33 +6,25 @@ export async function publishRefreshRequestWithErrorHandling(coordinatorCore, to
18
6
  qos: 1,
19
7
  retain: false
20
8
  });
21
- // QPA-CLI-10: Telemetry logs default to debug for quiet mode
22
9
  logger.debug('jwt.refresh.request.sent', { refreshRequestId });
23
10
  return true;
24
11
  }
25
12
  catch (caught) {
26
13
  const publishError = caught;
27
- // Check if this is a connection reset error (transient condition)
28
14
  const isConnectionError = publishError?.code === 'ECONNRESET' ||
29
- publishError?.errno === -54 || // macOS/Linux ECONNRESET errno
15
+ publishError?.errno === -54 ||
30
16
  publishError?.message?.includes('ECONNRESET') ||
31
17
  publishError?.message?.includes('Connection closed') ||
32
18
  publishError?.message?.includes('connection closed');
33
19
  if (isConnectionError) {
34
- // QPA-CLI-09: Return false instead of throwing - refresh is buffered, CLI stays alive
35
- // The MqttControlPlaneClient will detect the disconnect and set refreshPending=true
36
- // The re-arm logic will retry after reconnect
37
- // QPA-CLI-10: Telemetry logs default to debug for quiet mode
38
20
  logger.debug('jwt.refresh.publish.econnreset', {
39
21
  refreshRequestId,
40
22
  error: publishError?.message || String(publishError),
41
23
  code: publishError?.code,
42
24
  action: 'buffered_for_retry'
43
25
  });
44
- // Return false to indicate buffered (don't throw - prevents "Unexpected error" log)
45
26
  return false;
46
27
  }
47
- // For non-connection errors (e.g., JSON parse, invalid payload), rethrow
48
28
  logger.error('jwt.refresh.publish.error', {
49
29
  refreshRequestId,
50
30
  error: publishError?.message || String(publishError),
@@ -53,7 +33,6 @@ export async function publishRefreshRequestWithErrorHandling(coordinatorCore, to
53
33
  throw caught;
54
34
  }
55
35
  }
56
- /** Expiry (seconds since epoch) of a JWT, or null; no signature check. */
57
36
  export function jwtExpOf(jwt) {
58
37
  try {
59
38
  const part = String(jwt).split('.')[1];
@@ -1,8 +1,3 @@
1
- // Story 12.1 (step 2b; TypeScript in r3): lifecycle events for tunnels opened through @asyx/tunnel-core.
2
- // Operations (connect, open, close) are promises; what happens after a tunnel is open is events.
3
- // A Node EventEmitter crashes the process when 'error' is emitted with no listener, which c2
4
- // forbids, so this emitter refuses that event name: a tunnel that ends for good emits a final
5
- // 'state' event with state 'closed' and the typed error instead.
6
1
  import { EventEmitter } from 'node:events';
7
2
  export const STATES = Object.freeze(['opening', 'live', 'reconnecting', 'renewed', 'closed']);
8
3
  export class LifecycleEmitter extends EventEmitter {
@@ -12,17 +7,15 @@ export class LifecycleEmitter extends EventEmitter {
12
7
  throw new TypeError("LifecycleEmitter never emits 'error'; use setState('closed', { error })");
13
8
  return super.emit(name, ...args);
14
9
  }
15
- /** Change state and tell listeners. `detail` may carry `error` (on 'closed'), relay ids, etc. */
16
10
  setState(state, detail = {}) {
17
11
  if (!STATES.includes(state))
18
12
  throw new TypeError(`unknown tunnel state: ${state}`);
19
13
  if (this.state === 'closed')
20
- return; // closed is final
14
+ return;
21
15
  this.state = state;
22
16
  super.emit('state', { state, ...detail });
23
17
  super.emit(state, detail);
24
18
  }
25
- /** A non-fatal problem the caller may want to show (the core never prints). */
26
19
  warn(code, detail = {}) {
27
20
  super.emit('warning', { code, ...detail });
28
21
  }
@@ -1,23 +1,10 @@
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
1
  export class AwaiterMap {
9
2
  constructor(maxSize = 100, logger = null) {
10
3
  this.maxSize = maxSize;
11
4
  this.awaiters = new Map();
12
5
  this.nextId = 1;
13
- this.logger = logger; // QPA-CLI-10: Optional logger for quiet mode
6
+ this.logger = logger;
14
7
  }
15
- /**
16
- * Register an awaiter that will be resolved when a message matches the criteria
17
- * @param {Function} criteria - Function that returns true if message matches
18
- * @param {number} timeoutMs - Timeout in milliseconds
19
- * @returns {Promise} Promise that resolves with the matching message
20
- */
21
8
  register(criteria, timeoutMs = 5000) {
22
9
  if (this.awaiters.size >= this.maxSize) {
23
10
  throw new Error(`AwaiterMap is at capacity (${this.maxSize}). Cannot register more awaiters.`);
@@ -36,7 +23,6 @@ export class AwaiterMap {
36
23
  awaiter.resolve = resolve;
37
24
  awaiter.reject = reject;
38
25
  });
39
- // Set up timeout
40
26
  awaiter.timeoutId = setTimeout(() => {
41
27
  this.awaiters.delete(id);
42
28
  awaiter.reject(new Error(`Awaiter ${id} timed out after ${timeoutMs}ms`));
@@ -44,18 +30,11 @@ export class AwaiterMap {
44
30
  this.awaiters.set(id, awaiter);
45
31
  return promise;
46
32
  }
47
- /**
48
- * Process an incoming message against all registered awaiters
49
- * @param {Object} message - Message object with topic and payload
50
- * @returns {boolean} True if any awaiter was resolved
51
- */
52
33
  processMessage(message) {
53
34
  let resolved = false;
54
- // Log open_ack messages for debugging awaiter matching
55
35
  const isOpenAck = message.payload?.type === 'open_ack';
56
36
  const requestId = message.payload?.requestId;
57
37
  if (isOpenAck && requestId) {
58
- // QPA-CLI-10: Use logger at debug level for quiet mode
59
38
  if (this.logger) {
60
39
  this.logger.debug('awaiter.open_ack.received', {
61
40
  requestId,
@@ -69,7 +48,6 @@ export class AwaiterMap {
69
48
  try {
70
49
  const matched = awaiter.criteria(message);
71
50
  if (isOpenAck && requestId) {
72
- // QPA-CLI-10: Use logger at debug level for quiet mode
73
51
  if (this.logger) {
74
52
  this.logger.debug('awaiter.open_ack.checked', {
75
53
  requestId,
@@ -80,13 +58,11 @@ export class AwaiterMap {
80
58
  }
81
59
  }
82
60
  if (matched) {
83
- // Clear timeout and resolve
84
61
  clearTimeout(awaiter.timeoutId);
85
62
  this.awaiters.delete(id);
86
63
  awaiter.resolve(message);
87
64
  resolved = true;
88
65
  if (isOpenAck && requestId) {
89
- // QPA-CLI-10: Use logger at debug level for quiet mode
90
66
  if (this.logger) {
91
67
  this.logger.debug('awaiter.open_ack.resolved', {
92
68
  requestId,
@@ -98,13 +74,11 @@ export class AwaiterMap {
98
74
  }
99
75
  }
100
76
  catch (error) {
101
- // Criteria function threw an error - reject and clean up
102
77
  clearTimeout(awaiter.timeoutId);
103
78
  this.awaiters.delete(id);
104
79
  awaiter.reject(error);
105
80
  resolved = true;
106
81
  if (isOpenAck && requestId) {
107
- // QPA-CLI-10: Use logger at debug level for quiet mode
108
82
  if (this.logger) {
109
83
  this.logger.debug('awaiter.open_ack.criteria_error', {
110
84
  requestId,
@@ -117,7 +91,6 @@ export class AwaiterMap {
117
91
  }
118
92
  }
119
93
  if (isOpenAck && requestId && !resolved) {
120
- // QPA-CLI-10: Use logger at debug level for quiet mode (no_match is expected when awaiter already resolved)
121
94
  if (this.logger) {
122
95
  this.logger.debug('awaiter.open_ack.no_match', {
123
96
  requestId,
@@ -130,10 +103,6 @@ export class AwaiterMap {
130
103
  }
131
104
  return resolved;
132
105
  }
133
- /**
134
- * Get current statistics about the awaiter map
135
- * @returns {Object} Statistics object
136
- */
137
106
  getStats() {
138
107
  const now = Date.now();
139
108
  const ages = Array.from(this.awaiters.values()).map(a => now - a.createdAt);
@@ -145,11 +114,6 @@ export class AwaiterMap {
145
114
  averageAge: ages.length > 0 ? ages.reduce((a, b) => a + b, 0) / ages.length : 0
146
115
  };
147
116
  }
148
- /**
149
- * Cancel awaiters that match a test criteria
150
- * @param {Function} testCriteria - Function that returns true if an awaiter should be cancelled
151
- * @returns {number} Number of awaiters cancelled
152
- */
153
117
  cancelByCriteria(testCriteria) {
154
118
  let cancelled = 0;
155
119
  for (const [id, awaiter] of this.awaiters) {
@@ -162,15 +126,11 @@ export class AwaiterMap {
162
126
  }
163
127
  }
164
128
  catch (error) {
165
- // Test criteria threw an error - skip this awaiter
166
129
  continue;
167
130
  }
168
131
  }
169
132
  return cancelled;
170
133
  }
171
- /**
172
- * Clear all awaiters (for cleanup)
173
- */
174
134
  clear() {
175
135
  for (const [id, awaiter] of this.awaiters) {
176
136
  clearTimeout(awaiter.timeoutId);
@@ -178,12 +138,6 @@ export class AwaiterMap {
178
138
  }
179
139
  this.awaiters.clear();
180
140
  }
181
- /**
182
- * Create a criteria function for session ID matching (backward compatibility)
183
- * @param {string} sessionId - Session ID to match
184
- * @param {string} expectedTopic - Expected topic pattern
185
- * @returns {Function} Criteria function
186
- */
187
141
  static createSessionIdCriteria(sessionId, expectedTopic) {
188
142
  return (message) => {
189
143
  if (message.topic !== expectedTopic) {
@@ -201,12 +155,6 @@ export class AwaiterMap {
201
155
  }
202
156
  };
203
157
  }
204
- /**
205
- * Create a criteria function for correlation ID matching (future use)
206
- * @param {string} correlationId - Correlation ID to match
207
- * @param {string} expectedTopic - Expected topic pattern
208
- * @returns {Function} Criteria function
209
- */
210
158
  static createCorrelationIdCriteria(correlationId, expectedTopic) {
211
159
  return (message) => {
212
160
  if (message.topic !== expectedTopic) {