@posterly/cli 0.1.3 → 0.1.4

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/README.md CHANGED
@@ -8,6 +8,7 @@ Run the CLI without installing anything globally:
8
8
 
9
9
  ```bash
10
10
  npx @posterly/cli@latest auth:login
11
+ npx @posterly/cli@latest doctor --pretty
11
12
  npx @posterly/cli@latest whoami --pretty
12
13
  ```
13
14
 
@@ -20,6 +21,7 @@ Optional global install:
20
21
  ```bash
21
22
  npm i -g @posterly/cli@latest
22
23
  posterly auth:login
24
+ posterly doctor --pretty
23
25
  posterly whoami --pretty
24
26
  ```
25
27
 
@@ -36,6 +38,7 @@ folder. In that case `posterly` will only be available as
36
38
  ```bash
37
39
  posterly auth:login
38
40
  posterly auth:key
41
+ posterly doctor --pretty
39
42
  posterly whoami --pretty
40
43
  posterly accounts:list --pretty
41
44
  posterly accounts:disconnect 123 --confirm --pretty
@@ -49,10 +52,15 @@ posterly posts:create --account-id 123 --caption "Launching soon" --scheduled-at
49
52
  posterly posts:status 123 --status paused --confirm --pretty
50
53
  posterly posts:missing 123 --pretty
51
54
  posterly posts:release-id 123 --release-id launch-2026-05-16 --group-id campaign-42 --pretty
55
+ posterly posts:delete 123 --confirm --pretty
52
56
  posterly posts:delete-group campaign-42 --confirm --pretty
57
+ posterly webhooks:delete wh_123 --confirm --pretty
53
58
  posterly gbp:reviews --account-id 123 --unanswered --pretty
54
59
  posterly gbp:review-link 123 --pretty
55
60
  posterly gbp:audit 123 --pretty
61
+ posterly gbp:media --account-id 123 --pretty
62
+ posterly gbp:add-media --account-id 123 --source-url https://cdn.example.com/front.jpg --category COVER --confirm --pretty
63
+ posterly gbp:delete-media --account-id 123 --media-name accounts/123/locations/456/media/abc --confirm --pretty
56
64
  posterly gbp:suggest-reply --account-id 123 --star-rating 5 --review-text "Great service" --pretty
57
65
  posterly gbp:reply --account-id 123 --review-name accounts/123/locations/456/reviews/abc --comment "Thanks Alex. Glad we could help." --confirm --pretty
58
66
  ```
@@ -61,6 +69,11 @@ The CLI outputs JSON by default so it can be piped into `jq` or other tools. Use
61
69
  `--pretty` for formatted output. `--human` is accepted as an alias for
62
70
  `--pretty` for older examples.
63
71
 
72
+ Use `posterly doctor --pretty` to check Node version, the configured API origin,
73
+ whether an API key is present, whether the key works against `/api/v1/whoami`,
74
+ and whether a newer `@posterly/cli` package is published. Add `--no-npm` to skip
75
+ the npm registry check in locked-down environments.
76
+
64
77
  Authentication:
65
78
 
66
79
  - Prefer `posterly auth:login` for browser-based OAuth.
@@ -73,3 +86,6 @@ command-line arguments in interactive shells because argv can be stored in shell
73
86
  history or exposed through local process listings.
74
87
 
75
88
  Set `--url` or `POSTERLY_URL` to point at a non-production posterly deployment.
89
+ The CLI refuses to send API keys to non-local `http://` URLs by default. Use
90
+ `https://`, `http://localhost` for local development, or `--allow-insecure-url`
91
+ only for a trusted private development endpoint.
package/bin/posterly.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- import { readFile, mkdir, writeFile, rm } from 'node:fs/promises';
3
+ import { readFile, mkdir, writeFile, rm, chmod, rename } from 'node:fs/promises';
4
4
  import { existsSync } from 'node:fs';
5
5
  import os from 'node:os';
6
6
  import path from 'node:path';
