netriskscan-cli 1.6.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cli.ts","../src/commands/check.ts","../src/client/errors.ts","../src/client/headers.ts","../src/client/retry.ts","../src/client/NetRiskScanClient.ts","../src/utils/env.ts","../src/utils/ip.ts","../src/utils/exitCode.ts","../src/output/human.ts","../src/output/format.ts","../src/output/json.ts","../src/output/errors.ts","../src/commands/usage.ts","../src/commands/batch.ts","../src/utils/pool.ts","../src/output/jsonl.ts","../src/output/table.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { Command, CommanderError } from \"commander\";\nimport { registerCheckCommand } from \"./commands/check.js\";\nimport { registerUsageCommand } from \"./commands/usage.js\";\nimport { registerBatchCommand } from \"./commands/batch.js\";\nimport { ExitCode } from \"./utils/exitCode.js\";\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\nconst pkg = JSON.parse(readFileSync(join(__dirname, \"..\", \"package.json\"), \"utf8\")) as {\n version: string;\n};\n\nconst program = new Command();\n\nprogram\n .name(\"netriskscan\")\n .description(\n \"Query IP risk, network intelligence and reputation data from the NetRiskScan Developer API.\",\n )\n .version(pkg.version, \"-V, --version\", \"Show the CLI version\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ netriskscan check 1.1.1.1 # no account or API key needed\n $ netriskscan check 1.1.1.1 --json\n $ netriskscan usage # needs an API key\n $ netriskscan batch ips.txt --jsonl\n\ncheck and batch work with no setup at all: without an API key they use the\nanonymous daily trial, metered by public IP. The server reports how many\nrequests are left; the CLI never estimates it.\n\nEnvironment variables:\n NETRISKSCAN_API_KEY Optional for check/batch; required for account usage.\n\nNetRiskScan provides diagnostic network intelligence. Results should not be\ntreated as proof of malicious activity or used as the sole basis for legal,\nemployment, credit, identity, or other high-impact decisions.\n\nLearn more: https://github.com/TeamQQ/netriskscan-cli\n`,\n );\n\nregisterCheckCommand(program);\nregisterUsageCommand(program);\nregisterBatchCommand(program);\n\nprogram.exitOverride();\n\ntry {\n await program.parseAsync(process.argv);\n} catch (err) {\n if (err instanceof CommanderError) {\n if (err.code === \"commander.helpDisplayed\" || err.code === \"commander.version\") {\n process.exitCode = ExitCode.Success;\n } else {\n process.exitCode = ExitCode.InvalidArgument;\n }\n } else {\n process.stderr.write(`Unexpected error: ${err instanceof Error ? err.message : String(err)}\\n`);\n process.exitCode = ExitCode.GeneralError;\n }\n}\n","import type { Command } from \"commander\";\nimport ora from \"ora\";\nimport { NetRiskScanClient } from \"../client/NetRiskScanClient.js\";\nimport {\n ANONYMOUS_DAILY_LIMIT_CODE,\n NetRiskScanApiError,\n NetRiskScanNetworkError,\n} from \"../client/errors.js\";\nimport type { IpRiskResponse, RiskFlagName } from \"../client/types.js\";\nimport { resolveOptionalApiKey, resolveBaseUrl } from \"../utils/env.js\";\nimport { isValidIp } from \"../utils/ip.js\";\nimport { ExitCode, exitCodeForApiErrorCode, type ExitCodeValue } from \"../utils/exitCode.js\";\nimport { renderCheckResult, renderVerboseMeta } from \"../output/human.js\";\nimport { printJson } from \"../output/json.js\";\nimport { printAnonymousLimitError, printApiError, printNetworkError } from \"../output/errors.js\";\n\nconst KNOWN_FLAGS: readonly RiskFlagName[] = [\n \"proxy\",\n \"vpn\",\n \"tor\",\n \"datacenter\",\n \"scanner\",\n \"abuse\",\n];\n\ninterface CheckOptions {\n apiKey?: string;\n baseUrl?: string;\n json?: boolean;\n verbose?: boolean;\n debug?: boolean;\n timeout: string;\n maxRetries: string;\n failBelow?: string;\n failOn: string[];\n}\n\nfunction collect(value: string, previous: string[]): string[] {\n return [...previous, value];\n}\n\nexport function registerCheckCommand(program: Command): void {\n program\n .command(\"check <ip>\")\n .description(\"Check IP risk and network intelligence\")\n .option(\n \"--api-key <key>\",\n \"NetRiskScan API key (optional; uses the anonymous trial when omitted)\",\n )\n .option(\"--base-url <url>\", \"Override the API base URL (advanced)\")\n .option(\"--json\", \"Output machine-readable JSON\")\n .option(\"--verbose\", \"Show rate limit, quota and request id\")\n .option(\"--debug\", \"Show debug information on failure\")\n .option(\"--timeout <ms>\", \"Request timeout in milliseconds\", \"10000\")\n .option(\"--max-retries <n>\", \"Maximum automatic retries for 429/503\", \"3\")\n .option(\"--fail-below <index>\", \"Exit non-zero if risk.index is below this threshold (CI use)\")\n .option(\n \"--fail-on <flag>\",\n \"Exit non-zero if the given flag is true (repeatable): proxy, vpn, tor, datacenter, scanner, abuse\",\n collect,\n [] as string[],\n )\n .addHelpText(\n \"after\",\n `\nExamples:\n $ netriskscan check 1.1.1.1\n $ netriskscan check 1.1.1.1 --json\n $ netriskscan check 1.2.3.4 --fail-below 60\n $ netriskscan check 1.2.3.4 --fail-on tor --fail-on proxy\n\nNotes:\n An API key is optional. Without one, requests use the anonymous daily trial,\n metered by public IP; the response reports how many are left.\n`,\n )\n .action(async (ip: string, options: CheckOptions) => {\n await runCheck(ip, options);\n });\n}\n\nasync function runCheck(ip: string, options: CheckOptions): Promise<void> {\n const useJson = Boolean(options.json);\n\n for (const flag of options.failOn) {\n if (!KNOWN_FLAGS.includes(flag as RiskFlagName)) {\n process.stderr.write(\n `Error: unknown --fail-on flag \"${flag}\". Expected one of: ${KNOWN_FLAGS.join(\", \")}\\n`,\n );\n process.exitCode = ExitCode.InvalidArgument;\n return;\n }\n }\n\n if (!isValidIp(ip)) {\n process.stderr.write(`Error: \"${ip}\" is not a valid IPv4 or IPv6 address.\\n`);\n process.exitCode = ExitCode.InvalidArgument;\n return;\n }\n\n // Undefined is a supported mode: the client then omits Authorization and the server serves the\n // request from the anonymous daily trial.\n const client = new NetRiskScanClient({\n apiKey: resolveOptionalApiKey(options.apiKey),\n baseUrl: resolveBaseUrl(options.baseUrl),\n timeout: Number(options.timeout),\n maxRetries: Number(options.maxRetries),\n });\n\n const spinner = useJson\n ? undefined\n : ora({\n text: `Checking ${ip}...`,\n stream: process.stderr,\n isEnabled: process.stderr.isTTY,\n }).start();\n\n try {\n const { data, meta } = await client.checkIp(ip);\n spinner?.stop();\n\n if (useJson) {\n printJson(data);\n } else {\n renderCheckResult(ip, data);\n if (options.verbose) {\n renderVerboseMeta(meta);\n }\n }\n\n process.exitCode = evaluateCiPolicy(data, options);\n } catch (err) {\n spinner?.stop();\n handleCheckError(err, options);\n }\n}\n\nfunction evaluateCiPolicy(data: IpRiskResponse, options: CheckOptions): ExitCodeValue {\n if (options.failOn.length > 0) {\n for (const flag of options.failOn) {\n if (data.flags[flag as RiskFlagName] === true) {\n return ExitCode.CiPolicyFailed;\n }\n }\n }\n\n if (options.failBelow !== undefined) {\n if (data.risk.index === null) {\n return ExitCode.AssessmentUnavailable;\n }\n if (data.risk.index < Number(options.failBelow)) {\n return ExitCode.CiPolicyFailed;\n }\n }\n\n return ExitCode.Success;\n}\n\nfunction handleCheckError(err: unknown, options: CheckOptions): void {\n if (err instanceof NetRiskScanApiError) {\n if (err.code === ANONYMOUS_DAILY_LIMIT_CODE) {\n printAnonymousLimitError(err);\n } else {\n printApiError(err, { debug: options.debug });\n }\n process.exitCode = exitCodeForApiErrorCode(err.code);\n return;\n }\n if (err instanceof NetRiskScanNetworkError) {\n printNetworkError(err, { debug: options.debug });\n process.exitCode = ExitCode.ApiError;\n return;\n }\n if (options.debug && err instanceof Error) {\n process.stderr.write(`${err.stack ?? err.message}\\n`);\n } else {\n process.stderr.write(`Error: ${err instanceof Error ? err.message : String(err)}\\n`);\n }\n process.exitCode = ExitCode.GeneralError;\n}\n","export const KNOWN_ERROR_CODES = [\n \"invalid_ip\",\n \"invalid_request\",\n \"unsupported_parameter\",\n \"invalid_api_key\",\n \"api_key_disabled\",\n \"scope_not_allowed\",\n \"not_found\",\n \"feature_not_available\",\n \"rate_limit_exceeded\",\n \"quota_exceeded\",\n \"anonymous_daily_limit_reached\",\n \"temporarily_unavailable\",\n] as const;\n\nexport type KnownErrorCode = (typeof KNOWN_ERROR_CODES)[number];\n\n/**\n * The anonymous trial's daily allowance is spent. Deterministic until the UTC reset, so unlike\n * `rate_limit_exceeded` it is never retried - see `isRetryableFailure`.\n */\nexport const ANONYMOUS_DAILY_LIMIT_CODE = \"anonymous_daily_limit_reached\";\n\n/**\n * Anonymous-trial allowance carried on a `429 anonymous_daily_limit_reached`.\n *\n * Parsed once in the client layer so the output layer never has to touch an HTTP body. Every\n * field is optional: a server that only sends `code` and `message` must still work.\n */\nexport interface AnonymousLimitInfo {\n dailyLimit?: number;\n used?: number;\n remaining?: number;\n resetAt?: string;\n signupUrl?: string;\n}\n\nexport class NetRiskScanError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"NetRiskScanError\";\n }\n}\n\n/** Thrown for client-side configuration problems, e.g. a missing API key. */\nexport class NetRiskScanConfigError extends NetRiskScanError {\n constructor(message: string) {\n super(message);\n this.name = \"NetRiskScanConfigError\";\n }\n}\n\nexport interface NetRiskScanApiErrorOptions {\n status: number;\n code: string;\n requestId?: string;\n retryAfter?: number;\n anonymousUsage?: AnonymousLimitInfo;\n}\n\n/** Thrown when the Developer API responds with a non-2xx status. */\nexport class NetRiskScanApiError extends NetRiskScanError {\n readonly status: number;\n readonly code: string;\n readonly requestId?: string;\n readonly retryAfter?: number;\n /** Present when the server reported anonymous-trial allowance alongside the error. */\n readonly anonymousUsage?: AnonymousLimitInfo;\n\n constructor(message: string, options: NetRiskScanApiErrorOptions) {\n super(message);\n this.name = \"NetRiskScanApiError\";\n this.status = options.status;\n this.code = options.code;\n this.requestId = options.requestId;\n this.retryAfter = options.retryAfter;\n this.anonymousUsage = options.anonymousUsage;\n }\n}\n\nexport interface NetRiskScanNetworkErrorOptions {\n cause?: unknown;\n requestId?: string;\n}\n\n/** Thrown for transport-level failures: timeouts, DNS errors, connection resets, etc. */\nexport class NetRiskScanNetworkError extends NetRiskScanError {\n override readonly cause?: unknown;\n readonly requestId?: string;\n\n constructor(message: string, options: NetRiskScanNetworkErrorOptions = {}) {\n super(message);\n this.name = \"NetRiskScanNetworkError\";\n this.cause = options.cause;\n this.requestId = options.requestId;\n }\n}\n","import { randomBytes } from \"node:crypto\";\nimport type { QuotaInfo, RateLimitInfo } from \"./types.js\";\n\nconst REQUEST_ID_PATTERN = /^req_[A-Za-z0-9_-]{8,56}$/;\n\nexport function isValidRequestId(id: string): boolean {\n return REQUEST_ID_PATTERN.test(id);\n}\n\nexport function generateRequestId(): string {\n return `req_${randomBytes(12).toString(\"hex\")}`;\n}\n\nfunction parseIntHeader(value: string | null): number | undefined {\n if (value === null) return undefined;\n const n = Number(value);\n return Number.isFinite(n) ? n : undefined;\n}\n\nexport function parseRateLimit(headers: Headers): RateLimitInfo {\n return {\n limit: parseIntHeader(headers.get(\"x-ratelimit-limit\")),\n remaining: parseIntHeader(headers.get(\"x-ratelimit-remaining\")),\n reset: parseIntHeader(headers.get(\"x-ratelimit-reset\")),\n };\n}\n\nexport function parseQuota(headers: Headers): QuotaInfo {\n return {\n limit: parseIntHeader(headers.get(\"x-quota-limit\")),\n used: parseIntHeader(headers.get(\"x-quota-used\")),\n remaining: parseIntHeader(headers.get(\"x-quota-remaining\")),\n };\n}\n\n/** Never log or print a full API key. Keeps a short prefix/suffix for support purposes. */\nexport function redactApiKey(key: string): string {\n if (key.length <= 9) return \"*\".repeat(key.length);\n return `${key.slice(0, 9)}${\"*\".repeat(4)}${key.slice(-4)}`;\n}\n\nexport function redactAuthorizationHeader(value: string): string {\n const match = /^Bearer\\s+(.+)$/i.exec(value);\n if (!match) return \"[REDACTED]\";\n return `Bearer ${redactApiKey(match[1])}`;\n}\n","import { ANONYMOUS_DAILY_LIMIT_CODE } from \"./errors.js\";\n\n/** Only 429 and 503 are automatically retried; 400/401/403/404 never are. */\nexport function isRetryableStatus(status: number): boolean {\n return status === 429 || status === 503;\n}\n\n/**\n * Status *and* error code decide retryability, because not every 429 is transient.\n *\n * `rate_limit_exceeded` is a short per-minute window and retrying is the right behaviour.\n * `anonymous_daily_limit_reached` is a spent daily allowance that cannot come back before the\n * UTC reset, so retrying it only burns three more round-trips before failing identically.\n */\nexport function isRetryableFailure(status: number, code?: string): boolean {\n if (code === ANONYMOUS_DAILY_LIMIT_CODE) return false;\n return isRetryableStatus(status);\n}\n\nconst BASE_DELAY_MS = 1000;\nconst MAX_JITTER_MS = 250;\n\n/** Honors Retry-After when present; otherwise exponential backoff (1s, 2s, 4s, ...) with jitter. */\nexport function computeBackoffMs(attempt: number, retryAfterSeconds?: number): number {\n if (\n typeof retryAfterSeconds === \"number\" &&\n Number.isFinite(retryAfterSeconds) &&\n retryAfterSeconds >= 0\n ) {\n return retryAfterSeconds * 1000;\n }\n const base = BASE_DELAY_MS * 2 ** Math.max(0, attempt - 1);\n const jitter = Math.random() * MAX_JITTER_MS;\n return base + jitter;\n}\n\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n","import { NetRiskScanApiError, NetRiskScanConfigError, NetRiskScanNetworkError } from \"./errors.js\";\nimport { generateRequestId, isValidRequestId, parseQuota, parseRateLimit } from \"./headers.js\";\nimport { computeBackoffMs, isRetryableFailure, sleep } from \"./retry.js\";\nimport type { AnonymousLimitInfo } from \"./errors.js\";\nimport type {\n ApiErrorBody,\n ApiResult,\n IpRiskResponse,\n NetRiskScanClientOptions,\n RequestOptions,\n UsageResponse,\n} from \"./types.js\";\n\nconst DEFAULT_BASE_URL = \"https://api.netriskscan.com\";\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_MAX_RETRIES = 3;\n\nfunction isAbortError(err: unknown): boolean {\n return err instanceof Error && err.name === \"AbortError\";\n}\n\nasync function safeJson(res: Response): Promise<ApiErrorBody | undefined> {\n try {\n return (await res.json()) as ApiErrorBody;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Lifts the anonymous-trial fields off an error body, once, here. HTTP bodies are parsed in the\n * client layer only - the output layer receives a typed error, never JSON.\n */\nfunction parseAnonymousLimitInfo(body: ApiErrorBody | undefined): AnonymousLimitInfo | undefined {\n const error = body?.error;\n if (!error) return undefined;\n const { dailyLimit, used, remaining, resetAt, signupUrl } = error;\n if (\n dailyLimit === undefined &&\n used === undefined &&\n remaining === undefined &&\n resetAt === undefined &&\n signupUrl === undefined\n ) {\n return undefined;\n }\n return { dailyLimit, used, remaining, resetAt, signupUrl };\n}\n\n/**\n * Client for the NetRiskScan Developer API (`/v1/*` only).\n *\n * Works with no configuration at all: without an API key it sends no `Authorization` header and\n * the server serves the request from the anonymous daily trial, metered by public IP.\n *\n * @example Anonymous - no account, no key\n * ```ts\n * const client = new NetRiskScanClient();\n * const { data } = await client.checkIp(\"1.1.1.1\");\n * console.log(data.risk.index);\n * console.log(data.usage?.remaining);\n * ```\n *\n * @example Pass `apiKey` to use Developer Account quota instead of the anonymous trial\n * ```ts\n * const client = new NetRiskScanClient({ apiKey: process.env.NETRISKSCAN_API_KEY });\n * ```\n */\nexport class NetRiskScanClient {\n private readonly apiKey?: string;\n private readonly baseUrl: string;\n private readonly timeout: number;\n private readonly maxRetries: number;\n\n constructor(options: NetRiskScanClientOptions = {}) {\n // An absent key is a supported mode, not a misconfiguration: it selects the anonymous trial.\n this.apiKey = options.apiKey || undefined;\n this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n this.timeout = options.timeout ?? DEFAULT_TIMEOUT_MS;\n this.maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;\n }\n\n async checkIp(ip: string, options: RequestOptions = {}): Promise<ApiResult<IpRiskResponse>> {\n return this.request<IpRiskResponse>(`/v1/ip-risk/${encodeURIComponent(ip)}`, options);\n }\n\n /**\n * Account plan, billing period and quota. Unlike {@link checkIp} this is account data, so it\n * has no anonymous equivalent and requires an API key.\n */\n async getUsage(options: RequestOptions = {}): Promise<ApiResult<UsageResponse>> {\n if (!this.apiKey) {\n throw new NetRiskScanConfigError(\"An API key is required to query account usage.\");\n }\n return this.request<UsageResponse>(\"/v1/usage\", options);\n }\n\n private async request<T>(path: string, options: RequestOptions): Promise<ApiResult<T>> {\n const requestId =\n options.requestId && isValidRequestId(options.requestId)\n ? options.requestId\n : generateRequestId();\n\n let attempt = 0;\n\n while (true) {\n const timeoutController = new AbortController();\n const timer = setTimeout(() => timeoutController.abort(), this.timeout);\n const onExternalAbort = (): void => timeoutController.abort();\n options.signal?.addEventListener(\"abort\", onExternalAbort);\n\n try {\n const headers: Record<string, string> = {\n Accept: \"application/json\",\n \"X-Request-Id\": requestId,\n };\n // Only ever sent when a key actually exists. A `Bearer undefined` would read as a bad key\n // and earn a 401 instead of falling through to the anonymous trial.\n if (this.apiKey) {\n headers.Authorization = `Bearer ${this.apiKey}`;\n }\n\n const res = await fetch(`${this.baseUrl}${path}`, {\n method: \"GET\",\n headers,\n signal: timeoutController.signal,\n });\n\n const rateLimit = parseRateLimit(res.headers);\n const quota = parseQuota(res.headers);\n const responseRequestId = res.headers.get(\"x-request-id\") ?? requestId;\n\n if (res.ok) {\n const data = (await res.json()) as T;\n return { data, meta: { requestId: responseRequestId, rateLimit, quota } };\n }\n\n const body = await safeJson(res);\n const retryAfterHeader = res.headers.get(\"retry-after\");\n const retryAfter = retryAfterHeader !== null ? Number(retryAfterHeader) : undefined;\n\n if (isRetryableFailure(res.status, body?.error?.code) && attempt < this.maxRetries) {\n attempt += 1;\n await sleep(computeBackoffMs(attempt, retryAfter));\n continue;\n }\n\n throw new NetRiskScanApiError(body?.error?.message ?? res.statusText, {\n status: res.status,\n code: body?.error?.code ?? \"unknown_error\",\n requestId: body?.error?.requestId ?? responseRequestId,\n retryAfter,\n anonymousUsage: parseAnonymousLimitInfo(body),\n });\n } catch (err) {\n if (err instanceof NetRiskScanApiError) {\n throw err;\n }\n if (isAbortError(err)) {\n if (options.signal?.aborted) {\n throw err;\n }\n throw new NetRiskScanNetworkError(`Request timed out after ${this.timeout}ms`, {\n cause: err,\n requestId,\n });\n }\n throw new NetRiskScanNetworkError(\n err instanceof Error ? err.message : \"Network request failed\",\n {\n cause: err,\n requestId,\n },\n );\n } finally {\n clearTimeout(timer);\n options.signal?.removeEventListener(\"abort\", onExternalAbort);\n }\n }\n }\n}\n","import { NetRiskScanConfigError } from \"../client/errors.js\";\n\n/**\n * Resolves the API key for endpoints that work without one (`check`, `batch`).\n *\n * Returning `undefined` is a valid outcome, not a failure: it selects the anonymous trial. The\n * precedence is `--api-key` > `NETRISKSCAN_API_KEY` > anonymous. A key that is present but wrong\n * is still passed through - the CLI never silently drops a key the user configured and retries\n * anonymously, because that would turn an authentication problem into a confusing success.\n */\nexport function resolveOptionalApiKey(cliValue?: string): string | undefined {\n return cliValue || process.env.NETRISKSCAN_API_KEY || undefined;\n}\n\n/**\n * Resolves the API key for account-level endpoints (`usage`), which have no anonymous form.\n *\n * The message names the command on purpose: a generic \"API key is required\" here would suggest\n * the whole CLI needs an account, which is no longer true.\n */\nexport function resolveRequiredApiKey(cliValue?: string): string {\n const apiKey = resolveOptionalApiKey(cliValue);\n if (!apiKey) {\n throw new NetRiskScanConfigError(\n \"An API key is required for the usage command.\\n\\nSet NETRISKSCAN_API_KEY or use --api-key.\",\n );\n }\n return apiKey;\n}\n\nexport function resolveBaseUrl(cliValue?: string): string | undefined {\n return cliValue ?? process.env.NETRISKSCAN_BASE_URL;\n}\n","import { isIP } from \"node:net\";\n\nexport function isValidIp(value: string): boolean {\n return isIP(value) !== 0;\n}\n","import type { KnownErrorCode } from \"../client/errors.js\";\n\nexport const ExitCode = {\n Success: 0,\n GeneralError: 1,\n InvalidArgument: 2,\n AuthError: 3,\n ApiError: 4,\n RateLimitOrQuota: 5,\n CiPolicyFailed: 6,\n AssessmentUnavailable: 7,\n} as const;\n\nexport type ExitCodeValue = (typeof ExitCode)[keyof typeof ExitCode];\n\nexport function exitCodeForApiErrorCode(code: string): ExitCodeValue {\n switch (code as KnownErrorCode) {\n case \"invalid_api_key\":\n case \"api_key_disabled\":\n case \"scope_not_allowed\":\n return ExitCode.AuthError;\n // The anonymous daily trial is an allowance like any other, so it reuses code 5 rather than\n // adding an eighth exit code that every script would have to learn.\n case \"rate_limit_exceeded\":\n case \"quota_exceeded\":\n case \"anonymous_daily_limit_reached\":\n return ExitCode.RateLimitOrQuota;\n default:\n return ExitCode.ApiError;\n }\n}\n","import chalk from \"chalk\";\nimport type {\n IpLocation,\n IpRiskResponse,\n RequestUsage,\n ResponseMeta,\n RiskBand,\n RiskReason,\n UsageResponse,\n} from \"../client/types.js\";\nimport {\n formatDate,\n formatGeoName,\n formatIndex,\n formatNullable,\n formatNumber,\n formatOrDash,\n formatProxyType,\n formatRiskReasonCode,\n formatTriState,\n formatUtcTimestamp,\n reasonRow,\n row,\n} from \"./format.js\";\n\n/**\n * Anonymous-trial rows for the human `check` output.\n *\n * `Available` is printed verbatim from `usage.remaining` - the server is the only authority on\n * what is left, so this never falls back to `dailyLimit - used`. Each row is emitted only when\n * its value is actually a number, because `0` is a legitimate value that a truthiness check\n * would swallow on exactly the run where it matters most.\n */\nfunction anonymousUsageLines(usage: RequestUsage): string[] {\n const lines: string[] = [];\n if (typeof usage.remaining === \"number\") {\n lines.push(row(\"Available\", formatNumber(usage.remaining)));\n }\n if (typeof usage.dailyLimit === \"number\") {\n lines.push(row(\"Daily Limit\", formatNumber(usage.dailyLimit)));\n }\n const reset = formatUtcTimestamp(usage.resetAt);\n if (reset !== undefined) {\n lines.push(row(\"Reset\", reset));\n }\n return lines;\n}\n\n/**\n * Rows for the server's own explanations of the assessment.\n *\n * Rendering only: the list is whatever `risk.reasons` contained, in the server's order, with no\n * entry derived from `flags`/`network`, none filtered out, and none re-ranked. An empty or absent\n * list yields no rows at all, so the caller drops the section rather than printing a heading over\n * nothing - the common case for an ordinary address.\n */\nfunction riskReasonLines(reasons: readonly RiskReason[] | undefined): string[] {\n if (reasons === undefined || reasons.length === 0) return [];\n return reasons.map((reason) => {\n const severity = reason.severity ?? \"\";\n return reasonRow(formatRiskReasonCode(reason.code), severityColor(severity)(severity));\n });\n}\n\n/**\n * Severity is a secondary cue, never the message itself: the label already says what was found, so\n * an unrecognised severity simply renders uncoloured instead of being mapped to a guessed level.\n *\n * `info` is deliberately dim rather than warning-coloured - `Verified Search Crawler` and\n * `Public Infrastructure` explain why an address is *clean*, and colouring them like a threat\n * would misrepresent the server's own assessment.\n */\nfunction severityColor(severity: string): (text: string) => string {\n switch (severity) {\n case \"critical\":\n case \"high\":\n return chalk.red;\n case \"medium\":\n return chalk.yellow;\n case \"info\":\n return chalk.gray;\n default:\n return (text: string) => text;\n }\n}\n\n/**\n * Rows for network-level geolocation - where the network is routed, not where a device is.\n *\n * Each row appears only when the server actually sent that field: geo resolution is independently\n * partial (a country with no city is normal), and a wall of \"N/A\" rows would be noise dressed up as\n * data. An absent `location` object yields no rows, so the caller drops the whole section.\n */\nfunction locationLines(location: IpLocation | null | undefined): string[] {\n if (!location) return [];\n const lines: string[] = [];\n const country = formatGeoName(location.country, location.countryCode);\n if (country !== undefined) lines.push(row(\"Country\", country));\n const region = formatGeoName(location.region, location.regionCode);\n if (region !== undefined) lines.push(row(\"Region\", region));\n if (location.city) lines.push(row(\"City\", location.city));\n const continent = formatGeoName(location.continent, location.continentCode);\n if (continent !== undefined) lines.push(row(\"Continent\", continent));\n if (location.postalCode) lines.push(row(\"Postal Code\", location.postalCode));\n // A coordinate pair is shown only when the server sent both halves as real numbers. `0` is a\n // legitimate coordinate, so this is a type check, never a truthiness check; an anycast network\n // sends null for both and gets no row rather than a fabricated position.\n const { latitude, longitude } = location;\n if (\n typeof latitude === \"number\" &&\n Number.isFinite(latitude) &&\n typeof longitude === \"number\" &&\n Number.isFinite(longitude)\n ) {\n lines.push(row(\"Coordinates\", `${latitude}, ${longitude}`));\n }\n if (location.timeZone) lines.push(row(\"Time Zone\", location.timeZone));\n return lines;\n}\n\nfunction bandColor(band: RiskBand | null): (text: string) => string {\n switch (band) {\n case \"excellent\":\n case \"good\":\n return chalk.green;\n case \"fair\":\n return chalk.yellow;\n case \"poor\":\n case \"high_risk\":\n return chalk.red;\n default:\n return chalk.gray;\n }\n}\n\nexport function renderCheckResult(ip: string, data: IpRiskResponse): void {\n const lines: string[] = [];\n lines.push(chalk.bold(\"NetRiskScan\"));\n lines.push(\"\");\n lines.push(row(\"IP\", ip));\n lines.push(row(\"Index\", formatIndex(data.risk.index)));\n lines.push(\n row(\"Band\", data.risk.band ? bandColor(data.risk.band)(data.risk.band) : chalk.gray(\"N/A\")),\n );\n lines.push(row(\"Assessment\", data.risk.assessmentGrade));\n lines.push(\"\");\n\n if (data.risk.assessmentGrade === \"insufficient\" && data.risk.index === null) {\n lines.push(chalk.yellow(\"This address could not be reliably assessed.\"));\n lines.push(\"\");\n }\n\n // Directly under the verdict it explains, and only when the server sent one: these are the\n // server's reasons, so an empty or absent list means there is nothing to show - never a cue for\n // the CLI to work some out from flags.\n const reasonLines = riskReasonLines(data.risk.reasons);\n if (reasonLines.length > 0) {\n lines.push(chalk.bold(\"Risk Reasons\"));\n lines.push(...reasonLines);\n lines.push(\"\");\n }\n\n lines.push(chalk.bold(\"Network\"));\n lines.push(row(\"Type\", formatNullable(data.network.type)));\n // Omitted entirely when absent, unlike the fields around them, which render \"N/A\". Those describe every\n // address, so a missing one is worth showing as missing; these two exist only for the minority of\n // addresses NetRiskScan holds a first-party record for, and printing \"Profile N/A\" on every residential\n // lookup would be noise rather than information.\n if (data.network.profile) {\n lines.push(row(\"Profile\", data.network.profile));\n }\n if (data.network.service) {\n lines.push(row(\"Service\", data.network.service));\n }\n lines.push(row(\"Connection\", formatNullable(data.network.connectionType)));\n lines.push(row(\"ASN\", formatNullable(data.network.asn)));\n lines.push(row(\"Organization\", formatNullable(data.network.organization)));\n // Schema 1.6.0 additions, dropped when absent for the same reason as Profile/Service above.\n // Both are server-owned facts: never inferred from the ASN, organization or hostname, and the\n // range is never computed client-side.\n if (data.network.domain) {\n lines.push(row(\"Domain\", data.network.domain));\n }\n if (data.network.range) {\n lines.push(row(\"Network Range\", data.network.range));\n }\n lines.push(\"\");\n\n const geoLines = locationLines(data.location);\n if (geoLines.length > 0) {\n lines.push(chalk.bold(\"Location\"));\n lines.push(...geoLines);\n lines.push(\"\");\n }\n\n lines.push(chalk.bold(\"Signals\"));\n lines.push(row(\"Proxy\", formatTriState(data.flags.proxy)));\n lines.push(row(\"Proxy Type\", formatProxyType(data.flags.proxyType)));\n lines.push(row(\"VPN\", formatTriState(data.flags.vpn)));\n lines.push(row(\"Tor\", formatTriState(data.flags.tor)));\n lines.push(row(\"Datacenter\", formatTriState(data.flags.datacenter)));\n lines.push(row(\"Scanner\", formatTriState(data.flags.scanner)));\n lines.push(row(\"Abuse\", formatTriState(data.flags.abuse)));\n lines.push(\"\");\n\n // Identity, not a risk signal: a verified crawler must never read as a threat, so it gets its own\n // section rather than living inside Signals.\n lines.push(chalk.bold(\"Identity\"));\n lines.push(row(\"Search Crawler\", formatTriState(data.flags.searchCrawler)));\n lines.push(row(\"Crawler\", formatOrDash(data.flags.searchCrawlerName)));\n lines.push(\"\");\n\n // Only for the anonymous trial. An API-key caller's allowance is a billing-period quota, a\n // different thing entirely, and stays behind --verbose where it always was.\n if (data.usage?.mode === \"anonymous\") {\n const usageLines = anonymousUsageLines(data.usage);\n if (usageLines.length > 0) {\n lines.push(chalk.bold(\"Usage\"));\n lines.push(...usageLines);\n lines.push(\"\");\n }\n }\n\n lines.push(row(\"Request ID\", data.requestId));\n lines.push(\"\");\n\n lines.push(chalk.bold(\"Explore\"));\n lines.push(row(\"Web\", \"https://www.netriskscan.com\"));\n lines.push(row(\"GitHub\", \"https://github.com/TeamQQ/netriskscan-cli\"));\n\n process.stdout.write(`${lines.join(\"\\n\")}\\n`);\n}\n\nexport function renderVerboseMeta(meta: ResponseMeta): void {\n const lines: string[] = [\"\"];\n if (meta.rateLimit.remaining !== undefined && meta.rateLimit.limit !== undefined) {\n lines.push(\n row(\n \"Rate limit\",\n `${formatNumber(meta.rateLimit.remaining)} / ${formatNumber(meta.rateLimit.limit)} remaining`,\n ),\n );\n }\n if (meta.quota.remaining !== undefined && meta.quota.limit !== undefined) {\n lines.push(\n row(\n \"Quota\",\n `${formatNumber(meta.quota.remaining)} / ${formatNumber(meta.quota.limit)} remaining`,\n ),\n );\n }\n lines.push(row(\"Request ID\", meta.requestId));\n process.stdout.write(`${lines.join(\"\\n\")}\\n`);\n}\n\nexport function renderUsageResult(data: UsageResponse): void {\n const lines: string[] = [];\n lines.push(chalk.bold(\"NetRiskScan Usage\"));\n lines.push(\"\");\n lines.push(row(\"Plan\", data.plan));\n lines.push(\"\");\n lines.push(chalk.bold(\"Usage\"));\n lines.push(row(\"Used\", formatNumber(data.units.used)));\n lines.push(row(\"Remaining\", formatNumber(data.units.remaining)));\n lines.push(row(\"Limit\", formatNumber(data.units.limit)));\n lines.push(\"\");\n lines.push(chalk.bold(\"Rate limit\"));\n lines.push(row(\"Requests / minute\", formatNumber(data.rateLimit.requestsPerMinute)));\n lines.push(\"\");\n lines.push(chalk.bold(\"Billing period\"));\n lines.push(`${formatDate(data.period.start)} → ${formatDate(data.period.end)}`);\n\n process.stdout.write(`${lines.join(\"\\n\")}\\n`);\n}\n","/**\n * Formats a tri-state flag. `null`/`undefined` means \"not enough signal to judge\" and\n * must never collapse into \"No\" - that would silently turn \"unknown\" into \"false\".\n */\nexport function formatTriState(value: boolean | null | undefined): string {\n if (value === true) return \"Yes\";\n if (value === false) return \"No\";\n return \"Unknown\";\n}\n\nconst PROXY_TYPE_LABELS: Record<string, string> = {\n residential_proxy: \"Residential Proxy\",\n isp_proxy: \"ISP Proxy\",\n mobile_proxy: \"Mobile Proxy\",\n datacenter_proxy: \"Datacenter Proxy\",\n unknown_proxy: \"Unknown Proxy\",\n};\n\nconst PROXY_TYPE_LABELS_COMPACT: Record<string, string> = {\n residential_proxy: \"Residential\",\n isp_proxy: \"ISP\",\n mobile_proxy: \"Mobile\",\n datacenter_proxy: \"Datacenter\",\n unknown_proxy: \"Unknown\",\n};\n\n/**\n * Human-readable label for `flags.proxyType`. This is a classification detail, not a tri-state\n * signal - it only refines an address already flagged `proxy: true` - so missing/`null`/empty\n * renders as `-`, matching the placeholder every other Signals row uses for \"not applicable\", never\n * \"Unknown\".\n *\n * An unrecognised raw value renders as itself rather than throwing: `ProxyType` is a documented\n * union, but this reads live server JSON that a compile-time cast cannot actually enforce, and a\n * server that adds a new proxy subtype must not crash CLIs already in the wild.\n */\nexport function formatProxyType(value: string | null | undefined): string {\n if (value === null || value === undefined || value === \"\") return \"-\";\n return PROXY_TYPE_LABELS[value] ?? value;\n}\n\n/** Same mapping as {@link formatProxyType}, abbreviated for the batch table's narrower columns. */\nexport function formatProxyTypeCompact(value: string | null | undefined): string {\n if (value === null || value === undefined || value === \"\") return \"-\";\n return PROXY_TYPE_LABELS_COMPACT[value] ?? value;\n}\n\n/**\n * Passes a server-owned display name through unchanged (e.g. `flags.searchCrawlerName`) - never\n * reformatted, title-cased, or mapped through an enum, because the server already sends the\n * canonical form. Missing/`null`/empty renders as `-`.\n */\nexport function formatOrDash(value: string | null | undefined): string {\n return value === null || value === undefined || value === \"\" ? \"-\" : value;\n}\n\n/**\n * Joins a geo display name with its code: `United States` + `US` -> `United States (US)`.\n *\n * The server owns both halves, so neither is title-cased, translated, or derived from the other -\n * a bare code renders as the code, a bare name as the name. Returns `undefined` when the server\n * sent neither, so the caller drops the row instead of printing a placeholder for a field the\n * server never claimed to know.\n */\nexport function formatGeoName(\n name: string | null | undefined,\n code: string | null | undefined,\n): string | undefined {\n const hasName = name !== null && name !== undefined && name !== \"\";\n const hasCode = code !== null && code !== undefined && code !== \"\";\n if (hasName && hasCode) return `${name} (${code})`;\n if (hasName) return name;\n if (hasCode) return code;\n return undefined;\n}\n\n/**\n * Display labels for the reason codes the server emits today. Deliberately a lookup table and not\n * an exhaustive union: {@link formatRiskReasonCode} falls back for anything absent here, which is\n * what keeps an already-installed CLI working when the server adds a code.\n */\nconst RISK_REASON_LABELS: Record<string, string> = {\n RESIDENTIAL_PROXY_DETECTED: \"Residential Proxy Detected\",\n ISP_PROXY_DETECTED: \"ISP Proxy Detected\",\n MOBILE_PROXY_DETECTED: \"Mobile Proxy Detected\",\n DATACENTER_PROXY_DETECTED: \"Datacenter Proxy Detected\",\n PROXY_DETECTED: \"Proxy Detected\",\n VPN_DETECTED: \"VPN Detected\",\n TOR_RELAY: \"Tor Relay\",\n TOR_EXIT_NODE: \"Tor Exit Node\",\n KNOWN_SCANNER: \"Known Scanner\",\n ABUSE_ACTIVITY: \"Abuse Activity\",\n BLACKLIST_MATCH: \"Blacklist Match\",\n BOTNET_C2: \"Botnet C2\",\n COMPROMISED_HOST: \"Compromised Host\",\n VERIFIED_SEARCH_CRAWLER: \"Verified Search Crawler\",\n PUBLIC_INFRASTRUCTURE: \"Public Infrastructure\",\n RESIDENTIAL_NETWORK: \"Residential Network\",\n CONFLICTING_EVIDENCE: \"Conflicting Evidence\",\n INSUFFICIENT_EVIDENCE: \"Insufficient Evidence\",\n};\n\n/**\n * Human label for a `risk.reasons[].code`, for the default terminal output only - `--json` and\n * `--jsonl` always carry the raw `RESIDENTIAL_PROXY_DETECTED` form.\n *\n * An unrecognised code is title-cased rather than dropped, hidden behind \"Unknown\", or thrown on:\n * the reason vocabulary is additive server-side, so a CLI in the wild will meet codes that did not\n * exist when it shipped, and showing `NEW_FUTURE_SIGNAL` as `New Future Signal` still tells the\n * reader what the server said.\n */\nexport function formatRiskReasonCode(code: string | null | undefined): string {\n if (code === null || code === undefined || code === \"\") return \"-\";\n const known = RISK_REASON_LABELS[code];\n if (known !== undefined) return known;\n const words = code.split(/[_\\s]+/).filter((word) => word !== \"\");\n if (words.length === 0) return code;\n return words.map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join(\" \");\n}\n\n/** `index` can legitimately be 0, so this must not use a falsy check. */\nexport function formatIndex(value: number | null): string {\n return value === null ? \"N/A\" : String(value);\n}\n\nexport function formatNullable(value: string | null | undefined): string {\n return value === null || value === undefined || value === \"\" ? \"N/A\" : value;\n}\n\nexport function formatNumber(value: number): string {\n return value.toLocaleString(\"en-US\");\n}\n\nexport function formatDate(iso: string): string {\n return iso.slice(0, 10);\n}\n\n/** Shared label column so `check`, `batch` and the error renderers line up identically. */\nexport const LABEL_WIDTH = 18;\n\nexport function row(label: string, value: string): string {\n return `${label.padEnd(LABEL_WIDTH)}${value}`;\n}\n\n/**\n * Reason labels are sentences (\"Residential Proxy Detected\"), not the short keys the rest of the\n * output uses, so they get their own wider column rather than pushing {@link LABEL_WIDTH} out and\n * re-indenting every other section.\n */\nexport const REASON_LABEL_WIDTH = 30;\n\nexport function reasonRow(label: string, value: string): string {\n return value === \"\" ? label : `${label.padEnd(REASON_LABEL_WIDTH)}${value}`;\n}\n\n/**\n * Renders an ISO-8601 instant as `2026-08-29 00:00 UTC`, deliberately *not* in local time: the\n * anonymous allowance resets on the UTC day, and a localized timestamp would misdescribe when\n * that happens for most of the world.\n *\n * Returns `undefined` for a missing or unparseable value so callers can drop the row rather than\n * print \"Invalid Date\".\n */\nexport function formatUtcTimestamp(iso: string | null | undefined): string | undefined {\n if (!iso) return undefined;\n const date = new Date(iso);\n if (Number.isNaN(date.getTime())) return undefined;\n const pad = (n: number): string => String(n).padStart(2, \"0\");\n return (\n `${date.getUTCFullYear()}-${pad(date.getUTCMonth() + 1)}-${pad(date.getUTCDate())} ` +\n `${pad(date.getUTCHours())}:${pad(date.getUTCMinutes())} UTC`\n );\n}\n","/** Pretty JSON to stdout. Preserves `null` exactly as returned by the API - never coerced. */\nexport function printJson(data: unknown): void {\n process.stdout.write(`${JSON.stringify(data, null, 2)}\\n`);\n}\n","import chalk from \"chalk\";\nimport type {\n NetRiskScanApiError,\n NetRiskScanConfigError,\n NetRiskScanNetworkError,\n} from \"../client/errors.js\";\nimport { formatNumber, formatUtcTimestamp, row } from \"./format.js\";\n\n/** Used only when the server did not send its own `signupUrl`. */\nconst SIGNUP_URL = \"https://www.netriskscan.com/developer/register\";\n\nexport function printConfigError(err: NetRiskScanConfigError): void {\n process.stderr.write(`Error: ${err.message}\\n`);\n if (err.message.includes(\"API key\")) {\n process.stderr.write(\n \"\\nGet a free API key (no credit card required): https://www.netriskscan.com\\n\",\n );\n }\n}\n\n/**\n * The anonymous trial running out is an ordinary end-of-trial moment, not a protocol fault, so it\n * gets its own renderer instead of the `Code / Status / Message` dump. It tells the reader what\n * they have, when it comes back, and where to get more.\n */\nexport function printAnonymousLimitError(err: NetRiskScanApiError): void {\n const usage = err.anonymousUsage;\n const lines = [\n \"\",\n chalk.bold(\"NetRiskScan\"),\n \"\",\n chalk.yellow(\"Anonymous daily trial limit reached.\"),\n \"\",\n ];\n\n const usageLines: string[] = [\n // The request that returned this error was refused, so nothing is left regardless of what the\n // body reports; `remaining` is only trusted when the server actually sent it.\n row(\"Available\", formatNumber(typeof usage?.remaining === \"number\" ? usage.remaining : 0)),\n ];\n if (typeof usage?.dailyLimit === \"number\") {\n usageLines.push(row(\"Daily Limit\", formatNumber(usage.dailyLimit)));\n }\n const reset = formatUtcTimestamp(usage?.resetAt);\n if (reset !== undefined) {\n usageLines.push(row(\"Reset\", reset));\n }\n\n lines.push(chalk.bold(\"Usage\"), ...usageLines, \"\");\n lines.push(chalk.bold(\"Get more queries\"), usage?.signupUrl || SIGNUP_URL, \"\");\n\n process.stderr.write(`${lines.join(\"\\n\")}\\n`);\n}\n\nconst LABEL_WIDTH = 11;\n\nexport function printApiError(err: NetRiskScanApiError, options: { debug?: boolean } = {}): void {\n const lines = [\n \"\",\n chalk.red(\"NetRiskScan API error\"),\n \"\",\n `${\"Code\".padEnd(LABEL_WIDTH)}${err.code}`,\n `${\"Status\".padEnd(LABEL_WIDTH)}${err.status}`,\n `${\"Message\".padEnd(LABEL_WIDTH)}${err.message}`,\n ];\n if (err.requestId) {\n lines.push(`${\"Request ID\".padEnd(LABEL_WIDTH)}${err.requestId}`);\n }\n if (err.retryAfter !== undefined) {\n lines.push(`${\"Retry after\".padEnd(LABEL_WIDTH)}${err.retryAfter}s`);\n }\n lines.push(\"\");\n process.stderr.write(`${lines.join(\"\\n\")}\\n`);\n\n if (options.debug && err.stack) {\n process.stderr.write(`${err.stack}\\n`);\n }\n}\n\nexport function printNetworkError(\n err: NetRiskScanNetworkError,\n options: { debug?: boolean } = {},\n): void {\n process.stderr.write(`\\n${chalk.red(\"NetRiskScan request failed\")}\\n\\n${err.message}\\n\\n`);\n if (options.debug && err.stack) {\n process.stderr.write(`${err.stack}\\n`);\n }\n}\n","import type { Command } from \"commander\";\nimport ora from \"ora\";\nimport { NetRiskScanClient } from \"../client/NetRiskScanClient.js\";\nimport {\n NetRiskScanApiError,\n NetRiskScanConfigError,\n NetRiskScanNetworkError,\n} from \"../client/errors.js\";\nimport { resolveRequiredApiKey, resolveBaseUrl } from \"../utils/env.js\";\nimport { ExitCode, exitCodeForApiErrorCode } from \"../utils/exitCode.js\";\nimport { renderUsageResult, renderVerboseMeta } from \"../output/human.js\";\nimport { printJson } from \"../output/json.js\";\nimport { printApiError, printConfigError, printNetworkError } from \"../output/errors.js\";\n\ninterface UsageOptions {\n apiKey?: string;\n baseUrl?: string;\n json?: boolean;\n verbose?: boolean;\n debug?: boolean;\n timeout: string;\n maxRetries: string;\n}\n\nexport function registerUsageCommand(program: Command): void {\n program\n .command(\"usage\")\n .description(\"Show API usage and quota for the current billing period (requires an API key)\")\n .option(\"--api-key <key>\", \"NetRiskScan API key (required for this command)\")\n .option(\"--base-url <url>\", \"Override the API base URL (advanced)\")\n .option(\"--json\", \"Output machine-readable JSON\")\n .option(\"--verbose\", \"Show rate limit and request id\")\n .option(\"--debug\", \"Show debug information on failure\")\n .option(\"--timeout <ms>\", \"Request timeout in milliseconds\", \"10000\")\n .option(\"--max-retries <n>\", \"Maximum automatic retries for 429/503\", \"3\")\n .addHelpText(\n \"after\",\n `\nNotes:\n Requires a Developer API key. This reports Developer Account plan, billing\n period and quota, which has no anonymous equivalent - unlike check and batch,\n which work without a key.\n`,\n )\n .action(async (options: UsageOptions) => {\n await runUsage(options);\n });\n}\n\nasync function runUsage(options: UsageOptions): Promise<void> {\n const useJson = Boolean(options.json);\n\n let apiKey: string;\n try {\n apiKey = resolveRequiredApiKey(options.apiKey);\n } catch (err) {\n if (err instanceof NetRiskScanConfigError) {\n printConfigError(err);\n process.exitCode = ExitCode.AuthError;\n return;\n }\n throw err;\n }\n\n const client = new NetRiskScanClient({\n apiKey,\n baseUrl: resolveBaseUrl(options.baseUrl),\n timeout: Number(options.timeout),\n maxRetries: Number(options.maxRetries),\n });\n\n const spinner = useJson\n ? undefined\n : ora({\n text: \"Fetching usage...\",\n stream: process.stderr,\n isEnabled: process.stderr.isTTY,\n }).start();\n\n try {\n const { data, meta } = await client.getUsage();\n spinner?.stop();\n\n if (useJson) {\n printJson(data);\n } else {\n renderUsageResult(data);\n if (options.verbose) {\n renderVerboseMeta(meta);\n }\n }\n } catch (err) {\n spinner?.stop();\n if (err instanceof NetRiskScanApiError) {\n printApiError(err, { debug: options.debug });\n process.exitCode = exitCodeForApiErrorCode(err.code);\n return;\n }\n if (err instanceof NetRiskScanNetworkError) {\n printNetworkError(err, { debug: options.debug });\n process.exitCode = ExitCode.ApiError;\n return;\n }\n throw err;\n }\n}\n","import type { Command } from \"commander\";\nimport { createReadStream } from \"node:fs\";\nimport { createInterface } from \"node:readline\";\nimport { NetRiskScanClient } from \"../client/NetRiskScanClient.js\";\nimport { NetRiskScanApiError, NetRiskScanNetworkError } from \"../client/errors.js\";\nimport type { AnonymousLimitInfo } from \"../client/errors.js\";\nimport type { IpRiskResponse } from \"../client/types.js\";\nimport { resolveOptionalApiKey, resolveBaseUrl } from \"../utils/env.js\";\nimport { isValidIp } from \"../utils/ip.js\";\nimport { runPool } from \"../utils/pool.js\";\nimport { ExitCode, exitCodeForApiErrorCode, type ExitCodeValue } from \"../utils/exitCode.js\";\nimport { printJsonLine } from \"../output/jsonl.js\";\nimport { renderBatchTable } from \"../output/table.js\";\n\n/**\n * Client-side batch only: sends individual `GET /v1/ip-risk/{ip}` requests with controlled\n * concurrency. There is currently no server-side batch endpoint - do not call one.\n */\nconst MAX_CONCURRENCY = 20;\nconst DEFAULT_CONCURRENCY = 5;\n\nexport interface BatchItemError {\n code: string;\n message: string;\n requestId?: string;\n /** Present on `anonymous_daily_limit_reached`, so the summary can report the real allowance. */\n anonymousUsage?: AnonymousLimitInfo;\n}\n\nexport type BatchItemResult =\n | { ip: string; ok: true; result: IpRiskResponse }\n | { ip: string; ok: false; error: BatchItemError };\n\ninterface BatchOptions {\n apiKey?: string;\n baseUrl?: string;\n concurrency: string;\n jsonl?: boolean;\n timeout: string;\n maxRetries: string;\n}\n\nexport function registerBatchCommand(program: Command): void {\n program\n .command(\"batch <file>\")\n .description(\"Check multiple IP addresses (client-side batch over GET /v1/ip-risk/{ip})\")\n .option(\n \"--api-key <key>\",\n \"NetRiskScan API key (optional; uses the anonymous trial when omitted)\",\n )\n .option(\"--base-url <url>\", \"Override the API base URL (advanced)\")\n .option(\n \"--concurrency <n>\",\n `Number of concurrent requests (default: ${DEFAULT_CONCURRENCY}, max: ${MAX_CONCURRENCY})`,\n String(DEFAULT_CONCURRENCY),\n )\n .option(\"--jsonl\", \"Output newline-delimited JSON (one object per IP)\")\n .option(\"--timeout <ms>\", \"Request timeout in milliseconds\", \"10000\")\n .option(\"--max-retries <n>\", \"Maximum automatic retries for 429/503\", \"3\")\n .addHelpText(\n \"after\",\n `\nNotes:\n This is a client-side batch: it sends individual GET /v1/ip-risk/{ip}\n requests with controlled concurrency. NetRiskScan does not currently\n offer a server-side batch endpoint. Make sure the selected concurrency\n complies with the limits shown in your NetRiskScan Developer Dashboard.\n\n An API key is optional. Without an API key, requests use the anonymous daily\n trial, metered by public IP. How many remain is decided by the server, not by\n this CLI, and is reported in the summary after the table.\n\nInput format:\n One IP per line. Blank lines and lines starting with # are ignored.\n\nExamples:\n $ netriskscan batch ips.txt\n $ cat ips.txt | netriskscan batch -\n $ netriskscan batch ips.txt --concurrency 10 --jsonl > results.jsonl\n`,\n )\n .action(async (file: string, options: BatchOptions) => {\n await runBatch(file, options);\n });\n}\n\nasync function readIps(file: string): Promise<string[]> {\n const stream = file === \"-\" ? process.stdin : createReadStream(file, \"utf8\");\n const rl = createInterface({ input: stream, crlfDelay: Infinity });\n const ips: string[] = [];\n for await (const rawLine of rl) {\n const line = rawLine.trim();\n if (line === \"\" || line.startsWith(\"#\")) continue;\n ips.push(line);\n }\n return ips;\n}\n\nfunction parseConcurrency(value: string): number {\n const n = Number(value);\n if (!Number.isFinite(n) || n < 1) return DEFAULT_CONCURRENCY;\n if (n > MAX_CONCURRENCY) {\n process.stderr.write(\n `Warning: --concurrency ${n} exceeds the safety cap of ${MAX_CONCURRENCY}; using ${MAX_CONCURRENCY}.\\n` +\n \"Check your NetRiskScan Developer Dashboard for your plan's concurrency limit.\\n\",\n );\n return MAX_CONCURRENCY;\n }\n return Math.floor(n);\n}\n\nfunction toBatchError(err: unknown): BatchItemError {\n if (err instanceof NetRiskScanApiError) {\n return {\n code: err.code,\n message: err.message,\n requestId: err.requestId,\n anonymousUsage: err.anonymousUsage,\n };\n }\n if (err instanceof NetRiskScanNetworkError) {\n return { code: \"network_error\", message: err.message, requestId: err.requestId };\n }\n return { code: \"unknown_error\", message: err instanceof Error ? err.message : String(err) };\n}\n\nasync function runBatch(file: string, options: BatchOptions): Promise<void> {\n const ips = await readIps(file);\n if (ips.length === 0) {\n process.stderr.write(\"Error: no IP addresses found in input.\\n\");\n process.exitCode = ExitCode.InvalidArgument;\n return;\n }\n\n // No key means the anonymous trial. The CLI deliberately does not pre-check the input length\n // against a daily allowance: it cannot know how much of today's allowance was already spent,\n // and only the server can.\n const client = new NetRiskScanClient({\n apiKey: resolveOptionalApiKey(options.apiKey),\n baseUrl: resolveBaseUrl(options.baseUrl),\n timeout: Number(options.timeout),\n maxRetries: Number(options.maxRetries),\n });\n\n const concurrency = parseConcurrency(options.concurrency);\n\n const results = await runPool(ips, concurrency, async (ip): Promise<BatchItemResult> => {\n if (!isValidIp(ip)) {\n return {\n ip,\n ok: false,\n error: { code: \"invalid_ip\", message: `\"${ip}\" is not a valid IPv4 or IPv6 address.` },\n };\n }\n try {\n const { data } = await client.checkIp(ip);\n return { ip, ok: true, result: data };\n } catch (err) {\n return { ip, ok: false, error: toBatchError(err) };\n }\n });\n\n if (options.jsonl) {\n for (const item of results) {\n printJsonLine(item);\n }\n } else {\n renderBatchTable(results);\n }\n\n process.exitCode = computeBatchExitCode(results);\n}\n\nfunction computeBatchExitCode(results: readonly BatchItemResult[]): ExitCodeValue {\n const failures = results.filter((r): r is Extract<BatchItemResult, { ok: false }> => !r.ok);\n if (failures.length === 0) return ExitCode.Success;\n\n const codes = failures.map((f) => exitCodeForApiErrorCode(f.error.code));\n if (codes.includes(ExitCode.AuthError)) return ExitCode.AuthError;\n if (codes.includes(ExitCode.RateLimitOrQuota)) return ExitCode.RateLimitOrQuota;\n return ExitCode.ApiError;\n}\n","/** Runs `worker` over `items` with at most `concurrency` in flight, preserving result order. */\nexport async function runPool<T, R>(\n items: readonly T[],\n concurrency: number,\n worker: (item: T, index: number) => Promise<R>,\n): Promise<R[]> {\n const results: R[] = new Array(items.length);\n let cursor = 0;\n\n async function next(): Promise<void> {\n while (cursor < items.length) {\n const index = cursor++;\n results[index] = await worker(items[index] as T, index);\n }\n }\n\n const workerCount = Math.max(1, Math.min(concurrency, items.length));\n await Promise.all(Array.from({ length: workerCount }, () => next()));\n return results;\n}\n","/** One compact JSON object per line, so a failed line never breaks the rest of the stream. */\nexport function printJsonLine(data: unknown): void {\n process.stdout.write(`${JSON.stringify(data)}\\n`);\n}\n","import Table from \"cli-table3\";\nimport chalk from \"chalk\";\nimport type { BatchItemResult } from \"../commands/batch.js\";\nimport { ANONYMOUS_DAILY_LIMIT_CODE } from \"../client/errors.js\";\nimport {\n formatIndex,\n formatNumber,\n formatOrDash,\n formatProxyTypeCompact,\n formatTriState,\n row,\n} from \"./format.js\";\n\n/**\n * Anonymous-trial summary for a finished batch.\n *\n * The batch runs concurrently, so responses do not arrive in the order the server charged them:\n * one reply can say 22 remaining while a later-numbered one says 19. The lowest value observed is\n * the closest thing to the truth, so that is what gets reported. If any request was actually\n * refused for exhausting the trial, the answer is 0 no matter what the successful replies said.\n */\nfunction anonymousSummaryLines(results: readonly BatchItemResult[]): string[] {\n const remainings: number[] = [];\n const dailyLimits: number[] = [];\n let exhausted = false;\n\n for (const item of results) {\n if (item.ok) {\n const usage = item.result.usage;\n if (usage?.mode !== \"anonymous\") continue;\n if (typeof usage.remaining === \"number\") remainings.push(usage.remaining);\n if (typeof usage.dailyLimit === \"number\") dailyLimits.push(usage.dailyLimit);\n } else if (item.error.code === ANONYMOUS_DAILY_LIMIT_CODE) {\n exhausted = true;\n const limit = item.error.anonymousUsage?.dailyLimit;\n if (typeof limit === \"number\") dailyLimits.push(limit);\n }\n }\n\n if (!exhausted && remainings.length === 0) return [];\n\n const available = exhausted ? 0 : Math.min(...remainings);\n const lines = [\"\", chalk.bold(\"Anonymous trial\"), row(\"Available\", formatNumber(available))];\n if (dailyLimits.length > 0) {\n lines.push(row(\"Daily Limit\", formatNumber(Math.max(...dailyLimits))));\n }\n return lines;\n}\n\nexport function renderBatchTable(results: readonly BatchItemResult[]): void {\n const table = new Table({\n head: [\"IP\", \"Index\", \"Band\", \"Proxy\", \"Proxy Type\", \"VPN\", \"Tor\", \"Crawler\", \"Status\"],\n style: { head: [], border: [] },\n });\n\n for (const item of results) {\n if (item.ok) {\n const { result } = item;\n table.push([\n item.ip,\n formatIndex(result.risk.index),\n result.risk.band ?? \"N/A\",\n formatTriState(result.flags.proxy),\n formatProxyTypeCompact(result.flags.proxyType),\n formatTriState(result.flags.vpn),\n formatTriState(result.flags.tor),\n formatOrDash(result.flags.searchCrawlerName),\n chalk.green(\"ok\"),\n ]);\n } else {\n table.push([\n item.ip,\n \"-\",\n \"-\",\n \"-\",\n \"-\",\n \"-\",\n \"-\",\n \"-\",\n chalk.red(`error: ${item.error.code}`),\n ]);\n }\n }\n\n process.stdout.write(`${table.toString()}\\n`);\n\n const okCount = results.filter((r) => r.ok).length;\n const failCount = results.length - okCount;\n process.stdout.write(`\\n${okCount} succeeded, ${failCount} failed\\n`);\n\n const anonymous = anonymousSummaryLines(results);\n if (anonymous.length > 0) {\n process.stdout.write(`${anonymous.join(\"\\n\")}\\n`);\n }\n}\n"],"mappings":";;;AACA,SAAS,oBAAoB;AAC7B,SAAS,SAAS,YAAY;AAC9B,SAAS,qBAAqB;AAC9B,SAAS,SAAS,sBAAsB;;;ACHxC,OAAO,SAAS;;;ACoBT,IAAM,6BAA6B;AAgBnC,IAAM,mBAAN,cAA+B,MAAM;AAAA,EAC1C,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAGO,IAAM,yBAAN,cAAqC,iBAAiB;AAAA,EAC3D,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAWO,IAAM,sBAAN,cAAkC,iBAAiB;AAAA,EAC/C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EAET,YAAY,SAAiB,SAAqC;AAChE,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS,QAAQ;AACtB,SAAK,OAAO,QAAQ;AACpB,SAAK,YAAY,QAAQ;AACzB,SAAK,aAAa,QAAQ;AAC1B,SAAK,iBAAiB,QAAQ;AAAA,EAChC;AACF;AAQO,IAAM,0BAAN,cAAsC,iBAAiB;AAAA,EAC1C;AAAA,EACT;AAAA,EAET,YAAY,SAAiB,UAA0C,CAAC,GAAG;AACzE,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,QAAQ,QAAQ;AACrB,SAAK,YAAY,QAAQ;AAAA,EAC3B;AACF;;;AChGA,SAAS,mBAAmB;AAG5B,IAAM,qBAAqB;AAEpB,SAAS,iBAAiB,IAAqB;AACpD,SAAO,mBAAmB,KAAK,EAAE;AACnC;AAEO,SAAS,oBAA4B;AAC1C,SAAO,OAAO,YAAY,EAAE,EAAE,SAAS,KAA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U,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/utils/ip.ts","../src/utils/exitCode.ts","../src/output/human.ts","../src/utils/quotaWarnings.ts","../src/output/format.ts","../src/utils/browser.ts","../src/output/json.ts","../src/output/errors.ts","../src/client/errors.ts","../src/output/jsonl.ts","../src/commands/session.ts","../src/client/headers.ts","../src/client/retry.ts","../src/client/NetRiskScanClient.ts","../src/utils/credentials.ts","../src/utils/env.ts","../src/commands/usage.ts","../src/commands/batch.ts","../src/utils/pool.ts","../src/output/table.ts","../src/commands/auth.ts","../src/commands/billing.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 { registerAuthCommand } from \"./commands/auth.js\";\nimport { registerBillingCommands } from \"./commands/billing.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 and network intelligence, manage your API key, and view developer quota.\",\n )\n .version(pkg.version, \"-V, --version\", \"Show the CLI version\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ netriskscan check 1.1.1.1\n $ netriskscan check 1.1.1.1 --json\n $ netriskscan quota\n $ netriskscan batch ips.txt --jsonl\n $ netriskscan auth status\n $ netriskscan upgrade\n\nDeveloper API requires a valid API Key. Credentials are resolved from\n--api-key, NETRISKSCAN_API_KEY, then the OS credential store.\nWithout a key, an interactive query opens the Developer Console for setup.\nSign in there, create a key and run \"netriskscan auth save\".\n\nEnvironment variables:\n NETRISKSCAN_API_KEY Supply a Developer API key from a secret manager in CI.\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);\nregisterAuthCommand(program);\nregisterBillingCommands(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 type { IpRiskResponse, RiskFlagName } from \"../client/types.js\";\nimport { isValidIp } from \"../utils/ip.js\";\nimport { ExitCode, type ExitCodeValue } from \"../utils/exitCode.js\";\nimport { renderCheckResult, renderVerboseMeta } from \"../output/human.js\";\nimport { printJson } from \"../output/json.js\";\nimport { CliError, reportFailure } from \"../output/errors.js\";\nimport { warnAboutQuota } from \"../utils/quotaWarnings.js\";\nimport {\n isOfficialApi,\n offerQuotaUpgrade,\n quotaFailure,\n requireSession,\n runCommand,\n type CommandOptions,\n} from \"./session.js\";\n\nconst KNOWN_FLAGS: readonly RiskFlagName[] = [\n \"proxy\",\n \"vpn\",\n \"tor\",\n \"datacenter\",\n \"scanner\",\n \"abuse\",\n];\n\ninterface CheckOptions extends CommandOptions {\n verbose?: boolean;\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(\"--api-key <key>\", \"Developer API key (overrides the environment and OS store)\")\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 Developer API requires a valid API Key.\n`,\n )\n .action(async (ip: string, options: CheckOptions) => {\n await runCommand(options, () => 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 throw new CliError(\n \"invalid_argument\",\n `Unknown --fail-on flag \"${flag}\". Expected one of: ${KNOWN_FLAGS.join(\", \")}`,\n ExitCode.InvalidArgument,\n );\n }\n }\n\n if (!isValidIp(ip)) {\n throw new CliError(\n \"invalid_ip\",\n `\"${ip}\" is not a valid IPv4 or IPv6 address.`,\n ExitCode.InvalidArgument,\n );\n }\n\n const { key, client } = await requireSession(options);\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 if (isOfficialApi(options)) await warnAboutQuota(key, meta.quota);\n }\n\n process.exitCode = evaluateCiPolicy(data, options);\n } catch (err) {\n spinner?.stop();\n const failure = await quotaFailure(err, client);\n reportFailure(failure, options);\n process.exitCode = failure.exitCode;\n await offerQuotaUpgrade(failure.info.code, 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","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 \"monthly_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 { quotaUsagePercent } from \"../utils/quotaWarnings.js\";\nimport type {\n IpLocation,\n IpRiskResponse,\n RequestUsage,\n ResponseMeta,\n RiskBand,\n RiskReason,\n UsageResponse,\n} from \"../client/types.js\";\nimport {\n formatGeoName,\n formatIndex,\n formatNullable,\n formatNumber,\n formatOrDash,\n formatProxyType,\n formatRiskReasonCode,\n formatTriState,\n formatUtcTimestamp,\n reasonRow,\n row,\n} from \"./format.js\";\n\n/**\n * Anonymous-trial rows for the human `check` output.\n *\n * `Available` is printed verbatim from `usage.remaining` - the server is the only authority on\n * what is left, so this never falls back to `dailyLimit - used`. Each row is emitted only when\n * its value is actually a number, because `0` is a legitimate value that a truthiness check\n * would swallow on exactly the run where it matters most.\n */\nfunction anonymousUsageLines(usage: RequestUsage): string[] {\n const lines: string[] = [];\n if (typeof usage.remaining === \"number\") {\n lines.push(row(\"Available\", formatNumber(usage.remaining)));\n }\n if (typeof usage.dailyLimit === \"number\") {\n lines.push(row(\"Daily Limit\", formatNumber(usage.dailyLimit)));\n }\n const reset = formatUtcTimestamp(usage.resetAt);\n if (reset !== undefined) {\n lines.push(row(\"Reset\", reset));\n }\n return lines;\n}\n\n/**\n * Rows for the server's own explanations of the assessment.\n *\n * Rendering only: the list is whatever `risk.reasons` contained, in the server's order, with no\n * entry derived from `flags`/`network`, none filtered out, and none re-ranked. An empty or absent\n * list yields no rows at all, so the caller drops the section rather than printing a heading over\n * nothing - the common case for an ordinary address.\n */\nfunction riskReasonLines(reasons: readonly RiskReason[] | undefined): string[] {\n if (reasons === undefined || reasons.length === 0) return [];\n return reasons.map((reason) => {\n const severity = reason.severity ?? \"\";\n return reasonRow(formatRiskReasonCode(reason.code), severityColor(severity)(severity));\n });\n}\n\n/**\n * Severity is a secondary cue, never the message itself: the label already says what was found, so\n * an unrecognised severity simply renders uncoloured instead of being mapped to a guessed level.\n *\n * `info` is deliberately dim rather than warning-coloured - `Verified Search Crawler` and\n * `Public Infrastructure` explain why an address is *clean*, and colouring them like a threat\n * would misrepresent the server's own assessment.\n */\nfunction severityColor(severity: string): (text: string) => string {\n switch (severity) {\n case \"critical\":\n case \"high\":\n return chalk.red;\n case \"medium\":\n return chalk.yellow;\n case \"info\":\n return chalk.gray;\n default:\n return (text: string) => text;\n }\n}\n\n/**\n * Rows for network-level geolocation - where the network is routed, not where a device is.\n *\n * Each row appears only when the server actually sent that field: geo resolution is independently\n * partial (a country with no city is normal), and a wall of \"N/A\" rows would be noise dressed up as\n * data. An absent `location` object yields no rows, so the caller drops the whole section.\n */\nfunction locationLines(location: IpLocation | null | undefined): string[] {\n if (!location) return [];\n const lines: string[] = [];\n const country = formatGeoName(location.country, location.countryCode);\n if (country !== undefined) lines.push(row(\"Country\", country));\n const region = formatGeoName(location.region, location.regionCode);\n if (region !== undefined) lines.push(row(\"Region\", region));\n if (location.city) lines.push(row(\"City\", location.city));\n const continent = formatGeoName(location.continent, location.continentCode);\n if (continent !== undefined) lines.push(row(\"Continent\", continent));\n if (location.postalCode) lines.push(row(\"Postal Code\", location.postalCode));\n // A coordinate pair is shown only when the server sent both halves as real numbers. `0` is a\n // legitimate coordinate, so this is a type check, never a truthiness check; an anycast network\n // sends null for both and gets no row rather than a fabricated position.\n const { latitude, longitude } = location;\n if (\n typeof latitude === \"number\" &&\n Number.isFinite(latitude) &&\n typeof longitude === \"number\" &&\n Number.isFinite(longitude)\n ) {\n lines.push(row(\"Coordinates\", `${latitude}, ${longitude}`));\n }\n if (location.timeZone) lines.push(row(\"Time Zone\", location.timeZone));\n return lines;\n}\n\nfunction bandColor(band: RiskBand | null): (text: string) => string {\n switch (band) {\n case \"excellent\":\n case \"good\":\n return chalk.green;\n case \"fair\":\n return chalk.yellow;\n case \"poor\":\n case \"high_risk\":\n return chalk.red;\n default:\n return chalk.gray;\n }\n}\n\nexport function renderCheckResult(ip: string, data: IpRiskResponse): void {\n const lines: string[] = [];\n lines.push(chalk.bold(\"NetRiskScan\"));\n lines.push(\"\");\n lines.push(row(\"IP\", ip));\n lines.push(row(\"Index\", formatIndex(data.risk.index)));\n lines.push(\n row(\"Band\", data.risk.band ? bandColor(data.risk.band)(data.risk.band) : chalk.gray(\"N/A\")),\n );\n lines.push(row(\"Assessment\", data.risk.assessmentGrade));\n lines.push(\"\");\n\n if (data.risk.assessmentGrade === \"insufficient\" && data.risk.index === null) {\n lines.push(chalk.yellow(\"This address could not be reliably assessed.\"));\n lines.push(\"\");\n }\n\n // Directly under the verdict it explains, and only when the server sent one: these are the\n // server's reasons, so an empty or absent list means there is nothing to show - never a cue for\n // the CLI to work some out from flags.\n const reasonLines = riskReasonLines(data.risk.reasons);\n if (reasonLines.length > 0) {\n lines.push(chalk.bold(\"Risk Reasons\"));\n lines.push(...reasonLines);\n lines.push(\"\");\n }\n\n lines.push(chalk.bold(\"Network\"));\n lines.push(row(\"Type\", formatNullable(data.network.type)));\n // Omitted entirely when absent, unlike the fields around them, which render \"N/A\". Those describe every\n // address, so a missing one is worth showing as missing; these two exist only for the minority of\n // addresses NetRiskScan holds a first-party record for, and printing \"Profile N/A\" on every residential\n // lookup would be noise rather than information.\n if (data.network.profile) {\n lines.push(row(\"Profile\", data.network.profile));\n }\n if (data.network.service) {\n lines.push(row(\"Service\", data.network.service));\n }\n lines.push(row(\"Connection\", formatNullable(data.network.connectionType)));\n lines.push(row(\"ASN\", formatNullable(data.network.asn)));\n lines.push(row(\"Organization\", formatNullable(data.network.organization)));\n // Schema 1.6.0 additions, dropped when absent for the same reason as Profile/Service above.\n // Both are server-owned facts: never inferred from the ASN, organization or hostname, and the\n // range is never computed client-side.\n if (data.network.domain) {\n lines.push(row(\"Domain\", data.network.domain));\n }\n if (data.network.range) {\n lines.push(row(\"Network Range\", data.network.range));\n }\n lines.push(\"\");\n\n const geoLines = locationLines(data.location);\n if (geoLines.length > 0) {\n lines.push(chalk.bold(\"Location\"));\n lines.push(...geoLines);\n lines.push(\"\");\n }\n\n lines.push(chalk.bold(\"Signals\"));\n lines.push(row(\"Proxy\", formatTriState(data.flags.proxy)));\n lines.push(row(\"Proxy Type\", formatProxyType(data.flags.proxyType)));\n lines.push(row(\"VPN\", formatTriState(data.flags.vpn)));\n lines.push(row(\"Tor\", formatTriState(data.flags.tor)));\n lines.push(row(\"Datacenter\", formatTriState(data.flags.datacenter)));\n lines.push(row(\"Scanner\", formatTriState(data.flags.scanner)));\n lines.push(row(\"Abuse\", formatTriState(data.flags.abuse)));\n lines.push(\"\");\n\n // Identity, not a risk signal: a verified crawler must never read as a threat, so it gets its own\n // section rather than living inside Signals.\n lines.push(chalk.bold(\"Identity\"));\n lines.push(row(\"Search Crawler\", formatTriState(data.flags.searchCrawler)));\n lines.push(row(\"Crawler\", formatOrDash(data.flags.searchCrawlerName)));\n lines.push(\"\");\n\n // Only for the anonymous trial. An API-key caller's allowance is a billing-period quota, a\n // different thing entirely, and stays behind --verbose where it always was.\n if (data.usage?.mode === \"anonymous\") {\n const usageLines = anonymousUsageLines(data.usage);\n if (usageLines.length > 0) {\n lines.push(chalk.bold(\"Usage\"));\n lines.push(...usageLines);\n lines.push(\"\");\n }\n }\n\n lines.push(row(\"Request ID\", data.requestId));\n lines.push(\"\");\n\n lines.push(chalk.bold(\"Explore\"));\n lines.push(row(\"Web\", \"https://www.netriskscan.com\"));\n lines.push(row(\"GitHub\", \"https://github.com/TeamQQ/netriskscan-cli\"));\n\n process.stdout.write(`${lines.join(\"\\n\")}\\n`);\n}\n\nexport function renderVerboseMeta(meta: ResponseMeta): void {\n const lines: string[] = [\"\"];\n if (meta.rateLimit.remaining !== undefined && meta.rateLimit.limit !== undefined) {\n lines.push(\n row(\n \"Rate limit\",\n `${formatNumber(meta.rateLimit.remaining)} / ${formatNumber(meta.rateLimit.limit)} remaining`,\n ),\n );\n }\n if (meta.quota.remaining !== undefined && meta.quota.limit !== undefined) {\n lines.push(\n row(\n \"Quota\",\n `${formatNumber(meta.quota.remaining)} / ${formatNumber(meta.quota.limit)} remaining`,\n ),\n );\n }\n lines.push(row(\"Request ID\", meta.requestId));\n process.stdout.write(`${lines.join(\"\\n\")}\\n`);\n}\n\nexport function renderUsageResult(data: UsageResponse): void {\n const lines: string[] = [];\n lines.push(chalk.bold(\"NetRiskScan Usage\"));\n lines.push(\"\");\n lines.push(row(\"Plan\", data.plan));\n lines.push(\"\");\n lines.push(chalk.bold(\"Usage\"));\n lines.push(row(\"Used\", formatNumber(data.units.used)));\n lines.push(row(\"Remaining\", formatNumber(data.units.remaining)));\n lines.push(row(\"Limit\", formatNumber(data.units.limit)));\n const percent = quotaUsagePercent(data.units);\n if (percent !== undefined) lines.push(row(\"Used (%)\", `${percent.toFixed(1)}%`));\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(\"Monthly quota period\"));\n lines.push(row(\"Started\", formatUtcTimestamp(data.period.start) ?? data.period.start));\n lines.push(row(\"Resets\", formatUtcTimestamp(data.period.end) ?? data.period.end));\n\n process.stdout.write(`${lines.join(\"\\n\")}\\n`);\n}\n","import { createHash } from \"node:crypto\";\nimport { mkdir, stat, unlink, writeFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport type { QuotaInfo } from \"../client/types.js\";\nimport { formatNumber, row } from \"../output/format.js\";\nimport { WEB_PAGES } from \"./browser.js\";\n\nconst WARNING_LEVELS = [80, 95] as const;\n\nexport function quotaUsagePercent(quota: QuotaInfo): number | undefined {\n const { limit, used } = quota;\n return limit !== undefined && limit > 0 && used !== undefined ? (used / limit) * 100 : undefined;\n}\n\nfunction marker(key: string, limit: number, level: number): string {\n const fingerprint = createHash(\"sha256\").update(key).digest(\"hex\");\n return join(homedir(), \".netriskscan\", \"quota-warnings\", `${fingerprint}-${limit}-${level}`);\n}\n\nexport async function rearmQuotaWarnings(\n key: string,\n quota: QuotaInfo,\n periodStart?: string,\n): Promise<void> {\n const { limit } = quota;\n const percent = quotaUsagePercent(quota);\n if (limit === undefined || percent === undefined) return;\n const start = periodStart ? Date.parse(periodStart) : NaN;\n await Promise.all(\n WARNING_LEVELS.map(async (level) => {\n const path = marker(key, limit, level);\n try {\n if (percent < level || (Number.isFinite(start) && (await stat(path)).mtimeMs < start)) {\n await unlink(path);\n }\n } catch {\n // Missing or inaccessible warning metadata never changes the query outcome.\n }\n }),\n );\n}\n\nexport async function warnAboutQuota(key: string, quota: QuotaInfo): Promise<void> {\n const { limit, used, remaining } = quota;\n const percent = quotaUsagePercent(quota);\n if (limit === undefined || used === undefined || remaining === undefined || percent === undefined)\n return;\n await rearmQuotaWarnings(key, quota);\n let warnedAt: number | undefined;\n for (const level of WARNING_LEVELS) {\n if (percent < level) break;\n const path = marker(key, limit, level);\n try {\n await mkdir(dirname(path), { recursive: true, mode: 0o700 });\n await writeFile(path, \"\", { flag: \"wx\", mode: 0o600 });\n warnedAt = level;\n } catch {\n // Exclusive creation deduplicates concurrent invocations. Skip on an unavailable store.\n }\n }\n if (warnedAt === undefined) return;\n process.stderr.write(\n [\n \"\",\n warnedAt === WARNING_LEVELS[1]\n ? \"Monthly API quota almost exhausted.\"\n : \"Monthly API quota warning.\",\n row(\"Usage\", `${formatNumber(used)} / ${formatNumber(limit)}`),\n row(\"Remaining\", formatNumber(remaining)),\n \"For more quota, run npx netriskscan-cli upgrade\",\n WEB_PAGES.plans,\n \"\",\n ].join(\"\\n\") + \"\\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","import { spawn } from \"node:child_process\";\n\nexport const WEB_PAGES = {\n keys: \"https://www.netriskscan.com/developer/keys\",\n plans: \"https://www.netriskscan.com/pricing.html\",\n billing: \"https://www.netriskscan.com/developer/billing\",\n} as const;\n\nexport function isInteractive(machineOutput?: boolean): boolean {\n const ci = process.env.CI?.trim().toLowerCase();\n return Boolean(\n !machineOutput &&\n process.stdin.isTTY &&\n process.stdout.isTTY &&\n (!ci || ci === \"false\" || ci === \"0\") &&\n !process.env.GITHUB_ACTIONS &&\n !process.env.TF_BUILD,\n );\n}\n\n/** Only accepts known NetRiskScan HTTPS destinations. */\nexport async function openBrowser(page: keyof typeof WEB_PAGES): Promise<boolean> {\n const url = WEB_PAGES[page];\n const [command, ...args] =\n process.platform === \"win32\"\n ? [\"rundll32.exe\", \"url.dll,FileProtocolHandler\", url]\n : process.platform === \"darwin\"\n ? [\"open\", url]\n : [\"xdg-open\", url];\n const env = { ...process.env };\n for (const name of Object.keys(env)) {\n if (name.toUpperCase() === \"NETRISKSCAN_API_KEY\") delete env[name];\n }\n return new Promise((resolve) => {\n const child = spawn(command, args, { env, detached: true, stdio: \"ignore\", windowsHide: true });\n // Some launchers stay alive until the browser exits. Wait only for immediate launcher errors.\n const timer = setTimeout(() => finish(true), 400);\n function finish(opened: boolean): void {\n clearTimeout(timer);\n child.unref();\n resolve(opened);\n }\n child.once(\"error\", () => finish(false));\n child.once(\"exit\", (code) => finish(code === 0));\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 {\n isMonthlyQuotaError,\n NetRiskScanApiError,\n NetRiskScanNetworkError,\n} from \"../client/errors.js\";\nimport type { QuotaInfo } from \"../client/types.js\";\nimport { WEB_PAGES } from \"../utils/browser.js\";\nimport { ExitCode, exitCodeForApiErrorCode, type ExitCodeValue } from \"../utils/exitCode.js\";\nimport { formatNumber, formatUtcTimestamp, row } from \"./format.js\";\nimport { printJson } from \"./json.js\";\nimport { printJsonLine } from \"./jsonl.js\";\n\nexport class CliError extends Error {\n constructor(\n readonly code: string,\n message: string,\n readonly exitCode: ExitCodeValue,\n readonly url?: string,\n ) {\n super(message);\n }\n}\n\ninterface ErrorInfo {\n code: string;\n message: string;\n status?: number;\n requestId?: string;\n retryAfter?: number;\n quota?: QuotaInfo;\n plan?: string;\n resetAt?: string;\n upgradeUrl?: string;\n url?: string;\n}\n\nexport interface CommandFailure {\n exitCode: ExitCodeValue;\n info: ErrorInfo;\n cause: unknown;\n}\n\nexport function commandFailure(cause: unknown): CommandFailure {\n if (cause instanceof NetRiskScanApiError) {\n return {\n cause,\n exitCode: exitCodeForApiErrorCode(cause.code),\n info: {\n code: cause.code,\n message: cause.message,\n status: cause.status,\n requestId: cause.requestId,\n retryAfter: cause.retryAfter,\n quota:\n cause.quota && Object.values(cause.quota).some((value) => value !== undefined)\n ? cause.quota\n : undefined,\n resetAt: cause.quotaResetAt,\n upgradeUrl: isMonthlyQuotaError(cause.code) ? WEB_PAGES.plans : undefined,\n },\n };\n }\n if (cause instanceof NetRiskScanNetworkError) {\n return {\n cause,\n exitCode: ExitCode.ApiError,\n info: { code: \"network_error\", message: cause.message, requestId: cause.requestId },\n };\n }\n if (cause instanceof CliError) {\n return {\n cause,\n exitCode: cause.exitCode,\n info: { code: cause.code, message: cause.message, url: cause.url },\n };\n }\n return {\n cause,\n exitCode: ExitCode.GeneralError,\n info: {\n code: \"cli_error\",\n message: cause instanceof Error ? cause.message : \"Unexpected CLI error.\",\n },\n };\n}\n\nexport function reportFailure(\n failure: CommandFailure,\n options: { json?: boolean; jsonl?: boolean; debug?: boolean } = {},\n): void {\n const { info, cause } = failure;\n if (options.jsonl) {\n printJsonLine({ error: info });\n } else if (options.json) {\n printJson({ error: info });\n } else if (isMonthlyQuotaError(info.code)) {\n const lines = [\"\", chalk.yellow(\"Monthly API quota exceeded.\")];\n if (info.plan) lines.push(row(\"Current plan\", info.plan));\n if (info.quota?.limit !== undefined)\n lines.push(row(\"Monthly limit\", formatNumber(info.quota.limit)));\n if (info.quota?.used !== undefined) lines.push(row(\"Used\", formatNumber(info.quota.used)));\n if (info.quota?.remaining !== undefined)\n lines.push(row(\"Remaining\", formatNumber(info.quota.remaining)));\n const reset = formatUtcTimestamp(info.resetAt);\n if (reset) lines.push(row(\"Resets\", reset));\n lines.push(\"\", \"For more quota, run npx netriskscan-cli upgrade\", info.upgradeUrl ?? \"\", \"\");\n process.stderr.write(lines.join(\"\\n\"));\n } else if (cause instanceof NetRiskScanApiError) {\n printApiError(cause, options);\n } else if (cause instanceof NetRiskScanNetworkError) {\n printNetworkError(cause, options);\n } else {\n process.stderr.write(`Error: ${info.message}\\n`);\n if (info.url) process.stderr.write(`${info.url}\\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 { 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_disabled\",\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","/** 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 { createInterface } from \"node:readline/promises\";\nimport { DEFAULT_BASE_URL, NetRiskScanClient } from \"../client/NetRiskScanClient.js\";\nimport { isMonthlyQuotaError, NetRiskScanApiError } from \"../client/errors.js\";\nimport { commandFailure, reportFailure, CliError } from \"../output/errors.js\";\nimport { isInteractive, openBrowser, WEB_PAGES } from \"../utils/browser.js\";\nimport { credentials, CredentialStoreUnavailable } from \"../utils/credentials.js\";\nimport { resolveBaseUrl } from \"../utils/env.js\";\nimport { ExitCode } from \"../utils/exitCode.js\";\n\nexport interface CommandOptions {\n apiKey?: string;\n baseUrl?: string;\n json?: boolean;\n jsonl?: boolean;\n debug?: boolean;\n timeout?: string;\n maxRetries?: string;\n}\n\nexport async function runCommand(\n options: CommandOptions,\n action: () => Promise<void>,\n): Promise<void> {\n try {\n await action();\n } catch (error) {\n const failure = commandFailure(error);\n reportFailure(failure, options);\n process.exitCode = failure.exitCode;\n }\n}\n\nexport function suppliedKey(\n cliValue?: string,\n): { key: string; source: \"argument\" | \"environment\" } | undefined {\n if (cliValue !== undefined) return { key: validateKey(cliValue), source: \"argument\" };\n const key = process.env.NETRISKSCAN_API_KEY;\n return key ? { key: validateKey(key), source: \"environment\" } : undefined;\n}\n\nexport function validateKey(key: string): string {\n if (!/^[A-Za-z0-9._~+/-]+=*$/.test(key)) {\n throw new CliError(\n \"invalid_api_key\",\n \"The API key is empty or has invalid characters.\",\n ExitCode.AuthError,\n );\n }\n return key;\n}\n\nexport function isOfficialApi(options: CommandOptions): boolean {\n const baseUrl = resolveBaseUrl(options.baseUrl) ?? DEFAULT_BASE_URL;\n return baseUrl.replace(/\\/+$/, \"\") === DEFAULT_BASE_URL;\n}\n\nexport function createClient(key: string, options: CommandOptions): NetRiskScanClient {\n return new NetRiskScanClient({\n apiKey: validateKey(key),\n baseUrl: resolveBaseUrl(options.baseUrl),\n timeout: options.timeout === undefined ? undefined : Number(options.timeout),\n maxRetries: options.maxRetries === undefined ? undefined : Number(options.maxRetries),\n });\n}\n\nexport async function requireSession(options: CommandOptions, setup = true) {\n const supplied = suppliedKey(options.apiKey);\n const official = isOfficialApi(options);\n let key = supplied?.key;\n let storeUnavailable = false;\n if (!key && official) {\n try {\n key = (await credentials.read()) ?? undefined;\n } catch (error) {\n if (!(error instanceof CredentialStoreUnavailable)) throw error;\n storeUnavailable = true;\n }\n }\n if (!key) {\n const url = official ? WEB_PAGES.keys : undefined;\n const opened =\n official &&\n setup &&\n isInteractive(options.json || options.jsonl) &&\n (await openBrowser(\"keys\"));\n const message = opened\n ? \"The Developer Console opened. Continue with Google, create an API key, then use auth save or NETRISKSCAN_API_KEY and rerun your command.\"\n : \"Developer API requires a valid API key. Set NETRISKSCAN_API_KEY or use --api-key.\";\n const storeMessage = storeUnavailable ? \" The OS credential store is unavailable.\" : \"\";\n throw new CliError(\n opened ? \"auth_setup_required\" : \"api_key_required\",\n message + storeMessage,\n ExitCode.AuthError,\n url,\n );\n }\n return { key, client: createClient(key, options) };\n}\n\n/** Consult usage only after the server has refused a risk request for monthly exhaustion. */\nexport async function quotaFailure(error: unknown, client: NetRiskScanClient) {\n const failure = commandFailure(error);\n if (!(error instanceof NetRiskScanApiError) || !isMonthlyQuotaError(error.code)) return failure;\n try {\n const { data } = await client.getUsage();\n failure.info.plan = data.plan;\n failure.info.quota = {\n limit: error.quota?.limit ?? data.units.limit,\n used: error.quota?.used ?? data.units.used,\n remaining: error.quota?.remaining ?? data.units.remaining,\n };\n failure.info.resetAt = error.quotaResetAt ?? data.period.end;\n } catch {\n // The risk key may lack usage:read. Keep the original refusal and its headers.\n }\n return failure;\n}\nexport async function offerQuotaUpgrade(code: string, options: CommandOptions): Promise<void> {\n if (\n !isMonthlyQuotaError(code) ||\n !isOfficialApi(options) ||\n !isInteractive(options.json || options.jsonl)\n )\n return;\n const input = createInterface({ input: process.stdin, output: process.stderr });\n const controller = new AbortController();\n input.once(\"close\", () => controller.abort());\n try {\n const answer = (\n await input.question(\"Would you like to view available plans? [Y/n] \", {\n signal: controller.signal,\n })\n )\n .trim()\n .toLowerCase();\n if ((answer === \"\" || answer === \"y\" || answer === \"yes\") && !(await openBrowser(\"plans\"))) {\n process.stderr.write(`Open ${WEB_PAGES.plans} in your browser.\\n`);\n }\n } catch {\n // Closing the terminal or canceling the prompt leaves the quota failure intact.\n } finally {\n input.close();\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 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 * 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 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","import type { AsyncEntry } from \"@napi-rs/keyring\";\n\nexport class CredentialStoreUnavailable extends Error {\n constructor() {\n super(\n \"The OS credential store is unavailable. Use a secret manager to supply NETRISKSCAN_API_KEY.\",\n );\n }\n}\n\nasync function useStore<T>(operation: (entry: AsyncEntry) => Promise<T>): Promise<T> {\n try {\n const { AsyncEntry } = await import(\"@napi-rs/keyring\");\n const entry = new AsyncEntry(\"netriskscan-cli\", \"developer-api-key\", {\n linux: { store: \"secret-service\" },\n });\n return await operation(entry);\n } catch {\n throw new CredentialStoreUnavailable();\n }\n}\n\nexport const credentials = {\n read: () => useStore((entry) => entry.getPassword()),\n save: (key: string) => useStore((entry) => entry.setPassword(key)),\n remove: () => useStore((entry) => entry.deleteCredential()),\n};\n","export function resolveBaseUrl(cliValue?: string): string | undefined {\n return cliValue ?? process.env.NETRISKSCAN_BASE_URL;\n}\n","import type { Command } from \"commander\";\nimport ora from \"ora\";\nimport { renderUsageResult, renderVerboseMeta } from \"../output/human.js\";\nimport { printJson } from \"../output/json.js\";\nimport { rearmQuotaWarnings } from \"../utils/quotaWarnings.js\";\nimport { isOfficialApi, requireSession, runCommand, type CommandOptions } from \"./session.js\";\n\ninterface UsageOptions extends CommandOptions {\n verbose?: boolean;\n}\n\nexport function registerUsageCommand(program: Command): void {\n program\n .command(\"usage\")\n .alias(\"quota\")\n .description(\"Show API usage and quota for the current monthly quota period\")\n .option(\"--api-key <key>\", \"Developer API key (overrides the environment and OS store)\")\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 with the usage:read scope.\n`,\n )\n .action(async (options: UsageOptions) => {\n await runCommand(options, () => runUsage(options));\n });\n}\n\nasync function runUsage(options: UsageOptions): Promise<void> {\n const { key, client } = await requireSession(options);\n const spinner = options.json\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 (options.json) {\n printJson(data);\n } else {\n renderUsageResult(data);\n if (options.verbose) {\n renderVerboseMeta(meta);\n }\n }\n if (isOfficialApi(options)) await rearmQuotaWarnings(key, data.units, data.period.start);\n } finally {\n spinner?.stop();\n }\n}\n","import type { Command } from \"commander\";\nimport { createReadStream } from \"node:fs\";\nimport { createInterface } from \"node:readline\";\nimport { isMonthlyQuotaError, NetRiskScanApiError } from \"../client/errors.js\";\nimport type { IpRiskResponse, QuotaInfo } from \"../client/types.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\";\nimport { CliError, commandFailure, reportFailure } from \"../output/errors.js\";\nimport { warnAboutQuota } from \"../utils/quotaWarnings.js\";\nimport {\n isOfficialApi,\n offerQuotaUpgrade,\n quotaFailure,\n requireSession,\n runCommand,\n type CommandOptions,\n} from \"./session.js\";\n\nconst MAX_CONCURRENCY = 20;\nconst DEFAULT_CONCURRENCY = 5;\n\nexport interface BatchItemError {\n code: string;\n message: string;\n requestId?: string;\n quota?: QuotaInfo;\n plan?: string;\n resetAt?: string;\n upgradeUrl?: string;\n attempted?: false;\n}\n\nexport type BatchItemResult =\n | { ip: string; ok: true; result: IpRiskResponse }\n | { ip: string; ok: false; error: BatchItemError };\n\ninterface BatchOptions extends CommandOptions {\n concurrency: 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(\"--api-key <key>\", \"Developer API key (overrides the environment and OS store)\")\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 Developer API requires a valid API Key. This command sends individual\n GET /v1/ip-risk/{ip} requests using the selected concurrency.\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 runCommand(options, () => 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\nasync function runBatch(file: string, options: BatchOptions): Promise<void> {\n const ips = await readIps(file);\n if (ips.length === 0) {\n throw new CliError(\"empty_input\", \"No IP addresses found in input.\", ExitCode.InvalidArgument);\n }\n\n const { key, client } = await requireSession(options, file !== \"-\");\n const concurrency = parseConcurrency(options.concurrency);\n let strongestQuota: QuotaInfo | undefined;\n let blocked: NetRiskScanApiError | undefined;\n let quotaBlock: NetRiskScanApiError | undefined;\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 if (blocked) {\n return {\n ip,\n ok: false,\n error: {\n code: blocked.code,\n message: \"Skipped after the server refused a preceding request.\",\n attempted: false,\n },\n };\n }\n try {\n const { data, meta } = await client.checkIp(ip);\n if (\n meta.quota.remaining !== undefined &&\n (strongestQuota?.remaining === undefined || meta.quota.remaining < strongestQuota.remaining)\n ) {\n strongestQuota = meta.quota;\n }\n return { ip, ok: true, result: data };\n } catch (err) {\n const { code, message, requestId } = commandFailure(err).info;\n if (err instanceof NetRiskScanApiError) {\n if (isMonthlyQuotaError(code)) {\n quotaBlock ??= err;\n blocked ??= err;\n } else if (exitCodeForApiErrorCode(code) === ExitCode.AuthError) {\n blocked ??= err;\n }\n }\n return { ip, ok: false, error: { code, message, requestId } };\n }\n });\n const failure = quotaBlock ? await quotaFailure(quotaBlock, client) : undefined;\n\n if (options.jsonl) {\n for (const item of results) {\n if (failure && !item.ok && isMonthlyQuotaError(item.error.code)) {\n const { quota, plan, resetAt, upgradeUrl } = failure.info;\n Object.assign(item.error, { quota, plan, resetAt, upgradeUrl });\n }\n printJsonLine(item);\n }\n } else {\n renderBatchTable(results);\n if (failure) reportFailure(failure);\n else if (strongestQuota && isOfficialApi(options)) await warnAboutQuota(key, strongestQuota);\n }\n\n process.exitCode = computeBatchExitCode(results);\n if (failure && file !== \"-\") await offerQuotaUpgrade(failure.info.code, options);\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","import Table from \"cli-table3\";\nimport chalk from \"chalk\";\nimport type { BatchItemResult } from \"../commands/batch.js\";\nimport { formatIndex, formatOrDash, formatProxyTypeCompact, formatTriState } from \"./format.js\";\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","import type { Command } from \"commander\";\nimport { DEFAULT_BASE_URL } from \"../client/NetRiskScanClient.js\";\nimport { NetRiskScanApiError } from \"../client/errors.js\";\nimport { redactApiKey } from \"../client/headers.js\";\nimport { CliError, commandFailure } from \"../output/errors.js\";\nimport { printJson } from \"../output/json.js\";\nimport { row } from \"../output/format.js\";\nimport { isInteractive, WEB_PAGES } from \"../utils/browser.js\";\nimport { credentials, CredentialStoreUnavailable } from \"../utils/credentials.js\";\nimport { ExitCode } from \"../utils/exitCode.js\";\nimport { createClient, isOfficialApi, runCommand, suppliedKey, validateKey } from \"./session.js\";\n\ninterface AuthOptions {\n apiKey?: string;\n json?: boolean;\n stdin?: boolean;\n}\n\nexport function registerAuthCommand(program: Command): void {\n const auth = program.command(\"auth\").description(\"Manage the locally stored Developer API key\");\n\n auth\n .command(\"save\")\n .description(\"Save an existing Developer API key in the OS credential store\")\n .option(\"--stdin\", \"Read the key from piped stdin instead of NETRISKSCAN_API_KEY\")\n .option(\"--json\", \"Output machine-readable JSON\")\n .action((options: AuthOptions) =>\n runCommand(options, () => manageStore(() => saveKey(options))),\n );\n\n auth\n .command(\"show\")\n .description(\"Display the full stored API key in an interactive terminal\")\n .option(\"--json\", \"Return a machine-readable error without displaying the key\")\n .action((options: AuthOptions) =>\n runCommand(options, () => manageStore(() => showKey(options))),\n );\n\n auth\n .command(\"status\")\n .description(\"Show authentication, key source, and current plan\")\n .option(\"--api-key <key>\", \"Check an explicit Developer API key\")\n .option(\"--json\", \"Output machine-readable JSON with a masked key\")\n .action((options: AuthOptions) => runCommand(options, () => showStatus(options)));\n\n auth\n .command(\"logout\")\n .description(\"Remove the local key without revoking it at NetRiskScan\")\n .option(\"--json\", \"Output machine-readable JSON\")\n .action((options: AuthOptions) =>\n runCommand(options, () => manageStore(() => logout(options))),\n );\n}\n\nasync function manageStore(action: () => Promise<void>): Promise<void> {\n try {\n await action();\n } catch (error) {\n if (error instanceof CredentialStoreUnavailable) {\n throw new CliError(\"credential_store_unavailable\", error.message, ExitCode.AuthError);\n }\n throw error;\n }\n}\n\nasync function readStdinKey(): Promise<string> {\n if (process.stdin.isTTY) {\n throw new CliError(\n \"piped_key_required\",\n \"Pipe the key from a secret manager into stdin.\",\n ExitCode.InvalidArgument,\n );\n }\n let input = \"\";\n for await (const chunk of process.stdin) {\n input += String(chunk);\n if (input.length > 4096) {\n throw new CliError(\n \"invalid_api_key\",\n \"The supplied API key is too long.\",\n ExitCode.AuthError,\n );\n }\n }\n return validateKey(input.trim());\n}\n\nasync function saveKey(options: AuthOptions): Promise<void> {\n const key = options.stdin ? await readStdinKey() : suppliedKey()?.key;\n if (!key) {\n throw new CliError(\n \"api_key_required\",\n \"Supply an existing API key through NETRISKSCAN_API_KEY or --stdin.\",\n ExitCode.AuthError,\n WEB_PAGES.keys,\n );\n }\n\n // The store is used only for the official API. A scope rejection confirms the key is recognized.\n const client = createClient(key, { baseUrl: DEFAULT_BASE_URL, maxRetries: \"0\" });\n try {\n await client.getUsage();\n } catch (error) {\n if (!(\n error instanceof NetRiskScanApiError &&\n error.status === 403 &&\n error.code === \"scope_not_allowed\"\n ))\n throw error;\n }\n await credentials.save(key);\n process.env.NETRISKSCAN_API_KEY = key;\n if (options.json) printJson({ saved: true, storage: \"os_credential_store\" });\n else\n process.stdout.write(\n \"API key saved in the OS credential store. Rerun your original command.\\n\",\n );\n}\n\nasync function showKey(options: AuthOptions): Promise<void> {\n if (!isInteractive(options.json)) {\n throw new CliError(\n \"interactive_terminal_required\",\n \"Viewing a full API key requires an interactive terminal.\",\n ExitCode.InvalidArgument,\n );\n }\n const key = await credentials.read();\n if (!key) {\n throw new CliError(\n \"api_key_required\",\n \"No stored API key. Create a key in the Developer Console and run auth save.\",\n ExitCode.AuthError,\n WEB_PAGES.keys,\n );\n }\n validateKey(key);\n let plan = \"Unavailable\";\n try {\n const { data } = await createClient(key, {\n baseUrl: DEFAULT_BASE_URL,\n maxRetries: \"0\",\n }).getUsage();\n plan = data.plan;\n } catch {\n // The locally stored key is available to its owner even if the API is unreachable.\n }\n process.stdout.write(\n `${row(\"Plan\", plan)}\\n${row(\"Developer account\", \"See Developer Console\")}\\n\\nYour stored API key:\\n${key}\\n`,\n );\n}\n\nasync function showStatus(options: AuthOptions): Promise<void> {\n const supplied = suppliedKey(options.apiKey);\n let stored: string | null = null;\n let storage = \"empty\";\n try {\n stored = await credentials.read();\n if (stored) storage = \"saved\";\n } catch (error) {\n if (!(error instanceof CredentialStoreUnavailable)) throw error;\n storage = \"unavailable\";\n }\n const key = supplied?.key ?? (isOfficialApi(options) ? stored : null);\n let status = \"not_configured\";\n let plan: string | undefined;\n let failure: ReturnType<typeof commandFailure> | undefined;\n if (key) {\n try {\n const { data } = await createClient(key, { ...options, maxRetries: \"0\" }).getUsage();\n status = \"active\";\n plan = data.plan;\n } catch (error) {\n failure = commandFailure(error);\n status = failure.info.code;\n process.exitCode = failure.exitCode;\n }\n }\n const details = {\n configured: Boolean(key),\n status,\n source: supplied?.source ?? (key ? \"os_credential_store\" : undefined),\n key: key ? redactApiKey(key) : undefined,\n plan,\n storage,\n error: failure?.info,\n };\n if (options.json) {\n printJson(details);\n } else {\n const lines = [\n row(\"Authentication\", status),\n row(\"Local credential\", storage),\n row(\"Key source\", details.source ?? \"Unavailable\"),\n row(\"Key\", details.key ?? \"Unavailable\"),\n row(\"Plan\", plan ?? \"Unavailable\"),\n row(\"Account / key name\", \"See Developer Console\"),\n ];\n if (failure) lines.push(failure.info.message);\n if (!key) lines.push(WEB_PAGES.keys);\n process.stdout.write(`${lines.join(\"\\n\")}\\n`);\n }\n}\n\nasync function logout(options: AuthOptions): Promise<void> {\n const removed = await credentials.remove();\n const environmentKeyConfigured = Boolean(process.env.NETRISKSCAN_API_KEY);\n if (options.json) {\n printJson({ removed, serverKeyRevoked: false, environmentKeyConfigured });\n } else {\n const local = removed ? \"Removed the local credential.\" : \"No local credential was saved.\";\n process.stdout.write(\n `${local} The server API key remains valid until revoked in the Developer Console.\\n`,\n );\n if (environmentKeyConfigured)\n process.stdout.write(\n \"NETRISKSCAN_API_KEY is still set in this shell. Clear it in the parent shell to stop using it.\\n\",\n );\n }\n}\n","import type { Command } from \"commander\";\nimport { CliError } from \"../output/errors.js\";\nimport { isInteractive, openBrowser, WEB_PAGES } from \"../utils/browser.js\";\nimport { ExitCode } from \"../utils/exitCode.js\";\nimport { isOfficialApi, requireSession, runCommand, type CommandOptions } from \"./session.js\";\n\nexport function registerBillingCommands(program: Command): void {\n for (const [name, page, description] of [\n [\"upgrade\", \"plans\", \"Open NetRiskScan plans and upgrades in your browser\"],\n [\"billing\", \"billing\", \"Open NetRiskScan subscription and billing management\"],\n ] as const) {\n program\n .command(name)\n .description(description)\n .option(\"--api-key <key>\", \"Developer API key (overrides the environment and OS store)\")\n .option(\"--json\", \"Return a machine-readable browser action with its URL\")\n .action((options: CommandOptions) =>\n runCommand(options, async () => {\n const url = WEB_PAGES[page];\n if (!isInteractive(options.json)) {\n throw new CliError(\n \"browser_required\",\n \"Continue in a browser using the Developer Console.\",\n ExitCode.InvalidArgument,\n url,\n );\n }\n if (!isOfficialApi(options)) {\n throw new CliError(\n \"official_api_required\",\n \"This command requires the official NetRiskScan Developer API.\",\n ExitCode.InvalidArgument,\n url,\n );\n }\n const { client } = await requireSession(options, false);\n const { data } = await client.getUsage();\n process.stderr.write(`Current plan: ${data.plan}\\n`);\n if (!(await openBrowser(page))) {\n throw new CliError(\n \"browser_open_failed\",\n \"Could not open the default browser. Open the URL directly.\",\n ExitCode.GeneralError,\n url,\n );\n }\n process.stdout.write(\n `Opened ${url}\\nSign in with the account that owns this key. Run npx netriskscan-cli usage to refresh the plan and quota after your changes.\\n`,\n );\n }),\n );\n }\n}\n"],"mappings":";;;AACA,SAAS,oBAAoB;AAC7B,SAAS,WAAAA,UAAS,QAAAC,aAAY;AAC9B,SAAS,qBAAqB;AAC9B,SAAS,SAAS,sB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,UAAU,OAAO,GAAG,CAAC;AAAA,CAAI;AAC9F,YAAQ,WAAW,SAAS;AAAA,EAC9B;AACF;","names":["dirname","join","chalk","chalk","LABEL_WIDTH","program","ora","program","ora","createInterface","chalk","chalk","program","createInterface","program","program","dirname","join"]}
package/dist/index.d.ts CHANGED
@@ -301,10 +301,11 @@ declare class NetRiskScanClient {
301
301
  * has no anonymous equivalent and requires an API key.
302
302
  */
303
303
  getUsage(options?: RequestOptions): Promise<ApiResult<UsageResponse>>;
304
+ private redact;
304
305
  private request;
305
306
  }
