upload.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. const crypto = require('crypto');
  2. const storage = require('../storage');
  3. const config = require('../config');
  4. const mozlog = require('../log');
  5. const Limiter = require('../limiter');
  6. const { encryptedSize } = require('../../app/utils');
  7. const log = mozlog('send.upload');
  8. module.exports = async function(req, res) {
  9. const newId = crypto.randomBytes(8).toString('hex');
  10. const metadata = req.header('X-File-Metadata');
  11. const auth = req.header('Authorization');
  12. if (!metadata || !auth) {
  13. return res.sendStatus(400);
  14. }
  15. const owner = crypto.randomBytes(10).toString('hex');
  16. const meta = {
  17. owner,
  18. metadata,
  19. auth: auth.split(' ')[1],
  20. nonce: crypto.randomBytes(16).toString('base64')
  21. };
  22. try {
  23. const limiter = new Limiter(encryptedSize(config.max_file_size));
  24. const fileStream = req.pipe(limiter);
  25. //this hasn't been updated to expiration time setting yet
  26. //if you want to fallback to this code add this
  27. await storage.set(newId, fileStream, meta, config.default_expire_seconds);
  28. const protocol = config.env === 'production' ? 'https' : req.protocol;
  29. const url = `${protocol}://${req.get('host')}/download/${newId}/`;
  30. res.set('WWW-Authenticate', `send-v1 ${meta.nonce}`);
  31. res.json({
  32. url,
  33. owner: meta.owner,
  34. id: newId
  35. });
  36. } catch (e) {
  37. if (e.message === 'limit') {
  38. return res.sendStatus(413);
  39. }
  40. log.error('upload', e);
  41. res.sendStatus(500);
  42. }
  43. };