async function getWebCryptoBackend()

in modules/web-crypto-backend/src/backend-factory.ts [34:79]


  async function getWebCryptoBackend(): Promise<WebCryptoBackend> {
    /* Precondition: Access to a secure random source is required. */
    try {
      randomValues(1)
    } catch (ex) {
      throw new Error('No supported secure random')
    }

    const fallbackRequired = await fallbackRequiredPromise
    const subtle = pluckSubtleCrypto(window)
    const webCryptoFallback = await webCryptoFallbackPromise

    /* Postcondition: If a a subtle backend exists and a fallback is required, one must be configured.
     * In this case the subtle backend does not support zero byte GCM operations.
     */
    if (subtle && fallbackRequired && !webCryptoFallback) {
      throw new Error(
        'A Fallback is required for zero byte AES-GCM operations.'
      )
    }

    /* Postcondition: If no SubtleCrypto exists, a fallback must configured. */
    if (!subtle && !webCryptoFallback) {
      throw new Error(
        'A Fallback is required because no subtle backend exists.'
      )
    }

    if (!fallbackRequired && subtle) {
      return { subtle, randomValues }
    }

    if (fallbackRequired && subtle && webCryptoFallback) {
      return {
        nonZeroByteSubtle: subtle,
        randomValues,
        zeroByteSubtle: webCryptoFallback,
      }
    }

    if (fallbackRequired && !subtle && webCryptoFallback) {
      return { subtle: webCryptoFallback, randomValues }
    }

    throw new Error('unknown error')
  }