netriskscan-cli 2.0.0 → 2.2.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 CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  // src/cli.ts
4
4
  import { readFileSync } from "fs";
5
- import { dirname as dirname2, join as join2 } 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
 
@@ -29,8 +29,12 @@ var ExitCode = {
29
29
  function exitCodeForApiErrorCode(code) {
30
30
  switch (code) {
31
31
  case "invalid_api_key":
32
+ case "api_key_invalid":
33
+ case "api_key_required":
34
+ case "api_key_expired":
32
35
  case "api_key_disabled":
33
36
  case "scope_not_allowed":
37
+ case "subscription_required":
34
38
  return ExitCode.AuthError;
35
39
  // The anonymous daily trial is an allowance like any other, so it reuses code 5 rather than
36
40
  // adding an eighth exit code that every script would have to learn.
@@ -152,6 +156,7 @@ var WEB_PAGES = {
152
156
  plans: "https://www.netriskscan.com/pricing.html",
153
157
  billing: "https://www.netriskscan.com/developer/billing"
154
158
  };
159
+ var LOOPBACK_AUTHORIZATION_PAGE = "https://www.netriskscan.com/developer/cli/loopback";
155
160
  function isInteractive(machineOutput) {
156
161
  const ci = process.env.CI?.trim().toLowerCase();
157
162
  return Boolean(
@@ -159,7 +164,14 @@ function isInteractive(machineOutput) {
159
164
  );
160
165
  }
161
166
  async function openBrowser(page) {
162
- const url = WEB_PAGES[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] !== LOOPBACK_AUTHORIZATION_PAGE) return false;
172
+ return launch(destination.href);
173
+ }
174
+ async function launch(url) {
163
175
  const [command, ...args] = process.platform === "win32" ? ["rundll32.exe", "url.dll,FileProtocolHandler", url] : process.platform === "darwin" ? ["open", url] : ["xdg-open", url];
164
176
  const env = { ...process.env };
165
177
  for (const name of Object.keys(env)) {
@@ -418,6 +430,7 @@ function renderUsageResult(data) {
418
430
  lines.push(chalk.bold("Monthly quota period"));
419
431
  lines.push(row("Started", formatUtcTimestamp(data.period.start) ?? data.period.start));
420
432
  lines.push(row("Resets", formatUtcTimestamp(data.period.end) ?? data.period.end));
433
+ lines.push(row("Upgrade plans", WEB_PAGES.plans));
421
434
  process.stdout.write(`${lines.join("\n")}
422
435
  `);
423
436
  }
@@ -511,7 +524,8 @@ function commandFailure(cause) {
511
524
  retryAfter: cause.retryAfter,
512
525
  quota: cause.quota && Object.values(cause.quota).some((value) => value !== void 0) ? cause.quota : void 0,
513
526
  resetAt: cause.quotaResetAt,
514
- upgradeUrl: isMonthlyQuotaError(cause.code) ? WEB_PAGES.plans : void 0
527
+ upgradeUrl: isMonthlyQuotaError(cause.code) || cause.code === "subscription_required" ? WEB_PAGES.plans : void 0,
528
+ action: authenticationAction(cause.code)
515
529
  }
516
530
  };
517
531
  }
@@ -538,6 +552,21 @@ function commandFailure(cause) {
538
552
  }
539
553
  };
540
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
+ }
541
570
  function reportFailure(failure, options = {}) {
542
571
  const { info, cause } = failure;
543
572
  if (options.jsonl) {
@@ -558,6 +587,10 @@ function reportFailure(failure, options = {}) {
558
587
  process.stderr.write(lines.join("\n"));
559
588
  } else if (cause instanceof NetRiskScanApiError) {
560
589
  printApiError(cause, options);
590
+ if (info.action) process.stderr.write(`${info.action}
591
+ `);
592
+ if (info.upgradeUrl) process.stderr.write(`${info.upgradeUrl}
593
+ `);
561
594
  } else if (cause instanceof NetRiskScanNetworkError) {
562
595
  printNetworkError(cause, options);
563
596
  } else {
@@ -670,6 +703,11 @@ function isAbortError(err) {
670
703
  return err instanceof Error && err.name === "AbortError";
671
704
  }
672
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
+ }
673
711
  if (seconds === void 0 || !Number.isFinite(seconds) || seconds < 0) return void 0;
674
712
  const responseDate = Date.parse(headers.get("date") ?? "");
675
713
  const reset = new Date(
@@ -804,10 +842,10 @@ var CredentialStoreUnavailable = class extends Error {
804
842
  );
805
843
  }
806
844
  };
807
- async function useStore(operation) {
845
+ async function useStore(operation, name = "developer-api-key") {
808
846
  try {
809
847
  const { AsyncEntry } = await import("@napi-rs/keyring");
810
- const entry = new AsyncEntry("netriskscan-cli", "developer-api-key", {
848
+ const entry = new AsyncEntry("netriskscan-cli", name, {
811
849
  linux: { store: "secret-service" }
812
850
  });
813
851
  return await operation(entry);
@@ -820,12 +858,528 @@ var credentials = {
820
858
  save: (key) => useStore((entry) => entry.setPassword(key)),
821
859
  remove: () => useStore((entry) => entry.deleteCredential())
822
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
+ };
823
866
 
824
867
  // src/utils/env.ts
825
868
  function resolveBaseUrl(cliValue) {
826
869
  return cliValue ?? process.env.NETRISKSCAN_BASE_URL;
827
870
  }
828
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/oauthCallback.ts
921
+ import { createServer } from "http";
922
+ var OAUTH_TOKEN = /^[A-Za-z0-9_-]{43}$/;
923
+ var CALLBACK_PATH = "/oauth/callback";
924
+ var LOOPBACK_HOST = "127.0.0.1";
925
+ async function listenForAuthorization(state) {
926
+ let complete;
927
+ const result = new Promise((resolve) => {
928
+ complete = resolve;
929
+ });
930
+ let accepted = false;
931
+ let browserResponse;
932
+ const server = createServer((request, response) => {
933
+ response.setHeader("Cache-Control", "no-store");
934
+ response.setHeader("Referrer-Policy", "no-referrer");
935
+ response.setHeader("Content-Type", "text/plain; charset=utf-8");
936
+ response.setHeader("Connection", "close");
937
+ if (request.method !== "GET" || request.headers.host !== origin.host) {
938
+ response.writeHead(400).end("Invalid callback.");
939
+ return;
940
+ }
941
+ const url = request.url ?? "";
942
+ const separator = url.indexOf("?");
943
+ const path = separator < 0 ? url : url.slice(0, separator);
944
+ if (path !== CALLBACK_PATH) {
945
+ response.writeHead(404).end("Page not found.");
946
+ return;
947
+ }
948
+ const params = new URLSearchParams(separator < 0 ? "" : url.slice(separator + 1));
949
+ const states = params.getAll("state");
950
+ const codes = params.getAll("code");
951
+ const errors = params.getAll("error");
952
+ const code = codes.length === 1 && !errors.length && OAUTH_TOKEN.test(codes[0]) ? codes[0] : null;
953
+ const failure = errors.length === 1 && !codes.length && errors[0] ? errors[0] : null;
954
+ if (accepted || states.length !== 1 || states[0] !== state || !code && !failure) {
955
+ response.writeHead(400).end("Invalid or completed callback.");
956
+ return;
957
+ }
958
+ accepted = true;
959
+ const finish = () => {
960
+ if (code) complete({ code });
961
+ else if (failure) complete({ error: failure });
962
+ };
963
+ response.once("close", finish);
964
+ if (code) {
965
+ browserResponse = response;
966
+ complete({ code });
967
+ } else if (failure) {
968
+ response.writeHead(400).end("Google sign-in did not complete. Return to NetRiskScan CLI.");
969
+ complete({ error: failure });
970
+ }
971
+ });
972
+ const port = await new Promise((resolve, reject) => {
973
+ server.once(
974
+ "error",
975
+ () => reject(
976
+ new CliError(
977
+ "callback_unavailable",
978
+ "Could not start the local Google sign-in callback.",
979
+ ExitCode.AuthError
980
+ )
981
+ )
982
+ );
983
+ server.listen(0, LOOPBACK_HOST, () => {
984
+ const address = server.address();
985
+ if (address && typeof address !== "string") resolve(address.port);
986
+ });
987
+ });
988
+ const origin = new URL(`http://${LOOPBACK_HOST}:${port}`);
989
+ return {
990
+ redirectUri: new URL(CALLBACK_PATH, origin).href,
991
+ async wait(deadline, signal) {
992
+ let timer;
993
+ let cancel;
994
+ try {
995
+ signal.throwIfAborted();
996
+ const timeout = new Promise((_, reject) => {
997
+ cancel = () => reject(signal.reason);
998
+ signal.addEventListener("abort", cancel, { once: true });
999
+ timer = setTimeout(
1000
+ () => reject(
1001
+ new CliError(
1002
+ "transaction_expired",
1003
+ "Google authorization expired before the browser returned. Run the command again.",
1004
+ ExitCode.AuthError
1005
+ )
1006
+ ),
1007
+ Math.max(0, deadline - Date.now())
1008
+ );
1009
+ });
1010
+ const callback = await Promise.race([result, timeout]);
1011
+ signal.throwIfAborted();
1012
+ if ("code" in callback) return callback.code;
1013
+ if (callback.error === "access_denied") {
1014
+ throw new CliError(
1015
+ "authorization_canceled",
1016
+ "Google authorization was canceled.",
1017
+ ExitCode.AuthError
1018
+ );
1019
+ }
1020
+ if (callback.error === "temporarily_unavailable") {
1021
+ throw new CliError(
1022
+ "oauth_failed",
1023
+ "Google sign-in is temporarily unavailable. Try again later.",
1024
+ ExitCode.AuthError
1025
+ );
1026
+ }
1027
+ throw new CliError(
1028
+ "oauth_failed",
1029
+ "Google sign-in failed in the browser. Run the command again.",
1030
+ ExitCode.AuthError
1031
+ );
1032
+ } finally {
1033
+ clearTimeout(timer);
1034
+ if (cancel) signal.removeEventListener("abort", cancel);
1035
+ }
1036
+ },
1037
+ finish(success) {
1038
+ if (!browserResponse || browserResponse.writableEnded) return;
1039
+ if (success) {
1040
+ browserResponse.writeHead(200).end(
1041
+ "NetRiskScan CLI Authorization Successful\n\nYour account has been authenticated and an API key has been issued.\n\nYou can close this window and return to your terminal.\n"
1042
+ );
1043
+ } else {
1044
+ browserResponse.writeHead(400).end("NetRiskScan CLI could not finish authorization. Return to your terminal.");
1045
+ }
1046
+ },
1047
+ close() {
1048
+ server.close();
1049
+ if (!browserResponse || browserResponse.writableEnded) server.closeIdleConnections();
1050
+ else server.closeAllConnections();
1051
+ }
1052
+ };
1053
+ }
1054
+
1055
+ // src/commands/googleAuthorization.ts
1056
+ var AUTHORIZATION_PATH = "/v1/cli/authorization/loopback";
1057
+ var AUTHORIZATION_LIFETIME_MS = 10 * 6e4;
1058
+ var generateRsa = promisify(generateKeyPair);
1059
+ function authError(code, message, url) {
1060
+ return new CliError(code, message, ExitCode.AuthError, url);
1061
+ }
1062
+ function invalidResponse() {
1063
+ return authError(
1064
+ "invalid_auth_response",
1065
+ "NetRiskScan returned an invalid authorization response."
1066
+ );
1067
+ }
1068
+ function expired() {
1069
+ return authError(
1070
+ "transaction_expired",
1071
+ "Google authorization expired. Run the command again to start a new session."
1072
+ );
1073
+ }
1074
+ function checkedExpiry(value, deadline) {
1075
+ const timestamp = typeof value === "string" ? Date.parse(value) : NaN;
1076
+ if (!Number.isFinite(timestamp)) throw invalidResponse();
1077
+ const earliest = Math.min(deadline, timestamp);
1078
+ if (earliest <= Date.now()) throw expired();
1079
+ return earliest;
1080
+ }
1081
+ async function pendingAuthorization(installationId) {
1082
+ const saved = await authorizationStorage.read();
1083
+ if (saved) {
1084
+ let data;
1085
+ try {
1086
+ data = JSON.parse(Buffer.from(saved).toString("utf8"));
1087
+ } catch {
1088
+ throw authError(
1089
+ "invalid_local_authorization",
1090
+ "The saved authorization could not be read. Run netriskscan auth logout to clear it and try again."
1091
+ );
1092
+ }
1093
+ if (data && typeof data === "object") {
1094
+ const pending = data;
1095
+ if (pending.flow === "loopback" && pending.installationId === installationId && typeof pending.deadline === "number" && pending.deadline > Date.now() && typeof pending.transactionId === "string" && CLI_ID.test(pending.transactionId) && typeof pending.state === "string" && OAUTH_TOKEN.test(pending.state) && typeof pending.codeVerifier === "string" && OAUTH_TOKEN.test(pending.codeVerifier) && typeof pending.privateKey === "string" && typeof pending.authorizationCode === "string" && OAUTH_TOKEN.test(pending.authorizationCode)) {
1096
+ return pending;
1097
+ }
1098
+ }
1099
+ }
1100
+ }
1101
+ async function newTransaction(installationId) {
1102
+ const { privateKey } = await generateRsa("rsa", {
1103
+ modulusLength: 2048,
1104
+ privateKeyEncoding: { type: "pkcs8", format: "der" },
1105
+ publicKeyEncoding: { type: "spki", format: "der" }
1106
+ });
1107
+ const transaction = {
1108
+ transactionId: randomUUID2().replaceAll("-", ""),
1109
+ installationId,
1110
+ state: randomBytes2(32).toString("base64url"),
1111
+ codeVerifier: randomBytes2(32).toString("base64url"),
1112
+ privateKey: privateKey.toString("base64"),
1113
+ deadline: Date.now() + AUTHORIZATION_LIFETIME_MS
1114
+ };
1115
+ privateKey.fill(0);
1116
+ return transaction;
1117
+ }
1118
+ async function persist(pending) {
1119
+ const secret = Buffer.from(JSON.stringify(pending));
1120
+ try {
1121
+ await authorizationStorage.save(secret);
1122
+ } finally {
1123
+ secret.fill(0);
1124
+ }
1125
+ }
1126
+ async function pause(milliseconds, deadline, signal) {
1127
+ const remaining = deadline - Date.now();
1128
+ if (remaining <= 0) throw expired();
1129
+ await wait(Math.min(remaining, milliseconds), void 0, { signal });
1130
+ }
1131
+ async function post(path, body, deadline, signal) {
1132
+ for (let attempt = 0; ; attempt++) {
1133
+ signal.throwIfAborted();
1134
+ const remaining = deadline - Date.now();
1135
+ if (remaining <= 0) throw expired();
1136
+ const controller = new AbortController();
1137
+ const abort = () => controller.abort();
1138
+ const timer = setTimeout(abort, Math.min(1e4, remaining));
1139
+ signal.addEventListener("abort", abort, { once: true });
1140
+ let response;
1141
+ let data;
1142
+ try {
1143
+ response = await fetch(`${DEFAULT_BASE_URL}${path}`, {
1144
+ method: "POST",
1145
+ headers: { "Content-Type": "application/json", Accept: "application/json" },
1146
+ redirect: "error",
1147
+ signal: controller.signal,
1148
+ body: JSON.stringify(body)
1149
+ });
1150
+ if (response.status === 204 && path.endsWith("/acknowledge")) return {};
1151
+ const parsed = await response.json();
1152
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
1153
+ data = parsed;
1154
+ } catch {
1155
+ } finally {
1156
+ clearTimeout(timer);
1157
+ signal.removeEventListener("abort", abort);
1158
+ }
1159
+ signal.throwIfAborted();
1160
+ if (response?.ok && data && !path.endsWith("/acknowledge")) return data;
1161
+ const status = response?.status;
1162
+ const seconds = Number(response?.headers.get("retry-after") ?? 0);
1163
+ const backoff = Math.max(1e3, Number.isFinite(seconds) ? seconds * 1e3 : 0);
1164
+ if (attempt < 2 && (status === 429 || status === 503 || !response || response?.ok && !data)) {
1165
+ await pause(backoff, deadline, signal);
1166
+ continue;
1167
+ }
1168
+ if (!response)
1169
+ throw new CliError(
1170
+ "network_error",
1171
+ "Could not reach NetRiskScan during Google authorization.",
1172
+ ExitCode.ApiError
1173
+ );
1174
+ const code = data?.error?.code;
1175
+ if (path === AUTHORIZATION_PATH && (status === 404 || status === 405 || status === 501))
1176
+ throw authError(
1177
+ "loopback_authorization_unavailable",
1178
+ "NetRiskScan has not enabled automatic Google authorization for the CLI."
1179
+ );
1180
+ if (status === 410 || code === "authorization_code_expired") throw expired();
1181
+ if (status === 401)
1182
+ throw authError(
1183
+ "invalid_transaction_proof",
1184
+ "NetRiskScan rejected the authorization proof. Start a new authorization."
1185
+ );
1186
+ if (code === "installation_already_authorized" || code === "key_limit_reached") {
1187
+ throw authError(
1188
+ code,
1189
+ "This account already has a key for this installation or has reached its key limit. Manage your keys in the Developer Console.",
1190
+ WEB_PAGES.keys
1191
+ );
1192
+ }
1193
+ if (code === "already_delivered" || code === "key_unavailable" || code === "authorization_code_used") {
1194
+ throw authError(
1195
+ code,
1196
+ "This authorization cannot deliver a key. Check your local credentials and the Developer Console.",
1197
+ WEB_PAGES.keys
1198
+ );
1199
+ }
1200
+ if (code === "account_not_active")
1201
+ throw authError(
1202
+ code,
1203
+ "The Developer account associated with your Google sign-in is inactive."
1204
+ );
1205
+ if (status === 429 || status === 503) {
1206
+ throw new CliError(
1207
+ "authorization_unavailable",
1208
+ "NetRiskScan authorization is temporarily unavailable. Try again.",
1209
+ status === 429 ? ExitCode.RateLimitOrQuota : ExitCode.ApiError
1210
+ );
1211
+ }
1212
+ throw invalidResponse();
1213
+ }
1214
+ }
1215
+ function validatedBrowserUrl(data, pending) {
1216
+ const { transactionId, state } = pending;
1217
+ const hash = `#transactionId=${transactionId}&state=${state}`;
1218
+ if (data.flow !== "loopback" || data.transactionId !== transactionId || data.browserUrl !== LOOPBACK_AUTHORIZATION_PAGE + hash || "confirmationCode" in data) {
1219
+ throw invalidResponse();
1220
+ }
1221
+ return data.browserUrl;
1222
+ }
1223
+ function decryptKey(data, privateKey) {
1224
+ const ciphertext = typeof data.encryptedApiKey === "string" ? Buffer.from(data.encryptedApiKey, "base64") : void 0;
1225
+ if (data.encryption !== "RSA-OAEP-256" || typeof data.keyId !== "string" || !/^[a-f0-9]{8}$/.test(data.keyId) || ciphertext?.length !== 256) {
1226
+ throw invalidResponse();
1227
+ }
1228
+ try {
1229
+ const bytes = privateDecrypt(
1230
+ { key: privateKey, padding: constants.RSA_PKCS1_OAEP_PADDING, oaepHash: "sha256" },
1231
+ ciphertext
1232
+ );
1233
+ try {
1234
+ const key = bytes.toString("utf8");
1235
+ if (!key.startsWith(`nrs_live_${data.keyId}_`) || !/^nrs_live_[A-Za-z0-9_-]+$/.test(key) || key.length > 160) throw invalidResponse();
1236
+ return key;
1237
+ } finally {
1238
+ bytes.fill(0);
1239
+ }
1240
+ } catch {
1241
+ throw invalidResponse();
1242
+ }
1243
+ }
1244
+ async function beginAuthorization(installationId, signal) {
1245
+ const transaction = await newTransaction(installationId);
1246
+ signal.throwIfAborted();
1247
+ const callback = await listenForAuthorization(transaction.state);
1248
+ try {
1249
+ const { transactionId, state, codeVerifier, privateKey } = transaction;
1250
+ const data = await post(
1251
+ AUTHORIZATION_PATH,
1252
+ {
1253
+ transactionId,
1254
+ installationId,
1255
+ state,
1256
+ redirectUri: callback.redirectUri,
1257
+ codeChallenge: createHash2("sha256").update(codeVerifier).digest("base64url"),
1258
+ publicKey: createPublicKey(importPrivateKey(privateKey)).export({ type: "spki", format: "der" }).toString("base64")
1259
+ },
1260
+ transaction.deadline,
1261
+ signal
1262
+ );
1263
+ const url = validatedBrowserUrl(data, transaction);
1264
+ const deadline = checkedExpiry(data.expiresAt, transaction.deadline);
1265
+ process.stderr.write(
1266
+ "Complete Google sign-in in your browser. Waiting for the local callback\u2026\n"
1267
+ );
1268
+ if (!await openAuthorizationBrowser(url).catch(() => false))
1269
+ process.stderr.write(`Open this authorization URL in a browser on this computer:
1270
+ ${url}
1271
+ `);
1272
+ const authorizationCode = await callback.wait(deadline, signal);
1273
+ const pending = { ...transaction, flow: "loopback", deadline, authorizationCode };
1274
+ return { pending, callback };
1275
+ } catch (error) {
1276
+ callback.finish(false);
1277
+ callback.close();
1278
+ throw error;
1279
+ }
1280
+ }
1281
+ function importPrivateKey(value) {
1282
+ const bytes = Buffer.from(value, "base64");
1283
+ try {
1284
+ return createPrivateKey({ key: bytes, type: "pkcs8", format: "der" });
1285
+ } finally {
1286
+ bytes.fill(0);
1287
+ }
1288
+ }
1289
+ async function authorizeGoogle() {
1290
+ const controller = new AbortController();
1291
+ const cancel = () => controller.abort();
1292
+ process.once("SIGINT", cancel);
1293
+ let callback;
1294
+ try {
1295
+ const installationId = await getInstallationId();
1296
+ let pending = await pendingAuthorization(installationId);
1297
+ if (!pending) {
1298
+ const started = await beginAuthorization(installationId, controller.signal);
1299
+ pending = started.pending;
1300
+ callback = started.callback;
1301
+ await persist(pending);
1302
+ }
1303
+ const path = `${AUTHORIZATION_PATH}/${pending.transactionId}`;
1304
+ const proof = {
1305
+ codeVerifier: pending.codeVerifier,
1306
+ authorizationCode: pending.authorizationCode
1307
+ };
1308
+ const data = pending.delivery ?? await post(`${path}/exchange`, proof, pending.deadline, controller.signal);
1309
+ const email = data.accountEmail;
1310
+ if (typeof email !== "string" || email.length > 254 || !/^[^\s\p{C}@]+@[^\s\p{C}@]+$/u.test(email))
1311
+ throw invalidResponse();
1312
+ pending.deadline = checkedExpiry(data.expiresAt, pending.deadline);
1313
+ let key;
1314
+ if (data.status === "existing") {
1315
+ const saved = await credentials.read();
1316
+ const keyId = data.keyId;
1317
+ if (typeof keyId !== "string" || !/^[a-f0-9]{8}$/.test(keyId) || data.encryptedApiKey !== null || data.encryption !== null) throw invalidResponse();
1318
+ if (!saved?.startsWith(`nrs_live_${keyId}_`)) {
1319
+ await authorizationStorage.remove().catch(() => void 0);
1320
+ throw authError(
1321
+ "installation_already_authorized",
1322
+ "This installation has a key in your account. Revoke it in the Developer Console to issue a replacement.",
1323
+ WEB_PAGES.keys
1324
+ );
1325
+ }
1326
+ key = saved;
1327
+ } else {
1328
+ if (data.status !== "issued") throw invalidResponse();
1329
+ key = decryptKey(data, importPrivateKey(pending.privateKey));
1330
+ if (!pending.delivery) {
1331
+ pending.delivery = data;
1332
+ await persist(pending);
1333
+ }
1334
+ await credentials.save(key);
1335
+ }
1336
+ callback?.finish(true);
1337
+ try {
1338
+ const acknowledgementDeadline = Math.min(pending.deadline, Date.now() + 4e3);
1339
+ await post(`${path}/acknowledge`, proof, acknowledgementDeadline, controller.signal);
1340
+ await authorizationStorage.remove();
1341
+ } catch {
1342
+ process.stderr.write(
1343
+ "Your API key is saved. The authorization transaction will expire automatically.\n"
1344
+ );
1345
+ }
1346
+ controller.signal.throwIfAborted();
1347
+ process.stderr.write(
1348
+ `
1349
+ NetRiskScan CLI
1350
+
1351
+ Google Authentication Successful
1352
+
1353
+ Account : ${email}
1354
+ Key Status : Active
1355
+ Local Config : Saved
1356
+ `
1357
+ );
1358
+ process.stderr.write(`API Key : ${redactApiKey(key)}
1359
+ `);
1360
+ return key;
1361
+ } catch (error) {
1362
+ if (controller.signal.aborted)
1363
+ throw authError("authorization_canceled", "Google authorization was canceled.");
1364
+ if (error instanceof CredentialStoreUnavailable)
1365
+ throw authError("credential_store_unavailable", error.message);
1366
+ if (error instanceof CliError && [
1367
+ "transaction_expired",
1368
+ "invalid_transaction_proof",
1369
+ "already_delivered",
1370
+ "authorization_code_used",
1371
+ "key_unavailable"
1372
+ ].includes(error.code)) {
1373
+ await authorizationStorage.remove().catch(() => void 0);
1374
+ }
1375
+ throw error;
1376
+ } finally {
1377
+ callback?.finish(false);
1378
+ callback?.close();
1379
+ process.removeListener("SIGINT", cancel);
1380
+ }
1381
+ }
1382
+
829
1383
  // src/commands/session.ts
830
1384
  async function runCommand(options, action) {
831
1385
  try {
@@ -876,19 +1430,65 @@ async function requireSession(options, setup = true) {
876
1430
  storeUnavailable = true;
877
1431
  }
878
1432
  }
1433
+ const mayAuthorize = official && setup && isInteractive();
1434
+ const authorizeAndResume = async () => {
1435
+ const newKey = await authorizeGoogle();
1436
+ process.stderr.write("Authentication completed. Resuming previous request\u2026\n");
1437
+ return newKey;
1438
+ };
1439
+ const authorizedInitially = !key && mayAuthorize;
1440
+ if (authorizedInitially) key = await authorizeAndResume();
879
1441
  if (!key) {
880
- const url = official ? WEB_PAGES.keys : void 0;
881
- const opened = official && setup && isInteractive(options.json || options.jsonl) && await openBrowser("keys");
882
- const message = opened ? "The Developer Console opened. Continue with Google, create an API key, then use auth save or NETRISKSCAN_API_KEY and rerun your command." : "Developer API requires a valid API key. Set NETRISKSCAN_API_KEY or use --api-key.";
883
1442
  const storeMessage = storeUnavailable ? " The OS credential store is unavailable." : "";
884
1443
  throw new CliError(
885
- opened ? "auth_setup_required" : "api_key_required",
886
- message + storeMessage,
1444
+ "api_key_required",
1445
+ "Developer API requires a valid API key. Set NETRISKSCAN_API_KEY or use --api-key." + storeMessage,
1446
+ ExitCode.AuthError,
1447
+ official ? WEB_PAGES.keys : void 0
1448
+ );
1449
+ }
1450
+ let selectedKey = key;
1451
+ let client = createClient(key, options);
1452
+ let replacement;
1453
+ return {
1454
+ get key() {
1455
+ return selectedKey;
1456
+ },
1457
+ get client() {
1458
+ return client;
1459
+ },
1460
+ async request(operation) {
1461
+ if (replacement) return operation(await replacement);
1462
+ try {
1463
+ return await operation(client);
1464
+ } catch (error) {
1465
+ if (!mayAuthorize || authorizedInitially || !(error instanceof NetRiskScanApiError) || error.status !== 401 && error.status !== 403 || error.code !== "api_key_required" && error.code !== "api_key_expired")
1466
+ throw error;
1467
+ replacement ??= authorizeAndResume().then((newKey) => {
1468
+ if (supplied) {
1469
+ process.stderr.write(
1470
+ "Update the API key supplied by your shell or command for future invocations.\n"
1471
+ );
1472
+ }
1473
+ selectedKey = newKey;
1474
+ client = createClient(newKey, options);
1475
+ return client;
1476
+ });
1477
+ return operation(await replacement);
1478
+ }
1479
+ }
1480
+ };
1481
+ }
1482
+ async function loginInteractively(options) {
1483
+ if (!isOfficialApi(options) || !isInteractive(options.json)) {
1484
+ throw new CliError(
1485
+ "interactive_terminal_required",
1486
+ "Google sign-in requires an interactive terminal and the official NetRiskScan API.",
887
1487
  ExitCode.AuthError,
888
- url
1488
+ WEB_PAGES.keys
889
1489
  );
890
1490
  }
891
- return { key, client: createClient(key, options) };
1491
+ await authorizeGoogle();
892
1492
  }
893
1493
  async function quotaFailure(error, client) {
894
1494
  const failure = commandFailure(error);
@@ -978,15 +1578,21 @@ async function runCheck(ip, options) {
978
1578
  ExitCode.InvalidArgument
979
1579
  );
980
1580
  }
981
- const { key, client } = await requireSession(options);
1581
+ const session = await requireSession(options);
982
1582
  const spinner = useJson ? void 0 : ora({
983
- text: `Checking ${ip}...`,
1583
+ text: `Fetching IP risk information for ${ip}...`,
984
1584
  stream: process.stderr,
985
1585
  isEnabled: process.stderr.isTTY
986
- }).start();
1586
+ });
987
1587
  try {
988
- const { data, meta } = await client.checkIp(ip);
989
- spinner?.stop();
1588
+ const { data, meta } = await session.request(async (client) => {
1589
+ spinner?.start();
1590
+ try {
1591
+ return await client.checkIp(ip);
1592
+ } finally {
1593
+ spinner?.stop();
1594
+ }
1595
+ });
990
1596
  if (useJson) {
991
1597
  printJson(data);
992
1598
  } else {
@@ -994,12 +1600,11 @@ async function runCheck(ip, options) {
994
1600
  if (options.verbose) {
995
1601
  renderVerboseMeta(meta);
996
1602
  }
997
- if (isOfficialApi(options)) await warnAboutQuota(key, meta.quota);
1603
+ if (isOfficialApi(options)) await warnAboutQuota(session.key, meta.quota);
998
1604
  }
999
1605
  process.exitCode = evaluateCiPolicy(data, options);
1000
1606
  } catch (err) {
1001
- spinner?.stop();
1002
- const failure = await quotaFailure(err, client);
1607
+ const failure = await quotaFailure(err, session.client);
1003
1608
  reportFailure(failure, options);
1004
1609
  process.exitCode = failure.exitCode;
1005
1610
  await offerQuotaUpgrade(failure.info.code, options);
@@ -1038,15 +1643,21 @@ Notes:
1038
1643
  });
1039
1644
  }
1040
1645
  async function runUsage(options) {
1041
- const { key, client } = await requireSession(options);
1646
+ const session = await requireSession(options);
1042
1647
  const spinner = options.json ? void 0 : ora2({
1043
1648
  text: "Fetching usage...",
1044
1649
  stream: process.stderr,
1045
1650
  isEnabled: process.stderr.isTTY
1046
- }).start();
1651
+ });
1047
1652
  try {
1048
- const { data, meta } = await client.getUsage();
1049
- spinner?.stop();
1653
+ const { data, meta } = await session.request(async (client) => {
1654
+ spinner?.start();
1655
+ try {
1656
+ return await client.getUsage();
1657
+ } finally {
1658
+ spinner?.stop();
1659
+ }
1660
+ });
1050
1661
  if (options.json) {
1051
1662
  printJson(data);
1052
1663
  } else {
@@ -1055,7 +1666,8 @@ async function runUsage(options) {
1055
1666
  renderVerboseMeta(meta);
1056
1667
  }
1057
1668
  }
1058
- if (isOfficialApi(options)) await rearmQuotaWarnings(key, data.units, data.period.start);
1669
+ if (isOfficialApi(options))
1670
+ await rearmQuotaWarnings(session.key, data.units, data.period.start);
1059
1671
  } finally {
1060
1672
  spinner?.stop();
1061
1673
  }
@@ -1181,7 +1793,7 @@ async function runBatch(file, options) {
1181
1793
  if (ips.length === 0) {
1182
1794
  throw new CliError("empty_input", "No IP addresses found in input.", ExitCode.InvalidArgument);
1183
1795
  }
1184
- const { key, client } = await requireSession(options, file !== "-");
1796
+ const session = await requireSession(options, file !== "-");
1185
1797
  const concurrency = parseConcurrency(options.concurrency);
1186
1798
  let strongestQuota;
1187
1799
  let blocked;
@@ -1195,24 +1807,27 @@ async function runBatch(file, options) {
1195
1807
  };
1196
1808
  }
1197
1809
  if (blocked) {
1810
+ const { action, upgradeUrl } = commandFailure(blocked).info;
1198
1811
  return {
1199
1812
  ip,
1200
1813
  ok: false,
1201
1814
  error: {
1202
1815
  code: blocked.code,
1203
1816
  message: "Skipped after the server refused a preceding request.",
1817
+ action,
1818
+ upgradeUrl,
1204
1819
  attempted: false
1205
1820
  }
1206
1821
  };
1207
1822
  }
1208
1823
  try {
1209
- const { data, meta } = await client.checkIp(ip);
1824
+ const { data, meta } = await session.request((client) => client.checkIp(ip));
1210
1825
  if (meta.quota.remaining !== void 0 && (strongestQuota?.remaining === void 0 || meta.quota.remaining < strongestQuota.remaining)) {
1211
1826
  strongestQuota = meta.quota;
1212
1827
  }
1213
1828
  return { ip, ok: true, result: data };
1214
1829
  } catch (err) {
1215
- const { code, message, requestId } = commandFailure(err).info;
1830
+ const { code, message, requestId, action, upgradeUrl } = commandFailure(err).info;
1216
1831
  if (err instanceof NetRiskScanApiError) {
1217
1832
  if (isMonthlyQuotaError(code)) {
1218
1833
  quotaBlock ??= err;
@@ -1221,10 +1836,10 @@ async function runBatch(file, options) {
1221
1836
  blocked ??= err;
1222
1837
  }
1223
1838
  }
1224
- return { ip, ok: false, error: { code, message, requestId } };
1839
+ return { ip, ok: false, error: { code, message, requestId, action, upgradeUrl } };
1225
1840
  }
1226
1841
  });
1227
- const failure = quotaBlock ? await quotaFailure(quotaBlock, client) : void 0;
1842
+ const failure = quotaBlock ? await quotaFailure(quotaBlock, session.client) : void 0;
1228
1843
  if (options.jsonl) {
1229
1844
  for (const item of results) {
1230
1845
  if (failure && !item.ok && isMonthlyQuotaError(item.error.code)) {
@@ -1236,7 +1851,9 @@ async function runBatch(file, options) {
1236
1851
  } else {
1237
1852
  renderBatchTable(results);
1238
1853
  if (failure) reportFailure(failure);
1239
- else if (strongestQuota && isOfficialApi(options)) await warnAboutQuota(key, strongestQuota);
1854
+ else if (blocked) reportFailure(commandFailure(blocked));
1855
+ else if (strongestQuota && isOfficialApi(options))
1856
+ await warnAboutQuota(session.key, strongestQuota);
1240
1857
  }
1241
1858
  process.exitCode = computeBatchExitCode(results);
1242
1859
  if (failure && file !== "-") await offerQuotaUpgrade(failure.info.code, options);
@@ -1253,13 +1870,14 @@ function computeBatchExitCode(results) {
1253
1870
  // src/commands/auth.ts
1254
1871
  function registerAuthCommand(program2) {
1255
1872
  const auth = program2.command("auth").description("Manage the locally stored Developer API key");
1873
+ 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)));
1256
1874
  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(
1257
1875
  (options) => runCommand(options, () => manageStore(() => saveKey(options)))
1258
1876
  );
1259
- auth.command("show").description("Display the full stored API key in an interactive terminal").option("--json", "Return a machine-readable error without displaying the key").action(
1877
+ 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(
1260
1878
  (options) => runCommand(options, () => manageStore(() => showKey(options)))
1261
1879
  );
1262
- auth.command("status").description("Show authentication, key source, and current plan").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)));
1880
+ 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)));
1263
1881
  auth.command("logout").description("Remove the local key without revoking it at NetRiskScan").option("--json", "Output machine-readable JSON").action(
1264
1882
  (options) => runCommand(options, () => manageStore(() => logout(options)))
1265
1883
  );
