Skip to content

armgit / E2B

Public Imported from GitHub
0

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

feat(docs, cli): CLI auth (#128)

Pavel 'Strajk' Dolecekd4af12920e4a
diff --git a/apps/docs/package-lock.json b/apps/docs/package-lock.json
index 7c7876533..c462f9730 100644
--- a/apps/docs/package-lock.json
+++ b/apps/docs/package-lock.json
@@ -55,7 +55,7 @@
"zustand": "^4.3.2"
},
"devDependencies": {
- "@e2b/sdk": "^0.1.0",
+ "@e2b/sdk": "^0.2.4",
"@nodelib/fs.walk": "^2.0.0",
"encoding": "^0.1.13",
"eslint": "8.45.0",
@@ -256,14 +256,15 @@
}
},
"node_modules/@e2b/sdk": {
- "version": "0.1.0",
- "resolved": "https://registry.npmjs.org/@e2b/sdk/-/sdk-0.1.0.tgz",
- "integrity": "sha512-FtJ3s2uzIfXAxn81WJCM7/3paN3I7jGubwaiTQxED4eYNLEnhY+pCe6AGoAmdfGoZHahsX2ZcIRRxQXCAExrJg==",
+ "version": "0.2.4",
+ "resolved": "https://registry.npmjs.org/@e2b/sdk/-/sdk-0.2.4.tgz",
+ "integrity": "sha512-Rp6LG/VPKXcyN7NjEEEevI9eG1N4IkZVi2gKvT6TGK970xg5KS0BkYxnWLkO9QB/x7FuhGZBuAS5VabaJ+rVIQ==",
"dev": true,
"dependencies": {
"cross-fetch": "^3.1.5",
"normalize-path": "^3.0.0",
"openapi-typescript-fetch": "^1.1.3",
+ "platform": "^1.3.6",
"rpc-websocket-client": "^1.1.4"
}
},
@@ -6630,6 +6631,12 @@
"node": ">= 6"
}
},
+ "node_modules/platform": {
+ "version": "1.3.6",
+ "resolved": "https://registry.npmjs.org/platform/-/platform-1.3.6.tgz",
+ "integrity": "sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg==",
+ "dev": true
+ },
"node_modules/postcss": {
"version": "8.4.26",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.26.tgz",
@@ -9131,14 +9138,15 @@
}
},
"@e2b/sdk": {
- "version": "0.1.0",
- "resolved": "https://registry.npmjs.org/@e2b/sdk/-/sdk-0.1.0.tgz",
- "integrity": "sha512-FtJ3s2uzIfXAxn81WJCM7/3paN3I7jGubwaiTQxED4eYNLEnhY+pCe6AGoAmdfGoZHahsX2ZcIRRxQXCAExrJg==",
+ "version": "0.2.4",
+ "resolved": "https://registry.npmjs.org/@e2b/sdk/-/sdk-0.2.4.tgz",
+ "integrity": "sha512-Rp6LG/VPKXcyN7NjEEEevI9eG1N4IkZVi2gKvT6TGK970xg5KS0BkYxnWLkO9QB/x7FuhGZBuAS5VabaJ+rVIQ==",
"dev": true,
"requires": {
"cross-fetch": "^3.1.5",
"normalize-path": "^3.0.0",
"openapi-typescript-fetch": "^1.1.3",
+ "platform": "^1.3.6",
"rpc-websocket-client": "^1.1.4"
}
},
@@ -13691,6 +13699,12 @@
"resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.6.tgz",
"integrity": "sha512-saLsH7WeYYPiD25LDuLRRY/i+6HaPYr6G1OUlN39otzkSTxKnubR9RTxS3/Kk50s1g2JTgFwWQDQyplC5/SHZg=="
},
+ "platform": {
+ "version": "1.3.6",
+ "resolved": "https://registry.npmjs.org/platform/-/platform-1.3.6.tgz",
+ "integrity": "sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg==",
+ "dev": true
+ },
"postcss": {
"version": "8.4.26",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.26.tgz",
diff --git a/apps/docs/package.json b/apps/docs/package.json
index 1dc8c4c4d..24ec4aacc 100644
--- a/apps/docs/package.json
+++ b/apps/docs/package.json
@@ -59,7 +59,7 @@
"zustand": "^4.3.2"
},
"devDependencies": {
- "@e2b/sdk": "^0.1.0",
+ "@e2b/sdk": "^0.2.4",
"@nodelib/fs.walk": "^2.0.0",
"encoding": "^0.1.13",
"eslint": "8.45.0",
diff --git a/apps/docs/src/app/api/cli/page.tsx b/apps/docs/src/app/api/cli/page.tsx
new file mode 100644
index 000000000..b98e00e33
--- /dev/null
+++ b/apps/docs/src/app/api/cli/page.tsx
@@ -0,0 +1,123 @@
+'use client'
+
+import { useSearchParams } from 'next/navigation'
+import { useApiKey, useUser } from '@/utils/useUser'
+import { DialogAnimated } from '@/components/DialogAnimated'
+import { CloudIcon, LaptopIcon, Link2Icon } from 'lucide-react'
+import { Button } from '@/components/Button'
+import { useSignIn } from '@/utils/useSignIn'
+
+type UserConfig = {
+ email: string
+ accessToken: string
+ defaultTeamApiKey: string
+ defaultTeamId: string
+}
+
+export default function Page() {
+ const signIn = useSignIn()
+ const { user, isLoading: userIsLoading } = useUser()
+ const apiKey = useApiKey()
+ const searchParams = useSearchParams()
+ const searchParamsObj = Object.fromEntries(searchParams)
+ const { next, state } = searchParamsObj
+
+ // TODO: Consider sending back onetime code to be used to get access token
+ function redirectToCli() {
+ if (!next) return
+ if (!(user?.email && apiKey)) return
+ const { email, accessToken, defaultTeamId } = user
+ const newUrl = new URL(next)
+ const searchParamsObj: UserConfig = {
+ email,
+ defaultTeamApiKey: apiKey,
+ accessToken,
+ defaultTeamId,
+ }
+ newUrl.search = new URLSearchParams(searchParamsObj).toString()
+ window.location.href = newUrl.toString()
+ }
+
+ let content
+ if (state === 'error') {
+ content = (
+ <>
+ <div className="font-bold text-red-500">Error</div>
+ <div>Something went wrong, please try again</div>
+ <pre>{searchParamsObj.error}</pre> {/* TODO: Nicer, but it should never happen */}
+ </>
+ )
+ } else if (state === 'success') {
+ content = (
+ <>
+ <div className="font-bold text-emerald-400">Successfully linked</div>
+ <div>You can close this page and start using CLI.</div>
+ </>
+ )
+ } else {
+ const isNextValid = next.startsWith('http://localhost')
+ if (!isNextValid) {
+ content = (
+ <>
+ <div className="font-bold text-red-500">Error</div>
+ <div>Invalid redirect URL, only localhost is allowed</div>
+ </>
+ )
+ } else if (userIsLoading) {
+ content = <span className="text-gray-300">Loading, please wait</span>
+ } else if (!user) {
+ content = (
+ <>
+ <Button onClick={() => signIn()}>Sign In to continue</Button>
+ </>
+ )
+ } else {
+ content = (
+ <>
+ <Button onClick={() => redirectToCli()}>
+ Authorize CLI to use your account
+ </Button>
+ </>
+ )
+ }
+ }
+
+ return (
+ <div>
+ {/* It's not easy to override RootLayout without grouping everything into `(root)` dir */}
+ {/* So I'm hacking custom layout with full modal overlay */}
+ {/* https://github.com/vercel/next.js/issues/50591 */}
+ <DialogAnimated
+ open={true}
+ setOpen={() => {}} // intentionally prevent closing
+ >
+ <div className="py-6 sm:py-12">
+ <div className="mx-auto px-6 lg:px-8">
+ <div className="mx-auto sm:text-center">
+ <p
+ className="
+ flex items-center justify-center gap-4
+ text-3xl font-bold tracking-tight sm:text-4xl
+ "
+ >
+ <span className="text-gray-200">
+ <LaptopIcon size={60} />
+ </span>
+ <span className="text-gray-400">
+ <Link2Icon size={30} />
+ </span>
+ <span className="text-gray-200">
+ <CloudIcon size={60} />
+ </span>
+ </p>
+ <h2 className="mt-6 text-base font-semibold leading-7">
+ Linking CLI with your account
+ </h2>
+ <p className="mt-12 leading-8">{content}</p>
+ </div>
+ </div>
+ </div>
+ </DialogAnimated>
+ </div>
+ )
+}
diff --git a/apps/docs/src/utils/useUser.tsx b/apps/docs/src/utils/useUser.tsx
index 52d86f6e4..de835fe48 100644
--- a/apps/docs/src/utils/useUser.tsx
+++ b/apps/docs/src/utils/useUser.tsx
@@ -16,21 +16,17 @@ import * as Sentry from '@sentry/nextjs'
type UserContextType = {
isLoading: boolean
session: Session | null
- user: (User & { teams: any[]; apiKeys: any[] }) | null
+ user: User & {
+ teams: any[];
+ apiKeys: any[];
+ accessToken: string;
+ defaultTeamId: string;
+ } | null
error: Error | null
}
export const UserContext = createContext(undefined)
-function stdHandler({ line, timestamp, error }) {
- const timestampHumanFriendly = new Date(timestamp / 1000000) // timestamp is in nanoseconds
- .toISOString()
- .split('T')[1] // only time, date is not relevant for debugging
- .split('.')[0] // remove ms
- const emoji = error ? '🟥' : '🟦'
- console.log(`${emoji} [${timestampHumanFriendly}] ${line}`)
-}
-
export const CustomUserContextProvider = (props) => {
const supabase = createPagesBrowserClient()
const [session, setSession] = useState(null)
@@ -41,7 +37,6 @@ export const CustomUserContextProvider = (props) => {
useEffect(() => {
mounted.current = true
-
async function getSession() {
const {
data: { session },
@@ -59,7 +54,6 @@ export const CustomUserContextProvider = (props) => {
if (!session) setIsLoading(false) // if session is present, we set setLoading to false in the second useEffect
}
}
-
void getSession()
return () => {
mounted.current = false
@@ -107,15 +101,26 @@ export const CustomUserContextProvider = (props) => {
) // Due to RLS, we could also safely just fetch all, but let's be explicit for sure
if (apiKeysError) Sentry.captureException(apiKeysError)
+ const defaultTeamId = teams?.[0]?.team_id // TODO: Adjust when user can be part of multiple teams
+
+ const { data: accessToken, error: accessTokenError } = await supabase
+ .from('access_tokens')
+ .select('*')
+ .eq('user_id', session?.user.id) // Due to RLS, we could also safely just fetch all, but let's be explicit for sure
+ .limit(1)
+ .single()
+ if (accessTokenError) Sentry.captureException(accessTokenError)
+
setUser({
...session?.user,
teams,
apiKeys,
+ accessToken: accessToken?.access_token,
+ defaultTeamId,
error: teamsError || apiKeysError,
})
setIsLoading(false)
}
-
if (session) void getUserCustom()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [session])
@@ -157,7 +162,7 @@ export const useUser = (): UserContextType => {
return context
}
-export const useApiKey = (): string => {
+export const useApiKey = (): string => { // for convenience
const { user } = useUser()
return user?.apiKeys?.[0]?.api_key
}
diff --git a/packages/cli/package.json b/packages/cli/package.json
index e6322d592..de2eceda2 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -50,26 +50,19 @@
"package.json"
],
"bin": {
- "dbk": "dist/index.js",
- "devbook": "dist/index.js",
- "devbookctl": "dist/index.js",
- "dbkctl": "dist/index.js",
- "e2b": "dist/index.js",
- "E2B": "dist/index.js",
- "E2b": "dist/index.js",
- "etob": "dist/index.js",
- "EtoB": "dist/index.js",
- "Etob": "dist/index.js"
+ "e2b": "dist/index.js"
},
"dependencies": {
"@devbookhq/sdk": "^2.6.88",
"@iarna/toml": "^2.2.5",
"@nodelib/fs.walk": "^1.2.8",
+ "async-listen": "^3.0.1",
"boxen": "^7.0.0",
"chalk": "^5.1.2",
"chokidar": "^3.5.3",
"commander": "^9.4.1",
"docker-names": "^1.2.1",
+ "get-port": "^7.0.0",
"inquirer": "^8.0.0",
"parse-gitignore": "^2.0.0",
"update-notifier": "5.1.0",
@@ -78,4 +71,4 @@
"engines": {
"node": "~16"
}
-}
\ No newline at end of file
+}
diff --git a/packages/cli/src/commands/auth.ts b/packages/cli/src/commands/auth.ts
new file mode 100644
index 000000000..2b70857b5
--- /dev/null
+++ b/packages/cli/src/commands/auth.ts
@@ -0,0 +1,100 @@
+import * as commander from 'commander'
+import open from 'open'
+import {listen} from 'async-listen'
+import {asBold, asFormattedError} from 'src/utils/format'
+import path from 'path'
+import * as os from 'os'
+import fs from 'fs'
+import http from 'http'
+import pkg from '../../package.json'
+
+type UserConfig = {
+ email: string
+ accessToken: string
+ defaultTeamApiKey: string
+ defaultTeamId: string
+}
+
+const USER_CONFIG_PATH = path.join(os.homedir(), '.e2b', 'config.json') // TODO: Keep in Keychain
+const DOCS_BASE = process.env.E2B_DOCS_BASE || `https://e2b.dev/docs`
+
+export const loginCommand = new commander.Command('login')
+ .description('Login to e2b')
+ .action(async () => {
+ let userConfig
+ try {
+ userConfig = getUserConfig()
+ } catch (err) {
+ console.error(asFormattedError(`Failed to read user config`, err))
+ }
+ if (userConfig) {
+ console.log(
+ `Already logged in as ${asBold(
+ userConfig.email,
+ )}, if you want to login as a different user, logout first.`,
+ )
+ return
+ } else if (!userConfig) {
+ console.log('Attempting to login...')
+ userConfig = await signInWithBrowser()
+ if (!userConfig) {
+ console.info('Login aborted')
+ return
+ }
+ fs.mkdirSync(path.dirname(USER_CONFIG_PATH), { recursive: true })
+ fs.writeFileSync(USER_CONFIG_PATH, JSON.stringify(userConfig, null, 2))
+ }
+ console.log(`Logged in as ${asBold(userConfig.email)}`)
+ })
+
+export const logoutCommand = new commander.Command('logout')
+ .description('Logout of e2b')
+ .action(() => {
+ if (fs.existsSync(USER_CONFIG_PATH)) {
+ fs.unlinkSync(USER_CONFIG_PATH) // Delete user config
+ console.log(`Logged out.`)
+ } else {
+ console.log(`Not logged in, nothing to do`)
+ }
+ })
+
+export function getUserConfig(): UserConfig | null {
+ if (!fs.existsSync(USER_CONFIG_PATH)) return null
+ return JSON.parse(fs.readFileSync(USER_CONFIG_PATH, 'utf8'))
+}
+
+async function signInWithBrowser(): Promise<UserConfig> {
+ const server = http.createServer()
+ const { port } = await listen(server, 0, '127.0.0.1')
+ const loginUrl = new URL(`${DOCS_BASE}/api/cli`)
+ loginUrl.searchParams.set('next', `http://localhost:${port}`)
+ loginUrl.searchParams.set('cliVersion', pkg.version)
+
+ return new Promise((resolve, reject) => {
+ server.once('request', (req, res) => {
+ // Close the HTTP connection to prevent `server.close()` from hanging
+ res.setHeader('connection', 'close')
+ const followUpUrl = new URL(`${DOCS_BASE}/api/cli`)
+ const searchParams = new URL(req.url || '/', 'http://localhost').searchParams
+ const searchParamsObj = Object.fromEntries(searchParams.entries()) as UserConfig & {
+ error?: string
+ }
+ const { error } = searchParamsObj
+ if (error) {
+ reject(new Error(error))
+ followUpUrl.searchParams.set('state', 'error')
+ followUpUrl.searchParams.set('error', error)
+ } else {
+ resolve(searchParamsObj)
+ followUpUrl.searchParams.set('state', 'success')
+ followUpUrl.searchParams.set('email', searchParamsObj.email!)
+ }
+
+ res.statusCode = 302
+ res.setHeader('location', followUpUrl.href)
+ res.end()
+ })
+
+ return open(loginUrl.toString())
+ })
+}
diff --git a/packages/cli/src/commands/env/index.ts b/packages/cli/src/commands/env/index.ts
index 9509d9fae..2a53e7618 100644
--- a/packages/cli/src/commands/env/index.ts
+++ b/packages/cli/src/commands/env/index.ts
@@ -12,7 +12,7 @@ import { configName } from 'src/config'
import { setCommand } from './set'
export const envCommand = new commander.Command('env')
- .description(`Manage Devbook environments and their ${asLocal(configName)} configs`)
+ .description(`Manage e2b environments and their ${asLocal(configName)} configs`)
.addCommand(createCommand)
.addCommand(pushCommand)
.addCommand(publishCommand)
diff --git a/packages/cli/src/commands/index.ts b/packages/cli/src/commands/index.ts
index 6d6a9a0fe..fe8952649 100644
--- a/packages/cli/src/commands/index.ts
+++ b/packages/cli/src/commands/index.ts
@@ -1,9 +1,12 @@
import * as commander from 'commander'
-import { runCommand } from './run'
-import { envCommand } from './env'
+// import { envCommand } from './env'
+// import { runCommand } from './run'
+import { loginCommand, logoutCommand } from './auth'
export const program = new commander.Command()
- .description('Tool for interacting with Devbook from command line')
- .addCommand(runCommand, { hidden: true })
- .addCommand(envCommand, { isDefault: true })
+ .description('Tool for interacting with e2b from command line')
+ // .addCommand(envCommand, { isDefault: true }) // Re-enable later
+ // .addCommand(runCommand, { hidden: true }) // Re-enable later
+ .addCommand(loginCommand)
+ .addCommand(logoutCommand)
diff --git a/packages/cli/src/config/index.ts b/packages/cli/src/config/index.ts
index bff547d56..ec2ee07e1 100644
--- a/packages/cli/src/config/index.ts
+++ b/packages/cli/src/config/index.ts
@@ -10,9 +10,9 @@ const dockerNames = require('docker-names')
import { getFiles } from '../utils/filesystem'
import { asFormattedEnvironment, asLocalRelative } from 'src/utils/format'
-export const configName = 'dbk.toml'
+export const configName = 'e2b.toml'
-const configCommentHeader = `# This is a config for a Devbook environment
+const configCommentHeader = `# This is a config for a e2b environment
`
@@ -30,7 +30,7 @@ export const configSchema = yup.object({
}),
})
-export type DevbookConfig = yup.InferType<typeof configSchema>
+export type E2bConfig = yup.InferType<typeof configSchema>
export async function loadConfig(configPath: string) {
try {
@@ -41,10 +41,10 @@ export async function loadConfig(configPath: string) {
const tomlRaw = await fsPromise.readFile(configPath, 'utf-8')
const config = toml.parse(tomlRaw)
- return (await configSchema.validate(config)) as DevbookConfig
+ return (await configSchema.validate(config)) as E2bConfig
} catch (err: any) {
throw new Error(
- `Devbook environment config ${asLocalRelative(configPath)} cannot be loaded: ${
+ `E2b environment config ${asLocalRelative(configPath)} cannot be loaded: ${
err.message
}`,
)
@@ -53,7 +53,7 @@ export async function loadConfig(configPath: string) {
export async function saveConfig(
configPath: string,
- config: DevbookConfig,
+ config: E2bConfig,
overwrite?: boolean,
) {
try {
@@ -72,7 +72,7 @@ export async function saveConfig(
await fsPromise.writeFile(configPath, configCommentHeader + tomlRaw)
} catch (err: any) {
throw new Error(
- `Devbook environment config ${asFormattedEnvironment(
+ `e2b environment config ${asFormattedEnvironment(
config,
configPath,
)} cannot be saved: ${err.message}`,
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index 2b2fa5d04..42ecc2933 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -8,4 +8,4 @@ import * as packageJSON from '../package.json'
updateNotifier.default({ pkg: packageJSON }).notify()
-program.version(packageJSON.version, undefined, 'Display Devbook CLI version').parse()
+program.version(packageJSON.version, undefined, 'Display e2b CLI version').parse()