diff --git a/README.md b/README.md index a55c218..1eb4ff7 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: + +`PARSE_LINK_HEADER_MAXLEN` - 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 `PARSE_LINK_HEADER_MAXLEN` parameter is exceeded. if defined, an error will be thrown; if it's `null`, the function fails silently by returning `null`. Defaults to `null`. + ### 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 e01bfbe..3bb1c3d 100644 --- a/index.js +++ b/index.js @@ -4,6 +4,9 @@ var qs = require('querystring') , url = require('url') , xtend = require('xtend'); +const PARSE_LINK_HEADER_MAXLEN = parseInt(process.env.PARSE_LINK_HEADER_MAXLEN) || 2000; +const PARSE_LINK_HEADER_THROW_ON_MAXLEN_EXCEEDED = process.env.PARSE_LINK_HEADER_THROW_ON_MAXLEN_EXCEEDED != null + function hasRel(x) { return x && x.rel; } @@ -46,8 +49,21 @@ function parseLink(link) { } } +function checkHeader(linkHeader){ + if (!linkHeader) return false; + + if (linkHeader.length > PARSE_LINK_HEADER_MAXLEN) { + if (PARSE_LINK_HEADER_THROW_ON_MAXLEN_EXCEEDED) { + throw new Error('Input string too long, it should be under ' + PARSE_LINK_HEADER_MAXLEN + ' characters.'); + } else { + return false; + } + } + return true; +} + module.exports = function (linkHeader) { - if (!linkHeader) return null; + if (!checkHeader(linkHeader)) return null; return linkHeader.split(/,\s*