Skip to content

Commit 4ccc52d

Browse files
RiotRobott3chguy
andauthored
[Backport staging] Improve crypto init code and allow easier shimming (matrix-org#2792)
Co-authored-by: Michael Telatynski <[email protected]>
1 parent 63f4bf5 commit 4ccc52d

File tree

1 file changed

+21
-2
lines changed

1 file changed

+21
-2
lines changed

src/crypto/crypto.ts

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,18 +14,37 @@ See the License for the specific language governing permissions and
1414
limitations under the License.
1515
*/
1616

17+
import { logger } from "../logger";
18+
1719
export let crypto = global.window?.crypto;
1820
export let subtleCrypto = global.window?.crypto?.subtle ?? global.window?.crypto?.webkitSubtle;
1921
export let TextEncoder = global.window?.TextEncoder;
2022

2123
/* eslint-disable @typescript-eslint/no-var-requires */
2224
if (!crypto) {
23-
crypto = require("crypto").webcrypto;
25+
try {
26+
crypto = require("crypto").webcrypto;
27+
} catch (e) {
28+
logger.error("Failed to load webcrypto", e);
29+
}
2430
}
2531
if (!subtleCrypto) {
2632
subtleCrypto = crypto?.subtle;
2733
}
2834
if (!TextEncoder) {
29-
TextEncoder = require("util").TextEncoder;
35+
try {
36+
TextEncoder = require("util").TextEncoder;
37+
} catch (e) {
38+
logger.error("Failed to load TextEncoder util", e);
39+
}
3040
}
3141
/* eslint-enable @typescript-eslint/no-var-requires */
42+
43+
export function setCrypto(_crypto: Crypto): void {
44+
crypto = _crypto;
45+
subtleCrypto = _crypto.subtle ?? _crypto.webkitSubtle;
46+
}
47+
48+
export function setTextEncoder(_TextEncoder: typeof TextEncoder): void {
49+
TextEncoder = _TextEncoder;
50+
}

0 commit comments

Comments
 (0)