CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-node-forge

JavaScript implementations of network transports, cryptography, ciphers, PKI, message digests, and various utilities.

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

network-http.mddocs/

Network and HTTP Client

HTTP client implementation with TLS support, cookie management, and XMLHttpRequest interface. This module provides secure HTTP communications using forge's TLS implementation and flash-based socket pooling for cross-browser compatibility.

Note: This module is primarily designed for browser environments and requires Flash plugin support for full functionality.

Capabilities

XMLHttpRequest Interface

Standards-compliant XMLHttpRequest implementation using TLS and forge networking.

/**
 * Initialize the XHR system with configuration options
 * @param options - Configuration object for XHR initialization
 */
forge.xhr.init(options: {
  url?: string;              // Default base URL for relative requests
  flashId: string;           // DOM ID of the flash SocketPool element
  policyPort?: number;       // Port for flash policy server (default: 0)
  policyUrl?: string;        // Policy file URL instead of policy port
  msie?: boolean;            // True if browser is Internet Explorer
  connections?: number;      // Maximum concurrent connections (default: 10)
  caCerts?: string[];        // Array of PEM-formatted CA certificates
  cipherSuites?: object[];   // TLS cipher suites to use
  verify?: function;         // TLS certificate verification callback
  getCertificate?: function; // Client certificate callback
  getPrivateKey?: function;  // Client private key callback
  getSignature?: function;   // Client signature callback
  persistCookies?: boolean;  // Use persistent cookies via flash storage
  primeTlsSockets?: boolean; // Pre-connect TLS sockets for session caching
}): void;

/**
 * Create a new XMLHttpRequest instance
 * @param options - Optional configuration for this specific XHR
 * @returns XMLHttpRequest-compatible object
 */
forge.xhr.create(options?: {
  logWarningOnError?: boolean;  // Log warnings on HTTP errors
  verbose?: boolean;            // Verbose logging output
  logError?: function;          // Custom error logging function
  logWarning?: function;        // Custom warning logging function
  logDebug?: function;          // Custom debug logging function
  logVerbose?: function;        // Custom verbose logging function
  url?: string;                 // Base URL for this XHR (creates new client)
  policyPort?: number;          // Policy port for new client
  policyUrl?: string;           // Policy URL for new client
  connections?: number;         // Max connections for new client
  caCerts?: string[];           // CA certificates for new client
  cipherSuites?: object[];      // Cipher suites for new client
  verify?: function;            // Certificate verification for new client
  getCertificate?: function;    // Client certificate for new client
  getPrivateKey?: function;     // Client private key for new client
  getSignature?: function;      // Client signature for new client
  persistCookies?: boolean;     // Cookie persistence for new client
  primeTlsSockets?: boolean;    // Socket priming for new client
}): XMLHttpRequest;

/**
 * Clean up clients and socket pools
 */
forge.xhr.cleanup(): void;

interface XMLHttpRequest {
  // Standard XMLHttpRequest properties
  onreadystatechange: (() => void) | null;
  readyState: number;           // UNSENT=0, OPENED=1, HEADERS_RECEIVED=2, LOADING=3, DONE=4
  responseText: string;
  responseXML: Document | null;
  status: number;
  statusText: string;
  cookies?: object;             // Available cookies (forge extension)
  
  // Standard XMLHttpRequest methods
  open(method: string, url: string, async?: boolean, user?: string, password?: string): void;
  setRequestHeader(header: string, value: string): void;
  send(data?: string | Document): void;
  abort(): void;
  getAllResponseHeaders(): string;
  getResponseHeader(header: string): string | null;
}

HTTP Client

Lower-level HTTP client with TLS support and connection pooling.

/**
 * Create an HTTP client with TLS support
 * @param options - Client configuration options
 * @returns HTTP client instance
 */
forge.http.createClient(options: {
  url: string;                  // Base URL for the client
  socketPool: object;           // Socket pool instance
  policyPort?: number;          // Flash policy port
  policyUrl?: string;           // Flash policy URL
  connections?: number;         // Maximum concurrent connections
  caCerts?: string[];           // PEM-formatted CA certificates
  cipherSuites?: object[];      // TLS cipher suites
  persistCookies?: boolean;     // Enable persistent cookies
  primeTlsSockets?: boolean;    // Prime TLS sockets for performance
  verify?: function;            // Certificate verification callback
  getCertificate?: function;    // Client certificate callback
  getPrivateKey?: function;     // Client private key callback
  getSignature?: function;      // Client signature callback
}): HTTPClient;

interface HTTPClient {
  url: URL;                     // Client base URL
  secure: boolean;              // Whether client uses HTTPS
  
  send(options: {
    request: HTTPRequest;
    headerReady?: (event: object) => void;
    bodyReady?: (event: object) => void;
    error?: (event: object) => void;
  }): void;
  
  setCookie(cookie: Cookie): void;
  getCookie(name: string, path?: string): Cookie | null;
  removeCookie(name: string, path?: string): boolean;
  destroy(): void;
}

Cookie Management

