CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-twilio

A comprehensive Node.js SDK for the Twilio communications platform, enabling SMS, voice, video, and other communication services integration.

Pending
Overview
Eval results
Files

credential-providers.mddocs/

Credential Providers

Credential providers offer flexible authentication strategies for the Twilio SDK beyond basic username/password authentication. They support OAuth2 client credentials, organizational accounts, and scenarios where no authentication is required.

Capabilities

ClientCredentialProvider

OAuth2 client credentials provider for API authentication using client ID and secret instead of Account SID and Auth Token.

/**
 * OAuth2 client credentials provider for secure API authentication
 * Uses client credentials grant flow for token-based authentication
 */
class ClientCredentialProvider extends CredentialProvider {
  grantType: string;
  clientId: string;
  clientSecret: string;
  tokenManager: TokenManager | null;

  constructor();
  
  /**
   * Convert to authentication strategy for HTTP requests
   * @returns TokenAuthStrategy with managed OAuth2 tokens
   */
  toAuthStrategy(): AuthStrategy;
}

ClientCredentialProviderBuilder

Builder pattern for constructing client credential providers with fluent configuration.

/**
 * Builder for ClientCredentialProvider with fluent configuration
 * Provides step-by-step construction with validation
 */
class ClientCredentialProviderBuilder {
  constructor();

  /**
   * Set the OAuth2 client ID
   * @param clientId - The client identifier from Twilio console
   * @returns Builder instance for method chaining
   */
  setClientId(clientId: string): ClientCredentialProviderBuilder;

  /**
   * Set the OAuth2 client secret
   * @param clientSecret - The client secret from Twilio console
   * @returns Builder instance for method chaining
   */
  setClientSecret(clientSecret: string): ClientCredentialProviderBuilder;

  /**
   * Set custom token manager (optional)
   * @param tokenManager - Custom token manager implementation
   * @returns Builder instance for method chaining
   */
  setTokenManager(tokenManager: TokenManager): ClientCredentialProviderBuilder;

  /**
   * Build the configured credential provider
   * @returns Configured ClientCredentialProvider instance
   */
  build(): ClientCredentialProvider;
}

Usage Examples:

import TwilioSDK from "twilio";

// Access credential provider builders
const { ClientCredentialProviderBuilder, Twilio } = TwilioSDK;

// Basic OAuth2 authentication
const credentialProvider = new ClientCredentialProviderBuilder()
  .setClientId("your_client_id")
  .setClientSecret("your_client_secret")
  .build();

// Create Twilio client with OAuth2 credentials
const client = new Twilio();
client.setCredentialProvider(credentialProvider);

// Use client normally - authentication handled automatically
const message = await client.messages.create({
  body: "Hello from OAuth2!",
  from: "+1234567890",
  to: "+0987654321"
});

// With custom token manager
const customTokenManager = new CustomTokenManager();
const provider = new ClientCredentialProviderBuilder()
  .setClientId("client_id")
  .setClientSecret("client_secret")
  .setTokenManager(customTokenManager)
  .build();

OrgsCredentialProvider

Organization-level credential provider for multi-tenant applications and enterprise account management.

/**
 * Organization credential provider for enterprise and multi-tenant applications
 * Provides organization-scoped authentication with hierarchical access control
 */
class OrgsCredentialProvider extends CredentialProvider {
  grantType: string;
  clientId: string;
  clientSecret: string;
  tokenManager: TokenManager | null;

  constructor();
  
  /**
   * Convert to authentication strategy for HTTP requests
   * @returns TokenAuthStrategy with organization-scoped tokens
   */
  toAuthStrategy(): AuthStrategy;
}

OrgsCredentialProviderBuilder

Builder for organization credential providers with enterprise-specific configuration.

/**
 * Builder for OrgsCredentialProvider with organization-specific configuration
 * Supports enterprise account hierarchies and multi-tenant architectures
 */
