diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json new file mode 100644 index 0000000..56864e8 --- /dev/null +++ b/node_modules/.package-lock.json @@ -0,0 +1,101 @@ +{ + "name": "Medical-Website", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/basic-auth": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/basic-auth/-/basic-auth-2.0.1.tgz", + "integrity": "sha512-NF+epuEdnUYVlGuhaxbbq+dvJttwLnGY+YixlXlME5KpQ5W3CnXA5cVTneY3SPbPDRkcjMbifrwmFYcClgOZeg==", + "license": "MIT", + "dependencies": { + "safe-buffer": "5.1.2" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/helmet": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/helmet/-/helmet-8.0.0.tgz", + "integrity": "sha512-VyusHLEIIO5mjQPUI1wpOAEu+wl6Q0998jzTxqUYGE45xCIcAxy3MsbEK/yyJUJ3ADeMoB6MornPH6GMWAf+Pw==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/morgan": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/morgan/-/morgan-1.10.0.tgz", + "integrity": "sha512-AbegBVI4sh6El+1gNwvD5YIck7nSA36weD7xvIxG4in80j/UoK8AEGaWnnz8v1GxonMCltmlNs5ZKbGvl9b1XQ==", + "license": "MIT", + "dependencies": { + "basic-auth": "~2.0.1", + "debug": "2.6.9", + "depd": "~2.0.0", + "on-finished": "~2.3.0", + "on-headers": "~1.0.2" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/on-finished": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz", + "integrity": "sha512-ikqdkGAAyf/X/gPhXGvfgAytDZtDbr+bkNUJ0N9h5MI/dmdgCs3l6hoHrcUv41sRKew3jIwrp4qQDXiK99Utww==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/on-headers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.0.2.tgz", + "integrity": "sha512-pZAE+FJLoyITytdqK0U5s+FIpjN0JP3OzFi/u8Rx+EV5/W+JTWGXG8xFzevE7AjBfDqHv/8vL8qQsIhHnqRkrA==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "license": "MIT" + } + } +} diff --git a/node_modules/basic-auth/HISTORY.md b/node_modules/basic-auth/HISTORY.md new file mode 100644 index 0000000..2c44a01 --- /dev/null +++ b/node_modules/basic-auth/HISTORY.md @@ -0,0 +1,52 @@ +2.0.1 / 2018-09-19 +================== + + * deps: safe-buffer@5.1.2 + +2.0.0 / 2017-09-12 +================== + + * Drop support for Node.js below 0.8 + * Remove `auth(ctx)` signature -- pass in header or `auth(ctx.req)` + * Use `safe-buffer` for improved Buffer API + +1.1.0 / 2016-11-18 +================== + + * Add `auth.parse` for low-level string parsing + +1.0.4 / 2016-05-10 +================== + + * Improve error message when `req` argument is not an object + * Improve error message when `req` missing `headers` property + +1.0.3 / 2015-07-01 +================== + + * Fix regression accepting a Koa context + +1.0.2 / 2015-06-12 +================== + + * Improve error message when `req` argument missing + * perf: enable strict mode + * perf: hoist regular expression + * perf: parse with regular expressions + * perf: remove argument reassignment + +1.0.1 / 2015-05-04 +================== + + * Update readme + +1.0.0 / 2014-07-01 +================== + + * Support empty password + * Support empty username + +0.0.1 / 2013-11-30 +================== + + * Initial release diff --git a/node_modules/basic-auth/LICENSE b/node_modules/basic-auth/LICENSE new file mode 100644 index 0000000..89041f6 --- /dev/null +++ b/node_modules/basic-auth/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2013 TJ Holowaychuk +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2015-2016 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/basic-auth/README.md b/node_modules/basic-auth/README.md new file mode 100644 index 0000000..5f3d758 --- /dev/null +++ b/node_modules/basic-auth/README.md @@ -0,0 +1,113 @@ +# basic-auth + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Generic basic auth Authorization header field parser for whatever. + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +``` +$ npm install basic-auth +``` + +## API + + + +```js +var auth = require('basic-auth') +``` + +### auth(req) + +Get the basic auth credentials from the given request. The `Authorization` +header is parsed and if the header is invalid, `undefined` is returned, +otherwise an object with `name` and `pass` properties. + +### auth.parse(string) + +Parse a basic auth authorization header string. This will return an object +with `name` and `pass` properties, or `undefined` if the string is invalid. + +## Example + +Pass a Node.js request object to the module export. If parsing fails +`undefined` is returned, otherwise an object with `.name` and `.pass`. + + + +```js +var auth = require('basic-auth') +var user = auth(req) +// => { name: 'something', pass: 'whatever' } +``` + +A header string from any other location can also be parsed with +`auth.parse`, for example a `Proxy-Authorization` header: + + + +```js +var auth = require('basic-auth') +var user = auth.parse(req.getHeader('Proxy-Authorization')) +``` + +### With vanilla node.js http server + +```js +var http = require('http') +var auth = require('basic-auth') +var compare = require('tsscmp') + +// Create server +var server = http.createServer(function (req, res) { + var credentials = auth(req) + + // Check credentials + // The "check" function will typically be against your user store + if (!credentials || !check(credentials.name, credentials.pass)) { + res.statusCode = 401 + res.setHeader('WWW-Authenticate', 'Basic realm="example"') + res.end('Access denied') + } else { + res.end('Access granted') + } +}) + +// Basic function to validate credentials for example +function check (name, pass) { + var valid = true + + // Simple method to prevent short-circut and use timing-safe compare + valid = compare(name, 'john') && valid + valid = compare(pass, 'secret') && valid + + return valid +} + +// Listen +server.listen(3000) +``` + +# License + +[MIT](LICENSE) + +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/basic-auth/master +[coveralls-url]: https://coveralls.io/r/jshttp/basic-auth?branch=master +[downloads-image]: https://badgen.net/npm/dm/basic-auth +[downloads-url]: https://npmjs.org/package/basic-auth +[node-version-image]: https://badgen.net/npm/node/basic-auth +[node-version-url]: https://nodejs.org/en/download +[npm-image]: https://badgen.net/npm/v/basic-auth +[npm-url]: https://npmjs.org/package/basic-auth +[travis-image]: https://badgen.net/travis/jshttp/basic-auth/master +[travis-url]: https://travis-ci.org/jshttp/basic-auth diff --git a/node_modules/basic-auth/index.js b/node_modules/basic-auth/index.js new file mode 100644 index 0000000..9106e64 --- /dev/null +++ b/node_modules/basic-auth/index.js @@ -0,0 +1,133 @@ +/*! + * basic-auth + * Copyright(c) 2013 TJ Holowaychuk + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015-2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var Buffer = require('safe-buffer').Buffer + +/** + * Module exports. + * @public + */ + +module.exports = auth +module.exports.parse = parse + +/** + * RegExp for basic auth credentials + * + * credentials = auth-scheme 1*SP token68 + * auth-scheme = "Basic" ; case insensitive + * token68 = 1*( ALPHA / DIGIT / "-" / "." / "_" / "~" / "+" / "/" ) *"=" + * @private + */ + +var CREDENTIALS_REGEXP = /^ *(?:[Bb][Aa][Ss][Ii][Cc]) +([A-Za-z0-9._~+/-]+=*) *$/ + +/** + * RegExp for basic auth user/pass + * + * user-pass = userid ":" password + * userid = * + * password = *TEXT + * @private + */ + +var USER_PASS_REGEXP = /^([^:]*):(.*)$/ + +/** + * Parse the Authorization header field of a request. + * + * @param {object} req + * @return {object} with .name and .pass + * @public + */ + +function auth (req) { + if (!req) { + throw new TypeError('argument req is required') + } + + if (typeof req !== 'object') { + throw new TypeError('argument req is required to be an object') + } + + // get header + var header = getAuthorization(req) + + // parse header + return parse(header) +} + +/** + * Decode base64 string. + * @private + */ + +function decodeBase64 (str) { + return Buffer.from(str, 'base64').toString() +} + +/** + * Get the Authorization header from request object. + * @private + */ + +function getAuthorization (req) { + if (!req.headers || typeof req.headers !== 'object') { + throw new TypeError('argument req is required to have headers property') + } + + return req.headers.authorization +} + +/** + * Parse basic auth to object. + * + * @param {string} string + * @return {object} + * @public + */ + +function parse (string) { + if (typeof string !== 'string') { + return undefined + } + + // parse header + var match = CREDENTIALS_REGEXP.exec(string) + + if (!match) { + return undefined + } + + // decode user pass + var userPass = USER_PASS_REGEXP.exec(decodeBase64(match[1])) + + if (!userPass) { + return undefined + } + + // return credentials object + return new Credentials(userPass[1], userPass[2]) +} + +/** + * Object to represent user credentials. + * @private + */ + +function Credentials (name, pass) { + this.name = name + this.pass = pass +} diff --git a/node_modules/basic-auth/package.json b/node_modules/basic-auth/package.json new file mode 100644 index 0000000..01bd8dc --- /dev/null +++ b/node_modules/basic-auth/package.json @@ -0,0 +1,41 @@ +{ + "name": "basic-auth", + "description": "node.js basic auth parser", + "version": "2.0.1", + "license": "MIT", + "keywords": [ + "basic", + "auth", + "authorization", + "basicauth" + ], + "repository": "jshttp/basic-auth", + "dependencies": { + "safe-buffer": "5.1.2" + }, + "devDependencies": { + "eslint": "5.6.0", + "eslint-config-standard": "12.0.0", + "eslint-plugin-import": "2.14.0", + "eslint-plugin-markdown": "1.0.0-beta.6", + "eslint-plugin-node": "7.0.1", + "eslint-plugin-promise": "4.0.1", + "eslint-plugin-standard": "4.0.0", + "istanbul": "0.4.5", + "mocha": "5.2.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --check-leaks --reporter spec --bail", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + } +} diff --git a/node_modules/debug/.coveralls.yml b/node_modules/debug/.coveralls.yml new file mode 100644 index 0000000..20a7068 --- /dev/null +++ b/node_modules/debug/.coveralls.yml @@ -0,0 +1 @@ +repo_token: SIAeZjKYlHK74rbcFvNHMUzjRiMpflxve diff --git a/node_modules/debug/.eslintrc b/node_modules/debug/.eslintrc new file mode 100644 index 0000000..8a37ae2 --- /dev/null +++ b/node_modules/debug/.eslintrc @@ -0,0 +1,11 @@ +{ + "env": { + "browser": true, + "node": true + }, + "rules": { + "no-console": 0, + "no-empty": [1, { "allowEmptyCatch": true }] + }, + "extends": "eslint:recommended" +} diff --git a/node_modules/debug/.npmignore b/node_modules/debug/.npmignore new file mode 100644 index 0000000..5f60eec --- /dev/null +++ b/node_modules/debug/.npmignore @@ -0,0 +1,9 @@ +support +test +examples +example +*.sock +dist +yarn.lock +coverage +bower.json diff --git a/node_modules/debug/.travis.yml b/node_modules/debug/.travis.yml new file mode 100644 index 0000000..6c6090c --- /dev/null +++ b/node_modules/debug/.travis.yml @@ -0,0 +1,14 @@ + +language: node_js +node_js: + - "6" + - "5" + - "4" + +install: + - make node_modules + +script: + - make lint + - make test + - make coveralls diff --git a/node_modules/debug/CHANGELOG.md b/node_modules/debug/CHANGELOG.md new file mode 100644 index 0000000..eadaa18 --- /dev/null +++ b/node_modules/debug/CHANGELOG.md @@ -0,0 +1,362 @@ + +2.6.9 / 2017-09-22 +================== + + * remove ReDoS regexp in %o formatter (#504) + +2.6.8 / 2017-05-18 +================== + + * Fix: Check for undefined on browser globals (#462, @marbemac) + +2.6.7 / 2017-05-16 +================== + + * Fix: Update ms to 2.0.0 to fix regular expression denial of service vulnerability (#458, @hubdotcom) + * Fix: Inline extend function in node implementation (#452, @dougwilson) + * Docs: Fix typo (#455, @msasad) + +2.6.5 / 2017-04-27 +================== + + * Fix: null reference check on window.documentElement.style.WebkitAppearance (#447, @thebigredgeek) + * Misc: clean up browser reference checks (#447, @thebigredgeek) + * Misc: add npm-debug.log to .gitignore (@thebigredgeek) + + +2.6.4 / 2017-04-20 +================== + + * Fix: bug that would occure if process.env.DEBUG is a non-string value. (#444, @LucianBuzzo) + * Chore: ignore bower.json in npm installations. (#437, @joaovieira) + * Misc: update "ms" to v0.7.3 (@tootallnate) + +2.6.3 / 2017-03-13 +================== + + * Fix: Electron reference to `process.env.DEBUG` (#431, @paulcbetts) + * Docs: Changelog fix (@thebigredgeek) + +2.6.2 / 2017-03-10 +================== + + * Fix: DEBUG_MAX_ARRAY_LENGTH (#420, @slavaGanzin) + * Docs: Add backers and sponsors from Open Collective (#422, @piamancini) + * Docs: Add Slackin invite badge (@tootallnate) + +2.6.1 / 2017-02-10 +================== + + * Fix: Module's `export default` syntax fix for IE8 `Expected identifier` error + * Fix: Whitelist DEBUG_FD for values 1 and 2 only (#415, @pi0) + * Fix: IE8 "Expected identifier" error (#414, @vgoma) + * Fix: Namespaces would not disable once enabled (#409, @musikov) + +2.6.0 / 2016-12-28 +================== + + * Fix: added better null pointer checks for browser useColors (@thebigredgeek) + * Improvement: removed explicit `window.debug` export (#404, @tootallnate) + * Improvement: deprecated `DEBUG_FD` environment variable (#405, @tootallnate) + +2.5.2 / 2016-12-25 +================== + + * Fix: reference error on window within webworkers (#393, @KlausTrainer) + * Docs: fixed README typo (#391, @lurch) + * Docs: added notice about v3 api discussion (@thebigredgeek) + +2.5.1 / 2016-12-20 +================== + + * Fix: babel-core compatibility + +2.5.0 / 2016-12-20 +================== + + * Fix: wrong reference in bower file (@thebigredgeek) + * Fix: webworker compatibility (@thebigredgeek) + * Fix: output formatting issue (#388, @kribblo) + * Fix: babel-loader compatibility (#383, @escwald) + * Misc: removed built asset from repo and publications (@thebigredgeek) + * Misc: moved source files to /src (#378, @yamikuronue) + * Test: added karma integration and replaced babel with browserify for browser tests (#378, @yamikuronue) + * Test: coveralls integration (#378, @yamikuronue) + * Docs: simplified language in the opening paragraph (#373, @yamikuronue) + +2.4.5 / 2016-12-17 +================== + + * Fix: `navigator` undefined in Rhino (#376, @jochenberger) + * Fix: custom log function (#379, @hsiliev) + * Improvement: bit of cleanup + linting fixes (@thebigredgeek) + * Improvement: rm non-maintainted `dist/` dir (#375, @freewil) + * Docs: simplified language in the opening paragraph. (#373, @yamikuronue) + +2.4.4 / 2016-12-14 +================== + + * Fix: work around debug being loaded in preload scripts for electron (#368, @paulcbetts) + +2.4.3 / 2016-12-14 +================== + + * Fix: navigation.userAgent error for react native (#364, @escwald) + +2.4.2 / 2016-12-14 +================== + + * Fix: browser colors (#367, @tootallnate) + * Misc: travis ci integration (@thebigredgeek) + * Misc: added linting and testing boilerplate with sanity check (@thebigredgeek) + +2.4.1 / 2016-12-13 +================== + + * Fix: typo that broke the package (#356) + +2.4.0 / 2016-12-13 +================== + + * Fix: bower.json references unbuilt src entry point (#342, @justmatt) + * Fix: revert "handle regex special characters" (@tootallnate) + * Feature: configurable util.inspect()`options for NodeJS (#327, @tootallnate) + * Feature: %O`(big O) pretty-prints objects (#322, @tootallnate) + * Improvement: allow colors in workers (#335, @botverse) + * Improvement: use same color for same namespace. (#338, @lchenay) + +2.3.3 / 2016-11-09 +================== + + * Fix: Catch `JSON.stringify()` errors (#195, Jovan Alleyne) + * Fix: Returning `localStorage` saved values (#331, Levi Thomason) + * Improvement: Don't create an empty object when no `process` (Nathan Rajlich) + +2.3.2 / 2016-11-09 +================== + + * Fix: be super-safe in index.js as well (@TooTallNate) + * Fix: should check whether process exists (Tom Newby) + +2.3.1 / 2016-11-09 +================== + + * Fix: Added electron compatibility (#324, @paulcbetts) + * Improvement: Added performance optimizations (@tootallnate) + * Readme: Corrected PowerShell environment variable example (#252, @gimre) + * Misc: Removed yarn lock file from source control (#321, @fengmk2) + +2.3.0 / 2016-11-07 +================== + + * Fix: Consistent placement of ms diff at end of output (#215, @gorangajic) + * Fix: Escaping of regex special characters in namespace strings (#250, @zacronos) + * Fix: Fixed bug causing crash on react-native (#282, @vkarpov15) + * Feature: Enabled ES6+ compatible import via default export (#212 @bucaran) + * Feature: Added %O formatter to reflect Chrome's console.log capability (#279, @oncletom) + * Package: Update "ms" to 0.7.2 (#315, @DevSide) + * Package: removed superfluous version property from bower.json (#207 @kkirsche) + * Readme: fix USE_COLORS to DEBUG_COLORS + * Readme: Doc fixes for format string sugar (#269, @mlucool) + * Readme: Updated docs for DEBUG_FD and DEBUG_COLORS environment variables (#232, @mattlyons0) + * Readme: doc fixes for PowerShell (#271 #243, @exoticknight @unreadable) + * Readme: better docs for browser support (#224, @matthewmueller) + * Tooling: Added yarn integration for development (#317, @thebigredgeek) + * Misc: Renamed History.md to CHANGELOG.md (@thebigredgeek) + * Misc: Added license file (#226 #274, @CantemoInternal @sdaitzman) + * Misc: Updated contributors (@thebigredgeek) + +2.2.0 / 2015-05-09 +================== + + * package: update "ms" to v0.7.1 (#202, @dougwilson) + * README: add logging to file example (#193, @DanielOchoa) + * README: fixed a typo (#191, @amir-s) + * browser: expose `storage` (#190, @stephenmathieson) + * Makefile: add a `distclean` target (#189, @stephenmathieson) + +2.1.3 / 2015-03-13 +================== + + * Updated stdout/stderr example (#186) + * Updated example/stdout.js to match debug current behaviour + * Renamed example/stderr.js to stdout.js + * Update Readme.md (#184) + * replace high intensity foreground color for bold (#182, #183) + +2.1.2 / 2015-03-01 +================== + + * dist: recompile + * update "ms" to v0.7.0 + * package: update "browserify" to v9.0.3 + * component: fix "ms.js" repo location + * changed bower package name + * updated documentation about using debug in a browser + * fix: security error on safari (#167, #168, @yields) + +2.1.1 / 2014-12-29 +================== + + * browser: use `typeof` to check for `console` existence + * browser: check for `console.log` truthiness (fix IE 8/9) + * browser: add support for Chrome apps + * Readme: added Windows usage remarks + * Add `bower.json` to properly support bower install + +2.1.0 / 2014-10-15 +================== + + * node: implement `DEBUG_FD` env variable support + * package: update "browserify" to v6.1.0 + * package: add "license" field to package.json (#135, @panuhorsmalahti) + +2.0.0 / 2014-09-01 +================== + + * package: update "browserify" to v5.11.0 + * node: use stderr rather than stdout for logging (#29, @stephenmathieson) + +1.0.4 / 2014-07-15 +================== + + * dist: recompile + * example: remove `console.info()` log usage + * example: add "Content-Type" UTF-8 header to browser example + * browser: place %c marker after the space character + * browser: reset the "content" color via `color: inherit` + * browser: add colors support for Firefox >= v31 + * debug: prefer an instance `log()` function over the global one (#119) + * Readme: update documentation about styled console logs for FF v31 (#116, @wryk) + +1.0.3 / 2014-07-09 +================== + + * Add support for multiple wildcards in namespaces (#122, @seegno) + * browser: fix lint + +1.0.2 / 2014-06-10 +================== + + * browser: update color palette (#113, @gscottolson) + * common: make console logging function configurable (#108, @timoxley) + * node: fix %o colors on old node <= 0.8.x + * Makefile: find node path using shell/which (#109, @timoxley) + +1.0.1 / 2014-06-06 +================== + + * browser: use `removeItem()` to clear localStorage + * browser, node: don't set DEBUG if namespaces is undefined (#107, @leedm777) + * package: add "contributors" section + * node: fix comment typo + * README: list authors + +1.0.0 / 2014-06-04 +================== + + * make ms diff be global, not be scope + * debug: ignore empty strings in enable() + * node: make DEBUG_COLORS able to disable coloring + * *: export the `colors` array + * npmignore: don't publish the `dist` dir + * Makefile: refactor to use browserify + * package: add "browserify" as a dev dependency + * Readme: add Web Inspector Colors section + * node: reset terminal color for the debug content + * node: map "%o" to `util.inspect()` + * browser: map "%j" to `JSON.stringify()` + * debug: add custom "formatters" + * debug: use "ms" module for humanizing the diff + * Readme: add "bash" syntax highlighting + * browser: add Firebug color support + * browser: add colors for WebKit browsers + * node: apply log to `console` + * rewrite: abstract common logic for Node & browsers + * add .jshintrc file + +0.8.1 / 2014-04-14 +================== + + * package: re-add the "component" section + +0.8.0 / 2014-03-30 +================== + + * add `enable()` method for nodejs. Closes #27 + * change from stderr to stdout + * remove unnecessary index.js file + +0.7.4 / 2013-11-13 +================== + + * remove "browserify" key from package.json (fixes something in browserify) + +0.7.3 / 2013-10-30 +================== + + * fix: catch localStorage security error when cookies are blocked (Chrome) + * add debug(err) support. Closes #46 + * add .browser prop to package.json. Closes #42 + +0.7.2 / 2013-02-06 +================== + + * fix package.json + * fix: Mobile Safari (private mode) is broken with debug + * fix: Use unicode to send escape character to shell instead of octal to work with strict mode javascript + +0.7.1 / 2013-02-05 +================== + + * add repository URL to package.json + * add DEBUG_COLORED to force colored output + * add browserify support + * fix component. Closes #24 + +0.7.0 / 2012-05-04 +================== + + * Added .component to package.json + * Added debug.component.js build + +0.6.0 / 2012-03-16 +================== + + * Added support for "-" prefix in DEBUG [Vinay Pulim] + * Added `.enabled` flag to the node version [TooTallNate] + +0.5.0 / 2012-02-02 +================== + + * Added: humanize diffs. Closes #8 + * Added `debug.disable()` to the CS variant + * Removed padding. Closes #10 + * Fixed: persist client-side variant again. Closes #9 + +0.4.0 / 2012-02-01 +================== + + * Added browser variant support for older browsers [TooTallNate] + * Added `debug.enable('project:*')` to browser variant [TooTallNate] + * Added padding to diff (moved it to the right) + +0.3.0 / 2012-01-26 +================== + + * Added millisecond diff when isatty, otherwise UTC string + +0.2.0 / 2012-01-22 +================== + + * Added wildcard support + +0.1.0 / 2011-12-02 +================== + + * Added: remove colors unless stderr isatty [TooTallNate] + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/node_modules/debug/LICENSE b/node_modules/debug/LICENSE new file mode 100644 index 0000000..658c933 --- /dev/null +++ b/node_modules/debug/LICENSE @@ -0,0 +1,19 @@ +(The MIT License) + +Copyright (c) 2014 TJ Holowaychuk + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software +and associated documentation files (the 'Software'), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial +portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT +LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/node_modules/debug/Makefile b/node_modules/debug/Makefile new file mode 100644 index 0000000..584da8b --- /dev/null +++ b/node_modules/debug/Makefile @@ -0,0 +1,50 @@ +# get Makefile directory name: http://stackoverflow.com/a/5982798/376773 +THIS_MAKEFILE_PATH:=$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST)) +THIS_DIR:=$(shell cd $(dir $(THIS_MAKEFILE_PATH));pwd) + +# BIN directory +BIN := $(THIS_DIR)/node_modules/.bin + +# Path +PATH := node_modules/.bin:$(PATH) +SHELL := /bin/bash + +# applications +NODE ?= $(shell which node) +YARN ?= $(shell which yarn) +PKG ?= $(if $(YARN),$(YARN),$(NODE) $(shell which npm)) +BROWSERIFY ?= $(NODE) $(BIN)/browserify + +.FORCE: + +install: node_modules + +node_modules: package.json + @NODE_ENV= $(PKG) install + @touch node_modules + +lint: .FORCE + eslint browser.js debug.js index.js node.js + +test-node: .FORCE + istanbul cover node_modules/mocha/bin/_mocha -- test/**.js + +test-browser: .FORCE + mkdir -p dist + + @$(BROWSERIFY) \ + --standalone debug \ + . > dist/debug.js + + karma start --single-run + rimraf dist + +test: .FORCE + concurrently \ + "make test-node" \ + "make test-browser" + +coveralls: + cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js + +.PHONY: all install clean distclean diff --git a/node_modules/debug/README.md b/node_modules/debug/README.md new file mode 100644 index 0000000..f67be6b --- /dev/null +++ b/node_modules/debug/README.md @@ -0,0 +1,312 @@ +# debug +[![Build Status](https://travis-ci.org/visionmedia/debug.svg?branch=master)](https://travis-ci.org/visionmedia/debug) [![Coverage Status](https://coveralls.io/repos/github/visionmedia/debug/badge.svg?branch=master)](https://coveralls.io/github/visionmedia/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) +[![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors) + + + +A tiny node.js debugging utility modelled after node core's debugging technique. + +**Discussion around the V3 API is under way [here](https://github.com/visionmedia/debug/issues/370)** + +## Installation + +```bash +$ npm install debug +``` + +## Usage + +`debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. + +Example _app.js_: + +```js +var debug = require('debug')('http') + , http = require('http') + , name = 'My App'; + +// fake app + +debug('booting %s', name); + +http.createServer(function(req, res){ + debug(req.method + ' ' + req.url); + res.end('hello\n'); +}).listen(3000, function(){ + debug('listening'); +}); + +// fake worker of some kind + +require('./worker'); +``` + +Example _worker.js_: + +```js +var debug = require('debug')('worker'); + +setInterval(function(){ + debug('doing some work'); +}, 1000); +``` + + The __DEBUG__ environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: + + ![debug http and worker](http://f.cl.ly/items/18471z1H402O24072r1J/Screenshot.png) + + ![debug worker](http://f.cl.ly/items/1X413v1a3M0d3C2c1E0i/Screenshot.png) + +#### Windows note + + On Windows the environment variable is set using the `set` command. + + ```cmd + set DEBUG=*,-not_this + ``` + + Note that PowerShell uses different syntax to set environment variables. + + ```cmd + $env:DEBUG = "*,-not_this" + ``` + +Then, run the program to be debugged as usual. + +## Millisecond diff + + When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. + + ![](http://f.cl.ly/items/2i3h1d3t121M2Z1A3Q0N/Screenshot.png) + + When stdout is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below: + + ![](http://f.cl.ly/items/112H3i0e0o0P0a2Q2r11/Screenshot.png) + +## Conventions + + If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". + +## Wildcards + + The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. + + You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with "connect:". + +## Environment Variables + + When running through Node.js, you can set a few environment variables that will + change the behavior of the debug logging: + +| Name | Purpose | +|-----------|-------------------------------------------------| +| `DEBUG` | Enables/disables specific debugging namespaces. | +| `DEBUG_COLORS`| Whether or not to use colors in the debug output. | +| `DEBUG_DEPTH` | Object inspection depth. | +| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | + + + __Note:__ The environment variables beginning with `DEBUG_` end up being + converted into an Options object that gets used with `%o`/`%O` formatters. + See the Node.js documentation for + [`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) + for the complete list. + +## Formatters + + + Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. Below are the officially supported formatters: + +| Formatter | Representation | +|-----------|----------------| +| `%O` | Pretty-print an Object on multiple lines. | +| `%o` | Pretty-print an Object all on a single line. | +| `%s` | String. | +| `%d` | Number (both integer and float). | +| `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | +| `%%` | Single percent sign ('%'). This does not consume an argument. | + +### Custom formatters + + You can add custom formatters by extending the `debug.formatters` object. For example, if you wanted to add support for rendering a Buffer as hex with `%h`, you could do something like: + +```js +const createDebug = require('debug') +createDebug.formatters.h = (v) => { + return v.toString('hex') +} + +// …elsewhere +const debug = createDebug('foo') +debug('this is hex: %h', new Buffer('hello world')) +// foo this is hex: 68656c6c6f20776f726c6421 +0ms +``` + +## Browser support + You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), + or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), + if you don't want to build it yourself. + + Debug's enable state is currently persisted by `localStorage`. + Consider the situation shown below where you have `worker:a` and `worker:b`, + and wish to debug both. You can enable this using `localStorage.debug`: + +```js +localStorage.debug = 'worker:*' +``` + +And then refresh the page. + +```js +a = debug('worker:a'); +b = debug('worker:b'); + +setInterval(function(){ + a('doing some work'); +}, 1000); + +setInterval(function(){ + b('doing some work'); +}, 1200); +``` + +#### Web Inspector Colors + + Colors are also enabled on "Web Inspectors" that understand the `%c` formatting + option. These are WebKit web inspectors, Firefox ([since version + 31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) + and the Firebug plugin for Firefox (any version). + + Colored output looks something like: + + ![](https://cloud.githubusercontent.com/assets/71256/3139768/b98c5fd8-e8ef-11e3-862a-f7253b6f47c6.png) + + +## Output streams + + By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: + +Example _stdout.js_: + +```js +var debug = require('debug'); +var error = debug('app:error'); + +// by default stderr is used +error('goes to stderr!'); + +var log = debug('app:log'); +// set this namespace to log via console.log +log.log = console.log.bind(console); // don't forget to bind to console! +log('goes to stdout'); +error('still goes to stderr!'); + +// set all output to go via console.info +// overrides all per-namespace log settings +debug.log = console.info.bind(console); +error('now goes to stdout via console.info'); +log('still goes to stdout, but via console.info now'); +``` + + +## Authors + + - TJ Holowaychuk + - Nathan Rajlich + - Andrew Rhyne + +## Backers + +Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +## Sponsors + +Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +## License + +(The MIT License) + +Copyright (c) 2014-2016 TJ Holowaychuk <tj@vision-media.ca> + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/debug/component.json b/node_modules/debug/component.json new file mode 100644 index 0000000..9de2641 --- /dev/null +++ b/node_modules/debug/component.json @@ -0,0 +1,19 @@ +{ + "name": "debug", + "repo": "visionmedia/debug", + "description": "small debugging utility", + "version": "2.6.9", + "keywords": [ + "debug", + "log", + "debugger" + ], + "main": "src/browser.js", + "scripts": [ + "src/browser.js", + "src/debug.js" + ], + "dependencies": { + "rauchg/ms.js": "0.7.1" + } +} diff --git a/node_modules/debug/karma.conf.js b/node_modules/debug/karma.conf.js new file mode 100644 index 0000000..103a82d --- /dev/null +++ b/node_modules/debug/karma.conf.js @@ -0,0 +1,70 @@ +// Karma configuration +// Generated on Fri Dec 16 2016 13:09:51 GMT+0000 (UTC) + +module.exports = function(config) { + config.set({ + + // base path that will be used to resolve all patterns (eg. files, exclude) + basePath: '', + + + // frameworks to use + // available frameworks: https://npmjs.org/browse/keyword/karma-adapter + frameworks: ['mocha', 'chai', 'sinon'], + + + // list of files / patterns to load in the browser + files: [ + 'dist/debug.js', + 'test/*spec.js' + ], + + + // list of files to exclude + exclude: [ + 'src/node.js' + ], + + + // preprocess matching files before serving them to the browser + // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor + preprocessors: { + }, + + // test results reporter to use + // possible values: 'dots', 'progress' + // available reporters: https://npmjs.org/browse/keyword/karma-reporter + reporters: ['progress'], + + + // web server port + port: 9876, + + + // enable / disable colors in the output (reporters and logs) + colors: true, + + + // level of logging + // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG + logLevel: config.LOG_INFO, + + + // enable / disable watching file and executing tests whenever any file changes + autoWatch: true, + + + // start these browsers + // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher + browsers: ['PhantomJS'], + + + // Continuous Integration mode + // if true, Karma captures browsers, runs the tests and exits + singleRun: false, + + // Concurrency level + // how many browser should be started simultaneous + concurrency: Infinity + }) +} diff --git a/node_modules/debug/node.js b/node_modules/debug/node.js new file mode 100644 index 0000000..7fc36fe --- /dev/null +++ b/node_modules/debug/node.js @@ -0,0 +1 @@ +module.exports = require('./src/node'); diff --git a/node_modules/debug/package.json b/node_modules/debug/package.json new file mode 100644 index 0000000..dc787ba --- /dev/null +++ b/node_modules/debug/package.json @@ -0,0 +1,49 @@ +{ + "name": "debug", + "version": "2.6.9", + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/debug.git" + }, + "description": "small debugging utility", + "keywords": [ + "debug", + "log", + "debugger" + ], + "author": "TJ Holowaychuk ", + "contributors": [ + "Nathan Rajlich (http://n8.io)", + "Andrew Rhyne " + ], + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + }, + "devDependencies": { + "browserify": "9.0.3", + "chai": "^3.5.0", + "concurrently": "^3.1.0", + "coveralls": "^2.11.15", + "eslint": "^3.12.1", + "istanbul": "^0.4.5", + "karma": "^1.3.0", + "karma-chai": "^0.1.0", + "karma-mocha": "^1.3.0", + "karma-phantomjs-launcher": "^1.0.2", + "karma-sinon": "^1.0.5", + "mocha": "^3.2.0", + "mocha-lcov-reporter": "^1.2.0", + "rimraf": "^2.5.4", + "sinon": "^1.17.6", + "sinon-chai": "^2.8.0" + }, + "main": "./src/index.js", + "browser": "./src/browser.js", + "component": { + "scripts": { + "debug/index.js": "browser.js", + "debug/debug.js": "debug.js" + } + } +} diff --git a/node_modules/debug/src/browser.js b/node_modules/debug/src/browser.js new file mode 100644 index 0000000..7106924 --- /dev/null +++ b/node_modules/debug/src/browser.js @@ -0,0 +1,185 @@ +/** + * This is the web browser implementation of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = require('./debug'); +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = 'undefined' != typeof chrome + && 'undefined' != typeof chrome.storage + ? chrome.storage.local + : localstorage(); + +/** + * Colors. + */ + +exports.colors = [ + 'lightseagreen', + 'forestgreen', + 'goldenrod', + 'dodgerblue', + 'darkorchid', + 'crimson' +]; + +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { + return true; + } + + // is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +exports.formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (err) { + return '[UnexpectedJSONParseError]: ' + err.message; + } +}; + + +/** + * Colorize log arguments if enabled. + * + * @api public + */ + +function formatArgs(args) { + var useColors = this.useColors; + + args[0] = (useColors ? '%c' : '') + + this.namespace + + (useColors ? ' %c' : ' ') + + args[0] + + (useColors ? '%c ' : ' ') + + '+' + exports.humanize(this.diff); + + if (!useColors) return; + + var c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit') + + // the final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + var index = 0; + var lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, function(match) { + if ('%%' === match) return; + index++; + if ('%c' === match) { + // we only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); +} + +/** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public + */ + +function log() { + // this hackery is required for IE8/9, where + // the `console.log` function doesn't have 'apply' + return 'object' === typeof console + && console.log + && Function.prototype.apply.call(console.log, console, arguments); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + try { + if (null == namespaces) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch(e) {} +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + var r; + try { + r = exports.storage.debug; + } catch(e) {} + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; +} + +/** + * Enable namespaces listed in `localStorage.debug` initially. + */ + +exports.enable(load()); + +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + +function localstorage() { + try { + return window.localStorage; + } catch (e) {} +} diff --git a/node_modules/debug/src/debug.js b/node_modules/debug/src/debug.js new file mode 100644 index 0000000..6a5e3fc --- /dev/null +++ b/node_modules/debug/src/debug.js @@ -0,0 +1,202 @@ + +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; +exports.coerce = coerce; +exports.disable = disable; +exports.enable = enable; +exports.enabled = enabled; +exports.humanize = require('ms'); + +/** + * The currently active debug mode names, and names to skip. + */ + +exports.names = []; +exports.skips = []; + +/** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + +exports.formatters = {}; + +/** + * Previous log timestamp. + */ + +var prevTime; + +/** + * Select a color. + * @param {String} namespace + * @return {Number} + * @api private + */ + +function selectColor(namespace) { + var hash = 0, i; + + for (i in namespace) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return exports.colors[Math.abs(hash) % exports.colors.length]; +} + +/** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + +function createDebug(namespace) { + + function debug() { + // disabled? + if (!debug.enabled) return; + + var self = debug; + + // set `diff` timestamp + var curr = +new Date(); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + // turn the `arguments` into a proper Array + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + + args[0] = exports.coerce(args[0]); + + if ('string' !== typeof args[0]) { + // anything else let's inspect with %O + args.unshift('%O'); + } + + // apply any `formatters` transformations + var index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { + // if we encounter an escaped % then don't increase the array index + if (match === '%%') return match; + index++; + var formatter = exports.formatters[format]; + if ('function' === typeof formatter) { + var val = args[index]; + match = formatter.call(self, val); + + // now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // apply env-specific formatting (colors, etc.) + exports.formatArgs.call(self, args); + + var logFn = debug.log || exports.log || console.log.bind(console); + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.enabled = exports.enabled(namespace); + debug.useColors = exports.useColors(); + debug.color = selectColor(namespace); + + // env-specific initialization logic for debug instances + if ('function' === typeof exports.init) { + exports.init(debug); + } + + return debug; +} + +/** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + +function enable(namespaces) { + exports.save(namespaces); + + exports.names = []; + exports.skips = []; + + var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + var len = split.length; + + for (var i = 0; i < len; i++) { + if (!split[i]) continue; // ignore empty strings + namespaces = split[i].replace(/\*/g, '.*?'); + if (namespaces[0] === '-') { + exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + exports.names.push(new RegExp('^' + namespaces + '$')); + } + } +} + +/** + * Disable debug output. + * + * @api public + */ + +function disable() { + exports.enable(''); +} + +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + +function enabled(name) { + var i, len; + for (i = 0, len = exports.skips.length; i < len; i++) { + if (exports.skips[i].test(name)) { + return false; + } + } + for (i = 0, len = exports.names.length; i < len; i++) { + if (exports.names[i].test(name)) { + return true; + } + } + return false; +} + +/** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} diff --git a/node_modules/debug/src/index.js b/node_modules/debug/src/index.js new file mode 100644 index 0000000..e12cf4d --- /dev/null +++ b/node_modules/debug/src/index.js @@ -0,0 +1,10 @@ +/** + * Detect Electron renderer process, which is node, but we should + * treat as a browser. + */ + +if (typeof process !== 'undefined' && process.type === 'renderer') { + module.exports = require('./browser.js'); +} else { + module.exports = require('./node.js'); +} diff --git a/node_modules/debug/src/inspector-log.js b/node_modules/debug/src/inspector-log.js new file mode 100644 index 0000000..60ea6c0 --- /dev/null +++ b/node_modules/debug/src/inspector-log.js @@ -0,0 +1,15 @@ +module.exports = inspectorLog; + +// black hole +const nullStream = new (require('stream').Writable)(); +nullStream._write = () => {}; + +/** + * Outputs a `console.log()` to the Node.js Inspector console *only*. + */ +function inspectorLog() { + const stdout = console._stdout; + console._stdout = nullStream; + console.log.apply(console, arguments); + console._stdout = stdout; +} diff --git a/node_modules/debug/src/node.js b/node_modules/debug/src/node.js new file mode 100644 index 0000000..b15109c --- /dev/null +++ b/node_modules/debug/src/node.js @@ -0,0 +1,248 @@ +/** + * Module dependencies. + */ + +var tty = require('tty'); +var util = require('util'); + +/** + * This is the Node.js implementation of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = require('./debug'); +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; + +/** + * Colors. + */ + +exports.colors = [6, 2, 3, 4, 5, 1]; + +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ + +exports.inspectOpts = Object.keys(process.env).filter(function (key) { + return /^debug_/i.test(key); +}).reduce(function (obj, key) { + // camel-case + var prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); + + // coerce string value into JS value + var val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) val = true; + else if (/^(no|off|false|disabled)$/i.test(val)) val = false; + else if (val === 'null') val = null; + else val = Number(val); + + obj[prop] = val; + return obj; +}, {}); + +/** + * The file descriptor to write the `debug()` calls to. + * Set the `DEBUG_FD` env variable to override with another value. i.e.: + * + * $ DEBUG_FD=3 node script.js 3>debug.log + */ + +var fd = parseInt(process.env.DEBUG_FD, 10) || 2; + +if (1 !== fd && 2 !== fd) { + util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')() +} + +var stream = 1 === fd ? process.stdout : + 2 === fd ? process.stderr : + createWritableStdioStream(fd); + +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + +function useColors() { + return 'colors' in exports.inspectOpts + ? Boolean(exports.inspectOpts.colors) + : tty.isatty(fd); +} + +/** + * Map %o to `util.inspect()`, all on a single line. + */ + +exports.formatters.o = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n').map(function(str) { + return str.trim() + }).join(' '); +}; + +/** + * Map %o to `util.inspect()`, allowing multiple lines if needed. + */ + +exports.formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; + +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ + +function formatArgs(args) { + var name = this.namespace; + var useColors = this.useColors; + + if (useColors) { + var c = this.color; + var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; + + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); + } else { + args[0] = new Date().toUTCString() + + ' ' + name + ' ' + args[0]; + } +} + +/** + * Invokes `util.format()` with the specified arguments and writes to `stream`. + */ + +function log() { + return stream.write(util.format.apply(util, arguments) + '\n'); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + if (null == namespaces) { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } else { + process.env.DEBUG = namespaces; + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + return process.env.DEBUG; +} + +/** + * Copied from `node/src/node.js`. + * + * XXX: It's lame that node doesn't expose this API out-of-the-box. It also + * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. + */ + +function createWritableStdioStream (fd) { + var stream; + var tty_wrap = process.binding('tty_wrap'); + + // Note stream._type is used for test-module-load-list.js + + switch (tty_wrap.guessHandleType(fd)) { + case 'TTY': + stream = new tty.WriteStream(fd); + stream._type = 'tty'; + + // Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; + + case 'FILE': + var fs = require('fs'); + stream = new fs.SyncWriteStream(fd, { autoClose: false }); + stream._type = 'fs'; + break; + + case 'PIPE': + case 'TCP': + var net = require('net'); + stream = new net.Socket({ + fd: fd, + readable: false, + writable: true + }); + + // FIXME Should probably have an option in net.Socket to create a + // stream from an existing fd which is writable only. But for now + // we'll just add this hack and set the `readable` member to false. + // Test: ./node test/fixtures/echo.js < /etc/passwd + stream.readable = false; + stream.read = null; + stream._type = 'pipe'; + + // FIXME Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; + + default: + // Probably an error on in uv_guess_handle() + throw new Error('Implement me. Unknown stream file type!'); + } + + // For supporting legacy API we put the FD here. + stream.fd = fd; + + stream._isStdio = true; + + return stream; +} + +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ + +function init (debug) { + debug.inspectOpts = {}; + + var keys = Object.keys(exports.inspectOpts); + for (var i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} + +/** + * Enable namespaces listed in `process.env.DEBUG` initially. + */ + +exports.enable(load()); diff --git a/node_modules/depd/History.md b/node_modules/depd/History.md new file mode 100644 index 0000000..cd9ebaa --- /dev/null +++ b/node_modules/depd/History.md @@ -0,0 +1,103 @@ +2.0.0 / 2018-10-26 +================== + + * Drop support for Node.js 0.6 + * Replace internal `eval` usage with `Function` constructor + * Use instance methods on `process` to check for listeners + +1.1.2 / 2018-01-11 +================== + + * perf: remove argument reassignment + * Support Node.js 0.6 to 9.x + +1.1.1 / 2017-07-27 +================== + + * Remove unnecessary `Buffer` loading + * Support Node.js 0.6 to 8.x + +1.1.0 / 2015-09-14 +================== + + * Enable strict mode in more places + * Support io.js 3.x + * Support io.js 2.x + * Support web browser loading + - Requires bundler like Browserify or webpack + +1.0.1 / 2015-04-07 +================== + + * Fix `TypeError`s when under `'use strict'` code + * Fix useless type name on auto-generated messages + * Support io.js 1.x + * Support Node.js 0.12 + +1.0.0 / 2014-09-17 +================== + + * No changes + +0.4.5 / 2014-09-09 +================== + + * Improve call speed to functions using the function wrapper + * Support Node.js 0.6 + +0.4.4 / 2014-07-27 +================== + + * Work-around v8 generating empty stack traces + +0.4.3 / 2014-07-26 +================== + + * Fix exception when global `Error.stackTraceLimit` is too low + +0.4.2 / 2014-07-19 +================== + + * Correct call site for wrapped functions and properties + +0.4.1 / 2014-07-19 +================== + + * Improve automatic message generation for function properties + +0.4.0 / 2014-07-19 +================== + + * Add `TRACE_DEPRECATION` environment variable + * Remove non-standard grey color from color output + * Support `--no-deprecation` argument + * Support `--trace-deprecation` argument + * Support `deprecate.property(fn, prop, message)` + +0.3.0 / 2014-06-16 +================== + + * Add `NO_DEPRECATION` environment variable + +0.2.0 / 2014-06-15 +================== + + * Add `deprecate.property(obj, prop, message)` + * Remove `supports-color` dependency for node.js 0.8 + +0.1.0 / 2014-06-15 +================== + + * Add `deprecate.function(fn, message)` + * Add `process.on('deprecation', fn)` emitter + * Automatically generate message when omitted from `deprecate()` + +0.0.1 / 2014-06-15 +================== + + * Fix warning for dynamic calls at singe call site + +0.0.0 / 2014-06-15 +================== + + * Initial implementation diff --git a/node_modules/depd/LICENSE b/node_modules/depd/LICENSE new file mode 100644 index 0000000..248de7a --- /dev/null +++ b/node_modules/depd/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2018 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/depd/Readme.md b/node_modules/depd/Readme.md new file mode 100644 index 0000000..043d1ca --- /dev/null +++ b/node_modules/depd/Readme.md @@ -0,0 +1,280 @@ +# depd + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Linux Build][travis-image]][travis-url] +[![Windows Build][appveyor-image]][appveyor-url] +[![Coverage Status][coveralls-image]][coveralls-url] + +Deprecate all the things + +> With great modules comes great responsibility; mark things deprecated! + +## Install + +This module is installed directly using `npm`: + +```sh +$ npm install depd +``` + +This module can also be bundled with systems like +[Browserify](http://browserify.org/) or [webpack](https://webpack.github.io/), +though by default this module will alter it's API to no longer display or +track deprecations. + +## API + + + +```js +var deprecate = require('depd')('my-module') +``` + +This library allows you to display deprecation messages to your users. +This library goes above and beyond with deprecation warnings by +introspection of the call stack (but only the bits that it is interested +in). + +Instead of just warning on the first invocation of a deprecated +function and never again, this module will warn on the first invocation +of a deprecated function per unique call site, making it ideal to alert +users of all deprecated uses across the code base, rather than just +whatever happens to execute first. + +The deprecation warnings from this module also include the file and line +information for the call into the module that the deprecated function was +in. + +**NOTE** this library has a similar interface to the `debug` module, and +this module uses the calling file to get the boundary for the call stacks, +so you should always create a new `deprecate` object in each file and not +within some central file. + +### depd(namespace) + +Create a new deprecate function that uses the given namespace name in the +messages and will display the call site prior to the stack entering the +file this function was called from. It is highly suggested you use the +name of your module as the namespace. + +### deprecate(message) + +Call this function from deprecated code to display a deprecation message. +This message will appear once per unique caller site. Caller site is the +first call site in the stack in a different file from the caller of this +function. + +If the message is omitted, a message is generated for you based on the site +of the `deprecate()` call and will display the name of the function called, +similar to the name displayed in a stack trace. + +### deprecate.function(fn, message) + +Call this function to wrap a given function in a deprecation message on any +call to the function. An optional message can be supplied to provide a custom +message. + +### deprecate.property(obj, prop, message) + +Call this function to wrap a given property on object in a deprecation message +on any accessing or setting of the property. An optional message can be supplied +to provide a custom message. + +The method must be called on the object where the property belongs (not +inherited from the prototype). + +If the property is a data descriptor, it will be converted to an accessor +descriptor in order to display the deprecation message. + +### process.on('deprecation', fn) + +This module will allow easy capturing of deprecation errors by emitting the +errors as the type "deprecation" on the global `process`. If there are no +listeners for this type, the errors are written to STDERR as normal, but if +there are any listeners, nothing will be written to STDERR and instead only +emitted. From there, you can write the errors in a different format or to a +logging source. + +The error represents the deprecation and is emitted only once with the same +rules as writing to STDERR. The error has the following properties: + + - `message` - This is the message given by the library + - `name` - This is always `'DeprecationError'` + - `namespace` - This is the namespace the deprecation came from + - `stack` - This is the stack of the call to the deprecated thing + +Example `error.stack` output: + +``` +DeprecationError: my-cool-module deprecated oldfunction + at Object. ([eval]-wrapper:6:22) + at Module._compile (module.js:456:26) + at evalScript (node.js:532:25) + at startup (node.js:80:7) + at node.js:902:3 +``` + +### process.env.NO_DEPRECATION + +As a user of modules that are deprecated, the environment variable `NO_DEPRECATION` +is provided as a quick solution to silencing deprecation warnings from being +output. The format of this is similar to that of `DEBUG`: + +```sh +$ NO_DEPRECATION=my-module,othermod node app.js +``` + +This will suppress deprecations from being output for "my-module" and "othermod". +The value is a list of comma-separated namespaces. To suppress every warning +across all namespaces, use the value `*` for a namespace. + +Providing the argument `--no-deprecation` to the `node` executable will suppress +all deprecations (only available in Node.js 0.8 or higher). + +**NOTE** This will not suppress the deperecations given to any "deprecation" +event listeners, just the output to STDERR. + +### process.env.TRACE_DEPRECATION + +As a user of modules that are deprecated, the environment variable `TRACE_DEPRECATION` +is provided as a solution to getting more detailed location information in deprecation +warnings by including the entire stack trace. The format of this is the same as +`NO_DEPRECATION`: + +```sh +$ TRACE_DEPRECATION=my-module,othermod node app.js +``` + +This will include stack traces for deprecations being output for "my-module" and +"othermod". The value is a list of comma-separated namespaces. To trace every +warning across all namespaces, use the value `*` for a namespace. + +Providing the argument `--trace-deprecation` to the `node` executable will trace +all deprecations (only available in Node.js 0.8 or higher). + +**NOTE** This will not trace the deperecations silenced by `NO_DEPRECATION`. + +## Display + +![message](files/message.png) + +When a user calls a function in your library that you mark deprecated, they +will see the following written to STDERR (in the given colors, similar colors +and layout to the `debug` module): + +``` +bright cyan bright yellow +| | reset cyan +| | | | +▼ ▼ ▼ ▼ +my-cool-module deprecated oldfunction [eval]-wrapper:6:22 +▲ ▲ ▲ ▲ +| | | | +namespace | | location of mycoolmod.oldfunction() call + | deprecation message + the word "deprecated" +``` + +If the user redirects their STDERR to a file or somewhere that does not support +colors, they see (similar layout to the `debug` module): + +``` +Sun, 15 Jun 2014 05:21:37 GMT my-cool-module deprecated oldfunction at [eval]-wrapper:6:22 +▲ ▲ ▲ ▲ ▲ +| | | | | +timestamp of message namespace | | location of mycoolmod.oldfunction() call + | deprecation message + the word "deprecated" +``` + +## Examples + +### Deprecating all calls to a function + +This will display a deprecated message about "oldfunction" being deprecated +from "my-module" on STDERR. + +```js +var deprecate = require('depd')('my-cool-module') + +// message automatically derived from function name +// Object.oldfunction +exports.oldfunction = deprecate.function(function oldfunction () { + // all calls to function are deprecated +}) + +// specific message +exports.oldfunction = deprecate.function(function () { + // all calls to function are deprecated +}, 'oldfunction') +``` + +### Conditionally deprecating a function call + +This will display a deprecated message about "weirdfunction" being deprecated +from "my-module" on STDERR when called with less than 2 arguments. + +```js +var deprecate = require('depd')('my-cool-module') + +exports.weirdfunction = function () { + if (arguments.length < 2) { + // calls with 0 or 1 args are deprecated + deprecate('weirdfunction args < 2') + } +} +``` + +When calling `deprecate` as a function, the warning is counted per call site +within your own module, so you can display different deprecations depending +on different situations and the users will still get all the warnings: + +```js +var deprecate = require('depd')('my-cool-module') + +exports.weirdfunction = function () { + if (arguments.length < 2) { + // calls with 0 or 1 args are deprecated + deprecate('weirdfunction args < 2') + } else if (typeof arguments[0] !== 'string') { + // calls with non-string first argument are deprecated + deprecate('weirdfunction non-string first arg') + } +} +``` + +### Deprecating property access + +This will display a deprecated message about "oldprop" being deprecated +from "my-module" on STDERR when accessed. A deprecation will be displayed +when setting the value and when getting the value. + +```js +var deprecate = require('depd')('my-cool-module') + +exports.oldprop = 'something' + +// message automatically derives from property name +deprecate.property(exports, 'oldprop') + +// explicit message +deprecate.property(exports, 'oldprop', 'oldprop >= 0.10') +``` + +## License + +[MIT](LICENSE) + +[appveyor-image]: https://badgen.net/appveyor/ci/dougwilson/nodejs-depd/master?label=windows +[appveyor-url]: https://ci.appveyor.com/project/dougwilson/nodejs-depd +[coveralls-image]: https://badgen.net/coveralls/c/github/dougwilson/nodejs-depd/master +[coveralls-url]: https://coveralls.io/r/dougwilson/nodejs-depd?branch=master +[node-image]: https://badgen.net/npm/node/depd +[node-url]: https://nodejs.org/en/download/ +[npm-downloads-image]: https://badgen.net/npm/dm/depd +[npm-url]: https://npmjs.org/package/depd +[npm-version-image]: https://badgen.net/npm/v/depd +[travis-image]: https://badgen.net/travis/dougwilson/nodejs-depd/master?label=linux +[travis-url]: https://travis-ci.org/dougwilson/nodejs-depd diff --git a/node_modules/depd/index.js b/node_modules/depd/index.js new file mode 100644 index 0000000..1bf2fcf --- /dev/null +++ b/node_modules/depd/index.js @@ -0,0 +1,538 @@ +/*! + * depd + * Copyright(c) 2014-2018 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var relative = require('path').relative + +/** + * Module exports. + */ + +module.exports = depd + +/** + * Get the path to base files on. + */ + +var basePath = process.cwd() + +/** + * Determine if namespace is contained in the string. + */ + +function containsNamespace (str, namespace) { + var vals = str.split(/[ ,]+/) + var ns = String(namespace).toLowerCase() + + for (var i = 0; i < vals.length; i++) { + var val = vals[i] + + // namespace contained + if (val && (val === '*' || val.toLowerCase() === ns)) { + return true + } + } + + return false +} + +/** + * Convert a data descriptor to accessor descriptor. + */ + +function convertDataDescriptorToAccessor (obj, prop, message) { + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + var value = descriptor.value + + descriptor.get = function getter () { return value } + + if (descriptor.writable) { + descriptor.set = function setter (val) { return (value = val) } + } + + delete descriptor.value + delete descriptor.writable + + Object.defineProperty(obj, prop, descriptor) + + return descriptor +} + +/** + * Create arguments string to keep arity. + */ + +function createArgumentsString (arity) { + var str = '' + + for (var i = 0; i < arity; i++) { + str += ', arg' + i + } + + return str.substr(2) +} + +/** + * Create stack string from stack. + */ + +function createStackString (stack) { + var str = this.name + ': ' + this.namespace + + if (this.message) { + str += ' deprecated ' + this.message + } + + for (var i = 0; i < stack.length; i++) { + str += '\n at ' + stack[i].toString() + } + + return str +} + +/** + * Create deprecate for namespace in caller. + */ + +function depd (namespace) { + if (!namespace) { + throw new TypeError('argument namespace is required') + } + + var stack = getStack() + var site = callSiteLocation(stack[1]) + var file = site[0] + + function deprecate (message) { + // call to self as log + log.call(deprecate, message) + } + + deprecate._file = file + deprecate._ignored = isignored(namespace) + deprecate._namespace = namespace + deprecate._traced = istraced(namespace) + deprecate._warned = Object.create(null) + + deprecate.function = wrapfunction + deprecate.property = wrapproperty + + return deprecate +} + +/** + * Determine if event emitter has listeners of a given type. + * + * The way to do this check is done three different ways in Node.js >= 0.8 + * so this consolidates them into a minimal set using instance methods. + * + * @param {EventEmitter} emitter + * @param {string} type + * @returns {boolean} + * @private + */ + +function eehaslisteners (emitter, type) { + var count = typeof emitter.listenerCount !== 'function' + ? emitter.listeners(type).length + : emitter.listenerCount(type) + + return count > 0 +} + +/** + * Determine if namespace is ignored. + */ + +function isignored (namespace) { + if (process.noDeprecation) { + // --no-deprecation support + return true + } + + var str = process.env.NO_DEPRECATION || '' + + // namespace ignored + return containsNamespace(str, namespace) +} + +/** + * Determine if namespace is traced. + */ + +function istraced (namespace) { + if (process.traceDeprecation) { + // --trace-deprecation support + return true + } + + var str = process.env.TRACE_DEPRECATION || '' + + // namespace traced + return containsNamespace(str, namespace) +} + +/** + * Display deprecation message. + */ + +function log (message, site) { + var haslisteners = eehaslisteners(process, 'deprecation') + + // abort early if no destination + if (!haslisteners && this._ignored) { + return + } + + var caller + var callFile + var callSite + var depSite + var i = 0 + var seen = false + var stack = getStack() + var file = this._file + + if (site) { + // provided site + depSite = site + callSite = callSiteLocation(stack[1]) + callSite.name = depSite.name + file = callSite[0] + } else { + // get call site + i = 2 + depSite = callSiteLocation(stack[i]) + callSite = depSite + } + + // get caller of deprecated thing in relation to file + for (; i < stack.length; i++) { + caller = callSiteLocation(stack[i]) + callFile = caller[0] + + if (callFile === file) { + seen = true + } else if (callFile === this._file) { + file = this._file + } else if (seen) { + break + } + } + + var key = caller + ? depSite.join(':') + '__' + caller.join(':') + : undefined + + if (key !== undefined && key in this._warned) { + // already warned + return + } + + this._warned[key] = true + + // generate automatic message from call site + var msg = message + if (!msg) { + msg = callSite === depSite || !callSite.name + ? defaultMessage(depSite) + : defaultMessage(callSite) + } + + // emit deprecation if listeners exist + if (haslisteners) { + var err = DeprecationError(this._namespace, msg, stack.slice(i)) + process.emit('deprecation', err) + return + } + + // format and write message + var format = process.stderr.isTTY + ? formatColor + : formatPlain + var output = format.call(this, msg, caller, stack.slice(i)) + process.stderr.write(output + '\n', 'utf8') +} + +/** + * Get call site location as array. + */ + +function callSiteLocation (callSite) { + var file = callSite.getFileName() || '' + var line = callSite.getLineNumber() + var colm = callSite.getColumnNumber() + + if (callSite.isEval()) { + file = callSite.getEvalOrigin() + ', ' + file + } + + var site = [file, line, colm] + + site.callSite = callSite + site.name = callSite.getFunctionName() + + return site +} + +/** + * Generate a default message from the site. + */ + +function defaultMessage (site) { + var callSite = site.callSite + var funcName = site.name + + // make useful anonymous name + if (!funcName) { + funcName = '' + } + + var context = callSite.getThis() + var typeName = context && callSite.getTypeName() + + // ignore useless type name + if (typeName === 'Object') { + typeName = undefined + } + + // make useful type name + if (typeName === 'Function') { + typeName = context.name || typeName + } + + return typeName && callSite.getMethodName() + ? typeName + '.' + funcName + : funcName +} + +/** + * Format deprecation message without color. + */ + +function formatPlain (msg, caller, stack) { + var timestamp = new Date().toUTCString() + + var formatted = timestamp + + ' ' + this._namespace + + ' deprecated ' + msg + + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n at ' + stack[i].toString() + } + + return formatted + } + + if (caller) { + formatted += ' at ' + formatLocation(caller) + } + + return formatted +} + +/** + * Format deprecation message with color. + */ + +function formatColor (msg, caller, stack) { + var formatted = '\x1b[36;1m' + this._namespace + '\x1b[22;39m' + // bold cyan + ' \x1b[33;1mdeprecated\x1b[22;39m' + // bold yellow + ' \x1b[0m' + msg + '\x1b[39m' // reset + + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n \x1b[36mat ' + stack[i].toString() + '\x1b[39m' // cyan + } + + return formatted + } + + if (caller) { + formatted += ' \x1b[36m' + formatLocation(caller) + '\x1b[39m' // cyan + } + + return formatted +} + +/** + * Format call site location. + */ + +function formatLocation (callSite) { + return relative(basePath, callSite[0]) + + ':' + callSite[1] + + ':' + callSite[2] +} + +/** + * Get the stack as array of call sites. + */ + +function getStack () { + var limit = Error.stackTraceLimit + var obj = {} + var prep = Error.prepareStackTrace + + Error.prepareStackTrace = prepareObjectStackTrace + Error.stackTraceLimit = Math.max(10, limit) + + // capture the stack + Error.captureStackTrace(obj) + + // slice this function off the top + var stack = obj.stack.slice(1) + + Error.prepareStackTrace = prep + Error.stackTraceLimit = limit + + return stack +} + +/** + * Capture call site stack from v8. + */ + +function prepareObjectStackTrace (obj, stack) { + return stack +} + +/** + * Return a wrapped function in a deprecation message. + */ + +function wrapfunction (fn, message) { + if (typeof fn !== 'function') { + throw new TypeError('argument fn must be a function') + } + + var args = createArgumentsString(fn.length) + var stack = getStack() + var site = callSiteLocation(stack[1]) + + site.name = fn.name + + // eslint-disable-next-line no-new-func + var deprecatedfn = new Function('fn', 'log', 'deprecate', 'message', 'site', + '"use strict"\n' + + 'return function (' + args + ') {' + + 'log.call(deprecate, message, site)\n' + + 'return fn.apply(this, arguments)\n' + + '}')(fn, log, this, message, site) + + return deprecatedfn +} + +/** + * Wrap property in a deprecation message. + */ + +function wrapproperty (obj, prop, message) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new TypeError('argument obj must be object') + } + + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + + if (!descriptor) { + throw new TypeError('must call property on owner object') + } + + if (!descriptor.configurable) { + throw new TypeError('property must be configurable') + } + + var deprecate = this + var stack = getStack() + var site = callSiteLocation(stack[1]) + + // set site name + site.name = prop + + // convert data descriptor + if ('value' in descriptor) { + descriptor = convertDataDescriptorToAccessor(obj, prop, message) + } + + var get = descriptor.get + var set = descriptor.set + + // wrap getter + if (typeof get === 'function') { + descriptor.get = function getter () { + log.call(deprecate, message, site) + return get.apply(this, arguments) + } + } + + // wrap setter + if (typeof set === 'function') { + descriptor.set = function setter () { + log.call(deprecate, message, site) + return set.apply(this, arguments) + } + } + + Object.defineProperty(obj, prop, descriptor) +} + +/** + * Create DeprecationError for deprecation + */ + +function DeprecationError (namespace, message, stack) { + var error = new Error() + var stackString + + Object.defineProperty(error, 'constructor', { + value: DeprecationError + }) + + Object.defineProperty(error, 'message', { + configurable: true, + enumerable: false, + value: message, + writable: true + }) + + Object.defineProperty(error, 'name', { + enumerable: false, + configurable: true, + value: 'DeprecationError', + writable: true + }) + + Object.defineProperty(error, 'namespace', { + configurable: true, + enumerable: false, + value: namespace, + writable: true + }) + + Object.defineProperty(error, 'stack', { + configurable: true, + enumerable: false, + get: function () { + if (stackString !== undefined) { + return stackString + } + + // prepare stack trace + return (stackString = createStackString.call(this, stack)) + }, + set: function setter (val) { + stackString = val + } + }) + + return error +} diff --git a/node_modules/depd/lib/browser/index.js b/node_modules/depd/lib/browser/index.js new file mode 100644 index 0000000..6be45cc --- /dev/null +++ b/node_modules/depd/lib/browser/index.js @@ -0,0 +1,77 @@ +/*! + * depd + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = depd + +/** + * Create deprecate for namespace in caller. + */ + +function depd (namespace) { + if (!namespace) { + throw new TypeError('argument namespace is required') + } + + function deprecate (message) { + // no-op in browser + } + + deprecate._file = undefined + deprecate._ignored = true + deprecate._namespace = namespace + deprecate._traced = false + deprecate._warned = Object.create(null) + + deprecate.function = wrapfunction + deprecate.property = wrapproperty + + return deprecate +} + +/** + * Return a wrapped function in a deprecation message. + * + * This is a no-op version of the wrapper, which does nothing but call + * validation. + */ + +function wrapfunction (fn, message) { + if (typeof fn !== 'function') { + throw new TypeError('argument fn must be a function') + } + + return fn +} + +/** + * Wrap property in a deprecation message. + * + * This is a no-op version of the wrapper, which does nothing but call + * validation. + */ + +function wrapproperty (obj, prop, message) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new TypeError('argument obj must be object') + } + + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + + if (!descriptor) { + throw new TypeError('must call property on owner object') + } + + if (!descriptor.configurable) { + throw new TypeError('property must be configurable') + } +} diff --git a/node_modules/depd/package.json b/node_modules/depd/package.json new file mode 100644 index 0000000..3857e19 --- /dev/null +++ b/node_modules/depd/package.json @@ -0,0 +1,45 @@ +{ + "name": "depd", + "description": "Deprecate all the things", + "version": "2.0.0", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "keywords": [ + "deprecate", + "deprecated" + ], + "repository": "dougwilson/nodejs-depd", + "browser": "lib/browser/index.js", + "devDependencies": { + "benchmark": "2.1.4", + "beautify-benchmark": "0.2.4", + "eslint": "5.7.0", + "eslint-config-standard": "12.0.0", + "eslint-plugin-import": "2.14.0", + "eslint-plugin-markdown": "1.0.0-beta.7", + "eslint-plugin-node": "7.0.1", + "eslint-plugin-promise": "4.0.1", + "eslint-plugin-standard": "4.0.0", + "istanbul": "0.4.5", + "mocha": "5.2.0", + "safe-buffer": "5.1.2", + "uid-safe": "2.1.5" + }, + "files": [ + "lib/", + "History.md", + "LICENSE", + "index.js", + "Readme.md" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --bail test/", + "test-ci": "istanbul cover --print=none node_modules/mocha/bin/_mocha -- --reporter spec test/ && istanbul report lcovonly text-summary", + "test-cov": "istanbul cover --print=none node_modules/mocha/bin/_mocha -- --reporter dot test/ && istanbul report lcov text-summary" + } +} diff --git a/node_modules/ee-first/LICENSE b/node_modules/ee-first/LICENSE new file mode 100644 index 0000000..a7ae8ee --- /dev/null +++ b/node_modules/ee-first/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/ee-first/README.md b/node_modules/ee-first/README.md new file mode 100644 index 0000000..cbd2478 --- /dev/null +++ b/node_modules/ee-first/README.md @@ -0,0 +1,80 @@ +# EE First + +[![NPM version][npm-image]][npm-url] +[![Build status][travis-image]][travis-url] +[![Test coverage][coveralls-image]][coveralls-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] +[![Gittip][gittip-image]][gittip-url] + +Get the first event in a set of event emitters and event pairs, +then clean up after itself. + +## Install + +```sh +$ npm install ee-first +``` + +## API + +```js +var first = require('ee-first') +``` + +### first(arr, listener) + +Invoke `listener` on the first event from the list specified in `arr`. `arr` is +an array of arrays, with each array in the format `[ee, ...event]`. `listener` +will be called only once, the first time any of the given events are emitted. If +`error` is one of the listened events, then if that fires first, the `listener` +will be given the `err` argument. + +The `listener` is invoked as `listener(err, ee, event, args)`, where `err` is the +first argument emitted from an `error` event, if applicable; `ee` is the event +emitter that fired; `event` is the string event name that fired; and `args` is an +array of the arguments that were emitted on the event. + +```js +var ee1 = new EventEmitter() +var ee2 = new EventEmitter() + +first([ + [ee1, 'close', 'end', 'error'], + [ee2, 'error'] +], function (err, ee, event, args) { + // listener invoked +}) +``` + +#### .cancel() + +The group of listeners can be cancelled before being invoked and have all the event +listeners removed from the underlying event emitters. + +```js +var thunk = first([ + [ee1, 'close', 'end', 'error'], + [ee2, 'error'] +], function (err, ee, event, args) { + // listener invoked +}) + +// cancel and clean up +thunk.cancel() +``` + +[npm-image]: https://img.shields.io/npm/v/ee-first.svg?style=flat-square +[npm-url]: https://npmjs.org/package/ee-first +[github-tag]: http://img.shields.io/github/tag/jonathanong/ee-first.svg?style=flat-square +[github-url]: https://github.com/jonathanong/ee-first/tags +[travis-image]: https://img.shields.io/travis/jonathanong/ee-first.svg?style=flat-square +[travis-url]: https://travis-ci.org/jonathanong/ee-first +[coveralls-image]: https://img.shields.io/coveralls/jonathanong/ee-first.svg?style=flat-square +[coveralls-url]: https://coveralls.io/r/jonathanong/ee-first?branch=master +[license-image]: http://img.shields.io/npm/l/ee-first.svg?style=flat-square +[license-url]: LICENSE.md +[downloads-image]: http://img.shields.io/npm/dm/ee-first.svg?style=flat-square +[downloads-url]: https://npmjs.org/package/ee-first +[gittip-image]: https://img.shields.io/gittip/jonathanong.svg?style=flat-square +[gittip-url]: https://www.gittip.com/jonathanong/ diff --git a/node_modules/ee-first/index.js b/node_modules/ee-first/index.js new file mode 100644 index 0000000..501287c --- /dev/null +++ b/node_modules/ee-first/index.js @@ -0,0 +1,95 @@ +/*! + * ee-first + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = first + +/** + * Get the first event in a set of event emitters and event pairs. + * + * @param {array} stuff + * @param {function} done + * @public + */ + +function first(stuff, done) { + if (!Array.isArray(stuff)) + throw new TypeError('arg must be an array of [ee, events...] arrays') + + var cleanups = [] + + for (var i = 0; i < stuff.length; i++) { + var arr = stuff[i] + + if (!Array.isArray(arr) || arr.length < 2) + throw new TypeError('each array member must be [ee, events...]') + + var ee = arr[0] + + for (var j = 1; j < arr.length; j++) { + var event = arr[j] + var fn = listener(event, callback) + + // listen to the event + ee.on(event, fn) + // push this listener to the list of cleanups + cleanups.push({ + ee: ee, + event: event, + fn: fn, + }) + } + } + + function callback() { + cleanup() + done.apply(null, arguments) + } + + function cleanup() { + var x + for (var i = 0; i < cleanups.length; i++) { + x = cleanups[i] + x.ee.removeListener(x.event, x.fn) + } + } + + function thunk(fn) { + done = fn + } + + thunk.cancel = cleanup + + return thunk +} + +/** + * Create the event listener. + * @private + */ + +function listener(event, done) { + return function onevent(arg1) { + var args = new Array(arguments.length) + var ee = this + var err = event === 'error' + ? arg1 + : null + + // copy args to prevent arguments escaping scope + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } + + done(err, ee, event, args) + } +} diff --git a/node_modules/ee-first/package.json b/node_modules/ee-first/package.json new file mode 100644 index 0000000..b6d0b7d --- /dev/null +++ b/node_modules/ee-first/package.json @@ -0,0 +1,29 @@ +{ + "name": "ee-first", + "description": "return the first event in a set of ee/event pairs", + "version": "1.1.1", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com", + "twitter": "https://twitter.com/jongleberry" + }, + "contributors": [ + "Douglas Christopher Wilson " + ], + "license": "MIT", + "repository": "jonathanong/ee-first", + "devDependencies": { + "istanbul": "0.3.9", + "mocha": "2.2.5" + }, + "files": [ + "index.js", + "LICENSE" + ], + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + } +} diff --git a/node_modules/helmet/CHANGELOG.md b/node_modules/helmet/CHANGELOG.md new file mode 100644 index 0000000..0b776e0 --- /dev/null +++ b/node_modules/helmet/CHANGELOG.md @@ -0,0 +1,968 @@ +# Changelog + +## 8.0.0 + +### Changed + +- **Breaking:** `Strict-Transport-Security` now has a max-age of 365 days, up from 180 +- **Breaking:** `Content-Security-Policy` middleware now throws an error if a directive should have quotes but does not, such as `self` instead of `'self'`. See [#454](https://github.com/helmetjs/helmet/issues/454) +- **Breaking:** `Content-Security-Policy`'s `getDefaultDirectives` now returns a deep copy. This only affects users who were mutating the result +- **Breaking:** `Strict-Transport-Security` now throws an error when "includeSubDomains" option is misspelled. This was previously a warning + +### Removed + +- **Breaking:** Drop support for Node 16 and 17. Node 18+ is now required + +## 7.2.0 - 2024-09-28 + +### Changed + +- `Content-Security-Policy` middleware now warns if a directive should have quotes but does not, such as `self` instead of `'self'`. This will be an error in future versions. See [#454](https://github.com/helmetjs/helmet/issues/454) + +## 7.1.0 - 2023-11-07 + +### Added + +- `helmet.crossOriginEmbedderPolicy` now supports the `unsafe-none` directive. See [#477](https://github.com/helmetjs/helmet/pull/447) + +## 7.0.0 - 2023-05-06 + +### Changed + +- **Breaking:** `Cross-Origin-Embedder-Policy` middleware is now disabled by default. See [#411](https://github.com/helmetjs/helmet/issues/411) + +### Removed + +- **Breaking:** Drop support for Node 14 and 15. Node 16+ is now required +- **Breaking:** `Expect-CT` is no longer part of Helmet. If you still need it, you can use the [`expect-ct` package](https://www.npmjs.com/package/expect-ct). See [#378](https://github.com/helmetjs/helmet/issues/378) + +## 6.2.0 - 2023-05-06 + +- Expose header names (e.g., `strictTransportSecurity` for the `Strict-Transport-Security` header, instead of `hsts`) +- Rework documentation + +## 6.1.5 - 2023-04-11 + +### Fixed + +- Fixed yet another issue with TypeScript exports. See [#420](https://github.com/helmetjs/helmet/pull/418) + +## 6.1.4 - 2023-04-10 + +### Fixed + +- Fix another issue with TypeScript default exports. See [#418](https://github.com/helmetjs/helmet/pull/418) + +## 6.1.3 - 2023-04-10 + +### Fixed + +- Fix issue with TypeScript default exports. See [#417](https://github.com/helmetjs/helmet/pull/417) + +## 6.1.2 - 2023-04-09 + +### Fixed + +- Retored `main` to package to help with some build tools + +## 6.1.1 - 2023-04-08 + +### Fixed + +- Fixed missing package metadata + +## 6.1.0 - 2023-04-08 + +### Changed + +- Improve support for various TypeScript setups, including "nodenext". See [#405](https://github.com/helmetjs/helmet/pull/405) + +## 6.0.1 - 2022-11-29 + +### Fixed + +- `crossOriginEmbedderPolicy` did not accept options at the top level. See [#390](https://github.com/helmetjs/helmet/issues/390) + +## 6.0.0 - 2022-08-26 + +### Changed + +- **Breaking:** `helmet.contentSecurityPolicy` no longer sets `block-all-mixed-content` directive by default +- **Breaking:** `helmet.expectCt` is no longer set by default. It can, however, be explicitly enabled. It will be removed in Helmet 7. See [#310](https://github.com/helmetjs/helmet/issues/310) +- **Breaking:** Increase TypeScript strictness around some arguments. Only affects TypeScript users, and may not require any code changes. See [#369](https://github.com/helmetjs/helmet/issues/369) +- `helmet.frameguard` no longer offers a specific error when trying to use `ALLOW-FROM`; it just says that it is unsupported. Only the error message has changed + +### Removed + +- **Breaking:** Dropped support for Node 12 and 13. Node 14+ is now required + +## 5.1.1 - 2022-07-23 + +### Changed + +- Fix TypeScript bug with some TypeScript configurations. See [#375](https://github.com/helmetjs/helmet/pull/375) and [#359](https://github.com/helmetjs/helmet/issues/359) + +## 5.1.0 - 2022-05-17 + +### Added + +- `Cross-Origin-Embedder-Policy`: support `credentialless` policy. See [#365](https://github.com/helmetjs/helmet/pull/365) +- Documented how to set both `Content-Security-Policy` and `Content-Security-Policy-Report-Only` + +### Changed + +- Cleaned up some documentation around `Origin-Agent-Cluster` + +## 5.0.2 - 2022-01-22 + +### Changed + +- Improve imports for CommonJS and ECMAScript modules. See [#345](https://github.com/helmetjs/helmet/pull/345) +- Fixed some documentation + +## 5.0.1 - 2022-01-03 + +### Changed + +- Fixed some documentation + +### Removed + +- Removed some unused internal code + +## 5.0.0 - 2022-01-02 + +### Added + +- ECMAScript module imports (i.e., `import helmet from "helmet"` and `import { frameguard } from "helmet"`). See [#320](https://github.com/helmetjs/helmet/issues/320) + +### Changed + +- **Breaking:** `helmet.contentSecurityPolicy`: `useDefaults` option now defaults to `true` +- **Breaking:** `helmet.contentSecurityPolicy`: `form-action` directive is now set to `'self'` by default +- **Breaking:** `helmet.crossOriginEmbedderPolicy` is enabled by default +- **Breaking:** `helmet.crossOriginOpenerPolicy` is enabled by default +- **Breaking:** `helmet.crossOriginResourcePolicy` is enabled by default +- **Breaking:** `helmet.originAgentCluster` is enabled by default +- `helmet.frameguard`: add TypeScript editor autocomplete. See [#322](https://github.com/helmetjs/helmet/pull/322) +- Top-level `helmet()` function is slightly faster + +### Removed + +- **Breaking:** Drop support for Node 10 and 11. Node 12+ is now required + +## 4.6.0 - 2021-05-01 + +### Added + +- `helmet.contentSecurityPolicy`: the `useDefaults` option, defaulting to `false`, lets you selectively override defaults more easily +- Explicitly define TypeScript types in `package.json`. See [#303](https://github.com/helmetjs/helmet/pull/303) + +## 4.5.0 - 2021-04-17 + +### Added + +- `helmet.crossOriginEmbedderPolicy`: a new middleware for the `Cross-Origin-Embedder-Policy` header, disabled by default +- `helmet.crossOriginOpenerPolicy`: a new middleware for the `Cross-Origin-Opener-Policy` header, disabled by default +- `helmet.crossOriginResourcePolicy`: a new middleware for the `Cross-Origin-Resource-Policy` header, disabled by default + +### Changed + +- `true` enables a middleware with default options. Previously, this would fail with an error if the middleware was already enabled by default. +- Log a warning when passing options to `originAgentCluster` at the top level + +### Fixed + +- Incorrect documentation + +## 4.4.1 - 2021-01-18 + +### Changed + +- Shrink the published package by about 2.5 kB + +## 4.4.0 - 2021-01-17 + +### Added + +- `helmet.originAgentCluster`: a new middleware for the `Origin-Agent-Cluster` header, disabled by default + +## 4.3.1 - 2020-12-27 + +### Fixed + +- `helmet.contentSecurityPolicy`: broken TypeScript types. See [#283](https://github.com/helmetjs/helmet/issues/283) + +## 4.3.0 - 2020-12-27 + +### Added + +- `helmet.contentSecurityPolicy`: setting the `default-src` to `helmet.contentSecurityPolicy.dangerouslyDisableDefaultSrc` disables it + +### Changed + +- `helmet.frameguard`: slightly improved error messages for non-strings + +## 4.2.0 - 2020-11-01 + +### Added + +- `helmet.contentSecurityPolicy`: get the default directives with `contentSecurityPolicy.getDefaultDirectives()` + +### Changed + +- `helmet()` now supports objects that don't have `Object.prototype` in their chain, such as `Object.create(null)`, as options +- `helmet.expectCt`: `max-age` is now first. See [#264](https://github.com/helmetjs/helmet/pull/264) + +## 4.1.1 - 2020-09-10 + +### Changed + +- Fixed a few errors in the README + +## 4.1.0 - 2020-08-15 + +### Added + +- `helmet.contentSecurityPolicy`: + - Directive values can now include functions, as they could in Helmet 3. See [#243](https://github.com/helmetjs/helmet/issues/243) + +### Changed + +- Helmet should now play more nicely with TypeScript + +### Removed + +- The `HelmetOptions` interface is no longer exported. This only affects TypeScript users. If you need the functionality back, see [this comment](https://github.com/helmetjs/helmet/issues/235#issuecomment-674016883) + +## 4.0.0 - 2020-08-02 + +See the [Helmet 4 upgrade guide](https://github.com/helmetjs/helmet/wiki/Helmet-4-upgrade-guide) for help upgrading from Helmet 3. + +### Added + +- `helmet.contentSecurityPolicy`: + - If no `default-src` directive is supplied, an error is thrown + - Directive lists can be any iterable, not just arrays + +### Changed + +- This package no longer has dependencies. This should have no effect on end users, other than speeding up installation time. +- `helmet.contentSecurityPolicy`: + - There is now a default set of directives if none are supplied + - Duplicate keys now throw an error. See [helmetjs/csp#73](https://github.com/helmetjs/csp/issues/73) + - This middleware is more lenient, allowing more directive names or values +- `helmet.xssFilter` now disables the buggy XSS filter by default. See [#230](https://github.com/helmetjs/helmet/issues/230) + +### Removed + +- Dropped support for old Node versions. Node 10+ is now required +- `helmet.featurePolicy`. If you still need it, use the `feature-policy` package on npm. +- `helmet.hpkp`. If you still need it, use the `hpkp` package on npm. +- `helmet.noCache`. If you still need it, use the `nocache` package on npm. +- `helmet.contentSecurityPolicy`: + - Removed browser sniffing (including the `browserSniff` and `disableAndroid` parameters). See [helmetjs/csp#97](https://github.com/helmetjs/csp/issues/97) + - Removed conditional support. This includes directive functions and support for a function as the `reportOnly`. [Read this if you need help.](https://github.com/helmetjs/helmet/wiki/Conditionally-using-middleware) + - Removed a lot of checks—you should be checking your CSP with a different tool + - Removed support for legacy headers (and therefore the `setAllHeaders` parameter). [Read this if you need help.](https://github.com/helmetjs/helmet/wiki/Setting-legacy-Content-Security-Policy-headers-in-Helmet-4) + - Removed the `loose` option + - Removed support for functions as directive values. You must supply an iterable of strings +- `helmet.frameguard`: + - Dropped support for the `ALLOW-FROM` action. [Read more here.](https://github.com/helmetjs/helmet/wiki/How-to-use-X%E2%80%93Frame%E2%80%93Options's-%60ALLOW%E2%80%93FROM%60-directive) +- `helmet.hidePoweredBy` no longer accepts arguments. See [this article](https://github.com/helmetjs/helmet/wiki/How-to-set-a-custom-X%E2%80%93Powered%E2%80%93By-header) to see how to replicate the removed behavior. See [#224](https://github.com/helmetjs/helmet/issues/224). +- `helmet.hsts`: + - Dropped support for `includeSubdomains` with a lowercase D. See [#231](https://github.com/helmetjs/helmet/issues/231) + - Dropped support for `setIf`. [Read this if you need help.](https://github.com/helmetjs/helmet/wiki/Conditionally-using-middleware) See [#232](https://github.com/helmetjs/helmet/issues/232) +- `helmet.xssFilter` no longer accepts options. Read ["How to disable blocking with X-XSS-Protection"](https://github.com/helmetjs/helmet/wiki/How-to-disable-blocking-with-X%E2%80%93XSS%E2%80%93Protection) and ["How to enable the `report` directive with X-XSS-Protection"](https://github.com/helmetjs/helmet/wiki/How-to-enable-the-%60report%60-directive-with-X%E2%80%93XSS%E2%80%93Protection) if you need the legacy behavior. + +## 3.23.3 - 2020-06-26 + +### Changed + +- `helmet.expectCt` is no longer a separate package. This should have no effect on end users. +- `helmet.frameguard` is no longer a separate package. This should have no effect on end users. + +## 3.23.2 - 2020-06-23 + +### Changed + +- `helmet.dnsPrefetchControl` is no longer a separate package. This should have no effect on end users. + +## 3.23.1 - 2020-06-16 + +### Changed + +- `helmet.ieNoOpen` is no longer a separate package. This should have no effect on end users. + +## 3.23.0 - 2020-06-12 + +### Deprecated + +- `helmet.featurePolicy` is deprecated. Use the `feature-policy` module instead. + +## 3.22.1 - 2020-06-10 + +### Changed + +- Rewrote internals in TypeScript. This should have no effect on end users. + +## 3.22.0 - 2020-03-24 + +### Changed + +- Updated `helmet-csp` to v2.10.0 + - Add support for the `allow-downloads` sandbox directive. See [helmet-csp#103](https://github.com/helmetjs/csp/pull/103) + +### Deprecated + +- `helmet.noCache` is deprecated. Use the `nocache` module instead. See [#215](https://github.com/helmetjs/helmet/issues/215) + +## 3.21.3 - 2020-02-24 + +### Changed + +- Updated `helmet-csp` to v2.9.5 + - Updated `bowser` subdependency from 2.7.0 to 2.9.0 + - Fixed an issue some people were having when importing the `bowser` subdependency. See [helmet-csp#96](https://github.com/helmetjs/csp/issues/96) and [#101](https://github.com/helmetjs/csp/pull/101) + +## 3.21.2 - 2019-10-21 + +### Changed + +- Updated `helmet-csp` to v2.9.4 + - Updated `bowser` subdependency from 2.6.1 to 2.7.0. See [helmet-csp#94](https://github.com/helmetjs/csp/pull/94) + +## 3.21.1 - 2019-09-20 + +### Fixed + +- Updated `helmet-csp` to v2.9.2 + - Fixed a bug where a request from Firefox 4 could delete `default-src` from future responses + - Fixed tablet PC detection by updating `bowser` subdependency to latest version + +## 3.21.0 - 2019-09-04 + +### Added + +- Updated `x-xss-protection` to v1.3.0 + - Added `mode: null` to disable `mode=block` + +### Changed + +- Updated `helmet-csp` to v2.9.1 + - Updated `bowser` subdependency from 2.5.3 to 2.5.4. See [helmet-csp#88](https://github.com/helmetjs/csp/pull/88) + +## 3.20.1 - 2019-08-28 + +### Changed + +- Updated `helmet-csp` to v2.9.0 + +## 3.20.0 - 2019-07-24 + +### Changed + +- Updated `helmet-csp` to v2.8.0 + +## 3.19.0 - 2019-07-17 + +### Changed + +- Updated `dns-prefetch-control` to v0.2.0 +- Updated `dont-sniff-mimetype` to v1.1.0 +- Updated `helmet-crossdomain` to v0.4.0 +- Updated `hide-powered-by` to v1.1.0 +- Updated `x-xss-protection` to v1.2.0 + +## 3.18.0 - 2019-05-05 + +### Added + +- `featurePolicy` has 19 new features: `ambientLightSensor`, `documentDomain`, `documentWrite`, `encryptedMedia`, `fontDisplayLateSwap`, `layoutAnimations`, `legacyImageFormats`, `loadingFrameDefaultEager`, `oversizedImages`, `pictureInPicture`, `serial`, `syncScript`, `unoptimizedImages`, `unoptimizedLosslessImages`, `unoptimizedLossyImages`, `unsizedMedia`, `verticalScroll`, `wakeLock`, and `xr` + +### Changed + +- Updated `expect-ct` to v0.2.0 +- Updated `feature-policy` to v0.3.0 +- Updated `frameguard` to v3.1.0 +- Updated `nocache` to v2.1.0 + +## 3.17.0 - 2019-05-03 + +### Added + +- `referrerPolicy` now supports multiple values + +### Changed + +- Updated `referrerPolicy` to v1.2.0 + +## 3.16.0 - 2019-03-10 + +### Added + +- Add email to `bugs` field in `package.json` + +### Changed + +- Updated `hsts` to v2.2.0 +- Updated `ienoopen` to v1.1.0 +- Changelog is now in the [Keep A Changelog](https://keepachangelog.com/) format +- Dropped support for Node <4. See [the commit](https://github.com/helmetjs/helmet/commit/a49cec3ca58cce484d2d05e1f908549caa92ed03) for more information +- Updated Adam Baldwin's contact information + +### Deprecated + +- `helmet.hsts`'s `setIf` option has been deprecated and will be removed in `hsts@3`. See [helmetjs/hsts#22](https://github.com/helmetjs/hsts/issues/22) for more + +* The `includeSubdomains` option (with a lowercase `d`) has been deprecated and will be removed in `hsts@3`. Use the uppercase-D `includeSubDomains` option instead. See [helmetjs/hsts#21](https://github.com/helmetjs/hsts/issues/21) for more + +## 3.15.1 - 2019-02-10 + +### Deprecated + +- The `hpkp` middleware has been deprecated. If you still need to use this module, install the standalone `hpkp` module from npm. See [#180](https://github.com/helmetjs/helmet/issues/180) for more. + +## 3.15.0 - 2018-11-07 + +### Added + +- `helmet.featurePolicy` now supports four new features + +## 3.14.0 - 2018-10-09 + +### Added + +- `helmet.featurePolicy` middleware + +## 3.13.0 - 2018-07-22 + +### Added + +- `helmet.permittedCrossDomainPolicies` middleware + +## 3.12.2 - 2018-07-20 + +### Fixed + +- Removed `lodash.reduce` dependency from `csp` + +## 3.12.1 - 2018-05-16 + +### Fixed + +- `expectCt` should use comma instead of semicolon as delimiter + +## 3.12.0 - 2018-03-02 + +### Added + +- `xssFilter` now supports `reportUri` option + +## 3.11.0 - 2018-02-09 + +### Added + +- Main Helmet middleware is now named to help with debugging + +## 3.10.0 - 2018-01-23 + +### Added + +- `csp` now supports `prefix-src` directive + +### Fixed + +- `csp` no longer loads JSON files internally, helping some module bundlers +- `false` should be able to disable a CSP directive + +## 3.9.0 - 2017-10-13 + +### Added + +- `csp` now supports `strict-dynamic` value +- `csp` now supports `require-sri-for` directive + +### Changed + +- Removed `connect` dependency + +## 3.8.2 - 2017-09-27 + +### Changed + +- Updated `connect` dependency to latest + +## 3.8.1 - 2017-07-28 + +### Fixed + +- `csp` does not automatically set `report-to` when setting `report-uri` + +## 3.8.0 - 2017-07-21 + +### Changed + +- `hsts` no longer cares whether it's HTTPS and always sets the header + +## 3.7.0 - 2017-07-21 + +### Added + +- `csp` now supports `report-to` directive + +### Changed + +- Throw an error when used incorrectly +- Add a few documentation files to `npmignore` + +## 3.6.1 - 2017-05-21 + +### Changed + +- Bump `connect` version + +## 3.6.0 - 2017-05-04 + +### Added + +- `expectCt` middleware for setting the `Expect-CT` header + +## 3.5.0 - 2017-03-06 + +### Added + +- `csp` now supports the `worker-src` directive + +## 3.4.1 - 2017-02-24 + +### Changed + +- Bump `connect` version + +## 3.4.0 - 2017-01-13 + +### Added + +- `csp` now supports more `sandbox` directives + +## 3.3.0 - 2016-12-31 + +### Added + +- `referrerPolicy` allows `strict-origin` and `strict-origin-when-cross-origin` directives + +### Changed + +- Bump `connect` version + +## 3.2.0 - 2016-12-22 + +### Added + +- `csp` now allows `manifest-src` directive + +## 3.1.0 - 2016-11-03 + +### Added + +- `csp` now allows `frame-src` directive + +## 3.0.0 - 2016-10-28 + +### Changed + +- `csp` will check your directives for common mistakes and throw errors if it finds them. This can be disabled with `loose: true`. +- Empty arrays are no longer allowed in `csp`. For source lists (like `script-src` or `object-src`), use the standard `scriptSrc: ["'none'"]`. The `sandbox` directive can be `sandbox: true` to block everything. +- `false` can disable a CSP directive. For example, `scriptSrc: false` is the same as not specifying it. +- In CSP, `reportOnly: true` no longer requires a `report-uri` to be set. +- `hsts`'s `maxAge` now defaults to 180 days (instead of 1 day) +- `hsts`'s `maxAge` parameter is seconds, not milliseconds +- `hsts` includes subdomains by default +- `domain` parameter in `frameguard` cannot be empty + +### Removed + +- `noEtag` option no longer present in `noCache` +- iOS Chrome `connect-src` workaround in CSP module + +## 2.3.0 - 2016-09-30 + +### Added + +- `hpkp` middleware now supports the `includeSubDomains` property with a capital D + +### Fixed + +- `hpkp` was setting `includeSubdomains` instead of `includeSubDomains` + +## 2.2.0 - 2016-09-16 + +### Added + +- `referrerPolicy` middleware + +## 2.1.3 - 2016-09-07 + +### Changed + +- Top-level aliases (like `helmet.xssFilter`) are no longer dynamically required + +## 2.1.2 - 2016-07-27 + +### Deprecated + +- `nocache`'s `noEtag` option is now deprecated + +### Fixed + +- `csp` now better handles Firefox on mobile + +## 2.1.1 - 2016-06-10 + +### Changed + +- Remove several dependencies from `helmet-csp` + +### Fixed + +- `frameguard` had a documentation error about its default value +- `frameguard` docs in main Helmet readme said `frameguard`, not `helmet.frameguard` + +## 2.1.0 - 2016-05-18 + +### Added + +- `csp` lets you dynamically set `reportOnly` + +## 2.0.0 - 2016-04-29 + +### Added + +- Pass configuration to enable/disable default middlewares + +### Changed + +- `dnsPrefetchControl` middleware is now enabled by default + +### Removed + +- No more module aliases. There is now just one way to include each middleware +- `frameguard` can no longer be initialized with strings; you must use an object + +### Fixed + +- Make `hpkp` lowercase in documentation +- Update `hpkp` spec URL in readmes +- Update `frameguard` header name in readme + +## 1.3.0 - 2016-03-01 + +### Added + +- `hpkp` has a `setIf` option to conditionally set the header + +## 1.2.0 - 2016-02-29 + +### Added + +- `csp` now has a `browserSniff` option to disable all user-agent sniffing + +### Changed + +- `frameguard` can now be initialized with options +- Add `npmignore` file to speed up installs slightly + +## 1.1.0 - 2016-01-12 + +### Added + +- Code of conduct +- `dnsPrefetchControl` middleware + +### Fixed + +- `csp` readme had syntax errors + +## 1.0.2 - 2016-01-08 + +### Fixed + +- `csp` wouldn't recognize `IE Mobile` browsers +- `csp` had some errors in its readme +- Main readme had a syntax error + +## 1.0.1 - 2015-12-19 + +### Fixed + +- `csp` with no User Agent would cause errors + +## 1.0.0 - 2015-12-18 + +### Added + +- `csp` module supports dynamically-generated values + +### Changed + +- `csp` directives are now under the `directives` key +- `hpkp`'s `Report-Only` header is now opt-in, not opt-out +- Tweak readmes of every sub-repo + +### Removed + +- `crossdomain` middleware +- `csp` no longer throws errors when some directives aren't quoted (`'self'`, for example) +- `maxage` option in the `hpkp` middleware +- `safari5` option from `csp` module + +### Fixed + +- Old Firefox Content-Security-Policy behavior for `unsafe-inline` and `unsafe-eval` +- Dynamic `csp` policies is no longer recursive + +## 0.15.0 - 2015-11-26 + +### Changed + +- `hpkp` allows a `report-uri` without the `Report-Only` header + +## 0.14.0 - 2015-11-01 + +### Added + +- `nocache` now sends the `Surrogate-Control` header + +### Changed + +- `nocache` no longer contains the `private` directive in the `Cache-Control` header + +## 0.13.0 - 2015-10-23 + +### Added + +- `xssFilter` now has a function name +- Added new CSP docs to readme + +### Changed + +- HSTS option renamed from `includeSubdomains` to `includeSubDomains` + +## 0.11.0 - 2015-09-18 + +### Added + +- `csp` now supports Microsoft Edge +- CSP Level 2 support + +### Changed + +- Updated `connect` to 3.4.0 +- Updated `depd` to 1.1.0 + +### Fixed + +- Added `license` key to `csp`'s `package.json` +- Empty `csp` directives now support every directive, not just `sandbox` + +## 0.10.0 - 2015-07-08 + +### Added + +- Add "Handling CSP violations" to `csp` readme +- Add license to `package.json` + +### Changed + +- `hpkp` had a link to the wrong place in its readme +- `hpkp` requires 2 or more pins + +### Fixed + +- `hpkp` might have miscalculated `maxAge` slightly wrong + +## 0.9.0 - 2015-04-24 + +### Changed + +- `nocache` adds `private` to its `Cache-Control` directive +- Added a description to `package.json` + +## 0.8.0 - 2015-04-21 + +### Changed + +- Removed hefty Lodash dependency from HSTS and CSP +- Updated string detection module in Frameguard +- Changed readme slightly to better reflect project's focus + +### Deprecated + +- Deprecated `crossdomain` middleware + +### Removed + +- `crossdomain` is no longer a default middleware + +## 0.7.1 - 2015-03-23 + +### Changed + +- Updated all outdated dependencies (insofar as possible) +- HSTS now uses Lodash like all the rest of the libraries + +## 0.7.0 - 2015-03-05 + +### Added + +- `hpkp` middleware + +### Changed + +- Travis CI should test 0.10 and 0.12 +- Minor code cleanup + +## 0.6.2 - 2015-03-01 + +### Changed + +- Improved `xssFilter` performance +- Updated Lodash versions + +## 0.6.1 - 2015-02-13 + +### Added + +- "Other recommended modules" in README + +### Changed + +- Updated Lodash version + +### Fixed + +- `frameguard` middleware exported a function called `xframe` + +## 0.6.0 - 2015-01-21 + +### Added + +- You can disable `csp` for Android + +### Fixed + +- `csp` on Chrome Mobile on Android and iOS + +## 0.5.4 - 2014-12-21 + +### Changed + +- `nocache` should force revalidation + +## 0.5.3 - 2014-12-08 + +### Changed + +- `platform` version in CSP and X-XSS-Protection + +### Fixed + +- Updated bad wording in frameguard docs + +## 0.5.2 - 2014-11-16 + +### Changed + +- Updated Connect version + +### Fixed + +- Fixed minor `csp` bugfixes + +## 0.5.1 - 2014-11-09 + +### Changed + +- Updated URLs in `package.json` for new URL + +### Fixed + +- CSP would set all headers forever after receiving an unknown user agent + +## 0.5.0 - 2014-10-28 + +### Added + +- Most middlewares have some aliases now + +### Changed + +- `xframe` now called `frameguard` (though `xframe` still works) +- `frameguard` chooses sameorigin by default +- `frameguard` understands "SAME-ORIGIN" in addition to "SAMEORIGIN" +- `nocache` removed from default middleware stack +- Middleware split out into their own modules +- Documentation +- Updated supported Node version to at least 0.10.0 +- Bumped Connect version + +### Removed + +- Deprecation warnings + +### Fixed + +- Readme link was broken + +## 0.4.2 - 2014-10-16 + +### Added + +- Support preload in HSTS header + +## 0.4.1 - 2014-08-24 + +### Added + +- Use [helmet-crossdomain](https://github.com/helmetjs/crossdomain) to test the waters +- 2 spaces instead of 4 throughout the code + +## 0.4.0 - 2014-07-17 + +### Added + +- `nocache` now sets the Expires and Pragma headers +- `nocache` now allows you to crush ETags + +### Changed + +- Improved the docs for nosniff +- Reverted HSTS behavior of requiring a specified max-age + +### Fixed + +- Allow HSTS to have a max-age of 0 + +## 0.3.2 - 2014-06-30 + +### Added + +- All middleware functions are named +- Throw error with non-positive HSTS max-age + +### Changed + +- Added semicolons in README +- Make some Errors more specific + +### Removed + +- Removed all comment headers; refer to the readme + +### Fixed + +- `helmet()` was having issues +- Fixed Syntax errors in README + +This changelog was created after the release of 0.3.1. diff --git a/node_modules/helmet/LICENSE b/node_modules/helmet/LICENSE new file mode 100644 index 0000000..c156bd0 --- /dev/null +++ b/node_modules/helmet/LICENSE @@ -0,0 +1,22 @@ +The MIT License + +Copyright (c) 2012-2024 Evan Hahn, Adam Baldwin + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/helmet/README.md b/node_modules/helmet/README.md new file mode 100644 index 0000000..02c8304 --- /dev/null +++ b/node_modules/helmet/README.md @@ -0,0 +1,702 @@ +# Helmet + +Help secure Express apps by setting HTTP response headers. + +```javascript +import helmet from "helmet"; + +const app = express(); + +app.use(helmet()); +``` + +Helmet sets the following headers by default: + +- [`Content-Security-Policy`](#content-security-policy): A powerful allow-list of what can happen on your page which mitigates many attacks +- [`Cross-Origin-Opener-Policy`](#cross-origin-opener-policy): Helps process-isolate your page +- [`Cross-Origin-Resource-Policy`](#cross-origin-resource-policy): Blocks others from loading your resources cross-origin +- [`Origin-Agent-Cluster`](#origin-agent-cluster): Changes process isolation to be origin-based +- [`Referrer-Policy`](#referrer-policy): Controls the [`Referer`][Referer] header +- [`Strict-Transport-Security`](#strict-transport-security): Tells browsers to prefer HTTPS +- [`X-Content-Type-Options`](#x-content-type-options): Avoids [MIME sniffing] +- [`X-DNS-Prefetch-Control`](#x-dns-prefetch-control): Controls DNS prefetching +- [`X-Download-Options`](#x-download-options): Forces downloads to be saved (Internet Explorer only) +- [`X-Frame-Options`](#x-frame-options): Legacy header that mitigates [clickjacking] attacks +- [`X-Permitted-Cross-Domain-Policies`](#x-permitted-cross-domain-policies): Controls cross-domain behavior for Adobe products, like Acrobat +- [`X-Powered-By`](#x-powered-by): Info about the web server. Removed because it could be used in simple attacks +- [`X-XSS-Protection`](#x-xss-protection): Legacy header that tries to mitigate [XSS attacks][XSS], but makes things worse, so Helmet disables it + +Each header can be configured. For example, here's how you configure the `Content-Security-Policy` header: + +```js +// Configure the Content-Security-Policy header. +app.use( + helmet({ + contentSecurityPolicy: { + directives: { + "script-src": ["'self'", "example.com"], + }, + }, + }), +); +``` + +Headers can also be disabled. For example, here's how you disable the `Content-Security-Policy` and `X-Download-Options` headers: + +```js +// Disable the Content-Security-Policy and X-Download-Options headers +app.use( + helmet({ + contentSecurityPolicy: false, + xDownloadOptions: false, + }), +); +``` + +## Reference + +
+Content-Security-Policy + +Default: + +```http +Content-Security-Policy: default-src 'self';base-uri 'self';font-src 'self' https: data:;form-action 'self';frame-ancestors 'self';img-src 'self' data:;object-src 'none';script-src 'self';script-src-attr 'none';style-src 'self' https: 'unsafe-inline';upgrade-insecure-requests +``` + +The `Content-Security-Policy` header mitigates a large number of attacks, such as [cross-site scripting][XSS]. See [MDN's introductory article on Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP). + +This header is powerful but likely requires some configuration for your specific app. + +To configure this header, pass an object with a nested `directives` object. Each key is a directive name in camel case (such as `defaultSrc`) or kebab case (such as `default-src`). Each value is an array (or other iterable) of strings or functions for that directive. If a function appears in the array, it will be called with the request and response objects. + +```javascript +// Sets all of the defaults, but overrides `script-src` +// and disables the default `style-src`. +app.use( + helmet({ + contentSecurityPolicy: { + directives: { + "script-src": ["'self'", "example.com"], + "style-src": null, + }, + }, + }), +); +``` + +```js +// Sets the `script-src` directive to +// "'self' 'nonce-e33cc...'" +// (or similar) +app.use((req, res, next) => { + res.locals.cspNonce = crypto.randomBytes(32).toString("hex"); + next(); +}); +app.use( + helmet({ + contentSecurityPolicy: { + directives: { + scriptSrc: ["'self'", (req, res) => `'nonce-${res.locals.cspNonce}'`], + }, + }, + }), +); +``` + +These directives are merged into a default policy, which you can disable by setting `useDefaults` to `false`. + +```javascript +// Sets "Content-Security-Policy: default-src 'self'; +// script-src 'self' example.com;object-src 'none'; +// upgrade-insecure-requests" +app.use( + helmet({ + contentSecurityPolicy: { + useDefaults: false, + directives: { + defaultSrc: ["'self'"], + scriptSrc: ["'self'", "example.com"], + objectSrc: ["'none'"], + upgradeInsecureRequests: [], + }, + }, + }), +); +``` + +You can get the default directives object with `helmet.contentSecurityPolicy.getDefaultDirectives()`. Here is the default policy (formatted for readability): + +``` +default-src 'self'; +base-uri 'self'; +font-src 'self' https: data:; +form-action 'self'; +frame-ancestors 'self'; +img-src 'self' data:; +object-src 'none'; +script-src 'self'; +script-src-attr 'none'; +style-src 'self' https: 'unsafe-inline'; +upgrade-insecure-requests +``` + +The `default-src` directive can be explicitly disabled by setting its value to `helmet.contentSecurityPolicy.dangerouslyDisableDefaultSrc`, but this is not recommended. + +You can set the [`Content-Security-Policy-Report-Only`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only) instead: + +```javascript +// Sets the Content-Security-Policy-Report-Only header +app.use( + helmet({ + contentSecurityPolicy: { + directives: { + /* ... */ + }, + reportOnly: true, + }, + }), +); +``` + +Helmet performs very little validation on your CSP. You should rely on CSP checkers like [CSP Evaluator](https://csp-evaluator.withgoogle.com/) instead. + +To disable the `Content-Security-Policy` header: + +```js +app.use( + helmet({ + contentSecurityPolicy: false, + }), +); +``` + +You can use this as standalone middleware with `app.use(helmet.contentSecurityPolicy())`. + +
+ +
+Cross-Origin-Embedder-Policy + +This header is not set by default. + +The `Cross-Origin-Embedder-Policy` header helps control what resources can be loaded cross-origin. See [MDN's article on this header](https://developer.cdn.mozilla.net/en-US/docs/Web/HTTP/Headers/Cross-Origin-Embedder-Policy) for more. + +```js +// Helmet does not set Cross-Origin-Embedder-Policy +// by default. +app.use(helmet()); + +// Sets "Cross-Origin-Embedder-Policy: require-corp" +app.use(helmet({ crossOriginEmbedderPolicy: true })); + +// Sets "Cross-Origin-Embedder-Policy: credentialless" +app.use(helmet({ crossOriginEmbedderPolicy: { policy: "credentialless" } })); +``` + +You can use this as standalone middleware with `app.use(helmet.crossOriginEmbedderPolicy())`. + +
+ +
+Cross-Origin-Opener-Policy + +Default: + +```http +Cross-Origin-Opener-Policy: same-origin +``` + +The `Cross-Origin-Opener-Policy` header helps process-isolate your page. For more, see [MDN's article on this header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy). + +```js +// Sets "Cross-Origin-Opener-Policy: same-origin" +app.use(helmet()); + +// Sets "Cross-Origin-Opener-Policy: same-origin-allow-popups" +app.use( + helmet({ + crossOriginOpenerPolicy: { policy: "same-origin-allow-popups" }, + }), +); +``` + +To disable the `Cross-Origin-Opener-Policy` header: + +```js +app.use( + helmet({ + crossOriginOpenerPolicy: false, + }), +); +``` + +You can use this as standalone middleware with `app.use(helmet.crossOriginOpenerPolicy())`. + +
+ +
+Cross-Origin-Resource-Policy + +Default: + +```http +Cross-Origin-Resource-Policy: same-origin +``` + +The `Cross-Origin-Resource-Policy` header blocks others from loading your resources cross-origin in some cases. For more, see ["Consider deploying Cross-Origin Resource Policy"](https://resourcepolicy.fyi/) and [MDN's article on this header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Resource-Policy). + +```js +// Sets "Cross-Origin-Resource-Policy: same-origin" +app.use(helmet()); + +// Sets "Cross-Origin-Resource-Policy: same-site" +app.use(helmet({ crossOriginResourcePolicy: { policy: "same-site" } })); +``` + +To disable the `Cross-Origin-Resource-Policy` header: + +```js +app.use( + helmet({ + crossOriginResourcePolicy: false, + }), +); +``` + +You can use this as standalone middleware with `app.use(helmet.crossOriginResourcePolicy())`. + +
+ +
+Origin-Agent-Cluster + +Default: + +```http +Origin-Agent-Cluster: ?1 +``` + +The `Origin-Agent-Cluster` header provides a mechanism to allow web applications to isolate their origins from other processes. Read more about it [in the spec](https://whatpr.org/html/6214/origin.html#origin-keyed-agent-clusters). + +This header takes no options and is set by default. + +```js +// Sets "Origin-Agent-Cluster: ?1" +app.use(helmet()); +``` + +To disable the `Origin-Agent-Cluster` header: + +```js +app.use( + helmet({ + originAgentCluster: false, + }), +); +``` + +You can use this as standalone middleware with `app.use(helmet.originAgentCluster())`. + +
+ +
+Referrer-Policy + +Default: + +```http +Referrer-Policy: no-referrer +``` + +The `Referrer-Policy` header which controls what information is set in [the `Referer` request header][Referer]. See ["Referer header: privacy and security concerns"](https://developer.mozilla.org/en-US/docs/Web/Security/Referer_header:_privacy_and_security_concerns) and [the header's documentation](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy) on MDN for more. + +```js +// Sets "Referrer-Policy: no-referrer" +app.use(helmet()); +``` + +`policy` is a string or array of strings representing the policy. If passed as an array, it will be joined with commas, which is useful when setting [a fallback policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy#Specifying_a_fallback_policy). It defaults to `no-referrer`. + +```js +// Sets "Referrer-Policy: no-referrer" +app.use( + helmet({ + referrerPolicy: { + policy: "no-referrer", + }, + }), +); + +// Sets "Referrer-Policy: origin,unsafe-url" +app.use( + helmet({ + referrerPolicy: { + policy: ["origin", "unsafe-url"], + }, + }), +); +``` + +To disable the `Referrer-Policy` header: + +```js +app.use( + helmet({ + referrerPolicy: false, + }), +); +``` + +You can use this as standalone middleware with `app.use(helmet.referrerPolicy())`. + +
+ +
+Strict-Transport-Security + +Default: + +```http +Strict-Transport-Security: max-age=15552000; includeSubDomains +``` + +The `Strict-Transport-Security` header tells browsers to prefer HTTPS instead of insecure HTTP. See [the documentation on MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security) for more. + +```js +// Sets "Strict-Transport-Security: max-age=15552000; includeSubDomains" +app.use(helmet()); +``` + +`maxAge` is the number of seconds browsers should remember to prefer HTTPS. If passed a non-integer, the value is rounded down. It defaults to `15552000`, which is 180 days. + +`includeSubDomains` is a boolean which dictates whether to include the `includeSubDomains` directive, which makes this policy extend to subdomains. It defaults to `true`. + +`preload` is a boolean. If true, it adds the `preload` directive, expressing intent to add your HSTS policy to browsers. See [the "Preloading Strict Transport Security" section on MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security#Preloading_Strict_Transport_Security) for more. It defaults to `false`. + +```js +// Sets "Strict-Transport-Security: max-age=123456; includeSubDomains" +app.use( + helmet({ + strictTransportSecurity: { + maxAge: 123456, + }, + }), +); + +// Sets "Strict-Transport-Security: max-age=123456" +app.use( + helmet({ + strictTransportSecurity: { + maxAge: 123456, + includeSubDomains: false, + }, + }), +); + +// Sets "Strict-Transport-Security: max-age=123456; includeSubDomains; preload" +app.use( + helmet({ + strictTransportSecurity: { + maxAge: 63072000, + preload: true, + }, + }), +); +``` + +To disable the `Strict-Transport-Security` header: + +```js +app.use( + helmet({ + strictTransportSecurity: false, + }), +); +``` + +You may wish to disable this header for local development, as it can make your browser force redirects from `http://localhost` to `https://localhost`, which may not be desirable if you develop multiple apps using `localhost`. See [this issue](https://github.com/helmetjs/helmet/issues/451) for more discussion. + +You can use this as standalone middleware with `app.use(helmet.strictTransportSecurity())`. + +
+ +
+X-Content-Type-Options + +Default: + +```http +X-Content-Type-Options: nosniff +``` + +The `X-Content-Type-Options` mitigates [MIME type sniffing](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types#MIME_sniffing) which can cause security issues. See [documentation for this header on MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options) for more. + +This header takes no options and is set by default. + +```js +// Sets "X-Content-Type-Options: nosniff" +app.use(helmet()); +``` + +To disable the `X-Content-Type-Options` header: + +```js +app.use( + helmet({ + xContentTypeOptions: false, + }), +); +``` + +You can use this as standalone middleware with `app.use(helmet.xContentTypeOptions())`. + +
+ +
+X-DNS-Prefetch-Control + +Default: + +```http +X-DNS-Prefetch-Control: off +``` + +The `X-DNS-Prefetch-Control` header helps control DNS prefetching, which can improve user privacy at the expense of performance. See [documentation on MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-DNS-Prefetch-Control) for more. + +```js +// Sets "X-DNS-Prefetch-Control: off" +app.use(helmet()); +``` + +`allow` is a boolean dictating whether to enable DNS prefetching. It defaults to `false`. + +Examples: + +```js +// Sets "X-DNS-Prefetch-Control: off" +app.use( + helmet({ + xDnsPrefetchControl: { allow: false }, + }), +); + +// Sets "X-DNS-Prefetch-Control: on" +app.use( + helmet({ + xDnsPrefetchControl: { allow: true }, + }), +); +``` + +To disable the `X-DNS-Prefetch-Control` header and use the browser's default value: + +```js +app.use( + helmet({ + xDnsPrefetchControl: false, + }), +); +``` + +You can use this as standalone middleware with `app.use(helmet.xDnsPrefetchControl())`. + +
+ +
+X-Download-Options + +Default: + +```http +X-Download-Options: noopen +``` + +The `X-Download-Options` header is specific to Internet Explorer 8. It forces potentially-unsafe downloads to be saved, mitigating execution of HTML in your site's context. For more, see [this old post on MSDN](https://docs.microsoft.com/en-us/archive/blogs/ie/ie8-security-part-v-comprehensive-protection). + +This header takes no options and is set by default. + +```js +// Sets "X-Download-Options: noopen" +app.use(helmet()); +``` + +To disable the `X-Download-Options` header: + +```js +app.use( + helmet({ + xDownloadOptions: false, + }), +); +``` + +You can use this as standalone middleware with `app.use(helmet.xDownloadOptions())`. + +
+ +
+X-Frame-Options + +Default: + +```http +X-Frame-Options: SAMEORIGIN +``` + +The legacy `X-Frame-Options` header to help you mitigate [clickjacking attacks](https://en.wikipedia.org/wiki/Clickjacking). This header is superseded by [the `frame-ancestors` Content Security Policy directive](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/frame-ancestors) but is still useful on old browsers or if no CSP is used. For more, see [the documentation on MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options). + +```js +// Sets "X-Frame-Options: SAMEORIGIN" +app.use(helmet()); +``` + +`action` is a string that specifies which directive to use—either `DENY` or `SAMEORIGIN`. (A legacy directive, `ALLOW-FROM`, is not supported by Helmet. [Read more here.](https://github.com/helmetjs/helmet/wiki/How-to-use-X%E2%80%93Frame%E2%80%93Options's-%60ALLOW%E2%80%93FROM%60-directive)) It defaults to `SAMEORIGIN`. + +Examples: + +```js +// Sets "X-Frame-Options: DENY" +app.use( + helmet({ + xFrameOptions: { action: "deny" }, + }), +); + +// Sets "X-Frame-Options: SAMEORIGIN" +app.use( + helmet({ + xFrameOptions: { action: "sameorigin" }, + }), +); +``` + +To disable the `X-Frame-Options` header: + +```js +app.use( + helmet({ + xFrameOptions: false, + }), +); +``` + +You can use this as standalone middleware with `app.use(helmet.xFrameOptions())`. + +
+ +
+X-Permitted-Cross-Domain-Policies + +Default: + +```http +X-Permitted-Cross-Domain-Policies: none +``` + +The `X-Permitted-Cross-Domain-Policies` header tells some clients (mostly Adobe products) your domain's policy for loading cross-domain content. See [the description on OWASP](https://owasp.org/www-project-secure-headers/) for more. + +```js +// Sets "X-Permitted-Cross-Domain-Policies: none" +app.use(helmet()); +``` + +`permittedPolicies` is a string that must be `"none"`, `"master-only"`, `"by-content-type"`, or `"all"`. It defaults to `"none"`. + +Examples: + +```js +// Sets "X-Permitted-Cross-Domain-Policies: none" +app.use( + helmet({ + xPermittedCrossDomainPolicies: { + permittedPolicies: "none", + }, + }), +); + +// Sets "X-Permitted-Cross-Domain-Policies: by-content-type" +app.use( + helmet({ + xPermittedCrossDomainPolicies: { + permittedPolicies: "by-content-type", + }, + }), +); +``` + +To disable the `X-Permitted-Cross-Domain-Policies` header: + +```js +app.use( + helmet({ + xPermittedCrossDomainPolicies: false, + }), +); +``` + +You can use this as standalone middleware with `app.use(helmet.xPermittedCrossDomainPolicies())`. + +
+ +
+X-Powered-By + +Default: the `X-Powered-By` header, if present, is removed. + +Helmet removes the `X-Powered-By` header, which is set by default in Express and some other frameworks. Removing the header offers very limited security benefits (see [this discussion](https://github.com/expressjs/express/pull/2813#issuecomment-159270428)) and is mostly removed to save bandwidth, but may thwart simplistic attackers. + +Note: [Express has a built-in way to disable the `X-Powered-By` header](https://stackoverflow.com/a/12484642/804100), which you may wish to use instead. + +The removal of this header takes no options. The header is removed by default. + +To disable this behavior: + +```js +// Not required, but recommended for Express users: +app.disable("x-powered-by"); + +// Ask Helmet to ignore the X-Powered-By header. +app.use( + helmet({ + xPoweredBy: false, + }), +); +``` + +You can use this as standalone middleware with `app.use(helmet.xPoweredBy())`. + +
+ +
+X-XSS-Protection + +Default: + +```http +X-XSS-Protection: 0 +``` + +Helmet disables browsers' buggy cross-site scripting filter by setting the legacy `X-XSS-Protection` header to `0`. See [discussion about disabling the header here](https://github.com/helmetjs/helmet/issues/230) and [documentation on MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-XSS-Protection). + +This header takes no options and is set by default. + +To disable the `X-XSS-Protection` header: + +```js +// This is not recommended. +app.use( + helmet({ + xXssProtection: false, + }), +); +``` + +You can use this as standalone middleware with `app.use(helmet.xXssProtection())`. + +
+ +[Referer]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referer +[MIME sniffing]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types#mime_sniffing +[Clickjacking]: https://en.wikipedia.org/wiki/Clickjacking +[XSS]: https://developer.mozilla.org/en-US/docs/Glossary/Cross-site_scripting diff --git a/node_modules/helmet/SECURITY.md b/node_modules/helmet/SECURITY.md new file mode 100644 index 0000000..406d499 --- /dev/null +++ b/node_modules/helmet/SECURITY.md @@ -0,0 +1,7 @@ +# Security issue reporting & disclosure process + +If you feel you have found a security issue or concern with Helmet, please reach out to the maintainers. + +Contact Evan Hahn at or Adam Baldwin at . Evan Hahn [can also be reached in other ways](https://evanhahn.com/contact). + +We will try to communicate in a timely manner and address your concerns. diff --git a/node_modules/helmet/index.cjs b/node_modules/helmet/index.cjs new file mode 100644 index 0000000..cc7ebaa --- /dev/null +++ b/node_modules/helmet/index.cjs @@ -0,0 +1,584 @@ +"use strict" + +Object.defineProperties(exports, {__esModule: {value: true}, [Symbol.toStringTag]: {value: "Module"}}) + +const dangerouslyDisableDefaultSrc = Symbol("dangerouslyDisableDefaultSrc") +const SHOULD_BE_QUOTED = new Set(["none", "self", "strict-dynamic", "report-sample", "inline-speculation-rules", "unsafe-inline", "unsafe-eval", "unsafe-hashes", "wasm-unsafe-eval"]) +const getDefaultDirectives = () => ({ + "default-src": ["'self'"], + "base-uri": ["'self'"], + "font-src": ["'self'", "https:", "data:"], + "form-action": ["'self'"], + "frame-ancestors": ["'self'"], + "img-src": ["'self'", "data:"], + "object-src": ["'none'"], + "script-src": ["'self'"], + "script-src-attr": ["'none'"], + "style-src": ["'self'", "https:", "'unsafe-inline'"], + "upgrade-insecure-requests": [] +}) +const dashify = str => str.replace(/[A-Z]/g, capitalLetter => "-" + capitalLetter.toLowerCase()) +const isDirectiveValueInvalid = directiveValue => /;|,/.test(directiveValue) +const isDirectiveValueEntryInvalid = directiveValueEntry => SHOULD_BE_QUOTED.has(directiveValueEntry) || directiveValueEntry.startsWith("nonce-") || directiveValueEntry.startsWith("sha256-") || directiveValueEntry.startsWith("sha384-") || directiveValueEntry.startsWith("sha512-") +const invalidDirectiveValueError = directiveName => new Error(`Content-Security-Policy received an invalid directive value for ${JSON.stringify(directiveName)}`) +function normalizeDirectives(options) { + const defaultDirectives = getDefaultDirectives() + const {useDefaults = true, directives: rawDirectives = defaultDirectives} = options + const result = new Map() + const directiveNamesSeen = new Set() + const directivesExplicitlyDisabled = new Set() + for (const rawDirectiveName in rawDirectives) { + if (!Object.hasOwn(rawDirectives, rawDirectiveName)) { + continue + } + if (rawDirectiveName.length === 0 || /[^a-zA-Z0-9-]/.test(rawDirectiveName)) { + throw new Error(`Content-Security-Policy received an invalid directive name ${JSON.stringify(rawDirectiveName)}`) + } + const directiveName = dashify(rawDirectiveName) + if (directiveNamesSeen.has(directiveName)) { + throw new Error(`Content-Security-Policy received a duplicate directive ${JSON.stringify(directiveName)}`) + } + directiveNamesSeen.add(directiveName) + const rawDirectiveValue = rawDirectives[rawDirectiveName] + let directiveValue + if (rawDirectiveValue === null) { + if (directiveName === "default-src") { + throw new Error("Content-Security-Policy needs a default-src but it was set to `null`. If you really want to disable it, set it to `contentSecurityPolicy.dangerouslyDisableDefaultSrc`.") + } + directivesExplicitlyDisabled.add(directiveName) + continue + } else if (typeof rawDirectiveValue === "string") { + directiveValue = [rawDirectiveValue] + } else if (!rawDirectiveValue) { + throw new Error(`Content-Security-Policy received an invalid directive value for ${JSON.stringify(directiveName)}`) + } else if (rawDirectiveValue === dangerouslyDisableDefaultSrc) { + if (directiveName === "default-src") { + directivesExplicitlyDisabled.add("default-src") + continue + } else { + throw new Error(`Content-Security-Policy: tried to disable ${JSON.stringify(directiveName)} as if it were default-src; simply omit the key`) + } + } else { + directiveValue = rawDirectiveValue + } + for (const element of directiveValue) { + if (typeof element === "string" && (isDirectiveValueInvalid(element) || isDirectiveValueEntryInvalid(element))) { + throw invalidDirectiveValueError(directiveName) + } + } + result.set(directiveName, directiveValue) + } + if (useDefaults) { + Object.entries(defaultDirectives).forEach(([defaultDirectiveName, defaultDirectiveValue]) => { + if (!result.has(defaultDirectiveName) && !directivesExplicitlyDisabled.has(defaultDirectiveName)) { + result.set(defaultDirectiveName, defaultDirectiveValue) + } + }) + } + if (!result.size) { + throw new Error("Content-Security-Policy has no directives. Either set some or disable the header") + } + if (!result.has("default-src") && !directivesExplicitlyDisabled.has("default-src")) { + throw new Error("Content-Security-Policy needs a default-src but none was provided. If you really want to disable it, set it to `contentSecurityPolicy.dangerouslyDisableDefaultSrc`.") + } + return result +} +function getHeaderValue(req, res, normalizedDirectives) { + const result = [] + for (const [directiveName, rawDirectiveValue] of normalizedDirectives) { + let directiveValue = "" + for (const element of rawDirectiveValue) { + if (typeof element === "function") { + const newElement = element(req, res) + if (isDirectiveValueEntryInvalid(newElement)) { + return invalidDirectiveValueError(directiveName) + } + directiveValue += " " + newElement + } else { + directiveValue += " " + element + } + } + if (!directiveValue) { + result.push(directiveName) + } else if (isDirectiveValueInvalid(directiveValue)) { + return invalidDirectiveValueError(directiveName) + } else { + result.push(`${directiveName}${directiveValue}`) + } + } + return result.join(";") +} +const contentSecurityPolicy = function contentSecurityPolicy(options = {}) { + const headerName = options.reportOnly ? "Content-Security-Policy-Report-Only" : "Content-Security-Policy" + const normalizedDirectives = normalizeDirectives(options) + return function contentSecurityPolicyMiddleware(req, res, next) { + const result = getHeaderValue(req, res, normalizedDirectives) + if (result instanceof Error) { + next(result) + } else { + res.setHeader(headerName, result) + next() + } + } +} +contentSecurityPolicy.getDefaultDirectives = getDefaultDirectives +contentSecurityPolicy.dangerouslyDisableDefaultSrc = dangerouslyDisableDefaultSrc + +const ALLOWED_POLICIES$2 = new Set(["require-corp", "credentialless", "unsafe-none"]) +function getHeaderValueFromOptions$6({policy = "require-corp"}) { + if (ALLOWED_POLICIES$2.has(policy)) { + return policy + } else { + throw new Error(`Cross-Origin-Embedder-Policy does not support the ${JSON.stringify(policy)} policy`) + } +} +function crossOriginEmbedderPolicy(options = {}) { + const headerValue = getHeaderValueFromOptions$6(options) + return function crossOriginEmbedderPolicyMiddleware(_req, res, next) { + res.setHeader("Cross-Origin-Embedder-Policy", headerValue) + next() + } +} + +const ALLOWED_POLICIES$1 = new Set(["same-origin", "same-origin-allow-popups", "unsafe-none"]) +function getHeaderValueFromOptions$5({policy = "same-origin"}) { + if (ALLOWED_POLICIES$1.has(policy)) { + return policy + } else { + throw new Error(`Cross-Origin-Opener-Policy does not support the ${JSON.stringify(policy)} policy`) + } +} +function crossOriginOpenerPolicy(options = {}) { + const headerValue = getHeaderValueFromOptions$5(options) + return function crossOriginOpenerPolicyMiddleware(_req, res, next) { + res.setHeader("Cross-Origin-Opener-Policy", headerValue) + next() + } +} + +const ALLOWED_POLICIES = new Set(["same-origin", "same-site", "cross-origin"]) +function getHeaderValueFromOptions$4({policy = "same-origin"}) { + if (ALLOWED_POLICIES.has(policy)) { + return policy + } else { + throw new Error(`Cross-Origin-Resource-Policy does not support the ${JSON.stringify(policy)} policy`) + } +} +function crossOriginResourcePolicy(options = {}) { + const headerValue = getHeaderValueFromOptions$4(options) + return function crossOriginResourcePolicyMiddleware(_req, res, next) { + res.setHeader("Cross-Origin-Resource-Policy", headerValue) + next() + } +} + +function originAgentCluster() { + return function originAgentClusterMiddleware(_req, res, next) { + res.setHeader("Origin-Agent-Cluster", "?1") + next() + } +} + +const ALLOWED_TOKENS = new Set(["no-referrer", "no-referrer-when-downgrade", "same-origin", "origin", "strict-origin", "origin-when-cross-origin", "strict-origin-when-cross-origin", "unsafe-url", ""]) +function getHeaderValueFromOptions$3({policy = ["no-referrer"]}) { + const tokens = typeof policy === "string" ? [policy] : policy + if (tokens.length === 0) { + throw new Error("Referrer-Policy received no policy tokens") + } + const tokensSeen = new Set() + tokens.forEach(token => { + if (!ALLOWED_TOKENS.has(token)) { + throw new Error(`Referrer-Policy received an unexpected policy token ${JSON.stringify(token)}`) + } else if (tokensSeen.has(token)) { + throw new Error(`Referrer-Policy received a duplicate policy token ${JSON.stringify(token)}`) + } + tokensSeen.add(token) + }) + return tokens.join(",") +} +function referrerPolicy(options = {}) { + const headerValue = getHeaderValueFromOptions$3(options) + return function referrerPolicyMiddleware(_req, res, next) { + res.setHeader("Referrer-Policy", headerValue) + next() + } +} + +const DEFAULT_MAX_AGE = 365 * 24 * 60 * 60 +function parseMaxAge(value = DEFAULT_MAX_AGE) { + if (value >= 0 && Number.isFinite(value)) { + return Math.floor(value) + } else { + throw new Error(`Strict-Transport-Security: ${JSON.stringify(value)} is not a valid value for maxAge. Please choose a positive integer.`) + } +} +function getHeaderValueFromOptions$2(options) { + if ("maxage" in options) { + throw new Error("Strict-Transport-Security received an unsupported property, `maxage`. Did you mean to pass `maxAge`?") + } + if ("includeSubdomains" in options) { + throw new Error('Strict-Transport-Security middleware should use `includeSubDomains` instead of `includeSubdomains`. (The correct one has an uppercase "D".)') + } + const directives = [`max-age=${parseMaxAge(options.maxAge)}`] + if (options.includeSubDomains === undefined || options.includeSubDomains) { + directives.push("includeSubDomains") + } + if (options.preload) { + directives.push("preload") + } + return directives.join("; ") +} +function strictTransportSecurity(options = {}) { + const headerValue = getHeaderValueFromOptions$2(options) + return function strictTransportSecurityMiddleware(_req, res, next) { + res.setHeader("Strict-Transport-Security", headerValue) + next() + } +} + +function xContentTypeOptions() { + return function xContentTypeOptionsMiddleware(_req, res, next) { + res.setHeader("X-Content-Type-Options", "nosniff") + next() + } +} + +function xDnsPrefetchControl(options = {}) { + const headerValue = options.allow ? "on" : "off" + return function xDnsPrefetchControlMiddleware(_req, res, next) { + res.setHeader("X-DNS-Prefetch-Control", headerValue) + next() + } +} + +function xDownloadOptions() { + return function xDownloadOptionsMiddleware(_req, res, next) { + res.setHeader("X-Download-Options", "noopen") + next() + } +} + +function getHeaderValueFromOptions$1({action = "sameorigin"}) { + const normalizedAction = typeof action === "string" ? action.toUpperCase() : action + switch (normalizedAction) { + case "SAME-ORIGIN": + return "SAMEORIGIN" + case "DENY": + case "SAMEORIGIN": + return normalizedAction + default: + throw new Error(`X-Frame-Options received an invalid action ${JSON.stringify(action)}`) + } +} +function xFrameOptions(options = {}) { + const headerValue = getHeaderValueFromOptions$1(options) + return function xFrameOptionsMiddleware(_req, res, next) { + res.setHeader("X-Frame-Options", headerValue) + next() + } +} + +const ALLOWED_PERMITTED_POLICIES = new Set(["none", "master-only", "by-content-type", "all"]) +function getHeaderValueFromOptions({permittedPolicies = "none"}) { + if (ALLOWED_PERMITTED_POLICIES.has(permittedPolicies)) { + return permittedPolicies + } else { + throw new Error(`X-Permitted-Cross-Domain-Policies does not support ${JSON.stringify(permittedPolicies)}`) + } +} +function xPermittedCrossDomainPolicies(options = {}) { + const headerValue = getHeaderValueFromOptions(options) + return function xPermittedCrossDomainPoliciesMiddleware(_req, res, next) { + res.setHeader("X-Permitted-Cross-Domain-Policies", headerValue) + next() + } +} + +function xPoweredBy() { + return function xPoweredByMiddleware(_req, res, next) { + res.removeHeader("X-Powered-By") + next() + } +} + +function xXssProtection() { + return function xXssProtectionMiddleware(_req, res, next) { + res.setHeader("X-XSS-Protection", "0") + next() + } +} + +function getMiddlewareFunctionsFromOptions(options) { + const result = [] + switch (options.contentSecurityPolicy) { + case undefined: + case true: + result.push(contentSecurityPolicy()) + break + case false: + break + default: + result.push(contentSecurityPolicy(options.contentSecurityPolicy)) + break + } + switch (options.crossOriginEmbedderPolicy) { + case undefined: + case false: + break + case true: + result.push(crossOriginEmbedderPolicy()) + break + default: + result.push(crossOriginEmbedderPolicy(options.crossOriginEmbedderPolicy)) + break + } + switch (options.crossOriginOpenerPolicy) { + case undefined: + case true: + result.push(crossOriginOpenerPolicy()) + break + case false: + break + default: + result.push(crossOriginOpenerPolicy(options.crossOriginOpenerPolicy)) + break + } + switch (options.crossOriginResourcePolicy) { + case undefined: + case true: + result.push(crossOriginResourcePolicy()) + break + case false: + break + default: + result.push(crossOriginResourcePolicy(options.crossOriginResourcePolicy)) + break + } + switch (options.originAgentCluster) { + case undefined: + case true: + result.push(originAgentCluster()) + break + case false: + break + default: + console.warn("Origin-Agent-Cluster does not take options. Remove the property to silence this warning.") + result.push(originAgentCluster()) + break + } + switch (options.referrerPolicy) { + case undefined: + case true: + result.push(referrerPolicy()) + break + case false: + break + default: + result.push(referrerPolicy(options.referrerPolicy)) + break + } + if ("strictTransportSecurity" in options && "hsts" in options) { + throw new Error("Strict-Transport-Security option was specified twice. Remove `hsts` to silence this warning.") + } + const strictTransportSecurityOption = options.strictTransportSecurity ?? options.hsts + switch (strictTransportSecurityOption) { + case undefined: + case true: + result.push(strictTransportSecurity()) + break + case false: + break + default: + result.push(strictTransportSecurity(strictTransportSecurityOption)) + break + } + if ("xContentTypeOptions" in options && "noSniff" in options) { + throw new Error("X-Content-Type-Options option was specified twice. Remove `noSniff` to silence this warning.") + } + const xContentTypeOptionsOption = options.xContentTypeOptions ?? options.noSniff + switch (xContentTypeOptionsOption) { + case undefined: + case true: + result.push(xContentTypeOptions()) + break + case false: + break + default: + console.warn("X-Content-Type-Options does not take options. Remove the property to silence this warning.") + result.push(xContentTypeOptions()) + break + } + if ("xDnsPrefetchControl" in options && "dnsPrefetchControl" in options) { + throw new Error("X-DNS-Prefetch-Control option was specified twice. Remove `dnsPrefetchControl` to silence this warning.") + } + const xDnsPrefetchControlOption = options.xDnsPrefetchControl ?? options.dnsPrefetchControl + switch (xDnsPrefetchControlOption) { + case undefined: + case true: + result.push(xDnsPrefetchControl()) + break + case false: + break + default: + result.push(xDnsPrefetchControl(xDnsPrefetchControlOption)) + break + } + if ("xDownloadOptions" in options && "ieNoOpen" in options) { + throw new Error("X-Download-Options option was specified twice. Remove `ieNoOpen` to silence this warning.") + } + const xDownloadOptionsOption = options.xDownloadOptions ?? options.ieNoOpen + switch (xDownloadOptionsOption) { + case undefined: + case true: + result.push(xDownloadOptions()) + break + case false: + break + default: + console.warn("X-Download-Options does not take options. Remove the property to silence this warning.") + result.push(xDownloadOptions()) + break + } + if ("xFrameOptions" in options && "frameguard" in options) { + throw new Error("X-Frame-Options option was specified twice. Remove `frameguard` to silence this warning.") + } + const xFrameOptionsOption = options.xFrameOptions ?? options.frameguard + switch (xFrameOptionsOption) { + case undefined: + case true: + result.push(xFrameOptions()) + break + case false: + break + default: + result.push(xFrameOptions(xFrameOptionsOption)) + break + } + if ("xPermittedCrossDomainPolicies" in options && "permittedCrossDomainPolicies" in options) { + throw new Error("X-Permitted-Cross-Domain-Policies option was specified twice. Remove `permittedCrossDomainPolicies` to silence this warning.") + } + const xPermittedCrossDomainPoliciesOption = options.xPermittedCrossDomainPolicies ?? options.permittedCrossDomainPolicies + switch (xPermittedCrossDomainPoliciesOption) { + case undefined: + case true: + result.push(xPermittedCrossDomainPolicies()) + break + case false: + break + default: + result.push(xPermittedCrossDomainPolicies(xPermittedCrossDomainPoliciesOption)) + break + } + if ("xPoweredBy" in options && "hidePoweredBy" in options) { + throw new Error("X-Powered-By option was specified twice. Remove `hidePoweredBy` to silence this warning.") + } + const xPoweredByOption = options.xPoweredBy ?? options.hidePoweredBy + switch (xPoweredByOption) { + case undefined: + case true: + result.push(xPoweredBy()) + break + case false: + break + default: + console.warn("X-Powered-By does not take options. Remove the property to silence this warning.") + result.push(xPoweredBy()) + break + } + if ("xXssProtection" in options && "xssFilter" in options) { + throw new Error("X-XSS-Protection option was specified twice. Remove `xssFilter` to silence this warning.") + } + const xXssProtectionOption = options.xXssProtection ?? options.xssFilter + switch (xXssProtectionOption) { + case undefined: + case true: + result.push(xXssProtection()) + break + case false: + break + default: + console.warn("X-XSS-Protection does not take options. Remove the property to silence this warning.") + result.push(xXssProtection()) + break + } + return result +} +const helmet = Object.assign( + function helmet(options = {}) { + // People should be able to pass an options object with no prototype, + // so we want this optional chaining. + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + if (options.constructor?.name === "IncomingMessage") { + throw new Error("It appears you have done something like `app.use(helmet)`, but it should be `app.use(helmet())`.") + } + const middlewareFunctions = getMiddlewareFunctionsFromOptions(options) + return function helmetMiddleware(req, res, next) { + let middlewareIndex = 0 + ;(function internalNext(err) { + if (err) { + next(err) + return + } + const middlewareFunction = middlewareFunctions[middlewareIndex] + if (middlewareFunction) { + middlewareIndex++ + middlewareFunction(req, res, internalNext) + } else { + next() + } + })() + } + }, + { + contentSecurityPolicy, + crossOriginEmbedderPolicy, + crossOriginOpenerPolicy, + crossOriginResourcePolicy, + originAgentCluster, + referrerPolicy, + strictTransportSecurity, + xContentTypeOptions, + xDnsPrefetchControl, + xDownloadOptions, + xFrameOptions, + xPermittedCrossDomainPolicies, + xPoweredBy, + xXssProtection, + // Legacy aliases + dnsPrefetchControl: xDnsPrefetchControl, + xssFilter: xXssProtection, + permittedCrossDomainPolicies: xPermittedCrossDomainPolicies, + ieNoOpen: xDownloadOptions, + noSniff: xContentTypeOptions, + frameguard: xFrameOptions, + hidePoweredBy: xPoweredBy, + hsts: strictTransportSecurity + } +) + +exports.contentSecurityPolicy = contentSecurityPolicy +exports.crossOriginEmbedderPolicy = crossOriginEmbedderPolicy +exports.crossOriginOpenerPolicy = crossOriginOpenerPolicy +exports.crossOriginResourcePolicy = crossOriginResourcePolicy +exports.default = helmet +exports.dnsPrefetchControl = xDnsPrefetchControl +exports.frameguard = xFrameOptions +exports.hidePoweredBy = xPoweredBy +exports.hsts = strictTransportSecurity +exports.ieNoOpen = xDownloadOptions +exports.noSniff = xContentTypeOptions +exports.originAgentCluster = originAgentCluster +exports.permittedCrossDomainPolicies = xPermittedCrossDomainPolicies +exports.referrerPolicy = referrerPolicy +exports.strictTransportSecurity = strictTransportSecurity +exports.xContentTypeOptions = xContentTypeOptions +exports.xDnsPrefetchControl = xDnsPrefetchControl +exports.xDownloadOptions = xDownloadOptions +exports.xFrameOptions = xFrameOptions +exports.xPermittedCrossDomainPolicies = xPermittedCrossDomainPolicies +exports.xPoweredBy = xPoweredBy +exports.xXssProtection = xXssProtection +exports.xssFilter = xXssProtection + +module.exports = exports.default +module.exports.default = module.exports diff --git a/node_modules/helmet/index.d.cts b/node_modules/helmet/index.d.cts new file mode 100644 index 0000000..1d89231 --- /dev/null +++ b/node_modules/helmet/index.d.cts @@ -0,0 +1,186 @@ +import {IncomingMessage, ServerResponse} from "http" + +type ContentSecurityPolicyDirectiveValueFunction = (req: IncomingMessage, res: ServerResponse) => string +type ContentSecurityPolicyDirectiveValue = string | ContentSecurityPolicyDirectiveValueFunction +interface ContentSecurityPolicyOptions { + useDefaults?: boolean + directives?: Record | typeof dangerouslyDisableDefaultSrc> + reportOnly?: boolean +} +interface ContentSecurityPolicy { + (options?: Readonly): (req: IncomingMessage, res: ServerResponse, next: (err?: Error) => void) => void + getDefaultDirectives: typeof getDefaultDirectives + dangerouslyDisableDefaultSrc: typeof dangerouslyDisableDefaultSrc +} +declare const dangerouslyDisableDefaultSrc: unique symbol +declare const getDefaultDirectives: () => Record> +declare const contentSecurityPolicy: ContentSecurityPolicy + +interface CrossOriginEmbedderPolicyOptions { + policy?: "require-corp" | "credentialless" | "unsafe-none" +} +declare function crossOriginEmbedderPolicy(options?: Readonly): (_req: IncomingMessage, res: ServerResponse, next: () => void) => void + +interface CrossOriginOpenerPolicyOptions { + policy?: "same-origin" | "same-origin-allow-popups" | "unsafe-none" +} +declare function crossOriginOpenerPolicy(options?: Readonly): (_req: IncomingMessage, res: ServerResponse, next: () => void) => void + +interface CrossOriginResourcePolicyOptions { + policy?: "same-origin" | "same-site" | "cross-origin" +} +declare function crossOriginResourcePolicy(options?: Readonly): (_req: IncomingMessage, res: ServerResponse, next: () => void) => void + +declare function originAgentCluster(): (_req: IncomingMessage, res: ServerResponse, next: () => void) => void + +type ReferrerPolicyToken = "no-referrer" | "no-referrer-when-downgrade" | "same-origin" | "origin" | "strict-origin" | "origin-when-cross-origin" | "strict-origin-when-cross-origin" | "unsafe-url" | "" +interface ReferrerPolicyOptions { + policy?: ReferrerPolicyToken | ReferrerPolicyToken[] +} +declare function referrerPolicy(options?: Readonly): (_req: IncomingMessage, res: ServerResponse, next: () => void) => void + +interface StrictTransportSecurityOptions { + maxAge?: number + includeSubDomains?: boolean + preload?: boolean +} +declare function strictTransportSecurity(options?: Readonly): (_req: IncomingMessage, res: ServerResponse, next: () => void) => void + +declare function xContentTypeOptions(): (_req: IncomingMessage, res: ServerResponse, next: () => void) => void + +interface XDnsPrefetchControlOptions { + allow?: boolean +} +declare function xDnsPrefetchControl(options?: Readonly): (_req: IncomingMessage, res: ServerResponse, next: () => void) => void + +declare function xDownloadOptions(): (_req: IncomingMessage, res: ServerResponse, next: () => void) => void + +interface XFrameOptionsOptions { + action?: "deny" | "sameorigin" +} +declare function xFrameOptions(options?: Readonly): (_req: IncomingMessage, res: ServerResponse, next: () => void) => void + +interface XPermittedCrossDomainPoliciesOptions { + permittedPolicies?: "none" | "master-only" | "by-content-type" | "all" +} +declare function xPermittedCrossDomainPolicies(options?: Readonly): (_req: IncomingMessage, res: ServerResponse, next: () => void) => void + +declare function xPoweredBy(): (_req: IncomingMessage, res: ServerResponse, next: () => void) => void + +declare function xXssProtection(): (_req: IncomingMessage, res: ServerResponse, next: () => void) => void + +type HelmetOptions = { + contentSecurityPolicy?: ContentSecurityPolicyOptions | boolean + crossOriginEmbedderPolicy?: CrossOriginEmbedderPolicyOptions | boolean + crossOriginOpenerPolicy?: CrossOriginOpenerPolicyOptions | boolean + crossOriginResourcePolicy?: CrossOriginResourcePolicyOptions | boolean + originAgentCluster?: boolean + referrerPolicy?: ReferrerPolicyOptions | boolean +} & ( + | { + strictTransportSecurity?: StrictTransportSecurityOptions | boolean + hsts?: never + } + | { + hsts?: StrictTransportSecurityOptions | boolean + strictTransportSecurity?: never + } +) & + ( + | { + xContentTypeOptions?: boolean + noSniff?: never + } + | { + noSniff?: boolean + xContentTypeOptions?: never + } + ) & + ( + | { + xDnsPrefetchControl?: XDnsPrefetchControlOptions | boolean + dnsPrefetchControl?: never + } + | { + dnsPrefetchControl?: XDnsPrefetchControlOptions | boolean + xDnsPrefetchControl?: never + } + ) & + ( + | { + xDownloadOptions?: boolean + ieNoOpen?: never + } + | { + ieNoOpen?: boolean + xDownloadOptions?: never + } + ) & + ( + | { + xFrameOptions?: XFrameOptionsOptions | boolean + frameguard?: never + } + | { + frameguard?: XFrameOptionsOptions | boolean + xFrameOptions?: never + } + ) & + ( + | { + xPermittedCrossDomainPolicies?: XPermittedCrossDomainPoliciesOptions | boolean + permittedCrossDomainPolicies?: never + } + | { + permittedCrossDomainPolicies?: XPermittedCrossDomainPoliciesOptions | boolean + xPermittedCrossDomainPolicies?: never + } + ) & + ( + | { + xPoweredBy?: boolean + hidePoweredBy?: never + } + | { + hidePoweredBy?: boolean + xPoweredBy?: never + } + ) & + ( + | { + xXssProtection?: boolean + xssFilter?: never + } + | { + xssFilter?: boolean + xXssProtection?: never + } + ) +interface Helmet { + (options?: Readonly): (req: IncomingMessage, res: ServerResponse, next: (err?: unknown) => void) => void + contentSecurityPolicy: typeof contentSecurityPolicy + crossOriginEmbedderPolicy: typeof crossOriginEmbedderPolicy + crossOriginOpenerPolicy: typeof crossOriginOpenerPolicy + crossOriginResourcePolicy: typeof crossOriginResourcePolicy + originAgentCluster: typeof originAgentCluster + referrerPolicy: typeof referrerPolicy + strictTransportSecurity: typeof strictTransportSecurity + xContentTypeOptions: typeof xContentTypeOptions + xDnsPrefetchControl: typeof xDnsPrefetchControl + xDownloadOptions: typeof xDownloadOptions + xFrameOptions: typeof xFrameOptions + xPermittedCrossDomainPolicies: typeof xPermittedCrossDomainPolicies + xPoweredBy: typeof xPoweredBy + xXssProtection: typeof xXssProtection + dnsPrefetchControl: typeof xDnsPrefetchControl + frameguard: typeof xFrameOptions + hidePoweredBy: typeof xPoweredBy + hsts: typeof strictTransportSecurity + ieNoOpen: typeof xDownloadOptions + noSniff: typeof xContentTypeOptions + permittedCrossDomainPolicies: typeof xPermittedCrossDomainPolicies + xssFilter: typeof xXssProtection +} +declare const helmet: Helmet + +export {type HelmetOptions, contentSecurityPolicy, crossOriginEmbedderPolicy, crossOriginOpenerPolicy, crossOriginResourcePolicy, helmet as default, xDnsPrefetchControl as dnsPrefetchControl, xFrameOptions as frameguard, xPoweredBy as hidePoweredBy, strictTransportSecurity as hsts, xDownloadOptions as ieNoOpen, xContentTypeOptions as noSniff, originAgentCluster, xPermittedCrossDomainPolicies as permittedCrossDomainPolicies, referrerPolicy, strictTransportSecurity, xContentTypeOptions, xDnsPrefetchControl, xDownloadOptions, xFrameOptions, xPermittedCrossDomainPolicies, xPoweredBy, xXssProtection, xXssProtection as xssFilter} diff --git a/node_modules/helmet/index.d.mts b/node_modules/helmet/index.d.mts new file mode 100644 index 0000000..1d89231 --- /dev/null +++ b/node_modules/helmet/index.d.mts @@ -0,0 +1,186 @@ +import {IncomingMessage, ServerResponse} from "http" + +type ContentSecurityPolicyDirectiveValueFunction = (req: IncomingMessage, res: ServerResponse) => string +type ContentSecurityPolicyDirectiveValue = string | ContentSecurityPolicyDirectiveValueFunction +interface ContentSecurityPolicyOptions { + useDefaults?: boolean + directives?: Record | typeof dangerouslyDisableDefaultSrc> + reportOnly?: boolean +} +interface ContentSecurityPolicy { + (options?: Readonly): (req: IncomingMessage, res: ServerResponse, next: (err?: Error) => void) => void + getDefaultDirectives: typeof getDefaultDirectives + dangerouslyDisableDefaultSrc: typeof dangerouslyDisableDefaultSrc +} +declare const dangerouslyDisableDefaultSrc: unique symbol +declare const getDefaultDirectives: () => Record> +declare const contentSecurityPolicy: ContentSecurityPolicy + +interface CrossOriginEmbedderPolicyOptions { + policy?: "require-corp" | "credentialless" | "unsafe-none" +} +declare function crossOriginEmbedderPolicy(options?: Readonly): (_req: IncomingMessage, res: ServerResponse, next: () => void) => void + +interface CrossOriginOpenerPolicyOptions { + policy?: "same-origin" | "same-origin-allow-popups" | "unsafe-none" +} +declare function crossOriginOpenerPolicy(options?: Readonly): (_req: IncomingMessage, res: ServerResponse, next: () => void) => void + +interface CrossOriginResourcePolicyOptions { + policy?: "same-origin" | "same-site" | "cross-origin" +} +declare function crossOriginResourcePolicy(options?: Readonly): (_req: IncomingMessage, res: ServerResponse, next: () => void) => void + +declare function originAgentCluster(): (_req: IncomingMessage, res: ServerResponse, next: () => void) => void + +type ReferrerPolicyToken = "no-referrer" | "no-referrer-when-downgrade" | "same-origin" | "origin" | "strict-origin" | "origin-when-cross-origin" | "strict-origin-when-cross-origin" | "unsafe-url" | "" +interface ReferrerPolicyOptions { + policy?: ReferrerPolicyToken | ReferrerPolicyToken[] +} +declare function referrerPolicy(options?: Readonly): (_req: IncomingMessage, res: ServerResponse, next: () => void) => void + +interface StrictTransportSecurityOptions { + maxAge?: number + includeSubDomains?: boolean + preload?: boolean +} +declare function strictTransportSecurity(options?: Readonly): (_req: IncomingMessage, res: ServerResponse, next: () => void) => void + +declare function xContentTypeOptions(): (_req: IncomingMessage, res: ServerResponse, next: () => void) => void + +interface XDnsPrefetchControlOptions { + allow?: boolean +} +declare function xDnsPrefetchControl(options?: Readonly): (_req: IncomingMessage, res: ServerResponse, next: () => void) => void + +declare function xDownloadOptions(): (_req: IncomingMessage, res: ServerResponse, next: () => void) => void + +interface XFrameOptionsOptions { + action?: "deny" | "sameorigin" +} +declare function xFrameOptions(options?: Readonly): (_req: IncomingMessage, res: ServerResponse, next: () => void) => void + +interface XPermittedCrossDomainPoliciesOptions { + permittedPolicies?: "none" | "master-only" | "by-content-type" | "all" +} +declare function xPermittedCrossDomainPolicies(options?: Readonly): (_req: IncomingMessage, res: ServerResponse, next: () => void) => void + +declare function xPoweredBy(): (_req: IncomingMessage, res: ServerResponse, next: () => void) => void + +declare function xXssProtection(): (_req: IncomingMessage, res: ServerResponse, next: () => void) => void + +type HelmetOptions = { + contentSecurityPolicy?: ContentSecurityPolicyOptions | boolean + crossOriginEmbedderPolicy?: CrossOriginEmbedderPolicyOptions | boolean + crossOriginOpenerPolicy?: CrossOriginOpenerPolicyOptions | boolean + crossOriginResourcePolicy?: CrossOriginResourcePolicyOptions | boolean + originAgentCluster?: boolean + referrerPolicy?: ReferrerPolicyOptions | boolean +} & ( + | { + strictTransportSecurity?: StrictTransportSecurityOptions | boolean + hsts?: never + } + | { + hsts?: StrictTransportSecurityOptions | boolean + strictTransportSecurity?: never + } +) & + ( + | { + xContentTypeOptions?: boolean + noSniff?: never + } + | { + noSniff?: boolean + xContentTypeOptions?: never + } + ) & + ( + | { + xDnsPrefetchControl?: XDnsPrefetchControlOptions | boolean + dnsPrefetchControl?: never + } + | { + dnsPrefetchControl?: XDnsPrefetchControlOptions | boolean + xDnsPrefetchControl?: never + } + ) & + ( + | { + xDownloadOptions?: boolean + ieNoOpen?: never + } + | { + ieNoOpen?: boolean + xDownloadOptions?: never + } + ) & + ( + | { + xFrameOptions?: XFrameOptionsOptions | boolean + frameguard?: never + } + | { + frameguard?: XFrameOptionsOptions | boolean + xFrameOptions?: never + } + ) & + ( + | { + xPermittedCrossDomainPolicies?: XPermittedCrossDomainPoliciesOptions | boolean + permittedCrossDomainPolicies?: never + } + | { + permittedCrossDomainPolicies?: XPermittedCrossDomainPoliciesOptions | boolean + xPermittedCrossDomainPolicies?: never + } + ) & + ( + | { + xPoweredBy?: boolean + hidePoweredBy?: never + } + | { + hidePoweredBy?: boolean + xPoweredBy?: never + } + ) & + ( + | { + xXssProtection?: boolean + xssFilter?: never + } + | { + xssFilter?: boolean + xXssProtection?: never + } + ) +interface Helmet { + (options?: Readonly): (req: IncomingMessage, res: ServerResponse, next: (err?: unknown) => void) => void + contentSecurityPolicy: typeof contentSecurityPolicy + crossOriginEmbedderPolicy: typeof crossOriginEmbedderPolicy + crossOriginOpenerPolicy: typeof crossOriginOpenerPolicy + crossOriginResourcePolicy: typeof crossOriginResourcePolicy + originAgentCluster: typeof originAgentCluster + referrerPolicy: typeof referrerPolicy + strictTransportSecurity: typeof strictTransportSecurity + xContentTypeOptions: typeof xContentTypeOptions + xDnsPrefetchControl: typeof xDnsPrefetchControl + xDownloadOptions: typeof xDownloadOptions + xFrameOptions: typeof xFrameOptions + xPermittedCrossDomainPolicies: typeof xPermittedCrossDomainPolicies + xPoweredBy: typeof xPoweredBy + xXssProtection: typeof xXssProtection + dnsPrefetchControl: typeof xDnsPrefetchControl + frameguard: typeof xFrameOptions + hidePoweredBy: typeof xPoweredBy + hsts: typeof strictTransportSecurity + ieNoOpen: typeof xDownloadOptions + noSniff: typeof xContentTypeOptions + permittedCrossDomainPolicies: typeof xPermittedCrossDomainPolicies + xssFilter: typeof xXssProtection +} +declare const helmet: Helmet + +export {type HelmetOptions, contentSecurityPolicy, crossOriginEmbedderPolicy, crossOriginOpenerPolicy, crossOriginResourcePolicy, helmet as default, xDnsPrefetchControl as dnsPrefetchControl, xFrameOptions as frameguard, xPoweredBy as hidePoweredBy, strictTransportSecurity as hsts, xDownloadOptions as ieNoOpen, xContentTypeOptions as noSniff, originAgentCluster, xPermittedCrossDomainPolicies as permittedCrossDomainPolicies, referrerPolicy, strictTransportSecurity, xContentTypeOptions, xDnsPrefetchControl, xDownloadOptions, xFrameOptions, xPermittedCrossDomainPolicies, xPoweredBy, xXssProtection, xXssProtection as xssFilter} diff --git a/node_modules/helmet/index.mjs b/node_modules/helmet/index.mjs new file mode 100644 index 0000000..9ec2839 --- /dev/null +++ b/node_modules/helmet/index.mjs @@ -0,0 +1,555 @@ +const dangerouslyDisableDefaultSrc = Symbol("dangerouslyDisableDefaultSrc") +const SHOULD_BE_QUOTED = new Set(["none", "self", "strict-dynamic", "report-sample", "inline-speculation-rules", "unsafe-inline", "unsafe-eval", "unsafe-hashes", "wasm-unsafe-eval"]) +const getDefaultDirectives = () => ({ + "default-src": ["'self'"], + "base-uri": ["'self'"], + "font-src": ["'self'", "https:", "data:"], + "form-action": ["'self'"], + "frame-ancestors": ["'self'"], + "img-src": ["'self'", "data:"], + "object-src": ["'none'"], + "script-src": ["'self'"], + "script-src-attr": ["'none'"], + "style-src": ["'self'", "https:", "'unsafe-inline'"], + "upgrade-insecure-requests": [] +}) +const dashify = str => str.replace(/[A-Z]/g, capitalLetter => "-" + capitalLetter.toLowerCase()) +const isDirectiveValueInvalid = directiveValue => /;|,/.test(directiveValue) +const isDirectiveValueEntryInvalid = directiveValueEntry => SHOULD_BE_QUOTED.has(directiveValueEntry) || directiveValueEntry.startsWith("nonce-") || directiveValueEntry.startsWith("sha256-") || directiveValueEntry.startsWith("sha384-") || directiveValueEntry.startsWith("sha512-") +const invalidDirectiveValueError = directiveName => new Error(`Content-Security-Policy received an invalid directive value for ${JSON.stringify(directiveName)}`) +function normalizeDirectives(options) { + const defaultDirectives = getDefaultDirectives() + const {useDefaults = true, directives: rawDirectives = defaultDirectives} = options + const result = new Map() + const directiveNamesSeen = new Set() + const directivesExplicitlyDisabled = new Set() + for (const rawDirectiveName in rawDirectives) { + if (!Object.hasOwn(rawDirectives, rawDirectiveName)) { + continue + } + if (rawDirectiveName.length === 0 || /[^a-zA-Z0-9-]/.test(rawDirectiveName)) { + throw new Error(`Content-Security-Policy received an invalid directive name ${JSON.stringify(rawDirectiveName)}`) + } + const directiveName = dashify(rawDirectiveName) + if (directiveNamesSeen.has(directiveName)) { + throw new Error(`Content-Security-Policy received a duplicate directive ${JSON.stringify(directiveName)}`) + } + directiveNamesSeen.add(directiveName) + const rawDirectiveValue = rawDirectives[rawDirectiveName] + let directiveValue + if (rawDirectiveValue === null) { + if (directiveName === "default-src") { + throw new Error("Content-Security-Policy needs a default-src but it was set to `null`. If you really want to disable it, set it to `contentSecurityPolicy.dangerouslyDisableDefaultSrc`.") + } + directivesExplicitlyDisabled.add(directiveName) + continue + } else if (typeof rawDirectiveValue === "string") { + directiveValue = [rawDirectiveValue] + } else if (!rawDirectiveValue) { + throw new Error(`Content-Security-Policy received an invalid directive value for ${JSON.stringify(directiveName)}`) + } else if (rawDirectiveValue === dangerouslyDisableDefaultSrc) { + if (directiveName === "default-src") { + directivesExplicitlyDisabled.add("default-src") + continue + } else { + throw new Error(`Content-Security-Policy: tried to disable ${JSON.stringify(directiveName)} as if it were default-src; simply omit the key`) + } + } else { + directiveValue = rawDirectiveValue + } + for (const element of directiveValue) { + if (typeof element === "string" && (isDirectiveValueInvalid(element) || isDirectiveValueEntryInvalid(element))) { + throw invalidDirectiveValueError(directiveName) + } + } + result.set(directiveName, directiveValue) + } + if (useDefaults) { + Object.entries(defaultDirectives).forEach(([defaultDirectiveName, defaultDirectiveValue]) => { + if (!result.has(defaultDirectiveName) && !directivesExplicitlyDisabled.has(defaultDirectiveName)) { + result.set(defaultDirectiveName, defaultDirectiveValue) + } + }) + } + if (!result.size) { + throw new Error("Content-Security-Policy has no directives. Either set some or disable the header") + } + if (!result.has("default-src") && !directivesExplicitlyDisabled.has("default-src")) { + throw new Error("Content-Security-Policy needs a default-src but none was provided. If you really want to disable it, set it to `contentSecurityPolicy.dangerouslyDisableDefaultSrc`.") + } + return result +} +function getHeaderValue(req, res, normalizedDirectives) { + const result = [] + for (const [directiveName, rawDirectiveValue] of normalizedDirectives) { + let directiveValue = "" + for (const element of rawDirectiveValue) { + if (typeof element === "function") { + const newElement = element(req, res) + if (isDirectiveValueEntryInvalid(newElement)) { + return invalidDirectiveValueError(directiveName) + } + directiveValue += " " + newElement + } else { + directiveValue += " " + element + } + } + if (!directiveValue) { + result.push(directiveName) + } else if (isDirectiveValueInvalid(directiveValue)) { + return invalidDirectiveValueError(directiveName) + } else { + result.push(`${directiveName}${directiveValue}`) + } + } + return result.join(";") +} +const contentSecurityPolicy = function contentSecurityPolicy(options = {}) { + const headerName = options.reportOnly ? "Content-Security-Policy-Report-Only" : "Content-Security-Policy" + const normalizedDirectives = normalizeDirectives(options) + return function contentSecurityPolicyMiddleware(req, res, next) { + const result = getHeaderValue(req, res, normalizedDirectives) + if (result instanceof Error) { + next(result) + } else { + res.setHeader(headerName, result) + next() + } + } +} +contentSecurityPolicy.getDefaultDirectives = getDefaultDirectives +contentSecurityPolicy.dangerouslyDisableDefaultSrc = dangerouslyDisableDefaultSrc + +const ALLOWED_POLICIES$2 = new Set(["require-corp", "credentialless", "unsafe-none"]) +function getHeaderValueFromOptions$6({policy = "require-corp"}) { + if (ALLOWED_POLICIES$2.has(policy)) { + return policy + } else { + throw new Error(`Cross-Origin-Embedder-Policy does not support the ${JSON.stringify(policy)} policy`) + } +} +function crossOriginEmbedderPolicy(options = {}) { + const headerValue = getHeaderValueFromOptions$6(options) + return function crossOriginEmbedderPolicyMiddleware(_req, res, next) { + res.setHeader("Cross-Origin-Embedder-Policy", headerValue) + next() + } +} + +const ALLOWED_POLICIES$1 = new Set(["same-origin", "same-origin-allow-popups", "unsafe-none"]) +function getHeaderValueFromOptions$5({policy = "same-origin"}) { + if (ALLOWED_POLICIES$1.has(policy)) { + return policy + } else { + throw new Error(`Cross-Origin-Opener-Policy does not support the ${JSON.stringify(policy)} policy`) + } +} +function crossOriginOpenerPolicy(options = {}) { + const headerValue = getHeaderValueFromOptions$5(options) + return function crossOriginOpenerPolicyMiddleware(_req, res, next) { + res.setHeader("Cross-Origin-Opener-Policy", headerValue) + next() + } +} + +const ALLOWED_POLICIES = new Set(["same-origin", "same-site", "cross-origin"]) +function getHeaderValueFromOptions$4({policy = "same-origin"}) { + if (ALLOWED_POLICIES.has(policy)) { + return policy + } else { + throw new Error(`Cross-Origin-Resource-Policy does not support the ${JSON.stringify(policy)} policy`) + } +} +function crossOriginResourcePolicy(options = {}) { + const headerValue = getHeaderValueFromOptions$4(options) + return function crossOriginResourcePolicyMiddleware(_req, res, next) { + res.setHeader("Cross-Origin-Resource-Policy", headerValue) + next() + } +} + +function originAgentCluster() { + return function originAgentClusterMiddleware(_req, res, next) { + res.setHeader("Origin-Agent-Cluster", "?1") + next() + } +} + +const ALLOWED_TOKENS = new Set(["no-referrer", "no-referrer-when-downgrade", "same-origin", "origin", "strict-origin", "origin-when-cross-origin", "strict-origin-when-cross-origin", "unsafe-url", ""]) +function getHeaderValueFromOptions$3({policy = ["no-referrer"]}) { + const tokens = typeof policy === "string" ? [policy] : policy + if (tokens.length === 0) { + throw new Error("Referrer-Policy received no policy tokens") + } + const tokensSeen = new Set() + tokens.forEach(token => { + if (!ALLOWED_TOKENS.has(token)) { + throw new Error(`Referrer-Policy received an unexpected policy token ${JSON.stringify(token)}`) + } else if (tokensSeen.has(token)) { + throw new Error(`Referrer-Policy received a duplicate policy token ${JSON.stringify(token)}`) + } + tokensSeen.add(token) + }) + return tokens.join(",") +} +function referrerPolicy(options = {}) { + const headerValue = getHeaderValueFromOptions$3(options) + return function referrerPolicyMiddleware(_req, res, next) { + res.setHeader("Referrer-Policy", headerValue) + next() + } +} + +const DEFAULT_MAX_AGE = 365 * 24 * 60 * 60 +function parseMaxAge(value = DEFAULT_MAX_AGE) { + if (value >= 0 && Number.isFinite(value)) { + return Math.floor(value) + } else { + throw new Error(`Strict-Transport-Security: ${JSON.stringify(value)} is not a valid value for maxAge. Please choose a positive integer.`) + } +} +function getHeaderValueFromOptions$2(options) { + if ("maxage" in options) { + throw new Error("Strict-Transport-Security received an unsupported property, `maxage`. Did you mean to pass `maxAge`?") + } + if ("includeSubdomains" in options) { + throw new Error('Strict-Transport-Security middleware should use `includeSubDomains` instead of `includeSubdomains`. (The correct one has an uppercase "D".)') + } + const directives = [`max-age=${parseMaxAge(options.maxAge)}`] + if (options.includeSubDomains === undefined || options.includeSubDomains) { + directives.push("includeSubDomains") + } + if (options.preload) { + directives.push("preload") + } + return directives.join("; ") +} +function strictTransportSecurity(options = {}) { + const headerValue = getHeaderValueFromOptions$2(options) + return function strictTransportSecurityMiddleware(_req, res, next) { + res.setHeader("Strict-Transport-Security", headerValue) + next() + } +} + +function xContentTypeOptions() { + return function xContentTypeOptionsMiddleware(_req, res, next) { + res.setHeader("X-Content-Type-Options", "nosniff") + next() + } +} + +function xDnsPrefetchControl(options = {}) { + const headerValue = options.allow ? "on" : "off" + return function xDnsPrefetchControlMiddleware(_req, res, next) { + res.setHeader("X-DNS-Prefetch-Control", headerValue) + next() + } +} + +function xDownloadOptions() { + return function xDownloadOptionsMiddleware(_req, res, next) { + res.setHeader("X-Download-Options", "noopen") + next() + } +} + +function getHeaderValueFromOptions$1({action = "sameorigin"}) { + const normalizedAction = typeof action === "string" ? action.toUpperCase() : action + switch (normalizedAction) { + case "SAME-ORIGIN": + return "SAMEORIGIN" + case "DENY": + case "SAMEORIGIN": + return normalizedAction + default: + throw new Error(`X-Frame-Options received an invalid action ${JSON.stringify(action)}`) + } +} +function xFrameOptions(options = {}) { + const headerValue = getHeaderValueFromOptions$1(options) + return function xFrameOptionsMiddleware(_req, res, next) { + res.setHeader("X-Frame-Options", headerValue) + next() + } +} + +const ALLOWED_PERMITTED_POLICIES = new Set(["none", "master-only", "by-content-type", "all"]) +function getHeaderValueFromOptions({permittedPolicies = "none"}) { + if (ALLOWED_PERMITTED_POLICIES.has(permittedPolicies)) { + return permittedPolicies + } else { + throw new Error(`X-Permitted-Cross-Domain-Policies does not support ${JSON.stringify(permittedPolicies)}`) + } +} +function xPermittedCrossDomainPolicies(options = {}) { + const headerValue = getHeaderValueFromOptions(options) + return function xPermittedCrossDomainPoliciesMiddleware(_req, res, next) { + res.setHeader("X-Permitted-Cross-Domain-Policies", headerValue) + next() + } +} + +function xPoweredBy() { + return function xPoweredByMiddleware(_req, res, next) { + res.removeHeader("X-Powered-By") + next() + } +} + +function xXssProtection() { + return function xXssProtectionMiddleware(_req, res, next) { + res.setHeader("X-XSS-Protection", "0") + next() + } +} + +function getMiddlewareFunctionsFromOptions(options) { + const result = [] + switch (options.contentSecurityPolicy) { + case undefined: + case true: + result.push(contentSecurityPolicy()) + break + case false: + break + default: + result.push(contentSecurityPolicy(options.contentSecurityPolicy)) + break + } + switch (options.crossOriginEmbedderPolicy) { + case undefined: + case false: + break + case true: + result.push(crossOriginEmbedderPolicy()) + break + default: + result.push(crossOriginEmbedderPolicy(options.crossOriginEmbedderPolicy)) + break + } + switch (options.crossOriginOpenerPolicy) { + case undefined: + case true: + result.push(crossOriginOpenerPolicy()) + break + case false: + break + default: + result.push(crossOriginOpenerPolicy(options.crossOriginOpenerPolicy)) + break + } + switch (options.crossOriginResourcePolicy) { + case undefined: + case true: + result.push(crossOriginResourcePolicy()) + break + case false: + break + default: + result.push(crossOriginResourcePolicy(options.crossOriginResourcePolicy)) + break + } + switch (options.originAgentCluster) { + case undefined: + case true: + result.push(originAgentCluster()) + break + case false: + break + default: + console.warn("Origin-Agent-Cluster does not take options. Remove the property to silence this warning.") + result.push(originAgentCluster()) + break + } + switch (options.referrerPolicy) { + case undefined: + case true: + result.push(referrerPolicy()) + break + case false: + break + default: + result.push(referrerPolicy(options.referrerPolicy)) + break + } + if ("strictTransportSecurity" in options && "hsts" in options) { + throw new Error("Strict-Transport-Security option was specified twice. Remove `hsts` to silence this warning.") + } + const strictTransportSecurityOption = options.strictTransportSecurity ?? options.hsts + switch (strictTransportSecurityOption) { + case undefined: + case true: + result.push(strictTransportSecurity()) + break + case false: + break + default: + result.push(strictTransportSecurity(strictTransportSecurityOption)) + break + } + if ("xContentTypeOptions" in options && "noSniff" in options) { + throw new Error("X-Content-Type-Options option was specified twice. Remove `noSniff` to silence this warning.") + } + const xContentTypeOptionsOption = options.xContentTypeOptions ?? options.noSniff + switch (xContentTypeOptionsOption) { + case undefined: + case true: + result.push(xContentTypeOptions()) + break + case false: + break + default: + console.warn("X-Content-Type-Options does not take options. Remove the property to silence this warning.") + result.push(xContentTypeOptions()) + break + } + if ("xDnsPrefetchControl" in options && "dnsPrefetchControl" in options) { + throw new Error("X-DNS-Prefetch-Control option was specified twice. Remove `dnsPrefetchControl` to silence this warning.") + } + const xDnsPrefetchControlOption = options.xDnsPrefetchControl ?? options.dnsPrefetchControl + switch (xDnsPrefetchControlOption) { + case undefined: + case true: + result.push(xDnsPrefetchControl()) + break + case false: + break + default: + result.push(xDnsPrefetchControl(xDnsPrefetchControlOption)) + break + } + if ("xDownloadOptions" in options && "ieNoOpen" in options) { + throw new Error("X-Download-Options option was specified twice. Remove `ieNoOpen` to silence this warning.") + } + const xDownloadOptionsOption = options.xDownloadOptions ?? options.ieNoOpen + switch (xDownloadOptionsOption) { + case undefined: + case true: + result.push(xDownloadOptions()) + break + case false: + break + default: + console.warn("X-Download-Options does not take options. Remove the property to silence this warning.") + result.push(xDownloadOptions()) + break + } + if ("xFrameOptions" in options && "frameguard" in options) { + throw new Error("X-Frame-Options option was specified twice. Remove `frameguard` to silence this warning.") + } + const xFrameOptionsOption = options.xFrameOptions ?? options.frameguard + switch (xFrameOptionsOption) { + case undefined: + case true: + result.push(xFrameOptions()) + break + case false: + break + default: + result.push(xFrameOptions(xFrameOptionsOption)) + break + } + if ("xPermittedCrossDomainPolicies" in options && "permittedCrossDomainPolicies" in options) { + throw new Error("X-Permitted-Cross-Domain-Policies option was specified twice. Remove `permittedCrossDomainPolicies` to silence this warning.") + } + const xPermittedCrossDomainPoliciesOption = options.xPermittedCrossDomainPolicies ?? options.permittedCrossDomainPolicies + switch (xPermittedCrossDomainPoliciesOption) { + case undefined: + case true: + result.push(xPermittedCrossDomainPolicies()) + break + case false: + break + default: + result.push(xPermittedCrossDomainPolicies(xPermittedCrossDomainPoliciesOption)) + break + } + if ("xPoweredBy" in options && "hidePoweredBy" in options) { + throw new Error("X-Powered-By option was specified twice. Remove `hidePoweredBy` to silence this warning.") + } + const xPoweredByOption = options.xPoweredBy ?? options.hidePoweredBy + switch (xPoweredByOption) { + case undefined: + case true: + result.push(xPoweredBy()) + break + case false: + break + default: + console.warn("X-Powered-By does not take options. Remove the property to silence this warning.") + result.push(xPoweredBy()) + break + } + if ("xXssProtection" in options && "xssFilter" in options) { + throw new Error("X-XSS-Protection option was specified twice. Remove `xssFilter` to silence this warning.") + } + const xXssProtectionOption = options.xXssProtection ?? options.xssFilter + switch (xXssProtectionOption) { + case undefined: + case true: + result.push(xXssProtection()) + break + case false: + break + default: + console.warn("X-XSS-Protection does not take options. Remove the property to silence this warning.") + result.push(xXssProtection()) + break + } + return result +} +const helmet = Object.assign( + function helmet(options = {}) { + // People should be able to pass an options object with no prototype, + // so we want this optional chaining. + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + if (options.constructor?.name === "IncomingMessage") { + throw new Error("It appears you have done something like `app.use(helmet)`, but it should be `app.use(helmet())`.") + } + const middlewareFunctions = getMiddlewareFunctionsFromOptions(options) + return function helmetMiddleware(req, res, next) { + let middlewareIndex = 0 + ;(function internalNext(err) { + if (err) { + next(err) + return + } + const middlewareFunction = middlewareFunctions[middlewareIndex] + if (middlewareFunction) { + middlewareIndex++ + middlewareFunction(req, res, internalNext) + } else { + next() + } + })() + } + }, + { + contentSecurityPolicy, + crossOriginEmbedderPolicy, + crossOriginOpenerPolicy, + crossOriginResourcePolicy, + originAgentCluster, + referrerPolicy, + strictTransportSecurity, + xContentTypeOptions, + xDnsPrefetchControl, + xDownloadOptions, + xFrameOptions, + xPermittedCrossDomainPolicies, + xPoweredBy, + xXssProtection, + // Legacy aliases + dnsPrefetchControl: xDnsPrefetchControl, + xssFilter: xXssProtection, + permittedCrossDomainPolicies: xPermittedCrossDomainPolicies, + ieNoOpen: xDownloadOptions, + noSniff: xContentTypeOptions, + frameguard: xFrameOptions, + hidePoweredBy: xPoweredBy, + hsts: strictTransportSecurity + } +) + +export {contentSecurityPolicy, crossOriginEmbedderPolicy, crossOriginOpenerPolicy, crossOriginResourcePolicy, helmet as default, xDnsPrefetchControl as dnsPrefetchControl, xFrameOptions as frameguard, xPoweredBy as hidePoweredBy, strictTransportSecurity as hsts, xDownloadOptions as ieNoOpen, xContentTypeOptions as noSniff, originAgentCluster, xPermittedCrossDomainPolicies as permittedCrossDomainPolicies, referrerPolicy, strictTransportSecurity, xContentTypeOptions, xDnsPrefetchControl, xDownloadOptions, xFrameOptions, xPermittedCrossDomainPolicies, xPoweredBy, xXssProtection, xXssProtection as xssFilter} diff --git a/node_modules/helmet/package.json b/node_modules/helmet/package.json new file mode 100644 index 0000000..4088f52 --- /dev/null +++ b/node_modules/helmet/package.json @@ -0,0 +1,48 @@ +{ + "name": "helmet", + "description": "help secure Express/Connect apps with various HTTP headers", + "version": "8.0.0", + "author": "Adam Baldwin (https://evilpacket.net)", + "contributors": [ + "Evan Hahn (https://evanhahn.com)" + ], + "homepage": "https://helmetjs.github.io/", + "bugs": { + "url": "https://github.com/helmetjs/helmet/issues", + "email": "me@evanhahn.com" + }, + "repository": { + "type": "git", + "url": "git://github.com/helmetjs/helmet.git" + }, + "license": "MIT", + "keywords": [ + "express", + "security", + "headers", + "backend", + "content-security-policy", + "cross-origin-embedder-policy", + "cross-origin-opener-policy", + "cross-origin-resource-policy", + "origin-agent-cluster", + "referrer-policy", + "strict-transport-security", + "x-content-type-options", + "x-dns-prefetch-control", + "x-download-options", + "x-frame-options", + "x-permitted-cross-domain-policies", + "x-powered-by", + "x-xss-protection" + ], + "engines": { + "node": ">=18.0.0" + }, + "exports": { + "import": "./index.mjs", + "require": "./index.cjs" + }, + "main": "./index.cjs", + "types": "./index.d.cts" +} diff --git a/node_modules/morgan/HISTORY.md b/node_modules/morgan/HISTORY.md new file mode 100644 index 0000000..436db47 --- /dev/null +++ b/node_modules/morgan/HISTORY.md @@ -0,0 +1,215 @@ +1.10.0 / 2020-03-20 +=================== + + * Add `:total-time` token + * Fix trailing space in colored status code for `dev` format + * deps: basic-auth@~2.0.1 + - deps: safe-buffer@5.1.2 + * deps: depd@~2.0.0 + - Replace internal `eval` usage with `Function` constructor + - Use instance methods on `process` to check for listeners + * deps: on-headers@~1.0.2 + - Fix `res.writeHead` patch missing return value + +1.9.1 / 2018-09-10 +================== + + * Fix using special characters in format + * deps: depd@~1.1.2 + - perf: remove argument reassignment + +1.9.0 / 2017-09-26 +================== + + * Use `res.headersSent` when available + * deps: basic-auth@~2.0.0 + - Use `safe-buffer` for improved Buffer API + * deps: debug@2.6.9 + * deps: depd@~1.1.1 + - Remove unnecessary `Buffer` loading + +1.8.2 / 2017-05-23 +================== + + * deps: debug@2.6.8 + - Fix `DEBUG_MAX_ARRAY_LENGTH` + - deps: ms@2.0.0 + +1.8.1 / 2017-02-04 +================== + + * deps: debug@2.6.1 + - Fix deprecation messages in WebStorm and other editors + - Undeprecate `DEBUG_FD` set to `1` or `2` + +1.8.0 / 2017-02-04 +================== + + * Fix sending unnecessary `undefined` argument to token functions + * deps: basic-auth@~1.1.0 + * deps: debug@2.6.0 + - Allow colors in workers + - Deprecated `DEBUG_FD` environment variable + - Fix error when running under React Native + - Use same color for same namespace + - deps: ms@0.7.2 + * perf: enable strict mode in compiled functions + +1.7.0 / 2016-02-18 +================== + + * Add `digits` argument to `response-time` token + * deps: depd@~1.1.0 + - Enable strict mode in more places + - Support web browser loading + * deps: on-headers@~1.0.1 + - perf: enable strict mode + +1.6.1 / 2015-07-03 +================== + + * deps: basic-auth@~1.0.3 + +1.6.0 / 2015-06-12 +================== + + * Add `morgan.compile(format)` export + * Do not color 1xx status codes in `dev` format + * Fix `response-time` token to not include response latency + * Fix `status` token incorrectly displaying before response in `dev` format + * Fix token return values to be `undefined` or a string + * Improve representation of multiple headers in `req` and `res` tokens + * Use `res.getHeader` in `res` token + * deps: basic-auth@~1.0.2 + - perf: enable strict mode + - perf: hoist regular expression + - perf: parse with regular expressions + - perf: remove argument reassignment + * deps: on-finished@~2.3.0 + - Add defined behavior for HTTP `CONNECT` requests + - Add defined behavior for HTTP `Upgrade` requests + - deps: ee-first@1.1.1 + * pref: enable strict mode + * pref: reduce function closure scopes + * pref: remove dynamic compile on every request for `dev` format + * pref: remove an argument reassignment + * pref: skip function call without `skip` option + +1.5.3 / 2015-05-10 +================== + + * deps: basic-auth@~1.0.1 + * deps: debug@~2.2.0 + - deps: ms@0.7.1 + * deps: depd@~1.0.1 + * deps: on-finished@~2.2.1 + - Fix `isFinished(req)` when data buffered + +1.5.2 / 2015-03-15 +================== + + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + +1.5.1 / 2014-12-31 +================== + + * deps: debug@~2.1.1 + * deps: on-finished@~2.2.0 + +1.5.0 / 2014-11-06 +================== + + * Add multiple date formats + - `clf` for the common log format + - `iso` for the common ISO 8601 date time format + - `web` for the common RFC 1123 date time format + * Deprecate `buffer` option + * Fix date format in `common` and `combined` formats + * Fix token arguments to accept values with `"` + +1.4.1 / 2014-10-22 +================== + + * deps: on-finished@~2.1.1 + - Fix handling of pipelined requests + +1.4.0 / 2014-10-16 +================== + + * Add `debug` messages + * deps: depd@~1.0.0 + +1.3.2 / 2014-09-27 +================== + + * Fix `req.ip` integration when `immediate: false` + +1.3.1 / 2014-09-14 +================== + + * Remove un-used `bytes` dependency + * deps: depd@0.4.5 + +1.3.0 / 2014-09-01 +================== + + * Assert if `format` is not a function or string + +1.2.3 / 2014-08-16 +================== + + * deps: on-finished@2.1.0 + +1.2.2 / 2014-07-27 +================== + + * deps: depd@0.4.4 + - Work-around v8 generating empty stack traces + +1.2.1 / 2014-07-26 +================== + + * deps: depd@0.4.3 + - Fix exception when global `Error.stackTraceLimit` is too low + +1.2.0 / 2014-07-19 +================== + + * Add `:remote-user` token + * Add `combined` log format + * Add `common` log format + * Add `morgan(format, options)` function signature + * Deprecate `default` format -- use `combined` format instead + * Deprecate not providing a format + * Remove non-standard grey color from `dev` format + +1.1.1 / 2014-05-20 +================== + + * simplify method to get remote address + +1.1.0 / 2014-05-18 +================== + + * "dev" format will use same tokens as other formats + * `:response-time` token is now empty when immediate used + * `:response-time` token is now monotonic + * `:response-time` token has precision to 1 μs + * fix `:status` + immediate output in node.js 0.8 + * improve `buffer` option to prevent indefinite event loop holding + * deps: bytes@1.0.0 + - add negative support + +1.0.1 / 2014-05-04 +================== + + * Make buffer unique per morgan instance + * deps: bytes@0.3.0 + * added terabyte support + +1.0.0 / 2014-02-08 +================== + + * Initial release diff --git a/node_modules/morgan/LICENSE b/node_modules/morgan/LICENSE new file mode 100644 index 0000000..3fefed9 --- /dev/null +++ b/node_modules/morgan/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2014-2017 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/morgan/README.md b/node_modules/morgan/README.md new file mode 100644 index 0000000..fc1c4b4 --- /dev/null +++ b/node_modules/morgan/README.md @@ -0,0 +1,417 @@ +# morgan + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +HTTP request logger middleware for node.js + +> Named after [Dexter](http://en.wikipedia.org/wiki/Dexter_Morgan), a show you should not watch until completion. + +## API + + + +```js +var morgan = require('morgan') +``` + +### morgan(format, options) + +Create a new morgan logger middleware function using the given `format` and `options`. +The `format` argument may be a string of a predefined name (see below for the names), +a string of a format string, or a function that will produce a log entry. + +The `format` function will be called with three arguments `tokens`, `req`, and `res`, +where `tokens` is an object with all defined tokens, `req` is the HTTP request and `res` +is the HTTP response. The function is expected to return a string that will be the log +line, or `undefined` / `null` to skip logging. + +#### Using a predefined format string + + + +```js +morgan('tiny') +``` + +#### Using format string of predefined tokens + + + +```js +morgan(':method :url :status :res[content-length] - :response-time ms') +``` + +#### Using a custom format function + + + +``` js +morgan(function (tokens, req, res) { + return [ + tokens.method(req, res), + tokens.url(req, res), + tokens.status(req, res), + tokens.res(req, res, 'content-length'), '-', + tokens['response-time'](req, res), 'ms' + ].join(' ') +}) +``` + +#### Options + +Morgan accepts these properties in the options object. + +##### immediate + +Write log line on request instead of response. This means that a requests will +be logged even if the server crashes, _but data from the response (like the +response code, content length, etc.) cannot be logged_. + +##### skip + +Function to determine if logging is skipped, defaults to `false`. This function +will be called as `skip(req, res)`. + + + +```js +// EXAMPLE: only log error responses +morgan('combined', { + skip: function (req, res) { return res.statusCode < 400 } +}) +``` + +##### stream + +Output stream for writing log lines, defaults to `process.stdout`. + +#### Predefined Formats + +There are various pre-defined formats provided: + +##### combined + +Standard Apache combined log output. + +``` +:remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent" +``` + +##### common + +Standard Apache common log output. + +``` +:remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] +``` + +##### dev + +Concise output colored by response status for development use. The `:status` +token will be colored green for success codes, red for server error codes, +yellow for client error codes, cyan for redirection codes, and uncolored +for information codes. + +``` +:method :url :status :response-time ms - :res[content-length] +``` + +##### short + +Shorter than default, also including response time. + +``` +:remote-addr :remote-user :method :url HTTP/:http-version :status :res[content-length] - :response-time ms +``` + +##### tiny + +The minimal output. + +``` +:method :url :status :res[content-length] - :response-time ms +``` + +#### Tokens + +##### Creating new tokens + +To define a token, simply invoke `morgan.token()` with the name and a callback function. +This callback function is expected to return a string value. The value returned is then +available as ":type" in this case: + + + +```js +morgan.token('type', function (req, res) { return req.headers['content-type'] }) +``` + +Calling `morgan.token()` using the same name as an existing token will overwrite that +token definition. + +The token function is expected to be called with the arguments `req` and `res`, representing +the HTTP request and HTTP response. Additionally, the token can accept further arguments of +it's choosing to customize behavior. + +##### :date[format] + +The current date and time in UTC. The available formats are: + + - `clf` for the common log format (`"10/Oct/2000:13:55:36 +0000"`) + - `iso` for the common ISO 8601 date time format (`2000-10-10T13:55:36.000Z`) + - `web` for the common RFC 1123 date time format (`Tue, 10 Oct 2000 13:55:36 GMT`) + +If no format is given, then the default is `web`. + +##### :http-version + +The HTTP version of the request. + +##### :method + +The HTTP method of the request. + +##### :referrer + +The Referrer header of the request. This will use the standard mis-spelled Referer header if exists, otherwise Referrer. + +##### :remote-addr + +The remote address of the request. This will use `req.ip`, otherwise the standard `req.connection.remoteAddress` value (socket address). + +##### :remote-user + +The user authenticated as part of Basic auth for the request. + +##### :req[header] + +The given `header` of the request. If the header is not present, the +value will be displayed as `"-"` in the log. + +##### :res[header] + +The given `header` of the response. If the header is not present, the +value will be displayed as `"-"` in the log. + +##### :response-time[digits] + +The time between the request coming into `morgan` and when the response +headers are written, in milliseconds. + +The `digits` argument is a number that specifies the number of digits to +include on the number, defaulting to `3`, which provides microsecond precision. + +##### :status + +The status code of the response. + +If the request/response cycle completes before a response was sent to the +client (for example, the TCP socket closed prematurely by a client aborting +the request), then the status will be empty (displayed as `"-"` in the log). + +##### :total-time[digits] + +The time between the request coming into `morgan` and when the response +has finished being written out to the connection, in milliseconds. + +The `digits` argument is a number that specifies the number of digits to +include on the number, defaulting to `3`, which provides microsecond precision. + +##### :url + +The URL of the request. This will use `req.originalUrl` if exists, otherwise `req.url`. + +##### :user-agent + +The contents of the User-Agent header of the request. + +### morgan.compile(format) + +Compile a format string into a `format` function for use by `morgan`. A format string +is a string that represents a single log line and can utilize token syntax. +Tokens are references by `:token-name`. If tokens accept arguments, they can +be passed using `[]`, for example: `:token-name[pretty]` would pass the string +`'pretty'` as an argument to the token `token-name`. + +The function returned from `morgan.compile` takes three arguments `tokens`, `req`, and +`res`, where `tokens` is object with all defined tokens, `req` is the HTTP request and +`res` is the HTTP response. The function will return a string that will be the log line, +or `undefined` / `null` to skip logging. + +Normally formats are defined using `morgan.format(name, format)`, but for certain +advanced uses, this compile function is directly available. + +## Examples + +### express/connect + +Simple app that will log all request in the Apache combined format to STDOUT + +```js +var express = require('express') +var morgan = require('morgan') + +var app = express() + +app.use(morgan('combined')) + +app.get('/', function (req, res) { + res.send('hello, world!') +}) +``` + +### vanilla http server + +Simple app that will log all request in the Apache combined format to STDOUT + +```js +var finalhandler = require('finalhandler') +var http = require('http') +var morgan = require('morgan') + +// create "middleware" +var logger = morgan('combined') + +http.createServer(function (req, res) { + var done = finalhandler(req, res) + logger(req, res, function (err) { + if (err) return done(err) + + // respond to request + res.setHeader('content-type', 'text/plain') + res.end('hello, world!') + }) +}) +``` + +### write logs to a file + +#### single file + +Simple app that will log all requests in the Apache combined format to the file +`access.log`. + +```js +var express = require('express') +var fs = require('fs') +var morgan = require('morgan') +var path = require('path') + +var app = express() + +// create a write stream (in append mode) +var accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' }) + +// setup the logger +app.use(morgan('combined', { stream: accessLogStream })) + +app.get('/', function (req, res) { + res.send('hello, world!') +}) +``` + +#### log file rotation + +Simple app that will log all requests in the Apache combined format to one log +file per day in the `log/` directory using the +[rotating-file-stream module](https://www.npmjs.com/package/rotating-file-stream). + +```js +var express = require('express') +var morgan = require('morgan') +var path = require('path') +var rfs = require('rotating-file-stream') // version 2.x + +var app = express() + +// create a rotating write stream +var accessLogStream = rfs.createStream('access.log', { + interval: '1d', // rotate daily + path: path.join(__dirname, 'log') +}) + +// setup the logger +app.use(morgan('combined', { stream: accessLogStream })) + +app.get('/', function (req, res) { + res.send('hello, world!') +}) +``` + +### split / dual logging + +The `morgan` middleware can be used as many times as needed, enabling +combinations like: + + * Log entry on request and one on response + * Log all requests to file, but errors to console + * ... and more! + +Sample app that will log all requests to a file using Apache format, but +error responses are logged to the console: + +```js +var express = require('express') +var fs = require('fs') +var morgan = require('morgan') +var path = require('path') + +var app = express() + +// log only 4xx and 5xx responses to console +app.use(morgan('dev', { + skip: function (req, res) { return res.statusCode < 400 } +})) + +// log all requests to access.log +app.use(morgan('common', { + stream: fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' }) +})) + +app.get('/', function (req, res) { + res.send('hello, world!') +}) +``` + +### use custom token formats + +Sample app that will use custom token formats. This adds an ID to all requests and displays it using the `:id` token. + +```js +var express = require('express') +var morgan = require('morgan') +var uuid = require('node-uuid') + +morgan.token('id', function getId (req) { + return req.id +}) + +var app = express() + +app.use(assignId) +app.use(morgan(':id :method :url :response-time')) + +app.get('/', function (req, res) { + res.send('hello, world!') +}) + +function assignId (req, res, next) { + req.id = uuid.v4() + next() +} +``` + +## License + +[MIT](LICENSE) + +[coveralls-image]: https://badgen.net/coveralls/c/github/expressjs/morgan/master +[coveralls-url]: https://coveralls.io/r/expressjs/morgan?branch=master +[npm-downloads-image]: https://badgen.net/npm/dm/morgan +[npm-url]: https://npmjs.org/package/morgan +[npm-version-image]: https://badgen.net/npm/v/morgan +[travis-image]: https://badgen.net/travis/expressjs/morgan/master +[travis-url]: https://travis-ci.org/expressjs/morgan diff --git a/node_modules/morgan/index.js b/node_modules/morgan/index.js new file mode 100644 index 0000000..b33c4f2 --- /dev/null +++ b/node_modules/morgan/index.js @@ -0,0 +1,544 @@ +/*! + * morgan + * Copyright(c) 2010 Sencha Inc. + * Copyright(c) 2011 TJ Holowaychuk + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = morgan +module.exports.compile = compile +module.exports.format = format +module.exports.token = token + +/** + * Module dependencies. + * @private + */ + +var auth = require('basic-auth') +var debug = require('debug')('morgan') +var deprecate = require('depd')('morgan') +var onFinished = require('on-finished') +var onHeaders = require('on-headers') + +/** + * Array of CLF month names. + * @private + */ + +var CLF_MONTH = [ + 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', + 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' +] + +/** + * Default log buffer duration. + * @private + */ + +var DEFAULT_BUFFER_DURATION = 1000 + +/** + * Create a logger middleware. + * + * @public + * @param {String|Function} format + * @param {Object} [options] + * @return {Function} middleware + */ + +function morgan (format, options) { + var fmt = format + var opts = options || {} + + if (format && typeof format === 'object') { + opts = format + fmt = opts.format || 'default' + + // smart deprecation message + deprecate('morgan(options): use morgan(' + (typeof fmt === 'string' ? JSON.stringify(fmt) : 'format') + ', options) instead') + } + + if (fmt === undefined) { + deprecate('undefined format: specify a format') + } + + // output on request instead of response + var immediate = opts.immediate + + // check if log entry should be skipped + var skip = opts.skip || false + + // format function + var formatLine = typeof fmt !== 'function' + ? getFormatFunction(fmt) + : fmt + + // stream + var buffer = opts.buffer + var stream = opts.stream || process.stdout + + // buffering support + if (buffer) { + deprecate('buffer option') + + // flush interval + var interval = typeof buffer !== 'number' + ? DEFAULT_BUFFER_DURATION + : buffer + + // swap the stream + stream = createBufferStream(stream, interval) + } + + return function logger (req, res, next) { + // request data + req._startAt = undefined + req._startTime = undefined + req._remoteAddress = getip(req) + + // response data + res._startAt = undefined + res._startTime = undefined + + // record request start + recordStartTime.call(req) + + function logRequest () { + if (skip !== false && skip(req, res)) { + debug('skip request') + return + } + + var line = formatLine(morgan, req, res) + + if (line == null) { + debug('skip line') + return + } + + debug('log request') + stream.write(line + '\n') + }; + + if (immediate) { + // immediate log + logRequest() + } else { + // record response start + onHeaders(res, recordStartTime) + + // log when response finished + onFinished(res, logRequest) + } + + next() + } +} + +/** + * Apache combined log format. + */ + +morgan.format('combined', ':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"') + +/** + * Apache common log format. + */ + +morgan.format('common', ':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length]') + +/** + * Default format. + */ + +morgan.format('default', ':remote-addr - :remote-user [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"') +deprecate.property(morgan, 'default', 'default format: use combined format') + +/** + * Short format. + */ + +morgan.format('short', ':remote-addr :remote-user :method :url HTTP/:http-version :status :res[content-length] - :response-time ms') + +/** + * Tiny format. + */ + +morgan.format('tiny', ':method :url :status :res[content-length] - :response-time ms') + +/** + * dev (colored) + */ + +morgan.format('dev', function developmentFormatLine (tokens, req, res) { + // get the status code if response written + var status = headersSent(res) + ? res.statusCode + : undefined + + // get status color + var color = status >= 500 ? 31 // red + : status >= 400 ? 33 // yellow + : status >= 300 ? 36 // cyan + : status >= 200 ? 32 // green + : 0 // no color + + // get colored function + var fn = developmentFormatLine[color] + + if (!fn) { + // compile + fn = developmentFormatLine[color] = compile('\x1b[0m:method :url \x1b[' + + color + 'm:status\x1b[0m :response-time ms - :res[content-length]\x1b[0m') + } + + return fn(tokens, req, res) +}) + +/** + * request url + */ + +morgan.token('url', function getUrlToken (req) { + return req.originalUrl || req.url +}) + +/** + * request method + */ + +morgan.token('method', function getMethodToken (req) { + return req.method +}) + +/** + * response time in milliseconds + */ + +morgan.token('response-time', function getResponseTimeToken (req, res, digits) { + if (!req._startAt || !res._startAt) { + // missing request and/or response start time + return + } + + // calculate diff + var ms = (res._startAt[0] - req._startAt[0]) * 1e3 + + (res._startAt[1] - req._startAt[1]) * 1e-6 + + // return truncated value + return ms.toFixed(digits === undefined ? 3 : digits) +}) + +/** + * total time in milliseconds + */ + +morgan.token('total-time', function getTotalTimeToken (req, res, digits) { + if (!req._startAt || !res._startAt) { + // missing request and/or response start time + return + } + + // time elapsed from request start + var elapsed = process.hrtime(req._startAt) + + // cover to milliseconds + var ms = (elapsed[0] * 1e3) + (elapsed[1] * 1e-6) + + // return truncated value + return ms.toFixed(digits === undefined ? 3 : digits) +}) + +/** + * current date + */ + +morgan.token('date', function getDateToken (req, res, format) { + var date = new Date() + + switch (format || 'web') { + case 'clf': + return clfdate(date) + case 'iso': + return date.toISOString() + case 'web': + return date.toUTCString() + } +}) + +/** + * response status code + */ + +morgan.token('status', function getStatusToken (req, res) { + return headersSent(res) + ? String(res.statusCode) + : undefined +}) + +/** + * normalized referrer + */ + +morgan.token('referrer', function getReferrerToken (req) { + return req.headers.referer || req.headers.referrer +}) + +/** + * remote address + */ + +morgan.token('remote-addr', getip) + +/** + * remote user + */ + +morgan.token('remote-user', function getRemoteUserToken (req) { + // parse basic credentials + var credentials = auth(req) + + // return username + return credentials + ? credentials.name + : undefined +}) + +/** + * HTTP version + */ + +morgan.token('http-version', function getHttpVersionToken (req) { + return req.httpVersionMajor + '.' + req.httpVersionMinor +}) + +/** + * UA string + */ + +morgan.token('user-agent', function getUserAgentToken (req) { + return req.headers['user-agent'] +}) + +/** + * request header + */ + +morgan.token('req', function getRequestToken (req, res, field) { + // get header + var header = req.headers[field.toLowerCase()] + + return Array.isArray(header) + ? header.join(', ') + : header +}) + +/** + * response header + */ + +morgan.token('res', function getResponseHeader (req, res, field) { + if (!headersSent(res)) { + return undefined + } + + // get header + var header = res.getHeader(field) + + return Array.isArray(header) + ? header.join(', ') + : header +}) + +/** + * Format a Date in the common log format. + * + * @private + * @param {Date} dateTime + * @return {string} + */ + +function clfdate (dateTime) { + var date = dateTime.getUTCDate() + var hour = dateTime.getUTCHours() + var mins = dateTime.getUTCMinutes() + var secs = dateTime.getUTCSeconds() + var year = dateTime.getUTCFullYear() + + var month = CLF_MONTH[dateTime.getUTCMonth()] + + return pad2(date) + '/' + month + '/' + year + + ':' + pad2(hour) + ':' + pad2(mins) + ':' + pad2(secs) + + ' +0000' +} + +/** + * Compile a format string into a function. + * + * @param {string} format + * @return {function} + * @public + */ + +function compile (format) { + if (typeof format !== 'string') { + throw new TypeError('argument format must be a string') + } + + var fmt = String(JSON.stringify(format)) + var js = ' "use strict"\n return ' + fmt.replace(/:([-\w]{2,})(?:\[([^\]]+)\])?/g, function (_, name, arg) { + var tokenArguments = 'req, res' + var tokenFunction = 'tokens[' + String(JSON.stringify(name)) + ']' + + if (arg !== undefined) { + tokenArguments += ', ' + String(JSON.stringify(arg)) + } + + return '" +\n (' + tokenFunction + '(' + tokenArguments + ') || "-") + "' + }) + + // eslint-disable-next-line no-new-func + return new Function('tokens, req, res', js) +} + +/** + * Create a basic buffering stream. + * + * @param {object} stream + * @param {number} interval + * @public + */ + +function createBufferStream (stream, interval) { + var buf = [] + var timer = null + + // flush function + function flush () { + timer = null + stream.write(buf.join('')) + buf.length = 0 + } + + // write function + function write (str) { + if (timer === null) { + timer = setTimeout(flush, interval) + } + + buf.push(str) + } + + // return a minimal "stream" + return { write: write } +} + +/** + * Define a format with the given name. + * + * @param {string} name + * @param {string|function} fmt + * @public + */ + +function format (name, fmt) { + morgan[name] = fmt + return this +} + +/** + * Lookup and compile a named format function. + * + * @param {string} name + * @return {function} + * @public + */ + +function getFormatFunction (name) { + // lookup format + var fmt = morgan[name] || name || morgan.default + + // return compiled format + return typeof fmt !== 'function' + ? compile(fmt) + : fmt +} + +/** + * Get request IP address. + * + * @private + * @param {IncomingMessage} req + * @return {string} + */ + +function getip (req) { + return req.ip || + req._remoteAddress || + (req.connection && req.connection.remoteAddress) || + undefined +} + +/** + * Determine if the response headers have been sent. + * + * @param {object} res + * @returns {boolean} + * @private + */ + +function headersSent (res) { + // istanbul ignore next: node.js 0.8 support + return typeof res.headersSent !== 'boolean' + ? Boolean(res._header) + : res.headersSent +} + +/** + * Pad number to two digits. + * + * @private + * @param {number} num + * @return {string} + */ + +function pad2 (num) { + var str = String(num) + + // istanbul ignore next: num is current datetime + return (str.length === 1 ? '0' : '') + str +} + +/** + * Record the start time. + * @private + */ + +function recordStartTime () { + this._startAt = process.hrtime() + this._startTime = new Date() +} + +/** + * Define a token function with the given name, + * and callback fn(req, res). + * + * @param {string} name + * @param {function} fn + * @public + */ + +function token (name, fn) { + morgan[name] = fn + return this +} diff --git a/node_modules/morgan/package.json b/node_modules/morgan/package.json new file mode 100644 index 0000000..b25a647 --- /dev/null +++ b/node_modules/morgan/package.json @@ -0,0 +1,52 @@ +{ + "name": "morgan", + "description": "HTTP request logger middleware for node.js", + "version": "1.10.0", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "keywords": [ + "express", + "http", + "logger", + "middleware" + ], + "repository": "expressjs/morgan", + "dependencies": { + "basic-auth": "~2.0.1", + "debug": "2.6.9", + "depd": "~2.0.0", + "on-finished": "~2.3.0", + "on-headers": "~1.0.2" + }, + "devDependencies": { + "eslint": "6.8.0", + "eslint-config-standard": "14.1.0", + "eslint-plugin-import": "2.20.1", + "eslint-plugin-markdown": "1.0.2", + "eslint-plugin-node": "9.2.0", + "eslint-plugin-promise": "4.2.1", + "eslint-plugin-standard": "4.0.1", + "mocha": "7.1.1", + "nyc": "15.0.0", + "split": "1.0.1", + "supertest": "4.0.2" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.8.0" + }, + "scripts": { + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --check-leaks --reporter spec --bail", + "test-ci": "nyc --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/node_modules/ms/index.js b/node_modules/ms/index.js new file mode 100644 index 0000000..6a522b1 --- /dev/null +++ b/node_modules/ms/index.js @@ -0,0 +1,152 @@ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isNaN(val) === false) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + if (ms >= d) { + return Math.round(ms / d) + 'd'; + } + if (ms >= h) { + return Math.round(ms / h) + 'h'; + } + if (ms >= m) { + return Math.round(ms / m) + 'm'; + } + if (ms >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + return plural(ms, d, 'day') || + plural(ms, h, 'hour') || + plural(ms, m, 'minute') || + plural(ms, s, 'second') || + ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, n, name) { + if (ms < n) { + return; + } + if (ms < n * 1.5) { + return Math.floor(ms / n) + ' ' + name; + } + return Math.ceil(ms / n) + ' ' + name + 's'; +} diff --git a/node_modules/ms/license.md b/node_modules/ms/license.md new file mode 100644 index 0000000..69b6125 --- /dev/null +++ b/node_modules/ms/license.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Zeit, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/ms/package.json b/node_modules/ms/package.json new file mode 100644 index 0000000..6a31c81 --- /dev/null +++ b/node_modules/ms/package.json @@ -0,0 +1,37 @@ +{ + "name": "ms", + "version": "2.0.0", + "description": "Tiny milisecond conversion utility", + "repository": "zeit/ms", + "main": "./index", + "files": [ + "index.js" + ], + "scripts": { + "precommit": "lint-staged", + "lint": "eslint lib/* bin/*", + "test": "mocha tests.js" + }, + "eslintConfig": { + "extends": "eslint:recommended", + "env": { + "node": true, + "es6": true + } + }, + "lint-staged": { + "*.js": [ + "npm run lint", + "prettier --single-quote --write", + "git add" + ] + }, + "license": "MIT", + "devDependencies": { + "eslint": "3.19.0", + "expect.js": "0.3.1", + "husky": "0.13.3", + "lint-staged": "3.4.1", + "mocha": "3.4.1" + } +} diff --git a/node_modules/ms/readme.md b/node_modules/ms/readme.md new file mode 100644 index 0000000..84a9974 --- /dev/null +++ b/node_modules/ms/readme.md @@ -0,0 +1,51 @@ +# ms + +[![Build Status](https://travis-ci.org/zeit/ms.svg?branch=master)](https://travis-ci.org/zeit/ms) +[![Slack Channel](http://zeit-slackin.now.sh/badge.svg)](https://zeit.chat/) + +Use this package to easily convert various time formats to milliseconds. + +## Examples + +```js +ms('2 days') // 172800000 +ms('1d') // 86400000 +ms('10h') // 36000000 +ms('2.5 hrs') // 9000000 +ms('2h') // 7200000 +ms('1m') // 60000 +ms('5s') // 5000 +ms('1y') // 31557600000 +ms('100') // 100 +``` + +### Convert from milliseconds + +```js +ms(60000) // "1m" +ms(2 * 60000) // "2m" +ms(ms('10 hours')) // "10h" +``` + +### Time format written-out + +```js +ms(60000, { long: true }) // "1 minute" +ms(2 * 60000, { long: true }) // "2 minutes" +ms(ms('10 hours'), { long: true }) // "10 hours" +``` + +## Features + +- Works both in [node](https://nodejs.org) and in the browser. +- If a number is supplied to `ms`, a string with a unit is returned. +- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`). +- If you pass a string with a number and a valid unit, the number of equivalent ms is returned. + +## Caught a bug? + +1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device +2. Link the package to the global module directory: `npm link` +3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, node will now use your clone of ms! + +As always, you can run the tests using: `npm test` diff --git a/node_modules/on-finished/HISTORY.md b/node_modules/on-finished/HISTORY.md new file mode 100644 index 0000000..98ff0e9 --- /dev/null +++ b/node_modules/on-finished/HISTORY.md @@ -0,0 +1,88 @@ +2.3.0 / 2015-05-26 +================== + + * Add defined behavior for HTTP `CONNECT` requests + * Add defined behavior for HTTP `Upgrade` requests + * deps: ee-first@1.1.1 + +2.2.1 / 2015-04-22 +================== + + * Fix `isFinished(req)` when data buffered + +2.2.0 / 2014-12-22 +================== + + * Add message object to callback arguments + +2.1.1 / 2014-10-22 +================== + + * Fix handling of pipelined requests + +2.1.0 / 2014-08-16 +================== + + * Check if `socket` is detached + * Return `undefined` for `isFinished` if state unknown + +2.0.0 / 2014-08-16 +================== + + * Add `isFinished` function + * Move to `jshttp` organization + * Remove support for plain socket argument + * Rename to `on-finished` + * Support both `req` and `res` as arguments + * deps: ee-first@1.0.5 + +1.2.2 / 2014-06-10 +================== + + * Reduce listeners added to emitters + - avoids "event emitter leak" warnings when used multiple times on same request + +1.2.1 / 2014-06-08 +================== + + * Fix returned value when already finished + +1.2.0 / 2014-06-05 +================== + + * Call callback when called on already-finished socket + +1.1.4 / 2014-05-27 +================== + + * Support node.js 0.8 + +1.1.3 / 2014-04-30 +================== + + * Make sure errors passed as instanceof `Error` + +1.1.2 / 2014-04-18 +================== + + * Default the `socket` to passed-in object + +1.1.1 / 2014-01-16 +================== + + * Rename module to `finished` + +1.1.0 / 2013-12-25 +================== + + * Call callback when called on already-errored socket + +1.0.1 / 2013-12-20 +================== + + * Actually pass the error to the callback + +1.0.0 / 2013-12-20 +================== + + * Initial release diff --git a/node_modules/on-finished/LICENSE b/node_modules/on-finished/LICENSE new file mode 100644 index 0000000..5931fd2 --- /dev/null +++ b/node_modules/on-finished/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2013 Jonathan Ong +Copyright (c) 2014 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/on-finished/README.md b/node_modules/on-finished/README.md new file mode 100644 index 0000000..a0e1157 --- /dev/null +++ b/node_modules/on-finished/README.md @@ -0,0 +1,154 @@ +# on-finished + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Execute a callback when a HTTP request closes, finishes, or errors. + +## Install + +```sh +$ npm install on-finished +``` + +## API + +```js +var onFinished = require('on-finished') +``` + +### onFinished(res, listener) + +Attach a listener to listen for the response to finish. The listener will +be invoked only once when the response finished. If the response finished +to an error, the first argument will contain the error. If the response +has already finished, the listener will be invoked. + +Listening to the end of a response would be used to close things associated +with the response, like open files. + +Listener is invoked as `listener(err, res)`. + +```js +onFinished(res, function (err, res) { + // clean up open fds, etc. + // err contains the error is request error'd +}) +``` + +### onFinished(req, listener) + +Attach a listener to listen for the request to finish. The listener will +be invoked only once when the request finished. If the request finished +to an error, the first argument will contain the error. If the request +has already finished, the listener will be invoked. + +Listening to the end of a request would be used to know when to continue +after reading the data. + +Listener is invoked as `listener(err, req)`. + +```js +var data = '' + +req.setEncoding('utf8') +res.on('data', function (str) { + data += str +}) + +onFinished(req, function (err, req) { + // data is read unless there is err +}) +``` + +### onFinished.isFinished(res) + +Determine if `res` is already finished. This would be useful to check and +not even start certain operations if the response has already finished. + +### onFinished.isFinished(req) + +Determine if `req` is already finished. This would be useful to check and +not even start certain operations if the request has already finished. + +## Special Node.js requests + +### HTTP CONNECT method + +The meaning of the `CONNECT` method from RFC 7231, section 4.3.6: + +> The CONNECT method requests that the recipient establish a tunnel to +> the destination origin server identified by the request-target and, +> if successful, thereafter restrict its behavior to blind forwarding +> of packets, in both directions, until the tunnel is closed. Tunnels +> are commonly used to create an end-to-end virtual connection, through +> one or more proxies, which can then be secured using TLS (Transport +> Layer Security, [RFC5246]). + +In Node.js, these request objects come from the `'connect'` event on +the HTTP server. + +When this module is used on a HTTP `CONNECT` request, the request is +considered "finished" immediately, **due to limitations in the Node.js +interface**. This means if the `CONNECT` request contains a request entity, +the request will be considered "finished" even before it has been read. + +There is no such thing as a response object to a `CONNECT` request in +Node.js, so there is no support for for one. + +### HTTP Upgrade request + +The meaning of the `Upgrade` header from RFC 7230, section 6.1: + +> The "Upgrade" header field is intended to provide a simple mechanism +> for transitioning from HTTP/1.1 to some other protocol on the same +> connection. + +In Node.js, these request objects come from the `'upgrade'` event on +the HTTP server. + +When this module is used on a HTTP request with an `Upgrade` header, the +request is considered "finished" immediately, **due to limitations in the +Node.js interface**. This means if the `Upgrade` request contains a request +entity, the request will be considered "finished" even before it has been +read. + +There is no such thing as a response object to a `Upgrade` request in +Node.js, so there is no support for for one. + +## Example + +The following code ensures that file descriptors are always closed +once the response finishes. + +```js +var destroy = require('destroy') +var http = require('http') +var onFinished = require('on-finished') + +http.createServer(function onRequest(req, res) { + var stream = fs.createReadStream('package.json') + stream.pipe(res) + onFinished(res, function (err) { + destroy(stream) + }) +}) +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/on-finished.svg +[npm-url]: https://npmjs.org/package/on-finished +[node-version-image]: https://img.shields.io/node/v/on-finished.svg +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/on-finished/master.svg +[travis-url]: https://travis-ci.org/jshttp/on-finished +[coveralls-image]: https://img.shields.io/coveralls/jshttp/on-finished/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/on-finished?branch=master +[downloads-image]: https://img.shields.io/npm/dm/on-finished.svg +[downloads-url]: https://npmjs.org/package/on-finished diff --git a/node_modules/on-finished/index.js b/node_modules/on-finished/index.js new file mode 100644 index 0000000..9abd98f --- /dev/null +++ b/node_modules/on-finished/index.js @@ -0,0 +1,196 @@ +/*! + * on-finished + * Copyright(c) 2013 Jonathan Ong + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = onFinished +module.exports.isFinished = isFinished + +/** + * Module dependencies. + * @private + */ + +var first = require('ee-first') + +/** + * Variables. + * @private + */ + +/* istanbul ignore next */ +var defer = typeof setImmediate === 'function' + ? setImmediate + : function(fn){ process.nextTick(fn.bind.apply(fn, arguments)) } + +/** + * Invoke callback when the response has finished, useful for + * cleaning up resources afterwards. + * + * @param {object} msg + * @param {function} listener + * @return {object} + * @public + */ + +function onFinished(msg, listener) { + if (isFinished(msg) !== false) { + defer(listener, null, msg) + return msg + } + + // attach the listener to the message + attachListener(msg, listener) + + return msg +} + +/** + * Determine if message is already finished. + * + * @param {object} msg + * @return {boolean} + * @public + */ + +function isFinished(msg) { + var socket = msg.socket + + if (typeof msg.finished === 'boolean') { + // OutgoingMessage + return Boolean(msg.finished || (socket && !socket.writable)) + } + + if (typeof msg.complete === 'boolean') { + // IncomingMessage + return Boolean(msg.upgrade || !socket || !socket.readable || (msg.complete && !msg.readable)) + } + + // don't know + return undefined +} + +/** + * Attach a finished listener to the message. + * + * @param {object} msg + * @param {function} callback + * @private + */ + +function attachFinishedListener(msg, callback) { + var eeMsg + var eeSocket + var finished = false + + function onFinish(error) { + eeMsg.cancel() + eeSocket.cancel() + + finished = true + callback(error) + } + + // finished on first message event + eeMsg = eeSocket = first([[msg, 'end', 'finish']], onFinish) + + function onSocket(socket) { + // remove listener + msg.removeListener('socket', onSocket) + + if (finished) return + if (eeMsg !== eeSocket) return + + // finished on first socket event + eeSocket = first([[socket, 'error', 'close']], onFinish) + } + + if (msg.socket) { + // socket already assigned + onSocket(msg.socket) + return + } + + // wait for socket to be assigned + msg.on('socket', onSocket) + + if (msg.socket === undefined) { + // node.js 0.8 patch + patchAssignSocket(msg, onSocket) + } +} + +/** + * Attach the listener to the message. + * + * @param {object} msg + * @return {function} + * @private + */ + +function attachListener(msg, listener) { + var attached = msg.__onFinished + + // create a private single listener with queue + if (!attached || !attached.queue) { + attached = msg.__onFinished = createListener(msg) + attachFinishedListener(msg, attached) + } + + attached.queue.push(listener) +} + +/** + * Create listener on message. + * + * @param {object} msg + * @return {function} + * @private + */ + +function createListener(msg) { + function listener(err) { + if (msg.__onFinished === listener) msg.__onFinished = null + if (!listener.queue) return + + var queue = listener.queue + listener.queue = null + + for (var i = 0; i < queue.length; i++) { + queue[i](err, msg) + } + } + + listener.queue = [] + + return listener +} + +/** + * Patch ServerResponse.prototype.assignSocket for node.js 0.8. + * + * @param {ServerResponse} res + * @param {function} callback + * @private + */ + +function patchAssignSocket(res, callback) { + var assignSocket = res.assignSocket + + if (typeof assignSocket !== 'function') return + + // res.on('socket', callback) is broken in 0.8 + res.assignSocket = function _assignSocket(socket) { + assignSocket.call(this, socket) + callback(socket) + } +} diff --git a/node_modules/on-finished/package.json b/node_modules/on-finished/package.json new file mode 100644 index 0000000..b9df1bd --- /dev/null +++ b/node_modules/on-finished/package.json @@ -0,0 +1,31 @@ +{ + "name": "on-finished", + "description": "Execute a callback when a request closes, finishes, or errors", + "version": "2.3.0", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "repository": "jshttp/on-finished", + "dependencies": { + "ee-first": "1.1.1" + }, + "devDependencies": { + "istanbul": "0.3.9", + "mocha": "2.2.5" + }, + "engines": { + "node": ">= 0.8" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + } +} diff --git a/node_modules/on-headers/HISTORY.md b/node_modules/on-headers/HISTORY.md new file mode 100644 index 0000000..090598d --- /dev/null +++ b/node_modules/on-headers/HISTORY.md @@ -0,0 +1,21 @@ +1.0.2 / 2019-02-21 +================== + + * Fix `res.writeHead` patch missing return value + +1.0.1 / 2015-09-29 +================== + + * perf: enable strict mode + +1.0.0 / 2014-08-10 +================== + + * Honor `res.statusCode` change in `listener` + * Move to `jshttp` organization + * Prevent `arguments`-related de-opt + +0.0.0 / 2014-05-13 +================== + + * Initial implementation diff --git a/node_modules/on-headers/LICENSE b/node_modules/on-headers/LICENSE new file mode 100644 index 0000000..b7dce6c --- /dev/null +++ b/node_modules/on-headers/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/on-headers/README.md b/node_modules/on-headers/README.md new file mode 100644 index 0000000..ae84282 --- /dev/null +++ b/node_modules/on-headers/README.md @@ -0,0 +1,81 @@ +# on-headers + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Execute a listener when a response is about to write headers. + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install on-headers +``` + +## API + + + +```js +var onHeaders = require('on-headers') +``` + +### onHeaders(res, listener) + +This will add the listener `listener` to fire when headers are emitted for `res`. +The listener is passed the `response` object as it's context (`this`). Headers are +considered to be emitted only once, right before they are sent to the client. + +When this is called multiple times on the same `res`, the `listener`s are fired +in the reverse order they were added. + +## Examples + +```js +var http = require('http') +var onHeaders = require('on-headers') + +http + .createServer(onRequest) + .listen(3000) + +function addPoweredBy () { + // set if not set by end of request + if (!this.getHeader('X-Powered-By')) { + this.setHeader('X-Powered-By', 'Node.js') + } +} + +function onRequest (req, res) { + onHeaders(res, addPoweredBy) + + res.setHeader('Content-Type', 'text/plain') + res.end('hello!') +} +``` + +## Testing + +```sh +$ npm test +``` + +## License + +[MIT](LICENSE) + +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/on-headers/master +[coveralls-url]: https://coveralls.io/r/jshttp/on-headers?branch=master +[node-version-image]: https://badgen.net/npm/node/on-headers +[node-version-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/on-headers +[npm-url]: https://npmjs.org/package/on-headers +[npm-version-image]: https://badgen.net/npm/v/on-headers +[travis-image]: https://badgen.net/travis/jshttp/on-headers/master +[travis-url]: https://travis-ci.org/jshttp/on-headers diff --git a/node_modules/on-headers/index.js b/node_modules/on-headers/index.js new file mode 100644 index 0000000..7db6375 --- /dev/null +++ b/node_modules/on-headers/index.js @@ -0,0 +1,132 @@ +/*! + * on-headers + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = onHeaders + +/** + * Create a replacement writeHead method. + * + * @param {function} prevWriteHead + * @param {function} listener + * @private + */ + +function createWriteHead (prevWriteHead, listener) { + var fired = false + + // return function with core name and argument list + return function writeHead (statusCode) { + // set headers from arguments + var args = setWriteHeadHeaders.apply(this, arguments) + + // fire listener + if (!fired) { + fired = true + listener.call(this) + + // pass-along an updated status code + if (typeof args[0] === 'number' && this.statusCode !== args[0]) { + args[0] = this.statusCode + args.length = 1 + } + } + + return prevWriteHead.apply(this, args) + } +} + +/** + * Execute a listener when a response is about to write headers. + * + * @param {object} res + * @return {function} listener + * @public + */ + +function onHeaders (res, listener) { + if (!res) { + throw new TypeError('argument res is required') + } + + if (typeof listener !== 'function') { + throw new TypeError('argument listener must be a function') + } + + res.writeHead = createWriteHead(res.writeHead, listener) +} + +/** + * Set headers contained in array on the response object. + * + * @param {object} res + * @param {array} headers + * @private + */ + +function setHeadersFromArray (res, headers) { + for (var i = 0; i < headers.length; i++) { + res.setHeader(headers[i][0], headers[i][1]) + } +} + +/** + * Set headers contained in object on the response object. + * + * @param {object} res + * @param {object} headers + * @private + */ + +function setHeadersFromObject (res, headers) { + var keys = Object.keys(headers) + for (var i = 0; i < keys.length; i++) { + var k = keys[i] + if (k) res.setHeader(k, headers[k]) + } +} + +/** + * Set headers and other properties on the response object. + * + * @param {number} statusCode + * @private + */ + +function setWriteHeadHeaders (statusCode) { + var length = arguments.length + var headerIndex = length > 1 && typeof arguments[1] === 'string' + ? 2 + : 1 + + var headers = length >= headerIndex + 1 + ? arguments[headerIndex] + : undefined + + this.statusCode = statusCode + + if (Array.isArray(headers)) { + // handle array case + setHeadersFromArray(this, headers) + } else if (headers) { + // handle object case + setHeadersFromObject(this, headers) + } + + // copy leading arguments + var args = new Array(Math.min(length, headerIndex)) + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } + + return args +} diff --git a/node_modules/on-headers/package.json b/node_modules/on-headers/package.json new file mode 100644 index 0000000..1e9bf9e --- /dev/null +++ b/node_modules/on-headers/package.json @@ -0,0 +1,42 @@ +{ + "name": "on-headers", + "description": "Execute a listener when a response is about to write headers", + "version": "1.0.2", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "keywords": [ + "event", + "headers", + "http", + "onheaders" + ], + "repository": "jshttp/on-headers", + "devDependencies": { + "eslint": "5.14.1", + "eslint-config-standard": "12.0.0", + "eslint-plugin-import": "2.16.0", + "eslint-plugin-markdown": "1.0.0", + "eslint-plugin-node": "8.0.1", + "eslint-plugin-promise": "4.0.1", + "eslint-plugin-standard": "4.0.0", + "istanbul": "0.4.5", + "mocha": "6.0.1", + "supertest": "3.4.2" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/", + "version": "node scripts/version-history.js && git add HISTORY.md" + } +} diff --git a/node_modules/safe-buffer/LICENSE b/node_modules/safe-buffer/LICENSE new file mode 100644 index 0000000..0c068ce --- /dev/null +++ b/node_modules/safe-buffer/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Feross Aboukhadijeh + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/safe-buffer/README.md b/node_modules/safe-buffer/README.md new file mode 100644 index 0000000..e9a81af --- /dev/null +++ b/node_modules/safe-buffer/README.md @@ -0,0 +1,584 @@ +# safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] + +[travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg +[travis-url]: https://travis-ci.org/feross/safe-buffer +[npm-image]: https://img.shields.io/npm/v/safe-buffer.svg +[npm-url]: https://npmjs.org/package/safe-buffer +[downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg +[downloads-url]: https://npmjs.org/package/safe-buffer +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +#### Safer Node.js Buffer API + +**Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, +`Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** + +**Uses the built-in implementation when available.** + +## install + +``` +npm install safe-buffer +``` + +## usage + +The goal of this package is to provide a safe replacement for the node.js `Buffer`. + +It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to +the top of your node.js modules: + +```js +var Buffer = require('safe-buffer').Buffer + +// Existing buffer code will continue to work without issues: + +new Buffer('hey', 'utf8') +new Buffer([1, 2, 3], 'utf8') +new Buffer(obj) +new Buffer(16) // create an uninitialized buffer (potentially unsafe) + +// But you can use these new explicit APIs to make clear what you want: + +Buffer.from('hey', 'utf8') // convert from many types to a Buffer +Buffer.alloc(16) // create a zero-filled buffer (safe) +Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) +``` + +## api + +### Class Method: Buffer.from(array) + + +* `array` {Array} + +Allocates a new `Buffer` using an `array` of octets. + +```js +const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); + // creates a new Buffer containing ASCII bytes + // ['b','u','f','f','e','r'] +``` + +A `TypeError` will be thrown if `array` is not an `Array`. + +### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) + + +* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or + a `new ArrayBuffer()` +* `byteOffset` {Number} Default: `0` +* `length` {Number} Default: `arrayBuffer.length - byteOffset` + +When passed a reference to the `.buffer` property of a `TypedArray` instance, +the newly created `Buffer` will share the same allocated memory as the +TypedArray. + +```js +const arr = new Uint16Array(2); +arr[0] = 5000; +arr[1] = 4000; + +const buf = Buffer.from(arr.buffer); // shares the memory with arr; + +console.log(buf); + // Prints: + +// changing the TypedArray changes the Buffer also +arr[1] = 6000; + +console.log(buf); + // Prints: +``` + +The optional `byteOffset` and `length` arguments specify a memory range within +the `arrayBuffer` that will be shared by the `Buffer`. + +```js +const ab = new ArrayBuffer(10); +const buf = Buffer.from(ab, 0, 2); +console.log(buf.length); + // Prints: 2 +``` + +A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. + +### Class Method: Buffer.from(buffer) + + +* `buffer` {Buffer} + +Copies the passed `buffer` data onto a new `Buffer` instance. + +```js +const buf1 = Buffer.from('buffer'); +const buf2 = Buffer.from(buf1); + +buf1[0] = 0x61; +console.log(buf1.toString()); + // 'auffer' +console.log(buf2.toString()); + // 'buffer' (copy is not changed) +``` + +A `TypeError` will be thrown if `buffer` is not a `Buffer`. + +### Class Method: Buffer.from(str[, encoding]) + + +* `str` {String} String to encode. +* `encoding` {String} Encoding to use, Default: `'utf8'` + +Creates a new `Buffer` containing the given JavaScript string `str`. If +provided, the `encoding` parameter identifies the character encoding. +If not provided, `encoding` defaults to `'utf8'`. + +```js +const buf1 = Buffer.from('this is a tést'); +console.log(buf1.toString()); + // prints: this is a tést +console.log(buf1.toString('ascii')); + // prints: this is a tC)st + +const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); +console.log(buf2.toString()); + // prints: this is a tést +``` + +A `TypeError` will be thrown if `str` is not a string. + +### Class Method: Buffer.alloc(size[, fill[, encoding]]) + + +* `size` {Number} +* `fill` {Value} Default: `undefined` +* `encoding` {String} Default: `utf8` + +Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the +`Buffer` will be *zero-filled*. + +```js +const buf = Buffer.alloc(5); +console.log(buf); + // +``` + +The `size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +If `fill` is specified, the allocated `Buffer` will be initialized by calling +`buf.fill(fill)`. See [`buf.fill()`][] for more information. + +```js +const buf = Buffer.alloc(5, 'a'); +console.log(buf); + // +``` + +If both `fill` and `encoding` are specified, the allocated `Buffer` will be +initialized by calling `buf.fill(fill, encoding)`. For example: + +```js +const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); +console.log(buf); + // +``` + +Calling `Buffer.alloc(size)` can be significantly slower than the alternative +`Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance +contents will *never contain sensitive data*. + +A `TypeError` will be thrown if `size` is not a number. + +### Class Method: Buffer.allocUnsafe(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must +be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit +architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is +thrown. A zero-length Buffer will be created if a `size` less than or equal to +0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +```js +const buf = Buffer.allocUnsafe(5); +console.log(buf); + // + // (octets will be different, every time) +buf.fill(0); +console.log(buf); + // +``` + +A `TypeError` will be thrown if `size` is not a number. + +Note that the `Buffer` module pre-allocates an internal `Buffer` instance of +size `Buffer.poolSize` that is used as a pool for the fast allocation of new +`Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated +`new Buffer(size)` constructor) only when `size` is less than or equal to +`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default +value of `Buffer.poolSize` is `8192` but can be modified. + +Use of this pre-allocated internal memory pool is a key difference between +calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. +Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer +pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal +Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The +difference is subtle but can be important when an application requires the +additional performance that `Buffer.allocUnsafe(size)` provides. + +### Class Method: Buffer.allocUnsafeSlow(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The +`size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, +allocations under 4KB are, by default, sliced from a single pre-allocated +`Buffer`. This allows applications to avoid the garbage collection overhead of +creating many individually allocated Buffers. This approach improves both +performance and memory usage by eliminating the need to track and cleanup as +many `Persistent` objects. + +However, in the case where a developer may need to retain a small chunk of +memory from a pool for an indeterminate amount of time, it may be appropriate +to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then +copy out the relevant bits. + +```js +// need to keep around a few small chunks of memory +const store = []; + +socket.on('readable', () => { + const data = socket.read(); + // allocate for retained data + const sb = Buffer.allocUnsafeSlow(10); + // copy the data into the new allocation + data.copy(sb, 0, 0, 10); + store.push(sb); +}); +``` + +Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* +a developer has observed undue memory retention in their applications. + +A `TypeError` will be thrown if `size` is not a number. + +### All the Rest + +The rest of the `Buffer` API is exactly the same as in node.js. +[See the docs](https://nodejs.org/api/buffer.html). + + +## Related links + +- [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) +- [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) + +## Why is `Buffer` unsafe? + +Today, the node.js `Buffer` constructor is overloaded to handle many different argument +types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), +`ArrayBuffer`, and also `Number`. + +The API is optimized for convenience: you can throw any type at it, and it will try to do +what you want. + +Because the Buffer constructor is so powerful, you often see code like this: + +```js +// Convert UTF-8 strings to hex +function toHex (str) { + return new Buffer(str).toString('hex') +} +``` + +***But what happens if `toHex` is called with a `Number` argument?*** + +### Remote Memory Disclosure + +If an attacker can make your program call the `Buffer` constructor with a `Number` +argument, then they can make it allocate uninitialized memory from the node.js process. +This could potentially disclose TLS private keys, user data, or database passwords. + +When the `Buffer` constructor is passed a `Number` argument, it returns an +**UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like +this, you **MUST** overwrite the contents before returning it to the user. + +From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): + +> `new Buffer(size)` +> +> - `size` Number +> +> The underlying memory for `Buffer` instances created in this way is not initialized. +> **The contents of a newly created `Buffer` are unknown and could contain sensitive +> data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. + +(Emphasis our own.) + +Whenever the programmer intended to create an uninitialized `Buffer` you often see code +like this: + +```js +var buf = new Buffer(16) + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### Would this ever be a problem in real code? + +Yes. It's surprisingly common to forget to check the type of your variables in a +dynamically-typed language like JavaScript. + +Usually the consequences of assuming the wrong type is that your program crashes with an +uncaught exception. But the failure mode for forgetting to check the type of arguments to +the `Buffer` constructor is more catastrophic. + +Here's an example of a vulnerable service that takes a JSON payload and converts it to +hex: + +```js +// Take a JSON payload {str: "some string"} and convert it to hex +var server = http.createServer(function (req, res) { + var data = '' + req.setEncoding('utf8') + req.on('data', function (chunk) { + data += chunk + }) + req.on('end', function () { + var body = JSON.parse(data) + res.end(new Buffer(body.str).toString('hex')) + }) +}) + +server.listen(8080) +``` + +In this example, an http client just has to send: + +```json +{ + "str": 1000 +} +``` + +and it will get back 1,000 bytes of uninitialized memory from the server. + +This is a very serious bug. It's similar in severity to the +[the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process +memory by remote attackers. + + +### Which real-world packages were vulnerable? + +#### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) + +[Mathias Buus](https://github.com/mafintosh) and I +([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, +[`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow +anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get +them to reveal 20 bytes at a time of uninitialized memory from the node.js process. + +Here's +[the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) +that fixed it. We released a new fixed version, created a +[Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all +vulnerable versions on npm so users will get a warning to upgrade to a newer version. + +#### [`ws`](https://www.npmjs.com/package/ws) + +That got us wondering if there were other vulnerable packages. Sure enough, within a short +period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the +most popular WebSocket implementation in node.js. + +If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as +expected, then uninitialized server memory would be disclosed to the remote peer. + +These were the vulnerable methods: + +```js +socket.send(number) +socket.ping(number) +socket.pong(number) +``` + +Here's a vulnerable socket server with some echo functionality: + +```js +server.on('connection', function (socket) { + socket.on('message', function (message) { + message = JSON.parse(message) + if (message.type === 'echo') { + socket.send(message.data) // send back the user's message + } + }) +}) +``` + +`socket.send(number)` called on the server, will disclose server memory. + +Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue +was fixed, with a more detailed explanation. Props to +[Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the +[Node Security Project disclosure](https://nodesecurity.io/advisories/67). + + +### What's the solution? + +It's important that node.js offers a fast way to get memory otherwise performance-critical +applications would needlessly get a lot slower. + +But we need a better way to *signal our intent* as programmers. **When we want +uninitialized memory, we should request it explicitly.** + +Sensitive functionality should not be packed into a developer-friendly API that loosely +accepts many different types. This type of API encourages the lazy practice of passing +variables in without checking the type very carefully. + +#### A new API: `Buffer.allocUnsafe(number)` + +The functionality of creating buffers with uninitialized memory should be part of another +API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that +frequently gets user input of all sorts of different types passed into it. + +```js +var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### How do we fix node.js core? + +We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as +`semver-major`) which defends against one case: + +```js +var str = 16 +new Buffer(str, 'utf8') +``` + +In this situation, it's implied that the programmer intended the first argument to be a +string, since they passed an encoding as a second argument. Today, node.js will allocate +uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not +what the programmer intended. + +But this is only a partial solution, since if the programmer does `new Buffer(variable)` +(without an `encoding` parameter) there's no way to know what they intended. If `variable` +is sometimes a number, then uninitialized memory will sometimes be returned. + +### What's the real long-term fix? + +We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when +we need uninitialized memory. But that would break 1000s of packages. + +~~We believe the best solution is to:~~ + +~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ + +~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ + +#### Update + +We now support adding three new APIs: + +- `Buffer.from(value)` - convert from any type to a buffer +- `Buffer.alloc(size)` - create a zero-filled buffer +- `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size + +This solves the core problem that affected `ws` and `bittorrent-dht` which is +`Buffer(variable)` getting tricked into taking a number argument. + +This way, existing code continues working and the impact on the npm ecosystem will be +minimal. Over time, npm maintainers can migrate performance-critical code to use +`Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. + + +### Conclusion + +We think there's a serious design issue with the `Buffer` API as it exists today. It +promotes insecure software by putting high-risk functionality into a convenient API +with friendly "developer ergonomics". + +This wasn't merely a theoretical exercise because we found the issue in some of the +most popular npm packages. + +Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of +`buffer`. + +```js +var Buffer = require('safe-buffer').Buffer +``` + +Eventually, we hope that node.js core can switch to this new, safer behavior. We believe +the impact on the ecosystem would be minimal since it's not a breaking change. +Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while +older, insecure packages would magically become safe from this attack vector. + + +## links + +- [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) +- [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) +- [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) + + +## credit + +The original issues in `bittorrent-dht` +([disclosure](https://nodesecurity.io/advisories/68)) and +`ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by +[Mathias Buus](https://github.com/mafintosh) and +[Feross Aboukhadijeh](http://feross.org/). + +Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues +and for his work running the [Node Security Project](https://nodesecurity.io/). + +Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and +auditing the code. + + +## license + +MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) diff --git a/node_modules/safe-buffer/index.d.ts b/node_modules/safe-buffer/index.d.ts new file mode 100644 index 0000000..e9fed80 --- /dev/null +++ b/node_modules/safe-buffer/index.d.ts @@ -0,0 +1,187 @@ +declare module "safe-buffer" { + export class Buffer { + length: number + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer', data: any[] }; + equals(otherBuffer: Buffer): boolean; + compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + */ + constructor (str: string, encoding?: string); + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + */ + constructor (size: number); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: Uint8Array); + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + */ + constructor (arrayBuffer: ArrayBuffer); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: any[]); + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + */ + constructor (buffer: Buffer); + prototype: Buffer; + /** + * Allocates a new Buffer using an {array} of octets. + * + * @param array + */ + static from(array: any[]): Buffer; + /** + * When passed a reference to the .buffer property of a TypedArray instance, + * the newly created Buffer will share the same allocated memory as the TypedArray. + * The optional {byteOffset} and {length} arguments specify a memory range + * within the {arrayBuffer} that will be shared by the Buffer. + * + * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() + * @param byteOffset + * @param length + */ + static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Copies the passed {buffer} data onto a new Buffer instance. + * + * @param buffer + */ + static from(buffer: Buffer): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + * + * @param str + */ + static from(str: string, encoding?: string): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + static isBuffer(obj: any): obj is Buffer; + /** + * Returns true if {encoding} is a valid encoding argument. + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + * + * @param encoding string to test. + */ + static isEncoding(encoding: string): boolean; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + static byteLength(string: string, encoding?: string): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + static concat(list: Buffer[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + static compare(buf1: Buffer, buf2: Buffer): number; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @param fill if specified, buffer will be initialized by calling buf.fill(fill). + * If parameter is omitted, buffer will be filled with zeros. + * @param encoding encoding used for call to buf.fill while initalizing + */ + static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafe(size: number): Buffer; + /** + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafeSlow(size: number): Buffer; + } +} \ No newline at end of file diff --git a/node_modules/safe-buffer/index.js b/node_modules/safe-buffer/index.js new file mode 100644 index 0000000..22438da --- /dev/null +++ b/node_modules/safe-buffer/index.js @@ -0,0 +1,62 @@ +/* eslint-disable node/no-deprecated-api */ +var buffer = require('buffer') +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} diff --git a/node_modules/safe-buffer/package.json b/node_modules/safe-buffer/package.json new file mode 100644 index 0000000..623fbc3 --- /dev/null +++ b/node_modules/safe-buffer/package.json @@ -0,0 +1,37 @@ +{ + "name": "safe-buffer", + "description": "Safer Node.js Buffer API", + "version": "5.1.2", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "http://feross.org" + }, + "bugs": { + "url": "https://github.com/feross/safe-buffer/issues" + }, + "devDependencies": { + "standard": "*", + "tape": "^4.0.0" + }, + "homepage": "https://github.com/feross/safe-buffer", + "keywords": [ + "buffer", + "buffer allocate", + "node security", + "safe", + "safe-buffer", + "security", + "uninitialized" + ], + "license": "MIT", + "main": "index.js", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "git://github.com/feross/safe-buffer.git" + }, + "scripts": { + "test": "standard && tape test/*.js" + } +} diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..1493321 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,107 @@ +{ + "name": "Medical-Website", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "dependencies": { + "helmet": "^8.0.0", + "morgan": "^1.10.0" + } + }, + "node_modules/basic-auth": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/basic-auth/-/basic-auth-2.0.1.tgz", + "integrity": "sha512-NF+epuEdnUYVlGuhaxbbq+dvJttwLnGY+YixlXlME5KpQ5W3CnXA5cVTneY3SPbPDRkcjMbifrwmFYcClgOZeg==", + "license": "MIT", + "dependencies": { + "safe-buffer": "5.1.2" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/helmet": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/helmet/-/helmet-8.0.0.tgz", + "integrity": "sha512-VyusHLEIIO5mjQPUI1wpOAEu+wl6Q0998jzTxqUYGE45xCIcAxy3MsbEK/yyJUJ3ADeMoB6MornPH6GMWAf+Pw==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/morgan": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/morgan/-/morgan-1.10.0.tgz", + "integrity": "sha512-AbegBVI4sh6El+1gNwvD5YIck7nSA36weD7xvIxG4in80j/UoK8AEGaWnnz8v1GxonMCltmlNs5ZKbGvl9b1XQ==", + "license": "MIT", + "dependencies": { + "basic-auth": "~2.0.1", + "debug": "2.6.9", + "depd": "~2.0.0", + "on-finished": "~2.3.0", + "on-headers": "~1.0.2" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/on-finished": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz", + "integrity": "sha512-ikqdkGAAyf/X/gPhXGvfgAytDZtDbr+bkNUJ0N9h5MI/dmdgCs3l6hoHrcUv41sRKew3jIwrp4qQDXiK99Utww==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/on-headers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.0.2.tgz", + "integrity": "sha512-pZAE+FJLoyITytdqK0U5s+FIpjN0JP3OzFi/u8Rx+EV5/W+JTWGXG8xFzevE7AjBfDqHv/8vL8qQsIhHnqRkrA==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "license": "MIT" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..fc49b85 --- /dev/null +++ b/package.json @@ -0,0 +1,6 @@ +{ + "dependencies": { + "helmet": "^8.0.0", + "morgan": "^1.10.0" + } +}