Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
import { ApiClient, components, handleApiError } from './api'
import {
ClientFactory,
ConnectionConfig,
ConnectionOpts,
} from './connectionConfig'
import {
InvalidArgumentError,
SecretError,
SecretNotFoundError,
} from './errors'
import { Paginator } from './paginator'
import type { SandboxIamToken } from './sandbox/sandboxApi'
const INVALID_SECRET_NAME_CHARS = /[{}\p{Cc}]/u
function validateSecretName(name: string): void {
if (name.length === 0 || INVALID_SECRET_NAME_CHARS.test(name)) {
throw new InvalidArgumentError(
`secret name ${JSON.stringify(name)} is not usable: a secret name cannot be empty or contain '{', '}' or control characters, because it is interpolated into the '\${e2b.secrets.<name>}' placeholder the runtime resolves.`
)
}
}
/**
* Metadata of a secret. Secret values are write-only and never returned.
*/
export interface SecretInfo {
/**
* Secret ID.
*/
secretId: string
/**
* Secret name, unique within the project.
*/
name: string
/**
* Version served to readers that do not name one.
*/
version: number
/**
* Customer metadata of the secret.
*/
metadata: Record<string, string>
/**
* Time when the secret was created.
*/
createdAt: Date
/**
* Time when the secret was last updated.
*/
updatedAt: Date
}
export interface SecretCreateOpts extends ConnectionOpts {
/**
* Customer metadata to store with the secret.
*/
metadata?: Record<string, string>
}
export interface SecretUpdateOpts extends ConnectionOpts {
/**
* Customer metadata to store with the secret. When provided, replaces the
* stored metadata.
*/
metadata?: Record<string, string>
}
export type SecretGetInfoOpts = ConnectionOpts
export type SecretExistsOpts = ConnectionOpts
export type SecretDestroyOpts = ConnectionOpts
export interface SecretListOpts extends Omit<ConnectionOpts, 'signal'> {
/**
* Number of secrets to return per page.
*
* @default 100
*/
limit?: number
/**
* Token to the next page.
*/
nextToken?: string
}
function convertSecretInfo(
secret: components['schemas']['Secret']
): SecretInfo {
return {
secretId: secret.secretID,
name: secret.name,
version: secret.currentVersion,
metadata: secret.metadata ?? {},
createdAt: new Date(secret.createdAt),
updatedAt: new Date(secret.updatedAt),
}
}
/**
* Paginator for listing secrets.
*
* @example
* ```ts
* const paginator = Secret.list()
* while (paginator.hasNext) {
* const secrets = await paginator.nextItems()
* console.log(secrets)
* }
* ```
*/
export class SecretPaginator extends Paginator<SecretInfo> {
constructor(opts?: SecretListOpts) {
super(opts, opts?.limit, opts?.nextToken)
}
async nextItems(opts?: ConnectionOpts): Promise<SecretInfo[]> {
if (!this.hasNext) {
throw new Error('No more items to fetch')
}
const apiOpts = ConnectionConfig.mergeOpts(this.opts, opts)
const config = new ConnectionConfig(apiOpts)
const client = new ApiClient(config)
const res = await client.api.GET('/secrets', {
params: {
query: {
limit: this.limit,
nextToken: this.nextToken,
},
},
signal: config.getSignal(apiOpts?.requestTimeoutMs, apiOpts?.signal),
})
const err = handleApiError(res, SecretError)
if (err) {
throw err
}
this.updatePagination(res.response)
return (res.data ?? []).map(convertSecretInfo)
}
}
/**
* Module for managing E2B secrets and workload identity helpers.
*
* Secret values are write-only: they are accepted by {@link Secret.create}
* and {@link Secret.update} but never returned by any read surface.
*/
export class Secret extends ClientFactory {
/**
* Create a new secret and its first value.
*
* @param name name of the secret, unique within the project.
* @param value secret value. Write-only — never returned by the API.
* @param opts connection options.
*
* @returns the secret's ID, name, current version (`1` for a new secret),
* metadata, and creation and update times.
*/
static async create(
name: string,
value: string,
opts?: SecretCreateOpts
): Promise<SecretInfo> {
const apiOpts = this.resolveOpts(opts)
const config = new ConnectionConfig(apiOpts)
const client = new ApiClient(config)
const res = await client.api.POST('/secrets', {
body: {
name,
value,
metadata: apiOpts?.metadata,
},
signal: config.getSignal(apiOpts?.requestTimeoutMs, apiOpts?.signal),
})
const err = handleApiError(res, SecretError)
if (err) {
throw err
}
if (!res.data) {
throw new Error('Response data is missing')
}
return convertSecretInfo(res.data)
}
/**
* Update a secret's value by storing it as the secret's new version.
*
* @param secret secret ID or name.
* @param value new secret value. Write-only — never returned by the API.
* @param opts connection options.
*
* @returns the secret's ID, name, new current version, metadata, and
* creation and update times.
*/
static async update(
secret: string,
value: string,
opts?: SecretUpdateOpts
): Promise<SecretInfo> {
const apiOpts = this.resolveOpts(opts)
const config = new ConnectionConfig(apiOpts)
const client = new ApiClient(config)
const res = await client.api.POST('/secrets/{secretID}', {
params: {
path: {
secretID: secret,
},
},
body: {
value,
metadata: apiOpts?.metadata,
},
signal: config.getSignal(apiOpts?.requestTimeoutMs, apiOpts?.signal),
})
if (res.response.status === 404) {
throw new SecretNotFoundError(`Secret ${secret} not found`)
}
const err = handleApiError(res, SecretError)
if (err) {
throw err
}
if (!res.data) {
throw new Error('Response data is missing')
}
return convertSecretInfo(res.data)
}
/**
* Get a secret's metadata.
*
* @param secret secret ID or name.
* @param opts connection options.
*
* @returns the secret's ID, name, current version, metadata, and creation
* and update times.
*/
static async getInfo(
secret: string,
opts?: SecretGetInfoOpts
): Promise<SecretInfo> {
const apiOpts = this.resolveOpts(opts)
const config = new ConnectionConfig(apiOpts)
const client = new ApiClient(config)
const res = await client.api.GET('/secrets/{secretID}', {
params: {
path: {
secretID: secret,
},
},
signal: config.getSignal(apiOpts?.requestTimeoutMs, apiOpts?.signal),
})
if (res.response.status === 404) {
throw new SecretNotFoundError(`Secret ${secret} not found`)
}
const err = handleApiError(res, SecretError)
if (err) {
throw err
}
if (!res.data) {
throw new Error('Response data is missing')
}
return convertSecretInfo(res.data)
}
/**
* List the project's secrets.
*
* @param opts connection options.
*
* @returns paginator over the project's secrets. Drain it page by page:
* `while (paginator.hasNext) { const secrets = await paginator.nextItems() }`.
*
* @example
* ```ts
* const paginator = Secret.list({ limit: 50 })
* while (paginator.hasNext) {
* const secrets = await paginator.nextItems()
* }
* ```
*/
static list(opts?: SecretListOpts): SecretPaginator {
return new SecretPaginator(this.resolveOpts(opts))
}
/**
* Check whether a secret exists.
*
* @param secret secret ID or name.
* @param opts connection options.
*
* @returns `true` if the secret exists, `false` otherwise.
*/
static async exists(
secret: string,
opts?: SecretExistsOpts
): Promise<boolean> {
try {
await this.getInfo(secret, opts)
return true
} catch (err) {
if (err instanceof SecretNotFoundError) {
return false
}
throw err
}
}
/**
* Destroy a secret, making all its versions inaccessible.
*
* @param secret secret ID or name.
* @param opts connection options.
*
* @returns `true` if the secret was destroyed, `false` if it was not found.
*/
static async destroy(
secret: string,
opts?: SecretDestroyOpts
): Promise<boolean> {
const apiOpts = this.resolveOpts(opts)
const config = new ConnectionConfig(apiOpts)
const client = new ApiClient(config)
const res = await client.api.DELETE('/secrets/{secretID}', {
params: {
path: {
secretID: secret,
},
},
signal: config.getSignal(apiOpts?.requestTimeoutMs, apiOpts?.signal),
})
if (res.response.status === 404) {
return false
}
const err = handleApiError(res, SecretError)
if (err) {
throw err
}
return true
}
/**
* Format a placeholder that the runtime resolves to the secret's current
* value.
*
* This is a local formatting helper and makes no network call — it does
* not check whether the named secret exists. An unknown reference fails
* server-side when the placeholder is resolved.
*
* @param secret secret name.
*
* @returns placeholder string resolving to the secret's value.
*
* @example
* ```ts
* Secret.fill('openai-api-key')
* // '${e2b.secrets.openai-api-key}'
* ```
*/
static fill(secret: string): string {
validateSecretName(secret)
return `\${e2b.secrets.${secret}}`
}
/**
* Define a workload identity token to pass to `iam.tokens` when creating
* a sandbox.
*
* @param token workload token definition.
*
* @returns a token definition passable to `iam.tokens`.
*
* @example
* ```ts
* const sandbox = await Sandbox.create({
* iam: {
* tokens: {
* aws: Secret.iamToken({
* audience: 'sts.amazonaws.com',
* tokenType: 'JWT-SVID',
* }),
* },
* },
* })
* ```
*/
static iamToken(token: SandboxIamToken): SandboxIamToken {
return { ...token }
}
}