netriskscan-cli 1.2.0 → 1.4.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/dist/cli.js CHANGED
@@ -10,6 +10,7 @@ import { Command, CommanderError } from "commander";
10
10
  import ora from "ora";
11
11
 
12
12
  // src/client/errors.ts
13
+ var ANONYMOUS_DAILY_LIMIT_CODE = "anonymous_daily_limit_reached";
13
14
  var NetRiskScanError = class extends Error {
14
15
  constructor(message) {
15
16
  super(message);
@@ -27,6 +28,8 @@ var NetRiskScanApiError = class extends NetRiskScanError {
27
28
  code;
28
29
  requestId;
29
30
  retryAfter;
31
+ /** Present when the server reported anonymous-trial allowance alongside the error. */
32
+ anonymousUsage;
30
33
  constructor(message, options) {
31
34
  super(message);
32
35
  this.name = "NetRiskScanApiError";
@@ -34,6 +37,7 @@ var NetRiskScanApiError = class extends NetRiskScanError {
34
37
  this.code = options.code;
35
38
  this.requestId = options.requestId;
36
39
  this.retryAfter = options.retryAfter;
40
+ this.anonymousUsage = options.anonymousUsage;
37
41
  }
38
42
  };
39
43
  var NetRiskScanNetworkError = class extends NetRiskScanError {
@@ -80,6 +84,10 @@ function parseQuota(headers) {
80
84
  function isRetryableStatus(status) {
81
85
  return status === 429 || status === 503;
82
86
  }
87
+ function isRetryableFailure(status, code) {
88
+ if (code === ANONYMOUS_DAILY_LIMIT_CODE) return false;
89
+ return isRetryableStatus(status);
90
+ }
83
91
  var BASE_DELAY_MS = 1e3;
84
92
  var MAX_JITTER_MS = 250;
85
93
  function computeBackoffMs(attempt, retryAfterSeconds) {
@@ -108,18 +116,22 @@ async function safeJson(res) {
108
116
  return void 0;
109
117
  }
110
118
  }
119
+ function parseAnonymousLimitInfo(body) {
120
+ const error = body?.error;
121
+ if (!error) return void 0;
122
+ const { dailyLimit, used, remaining, resetAt, signupUrl } = error;
123
+ if (dailyLimit === void 0 && used === void 0 && remaining === void 0 && resetAt === void 0 && signupUrl === void 0) {
124
+ return void 0;
125
+ }
126
+ return { dailyLimit, used, remaining, resetAt, signupUrl };
127
+ }
111
128
  var NetRiskScanClient = class {
112
129
  apiKey;
113
130
  baseUrl;
114
131
  timeout;
115
132
  maxRetries;
116
- constructor(options) {
117
- if (!options.apiKey) {
118
- throw new NetRiskScanConfigError(
119
- "NetRiskScan API key is required.\n\nSet NETRISKSCAN_API_KEY or use --api-key."
120
- );
121
- }
122
- this.apiKey = options.apiKey;
133
+ constructor(options = {}) {
134
+ this.apiKey = options.apiKey || void 0;
123
135
  this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
124
136
  this.timeout = options.timeout ?? DEFAULT_TIMEOUT_MS;
125
137
  this.maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;
@@ -127,7 +139,14 @@ var NetRiskScanClient = class {
127
139
  async checkIp(ip, options = {}) {
128
140
  return this.request(`/v1/ip-risk/${encodeURIComponent(ip)}`, options);
129
141
  }
142
+ /**
143
+ * Account plan, billing period and quota. Unlike {@link checkIp} this is account data, so it
144
+ * has no anonymous equivalent and requires an API key.
145
+ */
130
146
  async getUsage(options = {}) {
147
+ if (!this.apiKey) {
148
+ throw new NetRiskScanConfigError("An API key is required to query account usage.");
149
+ }
131
150
  return this.request("/v1/usage", options);
132
151
  }
133
152
  async request(path, options) {
@@ -139,13 +158,16 @@ var NetRiskScanClient = class {
139
158
  const onExternalAbort = () => timeoutController.abort();
140
159
  options.signal?.addEventListener("abort", onExternalAbort);
141
160
  try {
161
+ const headers = {
162
+ Accept: "application/json",
163
+ "X-Request-Id": requestId
164
+ };
165
+ if (this.apiKey) {
166
+ headers.Authorization = `Bearer ${this.apiKey}`;
167
+ }
142
168
  const res = await fetch(`${this.baseUrl}${path}`, {
143
169
  method: "GET",
144
- headers: {
145
- Authorization: `Bearer ${this.apiKey}`,
146
- Accept: "application/json",
147
- "X-Request-Id": requestId
148
- },
170
+ headers,
149
171
  signal: timeoutController.signal
150
172
  });
151
173
  const rateLimit = parseRateLimit(res.headers);
@@ -158,7 +180,7 @@ var NetRiskScanClient = class {
158
180
  const body = await safeJson(res);
159
181
  const retryAfterHeader = res.headers.get("retry-after");
160
182
  const retryAfter = retryAfterHeader !== null ? Number(retryAfterHeader) : void 0;
161
- if (isRetryableStatus(res.status) && attempt < this.maxRetries) {
183
+ if (isRetryableFailure(res.status, body?.error?.code) && attempt < this.maxRetries) {
162
184
  attempt += 1;
163
185
  await sleep(computeBackoffMs(attempt, retryAfter));
164
186
  continue;
@@ -167,7 +189,8 @@ var NetRiskScanClient = class {
167
189
  status: res.status,
168
190
  code: body?.error?.code ?? "unknown_error",
169
191
  requestId: body?.error?.requestId ?? responseRequestId,
170
- retryAfter
192
+ retryAfter,
193
+ anonymousUsage: parseAnonymousLimitInfo(body)
171
194
  });
172
195
  } catch (err) {
173
196
  if (err instanceof NetRiskScanApiError) {
@@ -182,10 +205,13 @@ var NetRiskScanClient = class {
182
205
  requestId
183
206
  });
184
207
  }
185
- throw new NetRiskScanNetworkError(err instanceof Error ? err.message : "Network request failed", {
186
- cause: err,
187
- requestId
188
- });
208
+ throw new NetRiskScanNetworkError(
209
+ err instanceof Error ? err.message : "Network request failed",
210
+ {
211
+ cause: err,
212
+ requestId
213
+ }
214
+ );
189
215
  } finally {
190
216
  clearTimeout(timer);
191
217
  options.signal?.removeEventListener("abort", onExternalAbort);
@@ -195,11 +221,14 @@ var NetRiskScanClient = class {
195
221
  };
196
222
 
197
223
  // src/utils/env.ts
198
- function resolveApiKey(cliValue) {
199
- const apiKey = cliValue ?? process.env.NETRISKSCAN_API_KEY;
224
+ function resolveOptionalApiKey(cliValue) {
225
+ return cliValue || process.env.NETRISKSCAN_API_KEY || void 0;
226
+ }
227
+ function resolveRequiredApiKey(cliValue) {
228
+ const apiKey = resolveOptionalApiKey(cliValue);
200
229
  if (!apiKey) {
201
230
  throw new NetRiskScanConfigError(
202
- "NetRiskScan API key is required.\n\nSet NETRISKSCAN_API_KEY or use --api-key."
231
+ "An API key is required for the usage command.\n\nSet NETRISKSCAN_API_KEY or use --api-key."
203
232
  );
204
233
  }
205
234
  return apiKey;
@@ -231,8 +260,11 @@ function exitCodeForApiErrorCode(code) {
231
260
  case "api_key_disabled":
232
261
  case "scope_not_allowed":
233
262
  return ExitCode.AuthError;
263
+ // The anonymous daily trial is an allowance like any other, so it reuses code 5 rather than
264
+ // adding an eighth exit code that every script would have to learn.
234
265
  case "rate_limit_exceeded":
235
266
  case "quota_exceeded":
267
+ case "anonymous_daily_limit_reached":
236
268
  return ExitCode.RateLimitOrQuota;
237
269
  default:
238
270
  return ExitCode.ApiError;
@@ -248,6 +280,31 @@ function formatTriState(value) {
248
280
  if (value === false) return "No";
249
281
  return "Unknown";
250
282
  }
283
+ var PROXY_TYPE_LABELS = {
284
+ residential_proxy: "Residential Proxy",
285
+ isp_proxy: "ISP Proxy",
286
+ mobile_proxy: "Mobile Proxy",
287
+ datacenter_proxy: "Datacenter Proxy",
288
+ unknown_proxy: "Unknown Proxy"
289
+ };
290
+ var PROXY_TYPE_LABELS_COMPACT = {
291
+ residential_proxy: "Residential",
292
+ isp_proxy: "ISP",
293
+ mobile_proxy: "Mobile",
294
+ datacenter_proxy: "Datacenter",
295
+ unknown_proxy: "Unknown"
296
+ };
297
+ function formatProxyType(value) {
298
+ if (value === null || value === void 0 || value === "") return "-";
299
+ return PROXY_TYPE_LABELS[value] ?? value;
300
+ }
301
+ function formatProxyTypeCompact(value) {
302
+ if (value === null || value === void 0 || value === "") return "-";
303
+ return PROXY_TYPE_LABELS_COMPACT[value] ?? value;
304
+ }
305
+ function formatOrDash(value) {
306
+ return value === null || value === void 0 || value === "" ? "-" : value;
307
+ }
251
308
  function formatIndex(value) {
252
309
  return value === null ? "N/A" : String(value);
253
310
  }
@@ -260,12 +317,33 @@ function formatNumber(value) {
260
317
  function formatDate(iso) {
261
318
  return iso.slice(0, 10);
262
319
  }
263
-
264
- // src/output/human.ts
265
320
  var LABEL_WIDTH = 18;
266
321
  function row(label, value) {
267
322
  return `${label.padEnd(LABEL_WIDTH)}${value}`;
268
323
  }
324
+ function formatUtcTimestamp(iso) {
325
+ if (!iso) return void 0;
326
+ const date = new Date(iso);
327
+ if (Number.isNaN(date.getTime())) return void 0;
328
+ const pad = (n) => String(n).padStart(2, "0");
329
+ return `${date.getUTCFullYear()}-${pad(date.getUTCMonth() + 1)}-${pad(date.getUTCDate())} ${pad(date.getUTCHours())}:${pad(date.getUTCMinutes())} UTC`;
330
+ }
331
+
332
+ // src/output/human.ts
333
+ function anonymousUsageLines(usage) {
334
+ const lines = [];
335
+ if (typeof usage.remaining === "number") {
336
+ lines.push(row("Available", formatNumber(usage.remaining)));
337
+ }
338
+ if (typeof usage.dailyLimit === "number") {
339
+ lines.push(row("Daily Limit", formatNumber(usage.dailyLimit)));
340
+ }
341
+ const reset = formatUtcTimestamp(usage.resetAt);
342
+ if (reset !== void 0) {
343
+ lines.push(row("Reset", reset));
344
+ }
345
+ return lines;
346
+ }
269
347
  function bandColor(band) {
270
348
  switch (band) {
271
349
  case "excellent":
@@ -286,7 +364,9 @@ function renderCheckResult(ip, data) {
286
364
  lines.push("");
287
365
  lines.push(row("IP", ip));
288
366
  lines.push(row("Index", formatIndex(data.risk.index)));
289
- lines.push(row("Band", data.risk.band ? bandColor(data.risk.band)(data.risk.band) : chalk.gray("N/A")));
367
+ lines.push(
368
+ row("Band", data.risk.band ? bandColor(data.risk.band)(data.risk.band) : chalk.gray("N/A"))
369
+ );
290
370
  lines.push(row("Assessment", data.risk.assessmentGrade));
291
371
  lines.push("");
292
372
  if (data.risk.assessmentGrade === "insufficient" && data.risk.index === null) {
@@ -307,16 +387,29 @@ function renderCheckResult(ip, data) {
307
387
  lines.push("");
308
388
  lines.push(chalk.bold("Signals"));
309
389
  lines.push(row("Proxy", formatTriState(data.flags.proxy)));
390
+ lines.push(row("Proxy Type", formatProxyType(data.flags.proxyType)));
310
391
  lines.push(row("VPN", formatTriState(data.flags.vpn)));
311
392
  lines.push(row("Tor", formatTriState(data.flags.tor)));
312
393
  lines.push(row("Datacenter", formatTriState(data.flags.datacenter)));
313
394
  lines.push(row("Scanner", formatTriState(data.flags.scanner)));
314
395
  lines.push(row("Abuse", formatTriState(data.flags.abuse)));
315
396
  lines.push("");
397
+ lines.push(chalk.bold("Identity"));
398
+ lines.push(row("Search Crawler", formatTriState(data.flags.searchCrawler)));
399
+ lines.push(row("Crawler", formatOrDash(data.flags.searchCrawlerName)));
400
+ lines.push("");
401
+ if (data.usage?.mode === "anonymous") {
402
+ const usageLines = anonymousUsageLines(data.usage);
403
+ if (usageLines.length > 0) {
404
+ lines.push(chalk.bold("Usage"));
405
+ lines.push(...usageLines);
406
+ lines.push("");
407
+ }
408
+ }
316
409
  lines.push(row("Request ID", data.requestId));
317
410
  lines.push("");
318
411
  lines.push(chalk.bold("Explore"));
319
- lines.push(row("Web", "https://netriskscan.com"));
412
+ lines.push(row("Web", "https://www.netriskscan.com"));
320
413
  lines.push(row("GitHub", "https://github.com/TeamQQ/netriskscan-cli"));
321
414
  process.stdout.write(`${lines.join("\n")}
322
415
  `);
@@ -325,11 +418,19 @@ function renderVerboseMeta(meta) {
325
418
  const lines = [""];
326
419
  if (meta.rateLimit.remaining !== void 0 && meta.rateLimit.limit !== void 0) {
327
420
  lines.push(
328
- row("Rate limit", `${formatNumber(meta.rateLimit.remaining)} / ${formatNumber(meta.rateLimit.limit)} remaining`)
421
+ row(
422
+ "Rate limit",
423
+ `${formatNumber(meta.rateLimit.remaining)} / ${formatNumber(meta.rateLimit.limit)} remaining`
424
+ )
329
425
  );
330
426
  }
331
427
  if (meta.quota.remaining !== void 0 && meta.quota.limit !== void 0) {
332
- lines.push(row("Quota", `${formatNumber(meta.quota.remaining)} / ${formatNumber(meta.quota.limit)} remaining`));
428
+ lines.push(
429
+ row(
430
+ "Quota",
431
+ `${formatNumber(meta.quota.remaining)} / ${formatNumber(meta.quota.limit)} remaining`
432
+ )
433
+ );
333
434
  }
334
435
  lines.push(row("Request ID", meta.requestId));
335
436
  process.stdout.write(`${lines.join("\n")}
@@ -363,13 +464,42 @@ function printJson(data) {
363
464
 
364
465
  // src/output/errors.ts
365
466
  import chalk2 from "chalk";
467
+ var SIGNUP_URL = "https://www.netriskscan.com/developers";
366
468
  function printConfigError(err) {
367
469
  process.stderr.write(`Error: ${err.message}
368
470
  `);
369
471
  if (err.message.includes("API key")) {
370
- process.stderr.write("\nGet a free API key (no credit card required): https://netriskscan.com\n");
472
+ process.stderr.write(
473
+ "\nGet a free API key (no credit card required): https://www.netriskscan.com\n"
474
+ );
371
475
  }
372
476
  }
477
+ function printAnonymousLimitError(err) {
478
+ const usage = err.anonymousUsage;
479
+ const lines = [
480
+ "",
481
+ chalk2.bold("NetRiskScan"),
482
+ "",
483
+ chalk2.yellow("Anonymous daily trial limit reached."),
484
+ ""
485
+ ];
486
+ const usageLines = [
487
+ // The request that returned this error was refused, so nothing is left regardless of what the
488
+ // body reports; `remaining` is only trusted when the server actually sent it.
489
+ row("Available", formatNumber(typeof usage?.remaining === "number" ? usage.remaining : 0))
490
+ ];
491
+ if (typeof usage?.dailyLimit === "number") {
492
+ usageLines.push(row("Daily Limit", formatNumber(usage.dailyLimit)));
493
+ }
494
+ const reset = formatUtcTimestamp(usage?.resetAt);
495
+ if (reset !== void 0) {
496
+ usageLines.push(row("Reset", reset));
497
+ }
498
+ lines.push(chalk2.bold("Usage"), ...usageLines, "");
499
+ lines.push(chalk2.bold("Get more queries"), usage?.signupUrl || SIGNUP_URL, "");
500
+ process.stderr.write(`${lines.join("\n")}
501
+ `);
502
+ }
373
503
  var LABEL_WIDTH2 = 11;
374
504
  function printApiError(err, options = {}) {
375
505
  const lines = [
@@ -408,12 +538,22 @@ ${err.message}
408
538
  }
409
539
 
410
540
  // src/commands/check.ts
411
- var KNOWN_FLAGS = ["proxy", "vpn", "tor", "datacenter", "scanner", "abuse"];
541
+ var KNOWN_FLAGS = [
542
+ "proxy",
543
+ "vpn",
544
+ "tor",
545
+ "datacenter",
546
+ "scanner",
547
+ "abuse"
548
+ ];
412
549
  function collect(value, previous) {
413
550
  return [...previous, value];
414
551
  }
415
552
  function registerCheckCommand(program2) {
416
- program2.command("check <ip>").description("Check IP risk and network intelligence").option("--api-key <key>", "NetRiskScan API key (overrides NETRISKSCAN_API_KEY)").option("--base-url <url>", "Override the API base URL (advanced)").option("--json", "Output machine-readable JSON").option("--verbose", "Show rate limit, quota and request id").option("--debug", "Show debug information on failure").option("--timeout <ms>", "Request timeout in milliseconds", "10000").option("--max-retries <n>", "Maximum automatic retries for 429/503", "3").option("--fail-below <index>", "Exit non-zero if risk.index is below this threshold (CI use)").option(
553
+ program2.command("check <ip>").description("Check IP risk and network intelligence").option(
554
+ "--api-key <key>",
555
+ "NetRiskScan API key (optional; uses the anonymous trial when omitted)"
556
+ ).option("--base-url <url>", "Override the API base URL (advanced)").option("--json", "Output machine-readable JSON").option("--verbose", "Show rate limit, quota and request id").option("--debug", "Show debug information on failure").option("--timeout <ms>", "Request timeout in milliseconds", "10000").option("--max-retries <n>", "Maximum automatic retries for 429/503", "3").option("--fail-below <index>", "Exit non-zero if risk.index is below this threshold (CI use)").option(
417
557
  "--fail-on <flag>",
418
558
  "Exit non-zero if the given flag is true (repeatable): proxy, vpn, tor, datacenter, scanner, abuse",
419
559
  collect,
@@ -426,6 +566,10 @@ Examples:
426
566
  $ netriskscan check 1.1.1.1 --json
427
567
  $ netriskscan check 1.2.3.4 --fail-below 60
428
568
  $ netriskscan check 1.2.3.4 --fail-on tor --fail-on proxy
569
+
570
+ Notes:
571
+ An API key is optional. Without one, requests use the anonymous daily trial,
572
+ metered by public IP; the response reports how many are left.
429
573
  `
430
574
  ).action(async (ip, options) => {
431
575
  await runCheck(ip, options);
@@ -435,8 +579,10 @@ async function runCheck(ip, options) {
435
579
  const useJson = Boolean(options.json);
436
580
  for (const flag of options.failOn) {
437
581
  if (!KNOWN_FLAGS.includes(flag)) {
438
- process.stderr.write(`Error: unknown --fail-on flag "${flag}". Expected one of: ${KNOWN_FLAGS.join(", ")}
439
- `);
582
+ process.stderr.write(
583
+ `Error: unknown --fail-on flag "${flag}". Expected one of: ${KNOWN_FLAGS.join(", ")}
584
+ `
585
+ );
440
586
  process.exitCode = ExitCode.InvalidArgument;
441
587
  return;
442
588
  }
@@ -447,24 +593,17 @@ async function runCheck(ip, options) {
447
593
  process.exitCode = ExitCode.InvalidArgument;
448
594
  return;
449
595
  }
450
- let apiKey;
451
- try {
452
- apiKey = resolveApiKey(options.apiKey);
453
- } catch (err) {
454
- if (err instanceof NetRiskScanConfigError) {
455
- printConfigError(err);
456
- process.exitCode = ExitCode.AuthError;
457
- return;
458
- }
459
- throw err;
460
- }
461
596
  const client = new NetRiskScanClient({
462
- apiKey,
597
+ apiKey: resolveOptionalApiKey(options.apiKey),
463
598
  baseUrl: resolveBaseUrl(options.baseUrl),
464
599
  timeout: Number(options.timeout),
465
600
  maxRetries: Number(options.maxRetries)
466
601
  });
467
- const spinner = useJson ? void 0 : ora({ text: `Checking ${ip}...`, stream: process.stderr, isEnabled: process.stderr.isTTY }).start();
602
+ const spinner = useJson ? void 0 : ora({
603
+ text: `Checking ${ip}...`,
604
+ stream: process.stderr,
605
+ isEnabled: process.stderr.isTTY
606
+ }).start();
468
607
  try {
469
608
  const { data, meta } = await client.checkIp(ip);
470
609
  spinner?.stop();
@@ -502,7 +641,11 @@ function evaluateCiPolicy(data, options) {
502
641
  }
503
642
  function handleCheckError(err, options) {
504
643
  if (err instanceof NetRiskScanApiError) {
505
- printApiError(err, { debug: options.debug });
644
+ if (err.code === ANONYMOUS_DAILY_LIMIT_CODE) {
645
+ printAnonymousLimitError(err);
646
+ } else {
647
+ printApiError(err, { debug: options.debug });
648
+ }
506
649
  process.exitCode = exitCodeForApiErrorCode(err.code);
507
650
  return;
508
651
  }
@@ -524,7 +667,15 @@ function handleCheckError(err, options) {
524
667
  // src/commands/usage.ts
525
668
  import ora2 from "ora";
526
669
  function registerUsageCommand(program2) {
527
- program2.command("usage").description("Show API usage and quota for the current billing period").option("--api-key <key>", "NetRiskScan API key (overrides NETRISKSCAN_API_KEY)").option("--base-url <url>", "Override the API base URL (advanced)").option("--json", "Output machine-readable JSON").option("--verbose", "Show rate limit and request id").option("--debug", "Show debug information on failure").option("--timeout <ms>", "Request timeout in milliseconds", "10000").option("--max-retries <n>", "Maximum automatic retries for 429/503", "3").action(async (options) => {
670
+ program2.command("usage").description("Show API usage and quota for the current billing period (requires an API key)").option("--api-key <key>", "NetRiskScan API key (required for this command)").option("--base-url <url>", "Override the API base URL (advanced)").option("--json", "Output machine-readable JSON").option("--verbose", "Show rate limit and request id").option("--debug", "Show debug information on failure").option("--timeout <ms>", "Request timeout in milliseconds", "10000").option("--max-retries <n>", "Maximum automatic retries for 429/503", "3").addHelpText(
671
+ "after",
672
+ `
673
+ Notes:
674
+ Requires a Developer API key. This reports Developer Account plan, billing
675
+ period and quota, which has no anonymous equivalent - unlike check and batch,
676
+ which work without a key.
677
+ `
678
+ ).action(async (options) => {
528
679
  await runUsage(options);
529
680
  });
530
681
  }
@@ -532,7 +683,7 @@ async function runUsage(options) {
532
683
  const useJson = Boolean(options.json);
533
684
  let apiKey;
534
685
  try {
535
- apiKey = resolveApiKey(options.apiKey);
686
+ apiKey = resolveRequiredApiKey(options.apiKey);
536
687
  } catch (err) {
537
688
  if (err instanceof NetRiskScanConfigError) {
538
689
  printConfigError(err);
@@ -547,7 +698,11 @@ async function runUsage(options) {
547
698
  timeout: Number(options.timeout),
548
699
  maxRetries: Number(options.maxRetries)
549
700
  });
550
- const spinner = useJson ? void 0 : ora2({ text: "Fetching usage...", stream: process.stderr, isEnabled: process.stderr.isTTY }).start();
701
+ const spinner = useJson ? void 0 : ora2({
702
+ text: "Fetching usage...",
703
+ stream: process.stderr,
704
+ isEnabled: process.stderr.isTTY
705
+ }).start();
551
706
  try {
552
707
  const { data, meta } = await client.getUsage();
553
708
  spinner?.stop();
@@ -603,9 +758,33 @@ function printJsonLine(data) {
603
758
  // src/output/table.ts
604
759
  import Table from "cli-table3";
605
760
  import chalk3 from "chalk";
761
+ function anonymousSummaryLines(results) {
762
+ const remainings = [];
763
+ const dailyLimits = [];
764
+ let exhausted = false;
765
+ for (const item of results) {
766
+ if (item.ok) {
767
+ const usage = item.result.usage;
768
+ if (usage?.mode !== "anonymous") continue;
769
+ if (typeof usage.remaining === "number") remainings.push(usage.remaining);
770
+ if (typeof usage.dailyLimit === "number") dailyLimits.push(usage.dailyLimit);
771
+ } else if (item.error.code === ANONYMOUS_DAILY_LIMIT_CODE) {
772
+ exhausted = true;
773
+ const limit = item.error.anonymousUsage?.dailyLimit;
774
+ if (typeof limit === "number") dailyLimits.push(limit);
775
+ }
776
+ }
777
+ if (!exhausted && remainings.length === 0) return [];
778
+ const available = exhausted ? 0 : Math.min(...remainings);
779
+ const lines = ["", chalk3.bold("Anonymous trial"), row("Available", formatNumber(available))];
780
+ if (dailyLimits.length > 0) {
781
+ lines.push(row("Daily Limit", formatNumber(Math.max(...dailyLimits))));
782
+ }
783
+ return lines;
784
+ }
606
785
  function renderBatchTable(results) {
607
786
  const table = new Table({
608
- head: ["IP", "Index", "Band", "Proxy", "VPN", "Tor", "Status"],
787
+ head: ["IP", "Index", "Band", "Proxy", "Proxy Type", "VPN", "Tor", "Crawler", "Status"],
609
788
  style: { head: [], border: [] }
610
789
  });
611
790
  for (const item of results) {
@@ -616,12 +795,24 @@ function renderBatchTable(results) {
616
795
  formatIndex(result.risk.index),
617
796
  result.risk.band ?? "N/A",
618
797
  formatTriState(result.flags.proxy),
798
+ formatProxyTypeCompact(result.flags.proxyType),
619
799
  formatTriState(result.flags.vpn),
620
800
  formatTriState(result.flags.tor),
801
+ formatOrDash(result.flags.searchCrawlerName),
621
802
  chalk3.green("ok")
622
803
  ]);
623
804
  } else {
624
- table.push([item.ip, "-", "-", "-", "-", "-", chalk3.red(`error: ${item.error.code}`)]);
805
+ table.push([
806
+ item.ip,
807
+ "-",
808
+ "-",
809
+ "-",
810
+ "-",
811
+ "-",
812
+ "-",
813
+ "-",
814
+ chalk3.red(`error: ${item.error.code}`)
815
+ ]);
625
816
  }
626
817
  }
627
818
  process.stdout.write(`${table.toString()}
@@ -631,13 +822,21 @@ function renderBatchTable(results) {
631
822
  process.stdout.write(`
632
823
  ${okCount} succeeded, ${failCount} failed
633
824
  `);
825
+ const anonymous = anonymousSummaryLines(results);
826
+ if (anonymous.length > 0) {
827
+ process.stdout.write(`${anonymous.join("\n")}
828
+ `);
829
+ }
634
830
  }
635
831
 
636
832
  // src/commands/batch.ts
637
833
  var MAX_CONCURRENCY = 20;
638
834
  var DEFAULT_CONCURRENCY = 5;
639
835
  function registerBatchCommand(program2) {
640
- program2.command("batch <file>").description("Check multiple IP addresses (client-side batch over GET /v1/ip-risk/{ip})").option("--api-key <key>", "NetRiskScan API key (overrides NETRISKSCAN_API_KEY)").option("--base-url <url>", "Override the API base URL (advanced)").option(
836
+ program2.command("batch <file>").description("Check multiple IP addresses (client-side batch over GET /v1/ip-risk/{ip})").option(
837
+ "--api-key <key>",
838
+ "NetRiskScan API key (optional; uses the anonymous trial when omitted)"
839
+ ).option("--base-url <url>", "Override the API base URL (advanced)").option(
641
840
  "--concurrency <n>",
642
841
  `Number of concurrent requests (default: ${DEFAULT_CONCURRENCY}, max: ${MAX_CONCURRENCY})`,
643
842
  String(DEFAULT_CONCURRENCY)
@@ -650,6 +849,10 @@ Notes:
650
849
  offer a server-side batch endpoint. Make sure the selected concurrency
651
850
  complies with the limits shown in your NetRiskScan Developer Dashboard.
652
851
 
852
+ An API key is optional. Without an API key, requests use the anonymous daily
853
+ trial, metered by public IP. How many remain is decided by the server, not by
854
+ this CLI, and is reported in the summary after the table.
855
+
653
856
  Input format:
654
857
  One IP per line. Blank lines and lines starting with # are ignored.
655
858
 
@@ -688,7 +891,12 @@ Check your NetRiskScan Developer Dashboard for your plan's concurrency limit.
688
891
  }
689
892
  function toBatchError(err) {
690
893
  if (err instanceof NetRiskScanApiError) {
691
- return { code: err.code, message: err.message, requestId: err.requestId };
894
+ return {
895
+ code: err.code,
896
+ message: err.message,
897
+ requestId: err.requestId,
898
+ anonymousUsage: err.anonymousUsage
899
+ };
692
900
  }
693
901
  if (err instanceof NetRiskScanNetworkError) {
694
902
  return { code: "network_error", message: err.message, requestId: err.requestId };
@@ -696,17 +904,6 @@ function toBatchError(err) {
696
904
  return { code: "unknown_error", message: err instanceof Error ? err.message : String(err) };
697
905
  }
698
906
  async function runBatch(file, options) {
699
- let apiKey;
700
- try {
701
- apiKey = resolveApiKey(options.apiKey);
702
- } catch (err) {
703
- if (err instanceof NetRiskScanConfigError) {
704
- printConfigError(err);
705
- process.exitCode = ExitCode.AuthError;
706
- return;
707
- }
708
- throw err;
709
- }
710
907
  const ips = await readIps(file);
711
908
  if (ips.length === 0) {
712
909
  process.stderr.write("Error: no IP addresses found in input.\n");
@@ -714,7 +911,7 @@ async function runBatch(file, options) {
714
911
  return;
715
912
  }
716
913
  const client = new NetRiskScanClient({
717
- apiKey,
914
+ apiKey: resolveOptionalApiKey(options.apiKey),
718
915
  baseUrl: resolveBaseUrl(options.baseUrl),
719
916
  timeout: Number(options.timeout),
720
917
  maxRetries: Number(options.maxRetries)
@@ -757,17 +954,23 @@ function computeBatchExitCode(results) {
757
954
  var __dirname = dirname(fileURLToPath(import.meta.url));
758
955
  var pkg = JSON.parse(readFileSync(join(__dirname, "..", "package.json"), "utf8"));
759
956
  var program = new Command();
760
- program.name("netriskscan").description("Query IP risk, network intelligence and reputation data from the NetRiskScan Developer API.").version(pkg.version, "-V, --version", "Show the CLI version").addHelpText(
957
+ program.name("netriskscan").description(
958
+ "Query IP risk, network intelligence and reputation data from the NetRiskScan Developer API."
959
+ ).version(pkg.version, "-V, --version", "Show the CLI version").addHelpText(
761
960
  "after",
762
961
  `
763
962
  Examples:
764
- $ netriskscan check 1.1.1.1
963
+ $ netriskscan check 1.1.1.1 # no account or API key needed
765
964
  $ netriskscan check 1.1.1.1 --json
766
- $ netriskscan usage
965
+ $ netriskscan usage # needs an API key
767
966
  $ netriskscan batch ips.txt --jsonl
768
967
 
968
+ check and batch work with no setup at all: without an API key they use the
969
+ anonymous daily trial, metered by public IP. The server reports how many
970
+ requests are left; the CLI never estimates it.
971
+
769
972
  Environment variables:
770
- NETRISKSCAN_API_KEY API key used when --api-key is not provided
973
+ NETRISKSCAN_API_KEY Optional for check/batch; required for account usage.
771
974
 
772
975
  NetRiskScan provides diagnostic network intelligence. Results should not be
773
976
  treated as proof of malicious activity or used as the sole basis for legal,