netriskscan-cli 1.6.2 → 2.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 CHANGED
@@ -2,241 +2,13 @@
2
2
 
3
3
  // src/cli.ts
4
4
  import { readFileSync } from "fs";
5
- import { dirname, join } from "path";
5
+ import { dirname as dirname2, join as join2 } from "path";
6
6
  import { fileURLToPath } from "url";
7
7
  import { Command, CommanderError } from "commander";
8
8
 
9
9
  // src/commands/check.ts
10
10
  import ora from "ora";
11
11
 
12
- // src/client/errors.ts
13
- var ANONYMOUS_DAILY_LIMIT_CODE = "anonymous_daily_limit_reached";
14
- var NetRiskScanError = class extends Error {
15
- constructor(message) {
16
- super(message);
17
- this.name = "NetRiskScanError";
18
- }
19
- };
20
- var NetRiskScanConfigError = class extends NetRiskScanError {
21
- constructor(message) {
22
- super(message);
23
- this.name = "NetRiskScanConfigError";
24
- }
25
- };
26
- var NetRiskScanApiError = class extends NetRiskScanError {
27
- status;
28
- code;
29
- requestId;
30
- retryAfter;
31
- /** Present when the server reported anonymous-trial allowance alongside the error. */
32
- anonymousUsage;
33
- constructor(message, options) {
34
- super(message);
35
- this.name = "NetRiskScanApiError";
36
- this.status = options.status;
37
- this.code = options.code;
38
- this.requestId = options.requestId;
39
- this.retryAfter = options.retryAfter;
40
- this.anonymousUsage = options.anonymousUsage;
41
- }
42
- };
43
- var NetRiskScanNetworkError = class extends NetRiskScanError {
44
- cause;
45
- requestId;
46
- constructor(message, options = {}) {
47
- super(message);
48
- this.name = "NetRiskScanNetworkError";
49
- this.cause = options.cause;
50
- this.requestId = options.requestId;
51
- }
52
- };
53
-
54
- // src/client/headers.ts
55
- import { randomBytes } from "crypto";
56
- var REQUEST_ID_PATTERN = /^req_[A-Za-z0-9_-]{8,56}$/;
57
- function isValidRequestId(id) {
58
- return REQUEST_ID_PATTERN.test(id);
59
- }
60
- function generateRequestId() {
61
- return `req_${randomBytes(12).toString("hex")}`;
62
- }
63
- function parseIntHeader(value) {
64
- if (value === null) return void 0;
65
- const n = Number(value);
66
- return Number.isFinite(n) ? n : void 0;
67
- }
68
- function parseRateLimit(headers) {
69
- return {
70
- limit: parseIntHeader(headers.get("x-ratelimit-limit")),
71
- remaining: parseIntHeader(headers.get("x-ratelimit-remaining")),
72
- reset: parseIntHeader(headers.get("x-ratelimit-reset"))
73
- };
74
- }
75
- function parseQuota(headers) {
76
- return {
77
- limit: parseIntHeader(headers.get("x-quota-limit")),
78
- used: parseIntHeader(headers.get("x-quota-used")),
79
- remaining: parseIntHeader(headers.get("x-quota-remaining"))
80
- };
81
- }
82
-
83
- // src/client/retry.ts
84
- function isRetryableStatus(status) {
85
- return status === 429 || status === 503;
86
- }
87
- function isRetryableFailure(status, code) {
88
- if (code === ANONYMOUS_DAILY_LIMIT_CODE) return false;
89
- return isRetryableStatus(status);
90
- }
91
- var BASE_DELAY_MS = 1e3;
92
- var MAX_JITTER_MS = 250;
93
- function computeBackoffMs(attempt, retryAfterSeconds) {
94
- if (typeof retryAfterSeconds === "number" && Number.isFinite(retryAfterSeconds) && retryAfterSeconds >= 0) {
95
- return retryAfterSeconds * 1e3;
96
- }
97
- const base = BASE_DELAY_MS * 2 ** Math.max(0, attempt - 1);
98
- const jitter = Math.random() * MAX_JITTER_MS;
99
- return base + jitter;
100
- }
101
- function sleep(ms) {
102
- return new Promise((resolve) => setTimeout(resolve, ms));
103
- }
104
-
105
- // src/client/NetRiskScanClient.ts
106
- var DEFAULT_BASE_URL = "https://api.netriskscan.com";
107
- var DEFAULT_TIMEOUT_MS = 1e4;
108
- var DEFAULT_MAX_RETRIES = 3;
109
- function isAbortError(err) {
110
- return err instanceof Error && err.name === "AbortError";
111
- }
112
- async function safeJson(res) {
113
- try {
114
- return await res.json();
115
- } catch {
116
- return void 0;
117
- }
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
- }
128
- var NetRiskScanClient = class {
129
- apiKey;
130
- baseUrl;
131
- timeout;
132
- maxRetries;
133
- constructor(options = {}) {
134
- this.apiKey = options.apiKey || void 0;
135
- this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
136
- this.timeout = options.timeout ?? DEFAULT_TIMEOUT_MS;
137
- this.maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;
138
- }
139
- async checkIp(ip, options = {}) {
140
- return this.request(`/v1/ip-risk/${encodeURIComponent(ip)}`, options);
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
- */
146
- async getUsage(options = {}) {
147
- if (!this.apiKey) {
148
- throw new NetRiskScanConfigError("An API key is required to query account usage.");
149
- }
150
- return this.request("/v1/usage", options);
151
- }
152
- async request(path, options) {
153
- const requestId = options.requestId && isValidRequestId(options.requestId) ? options.requestId : generateRequestId();
154
- let attempt = 0;
155
- while (true) {
156
- const timeoutController = new AbortController();
157
- const timer = setTimeout(() => timeoutController.abort(), this.timeout);
158
- const onExternalAbort = () => timeoutController.abort();
159
- options.signal?.addEventListener("abort", onExternalAbort);
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
- }
168
- const res = await fetch(`${this.baseUrl}${path}`, {
169
- method: "GET",
170
- headers,
171
- signal: timeoutController.signal
172
- });
173
- const rateLimit = parseRateLimit(res.headers);
174
- const quota = parseQuota(res.headers);
175
- const responseRequestId = res.headers.get("x-request-id") ?? requestId;
176
- if (res.ok) {
177
- const data = await res.json();
178
- return { data, meta: { requestId: responseRequestId, rateLimit, quota } };
179
- }
180
- const body = await safeJson(res);
181
- const retryAfterHeader = res.headers.get("retry-after");
182
- const retryAfter = retryAfterHeader !== null ? Number(retryAfterHeader) : void 0;
183
- if (isRetryableFailure(res.status, body?.error?.code) && attempt < this.maxRetries) {
184
- attempt += 1;
185
- await sleep(computeBackoffMs(attempt, retryAfter));
186
- continue;
187
- }
188
- throw new NetRiskScanApiError(body?.error?.message ?? res.statusText, {
189
- status: res.status,
190
- code: body?.error?.code ?? "unknown_error",
191
- requestId: body?.error?.requestId ?? responseRequestId,
192
- retryAfter,
193
- anonymousUsage: parseAnonymousLimitInfo(body)
194
- });
195
- } catch (err) {
196
- if (err instanceof NetRiskScanApiError) {
197
- throw err;
198
- }
199
- if (isAbortError(err)) {
200
- if (options.signal?.aborted) {
201
- throw err;
202
- }
203
- throw new NetRiskScanNetworkError(`Request timed out after ${this.timeout}ms`, {
204
- cause: err,
205
- requestId
206
- });
207
- }
208
- throw new NetRiskScanNetworkError(
209
- err instanceof Error ? err.message : "Network request failed",
210
- {
211
- cause: err,
212
- requestId
213
- }
214
- );
215
- } finally {
216
- clearTimeout(timer);
217
- options.signal?.removeEventListener("abort", onExternalAbort);
218
- }
219
- }
220
- }
221
- };
222
-
223
- // src/utils/env.ts
224
- function resolveOptionalApiKey(cliValue) {
225
- return cliValue || process.env.NETRISKSCAN_API_KEY || void 0;
226
- }
227
- function resolveRequiredApiKey(cliValue) {
228
- const apiKey = resolveOptionalApiKey(cliValue);
229
- if (!apiKey) {
230
- throw new NetRiskScanConfigError(
231
- "An API key is required for the usage command.\n\nSet NETRISKSCAN_API_KEY or use --api-key."
232
- );
233
- }
234
- return apiKey;
235
- }
236
- function resolveBaseUrl(cliValue) {
237
- return cliValue ?? process.env.NETRISKSCAN_BASE_URL;
238
- }
239
-
240
12
  // src/utils/ip.ts
