upload.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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 url = `${config.deriveBaseUrl(req)}/download/${newId}/`;
  29. res.set('WWW-Authenticate', `send-v1 ${meta.nonce}`);
  30. res.json({
  31. url,
  32. owner: meta.owner,
  33. id: newId
  34. });
  35. } catch (e) {
  36. if (e.message === 'limit') {
  37. return res.sendStatus(413);
  38. }
  39. log.error('upload', e);
  40. res.sendStatus(500);
  41. }
  42. };