@@ -15,16 +15,37 @@ import {
15
15
  const DEFAULT_BASE_URL = 'https://www.poster.ly';
16
16
  const CONFIG_DIR = path.join(os.homedir(), '.posterly');
17
17
  const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
18
+ const CLI_PACKAGE_NAME = '@posterly/cli';
19
+ const CLI_NPM_LATEST_URL = 'https://registry.npmjs.org/@posterly%2fcli/latest';
20
+ const REQUEST_TIMEOUT_MS = 2500;
21
+ const REQUIRED_NODE_MAJOR = 20;
18
22
  const OAUTH_CLIENT_ID = 'posterly-cli';
19
23
  const OAUTH_CALLBACK_PORT = 37373;
20
24
  const OAUTH_CALLBACK_PATH = '/oauth/callback';
21
25
  const OAUTH_SCOPES = ['accounts:read', 'accounts:write', 'posts:read', 'posts:write', 'media:write', 'analytics:read'];
26
+ const TRUSTED_POSTERLY_HOSTS = new Set(['poster.ly', 'www.poster.ly']);
27
+ const GOOGLE_BUSINESS_MEDIA_CATEGORIES = [
28
+ 'COVER',
29
+ 'PROFILE',
30
+ 'LOGO',
31
+ 'EXTERIOR',
32
+ 'INTERIOR',
33
+ 'PRODUCT',
34
+ 'AT_WORK',
35
+ 'FOOD_AND_DRINK',
36
+ 'MENU',
37
+ 'COMMON_AREA',
38
+ 'ROOMS',
39
+ 'TEAMS',
40
+ 'ADDITIONAL',
41
+ ];
22
42
 
23
43
  const COMMANDS = [
24
44
  'auth:login [--url https://www.poster.ly] [--no-open]',
25
45
  'auth:key [--url https://www.poster.ly]',
26
46
  'auth:status',
27
47
  'auth:logout',
48
+ 'doctor [--url https://www.poster.ly] [--no-npm]',
28
49
  'whoami',
29
50
  'accounts:list|disconnect [--workspace-id id]',
30
51
  'connect:link [platform] [--workspace-id id] [--include-planned]',
@@ -35,7 +56,7 @@ const COMMANDS = [
35
56
  'slots:next',
36
57
  'media:upload|signed-upload|upload-from-url',
37
58
  'analytics:account|posts',
38
- 'gbp:reviews|review-link|audit|suggest-reply|reply|delete-reply',
59
+ 'gbp:reviews|review-link|audit|media|add-media|delete-media|suggest-reply|reply|delete-reply',
39
60
  'ai:video-options|video-function|generate-video|video-jobs|video-job',
40
61
  'activity:list',
41
62
  'notifications:list',
@@ -63,6 +84,7 @@ async function main() {
63
84
  if (command === 'auth:key') return saveKey(positional[0], flags);
64
85
  if (command === 'auth:status') return authStatus(flags);
65
86
  if (command === 'auth:logout') return logout(flags);
87
+ if (command === 'doctor') return doctor(flags);
66
88
 
67
89
  const client = await createClient(flags);
68
90
 
@@ -165,6 +187,9 @@ async function main() {
165
187
  group_id: flags.groupId,
166
188
  })), flags);
167
189
  case 'posts:delete':
190
+ if (!flagEnabled(flags.confirm)) {
191
+ throw new Error('Deleting a post is irreversible. Re-run with --confirm after verifying the post ID.');
192
+ }
168
193
  return print(await client.delete(`/posts/${required(positional[0] || flags.id, 'post id')}`), flags);
169
194
  case 'posts:delete-group':
170
195
  if (!flagEnabled(flags.confirm)) {
@@ -236,6 +261,34 @@ async function main() {
236
261
  account_id: flags.accountId || positional[0],
237
262
  location_id: flags.locationId,
238
263
  })), flags);
264
+ case 'gbp:media':
265
+ return print(await client.get(withQuery('/google-business/media', {
266
+ workspace_id: flags.workspaceId,
267
+ account_id: flags.accountId || positional[0],
268
+ location_id: flags.locationId,
269
+ })), flags);
270
+ case 'gbp:add-media':
271
+ if (!flagEnabled(flags.confirm)) {
272
+ throw new Error('Adding Google Business profile media changes the public listing. Re-run with --confirm after verifying the location, category, and media URL.');
273
+ }
274
+ return print(await client.post('/google-business/media', clean({
275
+ workspace_id: flags.workspaceId,
276
+ account_id: flags.accountId,
277
+ location_id: flags.locationId,
278
+ source_url: required(flags.sourceUrl || positional[0], '--source-url'),
279
+ category: validateGoogleBusinessMediaCategory(required(flags.category || positional[1], '--category')),
280
+ media_format: flags.mediaFormat ? validateGoogleBusinessMediaFormat(flags.mediaFormat) : undefined,
281
+ })), flags);
282
+ case 'gbp:delete-media':
283
+ if (!flagEnabled(flags.confirm)) {
284
+ throw new Error('Deleting Google Business profile media is irreversible. Re-run with --confirm after verifying the media resource name.');
285
+ }
286
+ return print(await client.delete('/google-business/media', clean({
287
+ workspace_id: flags.workspaceId,
288
+ account_id: flags.accountId,
289
+ location_id: flags.locationId,
290
+ media_name: required(flags.mediaName || positional[0], '--media-name'),
291
+ })), flags);
239
292
  case 'gbp:suggest-reply':
