netriskscan-cli 1.3.0 → 1.5.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 +34 -0
- package/README.md +187 -10
- package/dist/cli.js +127 -2
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +97 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,37 @@
|
|
|
1
|
+
# [1.5.0](https://github.com/TeamQQ/netriskscan-cli/compare/v1.4.0...v1.5.0) (2026-09-02)
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
### Features
|
|
5
|
+
|
|
6
|
+
* add geolocation and risk reasons to CLI ([7a47c02](https://github.com/TeamQQ/netriskscan-cli/commit/7a47c022c70ca108025edee7c24b9b851cbe8bde))
|
|
7
|
+
|
|
8
|
+
## Unreleased
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- IP geolocation output for `check` (`Location`: country, region, city, time zone), shown
|
|
13
|
+
only for the fields the server actually resolved
|
|
14
|
+
- Public risk-reason rendering for `check` (`Risk Reasons`), shown only when the server
|
|
15
|
+
sent any
|
|
16
|
+
- SDK typings for `location` and `risk.reasons`: `IpLocation` and `RiskReason`, both
|
|
17
|
+
exported from the package entry point
|
|
18
|
+
- Forward-compatible handling of future reason codes, categories and severities - an
|
|
19
|
+
unrecognised value renders instead of throwing or being dropped
|
|
20
|
+
|
|
21
|
+
### Notes
|
|
22
|
+
|
|
23
|
+
- `--json` / `--jsonl` remain a passthrough of the API response, so both new fields appear
|
|
24
|
+
there in their raw machine form with no remapping
|
|
25
|
+
- A server that predates either field still works unchanged, and neither field affects
|
|
26
|
+
`risk.index`, `--fail-below`, `--fail-on`, or any exit code
|
|
27
|
+
|
|
28
|
+
# [1.4.0](https://github.com/TeamQQ/netriskscan-cli/compare/v1.3.0...v1.4.0) (2026-09-02)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
### Features
|
|
32
|
+
|
|
33
|
+
* **check:** show proxy type and verified search crawler identity ([4386353](https://github.com/TeamQQ/netriskscan-cli/commit/43863534b3d51bb8ce7ba22ac5b0b07fc03c48ee))
|
|
34
|
+
|
|
1
35
|
# [1.3.0](https://github.com/TeamQQ/netriskscan-cli/compare/v1.2.0...v1.3.0) (2026-08-28)
|
|
2
36
|
|
|
3
37
|
|
package/README.md
CHANGED
|
@@ -22,6 +22,10 @@ Index 97
|
|
|
22
22
|
Band excellent
|
|
23
23
|
Assessment complete
|
|
24
24
|
|
|
25
|
+
Risk Reasons
|
|
26
|
+
Verified Search Crawler info
|
|
27
|
+
Public Infrastructure info
|
|
28
|
+
|
|
25
29
|
Network
|
|
26
30
|
Type public_infrastructure
|
|
27
31
|
Profile search_crawler
|
|
@@ -30,14 +34,25 @@ Connection direct
|
|
|
30
34
|
ASN AS714
|
|
31
35
|
Organization Apple Inc.
|
|
32
36
|
|
|
37
|
+
Location
|
|
38
|
+
Country United States (US)
|
|
39
|
+
Region California (CA)
|
|
40
|
+
City Cupertino
|
|
41
|
+
Time Zone America/Los_Angeles
|
|
42
|
+
|
|
33
43
|
Signals
|
|
34
44
|
Proxy No
|
|
45
|
+
Proxy Type -
|
|
35
46
|
VPN No
|
|
36
47
|
Tor No
|
|
37
48
|
Datacenter No
|
|
38
49
|
Scanner Unknown
|
|
39
50
|
Abuse No
|
|
40
51
|
|
|
52
|
+
Identity
|
|
53
|
+
Search Crawler Yes
|
|
54
|
+
Crawler Applebot
|
|
55
|
+
|
|
41
56
|
Usage
|
|
42
57
|
Available 29
|
|
43
58
|
Daily Limit 30
|
|
@@ -63,7 +78,9 @@ threat data changes.
|
|
|
63
78
|
- Known infrastructure identification for services such as search crawlers and public
|
|
64
79
|
infrastructure, instead of treating every address as a generic business or datacenter IP
|
|
65
80
|
- Proxy, VPN, Tor, abuse, blacklist and threat signals
|
|
66
|
-
-
|
|
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
|
|
83
|
+
- One normalized NetRiskScan Index instead of raw provider scores - higher is cleaner
|
|
67
84
|
- `unknown` and `not applicable` states are preserved, never collapsed into "false"
|
|
68
85
|
- Anonymous daily trial: run your first check with no account, no key, no configuration
|
|
69
86
|
- Human-readable CLI output plus JSON / JSONL for scripts, batches and CI
|
|
@@ -121,11 +138,18 @@ This is a read-only diagnostic tool. It does not make decisions for you, and the
|
|
|
121
138
|
never recomputes or approximates a risk score client-side - the `risk.index` returned by
|
|
122
139
|
the server is always the single source of truth.
|
|
123
140
|
|
|
141
|
+
**A higher NetRiskScan Index means a cleaner address, not a riskier one.** `95` is
|
|
142
|
+
`excellent`; `42` is `poor`. It is a cleanliness score, not a threat score - never read
|
|
143
|
+
`90` as "high risk".
|
|
144
|
+
|
|
124
145
|
## Features
|
|
125
146
|
|
|
126
147
|
- `check` and `batch` with no API key at all, via the anonymous daily trial
|
|
127
148
|
- `check`, `usage`, and client-side `batch` commands
|
|
128
149
|
- IPv4 and IPv6 support
|
|
150
|
+
- Proxy type classification (residential, ISP, mobile, datacenter) for detected proxies,
|
|
151
|
+
and verified search crawler identity (Googlebot, Bingbot, Applebot, ...)
|
|
152
|
+
- IP geolocation and server-generated risk reasons in `check`, `--json` and `--jsonl`
|
|
129
153
|
- Human-readable terminal output, `--json`, and `--jsonl` (batch) modes
|
|
130
154
|
- Correct three-state handling of risk flags (`true` / `false` / `null` - never coerced)
|
|
131
155
|
- CI-friendly exit codes and `--fail-below` / `--fail-on` policy gates
|
|
@@ -270,26 +294,129 @@ Index 92
|
|
|
270
294
|
Band excellent
|
|
271
295
|
Assessment complete
|
|
272
296
|
|
|
297
|
+
Risk Reasons
|
|
298
|
+
Public Infrastructure info
|
|
299
|
+
|
|
273
300
|
Network
|
|
274
301
|
Type public_infrastructure
|
|
275
302
|
Connection direct
|
|
276
303
|
ASN AS13335
|
|
277
304
|
Organization Cloudflare, Inc.
|
|
278
305
|
|
|
306
|
+
Location
|
|
307
|
+
Country United States (US)
|
|
308
|
+
Time Zone America/Los_Angeles
|
|
309
|
+
|
|
279
310
|
Signals
|
|
280
311
|
Proxy No
|
|
312
|
+
Proxy Type -
|
|
281
313
|
VPN No
|
|
282
314
|
Tor No
|
|
283
315
|
Datacenter Unknown
|
|
284
316
|
Scanner No
|
|
285
317
|
Abuse No
|
|
286
318
|
|
|
319
|
+
Identity
|
|
320
|
+
Search Crawler No
|
|
321
|
+
Crawler -
|
|
322
|
+
|
|
287
323
|
Request ID req_xxxxxxxx
|
|
288
324
|
```
|
|
289
325
|
|
|
290
326
|
Output above is illustrative of the format - actual values always come from the live
|
|
291
327
|
API response.
|
|
292
328
|
|
|
329
|
+
### Proxy Type
|
|
330
|
+
|
|
331
|
+
`Proxy Type` is a classification detail for an address already detected as a proxy - it
|
|
332
|
+
refines `Proxy`, it does not replace it. It renders as `-`, not `Unknown`, whenever the
|
|
333
|
+
address is not a proxy at all:
|
|
334
|
+
|
|
335
|
+
```text
|
|
336
|
+
Signals
|
|
337
|
+
Proxy Yes
|
|
338
|
+
Proxy Type Residential Proxy
|
|
339
|
+
```
|
|
340
|
+
|
|
341
|
+
The server-reported machine value (`residential_proxy`, `isp_proxy`, `mobile_proxy`,
|
|
342
|
+
`datacenter_proxy`, `unknown_proxy`) is what `--json`/`--jsonl` carry; the CLI only maps
|
|
343
|
+
it to a human-readable label (`Residential Proxy`, `ISP Proxy`, ...) in the default
|
|
344
|
+
terminal output.
|
|
345
|
+
|
|
346
|
+
### Search Crawler
|
|
347
|
+
|
|
348
|
+
The `Identity` block shows whether the NetRiskScan API has verified this address as a
|
|
349
|
+
known search engine crawler, and if so, its canonical name (`Googlebot`, `Bingbot`,
|
|
350
|
+
`Applebot`, ...) exactly as the server sends it - the CLI never reformats, cases, or
|
|
351
|
+
enumerates crawler names locally. **The CLI does not perform crawler verification
|
|
352
|
+
itself; it only displays the classification the API already returned.** A verified
|
|
353
|
+
crawler is identity information, not a risk signal, so it never affects `risk.index`,
|
|
354
|
+
`--fail-on`, or the CLI's exit code.
|
|
355
|
+
|
|
356
|
+
### Risk Reasons
|
|
357
|
+
|
|
358
|
+
`risk.reasons` is the server's own explanation of the assessment it just returned - the
|
|
359
|
+
CLI renders it and **never derives, infers, or invents a reason** from the flags it can
|
|
360
|
+
see. `flags.tor: true` is not enough to claim `TOR_EXIT_NODE`; only the server can say
|
|
361
|
+
whether an address is an exit node or an ordinary relay, and the CLI prints whichever it
|
|
362
|
+
actually sent.
|
|
363
|
+
|
|
364
|
+
```text
|
|
365
|
+
Risk Reasons
|
|
366
|
+
Residential Proxy Detected high
|
|
367
|
+
```
|
|
368
|
+
|
|
369
|
+
Reasons are **not proof of fraud or malicious activity**. `VPN_DETECTED` means a VPN was
|
|
370
|
+
detected, nothing more. Nor are they all negative: `VERIFIED_SEARCH_CRAWLER`,
|
|
371
|
+
`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".
|
|
373
|
+
|
|
374
|
+
```text
|
|
375
|
+
Risk Reasons
|
|
376
|
+
Verified Search Crawler info
|
|
377
|
+
Public Infrastructure info
|
|
378
|
+
```
|
|
379
|
+
|
|
380
|
+
Each reason carries a `code`, a `category` and a `severity`. The default output shows a
|
|
381
|
+
readable label (`Residential Proxy Detected`) and the severity; `--json` / `--jsonl`
|
|
382
|
+
always carry the raw machine values (`RESIDENTIAL_PROXY_DETECTED`, `anonymity`, `high`).
|
|
383
|
+
The vocabulary is **additive** - the API can introduce new codes at any time, and an
|
|
384
|
+
already-installed CLI renders an unfamiliar one rather than failing or hiding it.
|
|
385
|
+
|
|
386
|
+
Reasons are display-only: they never affect `risk.index`, `--fail-below`, `--fail-on`, or
|
|
387
|
+
the exit code. A server that predates the field simply omits it, and the section is not
|
|
388
|
+
shown when there is nothing to explain.
|
|
389
|
+
|
|
390
|
+
### Location
|
|
391
|
+
|
|
392
|
+
`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
|
|
394
|
+
whoever is using the address - a city can be the operator's aggregation point rather than
|
|
395
|
+
the user's town.
|
|
396
|
+
|
|
397
|
+
```text
|
|
398
|
+
Location
|
|
399
|
+
Country United States (US)
|
|
400
|
+
Region California (CA)
|
|
401
|
+
City Mountain View
|
|
402
|
+
Time Zone America/Los_Angeles
|
|
403
|
+
```
|
|
404
|
+
|
|
405
|
+
Every field is independently optional. Geo resolution is often partial, and the CLI shows
|
|
406
|
+
only what the server actually resolved rather than padding the block with placeholders -
|
|
407
|
+
a country-only result prints one row, and an address with no location at all prints no
|
|
408
|
+
`Location` section at all:
|
|
409
|
+
|
|
410
|
+
```text
|
|
411
|
+
Location
|
|
412
|
+
Country Germany (DE)
|
|
413
|
+
Time Zone Europe/Berlin
|
|
414
|
+
```
|
|
415
|
+
|
|
416
|
+
Names and codes are server-owned strings, printed verbatim: never translated,
|
|
417
|
+
re-capitalized, or derived from one another. `location` has no effect on the risk
|
|
418
|
+
assessment or on any exit code.
|
|
419
|
+
|
|
293
420
|
### Addresses that can't be scored
|
|
294
421
|
|
|
295
422
|
Private, loopback, reserved, and other non-routable addresses still return `HTTP 200`,
|
|
@@ -442,25 +569,52 @@ coerced to `false`, `0`, or a string):
|
|
|
442
569
|
|
|
443
570
|
```json
|
|
444
571
|
{
|
|
445
|
-
"requestId": "
|
|
446
|
-
"risk": {
|
|
572
|
+
"requestId": "req_example",
|
|
573
|
+
"risk": {
|
|
574
|
+
"index": 95,
|
|
575
|
+
"band": "excellent",
|
|
576
|
+
"assessmentGrade": "complete",
|
|
577
|
+
"reasons": [
|
|
578
|
+
{ "code": "VERIFIED_SEARCH_CRAWLER", "category": "identity", "severity": "info" }
|
|
579
|
+
]
|
|
580
|
+
},
|
|
447
581
|
"network": {
|
|
448
|
-
"type": "
|
|
449
|
-
"
|
|
450
|
-
"
|
|
451
|
-
"
|
|
582
|
+
"type": "public_infrastructure",
|
|
583
|
+
"profile": "search_crawler",
|
|
584
|
+
"service": "Googlebot",
|
|
585
|
+
"connectionType": "direct",
|
|
586
|
+
"asn": "AS15169",
|
|
587
|
+
"organization": "Google LLC"
|
|
588
|
+
},
|
|
589
|
+
"location": {
|
|
590
|
+
"countryCode": "US",
|
|
591
|
+
"country": "United States",
|
|
592
|
+
"regionCode": "CA",
|
|
593
|
+
"region": "California",
|
|
594
|
+
"city": "Mountain View",
|
|
595
|
+
"timeZone": "America/Los_Angeles"
|
|
452
596
|
},
|
|
453
597
|
"flags": {
|
|
454
598
|
"proxy": false,
|
|
599
|
+
"proxyType": null,
|
|
455
600
|
"vpn": false,
|
|
456
601
|
"tor": false,
|
|
457
602
|
"datacenter": false,
|
|
458
|
-
"scanner":
|
|
459
|
-
"abuse": false
|
|
603
|
+
"scanner": null,
|
|
604
|
+
"abuse": false,
|
|
605
|
+
"searchCrawler": true,
|
|
606
|
+
"searchCrawlerName": "Googlebot"
|
|
460
607
|
}
|
|
461
608
|
}
|
|
462
609
|
```
|
|
463
610
|
|
|
611
|
+
`risk.reasons`, `location`, `flags.proxyType` (when `flags.proxy` is `true`),
|
|
612
|
+
`flags.searchCrawler`, and `flags.searchCrawlerName` carry the server's raw machine values
|
|
613
|
+
in `--json`/`--jsonl` - e.g. `"RESIDENTIAL_PROXY_DETECTED"` and `"residential_proxy"`,
|
|
614
|
+
never the `Residential Proxy Detected` / `Residential Proxy` labels shown in the default
|
|
615
|
+
terminal output. A server that predates these fields simply omits the keys; the CLI does
|
|
616
|
+
not synthesize them.
|
|
617
|
+
|
|
464
618
|
In `--json` mode there is no spinner, no ANSI color, and no banner - stdout carries only
|
|
465
619
|
the JSON. Errors always go to stderr, so this composes cleanly:
|
|
466
620
|
|
|
@@ -477,7 +631,7 @@ netriskscan batch ips.txt --jsonl
|
|
|
477
631
|
One JSON object per line, one line per input IP:
|
|
478
632
|
|
|
479
633
|
```json
|
|
480
|
-
{"ip":"1.1.1.1","ok":true,"result":{"requestId":"req_...","risk":{...},"network":{...},"flags":{...}}}
|
|
634
|
+
{"ip":"1.1.1.1","ok":true,"result":{"requestId":"req_...","risk":{...,"reasons":[...]},"network":{...},"location":{...},"flags":{...}}}
|
|
481
635
|
{"ip":"8.8.8.8","ok":true,"result":{...}}
|
|
482
636
|
{"ip":"bad-ip","ok":false,"error":{"code":"invalid_ip","message":"..."}}
|
|
483
637
|
```
|
|
@@ -486,6 +640,11 @@ Designed for `netriskscan batch ips.txt --jsonl > results.jsonl` and downstream
|
|
|
486
640
|
line-oriented processing (`jq`, `grep`, log pipelines, etc.). A failed IP never causes
|
|
487
641
|
the whole batch to fail or drops output for the rest.
|
|
488
642
|
|
|
643
|
+
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.
|
|
647
|
+
|
|
489
648
|
## CI/CD
|
|
490
649
|
|
|
491
650
|
Use `check` with policy flags as a build/deploy gate:
|
|
@@ -671,6 +830,24 @@ const usage = await client.getUsage();
|
|
|
671
830
|
console.log(usage.data.units.remaining);
|
|
672
831
|
```
|
|
673
832
|
|
|
833
|
+
The response types are exported too, including `IpLocation` and `RiskReason`:
|
|
834
|
+
|
|
835
|
+
```ts
|
|
836
|
+
import type { IpRiskResponse, IpLocation, RiskReason } from "netriskscan-cli";
|
|
837
|
+
|
|
838
|
+
const { data } = await client.checkIp("66.249.87.5");
|
|
839
|
+
|
|
840
|
+
for (const reason of data.risk.reasons ?? []) {
|
|
841
|
+
console.log(reason.code, reason.severity);
|
|
842
|
+
}
|
|
843
|
+
console.log(data.location?.country ?? "unknown");
|
|
844
|
+
```
|
|
845
|
+
|
|
846
|
+
Both are optional on `IpRiskResponse`, and every field inside `IpLocation` is nullable: an
|
|
847
|
+
older server omits them entirely, and a newer one can resolve a country without a city.
|
|
848
|
+
`RiskReason.code` / `category` / `severity` are plain `string`s on purpose, so a reason
|
|
849
|
+
code added server-side after your build still type-checks and still renders.
|
|
850
|
+
|
|
674
851
|
See [examples/](examples/) for runnable scripts.
|
|
675
852
|
|
|
676
853
|
## Security
|
package/dist/cli.js
CHANGED
|
@@ -280,6 +280,67 @@ function formatTriState(value) {
|
|
|
280
280
|
if (value === false) return "No";
|
|
281
281
|
return "Unknown";
|
|
282
282
|
}
|
|
283
|
+
var PROXY_TYPE_LABELS = {
|
|
284
|
+
residential_proxy: "Residential Proxy",
|
|
285
|
+
isp_proxy: "ISP Proxy",
|
|
286
|
+
mobile_proxy: "Mobile Proxy",
|
|
287
|
+
datacenter_proxy: "Datacenter Proxy",
|
|
288
|
+
unknown_proxy: "Unknown Proxy"
|
|
289
|
+
};
|
|
290
|
+
var PROXY_TYPE_LABELS_COMPACT = {
|
|
291
|
+
residential_proxy: "Residential",
|
|
292
|
+
isp_proxy: "ISP",
|
|
293
|
+
mobile_proxy: "Mobile",
|
|
294
|
+
datacenter_proxy: "Datacenter",
|
|
295
|
+
unknown_proxy: "Unknown"
|
|
296
|
+
};
|
|
297
|
+
function formatProxyType(value) {
|
|
298
|
+
if (value === null || value === void 0 || value === "") return "-";
|
|
299
|
+
return PROXY_TYPE_LABELS[value] ?? value;
|
|
300
|
+
}
|
|
301
|
+
function formatProxyTypeCompact(value) {
|
|
302
|
+
if (value === null || value === void 0 || value === "") return "-";
|
|
303
|
+
return PROXY_TYPE_LABELS_COMPACT[value] ?? value;
|
|
304
|
+
}
|
|
305
|
+
function formatOrDash(value) {
|
|
306
|
+
return value === null || value === void 0 || value === "" ? "-" : value;
|
|
307
|
+
}
|
|
308
|
+
function formatGeoName(name, code) {
|
|
309
|
+
const hasName = name !== null && name !== void 0 && name !== "";
|
|
310
|
+
const hasCode = code !== null && code !== void 0 && code !== "";
|
|
311
|
+
if (hasName && hasCode) return `${name} (${code})`;
|
|
312
|
+
if (hasName) return name;
|
|
313
|
+
if (hasCode) return code;
|
|
314
|
+
return void 0;
|
|
315
|
+
}
|
|
316
|
+
var RISK_REASON_LABELS = {
|
|
317
|
+
RESIDENTIAL_PROXY_DETECTED: "Residential Proxy Detected",
|
|
318
|
+
ISP_PROXY_DETECTED: "ISP Proxy Detected",
|
|
319
|
+
MOBILE_PROXY_DETECTED: "Mobile Proxy Detected",
|
|
320
|
+
DATACENTER_PROXY_DETECTED: "Datacenter Proxy Detected",
|
|
321
|
+
PROXY_DETECTED: "Proxy Detected",
|
|
322
|
+
VPN_DETECTED: "VPN Detected",
|
|
323
|
+
TOR_RELAY: "Tor Relay",
|
|
324
|
+
TOR_EXIT_NODE: "Tor Exit Node",
|
|
325
|
+
KNOWN_SCANNER: "Known Scanner",
|
|
326
|
+
ABUSE_ACTIVITY: "Abuse Activity",
|
|
327
|
+
BLACKLIST_MATCH: "Blacklist Match",
|
|
328
|
+
BOTNET_C2: "Botnet C2",
|
|
329
|
+
COMPROMISED_HOST: "Compromised Host",
|
|
330
|
+
VERIFIED_SEARCH_CRAWLER: "Verified Search Crawler",
|
|
331
|
+
PUBLIC_INFRASTRUCTURE: "Public Infrastructure",
|
|
332
|
+
RESIDENTIAL_NETWORK: "Residential Network",
|
|
333
|
+
CONFLICTING_EVIDENCE: "Conflicting Evidence",
|
|
334
|
+
INSUFFICIENT_EVIDENCE: "Insufficient Evidence"
|
|
335
|
+
};
|
|
336
|
+
function formatRiskReasonCode(code) {
|
|
337
|
+
if (code === null || code === void 0 || code === "") return "-";
|
|
338
|
+
const known = RISK_REASON_LABELS[code];
|
|
339
|
+
if (known !== void 0) return known;
|
|
340
|
+
const words = code.split(/[_\s]+/).filter((word) => word !== "");
|
|
341
|
+
if (words.length === 0) return code;
|
|
342
|
+
return words.map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join(" ");
|
|
343
|
+
}
|
|
283
344
|
function formatIndex(value) {
|
|
284
345
|
return value === null ? "N/A" : String(value);
|
|
285
346
|
}
|
|
@@ -296,6 +357,10 @@ var LABEL_WIDTH = 18;
|
|
|
296
357
|
function row(label, value) {
|
|
297
358
|
return `${label.padEnd(LABEL_WIDTH)}${value}`;
|
|
298
359
|
}
|
|
360
|
+
var REASON_LABEL_WIDTH = 30;
|
|
361
|
+
function reasonRow(label, value) {
|
|
362
|
+
return value === "" ? label : `${label.padEnd(REASON_LABEL_WIDTH)}${value}`;
|
|
363
|
+
}
|
|
299
364
|
function formatUtcTimestamp(iso) {
|
|
300
365
|
if (!iso) return void 0;
|
|
301
366
|
const date = new Date(iso);
|
|
@@ -319,6 +384,37 @@ function anonymousUsageLines(usage) {
|
|
|
319
384
|
}
|
|
320
385
|
return lines;
|
|
321
386
|
}
|
|
387
|
+
function riskReasonLines(reasons) {
|
|
388
|
+
if (reasons === void 0 || reasons.length === 0) return [];
|
|
389
|
+
return reasons.map((reason) => {
|
|
390
|
+
const severity = reason.severity ?? "";
|
|
391
|
+
return reasonRow(formatRiskReasonCode(reason.code), severityColor(severity)(severity));
|
|
392
|
+
});
|
|
393
|
+
}
|
|
394
|
+
function severityColor(severity) {
|
|
395
|
+
switch (severity) {
|
|
396
|
+
case "critical":
|
|
397
|
+
case "high":
|
|
398
|
+
return chalk.red;
|
|
399
|
+
case "medium":
|
|
400
|
+
return chalk.yellow;
|
|
401
|
+
case "info":
|
|
402
|
+
return chalk.gray;
|
|
403
|
+
default:
|
|
404
|
+
return (text) => text;
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
function locationLines(location) {
|
|
408
|
+
if (!location) return [];
|
|
409
|
+
const lines = [];
|
|
410
|
+
const country = formatGeoName(location.country, location.countryCode);
|
|
411
|
+
if (country !== void 0) lines.push(row("Country", country));
|
|
412
|
+
const region = formatGeoName(location.region, location.regionCode);
|
|
413
|
+
if (region !== void 0) lines.push(row("Region", region));
|
|
414
|
+
if (location.city) lines.push(row("City", location.city));
|
|
415
|
+
if (location.timeZone) lines.push(row("Time Zone", location.timeZone));
|
|
416
|
+
return lines;
|
|
417
|
+
}
|
|
322
418
|
function bandColor(band) {
|
|
323
419
|
switch (band) {
|
|
324
420
|
case "excellent":
|
|
@@ -348,6 +444,12 @@ function renderCheckResult(ip, data) {
|
|
|
348
444
|
lines.push(chalk.yellow("This address could not be reliably assessed."));
|
|
349
445
|
lines.push("");
|
|
350
446
|
}
|
|
447
|
+
const reasonLines = riskReasonLines(data.risk.reasons);
|
|
448
|
+
if (reasonLines.length > 0) {
|
|
449
|
+
lines.push(chalk.bold("Risk Reasons"));
|
|
450
|
+
lines.push(...reasonLines);
|
|
451
|
+
lines.push("");
|
|
452
|
+
}
|
|
351
453
|
lines.push(chalk.bold("Network"));
|
|
352
454
|
lines.push(row("Type", formatNullable(data.network.type)));
|
|
353
455
|
if (data.network.profile) {
|
|
@@ -360,14 +462,25 @@ function renderCheckResult(ip, data) {
|
|
|
360
462
|
lines.push(row("ASN", formatNullable(data.network.asn)));
|
|
361
463
|
lines.push(row("Organization", formatNullable(data.network.organization)));
|
|
362
464
|
lines.push("");
|
|
465
|
+
const geoLines = locationLines(data.location);
|
|
466
|
+
if (geoLines.length > 0) {
|
|
467
|
+
lines.push(chalk.bold("Location"));
|
|
468
|
+
lines.push(...geoLines);
|
|
469
|
+
lines.push("");
|
|
470
|
+
}
|
|
363
471
|
lines.push(chalk.bold("Signals"));
|
|
364
472
|
lines.push(row("Proxy", formatTriState(data.flags.proxy)));
|
|
473
|
+
lines.push(row("Proxy Type", formatProxyType(data.flags.proxyType)));
|
|
365
474
|
lines.push(row("VPN", formatTriState(data.flags.vpn)));
|
|
366
475
|
lines.push(row("Tor", formatTriState(data.flags.tor)));
|
|
367
476
|
lines.push(row("Datacenter", formatTriState(data.flags.datacenter)));
|
|
368
477
|
lines.push(row("Scanner", formatTriState(data.flags.scanner)));
|
|
369
478
|
lines.push(row("Abuse", formatTriState(data.flags.abuse)));
|
|
370
479
|
lines.push("");
|
|
480
|
+
lines.push(chalk.bold("Identity"));
|
|
481
|
+
lines.push(row("Search Crawler", formatTriState(data.flags.searchCrawler)));
|
|
482
|
+
lines.push(row("Crawler", formatOrDash(data.flags.searchCrawlerName)));
|
|
483
|
+
lines.push("");
|
|
371
484
|
if (data.usage?.mode === "anonymous") {
|
|
372
485
|
const usageLines = anonymousUsageLines(data.usage);
|
|
373
486
|
if (usageLines.length > 0) {
|
|
@@ -754,7 +867,7 @@ function anonymousSummaryLines(results) {
|
|
|
754
867
|
}
|
|
755
868
|
function renderBatchTable(results) {
|
|
756
869
|
const table = new Table({
|
|
757
|
-
head: ["IP", "Index", "Band", "Proxy", "VPN", "Tor", "Status"],
|
|
870
|
+
head: ["IP", "Index", "Band", "Proxy", "Proxy Type", "VPN", "Tor", "Crawler", "Status"],
|
|
758
871
|
style: { head: [], border: [] }
|
|
759
872
|
});
|
|
760
873
|
for (const item of results) {
|
|
@@ -765,12 +878,24 @@ function renderBatchTable(results) {
|
|
|
765
878
|
formatIndex(result.risk.index),
|
|
766
879
|
result.risk.band ?? "N/A",
|
|
767
880
|
formatTriState(result.flags.proxy),
|
|
881
|
+
formatProxyTypeCompact(result.flags.proxyType),
|
|
768
882
|
formatTriState(result.flags.vpn),
|
|
769
883
|
formatTriState(result.flags.tor),
|
|
884
|
+
formatOrDash(result.flags.searchCrawlerName),
|
|
770
885
|
chalk3.green("ok")
|
|
771
886
|
]);
|
|
772
887
|
} else {
|
|
773
|
-
table.push([
|
|
888
|
+
table.push([
|
|
889
|
+
item.ip,
|
|
890
|
+
"-",
|
|
891
|
+
"-",
|
|
892
|
+
"-",
|
|
893
|
+
"-",
|
|
894
|
+
"-",
|
|
895
|
+
"-",
|
|
896
|
+
"-",
|
|
897
|
+
chalk3.red(`error: ${item.error.code}`)
|
|
898
|
+
]);
|
|
774
899
|
}
|
|
775
900
|
}
|
|
776
901
|
process.stdout.write(`${table.toString()}
|
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli.ts","../src/commands/check.ts","../src/client/errors.ts","../src/client/headers.ts","../src/client/retry.ts","../src/client/NetRiskScanClient.ts","../src/utils/env.ts","../src/utils/ip.ts","../src/utils/exitCode.ts","../src/output/human.ts","../src/output/format.ts","../src/output/json.ts","../src/output/errors.ts","../src/commands/usage.ts","../src/commands/batch.ts","../src/utils/pool.ts","../src/output/jsonl.ts","../src/output/table.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { Command, CommanderError } from \"commander\";\nimport { registerCheckCommand } from \"./commands/check.js\";\nimport { registerUsageCommand } from \"./commands/usage.js\";\nimport { registerBatchCommand } from \"./commands/batch.js\";\nimport { ExitCode } from \"./utils/exitCode.js\";\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\nconst pkg = JSON.parse(readFileSync(join(__dirname, \"..\", \"package.json\"), \"utf8\")) as {\n version: string;\n};\n\nconst program = new Command();\n\nprogram\n .name(\"netriskscan\")\n .description(\n \"Query IP risk, network intelligence and reputation data from the NetRiskScan Developer API.\",\n )\n .version(pkg.version, \"-V, --version\", \"Show the CLI version\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ netriskscan check 1.1.1.1 # no account or API key needed\n $ netriskscan check 1.1.1.1 --json\n $ netriskscan usage # needs an API key\n $ netriskscan batch ips.txt --jsonl\n\ncheck and batch work with no setup at all: without an API key they use the\nanonymous daily trial, metered by public IP. The server reports how many\nrequests are left; the CLI never estimates it.\n\nEnvironment variables:\n NETRISKSCAN_API_KEY Optional for check/batch; required for account usage.\n\nNetRiskScan provides diagnostic network intelligence. Results should not be\ntreated as proof of malicious activity or used as the sole basis for legal,\nemployment, credit, identity, or other high-impact decisions.\n\nLearn more: https://github.com/TeamQQ/netriskscan-cli\n`,\n );\n\nregisterCheckCommand(program);\nregisterUsageCommand(program);\nregisterBatchCommand(program);\n\nprogram.exitOverride();\n\ntry {\n await program.parseAsync(process.argv);\n} catch (err) {\n if (err instanceof CommanderError) {\n if (err.code === \"commander.helpDisplayed\" || err.code === \"commander.version\") {\n process.exitCode = ExitCode.Success;\n } else {\n process.exitCode = ExitCode.InvalidArgument;\n }\n } else {\n process.stderr.write(`Unexpected error: ${err instanceof Error ? err.message : String(err)}\\n`);\n process.exitCode = ExitCode.GeneralError;\n }\n}\n","import type { Command } from \"commander\";\nimport ora from \"ora\";\nimport { NetRiskScanClient } from \"../client/NetRiskScanClient.js\";\nimport {\n ANONYMOUS_DAILY_LIMIT_CODE,\n NetRiskScanApiError,\n NetRiskScanNetworkError,\n} from \"../client/errors.js\";\nimport type { IpRiskResponse, RiskFlagName } from \"../client/types.js\";\nimport { resolveOptionalApiKey, resolveBaseUrl } from \"../utils/env.js\";\nimport { isValidIp } from \"../utils/ip.js\";\nimport { ExitCode, exitCodeForApiErrorCode, type ExitCodeValue } from \"../utils/exitCode.js\";\nimport { renderCheckResult, renderVerboseMeta } from \"../output/human.js\";\nimport { printJson } from \"../output/json.js\";\nimport { printAnonymousLimitError, printApiError, printNetworkError } from \"../output/errors.js\";\n\nconst KNOWN_FLAGS: readonly RiskFlagName[] = [\n \"proxy\",\n \"vpn\",\n \"tor\",\n \"datacenter\",\n \"scanner\",\n \"abuse\",\n];\n\ninterface CheckOptions {\n apiKey?: string;\n baseUrl?: string;\n json?: boolean;\n verbose?: boolean;\n debug?: boolean;\n timeout: string;\n maxRetries: string;\n failBelow?: string;\n failOn: string[];\n}\n\nfunction collect(value: string, previous: string[]): string[] {\n return [...previous, value];\n}\n\nexport function registerCheckCommand(program: Command): void {\n program\n .command(\"check <ip>\")\n .description(\"Check IP risk and network intelligence\")\n .option(\n \"--api-key <key>\",\n \"NetRiskScan API key (optional; uses the anonymous trial when omitted)\",\n )\n .option(\"--base-url <url>\", \"Override the API base URL (advanced)\")\n .option(\"--json\", \"Output machine-readable JSON\")\n .option(\"--verbose\", \"Show rate limit, quota and request id\")\n .option(\"--debug\", \"Show debug information on failure\")\n .option(\"--timeout <ms>\", \"Request timeout in milliseconds\", \"10000\")\n .option(\"--max-retries <n>\", \"Maximum automatic retries for 429/503\", \"3\")\n .option(\"--fail-below <index>\", \"Exit non-zero if risk.index is below this threshold (CI use)\")\n .option(\n \"--fail-on <flag>\",\n \"Exit non-zero if the given flag is true (repeatable): proxy, vpn, tor, datacenter, scanner, abuse\",\n collect,\n [] as string[],\n )\n .addHelpText(\n \"after\",\n `\nExamples:\n $ netriskscan check 1.1.1.1\n $ netriskscan check 1.1.1.1 --json\n $ netriskscan check 1.2.3.4 --fail-below 60\n $ netriskscan check 1.2.3.4 --fail-on tor --fail-on proxy\n\nNotes:\n An API key is optional. Without one, requests use the anonymous daily trial,\n metered by public IP; the response reports how many are left.\n`,\n )\n .action(async (ip: string, options: CheckOptions) => {\n await runCheck(ip, options);\n });\n}\n\nasync function runCheck(ip: string, options: CheckOptions): Promise<void> {\n const useJson = Boolean(options.json);\n\n for (const flag of options.failOn) {\n if (!KNOWN_FLAGS.includes(flag as RiskFlagName)) {\n process.stderr.write(\n `Error: unknown --fail-on flag \"${flag}\". Expected one of: ${KNOWN_FLAGS.join(\", \")}\\n`,\n );\n process.exitCode = ExitCode.InvalidArgument;\n return;\n }\n }\n\n if (!isValidIp(ip)) {\n process.stderr.write(`Error: \"${ip}\" is not a valid IPv4 or IPv6 address.\\n`);\n process.exitCode = ExitCode.InvalidArgument;\n return;\n }\n\n // Undefined is a supported mode: the client then omits Authorization and the server serves the\n // request from the anonymous daily trial.\n const client = new NetRiskScanClient({\n apiKey: resolveOptionalApiKey(options.apiKey),\n baseUrl: resolveBaseUrl(options.baseUrl),\n timeout: Number(options.timeout),\n maxRetries: Number(options.maxRetries),\n });\n\n const spinner = useJson\n ? undefined\n : ora({\n text: `Checking ${ip}...`,\n stream: process.stderr,\n isEnabled: process.stderr.isTTY,\n }).start();\n\n try {\n const { data, meta } = await client.checkIp(ip);\n spinner?.stop();\n\n if (useJson) {\n printJson(data);\n } else {\n renderCheckResult(ip, data);\n if (options.verbose) {\n renderVerboseMeta(meta);\n }\n }\n\n process.exitCode = evaluateCiPolicy(data, options);\n } catch (err) {\n spinner?.stop();\n handleCheckError(err, options);\n }\n}\n\nfunction evaluateCiPolicy(data: IpRiskResponse, options: CheckOptions): ExitCodeValue {\n if (options.failOn.length > 0) {\n for (const flag of options.failOn) {\n if (data.flags[flag as RiskFlagName] === true) {\n return ExitCode.CiPolicyFailed;\n }\n }\n }\n\n if (options.failBelow !== undefined) {\n if (data.risk.index === null) {\n return ExitCode.AssessmentUnavailable;\n }\n if (data.risk.index < Number(options.failBelow)) {\n return ExitCode.CiPolicyFailed;\n }\n }\n\n return ExitCode.Success;\n}\n\nfunction handleCheckError(err: unknown, options: CheckOptions): void {\n if (err instanceof NetRiskScanApiError) {\n if (err.code === ANONYMOUS_DAILY_LIMIT_CODE) {\n printAnonymousLimitError(err);\n } else {\n printApiError(err, { debug: options.debug });\n }\n process.exitCode = exitCodeForApiErrorCode(err.code);\n return;\n }\n if (err instanceof NetRiskScanNetworkError) {\n printNetworkError(err, { debug: options.debug });\n process.exitCode = ExitCode.ApiError;\n return;\n }\n if (options.debug && err instanceof Error) {\n process.stderr.write(`${err.stack ?? err.message}\\n`);\n } else {\n process.stderr.write(`Error: ${err instanceof Error ? err.message : String(err)}\\n`);\n }\n process.exitCode = ExitCode.GeneralError;\n}\n","export const KNOWN_ERROR_CODES = [\n \"invalid_ip\",\n \"invalid_request\",\n \"unsupported_parameter\",\n \"invalid_api_key\",\n \"api_key_disabled\",\n \"scope_not_allowed\",\n \"not_found\",\n \"feature_not_available\",\n \"rate_limit_exceeded\",\n \"quota_exceeded\",\n \"anonymous_daily_limit_reached\",\n \"temporarily_unavailable\",\n] as const;\n\nexport type KnownErrorCode = (typeof KNOWN_ERROR_CODES)[number];\n\n/**\n * The anonymous trial's daily allowance is spent. Deterministic until the UTC reset, so unlike\n * `rate_limit_exceeded` it is never retried - see `isRetryableFailure`.\n */\nexport const ANONYMOUS_DAILY_LIMIT_CODE = \"anonymous_daily_limit_reached\";\n\n/**\n * Anonymous-trial allowance carried on a `429 anonymous_daily_limit_reached`.\n *\n * Parsed once in the client layer so the output layer never has to touch an HTTP body. Every\n * field is optional: a server that only sends `code` and `message` must still work.\n */\nexport interface AnonymousLimitInfo {\n dailyLimit?: number;\n used?: number;\n remaining?: number;\n resetAt?: string;\n signupUrl?: string;\n}\n\nexport class NetRiskScanError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"NetRiskScanError\";\n }\n}\n\n/** Thrown for client-side configuration problems, e.g. a missing API key. */\nexport class NetRiskScanConfigError extends NetRiskScanError {\n constructor(message: string) {\n super(message);\n this.name = \"NetRiskScanConfigError\";\n }\n}\n\nexport interface NetRiskScanApiErrorOptions {\n status: number;\n code: string;\n requestId?: string;\n retryAfter?: number;\n anonymousUsage?: AnonymousLimitInfo;\n}\n\n/** Thrown when the Developer API responds with a non-2xx status. */\nexport class NetRiskScanApiError extends NetRiskScanError {\n readonly status: number;\n readonly code: string;\n readonly requestId?: string;\n readonly retryAfter?: number;\n /** Present when the server reported anonymous-trial allowance alongside the error. */\n readonly anonymousUsage?: AnonymousLimitInfo;\n\n constructor(message: string, options: NetRiskScanApiErrorOptions) {\n super(message);\n this.name = \"NetRiskScanApiError\";\n this.status = options.status;\n this.code = options.code;\n this.requestId = options.requestId;\n this.retryAfter = options.retryAfter;\n this.anonymousUsage = options.anonymousUsage;\n }\n}\n\nexport interface NetRiskScanNetworkErrorOptions {\n cause?: unknown;\n requestId?: string;\n}\n\n/** Thrown for transport-level failures: timeouts, DNS errors, connection resets, etc. */\nexport class NetRiskScanNetworkError extends NetRiskScanError {\n override readonly cause?: unknown;\n readonly requestId?: string;\n\n constructor(message: string, options: NetRiskScanNetworkErrorOptions = {}) {\n super(message);\n this.name = \"NetRiskScanNetworkError\";\n this.cause = options.cause;\n this.requestId = options.requestId;\n }\n}\n","import { randomBytes } from \"node:crypto\";\nimport type { QuotaInfo, RateLimitInfo } from \"./types.js\";\n\nconst REQUEST_ID_PATTERN = /^req_[A-Za-z0-9_-]{8,56}$/;\n\nexport function isValidRequestId(id: string): boolean {\n return REQUEST_ID_PATTERN.test(id);\n}\n\nexport function generateRequestId(): string {\n return `req_${randomBytes(12).toString(\"hex\")}`;\n}\n\nfunction parseIntHeader(value: string | null): number | undefined {\n if (value === null) return undefined;\n const n = Number(value);\n return Number.isFinite(n) ? n : undefined;\n}\n\nexport function parseRateLimit(headers: Headers): RateLimitInfo {\n return {\n limit: parseIntHeader(headers.get(\"x-ratelimit-limit\")),\n remaining: parseIntHeader(headers.get(\"x-ratelimit-remaining\")),\n reset: parseIntHeader(headers.get(\"x-ratelimit-reset\")),\n };\n}\n\nexport function parseQuota(headers: Headers): QuotaInfo {\n return {\n limit: parseIntHeader(headers.get(\"x-quota-limit\")),\n used: parseIntHeader(headers.get(\"x-quota-used\")),\n remaining: parseIntHeader(headers.get(\"x-quota-remaining\")),\n };\n}\n\n/** Never log or print a full API key. Keeps a short prefix/suffix for support purposes. */\nexport function redactApiKey(key: string): string {\n if (key.length <= 9) return \"*\".repeat(key.length);\n return `${key.slice(0, 9)}${\"*\".repeat(4)}${key.slice(-4)}`;\n}\n\nexport function redactAuthorizationHeader(value: string): string {\n const match = /^Bearer\\s+(.+)$/i.exec(value);\n if (!match) return \"[REDACTED]\";\n return `Bearer ${redactApiKey(match[1])}`;\n}\n","import { ANONYMOUS_DAILY_LIMIT_CODE } from \"./errors.js\";\n\n/** Only 429 and 503 are automatically retried; 400/401/403/404 never are. */\nexport function isRetryableStatus(status: number): boolean {\n return status === 429 || status === 503;\n}\n\n/**\n * Status *and* error code decide retryability, because not every 429 is transient.\n *\n * `rate_limit_exceeded` is a short per-minute window and retrying is the right behaviour.\n * `anonymous_daily_limit_reached` is a spent daily allowance that cannot come back before the\n * UTC reset, so retrying it only burns three more round-trips before failing identically.\n */\nexport function isRetryableFailure(status: number, code?: string): boolean {\n if (code === ANONYMOUS_DAILY_LIMIT_CODE) return false;\n return isRetryableStatus(status);\n}\n\nconst BASE_DELAY_MS = 1000;\nconst MAX_JITTER_MS = 250;\n\n/** Honors Retry-After when present; otherwise exponential backoff (1s, 2s, 4s, ...) with jitter. */\nexport function computeBackoffMs(attempt: number, retryAfterSeconds?: number): number {\n if (\n typeof retryAfterSeconds === \"number\" &&\n Number.isFinite(retryAfterSeconds) &&\n retryAfterSeconds >= 0\n ) {\n return retryAfterSeconds * 1000;\n }\n const base = BASE_DELAY_MS * 2 ** Math.max(0, attempt - 1);\n const jitter = Math.random() * MAX_JITTER_MS;\n return base + jitter;\n}\n\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n","import { NetRiskScanApiError, NetRiskScanConfigError, NetRiskScanNetworkError } from \"./errors.js\";\nimport { generateRequestId, isValidRequestId, parseQuota, parseRateLimit } from \"./headers.js\";\nimport { computeBackoffMs, isRetryableFailure, sleep } from \"./retry.js\";\nimport type { AnonymousLimitInfo } from \"./errors.js\";\nimport type {\n ApiErrorBody,\n ApiResult,\n IpRiskResponse,\n NetRiskScanClientOptions,\n RequestOptions,\n UsageResponse,\n} from \"./types.js\";\n\nconst DEFAULT_BASE_URL = \"https://api.netriskscan.com\";\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_MAX_RETRIES = 3;\n\nfunction isAbortError(err: unknown): boolean {\n return err instanceof Error && err.name === \"AbortError\";\n}\n\nasync function safeJson(res: Response): Promise<ApiErrorBody | undefined> {\n try {\n return (await res.json()) as ApiErrorBody;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Lifts the anonymous-trial fields off an error body, once, here. HTTP bodies are parsed in the\n * client layer only - the output layer receives a typed error, never JSON.\n */\nfunction parseAnonymousLimitInfo(body: ApiErrorBody | undefined): AnonymousLimitInfo | undefined {\n const error = body?.error;\n if (!error) return undefined;\n const { dailyLimit, used, remaining, resetAt, signupUrl } = error;\n if (\n dailyLimit === undefined &&\n used === undefined &&\n remaining === undefined &&\n resetAt === undefined &&\n signupUrl === undefined\n ) {\n return undefined;\n }\n return { dailyLimit, used, remaining, resetAt, signupUrl };\n}\n\n/**\n * Client for the NetRiskScan Developer API (`/v1/*` only).\n *\n * Works with no configuration at all: without an API key it sends no `Authorization` header and\n * the server serves the request from the anonymous daily trial, metered by public IP.\n *\n * @example Anonymous - no account, no key\n * ```ts\n * const client = new NetRiskScanClient();\n * const { data } = await client.checkIp(\"1.1.1.1\");\n * console.log(data.risk.index);\n * console.log(data.usage?.remaining);\n * ```\n *\n * @example Pass `apiKey` to use Developer Account quota instead of the anonymous trial\n * ```ts\n * const client = new NetRiskScanClient({ apiKey: process.env.NETRISKSCAN_API_KEY });\n * ```\n */\nexport class NetRiskScanClient {\n private readonly apiKey?: string;\n private readonly baseUrl: string;\n private readonly timeout: number;\n private readonly maxRetries: number;\n\n constructor(options: NetRiskScanClientOptions = {}) {\n // An absent key is a supported mode, not a misconfiguration: it selects the anonymous trial.\n this.apiKey = options.apiKey || undefined;\n this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n this.timeout = options.timeout ?? DEFAULT_TIMEOUT_MS;\n this.maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;\n }\n\n async checkIp(ip: string, options: RequestOptions = {}): Promise<ApiResult<IpRiskResponse>> {\n return this.request<IpRiskResponse>(`/v1/ip-risk/${encodeURIComponent(ip)}`, options);\n }\n\n /**\n * Account plan, billing period and quota. Unlike {@link checkIp} this is account data, so it\n * has no anonymous equivalent and requires an API key.\n */\n async getUsage(options: RequestOptions = {}): Promise<ApiResult<UsageResponse>> {\n if (!this.apiKey) {\n throw new NetRiskScanConfigError(\"An API key is required to query account usage.\");\n }\n return this.request<UsageResponse>(\"/v1/usage\", options);\n }\n\n private async request<T>(path: string, options: RequestOptions): Promise<ApiResult<T>> {\n const requestId =\n options.requestId && isValidRequestId(options.requestId)\n ? options.requestId\n : generateRequestId();\n\n let attempt = 0;\n\n while (true) {\n const timeoutController = new AbortController();\n const timer = setTimeout(() => timeoutController.abort(), this.timeout);\n const onExternalAbort = (): void => timeoutController.abort();\n options.signal?.addEventListener(\"abort\", onExternalAbort);\n\n try {\n const headers: Record<string, string> = {\n Accept: \"application/json\",\n \"X-Request-Id\": requestId,\n };\n // Only ever sent when a key actually exists. A `Bearer undefined` would read as a bad key\n // and earn a 401 instead of falling through to the anonymous trial.\n if (this.apiKey) {\n headers.Authorization = `Bearer ${this.apiKey}`;\n }\n\n const res = await fetch(`${this.baseUrl}${path}`, {\n method: \"GET\",\n headers,\n signal: timeoutController.signal,\n });\n\n const rateLimit = parseRateLimit(res.headers);\n const quota = parseQuota(res.headers);\n const responseRequestId = res.headers.get(\"x-request-id\") ?? requestId;\n\n if (res.ok) {\n const data = (await res.json()) as T;\n return { data, meta: { requestId: responseRequestId, rateLimit, quota } };\n }\n\n const body = await safeJson(res);\n const retryAfterHeader = res.headers.get(\"retry-after\");\n const retryAfter = retryAfterHeader !== null ? Number(retryAfterHeader) : undefined;\n\n if (isRetryableFailure(res.status, body?.error?.code) && attempt < this.maxRetries) {\n attempt += 1;\n await sleep(computeBackoffMs(attempt, retryAfter));\n continue;\n }\n\n throw new NetRiskScanApiError(body?.error?.message ?? res.statusText, {\n status: res.status,\n code: body?.error?.code ?? \"unknown_error\",\n requestId: body?.error?.requestId ?? responseRequestId,\n retryAfter,\n anonymousUsage: parseAnonymousLimitInfo(body),\n });\n } catch (err) {\n if (err instanceof NetRiskScanApiError) {\n throw err;\n }\n if (isAbortError(err)) {\n if (options.signal?.aborted) {\n throw err;\n }\n throw new NetRiskScanNetworkError(`Request timed out after ${this.timeout}ms`, {\n cause: err,\n requestId,\n });\n }\n throw new NetRiskScanNetworkError(\n err instanceof Error ? err.message : \"Network request failed\",\n {\n cause: err,\n requestId,\n },\n );\n } finally {\n clearTimeout(timer);\n options.signal?.removeEventListener(\"abort\", onExternalAbort);\n }\n }\n }\n}\n","import { NetRiskScanConfigError } from \"../client/errors.js\";\n\n/**\n * Resolves the API key for endpoints that work without one (`check`, `batch`).\n *\n * Returning `undefined` is a valid outcome, not a failure: it selects the anonymous trial. The\n * precedence is `--api-key` > `NETRISKSCAN_API_KEY` > anonymous. A key that is present but wrong\n * is still passed through - the CLI never silently drops a key the user configured and retries\n * anonymously, because that would turn an authentication problem into a confusing success.\n */\nexport function resolveOptionalApiKey(cliValue?: string): string | undefined {\n return cliValue || process.env.NETRISKSCAN_API_KEY || undefined;\n}\n\n/**\n * Resolves the API key for account-level endpoints (`usage`), which have no anonymous form.\n *\n * The message names the command on purpose: a generic \"API key is required\" here would suggest\n * the whole CLI needs an account, which is no longer true.\n */\nexport function resolveRequiredApiKey(cliValue?: string): string {\n const apiKey = resolveOptionalApiKey(cliValue);\n if (!apiKey) {\n throw new NetRiskScanConfigError(\n \"An API key is required for the usage command.\\n\\nSet NETRISKSCAN_API_KEY or use --api-key.\",\n );\n }\n return apiKey;\n}\n\nexport function resolveBaseUrl(cliValue?: string): string | undefined {\n return cliValue ?? process.env.NETRISKSCAN_BASE_URL;\n}\n","import { isIP } from \"node:net\";\n\nexport function isValidIp(value: string): boolean {\n return isIP(value) !== 0;\n}\n","import type { KnownErrorCode } from \"../client/errors.js\";\n\nexport const ExitCode = {\n Success: 0,\n GeneralError: 1,\n InvalidArgument: 2,\n AuthError: 3,\n ApiError: 4,\n RateLimitOrQuota: 5,\n CiPolicyFailed: 6,\n AssessmentUnavailable: 7,\n} as const;\n\nexport type ExitCodeValue = (typeof ExitCode)[keyof typeof ExitCode];\n\nexport function exitCodeForApiErrorCode(code: string): ExitCodeValue {\n switch (code as KnownErrorCode) {\n case \"invalid_api_key\":\n case \"api_key_disabled\":\n case \"scope_not_allowed\":\n return ExitCode.AuthError;\n // The anonymous daily trial is an allowance like any other, so it reuses code 5 rather than\n // adding an eighth exit code that every script would have to learn.\n case \"rate_limit_exceeded\":\n case \"quota_exceeded\":\n case \"anonymous_daily_limit_reached\":\n return ExitCode.RateLimitOrQuota;\n default:\n return ExitCode.ApiError;\n }\n}\n","import chalk from \"chalk\";\nimport type {\n IpRiskResponse,\n RequestUsage,\n ResponseMeta,\n RiskBand,\n UsageResponse,\n} from \"../client/types.js\";\nimport {\n formatDate,\n formatIndex,\n formatNullable,\n formatNumber,\n formatTriState,\n formatUtcTimestamp,\n row,\n} from \"./format.js\";\n\n/**\n * Anonymous-trial rows for the human `check` output.\n *\n * `Available` is printed verbatim from `usage.remaining` - the server is the only authority on\n * what is left, so this never falls back to `dailyLimit - used`. Each row is emitted only when\n * its value is actually a number, because `0` is a legitimate value that a truthiness check\n * would swallow on exactly the run where it matters most.\n */\nfunction anonymousUsageLines(usage: RequestUsage): string[] {\n const lines: string[] = [];\n if (typeof usage.remaining === \"number\") {\n lines.push(row(\"Available\", formatNumber(usage.remaining)));\n }\n if (typeof usage.dailyLimit === \"number\") {\n lines.push(row(\"Daily Limit\", formatNumber(usage.dailyLimit)));\n }\n const reset = formatUtcTimestamp(usage.resetAt);\n if (reset !== undefined) {\n lines.push(row(\"Reset\", reset));\n }\n return lines;\n}\n\nfunction bandColor(band: RiskBand | null): (text: string) => string {\n switch (band) {\n case \"excellent\":\n case \"good\":\n return chalk.green;\n case \"fair\":\n return chalk.yellow;\n case \"poor\":\n case \"high_risk\":\n return chalk.red;\n default:\n return chalk.gray;\n }\n}\n\nexport function renderCheckResult(ip: string, data: IpRiskResponse): void {\n const lines: string[] = [];\n lines.push(chalk.bold(\"NetRiskScan\"));\n lines.push(\"\");\n lines.push(row(\"IP\", ip));\n lines.push(row(\"Index\", formatIndex(data.risk.index)));\n lines.push(\n row(\"Band\", data.risk.band ? bandColor(data.risk.band)(data.risk.band) : chalk.gray(\"N/A\")),\n );\n lines.push(row(\"Assessment\", data.risk.assessmentGrade));\n lines.push(\"\");\n\n if (data.risk.assessmentGrade === \"insufficient\" && data.risk.index === null) {\n lines.push(chalk.yellow(\"This address could not be reliably assessed.\"));\n lines.push(\"\");\n }\n\n lines.push(chalk.bold(\"Network\"));\n lines.push(row(\"Type\", formatNullable(data.network.type)));\n // Omitted entirely when absent, unlike the fields around them, which render \"N/A\". Those describe every\n // address, so a missing one is worth showing as missing; these two exist only for the minority of\n // addresses NetRiskScan holds a first-party record for, and printing \"Profile N/A\" on every residential\n // lookup would be noise rather than information.\n if (data.network.profile) {\n lines.push(row(\"Profile\", data.network.profile));\n }\n if (data.network.service) {\n lines.push(row(\"Service\", data.network.service));\n }\n lines.push(row(\"Connection\", formatNullable(data.network.connectionType)));\n lines.push(row(\"ASN\", formatNullable(data.network.asn)));\n lines.push(row(\"Organization\", formatNullable(data.network.organization)));\n lines.push(\"\");\n\n lines.push(chalk.bold(\"Signals\"));\n lines.push(row(\"Proxy\", formatTriState(data.flags.proxy)));\n lines.push(row(\"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 // 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\n/** `index` can legitimately be 0, so this must not use a falsy check. */\nexport function formatIndex(value: number | null): string {\n return value === null ? \"N/A\" : String(value);\n}\n\nexport function formatNullable(value: string | null | undefined): string {\n return value === null || value === undefined || value === \"\" ? \"N/A\" : value;\n}\n\nexport function formatNumber(value: number): string {\n return value.toLocaleString(\"en-US\");\n}\n\nexport function formatDate(iso: string): string {\n return iso.slice(0, 10);\n}\n\n/** Shared label column so `check`, `batch` and the error renderers line up identically. */\nexport const LABEL_WIDTH = 18;\n\nexport function row(label: string, value: string): string {\n return `${label.padEnd(LABEL_WIDTH)}${value}`;\n}\n\n/**\n * Renders an ISO-8601 instant as `2026-08-29 00:00 UTC`, deliberately *not* in local time: the\n * anonymous allowance resets on the UTC day, and a localized timestamp would misdescribe when\n * that happens for most of the world.\n *\n * Returns `undefined` for a missing or unparseable value so callers can drop the row rather than\n * print \"Invalid Date\".\n */\nexport function formatUtcTimestamp(iso: string | null | undefined): string | undefined {\n if (!iso) return undefined;\n const date = new Date(iso);\n if (Number.isNaN(date.getTime())) return undefined;\n const pad = (n: number): string => String(n).padStart(2, \"0\");\n return (\n `${date.getUTCFullYear()}-${pad(date.getUTCMonth() + 1)}-${pad(date.getUTCDate())} ` +\n `${pad(date.getUTCHours())}:${pad(date.getUTCMinutes())} UTC`\n );\n}\n","/** Pretty JSON to stdout. Preserves `null` exactly as returned by the API - never coerced. */\nexport function printJson(data: unknown): void {\n process.stdout.write(`${JSON.stringify(data, null, 2)}\\n`);\n}\n","import chalk from \"chalk\";\nimport type {\n NetRiskScanApiError,\n NetRiskScanConfigError,\n NetRiskScanNetworkError,\n} from \"../client/errors.js\";\nimport { formatNumber, formatUtcTimestamp, row } from \"./format.js\";\n\n/** Used only when the server did not send its own `signupUrl`. */\nconst SIGNUP_URL = \"https://www.netriskscan.com/developers\";\n\nexport function printConfigError(err: NetRiskScanConfigError): void {\n process.stderr.write(`Error: ${err.message}\\n`);\n if (err.message.includes(\"API key\")) {\n process.stderr.write(\n \"\\nGet a free API key (no credit card required): https://www.netriskscan.com\\n\",\n );\n }\n}\n\n/**\n * The anonymous trial running out is an ordinary end-of-trial moment, not a protocol fault, so it\n * gets its own renderer instead of the `Code / Status / Message` dump. It tells the reader what\n * they have, when it comes back, and where to get more.\n */\nexport function printAnonymousLimitError(err: NetRiskScanApiError): void {\n const usage = err.anonymousUsage;\n const lines = [\n \"\",\n chalk.bold(\"NetRiskScan\"),\n \"\",\n chalk.yellow(\"Anonymous daily trial limit reached.\"),\n \"\",\n ];\n\n const usageLines: string[] = [\n // The request that returned this error was refused, so nothing is left regardless of what the\n // body reports; `remaining` is only trusted when the server actually sent it.\n row(\"Available\", formatNumber(typeof usage?.remaining === \"number\" ? usage.remaining : 0)),\n ];\n if (typeof usage?.dailyLimit === \"number\") {\n usageLines.push(row(\"Daily Limit\", formatNumber(usage.dailyLimit)));\n }\n const reset = formatUtcTimestamp(usage?.resetAt);\n if (reset !== undefined) {\n usageLines.push(row(\"Reset\", reset));\n }\n\n lines.push(chalk.bold(\"Usage\"), ...usageLines, \"\");\n lines.push(chalk.bold(\"Get more queries\"), usage?.signupUrl || SIGNUP_URL, \"\");\n\n process.stderr.write(`${lines.join(\"\\n\")}\\n`);\n}\n\nconst LABEL_WIDTH = 11;\n\nexport function printApiError(err: NetRiskScanApiError, options: { debug?: boolean } = {}): void {\n const lines = [\n \"\",\n chalk.red(\"NetRiskScan API error\"),\n \"\",\n `${\"Code\".padEnd(LABEL_WIDTH)}${err.code}`,\n `${\"Status\".padEnd(LABEL_WIDTH)}${err.status}`,\n `${\"Message\".padEnd(LABEL_WIDTH)}${err.message}`,\n ];\n if (err.requestId) {\n lines.push(`${\"Request ID\".padEnd(LABEL_WIDTH)}${err.requestId}`);\n }\n if (err.retryAfter !== undefined) {\n lines.push(`${\"Retry after\".padEnd(LABEL_WIDTH)}${err.retryAfter}s`);\n }\n lines.push(\"\");\n process.stderr.write(`${lines.join(\"\\n\")}\\n`);\n\n if (options.debug && err.stack) {\n process.stderr.write(`${err.stack}\\n`);\n }\n}\n\nexport function printNetworkError(\n err: NetRiskScanNetworkError,\n options: { debug?: boolean } = {},\n): void {\n process.stderr.write(`\\n${chalk.red(\"NetRiskScan request failed\")}\\n\\n${err.message}\\n\\n`);\n if (options.debug && err.stack) {\n process.stderr.write(`${err.stack}\\n`);\n }\n}\n","import type { Command } from \"commander\";\nimport ora from \"ora\";\nimport { NetRiskScanClient } from \"../client/NetRiskScanClient.js\";\nimport {\n NetRiskScanApiError,\n NetRiskScanConfigError,\n NetRiskScanNetworkError,\n} from \"../client/errors.js\";\nimport { resolveRequiredApiKey, resolveBaseUrl } from \"../utils/env.js\";\nimport { ExitCode, exitCodeForApiErrorCode } from \"../utils/exitCode.js\";\nimport { renderUsageResult, renderVerboseMeta } from \"../output/human.js\";\nimport { printJson } from \"../output/json.js\";\nimport { printApiError, printConfigError, printNetworkError } from \"../output/errors.js\";\n\ninterface UsageOptions {\n apiKey?: string;\n baseUrl?: string;\n json?: boolean;\n verbose?: boolean;\n debug?: boolean;\n timeout: string;\n maxRetries: string;\n}\n\nexport function registerUsageCommand(program: Command): void {\n program\n .command(\"usage\")\n .description(\"Show API usage and quota for the current billing period (requires an API key)\")\n .option(\"--api-key <key>\", \"NetRiskScan API key (required for this command)\")\n .option(\"--base-url <url>\", \"Override the API base URL (advanced)\")\n .option(\"--json\", \"Output machine-readable JSON\")\n .option(\"--verbose\", \"Show rate limit and request id\")\n .option(\"--debug\", \"Show debug information on failure\")\n .option(\"--timeout <ms>\", \"Request timeout in milliseconds\", \"10000\")\n .option(\"--max-retries <n>\", \"Maximum automatic retries for 429/503\", \"3\")\n .addHelpText(\n \"after\",\n `\nNotes:\n Requires a Developer API key. This reports Developer Account plan, billing\n period and quota, which has no anonymous equivalent - unlike check and batch,\n which work without a key.\n`,\n )\n .action(async (options: UsageOptions) => {\n await runUsage(options);\n });\n}\n\nasync function runUsage(options: UsageOptions): Promise<void> {\n const useJson = Boolean(options.json);\n\n let apiKey: string;\n try {\n apiKey = resolveRequiredApiKey(options.apiKey);\n } catch (err) {\n if (err instanceof NetRiskScanConfigError) {\n printConfigError(err);\n process.exitCode = ExitCode.AuthError;\n return;\n }\n throw err;\n }\n\n const client = new NetRiskScanClient({\n apiKey,\n baseUrl: resolveBaseUrl(options.baseUrl),\n timeout: Number(options.timeout),\n maxRetries: Number(options.maxRetries),\n });\n\n const spinner = useJson\n ? undefined\n : ora({\n text: \"Fetching usage...\",\n stream: process.stderr,\n isEnabled: process.stderr.isTTY,\n }).start();\n\n try {\n const { data, meta } = await client.getUsage();\n spinner?.stop();\n\n if (useJson) {\n printJson(data);\n } else {\n renderUsageResult(data);\n if (options.verbose) {\n renderVerboseMeta(meta);\n }\n }\n } catch (err) {\n spinner?.stop();\n if (err instanceof NetRiskScanApiError) {\n printApiError(err, { debug: options.debug });\n process.exitCode = exitCodeForApiErrorCode(err.code);\n return;\n }\n if (err instanceof NetRiskScanNetworkError) {\n printNetworkError(err, { debug: options.debug });\n process.exitCode = ExitCode.ApiError;\n return;\n }\n throw err;\n }\n}\n","import type { Command } from \"commander\";\nimport { createReadStream } from \"node:fs\";\nimport { createInterface } from \"node:readline\";\nimport { NetRiskScanClient } from \"../client/NetRiskScanClient.js\";\nimport { NetRiskScanApiError, NetRiskScanNetworkError } from \"../client/errors.js\";\nimport type { AnonymousLimitInfo } from \"../client/errors.js\";\nimport type { IpRiskResponse } from \"../client/types.js\";\nimport { resolveOptionalApiKey, resolveBaseUrl } from \"../utils/env.js\";\nimport { isValidIp } from \"../utils/ip.js\";\nimport { runPool } from \"../utils/pool.js\";\nimport { ExitCode, exitCodeForApiErrorCode, type ExitCodeValue } from \"../utils/exitCode.js\";\nimport { printJsonLine } from \"../output/jsonl.js\";\nimport { renderBatchTable } from \"../output/table.js\";\n\n/**\n * Client-side batch only: sends individual `GET /v1/ip-risk/{ip}` requests with controlled\n * concurrency. There is currently no server-side batch endpoint - do not call one.\n */\nconst MAX_CONCURRENCY = 20;\nconst DEFAULT_CONCURRENCY = 5;\n\nexport interface BatchItemError {\n code: string;\n message: string;\n requestId?: string;\n /** Present on `anonymous_daily_limit_reached`, so the summary can report the real allowance. */\n anonymousUsage?: AnonymousLimitInfo;\n}\n\nexport type BatchItemResult =\n | { ip: string; ok: true; result: IpRiskResponse }\n | { ip: string; ok: false; error: BatchItemError };\n\ninterface BatchOptions {\n apiKey?: string;\n baseUrl?: string;\n concurrency: string;\n jsonl?: boolean;\n timeout: string;\n maxRetries: string;\n}\n\nexport function registerBatchCommand(program: Command): void {\n program\n .command(\"batch <file>\")\n .description(\"Check multiple IP addresses (client-side batch over GET /v1/ip-risk/{ip})\")\n .option(\n \"--api-key <key>\",\n \"NetRiskScan API key (optional; uses the anonymous trial when omitted)\",\n )\n .option(\"--base-url <url>\", \"Override the API base URL (advanced)\")\n .option(\n \"--concurrency <n>\",\n `Number of concurrent requests (default: ${DEFAULT_CONCURRENCY}, max: ${MAX_CONCURRENCY})`,\n String(DEFAULT_CONCURRENCY),\n )\n .option(\"--jsonl\", \"Output newline-delimited JSON (one object per IP)\")\n .option(\"--timeout <ms>\", \"Request timeout in milliseconds\", \"10000\")\n .option(\"--max-retries <n>\", \"Maximum automatic retries for 429/503\", \"3\")\n .addHelpText(\n \"after\",\n `\nNotes:\n This is a client-side batch: it sends individual GET /v1/ip-risk/{ip}\n requests with controlled concurrency. NetRiskScan does not currently\n offer a server-side batch endpoint. Make sure the selected concurrency\n complies with the limits shown in your NetRiskScan Developer Dashboard.\n\n An API key is optional. Without an API key, requests use the anonymous daily\n trial, metered by public IP. How many remain is decided by the server, not by\n this CLI, and is reported in the summary after the table.\n\nInput format:\n One IP per line. Blank lines and lines starting with # are ignored.\n\nExamples:\n $ netriskscan batch ips.txt\n $ cat ips.txt | netriskscan batch -\n $ netriskscan batch ips.txt --concurrency 10 --jsonl > results.jsonl\n`,\n )\n .action(async (file: string, options: BatchOptions) => {\n await runBatch(file, options);\n });\n}\n\nasync function readIps(file: string): Promise<string[]> {\n const stream = file === \"-\" ? process.stdin : createReadStream(file, \"utf8\");\n const rl = createInterface({ input: stream, crlfDelay: Infinity });\n const ips: string[] = [];\n for await (const rawLine of rl) {\n const line = rawLine.trim();\n if (line === \"\" || line.startsWith(\"#\")) continue;\n ips.push(line);\n }\n return ips;\n}\n\nfunction parseConcurrency(value: string): number {\n const n = Number(value);\n if (!Number.isFinite(n) || n < 1) return DEFAULT_CONCURRENCY;\n if (n > MAX_CONCURRENCY) {\n process.stderr.write(\n `Warning: --concurrency ${n} exceeds the safety cap of ${MAX_CONCURRENCY}; using ${MAX_CONCURRENCY}.\\n` +\n \"Check your NetRiskScan Developer Dashboard for your plan's concurrency limit.\\n\",\n );\n return MAX_CONCURRENCY;\n }\n return Math.floor(n);\n}\n\nfunction toBatchError(err: unknown): BatchItemError {\n if (err instanceof NetRiskScanApiError) {\n return {\n code: err.code,\n message: err.message,\n requestId: err.requestId,\n anonymousUsage: err.anonymousUsage,\n };\n }\n if (err instanceof NetRiskScanNetworkError) {\n return { code: \"network_error\", message: err.message, requestId: err.requestId };\n }\n return { code: \"unknown_error\", message: err instanceof Error ? err.message : String(err) };\n}\n\nasync function runBatch(file: string, options: BatchOptions): Promise<void> {\n const ips = await readIps(file);\n if (ips.length === 0) {\n process.stderr.write(\"Error: no IP addresses found in input.\\n\");\n process.exitCode = ExitCode.InvalidArgument;\n return;\n }\n\n // No key means the anonymous trial. The CLI deliberately does not pre-check the input length\n // against a daily allowance: it cannot know how much of today's allowance was already spent,\n // and only the server can.\n const client = new NetRiskScanClient({\n apiKey: resolveOptionalApiKey(options.apiKey),\n baseUrl: resolveBaseUrl(options.baseUrl),\n timeout: Number(options.timeout),\n maxRetries: Number(options.maxRetries),\n });\n\n const concurrency = parseConcurrency(options.concurrency);\n\n const results = await runPool(ips, concurrency, async (ip): Promise<BatchItemResult> => {\n if (!isValidIp(ip)) {\n return {\n ip,\n ok: false,\n error: { code: \"invalid_ip\", message: `\"${ip}\" is not a valid IPv4 or IPv6 address.` },\n };\n }\n try {\n const { data } = await client.checkIp(ip);\n return { ip, ok: true, result: data };\n } catch (err) {\n return { ip, ok: false, error: toBatchError(err) };\n }\n });\n\n if (options.jsonl) {\n for (const item of results) {\n printJsonLine(item);\n }\n } else {\n renderBatchTable(results);\n }\n\n process.exitCode = computeBatchExitCode(results);\n}\n\nfunction computeBatchExitCode(results: readonly BatchItemResult[]): ExitCodeValue {\n const failures = results.filter((r): r is Extract<BatchItemResult, { ok: false }> => !r.ok);\n if (failures.length === 0) return ExitCode.Success;\n\n const codes = failures.map((f) => exitCodeForApiErrorCode(f.error.code));\n if (codes.includes(ExitCode.AuthError)) return ExitCode.AuthError;\n if (codes.includes(ExitCode.RateLimitOrQuota)) return ExitCode.RateLimitOrQuota;\n return ExitCode.ApiError;\n}\n","/** Runs `worker` over `items` with at most `concurrency` in flight, preserving result order. */\nexport async function runPool<T, R>(\n items: readonly T[],\n concurrency: number,\n worker: (item: T, index: number) => Promise<R>,\n): Promise<R[]> {\n const results: R[] = new Array(items.length);\n let cursor = 0;\n\n async function next(): Promise<void> {\n while (cursor < items.length) {\n const index = cursor++;\n results[index] = await worker(items[index] as T, index);\n }\n }\n\n const workerCount = Math.max(1, Math.min(concurrency, items.length));\n await Promise.all(Array.from({ length: workerCount }, () => next()));\n return results;\n}\n","/** One compact JSON object per line, so a failed line never breaks the rest of the stream. */\nexport function printJsonLine(data: unknown): void {\n process.stdout.write(`${JSON.stringify(data)}\\n`);\n}\n","import Table from \"cli-table3\";\nimport chalk from \"chalk\";\nimport type { BatchItemResult } from \"../commands/batch.js\";\nimport { ANONYMOUS_DAILY_LIMIT_CODE } from \"../client/errors.js\";\nimport { formatIndex, formatNumber, formatTriState, row } 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\", \"VPN\", \"Tor\", \"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 formatTriState(result.flags.vpn),\n formatTriState(result.flags.tor),\n chalk.green(\"ok\"),\n ]);\n } else {\n table.push([item.ip, \"-\", \"-\", \"-\", \"-\", \"-\", chalk.red(`error: ${item.error.code}`)]);\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;A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AI;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 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;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qBAAqB,OAAO;AAC5B,qBAAqB,OAAO;AAC5B,qBAAqB,OAAO;AAE5B,QAAQ,aAAa;AAErB,IAAI;AACF,QAAM,QAAQ,WAAW,QAAQ,IAAI;AACvC,SAAS,KAAK;AACZ,MAAI,eAAe,gBAAgB;AACjC,QAAI,IAAI,SAAS,6BAA6B,IAAI,SAAS,qBAAqB;AAC9E,cAAQ,WAAW,SAAS;AAAA,IAC9B,OAAO;AACL,cAAQ,WAAW,SAAS;AAAA,IAC9B;AAAA,EACF,OAAO;AACL,YAAQ,OAAO,MAAM,qBAAqB,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAAA,CAAI;AAC9F,YAAQ,WAAW,SAAS;AAAA,EAC9B;AACF;","names":["chalk","chalk","LABEL_WIDTH","program","ora","program","ora","chalk","chalk","program"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,68 @@
|
|
|
1
1
|
type RiskBand = "excellent" | "good" | "fair" | "poor" | "high_risk" | "unknown";
|
|
2
2
|
type AssessmentGrade = "complete" | "partial" | "limited" | "insufficient";
|
|
3
|
+
/**
|
|
4
|
+
* Server classification of an address already flagged `proxy: true` - a documented, closed set of
|
|
5
|
+
* the subtypes the server currently emits. Unlike `network.type`/`profile`, this is kept as a real
|
|
6
|
+
* union rather than `string` because the CLI's own formatter needs to switch on it; that formatter
|
|
7
|
+
* still renders an unrecognised raw value verbatim instead of throwing, since a runtime response is
|
|
8
|
+
* never actually guaranteed to match this compile-time type.
|
|
9
|
+
*/
|
|
10
|
+
type ProxyType = "residential_proxy" | "isp_proxy" | "mobile_proxy" | "datacenter_proxy" | "unknown_proxy";
|
|
11
|
+
/**
|
|
12
|
+
* Network-level geolocation of the address, as `GET /v1/ip-risk/{ip}` reports it.
|
|
13
|
+
*
|
|
14
|
+
* This is where the *network* is registered/routed - never the device's GPS position, and never
|
|
15
|
+
* the end user's precise physical location. A city can be the operator's aggregation point rather
|
|
16
|
+
* than the subscriber's town.
|
|
17
|
+
*
|
|
18
|
+
* Every field is nullable and independently so: an address can resolve to a country with no region
|
|
19
|
+
* and no city. The CLI shows only what the server actually sent - a missing field is dropped, never
|
|
20
|
+
* back-filled from the code, translated, re-cased, or guessed from a neighbouring field.
|
|
21
|
+
*
|
|
22
|
+
* Only the fields the public API documents live here. Latitude/longitude, postal code, continent
|
|
23
|
+
* and accuracy radius are deliberately absent: they are not part of the `/v1` contract.
|
|
24
|
+
*/
|
|
25
|
+
interface IpLocation {
|
|
26
|
+
/** ISO 3166-1 alpha-2, e.g. `"US"`. */
|
|
27
|
+
countryCode: string | null;
|
|
28
|
+
/** Server-owned display name, e.g. `"United States"`. Shown verbatim. */
|
|
29
|
+
country: string | null;
|
|
30
|
+
/** ISO 3166-2 subdivision code without the country prefix, e.g. `"CA"`. */
|
|
31
|
+
regionCode: string | null;
|
|
32
|
+
/** Server-owned display name, e.g. `"California"`. Shown verbatim. */
|
|
33
|
+
region: string | null;
|
|
34
|
+
city: string | null;
|
|
35
|
+
/** IANA time zone id, e.g. `"America/Los_Angeles"`. */
|
|
36
|
+
timeZone: string | null;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* One server-generated explanation for the assessment.
|
|
40
|
+
*
|
|
41
|
+
* Reasons are *server-owned output*: the CLI renders them and never derives, infers, filters,
|
|
42
|
+
* re-orders or invents one from `flags`/`network`. `flags.tor === true` in particular does not
|
|
43
|
+
* imply `TOR_EXIT_NODE` - only the server can say which it is.
|
|
44
|
+
*
|
|
45
|
+
* Not every reason is negative. `VERIFIED_SEARCH_CRAWLER`, `PUBLIC_INFRASTRUCTURE` and
|
|
46
|
+
* `RESIDENTIAL_NETWORK` explain why an address scores *well*. A reason is an explanation of the
|
|
47
|
+
* assessment, never proof of malicious activity.
|
|
48
|
+
*
|
|
49
|
+
* All three fields are deliberately `string`, not closed unions. The vocabulary is additive: the
|
|
50
|
+
* server can introduce a new code, category or severity at any time, and a CLI already installed
|
|
51
|
+
* in the wild must render the unfamiliar value rather than throw, drop it, or relabel it
|
|
52
|
+
* "Unknown". Known codes at the time of writing - `RESIDENTIAL_PROXY_DETECTED`, `ISP_PROXY_DETECTED`,
|
|
53
|
+
* `MOBILE_PROXY_DETECTED`, `DATACENTER_PROXY_DETECTED`, `PROXY_DETECTED`, `VPN_DETECTED`,
|
|
54
|
+
* `TOR_RELAY`, `TOR_EXIT_NODE`, `KNOWN_SCANNER`, `ABUSE_ACTIVITY`, `BLACKLIST_MATCH`, `BOTNET_C2`,
|
|
55
|
+
* `COMPROMISED_HOST`, `VERIFIED_SEARCH_CRAWLER`, `PUBLIC_INFRASTRUCTURE`, `RESIDENTIAL_NETWORK`,
|
|
56
|
+
* `CONFLICTING_EVIDENCE`, `INSUFFICIENT_EVIDENCE` - are documentation, not an exhaustive contract.
|
|
57
|
+
*/
|
|
58
|
+
interface RiskReason {
|
|
59
|
+
/** Stable machine identifier, e.g. `"RESIDENTIAL_PROXY_DETECTED"`. */
|
|
60
|
+
code: string;
|
|
61
|
+
/** Grouping, e.g. `"anonymity"`, `"identity"`, `"network"`, `"threat"`. */
|
|
62
|
+
category: string;
|
|
63
|
+
/** e.g. `"critical"`, `"high"`, `"medium"`, `"low"`, `"info"`. */
|
|
64
|
+
severity: string;
|
|
65
|
+
}
|
|
3
66
|
/**
|
|
4
67
|
* Response of `GET /v1/ip-risk/{ip}`.
|
|
5
68
|
*
|
|
@@ -12,6 +75,15 @@ interface IpRiskResponse {
|
|
|
12
75
|
index: number | null;
|
|
13
76
|
band: RiskBand | null;
|
|
14
77
|
assessmentGrade: AssessmentGrade;
|
|
78
|
+
/**
|
|
79
|
+
* Why the server assessed the address this way. Absent (key omitted) on a server that predates
|
|
80
|
+
* the field, and legitimately `[]` on a newer one that had nothing to explain - both mean
|
|
81
|
+
* "print no reasons", never "the CLI should work some out".
|
|
82
|
+
*
|
|
83
|
+
* Purely explanatory: {@link index}, {@link band} and {@link assessmentGrade} are already the
|
|
84
|
+
* server's verdict and are never recomputed from this list.
|
|
85
|
+
*/
|
|
86
|
+
reasons?: RiskReason[];
|
|
15
87
|
};
|
|
16
88
|
network: {
|
|
17
89
|
type: string | null;
|
|
@@ -37,12 +109,36 @@ interface IpRiskResponse {
|
|
|
37
109
|
};
|
|
38
110
|
flags: {
|
|
39
111
|
proxy: boolean | null;
|
|
112
|
+
/**
|
|
113
|
+
* Subtype of an address already flagged `proxy: true`. `null` when not applicable or not
|
|
114
|
+
* determined. Absent (key omitted) on a server that predates this field - read defensively,
|
|
115
|
+
* the same way {@link IpRiskResponse.network}'s `profile`/`service` already are.
|
|
116
|
+
*/
|
|
117
|
+
proxyType?: ProxyType | null;
|
|
40
118
|
vpn: boolean | null;
|
|
41
119
|
tor: boolean | null;
|
|
42
120
|
datacenter: boolean | null;
|
|
43
121
|
scanner: boolean | null;
|
|
44
122
|
abuse: boolean | null;
|
|
123
|
+
/**
|
|
124
|
+
* Whether the server has verified this address as a known search engine crawler. Absent on a
|
|
125
|
+
* server that predates this field - read defensively.
|
|
126
|
+
*/
|
|
127
|
+
searchCrawler?: boolean | null;
|
|
128
|
+
/**
|
|
129
|
+
* Canonical crawler display name, e.g. `"Googlebot"`, `"Bingbot"`, `"Applebot"` - server-owned
|
|
130
|
+
* and shown verbatim, never reformatted. Deliberately `string`, not a closed union: the server
|
|
131
|
+
* adds crawlers as new sources are onboarded, and an unrecognised one must still render, not
|
|
132
|
+
* throw. Absent on a server that predates this field - read defensively.
|
|
133
|
+
*/
|
|
134
|
+
searchCrawlerName?: string | null;
|
|
45
135
|
};
|
|
136
|
+
/**
|
|
137
|
+
* Network-level geolocation. Absent (key omitted) on a server that predates the field, and
|
|
138
|
+
* `null` when the address could not be located at all - read defensively, exactly as
|
|
139
|
+
* {@link IpRiskResponse.network}'s `profile`/`service` already are.
|
|
140
|
+
*/
|
|
141
|
+
location?: IpLocation | null;
|
|
46
142
|
/**
|
|
47
143
|
* Access mode and, for the anonymous trial, how much of today's allowance is left.
|
|
48
144
|
*
|
|
@@ -227,4 +323,4 @@ declare class NetRiskScanNetworkError extends NetRiskScanError {
|
|
|
227
323
|
constructor(message: string, options?: NetRiskScanNetworkErrorOptions);
|
|
228
324
|
}
|
|
229
325
|
|
|
230
|
-
export { ANONYMOUS_DAILY_LIMIT_CODE, type AnonymousLimitInfo, type ApiErrorBody, type ApiResult, type AssessmentGrade, type IpRiskResponse, KNOWN_ERROR_CODES, type KnownErrorCode, NetRiskScanApiError, type NetRiskScanApiErrorOptions, NetRiskScanClient, type NetRiskScanClientOptions, NetRiskScanConfigError, NetRiskScanError, NetRiskScanNetworkError, type NetRiskScanNetworkErrorOptions, type QuotaInfo, type RateLimitInfo, type RequestOptions, type RequestUsage, type ResponseMeta, type RiskBand, type RiskFlagName, type UsageResponse };
|
|
326
|
+
export { ANONYMOUS_DAILY_LIMIT_CODE, type AnonymousLimitInfo, type ApiErrorBody, type ApiResult, type AssessmentGrade, type IpLocation, type IpRiskResponse, KNOWN_ERROR_CODES, type KnownErrorCode, NetRiskScanApiError, type NetRiskScanApiErrorOptions, NetRiskScanClient, type NetRiskScanClientOptions, NetRiskScanConfigError, NetRiskScanError, NetRiskScanNetworkError, type NetRiskScanNetworkErrorOptions, type ProxyType, type QuotaInfo, type RateLimitInfo, type RequestOptions, type RequestUsage, type ResponseMeta, type RiskBand, type RiskFlagName, type RiskReason, type UsageResponse };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "netriskscan-cli",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.5.0",
|
|
4
4
|
"description": "Official command-line client and SDK for the NetRiskScan Developer API - query IP risk, network intelligence and reputation data from your terminal.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"netriskscan",
|