asyx 0.9.2 → 0.10.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "asyx",
3
- "version": "0.9.2",
3
+ "version": "0.10.0",
4
4
  "description": "Asyx tunnel CLI — secure localhost exposure (HTTP, TCP, UDP)",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -30,6 +30,7 @@
30
30
  "bin/",
31
31
  "src/commands/.gitkeep",
32
32
  "src/commands/account.js",
33
+ "src/commands/app.js",
33
34
  "src/commands/in-use-messages.js",
34
35
  "src/commands/mqtt-broker.js",
35
36
  "src/commands/mqtt.js",
@@ -0,0 +1,180 @@
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
+ import fs from 'node:fs';
10
+ import path from 'node:path';
11
+ import os from 'node:os';
12
+ import { randomBytes } from 'node:crypto';
13
+ import { EXIT, describeAnswer } from '../lib/naming.js';
14
+
15
+ const LABEL_RE = /^[a-z0-9](?:[a-z0-9-]{1,28}[a-z0-9])$/;
16
+ const CA_URL = 'https://www.amazontrust.com/repository/AmazonRootCA1.pem';
17
+ export const appsDir = (home = os.homedir()) => path.join(home, '.asyx', 'apps');
18
+ export const newAppId = () => `app_${randomBytes(6).toString('hex').toUpperCase()}`;
19
+
20
+ /** The apps kept on this machine: [{ appId, name, hostname, status, dir }] */
21
+ 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);
27
+ }
28
+ export const findLocalApp = (name, home) => localApps(home).find((a) => a.name === name) || null;
29
+
30
+ async function deviceCredentials() {
31
+ const { loadAwsIotConfig } = await import('@asyx/mqtt-broker-aws');
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; }
37
+ }
38
+ 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 });
42
+ }
43
+ async function defaultKeyAndCsr(appId, dir) {
44
+ const { ensureKeyAndCsr } = await import('../lib/csr.js');
45
+ return ensureKeyAndCsr(appId, { dir });
46
+ }
47
+
48
+ 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.',
62
+ };
63
+
64
+ 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}.`);
93
+ 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}.`);
114
+ 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}`);
125
+ 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). */
165
+ 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;
168
+ }
169
+
170
+ 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
+
179
+ function writeJson(p, obj, mode = 0o600) { fs.writeFileSync(p, JSON.stringify(obj, null, 2) + '\n', { mode }); }
180
+ export { CA_URL };
package/src/lib/csr.js CHANGED
@@ -107,7 +107,8 @@ async function importPrivateKey(pkcs8Bytes) {
107
107
 
108
108
  export async function ensureKeyAndCsr(clientId, options = {}) {
109
109
  const { baseDir } = options;
110
- const dir = certsDirFor(clientId, baseDir);
110
+ // Story 12.2: an app's key and CSR are made in its own folder (~/.asyx/apps/<appId>/), options.dir.
111
+ const dir = options.dir || certsDirFor(clientId, baseDir);
111
112
  await ensureDir(dir);
112
113
  const keyPath = path.join(dir, 'private.pem.key');
113
114
  const csrPath = path.join(dir, 'device.csr.pem');
package/src/main.js CHANGED
@@ -36,6 +36,9 @@ Usage: asyx <command>
36
36
  port release --tcp|--udp <port>
37
37
  Give a port back to your account's block (not while a tunnel runs on it)
38
38
  tunnel Open an HTTP, TCP or UDP tunnel to a local port
39
+ app create <name> Create an app identity (its own key, certificate and address) from this device
40
+ app export <name> Hand an app's credentials over (--out <path>, a pipe, or --print)
41
+ app list The apps kept on this machine
39
42
  help Show this help
40
43
 
41
44
  Examples:
@@ -47,6 +50,8 @@ Usage: asyx <command>
47
50
  asyx tunnel --http --port 3000 --to orders-api.tunnel.asyx.ai
48
51
  asyx tunnel --tcp --port 5432 --to orders-api.tunnel.asyx.ai
49
52
  asyx tunnel --udp --port 27015 --to orders-api.tunnel.asyx.ai
53
+ asyx app create orders-api (--hostname <label>, --random or --address <existing>)
54
+ asyx tunnel --http --port 3000 --app orders-api
50
55
 
51
56
  Options for each tunnel type: asyx tunnel --help
52
57
  Documentation: https://www.asyx.ai/docs
@@ -70,9 +75,21 @@ Usage: asyx <command>
70
75
  } else if (cmd === "mqtt") {
71
76
  const { default: mqttCommand } = await import("./commands/mqtt.js");
72
77
  mqttCommand().catch(handleFailure('MQTT'));
78
+ } else if (cmd === "app") {
79
+ const { default: cmdApp } = await import("./commands/app.js"); // Story 12.2
80
+ cmdApp(process.argv.slice(3)).then((code) => process.exit(code), handleFailure('App'));
73
81
  } else if (cmd === "tunnel") {
82
+ let args = process.argv.slice(3);
83
+ const at = args.indexOf("--app"); // Story 12.2: run the tunnel as one of this machine's apps
84
+ if (at !== -1) {
85
+ const { appIdForTunnel } = await import("./commands/app.js");
86
+ const appId = appIdForTunnel(args[at + 1]);
87
+ if (!appId) { console.error(`No app named ${args[at + 1] || ''} on this machine. asyx app list shows the apps kept here.`); process.exit(2); }
88
+ process.env.ASYX_CLIENT_ID = appId;
89
+ args = [...args.slice(0, at), ...args.slice(at + 2)];
90
+ }
74
91
  const { default: tunnelCommand } = await import("./commands/tunnel.js");
75
- tunnelCommand(process.argv.slice(3)).catch(handleFailure('Tunnel'));
92
+ tunnelCommand(args).catch(handleFailure('Tunnel'));
76
93
  } else {
77
94
  console.log(`Unknown command: ${cmd}\nRun "asyx help" for the list of commands.`);
78
95
  process.exit(1);
@@ -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' | 'account';
12
+ export type TunnelType = 'http' | 'tcp' | 'udp' | 'account' | 'identity';
13
13
  export interface ControlPlaneSessionOptions {
14
14
  credentials: ControlPlaneCredentials;
15
15
  tunnelType: TunnelType;
@@ -0,0 +1,23 @@
1
+ import type { Logger } from '../types.js';
2
+ import type { ControlPlaneCredentials } from '../control-plane/session.js';
3
+ export type AppCreateCommand = {
4
+ name: string;
5
+ csrPem: string;
6
+ hostname?: string;
7
+ random?: boolean;
8
+ address?: string;
9
+ };
10
+ export type IdentityReply = {
11
+ op: string;
12
+ ok: boolean;
13
+ error?: string;
14
+ [k: string]: unknown;
15
+ };
16
+ export interface IdentityCommandOptions {
17
+ credentials: ControlPlaneCredentials;
18
+ command: AppCreateCommand;
19
+ logger: Logger;
20
+ timeoutMs?: number;
21
+ }
22
+ /** Sends one app create and resolves the service's answer (a refusal is { ok: false, error }). */
23
+ export declare function sendAppCreate(o: IdentityCommandOptions): Promise<IdentityReply>;
@@ -0,0 +1,51 @@
1
+ // Story 12.2: an identity command (app create) sent over the device's own certificate connection on
2
+ // asyx/tunnel/clients/<deviceId>/cmd/identity/create. A separate IoT rule routes that topic to the
3
+ // identity command function, which answers on the device's ack topic with
4
+ // { type: 'identity_ack', requestId, data }. One connection per command; it ends after the answer.
5
+ import { randomUUID } from 'node:crypto';
6
+ /** Sends one app create and resolves the service's answer (a refusal is { ok: false, error }). */
7
+ export async function sendAppCreate(o) {
8
+ const { credentials, command, logger, timeoutMs = 45000 } = 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: 'identity', metadata: { op: 'app_create' }, 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 = `ident-${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: 'identity_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 && p.type === 'identity_ack')
34
+ resolve(p.data);
35
+ });
36
+ });
37
+ await core.subscribe(`asyx/tunnel/clients/${base}/evt/#`, 0);
38
+ const instanceId = mqttClient.getClientId();
39
+ await core.publish({ topic: `asyx/tunnel/clients/${base}/cmd/identity/create`, payload: JSON.stringify({ ...command, requestId, clientId: base, instanceId }), qos: 1, retain: false });
40
+ logger.debug('identity.command.sent', { op: 'app_create', requestId });
41
+ return await answer;
42
+ }
43
+ finally {
44
+ if (timer)
45
+ clearTimeout(timer);
46
+ try {
47
+ await mqttClient.disconnect();
48
+ }
49
+ catch { /* already gone */ }
50
+ }
51
+ }