CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-slack--oauth

Official library for interacting with Slack's OAuth endpoints

Pending
Overview
Eval results
Files

oauth-flow.mddocs/

OAuth Flow Management

Complete OAuth 2.0 flow implementation for Slack app installations, handling URL generation, callback processing, and authorization queries with support for both OAuth v1 and v2.

Capabilities

InstallProvider Class

Main OAuth coordinator that manages the complete OAuth flow from installation to authorization.

/**
 * InstallProvider manages the complete OAuth flow for Slack app installations
 */
class InstallProvider {
  /** OAuth state store for CSRF protection */
  public stateStore?: StateStore;
  /** Installation data storage */
  public installationStore: InstallationStore;
  
  /**
   * Initialize OAuth provider with configuration options
   * @param options - OAuth configuration including client credentials and stores
   */
  constructor(options: InstallProviderOptions);
  
  /**
   * Handle requests to the install path, rendering install page or redirecting to OAuth
   * @param req - Incoming HTTP request
   * @param res - HTTP response for rendering install page
   * @param options - Optional install path configuration
   * @param installOptions - Optional OAuth parameters for this installation
   */
  async handleInstallPath(
    req: IncomingMessage,
    res: ServerResponse,
    options?: InstallPathOptions,
    installOptions?: InstallURLOptions
  ): Promise<void>;
  
  /**
   * Generate Slack OAuth installation URL
   * @param options - OAuth parameters including scopes and redirect settings  
   * @returns OAuth URL for redirecting users to Slack
   */
  async generateInstallUrl(options: InstallURLOptions): Promise<string>;
  
  /**
   * Handle OAuth callback from Slack after user authorization
   * @param req - Incoming callback request with authorization code
   * @param res - HTTP response for success/failure handling
   * @param options - Optional callback handlers for success/failure
   */
  async handleCallback(
    req: IncomingMessage,
    res: ServerResponse,
    options?: CallbackOptions
  ): Promise<void>;
  
  /**
   * Authorize API requests by fetching installation data
   * @param source - Query parameters to identify the installation
   * @returns Authorization result with tokens and identifiers
   */
  async authorize(source: InstallationQuery<boolean>): Promise<AuthorizeResult>;
}

InstallProviderOptions

Configuration options for initializing the OAuth provider.

interface InstallProviderOptions {
  /** Client ID from Slack app configuration */
  clientId: string;
  /** Client Secret from Slack app configuration */
  clientSecret: string;
  /** Optional custom installation store (defaults to MemoryInstallationStore) */
  installationStore?: InstallationStore;
  /** Optional custom Slack authorization URL */
  authorizationUrl?: string;
  /** Optional custom state store for OAuth state management */
  stateStore?: StateStore;
  /** Secret for built-in state store encryption */
  stateSecret?: string;
  /** OAuth version: "v1" for Classic Apps, "v2" for modern Apps (default: "v2") */
  authVersion?: "v1" | "v2";
  /** Enable/disable state verification for CSRF protection (default: true) */
  stateVerification?: boolean;
  /** Legacy state verification mode for backward compatibility (default: false) */
  legacyStateVerification?: boolean;
  /** Cookie name for state parameter storage (default: "slack-app-oauth-state") */
  stateCookieName?: string;
  /** State cookie expiration in seconds (default: 600) */
  stateCookieExpirationSeconds?: number;
  /** Skip install path rendering and redirect immediately (default: false) */
  directInstall?: boolean;
  /** Custom HTML renderer for install path */
  renderHtmlForInstallPath?: (url: string) => string;
  /** Custom logger instance */
  logger?: Logger;
  /** Log level when using default logger */
  logLevel?: LogLevel;
  /** Default installation URL options */
  installUrlOptions?: InstallURLOptions;
  /** Additional WebClient options (excluding logger and logLevel) */
  clientOptions?: Omit<WebClientOptions, 'logger' | 'logLevel'>;
}

InstallURLOptions

Options for configuring OAuth installation URLs.

interface InstallURLOptions {
  /** OAuth scopes to request from user (required) */
  scopes: string | string[];
  /** Additional user scopes for user token (OAuth v2 only) */
  userScopes?: string | string[];
  /** Custom redirect URI (must match app configuration) */
  redirectUri?: string;
  /** Team ID for direct team installation */
  teamId?: string;
  /** Additional metadata to pass through OAuth flow */
  metadata?: string;
}

CallbackOptions

Options for handling OAuth callback responses.

interface CallbackOptions {
  /**
   * Custom logic before installation execution
   * Return false to skip installation and handle response manually
   */
  beforeInstallation?: (
    options: InstallURLOptions,
    callbackReq: IncomingMessage,
    callbackRes: ServerResponse
  ) => Promise<boolean>;

  /**
   * Custom logic after installation but before storage
   * Return false to skip storage and handle response manually
   */
  afterInstallation?: (
    installation: Installation<"v1" | "v2", boolean>,
    options: InstallURLOptions,
    callbackReq: IncomingMessage,
    callbackRes: ServerResponse
  ) => Promise<boolean>;

