Debian Codegraph @

addons/web/static/lib/hoot/mock/crypto.js

raw
1 /** @odoo-module */
2
3 //-----------------------------------------------------------------------------
4 // Global
5 //-----------------------------------------------------------------------------
6
7 const {
8 Math: { random: $random, floor: $floor },
9 TextEncoder,
10 } = globalThis;
11
12 //-----------------------------------------------------------------------------
13 // Internal
14 //-----------------------------------------------------------------------------
15
16 /** @type {SubtleCrypto["decrypt"]} */
17 function decrypt(algorithm, key, data) {
18 return Promise.resolve($encode(data.replace("encrypted data:", "")));
19 }
20
21 /** @type {SubtleCrypto["encrypt"]} */
22 function encrypt(algorithm, key, data) {
23 return Promise.resolve(`encrypted data:${$decode(data)}`);
24 }
25
26 /** @type {Crypto["getRandomValues"]} */
27 function getRandomValues(array) {
28 for (let i = 0; i < array.length; i++) {
29 array[i] = $floor($random() * 256);
30 }
31 return array;
32 }
33
34 /** @type {SubtleCrypto["importKey"]} */
35 function importKey(format, keyData, algorithm, extractable, keyUsages) {
36 if (arguments.length < 5) {
37 throw new TypeError(
38 `Failed to execute 'importKey' on 'SubtleCrypto': 5 arguments required, but only ${arguments.length} present.`
39 );
40 }
41 if (!keyData || keyData.length === 0) {
42 throw new TypeError(
43 `Failed to execute 'importKey' on 'SubtleCrypto': The provided value cannot be converted to a sequence.`
44 );
45 }
46 const key = Symbol([algorithm, String(extractable), "secret", ...keyUsages].join("/"));
47 return Promise.resolve(key);
48 }
49
50 function randomUUID() {
51 return [4, 2, 2, 2, 6]
52 .map((length) => getRandomValues(new Uint8Array(length)).toHex())
53 .join("-");
54 }
55
56 const $encode = TextEncoder.prototype.encode.bind(new TextEncoder());
57 const $decode = TextDecoder.prototype.decode.bind(new TextDecoder("utf-8"));
58
59 //-----------------------------------------------------------------------------
60 // Exports
61 //-----------------------------------------------------------------------------
62
63 export const mockCrypto = {
64 getRandomValues,
65 randomUUID,
66 subtle: {
67 decrypt,
68 encrypt,
69 importKey,
70 },
71 };