netriskscan-cli 2.1.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/CHANGELOG.md CHANGED
@@ -1,3 +1,15 @@
1
+ # [2.2.0](https://github.com/TeamQQ/netriskscan-cli/compare/v2.1.0...v2.2.0) (2026-12-02)
2
+
3
+
4
+ ### Bug Fixes
5
+
6
+ * **auth:** honor one-time CLI key exchange and reuse saved keys ([b13453a](https://github.com/TeamQQ/netriskscan-cli/commit/b13453abd3081906ff75551033a8440e22d9985e))
7
+
8
+
9
+ ### Features
10
+
11
+ * **cli:** resume queries after loopback Google authorization ([31cf0b5](https://github.com/TeamQQ/netriskscan-cli/commit/31cf0b5f2e58d8a626df8d092e08ca043c4285b3))
12
+
1
13
  # [2.1.0](https://github.com/TeamQQ/netriskscan-cli/compare/v2.0.0...v2.1.0) (2026-12-02)
2
14
 
3
15
 
package/README.md CHANGED
@@ -33,11 +33,14 @@ Use the CLI for investigations and operational tasks. Use the TypeScript client
33
33
  npx netriskscan-cli check 8.8.8.8
34
34
  ```
35
35
 
36
- With no configured key in an interactive terminal, the CLI opens NetRiskScan's Google
37
- authorization page. Click **Continue with Google**, enter the eight-character confirmation
38
- code shown in the terminal, and approve the installation. NetRiskScan sets up a developer
39
- account when needed and issues the API key. The CLI saves the key in the OS credential
40
- store and continues your original query. With a configured key the lookup runs immediately.
36
+ With a configured key, the lookup runs immediately. When automatic Google sign-in is
37
+ available, the CLI opens your browser if an interactive command has no key. Complete
38
+ Google sign-in once. The browser returns to the CLI on `127.0.0.1`, and the CLI
39
+ saves the installation's key in the OS credential store and resumes the original query
40
+ with its existing options and output format.
41
+
42
+ The loopback endpoint requires the current NetRiskScan service. With an existing key
43
+ you can continue using the CLI on a headless device or against an older deployment.
41
44
 
42
45
  ## Product overview
43
46
 
@@ -115,9 +118,13 @@ To authorize the CLI before running a query, run:
115
118
  npx netriskscan-cli auth login
116
119
  ```
117
120
 
118
- If the system browser cannot open, the CLI prints the authorization link and
119
- confirmation code. Open the link in a browser on any device and keep the terminal
120
- running. The terminal waits up to ten minutes. Press Ctrl+C to cancel.
121
+ If the system browser cannot open, the CLI prints an authorization link. Open it in
122
+ a browser on the same computer and keep the terminal running. The terminal waits
123
+ up to ten minutes. Press Ctrl+C to cancel the query.
124
+
125
+ Interactive `check --json` and `batch --jsonl` keep the response on stdout and put
126
+ sign-in messages on stderr. Set `NETRISKSCAN_API_KEY` for CI, redirected output, or
127
+ batch input piped on stdin.
121
128
 
122
129
  For a key you already manage in the [Developer Console](https://www.netriskscan.com/developer/keys),
123
130
  use `ip-risk:read` for `check` and `batch` and `usage:read` for quota and plan
@@ -139,13 +146,12 @@ each invocation. `auth save` sets the variable within its own process.
139
146
  | `npx netriskscan-cli auth status` | Verifies the selected key and shows its masked value, storage, plan, and monthly usage. |
140
147
  | `npx netriskscan-cli auth logout` | Removes the local credential. Server-side revocation is available in the Developer Console. |
141
148
 
142
- The CLI displays the newly saved key once after authorization. Treat it as a sensitive
143
- credential. View your Google email and key name in the Developer Console.
149
+ The CLI stores the new API key in your OS credential store and displays a redacted
150
+ identifier. Existing installations reuse the matching saved key.
144
151
 
145
- The [Developer API authorization contract](https://www.netriskscan.com/assets/paid-api-v1.yaml)
146
- uses browser confirmation, PKCE-protected polling, and RSA-encrypted key delivery.
152
+ The loopback flow uses a random state, PKCE S256, and RSA-encrypted key delivery.
147
153
  The OS credential store holds the key and any pending delivery proof. If you remove
148
- the local key while the installation's server key is still active, revoke that key
154
+ the local key while the installation's server key is still active, manage the key
149
155
  in the Developer Console before authorizing a replacement.
150
156
 
151
157
  ## CLI and TypeScript integration
@@ -812,8 +818,8 @@ See [examples/](examples/) for runnable scripts.
812
818
 
813
819
  ## Security
814
820
 
815
- - The interactive CLI displays a newly saved key once after Google authorization.
816
- Use `auth key` to view a saved key again. Error output and browser URLs omit the API key.
821
+ - Google authorization displays a redacted key identifier. Use `auth key` to view a saved key explicitly.
822
+ Error output and browser URLs omit the API key.
817
823
  - There is no telemetry: **the CLI does not collect usage analytics or telemetry** of any
818
824
  kind, in any version.
819
825
  - If `--debug` needs to show an authorization value, it is redacted
@@ -839,7 +845,30 @@ Endpoints called by the CLI:
839
845
 
840
846
  - `GET /v1/ip-risk/{ip}` with `ip-risk:read`
841
847
  - `GET /v1/usage` with `usage:read`
842
- - `POST /v1/cli/authorization` and its poll, exchange, and acknowledge endpoints for Google sign-in
848
+ - `POST /v1/cli/authorization/loopback` and its exchange and acknowledgement endpoints
849
+ for automatic Google sign-in
850
+
851
+ ### Loopback authorization contract
852
+
853
+ The CLI sends `transactionId`, `installationId`, `state`, `redirectUri`,
854
+ `codeChallenge` (S256), and `publicKey` (base64 DER SPKI) in the start request.
855
+ The server returns `flow: "loopback"`, `transactionId`, `expiresAt`, and the
856
+ `https://www.netriskscan.com/developer/cli/loopback` browser URL
857
+ with `#transactionId=<id>&state=<state>`. The registered redirect URI uses an
858
+ ephemeral port on `http://127.0.0.1` and the exact path `/oauth/callback`.
859
+
860
+ After Google verifies the account, the server creates or links the Developer
861
+ account and redirects to the registered URI with `state` and a one-time `code`
862
+ (32 bytes encoded as base64url). It can instead return `state` and an OAuth
863
+ `error` such as `access_denied`. The CLI exchanges the code by posting
864
+ `{ codeVerifier, authorizationCode }` to `/v1/cli/authorization/loopback/{id}/exchange`.
865
+ The server verifies the PKCE proof, expiry, and code use, then issues a key bound
866
+ to the installation. An `issued` response contains `accountEmail`, `keyId`, `encryptedApiKey` (base64),
867
+ `encryption: "RSA-OAEP-256"`, and `expiresAt`. An `existing` response identifies the
868
+ installation's stored Key ID and carries no ciphertext. The code is redeemable once.
869
+ After saving the key, the CLI acknowledges delivery. If the server response was lost
870
+ or the existing local key is unavailable, revoke the installation key in the Developer
871
+ Console and sign in again.
843
872
 
844
873
  The [OpenAPI contract](https://www.netriskscan.com/assets/paid-api-v1.yaml) also
845
874
  documents the server-side batch endpoint. Key creation, rotation, and revocation
@@ -890,8 +919,9 @@ Yes - `netriskscan check <ip> --json` prints the raw API response, and
890
919
 
891
920
  ### Does NetRiskScan CLI work without an API key?
892
921
 
893
- The CLI obtains a key through [interactive Google authorization](#getting-an-api-key).
894
- For CI and machine output, set `NETRISKSCAN_API_KEY` before running the command.
922
+ The CLI can obtain a key through [interactive Google authorization](#getting-an-api-key)
923
+ using the loopback service. For unattended runs, set
924
+ `NETRISKSCAN_API_KEY` before running the command.
895
925
 
896
926
  ## Official resources
897
927
 
package/dist/cli.js CHANGED
@@ -156,7 +156,7 @@ var WEB_PAGES = {
156
156
  plans: "https://www.netriskscan.com/pricing.html",
157
157
  billing: "https://www.netriskscan.com/developer/billing"
158
158
  };
159
- var AUTHORIZATION_PAGE = "https://www.netriskscan.com/developer/cli";
159
+ var LOOPBACK_AUTHORIZATION_PAGE = "https://www.netriskscan.com/developer/cli/loopback";
160
160
  function isInteractive(machineOutput) {
161
161
  const ci = process.env.CI?.trim().toLowerCase();
162
162
  return Boolean(
@@ -168,7 +168,7 @@ async function openBrowser(page) {
168
168
  }
169
169
  async function openAuthorizationBrowser(url) {
170
170
  const destination = new URL(url);
171
- if (destination.href.split("#", 1)[0] !== AUTHORIZATION_PAGE) return false;
171
+ if (destination.href.split("#", 1)[0] !== LOOPBACK_AUTHORIZATION_PAGE) return false;
172
172
  return launch(destination.href);
173
173
  }
174
174
  async function launch(url) {
@@ -917,11 +917,144 @@ async function readId(path) {
917
917
  return id;
918
918
  }
919
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
+
920
1055
  // src/commands/googleAuthorization.ts
921
- var AUTHORIZATION_PATH = "/v1/cli/authorization";
1056
+ var AUTHORIZATION_PATH = "/v1/cli/authorization/loopback";
922
1057
  var AUTHORIZATION_LIFETIME_MS = 10 * 6e4;
923
- var POLL_INTERVAL_MS = 5e3;
924
- var TOKEN = /^[A-Za-z0-9_-]{43}$/;
925
1058
  var generateRsa = promisify(generateKeyPair);
926
1059
  function authError(code, message, url) {
927
1060
  return new CliError(code, message, ExitCode.AuthError, url);
@@ -958,18 +1091,20 @@ async function pendingAuthorization(installationId) {
958
1091
  );
959
1092
  }
960
1093
  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;
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;
964
1097
  }
965
1098
  }
966
1099
  }
1100
+ }
1101
+ async function newTransaction(installationId) {
967
1102
  const { privateKey } = await generateRsa("rsa", {
968
1103
  modulusLength: 2048,
969
1104
  privateKeyEncoding: { type: "pkcs8", format: "der" },
970
1105
  publicKeyEncoding: { type: "spki", format: "der" }
971
1106
  });
972
- const pending = {
1107
+ const transaction = {
973
1108
  transactionId: randomUUID2().replaceAll("-", ""),
974
1109
  installationId,
975
1110
  state: randomBytes2(32).toString("base64url"),
@@ -978,8 +1113,7 @@ async function pendingAuthorization(installationId) {
978
1113
  deadline: Date.now() + AUTHORIZATION_LIFETIME_MS
979
1114
  };
980
1115
  privateKey.fill(0);
981
- await persist(pending);
982
- return pending;
1116
+ return transaction;
983
1117
  }
984
1118
  async function persist(pending) {
985
1119
  const secret = Buffer.from(JSON.stringify(pending));
@@ -994,7 +1128,7 @@ async function pause(milliseconds, deadline, signal) {
994
1128
  if (remaining <= 0) throw expired();
995
1129
  await wait(Math.min(remaining, milliseconds), void 0, { signal });
996
1130
  }
997
- async function post(path, body, deadline, signal, polling = false) {
1131
+ async function post(path, body, deadline, signal) {
998
1132
  for (let attempt = 0; ; attempt++) {
999
1133
  signal.throwIfAborted();
1000
1134
  const remaining = deadline - Date.now();
@@ -1013,7 +1147,7 @@ async function post(path, body, deadline, signal, polling = false) {
1013
1147
  signal: controller.signal,
1014
1148
  body: JSON.stringify(body)
1015
1149
  });
1016
- if (response.status === 204 && path.endsWith("/acknowledge")) return { data: {} };
1150
+ if (response.status === 204 && path.endsWith("/acknowledge")) return {};
1017
1151
  const parsed = await response.json();
1018
1152
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
1019
1153
  data = parsed;
@@ -1023,15 +1157,10 @@ async function post(path, body, deadline, signal, polling = false) {
1023
1157
  signal.removeEventListener("abort", abort);
1024
1158
  }
1025
1159
  signal.throwIfAborted();
1026
- if (response?.ok && data && !path.endsWith("/acknowledge")) return { data };
1160
+ if (response?.ok && data && !path.endsWith("/acknowledge")) return data;
1027
1161
  const status = response?.status;
1028
1162
  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 };
1163
+ const backoff = Math.max(1e3, Number.isFinite(seconds) ? seconds * 1e3 : 0);
1035
1164
  if (attempt < 2 && (status === 429 || status === 503 || !response || response?.ok && !data)) {
1036
1165
  await pause(backoff, deadline, signal);
1037
1166
  continue;
@@ -1043,7 +1172,12 @@ async function post(path, body, deadline, signal, polling = false) {
1043
1172
  ExitCode.ApiError
1044
1173
  );
1045
1174
  const code = data?.error?.code;
1046
- if (status === 410) throw expired();
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();
1047
1181
  if (status === 401)
1048
1182
  throw authError(
1049
1183
  "invalid_transaction_proof",
@@ -1056,7 +1190,7 @@ async function post(path, body, deadline, signal, polling = false) {
1056
1190
  WEB_PAGES.keys
1057
1191
  );
1058
1192
  }
1059
- if (code === "already_delivered" || code === "key_unavailable") {
1193
+ if (code === "already_delivered" || code === "key_unavailable" || code === "authorization_code_used") {
1060
1194
  throw authError(
1061
1195
  code,
1062
1196
  "This authorization cannot deliver a key. Check your local credentials and the Developer Console.",
@@ -1064,7 +1198,10 @@ async function post(path, body, deadline, signal, polling = false) {
1064
1198
  );
1065
1199
  }
1066
1200
  if (code === "account_not_active")
1067
- throw authError(code, "An active, verified developer account is required.");
1201
+ throw authError(
1202
+ code,
1203
+ "The Developer account associated with your Google sign-in is inactive."
1204
+ );
1068
1205
  if (status === 429 || status === 503) {
1069
1206
  throw new CliError(
1070
1207
  "authorization_unavailable",
@@ -1077,46 +1214,15 @@ async function post(path, body, deadline, signal, polling = false) {
1077
1214
  }
1078
1215
  function validatedBrowserUrl(data, pending) {
1079
1216
  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) {
1217
+ const hash = `#transactionId=${transactionId}&state=${state}`;
1218
+ if (data.flow !== "loopback" || data.transactionId !== transactionId || data.browserUrl !== LOOPBACK_AUTHORIZATION_PAGE + hash || "confirmationCode" in data) {
1083
1219
  throw invalidResponse();
1084
1220
  }
1085
1221
  return data.browserUrl;
1086
1222
  }
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
1223
  function decryptKey(data, privateKey) {
1118
1224
  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) {
1225
+ if (data.encryption !== "RSA-OAEP-256" || typeof data.keyId !== "string" || !/^[a-f0-9]{8}$/.test(data.keyId) || ciphertext?.length !== 256) {
1120
1226
  throw invalidResponse();
1121
1227
  }
1122
1228
  try {
@@ -1126,7 +1232,7 @@ function decryptKey(data, privateKey) {
1126
1232
  );
1127
1233
  try {
1128
1234
  const key = bytes.toString("utf8");
1129
- if (!/^nrs_live_[A-Za-z0-9_-]+$/.test(key) || key.length > 160) throw invalidResponse();
1235
+ if (!key.startsWith(`nrs_live_${data.keyId}_`) || !/^nrs_live_[A-Za-z0-9_-]+$/.test(key) || key.length > 160) throw invalidResponse();
1130
1236
  return key;
1131
1237
  } finally {
1132
1238
  bytes.fill(0);
@@ -1135,58 +1241,99 @@ function decryptKey(data, privateKey) {
1135
1241
  throw invalidResponse();
1136
1242
  }
1137
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
+ }
1138
1289
  async function authorizeGoogle() {
1139
1290
  const controller = new AbortController();
1140
1291
  const cancel = () => controller.abort();
1141
1292
  process.once("SIGINT", cancel);
1293
+ let callback;
1142
1294
  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);
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;
1179
1301
  await persist(pending);
1180
1302
  }
1303
+ const path = `${AUTHORIZATION_PATH}/${pending.transactionId}`;
1181
1304
  const proof = {
1182
1305
  codeVerifier: pending.codeVerifier,
1183
1306
  authorizationCode: pending.authorizationCode
1184
1307
  };
1185
- const { data } = await post(`${path}/exchange`, proof, pending.deadline, controller.signal);
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();
1186
1312
  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;
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);
1190
1337
  try {
1191
1338
  const acknowledgementDeadline = Math.min(pending.deadline, Date.now() + 4e3);
1192
1339
  await post(`${path}/acknowledge`, proof, acknowledgementDeadline, controller.signal);
@@ -1197,18 +1344,19 @@ ${url}
1197
1344
  );
1198
1345
  }
1199
1346
  controller.signal.throwIfAborted();
1200
- process.stdout.write(
1347
+ process.stderr.write(
1201
1348
  `
1202
- NetRiskScan Authentication
1203
-
1204
- Google account : See signed-in account in the browser
1205
- Account status : Active
1206
- API Key : ${key}
1349
+ NetRiskScan CLI
1207
1350
 
1208
- API Key saved successfully.
1351
+ Google Authentication Successful
1209
1352
 
1353
+ Account : ${email}
1354
+ Key Status : Active
1355
+ Local Config : Saved
1210
1356
  `
1211
1357
  );
1358
+ process.stderr.write(`API Key : ${redactApiKey(key)}
1359
+ `);
1212
1360
  return key;
1213
1361
  } catch (error) {
1214
1362
  if (controller.signal.aborted)
@@ -1219,12 +1367,15 @@ API Key saved successfully.
1219
1367
  "transaction_expired",
1220
1368
  "invalid_transaction_proof",
1221
1369
  "already_delivered",
1370
+ "authorization_code_used",
1222
1371
  "key_unavailable"
1223
1372
  ].includes(error.code)) {
1224
1373
  await authorizationStorage.remove().catch(() => void 0);
1225
1374
  }
1226
1375
  throw error;
1227
1376
  } finally {
1377
+ callback?.finish(false);
1378
+ callback?.close();
1228
1379
  process.removeListener("SIGINT", cancel);
1229
1380
  }
1230
1381
  }
@@ -1279,9 +1430,14 @@ async function requireSession(options, setup = true) {
1279
1430
  storeUnavailable = true;
1280
1431
  }
1281
1432
  }
1282
- const mayAuthorize = official && setup && isInteractive(options.json || options.jsonl);
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
+ };
1283
1439
  const authorizedInitially = !key && mayAuthorize;
1284
- if (authorizedInitially) key = await authorizeGoogle();
1440
+ if (authorizedInitially) key = await authorizeAndResume();
1285
1441
  if (!key) {
1286
1442
  const storeMessage = storeUnavailable ? " The OS credential store is unavailable." : "";
1287
1443
  throw new CliError(
@@ -1308,7 +1464,7 @@ async function requireSession(options, setup = true) {
1308
1464
  } catch (error) {
1309
1465
  if (!mayAuthorize || authorizedInitially || !(error instanceof NetRiskScanApiError) || error.status !== 401 && error.status !== 403 || error.code !== "api_key_required" && error.code !== "api_key_expired")
1310
1466
  throw error;
1311
- replacement ??= authorizeGoogle().then((newKey) => {
1467
+ replacement ??= authorizeAndResume().then((newKey) => {
1312
1468
  if (supplied) {
1313
1469
  process.stderr.write(
1314
1470
  "Update the API key supplied by your shell or command for future invocations.\n"