js-libp2p-crypto/src/webcrypto.js
Alan Shaw a5e05603ef
fix: better error for missing web crypto
This PR simply detects missing web crypto and throws an error with an appropriate message.

This is a stepping stone that will help users understand the problem until we have time to do a refactor of this module and of all the modules that use it to enable optionally passing your own crypto implementation.

refs https://github.com/libp2p/js-libp2p-crypto/pull/149
refs https://github.com/libp2p/js-libp2p-crypto/pull/150
refs https://github.com/libp2p/js-libp2p-crypto/issues/105
refs https://github.com/ipfs/js-ipfs/issues/2153
refs https://github.com/ipfs/js-ipfs/issues/2017

License: MIT
Signed-off-by: Alan Shaw <alan@tableflip.io>
2019-07-22 11:21:22 +01:00

25 lines
754 B
JavaScript

/* eslint-env browser */
'use strict'
// Check native crypto exists and is enabled (In insecure context `self.crypto`
// exists but `self.crypto.subtle` does not).
exports.get = (win = self) => {
const nativeCrypto = win.crypto || win.msCrypto
if (!nativeCrypto || !nativeCrypto.subtle) {
throw Object.assign(
new Error(
'Missing Web Crypto API. ' +
'The most likely cause of this error is that this page is being accessed ' +
'from an insecure context (i.e. not HTTPS). For more information and ' +
'possible resolutions see ' +
'https://github.com/libp2p/js-libp2p-crypto/blob/master/README.md#web-crypto-api'
),
{ code: 'ERR_MISSING_WEB_CRYPTO' }
)
}
return nativeCrypto
}