240
293
  return print(await client.post('/google-business/reviews/suggest-reply', clean({
241
294
  workspace_id: flags.workspaceId,
@@ -322,6 +375,9 @@ async function main() {
322
375
  is_active: flags.active === undefined ? undefined : booleanFlag(flags.active),
323
376
  })), flags);
324
377
  case 'webhooks:delete':
378
+ if (!flagEnabled(flags.confirm)) {
379
+ throw new Error('Deleting a webhook is irreversible. Re-run with --confirm after verifying the webhook ID.');
380
+ }
325
381
  return print(await client.delete(`/webhooks/${required(positional[0] || flags.id, 'webhook id')}`), flags);
326
382
  case 'webhooks:test':
327
383
  return print(await client.post(`/webhooks/${required(positional[0] || flags.id, 'webhook id')}/test`, {}), flags);
@@ -366,12 +422,11 @@ function parseArgs(args) {
366
422
  }
367
423
 
368
424
  async function createClient(flags) {
369
- const config = await readConfig();
370
- const apiKey = flags.apiKey || process.env.POSTERLY_API_KEY || config.apiKey;
371
- const baseUrl = normalizeBaseUrl(flags.url || process.env.POSTERLY_URL || config.baseUrl || DEFAULT_BASE_URL);
425
+ const { apiKey, baseUrl } = await resolveAuthContext(flags);
372
426
  if (!apiKey) {
373
427
  throw new Error('Missing API key. Run `npx @posterly/cli@latest auth:login`, `posterly auth:login` after global install, run `posterly auth:key` and paste a key at the prompt, or set POSTERLY_API_KEY.');
374
428
  }
429
+ validateBaseUrlForKeyUse(baseUrl, flags, 'send an API key to');
375
430
 
376
431
  async function request(method, path, body) {
377
432
  const res = await fetch(`${baseUrl}/api/v1${path}`, {
@@ -404,6 +459,31 @@ async function createClient(flags) {
404
459
  };
405
460
  }
406
461
 
462
+ async function resolveAuthContext(flags = {}) {
463
+ const config = await readConfig();
464
+ const apiKey = flags.apiKey || process.env.POSTERLY_API_KEY || config.apiKey || '';
465
+ const baseUrl = normalizeBaseUrl(flags.url || process.env.POSTERLY_URL || config.baseUrl || DEFAULT_BASE_URL);
466
+ const authSource = flags.apiKey
467
+ ? 'flag'
468
+ : process.env.POSTERLY_API_KEY
469
+ ? 'env'
470
+ : config.apiKey
471
+ ? 'config'
472
+ : null;
473
+
474
+ return {
475
+ config,
476
+ apiKey,
477
+ baseUrl,
478
+ authSource,
479
+ authType: authSource === 'env'
480
+ ? 'env'
481
+ : authSource === 'flag'
482
+ ? 'api_key'
483
+ : config.authType || (config.apiKey ? 'api_key' : null),
484
+ };
485
+ }
486
+
407
487
  async function saveKey(key, flags) {
408
488
  if (key || flags.apiKey) {
409
489
  console.warn('Warning: passing API keys as command-line arguments can expose them through shell history or process listings. Prefer `posterly auth:key` with no argument or POSTERLY_API_KEY.');
@@ -413,13 +493,14 @@ async function saveKey(key, flags) {
413
493
  if (!apiKey) {
414
494
  throw new Error('Missing API key. Run `posterly auth:key` and paste a key at the prompt, pipe a key on stdin, use `npx @posterly/cli@latest auth:key`, or set POSTERLY_API_KEY.');
415
495
  }
416
- await mkdir(CONFIG_DIR, { recursive: true });
496
+ const baseUrl = normalizeBaseUrl(flags.url || process.env.POSTERLY_URL || DEFAULT_BASE_URL);
497
+ validateBaseUrlForKeyUse(baseUrl, flags, 'store an API key for');
417
498
  const config = {
418
499
  apiKey,
419
- baseUrl: normalizeBaseUrl(flags.url || process.env.POSTERLY_URL || DEFAULT_BASE_URL),
500
+ baseUrl,
420
501
  updatedAt: new Date().toISOString(),
421
502
  };
422
- await writeFile(CONFIG_FILE, `${JSON.stringify(config, null, 2)}\n`, 'utf8');
503
+ await writeConfig(config);
423
504
  return print({ saved: true, config_file: CONFIG_FILE, base_url: config.baseUrl }, flags);
424
505
  }
425
506
 
@@ -479,6 +560,7 @@ async function readApiKeyFromInput() {
479
560
 
480
561
  async function authLogin(flags) {
481
562
  const baseUrl = normalizeBaseUrl(flags.url || process.env.POSTERLY_URL || DEFAULT_BASE_URL);
563
+ validateBaseUrlForKeyUse(baseUrl, flags, 'start OAuth login against');
482
564
  const redirectUri = `http://127.0.0.1:${OAUTH_CALLBACK_PORT}${OAUTH_CALLBACK_PATH}`;
483
565
  const state = randomBytes(18).toString('base64url');
484
566
  const codeVerifier = randomBytes(48).toString('base64url');
@@ -509,7 +591,6 @@ async function authLogin(flags) {
509
591
  }
510
592
 
511
593
  const token = await loginPromise;
512
- await mkdir(CONFIG_DIR, { recursive: true });
513
594
  const config = {
514
595
  apiKey: token.access_token,
515
596
  baseUrl,
@@ -518,7 +599,7 @@ async function authLogin(flags) {
518
599
  expiresAt: token.expires_in ? new Date(Date.now() + Number(token.expires_in) * 1000).toISOString() : null,
519
600
  updatedAt: new Date().toISOString(),
520
601
  };
521
- await writeFile(CONFIG_FILE, `${JSON.stringify(config, null, 2)}\n`, 'utf8');
602
+ await writeConfig(config);
522
603
 
523
604
  return print({
524
605
  authenticated: true,
@@ -639,16 +720,18 @@ function errorHtml(message) {
639
720
  }
640
721
 
641
722
  async function authStatus(flags) {
642
- const config = await readConfig();
643
- const envKey = Boolean(process.env.POSTERLY_API_KEY);
723
+ const context = await resolveAuthContext(flags);
724
+ const baseUrlCheck = inspectBaseUrl(context.baseUrl);
644
725
  return print({
645
- authenticated: Boolean(envKey || config.apiKey),
646
- source: envKey ? 'env' : config.apiKey ? 'config' : null,
647
- base_url: process.env.POSTERLY_URL || config.baseUrl || DEFAULT_BASE_URL,
726
+ authenticated: Boolean(context.apiKey),
727
+ source: context.authSource,
728
+ base_url: context.baseUrl,
648
729
  config_file: CONFIG_FILE,
649
- auth_type: envKey ? 'env' : config.authType || (config.apiKey ? 'api_key' : null),
650
- scopes: config.scopes,
651
- expires_at: config.expiresAt,
730
+ auth_type: context.authType,
731
+ scopes: context.config.scopes,
732
+ expires_at: context.config.expiresAt,
733
+ base_url_check: summarizeBaseUrlCheck(baseUrlCheck),
734
+ next_step: authStatusNextStep({ hasApiKey: Boolean(context.apiKey), baseUrlCheck }),
652
735
  }, flags);
653
736
  }
654
737
 
@@ -657,6 +740,58 @@ async function logout(flags) {
657
740
  return print({ logged_out: true, config_file: CONFIG_FILE }, flags);
658
741
  }
659
742
 
743
+ async function doctor(flags) {
744
+ const context = await resolveAuthContext(flags);
745
+ const packageInfo = await readPackageInfo();
746
+ const baseUrlCheck = inspectBaseUrl(context.baseUrl);
747
+ const checks = [
748
+ nodeVersionCheck(),
749
+ {
750
+ name: 'base_url',
751
+ ok: baseUrlCheck.valid && (baseUrlCheck.secure || flagEnabled(flags.allowInsecureUrl)),
752
+ severity: baseUrlSeverity(baseUrlCheck, flags),
753
+ value: context.baseUrl,
754
+ ...summarizeBaseUrlCheck(baseUrlCheck),
755
+ },
756
+ {
757
+ name: 'auth_config',
758
+ ok: Boolean(context.apiKey),
759
+ severity: context.apiKey ? 'info' : 'error',
760
+ source: context.authSource,
761
+ config_file: CONFIG_FILE,
762
+ message: context.apiKey
763
+ ? `API key found via ${context.authSource}.`
764
+ : 'No API key found in POSTERLY_API_KEY, --api-key, or local config.',
765
+ },
766
+ ];
767
+
768
+ const latest = flagEnabled(flags.noNpm)
769
+ ? { skipped: true, reason: '--no-npm' }
770
+ : await fetchLatestCliVersion();
771
+ checks.push(npmVersionCheck(packageInfo.version, latest));
772
+
773
+ const canProbeApi = context.apiKey && baseUrlCheck.valid && (baseUrlCheck.secure || flagEnabled(flags.allowInsecureUrl));
774
+ const authProbe = canProbeApi
775
+ ? await probeWhoami(context.baseUrl, context.apiKey)
776
+ : null;
777
+ checks.push(apiAuthCheck(authProbe, { skippedBecause: context.apiKey ? 'base_url' : 'auth_config' }));
778
+
779
+ const ok = checks.every((check) => check.severity !== 'error');
780
+ if (!ok) {
781
+ process.exitCode = 1;
782
+ }
783
+ return print({
784
+ ok,
785
+ package: packageInfo,
786
+ base_url: context.baseUrl,
787
+ checks,
788
+ user: authProbe?.ok ? authProbe.user : undefined,
789
+ default_workspace: authProbe?.ok ? authProbe.default_workspace : undefined,
790
+ scopes: authProbe?.ok ? authProbe.scopes : undefined,
791
+ next_step: doctorNextStep({ checks, latest, authProbe }),
792
+ }, flags);
793
+ }
794
+
660
795
  async function readConfig() {
661
796
  try {
662
797
  return JSON.parse(await readFile(CONFIG_FILE, 'utf8'));
@@ -665,6 +800,33 @@ async function readConfig() {
665
800
  }
666
801
  }
667
802
 
803
+ async function ensureConfigDir() {
804
+ await mkdir(CONFIG_DIR, { recursive: true, mode: 0o700 });
805
+ await chmodIfPresent(CONFIG_DIR, 0o700);
806
+ }
807
+
808
+ async function writeConfig(config) {
809
+ await ensureConfigDir();
810
+ const tempFile = path.join(CONFIG_DIR, `.config.${process.pid}.${randomBytes(6).toString('hex')}.tmp`);
811
+ try {
812
+ await writeFile(tempFile, `${JSON.stringify(config, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
813
+ await chmodIfPresent(tempFile, 0o600);
814
+ await rename(tempFile, CONFIG_FILE);
815
+ await chmodIfPresent(CONFIG_FILE, 0o600);
816
+ } catch (error) {
817
+ await rm(tempFile, { force: true }).catch(() => {});
818
+ throw error;
819
+ }
820
+ }
821
+
822
+ async function chmodIfPresent(filePath, mode) {
823
+ try {
824
+ await chmod(filePath, mode);
825
+ } catch {
826
+ // Best-effort hardening for filesystems that do not fully support POSIX modes.
827
+ }
828
+ }
829
+
668
830
  async function postPayloadFromFlags(flags) {
669
831
  if (flags.file) return validatePostPayload(await readJson(required(flags.file, '--file')));
670
832
  return clean({
@@ -866,6 +1028,22 @@ function validatePostStatus(value) {
866
1028
  return status;
867
1029
  }
868
1030
 
1031
+ function validateGoogleBusinessMediaCategory(value) {
1032
+ const category = String(value || '').trim().toUpperCase();
1033
+ if (!GOOGLE_BUSINESS_MEDIA_CATEGORIES.includes(category)) {
1034
+ throw new Error(`Unknown Google Business media category "${value}". Allowed categories: ${formatList(GOOGLE_BUSINESS_MEDIA_CATEGORIES)}.`);
1035
+ }
1036
+ return category;
1037
+ }
1038
+
1039
+ function validateGoogleBusinessMediaFormat(value) {
1040
+ const format = String(value || '').trim().toUpperCase();
1041
+ if (!['PHOTO', 'VIDEO'].includes(format)) {
1042
+ throw new Error(`Unknown Google Business media format "${value}". Allowed formats: PHOTO, VIDEO.`);
1043
+ }
1044
+ return format;
1045
+ }
1046
+
869
1047
  function normalizeManifestKey(value) {
870
1048
  return String(value || '').trim().toLowerCase().replace(/[\s-]+/g, '_');
871
1049
  }
@@ -885,7 +1063,338 @@ function flagEnabled(value) {
885
1063
  }
886
1064
 
887
1065
  function normalizeBaseUrl(value) {
888
- return String(value || DEFAULT_BASE_URL).replace(/\/$/, '');
1066
+ const raw = String(value || DEFAULT_BASE_URL).trim();
1067
+ try {
1068
+ const url = new URL(raw);
1069
+ url.pathname = url.pathname.replace(/\/api\/v1\/?$/, '').replace(/\/+$/, '') || '/';
1070
+ url.search = '';
1071
+ url.hash = '';
1072
+ return url.toString().replace(/\/$/, '');
1073
+ } catch {
1074
+ return raw.replace(/\/api\/v1\/?$/, '').replace(/\/$/, '');
1075
+ }
1076
+ }
1077
+
1078
+ function inspectBaseUrl(baseUrl) {
1079
+ try {
1080
+ const url = new URL(baseUrl);
1081
+ const hostname = url.hostname.toLowerCase().replace(/^\[|\]$/g, '');
1082
+ const local = isLocalHost(hostname);
1083
+ const trustedPosterlyHost = TRUSTED_POSTERLY_HOSTS.has(hostname);
1084
+ const secure = url.protocol === 'https:' || (url.protocol === 'http:' && local);
1085
+ const warnings = [];
1086
+ if (!trustedPosterlyHost) {
1087
+ warnings.push(local ? 'local_development_host' : 'custom_host');
1088
+ }
1089
+ if (!secure) {
1090
+ warnings.push('insecure_non_local_url');
1091
+ }
1092
+
1093
+ return {
1094
+ valid: true,
1095
+ secure,
1096
+ protocol: url.protocol.replace(/:$/, ''),
1097
+ host: url.host,
1098
+ trusted_posterly_host: trustedPosterlyHost,
1099
+ local_development_host: local,
1100
+ warnings,
1101
+ message: baseUrlMessage({ secure, trustedPosterlyHost, local }),
1102
+ };
1103
+ } catch {
1104
+ return {
1105
+ valid: false,
1106
+ secure: false,
1107
+ warnings: ['invalid_url'],
1108
+ message: 'Base URL must include a scheme and host, for example https://www.poster.ly.',
1109
+ };
1110
+ }
1111
+ }
1112
+
1113
+ function summarizeBaseUrlCheck(check) {
1114
+ return clean({
1115
+ valid: check.valid,
1116
+ secure: check.secure,
1117
+ protocol: check.protocol,
1118
+ host: check.host,
1119
+ trusted_posterly_host: check.trusted_posterly_host,
1120
+ local_development_host: check.local_development_host,
1121
+ warnings: check.warnings,
1122
+ message: check.message,
1123
+ });
1124
+ }
1125
+
1126
+ function baseUrlSeverity(check, flags) {
1127
+ if (!check.valid) return 'error';
1128
+ if (!check.secure && !flagEnabled(flags.allowInsecureUrl)) return 'error';
1129
+ if (!check.trusted_posterly_host) return 'warning';
1130
+ return 'info';
1131
+ }
1132
+
1133
+ function validateBaseUrlForKeyUse(baseUrl, flags, action) {
1134
+ const check = inspectBaseUrl(baseUrl);
1135
+ if (!check.valid) {
1136
+ throw new Error(`${check.message} Received: ${baseUrl}`);
1137
+ }
1138
+ if (!check.secure && !flagEnabled(flags.allowInsecureUrl)) {
1139
+ throw new Error(`Refusing to ${action} ${baseUrl}. Use https, http://localhost for local development, or re-run with --allow-insecure-url only for a trusted private development endpoint.`);
1140
+ }
1141
+ }
1142
+
1143
+ function baseUrlMessage({ secure, trustedPosterlyHost, local }) {
1144
+ if (!secure) {
1145
+ return 'Non-local HTTP URLs are blocked for API-key requests.';
1146
+ }
1147
+ if (local) {
1148
+ return 'Local development URL accepted.';
1149
+ }
1150
+ if (!trustedPosterlyHost) {
1151
+ return 'Custom HTTPS host accepted; verify it is your intended posterly deployment before sending API keys.';
1152
+ }
1153
+ return 'Official posterly API host.';
1154
+ }
1155
+
1156
+ function isLocalHost(hostname) {
1157
+ return hostname === 'localhost'
1158
+ || hostname.endsWith('.localhost')
1159
+ || hostname === '::1'
1160
+ || hostname === '0.0.0.0'
1161
+ || hostname === '127.0.0.1'
1162
+ || hostname.startsWith('127.');
1163
+ }
1164
+
1165
+ let packageInfoCache;
1166
+
1167
+ async function readPackageInfo() {
1168
+ if (packageInfoCache) return packageInfoCache;
1169
+ try {
1170
+ const pkg = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8'));
1171
+ packageInfoCache = {
1172
+ name: typeof pkg.name === 'string' ? pkg.name : CLI_PACKAGE_NAME,
1173
+ version: typeof pkg.version === 'string' ? pkg.version : 'unknown',
1174
+ };
1175
+ } catch {
1176
+ packageInfoCache = { name: CLI_PACKAGE_NAME, version: 'unknown' };
1177
+ }
1178
+ return packageInfoCache;
1179
+ }
1180
+
1181
+ function nodeVersionCheck() {
1182
+ const major = Number.parseInt(process.versions.node.split('.')[0], 10);
1183
+ const ok = Number.isFinite(major) && major >= REQUIRED_NODE_MAJOR;
1184
+ return {
1185
+ name: 'node',
1186
+ ok,
1187
+ severity: ok ? 'info' : 'error',
1188
+ version: process.version,
1189
+ required: `>=${REQUIRED_NODE_MAJOR}`,
1190
+ message: ok
1191
+ ? 'Node version is supported.'
1192
+ : `Node ${REQUIRED_NODE_MAJOR}+ is required.`,
1193
+ };
1194
+ }
1195
+
1196
+ function npmVersionCheck(currentVersion, latest) {
1197
+ if (latest.skipped) {
1198
+ return {
1199
+ name: 'npm_latest',
1200
+ ok: true,
1201
+ severity: 'info',
1202
+ skipped: true,
1203
+ message: `Skipped npm latest check (${latest.reason}).`,
1204
+ };
1205
+ }
1206
+ if (latest.error) {
1207
+ return {
1208
+ name: 'npm_latest',
1209
+ ok: false,
1210
+ severity: 'warning',
1211
+ current_version: currentVersion,
1212
+ message: latest.error,
1213
+ };
1214
+ }
1215
+
1216
+ const comparison = compareSemver(currentVersion, latest.version);
1217
+ return {
1218
+ name: 'npm_latest',
1219
+ ok: comparison >= 0,
1220
+ severity: comparison < 0 ? 'warning' : 'info',
1221
+ current_version: currentVersion,
1222
+ latest_version: latest.version,
1223
+ update_status: comparison < 0
1224
+ ? 'update_available'
1225
+ : comparison > 0
1226
+ ? 'newer_than_npm'
1227
+ : 'current',
1228
+ message: comparison < 0
1229
+ ? `Update available: ${latest.version}.`
1230
+ : comparison > 0
1231
+ ? 'Local package is newer than npm latest; publish may still be pending.'
1232
+ : 'CLI package is current.',
1233
+ };
1234
+ }
1235
+
1236
+ function apiAuthCheck(probe, { skippedBecause }) {
1237
+ if (!probe) {
1238
+ return {
1239
+ name: 'api_auth',
1240
+ ok: false,
1241
+ severity: 'error',
1242
+ skipped: true,
1243
+ skipped_because: skippedBecause,
1244
+ message: skippedBecause === 'auth_config'
1245
+ ? 'Skipped because no API key is configured.'
1246
+ : 'Skipped because the base URL is not safe for API-key requests.',
1247
+ };
1248
+ }
1249
+
1250
+ if (probe.ok) {
1251
+ return {
1252
+ name: 'api_auth',
1253
+ ok: true,
1254
+ severity: 'info',
1255
+ status: probe.status,
1256
+ duration_ms: probe.duration_ms,
1257
+ message: 'API key validated against /api/v1/whoami.',
1258
+ };
1259
+ }
1260
+
1261
+ return {
1262
+ name: 'api_auth',
1263
+ ok: false,
1264
+ severity: 'error',
1265
+ status: probe.status,
1266
+ duration_ms: probe.duration_ms,
1267
+ message: probe.error || 'API key validation failed.',
1268
+ };
1269
+ }
1270
+
1271
+ async function probeWhoami(baseUrl, apiKey, timeoutMs = REQUEST_TIMEOUT_MS) {
1272
+ const startedAt = Date.now();
1273
+ const controller = new AbortController();
1274
+ const timeout = setTimeout(() => controller.abort(), timeoutMs);
1275
+
1276
+ try {
1277
+ const res = await fetch(`${baseUrl}/api/v1/whoami`, {
1278
+ method: 'GET',
1279
+ headers: {
1280
+ Authorization: `Bearer ${apiKey}`,
1281
+ Accept: 'application/json',
1282
+ 'X-Posterly-Source': 'cli_doctor',
1283
+ },
1284
+ signal: controller.signal,
1285
+ });
1286
+ const text = await res.text();
1287
+ const data = text ? safeJson(text) : {};
1288
+ if (!res.ok) {
1289
+ return {
1290
+ ok: false,
1291
+ status: res.status,
1292
+ duration_ms: Date.now() - startedAt,
1293
+ error: formatResponseError(data, text, res.statusText),
1294
+ };
1295
+ }
1296
+ return {
1297
+ ok: true,
1298
+ status: res.status,
1299
+ duration_ms: Date.now() - startedAt,
1300
+ user: data.user,
1301
+ default_workspace: data.default_workspace,
1302
+ scopes: Array.isArray(data.api_key?.scopes) ? data.api_key.scopes : undefined,
1303
+ };
1304
+ } catch (error) {
1305
+ return {
1306
+ ok: false,
1307
+ duration_ms: Date.now() - startedAt,
1308
+ error: error?.name === 'AbortError' ? `timed out after ${timeoutMs}ms` : error?.message || String(error),
1309
+ };
1310
+ } finally {
1311
+ clearTimeout(timeout);
1312
+ }
1313
+ }
1314
+
1315
+ async function fetchLatestCliVersion() {
1316
+ const controller = new AbortController();
1317
+ const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
1318
+
1319
+ try {
1320
+ const res = await fetch(CLI_NPM_LATEST_URL, {
1321
+ headers: { Accept: 'application/json' },
1322
+ signal: controller.signal,
1323
+ });
1324
+ if (!res.ok) {
1325
+ return { error: `npm registry returned HTTP ${res.status}` };
1326
+ }
1327
+ const data = await res.json();
1328
+ return typeof data.version === 'string'
1329
+ ? { version: data.version }
1330
+ : { error: 'npm registry response did not include a version' };
1331
+ } catch (error) {
1332
+ const reason = error?.name === 'AbortError' ? 'timed out' : error?.message || String(error);
1333
+ return { error: `could not check npm latest: ${reason}` };
1334
+ } finally {
1335
+ clearTimeout(timeout);
1336
+ }
1337
+ }
1338
+
1339
+ function authStatusNextStep({ hasApiKey, baseUrlCheck }) {
1340
+ if (!baseUrlCheck.valid) {
1341
+ return 'Fix POSTERLY_URL or --url so it includes a scheme and host.';
1342
+ }
1343
+ if (!baseUrlCheck.secure) {
1344
+ return 'Use an https posterly URL, or http://localhost for local development.';
1345
+ }
1346
+ if (!hasApiKey) {
1347
+ return 'Run `posterly auth:login`, `posterly auth:key`, or set POSTERLY_API_KEY.';
1348
+ }
1349
+ return 'Run `posterly doctor --pretty` to validate the API key against /api/v1/whoami.';
1350
+ }
1351
+
1352
+ function doctorNextStep({ checks, latest, authProbe }) {
1353
+ const byName = Object.fromEntries(checks.map((check) => [check.name, check]));
1354
+ if (byName.node?.severity === 'error') {
1355
+ return 'Install Node 20 or newer, then run `posterly doctor --pretty` again.';
1356
+ }
1357
+ if (byName.base_url?.severity === 'error') {
1358
+ return 'Fix POSTERLY_URL or --url before sending an API key.';
1359
+ }
1360
+ if (byName.auth_config?.severity === 'error') {
1361
+ return 'Run `posterly auth:login`, `posterly auth:key`, or set POSTERLY_API_KEY.';
1362
+ }
1363
+ if (byName.api_auth?.severity === 'error') {
1364
+ return 'Check the API key and base URL, then run `posterly whoami --pretty`.';
1365
+ }
1366
+ if (latest.version && compareSemver((byName.npm_latest?.current_version || '0.0.0'), latest.version) < 0) {
1367
+ return 'Update with `npm i -g @posterly/cli@latest`, or keep using `npx @posterly/cli@latest`.';
1368
+ }
1369
+ if (authProbe?.ok) {
1370
+ return 'CLI is ready. Try `posterly accounts:list --pretty` or `posterly platforms:list --pretty`.';
1371
+ }
1372
+ return 'Run `posterly whoami --pretty` after configuring auth.';
1373
+ }
1374
+
1375
+ function formatResponseError(data, fallback, statusText) {
1376
+ if (data && typeof data === 'object') {
1377
+ return data.error || data.message || data.code || statusText || 'API request failed';
1378
+ }
1379
+ return fallback || statusText || 'API request failed';
1380
+ }
1381
+
1382
+ function compareSemver(a, b) {
1383
+ const left = semverParts(a);
1384
+ const right = semverParts(b);
1385
+ for (let i = 0; i < 3; i += 1) {
1386
+ if (left[i] !== right[i]) return left[i] > right[i] ? 1 : -1;
1387
+ }
1388
+ return 0;
1389
+ }
1390
+
1391
+ function semverParts(value) {
1392
+ const parts = String(value || '').split(/[.-]/).slice(0, 3).map((part) => Number.parseInt(part, 10));
1393
+ return [
1394
+ Number.isFinite(parts[0]) ? parts[0] : 0,
1395
+ Number.isFinite(parts[1]) ? parts[1] : 0,
1396
+ Number.isFinite(parts[2]) ? parts[2] : 0,
1397
+ ];
889
1398
  }
890
1399
 
891
1400
  function safeJson(text) {
@@ -279,7 +279,8 @@ export const PLATFORM_MANIFEST = Object.freeze({
279
279
  "aliases": [],
280
280
  "postTypes": [
281
281
  "video",
282
- "image"
282
+ "image",
283
+ "carousel"
283
284
  ],
284
285
  "analyticsSupported": false,
285
286
  "helpers": [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@posterly/cli",
3
- "version": "0.1.3",
3
+ "version": "0.1.4",
4
4
  "description": "Command line interface for the posterly API",
5
5
  "license": "MIT",
6
6
  "type": "module",