netriskscan-cli 1.6.2 → 2.1.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 +157 -229
- package/dist/cli.js +1351 -443
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +8 -12
- package/dist/index.js +44 -11
- package/dist/index.js.map +1 -1
- package/package.json +6 -3
package/dist/index.d.ts
CHANGED
|
@@ -273,18 +273,9 @@ interface RequestOptions {
|
|
|
273
273
|
/**
|
|
274
274
|
* Client for the NetRiskScan Developer API (`/v1/*` only).
|
|
275
275
|
*
|
|
276
|
-
*
|
|
277
|
-
* the server serves the request from the anonymous daily trial, metered by public IP.
|
|
276
|
+
* Pass an API key for the current Developer API.
|
|
278
277
|
*
|
|
279
|
-
* @example
|
|
280
|
-
* ```ts
|
|
281
|
-
* const client = new NetRiskScanClient();
|
|
282
|
-
* const { data } = await client.checkIp("1.1.1.1");
|
|
283
|
-
* console.log(data.risk.index);
|
|
284
|
-
* console.log(data.usage?.remaining);
|
|
285
|
-
* ```
|
|
286
|
-
*
|
|
287
|
-
* @example Pass `apiKey` to use Developer Account quota instead of the anonymous trial
|
|
278
|
+
* @example
|
|
288
279
|
* ```ts
|
|
289
280
|
* const client = new NetRiskScanClient({ apiKey: process.env.NETRISKSCAN_API_KEY });
|
|
290
281
|
* ```
|
|
@@ -301,10 +292,11 @@ declare class NetRiskScanClient {
|
|
|
301
292
|
* has no anonymous equivalent and requires an API key.
|
|
302
293
|
*/
|
|
303
294
|
getUsage(options?: RequestOptions): Promise<ApiResult<UsageResponse>>;
|
|
295
|
+
private redact;
|
|
304
296
|
private request;
|
|
305
297
|
}
|
|
306
298
|
|
|
307
|
-
declare const KNOWN_ERROR_CODES: readonly ["invalid_ip", "invalid_request", "unsupported_parameter", "invalid_api_key", "api_key_disabled", "scope_not_allowed", "not_found", "feature_not_available", "rate_limit_exceeded", "quota_exceeded", "anonymous_daily_limit_reached", "temporarily_unavailable"];
|
|
299
|
+
declare const KNOWN_ERROR_CODES: readonly ["invalid_ip", "invalid_request", "unsupported_parameter", "invalid_api_key", "api_key_invalid", "api_key_required", "api_key_expired", "api_key_disabled", "subscription_required", "scope_not_allowed", "not_found", "feature_not_available", "rate_limit_exceeded", "quota_exceeded", "monthly_quota_exceeded", "anonymous_daily_limit_reached", "temporarily_unavailable"];
|
|
308
300
|
type KnownErrorCode = (typeof KNOWN_ERROR_CODES)[number];
|
|
309
301
|
/**
|
|
310
302
|
* The anonymous trial's daily allowance is spent. Deterministic until the UTC reset, so unlike
|
|
@@ -337,6 +329,8 @@ interface NetRiskScanApiErrorOptions {
|
|
|
337
329
|
requestId?: string;
|
|
338
330
|
retryAfter?: number;
|
|
339
331
|
anonymousUsage?: AnonymousLimitInfo;
|
|
332
|
+
quota?: QuotaInfo;
|
|
333
|
+
quotaResetAt?: string;
|
|
340
334
|
}
|
|
341
335
|
/** Thrown when the Developer API responds with a non-2xx status. */
|
|
342
336
|
declare class NetRiskScanApiError extends NetRiskScanError {
|
|
@@ -346,6 +340,8 @@ declare class NetRiskScanApiError extends NetRiskScanError {
|
|
|
346
340
|
readonly retryAfter?: number;
|
|
347
341
|
/** Present when the server reported anonymous-trial allowance alongside the error. */
|
|
348
342
|
readonly anonymousUsage?: AnonymousLimitInfo;
|
|
343
|
+
readonly quota?: QuotaInfo;
|
|
344
|
+
readonly quotaResetAt?: string;
|
|
349
345
|
constructor(message: string, options: NetRiskScanApiErrorOptions);
|
|
350
346
|
}
|
|
351
347
|
interface NetRiskScanNetworkErrorOptions {
|
package/dist/index.js
CHANGED
|
@@ -4,16 +4,24 @@ var KNOWN_ERROR_CODES = [
|
|
|
4
4
|
"invalid_request",
|
|
5
5
|
"unsupported_parameter",
|
|
6
6
|
"invalid_api_key",
|
|
7
|
+
"api_key_invalid",
|
|
8
|
+
"api_key_required",
|
|
9
|
+
"api_key_expired",
|
|
7
10
|
"api_key_disabled",
|
|
11
|
+
"subscription_required",
|
|
8
12
|
"scope_not_allowed",
|
|
9
13
|
"not_found",
|
|
10
14
|
"feature_not_available",
|
|
11
15
|
"rate_limit_exceeded",
|
|
12
16
|
"quota_exceeded",
|
|
17
|
+
"monthly_quota_exceeded",
|
|
13
18
|
"anonymous_daily_limit_reached",
|
|
14
19
|
"temporarily_unavailable"
|
|
15
20
|
];
|
|
16
21
|
var ANONYMOUS_DAILY_LIMIT_CODE = "anonymous_daily_limit_reached";
|
|
22
|
+
function isMonthlyQuotaError(code) {
|
|
23
|
+
return code === "quota_exceeded" || code === "monthly_quota_exceeded";
|
|
24
|
+
}
|
|
17
25
|
var NetRiskScanError = class extends Error {
|
|
18
26
|
constructor(message) {
|
|
19
27
|
super(message);
|
|
@@ -33,6 +41,8 @@ var NetRiskScanApiError = class extends NetRiskScanError {
|
|
|
33
41
|
retryAfter;
|
|
34
42
|
/** Present when the server reported anonymous-trial allowance alongside the error. */
|
|
35
43
|
anonymousUsage;
|
|
44
|
+
quota;
|
|
45
|
+
quotaResetAt;
|
|
36
46
|
constructor(message, options) {
|
|
37
47
|
super(message);
|
|
38
48
|
this.name = "NetRiskScanApiError";
|
|
@@ -41,6 +51,8 @@ var NetRiskScanApiError = class extends NetRiskScanError {
|
|
|
41
51
|
this.requestId = options.requestId;
|
|
42
52
|
this.retryAfter = options.retryAfter;
|
|
43
53
|
this.anonymousUsage = options.anonymousUsage;
|
|
54
|
+
this.quota = options.quota;
|
|
55
|
+
this.quotaResetAt = options.quotaResetAt;
|
|
44
56
|
}
|
|
45
57
|
};
|
|
46
58
|
var NetRiskScanNetworkError = class extends NetRiskScanError {
|
|
@@ -64,9 +76,9 @@ function generateRequestId() {
|
|
|
64
76
|
return `req_${randomBytes(12).toString("hex")}`;
|
|
65
77
|
}
|
|
66
78
|
function parseIntHeader(value) {
|
|
67
|
-
if (value === null) return void 0;
|
|
79
|
+
if (value === null || !/^\d+$/.test(value)) return void 0;
|
|
68
80
|
const n = Number(value);
|
|
69
|
-
return Number.
|
|
81
|
+
return Number.isSafeInteger(n) ? n : void 0;
|
|
70
82
|
}
|
|
71
83
|
function parseRateLimit(headers) {
|
|
72
84
|
return {
|
|
@@ -88,7 +100,7 @@ function isRetryableStatus(status) {
|
|
|
88
100
|
return status === 429 || status === 503;
|
|
89
101
|
}
|
|
90
102
|
function isRetryableFailure(status, code) {
|
|
91
|
-
if (code === ANONYMOUS_DAILY_LIMIT_CODE) return false;
|
|
103
|
+
if (code === ANONYMOUS_DAILY_LIMIT_CODE || isMonthlyQuotaError(code)) return false;
|
|
92
104
|
return isRetryableStatus(status);
|
|
93
105
|
}
|
|
94
106
|
var BASE_DELAY_MS = 1e3;
|
|
@@ -112,6 +124,19 @@ var DEFAULT_MAX_RETRIES = 3;
|
|
|
112
124
|
function isAbortError(err) {
|
|
113
125
|
return err instanceof Error && err.name === "AbortError";
|
|
114
126
|
}
|
|
127
|
+
function quotaResetAt(headers, seconds) {
|
|
128
|
+
const quotaReset = headers.get("x-quota-reset");
|
|
129
|
+
if (quotaReset && /^\d+$/.test(quotaReset)) {
|
|
130
|
+
const reset2 = new Date(Number(quotaReset) * 1e3);
|
|
131
|
+
if (Number.isFinite(reset2.getTime())) return reset2.toISOString();
|
|
132
|
+
}
|
|
133
|
+
if (seconds === void 0 || !Number.isFinite(seconds) || seconds < 0) return void 0;
|
|
134
|
+
const responseDate = Date.parse(headers.get("date") ?? "");
|
|
135
|
+
const reset = new Date(
|
|
136
|
+
(Number.isFinite(responseDate) ? responseDate : Date.now()) + seconds * 1e3
|
|
137
|
+
);
|
|
138
|
+
return Number.isFinite(reset.getTime()) ? reset.toISOString() : void 0;
|
|
139
|
+
}
|
|
115
140
|
async function safeJson(res) {
|
|
116
141
|
try {
|
|
117
142
|
return await res.json();
|
|
@@ -152,6 +177,9 @@ var NetRiskScanClient = class {
|
|
|
152
177
|
}
|
|
153
178
|
return this.request("/v1/usage", options);
|
|
154
179
|
}
|
|
180
|
+
redact(value) {
|
|
181
|
+
return this.apiKey ? value.replaceAll(this.apiKey, "[REDACTED]") : value;
|
|
182
|
+
}
|
|
155
183
|
async request(path, options) {
|
|
156
184
|
const requestId = options.requestId && isValidRequestId(options.requestId) ? options.requestId : generateRequestId();
|
|
157
185
|
let attempt = 0;
|
|
@@ -171,29 +199,34 @@ var NetRiskScanClient = class {
|
|
|
171
199
|
const res = await fetch(`${this.baseUrl}${path}`, {
|
|
172
200
|
method: "GET",
|
|
173
201
|
headers,
|
|
202
|
+
redirect: this.apiKey ? "error" : "follow",
|
|
174
203
|
signal: timeoutController.signal
|
|
175
204
|
});
|
|
176
205
|
const rateLimit = parseRateLimit(res.headers);
|
|
177
206
|
const quota = parseQuota(res.headers);
|
|
178
|
-
const responseRequestId = res.headers.get("x-request-id") ?? requestId;
|
|
207
|
+
const responseRequestId = this.redact(res.headers.get("x-request-id") ?? requestId);
|
|
179
208
|
if (res.ok) {
|
|
180
209
|
const data = await res.json();
|
|
181
210
|
return { data, meta: { requestId: responseRequestId, rateLimit, quota } };
|
|
182
211
|
}
|
|
183
212
|
const body = await safeJson(res);
|
|
184
213
|
const retryAfterHeader = res.headers.get("retry-after");
|
|
185
|
-
const
|
|
186
|
-
|
|
214
|
+
const delay = retryAfterHeader?.trim() ? Number(retryAfterHeader) : NaN;
|
|
215
|
+
const retryAfter = Number.isFinite(delay) && delay >= 0 ? delay : void 0;
|
|
216
|
+
const code = body?.error?.code ?? "unknown_error";
|
|
217
|
+
if (isRetryableFailure(res.status, code) && attempt < this.maxRetries) {
|
|
187
218
|
attempt += 1;
|
|
188
219
|
await sleep(computeBackoffMs(attempt, retryAfter));
|
|
189
220
|
continue;
|
|
190
221
|
}
|
|
191
|
-
throw new NetRiskScanApiError(body?.error?.message ?? res.statusText, {
|
|
222
|
+
throw new NetRiskScanApiError(this.redact(body?.error?.message ?? res.statusText), {
|
|
192
223
|
status: res.status,
|
|
193
|
-
code:
|
|
194
|
-
requestId: body?.error?.requestId ?? responseRequestId,
|
|
224
|
+
code: this.redact(code),
|
|
225
|
+
requestId: this.redact(body?.error?.requestId ?? responseRequestId),
|
|
195
226
|
retryAfter,
|
|
196
|
-
anonymousUsage: parseAnonymousLimitInfo(body)
|
|
227
|
+
anonymousUsage: parseAnonymousLimitInfo(body),
|
|
228
|
+
quota: isMonthlyQuotaError(code) ? quota : void 0,
|
|
229
|
+
quotaResetAt: isMonthlyQuotaError(code) ? quotaResetAt(res.headers, retryAfter) : void 0
|
|
197
230
|
});
|
|
198
231
|
} catch (err) {
|
|
199
232
|
if (err instanceof NetRiskScanApiError) {
|
|
@@ -209,7 +242,7 @@ var NetRiskScanClient = class {
|
|
|
209
242
|
});
|
|
210
243
|
}
|
|
211
244
|
throw new NetRiskScanNetworkError(
|
|
212
|
-
err instanceof Error ? err.message : "Network request failed",
|
|
245
|
+
err instanceof Error ? this.redact(err.message) : "Network request failed",
|
|
213
246
|
{
|
|
214
247
|
cause: err,
|
|
215
248
|
requestId
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/client/errors.ts","../src/client/headers.ts","../src/client/retry.ts","../src/client/NetRiskScanClient.ts"],"sourcesContent":["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"],"mappings":";AAAO,IAAM,oBAAoB;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAQO,IAAM,6BAA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UAAU;AAAA,UACrC;AAAA,YACE,OAAO;AAAA,YACP;AAAA,UACF;AAAA,QACF;AAAA,MACF,UAAE;AACA,qBAAa,KAAK;AAClB,gBAAQ,QAAQ,oBAAoB,SAAS,eAAe;AAAA,MAC9D;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/client/errors.ts","../src/client/headers.ts","../src/client/retry.ts","../src/client/NetRiskScanClient.ts"],"sourcesContent":["import type { QuotaInfo } from \"./types.js\";\n\nexport const KNOWN_ERROR_CODES = [\n \"invalid_ip\",\n \"invalid_request\",\n \"unsupported_parameter\",\n \"invalid_api_key\",\n \"api_key_invalid\",\n \"api_key_required\",\n \"api_key_expired\",\n \"api_key_disabled\",\n \"subscription_required\",\n \"scope_not_allowed\",\n \"not_found\",\n \"feature_not_available\",\n \"rate_limit_exceeded\",\n \"quota_exceeded\",\n \"monthly_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\nexport function isMonthlyQuotaError(code?: string): boolean {\n return code === \"quota_exceeded\" || code === \"monthly_quota_exceeded\";\n}\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 quota?: QuotaInfo;\n quotaResetAt?: string;\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 readonly quota?: QuotaInfo;\n readonly quotaResetAt?: string;\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 this.quota = options.quota;\n this.quotaResetAt = options.quotaResetAt;\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 || !/^\\d+$/.test(value)) return undefined;\n const n = Number(value);\n return Number.isSafeInteger(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 <= 13) 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, isMonthlyQuotaError } 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 || isMonthlyQuotaError(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 {\n isMonthlyQuotaError,\n NetRiskScanApiError,\n NetRiskScanConfigError,\n NetRiskScanNetworkError,\n} 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\nexport const 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\nfunction quotaResetAt(headers: Headers, seconds?: number): string | undefined {\n const quotaReset = headers.get(\"x-quota-reset\");\n if (quotaReset && /^\\d+$/.test(quotaReset)) {\n const reset = new Date(Number(quotaReset) * 1000);\n if (Number.isFinite(reset.getTime())) return reset.toISOString();\n }\n if (seconds === undefined || !Number.isFinite(seconds) || seconds < 0) return undefined;\n const responseDate = Date.parse(headers.get(\"date\") ?? \"\");\n const reset = new Date(\n (Number.isFinite(responseDate) ? responseDate : Date.now()) + seconds * 1000,\n );\n return Number.isFinite(reset.getTime()) ? reset.toISOString() : undefined;\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 * Pass an API key for the current Developer API.\n *\n * @example\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 // Optional for direct SDK clients that still connect to older servers.\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 redact(value: string): string {\n return this.apiKey ? value.replaceAll(this.apiKey, \"[REDACTED]\") : value;\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 redirect: this.apiKey ? \"error\" : \"follow\",\n signal: timeoutController.signal,\n });\n\n const rateLimit = parseRateLimit(res.headers);\n const quota = parseQuota(res.headers);\n const responseRequestId = this.redact(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 delay = retryAfterHeader?.trim() ? Number(retryAfterHeader) : NaN;\n const retryAfter = Number.isFinite(delay) && delay >= 0 ? delay : undefined;\n const code = body?.error?.code ?? \"unknown_error\";\n\n if (isRetryableFailure(res.status, code) && attempt < this.maxRetries) {\n attempt += 1;\n await sleep(computeBackoffMs(attempt, retryAfter));\n continue;\n }\n\n throw new NetRiskScanApiError(this.redact(body?.error?.message ?? res.statusText), {\n status: res.status,\n code: this.redact(code),\n requestId: this.redact(body?.error?.requestId ?? responseRequestId),\n retryAfter,\n anonymousUsage: parseAnonymousLimitInfo(body),\n quota: isMonthlyQuotaError(code) ? quota : undefined,\n quotaResetAt: isMonthlyQuotaError(code)\n ? quotaResetAt(res.headers, retryAfter)\n : undefined,\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 ? this.redact(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"],"mappings":";AAEO,IAAM,oBAAoB;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAQO,IAAM,6BAA6B;AAEnC,SAAS,oBAAoB,MAAwB;AAC1D,SAAO,SAAS,oBAAoB,SAAS;AAC/C;AAgBO,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;AAaO,IAAM,sBAAN,cAAkC,iBAAiB;AAAA,EAC/C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EAET,YAAY,SAAiB,SAAqC;AAChE,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS,QAAQ;AACtB,SAAK,OAAO,QAAQ;AACpB,SAAK,YAAY,QAAQ;AACzB,SAAK,aAAa,QAAQ;AAC1B,SAAK,iBAAiB,QAAQ;AAC9B,SAAK,QAAQ,QAAQ;AACrB,SAAK,eAAe,QAAQ;AAAA,EAC9B;AACF;AAQO,IAAM,0BAAN,cAAsC,iBAAiB;AAAA,EAC1C;AAAA,EACT;AAAA,EAET,YAAY,SAAiB,UAA0C,CAAC,GAAG;AACzE,UA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,IAAI,SAAS,UAAU,IACpC;AAAA,QACN,CAAC;AAAA,MACH,SAAS,KAAK;AACZ,YAAI,eAAe,qBAAqB;AACtC,gBAAM;AAAA,QACR;AACA,YAAI,aAAa,GAAG,GAAG;AACrB,cAAI,QAAQ,QAAQ,SAAS;AAC3B,kBAAM;AAAA,UACR;AACA,gBAAM,IAAI,wBAAwB,2BAA2B,KAAK,OAAO,MAAM;AAAA,YAC7E,OAAO;AAAA,YACP;AAAA,UACF,CAAC;AAAA,QACH;AACA,cAAM,IAAI;AAAA,UACR,eAAe,QAAQ,KAAK,OAAO,IAAI,OAAO,IAAI;AAAA,UAClD;AAAA,YACE,OAAO;AAAA,YACP;AAAA,UACF;AAAA,QACF;AAAA,MACF,UAAE;AACA,qBAAa,KAAK;AAClB,gBAAQ,QAAQ,oBAAoB,SAAS,eAAe;AAAA,MAC9D;AAAA,IACF;AAAA,EACF;AACF;","names":["reset"]}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "netriskscan-cli",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"description": "Official NetRiskScan CLI and TypeScript client for IP reputation
|
|
3
|
+
"version": "2.1.0",
|
|
4
|
+
"description": "Official NetRiskScan CLI and TypeScript client for IP reputation and network intelligence, with secure CLI API key storage and monthly quota reporting.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"netriskscan",
|
|
7
7
|
"ip-intelligence",
|
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
}
|
|
42
42
|
},
|
|
43
43
|
"bin": {
|
|
44
|
-
"netriskscan": "
|
|
44
|
+
"netriskscan": "dist/cli.js"
|
|
45
45
|
},
|
|
46
46
|
"files": [
|
|
47
47
|
"dist",
|
|
@@ -81,5 +81,8 @@
|
|
|
81
81
|
"typescript": "^5.5.4",
|
|
82
82
|
"typescript-eslint": "^8.3.0",
|
|
83
83
|
"vitest": "^2.0.5"
|
|
84
|
+
},
|
|
85
|
+
"optionalDependencies": {
|
|
86
|
+
"@napi-rs/keyring": "2.1.2"
|
|
84
87
|
}
|
|
85
88
|
}
|