  /** Custom success handler after successful OAuth flow */
  success?: (
    installation: Installation<"v1" | "v2", boolean>,
    installOptions: InstallURLOptions,
    req: IncomingMessage,
    res: ServerResponse
  ) => void;

  /** Async version of success handler (both execute if provided) */
  successAsync?: (
    installation: Installation<"v1" | "v2", boolean>,
    installOptions: InstallURLOptions,
    req: IncomingMessage,
    res: ServerResponse
  ) => Promise<void>;

  /** Custom failure handler for OAuth errors */
  failure?: (
    error: CodedError,
    installOptions: InstallURLOptions,
    req: IncomingMessage,
    res: ServerResponse
  ) => void;

  /** Async version of failure handler (both execute if provided) */
  failureAsync?: (
    error: CodedError,
    installOptions: InstallURLOptions,
    req: IncomingMessage,
    res: ServerResponse
  ) => Promise<void>;
}

/**
 * Default success handler - sends HTML success page
 */
function defaultCallbackSuccess(
  installation: Installation<"v1" | "v2", boolean>,
  installOptions: InstallURLOptions,
  req: IncomingMessage,
  res: ServerResponse
): void;

/**
 * Default failure handler - sends HTML error page
 */
function defaultCallbackFailure(
  error: CodedError,
  installOptions: InstallURLOptions,
  req: IncomingMessage,
  res: ServerResponse
): void;

AuthorizeResult

Result returned from the authorize method containing tokens and identifiers.

interface AuthorizeResult {
  /** Bot access token for API calls */
  botToken?: string;
  /** Bot refresh token for token renewal */
  botRefreshToken?: string;
  /** Bot token expiration timestamp (UTC seconds) */
  botTokenExpiresAt?: number;
  /** User access token for user-context API calls */
  userToken?: string;
  /** User refresh token for token renewal */
  userRefreshToken?: string;
  /** User token expiration timestamp (UTC seconds) */
  userTokenExpiresAt?: number;
  /** Bot user ID */
  botId?: string;
  /** Bot user ID in the workspace */
  botUserId?: string;
  /** Team (workspace) ID */
  teamId?: string;
  /** Enterprise Grid organization ID */
  enterpriseId?: string;
}

OAuth API Responses

Response types from Slack OAuth API endpoints.

interface OAuthV2Response extends WebAPICallResult {
  app_id: string;
  authed_user: {
    id: string;
    scope?: string;
    access_token?: string;
    token_type?: string;
    refresh_token?: string;
    expires_in?: number;
  };
  scope?: string;
  token_type?: "bot";
  access_token?: string;
  refresh_token?: string;
  expires_in?: number;
  bot_user_id?: string;
  team: { id: string; name: string } | null;
  enterprise: { name: string; id: string } | null;
  is_enterprise_install: boolean;
  incoming_webhook?: {
    url: string;
    channel: string;
    channel_id: string;
    configuration_url: string;
  };
}

interface OAuthV2TokenRefreshResponse extends WebAPICallResult {
  app_id: string;
  scope: string;
  token_type: "bot" | "user";
  access_token: string;
  refresh_token: string;
  expires_in: number;
  bot_user_id?: string;
  team: { id: string; name: string };
  enterprise: { name: string; id: string } | null;
  is_enterprise_install: boolean;
}

Default HTML Renderer

Default HTML renderer function for the install path.

/**
 * Default HTML renderer for install path - creates simple install page
 * @param url - OAuth installation URL to redirect to
 * @returns HTML string for install page
 */
function defaultRenderHtmlForInstallPath(url: string): string;

Usage Examples:

import { InstallProvider, InstallURLOptions } from "@slack/oauth";

// Basic setup
const installer = new InstallProvider({
  clientId: process.env.SLACK_CLIENT_ID!,
  clientSecret: process.env.SLACK_CLIENT_SECRET!,
  stateSecret: "my-secret-key",
});

// Generate install URL
const installUrl = await installer.generateInstallUrl({
  scopes: ["chat:write", "commands"],
  userScopes: ["chat:write"],
  metadata: "custom-data",
});

// Handle install path
app.get("/slack/install", async (req, res) => {
  await installer.handleInstallPath(req, res, {
    scopes: ["chat:write", "commands"],
  });
});

// Handle OAuth callback
app.get("/slack/oauth_redirect", async (req, res) => {
  await installer.handleCallback(req, res, {
    success: (installation, options, req, res) => {
      console.log("Installation successful:", installation.team?.id);
      res.send("Success!");
    },
    failure: (error, options, req, res) => {
      console.error("Installation failed:", error.message);
      res.send("Installation failed");
    },
  });
});

// Authorize requests
const auth = await installer.authorize({
  teamId: "T1234567890",
  isEnterpriseInstall: false,
});

if (auth.botToken) {
  // Use bot token for API calls
  const client = new WebClient(auth.botToken);
}

Install with Tessl CLI

npx tessl i tessl/npm-slack--oauth

docs

error-handling.md

index.md

installation-storage.md

oauth-flow.md

state-management.md

tile.json