netriskscan-cli 1.5.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,10 @@
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
+
1
8
  # [1.5.0](https://github.com/TeamQQ/netriskscan-cli/compare/v1.4.0...v1.5.0) (2026-09-02)
2
9
 
3
10
 
@@ -5,9 +12,7 @@
5
12
 
6
13
  * add geolocation and risk reasons to CLI ([7a47c02](https://github.com/TeamQQ/netriskscan-cli/commit/7a47c022c70ca108025edee7c24b9b851cbe8bde))
7
14
 
8
- ## Unreleased
9
-
10
- ### Added
15
+ ### Details
11
16
 
12
17
  - IP geolocation output for `check` (`Location`: country, region, city, time zone), shown
13
18
  only for the fields the server actually resolved
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,76 +12,33 @@ 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
- Risk Reasons
26
- Verified Search Crawler info
27
- Public Infrastructure info
28
-
29
- Network
30
- Type public_infrastructure
31
- Profile search_crawler
32
- Service Applebot
33
- Connection direct
34
- ASN AS714
35
- Organization Apple Inc.
36
-
37
- Location
38
- Country United States (US)
39
- Region California (CA)
40
- City Cupertino
41
- Time Zone America/Los_Angeles
42
-
43
- Signals
44
- Proxy No
45
- Proxy Type -
46
- VPN No
47
- Tor No
48
- Datacenter No
49
- Scanner Unknown
50
- Abuse No
51
-
52
- Identity
53
- Search Crawler Yes
54
- Crawler Applebot
55
-
56
- Usage
57
- Available 29
58
- Daily Limit 30
59
- Reset 2026-08-29 00:00 UTC
60
-
61
- Request ID req_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
62
-
63
- Explore
64
- Web https://www.netriskscan.com
65
- GitHub https://github.com/TeamQQ/netriskscan-cli
66
- ```
67
-
68
- **No account or API key required** for the anonymous trial - the command above works on a
69
- clean machine. The `Usage` block is the server telling you how much of today's free
70
- allowance is left; the CLI never estimates it. Add an API key when you need more
71
- (see [Getting an API key](#getting-an-api-key)).
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.
72
27
 
73
- Example output - actual values come from the live API and can change as reputation and
74
- 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.
75
31
 
76
32
  ## Why NetRiskScan?
77
33
 
78
34
  - Known infrastructure identification for services such as search crawlers and public
79
35
  infrastructure, instead of treating every address as a generic business or datacenter IP
80
36
  - Proxy, VPN, Tor, abuse, blacklist and threat signals
81
- - Network-level IP geolocation (country, region, city, time zone)
82
- - Public risk reasons: the server's own explanation of *why* an address scored as it did
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
83
42
  - One normalized NetRiskScan Index instead of raw provider scores - higher is cleaner
84
43
  - `unknown` and `not applicable` states are preserved, never collapsed into "false"
85
44
  - Anonymous daily trial: run your first check with no account, no key, no configuration
@@ -102,7 +61,9 @@ Powered by the [NetRiskScan Developer API](#developer-api).
102
61
 
103
62
  - [Why NetRiskScan?](#why-netriskscan)
104
63
  - [Introduction](#introduction)
64
+ - [IP Lookup and Reputation](#ip-lookup-and-reputation)
105
65
  - [Features](#features)
66
+ - [Use Cases](#use-cases)
106
67
  - [Installation](#installation)
107
68
  - [Anonymous trial](#anonymous-trial)
108
69
  - [Getting an API key](#getting-an-api-key)
@@ -120,6 +81,7 @@ Powered by the [NetRiskScan Developer API](#developer-api).
120
81
  - [SDK usage](#sdk-usage)
121
82
  - [Security](#security)
122
83
  - [Developer API](#developer-api)
84
+ - [FAQ](#faq)
123
85
  - [Official resources](#official-resources)
124
86
  - [Contributing](#contributing)
125
87
  - [License](#license)
@@ -142,6 +104,15 @@ the server is always the single source of truth.
142
104
  `excellent`; `42` is `poor`. It is a cleanliness score, not a threat score - never read
143
105
  `90` as "high risk".
144
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
+
145
116
  ## Features
146
117
 
147
118
  - `check` and `batch` with no API key at all, via the anonymous daily trial
@@ -149,7 +120,10 @@ the server is always the single source of truth.
149
120
  - IPv4 and IPv6 support
150
121
  - Proxy type classification (residential, ISP, mobile, datacenter) for detected proxies,
151
122
  and verified search crawler identity (Googlebot, Bingbot, Applebot, ...)
152
- - IP geolocation and server-generated risk reasons in `check`, `--json` and `--jsonl`
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)
153
127
  - Human-readable terminal output, `--json`, and `--jsonl` (batch) modes
154
128
  - Correct three-state handling of risk flags (`true` / `false` / `null` - never coerced)
155
129
  - CI-friendly exit codes and `--fail-below` / `--fail-on` policy gates
@@ -158,9 +132,23 @@ the server is always the single source of truth.
158
132
  - Zero telemetry
159
133
  - A typed `NetRiskScanClient` SDK you can import directly in Node.js/TypeScript
160
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
+
161
149
  ## Installation
162
150
 
163
- Run it without installing anything:
151
+ Run it without installing anything - a zero-setup terminal IP lookup:
164
152
 
165
153
  ```bash
166
154
  npx netriskscan-cli check 1.1.1.1
@@ -284,6 +272,11 @@ netriskscan check <ip> [options]
284
272
  Calls `GET /v1/ip-risk/{ip}` - no query string parameters are ever sent. An API key is
285
273
  optional; without one the request uses the [anonymous trial](#anonymous-trial).
286
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
+
287
280
  ```bash
288
281
  $ netriskscan check 1.1.1.1
289
282
 
@@ -302,9 +295,12 @@ Type public_infrastructure
302
295
  Connection direct
303
296
  ASN AS13335
304
297
  Organization Cloudflare, Inc.
298
+ Domain cloudflare.com
299
+ Network Range 1.1.1.0/24
305
300
 
306
301
  Location
307
302
  Country United States (US)
303
+ Continent North America (NA)
308
304
  Time Zone America/Los_Angeles
309
305
 
310
306
  Signals
@@ -326,6 +322,14 @@ Request ID req_xxxxxxxx
326
322
  Output above is illustrative of the format - actual values always come from the live
327
323
  API response.
328
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
+
329
333
  ### Proxy Type
330
334
 
331
335
  `Proxy Type` is a classification detail for an address already detected as a proxy - it
@@ -353,6 +357,32 @@ itself; it only displays the classification the API already returned.** A verifi
353
357
  crawler is identity information, not a risk signal, so it never affects `risk.index`,
354
358
  `--fail-on`, or the CLI's exit code.
355
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
+
356
386
  ### Risk Reasons
357
387
 
358
388
  `risk.reasons` is the server's own explanation of the assessment it just returned - the
@@ -369,7 +399,7 @@ Residential Proxy Detected high
369
399
  Reasons are **not proof of fraud or malicious activity**. `VPN_DETECTED` means a VPN was
370
400
  detected, nothing more. Nor are they all negative: `VERIFIED_SEARCH_CRAWLER`,
371
401
  `PUBLIC_INFRASTRUCTURE` and `RESIDENTIAL_NETWORK` are exactly the reasons an address
372
- scores *well*, which is why the block is called `Risk Reasons` and not "threats".
402
+ scores _well_, which is why the block is called `Risk Reasons` and not "threats".
373
403
 
374
404
  ```text
375
405
  Risk Reasons
@@ -390,16 +420,20 @@ shown when there is nothing to explain.
390
420
  ### Location
391
421
 
392
422
  `location` is **network-level IP geolocation**: where the address is registered and
393
- routed. It is **not** device or GPS location, and not the precise physical location of
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
394
425
  whoever is using the address - a city can be the operator's aggregation point rather than
395
426
  the user's town.
396
427
 
397
428
  ```text
398
429
  Location
399
430
  Country United States (US)
400
- Region California (CA)
401
- City Mountain View
402
- Time Zone America/Los_Angeles
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
403
437
  ```
404
438
 
405
439
  Every field is independently optional. Geo resolution is often partial, and the CLI shows
@@ -413,6 +447,22 @@ Country Germany (DE)
413
447
  Time Zone Europe/Berlin
414
448
  ```
415
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
+
416
466
  Names and codes are server-owned strings, printed verbatim: never translated,
417
467
  re-capitalized, or derived from one another. `location` has no effect on the risk
418
468
  assessment or on any exit code.
@@ -492,6 +542,10 @@ Supports `--json`, `--verbose`, `--api-key`, `--timeout`, and `--max-retries` ju
492
542
  netriskscan batch <file> [options]
493
543
  ```
494
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
+
495
549
  **Important:** NetRiskScan does not currently expose a server-side batch endpoint. This
496
550
  command is a **client-side batch**: it sends individual `GET /v1/ip-risk/{ip}` requests
497
551
  with a controlled concurrency limit. An API key is optional here too - without one, every
@@ -560,6 +614,8 @@ stream.
560
614
 
561
615
  ## JSON output
562
616
 
617
+ Add `--json` to turn `check` into a JSON IP lookup CLI for scripts and pipelines:
618
+
563
619
  ```bash
564
620
  netriskscan check 1.1.1.1 --json
565
621
  ```
@@ -574,9 +630,7 @@ coerced to `false`, `0`, or a string):
574
630
  "index": 95,
575
631
  "band": "excellent",
576
632
  "assessmentGrade": "complete",
577
- "reasons": [
578
- { "code": "VERIFIED_SEARCH_CRAWLER", "category": "identity", "severity": "info" }
579
- ]
633
+ "reasons": [{ "code": "VERIFIED_SEARCH_CRAWLER", "category": "identity", "severity": "info" }]
580
634
  },
581
635
  "network": {
582
636
  "type": "public_infrastructure",
@@ -584,7 +638,9 @@ coerced to `false`, `0`, or a string):
584
638
  "service": "Googlebot",
585
639
  "connectionType": "direct",
586
640
  "asn": "AS15169",
587
- "organization": "Google LLC"
641
+ "organization": "Google LLC",
642
+ "domain": "google.com",
643
+ "range": "66.249.66.0/24"
588
644
  },
