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.
- package/AGENTS.md +42 -0
- package/bin/asyx.js +1 -1
- package/package.json +3 -2
- package/src/commands/account.js +80 -71
- package/src/commands/app.js +317 -151
- package/src/commands/in-use-messages.js +47 -48
- package/src/commands/mqtt-broker.js +36 -49
- package/src/commands/mqtt.js +111 -149
- package/src/commands/name.js +24 -22
- package/src/commands/reject-messages.js +123 -123
- package/src/commands/setup.js +107 -131
- package/src/commands/sts.js +45 -61
- package/src/commands/tunnel.js +853 -932
- package/src/commands/validate-target-host.js +36 -59
- package/src/lib/aws-iot-config.js +26 -24
- package/src/lib/certs.js +15 -18
- package/src/lib/csr.js +107 -182
- package/src/lib/device.js +26 -37
- package/src/lib/ids.js +1 -2
- package/src/lib/naming.js +74 -68
- package/src/lib/pairing.js +10 -11
- package/src/lib/shared-transport.js +5 -9
- package/src/main.js +63 -53
- package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneClient.js +25 -287
- package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneTransport.js +0 -72
- package/vendor/tunnel-core/dist/control-plane/session.js +0 -20
- package/vendor/tunnel-core/dist/errors.js +0 -19
- package/vendor/tunnel-core/dist/flows/account.js +1 -6
- package/vendor/tunnel-core/dist/flows/goodbye.js +0 -4
- package/vendor/tunnel-core/dist/flows/http.js +24 -112
- package/vendor/tunnel-core/dist/flows/identity.js +11 -10
- package/vendor/tunnel-core/dist/flows/in-use.js +0 -6
- package/vendor/tunnel-core/dist/flows/reopen.js +0 -4
- package/vendor/tunnel-core/dist/flows/tcp.js +18 -84
- package/vendor/tunnel-core/dist/flows/udp.js +15 -52
- package/vendor/tunnel-core/dist/lib/fingerprint.js +38 -42
- package/vendor/tunnel-core/dist/lib/jwt-verifier.js +14 -67
- package/vendor/tunnel-core/dist/lib/logger.js +1 -9
- package/vendor/tunnel-core/dist/lib/refresh-helpers.js +1 -22
- package/vendor/tunnel-core/dist/lifecycle.js +1 -8
- package/vendor/tunnel-core/dist/mqtt/awaiter-map.js +1 -53
- package/vendor/tunnel-core/dist/mqtt/events/handlers.js +10 -64
- package/vendor/tunnel-core/dist/mqtt/events/index.js +3 -36
- package/vendor/tunnel-core/dist/mqtt/events/schemas.js +0 -1
- package/vendor/tunnel-core/dist/mqtt/ingress.js +0 -60
- package/vendor/tunnel-core/dist/state/assignment.js +6 -122
- package/vendor/tunnel-core/dist/state/instance-registry.js +0 -63
- package/vendor/tunnel-core/dist/tcp-v1/framing.js +2 -64
- package/vendor/tunnel-core/dist/tunnel/http-tunnel.js +64 -331
- package/vendor/tunnel-core/dist/tunnel/httpws-constants.js +5 -14
- package/vendor/tunnel-core/dist/tunnel/reconnect.js +10 -50
- package/vendor/tunnel-core/dist/tunnel/request-sink.js +0 -16
- package/vendor/tunnel-core/dist/tunnel/tcp-tunnel.js +32 -195
- package/vendor/tunnel-core/dist/tunnel/udp-tunnel.js +28 -153
- package/vendor/tunnel-core/dist/tunnel/ws-control.js +4 -39
- package/vendor/tunnel-core/dist/types.js +0 -2
- package/vendor/tunnel-core/dist/udp-v1/framing.js +2 -64
- package/vendor/tunnel-core/package.json +0 -25
- package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneClient.d.ts +0 -273
- package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneTransport.d.ts +0 -79
- package/vendor/tunnel-core/dist/control-plane/session.d.ts +0 -55
- package/vendor/tunnel-core/dist/errors.d.ts +0 -49
- package/vendor/tunnel-core/dist/flows/account.d.ts +0 -24
- package/vendor/tunnel-core/dist/flows/goodbye.d.ts +0 -10
- package/vendor/tunnel-core/dist/flows/http.d.ts +0 -61
- package/vendor/tunnel-core/dist/flows/identity.d.ts +0 -23
- package/vendor/tunnel-core/dist/flows/in-use.d.ts +0 -27
- package/vendor/tunnel-core/dist/flows/reopen.d.ts +0 -9
- package/vendor/tunnel-core/dist/flows/tcp.d.ts +0 -85
- package/vendor/tunnel-core/dist/flows/udp.d.ts +0 -52
- package/vendor/tunnel-core/dist/lib/adapt-logger.d.ts +0 -2
- package/vendor/tunnel-core/dist/lib/fingerprint.d.ts +0 -145
- package/vendor/tunnel-core/dist/lib/jwt-verifier.d.ts +0 -27
- package/vendor/tunnel-core/dist/lib/logger.d.ts +0 -9
- package/vendor/tunnel-core/dist/lib/refresh-helpers.d.ts +0 -16
- package/vendor/tunnel-core/dist/lifecycle.d.ts +0 -24
- package/vendor/tunnel-core/dist/mqtt/awaiter-map.d.ts +0 -56
- package/vendor/tunnel-core/dist/mqtt/events/handlers.d.ts +0 -60
- package/vendor/tunnel-core/dist/mqtt/events/index.d.ts +0 -1
- package/vendor/tunnel-core/dist/mqtt/events/schemas.d.ts +0 -498
- package/vendor/tunnel-core/dist/mqtt/ingress.d.ts +0 -63
- package/vendor/tunnel-core/dist/state/assignment.d.ts +0 -136
- package/vendor/tunnel-core/dist/state/instance-registry.d.ts +0 -88
- package/vendor/tunnel-core/dist/tcp-v1/framing.d.ts +0 -43
- package/vendor/tunnel-core/dist/tunnel/http-tunnel.d.ts +0 -140
- package/vendor/tunnel-core/dist/tunnel/httpws-constants.d.ts +0 -13
- package/vendor/tunnel-core/dist/tunnel/reconnect.d.ts +0 -76
- package/vendor/tunnel-core/dist/tunnel/request-sink.d.ts +0 -40
- package/vendor/tunnel-core/dist/tunnel/tcp-tunnel.d.ts +0 -92
- package/vendor/tunnel-core/dist/tunnel/udp-tunnel.d.ts +0 -93
- package/vendor/tunnel-core/dist/tunnel/ws-control.d.ts +0 -22
- package/vendor/tunnel-core/dist/types.d.ts +0 -24
- package/vendor/tunnel-core/dist/udp-v1/framing.d.ts +0 -41
package/src/commands/app.js
CHANGED
|
@@ -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
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
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
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
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
|
-
|
|
40
|
-
|
|
41
|
-
|
|
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
|
-
|
|
45
|
-
|
|
48
|
+
const { ensureKeyAndCsr } = await import('../lib/csr.js');
|
|
49
|
+
return ensureKeyAndCsr(appId, { dir });
|
|
46
50
|
}
|
|
47
|
-
|
|
48
51
|
const REFUSALS = {
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
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
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
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
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
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
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
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
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
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
|
-
|
|
167
|
-
|
|
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
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
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
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
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
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
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
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
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
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
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
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
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
|
-
|
|
62
|
-
|
|
63
|
-
|
|
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
|
});
|