From 1a2d02172178b7b1e85e0073d84fd23e90f6e8e3 Mon Sep 17 00:00:00 2001 From: Assaf Ben Josef Date: Sun, 24 Oct 2021 13:17:15 +0300 Subject: [PATCH] Create checkHeader func, add env vars and update documentation --- README.md | 8 ++++++++ index.js | 19 +++++++++++++++---- test/parse-link-header.js | 18 ++++++++++++++++++ 3 files changed, 41 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index a55c218..434c28b 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,14 @@ console.log(parsed); Parses the given link header containing [web links](http://tools.ietf.org/html/rfc5988) and returns an object keyed by the `rel` property that contains information about each link. +### Environmental Variables + +To avoid redundantly parsing of extremely long (invalid) input, the package uses 2 env variabes: + +`MAX_LINKHEADER_LENGTH` - Sets the number of characters the input should be limited to - longer inputs will not be handled. Defaults to `2000`. + +`PARSE_LINK_HEADER_THROW_ON_MAXLEN_EXCEEDED` - Defines behavior for when the `MAX_LINKHEADER_LENGTH` parameter is exceeded. if `true`, an error will be thrown; if `false`, the function fails silently by returning `null`. Defaults to `false`. + ### Formatting a link header The purpose of this module is to parse the link header information. To format an object generated by this module back to the link header string, use the [format-link-header](https://github.com/jonathansamines/format-link-header) module. diff --git a/index.js b/index.js index 6c964fa..776be22 100644 --- a/index.js +++ b/index.js @@ -4,6 +4,8 @@ var qs = require('querystring') , url = require('url') , xtend = require('xtend'); + + function hasRel(x) { return x && x.rel; } @@ -46,13 +48,22 @@ function parseLink(link) { } } -module.exports = function (linkHeader) { - if (!linkHeader) return null; - const MAX_LINKHEADER_LENGTH = 2000; +function checkHeader(linkHeader){ + if (!linkHeader) return false; + const MAX_LINKHEADER_LENGTH = process.env.MAX_LINKHEADER_LENGTH || 2000; + const PARSE_LINK_HEADER_THROW_ON_MAXLEN_EXCEEDED = process.env.PARSE_LINK_HEADER_THROW_ON_MAXLEN_EXCEEDED || false if (linkHeader.length > MAX_LINKHEADER_LENGTH) { + if (PARSE_LINK_HEADER_THROW_ON_MAXLEN_EXCEEDED) { throw new Error('Input string too long, it should be under ' + MAX_LINKHEADER_LENGTH + ' characters.'); + } + else return false; } - + return true; +} + +module.exports = function (linkHeader) { + if (!checkHeader(linkHeader)) return null; + return linkHeader.split(/,\s*