send/frontend/src/fileReceiver.js

91 lines
2.3 KiB
JavaScript
Raw Normal View History

2017-06-02 19:38:05 +00:00
const EventEmitter = require('events');
2017-06-28 18:30:14 +00:00
const { hexToArray } = require('./utils');
2017-06-02 19:38:05 +00:00
class FileReceiver extends EventEmitter {
constructor() {
super();
}
download() {
return window.crypto.subtle
.importKey(
'jwk',
{
kty: 'oct',
k: location.hash.slice(1),
2017-06-28 18:30:14 +00:00
alg: 'A128GCM',
ext: true
},
{
2017-06-20 20:03:04 +00:00
name: 'AES-GCM'
},
true,
['encrypt', 'decrypt']
)
.then(key => {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onprogress = event => {
if (event.lengthComputable && event.target.status !== 404) {
this.emit('progress', [event.loaded, event.total]);
}
};
xhr.onload = function(event) {
if (xhr.status === 404) {
reject(new Error('notfound'));
return;
}
const blob = new Blob([this.response]);
2017-08-09 19:56:32 +00:00
const type = xhr.getResponseHeader('Content-Type');
const meta = JSON.parse(xhr.getResponseHeader('X-File-Metadata'));
const fileReader = new FileReader();
fileReader.onload = function() {
resolve([
{
data: this.result,
filename: meta.filename,
2017-08-09 19:56:32 +00:00
type,
iv: meta.id
},
key
]);
};
fileReader.readAsArrayBuffer(blob);
};
xhr.open('get', '/assets' + location.pathname.slice(0, -1), true);
xhr.responseType = 'blob';
xhr.send();
});
})
2017-07-22 00:01:26 +00:00
.then(([fdata, key]) => {
2017-08-06 01:06:43 +00:00
this.emit('decrypting');
2017-07-22 00:01:26 +00:00
return Promise.all([
window.crypto.subtle
.decrypt(
{
name: 'AES-GCM',
iv: hexToArray(fdata.iv),
2017-07-24 19:16:01 +00:00
tagLength: 128
2017-07-22 00:01:26 +00:00
},
key,
fdata.data
)
.then(decrypted => {
return Promise.resolve(decrypted);
}),
2017-08-09 19:56:32 +00:00
{
name: decodeURIComponent(fdata.filename),
type: fdata.type
}
2017-07-22 00:01:26 +00:00
]);
});
2017-06-02 19:38:05 +00:00
}
}
module.exports = FileReceiver;