589
645
  "location": {
590
646
  "countryCode": "US",
@@ -592,7 +648,12 @@ coerced to `false`, `0`, or a string):
592
648
  "regionCode": "CA",
593
649
  "region": "California",
594
650
  "city": "Mountain View",
595
- "timeZone": "America/Los_Angeles"
651
+ "timeZone": "America/Los_Angeles",
652
+ "continentCode": "NA",
653
+ "continent": "North America",
654
+ "postalCode": "94043",
655
+ "latitude": 37.422,
656
+ "longitude": -122.084
596
657
  },
597
658
  "flags": {
598
659
  "proxy": false,
@@ -615,6 +676,11 @@ never the `Residential Proxy Detected` / `Residential Proxy` labels shown in the
615
676
  terminal output. A server that predates these fields simply omits the keys; the CLI does
616
677
  not synthesize them.
617
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.
683
+
618
684
  In `--json` mode there is no spinner, no ANSI color, and no banner - stdout carries only
619
685
  the JSON. Errors always go to stderr, so this composes cleanly:
620
686
 
@@ -641,13 +707,15 @@ line-oriented processing (`jq`, `grep`, log pipelines, etc.). A failed IP never
641
707
  the whole batch to fail or drops output for the rest.
642
708
 
643
709
  The envelope (`ip`, `ok`, `result` / `error`) belongs to the CLI; everything under
644
- `result` is the API response verbatim, so `location` and `risk.reasons` appear there
645
- untouched. The default batch table deliberately stays narrow - it grows no country, city
646
- or reason columns - so use `--jsonl` when you need the full record.
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.
647
714
 
648
715
  ## CI/CD
649
716
 
650
- 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:
651
719
 
652
720
  ```bash
653
721
  netriskscan check "$TARGET_IP" --fail-below 60
@@ -841,6 +909,14 @@ for (const reason of data.risk.reasons ?? []) {
841
909
  console.log(reason.code, reason.severity);
842
910
  }
843
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
+ }
844
920
  ```
845
921
 
846
922
  Both are optional on `IpRiskResponse`, and every field inside `IpLocation` is nullable: an
@@ -848,6 +924,13 @@ older server omits them entirely, and a newer one can resolve a country without
848
924
  `RiskReason.code` / `category` / `severity` are plain `string`s on purpose, so a reason
849
925
  code added server-side after your build still type-checks and still renders.
850
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
+
851
934
  See [examples/](examples/) for runnable scripts.
852
935
 
853
936
  ## Security
@@ -864,10 +947,11 @@ See [examples/](examples/) for runnable scripts.
864
947
 
865
948
  ## Developer API
866
949
 
867
- | | |
868
- | --------------- | ------------------------------------------- |
869
- | Base URL | `https://api.netriskscan.com` |
870
- | 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) |
871
955
 
