asyx 0.0.1 → 0.1.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.
@@ -0,0 +1,540 @@
1
+ // CP-1: Control-plane connect (TLS 8883) with bounded reconnect & graceful shutdown.
2
+ // CP-2: Session negotiation and registration with coordinator.
3
+ // CP-3F: Event envelope & dispatcher for control-plane responses.
4
+ // CP-3G: Single ingress with awaiters + dispatcher (fix multiple onMessage handlers).
5
+ import { constants as fsConstants } from 'node:fs';
6
+ import { access } from 'node:fs/promises';
7
+ import { join } from 'node:path';
8
+ import crypto from "node:crypto";
9
+ import logger from "../lib/logger.js";
10
+ import { dispatch as dispatchEvt } from "../mqtt/events/index.js";
11
+ import { MessageIngress } from "../mqtt/ingress.js";
12
+
13
+ const DEVICE_JSON_PATH = join(process.env.HOME ?? '', '.asyx', 'device.json');
14
+
15
+ export default async function tunnel(args = []) {
16
+ // Device credential guard
17
+ await access(DEVICE_JSON_PATH, fsConstants.F_OK).catch(() => {
18
+ console.error('This command is for dev use only. Missing ~/.asyx/device.json');
19
+ process.exit(2);
20
+ });
21
+
22
+ // Parse arguments using minimist-like approach
23
+ const parsed = parseArgs(args);
24
+
25
+ if (parsed.help || args.length === 0) {
26
+ logger.info("cli.help", {});
27
+ process.stdout.write(`Tunnel commands:\n`);
28
+ process.stdout.write(` asyx tunnel connect Connect to control plane (TLS 8883)\n`);
29
+ process.stdout.write(` asyx tunnel --http --port <n> Create HTTP tunnel on local port <n>\n`);
30
+ process.stdout.write(` asyx tunnel --help Show this help\n`);
31
+ return;
32
+ }
33
+
34
+ // Handle legacy connect command
35
+ if (args[0] === "connect") return connect();
36
+
37
+ // Handle new --http --port flags
38
+ if (parsed.http && parsed.port) {
39
+ return httpTunnel(parsed.port);
40
+ }
41
+
42
+ // Fail fast on unsupported combinations
43
+ if (parsed.http && !parsed.port) {
44
+ logger.error("cli.args.invalid", { reason: "--http requires --port" });
45
+ process.exit(2);
46
+ }
47
+
48
+ if (parsed.port && !parsed.http) {
49
+ logger.error("cli.args.invalid", { reason: "--port requires --http" });
50
+ process.exit(2);
51
+ }
52
+
53
+ logger.error("cli.args.unknown", { args: args.join(' ') });
54
+ process.stderr.write(`Unknown subcommand or invalid flags: ${args.join(' ')}\n`);
55
+ process.exit(2);
56
+ }
57
+
58
+ // Simple argument parser (minimist-like)
59
+ function parseArgs(args) {
60
+ const parsed = {};
61
+ for (let i = 0; i < args.length; i++) {
62
+ const arg = args[i];
63
+ if (arg === '--http') {
64
+ parsed.http = true;
65
+ } else if (arg === '--port') {
66
+ if (i + 1 < args.length) {
67
+ const port = parseInt(args[i + 1], 10);
68
+ if (isNaN(port) || port < 1 || port > 65535) {
69
+ logger.error("cli.args.port_invalid", { value: args[i + 1] });
70
+ process.stderr.write(`Error: Invalid port number: ${args[i + 1]}\n`);
71
+ process.exit(2);
72
+ }
73
+ parsed.port = port;
74
+ i++; // Skip next argument as it's the port value
75
+ } else {
76
+ logger.error("cli.args.port_missing", {});
77
+ process.stderr.write("Error: --port requires a port number\n");
78
+ process.exit(2);
79
+ }
80
+ } else if (arg === '--help' || arg === '-h') {
81
+ parsed.help = true;
82
+ }
83
+ }
84
+ return parsed;
85
+ }
86
+
87
+ async function connect() {
88
+ // 0) Imports (kept local to this command to avoid global side-effects)
89
+ const { loadAwsIotConfig, AwsIotTransport } = await import("@asyx/mqtt-broker-aws");
90
+ const { MqttCore } = await import("@asyx/mqtt-core");
91
+ // policy module path may vary between dev/prod builds; fall back to permissive in dev
92
+ const { default: clientPolicyFactory } =
93
+ (await import("@asyx/mqtt-client/dist/policy.js").catch(() => ({ default: null })));
94
+
95
+ // 1) Load IoT config (throws with clear messages if misconfigured)
96
+ let cfg;
97
+ try {
98
+ cfg = loadAwsIotConfig();
99
+ } catch (e) {
100
+ logger.error("config.error", { error: e?.message || String(e) });
101
+ process.exit(1);
102
+ }
103
+ logger.info("mqtt.connect.start", {});
104
+
105
+ // Preflight endpoint sanity check
106
+ if (/^\d{12}-ats\.iot\./.test(cfg.endpoint)) {
107
+ logger.error("mqtt.endpoint.invalid", { endpoint: cfg.endpoint });
108
+ process.exit(1);
109
+ }
110
+
111
+ // DNS check for clearer error
112
+ try {
113
+ const { promises: dns } = await import("node:dns");
114
+ await dns.lookup(cfg.endpoint);
115
+ } catch {
116
+ logger.error("mqtt.endpoint.unresolved", { endpoint: cfg.endpoint });
117
+ process.exit(1);
118
+ }
119
+
120
+ // 2) Build transport + core with policy guard
121
+ const t = new AwsIotTransport(logger);
122
+ const policy =
123
+ clientPolicyFactory ? clientPolicyFactory(cfg.clientId) : { canPublish: () => true, canSubscribe: () => true };
124
+ const core = new MqttCore(t, policy);
125
+
126
+ // Utility: topic helpers - v4.1 client topics only
127
+ const evtWildcard = `asyx/tunnel/clients/${cfg.clientId}/evt/#`;
128
+ const cmdOpenTopic = `asyx/tunnel/clients/${cfg.clientId}/cmd/open`;
129
+ const registrationTopic = `asyx/tunnel/clients/${cfg.clientId}/cmd/open`;
130
+ const acknowledgmentTopic = `asyx/tunnel/clients/${cfg.clientId}/evt/ack`;
131
+
132
+ async function performSessionRegistration(ingress) {
133
+ const sessionId = crypto.randomUUID();
134
+ const manifestVersion = Date.now().toString();
135
+ const issuedAt = new Date().toISOString();
136
+
137
+ // CP-3C: Collect hardware fingerprint
138
+ const { getFpHash } = await import("../lib/fingerprint.js");
139
+ const fingerprint = await getFpHash(cfg.clientId);
140
+
141
+ // Warn if fingerprint unavailable
142
+ if (fingerprint.fph === 'unavailable') {
143
+ logger.warn("fingerprint.unavailable", { clientId: cfg.clientId });
144
+ process.stderr.write('⚠️ hardware fingerprint unavailable; coordinator may require setup.\n');
145
+ }
146
+
147
+ const registrationPayload = {
148
+ clientId: cfg.clientId,
149
+ sessionId,
150
+ manifestVersion,
151
+ issuedAt,
152
+ ...fingerprint
153
+ };
154
+
155
+ // Use AwaiterMap to wait for matching ack; timeout after 5s.
156
+ const ackPromise = ingress.awaitSessionId(sessionId, acknowledgmentTopic, 5000);
157
+
158
+ // Publish once; no retries.
159
+ await core.publish({
160
+ topic: registrationTopic,
161
+ payload: JSON.stringify(registrationPayload),
162
+ qos: 1,
163
+ retain: false
164
+ });
165
+
166
+ try {
167
+ await ackPromise; // Ignore result for now; coordinator may not be running yet.
168
+ } catch (error) {
169
+ // Timeout or other error - ignore for now as coordinator may not be running
170
+ logger.warn("cp.registration.timeout", { error: error.message });
171
+ }
172
+ }
173
+
174
+ // initial connect (single attempt; no debug/retry noise)
175
+ try {
176
+ await core.connect({ protocol: "tls", keepalive: 30, clean: true });
177
+ } catch (e) {
178
+ logger.error("mqtt.connect.failed", { error: e?.message || String(e) });
179
+ process.exit(1);
180
+ }
181
+ await core.subscribe(evtWildcard, 0);
182
+
183
+ // CP-3G: Single ingress with awaiters + dispatcher (fix multiple onMessage handlers)
184
+ const ingress = new MessageIngress({
185
+ maxAwaiters: 100,
186
+ observability: process.env.ASYX_DEBUG === '1'
187
+ });
188
+
189
+ // Set up the CP-3F dispatcher
190
+ ingress.setDispatcher(dispatchEvt);
191
+
192
+ // Single onMessage handler that processes all messages
193
+ core.onMessage(async (m) => {
194
+ try {
195
+ await ingress.handleMessage(m);
196
+ } catch (e) {
197
+ // Map handler decisions to exit codes (business logic only)
198
+ if (e && e.code === "SETUP_REQUIRED") {
199
+ process.stderr.write(`❌ ${e.message}\n`);
200
+ // Ensure clean connection end, then exit 2
201
+ try { await core.end(); } catch {}
202
+ process.exit(2);
203
+ }
204
+ if (e && typeof e.code === "string" && e.code.startsWith("ERROR_")) {
205
+ process.stderr.write(`❌ ${e.message}\n`);
206
+ try { await core.end(); } catch {}
207
+ process.exit(1);
208
+ }
209
+ // Unknown exceptions — hard fail
210
+ process.stderr.write(`❌ Unexpected: ${e?.message || String(e)}\n`);
211
+ try { await core.end(); } catch {}
212
+ process.exit(1);
213
+ }
214
+ });
215
+
216
+
217
+ // CP-2: Session Registration (single publish; optional ack wait)
218
+ await performSessionRegistration(ingress);
219
+
220
+ // 6) Keep alive & auto-reconnect on failures seen at call sites
221
+ // In this CP-1 minimal pass, we rely on publish/subscribe errors to trigger reconnects if needed.
222
+ // For now, we simply keep the process alive until SIGINT/SIGTERM.
223
+
224
+ // 6) Graceful shutdown
225
+ let shuttingDown = false;
226
+ const onSig = async (sig) => {
227
+ if (shuttingDown) return;
228
+ shuttingDown = true;
229
+ logger.info("cli.shutdown", { sig });
230
+ const killer = setTimeout(() => {
231
+ logger.error("cli.shutdown.timeout", {});
232
+ process.exit(0);
233
+ }, 3000);
234
+ try { await core.end(); } catch (e) { /* ignore */ }
235
+ clearTimeout(killer);
236
+ process.exit(0);
237
+ };
238
+ process.once("SIGINT", onSig);
239
+ process.once("SIGTERM", onSig);
240
+
241
+ // park the process (no interval spam; just a pending promise)
242
+ await new Promise(() => {}); // eslint-disable-line no-new
243
+ }
244
+
245
+ async function httpTunnel(localPort) {
246
+ logger.info('cli.http.start', { localPort });
247
+ process.stdout.write(`🚀 Starting HTTP tunnel on port ${localPort}...\n`);
248
+
249
+ // 0) Imports (kept local to this command to avoid global side-effects)
250
+ const { loadAwsIotConfig, AwsIotTransport } = await import("@asyx/mqtt-broker-aws");
251
+ const { MqttCore } = await import("@asyx/mqtt-core");
252
+ const { waitForAssignment } = await import("../state/assignment.js");
253
+
254
+ // 1) Load IoT config (throws with clear messages if misconfigured)
255
+ let cfg;
256
+ try {
257
+ cfg = loadAwsIotConfig();
258
+ } catch (e) {
259
+ logger.error("config.error", { error: e?.message || String(e) });
260
+ process.stderr.write(`Config error: ${e?.message || e}\n`);
261
+ process.exit(1);
262
+ }
263
+
264
+ logger.info("cli.http.control_plane.establish", {});
265
+ process.stdout.write(`⏳ Establishing control-plane connection…\n`);
266
+
267
+ // CLI-IMG-ControlPlane-Watchdog: Add configurable timeout
268
+ const CONTROL_PLANE_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_TIMEOUT_MS || "60000", 10);
269
+
270
+ // 2) Build transport + core
271
+ const t = new AwsIotTransport(logger);
272
+ const core = new MqttCore(t, { canPublish: () => true, canSubscribe: () => true });
273
+
274
+ // CLI-IMG-ControlPlane-Watchdog: Expose helpers from transport
275
+ const isControlPlaneConnected = () => {
276
+ try {
277
+ if (t && typeof t.isControlPlaneConnected === 'function') return t.isControlPlaneConnected();
278
+ const underlying = (core && (core.transport || core._transport));
279
+ if (underlying && typeof underlying.isControlPlaneConnected === 'function') return underlying.isControlPlaneConnected();
280
+ return false;
281
+ } catch {
282
+ return false;
283
+ }
284
+ };
285
+ const waitForControlPlane = () => {
286
+ try {
287
+ if (t && typeof t.waitForConnect === 'function') return t.waitForConnect(CONTROL_PLANE_TIMEOUT_MS);
288
+ const underlying = (core && (core.transport || core._transport));
289
+ if (underlying && typeof underlying.waitForConnect === 'function') return underlying.waitForConnect(CONTROL_PLANE_TIMEOUT_MS);
290
+ // Fallback: poll isControlPlaneConnected until timeout
291
+ logger.warn('mqtt.control_plane.helper_missing', { fn: 'waitForConnect' });
292
+ const start = Date.now();
293
+ return new Promise((resolve, reject) => {
294
+ const interval = setInterval(() => {
295
+ if (isControlPlaneConnected()) {
296
+ clearInterval(interval);
297
+ resolve();
298
+ } else if (Date.now() - start >= CONTROL_PLANE_TIMEOUT_MS) {
299
+ clearInterval(interval);
300
+ reject(new Error('control_plane_timeout'));
301
+ }
302
+ }, 250);
303
+ });
304
+ } catch (e) {
305
+ return Promise.reject(e);
306
+ }
307
+ };
308
+
309
+ // CLI-IMG-MQTT-Parity: Track first connect for persistent sessions
310
+ let isFirstConnect = true;
311
+
312
+ // CLI-IMG-ControlPlane-Watchdog: Register MQTT callbacks before connect
313
+ t.onConnect(() => {
314
+ logger.info("mqtt.control_plane.connected", {});
315
+ process.stdout.write("✅ Control-plane connection established\n");
316
+ });
317
+
318
+ t.onDisconnect((err) => {
319
+ const msg = err ? err.message || err : "closed";
320
+ logger.warn("mqtt.control_plane.disconnected", { reason: msg });
321
+ process.stderr.write(`[mqtt] Control-plane connection lost: ${msg}\n`);
322
+ });
323
+
324
+ // CLI-IMG-MQTT-Parity: Use relay's robust transport configuration
325
+ const keepalive = parseInt(process.env.ASYX_CONTROL_PLANE_KEEPALIVE_SEC || "60", 10);
326
+ const reconnectMin = parseInt(process.env.ASYX_CONTROL_PLANE_RECONNECT_MIN_MS || "1000", 10);
327
+ const reconnectMax = parseInt(process.env.ASYX_CONTROL_PLANE_RECONNECT_MAX_MS || "30000", 10);
328
+ const cleanSession = process.env.ASYX_CONTROL_PLANE_CLEAN === "true";
329
+
330
+ // 3) Connect to control plane
331
+ try {
332
+ await core.connect({
333
+ protocol: "tls",
334
+ port: 443,
335
+ keepalive,
336
+ clean: cleanSession,
337
+ reconnectMinMs: reconnectMin,
338
+ reconnectMaxMs: reconnectMax
339
+ });
340
+ // transport will resolve waiters on connect; nothing else required here
341
+ } catch (e) {
342
+ logger.error("mqtt.connect.failed", { error: e?.message || String(e) });
343
+ process.stderr.write(`Tunnel command failed: ${e?.message || e}\n`);
344
+ process.exit(1);
345
+ }
346
+
347
+ // 4) Set up topics and message handling
348
+ const evtWildcard = `asyx/tunnel/clients/${cfg.clientId}/evt/#`;
349
+ const cmdOpenTopic = `asyx/tunnel/clients/${cfg.clientId}/cmd/open`;
350
+ const acknowledgmentTopic = `asyx/tunnel/clients/${cfg.clientId}/evt/ack`;
351
+
352
+ // CLI-IMG-MQTT-Parity: Only subscribe on first connect for persistent sessions
353
+ if (isFirstConnect) {
354
+ await core.subscribe(evtWildcard, 0);
355
+ isFirstConnect = false;
356
+ }
357
+
358
+ // 5) Set up message ingress and dispatcher
359
+ const ingress = new MessageIngress({
360
+ maxAwaiters: 100,
361
+ observability: process.env.ASYX_DEBUG === '1'
362
+ });
363
+
364
+ ingress.setDispatcher(dispatchEvt);
365
+
366
+ core.onMessage(async (m) => {
367
+ try {
368
+ await ingress.handleMessage(m);
369
+ } catch (e) {
370
+ if (e && e.code === "SETUP_REQUIRED") {
371
+ process.stderr.write(`❌ ${e.message}\n`);
372
+ try { await core.end(); } catch {}
373
+ process.exit(2);
374
+ }
375
+ if (e && typeof e.code === "string" && e.code.startsWith("ERROR_")) {
376
+ process.stderr.write(`❌ ${e.message}\n`);
377
+ try { await core.end(); } catch {}
378
+ process.exit(1);
379
+ }
380
+ process.stderr.write(`❌ Unexpected: ${e?.message || String(e)}\n`);
381
+ try { await core.end(); } catch {}
382
+ process.exit(1);
383
+ }
384
+ });
385
+
386
+ // 6) Publish cmd/open request
387
+ const requestId = crypto.randomUUID();
388
+ const { getFpHash } = await import("../lib/fingerprint.js");
389
+ const fingerprint = await getFpHash(cfg.clientId);
390
+
391
+ const openPayload = {
392
+ requestId,
393
+ proto: 'http',
394
+ localPort,
395
+ clientId: cfg.clientId,
396
+ ...fingerprint
397
+ };
398
+
399
+ // Publish the open request
400
+ await core.publish({
401
+ topic: cmdOpenTopic,
402
+ payload: JSON.stringify(openPayload),
403
+ qos: 1,
404
+ retain: false
405
+ });
406
+
407
+ logger.info("cli.cmd.open.sent", { requestId });
408
+
409
+ // 7) Wait for ack and then connect to relay
410
+ const ACK_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_ACK_TIMEOUT_MS || "10000", 10);
411
+
412
+ try {
413
+ const assignmentPromise = waitForAssignment(requestId, ACK_TIMEOUT_MS);
414
+ logger.info("cli.ack.wait.start", { requestId });
415
+ const assignment = await assignmentPromise;
416
+ logger.info("cli.ack.wait.resolved", { requestId });
417
+ logger.info("cli.assignment.received", { relayId: assignment.relayId });
418
+ // Persist assignment for refresh/fallback paths
419
+ try {
420
+ const { setAssignment } = await import("../state/assignment.js");
421
+ setAssignment(assignment);
422
+ } catch {}
423
+
424
+ // 8) Connect to relay using thin client behavior
425
+ await connectToRelay(
426
+ assignment,
427
+ cfg.clientId,
428
+ localPort,
429
+ core,
430
+ ingress,
431
+ { isControlPlaneConnected, waitForControlPlane, controlPlaneTimeoutMs: CONTROL_PLANE_TIMEOUT_MS }
432
+ );
433
+
434
+ } catch (error) {
435
+ logger.error("cli.ack.wait.failed", { error: error.message });
436
+ try { await core.end(); } catch {}
437
+ process.exit(1);
438
+ }
439
+ }
440
+
441
+ async function connectToRelay(
442
+ assignment,
443
+ deviceId,
444
+ localPort,
445
+ coordinatorCore,
446
+ coordinatorIngress,
447
+ controlPlaneHelpers
448
+ ) {
449
+ // Import WebSocket bridge logic (ported from client-mvp)
450
+ const { HttpTunnel } = await import("../tunnel/http-tunnel.js");
451
+
452
+ const tunnel = new HttpTunnel({
453
+ relayUrl: assignment.relayUrl,
454
+ jwt: assignment.jwt, // Use JWT as-is (no validation)
455
+ deviceId,
456
+ requestId: assignment.requestId,
457
+ localPort,
458
+ coordinatorCore, // CLI-IMG-WSReconnect: Pass coordinator connection for JWT refresh
459
+ coordinatorIngress, // CLI-IMG-WSReconnect: Pass coordinator ingress for JWT refresh
460
+ // CLI-IMG-ControlPlane-Watchdog: Pass control-plane helpers
461
+ isControlPlaneConnected: controlPlaneHelpers.isControlPlaneConnected,
462
+ waitForControlPlane: controlPlaneHelpers.waitForControlPlane,
463
+ controlPlaneTimeoutMs: controlPlaneHelpers.controlPlaneTimeoutMs,
464
+ log: {
465
+ info: (msgOrFields, maybeFields) => {
466
+ if (typeof msgOrFields === 'string') return logger.info(msgOrFields, maybeFields);
467
+ return logger.info(maybeFields, msgOrFields);
468
+ },
469
+ warn: (msgOrFields, maybeFields) => {
470
+ if (typeof msgOrFields === 'string') return logger.warn(msgOrFields, maybeFields);
471
+ return logger.warn(maybeFields, msgOrFields);
472
+ },
473
+ error: (msgOrFields, maybeFields) => {
474
+ if (typeof msgOrFields === 'string') return logger.error(msgOrFields, maybeFields);
475
+ return logger.error(maybeFields, msgOrFields);
476
+ },
477
+ debug: (msgOrFields, maybeFields) => {
478
+ if (typeof msgOrFields === 'string') return logger.debug(msgOrFields, maybeFields);
479
+ return logger.debug(maybeFields, msgOrFields);
480
+ }
481
+ }
482
+ });
483
+
484
+ try {
485
+ await tunnel.open();
486
+
487
+ // CLI-RES-DPJWT-LEAD: Schedule initial proactive refresh
488
+ tunnel.scheduleRefresh(assignment.jwt, 'open_ack');
489
+
490
+ logger.info("tunnel.active", { url: `http://localhost:${localPort}`, relayId: assignment.relayId, leaseMs: assignment.leaseMs });
491
+ process.stdout.write(`🌐 HTTP tunnel active on http://localhost:${localPort}\n`);
492
+ process.stdout.write(` Relay: ${assignment.relayId}\n`);
493
+ process.stdout.write(` Lease: ${assignment.leaseMs}ms\n`);
494
+ process.stdout.write(` Press Ctrl+C to stop\n`);
495
+
496
+ // CLI-IMG-WSReconnect: Set up graceful shutdown
497
+ let shuttingDown = false;
498
+ const onSig = async (sig) => {
499
+ if (shuttingDown) return;
500
+ shuttingDown = true;
501
+ logger.info("cli.signal.shutdown", { sig });
502
+ process.stdout.write(`signal ${sig} — shutting down…\n`);
503
+ const killer = setTimeout(() => {
504
+ logger.error("tunnel.close.timeout", {});
505
+ process.stderr.write("tunnel.close() timed out; forcing exit\n");
506
+ process.exit(0);
507
+ }, 3000);
508
+ try {
509
+ tunnel.close();
510
+ } catch (e) {
511
+ logger.error('tunnel.close.error', { error: e.message });
512
+ process.stderr.write(`Error closing tunnel: ${e.message}\n`);
513
+ }
514
+ clearTimeout(killer);
515
+ process.exit(0);
516
+ };
517
+ process.once("SIGINT", onSig);
518
+ process.once("SIGTERM", onSig);
519
+
520
+ // CLI-REFRESH-SIGNAL: External trigger to force JWT refresh (avoids SIGUSR1 inspector conflict)
521
+ try {
522
+ process.once('SIGUSR2', () => {
523
+ logger.warn('jwt.refresh.trigger', { source: 'signal', sig: 'SIGUSR2' });
524
+ try { tunnel.attemptJwtRefresh(); } catch (e) {
525
+ logger.error('jwt.refresh.trigger.error', { error: e?.message || String(e) });
526
+ }
527
+ });
528
+ } catch {}
529
+
530
+ // Keep process alive until SIGINT/SIGTERM
531
+ await new Promise(() => {});
532
+
533
+ } catch (error) {
534
+ logger.error('cli.tunnel.failed', { error: error.message });
535
+ process.stderr.write(`❌ Tunnel connection failed: ${error.message}\n`);
536
+ process.exit(1);
537
+ }
538
+ }
539
+
540
+ function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }
File without changes
@@ -0,0 +1,25 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+
5
+ export function certsDirFor(clientId) {
6
+ const base = path.join(os.homedir(), '.asyx', 'certs', clientId);
7
+ fs.mkdirSync(base, { recursive: true, mode: 0o700 });
8
+ return base;
9
+ }
10
+
11
+ export function writeCertBundle({ clientId, certPem, caPem, keyPem, endpoint, region }) {
12
+ if (!clientId) throw new Error('missing clientId');
13
+ if (!certPem || !caPem) throw new Error('missing certificate bundle');
14
+ const dir = certsDirFor(clientId);
15
+
16
+ // Files & perms
17
+ fs.writeFileSync(path.join(dir, 'device.pem.crt'), certPem, { mode: 0o600 });
18
+ if (keyPem) fs.writeFileSync(path.join(dir, 'private.pem.key'), keyPem, { mode: 0o600 });
19
+ fs.writeFileSync(path.join(dir, 'AmazonRootCA1.pem'), caPem, { mode: 0o644 });
20
+
21
+ const manifest = { clientId, endpoint, region, when: Math.floor(Date.now() / 1000) };
22
+ fs.writeFileSync(path.join(dir, 'manifest.json'), JSON.stringify(manifest, null, 2), { mode: 0o600 });
23
+
24
+ return dir;
25
+ }
package/src/lib/csr.js ADDED
@@ -0,0 +1,45 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { promisify } from 'node:util';
3
+ import fs from 'node:fs/promises';
4
+ import fssync from 'node:fs';
5
+ import path from 'node:path';
6
+ import os from 'node:os';
7
+
8
+ const pexec = promisify(execFile);
9
+
10
+ function certsDirFor(clientId) {
11
+ const home = os.homedir();
12
+ return path.join(home, '.asyx', 'certs', clientId);
13
+ }
14
+
15
+ async function ensureDir(p) {
16
+ await fs.mkdir(p, { recursive: true, mode: 0o700 });
17
+ }
18
+
19
+ async function chmodIfExists(p, mode) {
20
+ try { await fs.chmod(p, mode); } catch {}
21
+ }
22
+
23
+ export async function ensureKeyAndCsr(clientId) {
24
+ const dir = certsDirFor(clientId);
25
+ await ensureDir(dir);
26
+ const keyPath = path.join(dir, 'private.pem.key');
27
+ const csrPath = path.join(dir, 'device.csr.pem');
28
+
29
+ // Generate key if missing
30
+ if (!fssync.existsSync(keyPath)) {
31
+ await pexec('openssl', ['genrsa', '-out', keyPath, '2048']);
32
+ await chmodIfExists(keyPath, 0o600);
33
+ }
34
+
35
+ // Always (re)generate CSR to match current key
36
+ const subj = `/CN=${clientId}/O=Asyx`;
37
+ await pexec('openssl', ['req', '-new', '-key', keyPath, '-subj', subj, '-out', csrPath]);
38
+
39
+ const csrPem = await fs.readFile(csrPath, 'utf8');
40
+ if (!/^-----BEGIN CERTIFICATE REQUEST-----[\s\S]*-----END CERTIFICATE REQUEST-----\s*$/.test(csrPem)) {
41
+ throw new Error('csr_generation_failed');
42
+ }
43
+
44
+ return { keyPath, csrPath, csrPem, dir };
45
+ }
@@ -0,0 +1,18 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ import crypto from "node:crypto";
5
+
6
+ const DIR = join(homedir(), ".asyx");
7
+ const FILE = join(DIR, "device.json");
8
+
9
+ export function loadOrCreateClientId() {
10
+ if (!existsSync(DIR)) mkdirSync(DIR, { recursive: true });
11
+ if (existsSync(FILE)) {
12
+ const raw = JSON.parse(readFileSync(FILE, "utf8"));
13
+ if (raw?.clientId) return raw.clientId;
14
+ }
15
+ const clientId = "cli_" + crypto.randomUUID().replace(/-/g, "").slice(0, 12).toUpperCase();
16
+ writeFileSync(FILE, JSON.stringify({ clientId }, null, 2));
17
+ return clientId;
18
+ }