diff --git a/src/infra/secure-random.test.ts b/src/infra/secure-random.test.ts index 96f08252de4..6b2ea728ebd 100644 --- a/src/infra/secure-random.test.ts +++ b/src/infra/secure-random.test.ts @@ -1,20 +1,43 @@ -import { describe, expect, it } from "vitest"; +import { Buffer } from "node:buffer"; +import { describe, expect, it, vi } from "vitest"; + +const cryptoMocks = vi.hoisted(() => ({ + randomBytes: vi.fn((bytes: number) => Buffer.alloc(bytes, 0xab)), + randomUUID: vi.fn(), +})); + +vi.mock("node:crypto", () => ({ + randomBytes: cryptoMocks.randomBytes, + randomUUID: cryptoMocks.randomUUID, +})); + import { generateSecureToken, generateSecureUuid } from "./secure-random.js"; describe("secure-random", () => { - it("generates UUIDs", () => { - const first = generateSecureUuid(); - const second = generateSecureUuid(); - expect(first).not.toBe(second); - expect(first).toMatch( - /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i, - ); + it("delegates UUID generation to crypto.randomUUID", () => { + cryptoMocks.randomUUID.mockReturnValueOnce("uuid-1").mockReturnValueOnce("uuid-2"); + + expect(generateSecureUuid()).toBe("uuid-1"); + expect(generateSecureUuid()).toBe("uuid-2"); + expect(cryptoMocks.randomUUID).toHaveBeenCalledTimes(2); }); - it("generates url-safe tokens", () => { + it("generates url-safe tokens with the default byte count", () => { + cryptoMocks.randomBytes.mockClear(); + const defaultToken = generateSecureToken(); - const token18 = generateSecureToken(18); + + expect(cryptoMocks.randomBytes).toHaveBeenCalledWith(16); expect(defaultToken).toMatch(/^[A-Za-z0-9_-]+$/); - expect(token18).toMatch(/^[A-Za-z0-9_-]{24}$/); + expect(defaultToken).toHaveLength(Buffer.alloc(16, 0xab).toString("base64url").length); + }); + + it("passes custom byte counts through to crypto.randomBytes", () => { + cryptoMocks.randomBytes.mockClear(); + + const token18 = generateSecureToken(18); + + expect(cryptoMocks.randomBytes).toHaveBeenCalledWith(18); + expect(token18).toBe(Buffer.alloc(18, 0xab).toString("base64url")); }); });