drop.chapril.org-firefoxsend/frontend/src/fileReceiver.js

106 lines
2.8 KiB
JavaScript
Raw Normal View History

2017-06-02 21:38:05 +02:00
const EventEmitter = require('events');
2017-06-28 20:30:14 +02:00
const { hexToArray } = require('./utils');
2017-06-02 21:38:05 +02:00
class FileReceiver extends EventEmitter {
constructor() {
super();
}
download() {
return Promise.all([
new Promise((resolve, reject) => {
2017-06-09 19:44:12 +02:00
const xhr = new XMLHttpRequest();
2017-06-09 19:44:12 +02:00
xhr.onprogress = event => {
2017-07-11 20:18:31 +02:00
if (event.lengthComputable && event.target.status !== 404) {
2017-07-13 16:05:45 +02:00
this.emit('progress', [event.loaded, event.total]);
2017-06-02 21:38:05 +02:00
}
};
2017-06-10 01:56:25 +02:00
xhr.onload = function(event) {
if (xhr.status === 404) {
2017-06-06 23:24:51 +02:00
reject(
new Error('notfound')
2017-06-06 23:24:51 +02:00
);
2017-06-02 23:54:50 +02:00
return;
}
2017-06-09 19:44:12 +02:00
const blob = new Blob([this.response]);
const fileReader = new FileReader();
2017-06-02 21:38:05 +02:00
fileReader.onload = function() {
2017-06-29 19:30:08 +02:00
const meta = JSON.parse(xhr.getResponseHeader('X-File-Metadata'));
2017-06-02 21:38:05 +02:00
resolve({
data: this.result,
2017-06-29 19:27:36 +02:00
aad: meta.aad,
2017-07-07 23:47:56 +02:00
filename: meta.filename,
2017-07-10 21:45:20 +02:00
iv: meta.id
2017-06-02 21:38:05 +02:00
});
};
2017-06-02 21:38:05 +02:00
fileReader.readAsArrayBuffer(blob);
};
2017-06-02 21:38:05 +02:00
xhr.open('get', '/assets' + location.pathname.slice(0, -1), true);
xhr.responseType = 'blob';
xhr.send();
}),
window.crypto.subtle.importKey(
'jwk',
{
kty: 'oct',
k: location.hash.slice(1),
2017-06-28 20:30:14 +02:00
alg: 'A128GCM',
ext: true
},
{
2017-06-20 22:03:04 +02:00
name: 'AES-GCM'
},
true,
['encrypt', 'decrypt']
)
2017-07-22 02:01:26 +02:00
])
.then(([fdata, key]) => {
this.emit('decrypting', true);
return Promise.all([
window.crypto.subtle
.decrypt(
{
name: 'AES-GCM',
iv: hexToArray(fdata.iv),
2017-07-24 21:16:01 +02:00
additionalData: hexToArray(fdata.aad),
tagLength: 128
2017-07-22 02:01:26 +02:00
},
key,
fdata.data
)
.then(decrypted => {
this.emit('decrypting', false);
return Promise.resolve(decrypted);
}),
fdata.filename,
hexToArray(fdata.aad)
]);
2017-07-10 20:25:03 +02:00
})
2017-07-22 02:01:26 +02:00
.then(([decrypted, fname, proposedHash]) => {
this.emit('hashing', true);
return window.crypto.subtle
.digest('SHA-256', decrypted)
.then(calculatedHash => {
this.emit('hashing', false);
const integrity =
new Uint8Array(calculatedHash).toString() ===
proposedHash.toString();
if (!integrity) {
this.emit('unsafe', true);
return Promise.reject();
} else {
this.emit('safe', true);
return Promise.all([decrypted, decodeURIComponent(fname)]);
}
});
});
2017-06-02 21:38:05 +02:00
}
}
module.exports = FileReceiver;