@respan/cli 0.17.2 → 0.18.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,
@@ -34,7 +34,6 @@ export interface SpanData {
34
34
  completion_message?: Record<string, unknown> | null;
35
35
  warnings?: string;
36
36
  encoding_format?: string;
37
- disable_fallback?: boolean;
38
37
  respan_params?: Record<string, unknown>;
39
38
  field_name?: string;
40
39
  delimiter?: string;
@@ -37,7 +37,6 @@ export interface DemoPromptVersion {
37
37
  stream?: boolean;
38
38
  thinking?: Record<string, unknown>;
39
39
  variables?: Record<string, unknown>;
40
- load_balance_models?: Record<string, unknown>[];
41
40
  tools?: Record<string, unknown>[];
42
41
  tool_choice?: string | Record<string, unknown>;
43
42
  response_format?: Record<string, unknown>;