All files / src/encryption cryptoUtils.ts

78.26% Statements 18/23
70% Branches 7/10
100% Functions 3/3
78.26% Lines 18/23

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70  1x 120x           1x     151x 151x 151x       151x 151x     151x 151x 151x               1x                                   1x 120x 4x         116x     116x 116x                  
 
export function isSubtleCryptoAvailable(): boolean {
  return typeof crypto !== 'undefined' && typeof crypto.subtle !== 'undefined'
}
 
export function isNodeCryptoAvailable<T>(
  withFeature: (nodeCrypto: typeof import('crypto')) => boolean | T
): false | T
export function isNodeCryptoAvailable<T>(
  withFeature?: (nodeCrypto: typeof import('crypto')) => boolean | T
): boolean | T {
  try {
    const resolvedResult = require.resolve('crypto')
    Iif (!resolvedResult) {
      return false
    }
    // eslint-disable-next-line import/no-nodejs-modules,no-restricted-modules,global-require
    const cryptoModule = require('crypto') as typeof import('crypto')
    Iif (!cryptoModule) {
      return false
    }
    Eif (withFeature) {
      const features = withFeature(cryptoModule)
      return features
    }
    return true
  } catch (error) {
    return false
  }
}
 
export const NO_CRYPTO_LIB = 'Crypto lib not found. Either the WebCrypto "crypto.subtle" or Node.js "crypto" module must be available.'
 
export type TriplesecDecryptSignature =  (
  arg: { data: Buffer; key: Buffer }, cb: (err: Error | null, buff: Buffer | null) => void
) => void
 
export interface WebCryptoLib {
  lib: SubtleCrypto;
  name: 'subtleCrypto'
}
 
export interface NodeCryptoLib {
  lib: typeof import('crypto');
  name: 'nodeCrypto'
}
 
// Make async for future version which may lazy load.
// eslint-disable-next-line @typescript-eslint/require-await
export async function getCryptoLib(): Promise<WebCryptoLib | NodeCryptoLib> {
  if (isSubtleCryptoAvailable()) {
    return {
      lib: crypto.subtle,
      name: 'subtleCrypto'
    }
  } else {
    try {
      // eslint-disable-next-line max-len
      // eslint-disable-next-line import/no-nodejs-modules,no-restricted-modules,global-require,@typescript-eslint/no-var-requires
      const nodeCrypto = require('crypto') as typeof import('crypto')
      return {
        lib: nodeCrypto,
        name: 'nodeCrypto'
      }
    } catch (error) {
      throw new Error(NO_CRYPTO_LIB)
    }
  }
}