Skip to content

fix(randId): replace Math.random with crypto.getRandomValues and deterministic tests#1297

Draft
danditomaso with Copilot wants to merge 3 commits into
mainfrom
copilot/fix-review-comment-3567066678
Draft

fix(randId): replace Math.random with crypto.getRandomValues and deterministic tests#1297
danditomaso with Copilot wants to merge 3 commits into
mainfrom
copilot/fix-review-comment-3567066678

Conversation

Copilot AI commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

Description

randId used Math.random (not cryptographically random, limited to [0, 1e9)). The uniqueness test drew 1000 samples from a 32-bit space and asserted zero collisions — probabilistically sound but nondeterministic (birthday bound).

Related Issues

Changes Made

  • randId.ts: Replaced Math.floor(Math.random() * 1e9) with crypto.getRandomValues(new Uint32Array(1)) — full uint32 range, cryptographically secure
  • randId.test.ts: Stubbed crypto.getRandomValues with a monotonic counter for the uniqueness test, making expect(results.size).toBe(1000) fully deterministic; added spy assertion that the implementation calls crypto.getRandomValues
// Before
export const randId = () => Math.floor(Math.random() * 1e9);

// After
export const randId = (): number => {
  const buf = new Uint32Array(1);
  crypto.getRandomValues(buf);
  return buf[0];
};
// Uniqueness test — now deterministic
it("returns unique values across many calls", () => {
  let counter = 0;
  vi.spyOn(crypto, "getRandomValues").mockImplementation((array) => {
    if (array instanceof Uint32Array) array[0] = counter++;
    return array;
  });
  const results = new Set<number>();
  for (let i = 0; i < 1000; i++) results.add(randId());
  expect(results.size).toBe(1000);
});

Testing Done

Updated tests stub crypto.getRandomValues via vi.spyOn, removing all probabilistic assertions.

Screenshots (if applicable)

Checklist

  • Code follows project style guidelines
  • Documentation has been updated or added
  • Tests have been added or updated
  • All i18n translation labels have been added (read
    CONTRIBUTING_I18N_DEVELOPER_GUIDE.md for more details)

@vercel

vercel Bot commented Jul 14, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
web-test Ready Ready Preview, Comment Jul 17, 2026 1:37am

Request Review

Copilot AI changed the title [WIP] Fix code based on review comment 3567066678 fix(randId): replace Math.random with crypto.getRandomValues and deterministic tests Jul 14, 2026
Copilot AI requested a review from danditomaso July 14, 2026 01:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants