netriskscan-cli 2.0.0 → 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/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 AUTHORIZATION_PAGE = "https://www.netriskscan.com/developer/cli";
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] !== 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,377 @@ 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/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
+
829
1232
  // src/commands/session.ts
830
1233
  async function runCommand(options, action) {
831
1234
  try {
@@ -876,19 +1279,60 @@ async function requireSession(options, setup = true) {
876
1279
  storeUnavailable = true;
877
1280
  }
878
1281
  }
1282
+ const mayAuthorize = official && setup && isInteractive(options.json || options.jsonl);
1283
+ const authorizedInitially = !key && mayAuthorize;
1284
+ if (authorizedInitially) key = await authorizeGoogle();
879
1285
  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
1286
  const storeMessage = storeUnavailable ? " The OS credential store is unavailable." : "";
884
1287
  throw new CliError(
885
- opened ? "auth_setup_required" : "api_key_required",
886
- message + storeMessage,
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.",
887
1331
  ExitCode.AuthError,
888
- url
1332
+ WEB_PAGES.keys
889
1333
  );
890
1334
  }
891
- return { key, client: createClient(key, options) };
1335
+ await authorizeGoogle();
892
1336
  }
893
1337
  async function quotaFailure(error, client) {
894
1338
  const failure = commandFailure(error);
@@ -978,15 +1422,21 @@ async function runCheck(ip, options) {
978
1422
  ExitCode.InvalidArgument
979
1423
  );
980
1424
  }
981
- const { key, client } = await requireSession(options);
1425
+ const session = await requireSession(options);
982
1426
  const spinner = useJson ? void 0 : ora({
983
- text: `Checking ${ip}...`,
1427
+ text: `Fetching IP risk information for ${ip}...`,
984
1428
  stream: process.stderr,
985
1429
  isEnabled: process.stderr.isTTY
986
- }).start();
1430
+ });
987
1431
  try {
988
- const { data, meta } = await client.checkIp(ip);
989
- spinner?.stop();
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
+ });
990
1440
  if (useJson) {
991
1441
  printJson(data);
992
1442
  } else {
@@ -994,12 +1444,11 @@ async function runCheck(ip, options) {
994
1444
  if (options.verbose) {
995
1445
  renderVerboseMeta(meta);
996
1446
  }
997
- if (isOfficialApi(options)) await warnAboutQuota(key, meta.quota);
1447
+ if (isOfficialApi(options)) await warnAboutQuota(session.key, meta.quota);
998
1448
  }
999
1449
  process.exitCode = evaluateCiPolicy(data, options);
1000
1450
  } catch (err) {
1001
- spinner?.stop();
1002
- const failure = await quotaFailure(err, client);
1451
+ const failure = await quotaFailure(err, session.client);
1003
1452
  reportFailure(failure, options);
1004
1453
  process.exitCode = failure.exitCode;
1005
1454
  await offerQuotaUpgrade(failure.info.code, options);
@@ -1038,15 +1487,21 @@ Notes:
1038
1487
  });
1039
1488
  }
1040
1489
  async function runUsage(options) {
1041
- const { key, client } = await requireSession(options);
1490
+ const session = await requireSession(options);
1042
1491
  const spinner = options.json ? void 0 : ora2({
1043
1492
  text: "Fetching usage...",
1044
1493
  stream: process.stderr,
1045
1494
  isEnabled: process.stderr.isTTY
1046
- }).start();
1495
+ });
1047
1496
  try {
1048
- const { data, meta } = await client.getUsage();
1049
- spinner?.stop();
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
+ });
1050
1505
  if (options.json) {
1051
1506
  printJson(data);
1052
1507
  } else {
@@ -1055,7 +1510,8 @@ async function runUsage(options) {
1055
1510
  renderVerboseMeta(meta);
1056
1511
  }
1057
1512
  }
1058
- if (isOfficialApi(options)) await rearmQuotaWarnings(key, data.units, data.period.start);
1513
+ if (isOfficialApi(options))
1514
+ await rearmQuotaWarnings(session.key, data.units, data.period.start);
1059
1515
  } finally {
1060
1516
  spinner?.stop();
1061
1517
  }