306
307
 
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"];
308
+ 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", "monthly_quota_exceeded", "anonymous_daily_limit_reached", "temporarily_unavailable"];
308
309
  type KnownErrorCode = (typeof KNOWN_ERROR_CODES)[number];
309
310
  /**
310
311
  * The anonymous trial's daily allowance is spent. Deterministic until the UTC reset, so unlike
@@ -337,6 +338,8 @@ interface NetRiskScanApiErrorOptions {
337
338
  requestId?: string;
338
339
  retryAfter?: number;
339
340
  anonymousUsage?: AnonymousLimitInfo;
341
+ quota?: QuotaInfo;
342
+ quotaResetAt?: string;
340
343
  }
341
344
  /** Thrown when the Developer API responds with a non-2xx status. */
342
345
  declare class NetRiskScanApiError extends NetRiskScanError {
@@ -346,6 +349,8 @@ declare class NetRiskScanApiError extends NetRiskScanError {
346
349
  readonly retryAfter?: number;
347
350
  /** Present when the server reported anonymous-trial allowance alongside the error. */
348
351
  readonly anonymousUsage?: AnonymousLimitInfo;
352
+ readonly quota?: QuotaInfo;
353
+ readonly quotaResetAt?: string;
349
354
  constructor(message: string, options: NetRiskScanApiErrorOptions);
350
355
  }
351
356
  interface NetRiskScanNetworkErrorOptions {