@respan/cli 0.17.3 → 0.19.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.
@@ -2,6 +2,7 @@ import { Flags } from '@oclif/core';
2
2
  import { select, input } from '@inquirer/prompts';
3
3
  import * as http from 'node:http';
4
4
  import * as open from 'node:child_process';
5
+ import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
5
6
  import { BaseCommand } from '../../lib/base-command.js';
6
7
  import { setCredential, setActiveProfile } from '../../lib/config.js';
7
8
  import { printBanner, printLoginSuccess } from '../../lib/banner.js';
@@ -11,6 +12,44 @@ const CALLBACK_PATH = '/callback';
11
12
  const LOGIN_TIMEOUT_MS = 120_000;
12
13
  const LOGIN_URL_BASE = 'https://platform.respan.ai/login';
13
14
  const ENTERPRISE_LOGIN_URL_BASE = 'https://enterprise.respan.ai/login';
15
+ // Overrides the web login page, e.g. a staging frontend. Pair it with
16
+ // --base-url for that deployment's API.
17
+ const LOGIN_URL_ENV = 'RESPAN_LOGIN_URL';
18
+ const CODE_EXCHANGE_PATH = '/auth/cli/token/';
19
+ function base64Url(buffer) {
20
+ return buffer.toString('base64url');
21
+ }
22
+ function newLoginAttempt() {
23
+ const codeVerifier = base64Url(randomBytes(32));
24
+ return {
25
+ codeVerifier,
26
+ codeChallenge: base64Url(createHash('sha256').update(codeVerifier).digest()),
27
+ state: base64Url(randomBytes(16)),
28
+ };
29
+ }
30
+ function isSameState(expected, received) {
31
+ if (!received)
32
+ return false;
33
+ const expectedBytes = Buffer.from(expected);
34
+ const receivedBytes = Buffer.from(received);
35
+ return expectedBytes.length === receivedBytes.length && timingSafeEqual(expectedBytes, receivedBytes);
36
+ }
37
+ async function exchangeCode(baseUrl, code, attempt, redirectUri) {
38
+ const origin = baseUrl.replace(/\/+$/, '').replace(/\/api$/, '');
39
+ const response = await fetch(`${origin}${CODE_EXCHANGE_PATH}`, {
40
+ method: 'POST',
41
+ headers: { 'Content-Type': 'application/json' },
42
+ body: JSON.stringify({ code, code_verifier: attempt.codeVerifier, redirect_uri: redirectUri }),
43
+ });
44
+ if (!response.ok) {
45
+ throw new Error('The sign-in code was rejected or expired. Please run `respan auth login` again.');
46
+ }
47
+ const body = (await response.json());
48
+ if (!body.access || !body.refresh) {
49
+ throw new Error('The sign-in response was missing a token. Please try again.');
50
+ }
51
+ return { token: body.access, refreshToken: body.refresh, email: body.email };
52
+ }
14
53
  function openBrowser(url) {
15
54
  const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'start' : 'xdg-open';
16
55
  open.exec(`${cmd} "${url}"`);
@@ -31,29 +70,53 @@ function errorHtml(msg) {
31
70
  .card{text-align:center;padding:2rem}.icon{font-size:3rem;margin-bottom:1rem;color:#f06464}p{color:#aaa;margin-top:0.5rem}</style></head>
32
71
  <body><div class="card"><div class="icon">&#10007;</div><h2>Login failed</h2><p>${msg}</p></div></body></html>`;
33
72
  }
34
- function waitForBrowserLogin(enterprise) {
73
+ function waitForBrowserLogin(enterprise, baseUrl) {
74
+ const attempt = newLoginAttempt();
75
+ const redirectUri = `http://localhost:${CALLBACK_PORT}${CALLBACK_PATH}`;
35
76
  return new Promise((resolve, reject) => {
77
+ let isSettled = false;
78
+ const fail = (res, message) => {
79
+ res.writeHead(400, { 'Content-Type': 'text/html' });
80
+ res.end(errorHtml(message));
81
+ cleanup();
82
+ reject(new Error(message));
83
+ };
84
+ const succeed = (res, result) => {
85
+ res.writeHead(200, { 'Content-Type': 'text/html' });
86
+ res.end(successHtml());
87
+ cleanup();
88
+ resolve(result);
89
+ };
36
90
  const server = http.createServer((req, res) => {
37
91
  const url = new URL(req.url || '/', `http://localhost:${CALLBACK_PORT}`);
38
- if (url.pathname !== CALLBACK_PATH) {
92
+ if (url.pathname !== CALLBACK_PATH || isSettled) {
39
93
  res.writeHead(404);
40
94
  res.end('Not found');
41
95
  return;
42
96
  }
97
+ const code = url.searchParams.get('code');
98
+ if (code) {
99
+ // A callback for another login attempt (or a crafted link) is ignored
100
+ // without spending this attempt.
101
+ if (!isSameState(attempt.state, url.searchParams.get('state'))) {
102
+ res.writeHead(400, { 'Content-Type': 'text/html' });
103
+ res.end(errorHtml('This sign-in link is not from your current login. Please try again.'));
104
+ return;
105
+ }
106
+ isSettled = true;
107
+ exchangeCode(baseUrl, code, attempt, redirectUri).then((result) => succeed(res, result), (error) => fail(res, error.message));
108
+ return;
109
+ }
110
+ // A web app that predates the code flow sends the tokens themselves.
43
111
  const token = url.searchParams.get('token');
44
112
  const refreshToken = url.searchParams.get('refresh_token');
45
113
  const email = url.searchParams.get('email') || undefined;
114
+ isSettled = true;
46
115
  if (!token || !refreshToken) {
47
- res.writeHead(400, { 'Content-Type': 'text/html' });
48
- res.end(errorHtml('Missing token. Please try again.'));
49
- cleanup();
50
- reject(new Error('Login callback missing token or refresh_token.'));
116
+ fail(res, 'Missing sign-in code. Please try again.');
51
117
  return;
52
118
  }
53
- res.writeHead(200, { 'Content-Type': 'text/html' });
54
- res.end(successHtml());
55
- cleanup();
56
- resolve({ token, refreshToken, email });
119
+ succeed(res, { token, refreshToken, email });
57
120
  });
58
121
  const timeout = setTimeout(() => {
59
122
  cleanup();
@@ -72,11 +135,13 @@ function waitForBrowserLogin(enterprise) {
72
135
  }
73
136
  });
74
137
  server.listen(CALLBACK_PORT, '127.0.0.1', () => {
75
- const redirectUri = `http://localhost:${CALLBACK_PORT}${CALLBACK_PATH}`;
76
- const loginUrlBase = enterprise ? ENTERPRISE_LOGIN_URL_BASE : LOGIN_URL_BASE;
138
+ const loginUrlBase = process.env[LOGIN_URL_ENV] || (enterprise ? ENTERPRISE_LOGIN_URL_BASE : LOGIN_URL_BASE);
77
139
  const loginUrl = new URL(loginUrlBase);
78
140
  loginUrl.searchParams.set('mode', 'cli');
79
141
  loginUrl.searchParams.set('redirect_uri', redirectUri);
142
+ loginUrl.searchParams.set('code_challenge', attempt.codeChallenge);
143
+ loginUrl.searchParams.set('code_challenge_method', 'S256');
144
+ loginUrl.searchParams.set('state', attempt.state);
80
145
  console.log('');
81
146
  console.log(' Opening browser to log in...');
82
147
  console.log(` If the browser doesn't open, visit:`);
@@ -123,7 +188,7 @@ class AuthLogin extends BaseCommand {
123
188
  await printLoginSuccess(undefined, profile);
124
189
  return;
125
190
  }
126
- const result = await waitForBrowserLogin(enterprise);
191
+ const result = await waitForBrowserLogin(enterprise, baseUrl);
127
192
  setCredential(profile, {
128
193
  type: 'jwt',
129
194
  accessToken: result.token,
@@ -6,7 +6,7 @@ export default class EvaluatorsRun extends BaseCommand {
6
6
  };
7
7
  static flags: {
8
8
  'dataset-id': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
9
- 'log-ids': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
9
+ 'span-ids': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
10
10
  params: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
11
11
  'api-key': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
12
12
  'base-url': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
@@ -20,8 +20,8 @@ class EvaluatorsRun extends BaseCommand {
20
20
  ...extra,
21
21
  evaluator_id: args.id,
22
22
  ...(flags['dataset-id'] ? { dataset_id: flags['dataset-id'] } : {}),
23
- ...(flags['log-ids']
24
- ? { log_ids: flags['log-ids'].split(',').map((s) => s.trim()) }
23
+ ...(flags['span-ids']
24
+ ? { log_ids: flags['span-ids'].split(',').map((s) => s.trim()) }
25
25
  : {}),
26
26
  }));
27
27
  this.log(JSON.stringify(data, null, 2));
@@ -36,7 +36,7 @@ EvaluatorsRun.args = { id: Args.string({ description: 'Evaluator ID', required:
36
36
  EvaluatorsRun.flags = {
37
37
  ...BaseCommand.baseFlags,
38
38
  'dataset-id': Flags.string({ description: 'Dataset ID to evaluate against' }),
39
- 'log-ids': Flags.string({ description: 'Comma-separated log/span IDs to evaluate' }),
39
+ 'span-ids': Flags.string({ description: 'Comma-separated span IDs to evaluate (--log-ids still works)', aliases: ['log-ids'] }),
40
40
  params: Flags.string({ description: 'Additional parameters as JSON string' }),
41
41
  };
42
42
  export default EvaluatorsRun;
@@ -1,8 +1,9 @@
1
1
  import { BaseCommand } from '../../lib/base-command.js';
2
2
  export default class LogsGet extends BaseCommand {
3
3
  static description: string;
4
+ static aliases: string[];
4
5
  static args: {
5
- id: import("@oclif/core/interfaces").Arg<string, Record<string, unknown>>;
6
+ 'span-id': import("@oclif/core/interfaces").Arg<string, Record<string, unknown>>;
6
7
  };
7
8
  static flags: {
8
9
  'api-key': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
@@ -6,7 +6,7 @@ class LogsGet extends BaseCommand {
6
6
  this.globalFlags = flags;
7
7
  try {
8
8
  const client = this.getClient();
9
- const data = await this.spin('Fetching span', () => client.spans.retrieveSpan({ Authorization: this.getAuthHeader(), unique_id: args.id }));
9
+ const data = await this.spin('Fetching span', () => client.spans.retrieveSpan({ Authorization: this.getAuthHeader(), unique_id: args['span-id'] }));
10
10
  this.log(JSON.stringify(data, null, 2));
11
11
  }
12
12
  catch (error) {
@@ -14,7 +14,8 @@ class LogsGet extends BaseCommand {
14
14
  }
15
15
  }
16
16
  }
17
- LogsGet.description = 'Get a specific log span';
18
- LogsGet.args = { id: Args.string({ description: 'Span ID', required: true }) };
17
+ LogsGet.description = 'Get one span by its span ID (also: respan spans get)';
18
+ LogsGet.aliases = ['spans:get'];
19
+ LogsGet.args = { 'span-id': Args.string({ description: 'Span ID (span_id in MCP)', required: true }) };
19
20
  LogsGet.flags = { ...BaseCommand.baseFlags };
20
21
  export default LogsGet;
@@ -1,5 +1,6 @@
1
1
  import { BaseCommand } from '../../lib/base-command.js';
2
2
  export default class LogsList extends BaseCommand {
3
+ static aliases: string[];
3
4
  static description: string;
4
5
  static flags: {
5
6
  limit: import("@oclif/core/interfaces").OptionFlag<number, import("@oclif/core/interfaces").CustomOptions>;
@@ -13,7 +13,7 @@ class LogsList extends BaseCommand {
13
13
  filters = parseFilters(flags.filter);
14
14
  }
15
15
  const oneHourAgo = new Date(Date.now() - 60 * 60 * 1000).toISOString();
16
- const data = await this.spin('Fetching logs', () => client.spans.listSpans({
16
+ const data = await this.spin('Fetching spans', () => client.spans.listSpans({
17
17
  Authorization: this.getAuthHeader(),
18
18
  start_time: flags['start-time'] || oneHourAgo,
19
19
  end_time: flags['end-time'] || new Date().toISOString(),
@@ -36,7 +36,8 @@ class LogsList extends BaseCommand {
36
36
  }
37
37
  }
38
38
  }
39
- LogsList.description = `List and filter LLM request logs (spans).
39
+ LogsList.aliases = ['spans:list'];
40
+ LogsList.description = `List and filter spans (LLM request logs). Also: respan spans list.
40
41
 
41
42
  Supports pagination, sorting, time range, and server-side filtering.
42
43
 
@@ -1,5 +1,6 @@
1
1
  import { BaseCommand } from '../../lib/base-command.js';
2
2
  export default class LogsSummary extends BaseCommand {
3
+ static aliases: string[];
3
4
  static description: string;
4
5
  static flags: {
5
6
  'start-time': import("@oclif/core/interfaces").OptionFlag<string, import("@oclif/core/interfaces").CustomOptions>;
@@ -26,7 +26,8 @@ class LogsSummary extends BaseCommand {
26
26
  }
27
27
  }
28
28
  }
29
- LogsSummary.description = `Get aggregated summary statistics for log spans in a time range.
29
+ LogsSummary.aliases = ['spans:summary'];
30
+ LogsSummary.description = `Get aggregated summary statistics for spans in a time range. Also: respan spans summary.
30
31
 
31
32
  Returns total cost, total tokens, request count, and score summaries.
32
33
 
@@ -21,7 +21,7 @@ class ToolsCall extends BaseCommand {
21
21
  }
22
22
  }
23
23
  ToolsCall.description = 'Call a Respan MCP tool with its exact tool name and JSON arguments. Writes execute immediately; inspect tools list --json before calling.';
24
- ToolsCall.args = { name: Args.string({ description: 'MCP tool name, e.g. log_list or trace_get', required: true }) };
24
+ ToolsCall.args = { name: Args.string({ description: 'MCP tool name, e.g. span_list or trace_get', required: true }) };
25
25
  ToolsCall.flags = {
26
26
  ...BaseCommand.baseFlags,
27
27
  input: Flags.string({ description: 'JSON object of MCP tool arguments', exclusive: ['input-file'] }),
@@ -2,7 +2,7 @@ import { BaseCommand } from '../../lib/base-command.js';
2
2
  export default class TracesGet extends BaseCommand {
3
3
  static description: string;
4
4
  static args: {
5
- id: import("@oclif/core/interfaces").Arg<string, Record<string, unknown>>;
5
+ 'trace-id': import("@oclif/core/interfaces").Arg<string, Record<string, unknown>>;
6
6
  };
7
7
  static flags: {
8
8
  'api-key': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
@@ -6,7 +6,7 @@ class TracesGet extends BaseCommand {
6
6
  this.globalFlags = flags;
7
7
  try {
8
8
  const client = this.getClient();
9
- const data = await this.spin('Fetching trace', () => client.traces.retrieveTrace({ Authorization: this.getAuthHeader(), trace_unique_id: args.id }));
9
+ const data = await this.spin('Fetching trace', () => client.traces.retrieveTrace({ Authorization: this.getAuthHeader(), trace_unique_id: args['trace-id'] }));
10
10
  this.log(JSON.stringify(data, null, 2));
11
11
  }
12
12
  catch (error) {
@@ -15,6 +15,6 @@ class TracesGet extends BaseCommand {
15
15
  }
16
16
  }
17
17
  TracesGet.description = 'Get a specific trace';
18
- TracesGet.args = { id: Args.string({ description: 'Trace ID', required: true }) };
18
+ TracesGet.args = { 'trace-id': Args.string({ description: 'Trace ID (trace_id in MCP)', required: true }) };
19
19
  TracesGet.flags = { ...BaseCommand.baseFlags };
20
20
  export default TracesGet;