CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-mockttp

Mock HTTP server for testing HTTP clients and stubbing webservices

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

certificate-management.mddocs/

Certificate Management

TLS certificate generation and management utilities for HTTPS interception, including CA certificate creation and SPKI fingerprint generation.

Capabilities

Certificate Generation

Utilities for generating CA certificates and managing TLS infrastructure.

/**
 * Generate a Certificate Authority (CA) certificate and private key.
 * Used for creating custom CAs for HTTPS interception and testing.
 */
function generateCACertificate(options?: CAOptions): Promise<{key: string, cert: string}>;

/**
 * Generate SPKI (Subject Public Key Info) fingerprint from a certificate.
 * Used for certificate pinning and verification in tests.
 */
function generateSPKIFingerprint(certPem: string): Promise<string>;

interface CAOptions {
  /**
   * Key length in bits for the generated private key.
   * Default: 2048
   */
  keyLength?: number;
  
  /**
   * Common Name (CN) for the certificate subject.
   * Default: "Mockttp CA"
   */
  commonName?: string;
  
  /**
   * Organization Name (O) for the certificate subject.
   * Default: "Mockttp"
   */
  organizationName?: string;
  
  /**
   * Country Name (C) for the certificate subject.
   * Default: "US"
   */
  countryName?: string;
  
  /**
   * Certificate validity period in days.
   * Default: 3650 (10 years)
   */
  validityDays?: number;
}

Usage Examples:

import { generateCACertificate, generateSPKIFingerprint, getLocal } from "mockttp";

// Generate a custom CA certificate
const ca = await generateCACertificate({
  keyLength: 4096,
  commonName: "Test CA",
  organizationName: "My Test Suite",
  countryName: "GB",
  validityDays: 365
});

console.log("CA Certificate:", ca.cert);
console.log("CA Private Key:", ca.key);

// Generate SPKI fingerprint for certificate pinning
const spkiFingerprint = await generateSPKIFingerprint(ca.cert);
console.log("SPKI Fingerprint:", spkiFingerprint);

// Use the generated CA with Mockttp
const mockServer = getLocal({
  https: {
    ca: ca.cert,
    key: ca.key
  }
});

await mockServer.start();

Certificate Configuration Types

Types for configuring certificate usage in Mockttp servers.

/**
 * Base type for PEM-formatted certificate data.
 */
type PEM = string;

/**
 * Certificate configuration using string/Buffer data.
 */
interface CertDataOptions {
  /**
   * CA certificate in PEM format for signing generated certificates.
   */
  ca?: string | Buffer;
  
  /**
   * Server certificate in PEM format.
   */
  cert?: string | Buffer;
  
  /**
   * Private key in PEM format corresponding to the certificate.
   */
  key?: string | Buffer;
}

/**
 * Certificate configuration using file paths.
 */
interface CertPathOptions {
  /**
   * Path to CA certificate file.
   */
  caPath?: string;
  
  /**
   * Path to server certificate file.
   */
  certPath?: string;
  
  /**
   * Path to private key file.
   */
  keyPath?: string;
}

/**
 * Combined certificate options (used in MockttpHttpsOptions).
 */
type CertificateOptions = CertDataOptions & CertPathOptions & {
  /**
   * Key length for auto-generated certificates.
   * Default: 2048
   */
  keyLength?: number;
};

HTTPS Configuration

Complete HTTPS configuration options for Mockttp servers.

interface MockttpHttpsOptions extends CertificateOptions {
  /**
   * Default domain name for TLS connections without SNI.
   * Used when clients don't specify a hostname via Server Name Indication.
   */
  defaultDomain?: string;
  
  /**
   * Hostnames to pass through without TLS interception.
   * These connections will be forwarded directly to the upstream server.
   * Wildcards are supported using URLPattern syntax: '*.example.com'
   */
  tlsPassthrough?: Array<{hostname: string}>;
  
  /**
   * Only intercept TLS for these hostnames, pass through all others.
   * Mutually exclusive with tlsPassthrough - setting both will throw an error.
   * Wildcards are supported using URLPattern syntax: '*.example.com'
   */
  tlsInterceptOnly?: Array<{hostname: string}>;
  
  /**
   * TLS server configuration options.
   */
  tlsServerOptions?: {
    /**
     * Minimum TLS version to accept.
     * Allows tightening or relaxing TLS requirements for testing.
     */
    minVersion?: 'TLSv1.3' | 'TLSv1.2' | 'TLSv1.1' | 'TLSv1';
  };
}

