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,180 +1,346 @@
1
- // Story 12.2: app identities from an enrolled device.
2
- // asyx app create <name> [--hostname <label> | --random | --address <existing>] [--json]
3
- // asyx app export <name> (--out <path> | --print) (or pipe it: asyx app export <name> > file)
4
- // asyx app list [--json]
5
- // The key and CSR are made here and never leave this machine; the service checks this device's
6
- // certificate, creates the app's certificate and pins the app to its address. Credentials are kept only
7
- // under ~/.asyx/apps/<appId>/ (owner-only); the project folder gets asyx.json (no secrets) (c5).
8
- // exit 0 done, 1 refused or failed, 2 usage, 3 the name is not available
9
1
  import fs from 'node:fs';
10
2
  import path from 'node:path';
11
3
  import os from 'node:os';
12
4
  import { randomBytes } from 'node:crypto';
13
5
  import { EXIT, describeAnswer } from '../lib/naming.js';
14
-
15
6
  const LABEL_RE = /^[a-z0-9](?:[a-z0-9-]{1,28}[a-z0-9])$/;
16
7
  const CA_URL = 'https://www.amazontrust.com/repository/AmazonRootCA1.pem';
17
8
  export const appsDir = (home = os.homedir()) => path.join(home, '.asyx', 'apps');
18
9
  export const newAppId = () => `app_${randomBytes(6).toString('hex').toUpperCase()}`;
19
-
20
- /** The apps kept on this machine: [{ appId, name, hostname, status, dir }] */
21
10
  export function localApps(home) {
22
- const dir = appsDir(home);
23
- if (!fs.existsSync(dir)) return [];
24
- return fs.readdirSync(dir).filter((d) => /^app_[0-9A-F]{12}$/.test(d)).map((d) => {
25
- try { return { ...JSON.parse(fs.readFileSync(path.join(dir, d, 'app.json'), 'utf8')), dir: path.join(dir, d) }; } catch { return null; }
26
- }).filter(Boolean);
11
+ const dir = appsDir(home);
12
+ if (!fs.existsSync(dir))
13
+ return [];
14
+ return fs.readdirSync(dir).filter((d) => /^app_[0-9A-F]{12}$/.test(d)).map((d) => {
15
+ try {
16
+ return { ...JSON.parse(fs.readFileSync(path.join(dir, d, 'app.json'), 'utf8')), dir: path.join(dir, d) };
17
+ }
18
+ catch {
19
+ return null;
20
+ }
21
+ }).filter(Boolean);
27
22
  }
28
23
  export const findLocalApp = (name, home) => localApps(home).find((a) => a.name === name) || null;
29
-
30
24
  async function deviceCredentials() {
31
- const { loadAwsIotConfig } = await import('../lib/aws-iot-config.js');
32
- const prev = process.env.ASYX_CLIENT_ID; delete process.env.ASYX_CLIENT_ID; // always the device, never an app
33
- try {
34
- const cfg = await loadAwsIotConfig();
35
- return { endpoint: cfg.endpoint, region: cfg.region, clientId: cfg.clientId, caPath: cfg.caPath, ca: fs.readFileSync(cfg.caPath), cert: fs.readFileSync(cfg.certPath), key: fs.readFileSync(cfg.keyPath) };
36
- } finally { if (prev !== undefined) process.env.ASYX_CLIENT_ID = prev; }
25
+ const { loadAwsIotConfig } = await import('../lib/aws-iot-config.js');
26
+ const prev = process.env.ASYX_CLIENT_ID;
27
+ delete process.env.ASYX_CLIENT_ID;
28
+ try {
29
+ const cfg = await loadAwsIotConfig();
30
+ return { endpoint: cfg.endpoint, region: cfg.region, clientId: cfg.clientId, caPath: cfg.caPath, ca: fs.readFileSync(cfg.caPath), cert: fs.readFileSync(cfg.certPath), key: fs.readFileSync(cfg.keyPath) };
31
+ }
32
+ finally {
33
+ if (prev !== undefined)
34
+ process.env.ASYX_CLIENT_ID = prev;
35
+ }
37
36
  }
38
37
  async function defaultSend(credentials, command) {
39
- const { sendAppCreate } = await import('#tunnel-core/flows/identity.js');
40
- const { default: logger } = await import('#tunnel-core/lib/logger.js');
41
- return sendAppCreate({ credentials, command, logger });
38
+ const { sendAppCreate } = await import('#tunnel-core/flows/identity.js');
39
+ const { default: logger } = await import('#tunnel-core/lib/logger.js');
40
+ return sendAppCreate({ credentials, command, logger });
41
+ }
42
+ async function defaultStatus(credentials, appIds) {
43
+ const { sendAppStatus } = await import('#tunnel-core/flows/identity.js');
44
+ const { default: logger } = await import('#tunnel-core/lib/logger.js');
45
+ return sendAppStatus({ credentials, command: { appIds }, logger });
42
46
  }
