@nuelink/nuelink-cli 1.4.4 → 1.5.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/CHANGELOG.md CHANGED
@@ -1,13 +1,20 @@
1
- # Changelog
2
-
3
- ## 1.4.1 - 2026-08-18
4
-
5
- - Emit structured machine-readable errors when `--json` is enabled.
6
- - Reject blank required mutation fields and invalid runtime configuration.
7
- - Harden saved credential writes and avoid reading media during dry runs.
8
- - Include tests, security guidance, license, and repository metadata in the npm package.
9
-
10
- ## 1.4.0
11
-
12
- - Add dry-run mutation previews, stricter request validation, retries, timeouts,
13
- and expanded post creation options.
1
+ # Changelog
2
+
3
+ ## 1.5.0
4
+
5
+ - Preserve nullable post fields in `posts:add-json` and keep dry-run bodies aligned with sent requests.
6
+ - Restrict API base URLs to Nuelink or explicitly trusted HTTPS hosts; allow HTTP only for opted-in loopback development.
7
+ - Require delayed-comment text and delay together, reject GET dry-runs, and make no-command JSON errors machine-readable.
8
+ - Remove the package self-dependency and correct repository/package contents metadata.
9
+
10
+ ## 1.4.1 - 2026-08-18
11
+
12
+ - Emit structured machine-readable errors when `--json` is enabled.
13
+ - Reject blank required mutation fields and invalid runtime configuration.
14
+ - Harden saved credential writes and avoid reading media during dry runs.
15
+ - Include tests, security guidance, license, and repository metadata in the npm package.
16
+
17
+ ## 1.4.0
18
+
19
+ - Add dry-run mutation previews, stricter request validation, retries, timeouts,
20
+ and expanded post creation options.
@@ -0,0 +1,123 @@
1
+ # Contributing to Nuelink CLI
2
+
3
+ Thanks for your interest in contributing.
4
+
5
+ This document describes the contribution workflow, code standards, and release expectations for this repository.
6
+
7
+ ## Prerequisites
8
+
9
+ - Node.js 18.17+
10
+ - npm 9+
11
+ - Git
12
+
13
+ ## Local Setup
14
+
15
+ ```bash
16
+ npm ci
17
+ npm test
18
+ ```
19
+
20
+ ## Development Workflow
21
+
22
+ 1. Create a branch from `main`.
23
+ 2. Make focused changes with clear intent.
24
+ 3. Add or update tests for behavioral changes.
25
+ 4. Run validation locally.
26
+ 5. Open a pull request with context and testing notes.
27
+
28
+ ## Recommended Branch Naming
29
+
30
+ Use one of these patterns:
31
+
32
+ - `feat/<short-description>`
33
+ - `fix/<short-description>`
34
+ - `docs/<short-description>`
35
+ - `chore/<short-description>`
36
+
37
+ Examples:
38
+
39
+ - `feat/add-posts-delete-command`
40
+ - `fix/auth-status-token-mask`
41
+
42
+ ## Commit Guidance
43
+
44
+ Conventional commit style is recommended:
45
+
46
+ - `feat: add channels filtering support`
47
+ - `fix: handle non-json error responses`
48
+ - `docs: add security policy`
49
+ - `test: add mocked brands pagination test`
50
+
51
+ ## Quality Gates
52
+
53
+ Run before pushing:
54
+
55
+ ```bash
56
+ npm test
57
+ npm run check:pack
58
+ ```
59
+
60
+ ## Code Style
61
+
62
+ - Keep code simple and explicit.
63
+ - Prefer small functions with single responsibility.
64
+ - Do not log secrets or raw API tokens.
65
+ - Preserve command names and flag behavior unless intentionally versioned.
66
+ - Favor backward compatibility for CLI UX.
67
+
68
+ ## Tests
69
+
70
+ The test suite uses Node's built-in test runner with a mocked fetch preload.
71
+
72
+ - Main test file: `test/cli.test.mjs`
73
+ - Mock layer: `test/mock-fetch.mjs`
74
+
75
+ When adding commands, include tests for:
76
+
77
+ 1. URL path and query construction
78
+ 2. Request method and body shape
79
+ 3. Auth behavior where applicable
80
+
81
+ ## Pull Request Checklist
82
+
83
+ - [ ] Changes are scoped and documented
84
+ - [ ] Tests updated or added
85
+ - [ ] `npm test` passes
86
+ - [ ] `npm run check:pack` passes
87
+ - [ ] No credentials or sensitive values committed
88
+
89
+ ## Reporting Bugs
90
+
91
+ Include:
92
+
93
+ 1. CLI version (`nuelink-cli --version`)
94
+ 2. Node version (`node -v`)
95
+ 3. Reproduction command
96
+ 4. Expected vs actual behavior
97
+ 5. Relevant sanitized output
98
+
99
+ ## Feature Requests
100
+
101
+ Provide:
102
+
103
+ 1. Problem statement
104
+ 2. Proposed command/flags UX
105
+ 3. Example input/output
106
+ 4. Compatibility considerations
107
+
108
+ ## Release Process (Maintainers)
109
+
110
+ 1. Ensure CI is passing.
111
+ 2. Bump version in `package.json`.
112
+ 3. Validate with:
113
+
114
+ ```bash
115
+ npm test
116
+ npm run check:pack
117
+ ```
118
+
119
+ 4. Publish:
120
+
121
+ ```bash
122
+ npm publish --access public
123
+ ```
package/README.md CHANGED
@@ -177,7 +177,7 @@ nuelink-cli collections:create \
177
177
  nuelink-cli automations --brand-id 13493 --per-page 5 --page 1
178
178
  ```
179
179
 
180
- This table view is especially useful for quickly scanning automation status, sub-type, and feed URL.
180
+ This table view is especially useful for quickly scanning automation status, feed type, and feed URL.
181
181
 
182
182
  Create automation:
183
183
 
@@ -187,11 +187,10 @@ nuelink-cli automations:create \
187
187
  --collection-id 720 \
188
188
  --feed-url "https://www.nasa.gov/rss/dyn/breaking_news.rss" \
189
189
  --import-as-type IMAGE \
190
- --sub-type RSS \
191
- --title "NASA Breaking News" \
192
- --type FEED \
193
- --dynamic-title "{{title}}" \
194
- --dynamic-body "{{description}} {{link}}" \
190
+ --name "NASA Breaking News" \
191
+ --type RSS \
192
+ --title "{{title}}" \
193
+ --caption "{{description}} {{link}}" \
195
194
  --dry-run
196
195
  ```
197
196
 
@@ -232,6 +231,14 @@ Optional filters include `--status`, `--post-type`, `--posting-type`,
232
231
  `--created-from`, `--created-to`, `--sort-by`, and `--sort-order`.
233
232
  Creation date filters use `YYYY-MM-DD HH:mm:ss` UTC timestamps.
234
233
 
234
+ List posts across all collections, inspect the brand queue, or review published results:
235
+
236
+ ```bash
237
+ nuelink-cli brand-posts --brand-id 13493 --view SCHEDULED
238
+ nuelink-cli schedule --brand-id 13493
239
+ nuelink-cli published-posts --brand-id 13493 --status PUBLISHED --sort-by likes
240
+ ```
241
+
235
242
  Create post from JSON payload file:
236
243
 
237
244
  ```bash
@@ -239,6 +246,8 @@ nuelink-cli posts:add-json --brand-id 13493 --collection-id 33273 --payload ./po
239
246
  ```
240
247
 
241
248
  You can also pipe JSON through stdin with `--payload -`.
249
+ CLI 1.5.0 preserves contract-nullable fields exactly; the dry-run body matches
250
+ the JSON body sent by the request.
242
251
 
243
252
  Example `post.json`:
244
253
 