872
956
  This is a completely separate system from the netriskscan.com website's internal
873
957
  `/api/public/*` endpoints - different auth, different response shapes, no compatibility
@@ -892,6 +976,51 @@ See the official [Methodology](https://www.netriskscan.com/methodology.html) pag
892
976
  how the NetRiskScan Index itself is computed (this project does not - and will not -
893
977
  reimplement that logic client-side).
894
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
+
895
1024
  ## Official resources
896
1025
 
897
1026
  - [NetRiskScan](https://www.netriskscan.com) - web-based IP reputation and network
package/dist/cli.js CHANGED
@@ -412,6 +412,13 @@ function locationLines(location) {
412
412
  const region = formatGeoName(location.region, location.regionCode);
413
413
  if (region !== void 0) lines.push(row("Region", region));
414
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
+ }
415
422
  if (location.timeZone) lines.push(row("Time Zone", location.timeZone));
416
423
  return lines;
417
424
  }
@@ -461,6 +468,12 @@ function renderCheckResult(ip, data) {
461
468
  lines.push(row("Connection", formatNullable(data.network.connectionType)));
462
469
  lines.push(row("ASN", formatNullable(data.network.asn)));
463
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
+ }
464
477
  lines.push("");
465
478
  const geoLines = locationLines(data.location);
466
479
  if (geoLines.length > 0) {
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 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 five \"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 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 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;;;ACo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B,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,0BAAN,cAAsC,iBAAiB;AAAA,EAC1C;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,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
@@ -19,8 +19,10 @@ type ProxyType = "residential_proxy" | "isp_proxy" | "mobile_proxy" | "datacente
19
19
  * and no city. The CLI shows only what the server actually sent - a missing field is dropped, never
20
20
  * back-filled from the code, translated, re-cased, or guessed from a neighbouring field.
21
21
  *
22
- * Only the fields the public API documents live here. Latitude/longitude, postal code, continent
23
- * and accuracy radius are deliberately absent: they are not part of the `/v1` contract.
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`.
24
26
  */
25
27
  interface IpLocation {
26
28
  /** ISO 3166-1 alpha-2, e.g. `"US"`. */
@@ -34,6 +36,27 @@ interface IpLocation {
34
36
  city: string | null;
35
37
  /** IANA time zone id, e.g. `"America/Los_Angeles"`. */
36
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;
37
60
  }
38
61
  /**
39
62
  * One server-generated explanation for the assessment.
@@ -106,6 +129,19 @@ interface IpRiskResponse {
106
129
  connectionType: string | null;
107
130
  asn: string | null;
108
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;
109
145
  };
110
146
  flags: {
111
147
  proxy: boolean | null;
package/package.json CHANGED
@@ -1,22 +1,28 @@
1
1
  {
2
2
  "name": "netriskscan-cli",
3
- "version": "1.5.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",