Merge branch 'wt-repro' of https://github.com/continuedev/cli into wt-repro
This commit is contained in:
commit
f535343897
4 changed files with 188 additions and 72 deletions
19
package-lock.json
generated
19
package-lock.json
generated
|
|
@ -16,7 +16,6 @@
|
|||
"@types/react": "^19.1.8",
|
||||
"@types/turndown": "^5.0.5",
|
||||
"@workos-inc/node": "^7.45.0",
|
||||
"axios": "^1.8.4",
|
||||
"chalk": "^5.4.1",
|
||||
"commander": "^14.0.0",
|
||||
"diff": "^7.0.0",
|
||||
|
|
@ -50,7 +49,6 @@
|
|||
"@types/ink-testing-library": "^1.0.4",
|
||||
"@types/jest": "^29.5.14",
|
||||
"@types/readline-sync": "^1.4.8",
|
||||
"@types/uuid": "^9.0.8",
|
||||
"conventional-changelog-conventionalcommits": "^9.1.0",
|
||||
"cross-env": "^7.0.3",
|
||||
"ink-testing-library": "^4.0.0",
|
||||
|
|
@ -4644,17 +4642,6 @@
|
|||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/axios": {
|
||||
"version": "1.9.0",
|
||||
"resolved": "https://registry.npmjs.org/axios/-/axios-1.9.0.tgz",
|
||||
"integrity": "sha512-re4CqKTJaURpzbLHtIi6XpDv20/CnpXOtjRY5/CU32L8gU8ek9UIivcfvSWvmKEngmVbrUtPpdDwWDWL7DNHvg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"follow-redirects": "^1.15.6",
|
||||
"form-data": "^4.0.0",
|
||||
"proxy-from-env": "^1.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/babel-jest": {
|
||||
"version": "29.7.0",
|
||||
"resolved": "https://registry.npmjs.org/babel-jest/-/babel-jest-29.7.0.tgz",
|
||||
|
|
@ -13555,12 +13542,6 @@
|
|||
"node": ">= 0.10"
|
||||
}
|
||||
},
|
||||
"node_modules/proxy-from-env": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
|
||||
"integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/pure-rand": {
|
||||
"version": "6.1.0",
|
||||
"resolved": "https://registry.npmjs.org/pure-rand/-/pure-rand-6.1.0.tgz",
|
||||
|
|
|
|||
|
|
@ -38,7 +38,6 @@
|
|||
"@types/react": "^19.1.8",
|
||||
"@types/turndown": "^5.0.5",
|
||||
"@workos-inc/node": "^7.45.0",
|
||||
"axios": "^1.8.4",
|
||||
"chalk": "^5.4.1",
|
||||
"commander": "^14.0.0",
|
||||
"diff": "^7.0.0",
|
||||
|
|
@ -69,7 +68,6 @@
|
|||
"@types/ink-testing-library": "^1.0.4",
|
||||
"@types/jest": "^29.5.14",
|
||||
"@types/readline-sync": "^1.4.8",
|
||||
"@types/uuid": "^9.0.8",
|
||||
"conventional-changelog-conventionalcommits": "^9.1.0",
|
||||
"cross-env": "^7.0.3",
|
||||
"ink-testing-library": "^4.0.0",
|
||||
|
|
|
|||
|
|
@ -2,16 +2,20 @@ import {
|
|||
Configuration,
|
||||
DefaultApi,
|
||||
} from "@continuedev/sdk/dist/api/dist/index.js";
|
||||
import axios from "axios";
|
||||
import chalk from "chalk";
|
||||
import * as fs from "fs";
|
||||
import open from "open";
|
||||
import * as os from "os";
|
||||
import * as path from "path";
|
||||
import { createInterface } from "readline";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { env } from "../env.js";
|
||||
|
||||
// Polyfill fetch for Node < 18
|
||||
import nodeFetch from "node-fetch";
|
||||
if (!globalThis.fetch) {
|
||||
globalThis.fetch = nodeFetch as unknown as typeof globalThis.fetch;
|
||||
}
|
||||
|
||||
// Config file path
|
||||
const AUTH_CONFIG_PATH = path.join(os.homedir(), ".continue", "auth.json");
|
||||
|
||||
|
|
@ -209,25 +213,146 @@ function prompt(question: string): Promise<string> {
|
|||
}
|
||||
|
||||
/**
|
||||
* Gets the auth URL for the token page
|
||||
* Device authorization response from WorkOS
|
||||
*/
|
||||
function getAuthUrlForTokenPage(useOnboarding: boolean = false): string {
|
||||
const url = new URL("https://api.workos.com/user_management/authorize");
|
||||
const params = {
|
||||
response_type: "code",
|
||||
client_id: env.workOsClientId,
|
||||
redirect_uri: `${env.appUrl}/tokens/${
|
||||
useOnboarding ? "onboarding-" : ""
|
||||
}callback/cli`,
|
||||
state: uuidv4(),
|
||||
provider: "authkit",
|
||||
};
|
||||
interface DeviceAuthorizationResponse {
|
||||
device_code: string;
|
||||
user_code: string;
|
||||
verification_uri: string;
|
||||
verification_uri_complete: string;
|
||||
expires_in: number;
|
||||
interval: number;
|
||||
}
|
||||
|
||||
Object.keys(params).forEach((key) =>
|
||||
url.searchParams.append(key, params[key as keyof typeof params])
|
||||
);
|
||||
/**
|
||||
* Request device authorization from WorkOS
|
||||
*/
|
||||
async function requestDeviceAuthorization(): Promise<DeviceAuthorizationResponse> {
|
||||
try {
|
||||
const params = new URLSearchParams({
|
||||
client_id: env.workOsClientId,
|
||||
});
|
||||
|
||||
return url.toString();
|
||||
// Use WorkOS User Management device authorization endpoint
|
||||
const response = await fetch(
|
||||
"https://api.workos.com/user_management/authorize/device",
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
},
|
||||
body: params,
|
||||
}
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
} catch (error: any) {
|
||||
console.error(
|
||||
chalk.red("Device authorization error:"),
|
||||
error.message || error
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Poll for device authorization completion
|
||||
*/
|
||||
async function pollForDeviceToken(
|
||||
deviceCode: string,
|
||||
interval: number,
|
||||
expiresIn: number
|
||||
): Promise<AuthenticatedConfig> {
|
||||
const startTime = Date.now();
|
||||
const expirationTime = startTime + expiresIn * 1000;
|
||||
let currentInterval = interval;
|
||||
|
||||
while (Date.now() < expirationTime) {
|
||||
try {
|
||||
const params = new URLSearchParams({
|
||||
grant_type: "urn:ietf:params:oauth:grant-type:device_code",
|
||||
device_code: deviceCode,
|
||||
client_id: env.workOsClientId,
|
||||
});
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
};
|
||||
|
||||
// Poll WorkOS User Management token endpoint
|
||||
const response = await fetch(
|
||||
"https://api.workos.com/user_management/authenticate",
|
||||
{
|
||||
method: "POST",
|
||||
headers,
|
||||
body: params,
|
||||
}
|
||||
);
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
const { access_token, refresh_token, user } = data;
|
||||
|
||||
// Calculate token expiration (assuming 1 hour validity)
|
||||
const tokenExpiresAt = Date.now() + 60 * 60 * 1000;
|
||||
|
||||
const authConfig: AuthenticatedConfig = {
|
||||
userId: user.id,
|
||||
userEmail: user.email,
|
||||
accessToken: access_token,
|
||||
refreshToken: refresh_token,
|
||||
expiresAt: tokenExpiresAt,
|
||||
organizationId: null,
|
||||
};
|
||||
|
||||
// Save the config
|
||||
saveAuthConfig(authConfig);
|
||||
|
||||
return authConfig;
|
||||
} else {
|
||||
// Handle HTTP error responses
|
||||
const errorData = await response.json().catch(() => ({}));
|
||||
const errorCode = errorData.error;
|
||||
|
||||
// Log response details for debugging
|
||||
if (response.status === 401) {
|
||||
throw new Error(
|
||||
"Oops! We had trouble authenticating. Please try again and reach out if the error persists."
|
||||
);
|
||||
}
|
||||
|
||||
if (errorCode === "authorization_pending") {
|
||||
// Continue polling
|
||||
await new Promise((resolve) =>
|
||||
setTimeout(resolve, currentInterval * 1000)
|
||||
);
|
||||
continue;
|
||||
} else if (errorCode === "slow_down") {
|
||||
// Increase polling interval
|
||||
currentInterval += 5;
|
||||
await new Promise((resolve) =>
|
||||
setTimeout(resolve, currentInterval * 1000)
|
||||
);
|
||||
continue;
|
||||
} else if (errorCode === "access_denied") {
|
||||
throw new Error("User denied access");
|
||||
} else if (errorCode === "expired_token") {
|
||||
throw new Error("Device code has expired");
|
||||
} else {
|
||||
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
||||
}
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error(chalk.red("Token polling error:"), error.message || error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error("Device authorization timeout");
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -240,14 +365,22 @@ async function refreshToken(
|
|||
// Load existing config to preserve organizationId and other fields
|
||||
const existingConfig = loadAuthConfig();
|
||||
|
||||
const response = await axios.post(
|
||||
new URL("auth/refresh", env.apiBase).toString(),
|
||||
{
|
||||
const response = await fetch(new URL("auth/refresh", env.apiBase), {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
refreshToken,
|
||||
}
|
||||
);
|
||||
}),
|
||||
});
|
||||
|
||||
const { accessToken, refreshToken: newRefreshToken, user } = response.data;
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
const { accessToken, refreshToken: newRefreshToken, user } = data;
|
||||
|
||||
// Calculate token expiration (assuming 1 hour validity)
|
||||
const tokenExpiresAt = Date.now() + 60 * 60 * 1000;
|
||||
|
|
@ -273,21 +406,15 @@ async function refreshToken(
|
|||
|
||||
return authConfig;
|
||||
} catch (error: any) {
|
||||
console.error(
|
||||
chalk.red("Token refresh error:"),
|
||||
error.response?.data?.message || error.message || error
|
||||
);
|
||||
console.error(chalk.red("Token refresh error:"), error.message || error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticates using the Continue web flow
|
||||
* Authenticates using the WorkOS device flow
|
||||
*/
|
||||
export async function login(
|
||||
useOnboarding: boolean = false,
|
||||
onPrompt?: (promptText: string) => Promise<string>
|
||||
): Promise<AuthConfig> {
|
||||
export async function login(): Promise<AuthConfig> {
|
||||
// If CONTINUE_API_KEY environment variable exists, use that instead
|
||||
if (process.env.CONTINUE_API_KEY) {
|
||||
console.info(
|
||||
|
|
@ -302,31 +429,41 @@ export async function login(
|
|||
try {
|
||||
console.info(chalk.cyan("\nStarting authentication with Continue..."));
|
||||
|
||||
// Get auth URL using the direct implementation
|
||||
const authUrl = getAuthUrlForTokenPage(useOnboarding);
|
||||
console.info(chalk.gray(`Opening browser to sign in at: ${authUrl}`));
|
||||
await open(authUrl);
|
||||
// Request device authorization
|
||||
const deviceAuth = await requestDeviceAuthorization();
|
||||
|
||||
console.info(chalk.yellow("\nAfter signing in, you'll receive a token."));
|
||||
console.info(
|
||||
chalk.yellow(
|
||||
`Your authentication code: ${chalk.bold(deviceAuth.user_code)}`
|
||||
)
|
||||
);
|
||||
console.info(
|
||||
chalk.dim(
|
||||
`If the browser doesn't automatically open, use this link: ${deviceAuth.verification_uri_complete}`
|
||||
)
|
||||
);
|
||||
|
||||
// Get token from user
|
||||
const token = onPrompt
|
||||
? await onPrompt(chalk.yellow("Paste your sign-in token here: "))
|
||||
: await prompt(chalk.yellow("Paste your sign-in token here: "));
|
||||
// Try to open the complete verification URL in browser
|
||||
try {
|
||||
await open(deviceAuth.verification_uri_complete);
|
||||
} catch (error) {
|
||||
console.info(chalk.yellow("Unable to open browser automatically"));
|
||||
}
|
||||
|
||||
console.info(chalk.cyan("Verifying token..."));
|
||||
console.info(chalk.cyan("\nWaiting for confirmation..."));
|
||||
|
||||
// Exchange token for session
|
||||
const response = await refreshToken(token);
|
||||
// Poll for token
|
||||
const authConfig = await pollForDeviceToken(
|
||||
deviceAuth.device_code,
|
||||
deviceAuth.interval,
|
||||
deviceAuth.expires_in
|
||||
);
|
||||
|
||||
console.info(chalk.green("\nAuthentication successful!"));
|
||||
|
||||
return response;
|
||||
return authConfig;
|
||||
} catch (error: any) {
|
||||
console.error(
|
||||
chalk.red("Authentication error:"),
|
||||
error.response?.data?.message || error.message || error
|
||||
);
|
||||
console.error(chalk.red("Authentication error:"), error.message || error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -47,7 +47,7 @@ export async function handleSlashCommands(
|
|||
case "config":
|
||||
return { openConfigSelector: true };
|
||||
case "login":
|
||||
login(false, onLoginPrompt)
|
||||
login()
|
||||
.then(async (config) => {
|
||||
if (config && isAuthenticatedConfig(config)) {
|
||||
console.info(
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue