@f5-sales-demo/xcsh 21.6.1 → 21.6.2

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.
@@ -39,8 +39,7 @@
39
39
  </div>
40
40
 
41
41
  <script id="session-data" type="application/json">{{SESSION_DATA}}</script>
42
- <script src="https://cdnjs.cloudflare.com/ajax/libs/marked/15.0.4/marked.min.js" integrity="sha512-VmLxPVdDGeR+F0DzUHVqzHwaR4ZSSh1g/7aYXwKT1PAGVxunOEcysta+4H5Utvmpr2xExEPybZ8q+iM9F1tGdw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
43
- <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
42
+ <template-vendor-js/>
44
43
  <template-js/>
45
44
  </body>
46
45
  </html>
@@ -1483,7 +1483,7 @@
1483
1483
  const text = typeof content === 'string' ? content :
1484
1484
  content.filter(c => c.type === 'text').map(c => c.text).join('\n');
1485
1485
  if (text.trim()) {
1486
- html += `<div class="markdown-content">${safeMarkedParse(text)}</div>`;
1486
+ html += `<div class="markdown-content markdown-root">${safeMarkedParse(text)}</div>`;
1487
1487
  }
1488
1488
  html += '</div>';
1489
1489
  return html;
@@ -1494,7 +1494,7 @@
1494
1494
 
