asyx 0.2.4 → 0.3.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.
@@ -0,0 +1,68 @@
1
+ // UDP-S13: Target host validation with DNS resolution and loopback-only enforcement
2
+ import dns from 'node:dns';
3
+ import { promisify } from 'node:util';
4
+
5
+ const dnsLookup = promisify(dns.lookup);
6
+
7
+ /**
8
+ * Validate that target host resolves only to loopback addresses.
9
+ * @param {string} targetHost - Hostname or IP address to validate
10
+ * @returns {Promise<{isLoopback: boolean, resolvedIPs: string[]}>}
11
+ */
12
+ export async function validateTargetHost(targetHost) {
13
+ const normalizedHost = targetHost.toLowerCase().trim();
14
+
15
+ // Direct loopback IPs are always valid
16
+ if (normalizedHost === '127.0.0.1' || normalizedHost === '::1' || normalizedHost === 'localhost') {
17
+ return { isLoopback: true, resolvedIPs: [normalizedHost] };
18
+ }
19
+
20
+ // Try to resolve the hostname
21
+ try {
22
+ // dns.lookup resolves to the first IP (IPv4 or IPv6)
23
+ // We need to check all addresses, so we'll use dns.resolve4 and dns.resolve6
24
+ const resolve4 = promisify(dns.resolve4);
25
+ const resolve6 = promisify(dns.resolve6);
26
+
27
+ const ipv4Addresses = [];
28
+ const ipv6Addresses = [];
29
+
30
+ try {
31
+ const v4 = await resolve4(normalizedHost, { all: true });
32
+ ipv4Addresses.push(...v4.map(addr => addr.address));
33
+ } catch (e) {
34
+ // No IPv4 addresses
35
+ }
36
+
37
+ try {
38
+ const v6 = await resolve6(normalizedHost, { all: true });
39
+ ipv6Addresses.push(...v6.map(addr => addr.address));
40
+ } catch (e) {
41
+ // No IPv6 addresses
42
+ }
43
+
44
+ const allResolved = [...ipv4Addresses, ...ipv6Addresses];
45
+
46
+ if (allResolved.length === 0) {
47
+ // Couldn't resolve - treat as invalid
48
+ return { isLoopback: false, resolvedIPs: [] };
49
+ }
50
+
51
+ // Check if all resolved IPs are loopback
52
+ const loopbackIPs = ['127.0.0.1', '::1'];
53
+ const isAllLoopback = allResolved.every(ip => {
54
+ // Check exact match
55
+ if (loopbackIPs.includes(ip)) return true;
56
+ // Check IPv4 loopback range (127.0.0.0/8)
57
+ if (ip.startsWith('127.')) return true;
58
+ // Check IPv6 loopback
59
+ if (ip === '::1' || ip.toLowerCase() === '::1') return true;
60
+ return false;
61
+ });
62
+
63
+ return { isLoopback: isAllLoopback, resolvedIPs: allResolved };
64
+ } catch (error) {
65
+ // DNS resolution failed - throw so caller can handle it with proper error message
66
+ throw new Error(`DNS resolution failed for "${targetHost}": ${error.message}`);
67
+ }
68
+ }
package/src/lib/device.js CHANGED
@@ -3,7 +3,26 @@ import { homedir } from "node:os";
3
3
  import { join } from "node:path";
4
4
  import crypto from "node:crypto";
5
5
 
6
- const DIR = join(homedir(), ".asyx");
6
+ function resolveConfigDir() {
7
+ // Allow explicit override (useful for Windows/packaged builds)
8
+ if (process.env.ASYX_CONFIG_DIR && process.env.ASYX_CONFIG_DIR.trim()) {
9
+ return process.env.ASYX_CONFIG_DIR.trim();
10
+ }
11
+
12
+ // Standard resolution via os.homedir()
13
+ const home = homedir();
14
+ if (home) return join(home, ".asyx");
15
+
16
+ // Defensive fallbacks for Windows in case os.homedir() cannot resolve
17
+ if (process.env.USERPROFILE) return join(process.env.USERPROFILE, ".asyx");
18
+ if (process.env.HOMEDRIVE && process.env.HOMEPATH) {
19
+ return join(`${process.env.HOMEDRIVE}${process.env.HOMEPATH}`, ".asyx");
20
+ }
21
+
22
+ throw new Error("Unable to determine Asyx config directory (missing home directory)");
23
+ }
24
+
25
+ const DIR = resolveConfigDir();
7
26
  const FILE = join(DIR, "device.json");
