netriskscan-cli 1.4.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,35 @@
1
+ # [1.6.0](https://github.com/TeamQQ/netriskscan-cli/compare/v1.5.0...v1.6.0) (2026-11-17)
2
+
3
+
4
+ ### Features
5
+
6
+ * support IP intelligence schema 1.6.0 fields ([#1](https://github.com/TeamQQ/netriskscan-cli/issues/1)) ([7bf9f15](https://github.com/TeamQQ/netriskscan-cli/commit/7bf9f15b4b6c36833d502d09c05543d492c72a4d))
7
+
8
+ # [1.5.0](https://github.com/TeamQQ/netriskscan-cli/compare/v1.4.0...v1.5.0) (2026-09-02)
9
+
10
+
11
+ ### Features
12
+
13
+ * add geolocation and risk reasons to CLI ([7a47c02](https://github.com/TeamQQ/netriskscan-cli/commit/7a47c022c70ca108025edee7c24b9b851cbe8bde))
14
+
15
+ ### Details
16
+
17
+ - IP geolocation output for `check` (`Location`: country, region, city, time zone), shown
18
+ only for the fields the server actually resolved
19
+ - Public risk-reason rendering for `check` (`Risk Reasons`), shown only when the server
20
+ sent any
21
+ - SDK typings for `location` and `risk.reasons`: `IpLocation` and `RiskReason`, both
22
+ exported from the package entry point
23
+ - Forward-compatible handling of future reason codes, categories and severities - an
24
+ unrecognised value renders instead of throwing or being dropped
25
+
26
+ ### Notes
27
+
28
+ - `--json` / `--jsonl` remain a passthrough of the API response, so both new fields appear
29
+ there in their raw machine form with no remapping
30
+ - A server that predates either field still works unchanged, and neither field affects
31
+ `risk.index`, `--fail-below`, `--fail-on`, or any exit code
32
+
1
33
  # [1.4.0](https://github.com/TeamQQ/netriskscan-cli/compare/v1.3.0...v1.4.0) (2026-09-02)
2
34
 
3
35
 
package/README.md CHANGED
@@ -1,7 +1,9 @@
1
1
  # NetRiskScan CLI
2
2
 
3
- The official command-line client and TypeScript SDK for [NetRiskScan](https://www.netriskscan.com) -
4
- IP reputation, risk assessment, and network intelligence directly from your terminal.
3
+ Command-line client and TypeScript SDK for [NetRiskScan](https://www.netriskscan.com) —
4
+ an IP lookup CLI for IP reputation, IP risk, proxy/VPN/Tor and datacenter detection, and
5
+ network intelligence (ASN, organization, verified search-crawler identity), usable as a
6
+ command line IP lookup from your terminal or the Developer API.
5
7
 
6
8
  [![CI](https://github.com/TeamQQ/netriskscan-cli/actions/workflows/ci.yml/badge.svg)](https://github.com/TeamQQ/netriskscan-cli/actions/workflows/ci.yml)
7
9
  [![npm version](https://img.shields.io/npm/v/netriskscan-cli.svg)](https://www.npmjs.com/package/netriskscan-cli)
@@ -10,65 +12,34 @@ IP reputation, risk assessment, and network intelligence directly from your term
10
12
 
11
13
  [Website](https://www.netriskscan.com) · [npm](https://www.npmjs.com/package/netriskscan-cli) · [Developer API](#developer-api) · [Official resources](#official-resources)
12
14
 
15
+ <p align="center">
16
+ <img src="./demo/netriskscan-demo.gif" alt="netriskscan-cli check 17.241.200.160 in a terminal, showing IP, Index, Band, Network Type, Profile, Service, ASN, Organization, Proxy/VPN/Tor signals and verified Search Crawler identity" width="700" />
17
+ </p>
18
+
13
19
  ```bash
14
20
  npx netriskscan-cli check 17.241.200.160
15
21
  ```
16
22
 
17
- ```text
18
- NetRiskScan
19
-
20
- IP 17.241.200.160
21
- Index 97
22
- Band excellent
23
- Assessment complete
24
-
25
- Network
26
- Type public_infrastructure
27
- Profile search_crawler
28
- Service Applebot
29
- Connection direct
30
- ASN AS714
31
- Organization Apple Inc.
32
-
33
- Signals
34
- Proxy No
35
- Proxy Type -
36
- VPN No
37
- Tor No
38
- Datacenter No
39
- Scanner Unknown
40
- Abuse No
41
-
42
- Identity
43
- Search Crawler Yes
44
- Crawler Applebot
45
-
46
- Usage
47
- Available 29
48
- Daily Limit 30
49
- Reset 2026-08-29 00:00 UTC
50
-
51
- Request ID req_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
52
-
53
- Explore
54
- Web https://www.netriskscan.com
55
- GitHub https://github.com/TeamQQ/netriskscan-cli
56
- ```
23
+ **No signup. No API key. No configuration required.** The command above runs on a clean
24
+ machine and returns a real result from the live API, metered by an anonymous daily
25
+ allowance (currently 30 checks per public IP per UTC day - see
26
+ [Anonymous trial](#anonymous-trial)). Add a free [API key](#getting-an-api-key) for more.
57
27
 
58
- **No account or API key required** for the anonymous trial - the command above works on a
59
- clean machine. The `Usage` block is the server telling you how much of today's free
60
- allowance is left; the CLI never estimates it. Add an API key when you need more
61
- (see [Getting an API key](#getting-an-api-key)).
62
-
63
- Example output - actual values come from the live API and can change as reputation and
64
- threat data changes.
28
+ The values shown above and in the recording come from the live API and change as
29
+ reputation and threat data changes - see [IP risk check](#ip-risk-check) for a
30
+ field-by-field reference.
65
31
 
66
32
  ## Why NetRiskScan?
67
33
 
68
34
  - Known infrastructure identification for services such as search crawlers and public
69
35
  infrastructure, instead of treating every address as a generic business or datacenter IP
70
36
  - Proxy, VPN, Tor, abuse, blacklist and threat signals
71
- - One normalized NetRiskScan Index instead of raw provider scores
37
+ - Network-level IP geolocation (country, region, city, continent, postal code,
38
+ approximate coordinates, time zone)
39
+ - Network attribution: the operator's primary domain and the CIDR range containing the
40
+ address (IP Intelligence Schema 1.6.0)
41
+ - Public risk reasons: the server's own explanation of _why_ an address scored as it did
42
+ - One normalized NetRiskScan Index instead of raw provider scores - higher is cleaner
72
43
  - `unknown` and `not applicable` states are preserved, never collapsed into "false"
73
44
  - Anonymous daily trial: run your first check with no account, no key, no configuration
74
45
  - Human-readable CLI output plus JSON / JSONL for scripts, batches and CI
@@ -90,7 +61,9 @@ Powered by the [NetRiskScan Developer API](#developer-api).
90
61
 
91
62
  - [Why NetRiskScan?](#why-netriskscan)
92
63
  - [Introduction](#introduction)
64
+ - [IP Lookup and Reputation](#ip-lookup-and-reputation)
93
65
  - [Features](#features)
66
+ - [Use Cases](#use-cases)
94
67
  - [Installation](#installation)
95
68
  - [Anonymous trial](#anonymous-trial)
96
69
  - [Getting an API key](#getting-an-api-key)
@@ -108,6 +81,7 @@ Powered by the [NetRiskScan Developer API](#developer-api).
108
81
  - [SDK usage](#sdk-usage)
109
82
  - [Security](#security)
110
83
  - [Developer API](#developer-api)
84
+ - [FAQ](#faq)
111
85
  - [Official resources](#official-resources)
112
86
  - [Contributing](#contributing)
113
87
  - [License](#license)
@@ -126,6 +100,19 @@ This is a read-only diagnostic tool. It does not make decisions for you, and the
126
100
  never recomputes or approximates a risk score client-side - the `risk.index` returned by
127
101
  the server is always the single source of truth.
128
102
 
103
+ **A higher NetRiskScan Index means a cleaner address, not a riskier one.** `95` is
104
+ `excellent`; `42` is `poor`. It is a cleanliness score, not a threat score - never read
105
+ `90` as "high risk".
106
+
107
+ ## IP Lookup and Reputation
108
+
109
+ Use `netriskscan check` as a command-line IP lookup and reputation tool: give it an
110
+ IPv4 or IPv6 address and get back the NetRiskScan Index, ASN, organization, network
111
+ type and security signals in one call. It doubles as an IP risk checker CLI and IP
112
+ reputation checker CLI with no account or API key at all, via the
113
+ [anonymous trial](#anonymous-trial) - see [IP risk check](#ip-risk-check) for the full
114
+ field reference.
115
+
129
116
  ## Features
130
117
 
131
118
  - `check` and `batch` with no API key at all, via the anonymous daily trial
@@ -133,6 +120,10 @@ the server is always the single source of truth.
133
120
  - IPv4 and IPv6 support
134
121
  - Proxy type classification (residential, ISP, mobile, datacenter) for detected proxies,
135
122
  and verified search crawler identity (Googlebot, Bingbot, Applebot, ...)
123
+ - IP geolocation (country, region, city, continent, postal code, approximate
124
+ coordinates) and server-generated risk reasons in `check`, `--json` and `--jsonl`
125
+ - Network owner domain and CIDR range (IP Intelligence Schema 1.6.0 - purely additive,
126
+ older servers still fully supported)
136
127
  - Human-readable terminal output, `--json`, and `--jsonl` (batch) modes
137
128
  - Correct three-state handling of risk flags (`true` / `false` / `null` - never coerced)
138
129
  - CI-friendly exit codes and `--fail-below` / `--fail-on` policy gates
@@ -141,9 +132,23 @@ the server is always the single source of truth.
141
132
  - Zero telemetry
142
133
  - A typed `NetRiskScanClient` SDK you can import directly in Node.js/TypeScript
143
134
 
135
+ ## Use Cases
136
+
137
+ - Manual investigation of a suspicious IP during an incident or support ticket
138
+ - Checking a new VPS or server's IP reputation before deployment or DNS cutover - a
139
+ quick VPS IP reputation checker for ops and security teams
140
+ - Screening proxy, VPN and Tor traffic in login, checkout or signup flows
141
+ - Running a bulk IP reputation checker over log exports or CIDR-derived IP lists with
142
+ `batch`
143
+ - Gating a CI/CD pipeline or deploy job on `--fail-below` / `--fail-on` before trusting
144
+ an IP
145
+ - One step in an OSINT IP lookup workflow alongside other tools - NetRiskScan reports
146
+ network intelligence signals, not a full OSINT investigation platform
147
+ - Piping `--json` / `--jsonl` output into shell scripts, SIEM ingestion or log pipelines
148
+
144
149
  ## Installation
145
150
 
146
- Run it without installing anything:
151
+ Run it without installing anything - a zero-setup terminal IP lookup:
147
152
 
148
153
  ```bash
149
154
  npx netriskscan-cli check 1.1.1.1
@@ -267,6 +272,11 @@ netriskscan check <ip> [options]
267
272
  Calls `GET /v1/ip-risk/{ip}` - no query string parameters are ever sent. An API key is
268
273
  optional; without one the request uses the [anonymous trial](#anonymous-trial).
269
274
 
275
+ Supports **IP Intelligence Schema 1.6.0**: `network.domain` / `network.range` and the
276
+ extended `location` fields (continent, postal code, approximate coordinates). The
277
+ upgrade is purely additive - a server that predates these fields still works unchanged,
278
+ and `--json` / `--jsonl` pass every field through verbatim.
279
+
270
280
  ```bash
271
281
  $ netriskscan check 1.1.1.1
272
282
 
@@ -277,11 +287,21 @@ Index 92
277
287
  Band excellent
278
288
  Assessment complete
279
289
 
290
+ Risk Reasons
291
+ Public Infrastructure info
292
+
280
293
  Network
281
294
  Type public_infrastructure
282
295
  Connection direct
283
296
  ASN AS13335
284
297
  Organization Cloudflare, Inc.
298
+ Domain cloudflare.com
299
+ Network Range 1.1.1.0/24
300
+
301
+ Location
302
+ Country United States (US)
303
+ Continent North America (NA)
304
+ Time Zone America/Los_Angeles
285
305
 
286
306
  Signals
287
307
  Proxy No
@@ -302,6 +322,14 @@ Request ID req_xxxxxxxx
302
322
  Output above is illustrative of the format - actual values always come from the live
303
323
  API response.
304
324
 
325
+ ### Proxy, VPN and Tor Signals
326
+
327
+ `netriskscan check` doubles as a proxy detection CLI, VPN detection CLI and Tor
328
+ detection CLI in one command: the `Signals` block reports `Proxy`, `VPN`, `Tor`,
329
+ `Datacenter`, `Scanner` and `Abuse` as independent three-state flags
330
+ (`true` / `false` / `unknown`), so it also works as a datacenter IP checker without
331
+ collapsing an unresolved signal into a false negative.
332
+
305
333
  ### Proxy Type
306
334
 
307
335
  `Proxy Type` is a classification detail for an address already detected as a proxy - it
@@ -329,6 +357,116 @@ itself; it only displays the classification the API already returned.** A verifi
329
357
  crawler is identity information, not a risk signal, so it never affects `risk.index`,
330
358
  `--fail-on`, or the CLI's exit code.
331
359
 
360
+ ### Network Domain and Range
361
+
362
+ Schema 1.6.0 adds two network-attribution rows, shown only when the server resolved
363
+ them:
364
+
365
+ ```text
366
+ Network
367
+ Type public_infrastructure
368
+ Connection direct
369
+ ASN AS15169
370
+ Organization Google LLC
371
+ Domain google.com
372
+ Network Range 8.8.8.0/24
373
+ ```
374
+
375
+ - `Domain` is the **operating organisation's trusted primary domain** (e.g.
376
+ `google.com`, `cloudflare.com`) - the operator itself, not a website hosted on the
377
+ address and not a cloud customer's domain. The CLI never infers it from the ASN,
378
+ organization or reverse DNS; it prints only what the server sent.
379
+ - `Network Range` is the **canonical CIDR prefix containing the queried address** (IPv4
380
+ or IPv6, e.g. `8.8.8.0/24` or `2001:4860:4840::/42`). It is the server's answer, shown
381
+ verbatim - the CLI never computes, widens or guesses a range itself.
382
+
383
+ Both fields are optional and nullable: `null`, an empty value, or a server that predates
384
+ Schema 1.6.0 simply prints no row. Neither field affects `risk.index` or any exit code.
385
+
386
+ ### Risk Reasons
387
+
388
+ `risk.reasons` is the server's own explanation of the assessment it just returned - the
389
+ CLI renders it and **never derives, infers, or invents a reason** from the flags it can
390
+ see. `flags.tor: true` is not enough to claim `TOR_EXIT_NODE`; only the server can say
391
+ whether an address is an exit node or an ordinary relay, and the CLI prints whichever it
392
+ actually sent.
393
+
394
+ ```text
395
+ Risk Reasons
396
+ Residential Proxy Detected high
397
+ ```
398
+
399
+ Reasons are **not proof of fraud or malicious activity**. `VPN_DETECTED` means a VPN was
400
+ detected, nothing more. Nor are they all negative: `VERIFIED_SEARCH_CRAWLER`,
401
+ `PUBLIC_INFRASTRUCTURE` and `RESIDENTIAL_NETWORK` are exactly the reasons an address
402
+ scores _well_, which is why the block is called `Risk Reasons` and not "threats".
403
+
404
+ ```text
405
+ Risk Reasons
406
+ Verified Search Crawler info
407
+ Public Infrastructure info
408
+ ```
409
+
410
+ Each reason carries a `code`, a `category` and a `severity`. The default output shows a
411
+ readable label (`Residential Proxy Detected`) and the severity; `--json` / `--jsonl`
412
+ always carry the raw machine values (`RESIDENTIAL_PROXY_DETECTED`, `anonymity`, `high`).
413
+ The vocabulary is **additive** - the API can introduce new codes at any time, and an
414
+ already-installed CLI renders an unfamiliar one rather than failing or hiding it.
415
+
416
+ Reasons are display-only: they never affect `risk.index`, `--fail-below`, `--fail-on`, or
417
+ the exit code. A server that predates the field simply omits it, and the section is not
418
+ shown when there is nothing to explain.
419
+
420
+ ### Location
421
+
422
+ `location` is **network-level IP geolocation**: where the address is registered and
423
+ routed. As an IP geolocation CLI, `netriskscan check` reports this network-level data
424
+ only - it is **not** device or GPS location, and not the precise physical location of
425
+ whoever is using the address - a city can be the operator's aggregation point rather than
426
+ the user's town.
427
+
428
+ ```text
429
+ Location
430
+ Country United States (US)
431
+ Region Illinois (IL)
432
+ City Chicago
433
+ Continent North America (NA)
434
+ Postal Code 60666
435
+ Coordinates 41.8781, -87.6298
436
+ Time Zone America/Chicago
437
+ ```
438
+
439
+ Every field is independently optional. Geo resolution is often partial, and the CLI shows
440
+ only what the server actually resolved rather than padding the block with placeholders -
441
+ a country-only result prints one row, and an address with no location at all prints no
442
+ `Location` section at all:
443
+
444
+ ```text
445
+ Location
446
+ Country Germany (DE)
447
+ Time Zone Europe/Berlin
448
+ ```
449
+
450
+ Schema 1.6.0 extends the block with three more rows, each shown only when the server
451
+ resolved it:
452
+
453
+ - `Continent` - the UN geoscheme continent name and code, formatted exactly like
454
+ `Country` and `Region` (`North America (NA)`).
455
+ - `Postal Code` - the data source's postal code, printed verbatim as a string. Leading
456
+ zeros survive; it is never reformatted or parsed into a number.
457
+ - `Coordinates` - `latitude, longitude`, shown only when the server sent **both** as
458
+ numbers. This is an **approximate network location**, not a device GPS fix, and a
459
+ legitimate `0` coordinate is preserved (`0, 0` renders as `0, 0`).
460
+
461
+ Anycast networks (public DNS resolvers, some CDN edges), unlocatable addresses and
462
+ private/reserved addresses may return `null` for coordinates and postal code - an
463
+ anycast address has no single node position. The CLI then prints no row rather than a
464
+ fabricated value, and never completes, guesses or computes geography client-side.
465
+
466
+ Names and codes are server-owned strings, printed verbatim: never translated,
467
+ re-capitalized, or derived from one another. `location` has no effect on the risk
468
+ assessment or on any exit code.
469
+
332
470
  ### Addresses that can't be scored
333
471
 
334
472
  Private, loopback, reserved, and other non-routable addresses still return `HTTP 200`,
@@ -404,6 +542,10 @@ Supports `--json`, `--verbose`, `--api-key`, `--timeout`, and `--max-retries` ju
404
542
  netriskscan batch <file> [options]
405
543
  ```
406
544
 
545
+ Use `netriskscan batch` as a batch IP lookup CLI or bulk IP reputation checker: point
546
+ it at a file of one IP per line and get a risk result for every address, with
547
+ concurrency control and JSONL output for pipelines.
548
+
407
549
  **Important:** NetRiskScan does not currently expose a server-side batch endpoint. This
408
550
  command is a **client-side batch**: it sends individual `GET /v1/ip-risk/{ip}` requests
409
551
  with a controlled concurrency limit. An API key is optional here too - without one, every
@@ -472,6 +614,8 @@ stream.
472
614
 
473
615
  ## JSON output
474
616
 
617
+ Add `--json` to turn `check` into a JSON IP lookup CLI for scripts and pipelines:
618
+
475
619
  ```bash
476
620
  netriskscan check 1.1.1.1 --json
477
621
  ```
@@ -481,13 +625,35 @@ coerced to `false`, `0`, or a string):
481
625
 
482
626
  ```json
483
627
  {
484
- "requestId": "req_8f3ab21c9d",
485
- "risk": { "index": 72, "band": "good", "assessmentGrade": "complete" },
628
+ "requestId": "req_example",
629
+ "risk": {
630
+ "index": 95,
631
+ "band": "excellent",
632
+ "assessmentGrade": "complete",
633
+ "reasons": [{ "code": "VERIFIED_SEARCH_CRAWLER", "category": "identity", "severity": "info" }]
634
+ },
486
635
  "network": {
487
- "type": "residential",
488
- "connectionType": "isp",
489
- "asn": "AS4134",
490
- "organization": "China Telecom"
636
+ "type": "public_infrastructure",
637
+ "profile": "search_crawler",
638
+ "service": "Googlebot",
639
+ "connectionType": "direct",
640
+ "asn": "AS15169",
641
+ "organization": "Google LLC",
642
+ "domain": "google.com",
643
+ "range": "66.249.66.0/24"
644
+ },
645
+ "location": {
646
+ "countryCode": "US",
647
+ "country": "United States",
648
+ "regionCode": "CA",
649
+ "region": "California",
650
+ "city": "Mountain View",
651
+ "timeZone": "America/Los_Angeles",
652
+ "continentCode": "NA",
653
+ "continent": "North America",
654
+ "postalCode": "94043",
655
+ "latitude": 37.422,
656
+ "longitude": -122.084
491
657
  },
492
658
  "flags": {
493
659
  "proxy": false,
@@ -495,19 +661,25 @@ coerced to `false`, `0`, or a string):
495
661
  "vpn": false,
496
662
  "tor": false,
497
663
  "datacenter": false,
498
- "scanner": false,
664
+ "scanner": null,
499
665
  "abuse": false,
500
- "searchCrawler": false,
501
- "searchCrawlerName": null
666
+ "searchCrawler": true,
667
+ "searchCrawlerName": "Googlebot"
502
668
  }
503
669
  }
504
670
  ```
505
671
 
506
- `flags.proxyType` (when `flags.proxy` is `true`), `flags.searchCrawler`, and
507
- `flags.searchCrawlerName` carry the server's raw machine values in `--json`/`--jsonl` -
508
- e.g. `"residential_proxy"`, never the `Residential Proxy` label shown in the default
509
- terminal output. A server that predates these fields simply omits the keys; the CLI
510
- does not synthesize them.
672
+ `risk.reasons`, `location`, `flags.proxyType` (when `flags.proxy` is `true`),
673
+ `flags.searchCrawler`, and `flags.searchCrawlerName` carry the server's raw machine values
674
+ in `--json`/`--jsonl` - e.g. `"RESIDENTIAL_PROXY_DETECTED"` and `"residential_proxy"`,
675
+ never the `Residential Proxy Detected` / `Residential Proxy` labels shown in the default
676
+ terminal output. A server that predates these fields simply omits the keys; the CLI does
677
+ not synthesize them.
678
+
679
+ The Schema 1.6.0 fields (`network.domain`, `network.range`, `location.continentCode`,
680
+ `location.continent`, `location.postalCode`, `location.latitude`, `location.longitude`)
681
+ pass through the same way: `null` stays `null` (never `0`, `false` or `""`), a legitimate
682
+ `0` coordinate stays `0`, and `postalCode` stays a string.
511
683
 
512
684
  In `--json` mode there is no spinner, no ANSI color, and no banner - stdout carries only
513
685
  the JSON. Errors always go to stderr, so this composes cleanly:
@@ -525,7 +697,7 @@ netriskscan batch ips.txt --jsonl
525
697
  One JSON object per line, one line per input IP:
526
698
 
527
699
  ```json
528
- {"ip":"1.1.1.1","ok":true,"result":{"requestId":"req_...","risk":{...},"network":{...},"flags":{...}}}
700
+ {"ip":"1.1.1.1","ok":true,"result":{"requestId":"req_...","risk":{...,"reasons":[...]},"network":{...},"location":{...},"flags":{...}}}
529
701
  {"ip":"8.8.8.8","ok":true,"result":{...}}
530
702
  {"ip":"bad-ip","ok":false,"error":{"code":"invalid_ip","message":"..."}}
531
703
  ```
@@ -534,9 +706,16 @@ Designed for `netriskscan batch ips.txt --jsonl > results.jsonl` and downstream
534
706
  line-oriented processing (`jq`, `grep`, log pipelines, etc.). A failed IP never causes
535
707
  the whole batch to fail or drops output for the rest.
536
708
 
709
+ The envelope (`ip`, `ok`, `result` / `error`) belongs to the CLI; everything under
710
+ `result` is the API response verbatim, so `location`, `risk.reasons` and the Schema 1.6.0
711
+ network/geo fields (`domain`, `range`, continent, postal code, coordinates) appear there
712
+ untouched. The default batch table deliberately stays narrow - it grows no country, city,
713
+ domain, range or reason columns - so use `--jsonl` when you need the full record.
714
+
537
715
  ## CI/CD
538
716
 
539
- Use `check` with policy flags as a build/deploy gate:
717
+ `--fail-below` and `--fail-on` turn `check` into an IP reputation CI check: use it
718
+ with policy flags as a build/deploy gate:
540
719
 
541
720
  ```bash
542
721
  netriskscan check "$TARGET_IP" --fail-below 60
@@ -719,6 +898,39 @@ const usage = await client.getUsage();
719
898
  console.log(usage.data.units.remaining);
720
899
  ```
721
900
 
901
+ The response types are exported too, including `IpLocation` and `RiskReason`:
902
+
903
+ ```ts
904
+ import type { IpRiskResponse, IpLocation, RiskReason } from "netriskscan-cli";
905
+
906
+ const { data } = await client.checkIp("66.249.87.5");
907
+
908
+ for (const reason of data.risk.reasons ?? []) {
909
+ console.log(reason.code, reason.severity);
910
+ }
911
+ console.log(data.location?.country ?? "unknown");
912
+ console.log(data.network.domain ?? "unknown");
913
+ console.log(data.network.range ?? "unknown");
914
+
915
+ // Coordinates are a pair: both numbers or both null (anycast). 0 is a real coordinate.
916
+ const { latitude, longitude } = data.location ?? {};
917
+ if (typeof latitude === "number" && typeof longitude === "number") {
918
+ console.log("approximate network position:", latitude, longitude);
919
+ }
920
+ ```
921
+
922
+ Both are optional on `IpRiskResponse`, and every field inside `IpLocation` is nullable: an
923
+ older server omits them entirely, and a newer one can resolve a country without a city.
924
+ `RiskReason.code` / `category` / `severity` are plain `string`s on purpose, so a reason
925
+ code added server-side after your build still type-checks and still renders.
926
+
927
+ Schema 1.6.0 adds `network.domain` / `network.range` and `IpLocation.continentCode` /
928
+ `continent` / `postalCode` / `latitude` / `longitude`. All seven are optional and nullable
929
+ (`field?: T | null`): an older server omits them, a newer one can send `null`, and the
930
+ coordinate pair is either both numbers or both `null` (an anycast network has no single
931
+ node position). `postalCode` is a string, and `0` coordinates are legitimate values - read
932
+ them with a type check, never a truthiness check.
933
+
722
934
  See [examples/](examples/) for runnable scripts.
723
935
 
724
936
  ## Security
@@ -735,10 +947,11 @@ See [examples/](examples/) for runnable scripts.
735
947
 
736
948
  ## Developer API
737
949
 
738
- | | |
739
- | --------------- | ------------------------------------------- |
740
- | Base URL | `https://api.netriskscan.com` |
741
- | Current version | `v1` (path prefix `/v1`, **not** `/api/v1`) |
950
+ | | |
951
+ | --------------- | ---------------------------------------------------------------- |
952
+ | Base URL | `https://api.netriskscan.com` |
953
+ | Current version | `v1` (path prefix `/v1`, **not** `/api/v1`) |
954
+ | Response schema | IP Intelligence Schema 1.6.0 (additive; older servers supported) |
742
955
 
743
956
  This is a completely separate system from the netriskscan.com website's internal
744
957
  `/api/public/*` endpoints - different auth, different response shapes, no compatibility
@@ -763,6 +976,51 @@ See the official [Methodology](https://www.netriskscan.com/methodology.html) pag
763
976
  how the NetRiskScan Index itself is computed (this project does not - and will not -
764
977
  reimplement that logic client-side).
765
978
 
979
+ ## FAQ
980
+
981
+ ### How do I look up an IP address from the command line?
982
+
983
+ Run `netriskscan check <ip>` - no account or API key required for the anonymous daily
984
+ trial. See [Quick start](#quick-start).
985
+
986
+ ### How do I check IP reputation from a terminal?
987
+
988
+ `netriskscan check <ip>` prints the NetRiskScan Index, band, network and signal data
989
+ for that address. See [IP risk check](#ip-risk-check).
990
+
991
+ ### How do I check an IP risk score using the CLI?
992
+
993
+ The `Index` and `Band` fields in `netriskscan check` output are the risk score;
994
+ `--fail-below <index>` turns that score into a CI/CD gate. See [CI/CD](#cicd).
995
+
996
+ ### How do I detect proxy, VPN or Tor IPs from the command line?
997
+
998
+ `netriskscan check <ip>` reports `Proxy`, `VPN` and `Tor` as independent signals in
999
+ the `Signals` block, plus a `Proxy Type` classification when a proxy is detected. See
1000
+ [Proxy, VPN and Tor Signals](#proxy-vpn-and-tor-signals).
1001
+
1002
+ ### Can the CLI detect Tor exit nodes?
1003
+
1004
+ It reports the `Tor` signal and, when the API includes a Tor-exit-specific risk
1005
+ reason, prints it under `Risk Reasons` - the CLI only relays what the server
1006
+ verifies, it never infers exit-node status locally. See [Risk Reasons](#risk-reasons).
1007
+
1008
+ ### How do I check multiple IP addresses in bulk?
1009
+
1010
+ `netriskscan batch ips.txt` reads one IP per line and runs a client-side batch against
1011
+ the Developer API with controlled concurrency. See [Batch processing](#batch-processing).
1012
+
1013
+ ### Can I get IP lookup results as JSON?
1014
+
1015
+ Yes - `netriskscan check <ip> --json` prints the raw API response, and
1016
+ `netriskscan batch ips.txt --jsonl` prints one JSON object per line. See
1017
+ [JSON output](#json-output) and [JSONL output](#jsonl-output).
1018
+
1019
+ ### Does NetRiskScan CLI work without an API key?
1020
+
1021
+ Yes. `check` and `batch` run on an anonymous daily trial with no signup and no API
1022
+ key. `usage` always requires a key. See [Anonymous trial](#anonymous-trial).
1023
+
766
1024
  ## Official resources
767
1025
 
768
1026
  - [NetRiskScan](https://www.netriskscan.com) - web-based IP reputation and network
package/dist/cli.js CHANGED
@@ -305,6 +305,42 @@ function formatProxyTypeCompact(value) {
305
305
  function formatOrDash(value) {
306
306
  return value === null || value === void 0 || value === "" ? "-" : value;
307
307
  }
308
+ function formatGeoName(name, code) {
309
+ const hasName = name !== null && name !== void 0 && name !== "";
310
+ const hasCode = code !== null && code !== void 0 && code !== "";
311
+ if (hasName && hasCode) return `${name} (${code})`;
312
+ if (hasName) return name;
313
+ if (hasCode) return code;
314
+ return void 0;
315
+ }
316
+ var RISK_REASON_LABELS = {
317
+ RESIDENTIAL_PROXY_DETECTED: "Residential Proxy Detected",
318
+ ISP_PROXY_DETECTED: "ISP Proxy Detected",
319
+ MOBILE_PROXY_DETECTED: "Mobile Proxy Detected",
320
+ DATACENTER_PROXY_DETECTED: "Datacenter Proxy Detected",
321
+ PROXY_DETECTED: "Proxy Detected",
322
+ VPN_DETECTED: "VPN Detected",
323
+ TOR_RELAY: "Tor Relay",
324
+ TOR_EXIT_NODE: "Tor Exit Node",
325
+ KNOWN_SCANNER: "Known Scanner",
326
+ ABUSE_ACTIVITY: "Abuse Activity",
327
+ BLACKLIST_MATCH: "Blacklist Match",
328
+ BOTNET_C2: "Botnet C2",
329
+ COMPROMISED_HOST: "Compromised Host",
330
+ VERIFIED_SEARCH_CRAWLER: "Verified Search Crawler",
331
+ PUBLIC_INFRASTRUCTURE: "Public Infrastructure",
332
+ RESIDENTIAL_NETWORK: "Residential Network",
333
+ CONFLICTING_EVIDENCE: "Conflicting Evidence",
334
+ INSUFFICIENT_EVIDENCE: "Insufficient Evidence"
335
+ };
336
+ function formatRiskReasonCode(code) {
337
+ if (code === null || code === void 0 || code === "") return "-";
338
+ const known = RISK_REASON_LABELS[code];
339
+ if (known !== void 0) return known;
340
+ const words = code.split(/[_\s]+/).filter((word) => word !== "");
341
+ if (words.length === 0) return code;
342
+ return words.map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join(" ");
343
+ }
308
344
  function formatIndex(value) {
309
345
  return value === null ? "N/A" : String(value);
310
346
  }
@@ -321,6 +357,10 @@ var LABEL_WIDTH = 18;
321
357
  function row(label, value) {
322
358
  return `${label.padEnd(LABEL_WIDTH)}${value}`;
323
359
  }
360
+ var REASON_LABEL_WIDTH = 30;
361
+ function reasonRow(label, value) {
362
+ return value === "" ? label : `${label.padEnd(REASON_LABEL_WIDTH)}${value}`;
363
+ }
324
364
  function formatUtcTimestamp(iso) {
325
365
  if (!iso) return void 0;
326
366
  const date = new Date(iso);
@@ -344,6 +384,44 @@ function anonymousUsageLines(usage) {
344
384
  }
345
385
  return lines;
346
386
  }
387
+ function riskReasonLines(reasons) {
388
+ if (reasons === void 0 || reasons.length === 0) return [];
389
+ return reasons.map((reason) => {
390
+ const severity = reason.severity ?? "";
391
+ return reasonRow(formatRiskReasonCode(reason.code), severityColor(severity)(severity));
392
+ });
393
+ }
394
+ function severityColor(severity) {
395
+ switch (severity) {
396
+ case "critical":
397
+ case "high":
398
+ return chalk.red;
399
+ case "medium":
400
+ return chalk.yellow;
401
+ case "info":
402
+ return chalk.gray;
403
+ default:
404
+ return (text) => text;
405
+ }
406
+ }
407
+ function locationLines(location) {
408
+ if (!location) return [];
409
+ const lines = [];
410
+ const country = formatGeoName(location.country, location.countryCode);
411
+ if (country !== void 0) lines.push(row("Country", country));
412
+ const region = formatGeoName(location.region, location.regionCode);
413
+ if (region !== void 0) lines.push(row("Region", region));
414
+ if (location.city) lines.push(row("City", location.city));
415
+ const continent = formatGeoName(location.continent, location.continentCode);
416
+ if (continent !== void 0) lines.push(row("Continent", continent));
417
+ if (location.postalCode) lines.push(row("Postal Code", location.postalCode));
418
+ const { latitude, longitude } = location;
419
+ if (typeof latitude === "number" && Number.isFinite(latitude) && typeof longitude === "number" && Number.isFinite(longitude)) {
420
+ lines.push(row("Coordinates", `${latitude}, ${longitude}`));
421
+ }
422
+ if (location.timeZone) lines.push(row("Time Zone", location.timeZone));
423
+ return lines;
424
+ }
347
425
  function bandColor(band) {
348
426
  switch (band) {
349
427
  case "excellent":
@@ -373,6 +451,12 @@ function renderCheckResult(ip, data) {
373
451
  lines.push(chalk.yellow("This address could not be reliably assessed."));
374
452
  lines.push("");
375
453
  }
454
+ const reasonLines = riskReasonLines(data.risk.reasons);
455
+ if (reasonLines.length > 0) {
456
+ lines.push(chalk.bold("Risk Reasons"));
457
+ lines.push(...reasonLines);
458
+ lines.push("");
459
+ }
376
460
  lines.push(chalk.bold("Network"));
377
461
  lines.push(row("Type", formatNullable(data.network.type)));
378
462
  if (data.network.profile) {
@@ -384,7 +468,19 @@ function renderCheckResult(ip, data) {
384
468
  lines.push(row("Connection", formatNullable(data.network.connectionType)));
385
469
  lines.push(row("ASN", formatNullable(data.network.asn)));
386
470
  lines.push(row("Organization", formatNullable(data.network.organization)));
471
+ if (data.network.domain) {
472
+ lines.push(row("Domain", data.network.domain));
473
+ }
474
+ if (data.network.range) {
475
+ lines.push(row("Network Range", data.network.range));
476
+ }
387
477
  lines.push("");
478
+ const geoLines = locationLines(data.location);
479
+ if (geoLines.length > 0) {
480
+ lines.push(chalk.bold("Location"));
481
+ lines.push(...geoLines);
482
+ lines.push("");
483
+ }
388
484
  lines.push(chalk.bold("Signals"));
389
485
  lines.push(row("Proxy", formatTriState(data.flags.proxy)));
390
486
  lines.push(row("Proxy Type", formatProxyType(data.flags.proxyType)));
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cli.ts","../src/commands/check.ts","../src/client/errors.ts","../src/client/headers.ts","../src/client/retry.ts","../src/client/NetRiskScanClient.ts","../src/utils/env.ts","../src/utils/ip.ts","../src/utils/exitCode.ts","../src/output/human.ts","../src/output/format.ts","../src/output/json.ts","../src/output/errors.ts","../src/commands/usage.ts","../src/commands/batch.ts","../src/utils/pool.ts","../src/output/jsonl.ts","../src/output/table.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { Command, CommanderError } from \"commander\";\nimport { registerCheckCommand } from \"./commands/check.js\";\nimport { registerUsageCommand } from \"./commands/usage.js\";\nimport { registerBatchCommand } from \"./commands/batch.js\";\nimport { ExitCode } from \"./utils/exitCode.js\";\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\nconst pkg = JSON.parse(readFileSync(join(__dirname, \"..\", \"package.json\"), \"utf8\")) as {\n version: string;\n};\n\nconst program = new Command();\n\nprogram\n .name(\"netriskscan\")\n .description(\n \"Query IP risk, network intelligence and reputation data from the NetRiskScan Developer API.\",\n )\n .version(pkg.version, \"-V, --version\", \"Show the CLI version\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ netriskscan check 1.1.1.1 # no account or API key needed\n $ netriskscan check 1.1.1.1 --json\n $ netriskscan usage # needs an API key\n $ netriskscan batch ips.txt --jsonl\n\ncheck and batch work with no setup at all: without an API key they use the\nanonymous daily trial, metered by public IP. The server reports how many\nrequests are left; the CLI never estimates it.\n\nEnvironment variables:\n NETRISKSCAN_API_KEY Optional for check/batch; required for account usage.\n\nNetRiskScan provides diagnostic network intelligence. Results should not be\ntreated as proof of malicious activity or used as the sole basis for legal,\nemployment, credit, identity, or other high-impact decisions.\n\nLearn more: https://github.com/TeamQQ/netriskscan-cli\n`,\n );\n\nregisterCheckCommand(program);\nregisterUsageCommand(program);\nregisterBatchCommand(program);\n\nprogram.exitOverride();\n\ntry {\n await program.parseAsync(process.argv);\n} catch (err) {\n if (err instanceof CommanderError) {\n if (err.code === \"commander.helpDisplayed\" || err.code === \"commander.version\") {\n process.exitCode = ExitCode.Success;\n } else {\n process.exitCode = ExitCode.InvalidArgument;\n }\n } else {\n process.stderr.write(`Unexpected error: ${err instanceof Error ? err.message : String(err)}\\n`);\n process.exitCode = ExitCode.GeneralError;\n }\n}\n","import type { Command } from \"commander\";\nimport ora from \"ora\";\nimport { NetRiskScanClient } from \"../client/NetRiskScanClient.js\";\nimport {\n ANONYMOUS_DAILY_LIMIT_CODE,\n NetRiskScanApiError,\n NetRiskScanNetworkError,\n} from \"../client/errors.js\";\nimport type { IpRiskResponse, RiskFlagName } from \"../client/types.js\";\nimport { resolveOptionalApiKey, resolveBaseUrl } from \"../utils/env.js\";\nimport { isValidIp } from \"../utils/ip.js\";\nimport { ExitCode, exitCodeForApiErrorCode, type ExitCodeValue } from \"../utils/exitCode.js\";\nimport { renderCheckResult, renderVerboseMeta } from \"../output/human.js\";\nimport { printJson } from \"../output/json.js\";\nimport { printAnonymousLimitError, printApiError, printNetworkError } from \"../output/errors.js\";\n\nconst KNOWN_FLAGS: readonly RiskFlagName[] = [\n \"proxy\",\n \"vpn\",\n \"tor\",\n \"datacenter\",\n \"scanner\",\n \"abuse\",\n];\n\ninterface CheckOptions {\n apiKey?: string;\n baseUrl?: string;\n json?: boolean;\n verbose?: boolean;\n debug?: boolean;\n timeout: string;\n maxRetries: string;\n failBelow?: string;\n failOn: string[];\n}\n\nfunction collect(value: string, previous: string[]): string[] {\n return [...previous, value];\n}\n\nexport function registerCheckCommand(program: Command): void {\n program\n .command(\"check <ip>\")\n .description(\"Check IP risk and network intelligence\")\n .option(\n \"--api-key <key>\",\n \"NetRiskScan API key (optional; uses the anonymous trial when omitted)\",\n )\n .option(\"--base-url <url>\", \"Override the API base URL (advanced)\")\n .option(\"--json\", \"Output machine-readable JSON\")\n .option(\"--verbose\", \"Show rate limit, quota and request id\")\n .option(\"--debug\", \"Show debug information on failure\")\n .option(\"--timeout <ms>\", \"Request timeout in milliseconds\", \"10000\")\n .option(\"--max-retries <n>\", \"Maximum automatic retries for 429/503\", \"3\")\n .option(\"--fail-below <index>\", \"Exit non-zero if risk.index is below this threshold (CI use)\")\n .option(\n \"--fail-on <flag>\",\n \"Exit non-zero if the given flag is true (repeatable): proxy, vpn, tor, datacenter, scanner, abuse\",\n collect,\n [] as string[],\n )\n .addHelpText(\n \"after\",\n `\nExamples:\n $ netriskscan check 1.1.1.1\n $ netriskscan check 1.1.1.1 --json\n $ netriskscan check 1.2.3.4 --fail-below 60\n $ netriskscan check 1.2.3.4 --fail-on tor --fail-on proxy\n\nNotes:\n An API key is optional. Without one, requests use the anonymous daily trial,\n metered by public IP; the response reports how many are left.\n`,\n )\n .action(async (ip: string, options: CheckOptions) => {\n await runCheck(ip, options);\n });\n}\n\nasync function runCheck(ip: string, options: CheckOptions): Promise<void> {\n const useJson = Boolean(options.json);\n\n for (const flag of options.failOn) {\n if (!KNOWN_FLAGS.includes(flag as RiskFlagName)) {\n process.stderr.write(\n `Error: unknown --fail-on flag \"${flag}\". Expected one of: ${KNOWN_FLAGS.join(\", \")}\\n`,\n );\n process.exitCode = ExitCode.InvalidArgument;\n return;\n }\n }\n\n if (!isValidIp(ip)) {\n process.stderr.write(`Error: \"${ip}\" is not a valid IPv4 or IPv6 address.\\n`);\n process.exitCode = ExitCode.InvalidArgument;\n return;\n }\n\n // Undefined is a supported mode: the client then omits Authorization and the server serves the\n // request from the anonymous daily trial.\n const client = new NetRiskScanClient({\n apiKey: resolveOptionalApiKey(options.apiKey),\n baseUrl: resolveBaseUrl(options.baseUrl),\n timeout: Number(options.timeout),\n maxRetries: Number(options.maxRetries),\n });\n\n const spinner = useJson\n ? undefined\n : ora({\n text: `Checking ${ip}...`,\n stream: process.stderr,\n isEnabled: process.stderr.isTTY,\n }).start();\n\n try {\n const { data, meta } = await client.checkIp(ip);\n spinner?.stop();\n\n if (useJson) {\n printJson(data);\n } else {\n renderCheckResult(ip, data);\n if (options.verbose) {\n renderVerboseMeta(meta);\n }\n }\n\n process.exitCode = evaluateCiPolicy(data, options);\n } catch (err) {\n spinner?.stop();\n handleCheckError(err, options);\n }\n}\n\nfunction evaluateCiPolicy(data: IpRiskResponse, options: CheckOptions): ExitCodeValue {\n if (options.failOn.length > 0) {\n for (const flag of options.failOn) {\n if (data.flags[flag as RiskFlagName] === true) {\n return ExitCode.CiPolicyFailed;\n }\n }\n }\n\n if (options.failBelow !== undefined) {\n if (data.risk.index === null) {\n return ExitCode.AssessmentUnavailable;\n }\n if (data.risk.index < Number(options.failBelow)) {\n return ExitCode.CiPolicyFailed;\n }\n }\n\n return ExitCode.Success;\n}\n\nfunction handleCheckError(err: unknown, options: CheckOptions): void {\n if (err instanceof NetRiskScanApiError) {\n if (err.code === ANONYMOUS_DAILY_LIMIT_CODE) {\n printAnonymousLimitError(err);\n } else {\n printApiError(err, { debug: options.debug });\n }\n process.exitCode = exitCodeForApiErrorCode(err.code);\n return;\n }\n if (err instanceof NetRiskScanNetworkError) {\n printNetworkError(err, { debug: options.debug });\n process.exitCode = ExitCode.ApiError;\n return;\n }\n if (options.debug && err instanceof Error) {\n process.stderr.write(`${err.stack ?? err.message}\\n`);\n } else {\n process.stderr.write(`Error: ${err instanceof Error ? err.message : String(err)}\\n`);\n }\n process.exitCode = ExitCode.GeneralError;\n}\n","export const KNOWN_ERROR_CODES = [\n \"invalid_ip\",\n \"invalid_request\",\n \"unsupported_parameter\",\n \"invalid_api_key\",\n \"api_key_disabled\",\n \"scope_not_allowed\",\n \"not_found\",\n \"feature_not_available\",\n \"rate_limit_exceeded\",\n \"quota_exceeded\",\n \"anonymous_daily_limit_reached\",\n \"temporarily_unavailable\",\n] as const;\n\nexport type KnownErrorCode = (typeof KNOWN_ERROR_CODES)[number];\n\n/**\n * The anonymous trial's daily allowance is spent. Deterministic until the UTC reset, so unlike\n * `rate_limit_exceeded` it is never retried - see `isRetryableFailure`.\n */\nexport const ANONYMOUS_DAILY_LIMIT_CODE = \"anonymous_daily_limit_reached\";\n\n/**\n * Anonymous-trial allowance carried on a `429 anonymous_daily_limit_reached`.\n *\n * Parsed once in the client layer so the output layer never has to touch an HTTP body. Every\n * field is optional: a server that only sends `code` and `message` must still work.\n */\nexport interface AnonymousLimitInfo {\n dailyLimit?: number;\n used?: number;\n remaining?: number;\n resetAt?: string;\n signupUrl?: string;\n}\n\nexport class NetRiskScanError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"NetRiskScanError\";\n }\n}\n\n/** Thrown for client-side configuration problems, e.g. a missing API key. */\nexport class NetRiskScanConfigError extends NetRiskScanError {\n constructor(message: string) {\n super(message);\n this.name = \"NetRiskScanConfigError\";\n }\n}\n\nexport interface NetRiskScanApiErrorOptions {\n status: number;\n code: string;\n requestId?: string;\n retryAfter?: number;\n anonymousUsage?: AnonymousLimitInfo;\n}\n\n/** Thrown when the Developer API responds with a non-2xx status. */\nexport class NetRiskScanApiError extends NetRiskScanError {\n readonly status: number;\n readonly code: string;\n readonly requestId?: string;\n readonly retryAfter?: number;\n /** Present when the server reported anonymous-trial allowance alongside the error. */\n readonly anonymousUsage?: AnonymousLimitInfo;\n\n constructor(message: string, options: NetRiskScanApiErrorOptions) {\n super(message);\n this.name = \"NetRiskScanApiError\";\n this.status = options.status;\n this.code = options.code;\n this.requestId = options.requestId;\n this.retryAfter = options.retryAfter;\n this.anonymousUsage = options.anonymousUsage;\n }\n}\n\nexport interface NetRiskScanNetworkErrorOptions {\n cause?: unknown;\n requestId?: string;\n}\n\n/** Thrown for transport-level failures: timeouts, DNS errors, connection resets, etc. */\nexport class NetRiskScanNetworkError extends NetRiskScanError {\n override readonly cause?: unknown;\n readonly requestId?: string;\n\n constructor(message: string, options: NetRiskScanNetworkErrorOptions = {}) {\n super(message);\n this.name = \"NetRiskScanNetworkError\";\n this.cause = options.cause;\n this.requestId = options.requestId;\n }\n}\n","import { randomBytes } from \"node:crypto\";\nimport type { QuotaInfo, RateLimitInfo } from \"./types.js\";\n\nconst REQUEST_ID_PATTERN = /^req_[A-Za-z0-9_-]{8,56}$/;\n\nexport function isValidRequestId(id: string): boolean {\n return REQUEST_ID_PATTERN.test(id);\n}\n\nexport function generateRequestId(): string {\n return `req_${randomBytes(12).toString(\"hex\")}`;\n}\n\nfunction parseIntHeader(value: string | null): number | undefined {\n if (value === null) return undefined;\n const n = Number(value);\n return Number.isFinite(n) ? n : undefined;\n}\n\nexport function parseRateLimit(headers: Headers): RateLimitInfo {\n return {\n limit: parseIntHeader(headers.get(\"x-ratelimit-limit\")),\n remaining: parseIntHeader(headers.get(\"x-ratelimit-remaining\")),\n reset: parseIntHeader(headers.get(\"x-ratelimit-reset\")),\n };\n}\n\nexport function parseQuota(headers: Headers): QuotaInfo {\n return {\n limit: parseIntHeader(headers.get(\"x-quota-limit\")),\n used: parseIntHeader(headers.get(\"x-quota-used\")),\n remaining: parseIntHeader(headers.get(\"x-quota-remaining\")),\n };\n}\n\n/** Never log or print a full API key. Keeps a short prefix/suffix for support purposes. */\nexport function redactApiKey(key: string): string {\n if (key.length <= 9) return \"*\".repeat(key.length);\n return `${key.slice(0, 9)}${\"*\".repeat(4)}${key.slice(-4)}`;\n}\n\nexport function redactAuthorizationHeader(value: string): string {\n const match = /^Bearer\\s+(.+)$/i.exec(value);\n if (!match) return \"[REDACTED]\";\n return `Bearer ${redactApiKey(match[1])}`;\n}\n","import { ANONYMOUS_DAILY_LIMIT_CODE } from \"./errors.js\";\n\n/** Only 429 and 503 are automatically retried; 400/401/403/404 never are. */\nexport function isRetryableStatus(status: number): boolean {\n return status === 429 || status === 503;\n}\n\n/**\n * Status *and* error code decide retryability, because not every 429 is transient.\n *\n * `rate_limit_exceeded` is a short per-minute window and retrying is the right behaviour.\n * `anonymous_daily_limit_reached` is a spent daily allowance that cannot come back before the\n * UTC reset, so retrying it only burns three more round-trips before failing identically.\n */\nexport function isRetryableFailure(status: number, code?: string): boolean {\n if (code === ANONYMOUS_DAILY_LIMIT_CODE) return false;\n return isRetryableStatus(status);\n}\n\nconst BASE_DELAY_MS = 1000;\nconst MAX_JITTER_MS = 250;\n\n/** Honors Retry-After when present; otherwise exponential backoff (1s, 2s, 4s, ...) with jitter. */\nexport function computeBackoffMs(attempt: number, retryAfterSeconds?: number): number {\n if (\n typeof retryAfterSeconds === \"number\" &&\n Number.isFinite(retryAfterSeconds) &&\n retryAfterSeconds >= 0\n ) {\n return retryAfterSeconds * 1000;\n }\n const base = BASE_DELAY_MS * 2 ** Math.max(0, attempt - 1);\n const jitter = Math.random() * MAX_JITTER_MS;\n return base + jitter;\n}\n\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n","import { NetRiskScanApiError, NetRiskScanConfigError, NetRiskScanNetworkError } from \"./errors.js\";\nimport { generateRequestId, isValidRequestId, parseQuota, parseRateLimit } from \"./headers.js\";\nimport { computeBackoffMs, isRetryableFailure, sleep } from \"./retry.js\";\nimport type { AnonymousLimitInfo } from \"./errors.js\";\nimport type {\n ApiErrorBody,\n ApiResult,\n IpRiskResponse,\n NetRiskScanClientOptions,\n RequestOptions,\n UsageResponse,\n} from \"./types.js\";\n\nconst DEFAULT_BASE_URL = \"https://api.netriskscan.com\";\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_MAX_RETRIES = 3;\n\nfunction isAbortError(err: unknown): boolean {\n return err instanceof Error && err.name === \"AbortError\";\n}\n\nasync function safeJson(res: Response): Promise<ApiErrorBody | undefined> {\n try {\n return (await res.json()) as ApiErrorBody;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Lifts the anonymous-trial fields off an error body, once, here. HTTP bodies are parsed in the\n * client layer only - the output layer receives a typed error, never JSON.\n */\nfunction parseAnonymousLimitInfo(body: ApiErrorBody | undefined): AnonymousLimitInfo | undefined {\n const error = body?.error;\n if (!error) return undefined;\n const { dailyLimit, used, remaining, resetAt, signupUrl } = error;\n if (\n dailyLimit === undefined &&\n used === undefined &&\n remaining === undefined &&\n resetAt === undefined &&\n signupUrl === undefined\n ) {\n return undefined;\n }\n return { dailyLimit, used, remaining, resetAt, signupUrl };\n}\n\n/**\n * Client for the NetRiskScan Developer API (`/v1/*` only).\n *\n * Works with no configuration at all: without an API key it sends no `Authorization` header and\n * the server serves the request from the anonymous daily trial, metered by public IP.\n *\n * @example Anonymous - no account, no key\n * ```ts\n * const client = new NetRiskScanClient();\n * const { data } = await client.checkIp(\"1.1.1.1\");\n * console.log(data.risk.index);\n * console.log(data.usage?.remaining);\n * ```\n *\n * @example Pass `apiKey` to use Developer Account quota instead of the anonymous trial\n * ```ts\n * const client = new NetRiskScanClient({ apiKey: process.env.NETRISKSCAN_API_KEY });\n * ```\n */\nexport class NetRiskScanClient {\n private readonly apiKey?: string;\n private readonly baseUrl: string;\n private readonly timeout: number;\n private readonly maxRetries: number;\n\n constructor(options: NetRiskScanClientOptions = {}) {\n // An absent key is a supported mode, not a misconfiguration: it selects the anonymous trial.\n this.apiKey = options.apiKey || undefined;\n this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n this.timeout = options.timeout ?? DEFAULT_TIMEOUT_MS;\n this.maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;\n }\n\n async checkIp(ip: string, options: RequestOptions = {}): Promise<ApiResult<IpRiskResponse>> {\n return this.request<IpRiskResponse>(`/v1/ip-risk/${encodeURIComponent(ip)}`, options);\n }\n\n /**\n * Account plan, billing period and quota. Unlike {@link checkIp} this is account data, so it\n * has no anonymous equivalent and requires an API key.\n */\n async getUsage(options: RequestOptions = {}): Promise<ApiResult<UsageResponse>> {\n if (!this.apiKey) {\n throw new NetRiskScanConfigError(\"An API key is required to query account usage.\");\n }\n return this.request<UsageResponse>(\"/v1/usage\", options);\n }\n\n private async request<T>(path: string, options: RequestOptions): Promise<ApiResult<T>> {\n const requestId =\n options.requestId && isValidRequestId(options.requestId)\n ? options.requestId\n : generateRequestId();\n\n let attempt = 0;\n\n while (true) {\n const timeoutController = new AbortController();\n const timer = setTimeout(() => timeoutController.abort(), this.timeout);\n const onExternalAbort = (): void => timeoutController.abort();\n options.signal?.addEventListener(\"abort\", onExternalAbort);\n\n try {\n const headers: Record<string, string> = {\n Accept: \"application/json\",\n \"X-Request-Id\": requestId,\n };\n // Only ever sent when a key actually exists. A `Bearer undefined` would read as a bad key\n // and earn a 401 instead of falling through to the anonymous trial.\n if (this.apiKey) {\n headers.Authorization = `Bearer ${this.apiKey}`;\n }\n\n const res = await fetch(`${this.baseUrl}${path}`, {\n method: \"GET\",\n headers,\n signal: timeoutController.signal,\n });\n\n const rateLimit = parseRateLimit(res.headers);\n const quota = parseQuota(res.headers);\n const responseRequestId = res.headers.get(\"x-request-id\") ?? requestId;\n\n if (res.ok) {\n const data = (await res.json()) as T;\n return { data, meta: { requestId: responseRequestId, rateLimit, quota } };\n }\n\n const body = await safeJson(res);\n const retryAfterHeader = res.headers.get(\"retry-after\");\n const retryAfter = retryAfterHeader !== null ? Number(retryAfterHeader) : undefined;\n\n if (isRetryableFailure(res.status, body?.error?.code) && attempt < this.maxRetries) {\n attempt += 1;\n await sleep(computeBackoffMs(attempt, retryAfter));\n continue;\n }\n\n throw new NetRiskScanApiError(body?.error?.message ?? res.statusText, {\n status: res.status,\n code: body?.error?.code ?? \"unknown_error\",\n requestId: body?.error?.requestId ?? responseRequestId,\n retryAfter,\n anonymousUsage: parseAnonymousLimitInfo(body),\n });\n } catch (err) {\n if (err instanceof NetRiskScanApiError) {\n throw err;\n }\n if (isAbortError(err)) {\n if (options.signal?.aborted) {\n throw err;\n }\n throw new NetRiskScanNetworkError(`Request timed out after ${this.timeout}ms`, {\n cause: err,\n requestId,\n });\n }\n throw new NetRiskScanNetworkError(\n err instanceof Error ? err.message : \"Network request failed\",\n {\n cause: err,\n requestId,\n },\n );\n } finally {\n clearTimeout(timer);\n options.signal?.removeEventListener(\"abort\", onExternalAbort);\n }\n }\n }\n}\n","import { NetRiskScanConfigError } from \"../client/errors.js\";\n\n/**\n * Resolves the API key for endpoints that work without one (`check`, `batch`).\n *\n * Returning `undefined` is a valid outcome, not a failure: it selects the anonymous trial. The\n * precedence is `--api-key` > `NETRISKSCAN_API_KEY` > anonymous. A key that is present but wrong\n * is still passed through - the CLI never silently drops a key the user configured and retries\n * anonymously, because that would turn an authentication problem into a confusing success.\n */\nexport function resolveOptionalApiKey(cliValue?: string): string | undefined {\n return cliValue || process.env.NETRISKSCAN_API_KEY || undefined;\n}\n\n/**\n * Resolves the API key for account-level endpoints (`usage`), which have no anonymous form.\n *\n * The message names the command on purpose: a generic \"API key is required\" here would suggest\n * the whole CLI needs an account, which is no longer true.\n */\nexport function resolveRequiredApiKey(cliValue?: string): string {\n const apiKey = resolveOptionalApiKey(cliValue);\n if (!apiKey) {\n throw new NetRiskScanConfigError(\n \"An API key is required for the usage command.\\n\\nSet NETRISKSCAN_API_KEY or use --api-key.\",\n );\n }\n return apiKey;\n}\n\nexport function resolveBaseUrl(cliValue?: string): string | undefined {\n return cliValue ?? process.env.NETRISKSCAN_BASE_URL;\n}\n","import { isIP } from \"node:net\";\n\nexport function isValidIp(value: string): boolean {\n return isIP(value) !== 0;\n}\n","import type { KnownErrorCode } from \"../client/errors.js\";\n\nexport const ExitCode = {\n Success: 0,\n GeneralError: 1,\n InvalidArgument: 2,\n AuthError: 3,\n ApiError: 4,\n RateLimitOrQuota: 5,\n CiPolicyFailed: 6,\n AssessmentUnavailable: 7,\n} as const;\n\nexport type ExitCodeValue = (typeof ExitCode)[keyof typeof ExitCode];\n\nexport function exitCodeForApiErrorCode(code: string): ExitCodeValue {\n switch (code as KnownErrorCode) {\n case \"invalid_api_key\":\n case \"api_key_disabled\":\n case \"scope_not_allowed\":\n return ExitCode.AuthError;\n // The anonymous daily trial is an allowance like any other, so it reuses code 5 rather than\n // adding an eighth exit code that every script would have to learn.\n case \"rate_limit_exceeded\":\n case \"quota_exceeded\":\n case \"anonymous_daily_limit_reached\":\n return ExitCode.RateLimitOrQuota;\n default:\n return ExitCode.ApiError;\n }\n}\n","import chalk from \"chalk\";\nimport type {\n IpRiskResponse,\n RequestUsage,\n ResponseMeta,\n RiskBand,\n UsageResponse,\n} from \"../client/types.js\";\nimport {\n formatDate,\n formatIndex,\n formatNullable,\n formatNumber,\n formatOrDash,\n formatProxyType,\n formatTriState,\n formatUtcTimestamp,\n row,\n} from \"./format.js\";\n\n/**\n * Anonymous-trial rows for the human `check` output.\n *\n * `Available` is printed verbatim from `usage.remaining` - the server is the only authority on\n * what is left, so this never falls back to `dailyLimit - used`. Each row is emitted only when\n * its value is actually a number, because `0` is a legitimate value that a truthiness check\n * would swallow on exactly the run where it matters most.\n */\nfunction anonymousUsageLines(usage: RequestUsage): string[] {\n const lines: string[] = [];\n if (typeof usage.remaining === \"number\") {\n lines.push(row(\"Available\", formatNumber(usage.remaining)));\n }\n if (typeof usage.dailyLimit === \"number\") {\n lines.push(row(\"Daily Limit\", formatNumber(usage.dailyLimit)));\n }\n const reset = formatUtcTimestamp(usage.resetAt);\n if (reset !== undefined) {\n lines.push(row(\"Reset\", reset));\n }\n return lines;\n}\n\nfunction bandColor(band: RiskBand | null): (text: string) => string {\n switch (band) {\n case \"excellent\":\n case \"good\":\n return chalk.green;\n case \"fair\":\n return chalk.yellow;\n case \"poor\":\n case \"high_risk\":\n return chalk.red;\n default:\n return chalk.gray;\n }\n}\n\nexport function renderCheckResult(ip: string, data: IpRiskResponse): void {\n const lines: string[] = [];\n lines.push(chalk.bold(\"NetRiskScan\"));\n lines.push(\"\");\n lines.push(row(\"IP\", ip));\n lines.push(row(\"Index\", formatIndex(data.risk.index)));\n lines.push(\n row(\"Band\", data.risk.band ? bandColor(data.risk.band)(data.risk.band) : chalk.gray(\"N/A\")),\n );\n lines.push(row(\"Assessment\", data.risk.assessmentGrade));\n lines.push(\"\");\n\n if (data.risk.assessmentGrade === \"insufficient\" && data.risk.index === null) {\n lines.push(chalk.yellow(\"This address could not be reliably assessed.\"));\n lines.push(\"\");\n }\n\n lines.push(chalk.bold(\"Network\"));\n lines.push(row(\"Type\", formatNullable(data.network.type)));\n // Omitted entirely when absent, unlike the fields around them, which render \"N/A\". Those describe every\n // address, so a missing one is worth showing as missing; these two exist only for the minority of\n // addresses NetRiskScan holds a first-party record for, and printing \"Profile N/A\" on every residential\n // lookup would be noise rather than information.\n if (data.network.profile) {\n lines.push(row(\"Profile\", data.network.profile));\n }\n if (data.network.service) {\n lines.push(row(\"Service\", data.network.service));\n }\n lines.push(row(\"Connection\", formatNullable(data.network.connectionType)));\n lines.push(row(\"ASN\", formatNullable(data.network.asn)));\n lines.push(row(\"Organization\", formatNullable(data.network.organization)));\n lines.push(\"\");\n\n lines.push(chalk.bold(\"Signals\"));\n lines.push(row(\"Proxy\", formatTriState(data.flags.proxy)));\n lines.push(row(\"Proxy Type\", formatProxyType(data.flags.proxyType)));\n lines.push(row(\"VPN\", formatTriState(data.flags.vpn)));\n lines.push(row(\"Tor\", formatTriState(data.flags.tor)));\n lines.push(row(\"Datacenter\", formatTriState(data.flags.datacenter)));\n lines.push(row(\"Scanner\", formatTriState(data.flags.scanner)));\n lines.push(row(\"Abuse\", formatTriState(data.flags.abuse)));\n lines.push(\"\");\n\n // Identity, not a risk signal: a verified crawler must never read as a threat, so it gets its own\n // section rather than living inside Signals.\n lines.push(chalk.bold(\"Identity\"));\n lines.push(row(\"Search Crawler\", formatTriState(data.flags.searchCrawler)));\n lines.push(row(\"Crawler\", formatOrDash(data.flags.searchCrawlerName)));\n lines.push(\"\");\n\n // Only for the anonymous trial. An API-key caller's allowance is a billing-period quota, a\n // different thing entirely, and stays behind --verbose where it always was.\n if (data.usage?.mode === \"anonymous\") {\n const usageLines = anonymousUsageLines(data.usage);\n if (usageLines.length > 0) {\n lines.push(chalk.bold(\"Usage\"));\n lines.push(...usageLines);\n lines.push(\"\");\n }\n }\n\n lines.push(row(\"Request ID\", data.requestId));\n lines.push(\"\");\n\n lines.push(chalk.bold(\"Explore\"));\n lines.push(row(\"Web\", \"https://www.netriskscan.com\"));\n lines.push(row(\"GitHub\", \"https://github.com/TeamQQ/netriskscan-cli\"));\n\n process.stdout.write(`${lines.join(\"\\n\")}\\n`);\n}\n\nexport function renderVerboseMeta(meta: ResponseMeta): void {\n const lines: string[] = [\"\"];\n if (meta.rateLimit.remaining !== undefined && meta.rateLimit.limit !== undefined) {\n lines.push(\n row(\n \"Rate limit\",\n `${formatNumber(meta.rateLimit.remaining)} / ${formatNumber(meta.rateLimit.limit)} remaining`,\n ),\n );\n }\n if (meta.quota.remaining !== undefined && meta.quota.limit !== undefined) {\n lines.push(\n row(\n \"Quota\",\n `${formatNumber(meta.quota.remaining)} / ${formatNumber(meta.quota.limit)} remaining`,\n ),\n );\n }\n lines.push(row(\"Request ID\", meta.requestId));\n process.stdout.write(`${lines.join(\"\\n\")}\\n`);\n}\n\nexport function renderUsageResult(data: UsageResponse): void {\n const lines: string[] = [];\n lines.push(chalk.bold(\"NetRiskScan Usage\"));\n lines.push(\"\");\n lines.push(row(\"Plan\", data.plan));\n lines.push(\"\");\n lines.push(chalk.bold(\"Usage\"));\n lines.push(row(\"Used\", formatNumber(data.units.used)));\n lines.push(row(\"Remaining\", formatNumber(data.units.remaining)));\n lines.push(row(\"Limit\", formatNumber(data.units.limit)));\n lines.push(\"\");\n lines.push(chalk.bold(\"Rate limit\"));\n lines.push(row(\"Requests / minute\", formatNumber(data.rateLimit.requestsPerMinute)));\n lines.push(\"\");\n lines.push(chalk.bold(\"Billing period\"));\n lines.push(`${formatDate(data.period.start)} → ${formatDate(data.period.end)}`);\n\n process.stdout.write(`${lines.join(\"\\n\")}\\n`);\n}\n","/**\n * Formats a tri-state flag. `null`/`undefined` means \"not enough signal to judge\" and\n * must never collapse into \"No\" - that would silently turn \"unknown\" into \"false\".\n */\nexport function formatTriState(value: boolean | null | undefined): string {\n if (value === true) return \"Yes\";\n if (value === false) return \"No\";\n return \"Unknown\";\n}\n\nconst PROXY_TYPE_LABELS: Record<string, string> = {\n residential_proxy: \"Residential Proxy\",\n isp_proxy: \"ISP Proxy\",\n mobile_proxy: \"Mobile Proxy\",\n datacenter_proxy: \"Datacenter Proxy\",\n unknown_proxy: \"Unknown Proxy\",\n};\n\nconst PROXY_TYPE_LABELS_COMPACT: Record<string, string> = {\n residential_proxy: \"Residential\",\n isp_proxy: \"ISP\",\n mobile_proxy: \"Mobile\",\n datacenter_proxy: \"Datacenter\",\n unknown_proxy: \"Unknown\",\n};\n\n/**\n * Human-readable label for `flags.proxyType`. This is a classification detail, not a tri-state\n * signal - it only refines an address already flagged `proxy: true` - so missing/`null`/empty\n * renders as `-`, matching the placeholder every other Signals row uses for \"not applicable\", never\n * \"Unknown\".\n *\n * An unrecognised raw value renders as itself rather than throwing: `ProxyType` is a documented\n * union, but this reads live server JSON that a compile-time cast cannot actually enforce, and a\n * server that adds a new proxy subtype must not crash CLIs already in the wild.\n */\nexport function formatProxyType(value: string | null | undefined): string {\n if (value === null || value === undefined || value === \"\") return \"-\";\n return PROXY_TYPE_LABELS[value] ?? value;\n}\n\n/** Same mapping as {@link formatProxyType}, abbreviated for the batch table's narrower columns. */\nexport function formatProxyTypeCompact(value: string | null | undefined): string {\n if (value === null || value === undefined || value === \"\") return \"-\";\n return PROXY_TYPE_LABELS_COMPACT[value] ?? value;\n}\n\n/**\n * Passes a server-owned display name through unchanged (e.g. `flags.searchCrawlerName`) - never\n * reformatted, title-cased, or mapped through an enum, because the server already sends the\n * canonical form. Missing/`null`/empty renders as `-`.\n */\nexport function formatOrDash(value: string | null | undefined): string {\n return value === null || value === undefined || value === \"\" ? \"-\" : value;\n}\n\n/** `index` can legitimately be 0, so this must not use a falsy check. */\nexport function formatIndex(value: number | null): string {\n return value === null ? \"N/A\" : String(value);\n}\n\nexport function formatNullable(value: string | null | undefined): string {\n return value === null || value === undefined || value === \"\" ? \"N/A\" : value;\n}\n\nexport function formatNumber(value: number): string {\n return value.toLocaleString(\"en-US\");\n}\n\nexport function formatDate(iso: string): string {\n return iso.slice(0, 10);\n}\n\n/** Shared label column so `check`, `batch` and the error renderers line up identically. */\nexport const LABEL_WIDTH = 18;\n\nexport function row(label: string, value: string): string {\n return `${label.padEnd(LABEL_WIDTH)}${value}`;\n}\n\n/**\n * Renders an ISO-8601 instant as `2026-08-29 00:00 UTC`, deliberately *not* in local time: the\n * anonymous allowance resets on the UTC day, and a localized timestamp would misdescribe when\n * that happens for most of the world.\n *\n * Returns `undefined` for a missing or unparseable value so callers can drop the row rather than\n * print \"Invalid Date\".\n */\nexport function formatUtcTimestamp(iso: string | null | undefined): string | undefined {\n if (!iso) return undefined;\n const date = new Date(iso);\n if (Number.isNaN(date.getTime())) return undefined;\n const pad = (n: number): string => String(n).padStart(2, \"0\");\n return (\n `${date.getUTCFullYear()}-${pad(date.getUTCMonth() + 1)}-${pad(date.getUTCDate())} ` +\n `${pad(date.getUTCHours())}:${pad(date.getUTCMinutes())} UTC`\n );\n}\n","/** Pretty JSON to stdout. Preserves `null` exactly as returned by the API - never coerced. */\nexport function printJson(data: unknown): void {\n process.stdout.write(`${JSON.stringify(data, null, 2)}\\n`);\n}\n","import chalk from \"chalk\";\nimport type {\n NetRiskScanApiError,\n NetRiskScanConfigError,\n NetRiskScanNetworkError,\n} from \"../client/errors.js\";\nimport { formatNumber, formatUtcTimestamp, row } from \"./format.js\";\n\n/** Used only when the server did not send its own `signupUrl`. */\nconst SIGNUP_URL = \"https://www.netriskscan.com/developers\";\n\nexport function printConfigError(err: NetRiskScanConfigError): void {\n process.stderr.write(`Error: ${err.message}\\n`);\n if (err.message.includes(\"API key\")) {\n process.stderr.write(\n \"\\nGet a free API key (no credit card required): https://www.netriskscan.com\\n\",\n );\n }\n}\n\n/**\n * The anonymous trial running out is an ordinary end-of-trial moment, not a protocol fault, so it\n * gets its own renderer instead of the `Code / Status / Message` dump. It tells the reader what\n * they have, when it comes back, and where to get more.\n */\nexport function printAnonymousLimitError(err: NetRiskScanApiError): void {\n const usage = err.anonymousUsage;\n const lines = [\n \"\",\n chalk.bold(\"NetRiskScan\"),\n \"\",\n chalk.yellow(\"Anonymous daily trial limit reached.\"),\n \"\",\n ];\n\n const usageLines: string[] = [\n // The request that returned this error was refused, so nothing is left regardless of what the\n // body reports; `remaining` is only trusted when the server actually sent it.\n row(\"Available\", formatNumber(typeof usage?.remaining === \"number\" ? usage.remaining : 0)),\n ];\n if (typeof usage?.dailyLimit === \"number\") {\n usageLines.push(row(\"Daily Limit\", formatNumber(usage.dailyLimit)));\n }\n const reset = formatUtcTimestamp(usage?.resetAt);\n if (reset !== undefined) {\n usageLines.push(row(\"Reset\", reset));\n }\n\n lines.push(chalk.bold(\"Usage\"), ...usageLines, \"\");\n lines.push(chalk.bold(\"Get more queries\"), usage?.signupUrl || SIGNUP_URL, \"\");\n\n process.stderr.write(`${lines.join(\"\\n\")}\\n`);\n}\n\nconst LABEL_WIDTH = 11;\n\nexport function printApiError(err: NetRiskScanApiError, options: { debug?: boolean } = {}): void {\n const lines = [\n \"\",\n chalk.red(\"NetRiskScan API error\"),\n \"\",\n `${\"Code\".padEnd(LABEL_WIDTH)}${err.code}`,\n `${\"Status\".padEnd(LABEL_WIDTH)}${err.status}`,\n `${\"Message\".padEnd(LABEL_WIDTH)}${err.message}`,\n ];\n if (err.requestId) {\n lines.push(`${\"Request ID\".padEnd(LABEL_WIDTH)}${err.requestId}`);\n }\n if (err.retryAfter !== undefined) {\n lines.push(`${\"Retry after\".padEnd(LABEL_WIDTH)}${err.retryAfter}s`);\n }\n lines.push(\"\");\n process.stderr.write(`${lines.join(\"\\n\")}\\n`);\n\n if (options.debug && err.stack) {\n process.stderr.write(`${err.stack}\\n`);\n }\n}\n\nexport function printNetworkError(\n err: NetRiskScanNetworkError,\n options: { debug?: boolean } = {},\n): void {\n process.stderr.write(`\\n${chalk.red(\"NetRiskScan request failed\")}\\n\\n${err.message}\\n\\n`);\n if (options.debug && err.stack) {\n process.stderr.write(`${err.stack}\\n`);\n }\n}\n","import type { Command } from \"commander\";\nimport ora from \"ora\";\nimport { NetRiskScanClient } from \"../client/NetRiskScanClient.js\";\nimport {\n NetRiskScanApiError,\n NetRiskScanConfigError,\n NetRiskScanNetworkError,\n} from \"../client/errors.js\";\nimport { resolveRequiredApiKey, resolveBaseUrl } from \"../utils/env.js\";\nimport { ExitCode, exitCodeForApiErrorCode } from \"../utils/exitCode.js\";\nimport { renderUsageResult, renderVerboseMeta } from \"../output/human.js\";\nimport { printJson } from \"../output/json.js\";\nimport { printApiError, printConfigError, printNetworkError } from \"../output/errors.js\";\n\ninterface UsageOptions {\n apiKey?: string;\n baseUrl?: string;\n json?: boolean;\n verbose?: boolean;\n debug?: boolean;\n timeout: string;\n maxRetries: string;\n}\n\nexport function registerUsageCommand(program: Command): void {\n program\n .command(\"usage\")\n .description(\"Show API usage and quota for the current billing period (requires an API key)\")\n .option(\"--api-key <key>\", \"NetRiskScan API key (required for this command)\")\n .option(\"--base-url <url>\", \"Override the API base URL (advanced)\")\n .option(\"--json\", \"Output machine-readable JSON\")\n .option(\"--verbose\", \"Show rate limit and request id\")\n .option(\"--debug\", \"Show debug information on failure\")\n .option(\"--timeout <ms>\", \"Request timeout in milliseconds\", \"10000\")\n .option(\"--max-retries <n>\", \"Maximum automatic retries for 429/503\", \"3\")\n .addHelpText(\n \"after\",\n `\nNotes:\n Requires a Developer API key. This reports Developer Account plan, billing\n period and quota, which has no anonymous equivalent - unlike check and batch,\n which work without a key.\n`,\n )\n .action(async (options: UsageOptions) => {\n await runUsage(options);\n });\n}\n\nasync function runUsage(options: UsageOptions): Promise<void> {\n const useJson = Boolean(options.json);\n\n let apiKey: string;\n try {\n apiKey = resolveRequiredApiKey(options.apiKey);\n } catch (err) {\n if (err instanceof NetRiskScanConfigError) {\n printConfigError(err);\n process.exitCode = ExitCode.AuthError;\n return;\n }\n throw err;\n }\n\n const client = new NetRiskScanClient({\n apiKey,\n baseUrl: resolveBaseUrl(options.baseUrl),\n timeout: Number(options.timeout),\n maxRetries: Number(options.maxRetries),\n });\n\n const spinner = useJson\n ? undefined\n : ora({\n text: \"Fetching usage...\",\n stream: process.stderr,\n isEnabled: process.stderr.isTTY,\n }).start();\n\n try {\n const { data, meta } = await client.getUsage();\n spinner?.stop();\n\n if (useJson) {\n printJson(data);\n } else {\n renderUsageResult(data);\n if (options.verbose) {\n renderVerboseMeta(meta);\n }\n }\n } catch (err) {\n spinner?.stop();\n if (err instanceof NetRiskScanApiError) {\n printApiError(err, { debug: options.debug });\n process.exitCode = exitCodeForApiErrorCode(err.code);\n return;\n }\n if (err instanceof NetRiskScanNetworkError) {\n printNetworkError(err, { debug: options.debug });\n process.exitCode = ExitCode.ApiError;\n return;\n }\n throw err;\n }\n}\n","import type { Command } from \"commander\";\nimport { createReadStream } from \"node:fs\";\nimport { createInterface } from \"node:readline\";\nimport { NetRiskScanClient } from \"../client/NetRiskScanClient.js\";\nimport { NetRiskScanApiError, NetRiskScanNetworkError } from \"../client/errors.js\";\nimport type { AnonymousLimitInfo } from \"../client/errors.js\";\nimport type { IpRiskResponse } from \"../client/types.js\";\nimport { resolveOptionalApiKey, resolveBaseUrl } from \"../utils/env.js\";\nimport { isValidIp } from \"../utils/ip.js\";\nimport { runPool } from \"../utils/pool.js\";\nimport { ExitCode, exitCodeForApiErrorCode, type ExitCodeValue } from \"../utils/exitCode.js\";\nimport { printJsonLine } from \"../output/jsonl.js\";\nimport { renderBatchTable } from \"../output/table.js\";\n\n/**\n * Client-side batch only: sends individual `GET /v1/ip-risk/{ip}` requests with controlled\n * concurrency. There is currently no server-side batch endpoint - do not call one.\n */\nconst MAX_CONCURRENCY = 20;\nconst DEFAULT_CONCURRENCY = 5;\n\nexport interface BatchItemError {\n code: string;\n message: string;\n requestId?: string;\n /** Present on `anonymous_daily_limit_reached`, so the summary can report the real allowance. */\n anonymousUsage?: AnonymousLimitInfo;\n}\n\nexport type BatchItemResult =\n | { ip: string; ok: true; result: IpRiskResponse }\n | { ip: string; ok: false; error: BatchItemError };\n\ninterface BatchOptions {\n apiKey?: string;\n baseUrl?: string;\n concurrency: string;\n jsonl?: boolean;\n timeout: string;\n maxRetries: string;\n}\n\nexport function registerBatchCommand(program: Command): void {\n program\n .command(\"batch <file>\")\n .description(\"Check multiple IP addresses (client-side batch over GET /v1/ip-risk/{ip})\")\n .option(\n \"--api-key <key>\",\n \"NetRiskScan API key (optional; uses the anonymous trial when omitted)\",\n )\n .option(\"--base-url <url>\", \"Override the API base URL (advanced)\")\n .option(\n \"--concurrency <n>\",\n `Number of concurrent requests (default: ${DEFAULT_CONCURRENCY}, max: ${MAX_CONCURRENCY})`,\n String(DEFAULT_CONCURRENCY),\n )\n .option(\"--jsonl\", \"Output newline-delimited JSON (one object per IP)\")\n .option(\"--timeout <ms>\", \"Request timeout in milliseconds\", \"10000\")\n .option(\"--max-retries <n>\", \"Maximum automatic retries for 429/503\", \"3\")\n .addHelpText(\n \"after\",\n `\nNotes:\n This is a client-side batch: it sends individual GET /v1/ip-risk/{ip}\n requests with controlled concurrency. NetRiskScan does not currently\n offer a server-side batch endpoint. Make sure the selected concurrency\n complies with the limits shown in your NetRiskScan Developer Dashboard.\n\n An API key is optional. Without an API key, requests use the anonymous daily\n trial, metered by public IP. How many remain is decided by the server, not by\n this CLI, and is reported in the summary after the table.\n\nInput format:\n One IP per line. Blank lines and lines starting with # are ignored.\n\nExamples:\n $ netriskscan batch ips.txt\n $ cat ips.txt | netriskscan batch -\n $ netriskscan batch ips.txt --concurrency 10 --jsonl > results.jsonl\n`,\n )\n .action(async (file: string, options: BatchOptions) => {\n await runBatch(file, options);\n });\n}\n\nasync function readIps(file: string): Promise<string[]> {\n const stream = file === \"-\" ? process.stdin : createReadStream(file, \"utf8\");\n const rl = createInterface({ input: stream, crlfDelay: Infinity });\n const ips: string[] = [];\n for await (const rawLine of rl) {\n const line = rawLine.trim();\n if (line === \"\" || line.startsWith(\"#\")) continue;\n ips.push(line);\n }\n return ips;\n}\n\nfunction parseConcurrency(value: string): number {\n const n = Number(value);\n if (!Number.isFinite(n) || n < 1) return DEFAULT_CONCURRENCY;\n if (n > MAX_CONCURRENCY) {\n process.stderr.write(\n `Warning: --concurrency ${n} exceeds the safety cap of ${MAX_CONCURRENCY}; using ${MAX_CONCURRENCY}.\\n` +\n \"Check your NetRiskScan Developer Dashboard for your plan's concurrency limit.\\n\",\n );\n return MAX_CONCURRENCY;\n }\n return Math.floor(n);\n}\n\nfunction toBatchError(err: unknown): BatchItemError {\n if (err instanceof NetRiskScanApiError) {\n return {\n code: err.code,\n message: err.message,\n requestId: err.requestId,\n anonymousUsage: err.anonymousUsage,\n };\n }\n if (err instanceof NetRiskScanNetworkError) {\n return { code: \"network_error\", message: err.message, requestId: err.requestId };\n }\n return { code: \"unknown_error\", message: err instanceof Error ? err.message : String(err) };\n}\n\nasync function runBatch(file: string, options: BatchOptions): Promise<void> {\n const ips = await readIps(file);\n if (ips.length === 0) {\n process.stderr.write(\"Error: no IP addresses found in input.\\n\");\n process.exitCode = ExitCode.InvalidArgument;\n return;\n }\n\n // No key means the anonymous trial. The CLI deliberately does not pre-check the input length\n // against a daily allowance: it cannot know how much of today's allowance was already spent,\n // and only the server can.\n const client = new NetRiskScanClient({\n apiKey: resolveOptionalApiKey(options.apiKey),\n baseUrl: resolveBaseUrl(options.baseUrl),\n timeout: Number(options.timeout),\n maxRetries: Number(options.maxRetries),\n });\n\n const concurrency = parseConcurrency(options.concurrency);\n\n const results = await runPool(ips, concurrency, async (ip): Promise<BatchItemResult> => {\n if (!isValidIp(ip)) {\n return {\n ip,\n ok: false,\n error: { code: \"invalid_ip\", message: `\"${ip}\" is not a valid IPv4 or IPv6 address.` },\n };\n }\n try {\n const { data } = await client.checkIp(ip);\n return { ip, ok: true, result: data };\n } catch (err) {\n return { ip, ok: false, error: toBatchError(err) };\n }\n });\n\n if (options.jsonl) {\n for (const item of results) {\n printJsonLine(item);\n }\n } else {\n renderBatchTable(results);\n }\n\n process.exitCode = computeBatchExitCode(results);\n}\n\nfunction computeBatchExitCode(results: readonly BatchItemResult[]): ExitCodeValue {\n const failures = results.filter((r): r is Extract<BatchItemResult, { ok: false }> => !r.ok);\n if (failures.length === 0) return ExitCode.Success;\n\n const codes = failures.map((f) => exitCodeForApiErrorCode(f.error.code));\n if (codes.includes(ExitCode.AuthError)) return ExitCode.AuthError;\n if (codes.includes(ExitCode.RateLimitOrQuota)) return ExitCode.RateLimitOrQuota;\n return ExitCode.ApiError;\n}\n","/** Runs `worker` over `items` with at most `concurrency` in flight, preserving result order. */\nexport async function runPool<T, R>(\n items: readonly T[],\n concurrency: number,\n worker: (item: T, index: number) => Promise<R>,\n): Promise<R[]> {\n const results: R[] = new Array(items.length);\n let cursor = 0;\n\n async function next(): Promise<void> {\n while (cursor < items.length) {\n const index = cursor++;\n results[index] = await worker(items[index] as T, index);\n }\n }\n\n const workerCount = Math.max(1, Math.min(concurrency, items.length));\n await Promise.all(Array.from({ length: workerCount }, () => next()));\n return results;\n}\n","/** One compact JSON object per line, so a failed line never breaks the rest of the stream. */\nexport function printJsonLine(data: unknown): void {\n process.stdout.write(`${JSON.stringify(data)}\\n`);\n}\n","import Table from \"cli-table3\";\nimport chalk from \"chalk\";\nimport type { BatchItemResult } from \"../commands/batch.js\";\nimport { ANONYMOUS_DAILY_LIMIT_CODE } from \"../client/errors.js\";\nimport {\n formatIndex,\n formatNumber,\n formatOrDash,\n formatProxyTypeCompact,\n formatTriState,\n row,\n} from \"./format.js\";\n\n/**\n * Anonymous-trial summary for a finished batch.\n *\n * The batch runs concurrently, so responses do not arrive in the order the server charged them:\n * one reply can say 22 remaining while a later-numbered one says 19. The lowest value observed is\n * the closest thing to the truth, so that is what gets reported. If any request was actually\n * refused for exhausting the trial, the answer is 0 no matter what the successful replies said.\n */\nfunction anonymousSummaryLines(results: readonly BatchItemResult[]): string[] {\n const remainings: number[] = [];\n const dailyLimits: number[] = [];\n let exhausted = false;\n\n for (const item of results) {\n if (item.ok) {\n const usage = item.result.usage;\n if (usage?.mode !== \"anonymous\") continue;\n if (typeof usage.remaining === \"number\") remainings.push(usage.remaining);\n if (typeof usage.dailyLimit === \"number\") dailyLimits.push(usage.dailyLimit);\n } else if (item.error.code === ANONYMOUS_DAILY_LIMIT_CODE) {\n exhausted = true;\n const limit = item.error.anonymousUsage?.dailyLimit;\n if (typeof limit === \"number\") dailyLimits.push(limit);\n }\n }\n\n if (!exhausted && remainings.length === 0) return [];\n\n const available = exhausted ? 0 : Math.min(...remainings);\n const lines = [\"\", chalk.bold(\"Anonymous trial\"), row(\"Available\", formatNumber(available))];\n if (dailyLimits.length > 0) {\n lines.push(row(\"Daily Limit\", formatNumber(Math.max(...dailyLimits))));\n }\n return lines;\n}\n\nexport function renderBatchTable(results: readonly BatchItemResult[]): void {\n const table = new Table({\n head: [\"IP\", \"Index\", \"Band\", \"Proxy\", \"Proxy Type\", \"VPN\", \"Tor\", \"Crawler\", \"Status\"],\n style: { head: [], border: [] },\n });\n\n for (const item of results) {\n if (item.ok) {\n const { result } = item;\n table.push([\n item.ip,\n formatIndex(result.risk.index),\n result.risk.band ?? \"N/A\",\n formatTriState(result.flags.proxy),\n formatProxyTypeCompact(result.flags.proxyType),\n formatTriState(result.flags.vpn),\n formatTriState(result.flags.tor),\n formatOrDash(result.flags.searchCrawlerName),\n chalk.green(\"ok\"),\n ]);\n } else {\n table.push([\n item.ip,\n \"-\",\n \"-\",\n \"-\",\n \"-\",\n \"-\",\n \"-\",\n \"-\",\n chalk.red(`error: ${item.error.code}`),\n ]);\n }\n }\n\n process.stdout.write(`${table.toString()}\\n`);\n\n const okCount = results.filter((r) => r.ok).length;\n const failCount = results.length - okCount;\n process.stdout.write(`\\n${okCount} succeeded, ${failCount} failed\\n`);\n\n const anonymous = anonymousSummaryLines(results);\n if (anonymous.length > 0) {\n process.stdout.write(`${anonymous.join(\"\\n\")}\\n`);\n }\n}\n"],"mappings":";;;AACA,SAAS,oBAAoB;AAC7B,SAAS,SAAS,YAAY;AAC9B,SAAS,qBAAqB;AAC9B,SAAS,SAAS,sBAAsB;;;ACHxC,OA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F;AAEF,qBAAqB,OAAO;AAC5B,qBAAqB,OAAO;AAC5B,qBAAqB,OAAO;AAE5B,QAAQ,aAAa;AAErB,IAAI;AACF,QAAM,QAAQ,WAAW,QAAQ,IAAI;AACvC,SAAS,KAAK;AACZ,MAAI,eAAe,gBAAgB;AACjC,QAAI,IAAI,SAAS,6BAA6B,IAAI,SAAS,qBAAqB;AAC9E,cAAQ,WAAW,SAAS;AAAA,IAC9B,OAAO;AACL,cAAQ,WAAW,SAAS;AAAA,IAC9B;AAAA,EACF,OAAO;AACL,YAAQ,OAAO,MAAM,qBAAqB,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAAA,CAAI;AAC9F,YAAQ,WAAW,SAAS;AAAA,EAC9B;AACF;","names":["chalk","chalk","LABEL_WIDTH","program","ora","program","ora","chalk","chalk","program"]}
1
+ {"version":3,"sources":["../src/cli.ts","../src/commands/check.ts","../src/client/errors.ts","../src/client/headers.ts","../src/client/retry.ts","../src/client/NetRiskScanClient.ts","../src/utils/env.ts","../src/utils/ip.ts","../src/utils/exitCode.ts","../src/output/human.ts","../src/output/format.ts","../src/output/json.ts","../src/output/errors.ts","../src/commands/usage.ts","../src/commands/batch.ts","../src/utils/pool.ts","../src/output/jsonl.ts","../src/output/table.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { Command, CommanderError } from \"commander\";\nimport { registerCheckCommand } from \"./commands/check.js\";\nimport { registerUsageCommand } from \"./commands/usage.js\";\nimport { registerBatchCommand } from \"./commands/batch.js\";\nimport { ExitCode } from \"./utils/exitCode.js\";\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\nconst pkg = JSON.parse(readFileSync(join(__dirname, \"..\", \"package.json\"), \"utf8\")) as {\n version: string;\n};\n\nconst program = new Command();\n\nprogram\n .name(\"netriskscan\")\n .description(\n \"Query IP risk, network intelligence and reputation data from the NetRiskScan Developer API.\",\n )\n .version(pkg.version, \"-V, --version\", \"Show the CLI version\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ netriskscan check 1.1.1.1 # no account or API key needed\n $ netriskscan check 1.1.1.1 --json\n $ netriskscan usage # needs an API key\n $ netriskscan batch ips.txt --jsonl\n\ncheck and batch work with no setup at all: without an API key they use the\nanonymous daily trial, metered by public IP. The server reports how many\nrequests are left; the CLI never estimates it.\n\nEnvironment variables:\n NETRISKSCAN_API_KEY Optional for check/batch; required for account usage.\n\nNetRiskScan provides diagnostic network intelligence. Results should not be\ntreated as proof of malicious activity or used as the sole basis for legal,\nemployment, credit, identity, or other high-impact decisions.\n\nLearn more: https://github.com/TeamQQ/netriskscan-cli\n`,\n );\n\nregisterCheckCommand(program);\nregisterUsageCommand(program);\nregisterBatchCommand(program);\n\nprogram.exitOverride();\n\ntry {\n await program.parseAsync(process.argv);\n} catch (err) {\n if (err instanceof CommanderError) {\n if (err.code === \"commander.helpDisplayed\" || err.code === \"commander.version\") {\n process.exitCode = ExitCode.Success;\n } else {\n process.exitCode = ExitCode.InvalidArgument;\n }\n } else {\n process.stderr.write(`Unexpected error: ${err instanceof Error ? err.message : String(err)}\\n`);\n process.exitCode = ExitCode.GeneralError;\n }\n}\n","import type { Command } from \"commander\";\nimport ora from \"ora\";\nimport { NetRiskScanClient } from \"../client/NetRiskScanClient.js\";\nimport {\n ANONYMOUS_DAILY_LIMIT_CODE,\n NetRiskScanApiError,\n NetRiskScanNetworkError,\n} from \"../client/errors.js\";\nimport type { IpRiskResponse, RiskFlagName } from \"../client/types.js\";\nimport { resolveOptionalApiKey, resolveBaseUrl } from \"../utils/env.js\";\nimport { isValidIp } from \"../utils/ip.js\";\nimport { ExitCode, exitCodeForApiErrorCode, type ExitCodeValue } from \"../utils/exitCode.js\";\nimport { renderCheckResult, renderVerboseMeta } from \"../output/human.js\";\nimport { printJson } from \"../output/json.js\";\nimport { printAnonymousLimitError, printApiError, printNetworkError } from \"../output/errors.js\";\n\nconst KNOWN_FLAGS: readonly RiskFlagName[] = [\n \"proxy\",\n \"vpn\",\n \"tor\",\n \"datacenter\",\n \"scanner\",\n \"abuse\",\n];\n\ninterface CheckOptions {\n apiKey?: string;\n baseUrl?: string;\n json?: boolean;\n verbose?: boolean;\n debug?: boolean;\n timeout: string;\n maxRetries: string;\n failBelow?: string;\n failOn: string[];\n}\n\nfunction collect(value: string, previous: string[]): string[] {\n return [...previous, value];\n}\n\nexport function registerCheckCommand(program: Command): void {\n program\n .command(\"check <ip>\")\n .description(\"Check IP risk and network intelligence\")\n .option(\n \"--api-key <key>\",\n \"NetRiskScan API key (optional; uses the anonymous trial when omitted)\",\n )\n .option(\"--base-url <url>\", \"Override the API base URL (advanced)\")\n .option(\"--json\", \"Output machine-readable JSON\")\n .option(\"--verbose\", \"Show rate limit, quota and request id\")\n .option(\"--debug\", \"Show debug information on failure\")\n .option(\"--timeout <ms>\", \"Request timeout in milliseconds\", \"10000\")\n .option(\"--max-retries <n>\", \"Maximum automatic retries for 429/503\", \"3\")\n .option(\"--fail-below <index>\", \"Exit non-zero if risk.index is below this threshold (CI use)\")\n .option(\n \"--fail-on <flag>\",\n \"Exit non-zero if the given flag is true (repeatable): proxy, vpn, tor, datacenter, scanner, abuse\",\n collect,\n [] as string[],\n )\n .addHelpText(\n \"after\",\n `\nExamples:\n $ netriskscan check 1.1.1.1\n $ netriskscan check 1.1.1.1 --json\n $ netriskscan check 1.2.3.4 --fail-below 60\n $ netriskscan check 1.2.3.4 --fail-on tor --fail-on proxy\n\nNotes:\n An API key is optional. Without one, requests use the anonymous daily trial,\n metered by public IP; the response reports how many are left.\n`,\n )\n .action(async (ip: string, options: CheckOptions) => {\n await runCheck(ip, options);\n });\n}\n\nasync function runCheck(ip: string, options: CheckOptions): Promise<void> {\n const useJson = Boolean(options.json);\n\n for (const flag of options.failOn) {\n if (!KNOWN_FLAGS.includes(flag as RiskFlagName)) {\n process.stderr.write(\n `Error: unknown --fail-on flag \"${flag}\". Expected one of: ${KNOWN_FLAGS.join(\", \")}\\n`,\n );\n process.exitCode = ExitCode.InvalidArgument;\n return;\n }\n }\n\n if (!isValidIp(ip)) {\n process.stderr.write(`Error: \"${ip}\" is not a valid IPv4 or IPv6 address.\\n`);\n process.exitCode = ExitCode.InvalidArgument;\n return;\n }\n\n // Undefined is a supported mode: the client then omits Authorization and the server serves the\n // request from the anonymous daily trial.\n const client = new NetRiskScanClient({\n apiKey: resolveOptionalApiKey(options.apiKey),\n baseUrl: resolveBaseUrl(options.baseUrl),\n timeout: Number(options.timeout),\n maxRetries: Number(options.maxRetries),\n });\n\n const spinner = useJson\n ? undefined\n : ora({\n text: `Checking ${ip}...`,\n stream: process.stderr,\n isEnabled: process.stderr.isTTY,\n }).start();\n\n try {\n const { data, meta } = await client.checkIp(ip);\n spinner?.stop();\n\n if (useJson) {\n printJson(data);\n } else {\n renderCheckResult(ip, data);\n if (options.verbose) {\n renderVerboseMeta(meta);\n }\n }\n\n process.exitCode = evaluateCiPolicy(data, options);\n } catch (err) {\n spinner?.stop();\n handleCheckError(err, options);\n }\n}\n\nfunction evaluateCiPolicy(data: IpRiskResponse, options: CheckOptions): ExitCodeValue {\n if (options.failOn.length > 0) {\n for (const flag of options.failOn) {\n if (data.flags[flag as RiskFlagName] === true) {\n return ExitCode.CiPolicyFailed;\n }\n }\n }\n\n if (options.failBelow !== undefined) {\n if (data.risk.index === null) {\n return ExitCode.AssessmentUnavailable;\n }\n if (data.risk.index < Number(options.failBelow)) {\n return ExitCode.CiPolicyFailed;\n }\n }\n\n return ExitCode.Success;\n}\n\nfunction handleCheckError(err: unknown, options: CheckOptions): void {\n if (err instanceof NetRiskScanApiError) {\n if (err.code === ANONYMOUS_DAILY_LIMIT_CODE) {\n printAnonymousLimitError(err);\n } else {\n printApiError(err, { debug: options.debug });\n }\n process.exitCode = exitCodeForApiErrorCode(err.code);\n return;\n }\n if (err instanceof NetRiskScanNetworkError) {\n printNetworkError(err, { debug: options.debug });\n process.exitCode = ExitCode.ApiError;\n return;\n }\n if (options.debug && err instanceof Error) {\n process.stderr.write(`${err.stack ?? err.message}\\n`);\n } else {\n process.stderr.write(`Error: ${err instanceof Error ? err.message : String(err)}\\n`);\n }\n process.exitCode = ExitCode.GeneralError;\n}\n","export const KNOWN_ERROR_CODES = [\n \"invalid_ip\",\n \"invalid_request\",\n \"unsupported_parameter\",\n \"invalid_api_key\",\n \"api_key_disabled\",\n \"scope_not_allowed\",\n \"not_found\",\n \"feature_not_available\",\n \"rate_limit_exceeded\",\n \"quota_exceeded\",\n \"anonymous_daily_limit_reached\",\n \"temporarily_unavailable\",\n] as const;\n\nexport type KnownErrorCode = (typeof KNOWN_ERROR_CODES)[number];\n\n/**\n * The anonymous trial's daily allowance is spent. Deterministic until the UTC reset, so unlike\n * `rate_limit_exceeded` it is never retried - see `isRetryableFailure`.\n */\nexport const ANONYMOUS_DAILY_LIMIT_CODE = \"anonymous_daily_limit_reached\";\n\n/**\n * Anonymous-trial allowance carried on a `429 anonymous_daily_limit_reached`.\n *\n * Parsed once in the client layer so the output layer never has to touch an HTTP body. Every\n * field is optional: a server that only sends `code` and `message` must still work.\n */\nexport interface AnonymousLimitInfo {\n dailyLimit?: number;\n used?: number;\n remaining?: number;\n resetAt?: string;\n signupUrl?: string;\n}\n\nexport class NetRiskScanError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"NetRiskScanError\";\n }\n}\n\n/** Thrown for client-side configuration problems, e.g. a missing API key. */\nexport class NetRiskScanConfigError extends NetRiskScanError {\n constructor(message: string) {\n super(message);\n this.name = \"NetRiskScanConfigError\";\n }\n}\n\nexport interface NetRiskScanApiErrorOptions {\n status: number;\n code: string;\n requestId?: string;\n retryAfter?: number;\n anonymousUsage?: AnonymousLimitInfo;\n}\n\n/** Thrown when the Developer API responds with a non-2xx status. */\nexport class NetRiskScanApiError extends NetRiskScanError {\n readonly status: number;\n readonly code: string;\n readonly requestId?: string;\n readonly retryAfter?: number;\n /** Present when the server reported anonymous-trial allowance alongside the error. */\n readonly anonymousUsage?: AnonymousLimitInfo;\n\n constructor(message: string, options: NetRiskScanApiErrorOptions) {\n super(message);\n this.name = \"NetRiskScanApiError\";\n this.status = options.status;\n this.code = options.code;\n this.requestId = options.requestId;\n this.retryAfter = options.retryAfter;\n this.anonymousUsage = options.anonymousUsage;\n }\n}\n\nexport interface NetRiskScanNetworkErrorOptions {\n cause?: unknown;\n requestId?: string;\n}\n\n/** Thrown for transport-level failures: timeouts, DNS errors, connection resets, etc. */\nexport class NetRiskScanNetworkError extends NetRiskScanError {\n override readonly cause?: unknown;\n readonly requestId?: string;\n\n constructor(message: string, options: NetRiskScanNetworkErrorOptions = {}) {\n super(message);\n this.name = \"NetRiskScanNetworkError\";\n this.cause = options.cause;\n this.requestId = options.requestId;\n }\n}\n","import { randomBytes } from \"node:crypto\";\nimport type { QuotaInfo, RateLimitInfo } from \"./types.js\";\n\nconst REQUEST_ID_PATTERN = /^req_[A-Za-z0-9_-]{8,56}$/;\n\nexport function isValidRequestId(id: string): boolean {\n return REQUEST_ID_PATTERN.test(id);\n}\n\nexport function generateRequestId(): string {\n return `req_${randomBytes(12).toString(\"hex\")}`;\n}\n\nfunction parseIntHeader(value: string | null): number | undefined {\n if (value === null) return undefined;\n const n = Number(value);\n return Number.isFinite(n) ? n : undefined;\n}\n\nexport function parseRateLimit(headers: Headers): RateLimitInfo {\n return {\n limit: parseIntHeader(headers.get(\"x-ratelimit-limit\")),\n remaining: parseIntHeader(headers.get(\"x-ratelimit-remaining\")),\n reset: parseIntHeader(headers.get(\"x-ratelimit-reset\")),\n };\n}\n\nexport function parseQuota(headers: Headers): QuotaInfo {\n return {\n limit: parseIntHeader(headers.get(\"x-quota-limit\")),\n used: parseIntHeader(headers.get(\"x-quota-used\")),\n remaining: parseIntHeader(headers.get(\"x-quota-remaining\")),\n };\n}\n\n/** Never log or print a full API key. Keeps a short prefix/suffix for support purposes. */\nexport function redactApiKey(key: string): string {\n if (key.length <= 9) return \"*\".repeat(key.length);\n return `${key.slice(0, 9)}${\"*\".repeat(4)}${key.slice(-4)}`;\n}\n\nexport function redactAuthorizationHeader(value: string): string {\n const match = /^Bearer\\s+(.+)$/i.exec(value);\n if (!match) return \"[REDACTED]\";\n return `Bearer ${redactApiKey(match[1])}`;\n}\n","import { ANONYMOUS_DAILY_LIMIT_CODE } from \"./errors.js\";\n\n/** Only 429 and 503 are automatically retried; 400/401/403/404 never are. */\nexport function isRetryableStatus(status: number): boolean {\n return status === 429 || status === 503;\n}\n\n/**\n * Status *and* error code decide retryability, because not every 429 is transient.\n *\n * `rate_limit_exceeded` is a short per-minute window and retrying is the right behaviour.\n * `anonymous_daily_limit_reached` is a spent daily allowance that cannot come back before the\n * UTC reset, so retrying it only burns three more round-trips before failing identically.\n */\nexport function isRetryableFailure(status: number, code?: string): boolean {\n if (code === ANONYMOUS_DAILY_LIMIT_CODE) return false;\n return isRetryableStatus(status);\n}\n\nconst BASE_DELAY_MS = 1000;\nconst MAX_JITTER_MS = 250;\n\n/** Honors Retry-After when present; otherwise exponential backoff (1s, 2s, 4s, ...) with jitter. */\nexport function computeBackoffMs(attempt: number, retryAfterSeconds?: number): number {\n if (\n typeof retryAfterSeconds === \"number\" &&\n Number.isFinite(retryAfterSeconds) &&\n retryAfterSeconds >= 0\n ) {\n return retryAfterSeconds * 1000;\n }\n const base = BASE_DELAY_MS * 2 ** Math.max(0, attempt - 1);\n const jitter = Math.random() * MAX_JITTER_MS;\n return base + jitter;\n}\n\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n","import { NetRiskScanApiError, NetRiskScanConfigError, NetRiskScanNetworkError } from \"./errors.js\";\nimport { generateRequestId, isValidRequestId, parseQuota, parseRateLimit } from \"./headers.js\";\nimport { computeBackoffMs, isRetryableFailure, sleep } from \"./retry.js\";\nimport type { AnonymousLimitInfo } from \"./errors.js\";\nimport type {\n ApiErrorBody,\n ApiResult,\n IpRiskResponse,\n NetRiskScanClientOptions,\n RequestOptions,\n UsageResponse,\n} from \"./types.js\";\n\nconst DEFAULT_BASE_URL = \"https://api.netriskscan.com\";\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_MAX_RETRIES = 3;\n\nfunction isAbortError(err: unknown): boolean {\n return err instanceof Error && err.name === \"AbortError\";\n}\n\nasync function safeJson(res: Response): Promise<ApiErrorBody | undefined> {\n try {\n return (await res.json()) as ApiErrorBody;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Lifts the anonymous-trial fields off an error body, once, here. HTTP bodies are parsed in the\n * client layer only - the output layer receives a typed error, never JSON.\n */\nfunction parseAnonymousLimitInfo(body: ApiErrorBody | undefined): AnonymousLimitInfo | undefined {\n const error = body?.error;\n if (!error) return undefined;\n const { dailyLimit, used, remaining, resetAt, signupUrl } = error;\n if (\n dailyLimit === undefined &&\n used === undefined &&\n remaining === undefined &&\n resetAt === undefined &&\n signupUrl === undefined\n ) {\n return undefined;\n }\n return { dailyLimit, used, remaining, resetAt, signupUrl };\n}\n\n/**\n * Client for the NetRiskScan Developer API (`/v1/*` only).\n *\n * Works with no configuration at all: without an API key it sends no `Authorization` header and\n * the server serves the request from the anonymous daily trial, metered by public IP.\n *\n * @example Anonymous - no account, no key\n * ```ts\n * const client = new NetRiskScanClient();\n * const { data } = await client.checkIp(\"1.1.1.1\");\n * console.log(data.risk.index);\n * console.log(data.usage?.remaining);\n * ```\n *\n * @example Pass `apiKey` to use Developer Account quota instead of the anonymous trial\n * ```ts\n * const client = new NetRiskScanClient({ apiKey: process.env.NETRISKSCAN_API_KEY });\n * ```\n */\nexport class NetRiskScanClient {\n private readonly apiKey?: string;\n private readonly baseUrl: string;\n private readonly timeout: number;\n private readonly maxRetries: number;\n\n constructor(options: NetRiskScanClientOptions = {}) {\n // An absent key is a supported mode, not a misconfiguration: it selects the anonymous trial.\n this.apiKey = options.apiKey || undefined;\n this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n this.timeout = options.timeout ?? DEFAULT_TIMEOUT_MS;\n this.maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;\n }\n\n async checkIp(ip: string, options: RequestOptions = {}): Promise<ApiResult<IpRiskResponse>> {\n return this.request<IpRiskResponse>(`/v1/ip-risk/${encodeURIComponent(ip)}`, options);\n }\n\n /**\n * Account plan, billing period and quota. Unlike {@link checkIp} this is account data, so it\n * has no anonymous equivalent and requires an API key.\n */\n async getUsage(options: RequestOptions = {}): Promise<ApiResult<UsageResponse>> {\n if (!this.apiKey) {\n throw new NetRiskScanConfigError(\"An API key is required to query account usage.\");\n }\n return this.request<UsageResponse>(\"/v1/usage\", options);\n }\n\n private async request<T>(path: string, options: RequestOptions): Promise<ApiResult<T>> {\n const requestId =\n options.requestId && isValidRequestId(options.requestId)\n ? options.requestId\n : generateRequestId();\n\n let attempt = 0;\n\n while (true) {\n const timeoutController = new AbortController();\n const timer = setTimeout(() => timeoutController.abort(), this.timeout);\n const onExternalAbort = (): void => timeoutController.abort();\n options.signal?.addEventListener(\"abort\", onExternalAbort);\n\n try {\n const headers: Record<string, string> = {\n Accept: \"application/json\",\n \"X-Request-Id\": requestId,\n };\n // Only ever sent when a key actually exists. A `Bearer undefined` would read as a bad key\n // and earn a 401 instead of falling through to the anonymous trial.\n if (this.apiKey) {\n headers.Authorization = `Bearer ${this.apiKey}`;\n }\n\n const res = await fetch(`${this.baseUrl}${path}`, {\n method: \"GET\",\n headers,\n signal: timeoutController.signal,\n });\n\n const rateLimit = parseRateLimit(res.headers);\n const quota = parseQuota(res.headers);\n const responseRequestId = res.headers.get(\"x-request-id\") ?? requestId;\n\n if (res.ok) {\n const data = (await res.json()) as T;\n return { data, meta: { requestId: responseRequestId, rateLimit, quota } };\n }\n\n const body = await safeJson(res);\n const retryAfterHeader = res.headers.get(\"retry-after\");\n const retryAfter = retryAfterHeader !== null ? Number(retryAfterHeader) : undefined;\n\n if (isRetryableFailure(res.status, body?.error?.code) && attempt < this.maxRetries) {\n attempt += 1;\n await sleep(computeBackoffMs(attempt, retryAfter));\n continue;\n }\n\n throw new NetRiskScanApiError(body?.error?.message ?? res.statusText, {\n status: res.status,\n code: body?.error?.code ?? \"unknown_error\",\n requestId: body?.error?.requestId ?? responseRequestId,\n retryAfter,\n anonymousUsage: parseAnonymousLimitInfo(body),\n });\n } catch (err) {\n if (err instanceof NetRiskScanApiError) {\n throw err;\n }\n if (isAbortError(err)) {\n if (options.signal?.aborted) {\n throw err;\n }\n throw new NetRiskScanNetworkError(`Request timed out after ${this.timeout}ms`, {\n cause: err,\n requestId,\n });\n }\n throw new NetRiskScanNetworkError(\n err instanceof Error ? err.message : \"Network request failed\",\n {\n cause: err,\n requestId,\n },\n );\n } finally {\n clearTimeout(timer);\n options.signal?.removeEventListener(\"abort\", onExternalAbort);\n }\n }\n }\n}\n","import { NetRiskScanConfigError } from \"../client/errors.js\";\n\n/**\n * Resolves the API key for endpoints that work without one (`check`, `batch`).\n *\n * Returning `undefined` is a valid outcome, not a failure: it selects the anonymous trial. The\n * precedence is `--api-key` > `NETRISKSCAN_API_KEY` > anonymous. A key that is present but wrong\n * is still passed through - the CLI never silently drops a key the user configured and retries\n * anonymously, because that would turn an authentication problem into a confusing success.\n */\nexport function resolveOptionalApiKey(cliValue?: string): string | undefined {\n return cliValue || process.env.NETRISKSCAN_API_KEY || undefined;\n}\n\n/**\n * Resolves the API key for account-level endpoints (`usage`), which have no anonymous form.\n *\n * The message names the command on purpose: a generic \"API key is required\" here would suggest\n * the whole CLI needs an account, which is no longer true.\n */\nexport function resolveRequiredApiKey(cliValue?: string): string {\n const apiKey = resolveOptionalApiKey(cliValue);\n if (!apiKey) {\n throw new NetRiskScanConfigError(\n \"An API key is required for the usage command.\\n\\nSet NETRISKSCAN_API_KEY or use --api-key.\",\n );\n }\n return apiKey;\n}\n\nexport function resolveBaseUrl(cliValue?: string): string | undefined {\n return cliValue ?? process.env.NETRISKSCAN_BASE_URL;\n}\n","import { isIP } from \"node:net\";\n\nexport function isValidIp(value: string): boolean {\n return isIP(value) !== 0;\n}\n","import type { KnownErrorCode } from \"../client/errors.js\";\n\nexport const ExitCode = {\n Success: 0,\n GeneralError: 1,\n InvalidArgument: 2,\n AuthError: 3,\n ApiError: 4,\n RateLimitOrQuota: 5,\n CiPolicyFailed: 6,\n AssessmentUnavailable: 7,\n} as const;\n\nexport type ExitCodeValue = (typeof ExitCode)[keyof typeof ExitCode];\n\nexport function exitCodeForApiErrorCode(code: string): ExitCodeValue {\n switch (code as KnownErrorCode) {\n case \"invalid_api_key\":\n case \"api_key_disabled\":\n case \"scope_not_allowed\":\n return ExitCode.AuthError;\n // The anonymous daily trial is an allowance like any other, so it reuses code 5 rather than\n // adding an eighth exit code that every script would have to learn.\n case \"rate_limit_exceeded\":\n case \"quota_exceeded\":\n case \"anonymous_daily_limit_reached\":\n return ExitCode.RateLimitOrQuota;\n default:\n return ExitCode.ApiError;\n }\n}\n","import chalk from \"chalk\";\nimport type {\n IpLocation,\n IpRiskResponse,\n RequestUsage,\n ResponseMeta,\n RiskBand,\n RiskReason,\n UsageResponse,\n} from \"../client/types.js\";\nimport {\n formatDate,\n formatGeoName,\n formatIndex,\n formatNullable,\n formatNumber,\n formatOrDash,\n formatProxyType,\n formatRiskReasonCode,\n formatTriState,\n formatUtcTimestamp,\n reasonRow,\n row,\n} from \"./format.js\";\n\n/**\n * Anonymous-trial rows for the human `check` output.\n *\n * `Available` is printed verbatim from `usage.remaining` - the server is the only authority on\n * what is left, so this never falls back to `dailyLimit - used`. Each row is emitted only when\n * its value is actually a number, because `0` is a legitimate value that a truthiness check\n * would swallow on exactly the run where it matters most.\n */\nfunction anonymousUsageLines(usage: RequestUsage): string[] {\n const lines: string[] = [];\n if (typeof usage.remaining === \"number\") {\n lines.push(row(\"Available\", formatNumber(usage.remaining)));\n }\n if (typeof usage.dailyLimit === \"number\") {\n lines.push(row(\"Daily Limit\", formatNumber(usage.dailyLimit)));\n }\n const reset = formatUtcTimestamp(usage.resetAt);\n if (reset !== undefined) {\n lines.push(row(\"Reset\", reset));\n }\n return lines;\n}\n\n/**\n * Rows for the server's own explanations of the assessment.\n *\n * Rendering only: the list is whatever `risk.reasons` contained, in the server's order, with no\n * entry derived from `flags`/`network`, none filtered out, and none re-ranked. An empty or absent\n * list yields no rows at all, so the caller drops the section rather than printing a heading over\n * nothing - the common case for an ordinary address.\n */\nfunction riskReasonLines(reasons: readonly RiskReason[] | undefined): string[] {\n if (reasons === undefined || reasons.length === 0) return [];\n return reasons.map((reason) => {\n const severity = reason.severity ?? \"\";\n return reasonRow(formatRiskReasonCode(reason.code), severityColor(severity)(severity));\n });\n}\n\n/**\n * Severity is a secondary cue, never the message itself: the label already says what was found, so\n * an unrecognised severity simply renders uncoloured instead of being mapped to a guessed level.\n *\n * `info` is deliberately dim rather than warning-coloured - `Verified Search Crawler` and\n * `Public Infrastructure` explain why an address is *clean*, and colouring them like a threat\n * would misrepresent the server's own assessment.\n */\nfunction severityColor(severity: string): (text: string) => string {\n switch (severity) {\n case \"critical\":\n case \"high\":\n return chalk.red;\n case \"medium\":\n return chalk.yellow;\n case \"info\":\n return chalk.gray;\n default:\n return (text: string) => text;\n }\n}\n\n/**\n * Rows for network-level geolocation - where the network is routed, not where a device is.\n *\n * Each row appears only when the server actually sent that field: geo resolution is independently\n * partial (a country with no city is normal), and a wall of \"N/A\" rows would be noise dressed up as\n * data. An absent `location` object yields no rows, so the caller drops the whole section.\n */\nfunction locationLines(location: IpLocation | null | undefined): string[] {\n if (!location) return [];\n const lines: string[] = [];\n const country = formatGeoName(location.country, location.countryCode);\n if (country !== undefined) lines.push(row(\"Country\", country));\n const region = formatGeoName(location.region, location.regionCode);\n if (region !== undefined) lines.push(row(\"Region\", region));\n if (location.city) lines.push(row(\"City\", location.city));\n const continent = formatGeoName(location.continent, location.continentCode);\n if (continent !== undefined) lines.push(row(\"Continent\", continent));\n if (location.postalCode) lines.push(row(\"Postal Code\", location.postalCode));\n // A coordinate pair is shown only when the server sent both halves as real numbers. `0` is a\n // legitimate coordinate, so this is a type check, never a truthiness check; an anycast network\n // sends null for both and gets no row rather than a fabricated position.\n const { latitude, longitude } = location;\n if (\n typeof latitude === \"number\" &&\n Number.isFinite(latitude) &&\n typeof longitude === \"number\" &&\n Number.isFinite(longitude)\n ) {\n lines.push(row(\"Coordinates\", `${latitude}, ${longitude}`));\n }\n if (location.timeZone) lines.push(row(\"Time Zone\", location.timeZone));\n return lines;\n}\n\nfunction bandColor(band: RiskBand | null): (text: string) => string {\n switch (band) {\n case \"excellent\":\n case \"good\":\n return chalk.green;\n case \"fair\":\n return chalk.yellow;\n case \"poor\":\n case \"high_risk\":\n return chalk.red;\n default:\n return chalk.gray;\n }\n}\n\nexport function renderCheckResult(ip: string, data: IpRiskResponse): void {\n const lines: string[] = [];\n lines.push(chalk.bold(\"NetRiskScan\"));\n lines.push(\"\");\n lines.push(row(\"IP\", ip));\n lines.push(row(\"Index\", formatIndex(data.risk.index)));\n lines.push(\n row(\"Band\", data.risk.band ? bandColor(data.risk.band)(data.risk.band) : chalk.gray(\"N/A\")),\n );\n lines.push(row(\"Assessment\", data.risk.assessmentGrade));\n lines.push(\"\");\n\n if (data.risk.assessmentGrade === \"insufficient\" && data.risk.index === null) {\n lines.push(chalk.yellow(\"This address could not be reliably assessed.\"));\n lines.push(\"\");\n }\n\n // Directly under the verdict it explains, and only when the server sent one: these are the\n // server's reasons, so an empty or absent list means there is nothing to show - never a cue for\n // the CLI to work some out from flags.\n const reasonLines = riskReasonLines(data.risk.reasons);\n if (reasonLines.length > 0) {\n lines.push(chalk.bold(\"Risk Reasons\"));\n lines.push(...reasonLines);\n lines.push(\"\");\n }\n\n lines.push(chalk.bold(\"Network\"));\n lines.push(row(\"Type\", formatNullable(data.network.type)));\n // Omitted entirely when absent, unlike the fields around them, which render \"N/A\". Those describe every\n // address, so a missing one is worth showing as missing; these two exist only for the minority of\n // addresses NetRiskScan holds a first-party record for, and printing \"Profile N/A\" on every residential\n // lookup would be noise rather than information.\n if (data.network.profile) {\n lines.push(row(\"Profile\", data.network.profile));\n }\n if (data.network.service) {\n lines.push(row(\"Service\", data.network.service));\n }\n lines.push(row(\"Connection\", formatNullable(data.network.connectionType)));\n lines.push(row(\"ASN\", formatNullable(data.network.asn)));\n lines.push(row(\"Organization\", formatNullable(data.network.organization)));\n // Schema 1.6.0 additions, dropped when absent for the same reason as Profile/Service above.\n // Both are server-owned facts: never inferred from the ASN, organization or hostname, and the\n // range is never computed client-side.\n if (data.network.domain) {\n lines.push(row(\"Domain\", data.network.domain));\n }\n if (data.network.range) {\n lines.push(row(\"Network Range\", data.network.range));\n }\n lines.push(\"\");\n\n const geoLines = locationLines(data.location);\n if (geoLines.length > 0) {\n lines.push(chalk.bold(\"Location\"));\n lines.push(...geoLines);\n lines.push(\"\");\n }\n\n lines.push(chalk.bold(\"Signals\"));\n lines.push(row(\"Proxy\", formatTriState(data.flags.proxy)));\n lines.push(row(\"Proxy Type\", formatProxyType(data.flags.proxyType)));\n lines.push(row(\"VPN\", formatTriState(data.flags.vpn)));\n lines.push(row(\"Tor\", formatTriState(data.flags.tor)));\n lines.push(row(\"Datacenter\", formatTriState(data.flags.datacenter)));\n lines.push(row(\"Scanner\", formatTriState(data.flags.scanner)));\n lines.push(row(\"Abuse\", formatTriState(data.flags.abuse)));\n lines.push(\"\");\n\n // Identity, not a risk signal: a verified crawler must never read as a threat, so it gets its own\n // section rather than living inside Signals.\n lines.push(chalk.bold(\"Identity\"));\n lines.push(row(\"Search Crawler\", formatTriState(data.flags.searchCrawler)));\n lines.push(row(\"Crawler\", formatOrDash(data.flags.searchCrawlerName)));\n lines.push(\"\");\n\n // Only for the anonymous trial. An API-key caller's allowance is a billing-period quota, a\n // different thing entirely, and stays behind --verbose where it always was.\n if (data.usage?.mode === \"anonymous\") {\n const usageLines = anonymousUsageLines(data.usage);\n if (usageLines.length > 0) {\n lines.push(chalk.bold(\"Usage\"));\n lines.push(...usageLines);\n lines.push(\"\");\n }\n }\n\n lines.push(row(\"Request ID\", data.requestId));\n lines.push(\"\");\n\n lines.push(chalk.bold(\"Explore\"));\n lines.push(row(\"Web\", \"https://www.netriskscan.com\"));\n lines.push(row(\"GitHub\", \"https://github.com/TeamQQ/netriskscan-cli\"));\n\n process.stdout.write(`${lines.join(\"\\n\")}\\n`);\n}\n\nexport function renderVerboseMeta(meta: ResponseMeta): void {\n const lines: string[] = [\"\"];\n if (meta.rateLimit.remaining !== undefined && meta.rateLimit.limit !== undefined) {\n lines.push(\n row(\n \"Rate limit\",\n `${formatNumber(meta.rateLimit.remaining)} / ${formatNumber(meta.rateLimit.limit)} remaining`,\n ),\n );\n }\n if (meta.quota.remaining !== undefined && meta.quota.limit !== undefined) {\n lines.push(\n row(\n \"Quota\",\n `${formatNumber(meta.quota.remaining)} / ${formatNumber(meta.quota.limit)} remaining`,\n ),\n );\n }\n lines.push(row(\"Request ID\", meta.requestId));\n process.stdout.write(`${lines.join(\"\\n\")}\\n`);\n}\n\nexport function renderUsageResult(data: UsageResponse): void {\n const lines: string[] = [];\n lines.push(chalk.bold(\"NetRiskScan Usage\"));\n lines.push(\"\");\n lines.push(row(\"Plan\", data.plan));\n lines.push(\"\");\n lines.push(chalk.bold(\"Usage\"));\n lines.push(row(\"Used\", formatNumber(data.units.used)));\n lines.push(row(\"Remaining\", formatNumber(data.units.remaining)));\n lines.push(row(\"Limit\", formatNumber(data.units.limit)));\n lines.push(\"\");\n lines.push(chalk.bold(\"Rate limit\"));\n lines.push(row(\"Requests / minute\", formatNumber(data.rateLimit.requestsPerMinute)));\n lines.push(\"\");\n lines.push(chalk.bold(\"Billing period\"));\n lines.push(`${formatDate(data.period.start)} → ${formatDate(data.period.end)}`);\n\n process.stdout.write(`${lines.join(\"\\n\")}\\n`);\n}\n","/**\n * Formats a tri-state flag. `null`/`undefined` means \"not enough signal to judge\" and\n * must never collapse into \"No\" - that would silently turn \"unknown\" into \"false\".\n */\nexport function formatTriState(value: boolean | null | undefined): string {\n if (value === true) return \"Yes\";\n if (value === false) return \"No\";\n return \"Unknown\";\n}\n\nconst PROXY_TYPE_LABELS: Record<string, string> = {\n residential_proxy: \"Residential Proxy\",\n isp_proxy: \"ISP Proxy\",\n mobile_proxy: \"Mobile Proxy\",\n datacenter_proxy: \"Datacenter Proxy\",\n unknown_proxy: \"Unknown Proxy\",\n};\n\nconst PROXY_TYPE_LABELS_COMPACT: Record<string, string> = {\n residential_proxy: \"Residential\",\n isp_proxy: \"ISP\",\n mobile_proxy: \"Mobile\",\n datacenter_proxy: \"Datacenter\",\n unknown_proxy: \"Unknown\",\n};\n\n/**\n * Human-readable label for `flags.proxyType`. This is a classification detail, not a tri-state\n * signal - it only refines an address already flagged `proxy: true` - so missing/`null`/empty\n * renders as `-`, matching the placeholder every other Signals row uses for \"not applicable\", never\n * \"Unknown\".\n *\n * An unrecognised raw value renders as itself rather than throwing: `ProxyType` is a documented\n * union, but this reads live server JSON that a compile-time cast cannot actually enforce, and a\n * server that adds a new proxy subtype must not crash CLIs already in the wild.\n */\nexport function formatProxyType(value: string | null | undefined): string {\n if (value === null || value === undefined || value === \"\") return \"-\";\n return PROXY_TYPE_LABELS[value] ?? value;\n}\n\n/** Same mapping as {@link formatProxyType}, abbreviated for the batch table's narrower columns. */\nexport function formatProxyTypeCompact(value: string | null | undefined): string {\n if (value === null || value === undefined || value === \"\") return \"-\";\n return PROXY_TYPE_LABELS_COMPACT[value] ?? value;\n}\n\n/**\n * Passes a server-owned display name through unchanged (e.g. `flags.searchCrawlerName`) - never\n * reformatted, title-cased, or mapped through an enum, because the server already sends the\n * canonical form. Missing/`null`/empty renders as `-`.\n */\nexport function formatOrDash(value: string | null | undefined): string {\n return value === null || value === undefined || value === \"\" ? \"-\" : value;\n}\n\n/**\n * Joins a geo display name with its code: `United States` + `US` -> `United States (US)`.\n *\n * The server owns both halves, so neither is title-cased, translated, or derived from the other -\n * a bare code renders as the code, a bare name as the name. Returns `undefined` when the server\n * sent neither, so the caller drops the row instead of printing a placeholder for a field the\n * server never claimed to know.\n */\nexport function formatGeoName(\n name: string | null | undefined,\n code: string | null | undefined,\n): string | undefined {\n const hasName = name !== null && name !== undefined && name !== \"\";\n const hasCode = code !== null && code !== undefined && code !== \"\";\n if (hasName && hasCode) return `${name} (${code})`;\n if (hasName) return name;\n if (hasCode) return code;\n return undefined;\n}\n\n/**\n * Display labels for the reason codes the server emits today. Deliberately a lookup table and not\n * an exhaustive union: {@link formatRiskReasonCode} falls back for anything absent here, which is\n * what keeps an already-installed CLI working when the server adds a code.\n */\nconst RISK_REASON_LABELS: Record<string, string> = {\n RESIDENTIAL_PROXY_DETECTED: \"Residential Proxy Detected\",\n ISP_PROXY_DETECTED: \"ISP Proxy Detected\",\n MOBILE_PROXY_DETECTED: \"Mobile Proxy Detected\",\n DATACENTER_PROXY_DETECTED: \"Datacenter Proxy Detected\",\n PROXY_DETECTED: \"Proxy Detected\",\n VPN_DETECTED: \"VPN Detected\",\n TOR_RELAY: \"Tor Relay\",\n TOR_EXIT_NODE: \"Tor Exit Node\",\n KNOWN_SCANNER: \"Known Scanner\",\n ABUSE_ACTIVITY: \"Abuse Activity\",\n BLACKLIST_MATCH: \"Blacklist Match\",\n BOTNET_C2: \"Botnet C2\",\n COMPROMISED_HOST: \"Compromised Host\",\n VERIFIED_SEARCH_CRAWLER: \"Verified Search Crawler\",\n PUBLIC_INFRASTRUCTURE: \"Public Infrastructure\",\n RESIDENTIAL_NETWORK: \"Residential Network\",\n CONFLICTING_EVIDENCE: \"Conflicting Evidence\",\n INSUFFICIENT_EVIDENCE: \"Insufficient Evidence\",\n};\n\n/**\n * Human label for a `risk.reasons[].code`, for the default terminal output only - `--json` and\n * `--jsonl` always carry the raw `RESIDENTIAL_PROXY_DETECTED` form.\n *\n * An unrecognised code is title-cased rather than dropped, hidden behind \"Unknown\", or thrown on:\n * the reason vocabulary is additive server-side, so a CLI in the wild will meet codes that did not\n * exist when it shipped, and showing `NEW_FUTURE_SIGNAL` as `New Future Signal` still tells the\n * reader what the server said.\n */\nexport function formatRiskReasonCode(code: string | null | undefined): string {\n if (code === null || code === undefined || code === \"\") return \"-\";\n const known = RISK_REASON_LABELS[code];\n if (known !== undefined) return known;\n const words = code.split(/[_\\s]+/).filter((word) => word !== \"\");\n if (words.length === 0) return code;\n return words.map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join(\" \");\n}\n\n/** `index` can legitimately be 0, so this must not use a falsy check. */\nexport function formatIndex(value: number | null): string {\n return value === null ? \"N/A\" : String(value);\n}\n\nexport function formatNullable(value: string | null | undefined): string {\n return value === null || value === undefined || value === \"\" ? \"N/A\" : value;\n}\n\nexport function formatNumber(value: number): string {\n return value.toLocaleString(\"en-US\");\n}\n\nexport function formatDate(iso: string): string {\n return iso.slice(0, 10);\n}\n\n/** Shared label column so `check`, `batch` and the error renderers line up identically. */\nexport const LABEL_WIDTH = 18;\n\nexport function row(label: string, value: string): string {\n return `${label.padEnd(LABEL_WIDTH)}${value}`;\n}\n\n/**\n * Reason labels are sentences (\"Residential Proxy Detected\"), not the short keys the rest of the\n * output uses, so they get their own wider column rather than pushing {@link LABEL_WIDTH} out and\n * re-indenting every other section.\n */\nexport const REASON_LABEL_WIDTH = 30;\n\nexport function reasonRow(label: string, value: string): string {\n return value === \"\" ? label : `${label.padEnd(REASON_LABEL_WIDTH)}${value}`;\n}\n\n/**\n * Renders an ISO-8601 instant as `2026-08-29 00:00 UTC`, deliberately *not* in local time: the\n * anonymous allowance resets on the UTC day, and a localized timestamp would misdescribe when\n * that happens for most of the world.\n *\n * Returns `undefined` for a missing or unparseable value so callers can drop the row rather than\n * print \"Invalid Date\".\n */\nexport function formatUtcTimestamp(iso: string | null | undefined): string | undefined {\n if (!iso) return undefined;\n const date = new Date(iso);\n if (Number.isNaN(date.getTime())) return undefined;\n const pad = (n: number): string => String(n).padStart(2, \"0\");\n return (\n `${date.getUTCFullYear()}-${pad(date.getUTCMonth() + 1)}-${pad(date.getUTCDate())} ` +\n `${pad(date.getUTCHours())}:${pad(date.getUTCMinutes())} UTC`\n );\n}\n","/** Pretty JSON to stdout. Preserves `null` exactly as returned by the API - never coerced. */\nexport function printJson(data: unknown): void {\n process.stdout.write(`${JSON.stringify(data, null, 2)}\\n`);\n}\n","import chalk from \"chalk\";\nimport type {\n NetRiskScanApiError,\n NetRiskScanConfigError,\n NetRiskScanNetworkError,\n} from \"../client/errors.js\";\nimport { formatNumber, formatUtcTimestamp, row } from \"./format.js\";\n\n/** Used only when the server did not send its own `signupUrl`. */\nconst SIGNUP_URL = \"https://www.netriskscan.com/developers\";\n\nexport function printConfigError(err: NetRiskScanConfigError): void {\n process.stderr.write(`Error: ${err.message}\\n`);\n if (err.message.includes(\"API key\")) {\n process.stderr.write(\n \"\\nGet a free API key (no credit card required): https://www.netriskscan.com\\n\",\n );\n }\n}\n\n/**\n * The anonymous trial running out is an ordinary end-of-trial moment, not a protocol fault, so it\n * gets its own renderer instead of the `Code / Status / Message` dump. It tells the reader what\n * they have, when it comes back, and where to get more.\n */\nexport function printAnonymousLimitError(err: NetRiskScanApiError): void {\n const usage = err.anonymousUsage;\n const lines = [\n \"\",\n chalk.bold(\"NetRiskScan\"),\n \"\",\n chalk.yellow(\"Anonymous daily trial limit reached.\"),\n \"\",\n ];\n\n const usageLines: string[] = [\n // The request that returned this error was refused, so nothing is left regardless of what the\n // body reports; `remaining` is only trusted when the server actually sent it.\n row(\"Available\", formatNumber(typeof usage?.remaining === \"number\" ? usage.remaining : 0)),\n ];\n if (typeof usage?.dailyLimit === \"number\") {\n usageLines.push(row(\"Daily Limit\", formatNumber(usage.dailyLimit)));\n }\n const reset = formatUtcTimestamp(usage?.resetAt);\n if (reset !== undefined) {\n usageLines.push(row(\"Reset\", reset));\n }\n\n lines.push(chalk.bold(\"Usage\"), ...usageLines, \"\");\n lines.push(chalk.bold(\"Get more queries\"), usage?.signupUrl || SIGNUP_URL, \"\");\n\n process.stderr.write(`${lines.join(\"\\n\")}\\n`);\n}\n\nconst LABEL_WIDTH = 11;\n\nexport function printApiError(err: NetRiskScanApiError, options: { debug?: boolean } = {}): void {\n const lines = [\n \"\",\n chalk.red(\"NetRiskScan API error\"),\n \"\",\n `${\"Code\".padEnd(LABEL_WIDTH)}${err.code}`,\n `${\"Status\".padEnd(LABEL_WIDTH)}${err.status}`,\n `${\"Message\".padEnd(LABEL_WIDTH)}${err.message}`,\n ];\n if (err.requestId) {\n lines.push(`${\"Request ID\".padEnd(LABEL_WIDTH)}${err.requestId}`);\n }\n if (err.retryAfter !== undefined) {\n lines.push(`${\"Retry after\".padEnd(LABEL_WIDTH)}${err.retryAfter}s`);\n }\n lines.push(\"\");\n process.stderr.write(`${lines.join(\"\\n\")}\\n`);\n\n if (options.debug && err.stack) {\n process.stderr.write(`${err.stack}\\n`);\n }\n}\n\nexport function printNetworkError(\n err: NetRiskScanNetworkError,\n options: { debug?: boolean } = {},\n): void {\n process.stderr.write(`\\n${chalk.red(\"NetRiskScan request failed\")}\\n\\n${err.message}\\n\\n`);\n if (options.debug && err.stack) {\n process.stderr.write(`${err.stack}\\n`);\n }\n}\n","import type { Command } from \"commander\";\nimport ora from \"ora\";\nimport { NetRiskScanClient } from \"../client/NetRiskScanClient.js\";\nimport {\n NetRiskScanApiError,\n NetRiskScanConfigError,\n NetRiskScanNetworkError,\n} from \"../client/errors.js\";\nimport { resolveRequiredApiKey, resolveBaseUrl } from \"../utils/env.js\";\nimport { ExitCode, exitCodeForApiErrorCode } from \"../utils/exitCode.js\";\nimport { renderUsageResult, renderVerboseMeta } from \"../output/human.js\";\nimport { printJson } from \"../output/json.js\";\nimport { printApiError, printConfigError, printNetworkError } from \"../output/errors.js\";\n\ninterface UsageOptions {\n apiKey?: string;\n baseUrl?: string;\n json?: boolean;\n verbose?: boolean;\n debug?: boolean;\n timeout: string;\n maxRetries: string;\n}\n\nexport function registerUsageCommand(program: Command): void {\n program\n .command(\"usage\")\n .description(\"Show API usage and quota for the current billing period (requires an API key)\")\n .option(\"--api-key <key>\", \"NetRiskScan API key (required for this command)\")\n .option(\"--base-url <url>\", \"Override the API base URL (advanced)\")\n .option(\"--json\", \"Output machine-readable JSON\")\n .option(\"--verbose\", \"Show rate limit and request id\")\n .option(\"--debug\", \"Show debug information on failure\")\n .option(\"--timeout <ms>\", \"Request timeout in milliseconds\", \"10000\")\n .option(\"--max-retries <n>\", \"Maximum automatic retries for 429/503\", \"3\")\n .addHelpText(\n \"after\",\n `\nNotes:\n Requires a Developer API key. This reports Developer Account plan, billing\n period and quota, which has no anonymous equivalent - unlike check and batch,\n which work without a key.\n`,\n )\n .action(async (options: UsageOptions) => {\n await runUsage(options);\n });\n}\n\nasync function runUsage(options: UsageOptions): Promise<void> {\n const useJson = Boolean(options.json);\n\n let apiKey: string;\n try {\n apiKey = resolveRequiredApiKey(options.apiKey);\n } catch (err) {\n if (err instanceof NetRiskScanConfigError) {\n printConfigError(err);\n process.exitCode = ExitCode.AuthError;\n return;\n }\n throw err;\n }\n\n const client = new NetRiskScanClient({\n apiKey,\n baseUrl: resolveBaseUrl(options.baseUrl),\n timeout: Number(options.timeout),\n maxRetries: Number(options.maxRetries),\n });\n\n const spinner = useJson\n ? undefined\n : ora({\n text: \"Fetching usage...\",\n stream: process.stderr,\n isEnabled: process.stderr.isTTY,\n }).start();\n\n try {\n const { data, meta } = await client.getUsage();\n spinner?.stop();\n\n if (useJson) {\n printJson(data);\n } else {\n renderUsageResult(data);\n if (options.verbose) {\n renderVerboseMeta(meta);\n }\n }\n } catch (err) {\n spinner?.stop();\n if (err instanceof NetRiskScanApiError) {\n printApiError(err, { debug: options.debug });\n process.exitCode = exitCodeForApiErrorCode(err.code);\n return;\n }\n if (err instanceof NetRiskScanNetworkError) {\n printNetworkError(err, { debug: options.debug });\n process.exitCode = ExitCode.ApiError;\n return;\n }\n throw err;\n }\n}\n","import type { Command } from \"commander\";\nimport { createReadStream } from \"node:fs\";\nimport { createInterface } from \"node:readline\";\nimport { NetRiskScanClient } from \"../client/NetRiskScanClient.js\";\nimport { NetRiskScanApiError, NetRiskScanNetworkError } from \"../client/errors.js\";\nimport type { AnonymousLimitInfo } from \"../client/errors.js\";\nimport type { IpRiskResponse } from \"../client/types.js\";\nimport { resolveOptionalApiKey, resolveBaseUrl } from \"../utils/env.js\";\nimport { isValidIp } from \"../utils/ip.js\";\nimport { runPool } from \"../utils/pool.js\";\nimport { ExitCode, exitCodeForApiErrorCode, type ExitCodeValue } from \"../utils/exitCode.js\";\nimport { printJsonLine } from \"../output/jsonl.js\";\nimport { renderBatchTable } from \"../output/table.js\";\n\n/**\n * Client-side batch only: sends individual `GET /v1/ip-risk/{ip}` requests with controlled\n * concurrency. There is currently no server-side batch endpoint - do not call one.\n */\nconst MAX_CONCURRENCY = 20;\nconst DEFAULT_CONCURRENCY = 5;\n\nexport interface BatchItemError {\n code: string;\n message: string;\n requestId?: string;\n /** Present on `anonymous_daily_limit_reached`, so the summary can report the real allowance. */\n anonymousUsage?: AnonymousLimitInfo;\n}\n\nexport type BatchItemResult =\n | { ip: string; ok: true; result: IpRiskResponse }\n | { ip: string; ok: false; error: BatchItemError };\n\ninterface BatchOptions {\n apiKey?: string;\n baseUrl?: string;\n concurrency: string;\n jsonl?: boolean;\n timeout: string;\n maxRetries: string;\n}\n\nexport function registerBatchCommand(program: Command): void {\n program\n .command(\"batch <file>\")\n .description(\"Check multiple IP addresses (client-side batch over GET /v1/ip-risk/{ip})\")\n .option(\n \"--api-key <key>\",\n \"NetRiskScan API key (optional; uses the anonymous trial when omitted)\",\n )\n .option(\"--base-url <url>\", \"Override the API base URL (advanced)\")\n .option(\n \"--concurrency <n>\",\n `Number of concurrent requests (default: ${DEFAULT_CONCURRENCY}, max: ${MAX_CONCURRENCY})`,\n String(DEFAULT_CONCURRENCY),\n )\n .option(\"--jsonl\", \"Output newline-delimited JSON (one object per IP)\")\n .option(\"--timeout <ms>\", \"Request timeout in milliseconds\", \"10000\")\n .option(\"--max-retries <n>\", \"Maximum automatic retries for 429/503\", \"3\")\n .addHelpText(\n \"after\",\n `\nNotes:\n This is a client-side batch: it sends individual GET /v1/ip-risk/{ip}\n requests with controlled concurrency. NetRiskScan does not currently\n offer a server-side batch endpoint. Make sure the selected concurrency\n complies with the limits shown in your NetRiskScan Developer Dashboard.\n\n An API key is optional. Without an API key, requests use the anonymous daily\n trial, metered by public IP. How many remain is decided by the server, not by\n this CLI, and is reported in the summary after the table.\n\nInput format:\n One IP per line. Blank lines and lines starting with # are ignored.\n\nExamples:\n $ netriskscan batch ips.txt\n $ cat ips.txt | netriskscan batch -\n $ netriskscan batch ips.txt --concurrency 10 --jsonl > results.jsonl\n`,\n )\n .action(async (file: string, options: BatchOptions) => {\n await runBatch(file, options);\n });\n}\n\nasync function readIps(file: string): Promise<string[]> {\n const stream = file === \"-\" ? process.stdin : createReadStream(file, \"utf8\");\n const rl = createInterface({ input: stream, crlfDelay: Infinity });\n const ips: string[] = [];\n for await (const rawLine of rl) {\n const line = rawLine.trim();\n if (line === \"\" || line.startsWith(\"#\")) continue;\n ips.push(line);\n }\n return ips;\n}\n\nfunction parseConcurrency(value: string): number {\n const n = Number(value);\n if (!Number.isFinite(n) || n < 1) return DEFAULT_CONCURRENCY;\n if (n > MAX_CONCURRENCY) {\n process.stderr.write(\n `Warning: --concurrency ${n} exceeds the safety cap of ${MAX_CONCURRENCY}; using ${MAX_CONCURRENCY}.\\n` +\n \"Check your NetRiskScan Developer Dashboard for your plan's concurrency limit.\\n\",\n );\n return MAX_CONCURRENCY;\n }\n return Math.floor(n);\n}\n\nfunction toBatchError(err: unknown): BatchItemError {\n if (err instanceof NetRiskScanApiError) {\n return {\n code: err.code,\n message: err.message,\n requestId: err.requestId,\n anonymousUsage: err.anonymousUsage,\n };\n }\n if (err instanceof NetRiskScanNetworkError) {\n return { code: \"network_error\", message: err.message, requestId: err.requestId };\n }\n return { code: \"unknown_error\", message: err instanceof Error ? err.message : String(err) };\n}\n\nasync function runBatch(file: string, options: BatchOptions): Promise<void> {\n const ips = await readIps(file);\n if (ips.length === 0) {\n process.stderr.write(\"Error: no IP addresses found in input.\\n\");\n process.exitCode = ExitCode.InvalidArgument;\n return;\n }\n\n // No key means the anonymous trial. The CLI deliberately does not pre-check the input length\n // against a daily allowance: it cannot know how much of today's allowance was already spent,\n // and only the server can.\n const client = new NetRiskScanClient({\n apiKey: resolveOptionalApiKey(options.apiKey),\n baseUrl: resolveBaseUrl(options.baseUrl),\n timeout: Number(options.timeout),\n maxRetries: Number(options.maxRetries),\n });\n\n const concurrency = parseConcurrency(options.concurrency);\n\n const results = await runPool(ips, concurrency, async (ip): Promise<BatchItemResult> => {\n if (!isValidIp(ip)) {\n return {\n ip,\n ok: false,\n error: { code: \"invalid_ip\", message: `\"${ip}\" is not a valid IPv4 or IPv6 address.` },\n };\n }\n try {\n const { data } = await client.checkIp(ip);\n return { ip, ok: true, result: data };\n } catch (err) {\n return { ip, ok: false, error: toBatchError(err) };\n }\n });\n\n if (options.jsonl) {\n for (const item of results) {\n printJsonLine(item);\n }\n } else {\n renderBatchTable(results);\n }\n\n process.exitCode = computeBatchExitCode(results);\n}\n\nfunction computeBatchExitCode(results: readonly BatchItemResult[]): ExitCodeValue {\n const failures = results.filter((r): r is Extract<BatchItemResult, { ok: false }> => !r.ok);\n if (failures.length === 0) return ExitCode.Success;\n\n const codes = failures.map((f) => exitCodeForApiErrorCode(f.error.code));\n if (codes.includes(ExitCode.AuthError)) return ExitCode.AuthError;\n if (codes.includes(ExitCode.RateLimitOrQuota)) return ExitCode.RateLimitOrQuota;\n return ExitCode.ApiError;\n}\n","/** Runs `worker` over `items` with at most `concurrency` in flight, preserving result order. */\nexport async function runPool<T, R>(\n items: readonly T[],\n concurrency: number,\n worker: (item: T, index: number) => Promise<R>,\n): Promise<R[]> {\n const results: R[] = new Array(items.length);\n let cursor = 0;\n\n async function next(): Promise<void> {\n while (cursor < items.length) {\n const index = cursor++;\n results[index] = await worker(items[index] as T, index);\n }\n }\n\n const workerCount = Math.max(1, Math.min(concurrency, items.length));\n await Promise.all(Array.from({ length: workerCount }, () => next()));\n return results;\n}\n","/** One compact JSON object per line, so a failed line never breaks the rest of the stream. */\nexport function printJsonLine(data: unknown): void {\n process.stdout.write(`${JSON.stringify(data)}\\n`);\n}\n","import Table from \"cli-table3\";\nimport chalk from \"chalk\";\nimport type { BatchItemResult } from \"../commands/batch.js\";\nimport { ANONYMOUS_DAILY_LIMIT_CODE } from \"../client/errors.js\";\nimport {\n formatIndex,\n formatNumber,\n formatOrDash,\n formatProxyTypeCompact,\n formatTriState,\n row,\n} from \"./format.js\";\n\n/**\n * Anonymous-trial summary for a finished batch.\n *\n * The batch runs concurrently, so responses do not arrive in the order the server charged them:\n * one reply can say 22 remaining while a later-numbered one says 19. The lowest value observed is\n * the closest thing to the truth, so that is what gets reported. If any request was actually\n * refused for exhausting the trial, the answer is 0 no matter what the successful replies said.\n */\nfunction anonymousSummaryLines(results: readonly BatchItemResult[]): string[] {\n const remainings: number[] = [];\n const dailyLimits: number[] = [];\n let exhausted = false;\n\n for (const item of results) {\n if (item.ok) {\n const usage = item.result.usage;\n if (usage?.mode !== \"anonymous\") continue;\n if (typeof usage.remaining === \"number\") remainings.push(usage.remaining);\n if (typeof usage.dailyLimit === \"number\") dailyLimits.push(usage.dailyLimit);\n } else if (item.error.code === ANONYMOUS_DAILY_LIMIT_CODE) {\n exhausted = true;\n const limit = item.error.anonymousUsage?.dailyLimit;\n if (typeof limit === \"number\") dailyLimits.push(limit);\n }\n }\n\n if (!exhausted && remainings.length === 0) return [];\n\n const available = exhausted ? 0 : Math.min(...remainings);\n const lines = [\"\", chalk.bold(\"Anonymous trial\"), row(\"Available\", formatNumber(available))];\n if (dailyLimits.length > 0) {\n lines.push(row(\"Daily Limit\", formatNumber(Math.max(...dailyLimits))));\n }\n return lines;\n}\n\nexport function renderBatchTable(results: readonly BatchItemResult[]): void {\n const table = new Table({\n head: [\"IP\", \"Index\", \"Band\", \"Proxy\", \"Proxy Type\", \"VPN\", \"Tor\", \"Crawler\", \"Status\"],\n style: { head: [], border: [] },\n });\n\n for (const item of results) {\n if (item.ok) {\n const { result } = item;\n table.push([\n item.ip,\n formatIndex(result.risk.index),\n result.risk.band ?? \"N/A\",\n formatTriState(result.flags.proxy),\n formatProxyTypeCompact(result.flags.proxyType),\n formatTriState(result.flags.vpn),\n formatTriState(result.flags.tor),\n formatOrDash(result.flags.searchCrawlerName),\n chalk.green(\"ok\"),\n ]);\n } else {\n table.push([\n item.ip,\n \"-\",\n \"-\",\n \"-\",\n \"-\",\n \"-\",\n \"-\",\n \"-\",\n chalk.red(`error: ${item.error.code}`),\n ]);\n }\n }\n\n process.stdout.write(`${table.toString()}\\n`);\n\n const okCount = results.filter((r) => r.ok).length;\n const failCount = results.length - okCount;\n process.stdout.write(`\\n${okCount} succeeded, ${failCount} failed\\n`);\n\n const anonymous = anonymousSummaryLines(results);\n if (anonymous.length > 0) {\n process.stdout.write(`${anonymous.join(\"\\n\")}\\n`);\n }\n}\n"],"mappings":";;;AACA,SAAS,oBAAoB;AAC7B,SAAS,SAAS,YAAY;AAC9B,SAAS,qBAAqB;AAC9B,SAAS,SAAS,sBAAsB;;;ACHxC,OAAO,SAAS;;;ACoBT,IAAM,6BAA6B;AAgBnC,IAAM,mBAAN,cAA+B,MAAM;AAAA,EAC1C,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAGO,IAAM,yBAAN,cAAqC,iBAAiB;AAAA,EAC3D,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAWO,IAAM,sBAAN,cAAkC,iBAAiB;AAAA,EAC/C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EAET,YAAY,SAAiB,SAAqC;AAChE,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS,QAAQ;AACtB,SAAK,OAAO,QAAQ;AACpB,SAAK,YAAY,QAAQ;AACzB,SAAK,aAAa,QAAQ;AAC1B,SAAK,iBAAiB,QAAQ;AAAA,EAChC;AACF;AAQO,IAAM,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B,OAAO;AAC5B,qBAAqB,OAAO;AAC5B,qBAAqB,OAAO;AAE5B,QAAQ,aAAa;AAErB,IAAI;AACF,QAAM,QAAQ,WAAW,QAAQ,IAAI;AACvC,SAAS,KAAK;AACZ,MAAI,eAAe,gBAAgB;AACjC,QAAI,IAAI,SAAS,6BAA6B,IAAI,SAAS,qBAAqB;AAC9E,cAAQ,WAAW,SAAS;AAAA,IAC9B,OAAO;AACL,cAAQ,WAAW,SAAS;AAAA,IAC9B;AAAA,EACF,OAAO;AACL,YAAQ,OAAO,MAAM,qBAAqB,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAAA,CAAI;AAC9F,YAAQ,WAAW,SAAS;AAAA,EAC9B;AACF;","names":["chalk","chalk","LABEL_WIDTH","program","ora","program","ora","chalk","chalk","program"]}
package/dist/index.d.ts CHANGED
@@ -8,6 +8,84 @@ type AssessmentGrade = "complete" | "partial" | "limited" | "insufficient";
8
8
  * never actually guaranteed to match this compile-time type.
9
9
  */
10
10
  type ProxyType = "residential_proxy" | "isp_proxy" | "mobile_proxy" | "datacenter_proxy" | "unknown_proxy";
11
+ /**
12
+ * Network-level geolocation of the address, as `GET /v1/ip-risk/{ip}` reports it.
13
+ *
14
+ * This is where the *network* is registered/routed - never the device's GPS position, and never
15
+ * the end user's precise physical location. A city can be the operator's aggregation point rather
16
+ * than the subscriber's town.
17
+ *
18
+ * Every field is nullable and independently so: an address can resolve to a country with no region
19
+ * and no city. The CLI shows only what the server actually sent - a missing field is dropped, never
20
+ * back-filled from the code, translated, re-cased, or guessed from a neighbouring field.
21
+ *
22
+ * Only the fields the public API documents live here. Schema 1.6.0 added continent, postal code and
23
+ * an approximate coordinate pair; an accuracy radius is still not part of the `/v1` contract. The
24
+ * 1.6.0 additions are optional as well as nullable: a server that predates them omits the keys
25
+ * entirely, and a current one can send any of them as `null`.
26
+ */
27
+ interface IpLocation {
28
+ /** ISO 3166-1 alpha-2, e.g. `"US"`. */
29
+ countryCode: string | null;
30
+ /** Server-owned display name, e.g. `"United States"`. Shown verbatim. */
31
+ country: string | null;
32
+ /** ISO 3166-2 subdivision code without the country prefix, e.g. `"CA"`. */
33
+ regionCode: string | null;
34
+ /** Server-owned display name, e.g. `"California"`. Shown verbatim. */
35
+ region: string | null;
36
+ city: string | null;
37
+ /** IANA time zone id, e.g. `"America/Los_Angeles"`. */
38
+ timeZone: string | null;
39
+ /** UN geoscheme continent code, e.g. `"NA"`. Added in Schema 1.6.0; absent on older servers. */
40
+ continentCode?: string | null;
41
+ /** Continent English name, e.g. `"North America"`. Server-owned, shown verbatim. */
42
+ continent?: string | null;
43
+ /**
44
+ * Postal code exactly as the data source provides it - a string, never parsed into a number
45
+ * (leading zeros are significant). Added in Schema 1.6.0; absent on older servers.
46
+ */
47
+ postalCode?: string | null;
48
+ /**
49
+ * Approximate network latitude in [-90, 90] - where the network is routed, never the device's
50
+ * GPS position. Paired with {@link longitude}: the server sends both or neither, and an anycast
51
+ * network has no single node location, so both come back `null`. A legitimate `0` is a real
52
+ * coordinate and must survive - never drop it with a truthiness check. Added in Schema 1.6.0.
53
+ */
54
+ latitude?: number | null;
55
+ /**
56
+ * Approximate network longitude in [-180, 180]; same pairing, range and null semantics as
57
+ * {@link latitude}. Added in Schema 1.6.0; absent on older servers.
58
+ */
59
+ longitude?: number | null;
60
+ }
61
+ /**
62
+ * One server-generated explanation for the assessment.
63
+ *
64
+ * Reasons are *server-owned output*: the CLI renders them and never derives, infers, filters,
65
+ * re-orders or invents one from `flags`/`network`. `flags.tor === true` in particular does not
66
+ * imply `TOR_EXIT_NODE` - only the server can say which it is.
67
+ *
68
+ * Not every reason is negative. `VERIFIED_SEARCH_CRAWLER`, `PUBLIC_INFRASTRUCTURE` and
69
+ * `RESIDENTIAL_NETWORK` explain why an address scores *well*. A reason is an explanation of the
70
+ * assessment, never proof of malicious activity.
71
+ *
72
+ * All three fields are deliberately `string`, not closed unions. The vocabulary is additive: the
73
+ * server can introduce a new code, category or severity at any time, and a CLI already installed
74
+ * in the wild must render the unfamiliar value rather than throw, drop it, or relabel it
75
+ * "Unknown". Known codes at the time of writing - `RESIDENTIAL_PROXY_DETECTED`, `ISP_PROXY_DETECTED`,
76
+ * `MOBILE_PROXY_DETECTED`, `DATACENTER_PROXY_DETECTED`, `PROXY_DETECTED`, `VPN_DETECTED`,
77
+ * `TOR_RELAY`, `TOR_EXIT_NODE`, `KNOWN_SCANNER`, `ABUSE_ACTIVITY`, `BLACKLIST_MATCH`, `BOTNET_C2`,
78
+ * `COMPROMISED_HOST`, `VERIFIED_SEARCH_CRAWLER`, `PUBLIC_INFRASTRUCTURE`, `RESIDENTIAL_NETWORK`,
79
+ * `CONFLICTING_EVIDENCE`, `INSUFFICIENT_EVIDENCE` - are documentation, not an exhaustive contract.
80
+ */
81
+ interface RiskReason {
82
+ /** Stable machine identifier, e.g. `"RESIDENTIAL_PROXY_DETECTED"`. */
83
+ code: string;
84
+ /** Grouping, e.g. `"anonymity"`, `"identity"`, `"network"`, `"threat"`. */
85
+ category: string;
86
+ /** e.g. `"critical"`, `"high"`, `"medium"`, `"low"`, `"info"`. */
87
+ severity: string;
88
+ }
11
89
  /**
12
90
  * Response of `GET /v1/ip-risk/{ip}`.
13
91
  *
@@ -20,6 +98,15 @@ interface IpRiskResponse {
20
98
  index: number | null;
21
99
  band: RiskBand | null;
22
100
  assessmentGrade: AssessmentGrade;
101
+ /**
102
+ * Why the server assessed the address this way. Absent (key omitted) on a server that predates
103
+ * the field, and legitimately `[]` on a newer one that had nothing to explain - both mean
104
+ * "print no reasons", never "the CLI should work some out".
105
+ *
106
+ * Purely explanatory: {@link index}, {@link band} and {@link assessmentGrade} are already the
107
+ * server's verdict and are never recomputed from this list.
108
+ */
109
+ reasons?: RiskReason[];
23
110
  };
24
111
  network: {
25
112
  type: string | null;
@@ -42,6 +129,19 @@ interface IpRiskResponse {
42
129
  connectionType: string | null;
43
130
  asn: string | null;
44
131
  organization: string | null;
132
+ /**
133
+ * Trusted primary domain of the network's operating organisation, e.g. `"google.com"` - the
134
+ * operator itself, never a website hosted on the address or a cloud customer's domain.
135
+ * Server-owned: the CLI must never infer it from the ASN, organization or reverse DNS.
136
+ * Added in Schema 1.6.0; absent on older servers, `null` when no trusted mapping exists.
137
+ */
138
+ domain?: string | null;
139
+ /**
140
+ * Canonical CIDR prefix containing the queried address, e.g. `"8.8.8.0/24"` (IPv4 or IPv6).
141
+ * Server-owned and shown verbatim - the CLI never computes, widens or guesses a range itself.
142
+ * Added in Schema 1.6.0; absent on older servers, `null` when no containing range is available.
143
+ */
144
+ range?: string | null;
45
145
  };
46
146
  flags: {
47
147
  proxy: boolean | null;
@@ -69,6 +169,12 @@ interface IpRiskResponse {
69
169
  */
70
170
  searchCrawlerName?: string | null;
71
171
  };
172
+ /**
173
+ * Network-level geolocation. Absent (key omitted) on a server that predates the field, and
174
+ * `null` when the address could not be located at all - read defensively, exactly as
175
+ * {@link IpRiskResponse.network}'s `profile`/`service` already are.
176
+ */
177
+ location?: IpLocation | null;
72
178
  /**
73
179
  * Access mode and, for the anonymous trial, how much of today's allowance is left.
74
180
  *
@@ -253,4 +359,4 @@ declare class NetRiskScanNetworkError extends NetRiskScanError {
253
359
  constructor(message: string, options?: NetRiskScanNetworkErrorOptions);
254
360
  }
255
361
 
256
- export { ANONYMOUS_DAILY_LIMIT_CODE, type AnonymousLimitInfo, type ApiErrorBody, type ApiResult, type AssessmentGrade, type IpRiskResponse, KNOWN_ERROR_CODES, type KnownErrorCode, NetRiskScanApiError, type NetRiskScanApiErrorOptions, NetRiskScanClient, type NetRiskScanClientOptions, NetRiskScanConfigError, NetRiskScanError, NetRiskScanNetworkError, type NetRiskScanNetworkErrorOptions, type ProxyType, type QuotaInfo, type RateLimitInfo, type RequestOptions, type RequestUsage, type ResponseMeta, type RiskBand, type RiskFlagName, type UsageResponse };
362
+ export { ANONYMOUS_DAILY_LIMIT_CODE, type AnonymousLimitInfo, type ApiErrorBody, type ApiResult, type AssessmentGrade, type IpLocation, type IpRiskResponse, KNOWN_ERROR_CODES, type KnownErrorCode, NetRiskScanApiError, type NetRiskScanApiErrorOptions, NetRiskScanClient, type NetRiskScanClientOptions, NetRiskScanConfigError, NetRiskScanError, NetRiskScanNetworkError, type NetRiskScanNetworkErrorOptions, type ProxyType, type QuotaInfo, type RateLimitInfo, type RequestOptions, type RequestUsage, type ResponseMeta, type RiskBand, type RiskFlagName, type RiskReason, type UsageResponse };
package/package.json CHANGED
@@ -1,22 +1,28 @@
1
1
  {
2
2
  "name": "netriskscan-cli",
3
- "version": "1.4.0",
4
- "description": "Official command-line client and SDK for the NetRiskScan Developer API - query IP risk, network intelligence and reputation data from your terminal.",
3
+ "version": "1.6.0",
4
+ "description": "Official CLI and TypeScript client for IP lookup, IP risk, IP reputation, proxy/VPN/Tor detection and network intelligence via the NetRiskScan Developer API.",
5
5
  "keywords": [
6
6
  "netriskscan",
7
+ "cli",
8
+ "command-line",
7
9
  "ip",
10
+ "ip-lookup",
8
11
  "ip-risk",
9
12
  "ip-reputation",
10
13
  "ip-intelligence",
14
+ "geoip",
11
15
  "security",
12
16
  "cybersecurity",
13
- "cli",
17
+ "devsecops",
14
18
  "osint",
15
19
  "vpn-detection",
16
20
  "proxy-detection",
21
+ "tor-detection",
17
22
  "datacenter-detection",
18
23
  "network-intelligence",
19
- "threat-intelligence"
24
+ "threat-intelligence",
25
+ "batch-processing"
20
26
  ],
21
27
  "homepage": "https://www.netriskscan.com",
22
28
  "bugs": "https://github.com/TeamQQ/netriskscan-cli/issues",