netriskscan-cli 1.0.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 ADDED
@@ -0,0 +1,785 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli.ts
4
+ import { readFileSync } from "fs";
5
+ import { dirname, join } from "path";
6
+ import { fileURLToPath } from "url";
7
+ import { Command, CommanderError } from "commander";
8
+
9
+ // src/commands/check.ts
10
+ import ora from "ora";
11
+
12
+ // src/client/errors.ts
13
+ var NetRiskScanError = class extends Error {
14
+ constructor(message) {
15
+ super(message);
16
+ this.name = "NetRiskScanError";
17
+ }
18
+ };
19
+ var NetRiskScanConfigError = class extends NetRiskScanError {
20
+ constructor(message) {
21
+ super(message);
22
+ this.name = "NetRiskScanConfigError";
23
+ }
24
+ };
25
+ var NetRiskScanApiError = class extends NetRiskScanError {
26
+ status;
27
+ code;
28
+ requestId;
29
+ retryAfter;
30
+ constructor(message, options) {
31
+ super(message);
32
+ this.name = "NetRiskScanApiError";
33
+ this.status = options.status;
34
+ this.code = options.code;
35
+ this.requestId = options.requestId;
36
+ this.retryAfter = options.retryAfter;
37
+ }
38
+ };
39
+ var NetRiskScanNetworkError = class extends NetRiskScanError {
40
+ cause;
41
+ requestId;
42
+ constructor(message, options = {}) {
43
+ super(message);
44
+ this.name = "NetRiskScanNetworkError";
45
+ this.cause = options.cause;
46
+ this.requestId = options.requestId;
47
+ }
48
+ };
49
+
50
+ // src/client/headers.ts
51
+ import { randomBytes } from "crypto";
52
+ var REQUEST_ID_PATTERN = /^req_[A-Za-z0-9_-]{8,56}$/;
53
+ function isValidRequestId(id) {
54
+ return REQUEST_ID_PATTERN.test(id);
55
+ }
56
+ function generateRequestId() {
57
+ return `req_${randomBytes(12).toString("hex")}`;
58
+ }
59
+ function parseIntHeader(value) {
60
+ if (value === null) return void 0;
61
+ const n = Number(value);
62
+ return Number.isFinite(n) ? n : void 0;
63
+ }
64
+ function parseRateLimit(headers) {
65
+ return {
66
+ limit: parseIntHeader(headers.get("x-ratelimit-limit")),
67
+ remaining: parseIntHeader(headers.get("x-ratelimit-remaining")),
68
+ reset: parseIntHeader(headers.get("x-ratelimit-reset"))
69
+ };
70
+ }
71
+ function parseQuota(headers) {
72
+ return {
73
+ limit: parseIntHeader(headers.get("x-quota-limit")),
74
+ used: parseIntHeader(headers.get("x-quota-used")),
75
+ remaining: parseIntHeader(headers.get("x-quota-remaining"))
76
+ };
77
+ }
78
+
79
+ // src/client/retry.ts
80
+ function isRetryableStatus(status) {
81
+ return status === 429 || status === 503;
82
+ }
83
+ var BASE_DELAY_MS = 1e3;
84
+ var MAX_JITTER_MS = 250;
85
+ function computeBackoffMs(attempt, retryAfterSeconds) {
86
+ if (typeof retryAfterSeconds === "number" && Number.isFinite(retryAfterSeconds) && retryAfterSeconds >= 0) {
87
+ return retryAfterSeconds * 1e3;
88
+ }
89
+ const base = BASE_DELAY_MS * 2 ** Math.max(0, attempt - 1);
90
+ const jitter = Math.random() * MAX_JITTER_MS;
91
+ return base + jitter;
92
+ }
93
+ function sleep(ms) {
94
+ return new Promise((resolve) => setTimeout(resolve, ms));
95
+ }
96
+
97
+ // src/client/NetRiskScanClient.ts
98
+ var DEFAULT_BASE_URL = "https://api.netriskscan.com";
99
+ var DEFAULT_TIMEOUT_MS = 1e4;
100
+ var DEFAULT_MAX_RETRIES = 3;
101
+ function isAbortError(err) {
102
+ return err instanceof Error && err.name === "AbortError";
103
+ }
104
+ async function safeJson(res) {
105
+ try {
106
+ return await res.json();
107
+ } catch {
108
+ return void 0;
109
+ }
110
+ }
111
+ var NetRiskScanClient = class {
112
+ apiKey;
113
+ baseUrl;
114
+ timeout;
115
+ 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;
123
+ this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
124
+ this.timeout = options.timeout ?? DEFAULT_TIMEOUT_MS;
125
+ this.maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;
126
+ }
127
+ async checkIp(ip, options = {}) {
128
+ return this.request(`/v1/ip-risk/${encodeURIComponent(ip)}`, options);
129
+ }
130
+ async getUsage(options = {}) {
131
+ return this.request("/v1/usage", options);
132
+ }
133
+ async request(path, options) {
134
+ const requestId = options.requestId && isValidRequestId(options.requestId) ? options.requestId : generateRequestId();
135
+ let attempt = 0;
136
+ while (true) {
137
+ const timeoutController = new AbortController();
138
+ const timer = setTimeout(() => timeoutController.abort(), this.timeout);
139
+ const onExternalAbort = () => timeoutController.abort();
140
+ options.signal?.addEventListener("abort", onExternalAbort);
141
+ try {
142
+ const res = await fetch(`${this.baseUrl}${path}`, {
143
+ method: "GET",
144
+ headers: {
145
+ Authorization: `Bearer ${this.apiKey}`,
146
+ Accept: "application/json",
147
+ "X-Request-Id": requestId
148
+ },
149
+ signal: timeoutController.signal
150
+ });
151
+ const rateLimit = parseRateLimit(res.headers);
152
+ const quota = parseQuota(res.headers);
153
+ const responseRequestId = res.headers.get("x-request-id") ?? requestId;
154
+ if (res.ok) {
155
+ const data = await res.json();
156
+ return { data, meta: { requestId: responseRequestId, rateLimit, quota } };
157
+ }
158
+ const body = await safeJson(res);
159
+ const retryAfterHeader = res.headers.get("retry-after");
160
+ const retryAfter = retryAfterHeader !== null ? Number(retryAfterHeader) : void 0;
161
+ if (isRetryableStatus(res.status) && attempt < this.maxRetries) {
162
+ attempt += 1;
163
+ await sleep(computeBackoffMs(attempt, retryAfter));
164
+ continue;
165
+ }
166
+ throw new NetRiskScanApiError(body?.error?.message ?? res.statusText, {
167
+ status: res.status,
168
+ code: body?.error?.code ?? "unknown_error",
169
+ requestId: body?.error?.requestId ?? responseRequestId,
170
+ retryAfter
171
+ });
172
+ } catch (err) {
173
+ if (err instanceof NetRiskScanApiError) {
174
+ throw err;
175
+ }
176
+ if (isAbortError(err)) {
177
+ if (options.signal?.aborted) {
178
+ throw err;
179
+ }
180
+ throw new NetRiskScanNetworkError(`Request timed out after ${this.timeout}ms`, {
181
+ cause: err,
182
+ requestId
183
+ });
184
+ }
185
+ throw new NetRiskScanNetworkError(err instanceof Error ? err.message : "Network request failed", {
186
+ cause: err,
187
+ requestId
188
+ });
189
+ } finally {
190
+ clearTimeout(timer);
191
+ options.signal?.removeEventListener("abort", onExternalAbort);
192
+ }
193
+ }
194
+ }
195
+ };
196
+
197
+ // src/utils/env.ts
198
+ function resolveApiKey(cliValue) {
199
+ const apiKey = cliValue ?? process.env.NETRISKSCAN_API_KEY;
200
+ if (!apiKey) {
201
+ throw new NetRiskScanConfigError(
202
+ "NetRiskScan API key is required.\n\nSet NETRISKSCAN_API_KEY or use --api-key."
203
+ );
204
+ }
205
+ return apiKey;
206
+ }
207
+ function resolveBaseUrl(cliValue) {
208
+ return cliValue ?? process.env.NETRISKSCAN_BASE_URL;
209
+ }
210
+
211
+ // src/utils/ip.ts
212
+ import { isIP } from "net";
213
+ function isValidIp(value) {
214
+ return isIP(value) !== 0;
215
+ }
216
+
217
+ // src/utils/exitCode.ts
218
+ var ExitCode = {
219
+ Success: 0,
220
+ GeneralError: 1,
221
+ InvalidArgument: 2,
222
+ AuthError: 3,
223
+ ApiError: 4,
224
+ RateLimitOrQuota: 5,
225
+ CiPolicyFailed: 6,
226
+ AssessmentUnavailable: 7
227
+ };
228
+ function exitCodeForApiErrorCode(code) {
229
+ switch (code) {
230
+ case "invalid_api_key":
231
+ case "api_key_disabled":
232
+ case "scope_not_allowed":
233
+ return ExitCode.AuthError;
234
+ case "rate_limit_exceeded":
235
+ case "quota_exceeded":
236
+ return ExitCode.RateLimitOrQuota;
237
+ default:
238
+ return ExitCode.ApiError;
239
+ }
240
+ }
241
+
242
+ // src/output/human.ts
243
+ import chalk from "chalk";
244
+
245
+ // src/output/format.ts
246
+ function formatTriState(value) {
247
+ if (value === true) return "Yes";
248
+ if (value === false) return "No";
249
+ return "Unknown";
250
+ }
251
+ function formatIndex(value) {
252
+ return value === null ? "N/A" : String(value);
253
+ }
254
+ function formatNullable(value) {
255
+ return value === null || value === void 0 || value === "" ? "N/A" : value;
256
+ }
257
+ function formatNumber(value) {
258
+ return value.toLocaleString("en-US");
259
+ }
260
+ function formatDate(iso) {
261
+ return iso.slice(0, 10);
262
+ }
263
+
264
+ // src/output/human.ts
265
+ var LABEL_WIDTH = 18;
266
+ function row(label, value) {
267
+ return `${label.padEnd(LABEL_WIDTH)}${value}`;
268
+ }
269
+ function bandColor(band) {
270
+ switch (band) {
271
+ case "excellent":
272
+ case "good":
273
+ return chalk.green;
274
+ case "fair":
275
+ return chalk.yellow;
276
+ case "poor":
277
+ case "high_risk":
278
+ return chalk.red;
279
+ default:
280
+ return chalk.gray;
281
+ }
282
+ }
283
+ function renderCheckResult(ip, data) {
284
+ const lines = [];
285
+ lines.push(chalk.bold("NetRiskScan"));
286
+ lines.push("");
287
+ lines.push(row("IP", ip));
288
+ 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")));
290
+ lines.push(row("Assessment", data.risk.assessmentGrade));
291
+ lines.push("");
292
+ if (data.risk.assessmentGrade === "insufficient" && data.risk.index === null) {
293
+ lines.push(chalk.yellow("This address could not be reliably assessed."));
294
+ lines.push("");
295
+ }
296
+ lines.push(chalk.bold("Network"));
297
+ lines.push(row("Type", formatNullable(data.network.type)));
298
+ lines.push(row("Connection", formatNullable(data.network.connectionType)));
299
+ lines.push(row("ASN", formatNullable(data.network.asn)));
300
+ lines.push(row("Organization", formatNullable(data.network.organization)));
301
+ lines.push("");
302
+ lines.push(chalk.bold("Signals"));
303
+ lines.push(row("Proxy", formatTriState(data.flags.proxy)));
304
+ lines.push(row("VPN", formatTriState(data.flags.vpn)));
305
+ lines.push(row("Tor", formatTriState(data.flags.tor)));
306
+ lines.push(row("Datacenter", formatTriState(data.flags.datacenter)));
307
+ lines.push(row("Scanner", formatTriState(data.flags.scanner)));
308
+ lines.push(row("Abuse", formatTriState(data.flags.abuse)));
309
+ lines.push("");
310
+ lines.push(row("Request ID", data.requestId));
311
+ process.stdout.write(`${lines.join("\n")}
312
+ `);
313
+ }
314
+ function renderVerboseMeta(meta) {
315
+ const lines = [""];
316
+ if (meta.rateLimit.remaining !== void 0 && meta.rateLimit.limit !== void 0) {
317
+ lines.push(
318
+ row("Rate limit", `${formatNumber(meta.rateLimit.remaining)} / ${formatNumber(meta.rateLimit.limit)} remaining`)
319
+ );
320
+ }
321
+ if (meta.quota.remaining !== void 0 && meta.quota.limit !== void 0) {
322
+ lines.push(row("Quota", `${formatNumber(meta.quota.remaining)} / ${formatNumber(meta.quota.limit)} remaining`));
323
+ }
324
+ lines.push(row("Request ID", meta.requestId));
325
+ process.stdout.write(`${lines.join("\n")}
326
+ `);
327
+ }
328
+ function renderUsageResult(data) {
329
+ const lines = [];
330
+ lines.push(chalk.bold("NetRiskScan Usage"));
331
+ lines.push("");
332
+ lines.push(row("Plan", data.plan));
333
+ lines.push("");
334
+ lines.push(chalk.bold("Usage"));
335
+ lines.push(row("Used", formatNumber(data.units.used)));
336
+ lines.push(row("Remaining", formatNumber(data.units.remaining)));
337
+ lines.push(row("Limit", formatNumber(data.units.limit)));
338
+ lines.push("");
339
+ lines.push(chalk.bold("Rate limit"));
340
+ lines.push(row("Requests / minute", formatNumber(data.rateLimit.requestsPerMinute)));
341
+ lines.push("");
342
+ lines.push(chalk.bold("Billing period"));
343
+ lines.push(`${formatDate(data.period.start)} \u2192 ${formatDate(data.period.end)}`);
344
+ process.stdout.write(`${lines.join("\n")}
345
+ `);
346
+ }
347
+
348
+ // src/output/json.ts
349
+ function printJson(data) {
350
+ process.stdout.write(`${JSON.stringify(data, null, 2)}
351
+ `);
352
+ }
353
+
354
+ // src/output/errors.ts
355
+ import chalk2 from "chalk";
356
+ function printConfigError(err) {
357
+ process.stderr.write(`Error: ${err.message}
358
+ `);
359
+ }
360
+ var LABEL_WIDTH2 = 11;
361
+ function printApiError(err, options = {}) {
362
+ const lines = [
363
+ "",
364
+ chalk2.red("NetRiskScan API error"),
365
+ "",
366
+ `${"Code".padEnd(LABEL_WIDTH2)}${err.code}`,
367
+ `${"Status".padEnd(LABEL_WIDTH2)}${err.status}`,
368
+ `${"Message".padEnd(LABEL_WIDTH2)}${err.message}`
369
+ ];
370
+ if (err.requestId) {
371
+ lines.push(`${"Request ID".padEnd(LABEL_WIDTH2)}${err.requestId}`);
372
+ }
373
+ if (err.retryAfter !== void 0) {
374
+ lines.push(`${"Retry after".padEnd(LABEL_WIDTH2)}${err.retryAfter}s`);
375
+ }
376
+ lines.push("");
377
+ process.stderr.write(`${lines.join("\n")}
378
+ `);
379
+ if (options.debug && err.stack) {
380
+ process.stderr.write(`${err.stack}
381
+ `);
382
+ }
383
+ }
384
+ function printNetworkError(err, options = {}) {
385
+ process.stderr.write(`
386
+ ${chalk2.red("NetRiskScan request failed")}
387
+
388
+ ${err.message}
389
+
390
+ `);
391
+ if (options.debug && err.stack) {
392
+ process.stderr.write(`${err.stack}
393
+ `);
394
+ }
395
+ }
396
+
397
+ // src/commands/check.ts
398
+ var KNOWN_FLAGS = ["proxy", "vpn", "tor", "datacenter", "scanner", "abuse"];
399
+ function collect(value, previous) {
400
+ return [...previous, value];
401
+ }
402
+ function registerCheckCommand(program2) {
403
+ 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(
404
+ "--fail-on <flag>",
405
+ "Exit non-zero if the given flag is true (repeatable): proxy, vpn, tor, datacenter, scanner, abuse",
406
+ collect,
407
+ []
408
+ ).addHelpText(
409
+ "after",
410
+ `
411
+ Examples:
412
+ $ netriskscan check 1.1.1.1
413
+ $ netriskscan check 1.1.1.1 --json
414
+ $ netriskscan check 1.2.3.4 --fail-below 60
415
+ $ netriskscan check 1.2.3.4 --fail-on tor --fail-on proxy
416
+ `
417
+ ).action(async (ip, options) => {
418
+ await runCheck(ip, options);
419
+ });
420
+ }
421
+ async function runCheck(ip, options) {
422
+ const useJson = Boolean(options.json);
423
+ for (const flag of options.failOn) {
424
+ if (!KNOWN_FLAGS.includes(flag)) {
425
+ process.stderr.write(`Error: unknown --fail-on flag "${flag}". Expected one of: ${KNOWN_FLAGS.join(", ")}
426
+ `);
427
+ process.exitCode = ExitCode.InvalidArgument;
428
+ return;
429
+ }
430
+ }
431
+ if (!isValidIp(ip)) {
432
+ process.stderr.write(`Error: "${ip}" is not a valid IPv4 or IPv6 address.
433
+ `);
434
+ process.exitCode = ExitCode.InvalidArgument;
435
+ return;
436
+ }
437
+ let apiKey;
438
+ try {
439
+ apiKey = resolveApiKey(options.apiKey);
440
+ } catch (err) {
441
+ if (err instanceof NetRiskScanConfigError) {
442
+ printConfigError(err);
443
+ process.exitCode = ExitCode.AuthError;
444
+ return;
445
+ }
446
+ throw err;
447
+ }
448
+ const client = new NetRiskScanClient({
449
+ apiKey,
450
+ baseUrl: resolveBaseUrl(options.baseUrl),
451
+ timeout: Number(options.timeout),
452
+ maxRetries: Number(options.maxRetries)
453
+ });
454
+ const spinner = useJson ? void 0 : ora({ text: `Checking ${ip}...`, stream: process.stderr, isEnabled: process.stderr.isTTY }).start();
455
+ try {
456
+ const { data, meta } = await client.checkIp(ip);
457
+ spinner?.stop();
458
+ if (useJson) {
459
+ printJson(data);
460
+ } else {
461
+ renderCheckResult(ip, data);
462
+ if (options.verbose) {
463
+ renderVerboseMeta(meta);
464
+ }
465
+ }
466
+ process.exitCode = evaluateCiPolicy(data, options);
467
+ } catch (err) {
468
+ spinner?.stop();
469
+ handleCheckError(err, options);
470
+ }
471
+ }
472
+ function evaluateCiPolicy(data, options) {
473
+ if (options.failOn.length > 0) {
474
+ for (const flag of options.failOn) {
475
+ if (data.flags[flag] === true) {
476
+ return ExitCode.CiPolicyFailed;
477
+ }
478
+ }
479
+ }
480
+ if (options.failBelow !== void 0) {
481
+ if (data.risk.index === null) {
482
+ return ExitCode.AssessmentUnavailable;
483
+ }
484
+ if (data.risk.index < Number(options.failBelow)) {
485
+ return ExitCode.CiPolicyFailed;
486
+ }
487
+ }
488
+ return ExitCode.Success;
489
+ }
490
+ function handleCheckError(err, options) {
491
+ if (err instanceof NetRiskScanApiError) {
492
+ printApiError(err, { debug: options.debug });
493
+ process.exitCode = exitCodeForApiErrorCode(err.code);
494
+ return;
495
+ }
496
+ if (err instanceof NetRiskScanNetworkError) {
497
+ printNetworkError(err, { debug: options.debug });
498
+ process.exitCode = ExitCode.ApiError;
499
+ return;
500
+ }
501
+ if (options.debug && err instanceof Error) {
502
+ process.stderr.write(`${err.stack ?? err.message}
503
+ `);
504
+ } else {
505
+ process.stderr.write(`Error: ${err instanceof Error ? err.message : String(err)}
506
+ `);
507
+ }
508
+ process.exitCode = ExitCode.GeneralError;
509
+ }
510
+
511
+ // src/commands/usage.ts
512
+ import ora2 from "ora";
513
+ function registerUsageCommand(program2) {
514
+ 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) => {
515
+ await runUsage(options);
516
+ });
517
+ }
518
+ async function runUsage(options) {
519
+ const useJson = Boolean(options.json);
520
+ let apiKey;
521
+ try {
522
+ apiKey = resolveApiKey(options.apiKey);
523
+ } catch (err) {
524
+ if (err instanceof NetRiskScanConfigError) {
525
+ printConfigError(err);
526
+ process.exitCode = ExitCode.AuthError;
527
+ return;
528
+ }
529
+ throw err;
530
+ }
531
+ const client = new NetRiskScanClient({
532
+ apiKey,
533
+ baseUrl: resolveBaseUrl(options.baseUrl),
534
+ timeout: Number(options.timeout),
535
+ maxRetries: Number(options.maxRetries)
536
+ });
537
+ const spinner = useJson ? void 0 : ora2({ text: "Fetching usage...", stream: process.stderr, isEnabled: process.stderr.isTTY }).start();
538
+ try {
539
+ const { data, meta } = await client.getUsage();
540
+ spinner?.stop();
541
+ if (useJson) {
542
+ printJson(data);
543
+ } else {
544
+ renderUsageResult(data);
545
+ if (options.verbose) {
546
+ renderVerboseMeta(meta);
547
+ }
548
+ }
549
+ } catch (err) {
550
+ spinner?.stop();
551
+ if (err instanceof NetRiskScanApiError) {
552
+ printApiError(err, { debug: options.debug });
553
+ process.exitCode = exitCodeForApiErrorCode(err.code);
554
+ return;
555
+ }
556
+ if (err instanceof NetRiskScanNetworkError) {
557
+ printNetworkError(err, { debug: options.debug });
558
+ process.exitCode = ExitCode.ApiError;
559
+ return;
560
+ }
561
+ throw err;
562
+ }
563
+ }
564
+
565
+ // src/commands/batch.ts
566
+ import { createReadStream } from "fs";
567
+ import { createInterface } from "readline";
568
+
569
+ // src/utils/pool.ts
570
+ async function runPool(items, concurrency, worker) {
571
+ const results = new Array(items.length);
572
+ let cursor = 0;
573
+ async function next() {
574
+ while (cursor < items.length) {
575
+ const index = cursor++;
576
+ results[index] = await worker(items[index], index);
577
+ }
578
+ }
579
+ const workerCount = Math.max(1, Math.min(concurrency, items.length));
580
+ await Promise.all(Array.from({ length: workerCount }, () => next()));
581
+ return results;
582
+ }
583
+
584
+ // src/output/jsonl.ts
585
+ function printJsonLine(data) {
586
+ process.stdout.write(`${JSON.stringify(data)}
587
+ `);
588
+ }
589
+
590
+ // src/output/table.ts
591
+ import Table from "cli-table3";
592
+ import chalk3 from "chalk";
593
+ function renderBatchTable(results) {
594
+ const table = new Table({
595
+ head: ["IP", "Index", "Band", "Proxy", "VPN", "Tor", "Status"],
596
+ style: { head: [], border: [] }
597
+ });
598
+ for (const item of results) {
599
+ if (item.ok) {
600
+ const { result } = item;
601
+ table.push([
602
+ item.ip,
603
+ formatIndex(result.risk.index),
604
+ result.risk.band ?? "N/A",
605
+ formatTriState(result.flags.proxy),
606
+ formatTriState(result.flags.vpn),
607
+ formatTriState(result.flags.tor),
608
+ chalk3.green("ok")
609
+ ]);
610
+ } else {
611
+ table.push([item.ip, "-", "-", "-", "-", "-", chalk3.red(`error: ${item.error.code}`)]);
612
+ }
613
+ }
614
+ process.stdout.write(`${table.toString()}
615
+ `);
616
+ const okCount = results.filter((r) => r.ok).length;
617
+ const failCount = results.length - okCount;
618
+ process.stdout.write(`
619
+ ${okCount} succeeded, ${failCount} failed
620
+ `);
621
+ }
622
+
623
+ // src/commands/batch.ts
624
+ var MAX_CONCURRENCY = 20;
625
+ var DEFAULT_CONCURRENCY = 5;
626
+ function registerBatchCommand(program2) {
627
+ 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(
628
+ "--concurrency <n>",
629
+ `Number of concurrent requests (default: ${DEFAULT_CONCURRENCY}, max: ${MAX_CONCURRENCY})`,
630
+ String(DEFAULT_CONCURRENCY)
631
+ ).option("--jsonl", "Output newline-delimited JSON (one object per IP)").option("--timeout <ms>", "Request timeout in milliseconds", "10000").option("--max-retries <n>", "Maximum automatic retries for 429/503", "3").addHelpText(
632
+ "after",
633
+ `
634
+ Notes:
635
+ This is a client-side batch: it sends individual GET /v1/ip-risk/{ip}
636
+ requests with controlled concurrency. NetRiskScan does not currently
637
+ offer a server-side batch endpoint. Make sure the selected concurrency
638
+ complies with the limits shown in your NetRiskScan Developer Dashboard.
639
+
640
+ Input format:
641
+ One IP per line. Blank lines and lines starting with # are ignored.
642
+
643
+ Examples:
644
+ $ netriskscan batch ips.txt
645
+ $ cat ips.txt | netriskscan batch -
646
+ $ netriskscan batch ips.txt --concurrency 10 --jsonl > results.jsonl
647
+ `
648
+ ).action(async (file, options) => {
649
+ await runBatch(file, options);
650
+ });
651
+ }
652
+ async function readIps(file) {
653
+ const stream = file === "-" ? process.stdin : createReadStream(file, "utf8");
654
+ const rl = createInterface({ input: stream, crlfDelay: Infinity });
655
+ const ips = [];
656
+ for await (const rawLine of rl) {
657
+ const line = rawLine.trim();
658
+ if (line === "" || line.startsWith("#")) continue;
659
+ ips.push(line);
660
+ }
661
+ return ips;
662
+ }
663
+ function parseConcurrency(value) {
664
+ const n = Number(value);
665
+ if (!Number.isFinite(n) || n < 1) return DEFAULT_CONCURRENCY;
666
+ if (n > MAX_CONCURRENCY) {
667
+ process.stderr.write(
668
+ `Warning: --concurrency ${n} exceeds the safety cap of ${MAX_CONCURRENCY}; using ${MAX_CONCURRENCY}.
669
+ Check your NetRiskScan Developer Dashboard for your plan's concurrency limit.
670
+ `
671
+ );
672
+ return MAX_CONCURRENCY;
673
+ }
674
+ return Math.floor(n);
675
+ }
676
+ function toBatchError(err) {
677
+ if (err instanceof NetRiskScanApiError) {
678
+ return { code: err.code, message: err.message, requestId: err.requestId };
679
+ }
680
+ if (err instanceof NetRiskScanNetworkError) {
681
+ return { code: "network_error", message: err.message, requestId: err.requestId };
682
+ }
683
+ return { code: "unknown_error", message: err instanceof Error ? err.message : String(err) };
684
+ }
685
+ async function runBatch(file, options) {
686
+ let apiKey;
687
+ try {
688
+ apiKey = resolveApiKey(options.apiKey);
689
+ } catch (err) {
690
+ if (err instanceof NetRiskScanConfigError) {
691
+ printConfigError(err);
692
+ process.exitCode = ExitCode.AuthError;
693
+ return;
694
+ }
695
+ throw err;
696
+ }
697
+ const ips = await readIps(file);
698
+ if (ips.length === 0) {
699
+ process.stderr.write("Error: no IP addresses found in input.\n");
700
+ process.exitCode = ExitCode.InvalidArgument;
701
+ return;
702
+ }
703
+ const client = new NetRiskScanClient({
704
+ apiKey,
705
+ baseUrl: resolveBaseUrl(options.baseUrl),
706
+ timeout: Number(options.timeout),
707
+ maxRetries: Number(options.maxRetries)
708
+ });
709
+ const concurrency = parseConcurrency(options.concurrency);
710
+ const results = await runPool(ips, concurrency, async (ip) => {
711
+ if (!isValidIp(ip)) {
712
+ return {
713
+ ip,
714
+ ok: false,
715
+ error: { code: "invalid_ip", message: `"${ip}" is not a valid IPv4 or IPv6 address.` }
716
+ };
717
+ }
718
+ try {
719
+ const { data } = await client.checkIp(ip);
720
+ return { ip, ok: true, result: data };
721
+ } catch (err) {
722
+ return { ip, ok: false, error: toBatchError(err) };
723
+ }
724
+ });
725
+ if (options.jsonl) {
726
+ for (const item of results) {
727
+ printJsonLine(item);
728
+ }
729
+ } else {
730
+ renderBatchTable(results);
731
+ }
732
+ process.exitCode = computeBatchExitCode(results);
733
+ }
734
+ function computeBatchExitCode(results) {
735
+ const failures = results.filter((r) => !r.ok);
736
+ if (failures.length === 0) return ExitCode.Success;
737
+ const codes = failures.map((f) => exitCodeForApiErrorCode(f.error.code));
738
+ if (codes.includes(ExitCode.AuthError)) return ExitCode.AuthError;
739
+ if (codes.includes(ExitCode.RateLimitOrQuota)) return ExitCode.RateLimitOrQuota;
740
+ return ExitCode.ApiError;
741
+ }
742
+
743
+ // src/cli.ts
744
+ var __dirname = dirname(fileURLToPath(import.meta.url));
745
+ var pkg = JSON.parse(readFileSync(join(__dirname, "..", "package.json"), "utf8"));
746
+ var program = new Command();
747
+ 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(
748
+ "after",
749
+ `
750
+ Examples:
751
+ $ netriskscan check 1.1.1.1
752
+ $ netriskscan check 1.1.1.1 --json
753
+ $ netriskscan usage
754
+ $ netriskscan batch ips.txt --jsonl
755
+
756
+ Environment variables:
757
+ NETRISKSCAN_API_KEY API key used when --api-key is not provided
758
+
759
+ NetRiskScan provides diagnostic network intelligence. Results should not be
760
+ treated as proof of malicious activity or used as the sole basis for legal,
761
+ employment, credit, identity, or other high-impact decisions.
762
+
763
+ Learn more: https://github.com/TeamQQ/netriskscan-cli
764
+ `
765
+ );
766
+ registerCheckCommand(program);
767
+ registerUsageCommand(program);
768
+ registerBatchCommand(program);
769
+ program.exitOverride();
770
+ try {
771
+ await program.parseAsync(process.argv);
772
+ } catch (err) {
773
+ if (err instanceof CommanderError) {
774
+ if (err.code === "commander.helpDisplayed" || err.code === "commander.version") {
775
+ process.exitCode = ExitCode.Success;
776
+ } else {
777
+ process.exitCode = ExitCode.InvalidArgument;
778
+ }
779
+ } else {
780
+ process.stderr.write(`Unexpected error: ${err instanceof Error ? err.message : String(err)}
781
+ `);
782
+ process.exitCode = ExitCode.GeneralError;
783
+ }
784
+ }
785
+ //# sourceMappingURL=cli.js.map