241
13
  import { isIP } from "net";
242
14
  function isValidIp(value) {
@@ -264,6 +36,7 @@ function exitCodeForApiErrorCode(code) {
264
36
  // adding an eighth exit code that every script would have to learn.
265
37
  case "rate_limit_exceeded":
266
38
  case "quota_exceeded":
39
+ case "monthly_quota_exceeded":
267
40
  case "anonymous_daily_limit_reached":
268
41
  return ExitCode.RateLimitOrQuota;
269
42
  default:
@@ -274,6 +47,12 @@ function exitCodeForApiErrorCode(code) {
274
47
  // src/output/human.ts
275
48
  import chalk from "chalk";
276
49
 
50
+ // src/utils/quotaWarnings.ts
51
+ import { createHash } from "crypto";
52
+ import { mkdir, stat, unlink, writeFile } from "fs/promises";
53
+ import { homedir } from "os";
54
+ import { dirname, join } from "path";
55
+
277
56
  // src/output/format.ts
278
57
  function formatTriState(value) {
279
58
  if (value === true) return "Yes";
@@ -350,9 +129,6 @@ function formatNullable(value) {
350
129
  function formatNumber(value) {
351
130
  return value.toLocaleString("en-US");
352
131
  }
353
- function formatDate(iso) {
354
- return iso.slice(0, 10);
355
- }
356
132
  var LABEL_WIDTH = 18;
357
133
  function row(label, value) {
358
134
  return `${label.padEnd(LABEL_WIDTH)}${value}`;
@@ -369,6 +145,97 @@ function formatUtcTimestamp(iso) {
369
145
  return `${date.getUTCFullYear()}-${pad(date.getUTCMonth() + 1)}-${pad(date.getUTCDate())} ${pad(date.getUTCHours())}:${pad(date.getUTCMinutes())} UTC`;
370
146
  }
371
147
 
148
+ // src/utils/browser.ts
149
+ import { spawn } from "child_process";
150
+ var WEB_PAGES = {
151
+ keys: "https://www.netriskscan.com/developer/keys",
152
+ plans: "https://www.netriskscan.com/pricing.html",
153
+ billing: "https://www.netriskscan.com/developer/billing"
154
+ };
155
+ function isInteractive(machineOutput) {
156
+ const ci = process.env.CI?.trim().toLowerCase();
157
+ return Boolean(
158
+ !machineOutput && process.stdin.isTTY && process.stdout.isTTY && (!ci || ci === "false" || ci === "0") && !process.env.GITHUB_ACTIONS && !process.env.TF_BUILD
159
+ );
160
+ }
161
+ async function openBrowser(page) {
162
+ const url = WEB_PAGES[page];
163
+ const [command, ...args] = process.platform === "win32" ? ["rundll32.exe", "url.dll,FileProtocolHandler", url] : process.platform === "darwin" ? ["open", url] : ["xdg-open", url];
164
+ const env = { ...process.env };
165
+ for (const name of Object.keys(env)) {
166
+ if (name.toUpperCase() === "NETRISKSCAN_API_KEY") delete env[name];
167
+ }
168
+ return new Promise((resolve) => {
169
+ const child = spawn(command, args, { env, detached: true, stdio: "ignore", windowsHide: true });
170
+ const timer = setTimeout(() => finish(true), 400);
171
+ function finish(opened) {
172
+ clearTimeout(timer);
173
+ child.unref();
174
+ resolve(opened);
175
+ }
176
+ child.once("error", () => finish(false));
177
+ child.once("exit", (code) => finish(code === 0));
178
+ });
179
+ }
180
+
181
+ // src/utils/quotaWarnings.ts
182
+ var WARNING_LEVELS = [80, 95];
183
+ function quotaUsagePercent(quota) {
184
+ const { limit, used } = quota;
185
+ return limit !== void 0 && limit > 0 && used !== void 0 ? used / limit * 100 : void 0;
186
+ }
187
+ function marker(key, limit, level) {
188
+ const fingerprint = createHash("sha256").update(key).digest("hex");
189
+ return join(homedir(), ".netriskscan", "quota-warnings", `${fingerprint}-${limit}-${level}`);
190
+ }
191
+ async function rearmQuotaWarnings(key, quota, periodStart) {
192
+ const { limit } = quota;
193
+ const percent = quotaUsagePercent(quota);
194
+ if (limit === void 0 || percent === void 0) return;
195
+ const start = periodStart ? Date.parse(periodStart) : NaN;
196
+ await Promise.all(
197
+ WARNING_LEVELS.map(async (level) => {
198
+ const path = marker(key, limit, level);
199
+ try {
200
+ if (percent < level || Number.isFinite(start) && (await stat(path)).mtimeMs < start) {
201
+ await unlink(path);
202
+ }
203
+ } catch {
204
+ }
205
+ })
206
+ );
207
+ }
208
+ async function warnAboutQuota(key, quota) {
209
+ const { limit, used, remaining } = quota;
210
+ const percent = quotaUsagePercent(quota);
211
+ if (limit === void 0 || used === void 0 || remaining === void 0 || percent === void 0)
212
+ return;
213
+ await rearmQuotaWarnings(key, quota);
214
+ let warnedAt;
215
+ for (const level of WARNING_LEVELS) {
216
+ if (percent < level) break;
217
+ const path = marker(key, limit, level);
218
+ try {
219
+ await mkdir(dirname(path), { recursive: true, mode: 448 });
220
+ await writeFile(path, "", { flag: "wx", mode: 384 });
221
+ warnedAt = level;
222
+ } catch {
223
+ }
224
+ }
225
+ if (warnedAt === void 0) return;
226
+ process.stderr.write(
227
+ [
228
+ "",
229
+ warnedAt === WARNING_LEVELS[1] ? "Monthly API quota almost exhausted." : "Monthly API quota warning.",
230
+ row("Usage", `${formatNumber(used)} / ${formatNumber(limit)}`),
231
+ row("Remaining", formatNumber(remaining)),
232
+ "For more quota, run npx netriskscan-cli upgrade",
233
+ WEB_PAGES.plans,
234
+ ""
235
+ ].join("\n") + "\n"
236
+ );
237
+ }
238
+
372
239
  // src/output/human.ts
373
240
  function anonymousUsageLines(usage) {
374
241
  const lines = [];
@@ -542,12 +409,15 @@ function renderUsageResult(data) {
542
409
  lines.push(row("Used", formatNumber(data.units.used)));
543
410
  lines.push(row("Remaining", formatNumber(data.units.remaining)));
544
411
  lines.push(row("Limit", formatNumber(data.units.limit)));
412
+ const percent = quotaUsagePercent(data.units);
413
+ if (percent !== void 0) lines.push(row("Used (%)", `${percent.toFixed(1)}%`));
545
414
  lines.push("");
546
415
  lines.push(chalk.bold("Rate limit"));
547
416
  lines.push(row("Requests / minute", formatNumber(data.rateLimit.requestsPerMinute)));
548
417
  lines.push("");
549
- lines.push(chalk.bold("Billing period"));
550
- lines.push(`${formatDate(data.period.start)} \u2192 ${formatDate(data.period.end)}`);
418
+ lines.push(chalk.bold("Monthly quota period"));
419
+ lines.push(row("Started", formatUtcTimestamp(data.period.start) ?? data.period.start));
420
+ lines.push(row("Resets", formatUtcTimestamp(data.period.end) ?? data.period.end));
551
421
  process.stdout.write(`${lines.join("\n")}
552
422
  `);
553
423
  }
@@ -560,42 +430,143 @@ function printJson(data) {
560
430
 
561
431
  // src/output/errors.ts
562
432
  import chalk2 from "chalk";
563
- var SIGNUP_URL = "https://www.netriskscan.com/developer/register";
564
- function printConfigError(err) {
565
- process.stderr.write(`Error: ${err.message}
566
- `);
567
- if (err.message.includes("API key")) {
568
- process.stderr.write(
569
- "\nGet a free API key (no credit card required): https://www.netriskscan.com\n"
570
- );
571
- }
433
+
434
+ // src/client/errors.ts
435
+ var ANONYMOUS_DAILY_LIMIT_CODE = "anonymous_daily_limit_reached";
436
+ function isMonthlyQuotaError(code) {
437
+ return code === "quota_exceeded" || code === "monthly_quota_exceeded";
572
438
  }
573
- function printAnonymousLimitError(err) {
574
- const usage = err.anonymousUsage;
575
- const lines = [
576
- "",
577
- chalk2.bold("NetRiskScan"),
578
- "",
579
- chalk2.yellow("Anonymous daily trial limit reached."),
580
- ""
581
- ];
582
- const usageLines = [
583
- // The request that returned this error was refused, so nothing is left regardless of what the
584
- // body reports; `remaining` is only trusted when the server actually sent it.
585
- row("Available", formatNumber(typeof usage?.remaining === "number" ? usage.remaining : 0))
586
- ];
587
- if (typeof usage?.dailyLimit === "number") {
588
- usageLines.push(row("Daily Limit", formatNumber(usage.dailyLimit)));
439
+ var NetRiskScanError = class extends Error {
440
+ constructor(message) {
441
+ super(message);
442
+ this.name = "NetRiskScanError";
589
443
  }
590
- const reset = formatUtcTimestamp(usage?.resetAt);
591
- if (reset !== void 0) {
592
- usageLines.push(row("Reset", reset));
444
+ };
445
+ var NetRiskScanConfigError = class extends NetRiskScanError {
446
+ constructor(message) {
447
+ super(message);
448
+ this.name = "NetRiskScanConfigError";
593
449
  }
594
- lines.push(chalk2.bold("Usage"), ...usageLines, "");
595
- lines.push(chalk2.bold("Get more queries"), usage?.signupUrl || SIGNUP_URL, "");
596
- process.stderr.write(`${lines.join("\n")}
450
+ };
451
+ var NetRiskScanApiError = class extends NetRiskScanError {
452
+ status;
453
+ code;
454
+ requestId;
455
+ retryAfter;
456
+ /** Present when the server reported anonymous-trial allowance alongside the error. */
457
+ anonymousUsage;
458
+ quota;
459
+ quotaResetAt;
460
+ constructor(message, options) {
461
+ super(message);
462
+ this.name = "NetRiskScanApiError";
463
+ this.status = options.status;
464
+ this.code = options.code;
465
+ this.requestId = options.requestId;
466
+ this.retryAfter = options.retryAfter;
467
+ this.anonymousUsage = options.anonymousUsage;
468
+ this.quota = options.quota;
469
+ this.quotaResetAt = options.quotaResetAt;
470
+ }
471
+ };
472
+ var NetRiskScanNetworkError = class extends NetRiskScanError {
473
+ cause;
474
+ requestId;
475
+ constructor(message, options = {}) {
476
+ super(message);
477
+ this.name = "NetRiskScanNetworkError";
478
+ this.cause = options.cause;
479
+ this.requestId = options.requestId;
480
+ }
481
+ };
482
+
483
+ // src/output/jsonl.ts
484
+ function printJsonLine(data) {
485
+ process.stdout.write(`${JSON.stringify(data)}
597
486
  `);
598
487
  }
488
+
489
+ // src/output/errors.ts
490
+ var CliError = class extends Error {
491
+ constructor(code, message, exitCode, url) {
492
+ super(message);
493
+ this.code = code;
494
+ this.exitCode = exitCode;
495
+ this.url = url;
496
+ }
497
+ code;
498
+ exitCode;
499
+ url;
500
+ };
501
+ function commandFailure(cause) {
502
+ if (cause instanceof NetRiskScanApiError) {
503
+ return {
504
+ cause,
505
+ exitCode: exitCodeForApiErrorCode(cause.code),
506
+ info: {
507
+ code: cause.code,
508
+ message: cause.message,
509
+ status: cause.status,
510
+ requestId: cause.requestId,
511
+ retryAfter: cause.retryAfter,
512
+ quota: cause.quota && Object.values(cause.quota).some((value) => value !== void 0) ? cause.quota : void 0,
513
+ resetAt: cause.quotaResetAt,
514
+ upgradeUrl: isMonthlyQuotaError(cause.code) ? WEB_PAGES.plans : void 0
515
+ }
516
+ };
517
+ }
518
+ if (cause instanceof NetRiskScanNetworkError) {
519
+ return {
520
+ cause,
521
+ exitCode: ExitCode.ApiError,
522
+ info: { code: "network_error", message: cause.message, requestId: cause.requestId }
523
+ };
524
+ }
525
+ if (cause instanceof CliError) {
526
+ return {
527
+ cause,
528
+ exitCode: cause.exitCode,
529
+ info: { code: cause.code, message: cause.message, url: cause.url }
530
+ };
531
+ }
532
+ return {
533
+ cause,
534
+ exitCode: ExitCode.GeneralError,
535
+ info: {
536
+ code: "cli_error",
537
+ message: cause instanceof Error ? cause.message : "Unexpected CLI error."
538
+ }
539
+ };
540
+ }
541
+ function reportFailure(failure, options = {}) {
542
+ const { info, cause } = failure;
543
+ if (options.jsonl) {
544
+ printJsonLine({ error: info });
545
+ } else if (options.json) {
546
+ printJson({ error: info });
547
+ } else if (isMonthlyQuotaError(info.code)) {
548
+ const lines = ["", chalk2.yellow("Monthly API quota exceeded.")];
549
+ if (info.plan) lines.push(row("Current plan", info.plan));
550
+ if (info.quota?.limit !== void 0)
551
+ lines.push(row("Monthly limit", formatNumber(info.quota.limit)));
552
+ if (info.quota?.used !== void 0) lines.push(row("Used", formatNumber(info.quota.used)));
553
+ if (info.quota?.remaining !== void 0)
554
+ lines.push(row("Remaining", formatNumber(info.quota.remaining)));
555
+ const reset = formatUtcTimestamp(info.resetAt);
556
+ if (reset) lines.push(row("Resets", reset));
557
+ lines.push("", "For more quota, run npx netriskscan-cli upgrade", info.upgradeUrl ?? "", "");
558
+ process.stderr.write(lines.join("\n"));
559
+ } else if (cause instanceof NetRiskScanApiError) {
560
+ printApiError(cause, options);
561
+ } else if (cause instanceof NetRiskScanNetworkError) {
562
+ printNetworkError(cause, options);
563
+ } else {
564
+ process.stderr.write(`Error: ${info.message}
565
+ `);
566
+ if (info.url) process.stderr.write(`${info.url}
567
+ `);
568
+ }
569
+ }
599
570
  var LABEL_WIDTH2 = 11;
600
571
  function printApiError(err, options = {}) {
601
572
  const lines = [
@@ -633,6 +604,328 @@ ${err.message}
633
604
  }
634
605
  }
635
606
 
607
+ // src/commands/session.ts
608
+ import { createInterface } from "readline/promises";
609
+
610
+ // src/client/headers.ts
611
+ import { randomBytes } from "crypto";
612
+ var REQUEST_ID_PATTERN = /^req_[A-Za-z0-9_-]{8,56}$/;
613
+ function isValidRequestId(id) {
614
+ return REQUEST_ID_PATTERN.test(id);
615
+ }
616
+ function generateRequestId() {
617
+ return `req_${randomBytes(12).toString("hex")}`;
618
+ }
619
+ function parseIntHeader(value) {
620
+ if (value === null || !/^\d+$/.test(value)) return void 0;
621
+ const n = Number(value);
622
+ return Number.isSafeInteger(n) ? n : void 0;
623
+ }
624
+ function parseRateLimit(headers) {
625
+ return {
626
+ limit: parseIntHeader(headers.get("x-ratelimit-limit")),
627
+ remaining: parseIntHeader(headers.get("x-ratelimit-remaining")),
628
+ reset: parseIntHeader(headers.get("x-ratelimit-reset"))
629
+ };
630
+ }
631
+ function parseQuota(headers) {
632
+ return {
633
+ limit: parseIntHeader(headers.get("x-quota-limit")),
634
+ used: parseIntHeader(headers.get("x-quota-used")),
635
+ remaining: parseIntHeader(headers.get("x-quota-remaining"))
636
+ };
637
+ }
638
+ function redactApiKey(key) {
639
+ if (key.length <= 13) return "*".repeat(key.length);
640
+ return `${key.slice(0, 9)}${"*".repeat(4)}${key.slice(-4)}`;
641
+ }
642
+
643
+ // src/client/retry.ts
644
+ function isRetryableStatus(status) {
645
+ return status === 429 || status === 503;
646
+ }
647
+ function isRetryableFailure(status, code) {
648
+ if (code === ANONYMOUS_DAILY_LIMIT_CODE || isMonthlyQuotaError(code)) return false;
649
+ return isRetryableStatus(status);
650
+ }
651
+ var BASE_DELAY_MS = 1e3;
652
+ var MAX_JITTER_MS = 250;
653
+ function computeBackoffMs(attempt, retryAfterSeconds) {
654
+ if (typeof retryAfterSeconds === "number" && Number.isFinite(retryAfterSeconds) && retryAfterSeconds >= 0) {
655
+ return retryAfterSeconds * 1e3;
656
+ }
657
+ const base = BASE_DELAY_MS * 2 ** Math.max(0, attempt - 1);
658
+ const jitter = Math.random() * MAX_JITTER_MS;
659
+ return base + jitter;
660
+ }
661
+ function sleep(ms) {
662
+ return new Promise((resolve) => setTimeout(resolve, ms));
663
+ }
664
+
665
+ // src/client/NetRiskScanClient.ts
666
+ var DEFAULT_BASE_URL = "https://api.netriskscan.com";
667
+ var DEFAULT_TIMEOUT_MS = 1e4;
668
+ var DEFAULT_MAX_RETRIES = 3;
669
+ function isAbortError(err) {
670
+ return err instanceof Error && err.name === "AbortError";
671
+ }
672
+ function quotaResetAt(headers, seconds) {
673
+ if (seconds === void 0 || !Number.isFinite(seconds) || seconds < 0) return void 0;
674
+ const responseDate = Date.parse(headers.get("date") ?? "");
675
+ const reset = new Date(
676
+ (Number.isFinite(responseDate) ? responseDate : Date.now()) + seconds * 1e3
677
+ );
678
+ return Number.isFinite(reset.getTime()) ? reset.toISOString() : void 0;
679
+ }
680
+ async function safeJson(res) {
681
+ try {
682
+ return await res.json();
683
+ } catch {
684
+ return void 0;
685
+ }
686
+ }
687
+ function parseAnonymousLimitInfo(body) {
688
+ const error = body?.error;
689
+ if (!error) return void 0;
690
+ const { dailyLimit, used, remaining, resetAt, signupUrl } = error;
691
+ if (dailyLimit === void 0 && used === void 0 && remaining === void 0 && resetAt === void 0 && signupUrl === void 0) {
692
+ return void 0;
693
+ }
694
+ return { dailyLimit, used, remaining, resetAt, signupUrl };
695
+ }
696
+ var NetRiskScanClient = class {
697
+ apiKey;
698
+ baseUrl;
699
+ timeout;
700
+ maxRetries;
701
+ constructor(options = {}) {
702
+ this.apiKey = options.apiKey || void 0;
703
+ this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
704
+ this.timeout = options.timeout ?? DEFAULT_TIMEOUT_MS;
705
+ this.maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;
706
+ }
707
+ async checkIp(ip, options = {}) {
708
+ return this.request(`/v1/ip-risk/${encodeURIComponent(ip)}`, options);
709
+ }
710
+ /**
711
+ * Account plan, billing period and quota. Unlike {@link checkIp} this is account data, so it
712
+ * has no anonymous equivalent and requires an API key.
713
+ */
714
+ async getUsage(options = {}) {
715
+ if (!this.apiKey) {
716
+ throw new NetRiskScanConfigError("An API key is required to query account usage.");
717
+ }
718
+ return this.request("/v1/usage", options);
719
+ }
720
+ redact(value) {
721
+ return this.apiKey ? value.replaceAll(this.apiKey, "[REDACTED]") : value;
722
+ }
723
+ async request(path, options) {
724
+ const requestId = options.requestId && isValidRequestId(options.requestId) ? options.requestId : generateRequestId();
725
+ let attempt = 0;
726
+ while (true) {
727
+ const timeoutController = new AbortController();
728
+ const timer = setTimeout(() => timeoutController.abort(), this.timeout);
729
+ const onExternalAbort = () => timeoutController.abort();
730
+ options.signal?.addEventListener("abort", onExternalAbort);
731
+ try {
732
+ const headers = {
733
+ Accept: "application/json",
734
+ "X-Request-Id": requestId
735
+ };
736
+ if (this.apiKey) {
737
+ headers.Authorization = `Bearer ${this.apiKey}`;
738
+ }
739
+ const res = await fetch(`${this.baseUrl}${path}`, {
740
+ method: "GET",
741
+ headers,
742
+ redirect: this.apiKey ? "error" : "follow",
743
+ signal: timeoutController.signal
744
+ });
745
+ const rateLimit = parseRateLimit(res.headers);
746
+ const quota = parseQuota(res.headers);
747
+ const responseRequestId = this.redact(res.headers.get("x-request-id") ?? requestId);
748
+ if (res.ok) {
749
+ const data = await res.json();
750
+ return { data, meta: { requestId: responseRequestId, rateLimit, quota } };
751
+ }
752
+ const body = await safeJson(res);
753
+ const retryAfterHeader = res.headers.get("retry-after");
754
+ const delay = retryAfterHeader?.trim() ? Number(retryAfterHeader) : NaN;
755
+ const retryAfter = Number.isFinite(delay) && delay >= 0 ? delay : void 0;
756
+ const code = body?.error?.code ?? "unknown_error";
757
+ if (isRetryableFailure(res.status, code) && attempt < this.maxRetries) {
758
+ attempt += 1;
759
+ await sleep(computeBackoffMs(attempt, retryAfter));
760
+ continue;
761
+ }
762
+ throw new NetRiskScanApiError(this.redact(body?.error?.message ?? res.statusText), {
763
+ status: res.status,
764
+ code: this.redact(code),
765
+ requestId: this.redact(body?.error?.requestId ?? responseRequestId),
766
+ retryAfter,
767
+ anonymousUsage: parseAnonymousLimitInfo(body),
768
+ quota: isMonthlyQuotaError(code) ? quota : void 0,
769
+ quotaResetAt: isMonthlyQuotaError(code) ? quotaResetAt(res.headers, retryAfter) : void 0
770
+ });
771
+ } catch (err) {
772
+ if (err instanceof NetRiskScanApiError) {
773
+ throw err;
774
+ }
775
+ if (isAbortError(err)) {
776
+ if (options.signal?.aborted) {
777
+ throw err;
778
+ }
779
+ throw new NetRiskScanNetworkError(`Request timed out after ${this.timeout}ms`, {
780
+ cause: err,
781
+ requestId
782
+ });
783
+ }
784
+ throw new NetRiskScanNetworkError(
785
+ err instanceof Error ? this.redact(err.message) : "Network request failed",
786
+ {
787
+ cause: err,
788
+ requestId
789
+ }
790
+ );
791
+ } finally {
792
+ clearTimeout(timer);
793
+ options.signal?.removeEventListener("abort", onExternalAbort);
794
+ }
795
+ }
796
+ }
797
+ };
798
+
799
+ // src/utils/credentials.ts
800
+ var CredentialStoreUnavailable = class extends Error {
801
+ constructor() {
802
+ super(
803
+ "The OS credential store is unavailable. Use a secret manager to supply NETRISKSCAN_API_KEY."
804
+ );
805
+ }
806
+ };
807
+ async function useStore(operation) {
808
+ try {
809
+ const { AsyncEntry } = await import("@napi-rs/keyring");
810
+ const entry = new AsyncEntry("netriskscan-cli", "developer-api-key", {
811
+ linux: { store: "secret-service" }
812
+ });
813
+ return await operation(entry);
814
+ } catch {
815
+ throw new CredentialStoreUnavailable();
816
+ }
817
+ }
818
+ var credentials = {
819
+ read: () => useStore((entry) => entry.getPassword()),
820
+ save: (key) => useStore((entry) => entry.setPassword(key)),
821
+ remove: () => useStore((entry) => entry.deleteCredential())
822
+ };
823
+
824
+ // src/utils/env.ts
825
+ function resolveBaseUrl(cliValue) {
826
+ return cliValue ?? process.env.NETRISKSCAN_BASE_URL;
827
+ }
828
+
829
+ // src/commands/session.ts
830
+ async function runCommand(options, action) {
831
+ try {
832
+ await action();
833
+ } catch (error) {
834
+ const failure = commandFailure(error);
835
+ reportFailure(failure, options);
836
+ process.exitCode = failure.exitCode;
837
+ }
838
+ }
839
+ function suppliedKey(cliValue) {
840
+ if (cliValue !== void 0) return { key: validateKey(cliValue), source: "argument" };
841
+ const key = process.env.NETRISKSCAN_API_KEY;
842
+ return key ? { key: validateKey(key), source: "environment" } : void 0;
843
+ }
844
+ function validateKey(key) {
845
+ if (!/^[A-Za-z0-9._~+/-]+=*$/.test(key)) {
846
+ throw new CliError(
847
+ "invalid_api_key",
848
+ "The API key is empty or has invalid characters.",
849
+ ExitCode.AuthError
850
+ );
851
+ }
852
+ return key;
853
+ }
854
+ function isOfficialApi(options) {
855
+ const baseUrl = resolveBaseUrl(options.baseUrl) ?? DEFAULT_BASE_URL;
856
+ return baseUrl.replace(/\/+$/, "") === DEFAULT_BASE_URL;
857
+ }
858
+ function createClient(key, options) {
859
+ return new NetRiskScanClient({
860
+ apiKey: validateKey(key),
861
+ baseUrl: resolveBaseUrl(options.baseUrl),
862
+ timeout: options.timeout === void 0 ? void 0 : Number(options.timeout),
863
+ maxRetries: options.maxRetries === void 0 ? void 0 : Number(options.maxRetries)
864
+ });
865
+ }
866
+ async function requireSession(options, setup = true) {
867
+ const supplied = suppliedKey(options.apiKey);
868
+ const official = isOfficialApi(options);
869
+ let key = supplied?.key;
870
+ let storeUnavailable = false;
871
+ if (!key && official) {
872
+ try {
873
+ key = await credentials.read() ?? void 0;
874
+ } catch (error) {
875
+ if (!(error instanceof CredentialStoreUnavailable)) throw error;
876
+ storeUnavailable = true;
877
+ }
878
+ }
879
+ if (!key) {
880
+ const url = official ? WEB_PAGES.keys : void 0;
881
+ const opened = official && setup && isInteractive(options.json || options.jsonl) && await openBrowser("keys");
882
+ const message = opened ? "The Developer Console opened. Continue with Google, create an API key, then use auth save or NETRISKSCAN_API_KEY and rerun your command." : "Developer API requires a valid API key. Set NETRISKSCAN_API_KEY or use --api-key.";
883
+ const storeMessage = storeUnavailable ? " The OS credential store is unavailable." : "";
884
+ throw new CliError(
885
+ opened ? "auth_setup_required" : "api_key_required",
886
+ message + storeMessage,
887
+ ExitCode.AuthError,
888
+ url
889
+ );
890
+ }
891
+ return { key, client: createClient(key, options) };
892
+ }
893
+ async function quotaFailure(error, client) {
894
+ const failure = commandFailure(error);
895
+ if (!(error instanceof NetRiskScanApiError) || !isMonthlyQuotaError(error.code)) return failure;
896
+ try {
897
+ const { data } = await client.getUsage();
898
+ failure.info.plan = data.plan;
899
+ failure.info.quota = {
900
+ limit: error.quota?.limit ?? data.units.limit,
901
+ used: error.quota?.used ?? data.units.used,
902
+ remaining: error.quota?.remaining ?? data.units.remaining
903
+ };
904
+ failure.info.resetAt = error.quotaResetAt ?? data.period.end;
905
+ } catch {
906
+ }
907
+ return failure;
908
+ }
909
+ async function offerQuotaUpgrade(code, options) {
910
+ if (!isMonthlyQuotaError(code) || !isOfficialApi(options) || !isInteractive(options.json || options.jsonl))
911
+ return;
912
+ const input = createInterface({ input: process.stdin, output: process.stderr });
913
+ const controller = new AbortController();
914
+ input.once("close", () => controller.abort());
915
+ try {
916
+ const answer = (await input.question("Would you like to view available plans? [Y/n] ", {
917
+ signal: controller.signal
918
+ })).trim().toLowerCase();
919
+ if ((answer === "" || answer === "y" || answer === "yes") && !await openBrowser("plans")) {
920
+ process.stderr.write(`Open ${WEB_PAGES.plans} in your browser.
921
+ `);
922
+ }
923
+ } catch {
924
+ } finally {
925
+ input.close();
926
+ }
927
+ }
928
+
636
929
  // src/commands/check.ts
637
930
  var KNOWN_FLAGS = [
638
931
  "proxy",
@@ -646,10 +939,7 @@ function collect(value, previous) {
646
939
  return [...previous, value];
647
940
  }
648
941
  function registerCheckCommand(program2) {
649
- program2.command("check <ip>").description("Check IP risk and network intelligence").option(
650
- "--api-key <key>",
651
- "NetRiskScan API key (optional; uses the anonymous trial when omitted)"
652
- ).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(
942
+ program2.command("check <ip>").description("Check IP risk and network intelligence").option("--api-key <key>", "Developer API key (overrides the environment and OS store)").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(
653
943
  "--fail-on <flag>",
654
944
  "Exit non-zero if the given flag is true (repeatable): proxy, vpn, tor, datacenter, scanner, abuse",
655
945
  collect,
@@ -664,37 +954,31 @@ Examples:
664
954
  $ netriskscan check 1.2.3.4 --fail-on tor --fail-on proxy
665
955
 
666
956
  Notes:
667
- An API key is optional. Without one, requests use the anonymous daily trial,
668
- metered by public IP; the response reports how many are left.
957
+ Developer API requires a valid API Key.
669
958
  `
670
959
  ).action(async (ip, options) => {
671
- await runCheck(ip, options);
960
+ await runCommand(options, () => runCheck(ip, options));
672
961
  });
673
962
  }
674
963
  async function runCheck(ip, options) {
675
964
  const useJson = Boolean(options.json);
676
965
  for (const flag of options.failOn) {
677
966
  if (!KNOWN_FLAGS.includes(flag)) {
678
- process.stderr.write(
679
- `Error: unknown --fail-on flag "${flag}". Expected one of: ${KNOWN_FLAGS.join(", ")}
680
- `
967
+ throw new CliError(
968
+ "invalid_argument",
969
+ `Unknown --fail-on flag "${flag}". Expected one of: ${KNOWN_FLAGS.join(", ")}`,
970
+ ExitCode.InvalidArgument
681
971
  );
682
- process.exitCode = ExitCode.InvalidArgument;
683
- return;
684
972
  }
685
973
  }
686
974
  if (!isValidIp(ip)) {
687
- process.stderr.write(`Error: "${ip}" is not a valid IPv4 or IPv6 address.
688
- `);
689
- process.exitCode = ExitCode.InvalidArgument;
690
- return;
975
+ throw new CliError(
976
+ "invalid_ip",
977
+ `"${ip}" is not a valid IPv4 or IPv6 address.`,
978
+ ExitCode.InvalidArgument
979
+ );
691
980
  }
692
- const client = new NetRiskScanClient({
693
- apiKey: resolveOptionalApiKey(options.apiKey),
694
- baseUrl: resolveBaseUrl(options.baseUrl),
695
- timeout: Number(options.timeout),
696
- maxRetries: Number(options.maxRetries)
697
- });
981
+ const { key, client } = await requireSession(options);
698
982
  const spinner = useJson ? void 0 : ora({
699
983
  text: `Checking ${ip}...`,
700
984
  stream: process.stderr,
@@ -710,11 +994,15 @@ async function runCheck(ip, options) {
710
994
  if (options.verbose) {
711
995
  renderVerboseMeta(meta);
712
996
  }
997
+ if (isOfficialApi(options)) await warnAboutQuota(key, meta.quota);
713
998
  }
714
999
  process.exitCode = evaluateCiPolicy(data, options);
715
1000
  } catch (err) {
716
1001
  spinner?.stop();
717
- handleCheckError(err, options);
1002
+ const failure = await quotaFailure(err, client);
1003
+ reportFailure(failure, options);
1004
+ process.exitCode = failure.exitCode;
1005
+ await offerQuotaUpgrade(failure.info.code, options);
718
1006
  }
719
1007
  }
720
1008
  function evaluateCiPolicy(data, options) {
@@ -735,66 +1023,23 @@ function evaluateCiPolicy(data, options) {
735
1023
  }
736
1024
  return ExitCode.Success;
737
1025
  }
738
- function handleCheckError(err, options) {
739
- if (err instanceof NetRiskScanApiError) {
740
- if (err.code === ANONYMOUS_DAILY_LIMIT_CODE) {
741
- printAnonymousLimitError(err);
742
- } else {
743
- printApiError(err, { debug: options.debug });
744
- }
745
- process.exitCode = exitCodeForApiErrorCode(err.code);
746
- return;
747
- }
748
- if (err instanceof NetRiskScanNetworkError) {
749
- printNetworkError(err, { debug: options.debug });
750
- process.exitCode = ExitCode.ApiError;
751
- return;
752
- }
753
- if (options.debug && err instanceof Error) {
754
- process.stderr.write(`${err.stack ?? err.message}
755
- `);
756
- } else {
757
- process.stderr.write(`Error: ${err instanceof Error ? err.message : String(err)}
758
- `);
759
- }
760
- process.exitCode = ExitCode.GeneralError;
761
- }
762
1026
 
763
1027
  // src/commands/usage.ts
764
1028
  import ora2 from "ora";
765
1029
  function registerUsageCommand(program2) {
766
- 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(
1030
+ program2.command("usage").alias("quota").description("Show API usage and quota for the current monthly quota period").option("--api-key <key>", "Developer API key (overrides the environment and OS store)").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(
767
1031
  "after",
768
1032
  `
769
1033
  Notes:
770
- Requires a Developer API key. This reports Developer Account plan, billing
771
- period and quota, which has no anonymous equivalent - unlike check and batch,
772
- which work without a key.
1034
+ Requires a Developer API key with the usage:read scope.
773
1035
  `
774
1036
  ).action(async (options) => {
775
- await runUsage(options);
1037
+ await runCommand(options, () => runUsage(options));
776
1038
  });
777
1039
  }
778
1040
  async function runUsage(options) {
779
- const useJson = Boolean(options.json);
780
- let apiKey;
781
- try {
782
- apiKey = resolveRequiredApiKey(options.apiKey);
783
- } catch (err) {
784
- if (err instanceof NetRiskScanConfigError) {
785
- printConfigError(err);
786
- process.exitCode = ExitCode.AuthError;
787
- return;
788
- }
789
- throw err;
790
- }
791
- const client = new NetRiskScanClient({
792
- apiKey,
793
- baseUrl: resolveBaseUrl(options.baseUrl),
794
- timeout: Number(options.timeout),
795
- maxRetries: Number(options.maxRetries)
796
- });
797
- const spinner = useJson ? void 0 : ora2({
1041
+ const { key, client } = await requireSession(options);
1042
+ const spinner = options.json ? void 0 : ora2({
798
1043
  text: "Fetching usage...",
799
1044
  stream: process.stderr,
800
1045
  isEnabled: process.stderr.isTTY
@@ -802,7 +1047,7 @@ async function runUsage(options) {
802
1047
  try {
803
1048
  const { data, meta } = await client.getUsage();
804
1049
  spinner?.stop();
805
- if (useJson) {
1050
+ if (options.json) {
806
1051
  printJson(data);
807
1052
  } else {
808
1053
  renderUsageResult(data);
@@ -810,25 +1055,15 @@ async function runUsage(options) {
810
1055
  renderVerboseMeta(meta);
811
1056
  }
812
1057
  }
813
- } catch (err) {
1058
+ if (isOfficialApi(options)) await rearmQuotaWarnings(key, data.units, data.period.start);
1059
+ } finally {
814
1060
  spinner?.stop();
815
- if (err instanceof NetRiskScanApiError) {
816
- printApiError(err, { debug: options.debug });
817
- process.exitCode = exitCodeForApiErrorCode(err.code);
818
- return;
819
- }
820
- if (err instanceof NetRiskScanNetworkError) {
821
- printNetworkError(err, { debug: options.debug });
822
- process.exitCode = ExitCode.ApiError;
823
- return;
824
- }
825
- throw err;
826
1061
  }
827
1062
  }
828
1063
 
829
1064
  // src/commands/batch.ts
830
1065
  import { createReadStream } from "fs";
831
- import { createInterface } from "readline";
1066
+ import { createInterface as createInterface2 } from "readline";
832
1067
 
833
1068
  // src/utils/pool.ts
834
1069
  async function runPool(items, concurrency, worker) {
@@ -845,39 +1080,9 @@ async function runPool(items, concurrency, worker) {
845
1080
  return results;
846
1081
  }
847
1082
 
848
- // src/output/jsonl.ts
849
- function printJsonLine(data) {
850
- process.stdout.write(`${JSON.stringify(data)}
851
- `);
852
- }
853
-
854
1083
  // src/output/table.ts
855
1084
  import Table from "cli-table3";
856
1085
  import chalk3 from "chalk";
857
- function anonymousSummaryLines(results) {
858
- const remainings = [];
859
- const dailyLimits = [];
860
- let exhausted = false;
861
- for (const item of results) {
862
- if (item.ok) {
863
- const usage = item.result.usage;
864
- if (usage?.mode !== "anonymous") continue;
865
- if (typeof usage.remaining === "number") remainings.push(usage.remaining);
866
- if (typeof usage.dailyLimit === "number") dailyLimits.push(usage.dailyLimit);
867
- } else if (item.error.code === ANONYMOUS_DAILY_LIMIT_CODE) {
868
- exhausted = true;
869
- const limit = item.error.anonymousUsage?.dailyLimit;
870
- if (typeof limit === "number") dailyLimits.push(limit);
871
- }
872
- }
873
- if (!exhausted && remainings.length === 0) return [];
874
- const available = exhausted ? 0 : Math.min(...remainings);
875
- const lines = ["", chalk3.bold("Anonymous trial"), row("Available", formatNumber(available))];
876
- if (dailyLimits.length > 0) {
877
- lines.push(row("Daily Limit", formatNumber(Math.max(...dailyLimits))));
878
- }
879
- return lines;
880
- }
881
1086
  function renderBatchTable(results) {
882
1087
  const table = new Table({
883
1088
  head: ["IP", "Index", "Band", "Proxy", "Proxy Type", "VPN", "Tor", "Crawler", "Status"],
@@ -918,21 +1123,13 @@ function renderBatchTable(results) {
918
1123
  process.stdout.write(`
919
1124
  ${okCount} succeeded, ${failCount} failed
920
1125
  `);
921
- const anonymous = anonymousSummaryLines(results);
922
- if (anonymous.length > 0) {
923
- process.stdout.write(`${anonymous.join("\n")}
924
- `);
925
- }
926
1126
  }
927
1127
 
928
1128
  // src/commands/batch.ts
929
1129
  var MAX_CONCURRENCY = 20;
930
1130
  var DEFAULT_CONCURRENCY = 5;
931
1131
  function registerBatchCommand(program2) {
932
- program2.command("batch <file>").description("Check multiple IP addresses (client-side batch over GET /v1/ip-risk/{ip})").option(
933
- "--api-key <key>",
934
- "NetRiskScan API key (optional; uses the anonymous trial when omitted)"
935
- ).option("--base-url <url>", "Override the API base URL (advanced)").option(
1132
+ program2.command("batch <file>").description("Check multiple IP addresses (client-side batch over GET /v1/ip-risk/{ip})").option("--api-key <key>", "Developer API key (overrides the environment and OS store)").option("--base-url <url>", "Override the API base URL (advanced)").option(
936
1133
  "--concurrency <n>",
937
1134
  `Number of concurrent requests (default: ${DEFAULT_CONCURRENCY}, max: ${MAX_CONCURRENCY})`,
938
1135
  String(DEFAULT_CONCURRENCY)
@@ -940,14 +1137,8 @@ function registerBatchCommand(program2) {
940
1137
  "after",
941
1138
  `
942
1139
  Notes:
943
- This is a client-side batch: it sends individual GET /v1/ip-risk/{ip}
944
- requests with controlled concurrency. NetRiskScan does not currently
945
- offer a server-side batch endpoint. Make sure the selected concurrency
946
- complies with the limits shown in your NetRiskScan Developer Dashboard.
947
-
948
- An API key is optional. Without an API key, requests use the anonymous daily
949
- trial, metered by public IP. How many remain is decided by the server, not by
950
- this CLI, and is reported in the summary after the table.
1140
+ Developer API requires a valid API Key. This command sends individual
1141
+ GET /v1/ip-risk/{ip} requests using the selected concurrency.
951
1142
 
952
1143
  Input format:
953
1144
  One IP per line. Blank lines and lines starting with # are ignored.
@@ -958,12 +1149,12 @@ Examples:
958
1149
  $ netriskscan batch ips.txt --concurrency 10 --jsonl > results.jsonl
959
1150
  `
960
1151
  ).action(async (file, options) => {
961
- await runBatch(file, options);
1152
+ await runCommand(options, () => runBatch(file, options));
962
1153
  });
963
1154
  }
964
1155
  async function readIps(file) {
965
1156
  const stream = file === "-" ? process.stdin : createReadStream(file, "utf8");
966
- const rl = createInterface({ input: stream, crlfDelay: Infinity });
1157
+ const rl = createInterface2({ input: stream, crlfDelay: Infinity });
967
1158
  const ips = [];
968
1159
  for await (const rawLine of rl) {
969
1160
  const line = rawLine.trim();
@@ -985,34 +1176,16 @@ Check your NetRiskScan Developer Dashboard for your plan's concurrency limit.
985
1176
  }
986
1177
  return Math.floor(n);
987
1178
  }
988
- function toBatchError(err) {
989
- if (err instanceof NetRiskScanApiError) {
990
- return {
991
- code: err.code,
992
- message: err.message,
993
- requestId: err.requestId,
994
- anonymousUsage: err.anonymousUsage
995
- };
996
- }
997
- if (err instanceof NetRiskScanNetworkError) {
998
- return { code: "network_error", message: err.message, requestId: err.requestId };
999
- }
1000
- return { code: "unknown_error", message: err instanceof Error ? err.message : String(err) };
1001
- }
1002
1179
  async function runBatch(file, options) {
1003
1180
  const ips = await readIps(file);
1004
1181
  if (ips.length === 0) {
1005
- process.stderr.write("Error: no IP addresses found in input.\n");
1006
- process.exitCode = ExitCode.InvalidArgument;
1007
- return;
1182
+ throw new CliError("empty_input", "No IP addresses found in input.", ExitCode.InvalidArgument);
1008
1183
  }
1009
- const client = new NetRiskScanClient({
1010
- apiKey: resolveOptionalApiKey(options.apiKey),
1011
- baseUrl: resolveBaseUrl(options.baseUrl),
1012
- timeout: Number(options.timeout),
1013
- maxRetries: Number(options.maxRetries)
1014
- });
1184
+ const { key, client } = await requireSession(options, file !== "-");
1015
1185
  const concurrency = parseConcurrency(options.concurrency);
1186
+ let strongestQuota;
1187
+ let blocked;
1188
+ let quotaBlock;
1016
1189
  const results = await runPool(ips, concurrency, async (ip) => {
1017
1190
  if (!isValidIp(ip)) {
1018
1191
  return {
@@ -1021,21 +1194,52 @@ async function runBatch(file, options) {
1021
1194
  error: { code: "invalid_ip", message: `"${ip}" is not a valid IPv4 or IPv6 address.` }
1022
1195
  };
1023
1196
  }
1197
+ if (blocked) {
1198
+ return {
1199
+ ip,
1200
+ ok: false,
1201
+ error: {
1202
+ code: blocked.code,
1203
+ message: "Skipped after the server refused a preceding request.",
1204
+ attempted: false
1205
+ }
1206
+ };
1207
+ }
1024
1208
  try {
1025
- const { data } = await client.checkIp(ip);
1209
+ const { data, meta } = await client.checkIp(ip);
1210
+ if (meta.quota.remaining !== void 0 && (strongestQuota?.remaining === void 0 || meta.quota.remaining < strongestQuota.remaining)) {
1211
+ strongestQuota = meta.quota;
1212
+ }
1026
1213
  return { ip, ok: true, result: data };
1027
1214
  } catch (err) {
1028
- return { ip, ok: false, error: toBatchError(err) };
1215
+ const { code, message, requestId } = commandFailure(err).info;
1216
+ if (err instanceof NetRiskScanApiError) {
1217
+ if (isMonthlyQuotaError(code)) {
1218
+ quotaBlock ??= err;
1219
+ blocked ??= err;
1220
+ } else if (exitCodeForApiErrorCode(code) === ExitCode.AuthError) {
1221
+ blocked ??= err;
1222
+ }
1223
+ }
1224
+ return { ip, ok: false, error: { code, message, requestId } };
1029
1225
  }
1030
1226
  });
1227
+ const failure = quotaBlock ? await quotaFailure(quotaBlock, client) : void 0;
1031
1228
  if (options.jsonl) {
1032
1229
  for (const item of results) {
1230
+ if (failure && !item.ok && isMonthlyQuotaError(item.error.code)) {
1231
+ const { quota, plan, resetAt, upgradeUrl } = failure.info;
1232
+ Object.assign(item.error, { quota, plan, resetAt, upgradeUrl });
1233
+ }
1033
1234
  printJsonLine(item);
1034
1235
  }
1035
1236
  } else {
1036
1237
  renderBatchTable(results);
1238
+ if (failure) reportFailure(failure);
1239
+ else if (strongestQuota && isOfficialApi(options)) await warnAboutQuota(key, strongestQuota);
1037
1240
  }
1038
1241
  process.exitCode = computeBatchExitCode(results);
1242
+ if (failure && file !== "-") await offerQuotaUpgrade(failure.info.code, options);
1039
1243
  }
1040
1244
  function computeBatchExitCode(results) {
1041
1245
  const failures = results.filter((r) => !r.ok);
@@ -1046,27 +1250,253 @@ function computeBatchExitCode(results) {
1046
1250
  return ExitCode.ApiError;
1047
1251
  }
1048
1252
 
1253
+ // src/commands/auth.ts
1254
+ function registerAuthCommand(program2) {
1255
+ const auth = program2.command("auth").description("Manage the locally stored Developer API key");
1256
+ auth.command("save").description("Save an existing Developer API key in the OS credential store").option("--stdin", "Read the key from piped stdin instead of NETRISKSCAN_API_KEY").option("--json", "Output machine-readable JSON").action(
1257
+ (options) => runCommand(options, () => manageStore(() => saveKey(options)))
1258
+ );
1259
+ auth.command("show").description("Display the full stored API key in an interactive terminal").option("--json", "Return a machine-readable error without displaying the key").action(
1260
+ (options) => runCommand(options, () => manageStore(() => showKey(options)))
1261
+ );
1262
+ auth.command("status").description("Show authentication, key source, and current plan").option("--api-key <key>", "Check an explicit Developer API key").option("--json", "Output machine-readable JSON with a masked key").action((options) => runCommand(options, () => showStatus(options)));
1263
+ auth.command("logout").description("Remove the local key without revoking it at NetRiskScan").option("--json", "Output machine-readable JSON").action(
1264
+ (options) => runCommand(options, () => manageStore(() => logout(options)))
1265
+ );
1266
+ }
1267
+ async function manageStore(action) {
1268
+ try {
1269
+ await action();
1270
+ } catch (error) {
1271
+ if (error instanceof CredentialStoreUnavailable) {
1272
+ throw new CliError("credential_store_unavailable", error.message, ExitCode.AuthError);
1273
+ }
1274
+ throw error;
1275
+ }
1276
+ }
1277
+ async function readStdinKey() {
1278
+ if (process.stdin.isTTY) {
1279
+ throw new CliError(
1280
+ "piped_key_required",
1281
+ "Pipe the key from a secret manager into stdin.",
1282
+ ExitCode.InvalidArgument
1283
+ );
1284
+ }
1285
+ let input = "";
1286
+ for await (const chunk of process.stdin) {
1287
+ input += String(chunk);
1288
+ if (input.length > 4096) {
1289
+ throw new CliError(
1290
+ "invalid_api_key",
1291
+ "The supplied API key is too long.",
1292
+ ExitCode.AuthError
1293
+ );
1294
+ }
1295
+ }
1296
+ return validateKey(input.trim());
1297
+ }
1298
+ async function saveKey(options) {
1299
+ const key = options.stdin ? await readStdinKey() : suppliedKey()?.key;
1300
+ if (!key) {
1301
+ throw new CliError(
1302
+ "api_key_required",
1303
+ "Supply an existing API key through NETRISKSCAN_API_KEY or --stdin.",
1304
+ ExitCode.AuthError,
1305
+ WEB_PAGES.keys
1306
+ );
1307
+ }
1308
+ const client = createClient(key, { baseUrl: DEFAULT_BASE_URL, maxRetries: "0" });
1309
+ try {
1310
+ await client.getUsage();
1311
+ } catch (error) {
1312
+ if (!(error instanceof NetRiskScanApiError && error.status === 403 && error.code === "scope_not_allowed"))
1313
+ throw error;
1314
+ }
1315
+ await credentials.save(key);
1316
+ process.env.NETRISKSCAN_API_KEY = key;
1317
+ if (options.json) printJson({ saved: true, storage: "os_credential_store" });
1318
+ else
1319
+ process.stdout.write(
1320
+ "API key saved in the OS credential store. Rerun your original command.\n"
1321
+ );
1322
+ }
1323
+ async function showKey(options) {
1324
+ if (!isInteractive(options.json)) {
1325
+ throw new CliError(
1326
+ "interactive_terminal_required",
1327
+ "Viewing a full API key requires an interactive terminal.",
1328
+ ExitCode.InvalidArgument
1329
+ );
1330
+ }
1331
+ const key = await credentials.read();
1332
+ if (!key) {
1333
+ throw new CliError(
1334
+ "api_key_required",
1335
+ "No stored API key. Create a key in the Developer Console and run auth save.",
1336
+ ExitCode.AuthError,
1337
+ WEB_PAGES.keys
1338
+ );
1339
+ }
1340
+ validateKey(key);
1341
+ let plan = "Unavailable";
1342
+ try {
1343
+ const { data } = await createClient(key, {
1344
+ baseUrl: DEFAULT_BASE_URL,
1345
+ maxRetries: "0"
1346
+ }).getUsage();
1347
+ plan = data.plan;
1348
+ } catch {
1349
+ }
1350
+ process.stdout.write(
1351
+ `${row("Plan", plan)}
1352
+ ${row("Developer account", "See Developer Console")}
1353
+
1354
+ Your stored API key:
1355
+ ${key}
1356
+ `
1357
+ );
1358
+ }
1359
+ async function showStatus(options) {
1360
+ const supplied = suppliedKey(options.apiKey);
1361
+ let stored = null;
1362
+ let storage = "empty";
1363
+ try {
1364
+ stored = await credentials.read();
1365
+ if (stored) storage = "saved";
1366
+ } catch (error) {
1367
+ if (!(error instanceof CredentialStoreUnavailable)) throw error;
1368
+ storage = "unavailable";
1369
+ }
1370
+ const key = supplied?.key ?? (isOfficialApi(options) ? stored : null);
1371
+ let status = "not_configured";
1372
+ let plan;
1373
+ let failure;
1374
+ if (key) {
1375
+ try {
1376
+ const { data } = await createClient(key, { ...options, maxRetries: "0" }).getUsage();
1377
+ status = "active";
1378
+ plan = data.plan;
1379
+ } catch (error) {
1380
+ failure = commandFailure(error);
1381
+ status = failure.info.code;
1382
+ process.exitCode = failure.exitCode;
1383
+ }
1384
+ }
1385
+ const details = {
1386
+ configured: Boolean(key),
1387
+ status,
1388
+ source: supplied?.source ?? (key ? "os_credential_store" : void 0),
1389
+ key: key ? redactApiKey(key) : void 0,
1390
+ plan,
1391
+ storage,
1392
+ error: failure?.info
1393
+ };
1394
+ if (options.json) {
1395
+ printJson(details);
1396
+ } else {
1397
+ const lines = [
1398
+ row("Authentication", status),
1399
+ row("Local credential", storage),
1400
+ row("Key source", details.source ?? "Unavailable"),
1401
+ row("Key", details.key ?? "Unavailable"),
1402
+ row("Plan", plan ?? "Unavailable"),
1403
+ row("Account / key name", "See Developer Console")
1404
+ ];
1405
+ if (failure) lines.push(failure.info.message);
1406
+ if (!key) lines.push(WEB_PAGES.keys);
1407
+ process.stdout.write(`${lines.join("\n")}
1408
+ `);
1409
+ }
1410
+ }
1411
+ async function logout(options) {
1412
+ const removed = await credentials.remove();
1413
+ const environmentKeyConfigured = Boolean(process.env.NETRISKSCAN_API_KEY);
1414
+ if (options.json) {
1415
+ printJson({ removed, serverKeyRevoked: false, environmentKeyConfigured });
1416
+ } else {
1417
+ const local = removed ? "Removed the local credential." : "No local credential was saved.";
1418
+ process.stdout.write(
1419
+ `${local} The server API key remains valid until revoked in the Developer Console.
1420
+ `
1421
+ );
1422
+ if (environmentKeyConfigured)
1423
+ process.stdout.write(
1424
+ "NETRISKSCAN_API_KEY is still set in this shell. Clear it in the parent shell to stop using it.\n"
1425
+ );
1426
+ }
1427
+ }
1428
+
1429
+ // src/commands/billing.ts
1430
+ function registerBillingCommands(program2) {
1431
+ for (const [name, page, description] of [
1432
+ ["upgrade", "plans", "Open NetRiskScan plans and upgrades in your browser"],
1433
+ ["billing", "billing", "Open NetRiskScan subscription and billing management"]
1434
+ ]) {
1435
+ program2.command(name).description(description).option("--api-key <key>", "Developer API key (overrides the environment and OS store)").option("--json", "Return a machine-readable browser action with its URL").action(
1436
+ (options) => runCommand(options, async () => {
1437
+ const url = WEB_PAGES[page];
1438
+ if (!isInteractive(options.json)) {
1439
+ throw new CliError(
1440
+ "browser_required",
1441
+ "Continue in a browser using the Developer Console.",
1442
+ ExitCode.InvalidArgument,
1443
+ url
1444
+ );
1445
+ }
1446
+ if (!isOfficialApi(options)) {
1447
+ throw new CliError(
1448
+ "official_api_required",
1449
+ "This command requires the official NetRiskScan Developer API.",
1450
+ ExitCode.InvalidArgument,
1451
+ url
1452
+ );
1453
+ }
1454
+ const { client } = await requireSession(options, false);
1455
+ const { data } = await client.getUsage();
1456
+ process.stderr.write(`Current plan: ${data.plan}
1457
+ `);
1458
+ if (!await openBrowser(page)) {
1459
+ throw new CliError(
1460
+ "browser_open_failed",
1461
+ "Could not open the default browser. Open the URL directly.",
1462
+ ExitCode.GeneralError,
1463
+ url
1464
+ );
1465
+ }
1466
+ process.stdout.write(
1467
+ `Opened ${url}
1468
+ Sign in with the account that owns this key. Run npx netriskscan-cli usage to refresh the plan and quota after your changes.
1469
+ `
1470
+ );
1471
+ })
1472
+ );
1473
+ }
1474
+ }
1475
+
1049
1476
  // src/cli.ts
1050
- var __dirname = dirname(fileURLToPath(import.meta.url));
1051
- var pkg = JSON.parse(readFileSync(join(__dirname, "..", "package.json"), "utf8"));
1477
+ var __dirname = dirname2(fileURLToPath(import.meta.url));
1478
+ var pkg = JSON.parse(readFileSync(join2(__dirname, "..", "package.json"), "utf8"));
1052
1479
  var program = new Command();
1053
1480
  program.name("netriskscan").description(
1054
- "Query IP risk, network intelligence and reputation data from the NetRiskScan Developer API."
1481
+ "Query IP risk and network intelligence, manage your API key, and view developer quota."
1055
1482
  ).version(pkg.version, "-V, --version", "Show the CLI version").addHelpText(
1056
1483
  "after",
1057
1484
  `
1058
1485
  Examples:
1059
- $ netriskscan check 1.1.1.1 # no account or API key needed
1486
+ $ netriskscan check 1.1.1.1
1060
1487
  $ netriskscan check 1.1.1.1 --json
1061
- $ netriskscan usage # needs an API key
1488
+ $ netriskscan quota
1062
1489
  $ netriskscan batch ips.txt --jsonl
1490
+ $ netriskscan auth status
1491
+ $ netriskscan upgrade
1063
1492
 
1064
- check and batch work with no setup at all: without an API key they use the
1065
- anonymous daily trial, metered by public IP. The server reports how many
1066
- requests are left; the CLI never estimates it.
1493
+ Developer API requires a valid API Key. Credentials are resolved from
1494
+ --api-key, NETRISKSCAN_API_KEY, then the OS credential store.
1495
+ Without a key, an interactive query opens the Developer Console for setup.
1496
+ Sign in there, create a key and run "netriskscan auth save".
1067
1497
 
1068
1498
  Environment variables:
1069
- NETRISKSCAN_API_KEY Optional for check/batch; required for account usage.
1499
+ NETRISKSCAN_API_KEY Supply a Developer API key from a secret manager in CI.
1070
1500
 
1071
1501
  NetRiskScan provides diagnostic network intelligence. Results should not be
1072
1502
  treated as proof of malicious activity or used as the sole basis for legal,
@@ -1078,6 +1508,8 @@ Learn more: https://github.com/TeamQQ/netriskscan-cli
1078
1508
  registerCheckCommand(program);
1079
1509
  registerUsageCommand(program);
1080
1510
  registerBatchCommand(program);
1511
+ registerAuthCommand(program);
1512
+ registerBillingCommands(program);
1081
1513
  program.exitOverride();
1082
1514
  try {
1083
1515
  await program.parseAsync(process.argv);