2017-08-24 21:54:02 +00:00
|
|
|
const storage = require('../storage');
|
|
|
|
const mozlog = require('../log');
|
|
|
|
const log = mozlog('send.download');
|
2017-08-31 16:43:36 +00:00
|
|
|
const crypto = require('crypto');
|
2017-08-24 21:54:02 +00:00
|
|
|
|
|
|
|
module.exports = async function(req, res) {
|
|
|
|
const id = req.params.id;
|
|
|
|
|
|
|
|
try {
|
2017-08-31 16:43:36 +00:00
|
|
|
const auth = req.header('Authorization').split(' ')[1];
|
2017-08-24 21:54:02 +00:00
|
|
|
const meta = await storage.metadata(id);
|
2017-08-31 16:43:36 +00:00
|
|
|
const hmac = crypto.createHmac('sha256', Buffer.from(meta.auth, 'base64'));
|
|
|
|
hmac.update(Buffer.from(meta.nonce, 'base64'));
|
|
|
|
const verifyHash = hmac.digest();
|
|
|
|
if (!verifyHash.equals(Buffer.from(auth, 'base64'))) {
|
2017-11-30 21:41:09 +00:00
|
|
|
res.set('WWW-Authenticate', `send-v1 ${meta.nonce}`);
|
2017-08-31 16:43:36 +00:00
|
|
|
return res.sendStatus(401);
|
|
|
|
}
|
2017-11-30 21:41:09 +00:00
|
|
|
const nonce = crypto.randomBytes(16).toString('base64');
|
|
|
|
storage.setField(id, 'nonce', nonce);
|
2017-08-24 21:54:02 +00:00
|
|
|
const contentLength = await storage.length(id);
|
|
|
|
res.writeHead(200, {
|
2017-08-31 16:43:36 +00:00
|
|
|
'Content-Disposition': 'attachment',
|
2017-08-24 21:54:02 +00:00
|
|
|
'Content-Type': 'application/octet-stream',
|
|
|
|
'Content-Length': contentLength,
|
2017-08-31 16:43:36 +00:00
|
|
|
'X-File-Metadata': meta.metadata,
|
|
|
|
'WWW-Authenticate': `send-v1 ${nonce}`
|
2017-08-24 21:54:02 +00:00
|
|
|
});
|
|
|
|
const file_stream = storage.get(id);
|
|
|
|
|
|
|
|
file_stream.on('end', async () => {
|
2017-11-30 21:41:09 +00:00
|
|
|
const dl = (+meta.dl || 0) + 1;
|
|
|
|
const dlimit = +meta.dlimit || 1;
|
2017-08-24 21:54:02 +00:00
|
|
|
try {
|
2017-11-30 21:41:09 +00:00
|
|
|
if (dl >= dlimit) {
|
|
|
|
await storage.forceDelete(id);
|
|
|
|
} else {
|
|
|
|
await storage.setField(id, 'dl', dl);
|
|
|
|
}
|
2017-08-24 21:54:02 +00:00
|
|
|
} catch (e) {
|
2017-11-30 21:41:09 +00:00
|
|
|
log.info('StorageError:', id);
|
2017-08-24 21:54:02 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
file_stream.pipe(res);
|
|
|
|
} catch (e) {
|
|
|
|
res.sendStatus(404);
|
|
|
|
}
|
|
|
|
};
|