43
47
  async function defaultKeyAndCsr(appId, dir) {
44
- const { ensureKeyAndCsr } = await import('../lib/csr.js');
45
- return ensureKeyAndCsr(appId, { dir });
48
+ const { ensureKeyAndCsr } = await import('../lib/csr.js');
49
+ return ensureKeyAndCsr(appId, { dir });
46
50
  }
47
-
48
51
  const REFUSALS = {
49
- devices_only: 'Only a device can create apps. Run this on a computer set up with asyx setup.',
50
- identity_refused: 'The service did not accept this device\'s certificate. Run asyx setup again.',
51
- 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.',
52
- csr_invalid: 'The certificate request was not accepted. Run the command again.',
53
- invalid_name: 'An app name is 3 to 30 characters: lowercase letters, digits and hyphens, not starting or ending with a hyphen.',
54
- address_not_in_account: 'That address is not one of your account\'s addresses.',
55
- app_exists_other_request: 'An app with this name is being created from another request or another device.',
56
- app_id_taken: 'That app id is already used. Run the command again.',
57
- create_in_progress: 'This app is still being created. Run the command again in a moment.',
58
- create_failed_retry: 'The app could not be created and nothing was kept. Run the command again.',
59
- account_changed_retry: 'The account changed at the same moment. Run the command again.',
60
- no_port_block: 'This account has no port block yet. Contact support@asyx.ai.',
61
- address_exists: 'That address is already on your account.',
52
+ devices_only: 'Only a device can create apps. Run this on a computer set up with asyx setup.',
53
+ identity_refused: 'The service did not accept this device\'s certificate. Run asyx setup again.',
54
+ 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.',
55
+ csr_invalid: 'The certificate request was not accepted. Run the command again.',
56
+ invalid_name: 'An app name is 3 to 30 characters: lowercase letters, digits and hyphens, not starting or ending with a hyphen.',
57
+ address_not_in_account: 'That address is not one of your account\'s addresses.',
58
+ app_exists_other_request: 'An app with this name is being created from another request or another device.',
59
+ app_id_taken: 'That app id is already used. Run the command again.',
60
+ create_in_progress: 'This app is still being created. Run the command again in a moment.',
61
+ create_failed_retry: 'The app could not be created and nothing was kept. Run the command again.',
62
+ account_changed_retry: 'The account changed at the same moment. Run the command again.',
63
+ no_port_block: 'This account has no port block yet. Contact support@asyx.ai.',
64
+ address_exists: 'That address is already on your account.',
62
65
  };