1495
1495
  for (const block of msg.content) {
1496
1496
  if (block.type === 'text' && block.text.trim()) {
1497
- html += `<div class="assistant-text markdown-content">${safeMarkedParse(block.text)}</div>`;
1497
+ html += `<div class="assistant-text markdown-content markdown-root">${safeMarkedParse(block.text)}</div>`;
1498
1498
  } else if (block.type === 'thinking' && block.thinking.trim()) {
1499
1499
  html += `<div class="thinking-block">
1500
1500
  <div class="thinking-text">${escapeHtml(block.thinking)}</div>
@@ -1572,14 +1572,14 @@
1572
1572
  if (entry.type === 'branch_summary') {
1573
1573
  return `<div class="branch-summary" id="${entryId}">${tsHtml}
1574
1574
  <div class="branch-summary-header">Branch Summary</div>
1575
- <div class="markdown-content">${safeMarkedParse(entry.summary)}</div>
1575
+ <div class="markdown-content markdown-root">${safeMarkedParse(entry.summary)}</div>
1576
1576
  </div>`;
1577
1577
  }
1578
1578
 
1579
1579
  if (entry.type === 'custom_message' && entry.display) {
1580
1580
  return `<div class="hook-message" id="${entryId}">${tsHtml}
1581
1581
  <div class="hook-type">[${escapeHtml(entry.customType)}]</div>
1582
- <div class="markdown-content">${safeMarkedParse(typeof entry.content === 'string' ? entry.content : JSON.stringify(entry.content))}</div>
1582
+ <div class="markdown-content markdown-root">${safeMarkedParse(typeof entry.content === 'string' ? entry.content : JSON.stringify(entry.content))}</div>
1583
1583
  </div>`;
1584
1584
  }
1585
1585
 
@@ -1777,6 +1777,7 @@
1777
1777
  marked.use({
1778
1778
  breaks: true,
1779
1779
  gfm: true,
1780
+ extensions: xcshMath.createMathExtensions(),
1780
1781
  renderer: {
1781
1782
  // Code blocks: syntax highlight, no HTML escaping
1782
1783
  code(token) {
@@ -1806,6 +1807,28 @@
1806
1807
  // Inline code: escape HTML
1807
1808
  codespan(token) {
1808
1809
  return `<code>${escapeHtml(token.text)}</code>`;
1810
+ },
1811
+ // Raw HTML is source text in exports. Generated MathML arrives through
1812
+ // the math extension renderer and is unaffected by this boundary.
1813
+ html(token) {
1814
+ return escapeHtml(token.raw || token.text || '');
1815
+ },
1816
+ link(token) {
1817
+ const href = String(token.href || '');
1818
+ const label = this.parser.parseInline(token.tokens);
1819
+ if (!/^(?:https?:|mailto:|#|\/(?!\/)|\.\.?\/)/i.test(href)) {
1820
+ return label;
1821
+ }
1822
+ const title = token.title ? ` title="${escapeHtml(token.title)}"` : '';
1823
+ return `<a href="${escapeHtml(href)}"${title}>${label}</a>`;
1824
+ },
1825
+ image(token) {
1826
+ const href = String(token.href || '');
1827
+ if (!/^(?:https?:|data:image\/(?:png|gif|jpeg|webp);base64,|\/(?!\/)|\.\.?\/)/i.test(href)) {
1828
+ return escapeHtml(token.text || href);
1829
+ }
1830
+ const title = token.title ? ` title="${escapeHtml(token.title)}"` : '';
1831
+ return `<img src="${escapeHtml(href)}" alt="${escapeHtml(token.text || '')}"${title}>`;
1809
1832
  }
1810
1833
  }
1811
1834
  });
@@ -17,17 +17,17 @@ export interface BuildInfo {
17
17
  }
18
18
 
19
19
  export const BUILD_INFO: BuildInfo = {
20
- "version": "21.6.1",
21
- "commit": "db8ba10fa1b6c43cf1a0316cdc64b9cd11b8b3ba",
22
- "shortCommit": "db8ba10",
20
+ "version": "21.6.2",
21
+ "commit": "5e2a7c0fa5a0df2e2c8ba3431dcc7494baa0d347",
22
+ "shortCommit": "5e2a7c0",
23
23
  "branch": "main",
24
- "tag": "v21.6.1",
25
- "commitDate": "2026-09-02T10:51:55+00:00",
26
- "buildDate": "2026-09-02T11:27:32.586Z",
24
+ "tag": "v21.6.2",
25
+ "commitDate": "2026-09-02T13:57:01+00:00",
26
+ "buildDate": "2026-09-02T14:29:21.730Z",
27
27
  "dirty": true,
28
28
  "prNumber": "",
29
29
  "repoUrl": "https://github.com/f5-sales-demo/xcsh",
30
30
  "repoSlug": "f5-sales-demo/xcsh",
31
- "commitUrl": "https://github.com/f5-sales-demo/xcsh/commit/db8ba10fa1b6c43cf1a0316cdc64b9cd11b8b3ba",
32
- "releaseUrl": "https://github.com/f5-sales-demo/xcsh/releases/tag/v21.6.1"
31
+ "commitUrl": "https://github.com/f5-sales-demo/xcsh/commit/5e2a7c0fa5a0df2e2c8ba3431dcc7494baa0d347",
32
+ "releaseUrl": "https://github.com/f5-sales-demo/xcsh/releases/tag/v21.6.2"
33
33
  };
@@ -1,12 +1,65 @@
1
1
  import { Container, Input, matchesKey, Spacer, Text, TruncatedText } from "@f5-sales-demo/pi-tui";
2
- import type { XCSHContext } from "../../services/xcsh-context";
3
- import { deriveTenantFromUrl, isSensitiveEnvKey, XCSH_CONSOLE_PASSWORD, XCSH_USERNAME } from "../../services/xcsh-env";
2
+ import type { TokenValidationResult, XCSHContext } from "../../services/xcsh-context";
3
+ import {
4
+ deriveTenantFromUrl,
5
+ isSensitiveEnvKey,
6
+ normalizeApiUrl,
7
+ XCSH_API_TOKEN,
8
+ XCSH_API_URL,
9
+ XCSH_CONSOLE_PASSWORD,
10
+ XCSH_USERNAME,
11
+ } from "../../services/xcsh-env";
4
12
  import { theme } from "../theme/theme";
5
13
  import { matchesAppInterrupt } from "../utils/keybinding-matchers";
6
14
  import { DynamicBorder } from "./dynamic-border";
7
15
 
8
16
  const NAME_PATTERN = /^[a-zA-Z0-9_-]{1,64}$/;
9
17
 
18
+ type WizardCredentialKey =
19
+ | typeof XCSH_API_URL
20
+ | typeof XCSH_API_TOKEN
21
+ | typeof XCSH_USERNAME
22
+ | typeof XCSH_CONSOLE_PASSWORD;
23
+
24
+ /**
25
+ * Normalize a credential pasted from a shell or dotenv file without ever
26
+ * interpreting arbitrary assignments. Raw values remain valid, including
27
+ * tokens that contain or end with `=`.
28
+ */
29
+ export function normalizeWizardCredential(value: string, expectedKey: WizardCredentialKey): string | null {
30
+ if (/\r|\n/.test(value)) return null;
31
+ const trimmed = value.trim();
32
+ if (!trimmed) return "";
33
+ const assignment = trimmed.match(/^(?:#\s*)?(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/);
34
+ if (assignment) {
35
+ if (assignment[1] !== expectedKey) return null;
36
+ return unwrapWholeValueQuotes(assignment[2].trim());
37
+ }
38
+ if (trimmed === expectedKey || trimmed === `export ${expectedKey}` || trimmed === `#${expectedKey}`) return null;
39
+ // A shell-style assignment for another field must not silently become a token.
40
+ if (/^(?:#\s*)?(?:export\s+)?[A-Za-z_][A-Za-z0-9_]*\s*=/.test(trimmed)) return null;
41
+ return unwrapWholeValueQuotes(trimmed);
42
+ }
43
+
44
+ function unwrapWholeValueQuotes(value: string): string | null {
45
+ if (value.startsWith('"') || value.endsWith('"') || value.startsWith("'") || value.endsWith("'")) {
46
+ if (!(value.length >= 2 && value[0] === value.at(-1))) return null;
47
+ }
48
+ if (
49
+ value.length >= 2 &&
50
+ ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'")))
51
+ ) {
52
+ return value.slice(1, -1);
53
+ }
54
+ return value;
55
+ }
56
+
57
+ export function normalizeWizardUrl(value: string): string | null {
58
+ const normalized = normalizeWizardCredential(value, XCSH_API_URL);
59
+ if (normalized === null || validateWizardUrl(normalized)) return null;
60
+ return normalizeApiUrl(normalized);
61
+ }
62
+
10
63
  export function validateWizardUrl(url: string): string | null {
11
64
  if (!url.trim()) return "URL is required";
12
65
  try {
@@ -22,12 +75,45 @@ export function validateWizardUrl(url: string): string | null {
22
75
  }
23
76
  }
24
77
 
78
+ function prefill(input: Input, value: string): void {
79
+ input.setValue(value);
80
+ input.setCursorToEnd();
81
+ }
82
+
25
83
  export function validateWizardName(name: string): string | null {
26
84
  if (!name.trim()) return "Name is required";
27
85
  if (!NAME_PATTERN.test(name)) return "Name must be 1-64 characters: letters, digits, hyphens, underscores";
28
86
  return null;
29
87
  }
30
88
 
89
+ function validationFailureMessage(reason: TokenValidationResult["failureReason"]): string {
90
+ switch (reason) {
91
+ case "unauthorized":
92
+ return "Authentication failed (HTTP 401) — check your token";
93
+ case "forbidden":
94
+ return "Access forbidden (HTTP 403) — check token permissions";
95
+ case "redirect":
96
+ return "The tenant redirected this request — check the tenant URL";
97
+ case "non_json":
98
+ return "The tenant returned a non-JSON response — check the tenant URL";
99
+ case "rate_limited":
100
+ return "The tenant rate-limited validation — retry shortly";
101
+ case "server":
102
+ return "The tenant server failed validation — retry shortly";
103
+ case "timeout":
104
+ return "Validation timed out — check network access and the tenant URL";
105
+ default:
106
+ return "Could not reach the tenant — check the URL and network";
107
+ }
108
+ }
109
+
110
+ function validationDetails(state: WizardState, httpStatus?: number, latencyMs?: number): string {
111
+ const maskedToken = state.token.length > 4 ? `${"*".repeat(8)}${state.token.slice(-4)}` : "****";
112
+ const status = httpStatus === undefined ? "n/a" : String(httpStatus);
113
+ const latency = latencyMs === undefined ? "n/a" : `${latencyMs}ms`;
114
+ return `Endpoint: ${state.url}/api/web/namespaces | HTTP: ${status} | Latency: ${latency} | Token: ${maskedToken} (${state.token.length} chars)`;
115
+ }
116
+
31
117
  type WizardStep =
32
118
  | "url"
33
119
  | "token"
@@ -84,6 +170,8 @@ export class ContextAddWizard extends Container {
84
170
  #selectedIndex = 0;
85
171
  #validationError: string | null = null;
86
172
  #validationFailed = false;
173
+ #validationInFlight = false;
174
+ #validationDetails: string | null = null;
87
175
  #onCompleteCallback: (context: XCSHContext, activate: boolean) => void;
88
176
  #onCancelCallback: () => void;
89
177
  #onRenderCallback: () => void;
@@ -165,7 +253,7 @@ export class ContextAddWizard extends Container {
165
253
  this.#contentContainer.addChild(new Spacer(1));
166
254
 
167
255
  this.#inputField = new Input();
168
- this.#inputField.setValue(this.#state.url);
256
+ prefill(this.#inputField, this.#state.url);
169
257
  this.#contentContainer.addChild(this.#inputField);
170
258
  this.#contentContainer.addChild(new Spacer(1));
171
259
 
@@ -185,7 +273,7 @@ export class ContextAddWizard extends Container {
185
273
 
186
274
  this.#inputField = new Input();
187
275
  this.#inputField.setMasked(true);
188
- this.#inputField.setValue(this.#state.token);
276
+ prefill(this.#inputField, this.#state.token);
189
277
  this.#contentContainer.addChild(this.#inputField);
190
278
  this.#contentContainer.addChild(new Spacer(1));
191
279
 
@@ -204,8 +292,8 @@ export class ContextAddWizard extends Container {
204
292
  this.#contentContainer.addChild(new Spacer(1));
205
293
 
206
294
  this.#inputField = new Input();
207
- const prefill = this.#state.name || deriveTenantFromUrl(this.#state.url) || "";
208
- this.#inputField.setValue(prefill);
295
+ const initialValue = this.#state.name || deriveTenantFromUrl(this.#state.url) || "";
296
+ prefill(this.#inputField, initialValue);
209
297
  this.#contentContainer.addChild(this.#inputField);
210
298
  this.#contentContainer.addChild(new Spacer(1));
211
299
 
@@ -221,6 +309,10 @@ export class ContextAddWizard extends Container {
221
309
  if (this.#validationFailed) {
222
310
  this.#contentContainer.addChild(new Text(theme.fg("contentAccent", "Validation Failed")));
223
311
  this.#contentContainer.addChild(new Spacer(1));
312
+ if (this.#validationDetails) {
313
+ this.#contentContainer.addChild(new Text(theme.fg("muted", this.#validationDetails), 0, 0));
314
+ this.#contentContainer.addChild(new Spacer(1));
315
+ }
224
316
  this.#contentContainer.addChild(
225
317
  new Text(theme.fg("error", `✗ ${this.#validationError ?? "Validation failed"}`), 0, 0),
226
318
  );
@@ -243,10 +335,12 @@ export class ContextAddWizard extends Container {
243
335
  this.#contentContainer.addChild(new Text("Validating credentials...", 0, 0));
244
336
  this.#contentContainer.addChild(new Spacer(1));
245
337
 
246
- void this.#runValidation();
338
+ if (!this.#validationInFlight) void this.#runValidation();
247
339
  }
248
340
 
249
341
  async #runValidation(): Promise<void> {
342
+ if (this.#validationInFlight) return;
343
+ this.#validationInFlight = true;
250
344
  try {
251
345
  const { ContextService } = await import("../../services/xcsh-context");
252
346
  const service = await ContextService.getOrInit();
@@ -265,53 +359,22 @@ export class ContextAddWizard extends Container {
265
359
  return;
266
360
  }
267
361
 
268
- // Failure — show error with Retry/Edit options
362
+ // Failure — show error with Retry/Edit options.
269
363
  this.#validationFailed = true;
270
364
  this.#selectedIndex = 0;
271
- const errorMsg =
272
- result.status === "auth_error"
273
- ? "Authentication failed — check your token"
274
- : "Could not reach the server — check the URL";
275
- this.#contentContainer.clear();
276
- this.#contentContainer.addChild(new Text(theme.fg("contentAccent", "Validation Failed")));
277
- this.#contentContainer.addChild(new Spacer(1));
278
- this.#contentContainer.addChild(new Text(theme.fg("error", `✗ ${errorMsg}`), 0, 0));
279
- this.#contentContainer.addChild(new Spacer(1));
280
-
281
- const options = ["Retry", "Edit (start over)"];
282
- for (let i = 0; i < options.length; i++) {
283
- const isSelected = i === this.#selectedIndex;
284
- const prefix = isSelected ? theme.fg("chromeAccent", `${theme.nav.cursor} `) : " ";
285
- const text = isSelected ? theme.fg("contentAccent", options[i]) : options[i];
286
- this.#contentContainer.addChild(new Text(prefix + text, 0, 0));
287
- }
288
- this.#contentContainer.addChild(new Spacer(1));
289
- this.#contentContainer.addChild(
290
- new Text(theme.fg("muted", "[↑↓ to navigate, Enter to select, Esc to go back]"), 0, 0),
291
- );
365
+ this.#validationError = validationFailureMessage(result.failureReason);
366
+ this.#validationDetails = validationDetails(this.#state, result.httpStatus, result.latencyMs);
367
+ this.#renderStep();
292
368
  this.#requestRender();
293
369
  } catch (error) {
294
- const errorMsg = error instanceof Error ? error.message : String(error);
295
370
  this.#validationFailed = true;
296
371
  this.#selectedIndex = 0;
297
- this.#contentContainer.clear();
298
- this.#contentContainer.addChild(new Text(theme.fg("contentAccent", "Validation Failed")));
299
- this.#contentContainer.addChild(new Spacer(1));
300
- this.#contentContainer.addChild(new Text(theme.fg("error", `✗ ${errorMsg}`), 0, 0));
301
- this.#contentContainer.addChild(new Spacer(1));
302
-
303
- const options = ["Retry", "Edit (start over)"];
304
- for (let i = 0; i < options.length; i++) {
305
- const isSelected = i === this.#selectedIndex;
306
- const prefix = isSelected ? theme.fg("chromeAccent", `${theme.nav.cursor} `) : " ";
307
- const text = isSelected ? theme.fg("contentAccent", options[i]) : options[i];
308
- this.#contentContainer.addChild(new Text(prefix + text, 0, 0));
309
- }
310
- this.#contentContainer.addChild(new Spacer(1));
311
- this.#contentContainer.addChild(
312
- new Text(theme.fg("muted", "[↑↓ to navigate, Enter to select, Esc to go back]"), 0, 0),
313
- );
372
+ this.#validationError = error instanceof Error ? error.message : "Validation request failed";
373
+ this.#validationDetails = validationDetails(this.#state);
374
+ this.#renderStep();
314
375
  this.#requestRender();
376
+ } finally {
377
+ this.#validationInFlight = false;
315
378
  }
316
379
  }
317
380
 
@@ -322,7 +385,7 @@ export class ContextAddWizard extends Container {
322
385
  this.#contentContainer.addChild(new Spacer(1));
323
386
 
324
387
  this.#inputField = new Input();
325
- this.#inputField.setValue(this.#state.namespace);
388
+ prefill(this.#inputField, this.#state.namespace);
326
389
  this.#contentContainer.addChild(this.#inputField);
327
390
  this.#contentContainer.addChild(new Spacer(1));
328
391
 
@@ -341,7 +404,7 @@ export class ContextAddWizard extends Container {
341
404
  this.#contentContainer.addChild(new Spacer(1));
342
405
 
343
406
  this.#inputField = new Input();
344
- this.#inputField.setValue(this.#state.username);
407
+ prefill(this.#inputField, this.#state.username);
345
408
  this.#contentContainer.addChild(this.#inputField);
346
409
  this.#contentContainer.addChild(new Spacer(1));
347
410
 
@@ -358,7 +421,7 @@ export class ContextAddWizard extends Container {
358
421
 
359
422
  this.#inputField = new Input();
360
423
  this.#inputField.setMasked(true);
361
- this.#inputField.setValue(this.#state.password);
424
+ prefill(this.#inputField, this.#state.password);
362
425
  this.#contentContainer.addChild(this.#inputField);
363
426
  this.#contentContainer.addChild(new Spacer(1));
364
427
 
@@ -480,29 +543,44 @@ export class ContextAddWizard extends Container {
480
543
  #saveInputAndProceed(): void {
481
544
  if (!this.#inputField) return;
482
545
 
483
- const value = this.#inputField.getValue().trim();
546
+ const rawValue = this.#inputField.getValue();
547
+ const value = rawValue.trim();
484
548
 
485
549
  switch (this.#currentStep) {
486
550
  case "url": {
487
- const urlError = validateWizardUrl(value);
551
+ const normalizedUrl = normalizeWizardUrl(rawValue);
552
+ const urlError = normalizedUrl
553
+ ? null
554
+ : validateWizardUrl(normalizeWizardCredential(rawValue, XCSH_API_URL) ?? "");
488
555
  if (urlError) {
489
556
  this.#validationError = urlError;
490
557
  this.#renderStep();
491
558
  return;
492
559
  }
560
+ if (!normalizedUrl) {
561
+ this.#validationError = "Tenant URL must be a raw URL or XCSH_API_URL assignment";
562
+ this.#renderStep();
563
+ return;
564
+ }
493
565
  this.#validationError = null;
494
- this.#state.url = value;
566
+ this.#state.url = normalizedUrl;
495
567
  this.#currentStep = "token";
496
568
  break;
497
569
  }
498
570
  case "token": {
499
- if (!value) {
571
+ const normalizedToken = normalizeWizardCredential(rawValue, XCSH_API_TOKEN);
572
+ if (normalizedToken === null) {
573
+ this.#validationError = "Token must be a raw value or XCSH_API_TOKEN assignment";
574
+ this.#renderStep();
575
+ return;
576
+ }
577
+ if (!normalizedToken) {
500
578
  this.#validationError = "API token is required";
501
579
  this.#renderStep();
502
580
  return;
503
581
  }
504
582
  this.#validationError = null;
505
- this.#state.token = value;
583
+ this.#state.token = normalizedToken;
506
584
  this.#currentStep = "name";
507
585
  break;
508
586
  }
@@ -525,15 +603,24 @@ export class ContextAddWizard extends Container {
525
603
  break;
526
604
  }
527
605
  case "username": {
528
- // Trimmed: usernames never carry meaningful surrounding whitespace.
529
- this.#state.username = value;
606
+ const username = normalizeWizardCredential(rawValue, XCSH_USERNAME);
607
+ if (username === null) {
608
+ this.#validationError = "Username must be a raw value or XCSH_USERNAME assignment";
609
+ this.#renderStep();
610
+ return;
611
+ }
612
+ this.#state.username = username;
530
613
  this.#currentStep = "password";
531
614
  break;
532
615
  }
533
616
  case "password": {
534
- // Preserve the password exactly as typed — do NOT use the trimmed
535
- // `value`, since a password may legitimately contain whitespace.
536
- this.#state.password = this.#inputField.getValue();
617
+ const password = normalizeWizardCredential(rawValue, XCSH_CONSOLE_PASSWORD);
618
+ if (password === null) {
619
+ this.#validationError = "Password must be a raw value or XCSH_CONSOLE_PASSWORD assignment";
620
+ this.#renderStep();
621
+ return;
622
+ }
623
+ this.#state.password = password;
537
624
  this.#currentStep = "confirm";
538
625
  this.#selectedIndex = 0;
539
626
  break;
@@ -550,11 +637,16 @@ export class ContextAddWizard extends Container {
550
637
  this.#validationFailed = false;
551
638
  if (this.#selectedIndex === 0) {
552
639
  // Retry
640
+ this.#validationError = null;
641
+ this.#validationDetails = null;
553
642
  this.#renderStep();
554
643
  } else {
555
644
  // Edit — go back to url
556
645
  this.#currentStep = "url";
646
+ this.#state.token = "";
647
+ this.#state.password = "";
557
648
  this.#validationError = null;
649
+ this.#validationDetails = null;
558
650
  this.#selectedIndex = 0;
559
651
  this.#renderStep();
560
652
  }
@@ -72,6 +72,28 @@ export interface XCSHContext {
72
72
 
73
73
  export type AuthStatus = "connected" | "auth_error" | "offline" | "unknown";
74
74
 
75
+ /** Safe, actionable classification of a failed token validation request. */
76
+ export type ValidationFailureReason =
77
+ | "unauthorized"
78
+ | "forbidden"
79
+ | "redirect"
80
+ | "non_json"
81
+ | "rate_limited"
82
+ | "server"
83
+ | "timeout"
84
+ | "network";
85
+
86
+ export interface TokenValidationResult {
87
+ status: AuthStatus;
88
+ latencyMs?: number;
89
+ /** HTTP status, when a response was received. */
90
+ httpStatus?: number;
91
+ /** Safe failure category. No response body or credential data is included. */
92
+ failureReason?: ValidationFailureReason;
93
+ /** @deprecated Use failureReason. Retained for existing callers. */
94
+ errorClass?: "network" | "credential" | "url_not_found";
95
+ }
96
+
75
97
  export type TokenHealth = "ok" | "expiring" | "expired";
76
98
 
77
99
  export interface ContextStatus {
@@ -976,7 +998,7 @@ export class ContextService {
976
998
  timeoutMs?: number;
977
999
  apiUrl?: string;
978
1000
  apiToken?: string;
979
- }): Promise<{ status: AuthStatus; latencyMs?: number; errorClass?: "network" | "credential" | "url_not_found" }> {
1001
+ }): Promise<TokenValidationResult> {
980
1002
  // Use explicit credentials if provided (for non-active contexts or env-backed sessions),
981
1003
  // otherwise fall back to effective credentials (env override > active context)
982
1004
  const effectiveUrl = options?.apiUrl ?? process.env[XCSH_API_URL] ?? this.#activeContext?.apiUrl;
@@ -998,11 +1020,22 @@ export class ContextService {
998
1020
  (options?.apiUrl !== undefined && options.apiUrl !== activeUrl) ||
999
1021
  (options?.apiToken !== undefined && options.apiToken !== activeToken);
1000
1022
 
1001
- const url = `${effectiveUrl}/api/web/namespaces`;
1023
+ const url = `${normalizeApiUrl(effectiveUrl)}/api/web/namespaces`;
1002
1024
  const timeout = options?.timeoutMs ?? 3000;
1003
1025
  const checkedAt = Date.now();
1026
+ const start = performance.now();
1027
+ const recordResult = (result: TokenValidationResult): TokenValidationResult => {
1028
+ logger.debug("XCSH token validation", {
1029
+ endpoint: url,
1030
+ status: result.status,
1031
+ httpStatus: result.httpStatus,
1032
+ latencyMs: result.latencyMs,
1033
+ failureReason: result.failureReason,
1034
+ tokenLength: effectiveToken.length,
1035
+ });
1036
+ return result;
1037
+ };
1004
1038
  try {
1005
- const start = performance.now();
1006
1039
  const response = await fetch(url, {
1007
1040
  method: "GET",
1008
1041
  headers: { Authorization: `APIToken ${effectiveToken}`, Accept: "application/json" },
@@ -1016,31 +1049,74 @@ export class ContextService {
1016
1049
  }
1017
1050
  if (response.type === "opaqueredirect" || (response.status >= 300 && response.status < 400)) {
1018
1051
  if (!adHoc) this.#authStatus = "offline";
1019
- return { status: "offline", latencyMs, errorClass: "url_not_found" };
1052
+ return recordResult({
1053
+ status: "offline",
1054
+ latencyMs,
1055
+ httpStatus: response.status || undefined,
1056
+ failureReason: "redirect",
1057
+ errorClass: "url_not_found",
1058
+ });
1020
1059
  }
1021
- if (response.ok) {
1060
+ if (response.status === 200) {
1022
1061
  const contentType = response.headers.get("content-type") ?? "";
1023
1062
  if (!contentType.includes("application/json")) {
1024
1063
  if (!adHoc) this.#authStatus = "offline";
1025
- return { status: "offline", latencyMs, errorClass: "url_not_found" };
1064
+ return recordResult({
1065
+ status: "offline",
1066
+ latencyMs,
1067
+ httpStatus: response.status,
1068
+ failureReason: "non_json",
1069
+ errorClass: "url_not_found",
1070
+ });
1071
+ }
1072
+ try {
1073
+ await response.clone().json();
1074
+ } catch {
1075
+ if (!adHoc) this.#authStatus = "offline";
1076
+ return recordResult({
1077
+ status: "offline",
1078
+ latencyMs,
1079
+ httpStatus: response.status,
1080
+ failureReason: "non_json",
1081
+ errorClass: "url_not_found",
1082
+ });
1026
1083
  }
1027
1084
  if (!adHoc) this.#authStatus = "connected";
1028
- return { status: "connected", latencyMs };
1085
+ return recordResult({ status: "connected", latencyMs, httpStatus: response.status });
1029
1086
  }
1030
1087
  if (response.status === 401 || response.status === 403) {
1031
1088
  if (!adHoc) this.#authStatus = "auth_error";
1032
- return { status: "auth_error", latencyMs, errorClass: "credential" };
1089
+ return recordResult({
1090
+ status: "auth_error",
1091
+ latencyMs,
1092
+ httpStatus: response.status,
1093
+ failureReason: response.status === 401 ? "unauthorized" : "forbidden",
1094
+ errorClass: "credential",
1095
+ });
1033
1096
  }
1034
1097
  // 5xx, 429, etc. — server reachable but unhealthy; treat as offline so startup retry fires
1035
1098
  if (!adHoc) this.#authStatus = "offline";
1036
- return { status: "offline", latencyMs, errorClass: "network" };
1037
- } catch {
1099
+ return recordResult({
1100
+ status: "offline",
1101
+ latencyMs,
1102
+ httpStatus: response.status,
1103
+ failureReason: response.status === 429 ? "rate_limited" : response.status >= 500 ? "server" : "network",
1104
+ errorClass: "network",
1105
+ });
1106
+ } catch (error) {
1107
+ const latencyMs = Math.round(performance.now() - start);
1108
+ const isTimeout = error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError");
1038
1109
  if (!adHoc) {
1039
1110
  this.#lastAuthLatencyMs = Date.now() - checkedAt;
1040
1111
  this.#lastAuthCheckedAt = checkedAt;
1041
1112
  this.#authStatus = "offline";
1042
1113
  }
1043
- return { status: "offline", errorClass: "network" };
1114
+ return recordResult({
1115
+ status: "offline",
1116
+ latencyMs,
1117
+ failureReason: isTimeout ? "timeout" : "network",
1118
+ errorClass: "network",
1119
+ });
1044
1120
  }
1045
1121
  }
1046
1122