Manage service accounts and API keys for workspace automation. Service accounts enable programmatic access and automation workflows without requiring personal user accounts.
import { ElevenLabsClient } from "@elevenlabs/elevenlabs-js";
const client = new ElevenLabsClient({ apiKey: "your-api-key" });
// Access this API via: client.serviceAccountsList all service accounts in workspace.
/**
* @param requestOptions - Optional request configuration
* @returns List of service accounts
* @throws UnprocessableEntityError if request fails
*/
client.serviceAccounts.list(
requestOptions?: RequestOptions
): HttpResponsePromise<WorkspaceServiceAccountListResponseModel>;
interface WorkspaceServiceAccountListResponseModel {
/** Array of service accounts */
service_accounts: ServiceAccount[];
}
interface ServiceAccount {
/** Service account ID */
service_account_id: string;
/** Service account name */
name: string;
/** Description */
description?: string;
/** Creation timestamp */
created_at: number;
/** Number of API keys */
api_key_count: number;
/** Last used timestamp */
last_used_at?: number;
}Manage API keys for service accounts.
/**
* List API keys for service account
*/
client.serviceAccounts.apiKeys.list(
service_account_id: string,
requestOptions?: RequestOptions
): HttpResponsePromise<ServiceAccountApiKeyListResponseModel>;
/**
* Create new API key
*/
client.serviceAccounts.apiKeys.create(
service_account_id: string,
request: CreateServiceAccountApiKeyRequest,
requestOptions?: RequestOptions
): HttpResponsePromise<ServiceAccountApiKeyResponseModel>;
/**
* Delete API key
*/
client.serviceAccounts.apiKeys.delete(
service_account_id: string,
api_key_id: string,
requestOptions?: RequestOptions
): HttpResponsePromise<void>;
/**
* Update an existing API key
* @param service_account_id - Service account user ID
* @param api_key_id - API key ID to update
* @param request - Updated API key settings
* @param requestOptions - Optional request configuration
* @throws UnprocessableEntityError if request fails
*/
client.serviceAccounts.apiKeys.update(
service_account_id: string,
api_key_id: string,
request: BodyEditServiceAccountApiKeyV1ServiceAccountsServiceAccountUserIdApiKeysApiKeyIdPatch,
requestOptions?: RequestOptions
): HttpResponsePromise<unknown>;
interface CreateServiceAccountApiKeyRequest {
/** Key name */
name: string;
/** Key description */
description?: string;
/** Expiration timestamp (optional) */
expires_at?: number;
}
interface BodyEditServiceAccountApiKeyV1ServiceAccountsServiceAccountUserIdApiKeysApiKeyIdPatch {
/** Whether the key is enabled */
isEnabled?: boolean;
/** Updated key name */
name?: string;
/** Permission level: "all" or specific permissions */
permissions?: string;
}
interface ServiceAccountApiKeyResponseModel {
/** API key ID */
api_key_id: string;
/** API key value (only returned on creation) */
api_key?: string;
/** Key name */
name: string;
/** Description */
description?: string;
/** Creation timestamp */
created_at: number;
/** Expiration timestamp */
expires_at?: number;
/** Last used timestamp */
last_used_at?: number;
}
interface ServiceAccountApiKeyListResponseModel {
/** Array of API keys */
api_keys: ServiceAccountApiKeyResponseModel[];
}import { ElevenLabsClient } from "@elevenlabs/elevenlabs-js";
const client = new ElevenLabsClient({ apiKey: "your-api-key" });
// Get all service accounts
const accounts = await client.serviceAccounts.list();
console.log("Service Accounts:");
for (const account of accounts.service_accounts) {
console.log(`${account.name} (${account.service_account_id})`);
console.log(` Description: ${account.description || "N/A"}`);
console.log(` API Keys: ${account.api_key_count}`);
console.log(` Created: ${new Date(account.created_at * 1000).toLocaleString()}`);
if (account.last_used_at) {
console.log(` Last Used: ${new Date(account.last_used_at * 1000).toLocaleString()}`);
}
}// Get all API keys for a service account
const keys = await client.serviceAccounts.apiKeys.list("service-account-id");
console.log("API Keys:");
for (const key of keys.api_keys) {
console.log(`${key.name} (${key.api_key_id})`);
console.log(` Created: ${new Date(key.created_at * 1000).toLocaleString()}`);
if (key.expires_at) {
console.log(` Expires: ${new Date(key.expires_at * 1000).toLocaleString()}`);
}
if (key.last_used_at) {
console.log(` Last Used: ${new Date(key.last_used_at * 1000).toLocaleString()}`);
}
}// Create new API key for automation
const newKey = await client.serviceAccounts.apiKeys.create(
"service-account-id",
{
name: "Production Automation Key",
description: "API key for production automation workflows",
}
);
console.log("API Key Created:");
console.log("ID:", newKey.api_key_id);
console.log("Key:", newKey.api_key); // Only shown once!
console.log("\n⚠️ Save this key securely - it won't be shown again!");
// Store key securely
process.env.AUTOMATION_API_KEY = newKey.api_key!;// Create API key that expires in 90 days
const expirationDate = new Date();
expirationDate.setDate(expirationDate.getDate() + 90);
const tempKey = await client.serviceAccounts.apiKeys.create(
"service-account-id",
{
name: "Temporary Key",
description: "90-day temporary access key",
expires_at: Math.floor(expirationDate.getTime() / 1000),
}
);
console.log("Temporary key created, expires:", expirationDate.toLocaleDateString());// Revoke API key
await client.serviceAccounts.apiKeys.delete(
"service-account-id",
"api-key-id"
);
console.log("API key revoked");// Rotate API key (create new, delete old)
async function rotateApiKey(
serviceAccountId: string,
oldKeyId: string,
keyName: string
): Promise<string> {
// Create new key
const newKey = await client.serviceAccounts.apiKeys.create(
serviceAccountId,
{
name: `${keyName} (Rotated ${new Date().toISOString()})`,
description: "Rotated API key",
}
);
console.log("New API key created:", newKey.api_key_id);
// Delete old key
await client.serviceAccounts.apiKeys.delete(serviceAccountId, oldKeyId);
console.log("Old API key deleted:", oldKeyId);
return newKey.api_key!;
}
const newApiKey = await rotateApiKey(
"service-account-id",
"old-key-id",
"Production Key"
);// Check for expiring keys
async function checkExpiringKeys(
serviceAccountId: string,
daysThreshold: number = 30
): Promise<void> {
const keys = await client.serviceAccounts.apiKeys.list(serviceAccountId);
const now = Date.now() / 1000;
const threshold = now + (daysThreshold * 24 * 60 * 60);
console.log(`Keys expiring in next ${daysThreshold} days:`);
for (const key of keys.api_keys) {
if (key.expires_at && key.expires_at <= threshold) {
const daysLeft = Math.ceil((key.expires_at - now) / 86400);
console.log(`⚠️ ${key.name}: ${daysLeft} days remaining`);
}
}
}
await checkExpiringKeys("service-account-id", 30);// Find API keys that haven't been used recently
async function findUnusedKeys(
serviceAccountId: string,
daysUnused: number = 90
): Promise<ServiceAccountApiKeyResponseModel[]> {
const keys = await client.serviceAccounts.apiKeys.list(serviceAccountId);
const cutoff = Date.now() / 1000 - (daysUnused * 24 * 60 * 60);
return keys.api_keys.filter(key =>
!key.last_used_at || key.last_used_at < cutoff
);
}
const unusedKeys = await findUnusedKeys("service-account-id");
console.log(`Found ${unusedKeys.length} unused keys`);// Generate audit report for service accounts
async function auditServiceAccounts(): Promise<void> {
const accounts = await client.serviceAccounts.list();
console.log("=== Service Account Audit ===\n");
for (const account of accounts.service_accounts) {
console.log(`${account.name}:`);
const keys = await client.serviceAccounts.apiKeys.list(
account.service_account_id
);
console.log(` API Keys: ${keys.api_keys.length}`);
// Check for expired keys
const now = Date.now() / 1000;
const expiredKeys = keys.api_keys.filter(
k => k.expires_at && k.expires_at < now
);
if (expiredKeys.length > 0) {
console.log(` ⚠️ Expired keys: ${expiredKeys.length}`);
}
// Check for unused keys
const unusedKeys = keys.api_keys.filter(
k => !k.last_used_at
);
if (unusedKeys.length > 0) {
console.log(` ℹ️ Never used: ${unusedKeys.length}`);
}
console.log();
}
}
await auditServiceAccounts();// Create multiple API keys for different environments
const environments = ["development", "staging", "production"];
async function setupEnvironmentKeys(
serviceAccountId: string
): Promise<Record<string, string>> {
const keys: Record<string, string> = {};
for (const env of environments) {
const key = await client.serviceAccounts.apiKeys.create(
serviceAccountId,
{
name: `${env} Environment Key`,
description: `API key for ${env} environment`,
}
);
keys[env] = key.api_key!;
console.log(`Created ${env} key:`, key.api_key_id);
}
return keys;
}
const envKeys = await setupEnvironmentKeys("service-account-id");// Track API key usage
async function monitorKeyUsage(
serviceAccountId: string
): Promise<void> {
const keys = await client.serviceAccounts.apiKeys.list(serviceAccountId);
console.log("API Key Usage:");
for (const key of keys.api_keys) {
console.log(`${key.name}:`);
if (key.last_used_at) {
const daysSinceUse = Math.floor(
(Date.now() / 1000 - key.last_used_at) / 86400
);
console.log(` Last used: ${daysSinceUse} days ago`);
} else {
console.log(` Last used: Never`);
}
}
}
await monitorKeyUsage("service-account-id");// Delete all expired API keys
async function cleanupExpiredKeys(
serviceAccountId: string
): Promise<void> {
const keys = await client.serviceAccounts.apiKeys.list(serviceAccountId);
const now = Date.now() / 1000;
const expiredKeys = keys.api_keys.filter(
k => k.expires_at && k.expires_at < now
);
console.log(`Found ${expiredKeys.length} expired keys`);
for (const key of expiredKeys) {
await client.serviceAccounts.apiKeys.delete(
serviceAccountId,
key.api_key_id
);
console.log(`Deleted expired key: ${key.name}`);
}
}
await cleanupExpiredKeys("service-account-id");// Export inventory of all service account keys
async function exportKeysInventory(): Promise<void> {
const accounts = await client.serviceAccounts.list();
const inventory = [];
for (const account of accounts.service_accounts) {
const keys = await client.serviceAccounts.apiKeys.list(
account.service_account_id
);
for (const key of keys.api_keys) {
inventory.push({
service_account: account.name,
key_name: key.name,
created_at: new Date(key.created_at * 1000).toISOString(),
expires_at: key.expires_at
? new Date(key.expires_at * 1000).toISOString()
: "Never",
last_used: key.last_used_at
? new Date(key.last_used_at * 1000).toISOString()
: "Never",
});
}
}
await writeFile(
"keys_inventory.json",
JSON.stringify(inventory, null, 2)
);
console.log("Inventory exported to keys_inventory.json");
}
import { writeFile } from "fs/promises";
await exportKeysInventory();