63
-
64
66
  function parse(args) {
65
- const o = { json: false, rest: [] };
66
- for (let i = 0; i < args.length; i++) {
67
- const a = args[i];
68
- if (a === '--json') o.json = true;
69
- else if (a === '--random') o.random = true;
70
- else if (a === '--print') o.print = true;
71
- else if (a === '--hostname' || a === '--address' || a === '--out') { const v = args[++i]; if (!v || v.startsWith('--')) return { error: `${a} needs a value` }; o[a.slice(2)] = v; }
72
- else if (a.startsWith('--')) return { error: `unknown option ${a}` };
73
- else o.rest.push(a);
74
- }
75
- return o;
76
- }
77
-
78
- /** asyx app create */
79
- export async function cmdAppCreate(args, { home = os.homedir(), cwd = process.cwd(), send = defaultSend, credentials = deviceCredentials, keyAndCsr = defaultKeyAndCsr, out = console.log, err = console.error } = {}) {
80
- const o = parse(args);
81
- const usage = 'Usage: asyx app create <name> [--hostname <label> | --random | --address <existing>] [--json]';
82
- if (o.error || o.rest.length !== 1) { err(o.error ? `${o.error}\n${usage}` : usage); return EXIT.USAGE; }
83
- if ([o.hostname, o.random, o.address].filter(Boolean).length > 1) { err(`--hostname, --random and --address are exclusive.\n${usage}`); return EXIT.USAGE; }
84
- const name = o.rest[0].trim().toLowerCase();
85
- if (!LABEL_RE.test(name)) { err(REFUSALS.invalid_name); return EXIT.USAGE; }
86
- const say = (obj, line) => { if (o.json) out(JSON.stringify(obj)); else if (line) out(line); };
87
-
88
- // c4: an app this machine already holds is reported, nothing is created.
89
- const local = findLocalApp(name, home);
90
- if (local && local.status === 'active') {
91
- say({ ok: true, exists: true, appId: local.appId, name, hostname: local.hostname, credentials: 'this_machine', dir: local.dir },
92
- `App ${name} already exists (${local.appId}, ${local.hostname}). Its credentials are on this machine in ${local.dir}.`);
67
+ const o = { json: false, rest: [] };
68
+ for (let i = 0; i < args.length; i++) {
69
+ const a = args[i];
70
+ if (a === '--json')
71
+ o.json = true;
72
+ else if (a === '--random')
73
+ o.random = true;
74
+ else if (a === '--print')
75
+ o.print = true;
76
+ else if (a === '--replace')
77
+ o.replace = true;
78
+ else if (a === '--hostname' || a === '--address' || a === '--out') {
79
+ const v = args[++i];
80
+ if (!v || v.startsWith('--'))
81
+ return { error: `${a} needs a value` };
82
+ o[a.slice(2)] = v;
83
+ }
84
+ else if (a.startsWith('--'))
85
+ return { error: `unknown option ${a}` };
86
+ else
87
+ o.rest.push(a);
88
+ }
89
+ return o;
90
+ }
91
+ const day = (iso) => (iso ? String(iso).slice(0, 10) : null);
92
+ export async function reconcileApps({ home = os.homedir(), credentials = deviceCredentials, status = defaultStatus, out = console.log, quiet = false } = {}) {
93
+ const apps = localApps(home).filter((a) => a.status === 'active' || a.status === 'revoked');
94
+ const result = { checked: false, states: {}, removed: [] };
95
+ if (!apps.length)
96
+ return { ...result, checked: true };
97
+ let creds;
98
+ try {
99
+ creds = await credentials();
100
+ }
101
+ catch {
102
+ return { ...result, reason: 'no_device' };
103
+ }
104
+ let r;
105
+ try {
106
+ r = await status(creds, apps.map((a) => a.appId));
107
+ }
108
+ catch {
109
+ return { ...result, reason: 'unreachable' };
110
+ }
111
+ if (!r?.ok)
112
+ return { ...result, reason: r?.error || 'refused' };
113
+ for (const s of r.apps || []) {
114
+ const app = apps.find((a) => a.appId === s.appId);
115
+ if (!app)
116
+ continue;
117
+ result.states[s.appId] = s;
118
+ if (s.status === 'deleted') {
119
+ if (!quiet)
120
+ out(`App ${app.name} was deleted${s.deletedAt ? ` on ${day(s.deletedAt)}` : ''}. Removing its credentials from this machine (${app.dir}).`);
121
+ fs.rmSync(app.dir, { recursive: true, force: true });
122
+ result.removed.push(app.name);
123
+ }
124
+ else if (s.status === 'revoked' && app.status !== 'revoked') {
125
+ writeJson(path.join(app.dir, 'app.json'), { ...JSON.parse(fs.readFileSync(path.join(app.dir, 'app.json'), 'utf8')), status: 'revoked', revokedAt: s.revokedAt || null });
126
+ }
127
+ }
128
+ return { ...result, checked: true };
129
+ }
130
+ export function stoppedAppLine(name, s) {
131
+ if (!s)
132
+ return null;
133
+ if (s.status === 'revoked')
134
+ return `App ${name} was revoked${s.revokedAt ? ` on ${day(s.revokedAt)}` : ''}; it can no longer open tunnels. Create a replacement with asyx app create <new-name> --address ${s.address || '<address>'} --replace, or delete it in the console.`;
135
+ if (s.status === 'deleted')
136
+ return `App ${name} was deleted${s.deletedAt ? ` on ${day(s.deletedAt)}` : ''}; its credentials have been removed from this machine.`;
137
+ if (s.status === 'unknown')
138
+ return `App ${name} is not an app of this computer's account. If it was made under another account, run it there; otherwise asyx app forget ${name}.`;
139
+ return null;
140
+ }
141
+ export async function cmdAppCreate(args, { home = os.homedir(), cwd = process.cwd(), send = defaultSend, status = defaultStatus, credentials = deviceCredentials, keyAndCsr = defaultKeyAndCsr, out = console.log, err = console.error } = {}) {
142
+ const o = parse(args);
143
+ const usage = 'Usage: asyx app create <name> [--hostname <label> | --random | --address <existing> [--replace]] [--json]';
144
+ if (o.error || o.rest.length !== 1) {
145
+ err(o.error ? `${o.error}\n${usage}` : usage);
146
+ return EXIT.USAGE;
147
+ }
148
+ if ([o.hostname, o.random, o.address].filter(Boolean).length > 1) {
149
+ err(`--hostname, --random and --address are exclusive.\n${usage}`);
150
+ return EXIT.USAGE;
151
+ }
152
+ if (o.replace && !o.address) {
153
+ err(`--replace takes another app's address: use it with --address <existing>.\n${usage}`);
154
+ return EXIT.USAGE;
155
+ }
156
+ const name = o.rest[0].trim().toLowerCase();
157
+ if (!LABEL_RE.test(name)) {
158
+ err(REFUSALS.invalid_name);
159
+ return EXIT.USAGE;
160
+ }
161
+ const say = (obj, line) => { if (o.json)
162
+ out(JSON.stringify(obj));
163
+ else if (line)
164
+ out(line); };
165
+ await reconcileApps({ home, credentials, status, out: o.json ? () => { } : out });
166
+ const local = findLocalApp(name, home);
167
+ if (local && local.status === 'revoked') {
168
+ err(`App ${name} was revoked. Choose another name for its replacement (asyx app create <new-name> --address ${local.address || '<address>'} --replace), or delete ${name} in the console first.`);
169
+ return EXIT.FAILED;
170
+ }
171
+ if (local && local.status === 'active') {
172
+ say({ ok: true, exists: true, appId: local.appId, name, hostname: local.hostname, credentials: 'this_machine', dir: local.dir }, `App ${name} already exists (${local.appId}, ${local.hostname}). Its credentials are on this machine in ${local.dir}.`);
173
+ return EXIT.OK;
174
+ }
175
+ let creds;
176
+ try {
177
+ creds = await credentials();
178
+ }
179
+ catch {
180
+ say({ ok: false, error: 'setup_required' });
181
+ if (!o.json)
182
+ err('This computer is not set up yet. Run asyx setup first.');
183
+ return EXIT.FAILED;
184
+ }
185
+ const appId = local?.appId || newAppId();
186
+ const dir = path.join(appsDir(home), appId);
187
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
188
+ fs.chmodSync(dir, 0o700);
189
+ const { csrPem } = await keyAndCsr(appId, dir);
190
+ if (!local)
191
+ writeJson(path.join(dir, 'app.json'), { appId, name, status: 'pending', createdBy: creds.clientId });
192
+ let r;
193
+ try {
194
+ r = await send(creds, { name, csrPem, ...(o.hostname ? { hostname: o.hostname } : {}), ...(o.random ? { random: true } : {}), ...(o.address ? { address: o.address } : {}), ...(o.replace ? { replace: true } : {}) });
195
+ }
196
+ catch (e) {
197
+ say({ ok: false, error: e.code || 'network_error', message: e.message });
198
+ if (!o.json)
199
+ err(`Could not reach the service: ${e.message}. Run the same command again; it will not create a second app.`);
200
+ return EXIT.FAILED;
201
+ }
202
+ if (r?.ok && r.exists) {
203
+ fs.rmSync(dir, { recursive: true, force: true });
204
+ say({ ...r, credentials: 'another_machine' }, `App ${name} already exists (${r.appId}, ${r.hostname}). Its credentials are on another machine${r.createdBy ? ` (created from device ${r.createdBy})` : ''}; export them there with asyx app export ${name}.`);
205
+ return EXIT.OK;
206
+ }
207
+ if (r?.ok) {
208
+ fs.writeFileSync(path.join(dir, 'device.pem.crt'), r.certificatePem, { mode: 0o600 });
209
+ fs.copyFileSync(creds.caPath, path.join(dir, 'AmazonRootCA1.pem'));
210
+ writeJson(path.join(dir, 'manifest.json'), { endpoint: r.endpoint || creds.endpoint, region: creds.region || 'us-east-1' });
211
+ writeJson(path.join(dir, 'app.json'), { appId: r.appId, name, hostname: r.hostname, address: r.address, status: 'active', createdBy: creds.clientId });
212
+ for (const f of fs.readdirSync(dir))
213
+ fs.chmodSync(path.join(dir, f), 0o600);
214
+ writeJson(path.join(cwd, 'asyx.json'), { app: name, appId: r.appId, hostname: r.hostname }, 0o644);
215
+ say({ ok: true, appId: r.appId, name, hostname: r.hostname, address: r.address, dir, project: path.join(cwd, 'asyx.json') }, `App ${name} created (${r.appId}): it serves https://${r.hostname}${r.replaces ? `\nIt replaces ${r.replaces}, which can no longer serve this address; revoke or delete it in the console.` : ''}\nCredentials: ${dir} (only on this machine)\nProject: asyx.json written here (no secrets)\nRun it: asyx tunnel --http --port <port> --app ${name}`);
216
+ return EXIT.OK;
217
+ }
218
+ const e = r?.error || 'refused';
219
+ if (!['create_in_progress', 'app_exists_other_request'].includes(e))
220
+ fs.rmSync(dir, { recursive: true, force: true });
221
+ if (o.json)
222
+ out(JSON.stringify(r));
223
+ if (/^hostname_/.test(e)) {
224
+ if (!o.json) {
225
+ const label = o.hostname || name;
226
+ err(describeAnswer({ status: e, label, hostname: `${label}.tunnel.asyx.ai`, suggestions: r.suggestions || [] }));
227
+ }
228
+ return EXIT.NAME_UNAVAILABLE;
229
+ }
230
+ if (!o.json) {
231
+ if (e === 'address_limit_reached')
232
+ err(`Your plan allows ${r.limit} addresses and they are all in use. Delete one in the console first, or use --address <existing>.`);
233
+ else if (e === 'address_has_app')
234
+ err(`${r.address} already has an app (${r.app}). An address has at most one app; to replace that app, add --replace.`);
235
+ else
236
+ err(REFUSALS[e] || `The service refused the request (${e}).`);
237
+ }
238
+ return EXIT.FAILED;
239
+ }
240
+ export async function cmdAppExport(args, { home = os.homedir(), stdoutIsTTY = process.stdout.isTTY, write = (s) => process.stdout.write(s), status = defaultStatus, credentials = deviceCredentials, out = console.log, err = console.error } = {}) {
241
+ const o = parse(args);
242
+ if (o.error || o.rest.length !== 1) {
243
+ err('Usage: asyx app export <name> (--out <path> | --print)');
244
+ return EXIT.USAGE;
245
+ }
246
+ const rec = await reconcileApps({ home, credentials, status, out: err });
247
+ const app = findLocalApp(o.rest[0].trim().toLowerCase(), home);
248
+ if (app && app.status === 'revoked') {
249
+ err(stoppedAppLine(app.name, rec.states[app.appId] || { status: 'revoked', revokedAt: app.revokedAt, address: app.address }));
250
+ return EXIT.FAILED;
251
+ }
252
+ if (!app || app.status !== 'active') {
253
+ err(`No app named ${o.rest[0]} on this machine. asyx app list shows the apps kept here.`);
254
+ return EXIT.FAILED;
255
+ }
256
+ const read = (f) => fs.readFileSync(path.join(app.dir, f), 'utf8');
257
+ const bundle = JSON.stringify({ appId: app.appId, name: app.name, hostname: app.hostname, ...JSON.parse(read('manifest.json')), certificatePem: read('device.pem.crt'), privateKeyPem: read('private.pem.key'), caPem: read('AmazonRootCA1.pem') }, null, 2) + '\n';
258
+ if (o.out) {
259
+ fs.writeFileSync(o.out, bundle, { mode: 0o600 });
260
+ fs.chmodSync(o.out, 0o600);
261
+ out(`Wrote ${app.name}'s credentials to ${o.out} (owner-only). Keep it out of your project and version control.`);
262
+ return EXIT.OK;
263
+ }
264
+ if (stdoutIsTTY && !o.print) {
265
+ err('This would print a private key to the terminal. Use --out <path>, pipe it, or add --print.');
266
+ return EXIT.USAGE;
267
+ }
268
+ write(bundle);
93
269
  return EXIT.OK;
94
- }
95
- let creds;
96
- try { creds = await credentials(); }
97
- catch { say({ ok: false, error: 'setup_required' }); if (!o.json) err('This computer is not set up yet. Run asyx setup first.'); return EXIT.FAILED; }
98
-
99
- // A create that did not finish keeps its id, key and CSR, so running it again sends the same request (c14).
100
- const appId = local?.appId || newAppId();
101
- const dir = path.join(appsDir(home), appId);
102
- fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
103
- fs.chmodSync(dir, 0o700);
104
- const { csrPem } = await keyAndCsr(appId, dir);
105
- if (!local) writeJson(path.join(dir, 'app.json'), { appId, name, status: 'pending', createdBy: creds.clientId });
106
-
107
- let r;
108
- try { r = await send(creds, { name, csrPem, ...(o.hostname ? { hostname: o.hostname } : {}), ...(o.random ? { random: true } : {}), ...(o.address ? { address: o.address } : {}) }); }
109
- catch (e) { say({ ok: false, error: e.code || 'network_error', message: e.message }); if (!o.json) err(`Could not reach the service: ${e.message}. Run the same command again; it will not create a second app.`); return EXIT.FAILED; }
110
-
111
- if (r?.ok && r.exists) { // the name is taken by an app whose credentials are not on this machine
112
- fs.rmSync(dir, { recursive: true, force: true });
113
- say({ ...r, credentials: 'another_machine' }, `App ${name} already exists (${r.appId}, ${r.hostname}). Its credentials are on another machine${r.createdBy ? ` (created from device ${r.createdBy})` : ''}; export them there with asyx app export ${name}.`);
270
+ }
271
+ export async function cmdAppList(args, { home = os.homedir(), status = defaultStatus, credentials = deviceCredentials, out = console.log } = {}) {
272
+ const json = args.includes('--json');
273
+ const rec = await reconcileApps({ home, credentials, status, out: json ? () => { } : out });
274
+ const apps = localApps(home).map(({ appId, name, hostname, status: local }) => {
275
+ const s = rec.states[appId];
276
+ return { appId, name, hostname: s?.hostname || hostname, status: s?.status || local, checked: !!s };
277
+ });
278
+ if (json) {
279
+ out(JSON.stringify(apps));
280
+ return EXIT.OK;
281
+ }
282
+ if (!apps.length)
283
+ out('No apps on this machine. Create one with asyx app create <name>.');
284
+ else
285
+ for (const a of apps)
286
+ out(`${a.name} ${a.hostname || '-'} ${a.appId} ${a.status}`);
287
+ if (apps.length && !rec.checked)
288
+ out(rec.reason === 'no_device' ? '(states as last known here: this computer is not set up, so the service was not asked)' : `(states as last known here: the service could not be asked${rec.reason && rec.reason !== 'unreachable' ? ` (${rec.reason})` : ''})`);
114
289
  return EXIT.OK;
115
- }
116
- if (r?.ok) {
117
- fs.writeFileSync(path.join(dir, 'device.pem.crt'), r.certificatePem, { mode: 0o600 });
118
- fs.copyFileSync(creds.caPath, path.join(dir, 'AmazonRootCA1.pem'));
119
- writeJson(path.join(dir, 'manifest.json'), { endpoint: r.endpoint || creds.endpoint, region: creds.region || 'us-east-1' });
120
- writeJson(path.join(dir, 'app.json'), { appId: r.appId, name, hostname: r.hostname, address: r.address, status: 'active', createdBy: creds.clientId });
121
- for (const f of fs.readdirSync(dir)) fs.chmodSync(path.join(dir, f), 0o600);
122
- writeJson(path.join(cwd, 'asyx.json'), { app: name, appId: r.appId, hostname: r.hostname }, 0o644);
123
- say({ ok: true, appId: r.appId, name, hostname: r.hostname, address: r.address, dir, project: path.join(cwd, 'asyx.json') },
124
- `App ${name} created (${r.appId}): it serves https://${r.hostname}\nCredentials: ${dir} (only on this machine)\nProject: asyx.json written here (no secrets)\nRun it: asyx tunnel --http --port <port> --app ${name}`);
290
+ }
291
+ export function cmdAppForget(args, { home = os.homedir(), out = console.log, err = console.error } = {}) {
292
+ const o = parse(args);
293
+ if (o.error || o.rest.length !== 1) {
294
+ err('Usage: asyx app forget <name>');
295
+ return EXIT.USAGE;
296
+ }
297
+ const app = findLocalApp(o.rest[0].trim().toLowerCase(), home);
298
+ if (!app) {
299
+ err(`No app named ${o.rest[0]} on this machine. asyx app list shows the apps kept here.`);
300
+ return EXIT.FAILED;
301
+ }
302
+ fs.rmSync(app.dir, { recursive: true, force: true });
303
+ out(`Removed ${app.name}'s credentials from this machine (${app.dir}).${app.status === 'active' ? ' The app still exists on your account; delete it in the console to stop it everywhere.' : ''}`);
125
304
  return EXIT.OK;
126
- }
127
- const e = r?.error || 'refused';
128
- if (!['create_in_progress', 'app_exists_other_request'].includes(e)) fs.rmSync(dir, { recursive: true, force: true }); // nothing was kept
129
- if (o.json) out(JSON.stringify(r));
130
- if (/^hostname_/.test(e)) {
131
- if (!o.json) { const label = o.hostname || name; err(describeAnswer({ status: e, label, hostname: `${label}.tunnel.asyx.ai`, suggestions: r.suggestions || [] })); }
132
- return EXIT.NAME_UNAVAILABLE;
133
- }
134
- if (!o.json) {
135
- if (e === 'address_limit_reached') err(`Your plan allows ${r.limit} addresses and they are all in use. Delete one in the console first, or use --address <existing>.`);
136
- else if (e === 'address_has_app') err(`${r.address} already has an app (${r.app}). An address has at most one app.`);
137
- else err(REFUSALS[e] || `The service refused the request (${e}).`);
138
- }
139
- return EXIT.FAILED;
140
- }
141
-
142
- /** asyx app export: never prints credentials to a terminal without --print (c5). */
143
- export async function cmdAppExport(args, { home = os.homedir(), stdoutIsTTY = process.stdout.isTTY, write = (s) => process.stdout.write(s), out = console.log, err = console.error } = {}) {
144
- const o = parse(args);
145
- if (o.error || o.rest.length !== 1) { err('Usage: asyx app export <name> (--out <path> | --print)'); return EXIT.USAGE; }
146
- const app = findLocalApp(o.rest[0].trim().toLowerCase(), home);
147
- if (!app || app.status !== 'active') { err(`No app named ${o.rest[0]} on this machine. asyx app list shows the apps kept here.`); return EXIT.FAILED; }
148
- const read = (f) => fs.readFileSync(path.join(app.dir, f), 'utf8');
149
- const bundle = JSON.stringify({ appId: app.appId, name: app.name, hostname: app.hostname, ...JSON.parse(read('manifest.json')), certificatePem: read('device.pem.crt'), privateKeyPem: read('private.pem.key'), caPem: read('AmazonRootCA1.pem') }, null, 2) + '\n';
150
- if (o.out) { fs.writeFileSync(o.out, bundle, { mode: 0o600 }); fs.chmodSync(o.out, 0o600); out(`Wrote ${app.name}'s credentials to ${o.out} (owner-only). Keep it out of your project and version control.`); return EXIT.OK; }
151
- if (stdoutIsTTY && !o.print) { err('This would print a private key to the terminal. Use --out <path>, pipe it, or add --print.'); return EXIT.USAGE; }
152
- write(bundle);
153
- return EXIT.OK;
154
- }
155
-
156
- export function cmdAppList(args, { home = os.homedir(), out = console.log } = {}) {
157
- const apps = localApps(home).map(({ appId, name, hostname, status }) => ({ appId, name, hostname, status }));
158
- if (args.includes('--json')) out(JSON.stringify(apps));
159
- else if (!apps.length) out('No apps on this machine. Create one with asyx app create <name>.');
160
- else for (const a of apps) out(`${a.name} ${a.hostname || '-'} ${a.appId}${a.status !== 'active' ? ` (${a.status})` : ''}`);
161
- return EXIT.OK;
162
- }
163
-
164
- /** `asyx tunnel ... --app <name>`: run the tunnel as the app (its own certificate and address). */
305
+ }
306
+ export async function explainAppFailure(appId, { home = os.homedir(), credentials = deviceCredentials, status = defaultStatus, err = console.error } = {}) {
307
+ const app = localApps(home).find((a) => a.appId === appId);
308
+ if (!app)
309
+ return false;
310
+ const rec = await reconcileApps({ home, credentials, status, quiet: true });
311
+ const line = stoppedAppLine(app.name, rec.states[appId]);
312
+ if (line) {
313
+ err(`❌ ${line}`);
314
+ return true;
315
+ }
316
+ return false;
317
+ }
165
318
  export function appIdForTunnel(name, home = os.homedir()) {
166
- const app = findLocalApp(String(name || '').trim().toLowerCase(), home);
167
- return app && app.status === 'active' ? app.appId : null;
319
+ const app = findLocalApp(String(name || '').trim().toLowerCase(), home);
320
+ return app && app.status === 'active' ? app.appId : null;
321
+ }
322
+ export function appRefusalForTunnel(name, home = os.homedir()) {
323
+ const app = findLocalApp(String(name || '').trim().toLowerCase(), home);
324
+ if (!app)
325
+ return `No app named ${name || ''} on this machine. asyx app list shows the apps kept here.`;
326
+ if (app.status === 'revoked')
327
+ return stoppedAppLine(app.name, { status: 'revoked', revokedAt: app.revokedAt, address: app.address });
328
+ if (app.status !== 'active')
329
+ return `App ${app.name} was not fully created. Run asyx app create ${app.name} again.`;
330
+ return null;
168
331
  }
