|
| 1 | +import { describe, expect, it } from "vitest"; |
| 2 | +import { timingSafeEqual } from "../utils/crypto"; |
| 3 | + |
| 4 | +describe("timingSafeEqual", () => { |
| 5 | + it("returns true for identical strings", () => { |
| 6 | + expect(timingSafeEqual("abc", "abc")).toBe(true); |
| 7 | + }); |
| 8 | + |
| 9 | + it("returns false for same-length but different strings", () => { |
| 10 | + expect(timingSafeEqual("abc", "abd")).toBe(false); |
| 11 | + }); |
| 12 | + |
| 13 | + it("returns false for different-length strings", () => { |
| 14 | + expect(timingSafeEqual("abc", "abcd")).toBe(false); |
| 15 | + }); |
| 16 | + |
| 17 | + it("returns false for empty vs non-empty", () => { |
| 18 | + expect(timingSafeEqual("", "a")).toBe(false); |
| 19 | + }); |
| 20 | + |
| 21 | + it("returns true for two empty strings", () => { |
| 22 | + expect(timingSafeEqual("", "")).toBe(true); |
| 23 | + }); |
| 24 | + |
| 25 | + it("executes in constant time within ±200% CV (JS timing resolution limit)", () => { |
| 26 | + const token = "a".repeat(64); |
| 27 | + const correct = "a".repeat(64); |
| 28 | + const wrong = "b".repeat(64); |
| 29 | + |
| 30 | + for (let i = 0; i < 100; i++) { |
| 31 | + timingSafeEqual(token, correct); |
| 32 | + timingSafeEqual(token, wrong); |
| 33 | + } |
| 34 | + |
| 35 | + const correctTimes: number[] = []; |
| 36 | + const wrongTimes: number[] = []; |
| 37 | + |
| 38 | + for (let i = 0; i < 1000; i++) { |
| 39 | + const t1 = performance.now(); |
| 40 | + timingSafeEqual(token, correct); |
| 41 | + correctTimes.push(performance.now() - t1); |
| 42 | + |
| 43 | + const t2 = performance.now(); |
| 44 | + timingSafeEqual(token, wrong); |
| 45 | + wrongTimes.push(performance.now() - t2); |
| 46 | + } |
| 47 | + |
| 48 | + const mean = (arr: number[]) => arr.reduce((a, b) => a + b, 0) / arr.length; |
| 49 | + const correctMean = mean(correctTimes); |
| 50 | + const wrongMean = mean(wrongTimes); |
| 51 | + |
| 52 | + // The means should be within 2x of each other — proves no short-circuit |
| 53 | + const ratio = Math.max(correctMean, wrongMean) / Math.min(correctMean, wrongMean); |
| 54 | + expect(ratio).toBeLessThan(2); |
| 55 | + }); |
| 56 | +}); |
0 commit comments