verygoodsecurity / collect-js-react

MIT License
1 stars 15 forks source link

window.crypto.randomUUID is undefined #47

Open marcincodes opened 3 months ago

marcincodes commented 3 months ago

Expected Behavior

Fields should fallback to other solution when window.crypto.randomUUID() is not available

Current Behavior

window.crypto.randomUUID is undefined

Possible Solution

Write a fallback to react useId if it's available or getRandomValues() to generate uuid like id

function generateUUID() {
  // Check if crypto.randomUUID() is supported
  if (typeof crypto.randomUUID === "function") {
    return crypto.randomUUID();
  } else if (typeof React !== "undefined" && typeof React.useId === "function") {
    // Fallback to React.useId, but keep in mind this might not generate a proper UUID
    const id = React.useId();
    return id; // Return the ID as-is since React.useId doesn't guarantee a UUID format
  } else {
    // Fallback to crypto.getRandomValues()
    // Generate an array of 16 random bytes
    const buffer = new Uint8Array(16);
    window.crypto.getRandomValues(buffer);

    // Convert the byte array to a hexadecimal string
    let uuid = '';
    for (let i = 0; i < buffer.length; i++) {
      uuid += ('00' + buffer[i].toString(16)).slice(-2); // Pad with zeros
    }

    // Replace dashes to mimic UUID v4 format
    uuid = uuid.replace(/-/g, '').replace(/\b(.{6})(.{4})(.{4})(.{12})\b/, '$1-$2-$3-$4');
    return uuid;
  }
}

Source: https://www.phind.com/search?cache=u11vgs2u05g6gdllheburzal

It will be even better to use useId from react and fallback to other solutions

Steps to Reproduce (for bugs)

  1. Use one of the browser that doesn't support randomUUID(). Here is a list: https://caniuse.com/?search=randomUUID

Context

crypto.randomUUID() is relatively new, it was introduced 3 years ago and projects that have users with <iOS 15.3 encounter this problem. Workaround for now is to patch collect-js-react package

Your Environment

AnnaKudriasheva commented 3 months ago

Hi, @marcincodes! Thank you for reaching out, we'll prioritize and fix the issue by the end of the month. We'll let you know once it's ready!

flor-master commented 3 months ago

Hi @marcincodes you are right iOS 15.3 and less - don't support crypto.randomUUID() from the box we released a new version 1.2.0 and replace .randomUUID()

marcincodes commented 3 months ago

Hi, thanks for quick fix! We are testing right now new version, I'll keep you updated