Example #1
0
    return function jsonParser(req, res, next) {
        if (req._body) {
            return debug('body already parsed'), next()
        }

        req.body = req.body || {}

        // skip requests without bodies
        if (!typeis.hasBody(req)) {
            return debug('skip empty body'), next()
        }

        debug('content-type %j', req.headers['content-type'])

        // determine if request should be parsed
        //if (!shouldParse(req)) {
        //    return debug('skip parsing'), next()
        //}

        // assert charset per RFC 7159 sec 8.1
        var charset = getCharset(req) || 'utf-8'
        if (charset.substr(0, 4) !== 'utf-') {
            debug('invalid charset')
            next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', {
                charset: charset
            }))
            return
        }

        // read
        read(req, res, next, parse, debug, {
            encoding: charset,
            inflate: inflate,
            limit: limit,
            verify: verify
        })
    }
Example #2
0
		up.get_package(name, _options, function(err, up_res, etag) {
			if (err && err.status === 304)
				pkginfo._uplinks[up.upname].fetched = Date.now()

			if (err || !up_res) return cb(null, [err || Error('no data')])

			try {
				utils.validate_metadata(up_res, name)
			} catch(err) {
				self.logger.error({
					sub: 'out',
					err: err,
				}, 'package.json validating error @{!err.message}\n@{err.stack}')
				return cb(null, [err])
			}

			pkginfo._uplinks[up.upname] = {
				etag: etag,
				fetched: Date.now()
			}

			try {
				Storage._merge_versions(pkginfo, up_res, self.config)
			} catch(err) {
				self.logger.error({
					sub: 'out',
					err: err,
				}, 'package.json parsing error @{!err.message}\n@{err.stack}')
				return cb(null, [err])
			}

			// if we got to this point, assume that the correct package exists
			// on the uplink
			exists = true
			cb()
		})
Example #3
0
// Read and parse a request body.
function read(req, typeInfo, parseFn, resolve, reject) {
  const charset = (typeInfo.parameters.charset || 'utf-8').toLowerCase();

  // Assert charset encoding per JSON RFC 7159 sec 8.1
  if (charset.slice(0, 4) !== 'utf-') {
    throw httpError(415, `Unsupported charset "${charset.toUpperCase()}".`);
  }

  // Get content-encoding (e.g. gzip)
  const contentEncoding = req.headers['content-encoding'];
  const encoding =
    typeof contentEncoding === 'string'
      ? contentEncoding.toLowerCase()
      : 'identity';
  const length = encoding === 'identity' ? req.headers['content-length'] : null;
  const limit = 1000 * 1024; // 1mb
  const stream = decompressed(req, encoding);

  // Read body from stream.
  getBody(stream, { encoding: charset, length, limit }, (err, body) => {
    if (err) {
      return reject(
        err.type === 'encoding.unsupported'
          ? httpError(415, `Unsupported charset "${charset.toUpperCase()}".`)
          : httpError(400, `Invalid body: ${err.message}.`),
      );
    }

    try {
      // Decode and parse body.
      return resolve(parseFn(body));
    } catch (error) {
      return reject(error);
    }
  });
}
Example #4
0
 getCode: (statusCode: number, customMessage: string) => {
   return createError(statusCode, customMessage);
 },
Example #5
0
 getServiceUnavailable: (message: string = API_ERROR.RESOURCE_UNAVAILABLE) => {
   return createError(HTTP_STATUS.SERVICE_UNAVAILABLE, message);
 },
Example #6
0
 getUnauthorized: (message: string = 'no credentials provided') => {
   return createError(HTTP_STATUS.UNAUTHORIZED, message);
 },
Example #7
0
 getBadRequest: (customMessage?: string) => {
   return createError(HTTP_STATUS.BAD_REQUEST, customMessage);
 },
Example #8
0
 getConflict: (message: string = API_ERROR.PACKAGE_EXIST) => {
   return createError(HTTP_STATUS.CONFLICT, message);
 },
 return function (req, res, next) {
   var user = req.user;
   if (!user) return next(error(401));
   if (!~roles.indexOf(user.role)) return next(error(404));
   next();
 }
Example #10
0
 get500: () => {
   return createError(500);
 },
Example #11
0
 get400: (customMessage) => {
   return createError(400, customMessage);
 },
Example #12
0
 get422: (customMessage) => {
   return createError(422, customMessage || 'bad data');
 },