Usage Examples:

import { generateCACertificate, getLocal } from "mockttp";
import * as fs from "fs";

// Using generated certificates
const ca = await generateCACertificate({
  commonName: "Test CA",
  keyLength: 2048
});

const mockServer = getLocal({
  https: {
    ca: ca.cert,
    key: ca.key,
    defaultDomain: "localhost",
    tlsPassthrough: [
      { hostname: "*.googleapis.com" },
      { hostname: "secure-api.example.com" }
    ],
    tlsServerOptions: {
      minVersion: 'TLSv1.2'
    }
  }
});

// Using certificate files
const mockServerFromFiles = getLocal({
  https: {
    certPath: "/path/to/server.crt",
    keyPath: "/path/to/server.key",
    caPath: "/path/to/ca.crt"
  }
});

// Mixed configuration
const mockServerMixed = getLocal({
  https: {
    cert: fs.readFileSync("/path/to/server.crt"),
    key: fs.readFileSync("/path/to/server.key"),
    keyLength: 4096, // For any auto-generated certificates
    tlsInterceptOnly: [
      { hostname: "api.myapp.com" },
      { hostname: "*.internal.myapp.com" }
    ]
  }
});

Certificate Testing Patterns

Common patterns for testing with certificates:

Custom CA Testing: Generate a custom CA and configure clients to trust it Certificate Pinning: Use SPKI fingerprints to test certificate pinning implementations TLS Version Testing: Configure minimum TLS versions to test client compatibility SNI Testing: Test Server Name Indication handling with multiple hostnames Certificate Validation: Test client certificate validation with invalid or expired certificates

Example: Testing Certificate Pinning

import { generateCACertificate, generateSPKIFingerprint, getLocal } from "mockttp";

// Generate a test CA
const testCA = await generateCACertificate({
  commonName: "Test Certificate Pinning CA"
});

// Get the SPKI fingerprint for pinning
const expectedFingerprint = await generateSPKIFingerprint(testCA.cert);

// Set up mock server with the test CA
const mockServer = getLocal({
  https: {
    ca: testCA.cert,
    key: testCA.key
  }
});

await mockServer.start();

// Configure your HTTP client to expect the SPKI fingerprint
// and test that it properly validates certificate pins
console.log(`Configure client to pin: ${expectedFingerprint}`);

Example: Testing TLS Version Requirements

import { getLocal } from "mockttp";

// Server that only accepts TLS 1.3
const strictServer = getLocal({
  https: {
    keyLength: 2048,
    tlsServerOptions: {
      minVersion: 'TLSv1.3'
    }
  }
});

await strictServer.start();

// Test that older TLS clients are rejected
// while TLS 1.3 clients are accepted

Example: Selective TLS Interception

import { getLocal } from "mockttp";

// Only intercept specific domains, pass through everything else
const selectiveServer = getLocal({
  https: {
    keyLength: 2048,
    tlsInterceptOnly: [
      { hostname: "api.myapp.com" },
      { hostname: "*.test.myapp.com" }
    ]
  }
});

await selectiveServer.start();

// Requests to api.myapp.com and *.test.myapp.com will be intercepted
// All other HTTPS traffic will be passed through to real servers
await selectiveServer.forGet("https://api.myapp.com/test")
  .thenReply(200, "Mocked response");

// Requests to other domains like google.com will pass through unchanged

Certificate File Formats

Mockttp supports standard certificate file formats:

PEM Format: Text-based format with BEGIN/END markers, widely supported Certificate Files: .crt, .cer, .pem extensions commonly used Private Key Files: .key, .pem extensions commonly used CA Bundle Files: Multiple certificates concatenated in PEM format

All certificate data can be provided as strings, Buffers, or file paths. When using file paths, Mockttp will read the files at server startup time.

Certificate Security Notes

Testing Only: Generated certificates are intended for testing and development only Key Management: Keep private keys secure and don't commit them to version control CA Trust: Only install test CAs in test environments, never in production Certificate Validation: Always test both valid and invalid certificate scenarios Cleanup: Remove test CAs from system trust stores after testing

docs

certificate-management.md

event-monitoring.md

http-request-mocking.md

index.md

mock-server-setup.md

response-actions.md

websocket-mocking.md

tile.json