169
-
170
332
  export default async function cmdApp(argv, opts) {
171
- const [sub, ...rest] = argv;
172
- if (sub === 'create') return cmdAppCreate(rest, opts);
173
- if (sub === 'export') return cmdAppExport(rest, opts);
174
- if (sub === 'list') return cmdAppList(rest, opts);
175
- (opts?.err || console.error)('Usage: asyx app create <name> | asyx app export <name> | asyx app list');
176
- return EXIT.USAGE;
177
- }
178
-
333
+ const [sub, ...rest] = argv;
334
+ if (sub === 'create')
335
+ return cmdAppCreate(rest, opts);
336
+ if (sub === 'export')
337
+ return cmdAppExport(rest, opts);
338
+ if (sub === 'list')
339
+ return cmdAppList(rest, opts);
340
+ if (sub === 'forget')
341
+ return cmdAppForget(rest, opts);
342
+ (opts?.err || console.error)('Usage: asyx app create <name> | asyx app export <name> | asyx app list | asyx app forget <name>');
343
+ return EXIT.USAGE;
344
+ }
179
345
  function writeJson(p, obj, mode = 0o600) { fs.writeFileSync(p, JSON.stringify(obj, null, 2) + '\n', { mode }); }
180
346
  export { CA_URL };
@@ -1,64 +1,63 @@
1
- // Story 1.9 r2: what the CLI says when an address already runs a tunnel of this kind, while it waits,
2
- // and when a newer tunnel took the address over. Never an IP address. Exit code 75 (EX_TEMPFAIL:
3
- // "try again later") so a service manager can be told not to restart on it.
4
1
  import { setReplacedReporter } from '#tunnel-core/mqtt/events/handlers.js';