Example #13
0
 get409: () => {
   return createError(409, 'this package is already present');
 },
	// Handle proxy responses, allowing modification of a response
	// before sending it to the user
	function proxyResponseHandler(proxyResponse, request, response) {
		const originalHeaders = proxyResponse.headers;

		// If we have a Cloudinary error, save it to the response
		// and don't assume the response is an image
		if (originalHeaders['x-cld-error']) {
			// We reset the response headers to remove the caching that
			// Cloudinary specifies, as well as getting rid of the
			// `image/gif` Content-Type
			proxyResponse.headers = {};
			response.cloudinaryError = new Error(originalHeaders['x-cld-error']);
			response.cloudinaryError.status = proxyResponse.statusCode;
			if (/^resource not found .* HTML response$/i.test(response.cloudinaryError.message)) {
				response.cloudinaryError.message = 'The requested resource is not an image';
				response.cloudinaryError.status = 400;
			}
			if (/^(error in loading .* 403 forbidden$|resource not found)/i.test(response.cloudinaryError.message)) {
				response.cloudinaryError.message = 'The requested image could not be found';
				response.cloudinaryError.status = 404;
			}
			return;
		}

		// If we have a 40x/50x response at this point, Cloudinary
		// is so broken that it can't even send its own X-CLD-Error
		// header. We need to handle this to prevent these errors
		// from being cached
		if (proxyResponse.statusCode >= 400) {
			proxyResponse.headers = {};
			response.cloudinaryError = httpError(proxyResponse.statusCode);
			return;
		}

		// If we have a 30x response at this point, something has
		// gone pretty wrong with Cloudinary's fetch API – it should
		// never redirect
		if (proxyResponse.statusCode >= 300 && proxyResponse.statusCode !== 304 ) {
			proxyResponse.headers = {};
			response.cloudinaryError = httpError(500);
			return;
		}

		// Define our own headers for proxy responses
		proxyResponse.headers = {
			'Access-Control-Allow-Origin': '*',
			'Cache-Control': `public, max-age=${oneWeek}, stale-while-revalidate=${oneWeek}, stale-if-error=${oneWeek}`,
			'Content-Encoding': originalHeaders['content-encoding'],
			'Content-Type': originalHeaders['content-type'],
			'Content-Length': originalHeaders['content-length'],
			'Connection': 'keep-alive',
			'Etag': originalHeaders['etag'],
			'Last-Modified': originalHeaders['last-modified']
		};

		if (request.headers['accept'] && request.headers['accept'].includes('image/webp')) {
			proxyResponse.headers['FT-Image-Format'] = 'webp';
		} else if (request.headers['accept'] && request.headers['accept'].includes('image/jxr')) {
			proxyResponse.headers['FT-Image-Format'] = 'jpegxr';
		} else {
			proxyResponse.headers['FT-Image-Format'] = 'default';
		}

		switch (request.params.scheme) {
			case 'ftbrand':
			case 'ftcms':
			case 'ftflag':
			case 'fthead':
			case 'fticon':
			case 'ftlogo':
			case 'ftpodcast':
			case 'ftsocial':
			case 'specialisttitle':
				proxyResponse.headers['Surrogate-Control'] = `max-age=${oneYear}, stale-while-revalidate=${oneYear}, stale-if-error=${oneYear}`;
				break;
			default:
				proxyResponse.headers['Surrogate-Control'] = proxyResponse.headers['Cache-Control'];
				break;
		}

		const keyForAllImages = 'origami-image-service';
		const keyForImageType = proxyResponse.headers['Content-Type'];
		const keyForScheme = request.params.scheme;

		const normaliseKeys = (key = '') => key.toLowerCase();
		const encodeKeys = (key = '') => base64.encode(utf8.encode(key));

		proxyResponse.headers['Surrogate-Key'] = `${keyForAllImages} ${encodeKeys(normaliseKeys(keyForImageType))} ${encodeKeys(normaliseKeys(keyForScheme))} ${encodeKeys(request.params.schemeUrl)}`;

		if (request.transform && request.transform.getDpr()) {
			proxyResponse.headers['Content-Dpr'] = request.transform.getDpr();
		}

		proxyResponse.headers['Vary'] = 'FT-image-format, Content-Dpr, Accept';
	}
Example #15
0
 process.nextTick(function() {
   if (typeof(cb) === 'function') cb(Error('uplink is offline'))
   req.emit('error', Error('uplink is offline'))
 })