@@ -1332,7 +1950,7 @@ async function showKey(options) {
1332
1950
  if (!key) {
1333
1951
  throw new CliError(
1334
1952
  "api_key_required",
1335
- "No stored API key. Create a key in the Developer Console and run auth save.",
1953
+ "No stored API key. Run netriskscan auth login to sign in with Google.",
1336
1954
  ExitCode.AuthError,
1337
1955
  WEB_PAGES.keys
1338
1956
  );
@@ -1349,9 +1967,8 @@ async function showKey(options) {
1349
1967
  }
1350
1968
  process.stdout.write(
1351
1969
  `${row("Plan", plan)}
1352
- ${row("Developer account", "See Developer Console")}
1353
1970
 
1354
- Your stored API key:
1971
+ Your stored API key is a sensitive credential. Keep it private.
1355
1972
  ${key}
1356
1973
  `
1357
1974
  );
@@ -1369,13 +1986,13 @@ async function showStatus(options) {
1369
1986
  }
1370
1987
  const key = supplied?.key ?? (isOfficialApi(options) ? stored : null);
1371
1988
  let status = "not_configured";
1372
- let plan;
1989
+ let usage;
1373
1990
  let failure;
1374
1991
  if (key) {
1375
1992
  try {
1376
1993
  const { data } = await createClient(key, { ...options, maxRetries: "0" }).getUsage();
1377
1994
  status = "active";
1378
- plan = data.plan;
1995
+ usage = data;
1379
1996
  } catch (error) {
1380
1997
  failure = commandFailure(error);
1381
1998
  status = failure.info.code;
@@ -1387,7 +2004,10 @@ async function showStatus(options) {
1387
2004
  status,
1388
2005
  source: supplied?.source ?? (key ? "os_credential_store" : void 0),
1389
2006
  key: key ? redactApiKey(key) : void 0,
1390
- plan,
2007
+ plan: usage?.plan,
2008
+ accountStatus: usage ? "active" : void 0,
2009
+ quota: usage?.units,
2010
+ quotaResetAt: usage?.period.end,
1391
2011
  storage,
1392
2012
  error: failure?.info
1393
2013
  };
@@ -1399,9 +2019,18 @@ async function showStatus(options) {
1399
2019
  row("Local credential", storage),
1400
2020
  row("Key source", details.source ?? "Unavailable"),
1401
2021
  row("Key", details.key ?? "Unavailable"),
1402
- row("Plan", plan ?? "Unavailable"),
1403
- row("Account / key name", "See Developer Console")
2022
+ row("Plan", usage?.plan ?? "Unavailable"),
2023
+ row("Account status", usage ? "Active" : "Unavailable"),
2024
+ row("Google account", "See Developer Console")
1404
2025
  ];
2026
+ if (usage) {
2027
+ lines.push(
2028
+ row("Monthly limit", formatNumber(usage.units.limit)),
2029
+ row("Used", formatNumber(usage.units.used)),
2030
+ row("Remaining", formatNumber(usage.units.remaining)),
2031
+ row("Resets", formatUtcTimestamp(usage.period.end) ?? usage.period.end)
2032
+ );
2033
+ }
1405
2034
  if (failure) lines.push(failure.info.message);
1406
2035
  if (!key) lines.push(WEB_PAGES.keys);
1407
2036
  process.stdout.write(`${lines.join("\n")}
@@ -1409,6 +2038,7 @@ async function showStatus(options) {
1409
2038
  }
1410
2039
  }
1411
2040
  async function logout(options) {
2041
+ await authorizationStorage.remove();
1412
2042
  const removed = await credentials.remove();
1413
2043
  const environmentKeyConfigured = Boolean(process.env.NETRISKSCAN_API_KEY);
1414
2044
  if (options.json) {
@@ -1475,7 +2105,7 @@ Sign in with the account that owns this key. Run npx netriskscan-cli usage to re
1475
2105
 
1476
2106
  // src/cli.ts
1477
2107
  var __dirname = dirname2(fileURLToPath(import.meta.url));
1478
- var pkg = JSON.parse(readFileSync(join2(__dirname, "..", "package.json"), "utf8"));
2108
+ var pkg = JSON.parse(readFileSync(join3(__dirname, "..", "package.json"), "utf8"));
1479
2109
  var program = new Command();
1480
2110
  program.name("netriskscan").description(
1481
2111
  "Query IP risk and network intelligence, manage your API key, and view developer quota."
@@ -1488,12 +2118,14 @@ Examples:
1488
2118
  $ netriskscan quota
1489
2119
  $ netriskscan batch ips.txt --jsonl
1490
2120
  $ netriskscan auth status
2121
+ $ netriskscan auth key
1491
2122
  $ netriskscan upgrade
1492
2123
 
1493
2124
  Developer API requires a valid API Key. Credentials are resolved from
1494
2125
  --api-key, NETRISKSCAN_API_KEY, then the OS credential store.
1495
- Without a key, an interactive query opens the Developer Console for setup.
1496
- Sign in there, create a key and run "netriskscan auth save".
2126
+ Without a key, an interactive query opens the NetRiskScan Google authorization
2127
+ page. Enter the confirmation code in your browser to authorize the CLI.
2128
+ The CLI saves the API key in the OS credential store and resumes the query.
1497
2129
 
1498
2130
  Environment variables:
1499
2131
  NETRISKSCAN_API_KEY Supply a Developer API key from a secret manager in CI.