class OrgsCredentialProviderBuilder {
  constructor();

  /**
   * Set the organization client ID
   * @param clientId - The organization client identifier
   * @returns Builder instance for method chaining
   */
  setClientId(clientId: string): OrgsCredentialProviderBuilder;

  /**
   * Set the organization client secret
   * @param clientSecret - The organization client secret
   * @returns Builder instance for method chaining
   */
  setClientSecret(clientSecret: string): OrgsCredentialProviderBuilder;

  /**
   * Set custom organization token manager
   * @param tokenManager - Custom token manager for org-scoped tokens
   * @returns Builder instance for method chaining
   */
  setTokenManager(tokenManager: TokenManager): OrgsCredentialProviderBuilder;

  /**
   * Build the configured organization credential provider
   * @returns Configured OrgsCredentialProvider instance
   */
  build(): OrgsCredentialProvider;
}

Usage Examples:

import TwilioSDK from "twilio";

// Access organization credential provider builder
const { OrgsCredentialProviderBuilder, Twilio } = TwilioSDK;

// Organization-level authentication
const orgProvider = new OrgsCredentialProviderBuilder()
  .setClientId("org_client_id")
  .setClientSecret("org_client_secret")
  .build();

// Multi-tenant application setup
class TenantManager {
  private providers = new Map<string, OrgsCredentialProvider>();

  createTenantProvider(tenantId: string, clientId: string, clientSecret: string) {
    const provider = new OrgsCredentialProviderBuilder()
      .setClientId(clientId)
      .setClientSecret(clientSecret)
      .build();
    
    this.providers.set(tenantId, provider);
    return provider;
  }

  getTwilioClient(tenantId: string): Twilio {
    const provider = this.providers.get(tenantId);
    if (!provider) throw new Error(`No provider for tenant ${tenantId}`);
    
    const client = new Twilio();
    client.setCredentialProvider(provider);
    return client;
  }
}

NoAuthCredentialProvider

No-authentication provider for accessing public endpoints or testing scenarios where authentication is not required.

/**
 * No-authentication credential provider for public endpoints
 * Used for accessing Twilio resources that don't require authentication
 */
class NoAuthCredentialProvider extends CredentialProvider {
  constructor();

  /**
   * Convert to no-auth strategy that bypasses authentication
   * @returns NoAuthStrategy that doesn't add authentication headers
   */
  toAuthStrategy(): AuthStrategy;
}

Usage Examples:

import TwilioSDK from "twilio";

// Access no-auth credential provider
const { NoAuthCredentialProvider, Twilio } = TwilioSDK;

// For public endpoints or development testing
const noAuthProvider = new NoAuthCredentialProvider();

const client = new Twilio();
client.setCredentialProvider(noAuthProvider);

// Use for public endpoints that don't require auth
// Note: Most Twilio APIs do require authentication
const publicData = await client.request({
  method: "GET",
  uri: "https://api.twilio.com/public-endpoint"
});

// Development/testing scenario
if (process.env.NODE_ENV === "test") {
  const testClient = new Twilio();
  testClient.setCredentialProvider(new NoAuthCredentialProvider());
  // Use for mocked/stubbed testing
}

Base CredentialProvider

Abstract base class for all credential providers defining the common interface.

/**
 * Abstract base class for all credential providers
 * Defines the common interface for authentication strategies
 */
abstract class CredentialProvider {
  private authType: string;

  protected constructor(authType: string);

  /**
   * Get the authentication type identifier
   * @returns String identifier for the auth type
   */
  getAuthType(): string;

  /**
   * Convert provider to authentication strategy for HTTP requests
   * @returns AuthStrategy implementation for this provider type
   */
  abstract toAuthStrategy(): AuthStrategy;
}

Authentication Strategies

The authentication strategies that credential providers generate for HTTP client usage.

