CSRF-X Auth Library - v1.0.3
    Preparing search index...

    Class AuthClient

    Client for automating login against CSRF‑protected web applications.

    The client performs a two‑step login process:

    1. GET the login page to extract a CSRF token and capture any initial cookies.
    2. POST the credentials together with the CSRF token to authenticate.

    After successful login, the session (cookies, CSRF token, timestamp) is saved
    to disk. Subsequent calls can reuse the cached session without re‑authenticating.

    The client is configurable via environment variables (.env file) or constructor
    options. It supports retries with exponential backoff, timeouts, and optional
    Referer/Origin headers for servers that require them.

    Session caching:

    • Cache location: ~/.cache/libts-csrfx-auth/session.json (configurable)
    • Session freshness: 1 hour by default (see hasValidSession)
    • Use clearSession to remove cached credentials.
    // Basic usage with environment variables
    const auth = new AuthClient();
    const session = await auth.login();
    console.log('Logged in, CSRF token:', session.csrfToken);
    // Override credentials and use custom cache directory
    const auth = new AuthClient({
    email: 'user@example.com',
    password: 'secret',
    cacheDir: './my-cache'
    });
    // Check cached session before logging in
    if (await auth.hasValidSession()) {
    const session = await auth.getCachedSession();
    // use session...
    } else {
    await auth.login();
    }

    @public

    0.1.1

    Index

    Accessors

    • get cacheFilePath(): string

      Returns the filesystem path where the session cache is stored.

      Returns string

      Useful for debugging or manual inspection. Example:
      "/home/user/.cache/libts-csrfx-auth/session.json"

    • get configRef(): EnvConfig

      Returns the internal EnvConfig instance for advanced inspection.

      Returns EnvConfig

      Provides access to the normalized configuration, including base URL,
      login path, email, and password (if set).

    Constructors

    • Creates a new AuthClient instance.

      Parameters

      • options: LoginOptions = {}

        Optional overrides for environment‑based configuration.

      Returns AuthClient

      Configuration is resolved from constructor options first, then from environment
      variables (.env file or Bun.env). The client is ready to use immediately.
      No network requests are performed during construction.

      // Using environment variables only
      const auth = new AuthClient();
      // Overriding email and password
      const auth = new AuthClient({
      email: 'custom@example.com',
      password: 'override123'
      });

    Methods

    • Performs the complete login flow and returns the session data.

      Returns Promise<SessionData>

      The persisted session data (cookies, CSRF token, login flag, timestamp).

      With code INVALID_CREDENTIALS if email or password is missing.

      With code CSRF_NOT_FOUND if CSRF token cannot be extracted.

      With code CSRF_FETCH_FAILED if the login page request fails.

      With code CSRF_EXPIRED on HTTP 419.

      With code VALIDATION_ERROR on HTTP 422 (invalid credentials).

      With code TOO_MANY_REQUESTS on HTTP 429.

      With code SERVER_ERROR on HTTP 5xx.

      With code LOGIN_FAILED for other non‑2xx responses.

      Steps:

      • Validates that credentials are present (throws INVALID_CREDENTIALS if missing).
      • Fetches the login page (GET) to obtain a CSRF token and any initial cookies.
      • Builds a POST request with _token, email, and password.
      • Submits the request with cookies from both the cookie jar and cached session.
      • Validates the response (throws appropriate AuthError on failure).
      • Saves the resulting session (cookies, token) to disk cache.

      The method uses retries with exponential backoff for transient failures.

      const session = await auth.login();
      console.log(`Logged in at ${new Date(session.timestamp)}`);
      console.log(`CSRF token: ${session.csrfToken}`);
    • Retrieves the cached session from disk without checking freshness.

      Returns Promise<SessionData | null>

      The stored session, or null if no session exists or the file is corrupted.

      This method does not validate the age of the session or the loggedIn flag.
      Use hasValidSession for freshness and validity checks.

      const session = await auth.getCachedSession();
      if (session) console.log('Session exists, timestamp:', session.timestamp);
    • Checks whether a valid (fresh and logged‑in) session exists in the cache.

      Parameters

      • maxAgeMs: number = 3_600_000

        Maximum allowed age in milliseconds.

      Returns Promise<boolean>

      true if a cached session exists, is fresh, and loggedIn is true.

      maxAgeMs = 3_600_000 (1 hour)
      

      A session is considered valid if:

      • It exists on disk.
      • Its loggedIn property is true.
      • Its age (Date.now() - session.timestamp) is less than maxAgeMs.

      This method does not contact the server to verify the session.

      if (await auth.hasValidSession()) {
      // reuse session without logging in again
      const session = await auth.getCachedSession();
      } else {
      await auth.login();
      }
    • Clears both the in‑memory cookie jar and the persistent session cache.

      Returns Promise<void>

      Use this method to completely remove any stored authentication state.
      After clearing, the next call to login will start a fresh login flow.

      await auth.clearSession();
      // The next call to `login()` will start fresh.

    Properties

    config: EnvConfig

    Validated configuration object (base URL, paths, credentials).

    Contains normalized and validated values from environment variables
    and constructor overrides. Read‑only after construction.

    cacheManager: CacheManager

    Disk cache manager for persisting session data.

    Handles saving, loading, and clearing session data from the file system.
    The cache file path can be obtained via cacheFilePath.