8
27
 
9
28
  export function loadOrCreateClientId() {
@@ -16,3 +35,9 @@ export function loadOrCreateClientId() {
16
35
  writeFileSync(FILE, JSON.stringify({ clientId }, null, 2));
17
36
  return clientId;
18
37
  }
38
+
39
+ export function resetClientId() {
40
+ if (existsSync(FILE)) {
41
+ writeFileSync(FILE, JSON.stringify({}, null, 2));
42
+ }
43
+ }
@@ -0,0 +1,260 @@
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
+ import { createRemoteJWKSet, jwtVerify } from 'jose';
5
+ import logger from './logger.js';
6
+
7
+ // JWKS URL configuration (environment-specific)
8
+ const JWKS_URL_PROD = 'https://auth.asyx.ai/.well-known/jwks.json';
9
+ const JWKS_URL_DEV = 'https://auth.dev.asyx.ai/.well-known/jwks.json';
10
+
11
+ // Expected issuer and audience
12
+ const EXPECTED_ISSUER = 'https://auth.asyx.ai';
13
+ const EXPECTED_AUDIENCE = 'tunnel-relay';
14
+
15
+ // Singleton JWKS cache (shared across all tunnel instances)
16
+ let jwksCache = null;
17
+ let jwksInitialized = false;
18
+ let jwksInitPromise = null;
19
+
20
+ /**
21
+ * Initialize JWKS cache (lazy, on first use)
22
+ * @returns {Promise<void>}
23
+ */
24
+ async function initializeJWKS() {
25
+ if (jwksInitialized) {
26
+ return;
27
+ }
28
+
29
+ if (jwksInitPromise) {
30
+ return jwksInitPromise;
31
+ }
32
+
33
+ jwksInitPromise = (async () => {
34
+ try {
35
+ // Determine JWKS URL from environment
36
+ const env = process.env.ASYX_ENV || process.env.NODE_ENV || 'prod';
37
+ const jwksUrl = env === 'dev' || env === 'development' ? JWKS_URL_DEV : JWKS_URL_PROD;
38
+
39
+ // Allow override via environment variable
40
+ const jwksUrlOverride = process.env.ASYX_JWKS_URL;
41
+ const finalJwksUrl = jwksUrlOverride || jwksUrl;
42
+
43
+ logger.debug('jwt.jwks.initializing', { jwksUrl: finalJwksUrl, env });
44
+
45
+ // Create remote JWKS set (jose handles caching and refresh)
46
+ jwksCache = createRemoteJWKSet(new URL(finalJwksUrl));
47
+
48
+ // Test fetch to ensure JWKS is available (fail fast if not)
49
+ // jose's createRemoteJWKSet doesn't fetch immediately, so we need to trigger a fetch
50
+ // We'll do this on first verification attempt
51
+
52
+ jwksInitialized = true;
53
+ logger.info('jwt.jwks.initialized', { jwksUrl: finalJwksUrl });
54
+ } catch (error) {
55
+ jwksInitPromise = null;
56
+ logger.error('jwt.jwks.init_failed', { error: error.message });
57
+ throw error;
58
+ }
59
+ })();
60
+
61
+ return jwksInitPromise;
62
+ }
63
+
64
+ /**
65
+ * Verify assignment JWT with JWKS signature verification
66
+ * AC1.4/AC5.1: Validates signature, iss, aud, exp, relayId, protocol, tunnelMode, leaseId
67
+ * @param {string} token - JWT token to verify
68
+ * @param {Object} expectedClaims - Expected claim values
69
+ * @param {string} expectedClaims.relayId - Expected relayId
70
+ * @param {string} expectedClaims.protocol - Expected protocol ('udp' | 'tcp')
71
+ * @param {string} expectedClaims.tunnelMode - Expected tunnelMode ('udpWs-v1' | 'tcpWs-v1')
72
+ * @param {string} [expectedClaims.leaseId] - Expected leaseId (optional)
73
+ * @returns {Promise<Object>} Verified JWT payload
74
+ * @throws {Error} If JWT verification fails (signature, claims, or JWKS unavailable)
75
+ */
76
+ export async function verifyAssignmentJWT(token, expectedClaims = {}) {
77
+ // Initialize JWKS if not already done
78
+ if (!jwksInitialized) {
79
+ await initializeJWKS();
80
+ }
81
+
82
+ // AC1.4/AC5.1: Fail fast if JWKS is not available
83
+ if (!jwksCache) {
84
+ const error = new Error('JWKS not available - cannot verify assignment JWT');
85
+ error.code = 'JWKS_UNAVAILABLE';
86
+ logger.error('jwt.verification.jwks_unavailable', {
87
+ tokenLength: token?.length || 0,
88
+ expectedRelayId: expectedClaims.relayId
89
+ });
90
+ throw error;
91
+ }
92
+
93
+ try {
94
+ // Verify JWT signature and decode payload using JWKS
95
+ // jwtVerify automatically:
96
+ // - Fetches JWKS if not cached
97
+ // - Verifies signature using the key identified by 'kid' in JWT header
98
+ // - Validates exp, nbf, iat if present
99
+ const { payload, protectedHeader } = await jwtVerify(token, jwksCache, {
100
+ issuer: EXPECTED_ISSUER,
101
+ audience: EXPECTED_AUDIENCE,
102
+ // jose validates exp automatically with clock skew tolerance
103
+ // We'll get ERR_JWT_EXPIRED if expired, which we handle below
104
+ });
105
+
106
+ logger.debug('jwt.verification.signature_verified', {
107
+ kid: protectedHeader.kid,
108
+ alg: protectedHeader.alg,
109
+ relayId: payload.relayId,
110
+ protocol: payload.protocol,
111
+ tunnelMode: payload.tunnelMode
112
+ });
113
+
114
+ // AC5.1: Validate relayId matches expected
115
+ if (expectedClaims.relayId && payload.relayId !== expectedClaims.relayId) {
116
+ const error = new Error(`JWT relayId mismatch: ${payload.relayId} !== ${expectedClaims.relayId}`);
117
+ error.code = 'JWT_RELAYID_MISMATCH';
118
+ logger.error('jwt.verification.relayid_mismatch', {
119
+ expected: expectedClaims.relayId,
120
+ actual: payload.relayId,
121
+ leaseId: payload.leaseId
122
+ });
123
+ throw error;
124
+ }
125
+
126
+ // AC1.4: Validate protocol
127
+ if (expectedClaims.protocol && payload.protocol !== expectedClaims.protocol) {
128
+ const error = new Error(`JWT protocol mismatch: ${payload.protocol} !== ${expectedClaims.protocol}`);
129
+ error.code = 'JWT_PROTOCOL_MISMATCH';
130
+ logger.error('jwt.verification.protocol_mismatch', {
131
+ expected: expectedClaims.protocol,
132
+ actual: payload.protocol
133
+ });
134
+ throw error;
135
+ }
136
+
137
+ // AC1.4: Validate tunnelMode
138
+ if (expectedClaims.tunnelMode && payload.tunnelMode !== expectedClaims.tunnelMode) {
139
+ const error = new Error(`JWT tunnelMode mismatch: ${payload.tunnelMode} !== ${expectedClaims.tunnelMode}`);
140
+ error.code = 'JWT_TUNNELMODE_MISMATCH';
141
+ logger.error('jwt.verification.tunnelmode_mismatch', {
142
+ expected: expectedClaims.tunnelMode,
143
+ actual: payload.tunnelMode
144
+ });
145
+ throw error;
146
+ }
147
+
148
+ // AC5.1: Validate leaseId if provided
149
+ if (expectedClaims.leaseId && payload.leaseId && payload.leaseId !== expectedClaims.leaseId) {
150
+ const error = new Error(`JWT leaseId mismatch: ${payload.leaseId} !== ${expectedClaims.leaseId}`);
151
+ error.code = 'JWT_LEASEID_MISMATCH';
152
+ logger.error('jwt.verification.leaseid_mismatch', {
153
+ expected: expectedClaims.leaseId,
154
+ actual: payload.leaseId
155
+ });
156
+ throw error;
157
+ }
158
+
159
+ // AC1.4: Validate required claims are present
160
+ if (!payload.relayId) {
161
+ const error = new Error('Missing relayId in JWT payload');
162
+ error.code = 'JWT_MISSING_RELAYID';
163
+ throw error;
164
+ }
165
+
166
+ if (!payload.protocol) {
167
+ const error = new Error('Missing protocol in JWT payload');
168
+ error.code = 'JWT_MISSING_PROTOCOL';
169
+ throw error;
170
+ }
171
+
172
+ if (!payload.tunnelMode) {
173
+ const error = new Error('Missing tunnelMode in JWT payload');
174
+ error.code = 'JWT_MISSING_TUNNELMODE';
175
+ throw error;
176
+ }
177
+
178
+ logger.debug('jwt.verification.success', {
179
+ relayId: payload.relayId,
180
+ protocol: payload.protocol,
181
+ tunnelMode: payload.tunnelMode,
182
+ leaseId: payload.leaseId
183
+ });
184
+
185
+ return payload;
186
+ } catch (error) {
187
+ // Map jose errors to our error codes
188
+ if (error.code === 'ERR_JWKS_TIMEOUT' || error.code === 'ERR_JWKS_MULTIPLE_MATCHING_KEYS') {
189
+ const jwksError = new Error(`JWKS error: ${error.message}`);
190
+ jwksError.code = 'JWKS_ERROR';
191
+ logger.error('jwt.verification.jwks_error', {
192
+ error: error.message,
193
+ code: error.code
194
+ });
195
+ throw jwksError;
196
+ }
197
+
198
+ if (error.code === 'ERR_JWT_EXPIRED') {
199
+ const expiredError = new Error('JWT expired');
200
+ expiredError.code = 'JWT_EXPIRED';
201
+ logger.error('jwt.verification.expired', {
202
+ exp: error.claims?.exp,
203
+ now: Math.floor(Date.now() / 1000)
204
+ });
205
+ throw expiredError;
206
+ }
207
+
208
+ if (error.code === 'ERR_JWT_CLAIM_VALIDATION_FAILED') {
209
+ // This could be issuer or audience mismatch
210
+ const claimError = new Error(`JWT claim validation failed: ${error.message}`);
211
+ claimError.code = 'JWT_CLAIM_INVALID';
212
+ logger.error('jwt.verification.claim_failed', {
213
+ error: error.message,
214
+ claim: error.claim
215
+ });
216
+ throw claimError;
217
+ }
218
+
219
+ if (error.code === 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED') {
220
+ const sigError = new Error('JWT signature verification failed');
221
+ sigError.code = 'JWT_SIGNATURE_INVALID';
222
+ logger.error('jwt.verification.signature_failed', {
223
+ error: error.message
224
+ });
225
+ throw sigError;
226
+ }
227
+
228
+ // Re-throw our custom errors
229
+ if (error.code && error.code.startsWith('JWT_') || error.code === 'JWKS_UNAVAILABLE' || error.code === 'JWKS_ERROR') {
230
+ throw error;
231
+ }
232
+
233
+ // Unknown error - wrap it
234
+ const unknownError = new Error(`JWT verification failed: ${error.message}`);
235
+ unknownError.code = 'JWT_VERIFICATION_FAILED';
236
+ unknownError.originalError = error;
237
+ logger.error('jwt.verification.unknown_error', {
238
+ error: error.message,
239
+ code: error.code
240
+ });
241
+ throw unknownError;
242
+ }
243
+ }
244
+
245
+ /**
246
+ * Check if JWKS is available (for health checks)
247
+ * @returns {boolean} True if JWKS is initialized
248
+ */
249
+ export function isJWKSAvailable() {
250
+ return jwksInitialized && jwksCache !== null;
251
+ }
252
+
253
+ /**
254
+ * Reset JWKS cache (for testing or re-initialization)
255
+ */
256
+ export function resetJWKS() {
257
+ jwksCache = null;
258
+ jwksInitialized = false;
259
+ jwksInitPromise = null;
260
+ }
@@ -32,6 +32,20 @@ const registry = {
32
32
  },
33
33
 
34
34
  async open_ack(e) {
35
+ // TPB-12: Route by instanceId - get instance context from dispatcher
36
+ const instanceId = e._instanceId;
37
+ const instanceContext = e._instanceContext;
38
+
39
+ if (!instanceId || !instanceContext) {
40
+ logger.warn('open_ack.unknown_instance', {
41
+ requestId: e.requestId,
42
+ instanceId: e.instanceId || e.data?.instanceId || null,
43
+ leaseId: e.correlationId || e.data?.leaseId || null,
44
+ note: 'Event dropped - no matching instance context'
45
+ });
46
+ return;
47
+ }
48
+
35
49
  // Normalize legacy format to canonical format
36
50
  let data = e.data;
37
51
 
@@ -55,26 +69,46 @@ const registry = {
55
69
  // Suppress QP: enabled and Ack received messages - they'll be consolidated in final tunnel.active message
56
70
  const quickpassSlug = data.quickpass?.slug || null;
57
71
  if (quickpassSlug) {
58
- logger.info("qp.enabled", { group: quickpassSlug });
72
+ logger.info("qp.enabled", {
73
+ group: quickpassSlug,
74
+ instanceId,
75
+ tunnelType: instanceContext.tunnelType
76
+ });
59
77
  }
60
78
 
61
79
  // Build relay URL with fallbacks for missing fields
62
80
  // TCP-S4: Add fallbacks to prevent malformed URLs if TCP assignments omit fields
81
+ // UDP-S1: Add UDP support
63
82
  const proto = data.assignment?.proto || 'wss';
64
83
  const fqdn = data.assignment?.fqdn || data.fqdn || 'relay.unknown';
65
84
  // TCP-S4: Always use /tcp for TCP tunnels, /agent for HTTP tunnels
66
- // Detect TCP by checking for publicPort (TCP-specific) or proto === 'tcp'
67
- const isTcpTunnel = data.assignment?.publicPort !== undefined ||
68
- data.assignment?.proto === 'tcp' ||
69
- data.publicPort !== undefined;
70
- // Always override path for TCP tunnels, regardless of what Lambda returns
71
- const path = isTcpTunnel ? '/tcp' : (data.assignment?.path || '/agent');
85
+ // UDP-S1: Always use /udp for UDP tunnels
86
+ // Detect tunnel type by checking for publicPort (TCP/UDP-specific) or proto/tunnelMode
87
+ const isTcpTunnel = (data.assignment?.publicPort !== undefined ||
88
+ data.assignment?.proto === 'tcp' ||
89
+ data.publicPort !== undefined) &&
90
+ data.assignment?.tunnelMode !== 'udpWs-v1' &&
91
+ data.assignment?.protocol !== 'udp';
92
+ const isUdpTunnel = data.assignment?.tunnelMode === 'udpWs-v1' ||
93
+ data.assignment?.protocol === 'udp' ||
94
+ instanceContext.tunnelType === 'udp';
95
+ // Always override path for TCP/UDP tunnels, regardless of what Lambda returns
96
+ let path;
97
+ if (isUdpTunnel) {
98
+ path = '/udp';
99
+ } else if (isTcpTunnel) {
100
+ path = '/tcp';
101
+ } else {
102
+ path = data.assignment?.path || '/agent';
103
+ }
72
104
  const url = `${proto}://${fqdn}${path}`;
73
105
 
74
106
  // Log warning if fallbacks were used
75
107
  if (!data.assignment?.proto || !data.assignment?.fqdn || !data.assignment?.path) {
76
108
  logger.warn('open_ack.relay_url_fallback', {
77
109
  requestId: e.requestId,
110
+ instanceId,
111
+ tunnelType: instanceContext.tunnelType,
78
112
  proto: data.assignment?.proto || 'missing',
79
113
  fqdn: data.assignment?.fqdn || 'missing',
80
114
  path: data.assignment?.path || 'missing',
@@ -84,10 +118,15 @@ const registry = {
84
118
 
85
119
  // Store assignment in memory (never to disk)
86
120
  const leaseId = e.correlationId || data.leaseId || data.assignment?.leaseId || null;
87
- logger.debug("open_ack.lease_id", { requestId: e.requestId, leaseId });
121
+ logger.debug("open_ack.lease_id", {
122
+ requestId: e.requestId,
123
+ instanceId,
124
+ leaseId,
125
+ tunnelType: instanceContext.tunnelType
126
+ });
88
127
 
89
128
  // Check if this is a refresh (existing assignment) or initial connection
90
- const existingAssignment = getAssignment();
129
+ const existingAssignment = instanceContext.getAssignment(instanceId);
91
130
  const isRefresh = existingAssignment !== null;
92
131
 
93
132
  // TCP-S3: Extract TCP-specific fields from assignment
@@ -104,17 +143,26 @@ const registry = {
104
143
  if (!jwt) {
105
144
  logger.error('open_ack.missing_jwt', {
106
145
  requestId: e.requestId,
146
+ instanceId,
147
+ tunnelType: instanceContext.tunnelType,
107
148
  hasAssignment: !!data.assignment,
108
149
  hasDataJwt: !!data.jwt
109
150
  });
110
151
  throw new Error('Missing JWT in assignment');
111
152
  }
112
153
 
113
- setAssignment({
154
+ // UDP-S1: Extract UDP-specific fields from assignment
155
+ const tunnelMode = data.assignment?.tunnelMode || data.tunnelMode || null;
156
+ const protocol = data.assignment?.protocol || data.protocol || null;
157
+ const assignmentJwt = data.assignment?.assignmentJwt || data.assignmentJwt || jwt; // UDP-S1: Use assignmentJwt if available
158
+
159
+ // TPB-12: Use per-instance setAssignment
160
+ instanceContext.setAssignment(instanceId, {
114
161
  requestId: e.requestId,
115
162
  relayId: data.relayId,
116
163
  relayUrl: url,
117
- jwt, // Stored in memory only
164
+ jwt: assignmentJwt, // UDP-S1: Use assignmentJwt if available, fallback to jwt
165
+ assignmentJwt: assignmentJwt, // UDP-S1: Store assignmentJwt separately
118
166
  leaseMs: data.leaseMs,
119
167
  leaseId,
120
168
  quickpassSlug, // QPA-CLI-11: Store QuickPass slug for vault UX messaging
@@ -125,11 +173,17 @@ const registry = {
125
173
  // E3-S8: Store SRV provisioning status
126
174
  srvProvisioned,
127
175
  srvFqdn,
128
- warnings
176
+ warnings,
177
+ // UDP-S1: Store UDP-specific fields
178
+ tunnelMode,
179
+ protocol
129
180
  });
130
181
 
131
182
  logger.debug("open_ack.assignment_stored", {
132
- requestId: e.requestId,
183
+ requestId: e.requestId,
184
+ instanceId,
185
+ leaseId,
186
+ tunnelType: instanceContext.tunnelType,
133
187
  isRefresh,
134
188
  quickpassSlug,
135
189
  tcpAliasFqdn,
@@ -141,6 +195,8 @@ const registry = {
141
195
  if (warnings.includes('TCP_ALIAS_UNAVAILABLE') || warnings.some(w => w.code === 'TCP_ALIAS_UNAVAILABLE')) {
142
196
  logger.warn('tcp.alias.unavailable', {
143
197
  requestId: e.requestId,
198
+ instanceId,
199
+ tunnelType: instanceContext.tunnelType,
144
200
  fqdn,
145
201
  publicPort
146
202
  });
@@ -155,6 +211,17 @@ const registry = {
155
211
  const d = e.data;
156
212
  const reason = d.reason ? ` (${d.reason})` : "";
157
213
 
214
+ // TPB-12: Clean up expected requestId on rejection (prevents map leak)
215
+ const instanceId = e._instanceId || null;
216
+ if (instanceId) {
217
+ try {
218
+ const { clearExpectedRequestId } = await import("../../state/instance-registry.js");
219
+ clearExpectedRequestId(instanceId);
220
+ } catch (err) {
221
+ // Ignore cleanup errors (module may not be available in all contexts)
222
+ }
223
+ }
224
+
158
225
  // QPA-04: Handle invalid_secgroup rejection
159
226
  if (d.reason === 'invalid_secgroup' || d.reason === 'INVALID_SECGROUP') {
160
227
  // Extract slug from requestId context or data if available