/**
 * Authentication strategy interface for HTTP request authentication
 * Applied to outgoing requests to add appropriate authentication headers
 */
interface AuthStrategy {
  /**
   * Apply authentication to an HTTP request
   * @param request - The request configuration to authenticate
   * @returns Promise resolving to authenticated request config
   */
  apply(request: RequestConfig): Promise<RequestConfig>;
}

/**
 * Token-based authentication strategy using OAuth2 or similar tokens
 * Automatically handles token refresh and management
 */
class TokenAuthStrategy implements AuthStrategy {
  constructor(tokenManager: TokenManager);
  apply(request: RequestConfig): Promise<RequestConfig>;
}

/**
 * No-authentication strategy that bypasses authentication
 * Leaves requests unmodified without adding auth headers
 */
class NoAuthStrategy implements AuthStrategy {
  apply(request: RequestConfig): Promise<RequestConfig>;
}

Token Management

Token managers handle the lifecycle of OAuth2 and other authentication tokens.

/**
 * Token manager interface for OAuth2 and bearer token lifecycle management
 * Handles token acquisition, refresh, and caching
 */
interface TokenManager {
  /**
   * Get a valid access token, refreshing if necessary
   * @returns Promise resolving to current valid access token
   */
  getToken(): Promise<string>;

  /**
   * Force refresh of the current token
   * @returns Promise resolving to new access token
   */
  refreshToken(): Promise<string>;

  /**
   * Clear cached tokens and force re-authentication
   */
  clearToken(): void;
}

/**
 * API token manager for standard Twilio API OAuth2 flows
 * Handles client credentials grant type with automatic refresh
 */
class ApiTokenManager implements TokenManager {
  constructor(options: TokenManagerOptions);
  getToken(): Promise<string>;
  refreshToken(): Promise<string>;
  clearToken(): void;
}

/**
 * Organization token manager for enterprise OAuth2 flows
 * Provides organization-scoped tokens with hierarchical access
 */
class OrgsTokenManager implements TokenManager {
  constructor(options: TokenManagerOptions);
  getToken(): Promise<string>;
  refreshToken(): Promise<string>;
  clearToken(): void;
}

interface TokenManagerOptions {
  /** OAuth2 grant type (typically "client_credentials") */
  grantType: string;
  /** OAuth2 client identifier */
  clientId: string;
  /** OAuth2 client secret */
  clientSecret: string;
  /** Token endpoint URL (optional, uses Twilio default) */
  tokenUrl?: string;
  /** Token cache TTL in seconds (optional) */
  cacheTtl?: number;
}

Usage Examples:

// Custom token manager implementation
class CustomTokenManager implements TokenManager {
  private token: string | null = null;
  private expiry: Date | null = null;

  async getToken(): Promise<string> {
    if (!this.token || !this.expiry || this.expiry <= new Date()) {
      return this.refreshToken();
    }
    return this.token;
  }

  async refreshToken(): Promise<string> {
    // Custom token acquisition logic
    const response = await fetch("https://your-auth-server.com/token", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ 
        grant_type: "client_credentials",
        client_id: this.clientId,
        client_secret: this.clientSecret
      })
    });

    const data = await response.json();
    this.token = data.access_token;
    this.expiry = new Date(Date.now() + (data.expires_in * 1000));
    
    return this.token;
  }

  clearToken(): void {
    this.token = null;
    this.expiry = null;
  }
}

Types

interface RequestConfig {
  method: string;
  url: string;
  headers: Record<string, string>;
  data?: any;
  timeout?: number;
}

type AuthType = "client-credentials" | "noauth" | "basic";

interface ProviderConfig {
  authType: AuthType;
  clientId?: string;
  clientSecret?: string;
  tokenManager?: TokenManager;
}

Install with Tessl CLI

npx tessl i tessl/npm-twilio

docs

credential-providers.md

index.md

jwt.md

rest-client.md

twiml.md

webhooks.md

tile.json