Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

1.1 KB
Raw Blame
import crypto from "crypto";

/**
 * Performs constant-time comparison of two strings to prevent timing attacks.
 *
 * This function compares two strings in a way that takes the same amount of time
 * regardless of where the strings differ, mitigating timing side-channel attacks
 * (CWE-208).
 *
 * Use this for comparing security-sensitive values like:
 * - Webhook signatures
 * - HMAC digests
 * - API keys
 * - Authentication tokens
 *
 * @param provided - The value provided by the client/request
 * @param expected - The expected/computed value
 * @returns true if the strings match, false otherwise
 */
export function timingSafeCompare(
  provided: string | null | undefined,
  expected: string,
): boolean {
  if (!provided) {
    return false;
  }

  const providedBuffer = Buffer.from(provided, "utf8");
  const expectedBuffer = Buffer.from(expected, "utf8");

  // Length check before constant-time comparison
  if (providedBuffer.length !== expectedBuffer.length) {
    return false;
  }

  return crypto.timingSafeEqual(
    Uint8Array.from(providedBuffer),
    Uint8Array.from(expectedBuffer),
  );
}