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

jwt.mddocs/

JWT Authentication

JWT (JSON Web Token) authentication utilities provide secure token generation and validation for Twilio client applications, TaskRouter workers, and service capabilities. These tokens enable secure client-side access to Twilio services without exposing credentials.

Capabilities

AccessToken

Generates JWT access tokens for client-side applications that need to connect to Twilio services like Voice, Video, Chat, and Sync.

/**
 * JWT access token generator for Twilio client applications
 * Used to authenticate client-side applications and grant specific service capabilities
 */
class AccessToken {
  /** Default signing algorithm */
  static DEFAULT_ALGORITHM: "HS256";
  /** Supported signing algorithms */
  static ALGORITHMS: ["HS256", "HS384", "HS512"];
  
  accountSid: string;
  keySid: string;
  secret: string;
  ttl: number;
  identity: string;
  nbf?: number;
  region?: string;
  grants: Grant<any, any, any>[];

  /**
   * Creates a new access token instance
   * @param accountSid - The account's unique ID to which access is scoped
   * @param keySid - The signing key's unique ID (API Key SID)
   * @param secret - The secret to sign the token with (API Key Secret)
   * @param options - Token configuration options
   */
  constructor(
    accountSid: string,
    keySid: string,
    secret: string,
    options: AccessTokenOptions
  );

  /**
   * Add a service grant to the token
   * @param grant - Service-specific grant (Voice, Video, Chat, etc.)
   */
  addGrant<T extends Grant<any, any, any>>(grant: T): void;

  /**
   * Generate the JWT token string
   * @param algorithm - Signing algorithm (default: HS256)
   * @returns JWT token string
   */
  toJwt(algorithm?: "HS256" | "HS384" | "HS512"): string;
}

interface AccessTokenOptions {
  /** Time to live in seconds (default: 3600) */
  ttl?: number;
  /** Identity of the client user (required) */
  identity: string;
  /** Not before time from epoch in seconds */
  nbf?: number;
  /** Region value associated with this account */
  region?: string;
}

Usage Examples:

import TwilioSDK from "twilio";

// Access JWT utilities via namespace
const { jwt } = TwilioSDK;

// Create access token for voice calling
const accessToken = new jwt.AccessToken(
  "AC123...", // Account SID
  "SK456...", // API Key SID  
  "secret",   // API Key Secret
  { identity: "alice", ttl: 3600 }
);

// Add voice grant for incoming and outgoing calls
const voiceGrant = new jwt.AccessToken.VoiceGrant({
  incomingAllow: true,
  outgoingApplicationSid: "AP789..."
});
accessToken.addGrant(voiceGrant);

// Generate token for client application
const token = accessToken.toJwt();

Service Grants

Grant classes for specific Twilio services that can be added to access tokens.

abstract class Grant<TOptions, TPayload, TKey> {
  key: TKey;
  
  protected constructor(key: TKey);
  abstract toPayload(): TPayload;
}

/** TaskRouter grant for worker and workspace access */
class TaskRouterGrant extends Grant<TaskRouterGrantOptions, TaskRouterGrantPayload, "task_router"> {
  constructor(options?: TaskRouterGrantOptions);
}

interface TaskRouterGrantOptions {
  /** Workspace SID for TaskRouter operations */
  workspaceSid?: string;
  /** Worker SID for specific worker access */
  workerSid?: string;
  /** Role for the worker (e.g., "worker", "supervisor") */
  role?: string;
}

/** Chat grant for messaging and conversations */
class ChatGrant extends Grant<ChatGrantOptions, ChatGrantPayload, "chat"> {
  constructor(options?: ChatGrantOptions);
}

interface ChatGrantOptions {
  /** Chat service SID */
  serviceSid?: string;
  /** Endpoint ID for the client */
  endpointId?: string;
  /** Deployment role SID */
  deploymentRoleSid?: string;
  /** Push credential SID for notifications */
  pushCredentialSid?: string;
}

/** Video grant for room access and recording */
class VideoGrant extends Grant<VideoGrantOptions, VideoGrantPayload, "video"> {
  constructor(options?: VideoGrantOptions);
}

interface VideoGrantOptions {
  /** Specific room name to join */
  room?: string;
}