5
-
6
2
  export const EXIT_IN_USE = 75;
7
3
  export const tunnelOutput = { json: false, kindFlag: null, rerun: null };
8
-
9
4
  function clock(iso) {
10
- if (!iso) return null;
11
- const t = new Date(iso);
12
- if (Number.isNaN(t.getTime())) return null;
13
- const hm = t.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' });
14
- return t.toDateString() === new Date().toDateString() ? hm : `${t.toLocaleDateString([], { day: 'numeric', month: 'short' })} ${hm}`;
5
+ if (!iso)
6
+ return null;
7
+ const t = new Date(iso);
8
+ if (Number.isNaN(t.getTime()))
9
+ return null;
10
+ const hm = t.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' });
11
+ return t.toDateString() === new Date().toDateString() ? hm : `${t.toLocaleDateString([], { day: 'numeric', month: 'short' })} ${hm}`;
15
12
  }
16
-
17
- /** The refusal as lines of text (exported for tests). */
18
13
  export function inUseText(d = {}, { rerun = null } = {}) {
19
- const kind = String(d.kind || 'this').toUpperCase();
20
- const where = d.sameComputer ? 'this computer' : (d.machine ? `${d.machine}` : 'another connection');
21
- const since = clock(d.since);
22
- const serving = d.localPort ? ` (serving localhost:${d.localPort})` : '';
23
- const addr = d.hostname || 'This address';
24
- const lines = [
25
- `${addr} already has a${kind === 'HTTP' ? 'n' : ''} ${kind} tunnel from ${where}${since ? ` since ${since}` : ''}${serving}.`,
26
- `One address runs one ${kind} tunnel at a time.`,
27
- ];
28
- if (d.sameComputer) lines.push('Stop that tunnel first, or add --replace to take over.');
29
- else lines.push('If you moved this address on purpose, add --replace to take over. If that computer just lost its network, the address frees up within a minute; add --wait to keep trying.');
30
- if (rerun) lines.push(` ${rerun} --replace`);
31
- return lines.join('\n');
14
+ const kind = String(d.kind || 'this').toUpperCase();
15
+ const where = d.sameComputer ? 'this computer' : (d.machine ? `${d.machine}` : 'another connection');
16
+ const since = clock(d.since);
17
+ const serving = d.localPort ? ` (serving localhost:${d.localPort})` : '';
18
+ const addr = d.hostname || 'This address';
19
+ const lines = [
20
+ `${addr} already has a${kind === 'HTTP' ? 'n' : ''} ${kind} tunnel from ${where}${since ? ` since ${since}` : ''}${serving}.`,
21
+ `One address runs one ${kind} tunnel at a time.`,
22
+ ];
23
+ if (d.sameComputer)
24
+ lines.push('Stop that tunnel first, or add --replace to take over.');
25
+ else
26
+ lines.push('If you moved this address on purpose, add --replace to take over. If that computer just lost its network, the address frees up within a minute; add --wait to keep trying.');
27
+ if (rerun)
28
+ lines.push(` ${rerun} --replace`);
29
+ return lines.join('\n');
32
30
  }
