asyx 0.7.2 → 0.9.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.
package/README.md CHANGED
@@ -118,7 +118,9 @@ Hostnames and ports belong to your **account**, not to one computer. Any device
118
118
  asyx name check orders-api # is orders-api.tunnel.asyx.ai available? (no setup needed)
119
119
  asyx setup --hostname orders-api # enroll this machine with that name
120
120
  asyx setup --random # or a generated name such as quiet-otter-482
121
+ asyx setup --address fast # use one of your addresses as this device's default (also changes it on a device already set up)
121
122
  asyx setup # or choose on the approval page (it proposes <machine>-<account>)
123
+ asyx name add orders-api # add orders-api.tunnel.asyx.ai to your account from a set-up device
122
124
  ```
123
125
 
124
126
  Names use 3–30 characters: lowercase letters, digits and hyphens, starting and ending with a letter or digit. Some names are reserved. How many devices and addresses an account can have depends on its plan.
@@ -190,7 +192,12 @@ asyx tunnel --udp --port 27015 --to orders-api.tunnel.asyx.ai [--external-port <
190
192
  asyx tunnel --minecraft --to orders-api.tunnel.asyx.ai [--port 25565] [--name <alias>]
191
193
  ```
192
194
 
193
- **Public ports.** Your account has 10 TCP and 10 UDP public ports (its block). An address gets one of each kind the first time it opens a TCP or UDP tunnel and keeps it: every restart, from any of your devices, uses the same public port. `--external-port <p>` picks a specific port of your block for the address; a port that already belongs to another of your addresses is refused with its name. Ports are not released automatically.
195
+ **Public ports.** Your account has 10 TCP and 10 UDP public ports (its block). For TCP and UDP **the port is the address**: all your hostnames point at the same server, so `fast.tunnel.asyx.ai:10000` and `slow.tunnel.asyx.ai:10000` reach the same tunnel. The hostname a port was last opened under is its **label**:
196
+
197
+ - An address gets a port of each kind the first time it opens a TCP or UDP tunnel and keeps it: every restart, from any of your devices, uses the same public port.
198
+ - `--external-port <p>` opens a specific port of your block under the address you name. If that port is labelled for another of your addresses and nothing is running on it, its label moves and the CLI says so (`Port 10000 moved from fast to slow.`). If a tunnel is running on it, you are told where; add `--replace` to take it over.
199
+ - A port used by an app's address stays with the app; release it first to use it elsewhere.
200
+ - Labels never move by themselves, and ports are not released automatically: release one with `asyx port release --tcp 10003` (or `--udp`) or in the console, or delete its address. A port with a running tunnel is not released.
194
201
 
195
202
  After a tunnel opens, the CLI prints the public hostname (and port for TCP/UDP) plus the local target (`tcp://127.0.0.1:<port>` or `udp://127.0.0.1:<port>`).
196
203
 