Global cookie management functions for cross-domain scenarios.

/**
 * Set a cookie that applies to appropriate client domains
 * @param cookie - Cookie object with properties
 */
forge.xhr.setCookie(cookie: {
  name: string;        // Cookie name
  value: string;       // Cookie value
  comment?: string;    // Optional comment
  maxAge?: number;     // Age in seconds (-1 for session cookie)
  secure?: boolean;    // Require secure connection
  httpOnly?: boolean;  // Restrict to HTTP (ineffective in JavaScript)
  path?: string;       // Cookie path
  domain?: string;     // Cookie domain (must start with dot)
  version?: string;    // Cookie version
  created?: number;    // Creation time in UTC seconds
}): void;

/**
 * Get a cookie by name, path, and domain
 * @param name - Cookie name
 * @param path - Optional cookie path
 * @param domain - Optional cookie domain
 * @returns Cookie object, array of cookies, or null
 */
forge.xhr.getCookie(name: string, path?: string, domain?: string): Cookie | Cookie[] | null;

/**
 * Remove a cookie by name, path, and domain
 * @param name - Cookie name
 * @param path - Optional cookie path
 * @param domain - Optional cookie domain
 * @returns true if cookie was removed
 */
forge.xhr.removeCookie(name: string, path?: string, domain?: string): boolean;

interface Cookie {
  name: string;
  value: string;
  comment?: string;
  maxAge: number;
  secure: boolean;
  httpOnly: boolean;
  path: string;
  domain?: string;
  version?: string;
  created: number;
}

Usage Examples

Basic XMLHttpRequest Usage

// Initialize the XHR system
forge.xhr.init({
  url: 'https://api.example.com',
  flashId: 'socketPool',
  caCerts: [/* PEM certificates */],
  connections: 5
});

// Create and use an XMLHttpRequest
const xhr = forge.xhr.create();
xhr.onreadystatechange = function() {
  if (xhr.readyState === 4) {
    if (xhr.status === 200) {
      console.log('Response:', xhr.responseText);
    } else {
      console.error('Error:', xhr.status, xhr.statusText);
    }
  }
};

xhr.open('GET', '/api/data');
xhr.setRequestHeader('Accept', 'application/json');
xhr.send();

Advanced Configuration

// Initialize with custom TLS settings
forge.xhr.init({
  url: 'https://secure.example.com',
  flashId: 'secureSocketPool',
  caCerts: [
    '-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----'
  ],
  cipherSuites: [
    forge.tls.CipherSuites.TLS_RSA_WITH_AES_128_CBC_SHA,
    forge.tls.CipherSuites.TLS_RSA_WITH_AES_256_CBC_SHA
  ],
  verify: function(connection, verified, depth, certs) {
    // Custom certificate verification
    return verified;
  },
  persistCookies: true,
  primeTlsSockets: true
});

// Create XHR with custom logging
const xhr = forge.xhr.create({
  verbose: true,
  logWarningOnError: true,
  logDebug: function(category, message) {
    console.log(`[${category}] ${message}`);
  }
});

Cookie Management

// Set a cookie for all applicable domains
forge.xhr.setCookie({
  name: 'sessionId',
  value: 'abc123',
  maxAge: 3600,        // 1 hour
  secure: true,
  path: '/',
  domain: '.example.com'
});

// Get a specific cookie
const sessionCookie = forge.xhr.getCookie('sessionId', '/', '.example.com');
if (sessionCookie) {
  console.log('Session ID:', sessionCookie.value);
}

// Remove a cookie
const removed = forge.xhr.removeCookie('sessionId', '/', '.example.com');
console.log('Cookie removed:', removed);

Cross-Domain Requests

// Create XHR for a different domain
const crossDomainXhr = forge.xhr.create({
  url: 'https://api.partner.com',
  caCerts: [/* Partner's CA certificates */],
  verify: function(connection, verified, depth, certs) {
    // Verify partner's certificates
    return verifyPartnerCert(certs[0]);
  }
});

crossDomainXhr.open('POST', '/api/partner-data');
crossDomainXhr.setRequestHeader('Content-Type', 'application/json');
crossDomainXhr.send(JSON.stringify({ data: 'value' }));

Security Considerations

  1. Certificate Validation: Always implement proper certificate verification callbacks
  2. Flash Dependency: Requires Flash plugin for socket operations
  3. Cookie Security: Use secure flags and appropriate domains for sensitive cookies
  4. TLS Configuration: Choose strong cipher suites and avoid deprecated protocols
  5. Cross-Domain: Validate policy files and implement proper CORS handling

Browser Support

  • Flash Plugin: Required for socket pool functionality
  • TLS Support: Uses forge's JavaScript TLS implementation
  • Cookie Storage: Supports both JavaScript and Flash local storage
  • CORS: Handles cross-domain requests through flash policy files

docs

asn1.md

asymmetric-cryptography.md

index.md

logging.md

message-digests.md

network-http.md

pkcs.md

pki.md

random.md

symmetric-encryption.md

tls.md

utilities.md

web-forms.md

tile.json