/
index.test.js
48 lines (39 loc) · 1.34 KB
/
index.test.js
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
import { Encoder, UnsafeDecoder } from '.';
test('sample usage', () => {
// Sample object
const counter = {
current: 1,
increment() {
this.current += 1;
},
};
counter.increment();
expect(counter.current).toEqual(2);
// Encoding
const encoder = new Encoder();
const encoded = encoder.encode(counter);
expect(encoded).toMatchSnapshot();
// The encoded object can be serialized and deserialized to JSON if desired
const serialized = JSON.stringify(encoded);
const deserialized = JSON.parse(serialized);
// Decoding (this could be run in a different VM)
const decoder = new UnsafeDecoder();
const decoded = decoder.decode(deserialized);
expect(decoded.current).toEqual(2);
decoded.increment();
expect(decoded.current).toEqual(3);
});
test('one of the reasons UnsafeDecoder is unsafe', () => {
expect(Object.EVIL_THING_HAPPENED).toBeUndefined();
const maliciousInput = {
type: 'function',
id: '1',
// Normally, a function's source would start with something like
// function(). Because this doesn't, the malicious code gets executed
// as soon as we try to decode the input, even if we never try
// to call the decoded function.
source: 'Object.EVIL_THING_HAPPENED = true',
};
new UnsafeDecoder().decode(maliciousInput);
expect(Object.EVIL_THING_HAPPENED).toBeTruthy();
});