Skip to content

armgit / E2B

Public Imported from GitHub
0

Open-source, secure environment with real-world tools for enterprise-grade agents.

feat(cli): replace access token auth with Hydra OAuth flow (#1481)

Ben Fornefeld5370d54bfa89
diff --git a/.changeset/cli-hydra-oauth-flow.md b/.changeset/cli-hydra-oauth-flow.md
new file mode 100644
index 000000000..3980c38f9
--- /dev/null
+++ b/.changeset/cli-hydra-oauth-flow.md
@@ -0,0 +1,5 @@
+---
+"@e2b/cli": minor
+---
+
+Replace legacy access token auth with OAuth 2.0 refresh token flow. The CLI now authenticates via a public OAuth client using PKCE, receiving Hydra JWTs that are refreshed automatically. Config schema bumped to v1 with nested `identity`, `oauth`, and `tokens` sections. Old flat configs are deprecated and require re-login.
diff --git a/packages/cli/src/api.ts b/packages/cli/src/api.ts
index 207545a79..5ed5238e1 100644
--- a/packages/cli/src/api.ts
+++ b/packages/cli/src/api.ts
@@ -4,6 +4,9 @@ import * as e2b from 'e2b'
import { getUserConfig, UserConfig } from './user'
import { asBold, asPrimary } from './utils/format'
+export type Teams =
+ e2b.paths['/teams']['get']['responses'][200]['content']['application/json']
+
export let apiKey = process.env.E2B_API_KEY
export let accessToken = process.env.E2B_ACCESS_TOKEN
export const teamId = process.env.E2B_TEAM_ID
@@ -60,7 +63,7 @@ export function ensureAccessToken() {
// If accessToken is not already set (either from env var or from user config), try to get it from config file
if (!accessToken) {
const userConfig = getUserConfig()
- accessToken = userConfig?.accessToken
+ accessToken = userConfig?.tokens.access_token
}
if (!accessToken) {
@@ -96,7 +99,7 @@ export function resolveTeamId(
const userConfig = getUserConfig()
const resolvedAccessToken =
- process.env.E2B_ACCESS_TOKEN || userConfig?.accessToken
+ process.env.E2B_ACCESS_TOKEN || userConfig?.tokens.access_token
export const connectionConfig = new e2b.ConnectionConfig({
apiKey: process.env.E2B_API_KEY || userConfig?.teamApiKey,
diff --git a/packages/cli/src/commands/auth/configure.ts b/packages/cli/src/commands/auth/configure.ts
index 8ca43d66e..ed675d62a 100644
--- a/packages/cli/src/commands/auth/configure.ts
+++ b/packages/cli/src/commands/auth/configure.ts
@@ -2,13 +2,14 @@ import * as commander from 'commander'
import * as fs from 'fs'
import * as chalk from 'chalk'
import * as e2b from 'e2b'
-import { USER_CONFIG_PATH, writeUserConfig } from 'src/user'
+
import {
- client,
- connectionConfig,
- ensureAccessToken,
- ensureUserConfig,
-} from 'src/api'
+ USER_CONFIG_PATH,
+ getConfigRefreshTimestamp,
+ writeUserConfig,
+} from 'src/user'
+import { ensureUserConfig, Teams } from 'src/api'
+import { ensureValidAccessToken } from 'src/utils/token-refresh'
import { asBold, asFormattedTeam } from '../../utils/format'
import { handleE2BRequestError } from '../../utils/errors'
@@ -24,13 +25,23 @@ export const configureCommand = new commander.Command('configure')
return
}
+ // ensureValidAccessToken may refresh tokens and write them to disk.
+ // Re-read the config afterwards so we persist the refreshed tokens
+ // instead of overwriting them with stale in-memory copies.
+ const accessToken = await ensureValidAccessToken()
const userConfig = ensureUserConfig()
- ensureAccessToken()
- const signal = connectionConfig.getSignal()
- const res = await client.api.GET('/teams', { signal })
+ const config = new e2b.ConnectionConfig({
+ apiHeaders: { Authorization: `Bearer ${accessToken}` },
+ })
+ const authClient = new e2b.ApiClient(config, { requireApiKey: false })
+
+ const res = await authClient.api.GET('/teams', {
+ signal: config.getSignal(),
+ })
handleE2BRequestError(res, 'Error getting teams')
+ const teams = res.data as Teams
const team = (
await inquirer.default.prompt([
@@ -39,7 +50,7 @@ export const configureCommand = new commander.Command('configure')
message: chalk.default.underline('Select team'),
type: 'list',
pageSize: 50,
- choices: res.data.map((team: e2b.components['schemas']['Team']) => ({
+ choices: teams.map((team) => ({
name: asFormattedTeam(team, userConfig.teamId),
value: team,
})),
@@ -50,6 +61,7 @@ export const configureCommand = new commander.Command('configure')
userConfig.teamName = team.name
userConfig.teamId = team.teamID
userConfig.teamApiKey = team.apiKey
+ userConfig.last_refresh = getConfigRefreshTimestamp()
writeUserConfig(USER_CONFIG_PATH, userConfig)
console.log(`Team ${asBold(team.name)} (${team.teamID}) selected.\n`)
diff --git a/packages/cli/src/commands/auth/info.ts b/packages/cli/src/commands/auth/info.ts
index 76fd7a8ef..59ad26103 100644
--- a/packages/cli/src/commands/auth/info.ts
+++ b/packages/cli/src/commands/auth/info.ts
@@ -19,5 +19,6 @@ export const infoCommand = new commander.Command('info')
}
console.log(asFormattedConfig(userConfig))
+
process.exit(0)
})
diff --git a/packages/cli/src/commands/auth/login.ts b/packages/cli/src/commands/auth/login.ts
index 9b0b9faae..eb71cece5 100644
--- a/packages/cli/src/commands/auth/login.ts
+++ b/packages/cli/src/commands/auth/login.ts
@@ -6,14 +6,15 @@ import * as e2b from 'e2b'
import { pkg } from 'src'
import {
DOCS_BASE,
+ getConfigRefreshTimestamp,
getUserConfig,
+ writeUserConfig,
USER_CONFIG_PATH,
UserConfig,
- writeUserConfig,
} from 'src/user'
import { asBold, asFormattedConfig, asFormattedError } from 'src/utils/format'
import { openUrlInBrowser } from 'src/utils/openBrowser'
-import { connectionConfig } from 'src/api'
+import { connectionConfig, Teams } from 'src/api'
import { handleE2BRequestError } from '../../utils/errors'
export const loginCommand = new commander.Command('login')
@@ -41,21 +42,21 @@ export const loginCommand = new commander.Command('login')
return
}
- const accessToken =
- process.env.E2B_ACCESS_TOKEN || signInResponse.accessToken
+ const accessToken = signInResponse.accessToken
const signal = connectionConfig.getSignal()
const config = new e2b.ConnectionConfig({
apiHeaders: { Authorization: `Bearer ${accessToken}` },
})
const client = new e2b.ApiClient(config, { requireApiKey: false })
- const res = await client.api.GET('/teams', { signal })
+ const res = await client.api.GET('/teams', {
+ signal,
+ })
handleE2BRequestError(res, 'Error getting teams')
+ const teams = res.data as Teams
- const defaultTeam = res.data.find(
- (team: e2b.components['schemas']['Team']) => team.isDefault
- )
+ const defaultTeam = teams.find((team) => team.isDefault)
if (!defaultTeam) {
console.error(
asFormattedError('No default team found, please contact support')
@@ -64,8 +65,20 @@ export const loginCommand = new commander.Command('login')
}
userConfig = {
- email: signInResponse.email,
- accessToken,
+ version: 1,
+ identity: {
+ email: signInResponse.email,
+ },
+ oauth: {
+ token_endpoint: signInResponse.tokenEndpoint,
+ revoke_endpoint: signInResponse.revokeEndpoint,
+ client_id: signInResponse.clientId,
+ },
+ tokens: {
+ access_token: accessToken,
+ refresh_token: signInResponse.refreshToken,
+ },
+ last_refresh: getConfigRefreshTimestamp(),
teamName: defaultTeam.name,
teamId: defaultTeam.teamID,
teamApiKey: defaultTeam.apiKey,
@@ -75,9 +88,9 @@ export const loginCommand = new commander.Command('login')
}
console.log(
- `Logged in as ${asBold(userConfig.email)} with selected team ${asBold(
- userConfig.teamName
- )}`
+ `Logged in as ${asBold(
+ userConfig.identity.email
+ )} with selected team ${asBold(userConfig.teamName)}`
)
process.exit(0)
})
@@ -85,7 +98,10 @@ export const loginCommand = new commander.Command('login')
interface SignInWithBrowserResponse {
email: string
accessToken: string
- defaultTeamId: string
+ refreshToken: string
+ tokenEndpoint: string
+ revokeEndpoint: string
+ clientId: string
}
async function signInWithBrowser(): Promise<SignInWithBrowserResponse> {
@@ -112,6 +128,20 @@ async function signInWithBrowser(): Promise<SignInWithBrowserResponse> {
reject(new Error(error))
followUpUrl.searchParams.set('state', 'error')
followUpUrl.searchParams.set('error', error)
+ } else if (
+ !searchParamsObj.email ||
+ !searchParamsObj.accessToken ||
+ !searchParamsObj.refreshToken ||
+ !searchParamsObj.tokenEndpoint ||
+ !searchParamsObj.revokeEndpoint ||
+ !searchParamsObj.clientId
+ ) {
+ reject(new Error('Incomplete login response from server'))
+ followUpUrl.searchParams.set('state', 'error')
+ followUpUrl.searchParams.set(
+ 'error',
+ 'Incomplete login response from server'
+ )
} else {
resolve(searchParamsObj)
followUpUrl.searchParams.set('state', 'success')
diff --git a/packages/cli/src/commands/auth/logout.ts b/packages/cli/src/commands/auth/logout.ts
index 2ac5d41c3..57ce0434c 100644
--- a/packages/cli/src/commands/auth/logout.ts
+++ b/packages/cli/src/commands/auth/logout.ts
@@ -1,15 +1,36 @@
import * as commander from 'commander'
import * as fs from 'fs'
-import { USER_CONFIG_PATH } from 'src/user'
+import { getUserConfig, USER_CONFIG_PATH } from 'src/user'
export const logoutCommand = new commander.Command('logout')
.description('log out of CLI')
- .action(() => {
- if (fs.existsSync(USER_CONFIG_PATH)) {
- fs.unlinkSync(USER_CONFIG_PATH) // Delete user config
- console.log('Logged out.')
- } else {
+ .action(async () => {
+ if (!fs.existsSync(USER_CONFIG_PATH)) {
console.log('Not logged in, nothing to do')
+ return
+ }
+
+ let config
+ try {
+ config = getUserConfig()
+ } catch {
+ // Malformed config file — proceed to delete it below
+ }
+ if (config) {
+ await fetch(config.oauth.revoke_endpoint, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
+ body: new URLSearchParams({
+ token: config.tokens.refresh_token,
+ token_type_hint: 'refresh_token',
+ client_id: config.oauth.client_id,
+ }),
+ }).catch(() => {})
+ }
+
+ if (fs.existsSync(USER_CONFIG_PATH)) {
+ fs.unlinkSync(USER_CONFIG_PATH)
}
+ console.log('Logged out.')
})
diff --git a/packages/cli/src/user.ts b/packages/cli/src/user.ts
index 465228611..f3f715129 100644
--- a/packages/cli/src/user.ts
+++ b/packages/cli/src/user.ts
@@ -5,17 +5,40 @@ import * as fs from 'fs'
/**
* User configuration stored in ~/.e2b/config.json
*/
-export interface UserConfig {
+export interface UserIdentity {
email: string
- accessToken: string
+}
+
+export interface UserOAuth {
+ token_endpoint: string
+ revoke_endpoint: string
+ client_id: string
+}
+
+export interface UserTokens {
+ access_token: string
+ refresh_token: string
+}
+
+export interface UserConfig {
+ version: 1
+ identity: UserIdentity
+ oauth: UserOAuth
+ tokens: UserTokens
+ last_refresh: string
teamName: string
teamId: string
teamApiKey: string
dockerProxySet?: boolean
}
+type UnknownRecord = Record<string, unknown>
+
export const USER_CONFIG_PATH = path.join(os.homedir(), '.e2b', 'config.json') // TODO: Keep in Keychain
+export const DEPRECATED_USER_CONFIG_MESSAGE =
+ 'Your CLI authentication config is deprecated. You have been signed out. Please run `e2b auth login` again.'
+
export const DOCS_BASE =
process.env.E2B_DOCS_BASE ||
`https://${process.env.E2B_DOMAIN || 'e2b.dev'}/docs`
@@ -29,7 +52,43 @@ export const SANDBOX_INSPECT_URL = (sandboxId: string) =>
export function getUserConfig(): UserConfig | null {
if (!fs.existsSync(USER_CONFIG_PATH)) return null
- return JSON.parse(fs.readFileSync(USER_CONFIG_PATH, 'utf8'))
+ const config = JSON.parse(fs.readFileSync(USER_CONFIG_PATH, 'utf8'))
+
+ if (!isUserConfig(config)) {
+ fs.unlinkSync(USER_CONFIG_PATH)
+ console.error(DEPRECATED_USER_CONFIG_MESSAGE)
+ return null
+ }
+
+ return config
+}
+
+function isObject(value: unknown): value is UnknownRecord {
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
+}
+
+function isString(value: unknown): value is string {
+ return typeof value === 'string'
+}
+
+function isUserConfig(config: unknown): config is UserConfig {
+ if (!isObject(config)) return false
+ if (config.version !== 1) return false
+ return (
+ isObject(config.identity) &&
+ isString(config.identity.email) &&
+ isObject(config.oauth) &&
+ isString(config.oauth.token_endpoint) &&
+ isString(config.oauth.revoke_endpoint) &&
+ isString(config.oauth.client_id) &&
+ isObject(config.tokens) &&
+ isString(config.tokens.access_token) &&
+ isString(config.tokens.refresh_token)
+ )
+}
+
+export function getConfigRefreshTimestamp(): string {
+ return new Date().toISOString()
}
/**
diff --git a/packages/cli/src/utils/errors.ts b/packages/cli/src/utils/errors.ts
index 5b63dde97..f59a52220 100644
--- a/packages/cli/src/utils/errors.ts
+++ b/packages/cli/src/utils/errors.ts
@@ -10,19 +10,21 @@ export class E2BRequestError extends Error {
}
}
-export function handleE2BRequestError<T>(
- res: {
- data?: T | null | undefined
- error?: { code: number; message: string }
- },
- errMsg?: string
-): asserts res is { data: T; error?: undefined } {
- if (!res.error) {
- return
- }
+type E2BResponseError = { code?: number; message?: string }
+type E2BResponse<TData> =
+ | {
+ data: TData
+ error?: undefined
+ }
+ | {
+ data?: undefined
+ error: E2BResponseError
+ }
+
+function throwE2BRequestError(error: E2BResponseError, errMsg?: string): never {
let message: string
- const code = res.error?.code ?? 0
+ const code = error.code ?? 0
switch (code) {
case 400:
message = 'bad request'
@@ -46,7 +48,25 @@ export function handleE2BRequestError<T>(
throw new E2BRequestError(
`${errMsg && `${errMsg}: `}[${code}] ${message && `${message}: `}${
- res.error?.message ?? 'no message'
+ error.message ?? 'no message'
}`
)
}
+
+export function handleE2BRequestError(
+ res: { error: E2BResponseError },
+ errMsg?: string
+): never
+export function handleE2BRequestError<TData>(
+ res: E2BResponse<TData>,
+ errMsg?: string
+): asserts res is { data: TData; error?: undefined }
+export function handleE2BRequestError(
+ res: E2BResponse<unknown>,
+ errMsg?: string
+) {
+ if (!res.error) {
+ return
+ }
+ throwE2BRequestError(res.error, errMsg)
+}
diff --git a/packages/cli/src/utils/format.ts b/packages/cli/src/utils/format.ts
index 3fa676070..8476903b8 100644
--- a/packages/cli/src/utils/format.ts
+++ b/packages/cli/src/utils/format.ts
@@ -9,7 +9,7 @@ import { UserConfig } from '../user'
export const primaryColor = '#FFB766'
export function asFormattedConfig(config: UserConfig) {
- const email = asBold(config.email)
+ const email = asBold(config.identity.email)
const team = config.teamName
? asBold(config.teamName)
: asRed('Log out and log in to get team name')
diff --git a/packages/cli/src/utils/token-refresh.ts b/packages/cli/src/utils/token-refresh.ts
new file mode 100644
index 000000000..bf49bcd65
--- /dev/null
+++ b/packages/cli/src/utils/token-refresh.ts
@@ -0,0 +1,114 @@
+import * as fs from 'fs'
+
+import { getUserConfig, writeUserConfig, USER_CONFIG_PATH } from 'src/user'
+
+const REFRESH_SKEW_SECONDS = 60
+
+function decodeJwtExp(token: string): number | undefined {
+ const payload = token.split('.')[1]
+ if (!payload) return undefined
+ try {
+ const decoded = JSON.parse(
+ Buffer.from(payload, 'base64url').toString('utf8')
+ ) as { exp?: number }
+ return decoded.exp
+ } catch {
+ return undefined
+ }
+}
+
+export function isTokenExpired(accessToken: string): boolean {
+ const exp = decodeJwtExp(accessToken)
+ if (!exp) return true
+ return Math.floor(Date.now() / 1000) >= exp - REFRESH_SKEW_SECONDS
+}
+
+export class TokenRefreshError extends Error {
+ constructor(
+ public status: number,
+ public errorCode: string,
+ message: string
+ ) {
+ super(message)
+ this.name = 'TokenRefreshError'
+ }
+}
+
+type RefreshedTokens = {
+ access_token: string
+ refresh_token: string
+}
+
+export async function refreshOAuthToken(
+ refreshToken: string,
+ clientId: string,
+ tokenEndpoint: string
+): Promise<RefreshedTokens> {
+ const res = await fetch(tokenEndpoint, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
+ body: new URLSearchParams({
+ grant_type: 'refresh_token',
+ refresh_token: refreshToken,
+ client_id: clientId,
+ }),
+ })
+
+ if (!res.ok) {
+ const body = await res.json().catch(() => ({}) as Record<string, unknown>)
+ throw new TokenRefreshError(
+ res.status,
+ (body.error as string) ?? 'unknown',
+ (body.error_description as string) ?? 'Token refresh failed'
+ )
+ }
+
+ const data = (await res.json()) as {
+ access_token: string
+ refresh_token?: string
+ expires_in: number
+ }
+
+ return {
+ access_token: data.access_token,
+ refresh_token: data.refresh_token ?? refreshToken,
+ }
+}
+
+export async function ensureValidAccessToken(): Promise<string> {
+ const config = getUserConfig()
+ if (!config) {
+ throw new Error('No user config found, run `e2b auth login` first.')
+ }
+
+ if (!isTokenExpired(config.tokens.access_token)) {
+ return config.tokens.access_token
+ }
+
+ try {
+ const refreshed = await refreshOAuthToken(
+ config.tokens.refresh_token,
+ config.oauth.client_id,
+ config.oauth.token_endpoint
+ )
+
+ // Token refresh updates only tokens.* — it does NOT update last_refresh.
+ writeUserConfig(USER_CONFIG_PATH, {
+ ...config,
+ tokens: {
+ access_token: refreshed.access_token,
+ refresh_token: refreshed.refresh_token,
+ },
+ })
+
+ return refreshed.access_token
+ } catch (err) {
+ if (err instanceof TokenRefreshError && err.errorCode === 'invalid_grant') {
+ fs.rmSync(USER_CONFIG_PATH, { force: true })
+ throw new Error(
+ 'Your session has expired. Please run `e2b auth login` again.'
+ )
+ }
+ throw err
+ }
+}
diff --git a/packages/cli/tests/user_config_permissions.test.ts b/packages/cli/tests/user_config_permissions.test.ts
index 19c7e7d47..08b616f9b 100644
--- a/packages/cli/tests/user_config_permissions.test.ts
+++ b/packages/cli/tests/user_config_permissions.test.ts
@@ -19,8 +19,20 @@ describe('writeUserConfig', () => {
tmpDirs.push(tmpDir)
const configPath = path.join(tmpDir, '.e2b', 'config.json')
const config: UserConfig = {
- email: '[email protected]',
- accessToken: 'access-token-secret',
+ version: 1,
+ identity: {
+ email: '[email protected]',
+ },
+ oauth: {
+ token_endpoint: 'https://hydra.example.com/oauth2/token',
+ revoke_endpoint: 'https://hydra.example.com/oauth2/revoke',
+ client_id: 'cli-client-id',
+ },
+ tokens: {
+ access_token: 'access-token-secret',
+ refresh_token: 'refresh-token-secret',
+ },
+ last_refresh: '2024-06-24T12:00:00.000Z',
teamName: 'default',
teamId: 'team-id',
teamApiKey: 'team-api-key-secret',