@@ -236,8 +243,10 @@ Messages name the other computer by its name; they never contain an IP address.
236
243
  ```bash
237
244
  asyx help # commands; asyx tunnel --help for tunnel options
238
245
  asyx --version
239
- asyx setup [--hostname <name> | --random] [--json]
246
+ asyx setup [--hostname <name> | --random | --address <name>] [--json]
240
247
  asyx name check <name> [--json]
248
+ asyx name add <name> [--json]
249
+ asyx port release --tcp <port> | --udp <port> [--json]
241
250
  asyx tunnel --http --port <n> --to <hostname> [--secgroup <slug>]
242
251
  asyx tunnel --tcp --port <n> --to <hostname> [--name <alias>] [--external-port <p>]
243
252
  asyx tunnel --udp --port <n> --to <hostname> [--external-port <p>]
@@ -247,6 +256,22 @@ asyx tunnel --minecraft --to <hostname> [--port <n>] [--name <alias>]
247
256
 
248
257
  ---
249
258
 
259
+ ## What's new in 0.9.0
260
+
261
+ **Pick one of your addresses at setup** — `asyx setup --address <name>` makes one of your account's existing addresses this device's default instead of creating a new one. On a device that is already set up, it changes its default. The approval page also lists your addresses next to "A new address".
262
+
263
+ **Takeover email** — when `--replace` takes over a running tunnel, the account owner gets an email saying what was taken, when, and from which device and computer to which. The same device taking over a tunnel that was running on another computer is marked as suspicious.
264
+
265
+ **Devices and addresses in the console** — the console has a Devices page (remove a device, change its default address) and lets you add or delete addresses and release ports. A deleted address loses its DNS records, and its name stays yours for 24 hours.
266
+
267
+ ## What's new in 0.8.0
268
+
269
+ **Add an address from the terminal** — `asyx name add <name>` adds `<name>.tunnel.asyx.ai` to your account (within your plan, with the same name check as the console). Any of your devices can then serve it with `--to`.
270
+
271
+ **Release a port** — `asyx port release --tcp <port>` (or `--udp`) gives a port back to your account's block, so another address can use it. A port with a running tunnel is not released.
272
+
273
+ **Move a port to another address by naming it** — for TCP and UDP the port is the address and the hostname is its label. Opening a port of your block under another of your addresses (`--to slow.tunnel.asyx.ai --external-port 10000`) moves the label when nothing runs on it, and the CLI says so: `Port 10000 moved from fast to slow.` A port used by an app's address stays with the app.
274
+
250
275
  ## What's new in 0.7.2
251
276
 
252
277
  **Refusals always come with words** — if the cloud refuses a tunnel with a reason this version does not know yet, the CLI now shows the explanation the cloud sends instead of only a code. A device whose setup is incomplete is told to run `asyx setup` again (or contact support), and the tunnel stops with exit code 1.
@@ -369,7 +394,7 @@ Levels: `error` | `warn` | `info` | `debug` (default `info`).
369
394
  | Tunnel URL 502 / unreachable | Dev server not running on the same port |
370
395
  | Link stops while the computer sleeps | Expected—the tunnel serves only while the CLI runs and the machine is awake; when it wakes, the tunnel reconnects (and reopens its lease if needed) on the same address |
371
396
  | TCP/UDP tunnel ended after an outage | It retries for 15 minutes, then exits; run the same command again (raise `ASYX_TUNNEL_RECONNECT_MAX_MS` for longer outages) |
372
- | External port rejected | `--external-port` must be inside your account's 10-port block and not belong to another of your addresses (the message names it) |
397
+ | External port rejected | `--external-port` must be inside your account's 10-port block; a port in use by a running tunnel, or held by an app's address, is refused with where it is |
373
398
  | "… is not an address of this account" | Check the `--to` hostname; it must be one of your account's addresses (see the console) |
374
399
  | "This device is not set up for your account yet" | Run `asyx setup` again on that computer; if it persists, contact support@asyx.ai |
375
400
  | Windows: secure connection fails at startup | Re-run `asyx setup` to regenerate the device key |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "asyx",
3
- "version": "0.7.2",
3
+ "version": "0.9.0",
4
4
  "description": "Asyx tunnel CLI — secure localhost exposure (HTTP, TCP, UDP)",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -29,6 +29,7 @@
29
29
  "files": [
30
30
  "bin/",
31
31
  "src/commands/.gitkeep",
32
+ "src/commands/account.js",
32
33
  "src/commands/in-use-messages.js",
33
34
  "src/commands/mqtt-broker.js",
34
35
  "src/commands/mqtt.js",
@@ -0,0 +1,86 @@
1
+ // Story 2.11 c1/c3 from the CLI (owner decision 2026-11-27): `asyx name add <name>` and
2
+ // `asyx port release --tcp|--udp <port>`, sent over this device's own certificate connection. The
3
+ // service checks the certificate, allows devices only, keeps the plan's address limit and releases only
4
+ // a port that is not live. Deleting an address stays in the console.
5
+ // exit 0 done, 1 refused or failed, 2 usage, 3 the name is not available (name add)
6
+ import { normalizeLabel, describeAnswer, EXIT } from '../lib/naming.js';
7
+
8
+ const CONSOLE = 'asyx.ai/console/tunnel';
9
+
10
+ async function loadCredentials() {
11
+ const { loadAwsIotConfig } = await import('@asyx/mqtt-broker-aws');
12
+ const { readFileSync } = await import('node:fs');
13
+ const cfg = await loadAwsIotConfig();
14
+ return { endpoint: cfg.endpoint, clientId: cfg.clientId, ca: readFileSync(cfg.caPath), cert: readFileSync(cfg.certPath), key: readFileSync(cfg.keyPath) };
15
+ }
16
+ async function defaultSend(credentials, command) {
17
+ const { sendAccountCommand } = await import('#tunnel-core/flows/account.js');
18
+ const { default: logger } = await import('#tunnel-core/lib/logger.js');
19
+ return sendAccountCommand({ credentials, command, logger });
20
+ }
21
+
22
+ const REFUSALS = {
23
+ app_not_allowed: 'An app cannot change the account. Run this on a device, or use the console.',
24
+ identity_inactive: 'This device has been removed from its account. Run asyx setup to set it up again.',
25
+ identity_refused: 'The service did not accept this device\'s certificate. Run asyx setup again.',
26
+ account_not_migrated: 'This device is not set up for your account yet. Run asyx setup again; if that does not help, contact support@asyx.ai.',
27
+ account_changed_retry: 'The account changed at the same moment. Run the command again.',
28
+ no_port_block: 'This account has no port block yet. Contact support@asyx.ai.',
29
+ address_exists: 'That address is already on your account.',
30
+ };
31
+
32
+ export async function runAccountCommand(command, { json = false, send = defaultSend, credentials = loadCredentials, out = console.log, err = console.error } = {}) {
33
+ let creds;
34
+ try { creds = await credentials(); }
35
+ catch (e) {
36
+ if (json) out(JSON.stringify({ ok: false, error: 'setup_required' }));
37
+ else err('This computer is not set up yet. Run asyx setup first.');
38
+ return EXIT.FAILED;
39
+ }
40
+ let r;
41
+ try { r = await send(creds, command); }
42
+ catch (e) {
43
+ if (json) out(JSON.stringify({ ok: false, error: e.code || 'network_error', message: e.message }));
44
+ else err(`Could not reach the service: ${e.message}`);
45
+ return EXIT.FAILED;
46
+ }
47
+ if (json) { out(JSON.stringify(r)); }
48
+ if (r?.ok) {
49
+ if (!json && command.type === 'address_add') out(`${r.address.hostname} was added to your account. Open a tunnel on it with --to ${r.address.hostname}`);
50
+ if (!json && command.type === 'port_release') out(`${r.released.kind.toUpperCase()} port ${r.released.port} was released${r.released.address ? ` (it was ${r.released.address}'s)` : ''}.`);
51
+ return EXIT.OK;
52
+ }
53
+ const e = r?.error || 'refused';
54
+ if (command.type === 'address_add' && /^hostname_/.test(e)) {
55
+ if (!json) err(describeAnswer({ status: e, label: command.name, hostname: `${command.name}.tunnel.asyx.ai`, suggestions: r.suggestions || [] }));
56
+ return EXIT.NAME_UNAVAILABLE;
57
+ }
58
+ if (!json) {
59
+ if (e === 'address_limit_reached') err(`Your plan allows ${r.limit} addresses and they are all in use. Delete one in the console (${CONSOLE}) first.`);
60
+ else if (e === 'port_live') err(`${String(r.kind).toUpperCase()} port ${r.port} is in use by a running tunnel${r.address ? ` on ${r.address}` : ''}. Stop that tunnel first.`);
61
+ else if (e === 'port_not_assigned') err(`${String(r.kind).toUpperCase()} port ${r.port} is not assigned to any of your addresses.`);
62
+ else err(REFUSALS[e] || `The service refused the request (${e}).`);
63
+ }
64
+ return EXIT.FAILED;
65
+ }
66
+
67
+ /** `asyx name add <name> [--json]` */
68
+ export async function cmdNameAdd(args, opts = {}) {
69
+ const json = args.includes('--json');
70
+ const rest = args.filter((a) => a !== '--json');
71
+ if (rest.length !== 1) { (opts.err || console.error)('Usage: asyx name add <name> [--json]'); return EXIT.USAGE; }
72
+ const label = normalizeLabel(rest[0]) || String(rest[0]).trim().toLowerCase();
73
+ return runAccountCommand({ type: 'address_add', name: label }, { ...opts, json });
74
+ }
75
+
76
+ /** `asyx port release --tcp <port> | --udp <port> [--json]` */
77
+ export async function cmdPort(argv, opts = {}) {
78
+ const err = opts.err || console.error;
79
+ const json = argv.includes('--json');
80
+ const args = argv.filter((a) => a !== '--json');
81
+ const usage = () => { err('Usage: asyx port release --tcp <port> | --udp <port> [--json]'); return EXIT.USAGE; };
82
+ if (args[0] !== 'release' || args.length !== 3 || !['--tcp', '--udp'].includes(args[1])) return usage();
83
+ const port = Number(args[2]);
84
+ if (!Number.isInteger(port) || port < 1 || port > 65535) return usage();
85
+ return runAccountCommand({ type: 'port_release', kind: args[1].slice(2), port }, { ...opts, json });
86
+ }
@@ -3,10 +3,12 @@
3
3
  import { checkName, describeAnswer, normalizeLabel, EXIT } from '../lib/naming.js';
4
4
 
5
5
  export default async function cmdName(argv, { fetchImpl = fetch, out = console.log, err = console.error } = {}) {
6
+ // Story 2.11 c1: `asyx name add <name>` adds an address to the account (over this device's connection)
7
+ if (argv[0] === 'add') { const { cmdNameAdd } = await import('./account.js'); return cmdNameAdd(argv.slice(1), { out, err }); }
6
8
  const json = argv.includes('--json');
7
9
  const args = argv.filter((a) => a !== '--json');
8
10
  if (args[0] !== 'check' || !args[1] || args.length > 2) {
9
- err('Usage: asyx name check <name> [--json]');
11
+ err('Usage: asyx name check <name> [--json]\n asyx name add <name> [--json]');
10
12
  return EXIT.USAGE;
11
13
  }
12
14
  const raw = args[1];
@@ -90,6 +90,17 @@ export function printOpenReject({ code, reason, data }) {
90
90
  process.exit(1);
91
91
  return;
92
92
  }
93
+ // Story 2.11 c3 (port labels): a port an app's address uses stays with the app
94
+ case 'port_pinned_to_app': {
95
+ process.stderr.write(`Port ${d.requestedPort ?? ''} is used by the app on ${d.address || 'another address'}. Release it in the console (asyx.ai/console/tunnel) to use it for another address, or pick another port.\n`);
96
+ process.exit(1);
97
+ return;
98
+ }
99
+ case 'port_changed_retry': {
100
+ process.stderr.write(`Port ${d.requestedPort ?? ''} changed while the tunnel was opening. Run the command again.\n`);
101
+ process.exit(75);
102
+ return;
103
+ }
93
104
  case 'port_block_full': {
94
105
  const where = d.assigned && typeof d.assigned === 'object' ? Object.entries(d.assigned).map(([p, a]) => `${p} → ${a}`).join(', ') : '';
95
106
  process.stderr.write(`All 10 ${String(d.kind || '').toUpperCase()} ports of this account are assigned${where ? ` (${where})` : ''}. Release one in the console (asyx.ai/console/tunnel), then try again.\n`);
@@ -22,7 +22,8 @@ function isJsonResponse(res) {
22
22
  }
23
23
 
24
24
  /**
25
- * `asyx setup [--hostname <name> | --random] [--json]` (Stories 2.1 r3, 4.7).
25
+ * `asyx setup [--hostname <name> | --random | --address <name>] [--json]` (Stories 2.1 r3, 4.7, 2.11 c5/c8).
26
+ * --address: one of the account's addresses as this device's default (a new device, or one already set up).
26
27
  * Returns the exit code. The terminal never prompts: it prints the approval link, waits, and reports
27
28
  * the approved hostname. With --json, stdout carries one JSON object per line and nothing else.
28
29
  *
@@ -52,7 +53,7 @@ export async function runSetup(argv = [], deps = {}) {
52
53
  return code;
53
54
  };
54
55
 
55
- if (opts.error) return fail(EXIT.USAGE, 'usage', `${opts.error}\nUsage: asyx setup [--hostname <name> | --random] [--json]`);
56
+ if (opts.error) return fail(EXIT.USAGE, 'usage', `${opts.error}\nUsage: asyx setup [--hostname <name> | --random | --address <name>] [--json]`);
56
57
 
57
58
  const clientId = clientIdImpl();
58
59
  if (!/^cli_[A-F0-9]{12}$/.test(clientId)) return fail(EXIT.FAILED, 'invalid_client_id', 'Invalid clientId format (expected cli_[A-F0-9]{12})');
@@ -73,7 +74,7 @@ export async function runSetup(argv = [], deps = {}) {
73
74
 
74
75
  // 1) Approval link
75
76
  const ticket = randHex(16);
76
- const url = approvalUrl(CONSOLE_URL, { clientId, ticket, hostname: opts.hostname, random: opts.random });
77
+ const url = approvalUrl(CONSOLE_URL, { clientId, ticket, hostname: opts.hostname, random: opts.random, address: opts.address });
77
78
  const code = setupCode(ticket);
78
79
  emit({ event: 'approval_required', url, code, clientId, expiresInSeconds: Math.round(deadlineMs / 1000) });
79
80
  say('Approve this device in your browser:');
@@ -49,12 +49,16 @@ export default async function tunnel(args = []) {
49
49
 
50
50
  --to <hostname> the address this tunnel serves, e.g. --to orders-api.tunnel.asyx.ai: any
51
51
  address of your account; without it, this device's default address
52
- --external-port <p> a specific public port of your account's 10-port block (it then belongs
53
- to that address); without it, the address keeps its own port
52
+ --external-port <p> a specific public port of your account's 10-port block, opened under the
53
+ address you name (a port labelled for another address moves here when
54
+ nothing runs on it); without it, the address keeps its own port
54
55
  --replace take over this address's running tunnel of the same kind (it is told and stops)
55
56
  --wait if the address already runs this kind, keep trying every 30 s instead of exiting
56
57
  --json print refusals as JSON
57
58
 
59
+ For TCP and UDP the port is the address: any of your hostnames with that port reaches the same tunnel,
60
+ and the hostname you open it under is a label you change by naming the port.
61
+
58
62
  One address runs one HTTP, one TCP and one UDP tunnel at a time. A second tunnel of
59
63
  the same kind is refused with the reason and exit code 75 (also when a tunnel is
60
64
  taken over by --replace), so a service manager can be told not to restart on it.
@@ -764,7 +768,9 @@ async function tcpTunnel(localPort, serviceName, kind = null, requestedExternalP
764
768
  process.exit(1);
765
769
  });
766
770
  // TCP-S3 / E3-S8: where the server is reachable, printed when the assignment arrives
767
- handle.on('assigned', ({ tcpAliasFqdn, srvProvisioned, srvFqdn, fqdn, publicPort, aliasRequestedButFailed }) => {
771
+ handle.on('assigned', ({ tcpAliasFqdn, srvProvisioned, srvFqdn, fqdn, publicPort, aliasRequestedButFailed, portMoved }) => {
772
+ // Story 2.11 c3: naming a port labelled for another address moved its label here
773
+ if (portMoved?.from) process.stdout.write(`Port ${portMoved.port} moved from ${portMoved.from} to ${portMoved.to}.\n`);
768
774
  if (tcpAliasFqdn) {
769
775
  process.stdout.write(`Your TCP server is available at:\n\n`);
770
776
  process.stdout.write(` ${tcpAliasFqdn}\n`);
@@ -927,6 +933,7 @@ async function udpTunnel(targetPort, requestedExternalPort = null, targetHost =
927
933
  const assignment = handle.assignment;
928
934
 
929
935
  // Tunnel live message (UDP-S13: both fqdn and fqdn:publicPort; the CLI does not bind the service port)
936
+ if (assignment.portMoved?.from) process.stdout.write(`Port ${assignment.portMoved.port} moved from ${assignment.portMoved.from} to ${assignment.portMoved.to}.\n`); // Story 2.11 c3
930
937
  process.stdout.write(`🔌 UDP tunnel active (ready for datagrams)\n`);
931
938
  process.stdout.write(` App target: ${targetHost}:${targetPort}\n`);
932
939
  if (assignment.fqdn) {
package/src/lib/naming.js CHANGED
@@ -20,7 +20,7 @@ export function normalizeLabel(input) {
20
20
 
21
21
  /** Parses `asyx setup` options. Returns { hostname, random, json } or { error }. */
22
22
  export function parseSetupArgs(argv) {
23
- const out = { hostname: null, random: false, json: false };
23
+ const out = { hostname: null, random: false, json: false, address: null };
24
24
  for (let i = 0; i < argv.length; i++) {
25
25
  const a = argv[i];
26
26
  if (a === 'setup') continue;
@@ -32,18 +32,26 @@ export function parseSetupArgs(argv) {
32
32
  const label = normalizeLabel(v);
33
33
  if (!label) return { error: `"${v}" is not a valid name: use 3-30 characters a-z, 0-9 and hyphens, starting and ending with a letter or digit` };
34
34
  out.hostname = label;
35
+ } else if (a === '--address' || a.startsWith('--address=')) {
36
+ // Story 2.11 c5/c8: one of the account's addresses as this device's default (new or already set up)
37
+ const v = a.includes('=') ? a.slice(a.indexOf('=') + 1) : argv[++i];
38
+ if (!v) return { error: '--address needs one of your addresses, for example --address orders-api' };
39
+ const label = normalizeLabel(v);
40
+ if (!label) return { error: `"${v}" is not a valid address name` };
41
+ out.address = label;
35
42
  } else return { error: `unknown option ${a}` };
36
43
  }
37
- if (out.hostname && out.random) return { error: 'use either --hostname or --random, not both' };
44
+ if ([out.hostname, out.random, out.address].filter(Boolean).length > 1) return { error: 'use one of --hostname, --random or --address' };
38
45
  return out;
39
46
  }
40
47
 
41
48
  /** The approval link. v=2 tells the page this CLI supports device naming (2.1 r3). */
42
- export function approvalUrl(base, { clientId, ticket, hostname, random, machine = os.hostname() }) {
49
+ export function approvalUrl(base, { clientId, ticket, hostname, random, address, machine = os.hostname() }) {
43
50
  const q = new URLSearchParams({ clientId, ticket, v: '2' });
44
51
  if (machine) q.set('machine', String(machine).slice(0, 64));
45
52
  if (hostname) q.set('hostname', hostname);
46
53
  if (random) q.set('random', '1');
54
+ if (address) q.set('address', address); // Story 2.11 c5/c8
47
55
  return `${base}?${q.toString()}`;
48
56
  }
49
57
 
package/src/main.js CHANGED
@@ -32,13 +32,18 @@ Usage: asyx <command>
32
32
  Commands:
33
33
  setup Enroll this machine (prints an approval link; opens your browser)
34
34
  name check <name> Is <name>.tunnel.asyx.ai available? (works before setup)
35
+ name add <name> Add <name>.tunnel.asyx.ai to your account as a new address
36
+ port release --tcp|--udp <port>
37
+ Give a port back to your account's block (not while a tunnel runs on it)
35
38
  tunnel Open an HTTP, TCP or UDP tunnel to a local port
36
39
  help Show this help
37
40
 
38
41
  Examples:
39
42
  asyx setup
40
43
  asyx setup --hostname orders-api (or --random; add --json for agents)
44
+ asyx setup --address fast (use one of your addresses as this device's default)
41
45
  asyx name check orders-api
46
+ asyx name add orders-api
42
47
  asyx tunnel --http --port 3000 --to orders-api.tunnel.asyx.ai
43
48
  asyx tunnel --tcp --port 5432 --to orders-api.tunnel.asyx.ai
44
49
  asyx tunnel --udp --port 27015 --to orders-api.tunnel.asyx.ai
@@ -56,7 +61,10 @@ Usage: asyx <command>
56
61
  cmdSetup(process.argv.slice(2)).catch(handleFailure('Setup'));
57
62
  } else if (cmd === "name") {
58
63
  const { default: cmdName } = await import("./commands/name.js");
59
- cmdName(process.argv.slice(3)).then((code) => process.exit(code), handleFailure('Name check'));
64
+ cmdName(process.argv.slice(3)).then((code) => process.exit(code), handleFailure('Name'));
65
+ } else if (cmd === "port") {
66
+ const { cmdPort } = await import("./commands/account.js"); // Story 2.11 c3
67
+ cmdPort(process.argv.slice(3)).then((code) => process.exit(code), handleFailure('Port release'));
60
68
  } else if (cmd === "sts") {
61
69
  cmdSts(process.argv.slice(2)).catch(handleFailure('STS'));
62
70
  } else if (cmd === "mqtt") {
@@ -9,7 +9,7 @@ export interface ControlPlaneCredentials {
9
9
  cert: Buffer | string;
10
10
  key: Buffer | string;
11
11
  }
12
- export type TunnelType = 'http' | 'tcp' | 'udp';
12
+ export type TunnelType = 'http' | 'tcp' | 'udp' | 'account';
13
13
  export interface ControlPlaneSessionOptions {
14
14
  credentials: ControlPlaneCredentials;
15
15
  tunnelType: TunnelType;
@@ -0,0 +1,24 @@
1
+ import type { Logger } from '../types.js';
2
+ import type { ControlPlaneCredentials } from '../control-plane/session.js';
3
+ export type AccountCommand = {
4
+ type: 'address_add';
5
+ name: string;
6
+ } | {
7
+ type: 'port_release';
8
+ kind: 'tcp' | 'udp';
9
+ port: number;
10
+ };
11
+ export type AccountReply = {
12
+ op: string;
13
+ ok: boolean;
14
+ error?: string;
15
+ [k: string]: unknown;
16
+ };
17
+ export interface AccountCommandOptions {
18
+ credentials: ControlPlaneCredentials;
19
+ command: AccountCommand;
20
+ logger: Logger;
21
+ timeoutMs?: number;
22
+ }
23
+ /** Sends one account command and resolves the coordinator's answer (a refusal is { ok: false, error }). */
24
+ export declare function sendAccountCommand(o: AccountCommandOptions): Promise<AccountReply>;
@@ -0,0 +1,55 @@
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
+ import { randomUUID } from 'node:crypto';
6
+ /** Sends one account command and resolves the coordinator's answer (a refusal is { ok: false, error }). */
7
+ export async function sendAccountCommand(o) {
8
+ const { credentials, command, logger, timeoutMs = 30000 } = o;
9
+ const { MqttCore } = await import('@asyx/mqtt-core');
10
+ const { createControlPlaneSession } = await import('../control-plane/session.js');
11
+ const { MqttControlPlaneTransport } = await import('../control-plane/MqttControlPlaneTransport.js');
12
+ const base = credentials.clientId;
13
+ const session = createControlPlaneSession({
14
+ credentials, tunnelType: 'account', metadata: { op: command.type }, logger,
15
+ onRefreshLease: async () => null, trackSubscriptionReady: false, reportOffline: false, verboseRotationLogs: false,
16
+ });
17
+ const mqttClient = session.mqttClient;
18
+ const core = new MqttCore(new MqttControlPlaneTransport(mqttClient), { canPublish: () => true, canSubscribe: () => true });
19
+ const requestId = `acct-${randomUUID()}`;
20
+ let timer;
21
+ try {
22
+ await mqttClient.connect();
23
+ const answer = new Promise((resolve, reject) => {
24
+ timer = setTimeout(() => reject(Object.assign(new Error('no answer from the service'), { code: 'account_timeout' })), timeoutMs);
25
+ core.onMessage(async (m) => {
26
+ let p;
27
+ try {
28
+ p = typeof m.payload === 'string' ? JSON.parse(m.payload) : JSON.parse(Buffer.from(m.payload).toString('utf8'));
29
+ }
30
+ catch {
31
+ return;
32
+ }
33
+ if (p?.requestId !== requestId)
34
+ return;
35
+ if (p.type === 'account_ack')
36
+ resolve(p.data);
37
+ else if (p.type === 'open_reject')
38
+ resolve({ op: command.type, ok: false, error: String(p.data?.reason || 'refused'), ...(p.data || {}) });
39
+ });
40
+ });
41
+ await core.subscribe(`asyx/tunnel/clients/${base}/evt/#`, 0);
42
+ const instanceId = mqttClient.getClientId();
43
+ await core.publish({ topic: `asyx/tunnel/clients/${base}/cmd/open`, payload: JSON.stringify({ ...command, requestId, clientId: base, instanceId }), qos: 1, retain: false });
44
+ logger.debug('account.command.sent', { op: command.type, requestId });
45
+ return await answer;
46
+ }
47
+ finally {
48
+ if (timer)
49
+ clearTimeout(timer);
50
+ try {
51
+ await mqttClient.disconnect();
52
+ }
53
+ catch { /* already gone */ }
54
+ }
55
+ }
@@ -29,6 +29,13 @@ export type TcpAssignedEvent = {
29
29
  fqdn?: string;
30
30
  publicPort?: number;
31
31
  aliasRequestedButFailed?: boolean;
32
+ /** Story 2.11 c3: the named port was labelled for another address and its label moved to this one. */
33
+ portMoved?: {
34
+ port: number;
35
+ kind: string;
36
+ from: string;
37
+ to: string;
38
+ } | null;
32
39
  };
