/
MainWorker.ts
194 lines (176 loc) · 4.51 KB
/
MainWorker.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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
import serializeError from 'serialize-error';
import { IArrayBufferViewWithPromise, parse, stringify } from './serializeBinary';
const SUBTLE_METHODS = [
'encrypt',
'decrypt',
'sign',
'verify',
'digest',
'generateKey',
'deriveKey',
'deriveBits',
'importKey',
'exportKey',
'wrapKey',
'unwrapKey',
];
/*
MainWorker provides a `crypto` attribute that proxies method calls
to the webview.
It sends strings to the webview in the format:
{
id: <id>,
method: getRandomValues | subtle.<method name>,
args: [<serialized arg>]
}
When the webview succeeds in completeing that method, it gets backs:
{
id: <id>,
value: <serialized return value>
}
And when it fails:
{
id: <id>,
reason: <serialized rejected reason>,
}
*/
export default class MainWorker {
get crypto(): Crypto {
const callMethod = this.callMethod;
return {
subtle: this.subtle,
getRandomValues: this.getRandomValues.bind(this),
fake: true,
} as any;
}
private get subtle(): SubtleCrypto {
const s: any = {};
for (const m of SUBTLE_METHODS) {
s[m] = (...args: any[]) => {
return this.callMethod(`subtle.${m}`, args, true);
};
}
return s as SubtleCrypto;
}
// http://stackoverflow.com/a/105074/907060
private static uuid() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return `${s4()}-${s4()}-${s4()}-${s4()}-${s4()}-${s4()}-${s4()}-${s4()}`;
}
// hold a queue of messages to send, in case someone calls crypto
// before the webview is initialized
private toSend: string[] = [];
private readyToSend = false;
// Holds the `resolve` and `reject` function for all the promises
// we are working on
private messages: {
[id: string]: {
resolve: (value: any) => void;
reject: (reason: any) => void;
};
} = {};
// sendToWebView should take a string and send that message to the webview
constructor(private sendToWebView: (message: string) => void, private debug = false) {}
onWebViewMessage(message: string): void {
// first message just tells us the webview is ready
if (!this.readyToSend) {
if (this.debug) {
console.log('[webview-crypto] Got first message; ready to send');
}
this.readyToSend = true;
for (const m of this.toSend) {
this.sendToWebView(m);
}
return;
}
parse(message)
.then(({ id, value, reason }) => {
if (this.debug) {
console.log(
'[webview-crypto] Received message:',
JSON.stringify({
id,
value,
reason,
}),
);
}
if (!id) {
console.warn(
'[webview-crypto] no ID passed back from message:',
JSON.stringify(serializeError(reason)),
);
return;
}
const { resolve, reject } = this.messages[id];
if (value) {
resolve(value);
} else {
reject(reason);
}
delete this.messages[id];
})
.catch((reason) => {
console.warn(
'[webview-crypto] error in `parse` of message:',
JSON.stringify(message),
'reason:',
JSON.stringify(serializeError(reason)),
);
});
}
private getRandomValues(array: IArrayBufferViewWithPromise): IArrayBufferViewWithPromise {
const promise = this.callMethod('getRandomValues', [array], false);
// make the _promise not enumerable so it isn't JSON stringified,
// which could lead to an infinite loop with Angular's zone promises
Object.defineProperty(array, '_promise', {
value: promise,
configurable: true,
enumerable: false,
writable: true,
});
promise.then((updatedArray: ArrayBufferView) => {
(array as any).set(updatedArray);
});
return array;
}
private callMethod(method: string, args: any[], waitForArrayBufferView: boolean): Promise<any> {
const id = MainWorker.uuid();
// store this promise, so we can resolve it when we get a message
// back from the web view
const promise = new Promise((resolve, reject) => {
this.messages[id] = { resolve, reject };
});
const payloadObject = { method, id, args };
if (this.debug) {
console.log(
'[webview-crypto] Sending message:',
JSON.stringify({
method,
args,
payloadObject,
}),
);
}
stringify(payloadObject, waitForArrayBufferView)
.then((message) => {
if (this.readyToSend) {
this.sendToWebView(message);
} else {
this.toSend.push(message);
}
})
.catch((reason) => {
this.messages[id].reject({
message: `exception in stringify-ing message: ${method} ${id}`,
reason,
});
delete this.messages[id];
});
return promise;
}
}