@@ -1181,7 +1637,7 @@ async function runBatch(file, options) {
1181
1637
  if (ips.length === 0) {
1182
1638
  throw new CliError("empty_input", "No IP addresses found in input.", ExitCode.InvalidArgument);
1183
1639
  }
1184
- const { key, client } = await requireSession(options, file !== "-");
1640
+ const session = await requireSession(options, file !== "-");
1185
1641
  const concurrency = parseConcurrency(options.concurrency);
1186
1642
  let strongestQuota;
1187
1643
  let blocked;
@@ -1195,24 +1651,27 @@ async function runBatch(file, options) {
1195
1651
  };
1196
1652
  }
1197
1653
  if (blocked) {
1654
+ const { action, upgradeUrl } = commandFailure(blocked).info;
1198
1655
  return {
1199
1656
  ip,
1200
1657
  ok: false,
1201
1658
  error: {
1202
1659
  code: blocked.code,
1203
1660
  message: "Skipped after the server refused a preceding request.",
1661
+ action,
1662
+ upgradeUrl,
1204
1663
  attempted: false
1205
1664
  }
1206
1665
  };
1207
1666
  }
1208
1667
  try {
1209
- const { data, meta } = await client.checkIp(ip);
1668
+ const { data, meta } = await session.request((client) => client.checkIp(ip));
1210
1669
  if (meta.quota.remaining !== void 0 && (strongestQuota?.remaining === void 0 || meta.quota.remaining < strongestQuota.remaining)) {
1211
1670
  strongestQuota = meta.quota;
1212
1671
  }
1213
1672
  return { ip, ok: true, result: data };
1214
1673
  } catch (err) {
1215
- const { code, message, requestId } = commandFailure(err).info;
1674
+ const { code, message, requestId, action, upgradeUrl } = commandFailure(err).info;
1216
1675
  if (err instanceof NetRiskScanApiError) {
1217
1676
  if (isMonthlyQuotaError(code)) {
1218
1677
  quotaBlock ??= err;
@@ -1221,10 +1680,10 @@ async function runBatch(file, options) {
1221
1680
  blocked ??= err;
1222
1681
  }
1223
1682
  }
1224
- return { ip, ok: false, error: { code, message, requestId } };
1683
+ return { ip, ok: false, error: { code, message, requestId, action, upgradeUrl } };
1225
1684
  }
1226
1685
  });
1227
- const failure = quotaBlock ? await quotaFailure(quotaBlock, client) : void 0;
1686
+ const failure = quotaBlock ? await quotaFailure(quotaBlock, session.client) : void 0;
1228
1687
  if (options.jsonl) {
1229
1688
  for (const item of results) {
1230
1689
  if (failure && !item.ok && isMonthlyQuotaError(item.error.code)) {
@@ -1236,7 +1695,9 @@ async function runBatch(file, options) {
1236
1695
  } else {
1237
1696
  renderBatchTable(results);
1238
1697
  if (failure) reportFailure(failure);
1239
- else if (strongestQuota && isOfficialApi(options)) await warnAboutQuota(key, strongestQuota);
1698
+ else if (blocked) reportFailure(commandFailure(blocked));
1699
+ else if (strongestQuota && isOfficialApi(options))
1700
+ await warnAboutQuota(session.key, strongestQuota);
1240
1701
  }
1241
1702
  process.exitCode = computeBatchExitCode(results);
1242
1703
  if (failure && file !== "-") await offerQuotaUpgrade(failure.info.code, options);
@@ -1253,13 +1714,14 @@ function computeBatchExitCode(results) {
1253
1714
  // src/commands/auth.ts
1254
1715
  function registerAuthCommand(program2) {
1255
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)));
1256
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(
1257
1719
  (options) => runCommand(options, () => manageStore(() => saveKey(options)))
1258
1720
  );
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(
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(
1260
1722
  (options) => runCommand(options, () => manageStore(() => showKey(options)))
1261
1723
  );
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)));
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)));
1263
1725
  auth.command("logout").description("Remove the local key without revoking it at NetRiskScan").option("--json", "Output machine-readable JSON").action(
1264
1726
  (options) => runCommand(options, () => manageStore(() => logout(options)))
1265
1727
  );
