-
Notifications
You must be signed in to change notification settings - Fork 8
/
comm.js
58 lines (52 loc) · 1.37 KB
/
comm.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
49
50
51
52
53
54
55
56
57
58
/**
* Desktop <--> extension communication module
*/
ext.comm = {
send: function(cmd, data, options)
{
options || (options = {});
var req = new XMLHttpRequest();
req.onload = function() {
var res = this.responseText;
try {
var obj = JSON.parse(res);
} catch(e) {
if(options.error) options.error('comm: error parsing json: '+ res);
return;
}
if(obj.error) {
if(options.error) options.error(obj.error, obj.code);
} else {
if(options.success) options.success(obj);
}
};
req.onerror = function() {
// signal a timeout
if(options.error) options.error(null, -1);
};
data = ext.comm.process(cmd, data, options.pubkey);
var url = 'http://127.0.0.1:7471/'+cmd+'?data='+encodeURIComponent(data);
req.open('get', url, true);
req.send();
},
/**
* process the data we're sending. if we're doing a simple pair request,
* just JSON encode it.
*
* for any other outgoing request, we're going to encrypt the data via the
* public key the desktop app sent us.
*/
process: function(cmd, data, optional_pubkey)
{
var str = JSON.stringify(data);
if(cmd == 'pair') return str;
if(optional_pubkey) {
var key = sjcl.codec.hex.toBits(optional_pubkey);
} else {
var key = ext.pairing.get_key({binary: true});
}
if(!key) return false;
data = tcrypt.asym.encrypt(key, str);
return tcrypt.to_base64(data);
}
};