azdo-cli 0.10.0-develop.526 → 0.10.0-develop.556

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.
Files changed (3) hide show
  1. package/README.md +2 -1
  2. package/dist/index.js +217 -3
  3. package/package.json +3 -3
package/README.md CHANGED
@@ -17,7 +17,8 @@ Azure DevOps CLI focused on work item read/write workflows.
17
17
  - Check branch pull request status, open PRs to `develop`, list PR comment threads for any PR (`--pr-number`), and resolve/reopen threads from the CLI (`pr`)
18
18
  - Persist org/project/default fields in local config (`config`)
19
19
  - List all fields of a work item (`list-fields`)
20
- - Authenticate per Azure DevOps organization with `azdo auth login` — OAuth (Microsoft Entra) by default, or a Personal Access Token via `--use-pat` (or the `AZDO_PAT` env var). Credentials are stored in the OS credential store. Inspect with `azdo auth status`, remove with `azdo auth logout`. See [docs/authentication.md](docs/authentication.md).
20
+ - Authenticate per Azure DevOps organization with `azdo auth login` — OAuth (Microsoft Entra) by default, or a Personal Access Token via `--use-pat` (or the `AZDO_PAT` env var). Credentials are stored in the OS credential store. Inspect with `azdo auth status`, remove with `azdo auth logout`. Diagnose auth problems with `azdo auth diagnose`. See [docs/authentication.md](docs/authentication.md).
21
+ - Trace all HTTP requests to a local file with `--trace <filepath>` (sensitive headers and tokens are automatically redacted).
21
22
 
22
23
  ## Installation
23
24
 
package/dist/index.js CHANGED
@@ -51,6 +51,78 @@ var version = pkg.version;
51
51
  // src/commands/get-item.ts
52
52
  import { Command } from "commander";
53
53
 
54
+ // src/services/trace-writer.ts
55
+ import { openSync, writeSync, closeSync } from "fs";
56
+ import { platform } from "os";
57
+ var REDACTED = "[REDACTED]";
58
+ var SENSITIVE_HEADER = /^(authorization|x-.*token)$/i;
59
+ var SENSITIVE_QUERY_PARAM = /^(token|pat)$/i;
60
+ var SENSITIVE_BODY_FIELD = /^(token|accessToken|pat)$/;
61
+ function redactHeaders(headers) {
62
+ const out = {};
63
+ for (const [key, value] of Object.entries(headers)) {
64
+ out[key] = SENSITIVE_HEADER.test(key) ? REDACTED : value;
65
+ }
66
+ return out;
67
+ }
68
+ function redactUrl(url) {
69
+ try {
70
+ const u = new URL(url);
71
+ for (const [key] of u.searchParams.entries()) {
72
+ if (SENSITIVE_QUERY_PARAM.test(key)) {
73
+ u.searchParams.set(key, REDACTED);
74
+ }
75
+ }
76
+ return u.toString();
77
+ } catch {
78
+ return url;
79
+ }
80
+ }
81
+ function redactBody(body) {
82
+ if (body === null) return null;
83
+ try {
84
+ const parsed = JSON.parse(body);
85
+ let changed = false;
86
+ const redacted = { ...parsed };
87
+ for (const key of Object.keys(parsed)) {
88
+ if (SENSITIVE_BODY_FIELD.test(key)) {
89
+ redacted[key] = REDACTED;
90
+ changed = true;
91
+ }
92
+ }
93
+ return changed ? JSON.stringify(redacted) : body;
94
+ } catch {
95
+ return body;
96
+ }
97
+ }
98
+ var TraceWriter = class {
99
+ fd;
100
+ constructor(filepath) {
101
+ const mode = platform() === "win32" ? void 0 : 384;
102
+ this.fd = openSync(filepath, "a", mode);
103
+ }
104
+ append(entry) {
105
+ const line = JSON.stringify(entry) + "\n\n";
106
+ writeSync(this.fd, line);
107
+ }
108
+ close() {
109
+ closeSync(this.fd);
110
+ }
111
+ };
112
+ var activeWriter = null;
113
+ function initTraceWriter(filepath) {
114
+ try {
115
+ activeWriter = new TraceWriter(filepath);
116
+ } catch (err) {
117
+ const msg = err instanceof Error ? err.message : String(err);
118
+ process.stderr.write(`Warning: could not open trace file "${filepath}": ${msg}
119
+ `);
120
+ }
121
+ }
122
+ function getActiveTraceWriter() {
123
+ return activeWriter;
124
+ }
125
+
54
126
  // src/services/azdo-client.ts