@@ -1332,7 +1794,7 @@ async function showKey(options) {
1332
1794
  if (!key) {
1333
1795
  throw new CliError(
1334
1796
  "api_key_required",
1335
- "No stored API key. Create a key in the Developer Console and run auth save.",
1797
+ "No stored API key. Run netriskscan auth login to sign in with Google.",
1336
1798
  ExitCode.AuthError,
1337
1799
  WEB_PAGES.keys
1338
1800
  );
@@ -1349,9 +1811,8 @@ async function showKey(options) {
1349
1811
  }
1350
1812
  process.stdout.write(
1351
1813
  `${row("Plan", plan)}
1352
- ${row("Developer account", "See Developer Console")}
1353
1814
 
1354
- Your stored API key:
1815
+ Your stored API key is a sensitive credential. Keep it private.
1355
1816
  ${key}
1356
1817
  `
1357
1818
  );
@@ -1369,13 +1830,13 @@ async function showStatus(options) {
1369
1830
  }
1370
1831
  const key = supplied?.key ?? (isOfficialApi(options) ? stored : null);
1371
1832
  let status = "not_configured";
1372
- let plan;
1833
+ let usage;
1373
1834
  let failure;
1374
1835
  if (key) {
1375
1836
  try {
1376
1837
  const { data } = await createClient(key, { ...options, maxRetries: "0" }).getUsage();
1377
1838
  status = "active";
1378
- plan = data.plan;
1839
+ usage = data;
1379
1840
  } catch (error) {
1380
1841
  failure = commandFailure(error);
1381
1842
  status = failure.info.code;
@@ -1387,7 +1848,10 @@ async function showStatus(options) {
1387
1848
  status,
1388
1849
  source: supplied?.source ?? (key ? "os_credential_store" : void 0),
1389
1850
  key: key ? redactApiKey(key) : void 0,
1390
- plan,
1851
+ plan: usage?.plan,
1852
+ accountStatus: usage ? "active" : void 0,
1853
+ quota: usage?.units,
1854
+ quotaResetAt: usage?.period.end,
1391
1855
  storage,
1392
1856
  error: failure?.info
1393
1857
  };
@@ -1399,9 +1863,18 @@ async function showStatus(options) {
1399
1863
  row("Local credential", storage),
1400
1864
  row("Key source", details.source ?? "Unavailable"),
1401
1865
  row("Key", details.key ?? "Unavailable"),
1402
- row("Plan", plan ?? "Unavailable"),
1403
- row("Account / key name", "See Developer Console")
1866
+ row("Plan", usage?.plan ?? "Unavailable"),
1867
+ row("Account status", usage ? "Active" : "Unavailable"),
1868
+ row("Google account", "See Developer Console")
1404
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
+ }
1405
1878
  if (failure) lines.push(failure.info.message);
1406
1879
  if (!key) lines.push(WEB_PAGES.keys);
1407
1880
  process.stdout.write(`${lines.join("\n")}
@@ -1409,6 +1882,7 @@ async function showStatus(options) {
1409
1882
  }
1410
1883
  }
1411
1884
  async function logout(options) {
1885
+ await authorizationStorage.remove();
1412
1886
  const removed = await credentials.remove();
1413
1887
  const environmentKeyConfigured = Boolean(process.env.NETRISKSCAN_API_KEY);
1414
1888
  if (options.json) {
@@ -1475,7 +1949,7 @@ Sign in with the account that owns this key. Run npx netriskscan-cli usage to re
1475
1949
 
1476
1950
  // src/cli.ts
1477
1951
  var __dirname = dirname2(fileURLToPath(import.meta.url));
1478
- var pkg = JSON.parse(readFileSync(join2(__dirname, "..", "package.json"), "utf8"));
1952
+ var pkg = JSON.parse(readFileSync(join3(__dirname, "..", "package.json"), "utf8"));
1479
1953
  var program = new Command();
1480
1954
  program.name("netriskscan").description(
1481
1955
  "Query IP risk and network intelligence, manage your API key, and view developer quota."
@@ -1488,12 +1962,14 @@ Examples:
1488
1962
  $ netriskscan quota
1489
1963
  $ netriskscan batch ips.txt --jsonl
1490
1964
  $ netriskscan auth status
1965
+ $ netriskscan auth key
1491
1966
  $ netriskscan upgrade
1492
1967
 
1493
1968
  Developer API requires a valid API Key. Credentials are resolved from
1494
1969
  --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".
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.
1497
1973
 
1498
1974
  Environment variables:
1499
1975
  NETRISKSCAN_API_KEY Supply a Developer API key from a secret manager in CI.