Example #16
0
File: nuts.js Project: PlutoVR/nuts
Nuts.prototype.onDownload = function(req, res, next) {
    var that           = this;
    var channel        = req.params.channel;
    var platform       = req.params.platform;
    var tag            = req.params.tag || 'latest';
    var filename       = req.params.filename;
    var filetypeWanted = req.query.filetype;

    // When serving a specific file, platform is not required
    if (!filename) {
        // Detect platform from useragent
        if (!platform) {
            if (req.useragent.isMac) platform = platforms.OSX;
            if (req.useragent.isWindows) platform = platforms.WINDOWS;
            if (req.useragent.isLinux) platform = platforms.LINUX;
            if (req.useragent.isLinux64) platform = platforms.LINUX_64;
        }

        if (!platform) {
            return next(createError(400, 'No platform specified and impossible to detect one'));
        }
    } else {
        platform = null;
    }

    // If specific version, don't enforce a channel
    if (tag != 'latest') {
        channel = '*';
    }

    this.versions.resolve({
        channel: channel,
        platform: platform,
        tag: tag
    })

    // Fallback to any channels if no version found on stable one
    .fail(function(err) {
        if (channel || tag != 'latest') throw err;

        return that.versions.resolve({
            channel: '*',
            platform: platform,
            tag: tag
        });
    })

    // Serve downloads
    .then(function(version) {
        var asset;

        if (filename) {
            asset = _.find(version.platforms, {
                filename: filename
            });
        } else {
            asset = platforms.resolve(version, platform, {
                wanted: filetypeWanted? '.'+filetypeWanted : null
            });
        }

        if (!asset) {
            throw createError(404, 'No download available for platform ' + platform
                + ' for version ' + version.tag + ' (' + (channel || 'beta') + ')');
        }

        // Call analytic middleware, then serve
        return that.serveAsset(req, res, version, asset);
    })
    .fail(next);
};
    return function serveIndex(req, res, next) {
        if (req.method !== 'GET' && req.method !== 'HEAD') {
            res.statusCode = 'OPTIONS' === req.method
                ? 200
                : 405;
            res.setHeader('Allow', 'GET, HEAD, OPTIONS');
            res.end();
            return;
        }

        // parse URLs
        var url = parseUrl(req);
        var originalUrl = parseUrl.original(req);
        var dir = decodeURIComponent(url.pathname);
        var originalDir = decodeURIComponent(originalUrl.pathname);

        // join / normalize from root dir
        var path = normalize(join(root, dir));

        // null byte(s), bad request
        if (~path.indexOf('\0')) return next(createError(400));

        // malicious path
        if ((path + sep).substr(0, root.length) !== root) {
            debug('malicious path "%s"', path);
            return next(createError(403));
        }

        // determine ".." display
        var showUp = normalize(resolve(path) + sep) !== root;

        // check if we have a directory
        debug('stat "%s"', path);
        fs.stat(path, function (err, stat) {
            if (err && err.code === 'ENOENT') {
                return next();
            }

            if (err) {
                err.status = err.code === 'ENAMETOOLONG'
                    ? 414
                    : 500;
                return next(err);
            }

            if (!stat.isDirectory()) return next();

            // fetch files
            debug('readdir "%s"', path);
            fs.readdir(path, function (err, files) {
                if (err) return next(err);
                if (!hidden) files = removeHidden(files);
                if (filter) files = files.filter(function (filename, index, list) {
                    return filter(filename, index, list, path);
                });
                files.sort();

                // content-negotiation
                var accept = accepts(req);
                var type = accept.type(mediaTypes);

                // not acceptable
                if (!type) return next(createError(406));
                exports[mediaType[type]](req, res, files, next, originalDir, showUp, icons, path, view, template, stylesheet);
            });
        });
    };
Example #18
0
 get403: () => {
   return createError(403, 'can\'t use this filename');
 },
exports.user.exists = function (req, res, next) {
  if (!req.user) return next(error(401));
  next();
}
Example #20
0
 get503: () => {
   return createError(500, 'resource temporarily unavailable');
 },
Example #21
0
 getBadData: (customMessage?: string) => {
   return createError(HTTP_STATUS.BAD_DATA, customMessage || API_ERROR.BAD_DATA);
 },
Example #22
0
 get404: (customMessage) => {
   return createError(404, customMessage || 'no such package available');
 },
Example #23
0
 getInternalError: (customMessage?: string) => {
   return customMessage ? createError(HTTP_STATUS.INTERNAL_ERROR, customMessage) : createError(HTTP_STATUS.INTERNAL_ERROR);
 },
Example #24
0
app.all('*', function(req, res, next){
  debug('404 * route');
  next(httpErrors(404, 'no such route'));
});
Example #25
0
 getForbidden: (message: string = "can't use this filename") => {
   return createError(HTTP_STATUS.FORBIDDEN, message);
 },
 Object.keys(reqBody).forEach((key) => {
   if (teamKeys.indexOf(key) === -1) return reject(httpErrors(400, 'key does not exist'));
 });
Example #27
0
 getNotFound: (customMessage?: string) => {
   return createError(HTTP_STATUS.NOT_FOUND, customMessage || API_ERROR.NO_PACKAGE);
 },
 .catch(err => reject(httpErrors(404, err.message)));
Example #29
0
app.use(function(req, res, next) {
  next(createError(404));
});
 .catch(() => reject(httpErrors(404, 'team not found')));