33
-
34
31
  export function exitInUse(d = {}) {
35
- if (tunnelOutput.json) {
36
- process.stdout.write(JSON.stringify({ error: 'address_in_use', kind: d.kind ?? null, hostname: d.hostname ?? null, since: d.since ?? null, machine: d.machine ?? null, sameComputer: d.sameComputer === true, localPort: d.localPort ?? null, retryable: true }) + '\n');
37
- } else {
38
- process.stderr.write(`❌ ${inUseText(d, { rerun: tunnelOutput.rerun })}\n`);
39
- }
40
- process.exit(EXIT_IN_USE);
32
+ if (tunnelOutput.json) {
33
+ process.stdout.write(JSON.stringify({ error: 'address_in_use', kind: d.kind ?? null, hostname: d.hostname ?? null, since: d.since ?? null, machine: d.machine ?? null, sameComputer: d.sameComputer === true, localPort: d.localPort ?? null, retryable: true }) + '\n');
34
+ }
35
+ else {
36
+ process.stderr.write(`❌ ${inUseText(d, { rerun: tunnelOutput.rerun })}\n`);
37
+ }
38
+ process.exit(EXIT_IN_USE);
41
39
  }
42
-
43
40
  let lastWaitKey = '';
44
41
  export function printWaiting({ details = {}, delayMs, sameComputer }) {
45
- const key = `${sameComputer}|${details.machine}|${details.since}`;
46
- if (key === lastWaitKey) return; // one line per change
47
- lastWaitKey = key;
48
- if (sameComputer) process.stdout.write('⏳ Waiting for the previous tunnel on this computer to close…\n');
49
- else process.stdout.write(`⏳ ${details.hostname || 'The address'} is in use by ${details.machine || 'another connection'}; trying again every ${Math.round(delayMs / 1000)} s (--wait). Press Ctrl+C to stop.\n`);
42
+ const key = `${sameComputer}|${details.machine}|${details.since}`;
43
+ if (key === lastWaitKey)
44
+ return;
45
+ lastWaitKey = key;
46
+ if (sameComputer)
47
+ process.stdout.write('⏳ Waiting for the previous tunnel on this computer to close…\n');
48
+ else
49
+ process.stdout.write(`⏳ ${details.hostname || 'The address'} is in use by ${details.machine || 'another connection'}; trying again every ${Math.round(delayMs / 1000)} s (--wait). Press Ctrl+C to stop.\n`);
50
50
  }