/** Sync grant for real-time data synchronization */
class SyncGrant extends Grant<SyncGrantOptions, SyncGrantPayload, "data_sync"> {
  constructor(options?: SyncGrantOptions);
}

interface SyncGrantOptions {
  /** Sync service SID */
  serviceSid?: string;
  /** Endpoint ID for sync operations */
  endpointId?: string;
}

/** Voice grant for telephony capabilities */
class VoiceGrant extends Grant<VoiceGrantOptions, VoiceGrantPayload, "voice"> {
  constructor(options?: VoiceGrantOptions);
}

interface VoiceGrantOptions {
  /** Allow incoming calls */
  incomingAllow?: boolean;
  /** Application SID for outgoing calls */
  outgoingApplicationSid?: string;
  /** Parameters for outgoing application */
  outgoingApplicationParams?: object;
  /** Endpoint ID for push notifications */
  endpointId?: string;
}

/** Playback grant for media playback */
class PlaybackGrant extends Grant<PlaybackGrantOptions, PlaybackGrantPayload, "player"> {
  constructor(options?: PlaybackGrantOptions);
}

interface PlaybackGrantOptions {
  /** Grant access for media playback */
  grant?: object;
}

Usage Examples:

// Multi-service access token
const accessToken = new jwt.AccessToken("AC123...", "SK456...", "secret", {
  identity: "user123",
  ttl: 7200 // 2 hours
});

// Add multiple grants for different services
accessToken.addGrant(new jwt.AccessToken.VoiceGrant({
  incomingAllow: true,
  outgoingApplicationSid: "AP789..."
}));

accessToken.addGrant(new jwt.AccessToken.VideoGrant({
  room: "support-room"
}));

accessToken.addGrant(new jwt.AccessToken.ChatGrant({
  serviceSid: "IS456...",
  endpointId: "user123"
}));

const token = accessToken.toJwt();

ClientCapability

Generates JWT capability tokens for Twilio Client applications to control voice calling permissions and event access.

/**
 * JWT capability token generator for Twilio Client applications
 * Controls permissions for voice calling and event streaming
 */
class ClientCapability {
  static EventStreamScope: typeof EventStreamScope;
  static IncomingClientScope: typeof IncomingClientScope;
  static OutgoingClientScope: typeof OutgoingClientScope;
  
  accountSid: string;
  authToken: string;
  ttl: number;
  scopes: Scope[];

  /**
   * Creates a new client capability instance
   * @param options - Capability configuration
   */
  constructor(options: ClientCapabilityOptions);

  /**
   * Add a capability scope to the token
   * @param scope - Capability scope (incoming, outgoing, or event stream)
   */
  addScope(scope: Scope): void;

  /**
   * Generate the capability token
   * @returns JWT capability token string
   */
  toJwt(): string;
}

interface ClientCapabilityOptions {
  /** Twilio Account SID */
  accountSid: string;
  /** Auth Token for signing */
  authToken: string;
  /** Time to live in seconds (default: 3600) */
  ttl?: number;
}

Capability Scopes

Scope classes that define specific permissions for Twilio Client applications.

interface Scope {
  scope: string;
  payload(): string;
}

/** Allow client to receive incoming calls */
class IncomingClientScope implements Scope {
  scope: "scope:client:incoming";
  clientName: string;

  constructor(clientName: string);
  payload(): string;
}

/** Allow client to make outgoing calls */
class OutgoingClientScope implements Scope {
  scope: "scope:client:outgoing";
  applicationSid: string;
  clientName?: string;
  params?: object;

  constructor(options: OutgoingClientScopeOptions);
  payload(): string;
}

interface OutgoingClientScopeOptions {
  /** TwiML Application SID for outgoing calls */
  applicationSid: string;
  /** Client name for identification */
  clientName?: string;
  /** Additional parameters for the application */
  params?: object;
}

/** Allow client to subscribe to event streams */
class EventStreamScope implements Scope {
  scope: "scope:stream:subscribe";
  filters: object;

  constructor(filters?: object);
  payload(): string;
}

Usage Examples:

// Client capability for voice calling
const capability = new jwt.ClientCapability({
  accountSid: "AC123...",
  authToken: "auth_token_here",
  ttl: 3600
});

// Allow incoming calls for specific client
capability.addScope(new jwt.ClientCapability.IncomingClientScope("alice"));

