-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
universal-crypto.ts
34 lines (30 loc) · 1.07 KB
/
universal-crypto.ts
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
import type { createCipheriv, createDecipheriv } from 'crypto';
type UniversalCrypto = {
getRandomValues: (length: number) => Uint8Array;
randomBytes: (length: number) => Uint8Array;
subtle: SubtleCrypto;
createCipheriv: typeof createCipheriv;
createDecipheriv: typeof createDecipheriv;
};
let selectedCrypto;
let selectedStrategy: 'Node' | 'Web' = 'Node';
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
if (typeof globalThis !== 'undefined' && globalThis.crypto) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
selectedCrypto = globalThis.crypto;
selectedStrategy = 'Web';
}
if (!selectedCrypto && typeof require === 'function') {
try {
// eslint-disable-next-line global-require
selectedCrypto = require('crypto');
selectedStrategy = 'Node';
} catch (error) {
// eslint-disable-next-line no-console
console.error('keystore expects a standard Web browser or Node environment.', error);
}
}
export const crypto: UniversalCrypto = selectedCrypto;
export const strategy = selectedStrategy;