@nuelink/nuelink-cli 1.3.9 → 1.4.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.
package/src/commands.js CHANGED
@@ -1,11 +1,12 @@
1
1
  import { readFile, stat } from "node:fs/promises";
2
2
  import readline from "node:readline";
3
3
  import path from "node:path";
4
- import chalk from "chalk";
5
-
6
- import { clearApiKey, maskToken, readConfig, resolveApiKey, CONFIG_FILE, decryptApiKey, saveApiKey } from "./config.js";
4
+ import chalk from "chalk";
5
+
6
+ import { clearApiKey, maskToken, readConfig, resolveApiKey, CONFIG_FILE, decryptApiKey, saveApiKey } from "./config.js";
7
+ import { CliError, printCliError } from "./errors.js";
7
8
  import { brandPath, collectionPath, nuelinkRequest } from "./http.js";
8
- import { buildPostPayload, parseCsv, validateRawPostPayload, VALID_PUBLISH_MODES } from "./postPayload.js";
9
+ import { buildPostPayload, parseCsv, validateRawPostPayload, VALID_PUBLISH_MODES } from "./postPayload.js";
9
10
  import {
10
11
  VALID_AUTOMATION_SUB_TYPES,
11
12
  VALID_AUTOMATION_TYPES,
@@ -20,8 +21,9 @@ import {
20
21
  splitCsv,
21
22
  validateHttpUrl,
22
23
  validateMediaFile,
23
- validateQueueSlots,
24
- } from "./validation.js";
24
+ validateQueueSlots,
25
+ validateRequiredString,
26
+ } from "./validation.js";
25
27
 
26
28
  function extractApiKeyArg(args) {
27
29
  const sanitizedArgs = [];
@@ -138,7 +140,7 @@ async function promptHidden(promptText) {
138
140
  });
139
141
  }
140
142
 
141
- async function resolveLoginApiKey(options, fallbackApiKey) {
143
+ async function resolveLoginApiKey(options, fallbackApiKey) {
142
144
  if (options.apiKey || fallbackApiKey) {
143
145
  return String(options.apiKey || fallbackApiKey).trim();
144
146
  }
@@ -148,8 +150,8 @@ async function resolveLoginApiKey(options, fallbackApiKey) {
148
150
  }
149
151
 
150
152
  return promptHidden("API key: ");
151
- }
152
-
153
+ }
154
+
153
155
  function buildRequestOptions(program) {
154
156
  const options = program.opts();
155
157
 
@@ -178,16 +180,19 @@ async function executeRequest(program, runtimeApiKey, request) {
178
180
  });
179
181
  }
180
182
 
181
- function withCommandErrorHandling(handler) {
182
- return async (...args) => {
183
- try {
184
- await handler(...args);
185
- } catch (error) {
186
- console.error(chalk.red(error.message));
187
- process.exitCode = 1;
188
- }
189
- };
190
- }
183
+ function withCommandErrorHandling(program, handler) {
184
+ return async (...args) => {
185
+ try {
186
+ await handler(...args);
187
+ } catch (error) {
188
+ printCliError(error, {
189
+ json: Boolean(program.opts().json),
190
+ fallbackCode: "VALIDATION_ERROR",
191
+ });
192
+ process.exitCode = 1;
193
+ }
194
+ };
195
+ }
191
196
 