// Allow outgoing calls through TwiML application
capability.addScope(new jwt.ClientCapability.OutgoingClientScope({
  applicationSid: "AP456...",
  clientName: "alice"
}));

// Allow event stream subscription with filters
capability.addScope(new jwt.ClientCapability.EventStreamScope({
  account_sid: "AC123..."
}));

const token = capability.toJwt();

TaskRouterCapability

Specialized JWT generator for TaskRouter workers and supervisors with workspace-level permissions.

/**
 * JWT capability generator for TaskRouter operations
 * Provides workspace and worker-level access control
 */
class TaskRouterCapability {
  constructor(accountSid: string, authToken: string, workspaceSid: string, channelId: string);
  
  /**
   * Allow worker to receive reservations
   */
  allowWorkerActivityUpdates(): TaskRouterCapability;
  
  /**
   * Allow worker to fetch reservations
   */
  allowWorkerFetchReservations(): TaskRouterCapability;
  
  /**
   * Allow worker to update reservations
   */
  allowWorkerReservationsUpdate(): TaskRouterCapability;
  
  /**
   * Generate the capability token
   */
  toJwt(): string;
}

ValidationToken

JWT validation for incoming Twilio requests to ensure they originate from Twilio servers.

/**
 * JWT validator for incoming Twilio requests
 * Ensures request authenticity using public key cryptography
 */
class ValidationToken {
  static readonly DEFAULT_ALGORITHM: "RS256";
  static readonly ALGORITHMS: ["RS256", "PS256"];
  
  readonly accountSid: string;
  readonly credentialSid: string;
  readonly signingKey: string;
  readonly privateKey: string;
  readonly algorithm: Algorithm;
  ttl: number;

  /**
   * Creates a validation token instance
   * @param opts - Validation configuration options
   */
  constructor(opts: ValidationTokenOptions);

  /**
   * Get request canonicalizer for signature validation
   * @param request - HTTP request object
   * @returns Request canonicalizer instance
   */
  getRequestCanonicalizer(request: ValidationRequest): RequestCanonicalizer;

  /**
   * Generate validation token for outbound requests
   * @param canonicalizer - Request canonicalizer
   * @returns JWT validation token
   */
  generateToken(canonicalizer: RequestCanonicalizer): string;
}

interface ValidationTokenOptions {
  /** Account SID */
  accountSid: string;
  /** Public key credential SID */
  credentialSid: string;
  /** Signing key identifier */
  signingKey: string;
  /** Private key for signing */
  privateKey: string;
  /** Signing algorithm (default: RS256) */
  algorithm?: "RS256" | "PS256";
  /** Token time to live (default: 300) */
  ttl?: number;
}

interface ValidationRequest {
  /** Request headers */
  headers?: object;
  /** Request URL */
  url: string;
  /** HTTP method */
  method: string;
  /** Query parameters */
  params?: object;
  /** Request body data */
  data?: any;
}

Usage Examples:

// Validate incoming request from Twilio
const validationToken = new jwt.ValidationToken({
  accountSid: "AC123...",
  credentialSid: "CR456...",
  signingKey: "signing_key_here",
  privateKey: "-----BEGIN PRIVATE KEY-----\n...",
  algorithm: "RS256"
});

// Canonicalize the request for validation
const canonicalizer = validationToken.getRequestCanonicalizer({
  url: "https://myapp.com/webhook",
  method: "POST",
  headers: request.headers,
  data: request.body
});

// Generate validation token
const token = validationToken.generateToken(canonicalizer);

TaskRouter Utilities

Utility functions for TaskRouter JWT token operations and capability management.

namespace util {
  /**
   * Build TaskRouter capability URL for specific operations
   * @param accountSid - Account SID
   * @param workspaceSid - Workspace SID
   * @param channelId - Channel identifier
   * @param version - API version (default: "v1")
   * @returns Formatted capability URL
   */
  function buildWorkspaceUrl(
    accountSid: string,
    workspaceSid: string,
    channelId: string,
    version?: string
  ): string;
}

Types

type Algorithm = "HS256" | "HS384" | "HS512" | "RS256" | "PS256";

interface RequestCanonicalizer {
  /** Canonicalized request string for signature validation */
  canonicalizedRequest: string;
  
  /** Generate signature hash */
  getSignatureHash(): string;
}

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