netriskscan-cli 1.6.2 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +34 -0
- package/README.md +157 -229
- package/dist/cli.js +1351 -443
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +8 -12
- package/dist/index.js +44 -11
- package/dist/index.js.map +1 -1
- package/package.json +6 -3
package/dist/cli.js
CHANGED
|
@@ -2,241 +2,13 @@
|
|
|
2
2
|
|
|
3
3
|
// src/cli.ts
|
|
4
4
|
import { readFileSync } from "fs";
|
|
5
|
-
import { dirname, join } from "path";
|
|
5
|
+
import { dirname as dirname2, join as join3 } from "path";
|
|
6
6
|
import { fileURLToPath } from "url";
|
|
7
7
|
import { Command, CommanderError } from "commander";
|
|
8
8
|
|
|
9
9
|
// src/commands/check.ts
|
|
10
10
|
import ora from "ora";
|
|
11
11
|
|
|
12
|
-
// src/client/errors.ts
|
|
13
|
-
var ANONYMOUS_DAILY_LIMIT_CODE = "anonymous_daily_limit_reached";
|
|
14
|
-
var NetRiskScanError = class extends Error {
|
|
15
|
-
constructor(message) {
|
|
16
|
-
super(message);
|
|
17
|
-
this.name = "NetRiskScanError";
|
|
18
|
-
}
|
|
19
|
-
};
|
|
20
|
-
var NetRiskScanConfigError = class extends NetRiskScanError {
|
|
21
|
-
constructor(message) {
|
|
22
|
-
super(message);
|
|
23
|
-
this.name = "NetRiskScanConfigError";
|
|
24
|
-
}
|
|
25
|
-
};
|
|
26
|
-
var NetRiskScanApiError = class extends NetRiskScanError {
|
|
27
|
-
status;
|
|
28
|
-
code;
|
|
29
|
-
requestId;
|
|
30
|
-
retryAfter;
|
|
31
|
-
/** Present when the server reported anonymous-trial allowance alongside the error. */
|
|
32
|
-
anonymousUsage;
|
|
33
|
-
constructor(message, options) {
|
|
34
|
-
super(message);
|
|
35
|
-
this.name = "NetRiskScanApiError";
|
|
36
|
-
this.status = options.status;
|
|
37
|
-
this.code = options.code;
|
|
38
|
-
this.requestId = options.requestId;
|
|
39
|
-
this.retryAfter = options.retryAfter;
|
|
40
|
-
this.anonymousUsage = options.anonymousUsage;
|
|
41
|
-
}
|
|
42
|
-
};
|
|
43
|
-
var NetRiskScanNetworkError = class extends NetRiskScanError {
|
|
44
|
-
cause;
|
|
45
|
-
requestId;
|
|
46
|
-
constructor(message, options = {}) {
|
|
47
|
-
super(message);
|
|
48
|
-
this.name = "NetRiskScanNetworkError";
|
|
49
|
-
this.cause = options.cause;
|
|
50
|
-
this.requestId = options.requestId;
|
|
51
|
-
}
|
|
52
|
-
};
|
|
53
|
-
|
|
54
|
-
// src/client/headers.ts
|
|
55
|
-
import { randomBytes } from "crypto";
|
|
56
|
-
var REQUEST_ID_PATTERN = /^req_[A-Za-z0-9_-]{8,56}$/;
|
|
57
|
-
function isValidRequestId(id) {
|
|
58
|
-
return REQUEST_ID_PATTERN.test(id);
|
|
59
|
-
}
|
|
60
|
-
function generateRequestId() {
|
|
61
|
-
return `req_${randomBytes(12).toString("hex")}`;
|
|
62
|
-
}
|
|
63
|
-
function parseIntHeader(value) {
|
|
64
|
-
if (value === null) return void 0;
|
|
65
|
-
const n = Number(value);
|
|
66
|
-
return Number.isFinite(n) ? n : void 0;
|
|
67
|
-
}
|
|
68
|
-
function parseRateLimit(headers) {
|
|
69
|
-
return {
|
|
70
|
-
limit: parseIntHeader(headers.get("x-ratelimit-limit")),
|
|
71
|
-
remaining: parseIntHeader(headers.get("x-ratelimit-remaining")),
|
|
72
|
-
reset: parseIntHeader(headers.get("x-ratelimit-reset"))
|
|
73
|
-
};
|
|
74
|
-
}
|
|
75
|
-
function parseQuota(headers) {
|
|
76
|
-
return {
|
|
77
|
-
limit: parseIntHeader(headers.get("x-quota-limit")),
|
|
78
|
-
used: parseIntHeader(headers.get("x-quota-used")),
|
|
79
|
-
remaining: parseIntHeader(headers.get("x-quota-remaining"))
|
|
80
|
-
};
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
// src/client/retry.ts
|
|
84
|
-
function isRetryableStatus(status) {
|
|
85
|
-
return status === 429 || status === 503;
|
|
86
|
-
}
|
|
87
|
-
function isRetryableFailure(status, code) {
|
|
88
|
-
if (code === ANONYMOUS_DAILY_LIMIT_CODE) return false;
|
|
89
|
-
return isRetryableStatus(status);
|
|
90
|
-
}
|
|
91
|
-
var BASE_DELAY_MS = 1e3;
|
|
92
|
-
var MAX_JITTER_MS = 250;
|
|
93
|
-
function computeBackoffMs(attempt, retryAfterSeconds) {
|
|
94
|
-
if (typeof retryAfterSeconds === "number" && Number.isFinite(retryAfterSeconds) && retryAfterSeconds >= 0) {
|
|
95
|
-
return retryAfterSeconds * 1e3;
|
|
96
|
-
}
|
|
97
|
-
const base = BASE_DELAY_MS * 2 ** Math.max(0, attempt - 1);
|
|
98
|
-
const jitter = Math.random() * MAX_JITTER_MS;
|
|
99
|
-
return base + jitter;
|
|
100
|
-
}
|
|
101
|
-
function sleep(ms) {
|
|
102
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
// src/client/NetRiskScanClient.ts
|
|
106
|
-
var DEFAULT_BASE_URL = "https://api.netriskscan.com";
|
|
107
|
-
var DEFAULT_TIMEOUT_MS = 1e4;
|
|
108
|
-
var DEFAULT_MAX_RETRIES = 3;
|
|
109
|
-
function isAbortError(err) {
|
|
110
|
-
return err instanceof Error && err.name === "AbortError";
|
|
111
|
-
}
|
|
112
|
-
async function safeJson(res) {
|
|
113
|
-
try {
|
|
114
|
-
return await res.json();
|
|
115
|
-
} catch {
|
|
116
|
-
return void 0;
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
function parseAnonymousLimitInfo(body) {
|
|
120
|
-
const error = body?.error;
|
|
121
|
-
if (!error) return void 0;
|
|
122
|
-
const { dailyLimit, used, remaining, resetAt, signupUrl } = error;
|
|
123
|
-
if (dailyLimit === void 0 && used === void 0 && remaining === void 0 && resetAt === void 0 && signupUrl === void 0) {
|
|
124
|
-
return void 0;
|
|
125
|
-
}
|
|
126
|
-
return { dailyLimit, used, remaining, resetAt, signupUrl };
|
|
127
|
-
}
|
|
128
|
-
var NetRiskScanClient = class {
|
|
129
|
-
apiKey;
|
|
130
|
-
baseUrl;
|
|
131
|
-
timeout;
|
|
132
|
-
maxRetries;
|
|
133
|
-
constructor(options = {}) {
|
|
134
|
-
this.apiKey = options.apiKey || void 0;
|
|
135
|
-
this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
136
|
-
this.timeout = options.timeout ?? DEFAULT_TIMEOUT_MS;
|
|
137
|
-
this.maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;
|
|
138
|
-
}
|
|
139
|
-
async checkIp(ip, options = {}) {
|
|
140
|
-
return this.request(`/v1/ip-risk/${encodeURIComponent(ip)}`, options);
|
|
141
|
-
}
|
|
142
|
-
/**
|
|
143
|
-
* Account plan, billing period and quota. Unlike {@link checkIp} this is account data, so it
|
|
144
|
-
* has no anonymous equivalent and requires an API key.
|
|
145
|
-
*/
|
|
146
|
-
async getUsage(options = {}) {
|
|
147
|
-
if (!this.apiKey) {
|
|
148
|
-
throw new NetRiskScanConfigError("An API key is required to query account usage.");
|
|
149
|
-
}
|
|
150
|
-
return this.request("/v1/usage", options);
|
|
151
|
-
}
|
|
152
|
-
async request(path, options) {
|
|
153
|
-
const requestId = options.requestId && isValidRequestId(options.requestId) ? options.requestId : generateRequestId();
|
|
154
|
-
let attempt = 0;
|
|
155
|
-
while (true) {
|
|
156
|
-
const timeoutController = new AbortController();
|
|
157
|
-
const timer = setTimeout(() => timeoutController.abort(), this.timeout);
|
|
158
|
-
const onExternalAbort = () => timeoutController.abort();
|
|
159
|
-
options.signal?.addEventListener("abort", onExternalAbort);
|
|
160
|
-
try {
|
|
161
|
-
const headers = {
|
|
162
|
-
Accept: "application/json",
|
|
163
|
-
"X-Request-Id": requestId
|
|
164
|
-
};
|
|
165
|
-
if (this.apiKey) {
|
|
166
|
-
headers.Authorization = `Bearer ${this.apiKey}`;
|
|
167
|
-
}
|
|
168
|
-
const res = await fetch(`${this.baseUrl}${path}`, {
|
|
169
|
-
method: "GET",
|
|
170
|
-
headers,
|
|
171
|
-
signal: timeoutController.signal
|
|
172
|
-
});
|
|
173
|
-
const rateLimit = parseRateLimit(res.headers);
|
|
174
|
-
const quota = parseQuota(res.headers);
|
|
175
|
-
const responseRequestId = res.headers.get("x-request-id") ?? requestId;
|
|
176
|
-
if (res.ok) {
|
|
177
|
-
const data = await res.json();
|
|
178
|
-
return { data, meta: { requestId: responseRequestId, rateLimit, quota } };
|
|
179
|
-
}
|
|
180
|
-
const body = await safeJson(res);
|
|
181
|
-
const retryAfterHeader = res.headers.get("retry-after");
|
|
182
|
-
const retryAfter = retryAfterHeader !== null ? Number(retryAfterHeader) : void 0;
|
|
183
|
-
if (isRetryableFailure(res.status, body?.error?.code) && attempt < this.maxRetries) {
|
|
184
|
-
attempt += 1;
|
|
185
|
-
await sleep(computeBackoffMs(attempt, retryAfter));
|
|
186
|
-
continue;
|
|
187
|
-
}
|
|
188
|
-
throw new NetRiskScanApiError(body?.error?.message ?? res.statusText, {
|
|
189
|
-
status: res.status,
|
|
190
|
-
code: body?.error?.code ?? "unknown_error",
|
|
191
|
-
requestId: body?.error?.requestId ?? responseRequestId,
|
|
192
|
-
retryAfter,
|
|
193
|
-
anonymousUsage: parseAnonymousLimitInfo(body)
|
|
194
|
-
});
|
|
195
|
-
} catch (err) {
|
|
196
|
-
if (err instanceof NetRiskScanApiError) {
|
|
197
|
-
throw err;
|
|
198
|
-
}
|
|
199
|
-
if (isAbortError(err)) {
|
|
200
|
-
if (options.signal?.aborted) {
|
|
201
|
-
throw err;
|
|
202
|
-
}
|
|
203
|
-
throw new NetRiskScanNetworkError(`Request timed out after ${this.timeout}ms`, {
|
|
204
|
-
cause: err,
|
|
205
|
-
requestId
|
|
206
|
-
});
|
|
207
|
-
}
|
|
208
|
-
throw new NetRiskScanNetworkError(
|
|
209
|
-
err instanceof Error ? err.message : "Network request failed",
|
|
210
|
-
{
|
|
211
|
-
cause: err,
|
|
212
|
-
requestId
|
|
213
|
-
}
|
|
214
|
-
);
|
|
215
|
-
} finally {
|
|
216
|
-
clearTimeout(timer);
|
|
217
|
-
options.signal?.removeEventListener("abort", onExternalAbort);
|
|
218
|
-
}
|
|
219
|
-
}
|
|
220
|
-
}
|
|
221
|
-
};
|
|
222
|
-
|
|
223
|
-
// src/utils/env.ts
|
|
224
|
-
function resolveOptionalApiKey(cliValue) {
|
|
225
|
-
return cliValue || process.env.NETRISKSCAN_API_KEY || void 0;
|
|
226
|
-
}
|
|
227
|
-
function resolveRequiredApiKey(cliValue) {
|
|
228
|
-
const apiKey = resolveOptionalApiKey(cliValue);
|
|
229
|
-
if (!apiKey) {
|
|
230
|
-
throw new NetRiskScanConfigError(
|
|
231
|
-
"An API key is required for the usage command.\n\nSet NETRISKSCAN_API_KEY or use --api-key."
|
|
232
|
-
);
|
|
233
|
-
}
|
|
234
|
-
return apiKey;
|
|
235
|
-
}
|
|
236
|
-
function resolveBaseUrl(cliValue) {
|
|
237
|
-
return cliValue ?? process.env.NETRISKSCAN_BASE_URL;
|
|
238
|
-
}
|
|
239
|
-
|
|
240
12
|
// src/utils/ip.ts
|
|
241
13
|
import { isIP } from "net";
|
|
242
14
|
function isValidIp(value) {
|
|
@@ -257,13 +29,18 @@ var ExitCode = {
|
|
|
257
29
|
function exitCodeForApiErrorCode(code) {
|
|
258
30
|
switch (code) {
|
|
259
31
|
case "invalid_api_key":
|
|
32
|
+
case "api_key_invalid":
|
|
33
|
+
case "api_key_required":
|
|
34
|
+
case "api_key_expired":
|
|
260
35
|
case "api_key_disabled":
|
|
261
36
|
case "scope_not_allowed":
|
|
37
|
+
case "subscription_required":
|
|
262
38
|
return ExitCode.AuthError;
|
|
263
39
|
// The anonymous daily trial is an allowance like any other, so it reuses code 5 rather than
|
|
264
40
|
// adding an eighth exit code that every script would have to learn.
|
|
265
41
|
case "rate_limit_exceeded":
|
|
266
42
|
case "quota_exceeded":
|
|
43
|
+
case "monthly_quota_exceeded":
|
|
267
44
|
case "anonymous_daily_limit_reached":
|
|
268
45
|
return ExitCode.RateLimitOrQuota;
|
|
269
46
|
default:
|
|
@@ -274,6 +51,12 @@ function exitCodeForApiErrorCode(code) {
|
|
|
274
51
|
// src/output/human.ts
|
|
275
52
|
import chalk from "chalk";
|
|
276
53
|
|
|
54
|
+
// src/utils/quotaWarnings.ts
|
|
55
|
+
import { createHash } from "crypto";
|
|
56
|
+
import { mkdir, stat, unlink, writeFile } from "fs/promises";
|
|
57
|
+
import { homedir } from "os";
|
|
58
|
+
import { dirname, join } from "path";
|
|
59
|
+
|
|
277
60
|
// src/output/format.ts
|
|
278
61
|
function formatTriState(value) {
|
|
279
62
|
if (value === true) return "Yes";
|
|
@@ -350,9 +133,6 @@ function formatNullable(value) {
|
|
|
350
133
|
function formatNumber(value) {
|
|
351
134
|
return value.toLocaleString("en-US");
|
|
352
135
|
}
|
|
353
|
-
function formatDate(iso) {
|
|
354
|
-
return iso.slice(0, 10);
|
|
355
|
-
}
|
|
356
136
|
var LABEL_WIDTH = 18;
|
|
357
137
|
function row(label, value) {
|
|
358
138
|
return `${label.padEnd(LABEL_WIDTH)}${value}`;
|
|
@@ -369,6 +149,105 @@ function formatUtcTimestamp(iso) {
|
|
|
369
149
|
return `${date.getUTCFullYear()}-${pad(date.getUTCMonth() + 1)}-${pad(date.getUTCDate())} ${pad(date.getUTCHours())}:${pad(date.getUTCMinutes())} UTC`;
|
|
370
150
|
}
|
|
371
151
|
|
|
152
|
+
// src/utils/browser.ts
|
|
153
|
+
import { spawn } from "child_process";
|
|
154
|
+
var WEB_PAGES = {
|
|
155
|
+
keys: "https://www.netriskscan.com/developer/keys",
|
|
156
|
+
plans: "https://www.netriskscan.com/pricing.html",
|
|
157
|
+
billing: "https://www.netriskscan.com/developer/billing"
|
|
158
|
+
};
|
|
159
|
+
var AUTHORIZATION_PAGE = "https://www.netriskscan.com/developer/cli";
|
|
160
|
+
function isInteractive(machineOutput) {
|
|
161
|
+
const ci = process.env.CI?.trim().toLowerCase();
|
|
162
|
+
return Boolean(
|
|
163
|
+
!machineOutput && process.stdin.isTTY && process.stdout.isTTY && (!ci || ci === "false" || ci === "0") && !process.env.GITHUB_ACTIONS && !process.env.TF_BUILD
|
|
164
|
+
);
|
|
165
|
+
}
|
|
166
|
+
async function openBrowser(page) {
|
|
167
|
+
return launch(WEB_PAGES[page]);
|
|
168
|
+
}
|
|
169
|
+
async function openAuthorizationBrowser(url) {
|
|
170
|
+
const destination = new URL(url);
|
|
171
|
+
if (destination.href.split("#", 1)[0] !== AUTHORIZATION_PAGE) return false;
|
|
172
|
+
return launch(destination.href);
|
|
173
|
+
}
|
|
174
|
+
async function launch(url) {
|
|
175
|
+
const [command, ...args] = process.platform === "win32" ? ["rundll32.exe", "url.dll,FileProtocolHandler", url] : process.platform === "darwin" ? ["open", url] : ["xdg-open", url];
|
|
176
|
+
const env = { ...process.env };
|
|
177
|
+
for (const name of Object.keys(env)) {
|
|
178
|
+
if (name.toUpperCase() === "NETRISKSCAN_API_KEY") delete env[name];
|
|
179
|
+
}
|
|
180
|
+
return new Promise((resolve) => {
|
|
181
|
+
const child = spawn(command, args, { env, detached: true, stdio: "ignore", windowsHide: true });
|
|
182
|
+
const timer = setTimeout(() => finish(true), 400);
|
|
183
|
+
function finish(opened) {
|
|
184
|
+
clearTimeout(timer);
|
|
185
|
+
child.unref();
|
|
186
|
+
resolve(opened);
|
|
187
|
+
}
|
|
188
|
+
child.once("error", () => finish(false));
|
|
189
|
+
child.once("exit", (code) => finish(code === 0));
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// src/utils/quotaWarnings.ts
|
|
194
|
+
var WARNING_LEVELS = [80, 95];
|
|
195
|
+
function quotaUsagePercent(quota) {
|
|
196
|
+
const { limit, used } = quota;
|
|
197
|
+
return limit !== void 0 && limit > 0 && used !== void 0 ? used / limit * 100 : void 0;
|
|
198
|
+
}
|
|
199
|
+
function marker(key, limit, level) {
|
|
200
|
+
const fingerprint = createHash("sha256").update(key).digest("hex");
|
|
201
|
+
return join(homedir(), ".netriskscan", "quota-warnings", `${fingerprint}-${limit}-${level}`);
|
|
202
|
+
}
|
|
203
|
+
async function rearmQuotaWarnings(key, quota, periodStart) {
|
|
204
|
+
const { limit } = quota;
|
|
205
|
+
const percent = quotaUsagePercent(quota);
|
|
206
|
+
if (limit === void 0 || percent === void 0) return;
|
|
207
|
+
const start = periodStart ? Date.parse(periodStart) : NaN;
|
|
208
|
+
await Promise.all(
|
|
209
|
+
WARNING_LEVELS.map(async (level) => {
|
|
210
|
+
const path = marker(key, limit, level);
|
|
211
|
+
try {
|
|
212
|
+
if (percent < level || Number.isFinite(start) && (await stat(path)).mtimeMs < start) {
|
|
213
|
+
await unlink(path);
|
|
214
|
+
}
|
|
215
|
+
} catch {
|
|
216
|
+
}
|
|
217
|
+
})
|
|
218
|
+
);
|
|
219
|
+
}
|
|
220
|
+
async function warnAboutQuota(key, quota) {
|
|
221
|
+
const { limit, used, remaining } = quota;
|
|
222
|
+
const percent = quotaUsagePercent(quota);
|
|
223
|
+
if (limit === void 0 || used === void 0 || remaining === void 0 || percent === void 0)
|
|
224
|
+
return;
|
|
225
|
+
await rearmQuotaWarnings(key, quota);
|
|
226
|
+
let warnedAt;
|
|
227
|
+
for (const level of WARNING_LEVELS) {
|
|
228
|
+
if (percent < level) break;
|
|
229
|
+
const path = marker(key, limit, level);
|
|
230
|
+
try {
|
|
231
|
+
await mkdir(dirname(path), { recursive: true, mode: 448 });
|
|
232
|
+
await writeFile(path, "", { flag: "wx", mode: 384 });
|
|
233
|
+
warnedAt = level;
|
|
234
|
+
} catch {
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
if (warnedAt === void 0) return;
|
|
238
|
+
process.stderr.write(
|
|
239
|
+
[
|
|
240
|
+
"",
|
|
241
|
+
warnedAt === WARNING_LEVELS[1] ? "Monthly API quota almost exhausted." : "Monthly API quota warning.",
|
|
242
|
+
row("Usage", `${formatNumber(used)} / ${formatNumber(limit)}`),
|
|
243
|
+
row("Remaining", formatNumber(remaining)),
|
|
244
|
+
"For more quota, run npx netriskscan-cli upgrade",
|
|
245
|
+
WEB_PAGES.plans,
|
|
246
|
+
""
|
|
247
|
+
].join("\n") + "\n"
|
|
248
|
+
);
|
|
249
|
+
}
|
|
250
|
+
|
|
372
251
|
// src/output/human.ts
|
|
373
252
|
function anonymousUsageLines(usage) {
|
|
374
253
|
const lines = [];
|
|
@@ -542,12 +421,16 @@ function renderUsageResult(data) {
|
|
|
542
421
|
lines.push(row("Used", formatNumber(data.units.used)));
|
|
543
422
|
lines.push(row("Remaining", formatNumber(data.units.remaining)));
|
|
544
423
|
lines.push(row("Limit", formatNumber(data.units.limit)));
|
|
424
|
+
const percent = quotaUsagePercent(data.units);
|
|
425
|
+
if (percent !== void 0) lines.push(row("Used (%)", `${percent.toFixed(1)}%`));
|
|
545
426
|
lines.push("");
|
|
546
427
|
lines.push(chalk.bold("Rate limit"));
|
|
547
428
|
lines.push(row("Requests / minute", formatNumber(data.rateLimit.requestsPerMinute)));
|
|
548
429
|
lines.push("");
|
|
549
|
-
lines.push(chalk.bold("
|
|
550
|
-
lines.push(
|
|
430
|
+
lines.push(chalk.bold("Monthly quota period"));
|
|
431
|
+
lines.push(row("Started", formatUtcTimestamp(data.period.start) ?? data.period.start));
|
|
432
|
+
lines.push(row("Resets", formatUtcTimestamp(data.period.end) ?? data.period.end));
|
|
433
|
+
lines.push(row("Upgrade plans", WEB_PAGES.plans));
|
|
551
434
|
process.stdout.write(`${lines.join("\n")}
|
|
552
435
|
`);
|
|
553
436
|
}
|
|
@@ -560,41 +443,162 @@ function printJson(data) {
|
|
|
560
443
|
|
|
561
444
|
// src/output/errors.ts
|
|
562
445
|
import chalk2 from "chalk";
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
process.stderr.write(
|
|
569
|
-
"\nGet a free API key (no credit card required): https://www.netriskscan.com\n"
|
|
570
|
-
);
|
|
571
|
-
}
|
|
446
|
+
|
|
447
|
+
// src/client/errors.ts
|
|
448
|
+
var ANONYMOUS_DAILY_LIMIT_CODE = "anonymous_daily_limit_reached";
|
|
449
|
+
function isMonthlyQuotaError(code) {
|
|
450
|
+
return code === "quota_exceeded" || code === "monthly_quota_exceeded";
|
|
572
451
|
}
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
""
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
452
|
+
var NetRiskScanError = class extends Error {
|
|
453
|
+
constructor(message) {
|
|
454
|
+
super(message);
|
|
455
|
+
this.name = "NetRiskScanError";
|
|
456
|
+
}
|
|
457
|
+
};
|
|
458
|
+
var NetRiskScanConfigError = class extends NetRiskScanError {
|
|
459
|
+
constructor(message) {
|
|
460
|
+
super(message);
|
|
461
|
+
this.name = "NetRiskScanConfigError";
|
|
462
|
+
}
|
|
463
|
+
};
|
|
464
|
+
var NetRiskScanApiError = class extends NetRiskScanError {
|
|
465
|
+
status;
|
|
466
|
+
code;
|
|
467
|
+
requestId;
|
|
468
|
+
retryAfter;
|
|
469
|
+
/** Present when the server reported anonymous-trial allowance alongside the error. */
|
|
470
|
+
anonymousUsage;
|
|
471
|
+
quota;
|
|
472
|
+
quotaResetAt;
|
|
473
|
+
constructor(message, options) {
|
|
474
|
+
super(message);
|
|
475
|
+
this.name = "NetRiskScanApiError";
|
|
476
|
+
this.status = options.status;
|
|
477
|
+
this.code = options.code;
|
|
478
|
+
this.requestId = options.requestId;
|
|
479
|
+
this.retryAfter = options.retryAfter;
|
|
480
|
+
this.anonymousUsage = options.anonymousUsage;
|
|
481
|
+
this.quota = options.quota;
|
|
482
|
+
this.quotaResetAt = options.quotaResetAt;
|
|
483
|
+
}
|
|
484
|
+
};
|
|
485
|
+
var NetRiskScanNetworkError = class extends NetRiskScanError {
|
|
486
|
+
cause;
|
|
487
|
+
requestId;
|
|
488
|
+
constructor(message, options = {}) {
|
|
489
|
+
super(message);
|
|
490
|
+
this.name = "NetRiskScanNetworkError";
|
|
491
|
+
this.cause = options.cause;
|
|
492
|
+
this.requestId = options.requestId;
|
|
493
|
+
}
|
|
494
|
+
};
|
|
495
|
+
|
|
496
|
+
// src/output/jsonl.ts
|
|
497
|
+
function printJsonLine(data) {
|
|
498
|
+
process.stdout.write(`${JSON.stringify(data)}
|
|
499
|
+
`);
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
// src/output/errors.ts
|
|
503
|
+
var CliError = class extends Error {
|
|
504
|
+
constructor(code, message, exitCode, url) {
|
|
505
|
+
super(message);
|
|
506
|
+
this.code = code;
|
|
507
|
+
this.exitCode = exitCode;
|
|
508
|
+
this.url = url;
|
|
509
|
+
}
|
|
510
|
+
code;
|
|
511
|
+
exitCode;
|
|
512
|
+
url;
|
|
513
|
+
};
|
|
514
|
+
function commandFailure(cause) {
|
|
515
|
+
if (cause instanceof NetRiskScanApiError) {
|
|
516
|
+
return {
|
|
517
|
+
cause,
|
|
518
|
+
exitCode: exitCodeForApiErrorCode(cause.code),
|
|
519
|
+
info: {
|
|
520
|
+
code: cause.code,
|
|
521
|
+
message: cause.message,
|
|
522
|
+
status: cause.status,
|
|
523
|
+
requestId: cause.requestId,
|
|
524
|
+
retryAfter: cause.retryAfter,
|
|
525
|
+
quota: cause.quota && Object.values(cause.quota).some((value) => value !== void 0) ? cause.quota : void 0,
|
|
526
|
+
resetAt: cause.quotaResetAt,
|
|
527
|
+
upgradeUrl: isMonthlyQuotaError(cause.code) || cause.code === "subscription_required" ? WEB_PAGES.plans : void 0,
|
|
528
|
+
action: authenticationAction(cause.code)
|
|
529
|
+
}
|
|
530
|
+
};
|
|
531
|
+
}
|
|
532
|
+
if (cause instanceof NetRiskScanNetworkError) {
|
|
533
|
+
return {
|
|
534
|
+
cause,
|
|
535
|
+
exitCode: ExitCode.ApiError,
|
|
536
|
+
info: { code: "network_error", message: cause.message, requestId: cause.requestId }
|
|
537
|
+
};
|
|
538
|
+
}
|
|
539
|
+
if (cause instanceof CliError) {
|
|
540
|
+
return {
|
|
541
|
+
cause,
|
|
542
|
+
exitCode: cause.exitCode,
|
|
543
|
+
info: { code: cause.code, message: cause.message, url: cause.url }
|
|
544
|
+
};
|
|
545
|
+
}
|
|
546
|
+
return {
|
|
547
|
+
cause,
|
|
548
|
+
exitCode: ExitCode.GeneralError,
|
|
549
|
+
info: {
|
|
550
|
+
code: "cli_error",
|
|
551
|
+
message: cause instanceof Error ? cause.message : "Unexpected CLI error."
|
|
552
|
+
}
|
|
553
|
+
};
|
|
554
|
+
}
|
|
555
|
+
function authenticationAction(code) {
|
|
556
|
+
switch (code) {
|
|
557
|
+
case "api_key_required":
|
|
558
|
+
case "invalid_api_key":
|
|
559
|
+
case "api_key_invalid":
|
|
560
|
+
case "api_key_expired":
|
|
561
|
+
return "Verify the configured key or run npx netriskscan-cli auth login.";
|
|
562
|
+
case "api_key_disabled":
|
|
563
|
+
return "Check the key, account, and subscription status in the Developer Console.";
|
|
564
|
+
case "subscription_required":
|
|
565
|
+
return "Run npx netriskscan-cli upgrade to view available plans.";
|
|
566
|
+
default:
|
|
567
|
+
return void 0;
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
function reportFailure(failure, options = {}) {
|
|
571
|
+
const { info, cause } = failure;
|
|
572
|
+
if (options.jsonl) {
|
|
573
|
+
printJsonLine({ error: info });
|
|
574
|
+
} else if (options.json) {
|
|
575
|
+
printJson({ error: info });
|
|
576
|
+
} else if (isMonthlyQuotaError(info.code)) {
|
|
577
|
+
const lines = ["", chalk2.yellow("Monthly API quota exceeded.")];
|
|
578
|
+
if (info.plan) lines.push(row("Current plan", info.plan));
|
|
579
|
+
if (info.quota?.limit !== void 0)
|
|
580
|
+
lines.push(row("Monthly limit", formatNumber(info.quota.limit)));
|
|
581
|
+
if (info.quota?.used !== void 0) lines.push(row("Used", formatNumber(info.quota.used)));
|
|
582
|
+
if (info.quota?.remaining !== void 0)
|
|
583
|
+
lines.push(row("Remaining", formatNumber(info.quota.remaining)));
|
|
584
|
+
const reset = formatUtcTimestamp(info.resetAt);
|
|
585
|
+
if (reset) lines.push(row("Resets", reset));
|
|
586
|
+
lines.push("", "For more quota, run npx netriskscan-cli upgrade", info.upgradeUrl ?? "", "");
|
|
587
|
+
process.stderr.write(lines.join("\n"));
|
|
588
|
+
} else if (cause instanceof NetRiskScanApiError) {
|
|
589
|
+
printApiError(cause, options);
|
|
590
|
+
if (info.action) process.stderr.write(`${info.action}
|
|
591
|
+
`);
|
|
592
|
+
if (info.upgradeUrl) process.stderr.write(`${info.upgradeUrl}
|
|
593
|
+
`);
|
|
594
|
+
} else if (cause instanceof NetRiskScanNetworkError) {
|
|
595
|
+
printNetworkError(cause, options);
|
|
596
|
+
} else {
|
|
597
|
+
process.stderr.write(`Error: ${info.message}
|
|
598
|
+
`);
|
|
599
|
+
if (info.url) process.stderr.write(`${info.url}
|
|
600
|
+
`);
|
|
593
601
|
}
|
|
594
|
-
lines.push(chalk2.bold("Usage"), ...usageLines, "");
|
|
595
|
-
lines.push(chalk2.bold("Get more queries"), usage?.signupUrl || SIGNUP_URL, "");
|
|
596
|
-
process.stderr.write(`${lines.join("\n")}
|
|
597
|
-
`);
|
|
598
602
|
}
|
|
599
603
|
var LABEL_WIDTH2 = 11;
|
|
600
604
|
function printApiError(err, options = {}) {
|
|
@@ -633,6 +637,739 @@ ${err.message}
|
|
|
633
637
|
}
|
|
634
638
|
}
|
|
635
639
|
|
|
640
|
+
// src/commands/session.ts
|
|
641
|
+
import { createInterface } from "readline/promises";
|
|
642
|
+
|
|
643
|
+
// src/client/headers.ts
|
|
644
|
+
import { randomBytes } from "crypto";
|
|
645
|
+
var REQUEST_ID_PATTERN = /^req_[A-Za-z0-9_-]{8,56}$/;
|
|
646
|
+
function isValidRequestId(id) {
|
|
647
|
+
return REQUEST_ID_PATTERN.test(id);
|
|
648
|
+
}
|
|
649
|
+
function generateRequestId() {
|
|
650
|
+
return `req_${randomBytes(12).toString("hex")}`;
|
|
651
|
+
}
|
|
652
|
+
function parseIntHeader(value) {
|
|
653
|
+
if (value === null || !/^\d+$/.test(value)) return void 0;
|
|
654
|
+
const n = Number(value);
|
|
655
|
+
return Number.isSafeInteger(n) ? n : void 0;
|
|
656
|
+
}
|
|
657
|
+
function parseRateLimit(headers) {
|
|
658
|
+
return {
|
|
659
|
+
limit: parseIntHeader(headers.get("x-ratelimit-limit")),
|
|
660
|
+
remaining: parseIntHeader(headers.get("x-ratelimit-remaining")),
|
|
661
|
+
reset: parseIntHeader(headers.get("x-ratelimit-reset"))
|
|
662
|
+
};
|
|
663
|
+
}
|
|
664
|
+
function parseQuota(headers) {
|
|
665
|
+
return {
|
|
666
|
+
limit: parseIntHeader(headers.get("x-quota-limit")),
|
|
667
|
+
used: parseIntHeader(headers.get("x-quota-used")),
|
|
668
|
+
remaining: parseIntHeader(headers.get("x-quota-remaining"))
|
|
669
|
+
};
|
|
670
|
+
}
|
|
671
|
+
function redactApiKey(key) {
|
|
672
|
+
if (key.length <= 13) return "*".repeat(key.length);
|
|
673
|
+
return `${key.slice(0, 9)}${"*".repeat(4)}${key.slice(-4)}`;
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
// src/client/retry.ts
|
|
677
|
+
function isRetryableStatus(status) {
|
|
678
|
+
return status === 429 || status === 503;
|
|
679
|
+
}
|
|
680
|
+
function isRetryableFailure(status, code) {
|
|
681
|
+
if (code === ANONYMOUS_DAILY_LIMIT_CODE || isMonthlyQuotaError(code)) return false;
|
|
682
|
+
return isRetryableStatus(status);
|
|
683
|
+
}
|
|
684
|
+
var BASE_DELAY_MS = 1e3;
|
|
685
|
+
var MAX_JITTER_MS = 250;
|
|
686
|
+
function computeBackoffMs(attempt, retryAfterSeconds) {
|
|
687
|
+
if (typeof retryAfterSeconds === "number" && Number.isFinite(retryAfterSeconds) && retryAfterSeconds >= 0) {
|
|
688
|
+
return retryAfterSeconds * 1e3;
|
|
689
|
+
}
|
|
690
|
+
const base = BASE_DELAY_MS * 2 ** Math.max(0, attempt - 1);
|
|
691
|
+
const jitter = Math.random() * MAX_JITTER_MS;
|
|
692
|
+
return base + jitter;
|
|
693
|
+
}
|
|
694
|
+
function sleep(ms) {
|
|
695
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
// src/client/NetRiskScanClient.ts
|
|
699
|
+
var DEFAULT_BASE_URL = "https://api.netriskscan.com";
|
|
700
|
+
var DEFAULT_TIMEOUT_MS = 1e4;
|
|
701
|
+
var DEFAULT_MAX_RETRIES = 3;
|
|
702
|
+
function isAbortError(err) {
|
|
703
|
+
return err instanceof Error && err.name === "AbortError";
|
|
704
|
+
}
|
|
705
|
+
function quotaResetAt(headers, seconds) {
|
|
706
|
+
const quotaReset = headers.get("x-quota-reset");
|
|
707
|
+
if (quotaReset && /^\d+$/.test(quotaReset)) {
|
|
708
|
+
const reset2 = new Date(Number(quotaReset) * 1e3);
|
|
709
|
+
if (Number.isFinite(reset2.getTime())) return reset2.toISOString();
|
|
710
|
+
}
|
|
711
|
+
if (seconds === void 0 || !Number.isFinite(seconds) || seconds < 0) return void 0;
|
|
712
|
+
const responseDate = Date.parse(headers.get("date") ?? "");
|
|
713
|
+
const reset = new Date(
|
|
714
|
+
(Number.isFinite(responseDate) ? responseDate : Date.now()) + seconds * 1e3
|
|
715
|
+
);
|
|
716
|
+
return Number.isFinite(reset.getTime()) ? reset.toISOString() : void 0;
|
|
717
|
+
}
|
|
718
|
+
async function safeJson(res) {
|
|
719
|
+
try {
|
|
720
|
+
return await res.json();
|
|
721
|
+
} catch {
|
|
722
|
+
return void 0;
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
function parseAnonymousLimitInfo(body) {
|
|
726
|
+
const error = body?.error;
|
|
727
|
+
if (!error) return void 0;
|
|
728
|
+
const { dailyLimit, used, remaining, resetAt, signupUrl } = error;
|
|
729
|
+
if (dailyLimit === void 0 && used === void 0 && remaining === void 0 && resetAt === void 0 && signupUrl === void 0) {
|
|
730
|
+
return void 0;
|
|
731
|
+
}
|
|
732
|
+
return { dailyLimit, used, remaining, resetAt, signupUrl };
|
|
733
|
+
}
|
|
734
|
+
var NetRiskScanClient = class {
|
|
735
|
+
apiKey;
|
|
736
|
+
baseUrl;
|
|
737
|
+
timeout;
|
|
738
|
+
maxRetries;
|
|
739
|
+
constructor(options = {}) {
|
|
740
|
+
this.apiKey = options.apiKey || void 0;
|
|
741
|
+
this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
742
|
+
this.timeout = options.timeout ?? DEFAULT_TIMEOUT_MS;
|
|
743
|
+
this.maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;
|
|
744
|
+
}
|
|
745
|
+
async checkIp(ip, options = {}) {
|
|
746
|
+
return this.request(`/v1/ip-risk/${encodeURIComponent(ip)}`, options);
|
|
747
|
+
}
|
|
748
|
+
/**
|
|
749
|
+
* Account plan, billing period and quota. Unlike {@link checkIp} this is account data, so it
|
|
750
|
+
* has no anonymous equivalent and requires an API key.
|
|
751
|
+
*/
|
|
752
|
+
async getUsage(options = {}) {
|
|
753
|
+
if (!this.apiKey) {
|
|
754
|
+
throw new NetRiskScanConfigError("An API key is required to query account usage.");
|
|
755
|
+
}
|
|
756
|
+
return this.request("/v1/usage", options);
|
|
757
|
+
}
|
|
758
|
+
redact(value) {
|
|
759
|
+
return this.apiKey ? value.replaceAll(this.apiKey, "[REDACTED]") : value;
|
|
760
|
+
}
|
|
761
|
+
async request(path, options) {
|
|
762
|
+
const requestId = options.requestId && isValidRequestId(options.requestId) ? options.requestId : generateRequestId();
|
|
763
|
+
let attempt = 0;
|
|
764
|
+
while (true) {
|
|
765
|
+
const timeoutController = new AbortController();
|
|
766
|
+
const timer = setTimeout(() => timeoutController.abort(), this.timeout);
|
|
767
|
+
const onExternalAbort = () => timeoutController.abort();
|
|
768
|
+
options.signal?.addEventListener("abort", onExternalAbort);
|
|
769
|
+
try {
|
|
770
|
+
const headers = {
|
|
771
|
+
Accept: "application/json",
|
|
772
|
+
"X-Request-Id": requestId
|
|
773
|
+
};
|
|
774
|
+
if (this.apiKey) {
|
|
775
|
+
headers.Authorization = `Bearer ${this.apiKey}`;
|
|
776
|
+
}
|
|
777
|
+
const res = await fetch(`${this.baseUrl}${path}`, {
|
|
778
|
+
method: "GET",
|
|
779
|
+
headers,
|
|
780
|
+
redirect: this.apiKey ? "error" : "follow",
|
|
781
|
+
signal: timeoutController.signal
|
|
782
|
+
});
|
|
783
|
+
const rateLimit = parseRateLimit(res.headers);
|
|
784
|
+
const quota = parseQuota(res.headers);
|
|
785
|
+
const responseRequestId = this.redact(res.headers.get("x-request-id") ?? requestId);
|
|
786
|
+
if (res.ok) {
|
|
787
|
+
const data = await res.json();
|
|
788
|
+
return { data, meta: { requestId: responseRequestId, rateLimit, quota } };
|
|
789
|
+
}
|
|
790
|
+
const body = await safeJson(res);
|
|
791
|
+
const retryAfterHeader = res.headers.get("retry-after");
|
|
792
|
+
const delay = retryAfterHeader?.trim() ? Number(retryAfterHeader) : NaN;
|
|
793
|
+
const retryAfter = Number.isFinite(delay) && delay >= 0 ? delay : void 0;
|
|
794
|
+
const code = body?.error?.code ?? "unknown_error";
|
|
795
|
+
if (isRetryableFailure(res.status, code) && attempt < this.maxRetries) {
|
|
796
|
+
attempt += 1;
|
|
797
|
+
await sleep(computeBackoffMs(attempt, retryAfter));
|
|
798
|
+
continue;
|
|
799
|
+
}
|
|
800
|
+
throw new NetRiskScanApiError(this.redact(body?.error?.message ?? res.statusText), {
|
|
801
|
+
status: res.status,
|
|
802
|
+
code: this.redact(code),
|
|
803
|
+
requestId: this.redact(body?.error?.requestId ?? responseRequestId),
|
|
804
|
+
retryAfter,
|
|
805
|
+
anonymousUsage: parseAnonymousLimitInfo(body),
|
|
806
|
+
quota: isMonthlyQuotaError(code) ? quota : void 0,
|
|
807
|
+
quotaResetAt: isMonthlyQuotaError(code) ? quotaResetAt(res.headers, retryAfter) : void 0
|
|
808
|
+
});
|
|
809
|
+
} catch (err) {
|
|
810
|
+
if (err instanceof NetRiskScanApiError) {
|
|
811
|
+
throw err;
|
|
812
|
+
}
|
|
813
|
+
if (isAbortError(err)) {
|
|
814
|
+
if (options.signal?.aborted) {
|
|
815
|
+
throw err;
|
|
816
|
+
}
|
|
817
|
+
throw new NetRiskScanNetworkError(`Request timed out after ${this.timeout}ms`, {
|
|
818
|
+
cause: err,
|
|
819
|
+
requestId
|
|
820
|
+
});
|
|
821
|
+
}
|
|
822
|
+
throw new NetRiskScanNetworkError(
|
|
823
|
+
err instanceof Error ? this.redact(err.message) : "Network request failed",
|
|
824
|
+
{
|
|
825
|
+
cause: err,
|
|
826
|
+
requestId
|
|
827
|
+
}
|
|
828
|
+
);
|
|
829
|
+
} finally {
|
|
830
|
+
clearTimeout(timer);
|
|
831
|
+
options.signal?.removeEventListener("abort", onExternalAbort);
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
};
|
|
836
|
+
|
|
837
|
+
// src/utils/credentials.ts
|
|
838
|
+
var CredentialStoreUnavailable = class extends Error {
|
|
839
|
+
constructor() {
|
|
840
|
+
super(
|
|
841
|
+
"The OS credential store is unavailable. Use a secret manager to supply NETRISKSCAN_API_KEY."
|
|
842
|
+
);
|
|
843
|
+
}
|
|
844
|
+
};
|
|
845
|
+
async function useStore(operation, name = "developer-api-key") {
|
|
846
|
+
try {
|
|
847
|
+
const { AsyncEntry } = await import("@napi-rs/keyring");
|
|
848
|
+
const entry = new AsyncEntry("netriskscan-cli", name, {
|
|
849
|
+
linux: { store: "secret-service" }
|
|
850
|
+
});
|
|
851
|
+
return await operation(entry);
|
|
852
|
+
} catch {
|
|
853
|
+
throw new CredentialStoreUnavailable();
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
var credentials = {
|
|
857
|
+
read: () => useStore((entry) => entry.getPassword()),
|
|
858
|
+
save: (key) => useStore((entry) => entry.setPassword(key)),
|
|
859
|
+
remove: () => useStore((entry) => entry.deleteCredential())
|
|
860
|
+
};
|
|
861
|
+
var authorizationStorage = {
|
|
862
|
+
read: () => useStore((entry) => entry.getSecret(), "google-authorization"),
|
|
863
|
+
save: (value) => useStore((entry) => entry.setSecret(value), "google-authorization"),
|
|
864
|
+
remove: () => useStore((entry) => entry.deleteCredential(), "google-authorization")
|
|
865
|
+
};
|
|
866
|
+
|
|
867
|
+
// src/utils/env.ts
|
|
868
|
+
function resolveBaseUrl(cliValue) {
|
|
869
|
+
return cliValue ?? process.env.NETRISKSCAN_BASE_URL;
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
// src/commands/googleAuthorization.ts
|
|
873
|
+
import {
|
|
874
|
+
constants,
|
|
875
|
+
createHash as createHash2,
|
|
876
|
+
createPrivateKey,
|
|
877
|
+
createPublicKey,
|
|
878
|
+
generateKeyPair,
|
|
879
|
+
privateDecrypt,
|
|
880
|
+
randomBytes as randomBytes2,
|
|
881
|
+
randomUUID as randomUUID2
|
|
882
|
+
} from "crypto";
|
|
883
|
+
import { setTimeout as wait } from "timers/promises";
|
|
884
|
+
import { promisify } from "util";
|
|
885
|
+
|
|
886
|
+
// src/utils/installation.ts
|
|
887
|
+
import { randomUUID } from "crypto";
|
|
888
|
+
import { link, mkdir as mkdir2, readFile, unlink as unlink2, writeFile as writeFile2 } from "fs/promises";
|
|
889
|
+
import { homedir as homedir2 } from "os";
|
|
890
|
+
import { join as join2 } from "path";
|
|
891
|
+
var CLI_ID = /^[a-f0-9]{32}$/;
|
|
892
|
+
async function getInstallationId() {
|
|
893
|
+
const directory = join2(homedir2(), ".netriskscan");
|
|
894
|
+
const path = join2(directory, "installation-id");
|
|
895
|
+
try {
|
|
896
|
+
return await readId(path);
|
|
897
|
+
} catch (error) {
|
|
898
|
+
if (error.code !== "ENOENT") throw error;
|
|
899
|
+
}
|
|
900
|
+
await mkdir2(directory, { recursive: true, mode: 448 });
|
|
901
|
+
const id = randomUUID().replaceAll("-", "");
|
|
902
|
+
const temporaryPath = join2(directory, `installation-${id}.tmp`);
|
|
903
|
+
await writeFile2(temporaryPath, id, { flag: "wx", mode: 384 });
|
|
904
|
+
try {
|
|
905
|
+
await link(temporaryPath, path);
|
|
906
|
+
return id;
|
|
907
|
+
} catch (error) {
|
|
908
|
+
if (error.code !== "EEXIST") throw error;
|
|
909
|
+
return await readId(path);
|
|
910
|
+
} finally {
|
|
911
|
+
await unlink2(temporaryPath);
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
async function readId(path) {
|
|
915
|
+
const id = (await readFile(path, "utf8")).trim();
|
|
916
|
+
if (!CLI_ID.test(id)) throw new Error("The NetRiskScan installation ID could not be read.");
|
|
917
|
+
return id;
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
// src/commands/googleAuthorization.ts
|
|
921
|
+
var AUTHORIZATION_PATH = "/v1/cli/authorization";
|
|
922
|
+
var AUTHORIZATION_LIFETIME_MS = 10 * 6e4;
|
|
923
|
+
var POLL_INTERVAL_MS = 5e3;
|
|
924
|
+
var TOKEN = /^[A-Za-z0-9_-]{43}$/;
|
|
925
|
+
var generateRsa = promisify(generateKeyPair);
|
|
926
|
+
function authError(code, message, url) {
|
|
927
|
+
return new CliError(code, message, ExitCode.AuthError, url);
|
|
928
|
+
}
|
|
929
|
+
function invalidResponse() {
|
|
930
|
+
return authError(
|
|
931
|
+
"invalid_auth_response",
|
|
932
|
+
"NetRiskScan returned an invalid authorization response."
|
|
933
|
+
);
|
|
934
|
+
}
|
|
935
|
+
function expired() {
|
|
936
|
+
return authError(
|
|
937
|
+
"transaction_expired",
|
|
938
|
+
"Google authorization expired. Run the command again to start a new session."
|
|
939
|
+
);
|
|
940
|
+
}
|
|
941
|
+
function checkedExpiry(value, deadline) {
|
|
942
|
+
const timestamp = typeof value === "string" ? Date.parse(value) : NaN;
|
|
943
|
+
if (!Number.isFinite(timestamp)) throw invalidResponse();
|
|
944
|
+
const earliest = Math.min(deadline, timestamp);
|
|
945
|
+
if (earliest <= Date.now()) throw expired();
|
|
946
|
+
return earliest;
|
|
947
|
+
}
|
|
948
|
+
async function pendingAuthorization(installationId) {
|
|
949
|
+
const saved = await authorizationStorage.read();
|
|
950
|
+
if (saved) {
|
|
951
|
+
let data;
|
|
952
|
+
try {
|
|
953
|
+
data = JSON.parse(Buffer.from(saved).toString("utf8"));
|
|
954
|
+
} catch {
|
|
955
|
+
throw authError(
|
|
956
|
+
"invalid_local_authorization",
|
|
957
|
+
"The saved authorization could not be read. Run netriskscan auth logout to clear it and try again."
|
|
958
|
+
);
|
|
959
|
+
}
|
|
960
|
+
if (data && typeof data === "object") {
|
|
961
|
+
const pending2 = data;
|
|
962
|
+
if (pending2.installationId === installationId && typeof pending2.deadline === "number" && pending2.deadline > Date.now() && typeof pending2.transactionId === "string" && CLI_ID.test(pending2.transactionId) && typeof pending2.state === "string" && TOKEN.test(pending2.state) && typeof pending2.codeVerifier === "string" && TOKEN.test(pending2.codeVerifier) && typeof pending2.privateKey === "string" && (pending2.authorizationCode === void 0 || TOKEN.test(pending2.authorizationCode))) {
|
|
963
|
+
return pending2;
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
const { privateKey } = await generateRsa("rsa", {
|
|
968
|
+
modulusLength: 2048,
|
|
969
|
+
privateKeyEncoding: { type: "pkcs8", format: "der" },
|
|
970
|
+
publicKeyEncoding: { type: "spki", format: "der" }
|
|
971
|
+
});
|
|
972
|
+
const pending = {
|
|
973
|
+
transactionId: randomUUID2().replaceAll("-", ""),
|
|
974
|
+
installationId,
|
|
975
|
+
state: randomBytes2(32).toString("base64url"),
|
|
976
|
+
codeVerifier: randomBytes2(32).toString("base64url"),
|
|
977
|
+
privateKey: privateKey.toString("base64"),
|
|
978
|
+
deadline: Date.now() + AUTHORIZATION_LIFETIME_MS
|
|
979
|
+
};
|
|
980
|
+
privateKey.fill(0);
|
|
981
|
+
await persist(pending);
|
|
982
|
+
return pending;
|
|
983
|
+
}
|
|
984
|
+
async function persist(pending) {
|
|
985
|
+
const secret = Buffer.from(JSON.stringify(pending));
|
|
986
|
+
try {
|
|
987
|
+
await authorizationStorage.save(secret);
|
|
988
|
+
} finally {
|
|
989
|
+
secret.fill(0);
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
async function pause(milliseconds, deadline, signal) {
|
|
993
|
+
const remaining = deadline - Date.now();
|
|
994
|
+
if (remaining <= 0) throw expired();
|
|
995
|
+
await wait(Math.min(remaining, milliseconds), void 0, { signal });
|
|
996
|
+
}
|
|
997
|
+
async function post(path, body, deadline, signal, polling = false) {
|
|
998
|
+
for (let attempt = 0; ; attempt++) {
|
|
999
|
+
signal.throwIfAborted();
|
|
1000
|
+
const remaining = deadline - Date.now();
|
|
1001
|
+
if (remaining <= 0) throw expired();
|
|
1002
|
+
const controller = new AbortController();
|
|
1003
|
+
const abort = () => controller.abort();
|
|
1004
|
+
const timer = setTimeout(abort, Math.min(1e4, remaining));
|
|
1005
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
1006
|
+
let response;
|
|
1007
|
+
let data;
|
|
1008
|
+
try {
|
|
1009
|
+
response = await fetch(`${DEFAULT_BASE_URL}${path}`, {
|
|
1010
|
+
method: "POST",
|
|
1011
|
+
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
|
1012
|
+
redirect: "error",
|
|
1013
|
+
signal: controller.signal,
|
|
1014
|
+
body: JSON.stringify(body)
|
|
1015
|
+
});
|
|
1016
|
+
if (response.status === 204 && path.endsWith("/acknowledge")) return { data: {} };
|
|
1017
|
+
const parsed = await response.json();
|
|
1018
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
|
|
1019
|
+
data = parsed;
|
|
1020
|
+
} catch {
|
|
1021
|
+
} finally {
|
|
1022
|
+
clearTimeout(timer);
|
|
1023
|
+
signal.removeEventListener("abort", abort);
|
|
1024
|
+
}
|
|
1025
|
+
signal.throwIfAborted();
|
|
1026
|
+
if (response?.ok && data && !path.endsWith("/acknowledge")) return { data };
|
|
1027
|
+
const status = response?.status;
|
|
1028
|
+
const seconds = Number(response?.headers.get("retry-after") ?? 0);
|
|
1029
|
+
const backoff = Math.max(
|
|
1030
|
+
polling ? POLL_INTERVAL_MS : 1e3,
|
|
1031
|
+
Number.isFinite(seconds) ? seconds * 1e3 : 0
|
|
1032
|
+
);
|
|
1033
|
+
if (polling && (status === 429 || status === 503 || !response))
|
|
1034
|
+
return { data: {}, delay: backoff };
|
|
1035
|
+
if (attempt < 2 && (status === 429 || status === 503 || !response || response?.ok && !data)) {
|
|
1036
|
+
await pause(backoff, deadline, signal);
|
|
1037
|
+
continue;
|
|
1038
|
+
}
|
|
1039
|
+
if (!response)
|
|
1040
|
+
throw new CliError(
|
|
1041
|
+
"network_error",
|
|
1042
|
+
"Could not reach NetRiskScan during Google authorization.",
|
|
1043
|
+
ExitCode.ApiError
|
|
1044
|
+
);
|
|
1045
|
+
const code = data?.error?.code;
|
|
1046
|
+
if (status === 410) throw expired();
|
|
1047
|
+
if (status === 401)
|
|
1048
|
+
throw authError(
|
|
1049
|
+
"invalid_transaction_proof",
|
|
1050
|
+
"NetRiskScan rejected the authorization proof. Start a new authorization."
|
|
1051
|
+
);
|
|
1052
|
+
if (code === "installation_already_authorized" || code === "key_limit_reached") {
|
|
1053
|
+
throw authError(
|
|
1054
|
+
code,
|
|
1055
|
+
"This account already has a key for this installation or has reached its key limit. Manage your keys in the Developer Console.",
|
|
1056
|
+
WEB_PAGES.keys
|
|
1057
|
+
);
|
|
1058
|
+
}
|
|
1059
|
+
if (code === "already_delivered" || code === "key_unavailable") {
|
|
1060
|
+
throw authError(
|
|
1061
|
+
code,
|
|
1062
|
+
"This authorization cannot deliver a key. Check your local credentials and the Developer Console.",
|
|
1063
|
+
WEB_PAGES.keys
|
|
1064
|
+
);
|
|
1065
|
+
}
|
|
1066
|
+
if (code === "account_not_active")
|
|
1067
|
+
throw authError(code, "An active, verified developer account is required.");
|
|
1068
|
+
if (status === 429 || status === 503) {
|
|
1069
|
+
throw new CliError(
|
|
1070
|
+
"authorization_unavailable",
|
|
1071
|
+
"NetRiskScan authorization is temporarily unavailable. Try again.",
|
|
1072
|
+
status === 429 ? ExitCode.RateLimitOrQuota : ExitCode.ApiError
|
|
1073
|
+
);
|
|
1074
|
+
}
|
|
1075
|
+
throw invalidResponse();
|
|
1076
|
+
}
|
|
1077
|
+
}
|
|
1078
|
+
function validatedBrowserUrl(data, pending) {
|
|
1079
|
+
const { transactionId, state } = pending;
|
|
1080
|
+
const hash = `#transactionId=${transactionId}&state=${state}&purpose=authorization`;
|
|
1081
|
+
const confirmation = createHash2("sha256").update(state).digest("hex").slice(0, 8).toUpperCase();
|
|
1082
|
+
if (data.transactionId !== transactionId || data.browserUrl !== AUTHORIZATION_PAGE + hash || data.confirmationCode !== confirmation || data.intervalSeconds !== POLL_INTERVAL_MS / 1e3) {
|
|
1083
|
+
throw invalidResponse();
|
|
1084
|
+
}
|
|
1085
|
+
return data.browserUrl;
|
|
1086
|
+
}
|
|
1087
|
+
async function pollForCode(path, pending, signal) {
|
|
1088
|
+
let delay = POLL_INTERVAL_MS;
|
|
1089
|
+
while (true) {
|
|
1090
|
+
await pause(delay, pending.deadline, signal);
|
|
1091
|
+
const result = await post(
|
|
1092
|
+
`${path}/poll`,
|
|
1093
|
+
{ codeVerifier: pending.codeVerifier },
|
|
1094
|
+
pending.deadline,
|
|
1095
|
+
signal,
|
|
1096
|
+
true
|
|
1097
|
+
);
|
|
1098
|
+
if (result.delay !== void 0) {
|
|
1099
|
+
delay = result.delay;
|
|
1100
|
+
continue;
|
|
1101
|
+
}
|
|
1102
|
+
delay = POLL_INTERVAL_MS;
|
|
1103
|
+
const { status, authorizationCode, expiresAt } = result.data;
|
|
1104
|
+
pending.deadline = checkedExpiry(expiresAt, pending.deadline);
|
|
1105
|
+
if (status === "authorized" && typeof authorizationCode === "string" && TOKEN.test(authorizationCode))
|
|
1106
|
+
return authorizationCode;
|
|
1107
|
+
if (status === "issued" || status === "delivered") {
|
|
1108
|
+
throw authError(
|
|
1109
|
+
"already_delivered",
|
|
1110
|
+
"The transaction has already exchanged its code. Check your stored key or manage it in the Developer Console.",
|
|
1111
|
+
WEB_PAGES.keys
|
|
1112
|
+
);
|
|
1113
|
+
}
|
|
1114
|
+
if (status !== "pending" || authorizationCode !== null) throw invalidResponse();
|
|
1115
|
+
}
|
|
1116
|
+
}
|
|
1117
|
+
function decryptKey(data, privateKey) {
|
|
1118
|
+
const ciphertext = typeof data.encryptedApiKey === "string" ? Buffer.from(data.encryptedApiKey, "base64") : void 0;
|
|
1119
|
+
if (data.encryption !== "RSA-OAEP-256" || typeof data.keyId !== "string" || !data.keyId || ciphertext?.length !== 256) {
|
|
1120
|
+
throw invalidResponse();
|
|
1121
|
+
}
|
|
1122
|
+
try {
|
|
1123
|
+
const bytes = privateDecrypt(
|
|
1124
|
+
{ key: privateKey, padding: constants.RSA_PKCS1_OAEP_PADDING, oaepHash: "sha256" },
|
|
1125
|
+
ciphertext
|
|
1126
|
+
);
|
|
1127
|
+
try {
|
|
1128
|
+
const key = bytes.toString("utf8");
|
|
1129
|
+
if (!/^nrs_live_[A-Za-z0-9_-]+$/.test(key) || key.length > 160) throw invalidResponse();
|
|
1130
|
+
return key;
|
|
1131
|
+
} finally {
|
|
1132
|
+
bytes.fill(0);
|
|
1133
|
+
}
|
|
1134
|
+
} catch {
|
|
1135
|
+
throw invalidResponse();
|
|
1136
|
+
}
|
|
1137
|
+
}
|
|
1138
|
+
async function authorizeGoogle() {
|
|
1139
|
+
const controller = new AbortController();
|
|
1140
|
+
const cancel = () => controller.abort();
|
|
1141
|
+
process.once("SIGINT", cancel);
|
|
1142
|
+
try {
|
|
1143
|
+
const pending = await pendingAuthorization(await getInstallationId());
|
|
1144
|
+
const privateKey = createPrivateKey({
|
|
1145
|
+
key: Buffer.from(pending.privateKey, "base64"),
|
|
1146
|
+
type: "pkcs8",
|
|
1147
|
+
format: "der"
|
|
1148
|
+
});
|
|
1149
|
+
const path = `${AUTHORIZATION_PATH}/${pending.transactionId}`;
|
|
1150
|
+
if (!pending.authorizationCode) {
|
|
1151
|
+
const { data: data2 } = await post(
|
|
1152
|
+
AUTHORIZATION_PATH,
|
|
1153
|
+
{
|
|
1154
|
+
transactionId: pending.transactionId,
|
|
1155
|
+
installationId: pending.installationId,
|
|
1156
|
+
state: pending.state,
|
|
1157
|
+
codeChallenge: createHash2("sha256").update(pending.codeVerifier).digest("base64url"),
|
|
1158
|
+
publicKey: createPublicKey(privateKey).export({ type: "spki", format: "der" }).toString("base64")
|
|
1159
|
+
},
|
|
1160
|
+
pending.deadline,
|
|
1161
|
+
controller.signal
|
|
1162
|
+
);
|
|
1163
|
+
const url = validatedBrowserUrl(data2, pending);
|
|
1164
|
+
pending.deadline = checkedExpiry(data2.expiresAt, pending.deadline);
|
|
1165
|
+
process.stderr.write(
|
|
1166
|
+
`NetRiskScan Google sign-in
|
|
1167
|
+
Confirmation code: ${data2.confirmationCode}
|
|
1168
|
+
`
|
|
1169
|
+
);
|
|
1170
|
+
if (!await openAuthorizationBrowser(url).catch(() => false)) {
|
|
1171
|
+
process.stderr.write(`Open this authorization page on a device with a browser:
|
|
1172
|
+
${url}
|
|
1173
|
+
`);
|
|
1174
|
+
}
|
|
1175
|
+
process.stderr.write(
|
|
1176
|
+
"Continue with Google and enter the confirmation code in the browser. Waiting for approval\u2026\n"
|
|
1177
|
+
);
|
|
1178
|
+
pending.authorizationCode = await pollForCode(path, pending, controller.signal);
|
|
1179
|
+
await persist(pending);
|
|
1180
|
+
}
|
|
1181
|
+
const proof = {
|
|
1182
|
+
codeVerifier: pending.codeVerifier,
|
|
1183
|
+
authorizationCode: pending.authorizationCode
|
|
1184
|
+
};
|
|
1185
|
+
const { data } = await post(`${path}/exchange`, proof, pending.deadline, controller.signal);
|
|
1186
|
+
pending.deadline = checkedExpiry(data.expiresAt, pending.deadline);
|
|
1187
|
+
const key = decryptKey(data, privateKey);
|
|
1188
|
+
await credentials.save(key);
|
|
1189
|
+
process.env.NETRISKSCAN_API_KEY = key;
|
|
1190
|
+
try {
|
|
1191
|
+
const acknowledgementDeadline = Math.min(pending.deadline, Date.now() + 4e3);
|
|
1192
|
+
await post(`${path}/acknowledge`, proof, acknowledgementDeadline, controller.signal);
|
|
1193
|
+
await authorizationStorage.remove();
|
|
1194
|
+
} catch {
|
|
1195
|
+
process.stderr.write(
|
|
1196
|
+
"Your API key is saved. The authorization transaction will expire automatically.\n"
|
|
1197
|
+
);
|
|
1198
|
+
}
|
|
1199
|
+
controller.signal.throwIfAborted();
|
|
1200
|
+
process.stdout.write(
|
|
1201
|
+
`
|
|
1202
|
+
NetRiskScan Authentication
|
|
1203
|
+
|
|
1204
|
+
Google account : See signed-in account in the browser
|
|
1205
|
+
Account status : Active
|
|
1206
|
+
API Key : ${key}
|
|
1207
|
+
|
|
1208
|
+
API Key saved successfully.
|
|
1209
|
+
|
|
1210
|
+
`
|
|
1211
|
+
);
|
|
1212
|
+
return key;
|
|
1213
|
+
} catch (error) {
|
|
1214
|
+
if (controller.signal.aborted)
|
|
1215
|
+
throw authError("authorization_canceled", "Google authorization was canceled.");
|
|
1216
|
+
if (error instanceof CredentialStoreUnavailable)
|
|
1217
|
+
throw authError("credential_store_unavailable", error.message);
|
|
1218
|
+
if (error instanceof CliError && [
|
|
1219
|
+
"transaction_expired",
|
|
1220
|
+
"invalid_transaction_proof",
|
|
1221
|
+
"already_delivered",
|
|
1222
|
+
"key_unavailable"
|
|
1223
|
+
].includes(error.code)) {
|
|
1224
|
+
await authorizationStorage.remove().catch(() => void 0);
|
|
1225
|
+
}
|
|
1226
|
+
throw error;
|
|
1227
|
+
} finally {
|
|
1228
|
+
process.removeListener("SIGINT", cancel);
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
|
|
1232
|
+
// src/commands/session.ts
|
|
1233
|
+
async function runCommand(options, action) {
|
|
1234
|
+
try {
|
|
1235
|
+
await action();
|
|
1236
|
+
} catch (error) {
|
|
1237
|
+
const failure = commandFailure(error);
|
|
1238
|
+
reportFailure(failure, options);
|
|
1239
|
+
process.exitCode = failure.exitCode;
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
function suppliedKey(cliValue) {
|
|
1243
|
+
if (cliValue !== void 0) return { key: validateKey(cliValue), source: "argument" };
|
|
1244
|
+
const key = process.env.NETRISKSCAN_API_KEY;
|
|
1245
|
+
return key ? { key: validateKey(key), source: "environment" } : void 0;
|
|
1246
|
+
}
|
|
1247
|
+
function validateKey(key) {
|
|
1248
|
+
if (!/^[A-Za-z0-9._~+/-]+=*$/.test(key)) {
|
|
1249
|
+
throw new CliError(
|
|
1250
|
+
"invalid_api_key",
|
|
1251
|
+
"The API key is empty or has invalid characters.",
|
|
1252
|
+
ExitCode.AuthError
|
|
1253
|
+
);
|
|
1254
|
+
}
|
|
1255
|
+
return key;
|
|
1256
|
+
}
|
|
1257
|
+
function isOfficialApi(options) {
|
|
1258
|
+
const baseUrl = resolveBaseUrl(options.baseUrl) ?? DEFAULT_BASE_URL;
|
|
1259
|
+
return baseUrl.replace(/\/+$/, "") === DEFAULT_BASE_URL;
|
|
1260
|
+
}
|
|
1261
|
+
function createClient(key, options) {
|
|
1262
|
+
return new NetRiskScanClient({
|
|
1263
|
+
apiKey: validateKey(key),
|
|
1264
|
+
baseUrl: resolveBaseUrl(options.baseUrl),
|
|
1265
|
+
timeout: options.timeout === void 0 ? void 0 : Number(options.timeout),
|
|
1266
|
+
maxRetries: options.maxRetries === void 0 ? void 0 : Number(options.maxRetries)
|
|
1267
|
+
});
|
|
1268
|
+
}
|
|
1269
|
+
async function requireSession(options, setup = true) {
|
|
1270
|
+
const supplied = suppliedKey(options.apiKey);
|
|
1271
|
+
const official = isOfficialApi(options);
|
|
1272
|
+
let key = supplied?.key;
|
|
1273
|
+
let storeUnavailable = false;
|
|
1274
|
+
if (!key && official) {
|
|
1275
|
+
try {
|
|
1276
|
+
key = await credentials.read() ?? void 0;
|
|
1277
|
+
} catch (error) {
|
|
1278
|
+
if (!(error instanceof CredentialStoreUnavailable)) throw error;
|
|
1279
|
+
storeUnavailable = true;
|
|
1280
|
+
}
|
|
1281
|
+
}
|
|
1282
|
+
const mayAuthorize = official && setup && isInteractive(options.json || options.jsonl);
|
|
1283
|
+
const authorizedInitially = !key && mayAuthorize;
|
|
1284
|
+
if (authorizedInitially) key = await authorizeGoogle();
|
|
1285
|
+
if (!key) {
|
|
1286
|
+
const storeMessage = storeUnavailable ? " The OS credential store is unavailable." : "";
|
|
1287
|
+
throw new CliError(
|
|
1288
|
+
"api_key_required",
|
|
1289
|
+
"Developer API requires a valid API key. Set NETRISKSCAN_API_KEY or use --api-key." + storeMessage,
|
|
1290
|
+
ExitCode.AuthError,
|
|
1291
|
+
official ? WEB_PAGES.keys : void 0
|
|
1292
|
+
);
|
|
1293
|
+
}
|
|
1294
|
+
let selectedKey = key;
|
|
1295
|
+
let client = createClient(key, options);
|
|
1296
|
+
let replacement;
|
|
1297
|
+
return {
|
|
1298
|
+
get key() {
|
|
1299
|
+
return selectedKey;
|
|
1300
|
+
},
|
|
1301
|
+
get client() {
|
|
1302
|
+
return client;
|
|
1303
|
+
},
|
|
1304
|
+
async request(operation) {
|
|
1305
|
+
if (replacement) return operation(await replacement);
|
|
1306
|
+
try {
|
|
1307
|
+
return await operation(client);
|
|
1308
|
+
} catch (error) {
|
|
1309
|
+
if (!mayAuthorize || authorizedInitially || !(error instanceof NetRiskScanApiError) || error.status !== 401 && error.status !== 403 || error.code !== "api_key_required" && error.code !== "api_key_expired")
|
|
1310
|
+
throw error;
|
|
1311
|
+
replacement ??= authorizeGoogle().then((newKey) => {
|
|
1312
|
+
if (supplied) {
|
|
1313
|
+
process.stderr.write(
|
|
1314
|
+
"Update the API key supplied by your shell or command for future invocations.\n"
|
|
1315
|
+
);
|
|
1316
|
+
}
|
|
1317
|
+
selectedKey = newKey;
|
|
1318
|
+
client = createClient(newKey, options);
|
|
1319
|
+
return client;
|
|
1320
|
+
});
|
|
1321
|
+
return operation(await replacement);
|
|
1322
|
+
}
|
|
1323
|
+
}
|
|
1324
|
+
};
|
|
1325
|
+
}
|
|
1326
|
+
async function loginInteractively(options) {
|
|
1327
|
+
if (!isOfficialApi(options) || !isInteractive(options.json)) {
|
|
1328
|
+
throw new CliError(
|
|
1329
|
+
"interactive_terminal_required",
|
|
1330
|
+
"Google sign-in requires an interactive terminal and the official NetRiskScan API.",
|
|
1331
|
+
ExitCode.AuthError,
|
|
1332
|
+
WEB_PAGES.keys
|
|
1333
|
+
);
|
|
1334
|
+
}
|
|
1335
|
+
await authorizeGoogle();
|
|
1336
|
+
}
|
|
1337
|
+
async function quotaFailure(error, client) {
|
|
1338
|
+
const failure = commandFailure(error);
|
|
1339
|
+
if (!(error instanceof NetRiskScanApiError) || !isMonthlyQuotaError(error.code)) return failure;
|
|
1340
|
+
try {
|
|
1341
|
+
const { data } = await client.getUsage();
|
|
1342
|
+
failure.info.plan = data.plan;
|
|
1343
|
+
failure.info.quota = {
|
|
1344
|
+
limit: error.quota?.limit ?? data.units.limit,
|
|
1345
|
+
used: error.quota?.used ?? data.units.used,
|
|
1346
|
+
remaining: error.quota?.remaining ?? data.units.remaining
|
|
1347
|
+
};
|
|
1348
|
+
failure.info.resetAt = error.quotaResetAt ?? data.period.end;
|
|
1349
|
+
} catch {
|
|
1350
|
+
}
|
|
1351
|
+
return failure;
|
|
1352
|
+
}
|
|
1353
|
+
async function offerQuotaUpgrade(code, options) {
|
|
1354
|
+
if (!isMonthlyQuotaError(code) || !isOfficialApi(options) || !isInteractive(options.json || options.jsonl))
|
|
1355
|
+
return;
|
|
1356
|
+
const input = createInterface({ input: process.stdin, output: process.stderr });
|
|
1357
|
+
const controller = new AbortController();
|
|
1358
|
+
input.once("close", () => controller.abort());
|
|
1359
|
+
try {
|
|
1360
|
+
const answer = (await input.question("Would you like to view available plans? [Y/n] ", {
|
|
1361
|
+
signal: controller.signal
|
|
1362
|
+
})).trim().toLowerCase();
|
|
1363
|
+
if ((answer === "" || answer === "y" || answer === "yes") && !await openBrowser("plans")) {
|
|
1364
|
+
process.stderr.write(`Open ${WEB_PAGES.plans} in your browser.
|
|
1365
|
+
`);
|
|
1366
|
+
}
|
|
1367
|
+
} catch {
|
|
1368
|
+
} finally {
|
|
1369
|
+
input.close();
|
|
1370
|
+
}
|
|
1371
|
+
}
|
|
1372
|
+
|
|
636
1373
|
// src/commands/check.ts
|
|
637
1374
|
var KNOWN_FLAGS = [
|
|
638
1375
|
"proxy",
|
|
@@ -646,10 +1383,7 @@ function collect(value, previous) {
|
|
|
646
1383
|
return [...previous, value];
|
|
647
1384
|
}
|
|
648
1385
|
function registerCheckCommand(program2) {
|
|
649
|
-
program2.command("check <ip>").description("Check IP risk and network intelligence").option(
|
|
650
|
-
"--api-key <key>",
|
|
651
|
-
"NetRiskScan API key (optional; uses the anonymous trial when omitted)"
|
|
652
|
-
).option("--base-url <url>", "Override the API base URL (advanced)").option("--json", "Output machine-readable JSON").option("--verbose", "Show rate limit, quota and request id").option("--debug", "Show debug information on failure").option("--timeout <ms>", "Request timeout in milliseconds", "10000").option("--max-retries <n>", "Maximum automatic retries for 429/503", "3").option("--fail-below <index>", "Exit non-zero if risk.index is below this threshold (CI use)").option(
|
|
1386
|
+
program2.command("check <ip>").description("Check IP risk and network intelligence").option("--api-key <key>", "Developer API key (overrides the environment and OS store)").option("--base-url <url>", "Override the API base URL (advanced)").option("--json", "Output machine-readable JSON").option("--verbose", "Show rate limit, quota and request id").option("--debug", "Show debug information on failure").option("--timeout <ms>", "Request timeout in milliseconds", "10000").option("--max-retries <n>", "Maximum automatic retries for 429/503", "3").option("--fail-below <index>", "Exit non-zero if risk.index is below this threshold (CI use)").option(
|
|
653
1387
|
"--fail-on <flag>",
|
|
654
1388
|
"Exit non-zero if the given flag is true (repeatable): proxy, vpn, tor, datacenter, scanner, abuse",
|
|
655
1389
|
collect,
|
|
@@ -664,45 +1398,45 @@ Examples:
|
|
|
664
1398
|
$ netriskscan check 1.2.3.4 --fail-on tor --fail-on proxy
|
|
665
1399
|
|
|
666
1400
|
Notes:
|
|
667
|
-
|
|
668
|
-
metered by public IP; the response reports how many are left.
|
|
1401
|
+
Developer API requires a valid API Key.
|
|
669
1402
|
`
|
|
670
1403
|
).action(async (ip, options) => {
|
|
671
|
-
await runCheck(ip, options);
|
|
1404
|
+
await runCommand(options, () => runCheck(ip, options));
|
|
672
1405
|
});
|
|
673
1406
|
}
|
|
674
1407
|
async function runCheck(ip, options) {
|
|
675
1408
|
const useJson = Boolean(options.json);
|
|
676
1409
|
for (const flag of options.failOn) {
|
|
677
1410
|
if (!KNOWN_FLAGS.includes(flag)) {
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
`
|
|
1411
|
+
throw new CliError(
|
|
1412
|
+
"invalid_argument",
|
|
1413
|
+
`Unknown --fail-on flag "${flag}". Expected one of: ${KNOWN_FLAGS.join(", ")}`,
|
|
1414
|
+
ExitCode.InvalidArgument
|
|
681
1415
|
);
|
|
682
|
-
process.exitCode = ExitCode.InvalidArgument;
|
|
683
|
-
return;
|
|
684
1416
|
}
|
|
685
1417
|
}
|
|
686
1418
|
if (!isValidIp(ip)) {
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
1419
|
+
throw new CliError(
|
|
1420
|
+
"invalid_ip",
|
|
1421
|
+
`"${ip}" is not a valid IPv4 or IPv6 address.`,
|
|
1422
|
+
ExitCode.InvalidArgument
|
|
1423
|
+
);
|
|
691
1424
|
}
|
|
692
|
-
const
|
|
693
|
-
apiKey: resolveOptionalApiKey(options.apiKey),
|
|
694
|
-
baseUrl: resolveBaseUrl(options.baseUrl),
|
|
695
|
-
timeout: Number(options.timeout),
|
|
696
|
-
maxRetries: Number(options.maxRetries)
|
|
697
|
-
});
|
|
1425
|
+
const session = await requireSession(options);
|
|
698
1426
|
const spinner = useJson ? void 0 : ora({
|
|
699
|
-
text: `
|
|
1427
|
+
text: `Fetching IP risk information for ${ip}...`,
|
|
700
1428
|
stream: process.stderr,
|
|
701
1429
|
isEnabled: process.stderr.isTTY
|
|
702
|
-
})
|
|
1430
|
+
});
|
|
703
1431
|
try {
|
|
704
|
-
const { data, meta } = await
|
|
705
|
-
|
|
1432
|
+
const { data, meta } = await session.request(async (client) => {
|
|
1433
|
+
spinner?.start();
|
|
1434
|
+
try {
|
|
1435
|
+
return await client.checkIp(ip);
|
|
1436
|
+
} finally {
|
|
1437
|
+
spinner?.stop();
|
|
1438
|
+
}
|
|
1439
|
+
});
|
|
706
1440
|
if (useJson) {
|
|
707
1441
|
printJson(data);
|
|
708
1442
|
} else {
|
|
@@ -710,11 +1444,14 @@ async function runCheck(ip, options) {
|
|
|
710
1444
|
if (options.verbose) {
|
|
711
1445
|
renderVerboseMeta(meta);
|
|
712
1446
|
}
|
|
1447
|
+
if (isOfficialApi(options)) await warnAboutQuota(session.key, meta.quota);
|
|
713
1448
|
}
|
|
714
1449
|
process.exitCode = evaluateCiPolicy(data, options);
|
|
715
1450
|
} catch (err) {
|
|
716
|
-
|
|
717
|
-
|
|
1451
|
+
const failure = await quotaFailure(err, session.client);
|
|
1452
|
+
reportFailure(failure, options);
|
|
1453
|
+
process.exitCode = failure.exitCode;
|
|
1454
|
+
await offerQuotaUpgrade(failure.info.code, options);
|
|
718
1455
|
}
|
|
719
1456
|
}
|
|
720
1457
|
function evaluateCiPolicy(data, options) {
|
|
@@ -735,74 +1472,37 @@ function evaluateCiPolicy(data, options) {
|
|
|
735
1472
|
}
|
|
736
1473
|
return ExitCode.Success;
|
|
737
1474
|
}
|
|
738
|
-
function handleCheckError(err, options) {
|
|
739
|
-
if (err instanceof NetRiskScanApiError) {
|
|
740
|
-
if (err.code === ANONYMOUS_DAILY_LIMIT_CODE) {
|
|
741
|
-
printAnonymousLimitError(err);
|
|
742
|
-
} else {
|
|
743
|
-
printApiError(err, { debug: options.debug });
|
|
744
|
-
}
|
|
745
|
-
process.exitCode = exitCodeForApiErrorCode(err.code);
|
|
746
|
-
return;
|
|
747
|
-
}
|
|
748
|
-
if (err instanceof NetRiskScanNetworkError) {
|
|
749
|
-
printNetworkError(err, { debug: options.debug });
|
|
750
|
-
process.exitCode = ExitCode.ApiError;
|
|
751
|
-
return;
|
|
752
|
-
}
|
|
753
|
-
if (options.debug && err instanceof Error) {
|
|
754
|
-
process.stderr.write(`${err.stack ?? err.message}
|
|
755
|
-
`);
|
|
756
|
-
} else {
|
|
757
|
-
process.stderr.write(`Error: ${err instanceof Error ? err.message : String(err)}
|
|
758
|
-
`);
|
|
759
|
-
}
|
|
760
|
-
process.exitCode = ExitCode.GeneralError;
|
|
761
|
-
}
|
|
762
1475
|
|
|
763
1476
|
// src/commands/usage.ts
|
|
764
1477
|
import ora2 from "ora";
|
|
765
1478
|
function registerUsageCommand(program2) {
|
|
766
|
-
program2.command("usage").description("Show API usage and quota for the current
|
|
1479
|
+
program2.command("usage").alias("quota").description("Show API usage and quota for the current monthly quota period").option("--api-key <key>", "Developer API key (overrides the environment and OS store)").option("--base-url <url>", "Override the API base URL (advanced)").option("--json", "Output machine-readable JSON").option("--verbose", "Show rate limit and request id").option("--debug", "Show debug information on failure").option("--timeout <ms>", "Request timeout in milliseconds", "10000").option("--max-retries <n>", "Maximum automatic retries for 429/503", "3").addHelpText(
|
|
767
1480
|
"after",
|
|
768
1481
|
`
|
|
769
1482
|
Notes:
|
|
770
|
-
Requires a Developer API key
|
|
771
|
-
period and quota, which has no anonymous equivalent - unlike check and batch,
|
|
772
|
-
which work without a key.
|
|
1483
|
+
Requires a Developer API key with the usage:read scope.
|
|
773
1484
|
`
|
|
774
1485
|
).action(async (options) => {
|
|
775
|
-
await runUsage(options);
|
|
1486
|
+
await runCommand(options, () => runUsage(options));
|
|
776
1487
|
});
|
|
777
1488
|
}
|
|
778
1489
|
async function runUsage(options) {
|
|
779
|
-
const
|
|
780
|
-
|
|
781
|
-
try {
|
|
782
|
-
apiKey = resolveRequiredApiKey(options.apiKey);
|
|
783
|
-
} catch (err) {
|
|
784
|
-
if (err instanceof NetRiskScanConfigError) {
|
|
785
|
-
printConfigError(err);
|
|
786
|
-
process.exitCode = ExitCode.AuthError;
|
|
787
|
-
return;
|
|
788
|
-
}
|
|
789
|
-
throw err;
|
|
790
|
-
}
|
|
791
|
-
const client = new NetRiskScanClient({
|
|
792
|
-
apiKey,
|
|
793
|
-
baseUrl: resolveBaseUrl(options.baseUrl),
|
|
794
|
-
timeout: Number(options.timeout),
|
|
795
|
-
maxRetries: Number(options.maxRetries)
|
|
796
|
-
});
|
|
797
|
-
const spinner = useJson ? void 0 : ora2({
|
|
1490
|
+
const session = await requireSession(options);
|
|
1491
|
+
const spinner = options.json ? void 0 : ora2({
|
|
798
1492
|
text: "Fetching usage...",
|
|
799
1493
|
stream: process.stderr,
|
|
800
1494
|
isEnabled: process.stderr.isTTY
|
|
801
|
-
})
|
|
1495
|
+
});
|
|
802
1496
|
try {
|
|
803
|
-
const { data, meta } = await
|
|
804
|
-
|
|
805
|
-
|
|
1497
|
+
const { data, meta } = await session.request(async (client) => {
|
|
1498
|
+
spinner?.start();
|
|
1499
|
+
try {
|
|
1500
|
+
return await client.getUsage();
|
|
1501
|
+
} finally {
|
|
1502
|
+
spinner?.stop();
|
|
1503
|
+
}
|
|
1504
|
+
});
|
|
1505
|
+
if (options.json) {
|
|
806
1506
|
printJson(data);
|
|
807
1507
|
} else {
|
|
808
1508
|
renderUsageResult(data);
|
|
@@ -810,25 +1510,16 @@ async function runUsage(options) {
|
|
|
810
1510
|
renderVerboseMeta(meta);
|
|
811
1511
|
}
|
|
812
1512
|
}
|
|
813
|
-
|
|
1513
|
+
if (isOfficialApi(options))
|
|
1514
|
+
await rearmQuotaWarnings(session.key, data.units, data.period.start);
|
|
1515
|
+
} finally {
|
|
814
1516
|
spinner?.stop();
|
|
815
|
-
if (err instanceof NetRiskScanApiError) {
|
|
816
|
-
printApiError(err, { debug: options.debug });
|
|
817
|
-
process.exitCode = exitCodeForApiErrorCode(err.code);
|
|
818
|
-
return;
|
|
819
|
-
}
|
|
820
|
-
if (err instanceof NetRiskScanNetworkError) {
|
|
821
|
-
printNetworkError(err, { debug: options.debug });
|
|
822
|
-
process.exitCode = ExitCode.ApiError;
|
|
823
|
-
return;
|
|
824
|
-
}
|
|
825
|
-
throw err;
|
|
826
1517
|
}
|
|
827
1518
|
}
|
|
828
1519
|
|
|
829
1520
|
// src/commands/batch.ts
|
|
830
1521
|
import { createReadStream } from "fs";
|
|
831
|
-
import { createInterface } from "readline";
|
|
1522
|
+
import { createInterface as createInterface2 } from "readline";
|
|
832
1523
|
|
|
833
1524
|
// src/utils/pool.ts
|
|
834
1525
|
async function runPool(items, concurrency, worker) {
|
|
@@ -845,39 +1536,9 @@ async function runPool(items, concurrency, worker) {
|
|
|
845
1536
|
return results;
|
|
846
1537
|
}
|
|
847
1538
|
|
|
848
|
-
// src/output/jsonl.ts
|
|
849
|
-
function printJsonLine(data) {
|
|
850
|
-
process.stdout.write(`${JSON.stringify(data)}
|
|
851
|
-
`);
|
|
852
|
-
}
|
|
853
|
-
|
|
854
1539
|
// src/output/table.ts
|
|
855
1540
|
import Table from "cli-table3";
|
|
856
1541
|
import chalk3 from "chalk";
|
|
857
|
-
function anonymousSummaryLines(results) {
|
|
858
|
-
const remainings = [];
|
|
859
|
-
const dailyLimits = [];
|
|
860
|
-
let exhausted = false;
|
|
861
|
-
for (const item of results) {
|
|
862
|
-
if (item.ok) {
|
|
863
|
-
const usage = item.result.usage;
|
|
864
|
-
if (usage?.mode !== "anonymous") continue;
|
|
865
|
-
if (typeof usage.remaining === "number") remainings.push(usage.remaining);
|
|
866
|
-
if (typeof usage.dailyLimit === "number") dailyLimits.push(usage.dailyLimit);
|
|
867
|
-
} else if (item.error.code === ANONYMOUS_DAILY_LIMIT_CODE) {
|
|
868
|
-
exhausted = true;
|
|
869
|
-
const limit = item.error.anonymousUsage?.dailyLimit;
|
|
870
|
-
if (typeof limit === "number") dailyLimits.push(limit);
|
|
871
|
-
}
|
|
872
|
-
}
|
|
873
|
-
if (!exhausted && remainings.length === 0) return [];
|
|
874
|
-
const available = exhausted ? 0 : Math.min(...remainings);
|
|
875
|
-
const lines = ["", chalk3.bold("Anonymous trial"), row("Available", formatNumber(available))];
|
|
876
|
-
if (dailyLimits.length > 0) {
|
|
877
|
-
lines.push(row("Daily Limit", formatNumber(Math.max(...dailyLimits))));
|
|
878
|
-
}
|
|
879
|
-
return lines;
|
|
880
|
-
}
|
|
881
1542
|
function renderBatchTable(results) {
|
|
882
1543
|
const table = new Table({
|
|
883
1544
|
head: ["IP", "Index", "Band", "Proxy", "Proxy Type", "VPN", "Tor", "Crawler", "Status"],
|
|
@@ -918,21 +1579,13 @@ function renderBatchTable(results) {
|
|
|
918
1579
|
process.stdout.write(`
|
|
919
1580
|
${okCount} succeeded, ${failCount} failed
|
|
920
1581
|
`);
|
|
921
|
-
const anonymous = anonymousSummaryLines(results);
|
|
922
|
-
if (anonymous.length > 0) {
|
|
923
|
-
process.stdout.write(`${anonymous.join("\n")}
|
|
924
|
-
`);
|
|
925
|
-
}
|
|
926
1582
|
}
|
|
927
1583
|
|
|
928
1584
|
// src/commands/batch.ts
|
|
929
1585
|
var MAX_CONCURRENCY = 20;
|
|
930
1586
|
var DEFAULT_CONCURRENCY = 5;
|
|
931
1587
|
function registerBatchCommand(program2) {
|
|
932
|
-
program2.command("batch <file>").description("Check multiple IP addresses (client-side batch over GET /v1/ip-risk/{ip})").option(
|
|
933
|
-
"--api-key <key>",
|
|
934
|
-
"NetRiskScan API key (optional; uses the anonymous trial when omitted)"
|
|
935
|
-
).option("--base-url <url>", "Override the API base URL (advanced)").option(
|
|
1588
|
+
program2.command("batch <file>").description("Check multiple IP addresses (client-side batch over GET /v1/ip-risk/{ip})").option("--api-key <key>", "Developer API key (overrides the environment and OS store)").option("--base-url <url>", "Override the API base URL (advanced)").option(
|
|
936
1589
|
"--concurrency <n>",
|
|
937
1590
|
`Number of concurrent requests (default: ${DEFAULT_CONCURRENCY}, max: ${MAX_CONCURRENCY})`,
|
|
938
1591
|
String(DEFAULT_CONCURRENCY)
|
|
@@ -940,14 +1593,8 @@ function registerBatchCommand(program2) {
|
|
|
940
1593
|
"after",
|
|
941
1594
|
`
|
|
942
1595
|
Notes:
|
|
943
|
-
|
|
944
|
-
requests
|
|
945
|
-
offer a server-side batch endpoint. Make sure the selected concurrency
|
|
946
|
-
complies with the limits shown in your NetRiskScan Developer Dashboard.
|
|
947
|
-
|
|
948
|
-
An API key is optional. Without an API key, requests use the anonymous daily
|
|
949
|
-
trial, metered by public IP. How many remain is decided by the server, not by
|
|
950
|
-
this CLI, and is reported in the summary after the table.
|
|
1596
|
+
Developer API requires a valid API Key. This command sends individual
|
|
1597
|
+
GET /v1/ip-risk/{ip} requests using the selected concurrency.
|
|
951
1598
|
|
|
952
1599
|
Input format:
|
|
953
1600
|
One IP per line. Blank lines and lines starting with # are ignored.
|
|
@@ -958,12 +1605,12 @@ Examples:
|
|
|
958
1605
|
$ netriskscan batch ips.txt --concurrency 10 --jsonl > results.jsonl
|
|
959
1606
|
`
|
|
960
1607
|
).action(async (file, options) => {
|
|
961
|
-
await runBatch(file, options);
|
|
1608
|
+
await runCommand(options, () => runBatch(file, options));
|
|
962
1609
|
});
|
|
963
1610
|
}
|
|
964
1611
|
async function readIps(file) {
|
|
965
1612
|
const stream = file === "-" ? process.stdin : createReadStream(file, "utf8");
|
|
966
|
-
const rl =
|
|
1613
|
+
const rl = createInterface2({ input: stream, crlfDelay: Infinity });
|
|
967
1614
|
const ips = [];
|
|
968
1615
|
for await (const rawLine of rl) {
|
|
969
1616
|
const line = rawLine.trim();
|
|
@@ -985,34 +1632,16 @@ Check your NetRiskScan Developer Dashboard for your plan's concurrency limit.
|
|
|
985
1632
|
}
|
|
986
1633
|
return Math.floor(n);
|
|
987
1634
|
}
|
|
988
|
-
function toBatchError(err) {
|
|
989
|
-
if (err instanceof NetRiskScanApiError) {
|
|
990
|
-
return {
|
|
991
|
-
code: err.code,
|
|
992
|
-
message: err.message,
|
|
993
|
-
requestId: err.requestId,
|
|
994
|
-
anonymousUsage: err.anonymousUsage
|
|
995
|
-
};
|
|
996
|
-
}
|
|
997
|
-
if (err instanceof NetRiskScanNetworkError) {
|
|
998
|
-
return { code: "network_error", message: err.message, requestId: err.requestId };
|
|
999
|
-
}
|
|
1000
|
-
return { code: "unknown_error", message: err instanceof Error ? err.message : String(err) };
|
|
1001
|
-
}
|
|
1002
1635
|
async function runBatch(file, options) {
|
|
1003
1636
|
const ips = await readIps(file);
|
|
1004
1637
|
if (ips.length === 0) {
|
|
1005
|
-
|
|
1006
|
-
process.exitCode = ExitCode.InvalidArgument;
|
|
1007
|
-
return;
|
|
1638
|
+
throw new CliError("empty_input", "No IP addresses found in input.", ExitCode.InvalidArgument);
|
|
1008
1639
|
}
|
|
1009
|
-
const
|
|
1010
|
-
apiKey: resolveOptionalApiKey(options.apiKey),
|
|
1011
|
-
baseUrl: resolveBaseUrl(options.baseUrl),
|
|
1012
|
-
timeout: Number(options.timeout),
|
|
1013
|
-
maxRetries: Number(options.maxRetries)
|
|
1014
|
-
});
|
|
1640
|
+
const session = await requireSession(options, file !== "-");
|
|
1015
1641
|
const concurrency = parseConcurrency(options.concurrency);
|
|
1642
|
+
let strongestQuota;
|
|
1643
|
+
let blocked;
|
|
1644
|
+
let quotaBlock;
|
|
1016
1645
|
const results = await runPool(ips, concurrency, async (ip) => {
|
|
1017
1646
|
if (!isValidIp(ip)) {
|
|
1018
1647
|
return {
|
|
@@ -1021,21 +1650,57 @@ async function runBatch(file, options) {
|
|
|
1021
1650
|
error: { code: "invalid_ip", message: `"${ip}" is not a valid IPv4 or IPv6 address.` }
|
|
1022
1651
|
};
|
|
1023
1652
|
}
|
|
1653
|
+
if (blocked) {
|
|
1654
|
+
const { action, upgradeUrl } = commandFailure(blocked).info;
|
|
1655
|
+
return {
|
|
1656
|
+
ip,
|
|
1657
|
+
ok: false,
|
|
1658
|
+
error: {
|
|
1659
|
+
code: blocked.code,
|
|
1660
|
+
message: "Skipped after the server refused a preceding request.",
|
|
1661
|
+
action,
|
|
1662
|
+
upgradeUrl,
|
|
1663
|
+
attempted: false
|
|
1664
|
+
}
|
|
1665
|
+
};
|
|
1666
|
+
}
|
|
1024
1667
|
try {
|
|
1025
|
-
const { data } = await client.checkIp(ip);
|
|
1668
|
+
const { data, meta } = await session.request((client) => client.checkIp(ip));
|
|
1669
|
+
if (meta.quota.remaining !== void 0 && (strongestQuota?.remaining === void 0 || meta.quota.remaining < strongestQuota.remaining)) {
|
|
1670
|
+
strongestQuota = meta.quota;
|
|
1671
|
+
}
|
|
1026
1672
|
return { ip, ok: true, result: data };
|
|
1027
1673
|
} catch (err) {
|
|
1028
|
-
|
|
1674
|
+
const { code, message, requestId, action, upgradeUrl } = commandFailure(err).info;
|
|
1675
|
+
if (err instanceof NetRiskScanApiError) {
|
|
1676
|
+
if (isMonthlyQuotaError(code)) {
|
|
1677
|
+
quotaBlock ??= err;
|
|
1678
|
+
blocked ??= err;
|
|
1679
|
+
} else if (exitCodeForApiErrorCode(code) === ExitCode.AuthError) {
|
|
1680
|
+
blocked ??= err;
|
|
1681
|
+
}
|
|
1682
|
+
}
|
|
1683
|
+
return { ip, ok: false, error: { code, message, requestId, action, upgradeUrl } };
|
|
1029
1684
|
}
|
|
1030
1685
|
});
|
|
1686
|
+
const failure = quotaBlock ? await quotaFailure(quotaBlock, session.client) : void 0;
|
|
1031
1687
|
if (options.jsonl) {
|
|
1032
1688
|
for (const item of results) {
|
|
1689
|
+
if (failure && !item.ok && isMonthlyQuotaError(item.error.code)) {
|
|
1690
|
+
const { quota, plan, resetAt, upgradeUrl } = failure.info;
|
|
1691
|
+
Object.assign(item.error, { quota, plan, resetAt, upgradeUrl });
|
|
1692
|
+
}
|
|
1033
1693
|
printJsonLine(item);
|
|
1034
1694
|
}
|
|
1035
1695
|
} else {
|
|
1036
1696
|
renderBatchTable(results);
|
|
1697
|
+
if (failure) reportFailure(failure);
|
|
1698
|
+
else if (blocked) reportFailure(commandFailure(blocked));
|
|
1699
|
+
else if (strongestQuota && isOfficialApi(options))
|
|
1700
|
+
await warnAboutQuota(session.key, strongestQuota);
|
|
1037
1701
|
}
|
|
1038
1702
|
process.exitCode = computeBatchExitCode(results);
|
|
1703
|
+
if (failure && file !== "-") await offerQuotaUpgrade(failure.info.code, options);
|
|
1039
1704
|
}
|
|
1040
1705
|
function computeBatchExitCode(results) {
|
|
1041
1706
|
const failures = results.filter((r) => !r.ok);
|
|
@@ -1046,27 +1711,268 @@ function computeBatchExitCode(results) {
|
|
|
1046
1711
|
return ExitCode.ApiError;
|
|
1047
1712
|
}
|
|
1048
1713
|
|
|
1714
|
+
// src/commands/auth.ts
|
|
1715
|
+
function registerAuthCommand(program2) {
|
|
1716
|
+
const auth = program2.command("auth").description("Manage the locally stored Developer API key");
|
|
1717
|
+
auth.command("login").description("Sign in with Google and securely save a NetRiskScan API key").option("--json", "Return a machine-readable error when browser interaction is required").action((options) => runCommand(options, () => loginInteractively(options)));
|
|
1718
|
+
auth.command("save").description("Save an existing Developer API key in the OS credential store").option("--stdin", "Read the key from piped stdin instead of NETRISKSCAN_API_KEY").option("--json", "Output machine-readable JSON").action(
|
|
1719
|
+
(options) => runCommand(options, () => manageStore(() => saveKey(options)))
|
|
1720
|
+
);
|
|
1721
|
+
auth.command("show").alias("key").description("Display the full stored API key in an interactive terminal").option("--json", "Return a machine-readable error without displaying the key").action(
|
|
1722
|
+
(options) => runCommand(options, () => manageStore(() => showKey(options)))
|
|
1723
|
+
);
|
|
1724
|
+
auth.command("status").description("Show authentication, key source, current plan, and monthly quota").option("--api-key <key>", "Check an explicit Developer API key").option("--json", "Output machine-readable JSON with a masked key").action((options) => runCommand(options, () => showStatus(options)));
|
|
1725
|
+
auth.command("logout").description("Remove the local key without revoking it at NetRiskScan").option("--json", "Output machine-readable JSON").action(
|
|
1726
|
+
(options) => runCommand(options, () => manageStore(() => logout(options)))
|
|
1727
|
+
);
|
|
1728
|
+
}
|
|
1729
|
+
async function manageStore(action) {
|
|
1730
|
+
try {
|
|
1731
|
+
await action();
|
|
1732
|
+
} catch (error) {
|
|
1733
|
+
if (error instanceof CredentialStoreUnavailable) {
|
|
1734
|
+
throw new CliError("credential_store_unavailable", error.message, ExitCode.AuthError);
|
|
1735
|
+
}
|
|
1736
|
+
throw error;
|
|
1737
|
+
}
|
|
1738
|
+
}
|
|
1739
|
+
async function readStdinKey() {
|
|
1740
|
+
if (process.stdin.isTTY) {
|
|
1741
|
+
throw new CliError(
|
|
1742
|
+
"piped_key_required",
|
|
1743
|
+
"Pipe the key from a secret manager into stdin.",
|
|
1744
|
+
ExitCode.InvalidArgument
|
|
1745
|
+
);
|
|
1746
|
+
}
|
|
1747
|
+
let input = "";
|
|
1748
|
+
for await (const chunk of process.stdin) {
|
|
1749
|
+
input += String(chunk);
|
|
1750
|
+
if (input.length > 4096) {
|
|
1751
|
+
throw new CliError(
|
|
1752
|
+
"invalid_api_key",
|
|
1753
|
+
"The supplied API key is too long.",
|
|
1754
|
+
ExitCode.AuthError
|
|
1755
|
+
);
|
|
1756
|
+
}
|
|
1757
|
+
}
|
|
1758
|
+
return validateKey(input.trim());
|
|
1759
|
+
}
|
|
1760
|
+
async function saveKey(options) {
|
|
1761
|
+
const key = options.stdin ? await readStdinKey() : suppliedKey()?.key;
|
|
1762
|
+
if (!key) {
|
|
1763
|
+
throw new CliError(
|
|
1764
|
+
"api_key_required",
|
|
1765
|
+
"Supply an existing API key through NETRISKSCAN_API_KEY or --stdin.",
|
|
1766
|
+
ExitCode.AuthError,
|
|
1767
|
+
WEB_PAGES.keys
|
|
1768
|
+
);
|
|
1769
|
+
}
|
|
1770
|
+
const client = createClient(key, { baseUrl: DEFAULT_BASE_URL, maxRetries: "0" });
|
|
1771
|
+
try {
|
|
1772
|
+
await client.getUsage();
|
|
1773
|
+
} catch (error) {
|
|
1774
|
+
if (!(error instanceof NetRiskScanApiError && error.status === 403 && error.code === "scope_not_allowed"))
|
|
1775
|
+
throw error;
|
|
1776
|
+
}
|
|
1777
|
+
await credentials.save(key);
|
|
1778
|
+
process.env.NETRISKSCAN_API_KEY = key;
|
|
1779
|
+
if (options.json) printJson({ saved: true, storage: "os_credential_store" });
|
|
1780
|
+
else
|
|
1781
|
+
process.stdout.write(
|
|
1782
|
+
"API key saved in the OS credential store. Rerun your original command.\n"
|
|
1783
|
+
);
|
|
1784
|
+
}
|
|
1785
|
+
async function showKey(options) {
|
|
1786
|
+
if (!isInteractive(options.json)) {
|
|
1787
|
+
throw new CliError(
|
|
1788
|
+
"interactive_terminal_required",
|
|
1789
|
+
"Viewing a full API key requires an interactive terminal.",
|
|
1790
|
+
ExitCode.InvalidArgument
|
|
1791
|
+
);
|
|
1792
|
+
}
|
|
1793
|
+
const key = await credentials.read();
|
|
1794
|
+
if (!key) {
|
|
1795
|
+
throw new CliError(
|
|
1796
|
+
"api_key_required",
|
|
1797
|
+
"No stored API key. Run netriskscan auth login to sign in with Google.",
|
|
1798
|
+
ExitCode.AuthError,
|
|
1799
|
+
WEB_PAGES.keys
|
|
1800
|
+
);
|
|
1801
|
+
}
|
|
1802
|
+
validateKey(key);
|
|
1803
|
+
let plan = "Unavailable";
|
|
1804
|
+
try {
|
|
1805
|
+
const { data } = await createClient(key, {
|
|
1806
|
+
baseUrl: DEFAULT_BASE_URL,
|
|
1807
|
+
maxRetries: "0"
|
|
1808
|
+
}).getUsage();
|
|
1809
|
+
plan = data.plan;
|
|
1810
|
+
} catch {
|
|
1811
|
+
}
|
|
1812
|
+
process.stdout.write(
|
|
1813
|
+
`${row("Plan", plan)}
|
|
1814
|
+
|
|
1815
|
+
Your stored API key is a sensitive credential. Keep it private.
|
|
1816
|
+
${key}
|
|
1817
|
+
`
|
|
1818
|
+
);
|
|
1819
|
+
}
|
|
1820
|
+
async function showStatus(options) {
|
|
1821
|
+
const supplied = suppliedKey(options.apiKey);
|
|
1822
|
+
let stored = null;
|
|
1823
|
+
let storage = "empty";
|
|
1824
|
+
try {
|
|
1825
|
+
stored = await credentials.read();
|
|
1826
|
+
if (stored) storage = "saved";
|
|
1827
|
+
} catch (error) {
|
|
1828
|
+
if (!(error instanceof CredentialStoreUnavailable)) throw error;
|
|
1829
|
+
storage = "unavailable";
|
|
1830
|
+
}
|
|
1831
|
+
const key = supplied?.key ?? (isOfficialApi(options) ? stored : null);
|
|
1832
|
+
let status = "not_configured";
|
|
1833
|
+
let usage;
|
|
1834
|
+
let failure;
|
|
1835
|
+
if (key) {
|
|
1836
|
+
try {
|
|
1837
|
+
const { data } = await createClient(key, { ...options, maxRetries: "0" }).getUsage();
|
|
1838
|
+
status = "active";
|
|
1839
|
+
usage = data;
|
|
1840
|
+
} catch (error) {
|
|
1841
|
+
failure = commandFailure(error);
|
|
1842
|
+
status = failure.info.code;
|
|
1843
|
+
process.exitCode = failure.exitCode;
|
|
1844
|
+
}
|
|
1845
|
+
}
|
|
1846
|
+
const details = {
|
|
1847
|
+
configured: Boolean(key),
|
|
1848
|
+
status,
|
|
1849
|
+
source: supplied?.source ?? (key ? "os_credential_store" : void 0),
|
|
1850
|
+
key: key ? redactApiKey(key) : void 0,
|
|
1851
|
+
plan: usage?.plan,
|
|
1852
|
+
accountStatus: usage ? "active" : void 0,
|
|
1853
|
+
quota: usage?.units,
|
|
1854
|
+
quotaResetAt: usage?.period.end,
|
|
1855
|
+
storage,
|
|
1856
|
+
error: failure?.info
|
|
1857
|
+
};
|
|
1858
|
+
if (options.json) {
|
|
1859
|
+
printJson(details);
|
|
1860
|
+
} else {
|
|
1861
|
+
const lines = [
|
|
1862
|
+
row("Authentication", status),
|
|
1863
|
+
row("Local credential", storage),
|
|
1864
|
+
row("Key source", details.source ?? "Unavailable"),
|
|
1865
|
+
row("Key", details.key ?? "Unavailable"),
|
|
1866
|
+
row("Plan", usage?.plan ?? "Unavailable"),
|
|
1867
|
+
row("Account status", usage ? "Active" : "Unavailable"),
|
|
1868
|
+
row("Google account", "See Developer Console")
|
|
1869
|
+
];
|
|
1870
|
+
if (usage) {
|
|
1871
|
+
lines.push(
|
|
1872
|
+
row("Monthly limit", formatNumber(usage.units.limit)),
|
|
1873
|
+
row("Used", formatNumber(usage.units.used)),
|
|
1874
|
+
row("Remaining", formatNumber(usage.units.remaining)),
|
|
1875
|
+
row("Resets", formatUtcTimestamp(usage.period.end) ?? usage.period.end)
|
|
1876
|
+
);
|
|
1877
|
+
}
|
|
1878
|
+
if (failure) lines.push(failure.info.message);
|
|
1879
|
+
if (!key) lines.push(WEB_PAGES.keys);
|
|
1880
|
+
process.stdout.write(`${lines.join("\n")}
|
|
1881
|
+
`);
|
|
1882
|
+
}
|
|
1883
|
+
}
|
|
1884
|
+
async function logout(options) {
|
|
1885
|
+
await authorizationStorage.remove();
|
|
1886
|
+
const removed = await credentials.remove();
|
|
1887
|
+
const environmentKeyConfigured = Boolean(process.env.NETRISKSCAN_API_KEY);
|
|
1888
|
+
if (options.json) {
|
|
1889
|
+
printJson({ removed, serverKeyRevoked: false, environmentKeyConfigured });
|
|
1890
|
+
} else {
|
|
1891
|
+
const local = removed ? "Removed the local credential." : "No local credential was saved.";
|
|
1892
|
+
process.stdout.write(
|
|
1893
|
+
`${local} The server API key remains valid until revoked in the Developer Console.
|
|
1894
|
+
`
|
|
1895
|
+
);
|
|
1896
|
+
if (environmentKeyConfigured)
|
|
1897
|
+
process.stdout.write(
|
|
1898
|
+
"NETRISKSCAN_API_KEY is still set in this shell. Clear it in the parent shell to stop using it.\n"
|
|
1899
|
+
);
|
|
1900
|
+
}
|
|
1901
|
+
}
|
|
1902
|
+
|
|
1903
|
+
// src/commands/billing.ts
|
|
1904
|
+
function registerBillingCommands(program2) {
|
|
1905
|
+
for (const [name, page, description] of [
|
|
1906
|
+
["upgrade", "plans", "Open NetRiskScan plans and upgrades in your browser"],
|
|
1907
|
+
["billing", "billing", "Open NetRiskScan subscription and billing management"]
|
|
1908
|
+
]) {
|
|
1909
|
+
program2.command(name).description(description).option("--api-key <key>", "Developer API key (overrides the environment and OS store)").option("--json", "Return a machine-readable browser action with its URL").action(
|
|
1910
|
+
(options) => runCommand(options, async () => {
|
|
1911
|
+
const url = WEB_PAGES[page];
|
|
1912
|
+
if (!isInteractive(options.json)) {
|
|
1913
|
+
throw new CliError(
|
|
1914
|
+
"browser_required",
|
|
1915
|
+
"Continue in a browser using the Developer Console.",
|
|
1916
|
+
ExitCode.InvalidArgument,
|
|
1917
|
+
url
|
|
1918
|
+
);
|
|
1919
|
+
}
|
|
1920
|
+
if (!isOfficialApi(options)) {
|
|
1921
|
+
throw new CliError(
|
|
1922
|
+
"official_api_required",
|
|
1923
|
+
"This command requires the official NetRiskScan Developer API.",
|
|
1924
|
+
ExitCode.InvalidArgument,
|
|
1925
|
+
url
|
|
1926
|
+
);
|
|
1927
|
+
}
|
|
1928
|
+
const { client } = await requireSession(options, false);
|
|
1929
|
+
const { data } = await client.getUsage();
|
|
1930
|
+
process.stderr.write(`Current plan: ${data.plan}
|
|
1931
|
+
`);
|
|
1932
|
+
if (!await openBrowser(page)) {
|
|
1933
|
+
throw new CliError(
|
|
1934
|
+
"browser_open_failed",
|
|
1935
|
+
"Could not open the default browser. Open the URL directly.",
|
|
1936
|
+
ExitCode.GeneralError,
|
|
1937
|
+
url
|
|
1938
|
+
);
|
|
1939
|
+
}
|
|
1940
|
+
process.stdout.write(
|
|
1941
|
+
`Opened ${url}
|
|
1942
|
+
Sign in with the account that owns this key. Run npx netriskscan-cli usage to refresh the plan and quota after your changes.
|
|
1943
|
+
`
|
|
1944
|
+
);
|
|
1945
|
+
})
|
|
1946
|
+
);
|
|
1947
|
+
}
|
|
1948
|
+
}
|
|
1949
|
+
|
|
1049
1950
|
// src/cli.ts
|
|
1050
|
-
var __dirname =
|
|
1051
|
-
var pkg = JSON.parse(readFileSync(
|
|
1951
|
+
var __dirname = dirname2(fileURLToPath(import.meta.url));
|
|
1952
|
+
var pkg = JSON.parse(readFileSync(join3(__dirname, "..", "package.json"), "utf8"));
|
|
1052
1953
|
var program = new Command();
|
|
1053
1954
|
program.name("netriskscan").description(
|
|
1054
|
-
"Query IP risk
|
|
1955
|
+
"Query IP risk and network intelligence, manage your API key, and view developer quota."
|
|
1055
1956
|
).version(pkg.version, "-V, --version", "Show the CLI version").addHelpText(
|
|
1056
1957
|
"after",
|
|
1057
1958
|
`
|
|
1058
1959
|
Examples:
|
|
1059
|
-
$ netriskscan check 1.1.1.1
|
|
1960
|
+
$ netriskscan check 1.1.1.1
|
|
1060
1961
|
$ netriskscan check 1.1.1.1 --json
|
|
1061
|
-
$ netriskscan
|
|
1962
|
+
$ netriskscan quota
|
|
1062
1963
|
$ netriskscan batch ips.txt --jsonl
|
|
1964
|
+
$ netriskscan auth status
|
|
1965
|
+
$ netriskscan auth key
|
|
1966
|
+
$ netriskscan upgrade
|
|
1063
1967
|
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1968
|
+
Developer API requires a valid API Key. Credentials are resolved from
|
|
1969
|
+
--api-key, NETRISKSCAN_API_KEY, then the OS credential store.
|
|
1970
|
+
Without a key, an interactive query opens the NetRiskScan Google authorization
|
|
1971
|
+
page. Enter the confirmation code in your browser to authorize the CLI.
|
|
1972
|
+
The CLI saves the API key in the OS credential store and resumes the query.
|
|
1067
1973
|
|
|
1068
1974
|
Environment variables:
|
|
1069
|
-
NETRISKSCAN_API_KEY
|
|
1975
|
+
NETRISKSCAN_API_KEY Supply a Developer API key from a secret manager in CI.
|
|
1070
1976
|
|
|
1071
1977
|
NetRiskScan provides diagnostic network intelligence. Results should not be
|
|
1072
1978
|
treated as proof of malicious activity or used as the sole basis for legal,
|
|
@@ -1078,6 +1984,8 @@ Learn more: https://github.com/TeamQQ/netriskscan-cli
|
|
|
1078
1984
|
registerCheckCommand(program);
|
|
1079
1985
|
registerUsageCommand(program);
|
|
1080
1986
|
registerBatchCommand(program);
|
|
1987
|
+
registerAuthCommand(program);
|
|
1988
|
+
registerBillingCommands(program);
|
|
1081
1989
|
program.exitOverride();
|
|
1082
1990
|
try {
|
|
1083
1991
|
await program.parseAsync(process.argv);
|