asyx 0.10.1 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/AGENTS.md +42 -0
  2. package/bin/asyx.js +1 -1
  3. package/package.json +3 -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 +11 -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 +14 -67
  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,137 +1,65 @@
1
- /**
2
- * MqttControlPlaneTransport
3
- *
4
- * Adapter that wraps MqttControlPlaneClient to implement the Transport interface
5
- * required by MqttCore. This allows us to use MqttControlPlaneClient for connection
6
- * management while still using MqttCore for the higher-level API.
7
- */
8
1
  import { MqttControlPlaneClient } from './MqttControlPlaneClient.js';
9
- /**
10
- * Transport adapter that wraps MqttControlPlaneClient.
11
- * Implements the Transport interface from @asyx/mqtt-core.
12
- */
13
2
  export class MqttControlPlaneTransport {
14
- /**
15
- * @param {MqttControlPlaneClient} client
16
- */
17
3
  constructor(client) {
18
4
  this.client = client;
19
5
  this._messageHandler = null;
20
6
  this._connectHandler = null;
21
7
  this._disconnectHandler = null;
22
- // Store original callbacks to preserve them
23
8
  const originalOnConnected = this.client.onConnected;
24
9
  const originalOnOffline = this.client.onOffline;
25
- // Wire up handlers when client connects (chain with existing callbacks)
26
10
  this.client.onConnected = async (mqttClient) => {
27
- // Wire up message handler (setMessageHandler ensures it's wired on reconnect)
28
11
  if (this._messageHandler) {
29
12
  this.client.setMessageHandler(this._messageHandler);
30
13
  }
31
- // Call original callback (set by tunnel.js)
32
14
  if (originalOnConnected) {
33
15
  await originalOnConnected(mqttClient);
34
16
  }
35
- // Call Transport connect handler (for MqttCore)
36
17
  if (this._connectHandler) {
37
18
  this._connectHandler();
38
19
  }
39
20
  };
40
- // Wire up disconnect handler (chain with existing callbacks)
41
21
  this.client.onOffline = (reason) => {
42
- // Call original callback (set by tunnel.js)
43
22
  if (originalOnOffline) {
44
23
  originalOnOffline(reason);
45
24
  }
46
- // Call Transport disconnect handler (for MqttCore)
47
25
  if (this._disconnectHandler) {
48
26
  this._disconnectHandler(new Error(reason));
49
27
  }
50
28
  };
51
29
  }
52
- /**
53
- * Transport interface: connect
54
- * @param {any} opts - ConnectOptions (ignored, client manages its own connection)
55
- * @returns {Promise<void>}
56
- */
57
30
  async connect(opts) {
58
- // Client manages its own connection, just ensure it's connected
59
31
  if (!this.client.isOnline()) {
60
32
  await this.client.connect();
61
33
  }
62
34
  }
63
- /**
64
- * Transport interface: end
65
- * @returns {Promise<void>}
66
- */
67
35
  async end() {
68
36
  return this.client.disconnect();
69
37
  }
70
- /**
71
- * Transport interface: publish
72
- * @param {{topic: string, payload: string | Buffer | Uint8Array, qos?: 0 | 1, retain?: boolean}} p
73
- * @returns {Promise<void>}
74
- */
75
38
  async publish(p) {
76
39
  const payload = p.payload instanceof Uint8Array
77
40
  ? Buffer.from(p.payload)
78
41
  : (typeof p.payload === 'string' ? p.payload : p.payload);
79
42
  return this.client.publish(p.topic, payload, { qos: p.qos ?? 0, retain: p.retain ?? false });
80
43
  }
81
- /**
82
- * Transport interface: subscribe
83
- * @param {string} topic
84
- * @param {0 | 1} [qos=0]
85
- * @returns {Promise<{topic: string, qos: 0 | 1}>}
86
- */
87
44
  async subscribe(topic, qos = 0) {
88
- // Story 12.1 r3 (type check): the client resolves with nothing, not the {topic, qos} SubAck the
89
- // mqtt-core Transport interface declares; no caller uses the result today. Kept as is (CLI unchanged).
90
- // @ts-expect-error see above
91
45
  return this.client.subscribe(topic, qos);
92
46
  }
93
- /**
94
- * Transport interface: unsubscribe
95
- * @param {string} topic
96
- * @returns {Promise<void>}
97
- */
98
47
  async unsubscribe(topic) {
99
- // Story 12.1 r3 (type check): MqttControlPlaneClient has no unsubscribe(), so this would throw;
100
- // nothing calls it today (the tunnel never unsubscribes). Recorded, not changed (CLI unchanged).
101
- // @ts-expect-error see above
102
48
  return this.client.unsubscribe(topic);
103
49
  }
104
- /**
105
- * Transport interface: onMessage
106
- * @param {(message: {topic: string, payload: Uint8Array}) => void} cb
107
- */
108
50
  onMessage(cb) {
109
51
  this._messageHandler = cb;
110
- // Set message handler on client (will be wired on connect/reconnect)
111
52
  this.client.setMessageHandler(cb);
112
53
  }
113
- /**
114
- * Transport interface: onConnect
115
- * @param {() => void} cb
116
- */
117
54
  onConnect(cb) {
118
55
  this._connectHandler = cb;
119
- // If already connected, call immediately
120
56
  if (this.client.isOnline()) {
121
57
  cb();
122
58
  }
123
59
  }
124
- /**
125
- * Transport interface: onDisconnect
126
- * @param {(err?: unknown) => void} cb
127
- */
128
60
  onDisconnect(cb) {
129
61
  this._disconnectHandler = cb;
130
62
  }
131
- /**
132
- * Expose client for helpers that need direct access
133
- * @returns {MqttControlPlaneClient}
134
- */
135
63
  getClient() {
136
64
  return this.client;
137
65
  }
@@ -1,11 +1,3 @@
1
- // Story 12.1 (step 2b, sub-step 2; TypeScript in r3): the control-plane session shared by the HTTP, TCP and UDP
2
- // tunnels. Moved from the three copies in clients/asyx/src/commands/tunnel.js with their differences
3
- // kept as explicit options (12.1 must not change behaviour); the user-facing lines the copies
4
- // printed are now events the caller prints:
5
- // 'connected' after each (re)connect and instance re-registration (CLI: "✅ Control-plane sealed")
6
- // 'offline' { reason } when the connection is lost (CLI: "[mqtt] Control-plane connection lost: …")
7
- // 'fatal' { reason, error } when the client gives up (CLI: message, exit 1)
8
- // Credentials are values ({ endpoint, clientId, ca, cert, key }); reading them from disk is the caller's job.
9
1
  import { EventEmitter } from 'node:events';
10
2
  import { MqttControlPlaneClient } from './MqttControlPlaneClient.js';
11
3
  class SessionEvents extends EventEmitter {
@@ -19,26 +11,20 @@ export function createControlPlaneSession(o) {
19
11
  const { credentials, tunnelType, metadata, logger, onRefreshLease, onLeaseClosed, getTunnel = () => null, trackSubscriptionReady = true, reportOffline = true, verboseRotationLogs = true, keepaliveSec = parseInt(process.env.ASYX_CONTROL_PLANE_KEEPALIVE_SEC || '60', 10), mode = process.env.ASYX_MQTT_CLIENTID_MODE === 'legacy' ? 'legacy' : 'unique', } = o;
20
12
  const events = new SessionEvents();
21
13
  const baseClientId = credentials.clientId;
22
- // TPB-12: instanceId is the full MQTT client id; it changes when the client id rotates on reconnect
23
14
  const instanceIdRef = o.instanceIdRef || { instanceId: null };
24
- // Track subscription state so renewal requests wait for the subscription to be active
25
15
  const subscriptionReadyRef = o.subscriptionReadyRef || { ready: false };
26
16
  const callbacks = {
27
17
  onConnected: async () => {
28
18
  const newClientId = mqttClient.getClientId();
29
19
  logger.debug('mqtt.control_plane.connected', { clientId: newClientId });
30
- // TPB-12: Update instance registry if clientId changed on reconnect
31
20
  if (instanceIdRef.instanceId && newClientId !== instanceIdRef.instanceId) {
32
21
  const oldInstanceId = instanceIdRef.instanceId;
33
22
  logger.debug('cli.instance.clientid_rotated', { oldInstanceId, newInstanceId: newClientId, tunnelType });
34
- // Imported here, as the original code did, so they load only when a rotation happens
35
23
  const { unregisterInstance, registerInstance, getInstance, setExpectedRequestId } = await import('../state/instance-registry.js');
36
24
  const { setAssignment, getAssignment, migrateInstanceAssignment } = await import('../state/assignment.js');
37
25
  const oldContext = getInstance(oldInstanceId);
38
26
  if (oldContext) {
39
- // Preserve expectedRequestId before unregistering (for in-flight refresh/reconnect)
40
27
  const preservedRequestId = oldContext.expectedRequestId;
41
- // Register new instance FIRST (before unregistering old) to ensure routing works
42
28
  registerInstance(newClientId, { tunnelType, setAssignment, getAssignment, metadata: oldContext.metadata || metadata });
43
29
  if (preservedRequestId) {
44
30
  setExpectedRequestId(newClientId, preservedRequestId);
@@ -47,7 +33,6 @@ export function createControlPlaneSession(o) {
47
33
  }
48
34
  }
49
35
  unregisterInstance(oldInstanceId);
50
- // Move the assignment onto the new id and drop the old key.
51
36
  const migration = migrateInstanceAssignment(tunnelType === 'http'
52
37
  ? { oldId: oldInstanceId, newId: newClientId, tunnel: getTunnel() }
53
38
  : { oldId: oldInstanceId, newId: newClientId });
@@ -60,20 +45,17 @@ export function createControlPlaneSession(o) {
60
45
  instanceIdRef.instanceId = newClientId;
61
46
  }
62
47
  events.emit('connected', { clientId: newClientId });
63
- // Resubscribe to topics on reconnect (MqttControlPlaneClient manages subscriptions)
64
48
  const evtWildcard = `asyx/tunnel/clients/${baseClientId}/evt/#`;
65
49
  if (trackSubscriptionReady)
66
50
  subscriptionReadyRef.ready = false;
67
51
  try {
68
52
  await mqttClient.subscribe(evtWildcard, 0);
69
53
  logger.debug('mqtt.control_plane.resubscribed', { topic: evtWildcard });
70
- // subscribe() resolves only after the broker acknowledges
71
54
  if (trackSubscriptionReady)
72
55
  subscriptionReadyRef.ready = true;
73
56
  }
74
57
  catch (e) {
75
58
  logger.debug('mqtt.control_plane.resubscribe.failed', { error: e?.message || String(e) });
76
- // Mark ready even on failure to avoid blocking forever
77
59
  if (trackSubscriptionReady)
78
60
  subscriptionReadyRef.ready = true;
79
61
  }
@@ -89,7 +71,6 @@ export function createControlPlaneSession(o) {
89
71
  callbacks.onOffline = (reason) => {
90
72
  logger.debug('mqtt.control_plane.disconnected', { reason, clientId: mqttClient.getClientId() });
91
73
  events.emit('offline', { reason });
92
- // Clear the ready flag so renewals wait for resubscription after the reconnect
93
74
  subscriptionReadyRef.ready = false;
94
75
  };
95
76
  }
@@ -105,7 +86,6 @@ export function createControlPlaneSession(o) {
105
86
  rejectUnauthorized: true,
106
87
  keepalive: keepaliveSec,
107
88
  connectTimeout: 8000,
108
- // ALPN for port 443 (AWS IoT)
109
89
  ALPNProtocols: ['x-amzn-mqtt-ca'],
110
90
  },
111
91
  mode,
@@ -1,16 +1,7 @@
1
- // Story 12.1 (step 2b; TypeScript in r3): typed errors for @asyx/tunnel-core.
2
- // Classes by what the caller should do; the `code` is the contract (docs/proposals/tunnel-core-shape-12.1.md).
3
- // The core holds no user-facing wording: `message` is for logs and developers, the CLI maps `code`
4
- // to its own text and exit codes.
5
1
  export class TunnelError extends Error {
6
- /** Stable, machine-readable reason. */
7
2
  code;
8
3
  retryable;
9
4
  details;
10
- /**
11
- * @param code stable, machine-readable reason
12
- * @param message developer-facing description (never shown to users as-is by the CLI)
13
- */
14
5
  constructor(code, message = code, { retryable = false, cause, details } = {}) {
15
6
  super(message, cause === undefined ? undefined : { cause });
16
7
  this.name = new.target.name;
@@ -20,31 +11,21 @@ export class TunnelError extends Error {
20
11
  this.details = details;
21
12
  }
22
13
  }
23
- /** The machine is not enrolled, or the coordinator wants it to enroll again. */
24
14
  export class SetupRequiredError extends TunnelError {
25
15
  constructor(code = 'setup_required', message, opts) { super(code, message, { retryable: false, ...opts }); }
26
16
  }
27
- /**
28
- * The coordinator said no. `code` is the coordinator's own reason, passed through unchanged, so a
29
- * new reason on the server needs no client release (e.g. port_out_of_block, invalid_secgroup,
30
- * cap_exceeded, hostname_not_assigned, revoked).
31
- */
32
17
  export class RefusedError extends TunnelError {
33
18
  constructor(code, message, opts) { super(code || 'refused', message, { retryable: false, ...opts }); }
34
19
  }
35
- /** Network or transport failure; usually worth retrying. */
36
20
  export class ConnectionError extends TunnelError {
37
21
  constructor(code = 'connection_failed', message, opts) { super(code, message, { retryable: true, ...opts }); }
38
22
  }
39
- /** Bad local input (arguments, configuration, credentials on disk). */
40
23
  export class ConfigError extends TunnelError {
41
24
  constructor(code = 'invalid_config', message, opts) { super(code, message, { retryable: false, ...opts }); }
42
25
  }
43
- /** A bug or an unexpected state inside the core. */
44
26
  export class InternalError extends TunnelError {
45
27
  constructor(code = 'internal', message, opts) { super(code, message, { retryable: false, ...opts }); }
46
28
  }
47
- /** Wrap anything thrown into a TunnelError without losing it. */
48
29
  export function toTunnelError(e, fallbackCode = 'internal') {
49
30
  if (e instanceof TunnelError)
50
31
  return e;
@@ -1,9 +1,4 @@
1
- // Story 2.11 c1/c3 from the CLI (owner decision 2026-11-27): an account command (`asyx name add`,
2
- // `asyx port release`) sent over the device's own certificate connection to the coordinator, which checks
3
- // the certificate (Defect 11.22), allows devices only, and answers on the device's ack topic with
4
- // { type: 'account_ack', requestId, data }. One connection per command; it ends after the answer.
5
1
  import { randomUUID } from 'node:crypto';
6
- /** Sends one account command and resolves the coordinator's answer (a refusal is { ok: false, error }). */
7
2
  export async function sendAccountCommand(o) {
8
3
  const { credentials, command, logger, timeoutMs = 30000 } = o;
9
4
  const { MqttCore } = await import('@asyx/mqtt-core');
@@ -50,6 +45,6 @@ export async function sendAccountCommand(o) {
50
45
  try {
51
46
  await mqttClient.disconnect();
52
47
  }
53
- catch { /* already gone */ }
48
+ catch { }
54
49
  }
55
50
  }
@@ -1,7 +1,3 @@
1
- // Story 3.13: a tunnel that stops on purpose tells the cloud, so its lease is closed at once. The close is
2
- // sent over the device's own certificate connection (the coordinator's 11.22 checks apply) on its cmd/open
3
- // topic, and the stop waits at most `timeoutMs` for the broker to take it (QoS 1); a goodbye never delays
4
- // a stop longer than that, and a stop without one falls back to Story 3.12 (expiry plus grace).
5
1
  import { randomUUID } from 'node:crypto';
6
2
  export async function sayGoodbye(h, timeoutMs = 2000) {
7
3
  const leaseId = h?.assignment?.leaseId;