33
40
  /** What open() resolves to and the 'live' state carries. */
34
41
  export type TcpTunnelInfo = {
@@ -2,7 +2,7 @@
2
2
  // connectToRelayTcp() in clients/asyx/src/commands/tunnel.js. Behaviour is unchanged; what the CLI
3
3
  // printed or exited on is now an event or a typed error, and the CLI maps both to its old wording:
4
4
  // 'control-connected' / 'control-fatal' (TCP has never reported a lost control-plane connection)
5
- // 'assigned' { tcpAliasFqdn, srvProvisioned, srvFqdn, fqdn, publicPort, aliasRequestedButFailed }
5
+ // 'assigned' { tcpAliasFqdn, srvProvisioned, srvFqdn, fqdn, publicPort, aliasRequestedButFailed, portMoved }
6
6
  // when the coordinator's assignment arrives (the CLI prints where the server is reachable)
7
7
  // state events: 'opening', 'live', 'renewed', and a final 'closed' { error } when a reply ends
8
8
  // the tunnel after it opened (SetupRequiredError, RefusedError, InternalError).
@@ -415,6 +415,7 @@ export class TcpTunnelHandle extends LifecycleEmitter {
415
415
  fqdn: assignment.fqdn,
416
416
  publicPort: assignment.publicPort,
417
417
  aliasRequestedButFailed,
418
+ portMoved: assignment.portMoved || null,
418
419
  });