192
197
  function registerCommands(program, runtimeApiKey, cliVersion) {
193
198
  program
@@ -196,8 +201,8 @@ function registerCommands(program, runtimeApiKey, cliVersion) {
196
201
  .description("Nuelink CLI for the Public API")
197
202
  .option("-a, --api-key <apiKey>", "Use API key for this invocation only")
198
203
  .option("--auth <apiKey>", "Deprecated alias for --api-key")
199
- .option("--dry-run", "Print the validated request without sending it")
200
- .option("--json", "Output raw JSON instead of tables for list commands")
204
+ .option("--dry-run", "Print the validated request without sending it")
205
+ .option("--json", "Output machine-readable JSON for successes and failures")
201
206
  .option("--quiet", "Suppress non-essential success banners");
202
207
 
203
208
  program
@@ -205,7 +210,7 @@ function registerCommands(program, runtimeApiKey, cliVersion) {
205
210
  .description("Persist an API key to local config")
206
211
  .option("--api-key <apiKey>", "API key to save (prefer stdin or interactive prompt)")
207
212
  .option("--stdin", "Read API key from stdin")
208
- .action(withCommandErrorHandling(async (options) => {
213
+ .action(withCommandErrorHandling(program, async (options) => {
209
214
  const apiKey = await resolveLoginApiKey(options, runtimeApiKey);
210
215
 
211
216
  if (!apiKey) {
@@ -214,64 +219,95 @@ function registerCommands(program, runtimeApiKey, cliVersion) {
214
219
 
215
220
  process.env.NUELINK_API_KEY = apiKey;
216
221
  await saveApiKey(apiKey);
217
- console.log(chalk.green("API key saved to local config."));
218
- }));
222
+ if (program.opts().json) {
223
+ console.log(JSON.stringify({ success: true, source: "saved_config" }));
224
+ } else {
225
+ console.log(chalk.green("API key saved to local config."));
226
+ }
227
+ }));
219
228
 
220
229
  program
221
230
  .command("auth:clear")
222
231
  .description("Remove the saved API key")
223
- .action(withCommandErrorHandling(async () => {
224
- await clearApiKey();
225
- console.log(chalk.yellow("Saved API key removed."));
226
- }));
232
+ .action(withCommandErrorHandling(program, async () => {
233
+ await clearApiKey();
234
+ if (program.opts().json) {
235
+ console.log(JSON.stringify({ success: true, cleared: true }));
236
+ } else {
237
+ console.log(chalk.yellow("Saved API key removed."));
238
+ }
239
+ }));
227
240
 
228
241
  program
229
242
  .command("auth:status")
230
243
  .description("Show where auth is currently resolved from")
231
- .action(withCommandErrorHandling(async () => {
232
- if (runtimeApiKey) {
233
- console.log(chalk.green(`Auth source: runtime CLI flag (${maskToken(runtimeApiKey)})`));
234
- return;
235
- }
236
-
237
- if (process.env.NUELINK_API_KEY) {
238
- console.log(chalk.green(`Auth source: NUELINK_API_KEY (${maskToken(process.env.NUELINK_API_KEY)})`));
239
- return;
240
- }
244
+ .action(withCommandErrorHandling(program, async () => {
245
+ if (runtimeApiKey) {
246
+ if (program.opts().json) {
247
+ console.log(JSON.stringify({ authenticated: true, source: "runtime_flag", token: maskToken(runtimeApiKey) }));
248
+ } else {
249
+ console.log(chalk.green(`Auth source: runtime CLI flag (${maskToken(runtimeApiKey)})`));
250
+ }
251
+ return;
252
+ }
253
+
254
+ if (process.env.NUELINK_API_KEY) {
255
+ if (program.opts().json) {
256
+ console.log(JSON.stringify({ authenticated: true, source: "environment", token: maskToken(process.env.NUELINK_API_KEY) }));
257
+ } else {
258
+ console.log(chalk.green(`Auth source: NUELINK_API_KEY (${maskToken(process.env.NUELINK_API_KEY)})`));
259
+ }
260
+ return;
261
+ }
241
262
 
242
263
  const config = await readConfig();
243
- const storedApiKey = decryptApiKey(config);
244
- if (storedApiKey) {
245
- console.log(chalk.green(`Auth source: saved config (${maskToken(storedApiKey)})`));
246
-
247
- try {
248
- const fileStat = await stat(CONFIG_FILE);
249
- console.log(chalk.blue(`Config path: ${CONFIG_FILE}`));
250
- console.log(chalk.blue(`Last updated: ${fileStat.mtime.toISOString()}`));
251
- } catch {
252
- // Ignore non-critical stat failure.
253
- }
254
-
255
- return;
256
- }
257
-
258
- console.log(chalk.yellow("No API key configured. Use auth:login to save one, or pass --api-key for a single command."));
259
- process.exitCode = 1;
260
- }));
261
-
262
- program
263
- .command("me")
264
- .description("Get current profile")
265
- .action(withCommandErrorHandling(async () => {
264
+ const storedApiKey = decryptApiKey(config);
265
+ if (storedApiKey) {
266
+ let lastUpdated;
267
+
268
+ try {
269
+ const fileStat = await stat(CONFIG_FILE);
270
+ lastUpdated = fileStat.mtime.toISOString();
271
+ } catch {
272
+ // Ignore non-critical stat failure.
273
+ }
274
+
275
+ if (program.opts().json) {
276
+ console.log(JSON.stringify({
277
+ authenticated: true,
278
+ source: "saved_config",
279
+ token: maskToken(storedApiKey),
280
+ configPath: CONFIG_FILE,
281
+ lastUpdated: lastUpdated || null,
282
+ }));
283
+ } else {
284
+ console.log(chalk.green(`Auth source: saved config (${maskToken(storedApiKey)})`));
285
+ console.log(chalk.blue(`Config path: ${CONFIG_FILE}`));
286
+ if (lastUpdated) console.log(chalk.blue(`Last updated: ${lastUpdated}`));
287
+ }
288
+
289
+ return;
290
+ }
291
+
292
+ throw new CliError(
293
+ "AUTH_MISSING",
294
+ "No API key configured. Use auth:login to save one, or pass --api-key for a single command.",
295
+ );
296
+ }));
297
+
298
+ program
299
+ .command("me")
300
+ .description("Get current profile")
301
+ .action(withCommandErrorHandling(program, async () => {
266
302
  await executeRequest(program, runtimeApiKey, { endpoint: "/me" });
267
303
  }));
268
304
 
269
- program
270
- .command("brands")
305
+ program
306
+ .command("brands")
271
307
  .description("List brands")
272
308
  .option("--per-page <number>", "Items per page", "25")
273
309
  .option("--page <number>", "Page number", "1")
274
- .action(withCommandErrorHandling(async (options) => {
310
+ .action(withCommandErrorHandling(program, async (options) => {
275
311
  await executeRequest(program, runtimeApiKey, {
276
312
  endpoint: "/brands",
277
313
  query: {
@@ -281,13 +317,13 @@ function registerCommands(program, runtimeApiKey, cliVersion) {
281
317
  });
282
318
  }));
283
319
 
284
- program
285
- .command("collections")
320
+ program
321
+ .command("collections")
286
322
  .description("List collections for a brand")
287
323
  .requiredOption("--brand-id <id>", "Brand ID")
288
324
  .option("--per-page <number>", "Items per page", "25")
289
325
  .option("--page <number>", "Page number", "1")
290
- .action(withCommandErrorHandling(async (options) => {
326
+ .action(withCommandErrorHandling(program, async (options) => {
291
327
  await executeRequest(program, runtimeApiKey, {
292
328
  endpoint: `${brandPath(parsePositiveInteger(options.brandId, "brand-id"))}/collections`,
293
329
  query: {
@@ -297,8 +333,8 @@ function registerCommands(program, runtimeApiKey, cliVersion) {
297
333
  });
298
334
  }));
299
335
 
300
- program
301
- .command("collections:create")
336
+ program
337
+ .command("collections:create")
302
338
  .description("Create a collection")
303
339
  .requiredOption("--brand-id <id>", "Brand ID")
304
340
  .requiredOption("--title <title>", "Collection title")
@@ -306,7 +342,7 @@ function registerCommands(program, runtimeApiKey, cliVersion) {
306
342
  .option("--max-republish <number>", "Max republish")
307
343
  .option("--channels <ids>", "Comma-separated channel IDs")
308
344
  .option("--queues <slots>", "Comma-separated queue slots (e.g. Mon 10:10,Mon 12:12)")
309
- .action(withCommandErrorHandling(async (options) => {
345
+ .action(withCommandErrorHandling(program, async (options) => {
310
346
  const channels = splitCsv(options.channels).map((id) => parsePositiveInteger(id, "channel-id"));
311
347
  const queues = validateQueueSlots(splitCsv(options.queues));
312
348
 
@@ -314,7 +350,7 @@ function registerCommands(program, runtimeApiKey, cliVersion) {
314
350
  method: "POST",
315
351
  endpoint: `${brandPath(parsePositiveInteger(options.brandId, "brand-id"))}/collections`,
316
352
  body: {
317
- title: validateMaxLength(options.title, 255, "title"),
353
+ title: validateRequiredString(options.title, 255, "title"),
318
354
  description: validateMaxLength(options.description, 1000, "description"),
319
355
  maxRepublish: parseOptionalNonNegativeInteger(options.maxRepublish, "max-republish"),
320
356
  channels,
@@ -323,14 +359,14 @@ function registerCommands(program, runtimeApiKey, cliVersion) {
323
359
  });
324
360
  }));
325
361
 
326
- program
327
- .command("automations")
362
+ program
363
+ .command("automations")
328
364
  .description("List automations for a brand")
329
365
  .requiredOption("--brand-id <id>", "Brand ID")
330
366
  .option("--per-page <number>", "Items per page", "25")
331
- .option("--page <number>", "Page number", "1")
332
- .action(withCommandErrorHandling(async (options) => {
333
- await executeRequest(program, runtimeApiKey, {
367
+ .option("--page <number>", "Page number", "1")
368
+ .action(withCommandErrorHandling(program, async (options) => {
369
+ await executeRequest(program, runtimeApiKey, {
334
370
  endpoint: `${brandPath(parsePositiveInteger(options.brandId, "brand-id"))}/automations`,
335
371
  query: {
336
372
  per_page: parseIntegerInRange(options.perPage, "per-page", 1, 100),
@@ -339,8 +375,8 @@ function registerCommands(program, runtimeApiKey, cliVersion) {
339
375
  });
340
376
  }));
341
377
 
342
- program
343
- .command("automations:create")
378
+ program
379
+ .command("automations:create")
344
380
  .description("Create an automation")
345
381
  .requiredOption("--brand-id <id>", "Brand ID")
346
382
  .requiredOption("--collection-id <id>", "Collection ID")
@@ -354,37 +390,37 @@ function registerCommands(program, runtimeApiKey, cliVersion) {
354
390
  .option("--description <text>", "Automation description")
355
391
  .option("--load-old-posts <boolean>", "Import existing feed items: true/false")
356
392
  .option("--add-posts-as-draft <boolean>", "Create imported posts as drafts: true/false")
357
- .option("--refresh-rate <hours>", "Refresh interval (24, 12, 6, or 1 hours)")
358
- .action(withCommandErrorHandling(async (options) => {
359
- await executeRequest(program, runtimeApiKey, {
360
- method: "POST",
361
- endpoint: `${brandPath(parsePositiveInteger(options.brandId, "brand-id"))}/automations`,
362
- body: {
363
- collectionId: parsePositiveInteger(options.collectionId, "collection-id"),
364
- feedUrl: validateHttpUrl(options.feedUrl, "feed-url"),
365
- importAsType: normalizeEnum(options.importAsType, "import-as-type", VALID_IMPORT_AS_TYPES),
366
- subType: normalizeEnum(options.subType, "sub-type", VALID_AUTOMATION_SUB_TYPES),
367
- title: validateMaxLength(options.title, 255, "title"),
368
- type: normalizeEnum(options.type, "type", VALID_AUTOMATION_TYPES),
369
- dynamicTitle: validateMaxLength(options.dynamicTitle, 255, "dynamic-title"),
370
- dynamicBody: validateMaxLength(options.dynamicBody, 255, "dynamic-body"),
371
- description: options.description,
372
- loadOldPosts: parseBooleanStrict(options.loadOldPosts, "load-old-posts"),
373
- addPostsAsDraft: parseBooleanStrict(options.addPostsAsDraft, "add-posts-as-draft"),
374
- refreshRate: options.refreshRate === undefined
375
- ? undefined
376
- : Number(normalizeEnum(options.refreshRate, "refresh-rate", ["24", "12", "6", "1"])),
377
- },
378
- });
393
+ .option("--refresh-rate <hours>", "Refresh interval (24, 12, 6, or 1 hours)")
394
+ .action(withCommandErrorHandling(program, async (options) => {
395
+ await executeRequest(program, runtimeApiKey, {
396
+ method: "POST",
397
+ endpoint: `${brandPath(parsePositiveInteger(options.brandId, "brand-id"))}/automations`,
398
+ body: {
399
+ collectionId: parsePositiveInteger(options.collectionId, "collection-id"),
400
+ feedUrl: validateHttpUrl(options.feedUrl, "feed-url"),
401
+ importAsType: normalizeEnum(options.importAsType, "import-as-type", VALID_IMPORT_AS_TYPES),
402
+ subType: normalizeEnum(options.subType, "sub-type", VALID_AUTOMATION_SUB_TYPES),
403
+ title: validateRequiredString(options.title, 255, "title"),
404
+ type: normalizeEnum(options.type, "type", VALID_AUTOMATION_TYPES),
405
+ dynamicTitle: validateMaxLength(options.dynamicTitle, 255, "dynamic-title"),
406
+ dynamicBody: validateMaxLength(options.dynamicBody, 255, "dynamic-body"),
407
+ description: options.description,
408
+ loadOldPosts: parseBooleanStrict(options.loadOldPosts, "load-old-posts"),
409
+ addPostsAsDraft: parseBooleanStrict(options.addPostsAsDraft, "add-posts-as-draft"),
410
+ refreshRate: options.refreshRate === undefined
411
+ ? undefined
412
+ : Number(normalizeEnum(options.refreshRate, "refresh-rate", ["24", "12", "6", "1"])),
413
+ },
414
+ });
379
415
  }));
380
416
 
381
- program
382
- .command("channels")
417
+ program
418
+ .command("channels")
383
419
  .description("List channels for a brand")
384
420
  .requiredOption("--brand-id <id>", "Brand ID")
385
421
  .option("--per-page <number>", "Items per page", "25")
386
422
  .option("--page <number>", "Page number", "1")
387
- .action(withCommandErrorHandling(async (options) => {
423
+ .action(withCommandErrorHandling(program, async (options) => {
388
424
  await executeRequest(program, runtimeApiKey, {
389
425
  endpoint: `${brandPath(parsePositiveInteger(options.brandId, "brand-id"))}/channels`,
390
426
  query: {
@@ -394,14 +430,14 @@ function registerCommands(program, runtimeApiKey, cliVersion) {
394
430
  });
395
431
  }));
396
432
 
397
- program
398
- .command("media")
433
+ program
434
+ .command("media")
399
435
  .description("List media for a brand")
400
436
  .requiredOption("--brand-id <id>", "Brand ID")
401
437
  .option("--type <type>", `Media type filter (${VALID_MEDIA_FILTER_TYPES.join(", ")})`)
402
438
  .option("--per-page <number>", "Items per page", "25")
403
439
  .option("--page <number>", "Page number", "1")
404
- .action(withCommandErrorHandling(async (options) => {
440
+ .action(withCommandErrorHandling(program, async (options) => {
405
441
  await executeRequest(program, runtimeApiKey, {
406
442
  endpoint: `${brandPath(parsePositiveInteger(options.brandId, "brand-id"))}/media`,
407
443
  query: {
@@ -414,24 +450,29 @@ function registerCommands(program, runtimeApiKey, cliVersion) {
414
450
  });
415
451
  }));
416
452
 
417
- program
418
- .command("media:upload")
453
+ program
454
+ .command("media:upload")
419
455
  .description("Upload a media file")
420
456
  .requiredOption("--brand-id <id>", "Brand ID")
421
457
  .requiredOption("--file <path>", "Path to local file")
422
- .action(withCommandErrorHandling(async (options) => {
458
+ .action(withCommandErrorHandling(program, async (options) => {
423
459
  const brandId = parsePositiveInteger(options.brandId, "brand-id");
424
460
  const fileStat = await stat(options.file);
425
461
  const { mediaType, size } = validateMediaFile(options.file, fileStat);
426
- const formData = new FormData();
427
- const fileBuffer = await readFile(options.file);
428
- const fileBlob = new Blob([fileBuffer], { type: mediaType });
429
- formData.append("media", fileBlob, path.basename(options.file));
462
+ let multipart = true;
463
+
464
+ if (!program.opts().dryRun) {
465
+ const formData = new FormData();
466
+ const fileBuffer = await readFile(options.file);
467
+ const fileBlob = new Blob([fileBuffer], { type: mediaType });
468
+ formData.append("media", fileBlob, path.basename(options.file));
469
+ multipart = formData;
470
+ }
430
471
 
431
472
  await executeRequest(program, runtimeApiKey, {
432
473
  method: "POST",
433
474
  endpoint: `${brandPath(brandId)}/media`,
434
- multipart: formData,
475
+ multipart,
435
476
  dryRunBody: {
436
477
  file: path.basename(options.file),
437
478
  size,
@@ -440,14 +481,14 @@ function registerCommands(program, runtimeApiKey, cliVersion) {
440
481
  });
441
482
  }));
442
483
 
443
- program
444
- .command("posts")
484
+ program
485
+ .command("posts")
445
486
  .description("List posts in a collection")
446
487
  .requiredOption("--brand-id <id>", "Brand ID")
447
488
  .requiredOption("--collection-id <id>", "Collection ID")
448
489
  .option("--per-page <number>", "Items per page", "25")
449
490
  .option("--page <number>", "Page number", "1")
450
- .action(withCommandErrorHandling(async (options) => {
491
+ .action(withCommandErrorHandling(program, async (options) => {
451
492
  await executeRequest(program, runtimeApiKey, {
452
493
  endpoint: `${collectionPath(
453
494
  parsePositiveInteger(options.brandId, "brand-id"),
@@ -460,17 +501,17 @@ function registerCommands(program, runtimeApiKey, cliVersion) {
460
501
  });
461
502
  }));
462
503
 
463
- program
464
- .command("posts:add-json")
504
+ program
505
+ .command("posts:add-json")
465
506
  .description("Create a post using a JSON payload file")
466
507
  .requiredOption("--brand-id <id>", "Brand ID")
467
508
  .requiredOption("--collection-id <id>", "Collection ID")
468
509
  .requiredOption("--payload <file>", "Path to JSON payload file")
469
- .action(withCommandErrorHandling(async (options) => {
510
+ .action(withCommandErrorHandling(program, async (options) => {
470
511
  const payloadText = options.payload === "-"
471
512
  ? await readStdinText()
472
513
  : await readFile(options.payload, "utf8");
473
- const payload = validateRawPostPayload(parseJsonString(payloadText, "payload"));
514
+ const payload = validateRawPostPayload(parseJsonString(payloadText, "payload"));
474
515
 
475
516
  await executeRequest(program, runtimeApiKey, {
476
517
  method: "POST",
@@ -482,8 +523,8 @@ function registerCommands(program, runtimeApiKey, cliVersion) {
482
523
  });
483
524
  }));
484
525
 
485
- program
486
- .command("posts:create")
526
+ program
527
+ .command("posts:create")
487
528
  .description("Create a post using CLI options")
488
529
  .requiredOption("--brand-id <id>", "Brand ID")
489
530
  .requiredOption("--collection-id <id>", "Collection ID")
@@ -515,8 +556,8 @@ function registerCommands(program, runtimeApiKey, cliVersion) {
515
556
  .option("--youtube-tags <tags>", "Comma-separated YouTube tags")
516
557
  .option("--youtube-playlists <json>", "YouTube playlists JSON string")
517
558
  .option("--googlemybusiness-upload-to-photos-section <boolean>", "Upload to Google Business Profile photos: true/false")
518
- .action(withCommandErrorHandling(async (options) => {
519
- const payload = buildPostPayload(options);
559
+ .action(withCommandErrorHandling(program, async (options) => {
560
+ const payload = buildPostPayload(options);
520
561
 
521
562
  await executeRequest(program, runtimeApiKey, {
522
563
  method: "POST",
package/src/config.js CHANGED
@@ -1,19 +1,60 @@
1
- import crypto from "node:crypto";
2
- import os from "node:os";
3
- import path from "node:path";
4
- import { readFile, writeFile, mkdir, chmod } from "node:fs/promises";
1
+ import crypto from "node:crypto";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { chmod, lstat, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
5
+ import { CliError } from "./errors.js";
5
6
 
6
7
  const CONFIG_DIR = path.join(os.homedir(), ".nuelink-cli");
7
8
  const CONFIG_FILE = path.join(CONFIG_DIR, "config.json");
8
- const CONFIG_ENCRYPTION_SALT = "nuelink-cli-config-salt-v1";
9
- const CONFIG_ENCRYPTION_PASSPHRASE = "nuelink-cli::config::v1::auth";
10
-
11
- async function readConfig() {
12
- try {
13
- const content = await readFile(CONFIG_FILE, "utf8");
14
- return JSON.parse(content);
15
- } catch {
16
- return {};
9
+ const CONFIG_ENCRYPTION_SALT = "nuelink-cli-config-salt-v1";
10
+ const CONFIG_ENCRYPTION_PASSPHRASE = "nuelink-cli::config::v1::auth";
11
+
12
+ async function ensureSafeConfigDirectory({ create = false } = {}) {
13
+ try {
14
+ const directoryStat = await lstat(CONFIG_DIR);
15
+ if (directoryStat.isSymbolicLink() || !directoryStat.isDirectory()) {
16
+ throw new CliError("CONFIG_UNSAFE", `Refusing unsafe config directory: ${CONFIG_DIR}`);
17
+ }
18
+ } catch (error) {
19
+ if (error?.code !== "ENOENT") throw error;
20
+ if (!create) return false;
21
+ await mkdir(CONFIG_DIR, { recursive: true, mode: 0o700 });
22
+ }
23
+
24
+ try {
25
+ await chmod(CONFIG_DIR, 0o700);
26
+ } catch {
27
+ // Ignore on platforms where chmod permissions are not meaningful.
28
+ }
29
+
30
+ return true;
31
+ }
32
+
33
+ async function readConfig() {
34
+ try {
35
+ if (!await ensureSafeConfigDirectory()) return {};
36
+
37
+ const fileStat = await lstat(CONFIG_FILE);
38
+ if (fileStat.isSymbolicLink() || !fileStat.isFile()) {
39
+ throw new CliError("CONFIG_UNSAFE", `Refusing unsafe config path: ${CONFIG_FILE}`);
40
+ }
41
+
42
+ try {
43
+ await chmod(CONFIG_FILE, 0o600);
44
+ } catch {
45
+ // Ignore on platforms where chmod permissions are not meaningful.
46
+ }
47
+
48
+ const content = await readFile(CONFIG_FILE, "utf8");
49
+ try {
50
+ return JSON.parse(content);
51
+ } catch {
52
+ throw new CliError("CONFIG_INVALID", `Config file is not valid JSON: ${CONFIG_FILE}`);
53
+ }
54
+ } catch (error) {
55
+ if (error?.code === "ENOENT") return {};
56
+ if (error instanceof CliError) throw error;
57
+ throw new CliError("CONFIG_READ_FAILED", `Unable to read config file: ${error.message}`);
17
58
  }
18
59
  }
19
60
 
@@ -35,21 +76,25 @@ function encryptApiKey(apiKey) {
35
76
  };
36
77
  }
37
78
 
38
- function decryptApiKey(config) {
39
- if (config?.encryptedApiKey && config?.iv && config?.authTag) {
40
- const decipher = crypto.createDecipheriv(
41
- "aes-256-gcm",
42
- getConfigCipherKey(),
43
- Buffer.from(config.iv, "base64"),
44
- );
45
- decipher.setAuthTag(Buffer.from(config.authTag, "base64"));
46
-
47
- const decrypted = Buffer.concat([
48
- decipher.update(Buffer.from(config.encryptedApiKey, "base64")),
49
- decipher.final(),
50
- ]);
51
-
52
- return decrypted.toString("utf8");
79
+ function decryptApiKey(config) {
80
+ if (config?.encryptedApiKey && config?.iv && config?.authTag) {
81
+ try {
82
+ const decipher = crypto.createDecipheriv(
83
+ "aes-256-gcm",
84
+ getConfigCipherKey(),
85
+ Buffer.from(config.iv, "base64"),
86
+ );
87
+ decipher.setAuthTag(Buffer.from(config.authTag, "base64"));
88
+
89
+ const decrypted = Buffer.concat([
90
+ decipher.update(Buffer.from(config.encryptedApiKey, "base64")),
91
+ decipher.final(),
92
+ ]);
93
+
94
+ return decrypted.toString("utf8");
95
+ } catch {
96
+ throw new CliError("CONFIG_INVALID", `Saved credentials are invalid: ${CONFIG_FILE}`);
97
+ }
53
98
  }
54
99
 
55
100
  if (config?.apiKey) {
@@ -59,16 +104,40 @@ function decryptApiKey(config) {
59
104
  return undefined;
60
105
  }
61
106
 
62
- async function writeConfig(config) {
63
- await mkdir(CONFIG_DIR, { recursive: true });
64
- await writeFile(CONFIG_FILE, JSON.stringify(config, null, 2), "utf8");
65
-
66
- try {
67
- await chmod(CONFIG_FILE, 0o600);
68
- } catch {
69
- // Ignore on platforms where chmod permissions are not meaningful.
70
- }
71
- }
107
+ async function writeConfig(config) {
108
+ await ensureSafeConfigDirectory({ create: true });
109
+
110
+ try {
111
+ const existing = await lstat(CONFIG_FILE);
112
+ if (existing.isSymbolicLink() || !existing.isFile()) {
113
+ throw new CliError("CONFIG_UNSAFE", `Refusing unsafe config path: ${CONFIG_FILE}`);
114
+ }
115
+ } catch (error) {
116
+ if (error?.code !== "ENOENT") throw error;
117
+ }
118
+
119
+ const temporaryFile = path.join(
120
+ CONFIG_DIR,
121
+ `.config-${process.pid}-${crypto.randomBytes(8).toString("hex")}.tmp`,
122
+ );
123
+
124
+ try {
125
+ await writeFile(temporaryFile, JSON.stringify(config, null, 2), {
126
+ encoding: "utf8",
127
+ flag: "wx",
128
+ mode: 0o600,
129
+ });
130
+ await rename(temporaryFile, CONFIG_FILE);
131
+
132
+ try {
133
+ await chmod(CONFIG_FILE, 0o600);
134
+ } catch {
135
+ // Ignore on platforms where chmod permissions are not meaningful.
136
+ }
137
+ } finally {
138
+ await rm(temporaryFile, { force: true });
139
+ }
140
+ }
72
141
 
73
142
  async function saveApiKey(apiKey) {
74
143
  await writeConfig(encryptApiKey(apiKey));