51
-
52
- /** The text when a newer tunnel took this address over (exported for tests). */
53
51
  export function replacedText(r = {}) {
54
- const at = clock(r.at) || 'just now';
55
- const kind = r.kind ? String(r.kind).toUpperCase() + ' ' : '';
56
- const by = r.by ? ` from ${r.by}` : '';
57
- return `This ${kind}tunnel was taken over at ${at} by a new tunnel${by} for the same address (--replace). It has stopped and will not reconnect.`;
52
+ const at = clock(r.at) || 'just now';
53
+ const kind = r.kind ? String(r.kind).toUpperCase() + ' ' : '';
54
+ const by = r.by ? ` from ${r.by}` : '';
55
+ return `This ${kind}tunnel was taken over at ${at} by a new tunnel${by} for the same address (--replace). It has stopped and will not reconnect.`;
58
56
  }
59
-
60
57
  setReplacedReporter((r) => {
61
- if (tunnelOutput.json) process.stdout.write(JSON.stringify({ error: 'replaced', kind: r.kind ?? null, at: r.at ?? null, by: r.by ?? null }) + '\n');
62
- else process.stderr.write(`❌ ${replacedText(r)}\n`);
63
- process.exit(EXIT_IN_USE);
58
+ if (tunnelOutput.json)
59
+ process.stdout.write(JSON.stringify({ error: 'replaced', kind: r.kind ?? null, at: r.at ?? null, by: r.by ?? null }) + '\n');
60
+ else
61
+ process.stderr.write(`❌ ${replacedText(r)}\n`);
62
+ process.exit(EXIT_IN_USE);
64
63
  });