419
420
  if (tcpAliasFqdn) {
420
421
  logger.debug('tcp.alias.ready', { requestId, tcpAliasFqdn, fqdn: assignment.fqdn, publicPort: assignment.publicPort });
@@ -177,7 +177,9 @@ const registry = {
177
177
  warnings,
178
178
  // UDP-S1: Store UDP-specific fields
179
179
  tunnelMode,
180
- protocol
180
+ protocol,
181
+ // Story 2.11 c3: the named port's label moved to this address ({ port, kind, from, to })
182
+ portMoved: data.portMoved || null
181
183
  });
182
184
  logger.debug("open_ack.assignment_stored", {
183
185
  requestId: e.requestId,
@@ -6,13 +6,13 @@ export const Envelope: z.ZodObject<{
6
6
  data: z.ZodUnknown;
7
7
  }, "strip", z.ZodTypeAny, {
8
8
  requestId?: string;
9
- type?: "setup_required" | "error" | "open_ack" | "open_reject";
9
+ type?: "setup_required" | "error" | "open_reject" | "open_ack";
10
10
  v?: 1;
11
11
  ts?: number;
12
12
  data?: unknown;
13
13
  }, {
14
14
  requestId?: string;
15
- type?: "setup_required" | "error" | "open_ack" | "open_reject";
15
+ type?: "setup_required" | "error" | "open_reject" | "open_ack";
16
16
  v?: 1;
17
17
  ts?: number;
18
18
  data?: unknown;
@@ -19,6 +19,7 @@
19
19
  * @param {string} [assignment.tunnelMode]
20
20
  * @param {string} [assignment.protocol]
21
21
  * @param {string} [assignment.assignmentJwt]
22
+ * @param {{ port: number, kind: string, from: string, to: string }} [assignment.portMoved] Story 2.11 c3
22
23
  */
23
24
  export function setAssignment(instanceId: string, assignment: {
24
25
  requestId: string;
@@ -37,6 +38,12 @@ export function setAssignment(instanceId: string, assignment: {
37
38
  tunnelMode?: string;
38
39
  protocol?: string;
39
40
  assignmentJwt?: string;
41
+ portMoved?: {
42
+ port: number;
43
+ kind: string;
44
+ from: string;
45
+ to: string;
46
+ };
40
47
  }): void;
41
48
  /**
42
49
  * Get assignment for a specific tunnel instance
@@ -28,6 +28,7 @@ const assignmentWaiters = new Map();
28
28
  * @param {string} [assignment.tunnelMode]
29
29
  * @param {string} [assignment.protocol]
30
30
  * @param {string} [assignment.assignmentJwt]
31
+ * @param {{ port: number, kind: string, from: string, to: string }} [assignment.portMoved] Story 2.11 c3
31
32
  */
32
33
  export function setAssignment(instanceId, assignment) {
33
34
  // Backward compatibility: if instanceId is not provided, treat as legacy single-instance
@@ -57,6 +58,7 @@ export function setAssignment(instanceId, assignment) {
57
58
  tunnelMode: assignment.tunnelMode || null,
58
59
  protocol: assignment.protocol || null,
59
60
  assignmentJwt: assignment.assignmentJwt || null, // UDP-S1: Store assignmentJwt separately
61
+ portMoved: assignment.portMoved || null, // Story 2.11 c3: the port's label moved to this address
60
62
  timestamp: Date.now(),
61
63
  lastRefreshMs: undefined,
62
64
  lastRefreshIso: undefined,