@@ -287,10 +296,51 @@ nuelink-cli posts:create \
287
296
  ```
288
297
 
289
298
  Review each mutation preview, then repeat the same command without `--dry-run`
290
- only when you intend to send it.
299
+ only when you intend to send it. `--dry-run` is supported for mutations; GET
300
+ commands reject it instead of silently suppressing the read. Post creation and
301
+ update schedule values are brand-local and must be at least 10 minutes ahead;
302
+ date filters and returned `postDate` values are UTC.
291
303
 
292
304
  Supported publish modes are `DRAFT`, `QUEUE`, `SCHEDULE`, and `IMMEDIATE`. When using `SCHEDULE`, pass `--scheduled-at` in `YYYY-MM-DD HH:mm:ss` format. Poll correct-option indexes are zero-based.
293
305
 
306
+ Preview a post lifecycle update or sensitive deletion before executing it:
307
+
308
+ ```bash
309
+ nuelink-cli posts:update --brand-id 13493 --post-id 8801 \
310
+ --publish-mode SCHEDULE --scheduled-at "BRAND_LOCAL_YYYY-MM-DD_HH:mm:ss" --dry-run
311
+ nuelink-cli posts:update --brand-id 13493 --post-id 8801 \
312
+ --queue-position FRONT --dry-run
313
+ nuelink-cli posts:move --brand-id 13493 --source-collection-id 33273 \
314
+ --destination-collection-id 33274 --post-ids "8801,8802" --dry-run
315
+ nuelink-cli posts:delete --brand-id 13493 --post-id 8801 --dry-run
316
+ ```
317
+
318
+ Moving is atomic: all supplied posts (at most 100) must belong to the source collection. Deletion is permanent and the API rejects it unless sensitive AI actions are enabled for the account.
319
+
320
+ Published-post results are returned unchanged in `--json` mode. Each per-channel
321
+ record includes `likes`, `comments`, `shares`, `views`, `saves`, `engagement`,
322
+ `clicks`, `impressions`, and `reach` under `results`:
323
+
324
+ ```json
325
+ {
326
+ "id": 120045,
327
+ "postId": 8801,
328
+ "collectionId": 33273,
329
+ "channel": { "id": 501, "name": "Acme on LinkedIn", "type": "LinkedIn" },
330
+ "postType": "IMAGE",
331
+ "body": "Our new product is live.",
332
+ "url": "https://www.linkedin.com/feed/update/urn:li:share:123",
333
+ "status": "PUBLISHED",
334
+ "message": null,
335
+ "publishedAt": "2026-10-10T14:00:00.000000Z",
336
+ "results": {
337
+ "likes": 42, "comments": 5, "shares": 3, "views": 1200,
338
+ "saves": 18, "engagement": 68, "clicks": 27,
339
+ "impressions": 1540, "reach": 1310
340
+ }
341
+ }
342
+ ```
343
+
294
344
  Pagination uses `--page >= 1` and `--per-page` from 1 through 100. Media type
295
345
  filters are `IMAGE`, `VIDEO`, `GIF`, `APPLICATION`, `DOCUMENT`, and `CSV`.
296
346
  Uploads accept JPEG, PNG, BMP, MP4, MOV, or PDF files up to 100 MiB.
@@ -300,14 +350,16 @@ Uploads accept JPEG, PNG, BMP, MP4, MOV, or PDF files up to 100 MiB.
300
350
  - Table-mode list requests print `OK <METHOD> <PATH>` plus formatted output
301
351
  - JSON output mode prints only the JSON response body to stdout
302
352
  - `--quiet` suppresses success banners while keeping the response output
303
- - `--dry-run` prints the validated request without sending it
353
+ - `--dry-run` prints the validated mutation request without sending it; it is not supported for GET requests
304
354
  - Failed requests print HTTP status and response payload when available
305
355
  - Exit code is non-zero on failure
306
356
 
307
357
  ## Environment Variables
308
358
 
309
359
  - `NUELINK_API_KEY`: API key fallback if not passed via CLI flag
310
- - `NUELINK_BASE_URL`: Override API base URL for testing or documented self-hosted scenarios
360
+ - `NUELINK_BASE_URL`: Override API base URL (Nuelink host or an exact trusted HTTPS host)
361
+ - `NUELINK_TRUSTED_HOSTS`: Comma-separated exact host allowlist for HTTPS API overrides you control; never include a production key for an untrusted host
362
+ - `NUELINK_ALLOW_INSECURE_HTTP=1`: Permit HTTP only for loopback development hosts
311
363
  - `NUELINK_TIMEOUT_MS`: request timeout in milliseconds (default: `30000`)
312
364
 
313
365
  Example:
package/package.json CHANGED
@@ -1,23 +1,23 @@
1
1
  {
2
2
  "name": "@nuelink/nuelink-cli",
3
- "version": "1.4.4",
3
+ "version": "1.5.0",
4
4
  "description": "The official Nuelink CLI for automating social media workflows from your terminal. Schedule posts, upload media, manage brands, and integrate Nuelink into scripts, CI/CD pipelines, and AI agents.",
5
5
  "license": "MIT",
6
6
  "author": "Nuelink",
7
7
  "repository": {
8
8
  "type": "git",
9
- "url": "git+https://github.com/Nuelink/nuelink-cli.git"
9
+ "url": "git+https://github.com/kreatinc/nuelink-cli.git"
10
10
  },
11
- "homepage": "https://github.com/Nuelink/nuelink-cli#readme",
11
+ "homepage": "https://github.com/kreatinc/nuelink-cli#readme",
12
12
  "bugs": {
13
- "url": "https://github.com/Nuelink/nuelink-cli/issues"
13
+ "url": "https://github.com/kreatinc/nuelink-cli/issues"
14
14
  },
15
15
  "type": "module",
16
16
  "main": "./src/cli.js",
17
17
  "scripts": {
18
18
  "test": "node --test test/cli.test.mjs",
19
19
  "smoke:auth": "node src/cli.js auth:status",
20
- "check:pack": "npm pack --dry-run",
20
+ "check:pack": "node scripts/check-pack.mjs",
21
21
  "check:pack:installed": "node scripts/check-packed-package.mjs"
22
22
  },
23
23
  "engines": {
@@ -28,6 +28,7 @@
28
28
  "test",
29
29
  "CHANGELOG.md",
30
30
  "README.md",
31
+ "CONTRIBUTING.md",
31
32
  "SECURITY.md",
32
33
  "LICENSE"
33
34
  ],
@@ -41,7 +42,6 @@
41
42
  "automation"
42
43
  ],
43
44
  "dependencies": {
44
- "@nuelink/nuelink-cli": "^1.4.4",
45
45
  "chalk": "^5.6.2",
46
46
  "commander": "^13.1.0"
47
47
  },
package/src/cli.js CHANGED
@@ -28,7 +28,7 @@ const hasHelpFlag = parsedAuth.sanitizedArgs.includes("--help") || parsedAuth.sa
28
28
  const hasVersionFlag = parsedAuth.sanitizedArgs.includes("--version") || parsedAuth.sanitizedArgs.includes("-V");
29
29
 
30
30
  if (!argvHasCommand && !hasHelpFlag && !hasVersionFlag) {
31
- if (runtimeApiKey) {
31
+ if (runtimeApiKey || jsonMode) {
32
32
  printCliError(
33
33
  new CliError("USAGE_ERROR", "Missing command. Provide a command such as 'me' or 'auth:login'."),
34
34
  { json: jsonMode },
package/src/commands.js CHANGED
@@ -8,20 +8,25 @@ import { CliError, printCliError } from "./errors.js";
8
8
  import { brandPath, collectionPath, nuelinkRequest } from "./http.js";
9
9
  import { buildPostPayload, parseCsv, validateRawPostPayload, VALID_PUBLISH_MODES } from "./postPayload.js";
10
10
  import {
11
- VALID_AUTOMATION_SUB_TYPES,
12
- VALID_AUTOMATION_TYPES,
11
+ VALID_FEED_TYPES,
13
12
  VALID_IMPORT_AS_TYPES,
14
13
  VALID_MEDIA_FILTER_TYPES,
15
14
  VALID_POST_STATUSES,
16
15
  VALID_POST_TYPES,
17
16
  VALID_POSTING_TYPES,
17
+ VALID_POST_VIEWS,
18
18
  VALID_POST_SORT_FIELDS,
19
+ VALID_POST_UPDATE_MODES,
20
+ VALID_QUEUE_POSITIONS,
21
+ VALID_PUBLISHED_POST_STATUSES,
22
+ VALID_PUBLISHED_POST_SORT_FIELDS,
19
23
  VALID_SORT_ORDERS,
20
24
  normalizeEnum,
21
25
  parseBooleanStrict,
22
26
  parseIntegerInRange,
23
27
  parseJsonString,
24
28
  parseOptionalNonNegativeInteger,
29
+ parseOptionalPositiveInteger,
25
30
  parsePositiveInteger,
26
31
  splitCsv,
27
32
  validateHttpUrl,
@@ -395,12 +400,10 @@ function registerCommands(program, runtimeApiKey, cliVersion) {
395
400
  .requiredOption("--collection-id <id>", "Collection ID")
396
401
  .requiredOption("--feed-url <url>", "Feed URL")
397
402
  .requiredOption("--import-as-type <type>", "Import type, e.g. IMAGE")
398
- .requiredOption("--sub-type <type>", "Sub type, e.g. RSS")
399
- .requiredOption("--title <title>", "Automation title")
400
- .option("--type <type>", "Automation type", "FEED")
401
- .option("--dynamic-title <text>", "Dynamic title", "{{title}}")
402
- .option("--dynamic-body <text>", "Dynamic body")
403
- .option("--description <text>", "Automation description")
403
+ .requiredOption("--name <name>", "Automation name")
404
+ .requiredOption("--type <type>", `Feed type (${VALID_FEED_TYPES.join(", ")})`)
405
+ .option("--title <text>", "Imported post title template", "{{title}}")
406
+ .option("--caption <text>", "Imported post caption template")
404
407
  .option("--load-old-posts <boolean>", "Import existing feed items: true/false")
405
408
  .option("--add-posts-as-draft <boolean>", "Create imported posts as drafts: true/false")
406
409
  .option("--refresh-rate <hours>", "Refresh interval (24, 12, 6, or 1 hours)")
@@ -409,15 +412,13 @@ function registerCommands(program, runtimeApiKey, cliVersion) {
409
412
  method: "POST",
410
413
  endpoint: `${brandPath(parsePositiveInteger(options.brandId, "brand-id"))}/automations`,
411
414
  body: {
415
+ name: validateRequiredString(options.name, 255, "name"),
412
416
  collectionId: parsePositiveInteger(options.collectionId, "collection-id"),
417
+ type: normalizeEnum(options.type, "type", VALID_FEED_TYPES),
413
418
  feedUrl: validateHttpUrl(options.feedUrl, "feed-url"),
414
419
  importAsType: normalizeEnum(options.importAsType, "import-as-type", VALID_IMPORT_AS_TYPES),
415
- subType: normalizeEnum(options.subType, "sub-type", VALID_AUTOMATION_SUB_TYPES),
416
- title: validateRequiredString(options.title, 255, "title"),
417
- type: normalizeEnum(options.type, "type", VALID_AUTOMATION_TYPES),
418
- dynamicTitle: validateMaxLength(options.dynamicTitle, 255, "dynamic-title"),
419
- dynamicBody: validateMaxLength(options.dynamicBody, 255, "dynamic-body"),
420
- description: options.description,
420
+ title: validateMaxLength(options.title, 255, "title"),
421
+ caption: validateMaxLength(options.caption, 255, "caption"),
421
422
  loadOldPosts: parseBooleanStrict(options.loadOldPosts, "load-old-posts"),
422
423
  addPostsAsDraft: parseBooleanStrict(options.addPostsAsDraft, "add-posts-as-draft"),
423
424
  refreshRate: options.refreshRate === undefined
@@ -552,6 +553,195 @@ function registerCommands(program, runtimeApiKey, cliVersion) {
552
553
  });
553
554
  }));
554
555
 
556
+ program
557
+ .command("schedule")
558
+ .description("Get the weekly queue schedule for a brand")
559
+ .requiredOption("--brand-id <id>", "Brand ID")
560
+ .action(withCommandErrorHandling(program, async (options) => {
561
+ await executeRequest(program, runtimeApiKey, {
562
+ endpoint: `${brandPath(parsePositiveInteger(options.brandId, "brand-id"))}/schedule`,
563
+ });
564
+ }));
565
+
566
+ program
567
+ .command("brand-posts")
568
+ .description("List posts across all collections in a brand")
569
+ .requiredOption("--brand-id <id>", "Brand ID")
570
+ .option("--collection-id <id>", "Only return posts from this collection")
571
+ .option("--view <view>", `Post view (${VALID_POST_VIEWS.join(", ")})`)
572
+ .option("--per-page <number>", "Items per page", "25")
573
+ .option("--page <number>", "Page number", "1")
574
+ .option("--status <status>", `Post status (${VALID_POST_STATUSES.join(", ")})`)
575
+ .option("--post-type <type>", `Post type (${VALID_POST_TYPES.join(", ")})`)
576
+ .option("--posting-type <type>", `Posting type (${VALID_POSTING_TYPES.join(", ")})`)
577
+ .option("--created-from <datetime>", "Created at or after UTC time (YYYY-MM-DD HH:mm:ss)")
578
+ .option("--created-to <datetime>", "Created at or before UTC time (YYYY-MM-DD HH:mm:ss)")
579
+ .option("--sort-by <field>", `Sort field (${VALID_POST_SORT_FIELDS.join(", ")})`)
580
+ .option("--sort-order <order>", `Sort order (${VALID_SORT_ORDERS.join(", ")})`)
581
+ .action(withCommandErrorHandling(program, async (options) => {
582
+ const createdFrom = validatePostDateTime(options.createdFrom, "created-from");
583
+ const createdTo = validatePostDateTime(options.createdTo, "created-to");
584
+ if (createdFrom && createdTo && createdTo < createdFrom) {
585
+ throw new Error("created-to must not precede created-from.");
586
+ }
587
+ const sortBy = options.sortBy === undefined ? undefined : String(options.sortBy).trim().toLowerCase();
588
+ if (sortBy && !VALID_POST_SORT_FIELDS.includes(sortBy)) {
589
+ throw new Error(`Invalid sort-by "${options.sortBy}". Expected one of: ${VALID_POST_SORT_FIELDS.join(", ")}.`);
590
+ }
591
+ const sortOrder = options.sortOrder === undefined ? undefined : String(options.sortOrder).trim().toLowerCase();
592
+ if (sortOrder && !VALID_SORT_ORDERS.includes(sortOrder)) {
593
+ throw new Error(`Invalid sort-order "${options.sortOrder}". Expected one of: ${VALID_SORT_ORDERS.join(", ")}.`);
594
+ }
595
+
596
+ await executeRequest(program, runtimeApiKey, {
597
+ endpoint: `${brandPath(parsePositiveInteger(options.brandId, "brand-id"))}/posts`,
598
+ query: {
599
+ collection_id: parseOptionalPositiveInteger(options.collectionId, "collection-id"),
600
+ view: options.view ? normalizeEnum(options.view, "view", VALID_POST_VIEWS) : undefined,
601
+ per_page: parseIntegerInRange(options.perPage, "per-page", 1, 100),
602
+ page: parsePositiveInteger(options.page, "page"),
603
+ status: options.status ? normalizeEnum(options.status, "status", VALID_POST_STATUSES) : undefined,
604
+ post_type: options.postType ? normalizeEnum(options.postType, "post-type", VALID_POST_TYPES) : undefined,
605
+ posting_type: options.postingType ? normalizeEnum(options.postingType, "posting-type", VALID_POSTING_TYPES) : undefined,
606
+ created_from: createdFrom,
607
+ created_to: createdTo,
608
+ sort_by: sortBy,
609
+ sort_order: sortOrder,
610
+ },
611
+ });
612
+ }));
613
+
614
+ program
615
+ .command("posts:move")
616
+ .description("Move posts between collections in a brand")
617
+ .requiredOption("--brand-id <id>", "Brand ID")
618
+ .requiredOption("--source-collection-id <id>", "Source collection ID")
619
+ .requiredOption("--destination-collection-id <id>", "Destination collection ID")
620
+ .requiredOption("--post-ids <ids>", "Comma-separated post IDs (1-100)")
621
+ .action(withCommandErrorHandling(program, async (options) => {
622
+ const sourceCollectionId = parsePositiveInteger(options.sourceCollectionId, "source-collection-id");
623
+ const destinationCollectionId = parsePositiveInteger(options.destinationCollectionId, "destination-collection-id");
624
+ if (sourceCollectionId === destinationCollectionId) {
625
+ throw new Error("destination-collection-id must differ from source-collection-id.");
626
+ }
627
+ const postIds = splitCsv(options.postIds).map((id) => parsePositiveInteger(id, "post-ids"));
628
+ if (postIds.length === 0 || postIds.length > 100) {
629
+ throw new Error("post-ids must contain between 1 and 100 post IDs.");
630
+ }
631
+ if (new Set(postIds).size !== postIds.length) {
632
+ throw new Error("post-ids must not contain duplicates.");
633
+ }
634
+
635
+ await executeRequest(program, runtimeApiKey, {
636
+ method: "PATCH",
637
+ endpoint: `${brandPath(parsePositiveInteger(options.brandId, "brand-id"))}/posts/move`,
638
+ body: {
639
+ sourceCollectionId,
640
+ destinationCollectionId,
641
+ postIds,
642
+ },
643
+ });
644
+ }));
645
+
646
+ program
647
+ .command("posts:update")
648
+ .description("Reschedule, re-queue, draft, or reposition a post")
649
+ .requiredOption("--brand-id <id>", "Brand ID")
650
+ .requiredOption("--post-id <id>", "Post ID")
651
+ .option("--publish-mode <mode>", `Publish mode (${VALID_POST_UPDATE_MODES.join(", ")})`)
652
+ .option("--scheduled-at <value>", "Brand-local publish datetime (YYYY-MM-DD HH:mm:ss)")
653
+ .option("--queue-position <position>", `Queue position (${VALID_QUEUE_POSITIONS.join(", ")})`)
654
+ .action(withCommandErrorHandling(program, async (options) => {
655
+ const publishMode = options.publishMode
656
+ ? normalizeEnum(options.publishMode, "publish-mode", VALID_POST_UPDATE_MODES)
657
+ : undefined;
658
+ const queuePosition = options.queuePosition
659
+ ? normalizeEnum(options.queuePosition, "queue-position", VALID_QUEUE_POSITIONS)
660
+ : undefined;
661
+ const scheduledAt = validatePostDateTime(options.scheduledAt, "scheduled-at");
662
+ if (!publishMode && !queuePosition) {
663
+ throw new Error("At least one of publish-mode or queue-position is required.");
664
+ }
665
+ if (publishMode === "SCHEDULE" && !scheduledAt) {
666
+ throw new Error("scheduled-at is required when publish-mode is SCHEDULE.");
667
+ }
668
+ if (publishMode !== "SCHEDULE" && scheduledAt) {
669
+ throw new Error("scheduled-at is only allowed when publish-mode is SCHEDULE.");
670
+ }
671
+
672
+ await executeRequest(program, runtimeApiKey, {
673
+ method: "PATCH",
674
+ endpoint: `${brandPath(parsePositiveInteger(options.brandId, "brand-id"))}/posts/${parsePositiveInteger(options.postId, "post-id")}`,
675
+ body: {
676
+ publishMode,
677
+ scheduledAt,
678
+ queuePosition,
679
+ },
680
+ });
681
+ }));
682
+
683
+ program
684
+ .command("posts:delete")
685
+ .description("Permanently delete a post (requires sensitive actions to be enabled)")
686
+ .requiredOption("--brand-id <id>", "Brand ID")
687
+ .requiredOption("--post-id <id>", "Post ID")
688
+ .action(withCommandErrorHandling(program, async (options) => {
689
+ await executeRequest(program, runtimeApiKey, {
690
+ method: "DELETE",
691
+ endpoint: `${brandPath(parsePositiveInteger(options.brandId, "brand-id"))}/posts/${parsePositiveInteger(options.postId, "post-id")}`,
692
+ });
693
+ }));
694
+
695
+ program
696
+ .command("published-posts")
697
+ .description("List published posts and engagement results for a brand")
698
+ .requiredOption("--brand-id <id>", "Brand ID")
699
+ .option("--per-page <number>", "Items per page", "25")
700
+ .option("--page <number>", "Page number", "1")
701
+ .option("--status <status>", `Published status (${VALID_PUBLISHED_POST_STATUSES.join(", ")})`, "PUBLISHED")
702
+ .option("--collection-id <id>", "Collection ID")
703
+ .option("--channel-id <id>", "Channel ID")
704
+ .option("--post-id <id>", "Source post ID")
705
+ .option("--post-type <type>", "Post type")
706
+ .option("--search <text>", "Search published text")
707
+ .option("--published-from <datetime>", "Published at or after UTC time (YYYY-MM-DD HH:mm:ss)")
708
+ .option("--published-to <datetime>", "Published at or before UTC time (YYYY-MM-DD HH:mm:ss)")
709
+ .option("--sort-by <field>", `Sort field (${VALID_PUBLISHED_POST_SORT_FIELDS.join(", ")})`, "id")
710
+ .option("--sort-order <order>", `Sort order (${VALID_SORT_ORDERS.join(", ")})`, "desc")
711
+ .action(withCommandErrorHandling(program, async (options) => {
712
+ const publishedFrom = validatePostDateTime(options.publishedFrom, "published-from");
713
+ const publishedTo = validatePostDateTime(options.publishedTo, "published-to");
714
+ if (publishedFrom && publishedTo && publishedTo < publishedFrom) {
715
+ throw new Error("published-to must not precede published-from.");
716
+ }
717
+ const sortBy = String(options.sortBy).trim().toLowerCase();
718
+ if (!VALID_PUBLISHED_POST_SORT_FIELDS.includes(sortBy)) {
719
+ throw new Error(`Invalid sort-by "${options.sortBy}". Expected one of: ${VALID_PUBLISHED_POST_SORT_FIELDS.join(", ")}.`);
720
+ }
721
+ const sortOrder = String(options.sortOrder).trim().toLowerCase();
722
+ if (!VALID_SORT_ORDERS.includes(sortOrder)) {
723
+ throw new Error(`Invalid sort-order "${options.sortOrder}". Expected one of: ${VALID_SORT_ORDERS.join(", ")}.`);
724
+ }
725
+
726
+ await executeRequest(program, runtimeApiKey, {
727
+ endpoint: `${brandPath(parsePositiveInteger(options.brandId, "brand-id"))}/published-posts`,
728
+ query: {
729
+ per_page: parseIntegerInRange(options.perPage, "per-page", 1, 100),
730
+ page: parsePositiveInteger(options.page, "page"),
731
+ status: normalizeEnum(options.status, "status", VALID_PUBLISHED_POST_STATUSES),
732
+ collection_id: parseOptionalPositiveInteger(options.collectionId, "collection-id"),
733
+ channel_id: parseOptionalPositiveInteger(options.channelId, "channel-id"),
734
+ post_id: parseOptionalPositiveInteger(options.postId, "post-id"),
735
+ post_type: options.postType,
736
+ search: validateMaxLength(options.search, 255, "search"),
737
+ published_from: publishedFrom,
738
+ published_to: publishedTo,
739
+ sort_by: sortBy,
740
+ sort_order: sortOrder,
741
+ },
742
+ });
743
+ }));
744
+
555
745
  program
556
746
  .command("posts:add-json")
557
747
  .description("Create a post using a JSON payload file")
@@ -609,6 +799,12 @@ function registerCommands(program, runtimeApiKey, cliVersion) {
609
799
  .option("--youtube-playlists <json>", "YouTube playlists JSON string")
610
800
  .option("--googlemybusiness-upload-to-photos-section <boolean>", "Upload to Google Business Profile photos: true/false")
611
801
  .action(withCommandErrorHandling(program, async (options) => {
802
+ if (options.comment === undefined && options.commentDelay !== undefined) {
803
+ throw new Error("comment and comment-delay must be provided together.");
804
+ }
805
+ if (options.comment !== undefined && options.commentDelay === undefined) {
806
+ throw new Error("comment and comment-delay must be provided together.");
807
+ }
612
808
  const payload = buildPostPayload(options);
613
809
 
614
810
  await executeRequest(program, runtimeApiKey, {
package/src/http.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { createRequire } from "node:module";
2
+ import { isIP } from "node:net";
2
3
  import chalk from "chalk";
3
4
  import { CliError } from "./errors.js";
4
5
  import { printApiResponse } from "./output.js";
@@ -8,6 +9,53 @@ const { version: cliVersion } = require("../package.json");
8
9
 
9
10
  const DEFAULT_API_BASE_URL = "https://app.nuelink.com/api/public/v1";
10
11
 
12
+ function isLoopbackHostname(hostname) {
13
+ const normalized = hostname.toLowerCase().replace(/^\[|\]$/g, "");
14
+ if (normalized === "localhost" || normalized.endsWith(".localhost") || normalized === "::1") {
15
+ return true;
16
+ }
17
+ const addressType = isIP(normalized);
18
+ if (addressType === 4) {
19
+ return Number(normalized.split(".")[0]) === 127;
20
+ }
21
+ return false;
22
+ }
23
+
24
+ function validateApiBaseUrl(apiBaseUrl) {
25
+ let url;
26
+ try {
27
+ url = new URL(apiBaseUrl);
28
+ } catch {
29
+ throw new CliError("CONFIG_INVALID", "NUELINK_BASE_URL must be a valid absolute URL.");
30
+ }
31
+
32
+ if (url.username || url.password || url.search || url.hash) {
33
+ throw new CliError("CONFIG_INVALID", "NUELINK_BASE_URL must not include credentials, a query, or a fragment.");
34
+ }
35
+
36
+ const trustedHosts = new Set([
37
+ "app.nuelink.com",
38
+ ...(process.env.NUELINK_TRUSTED_HOSTS || "")
39
+ .split(",")
40
+ .map((host) => host.trim().toLowerCase())
41
+ .filter(Boolean),
42
+ ]);
43
+ const loopback = isLoopbackHostname(url.hostname);
44
+ const allowInsecureLoopback = process.env.NUELINK_ALLOW_INSECURE_HTTP === "1";
45
+
46
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback && allowInsecureLoopback)) {
47
+ throw new CliError("CONFIG_INVALID", "NUELINK_BASE_URL must use HTTPS (HTTP is allowed only for loopback with NUELINK_ALLOW_INSECURE_HTTP=1).");
48
+ }
49
+ if (!loopback && !trustedHosts.has(url.host.toLowerCase())) {
50
+ throw new CliError(
51
+ "CONFIG_INVALID",
52
+ "NUELINK_BASE_URL host is not trusted. Add its exact host to NUELINK_TRUSTED_HOSTS only if you control that HTTPS endpoint.",
53
+ );
54
+ }
55
+
56
+ return url;
57
+ }
58
+
11
59
  function readIntegerEnvironment(name, fallback, { minimum = 0, maximum = 600000 } = {}) {
12
60
  const raw = process.env[name];
13
61
  if (raw === undefined || raw === "") return fallback;
@@ -54,11 +102,8 @@ function collectionPath(brandId, collectionId) {
54
102
  }
55
103
 
56
104
  function buildApiUrl(endpoint, apiBaseUrl) {
57
- try {
58
- return new URL(endpoint.replace(/^\//, ""), `${apiBaseUrl.replace(/\/?$/, "/")}`);
59
- } catch {
60
- throw new CliError("CONFIG_INVALID", "NUELINK_BASE_URL must be a valid absolute URL.");
61
- }
105
+ const baseUrl = validateApiBaseUrl(apiBaseUrl);
106
+ return new URL(endpoint.replace(/^\//, ""), `${baseUrl.toString().replace(/\/?$/, "/")}`);
62
107
  }
63
108
 
64
109
  function shouldRetryRequest(method, statusCode, attempt, maxGetRetries) {
@@ -117,6 +162,9 @@ async function nuelinkRequest({ apiKey, method = "GET", endpoint, query, body, m
117
162
  }
118
163
 
119
164
  if (dryRun) {
165
+ if (method === "GET") {
166
+ throw new CliError("VALIDATION_ERROR", "--dry-run is only supported for API mutations; GET requests are not sent or previewed.");
167
+ }
120
168
  printDryRun({ method, url, query, body, multipart, dryRunBody });
121
169
  return { dryRun: true };
122
170
  }
package/src/output.js CHANGED
@@ -42,6 +42,7 @@ function pickColumns(items) {
42
42
  "status",
43
43
  "type",
44
44
  "subType",
45
+ "queueStatus",
45
46
  "timezone",
46
47
  "collectionId",
47
48
  "postType",
@@ -180,4 +181,4 @@ export {
180
181
  printApiResponse,
181
182
  renderPagination,
182
183
  renderTable,
183
- };
184
+ };
@@ -83,7 +83,7 @@ function validateRawPostPayload(payload) {
83
83
  if (payload.autoThreadText !== undefined && payload.autoThreadText !== null && typeof payload.autoThreadText !== "boolean") {
84
84
  throw new Error("Invalid autoThreadText. Expected a boolean or null.");
85
85
  }
86
- if (payload.link !== undefined) {
86
+ if (payload.link !== undefined && payload.link !== null) {
87
87
  validateHttpUrl(payload.link, "link");
88
88
  }
89
89
 
@@ -92,8 +92,10 @@ function validateRawPostPayload(payload) {
92
92
  ? validateRequiredString(payload.caption, 3000, "caption")
93
93
  : payload.caption === undefined
94
94
  ? undefined
95
- : String(payload.caption).trim();
96
- if (poll !== undefined) {
95
+ : payload.caption === null
96
+ ? null
97
+ : String(payload.caption).trim();
98
+ if (poll !== undefined && poll !== null) {
97
99
  if (!poll || typeof poll !== "object" || Array.isArray(poll)) {
98
100
  throw new Error("Invalid poll. Expected a JSON object.");
99
101
  }
@@ -107,7 +109,7 @@ function validateRawPostPayload(payload) {
107
109
  options.forEach((option) => validateOptionalLength(option, 30, "poll-option"));
108
110
  }
109
111
 
110
- if (payload.media !== undefined) {
112
+ if (payload.media !== undefined && payload.media !== null) {
111
113
  if (!Array.isArray(payload.media)) {
112
114
  throw new Error("Invalid media. Expected an array.");
113
115
  }
@@ -130,7 +132,9 @@ function validateRawPostPayload(payload) {
130
132
  ...payload,
131
133
  ...(payload.caption !== undefined ? { caption } : {}),
132
134
  publishMode,
133
- ...(payload.scheduledAt !== undefined ? { scheduledAt } : {}),
135
+ ...(payload.scheduledAt !== undefined
136
+ ? { scheduledAt: payload.scheduledAt === null ? null : scheduledAt }
137
+ : {}),
134
138
  };
135
139
  }
136
140
 
@@ -158,6 +162,12 @@ function buildPostPayload(options) {
158
162
  if (options.pollPeriod && !VALID_POLL_PERIODS.includes(options.pollPeriod)) {
159
163
  throw new Error(`Invalid poll-period. Expected one of: ${VALID_POLL_PERIODS.join(", ")}.`);
160
164
  }
165
+ if ((options.comment === undefined) !== (options.commentDelay === undefined)) {
166
+ throw new Error("comment and comment-delay must be provided together.");
167
+ }
168
+ if (options.comment !== undefined) {
169
+ validateRequiredString(options.comment, 1000, "comment");
170
+ }
161
171
  if (options.instagramTrialReel && !VALID_TRIAL_REEL_MODES.includes(options.instagramTrialReel)) {
162
172
  throw new Error(`Invalid instagram-trial-reel. Expected one of: ${VALID_TRIAL_REEL_MODES.join(", ")}.`);
163
173
  }
package/src/validation.js CHANGED
@@ -1,7 +1,6 @@
1
1
  import path from "node:path";
2
2
 
3
- const VALID_AUTOMATION_TYPES = ["FEED"];
4
- const VALID_AUTOMATION_SUB_TYPES = [
3
+ const VALID_FEED_TYPES = [
5
4
  "YOUTUBE",
6
5
  "RSS",
7
6
  "ATOM",
@@ -38,7 +37,12 @@ const VALID_POST_TYPES = [
38
37
  "SLIDES", "REEL", "TIKTOK", "STORY", "POLL", "ENGAGE_COMMENT",
39
38
  ];
40
39
  const VALID_POSTING_TYPES = ["NOW", "SCHEDULE", "QUEUE", "DRAFT"];
40
+ const VALID_POST_VIEWS = ["QUEUE", "SCHEDULED", "DRAFT", "PUBLISHED"];
41
41
  const VALID_POST_SORT_FIELDS = ["id", "title", "post_date", "created_at", "updated_at"];
42
+ const VALID_POST_UPDATE_MODES = ["DRAFT", "SCHEDULE", "QUEUE"];
43
+ const VALID_QUEUE_POSITIONS = ["FRONT", "BACK"];
44
+ const VALID_PUBLISHED_POST_STATUSES = ["PUBLISHED", "FAILED", "RETRYING", "SKIPPED", "SENT"];
45
+ const VALID_PUBLISHED_POST_SORT_FIELDS = ["id", "created_at", "likes", "comments", "shares"];
42
46
  const VALID_SORT_ORDERS = ["asc", "desc"];
43
47
  const SUPPORTED_MEDIA_TYPES = new Map([
44
48
  [".jpg", "image/jpeg"],
@@ -266,8 +270,9 @@ function validatePollOptions(options, correctOptionIndex) {
266
270
  throw new Error("Polls require at least two options.");
267
271
  }
268
272
 
269
- if (correctOptionIndex !== undefined && (correctOptionIndex < 0 || correctOptionIndex >= options.length)) {
270
- throw new Error("poll-correct-option-index must point to an existing poll option.");
273
+ if (correctOptionIndex !== undefined && correctOptionIndex !== null
274
+ && (!Number.isInteger(correctOptionIndex) || correctOptionIndex < 0)) {
275
+ throw new Error("poll-correct-option-index must be a non-negative integer.");
271
276
  }
272
277
  }
273
278
 
@@ -312,14 +317,18 @@ function validateMediaFile(filePath, fileStat) {
312
317
  }
313
318
 
314
319
  export {
315
- VALID_AUTOMATION_SUB_TYPES,
316
- VALID_AUTOMATION_TYPES,
320
+ VALID_FEED_TYPES,
317
321
  VALID_IMPORT_AS_TYPES,
318
322
  VALID_MEDIA_FILTER_TYPES,
319
323
  VALID_POST_STATUSES,
320
324
  VALID_POST_TYPES,
321
325
  VALID_POSTING_TYPES,
326
+ VALID_POST_VIEWS,
322
327
  VALID_POST_SORT_FIELDS,
328
+ VALID_POST_UPDATE_MODES,
329
+ VALID_QUEUE_POSITIONS,
330
+ VALID_PUBLISHED_POST_STATUSES,
331
+ VALID_PUBLISHED_POST_SORT_FIELDS,
323
332
  VALID_SORT_ORDERS,
324
333
  parseBooleanStrict,
325
334
  parseIntegerInRange,
package/test/cli.test.mjs CHANGED
@@ -294,7 +294,7 @@ test("version flags print package version", async () => {
294
294
  });
295
295
 
296
296
  assert.equal(result.status, 0, result.stderr);
297
- assert.equal(result.stdout.trim(), "1.4.4");
297
+ assert.equal(result.stdout.trim(), "1.5.0");
298
298
  assert.equal(result.stderr, "");
299
299
  }
300
300
  });
@@ -364,9 +364,9 @@ test("automations:create works when boolean flags are omitted", async () => {
364
364
  "https://example.com/feed.xml",
365
365
  "--import-as-type",
366
366
  "IMAGE",
367
- "--sub-type",
367
+ "--type",
368
368
  "RSS",
369
- "--title",
369
+ "--name",
370
370
  "Automation",
371
371
  ],
372
372
  homeDir,
@@ -377,6 +377,10 @@ test("automations:create works when boolean flags are omitted", async () => {
377
377
 
378
378
  const capture = JSON.parse(await readFile(capturePath, "utf8"));
379
379
  assert.equal(capture.method, "POST");
380
+ assert.equal(capture.body.name, "Automation");
381
+ assert.equal(capture.body.type, "RSS");
382
+ assert.equal(capture.body.title, "{{title}}");
383
+ assert.equal(capture.body.subType, undefined);
380
384
  assert.equal(capture.body.loadOldPosts, undefined);
381
385
  assert.equal(capture.body.addPostsAsDraft, undefined);
382
386
  });
@@ -603,6 +607,54 @@ test("posts:add-json can read payload from stdin", async () => {
603
607
  assert.equal(capture.body.publishMode, "DRAFT");
604
608
  });
605
609
 
610
+ test("posts:add-json preserves nullable contract fields for dry-run and request bodies", async () => {
611
+ const homeDir = await setupTempHome();
612
+ const payloadPath = path.join(homeDir, "nullable-payload.json");
613
+ const payloads = [
614
+ {
615
+ title: null,
616
+ caption: null,
617
+ poll: { question: "Question?", options: ["One", "Two"], period: "1d" },
618
+ alt: null,
619
+ link: null,
620
+ publishMode: "DRAFT",
621
+ scheduledAt: null,
622
+ media: null,
623
+ postAsStory: null,
624
+ autoThreadText: null,
625
+ comment: null,
626
+ },
627
+ {
628
+ caption: "Caption with a nullable poll",
629
+ poll: null,
630
+ publishMode: "DRAFT",
631
+ },
632
+ ];
633
+
634
+ for (const [index, payload] of payloads.entries()) {
635
+ await writeFile(payloadPath, JSON.stringify(payload), "utf8");
636
+ const dryRun = runCli({
637
+ args: ["--dry-run", "posts:add-json", "--brand-id", "10", "--collection-id", "20", "--payload", payloadPath],
638
+ homeDir,
639
+ capturePath: path.join(homeDir, `capture-null-dry-run-${index}.json`),
640
+ extraEnv: { NUELINK_API_KEY: "" },
641
+ });
642
+ assert.equal(dryRun.status, 0, dryRun.stderr);
643
+ assert.deepEqual(JSON.parse(dryRun.stdout).body, payload);
644
+
645
+ const capturePath = path.join(homeDir, `capture-null-live-${index}.json`);
646
+ const live = runCli({
647
+ args: ["posts:add-json", "--brand-id", "10", "--collection-id", "20", "--payload", payloadPath],
648
+ homeDir,
649
+ capturePath,
650
+ });
651
+ assert.equal(live.status, 0, live.stderr);
652
+ const capture = JSON.parse(await readFile(capturePath, "utf8"));
653
+ assert.deepEqual(capture.body, payload);
654
+ assert.deepEqual(capture.body, JSON.parse(dryRun.stdout).body);
655
+ }
656
+ });
657
+
606
658
  test("posts:add-json rejects invalid JSON payloads", async () => {
607
659
  const homeDir = await setupTempHome();
608
660
 
@@ -924,9 +976,9 @@ test("automations:create rejects invalid feed urls", async () => {
924
976
  "notaurl",
925
977
  "--import-as-type",
926
978
  "IMAGE",
927
- "--sub-type",
979
+ "--type",
928
980
  "RSS",
929
- "--title",
981
+ "--name",
930
982
  "Automation",
931
983
  ],
932
984
  homeDir,
@@ -951,9 +1003,9 @@ test("automations:create rejects invalid enum values", async () => {
951
1003
  "https://www.nasa.gov/rss/dyn/breaking_news.rss",
952
1004
  "--import-as-type",
953
1005
  "AUDIO",
954
- "--sub-type",
1006
+ "--type",
955
1007
  "RSS",
956
- "--title",
1008
+ "--name",
957
1009
  "Automation",
958
1010
  ],
959
1011
  homeDir,
@@ -1012,6 +1064,150 @@ test("posts:create requires scheduled-at for scheduled posts", async () => {
1012
1064
  assert.match(result.stderr, /scheduledAt is required/);
1013
1065
  });
1014
1066
 
1067
+ test("schedule requests the brand weekly schedule", async () => {
1068
+ const homeDir = await setupTempHome();
1069
+ const capturePath = path.join(homeDir, "capture-schedule.json");
1070
+ const result = runCli({
1071
+ args: ["schedule", "--brand-id", "42"],
1072
+ homeDir,
1073
+ capturePath,
1074
+ });
1075
+
1076
+ assert.equal(result.status, 0, result.stderr);
1077
+ const capture = JSON.parse(await readFile(capturePath, "utf8"));
1078
+ assert.equal(new URL(capture.url).pathname, "/api/public/v1/brands/42/schedule");
1079
+ });
1080
+
1081
+ test("brand-posts forwards brand-wide post filters", async () => {
1082
+ const homeDir = await setupTempHome();
1083
+ const capturePath = path.join(homeDir, "capture-brand-posts.json");
1084
+ const result = runCli({
1085
+ args: [
1086
+ "brand-posts", "--brand-id", "42", "--collection-id", "77",
1087
+ "--view", "scheduled", "--status", "pending", "--sort-by", "post_date",
1088
+ ],
1089
+ homeDir,
1090
+ capturePath,
1091
+ });
1092
+
1093
+ assert.equal(result.status, 0, result.stderr);
1094
+ const capture = JSON.parse(await readFile(capturePath, "utf8"));
1095
+ const url = new URL(capture.url);
1096
+ assert.equal(url.pathname, "/api/public/v1/brands/42/posts");
1097
+ assert.equal(url.searchParams.get("collection_id"), "77");
1098
+ assert.equal(url.searchParams.get("view"), "SCHEDULED");
1099
+ assert.equal(url.searchParams.get("status"), "PENDING");
1100
+ });
1101
+
1102
+ test("posts:update builds the documented patch payload", async () => {
1103
+ const homeDir = await setupTempHome();
1104
+ const capturePath = path.join(homeDir, "capture-post-update.json");
1105
+ const result = runCli({
1106
+ args: [
1107
+ "posts:update", "--brand-id", "42", "--post-id", "8801",
1108
+ "--publish-mode", "schedule", "--scheduled-at", "2026-10-12 09:00:00",
1109
+ ],
1110
+ homeDir,
1111
+ capturePath,
1112
+ });
1113
+
1114
+ assert.equal(result.status, 0, result.stderr);
1115
+ const capture = JSON.parse(await readFile(capturePath, "utf8"));
1116
+ assert.equal(capture.method, "PATCH");
1117
+ assert.equal(new URL(capture.url).pathname, "/api/public/v1/brands/42/posts/8801");
1118
+ assert.deepEqual(capture.body, {
1119
+ publishMode: "SCHEDULE",
1120
+ scheduledAt: "2026-10-12 09:00:00",
1121
+ });
1122
+ });
1123
+
1124
+ test("posts:move builds the documented atomic move payload", async () => {
1125
+ const homeDir = await setupTempHome();
1126
+ const capturePath = path.join(homeDir, "capture-post-move.json");
1127
+ const result = runCli({
1128
+ args: [
1129
+ "posts:move", "--brand-id", "42", "--source-collection-id", "77",
1130
+ "--destination-collection-id", "81", "--post-ids", "8801,8802",
1131
+ ],
1132
+ homeDir,
1133
+ capturePath,
1134
+ });
1135
+
1136
+ assert.equal(result.status, 0, result.stderr);
1137
+ const capture = JSON.parse(await readFile(capturePath, "utf8"));
1138
+ assert.equal(capture.method, "PATCH");
1139
+ assert.equal(new URL(capture.url).pathname, "/api/public/v1/brands/42/posts/move");
1140
+ assert.deepEqual(capture.body, {
1141
+ sourceCollectionId: 77,
1142
+ destinationCollectionId: 81,
1143
+ postIds: [8801, 8802],
1144
+ });
1145
+ });
1146
+
1147
+ test("posts:move rejects the same source and destination collection", async () => {
1148
+ const homeDir = await setupTempHome();
1149
+ const result = runCli({
1150
+ args: [
1151
+ "posts:move", "--brand-id", "42", "--source-collection-id", "77",
1152
+ "--destination-collection-id", "77", "--post-ids", "8801",
1153
+ ],
1154
+ homeDir,
1155
+ capturePath: path.join(homeDir, "capture-invalid-post-move.json"),
1156
+ });
1157
+
1158
+ assert.equal(result.status, 1);
1159
+ assert.match(result.stderr, /destination-collection-id must differ from source-collection-id/);
1160
+ });
1161
+
1162
+ test("posts:update requires an update operation", async () => {
1163
+ const homeDir = await setupTempHome();
1164
+ const result = runCli({
1165
+ args: ["posts:update", "--brand-id", "42", "--post-id", "8801"],
1166
+ homeDir,
1167
+ capturePath: path.join(homeDir, "capture-empty-post-update.json"),
1168
+ });
1169
+
1170
+ assert.equal(result.status, 1);
1171
+ assert.match(result.stderr, /At least one of publish-mode or queue-position is required/);
1172
+ });
1173
+
1174
+ test("posts:delete targets the sensitive delete endpoint", async () => {
1175
+ const homeDir = await setupTempHome();
1176
+ const capturePath = path.join(homeDir, "capture-post-delete.json");
1177
+ const result = runCli({
1178
+ args: ["posts:delete", "--brand-id", "42", "--post-id", "8801"],
1179
+ homeDir,
1180
+ capturePath,
1181
+ });
1182
+
1183
+ assert.equal(result.status, 0, result.stderr);
1184
+ const capture = JSON.parse(await readFile(capturePath, "utf8"));
1185
+ assert.equal(capture.method, "DELETE");
1186
+ assert.equal(new URL(capture.url).pathname, "/api/public/v1/brands/42/posts/8801");
1187
+ });
1188
+
1189
+ test("published-posts forwards result filters", async () => {
1190
+ const homeDir = await setupTempHome();
1191
+ const capturePath = path.join(homeDir, "capture-published-posts.json");
1192
+ const result = runCli({
1193
+ args: [
1194
+ "published-posts", "--brand-id", "42", "--status", "failed",
1195
+ "--channel-id", "501", "--search", "launch", "--sort-by", "likes",
1196
+ ],
1197
+ homeDir,
1198
+ capturePath,
1199
+ });
1200
+
1201
+ assert.equal(result.status, 0, result.stderr);
1202
+ const capture = JSON.parse(await readFile(capturePath, "utf8"));
1203
+ const url = new URL(capture.url);
1204
+ assert.equal(url.pathname, "/api/public/v1/brands/42/published-posts");
1205
+ assert.equal(url.searchParams.get("status"), "FAILED");
1206
+ assert.equal(url.searchParams.get("channel_id"), "501");
1207
+ assert.equal(url.searchParams.get("search"), "launch");
1208
+ assert.equal(url.searchParams.get("sort_by"), "likes");
1209
+ });
1210
+
1015
1211
  test("base url can be overridden for testing", async () => {
1016
1212
  const homeDir = await setupTempHome();
1017
1213
  const capturePath = path.join(homeDir, "capture-base-url.json");
@@ -1022,6 +1218,7 @@ test("base url can be overridden for testing", async () => {
1022
1218
  capturePath,
1023
1219
  extraEnv: {
1024
1220
  NUELINK_BASE_URL: "https://example.test/custom/v1",
1221
+ NUELINK_TRUSTED_HOSTS: "example.test",
1025
1222
  },
1026
1223
  });
1027
1224
 
@@ -1032,6 +1229,77 @@ test("base url can be overridden for testing", async () => {
1032
1229
  assert.equal(new URL(capture.url).pathname, "/custom/v1/brands");
1033
1230
  });
1034
1231
 
1232
+ for (const [name, baseUrl, extraEnv] of [
1233
+ ["rejects plaintext remote base URLs before authentication", "http://api.example.test/v1", {}],
1234
+ ["rejects untrusted HTTPS base URLs before authentication", "https://attacker.example.test/v1", {}],
1235
+ ["rejects URL credentials in the base URL", "https://user:secret@app.nuelink.com/api/public/v1", {}],
1236
+ ]) {
1237
+ test(name, async () => {
1238
+ const homeDir = await setupTempHome();
1239
+ const capturePath = path.join(homeDir, "capture-rejected-base-url.json");
1240
+ const result = runCli({
1241
+ args: ["--json", "brands"],
1242
+ homeDir,
1243
+ capturePath,
1244
+ extraEnv: { NUELINK_API_KEY: "", NUELINK_BASE_URL: baseUrl, ...extraEnv },
1245
+ });
1246
+ const error = assertJsonError(result, "CONFIG_INVALID");
1247
+ assert.match(error.message, /NUELINK_BASE_URL/);
1248
+ await assert.rejects(readFile(capturePath, "utf8"));
1249
+ });
1250
+ }
1251
+
1252
+ test("allows loopback HTTP only with explicit opt-in", async () => {
1253
+ const homeDir = await setupTempHome();
1254
+ const capturePath = path.join(homeDir, "capture-loopback-base-url.json");
1255
+ const result = runCli({
1256
+ args: ["brands"],
1257
+ homeDir,
1258
+ capturePath,
1259
+ extraEnv: {
1260
+ NUELINK_BASE_URL: "http://127.0.0.1:8787/api/public/v1",
1261
+ NUELINK_ALLOW_INSECURE_HTTP: "1",
1262
+ },
1263
+ });
1264
+ assert.equal(result.status, 0, result.stderr);
1265
+ const capture = JSON.parse(await readFile(capturePath, "utf8"));
1266
+ assert.equal(new URL(capture.url).origin, "http://127.0.0.1:8787");
1267
+ });
1268
+
1269
+ test("posts:create requires comment and comment-delay as a pair", async () => {
1270
+ const homeDir = await setupTempHome();
1271
+ for (const args of [
1272
+ ["posts:create", "--brand-id", "1", "--collection-id", "2", "--comment-delay", "30", "--dry-run"],
1273
+ ["posts:create", "--brand-id", "1", "--collection-id", "2", "--comment", "First comment", "--dry-run"],
1274
+ ]) {
1275
+ const capturePath = path.join(homeDir, `capture-comment-${args.includes("--comment-delay") ? "delay" : "text"}.json`);
1276
+ const result = runCli({ args, homeDir, capturePath });
1277
+ assert.equal(result.status, 1);
1278
+ assert.match(result.stderr, /comment and comment-delay must be provided together/);
1279
+ await assert.rejects(readFile(capturePath, "utf8"));
1280
+ }
1281
+ });
1282
+
1283
+ test("JSON mode without a command returns a structured usage error", async () => {
1284
+ const homeDir = await setupTempHome();
1285
+ const result = runCli({
1286
+ args: ["--json"],
1287
+ homeDir,
1288
+ capturePath: path.join(homeDir, "capture-json-no-command.json"),
1289
+ extraEnv: { NUELINK_API_KEY: "" },
1290
+ });
1291
+ assertJsonError(result, "USAGE_ERROR");
1292
+ });
1293
+
1294
+ test("GET requests reject dry-run instead of silently suppressing the read", async () => {
1295
+ const homeDir = await setupTempHome();
1296
+ const capturePath = path.join(homeDir, "capture-get-dry-run.json");
1297
+ const result = runCli({ args: ["--dry-run", "brands"], homeDir, capturePath });
1298
+ assert.equal(result.status, 1);
1299
+ assert.match(result.stderr, /--dry-run is only supported for API mutations/);
1300
+ await assert.rejects(readFile(capturePath, "utf8"));
1301
+ });
1302
+
1035
1303
  test("get requests retry on 429 and then succeed", async () => {
1036
1304
  const homeDir = await setupTempHome();
1037
1305
  const capturePath = path.join(homeDir, "capture-retry.json");
@@ -1116,11 +1384,11 @@ for (const fixture of [
1116
1384
  args: ["collections:create", "--brand-id", "1", "--title", " ", "--dry-run"],
1117
1385
  },
1118
1386
  {
1119
- name: "automation titles",
1387
+ name: "automation names",
1120
1388
  args: [
1121
1389
  "automations:create", "--brand-id", "1", "--collection-id", "2",
1122
1390
  "--feed-url", "https://example.com/feed.xml", "--import-as-type", "IMAGE",
1123
- "--sub-type", "RSS", "--title", " ", "--dry-run",
1391
+ "--type", "RSS", "--name", " ", "--dry-run",
1124
1392
  ],
1125
1393
  },
1126
1394
  {
@@ -165,12 +165,16 @@ globalThis.fetch = async (input, init = {}) => {
165
165
  payload.data = [
166
166
  {
167
167
  id: 21682,
168
- title: "NASA Breaking News",
169
- description: "NASA Breaking News RSS Automation",
168
+ name: "NASA Breaking News",
170
169
  collectionId: 720,
171
170
  status: "ACTIVE",
172
- subType: "RSS",
171
+ type: "RSS",
173
172
  feedUrl: "https://www.nasa.gov/rss/dyn/breaking_news.rss",
173
+ runCount: 0,
174
+ importAsType: "IMAGE",
175
+ lastRun: 0,
176
+ title: "{{title}}",
177
+ caption: "{{description}} {{link}}",
174
178
  createdAt: "2026-06-29T14:24:13.000000Z",
175
179
  updatedAt: "2026-06-29T14:24:13.000000Z",
176
180
  },
@@ -165,12 +165,16 @@ globalThis.fetch = async (input, init = {}) => {
165
165
  payload.data = [
166
166
  {
167
167
  id: 21682,
168
- title: "NASA Breaking News",
169
- description: "NASA Breaking News RSS Automation",
168
+ name: "NASA Breaking News",
170
169
  collectionId: 720,
171
170
  status: "ACTIVE",
172
- subType: "RSS",
171
+ type: "RSS",
173
172
  feedUrl: "https://www.nasa.gov/rss/dyn/breaking_news.rss",
173
+ runCount: 0,
174
+ importAsType: "IMAGE",
175
+ lastRun: 0,
176
+ title: "{{title}}",
177
+ caption: "{{description}} {{link}}",
174
178
  createdAt: "2026-06-29T14:24:13.000000Z",
175
179
  updatedAt: "2026-06-29T14:24:13.000000Z",
176
180
  },