55
127
  var DEFAULT_FIELDS = [
56
128
  "System.Title",
@@ -74,12 +146,48 @@ function authHeaders(credentialOrPat) {
74
146
  const token = Buffer.from(`:${credentialOrPat.pat}`).toString("base64");
75
147
  return { Authorization: `Basic ${token}` };
76
148
  }
149
+ async function fetchRaw(url, init) {
150
+ let response;
151
+ try {
152
+ response = await fetch(url, init);
153
+ } catch (err) {
154
+ throw new Error(`NETWORK_ERROR: ${err instanceof Error ? err.message : String(err)}`, { cause: err });
155
+ }
156
+ const body = await response.text();
157
+ return { status: response.status, body };
158
+ }
77
159
  async function fetchWithErrors(url, init) {
160
+ const writer = getActiveTraceWriter();
78
161
  let response;
79
162
  try {
80
163
  response = await fetch(url, init);
81
- } catch {
82
- throw new Error("NETWORK_ERROR");
164
+ } catch (err) {
165
+ throw new Error("NETWORK_ERROR", { cause: err });
166
+ }
167
+ if (writer) {
168
+ const reqHeaders = redactHeaders(init.headers ?? {});
169
+ const reqBody = typeof init.body === "string" ? redactBody(init.body) : null;
170
+ let responseBody = "";
171
+ const clone = response.clone();
172
+ try {
173
+ responseBody = await clone.text();
174
+ } catch {
175
+ }
176
+ const respHeaders = {};
177
+ response.headers.forEach((v, k) => {
178
+ respHeaders[k] = v;
179
+ });
180
+ const entry = {
181
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
182
+ method: (init.method ?? "GET").toUpperCase(),
183
+ url: redactUrl(url),
184
+ requestHeaders: reqHeaders,
185
+ requestBody: reqBody ?? null,
186
+ responseStatus: response.status,
187
+ responseHeaders: respHeaders,
188
+ responseBody
189
+ };
190
+ writer.append(entry);
83
191
  }
84
192
  if (response.status === 401) throw new Error("AUTH_FAILED");
85
193
  if (response.status === 403) throw new Error("PERMISSION_DENIED");
@@ -867,11 +975,18 @@ function parseSingleRemoteLine(line) {
867
975
  const url = urlEnd === -1 ? afterTab : afterTab.slice(0, urlEnd);
868
976
  return { remoteName, url };
869
977
  }
978
+ function decodePctSegment(segment) {
979
+ try {
980
+ return decodeURIComponent(segment);
981
+ } catch {
982
+ return segment;
983
+ }
984
+ }
870
985
  function matchAzdoRemote(remoteName, url) {
871
986
  for (const pattern of patterns) {
872
987
  const match = pattern.exec(url);
873
988
  if (!match) continue;
874
- const project = match[2];
989
+ const project = decodePctSegment(match[2]);
875
990
  if (/^DefaultCollection$/i.test(project)) return null;
876
991
  return { remoteName, org: match[1], project, hasEmbeddedSecret: httpsEmbeddedSecret.test(url) };
877
992
  }
@@ -1561,6 +1676,79 @@ function createClearPatCommand() {
1561
1676
 
1562
1677
  // src/commands/auth.ts
1563
1678
  import { Command as Command3 } from "commander";
1679
+
1680
+ // src/services/auth-diagnostics.ts
1681
+ async function runConnectivityTest(org, cred) {
1682
+ const url = `https://dev.azure.com/${encodeURIComponent(org)}/_apis/projects?api-version=7.1&$top=1`;
1683
+ let result;
1684
+ try {
1685
+ result = await fetchRaw(url, { headers: authHeaders(cred) });
1686
+ } catch (err) {
1687
+ return { status: "failed", error: err instanceof Error ? err.message : String(err) };
1688
+ }
1689
+ if (result.status >= 200 && result.status < 300) {
1690
+ return { status: "ok", error: null };
1691
+ }
1692
+ let error = `HTTP ${result.status}`;
1693
+ try {
1694
+ const parsed = JSON.parse(result.body);
1695
+ if (typeof parsed.message === "string" && parsed.message.trim() !== "") {
1696
+ error = parsed.message.trim();
1697
+ }
1698
+ } catch {
1699
+ }
1700
+ return { status: "failed", error };
1701
+ }
1702
+ async function diagnoseAuth(org, project, resolveCredential) {
1703
+ const cred = await resolveCredential(org);
1704
+ if (cred === null) {
1705
+ return {
1706
+ authType: "none",
1707
+ credentialSource: null,
1708
+ org,
1709
+ project,
1710
+ connectivityStatus: "no-credentials",
1711
+ connectivityError: null
1712
+ };
1713
+ }
1714
+ const connectivity = await runConnectivityTest(org, cred);
1715
+ const envVarName = process.env.AZDO_PAT ? "AZDO_PAT" : "dotenv";
1716
+ const sourceLabel = cred.source === "env" ? `env:${envVarName}` : "credential-store";
1717
+ return {
1718
+ authType: cred.kind ?? "pat",
1719
+ credentialSource: sourceLabel,
1720
+ org,
1721
+ project,
1722
+ connectivityStatus: connectivity.status,
1723
+ connectivityError: connectivity.error
1724
+ };
1725
+ }
1726
+ function formatDiagnosticReport(report, json) {
1727
+ if (json) {
1728
+ return JSON.stringify(report, null, 2);
1729
+ }
1730
+ let connectivityLine;
1731
+ if (report.connectivityStatus === "ok") {
1732
+ connectivityLine = "OK";
1733
+ } else if (report.connectivityStatus === "no-credentials") {
1734
+ connectivityLine = "no credentials found";
1735
+ } else {
1736
+ connectivityLine = "FAILED";
1737
+ }
1738
+ const lines = [
1739
+ `Auth type: ${report.authType}`,
1740
+ `Source: ${report.credentialSource ?? "(none)"}`,
1741
+ `Org: ${report.org}`,
1742
+ `Project: ${report.project ?? "(not set)"}`,
1743
+ `Connectivity: ${connectivityLine}`
1744
+ ];
1745
+ if (report.connectivityStatus === "failed" && report.connectivityError !== null) {
1746
+ lines.push(`Error: ${report.connectivityError}`);
1747
+ }
1748
+ return lines.join("\n");
1749
+ }
1750
+
1751
+ // src/commands/auth.ts
1564
1752
  async function readStdinToString() {
1565
1753
  const chunks = [];
1566
1754
  for await (const chunk of process.stdin) {
@@ -1982,6 +2170,25 @@ Note: \`azdo auth\` (no subcommand) preserves the legacy PAT-prompt entry point;
1982
2170
  const globals = logoutCmd.optsWithGlobals();
1983
2171
  await handleLogout(options, globals.org);
1984
2172
  });
2173
+ const diagnoseCmd = command.command("diagnose").description("Show auth type, credential source, org, and live connectivity test result").option("--org <name>", "Azure DevOps organization (overrides context resolution)").option("--project <name>", "Azure DevOps project (optional context)").option("--json", "emit JSON instead of human-readable text", false);
2174
+ diagnoseCmd.action(async (options) => {
2175
+ const globals = diagnoseCmd.optsWithGlobals();
2176
+ const orgName = options.org ?? globals.org;
2177
+ const resolved = resolveOrg({ org: orgName });
2178
+ if (!resolved) {
2179
+ process.stderr.write(`${formatResolutionError()}
2180
+ `);
2181
+ process.exitCode = 1;
2182
+ return;
2183
+ }
2184
+ const report = await diagnoseAuth(resolved.org, options.project ?? null, resolveAuthCredential);
2185
+ const output = formatDiagnosticReport(report, options.json ?? false);
2186
+ process.stdout.write(`${output}
2187
+ `);
2188
+ if (report.connectivityStatus === "failed") {
2189
+ process.exitCode = 1;
2190
+ }
2191
+ });
1985
2192
  return command;
1986
2193
  }
1987
2194
 
@@ -5203,6 +5410,7 @@ process.stderr.on("error", exitOnEpipe);
5203
5410
  var program = new Command17();
5204
5411
  program.name("azdo").description("Azure DevOps CLI tool").version(version, "-v, --version");
5205
5412
  program.option("--no-update-check", "Skip the check for a newer published version");
5413
+ program.option("--trace <filepath>", "Append redacted HTTP request/response trace to a file (owner-read-only permissions)");
5206
5414
  program.addCommand(createGetItemCommand());
5207
5415
  program.addCommand(createAuthCommand());
5208
5416
  program.addCommand(createClearPatCommand());
@@ -5220,6 +5428,12 @@ program.addCommand(createCommentsCommand());
5220
5428
  program.addCommand(createDownloadAttachmentCommand());
5221
5429
  program.addCommand(createRelationsCommand());
5222
5430
  program.showHelpAfterError();
5431
+ program.hook("preAction", () => {
5432
+ const { trace } = program.opts();
5433
+ if (trace) {
5434
+ initTraceWriter(trace);
5435
+ }
5436
+ });
5223
5437
  program.hook("postAction", async () => {
5224
5438
  const notice = await getUpdateNotice({ enabled: program.opts().updateCheck });
5225
5439
  if (notice) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "azdo-cli",
3
- "version": "0.10.0-develop.526",
3
+ "version": "0.10.0-develop.556",
4
4
  "description": "Azure DevOps CLI tool",
5
5
  "type": "module",
6
6
  "bin": {
@@ -14,8 +14,8 @@
14
14
  "lint": "eslint src/",
15
15
  "typecheck": "tsc --noEmit",
16
16
  "format": "prettier --check src/",
17
- "test": "npm run build && vitest run tests/unit tests/integration",
18
- "test:unit": "npm run build && vitest run tests/unit",
17
+ "test": "npm run typecheck && npm run lint && npm run build && vitest run tests/unit tests/integration",
18
+ "test:unit": "npm run typecheck && npm run lint && npm run build && vitest run tests/unit",
19
19
  "test:integration": "npm run build && vitest run tests/integration",
20
20
  "test:integration:full": "bash scripts/setup-keyring.sh && npm run test:integration"
21
21
  },