diff --git a/system/login/node_modules/.package-lock.json b/system/login/node_modules/.package-lock.json new file mode 100644 index 0000000..e8b01ae --- /dev/null +++ b/system/login/node_modules/.package-lock.json @@ -0,0 +1,670 @@ +{ + "name": "login", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==" + }, + "node_modules/body-parser": { + "version": "1.20.2", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.2.tgz", + "integrity": "sha512-ml9pReCu3M61kGlqoTm2umSXTlRTuGTx0bfYj+uIUKKYycG5NtSbeetV3faSU6R7ajOPw0g/J1PvK4qNy7s5bA==", + "dependencies": { + "bytes": "3.1.2", + "content-type": "~1.0.5", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "on-finished": "2.4.1", + "qs": "6.11.0", + "raw-body": "2.5.2", + "type-is": "~1.6.18", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz", + "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", + "dependencies": { + "function-bind": "^1.1.1", + "get-intrinsic": "^1.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/content-disposition": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.5.0.tgz", + "integrity": "sha512-YZ3GUyn/o8gfKJlnlX7g7xq4gyO6OSuhGPKaaGssGB2qgDUS0gPgtTvoyZLTt9Ab6dC4hfc9dV5arkvc/OCmrw==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", + "integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==" + }, + "node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "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==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "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==" + }, + "node_modules/encodeurl": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express": { + "version": "4.18.2", + "resolved": "https://registry.npmjs.org/express/-/express-4.18.2.tgz", + "integrity": "sha512-5/PsL6iGPdfQ/lKM1UuielYgv3BUoJfz1aUwU9vHZ+J7gyvwdQXFEBIEIaxeGf0GIcreATNyBExtalisDbuMqQ==", + "dependencies": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "1.20.1", + "content-disposition": "0.5.4", + "content-type": "~1.0.4", + "cookie": "0.5.0", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "2.0.0", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "1.2.0", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "merge-descriptors": "1.0.1", + "methods": "~1.1.2", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "path-to-regexp": "0.1.7", + "proxy-addr": "~2.0.7", + "qs": "6.11.0", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "0.18.0", + "serve-static": "1.15.0", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.10.0" + } + }, + "node_modules/express/node_modules/body-parser": { + "version": "1.20.1", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.1.tgz", + "integrity": "sha512-jWi7abTbYwajOytWCQc37VulmWiRae5RyTpaCyDcS5/lMdtwSz5lOpDE67srw/HYe35f1z3fDQw+3txg7gNtWw==", + "dependencies": { + "bytes": "3.1.2", + "content-type": "~1.0.4", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "on-finished": "2.4.1", + "qs": "6.11.0", + "raw-body": "2.5.1", + "type-is": "~1.6.18", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/express/node_modules/raw-body": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.1.tgz", + "integrity": "sha512-qqJBtEyVgS0ZmPGdCFPWJ3FreoqvG4MVQln/kCgF7Olq95IbOp0/BWyMwbdtn4VTvkM8Y7khCQ2Xgk/tcrCXig==", + "dependencies": { + "bytes": "3.1.2", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/finalhandler": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.2.0.tgz", + "integrity": "sha512-5uXcUVftlQMFnWC9qu/svkWv3GTd2PfUhK/3PLkYNAe7FbqJMt3515HaxE6eRL74GdsriiwujiawdaB1BpEISg==", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "statuses": "2.0.1", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/function-bind": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", + "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==" + }, + "node_modules/get-intrinsic": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.1.tgz", + "integrity": "sha512-2DcsyfABl+gVHEfCOaTrWgyt+tb6MSEGmKq+kI5HwLbIYgjgmMcV8KQ41uaKz1xxUcn9tJtgFbQUEVcEbd0FYw==", + "dependencies": { + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", + "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", + "dependencies": { + "function-bind": "^1.1.1" + }, + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/has-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.0.1.tgz", + "integrity": "sha512-7qE+iP+O+bgF9clE5+UoBFzE65mlBiVj3tKCrlNQ0Ogwm0BjpT/gK4SlLYDMybDh5I3TCTKnPPa0oMG7JDYrhg==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/http-errors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "dependencies": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/merge-descriptors": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", + "integrity": "sha512-cCi6g3/Zr1iqQi6ySbseM1Xvooa98N0w31jzUYrXPX2xqObmFGHJ0tQ5u74H3mVh7wLouTseZyYIq39g8cNp1w==" + }, + "node_modules/methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" + }, + "node_modules/negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/nodemailer": { + "version": "6.9.7", + "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-6.9.7.tgz", + "integrity": "sha512-rUtR77ksqex/eZRLmQ21LKVH5nAAsVicAtAYudK7JgwenEDZ0UIQ1adUGqErz7sMkWYxWTTU1aeP2Jga6WQyJw==", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/object-inspect": { + "version": "1.12.3", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.12.3.tgz", + "integrity": "sha512-geUvdk7c+eizMNUDkRpW1wJwgfOiOeHbxBR/hLXK1aT6zmVSO0jsQcs7fj6MGw89jC/cjGfLcNOrtMYtGqm81g==", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path": { + "version": "0.12.7", + "resolved": "https://registry.npmjs.org/path/-/path-0.12.7.tgz", + "integrity": "sha512-aXXC6s+1w7otVF9UletFkFcDsJeO7lSZBPUQhtb5O0xJe8LtYhj/GxldoL09bBj9+ZmE2hNoHqQSFMN5fikh4Q==", + "dependencies": { + "process": "^0.11.1", + "util": "^0.10.3" + } + }, + "node_modules/path-to-regexp": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", + "integrity": "sha512-5DFkuoqlv1uYQKxy8omFBeJPQcdoE07Kv2sferDCrAq1ohOU+MSDswDIbnx3YAM60qIOnYa53wBhXW0EbMonrQ==" + }, + "node_modules/process": { + "version": "0.11.10", + "resolved": "https://registry.npmjs.org/process/-/process-0.11.10.tgz", + "integrity": "sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A==", + "engines": { + "node": ">= 0.6.0" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/qs": { + "version": "6.11.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.11.0.tgz", + "integrity": "sha512-MvjoMCJwEarSbUYk5O+nmoSzSutSsTwF85zcHPQ9OrlFoZOYIjaqBAJIqIXjptyD5vThxGq52Xu/MaJzRkIk4Q==", + "dependencies": { + "side-channel": "^1.0.4" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.2.tgz", + "integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==", + "dependencies": { + "bytes": "3.1.2", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" + }, + "node_modules/send": { + "version": "0.18.0", + "resolved": "https://registry.npmjs.org/send/-/send-0.18.0.tgz", + "integrity": "sha512-qqWzuOjSFOuqPjFe4NOsMLafToQQwBSOEpS+FwEt3A2V3vKubTquT3vmLTQpFgMXp8AlFWFuP1qKaJZOtPpVXg==", + "dependencies": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "2.4.1", + "range-parser": "~1.2.1", + "statuses": "2.0.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/send/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + }, + "node_modules/serve-static": { + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.15.0.tgz", + "integrity": "sha512-XGuRDNjXUijsUL0vl6nSD7cwURuzEgglbOaFuZM9g3kwDXOWVTck0jLzjPzGD+TazWbboZYu52/9/XPdUgne9g==", + "dependencies": { + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "0.18.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==" + }, + "node_modules/side-channel": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.4.tgz", + "integrity": "sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw==", + "dependencies": { + "call-bind": "^1.0.0", + "get-intrinsic": "^1.0.2", + "object-inspect": "^1.9.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/util": { + "version": "0.10.4", + "resolved": "https://registry.npmjs.org/util/-/util-0.10.4.tgz", + "integrity": "sha512-0Pm9hTQ3se5ll1XihRic3FDIku70C+iHUdT/W926rSgHV5QgXsYbKZN8MSC3tJtSkhuROzvsQjAaFENRXr+19A==", + "dependencies": { + "inherits": "2.0.3" + } + }, + "node_modules/util/node_modules/inherits": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "integrity": "sha512-x00IRNXNy63jwGkJmzPigoySHbaqpNuzKbBOmzK+g2OdZpQ9w+sxCN+VSB3ja7IAge2OP2qpfxTjeNcyjmW1uw==" + }, + "node_modules/utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "engines": { + "node": ">= 0.8" + } + } + } +} diff --git a/system/login/node_modules/body-parser/HISTORY.md b/system/login/node_modules/body-parser/HISTORY.md new file mode 100644 index 0000000..b892491 --- /dev/null +++ b/system/login/node_modules/body-parser/HISTORY.md @@ -0,0 +1,665 @@ +1.20.2 / 2023-02-21 +=================== + + * Fix strict json error message on Node.js 19+ + * deps: content-type@~1.0.5 + - perf: skip value escaping when unnecessary + * deps: raw-body@2.5.2 + +1.20.1 / 2022-10-06 +=================== + + * deps: qs@6.11.0 + * perf: remove unnecessary object clone + +1.20.0 / 2022-04-02 +=================== + + * Fix error message for json parse whitespace in `strict` + * Fix internal error when inflated body exceeds limit + * Prevent loss of async hooks context + * Prevent hanging when request already read + * deps: depd@2.0.0 + - Replace internal `eval` usage with `Function` constructor + - Use instance methods on `process` to check for listeners + * deps: http-errors@2.0.0 + - deps: depd@2.0.0 + - deps: statuses@2.0.1 + * deps: on-finished@2.4.1 + * deps: qs@6.10.3 + * deps: raw-body@2.5.1 + - deps: http-errors@2.0.0 + +1.19.2 / 2022-02-15 +=================== + + * deps: bytes@3.1.2 + * deps: qs@6.9.7 + * Fix handling of `__proto__` keys + * deps: raw-body@2.4.3 + - deps: bytes@3.1.2 + +1.19.1 / 2021-12-10 +=================== + + * deps: bytes@3.1.1 + * deps: http-errors@1.8.1 + - deps: inherits@2.0.4 + - deps: toidentifier@1.0.1 + - deps: setprototypeof@1.2.0 + * deps: qs@6.9.6 + * deps: raw-body@2.4.2 + - deps: bytes@3.1.1 + - deps: http-errors@1.8.1 + * deps: safe-buffer@5.2.1 + * deps: type-is@~1.6.18 + +1.19.0 / 2019-04-25 +=================== + + * deps: bytes@3.1.0 + - Add petabyte (`pb`) support + * deps: http-errors@1.7.2 + - Set constructor name when possible + - deps: setprototypeof@1.1.1 + - deps: statuses@'>= 1.5.0 < 2' + * deps: iconv-lite@0.4.24 + - Added encoding MIK + * deps: qs@6.7.0 + - Fix parsing array brackets after index + * deps: raw-body@2.4.0 + - deps: bytes@3.1.0 + - deps: http-errors@1.7.2 + - deps: iconv-lite@0.4.24 + * deps: type-is@~1.6.17 + - deps: mime-types@~2.1.24 + - perf: prevent internal `throw` on invalid type + +1.18.3 / 2018-05-14 +=================== + + * Fix stack trace for strict json parse error + * deps: depd@~1.1.2 + - perf: remove argument reassignment + * deps: http-errors@~1.6.3 + - deps: depd@~1.1.2 + - deps: setprototypeof@1.1.0 + - deps: statuses@'>= 1.3.1 < 2' + * deps: iconv-lite@0.4.23 + - Fix loading encoding with year appended + - Fix deprecation warnings on Node.js 10+ + * deps: qs@6.5.2 + * deps: raw-body@2.3.3 + - deps: http-errors@1.6.3 + - deps: iconv-lite@0.4.23 + * deps: type-is@~1.6.16 + - deps: mime-types@~2.1.18 + +1.18.2 / 2017-09-22 +=================== + + * deps: debug@2.6.9 + * perf: remove argument reassignment + +1.18.1 / 2017-09-12 +=================== + + * deps: content-type@~1.0.4 + - perf: remove argument reassignment + - perf: skip parameter parsing when no parameters + * deps: iconv-lite@0.4.19 + - Fix ISO-8859-1 regression + - Update Windows-1255 + * deps: qs@6.5.1 + - Fix parsing & compacting very deep objects + * deps: raw-body@2.3.2 + - deps: iconv-lite@0.4.19 + +1.18.0 / 2017-09-08 +=================== + + * Fix JSON strict violation error to match native parse error + * Include the `body` property on verify errors + * Include the `type` property on all generated errors + * Use `http-errors` to set status code on errors + * deps: bytes@3.0.0 + * deps: debug@2.6.8 + * deps: depd@~1.1.1 + - Remove unnecessary `Buffer` loading + * deps: http-errors@~1.6.2 + - deps: depd@1.1.1 + * deps: iconv-lite@0.4.18 + - Add support for React Native + - Add a warning if not loaded as utf-8 + - Fix CESU-8 decoding in Node.js 8 + - Improve speed of ISO-8859-1 encoding + * deps: qs@6.5.0 + * deps: raw-body@2.3.1 + - Use `http-errors` for standard emitted errors + - deps: bytes@3.0.0 + - deps: iconv-lite@0.4.18 + - perf: skip buffer decoding on overage chunk + * perf: prevent internal `throw` when missing charset + +1.17.2 / 2017-05-17 +=================== + + * deps: debug@2.6.7 + - Fix `DEBUG_MAX_ARRAY_LENGTH` + - deps: ms@2.0.0 + * deps: type-is@~1.6.15 + - deps: mime-types@~2.1.15 + +1.17.1 / 2017-03-06 +=================== + + * deps: qs@6.4.0 + - Fix regression parsing keys starting with `[` + +1.17.0 / 2017-03-01 +=================== + + * deps: http-errors@~1.6.1 + - Make `message` property enumerable for `HttpError`s + - deps: setprototypeof@1.0.3 + * deps: qs@6.3.1 + - Fix compacting nested arrays + +1.16.1 / 2017-02-10 +=================== + + * deps: debug@2.6.1 + - Fix deprecation messages in WebStorm and other editors + - Undeprecate `DEBUG_FD` set to `1` or `2` + +1.16.0 / 2017-01-17 +=================== + + * 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 + * deps: http-errors@~1.5.1 + - deps: inherits@2.0.3 + - deps: setprototypeof@1.0.2 + - deps: statuses@'>= 1.3.1 < 2' + * deps: iconv-lite@0.4.15 + - Added encoding MS-31J + - Added encoding MS-932 + - Added encoding MS-936 + - Added encoding MS-949 + - Added encoding MS-950 + - Fix GBK/GB18030 handling of Euro character + * deps: qs@6.2.1 + - Fix array parsing from skipping empty values + * deps: raw-body@~2.2.0 + - deps: iconv-lite@0.4.15 + * deps: type-is@~1.6.14 + - deps: mime-types@~2.1.13 + +1.15.2 / 2016-06-19 +=================== + + * deps: bytes@2.4.0 + * deps: content-type@~1.0.2 + - perf: enable strict mode + * deps: http-errors@~1.5.0 + - Use `setprototypeof` module to replace `__proto__` setting + - deps: statuses@'>= 1.3.0 < 2' + - perf: enable strict mode + * deps: qs@6.2.0 + * deps: raw-body@~2.1.7 + - deps: bytes@2.4.0 + - perf: remove double-cleanup on happy path + * deps: type-is@~1.6.13 + - deps: mime-types@~2.1.11 + +1.15.1 / 2016-05-05 +=================== + + * deps: bytes@2.3.0 + - Drop partial bytes on all parsed units + - Fix parsing byte string that looks like hex + * deps: raw-body@~2.1.6 + - deps: bytes@2.3.0 + * deps: type-is@~1.6.12 + - deps: mime-types@~2.1.10 + +1.15.0 / 2016-02-10 +=================== + + * deps: http-errors@~1.4.0 + - Add `HttpError` export, for `err instanceof createError.HttpError` + - deps: inherits@2.0.1 + - deps: statuses@'>= 1.2.1 < 2' + * deps: qs@6.1.0 + * deps: type-is@~1.6.11 + - deps: mime-types@~2.1.9 + +1.14.2 / 2015-12-16 +=================== + + * deps: bytes@2.2.0 + * deps: iconv-lite@0.4.13 + * deps: qs@5.2.0 + * deps: raw-body@~2.1.5 + - deps: bytes@2.2.0 + - deps: iconv-lite@0.4.13 + * deps: type-is@~1.6.10 + - deps: mime-types@~2.1.8 + +1.14.1 / 2015-09-27 +=================== + + * Fix issue where invalid charset results in 400 when `verify` used + * deps: iconv-lite@0.4.12 + - Fix CESU-8 decoding in Node.js 4.x + * deps: raw-body@~2.1.4 + - Fix masking critical errors from `iconv-lite` + - deps: iconv-lite@0.4.12 + * deps: type-is@~1.6.9 + - deps: mime-types@~2.1.7 + +1.14.0 / 2015-09-16 +=================== + + * Fix JSON strict parse error to match syntax errors + * Provide static `require` analysis in `urlencoded` parser + * deps: depd@~1.1.0 + - Support web browser loading + * deps: qs@5.1.0 + * deps: raw-body@~2.1.3 + - Fix sync callback when attaching data listener causes sync read + * deps: type-is@~1.6.8 + - Fix type error when given invalid type to match against + - deps: mime-types@~2.1.6 + +1.13.3 / 2015-07-31 +=================== + + * deps: type-is@~1.6.6 + - deps: mime-types@~2.1.4 + +1.13.2 / 2015-07-05 +=================== + + * deps: iconv-lite@0.4.11 + * deps: qs@4.0.0 + - Fix dropping parameters like `hasOwnProperty` + - Fix user-visible incompatibilities from 3.1.0 + - Fix various parsing edge cases + * deps: raw-body@~2.1.2 + - Fix error stack traces to skip `makeError` + - deps: iconv-lite@0.4.11 + * deps: type-is@~1.6.4 + - deps: mime-types@~2.1.2 + - perf: enable strict mode + - perf: remove argument reassignment + +1.13.1 / 2015-06-16 +=================== + + * deps: qs@2.4.2 + - Downgraded from 3.1.0 because of user-visible incompatibilities + +1.13.0 / 2015-06-14 +=================== + + * Add `statusCode` property on `Error`s, in addition to `status` + * Change `type` default to `application/json` for JSON parser + * Change `type` default to `application/x-www-form-urlencoded` for urlencoded parser + * Provide static `require` analysis + * Use the `http-errors` module to generate errors + * deps: bytes@2.1.0 + - Slight optimizations + * deps: iconv-lite@0.4.10 + - The encoding UTF-16 without BOM now defaults to UTF-16LE when detection fails + - Leading BOM is now removed when decoding + * 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 + * deps: qs@3.1.0 + - Fix dropping parameters like `hasOwnProperty` + - Fix various parsing edge cases + - Parsed object now has `null` prototype + * deps: raw-body@~2.1.1 + - Use `unpipe` module for unpiping requests + - deps: iconv-lite@0.4.10 + * deps: type-is@~1.6.3 + - deps: mime-types@~2.1.1 + - perf: reduce try block size + - perf: remove bitwise operations + * perf: enable strict mode + * perf: remove argument reassignment + * perf: remove delete call + +1.12.4 / 2015-05-10 +=================== + + * deps: debug@~2.2.0 + * deps: qs@2.4.2 + - Fix allowing parameters like `constructor` + * deps: on-finished@~2.2.1 + * deps: raw-body@~2.0.1 + - Fix a false-positive when unpiping in Node.js 0.8 + - deps: bytes@2.0.1 + * deps: type-is@~1.6.2 + - deps: mime-types@~2.0.11 + +1.12.3 / 2015-04-15 +=================== + + * Slight efficiency improvement when not debugging + * deps: depd@~1.0.1 + * deps: iconv-lite@0.4.8 + - Add encoding alias UNICODE-1-1-UTF-7 + * deps: raw-body@1.3.4 + - Fix hanging callback if request aborts during read + - deps: iconv-lite@0.4.8 + +1.12.2 / 2015-03-16 +=================== + + * deps: qs@2.4.1 + - Fix error when parameter `hasOwnProperty` is present + +1.12.1 / 2015-03-15 +=================== + + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + * deps: type-is@~1.6.1 + - deps: mime-types@~2.0.10 + +1.12.0 / 2015-02-13 +=================== + + * add `debug` messages + * accept a function for the `type` option + * use `content-type` to parse `Content-Type` headers + * deps: iconv-lite@0.4.7 + - Gracefully support enumerables on `Object.prototype` + * deps: raw-body@1.3.3 + - deps: iconv-lite@0.4.7 + * deps: type-is@~1.6.0 + - fix argument reassignment + - fix false-positives in `hasBody` `Transfer-Encoding` check + - support wildcard for both type and subtype (`*/*`) + - deps: mime-types@~2.0.9 + +1.11.0 / 2015-01-30 +=================== + + * make internal `extended: true` depth limit infinity + * deps: type-is@~1.5.6 + - deps: mime-types@~2.0.8 + +1.10.2 / 2015-01-20 +=================== + + * deps: iconv-lite@0.4.6 + - Fix rare aliases of single-byte encodings + * deps: raw-body@1.3.2 + - deps: iconv-lite@0.4.6 + +1.10.1 / 2015-01-01 +=================== + + * deps: on-finished@~2.2.0 + * deps: type-is@~1.5.5 + - deps: mime-types@~2.0.7 + +1.10.0 / 2014-12-02 +=================== + + * make internal `extended: true` array limit dynamic + +1.9.3 / 2014-11-21 +================== + + * deps: iconv-lite@0.4.5 + - Fix Windows-31J and X-SJIS encoding support + * deps: qs@2.3.3 + - Fix `arrayLimit` behavior + * deps: raw-body@1.3.1 + - deps: iconv-lite@0.4.5 + * deps: type-is@~1.5.3 + - deps: mime-types@~2.0.3 + +1.9.2 / 2014-10-27 +================== + + * deps: qs@2.3.2 + - Fix parsing of mixed objects and values + +1.9.1 / 2014-10-22 +================== + + * deps: on-finished@~2.1.1 + - Fix handling of pipelined requests + * deps: qs@2.3.0 + - Fix parsing of mixed implicit and explicit arrays + * deps: type-is@~1.5.2 + - deps: mime-types@~2.0.2 + +1.9.0 / 2014-09-24 +================== + + * include the charset in "unsupported charset" error message + * include the encoding in "unsupported content encoding" error message + * deps: depd@~1.0.0 + +1.8.4 / 2014-09-23 +================== + + * fix content encoding to be case-insensitive + +1.8.3 / 2014-09-19 +================== + + * deps: qs@2.2.4 + - Fix issue with object keys starting with numbers truncated + +1.8.2 / 2014-09-15 +================== + + * deps: depd@0.4.5 + +1.8.1 / 2014-09-07 +================== + + * deps: media-typer@0.3.0 + * deps: type-is@~1.5.1 + +1.8.0 / 2014-09-05 +================== + + * make empty-body-handling consistent between chunked requests + - empty `json` produces `{}` + - empty `raw` produces `new Buffer(0)` + - empty `text` produces `''` + - empty `urlencoded` produces `{}` + * deps: qs@2.2.3 + - Fix issue where first empty value in array is discarded + * deps: type-is@~1.5.0 + - fix `hasbody` to be true for `content-length: 0` + +1.7.0 / 2014-09-01 +================== + + * add `parameterLimit` option to `urlencoded` parser + * change `urlencoded` extended array limit to 100 + * respond with 413 when over `parameterLimit` in `urlencoded` + +1.6.7 / 2014-08-29 +================== + + * deps: qs@2.2.2 + - Remove unnecessary cloning + +1.6.6 / 2014-08-27 +================== + + * deps: qs@2.2.0 + - Array parsing fix + - Performance improvements + +1.6.5 / 2014-08-16 +================== + + * deps: on-finished@2.1.0 + +1.6.4 / 2014-08-14 +================== + + * deps: qs@1.2.2 + +1.6.3 / 2014-08-10 +================== + + * deps: qs@1.2.1 + +1.6.2 / 2014-08-07 +================== + + * deps: qs@1.2.0 + - Fix parsing array of objects + +1.6.1 / 2014-08-06 +================== + + * deps: qs@1.1.0 + - Accept urlencoded square brackets + - Accept empty values in implicit array notation + +1.6.0 / 2014-08-05 +================== + + * deps: qs@1.0.2 + - Complete rewrite + - Limits array length to 20 + - Limits object depth to 5 + - Limits parameters to 1,000 + +1.5.2 / 2014-07-27 +================== + + * deps: depd@0.4.4 + - Work-around v8 generating empty stack traces + +1.5.1 / 2014-07-26 +================== + + * deps: depd@0.4.3 + - Fix exception when global `Error.stackTraceLimit` is too low + +1.5.0 / 2014-07-20 +================== + + * deps: depd@0.4.2 + - Add `TRACE_DEPRECATION` environment variable + - Remove non-standard grey color from color output + - Support `--no-deprecation` argument + - Support `--trace-deprecation` argument + * deps: iconv-lite@0.4.4 + - Added encoding UTF-7 + * deps: raw-body@1.3.0 + - deps: iconv-lite@0.4.4 + - Added encoding UTF-7 + - Fix `Cannot switch to old mode now` error on Node.js 0.10+ + * deps: type-is@~1.3.2 + +1.4.3 / 2014-06-19 +================== + + * deps: type-is@1.3.1 + - fix global variable leak + +1.4.2 / 2014-06-19 +================== + + * deps: type-is@1.3.0 + - improve type parsing + +1.4.1 / 2014-06-19 +================== + + * fix urlencoded extended deprecation message + +1.4.0 / 2014-06-19 +================== + + * add `text` parser + * add `raw` parser + * check accepted charset in content-type (accepts utf-8) + * check accepted encoding in content-encoding (accepts identity) + * deprecate `bodyParser()` middleware; use `.json()` and `.urlencoded()` as needed + * deprecate `urlencoded()` without provided `extended` option + * lazy-load urlencoded parsers + * parsers split into files for reduced mem usage + * support gzip and deflate bodies + - set `inflate: false` to turn off + * deps: raw-body@1.2.2 + - Support all encodings from `iconv-lite` + +1.3.1 / 2014-06-11 +================== + + * deps: type-is@1.2.1 + - Switch dependency from mime to mime-types@1.0.0 + +1.3.0 / 2014-05-31 +================== + + * add `extended` option to urlencoded parser + +1.2.2 / 2014-05-27 +================== + + * deps: raw-body@1.1.6 + - assert stream encoding on node.js 0.8 + - assert stream encoding on node.js < 0.10.6 + - deps: bytes@1 + +1.2.1 / 2014-05-26 +================== + + * invoke `next(err)` after request fully read + - prevents hung responses and socket hang ups + +1.2.0 / 2014-05-11 +================== + + * add `verify` option + * deps: type-is@1.2.0 + - support suffix matching + +1.1.2 / 2014-05-11 +================== + + * improve json parser speed + +1.1.1 / 2014-05-11 +================== + + * fix repeated limit parsing with every request + +1.1.0 / 2014-05-10 +================== + + * add `type` option + * deps: pin for safety and consistency + +1.0.2 / 2014-04-14 +================== + + * use `type-is` module + +1.0.1 / 2014-03-20 +================== + + * lower default limits to 100kb diff --git a/system/login/node_modules/body-parser/LICENSE b/system/login/node_modules/body-parser/LICENSE new file mode 100644 index 0000000..386b7b6 --- /dev/null +++ b/system/login/node_modules/body-parser/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2014-2015 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/system/login/node_modules/body-parser/README.md b/system/login/node_modules/body-parser/README.md new file mode 100644 index 0000000..38553bf --- /dev/null +++ b/system/login/node_modules/body-parser/README.md @@ -0,0 +1,465 @@ +# body-parser + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Build Status][ci-image]][ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Node.js body parsing middleware. + +Parse incoming request bodies in a middleware before your handlers, available +under the `req.body` property. + +**Note** As `req.body`'s shape is based on user-controlled input, all +properties and values in this object are untrusted and should be validated +before trusting. For example, `req.body.foo.toString()` may fail in multiple +ways, for example the `foo` property may not be there or may not be a string, +and `toString` may not be a function and instead a string or other user input. + +[Learn about the anatomy of an HTTP transaction in Node.js](https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/). + +_This does not handle multipart bodies_, due to their complex and typically +large nature. For multipart bodies, you may be interested in the following +modules: + + * [busboy](https://www.npmjs.org/package/busboy#readme) and + [connect-busboy](https://www.npmjs.org/package/connect-busboy#readme) + * [multiparty](https://www.npmjs.org/package/multiparty#readme) and + [connect-multiparty](https://www.npmjs.org/package/connect-multiparty#readme) + * [formidable](https://www.npmjs.org/package/formidable#readme) + * [multer](https://www.npmjs.org/package/multer#readme) + +This module provides the following parsers: + + * [JSON body parser](#bodyparserjsonoptions) + * [Raw body parser](#bodyparserrawoptions) + * [Text body parser](#bodyparsertextoptions) + * [URL-encoded form body parser](#bodyparserurlencodedoptions) + +Other body parsers you might be interested in: + +- [body](https://www.npmjs.org/package/body#readme) +- [co-body](https://www.npmjs.org/package/co-body#readme) + +## Installation + +```sh +$ npm install body-parser +``` + +## API + +```js +var bodyParser = require('body-parser') +``` + +The `bodyParser` object exposes various factories to create middlewares. All +middlewares will populate the `req.body` property with the parsed body when +the `Content-Type` request header matches the `type` option, or an empty +object (`{}`) if there was no body to parse, the `Content-Type` was not matched, +or an error occurred. + +The various errors returned by this module are described in the +[errors section](#errors). + +### bodyParser.json([options]) + +Returns middleware that only parses `json` and only looks at requests where +the `Content-Type` header matches the `type` option. This parser accepts any +Unicode encoding of the body and supports automatic inflation of `gzip` and +`deflate` encodings. + +A new `body` object containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). + +#### Options + +The `json` function takes an optional `options` object that may contain any of +the following keys: + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### reviver + +The `reviver` option is passed directly to `JSON.parse` as the second +argument. You can find more information on this argument +[in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Example.3A_Using_the_reviver_parameter). + +##### strict + +When set to `true`, will only accept arrays and objects; when `false` will +accept anything `JSON.parse` accepts. Defaults to `true`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a string, array of strings, or a function. If not a +function, `type` option is passed directly to the +[type-is](https://www.npmjs.org/package/type-is#readme) library and this can +be an extension name (like `json`), a mime type (like `application/json`), or +a mime type with a wildcard (like `*/*` or `*/json`). If a function, the `type` +option is called as `fn(req)` and the request is parsed if it returns a truthy +value. Defaults to `application/json`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +### bodyParser.raw([options]) + +Returns middleware that parses all bodies as a `Buffer` and only looks at +requests where the `Content-Type` header matches the `type` option. This +parser supports automatic inflation of `gzip` and `deflate` encodings. + +A new `body` object containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). This will be a `Buffer` object +of the body. + +#### Options + +The `raw` function takes an optional `options` object that may contain any of +the following keys: + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a string, array of strings, or a function. +If not a function, `type` option is passed directly to the +[type-is](https://www.npmjs.org/package/type-is#readme) library and this +can be an extension name (like `bin`), a mime type (like +`application/octet-stream`), or a mime type with a wildcard (like `*/*` or +`application/*`). If a function, the `type` option is called as `fn(req)` +and the request is parsed if it returns a truthy value. Defaults to +`application/octet-stream`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +### bodyParser.text([options]) + +Returns middleware that parses all bodies as a string and only looks at +requests where the `Content-Type` header matches the `type` option. This +parser supports automatic inflation of `gzip` and `deflate` encodings. + +A new `body` string containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). This will be a string of the +body. + +#### Options + +The `text` function takes an optional `options` object that may contain any of +the following keys: + +##### defaultCharset + +Specify the default character set for the text content if the charset is not +specified in the `Content-Type` header of the request. Defaults to `utf-8`. + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a string, array of strings, or a function. If not +a function, `type` option is passed directly to the +[type-is](https://www.npmjs.org/package/type-is#readme) library and this can +be an extension name (like `txt`), a mime type (like `text/plain`), or a mime +type with a wildcard (like `*/*` or `text/*`). If a function, the `type` +option is called as `fn(req)` and the request is parsed if it returns a +truthy value. Defaults to `text/plain`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +### bodyParser.urlencoded([options]) + +Returns middleware that only parses `urlencoded` bodies and only looks at +requests where the `Content-Type` header matches the `type` option. This +parser accepts only UTF-8 encoding of the body and supports automatic +inflation of `gzip` and `deflate` encodings. + +A new `body` object containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). This object will contain +key-value pairs, where the value can be a string or array (when `extended` is +`false`), or any type (when `extended` is `true`). + +#### Options + +The `urlencoded` function takes an optional `options` object that may contain +any of the following keys: + +##### extended + +The `extended` option allows to choose between parsing the URL-encoded data +with the `querystring` library (when `false`) or the `qs` library (when +`true`). The "extended" syntax allows for rich objects and arrays to be +encoded into the URL-encoded format, allowing for a JSON-like experience +with URL-encoded. For more information, please +[see the qs library](https://www.npmjs.org/package/qs#readme). + +Defaults to `true`, but using the default has been deprecated. Please +research into the difference between `qs` and `querystring` and choose the +appropriate setting. + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### parameterLimit + +The `parameterLimit` option controls the maximum number of parameters that +are allowed in the URL-encoded data. If a request contains more parameters +than this value, a 413 will be returned to the client. Defaults to `1000`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a string, array of strings, or a function. If not +a function, `type` option is passed directly to the +[type-is](https://www.npmjs.org/package/type-is#readme) library and this can +be an extension name (like `urlencoded`), a mime type (like +`application/x-www-form-urlencoded`), or a mime type with a wildcard (like +`*/x-www-form-urlencoded`). If a function, the `type` option is called as +`fn(req)` and the request is parsed if it returns a truthy value. Defaults +to `application/x-www-form-urlencoded`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +## Errors + +The middlewares provided by this module create errors using the +[`http-errors` module](https://www.npmjs.com/package/http-errors). The errors +will typically have a `status`/`statusCode` property that contains the suggested +HTTP response code, an `expose` property to determine if the `message` property +should be displayed to the client, a `type` property to determine the type of +error without matching against the `message`, and a `body` property containing +the read body, if available. + +The following are the common errors created, though any error can come through +for various reasons. + +### content encoding unsupported + +This error will occur when the request had a `Content-Encoding` header that +contained an encoding but the "inflation" option was set to `false`. The +`status` property is set to `415`, the `type` property is set to +`'encoding.unsupported'`, and the `charset` property will be set to the +encoding that is unsupported. + +### entity parse failed + +This error will occur when the request contained an entity that could not be +parsed by the middleware. The `status` property is set to `400`, the `type` +property is set to `'entity.parse.failed'`, and the `body` property is set to +the entity value that failed parsing. + +### entity verify failed + +This error will occur when the request contained an entity that could not be +failed verification by the defined `verify` option. The `status` property is +set to `403`, the `type` property is set to `'entity.verify.failed'`, and the +`body` property is set to the entity value that failed verification. + +### request aborted + +This error will occur when the request is aborted by the client before reading +the body has finished. The `received` property will be set to the number of +bytes received before the request was aborted and the `expected` property is +set to the number of expected bytes. The `status` property is set to `400` +and `type` property is set to `'request.aborted'`. + +### request entity too large + +This error will occur when the request body's size is larger than the "limit" +option. The `limit` property will be set to the byte limit and the `length` +property will be set to the request body's length. The `status` property is +set to `413` and the `type` property is set to `'entity.too.large'`. + +### request size did not match content length + +This error will occur when the request's length did not match the length from +the `Content-Length` header. This typically occurs when the request is malformed, +typically when the `Content-Length` header was calculated based on characters +instead of bytes. The `status` property is set to `400` and the `type` property +is set to `'request.size.invalid'`. + +### stream encoding should not be set + +This error will occur when something called the `req.setEncoding` method prior +to this middleware. This module operates directly on bytes only and you cannot +call `req.setEncoding` when using this module. The `status` property is set to +`500` and the `type` property is set to `'stream.encoding.set'`. + +### stream is not readable + +This error will occur when the request is no longer readable when this middleware +attempts to read it. This typically means something other than a middleware from +this module read the request body already and the middleware was also configured to +read the same request. The `status` property is set to `500` and the `type` +property is set to `'stream.not.readable'`. + +### too many parameters + +This error will occur when the content of the request exceeds the configured +`parameterLimit` for the `urlencoded` parser. The `status` property is set to +`413` and the `type` property is set to `'parameters.too.many'`. + +### unsupported charset "BOGUS" + +This error will occur when the request had a charset parameter in the +`Content-Type` header, but the `iconv-lite` module does not support it OR the +parser does not support it. The charset is contained in the message as well +as in the `charset` property. The `status` property is set to `415`, the +`type` property is set to `'charset.unsupported'`, and the `charset` property +is set to the charset that is unsupported. + +### unsupported content encoding "bogus" + +This error will occur when the request had a `Content-Encoding` header that +contained an unsupported encoding. The encoding is contained in the message +as well as in the `encoding` property. The `status` property is set to `415`, +the `type` property is set to `'encoding.unsupported'`, and the `encoding` +property is set to the encoding that is unsupported. + +## Examples + +### Express/Connect top-level generic + +This example demonstrates adding a generic JSON and URL-encoded parser as a +top-level middleware, which will parse the bodies of all incoming requests. +This is the simplest setup. + +```js +var express = require('express') +var bodyParser = require('body-parser') + +var app = express() + +// parse application/x-www-form-urlencoded +app.use(bodyParser.urlencoded({ extended: false })) + +// parse application/json +app.use(bodyParser.json()) + +app.use(function (req, res) { + res.setHeader('Content-Type', 'text/plain') + res.write('you posted:\n') + res.end(JSON.stringify(req.body, null, 2)) +}) +``` + +### Express route-specific + +This example demonstrates adding body parsers specifically to the routes that +need them. In general, this is the most recommended way to use body-parser with +Express. + +```js +var express = require('express') +var bodyParser = require('body-parser') + +var app = express() + +// create application/json parser +var jsonParser = bodyParser.json() + +// create application/x-www-form-urlencoded parser +var urlencodedParser = bodyParser.urlencoded({ extended: false }) + +// POST /login gets urlencoded bodies +app.post('/login', urlencodedParser, function (req, res) { + res.send('welcome, ' + req.body.username) +}) + +// POST /api/users gets JSON bodies +app.post('/api/users', jsonParser, function (req, res) { + // create user in req.body +}) +``` + +### Change accepted type for parsers + +All the parsers accept a `type` option which allows you to change the +`Content-Type` that the middleware will parse. + +```js +var express = require('express') +var bodyParser = require('body-parser') + +var app = express() + +// parse various different custom JSON types as JSON +app.use(bodyParser.json({ type: 'application/*+json' })) + +// parse some custom thing into a Buffer +app.use(bodyParser.raw({ type: 'application/vnd.custom-type' })) + +// parse an HTML body into a string +app.use(bodyParser.text({ type: 'text/html' })) +``` + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/expressjs/body-parser/master?label=ci +[ci-url]: https://github.com/expressjs/body-parser/actions/workflows/ci.yml +[coveralls-image]: https://badgen.net/coveralls/c/github/expressjs/body-parser/master +[coveralls-url]: https://coveralls.io/r/expressjs/body-parser?branch=master +[node-version-image]: https://badgen.net/npm/node/body-parser +[node-version-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/body-parser +[npm-url]: https://npmjs.org/package/body-parser +[npm-version-image]: https://badgen.net/npm/v/body-parser diff --git a/system/login/node_modules/body-parser/SECURITY.md b/system/login/node_modules/body-parser/SECURITY.md new file mode 100644 index 0000000..9694d42 --- /dev/null +++ b/system/login/node_modules/body-parser/SECURITY.md @@ -0,0 +1,25 @@ +# Security Policies and Procedures + +## Reporting a Bug + +The Express team and community take all security bugs seriously. Thank you +for improving the security of Express. We appreciate your efforts and +responsible disclosure and will make every effort to acknowledge your +contributions. + +Report security bugs by emailing the current owner(s) of `body-parser`. This +information can be found in the npm registry using the command +`npm owner ls body-parser`. +If unsure or unable to get the information from the above, open an issue +in the [project issue tracker](https://github.com/expressjs/body-parser/issues) +asking for the current contact information. + +To ensure the timely response to your report, please ensure that the entirety +of the report is contained within the email body and not solely behind a web +link or an attachment. + +At least one owner will acknowledge your email within 48 hours, and will send a +more detailed response within 48 hours indicating the next steps in handling +your report. After the initial reply to your report, the owners will +endeavor to keep you informed of the progress towards a fix and full +announcement, and may ask for additional information or guidance. diff --git a/system/login/node_modules/body-parser/index.js b/system/login/node_modules/body-parser/index.js new file mode 100644 index 0000000..bb24d73 --- /dev/null +++ b/system/login/node_modules/body-parser/index.js @@ -0,0 +1,156 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var deprecate = require('depd')('body-parser') + +/** + * Cache of loaded parsers. + * @private + */ + +var parsers = Object.create(null) + +/** + * @typedef Parsers + * @type {function} + * @property {function} json + * @property {function} raw + * @property {function} text + * @property {function} urlencoded + */ + +/** + * Module exports. + * @type {Parsers} + */ + +exports = module.exports = deprecate.function(bodyParser, + 'bodyParser: use individual json/urlencoded middlewares') + +/** + * JSON parser. + * @public + */ + +Object.defineProperty(exports, 'json', { + configurable: true, + enumerable: true, + get: createParserGetter('json') +}) + +/** + * Raw parser. + * @public + */ + +Object.defineProperty(exports, 'raw', { + configurable: true, + enumerable: true, + get: createParserGetter('raw') +}) + +/** + * Text parser. + * @public + */ + +Object.defineProperty(exports, 'text', { + configurable: true, + enumerable: true, + get: createParserGetter('text') +}) + +/** + * URL-encoded parser. + * @public + */ + +Object.defineProperty(exports, 'urlencoded', { + configurable: true, + enumerable: true, + get: createParserGetter('urlencoded') +}) + +/** + * Create a middleware to parse json and urlencoded bodies. + * + * @param {object} [options] + * @return {function} + * @deprecated + * @public + */ + +function bodyParser (options) { + // use default type for parsers + var opts = Object.create(options || null, { + type: { + configurable: true, + enumerable: true, + value: undefined, + writable: true + } + }) + + var _urlencoded = exports.urlencoded(opts) + var _json = exports.json(opts) + + return function bodyParser (req, res, next) { + _json(req, res, function (err) { + if (err) return next(err) + _urlencoded(req, res, next) + }) + } +} + +/** + * Create a getter for loading a parser. + * @private + */ + +function createParserGetter (name) { + return function get () { + return loadParser(name) + } +} + +/** + * Load a parser module. + * @private + */ + +function loadParser (parserName) { + var parser = parsers[parserName] + + if (parser !== undefined) { + return parser + } + + // this uses a switch for static require analysis + switch (parserName) { + case 'json': + parser = require('./lib/types/json') + break + case 'raw': + parser = require('./lib/types/raw') + break + case 'text': + parser = require('./lib/types/text') + break + case 'urlencoded': + parser = require('./lib/types/urlencoded') + break + } + + // store to prevent invoking require() + return (parsers[parserName] = parser) +} diff --git a/system/login/node_modules/body-parser/lib/read.js b/system/login/node_modules/body-parser/lib/read.js new file mode 100644 index 0000000..fce6283 --- /dev/null +++ b/system/login/node_modules/body-parser/lib/read.js @@ -0,0 +1,205 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var createError = require('http-errors') +var destroy = require('destroy') +var getBody = require('raw-body') +var iconv = require('iconv-lite') +var onFinished = require('on-finished') +var unpipe = require('unpipe') +var zlib = require('zlib') + +/** + * Module exports. + */ + +module.exports = read + +/** + * Read a request into a buffer and parse. + * + * @param {object} req + * @param {object} res + * @param {function} next + * @param {function} parse + * @param {function} debug + * @param {object} options + * @private + */ + +function read (req, res, next, parse, debug, options) { + var length + var opts = options + var stream + + // flag as parsed + req._body = true + + // read options + var encoding = opts.encoding !== null + ? opts.encoding + : null + var verify = opts.verify + + try { + // get the content stream + stream = contentstream(req, debug, opts.inflate) + length = stream.length + stream.length = undefined + } catch (err) { + return next(err) + } + + // set raw-body options + opts.length = length + opts.encoding = verify + ? null + : encoding + + // assert charset is supported + if (opts.encoding === null && encoding !== null && !iconv.encodingExists(encoding)) { + return next(createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { + charset: encoding.toLowerCase(), + type: 'charset.unsupported' + })) + } + + // read body + debug('read body') + getBody(stream, opts, function (error, body) { + if (error) { + var _error + + if (error.type === 'encoding.unsupported') { + // echo back charset + _error = createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { + charset: encoding.toLowerCase(), + type: 'charset.unsupported' + }) + } else { + // set status code on error + _error = createError(400, error) + } + + // unpipe from stream and destroy + if (stream !== req) { + unpipe(req) + destroy(stream, true) + } + + // read off entire request + dump(req, function onfinished () { + next(createError(400, _error)) + }) + return + } + + // verify + if (verify) { + try { + debug('verify body') + verify(req, res, body, encoding) + } catch (err) { + next(createError(403, err, { + body: body, + type: err.type || 'entity.verify.failed' + })) + return + } + } + + // parse + var str = body + try { + debug('parse body') + str = typeof body !== 'string' && encoding !== null + ? iconv.decode(body, encoding) + : body + req.body = parse(str) + } catch (err) { + next(createError(400, err, { + body: str, + type: err.type || 'entity.parse.failed' + })) + return + } + + next() + }) +} + +/** + * Get the content stream of the request. + * + * @param {object} req + * @param {function} debug + * @param {boolean} [inflate=true] + * @return {object} + * @api private + */ + +function contentstream (req, debug, inflate) { + var encoding = (req.headers['content-encoding'] || 'identity').toLowerCase() + var length = req.headers['content-length'] + var stream + + debug('content-encoding "%s"', encoding) + + if (inflate === false && encoding !== 'identity') { + throw createError(415, 'content encoding unsupported', { + encoding: encoding, + type: 'encoding.unsupported' + }) + } + + switch (encoding) { + case 'deflate': + stream = zlib.createInflate() + debug('inflate body') + req.pipe(stream) + break + case 'gzip': + stream = zlib.createGunzip() + debug('gunzip body') + req.pipe(stream) + break + case 'identity': + stream = req + stream.length = length + break + default: + throw createError(415, 'unsupported content encoding "' + encoding + '"', { + encoding: encoding, + type: 'encoding.unsupported' + }) + } + + return stream +} + +/** + * Dump the contents of a request. + * + * @param {object} req + * @param {function} callback + * @api private + */ + +function dump (req, callback) { + if (onFinished.isFinished(req)) { + callback(null) + } else { + onFinished(req, callback) + req.resume() + } +} diff --git a/system/login/node_modules/body-parser/lib/types/json.js b/system/login/node_modules/body-parser/lib/types/json.js new file mode 100644 index 0000000..59f3f7e --- /dev/null +++ b/system/login/node_modules/body-parser/lib/types/json.js @@ -0,0 +1,247 @@ +/*! + * body-parser + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var bytes = require('bytes') +var contentType = require('content-type') +var createError = require('http-errors') +var debug = require('debug')('body-parser:json') +var read = require('../read') +var typeis = require('type-is') + +/** + * Module exports. + */ + +module.exports = json + +/** + * RegExp to match the first non-space in a string. + * + * Allowed whitespace is defined in RFC 7159: + * + * ws = *( + * %x20 / ; Space + * %x09 / ; Horizontal tab + * %x0A / ; Line feed or New line + * %x0D ) ; Carriage return + */ + +var FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*([^\x20\x09\x0a\x0d])/ // eslint-disable-line no-control-regex + +var JSON_SYNTAX_CHAR = '#' +var JSON_SYNTAX_REGEXP = /#+/g + +/** + * Create a middleware to parse JSON bodies. + * + * @param {object} [options] + * @return {function} + * @public + */ + +function json (options) { + var opts = options || {} + + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var inflate = opts.inflate !== false + var reviver = opts.reviver + var strict = opts.strict !== false + var type = opts.type || 'application/json' + var verify = opts.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + function parse (body) { + if (body.length === 0) { + // special-case empty json body, as it's a common client-side mistake + // TODO: maybe make this configurable or part of "strict" option + return {} + } + + if (strict) { + var first = firstchar(body) + + if (first !== '{' && first !== '[') { + debug('strict violation') + throw createStrictSyntaxError(body, first) + } + } + + try { + debug('parse json') + return JSON.parse(body, reviver) + } catch (e) { + throw normalizeJsonSyntaxError(e, { + message: e.message, + stack: e.stack + }) + } + } + + return function jsonParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return + } + + req.body = req.body || {} + + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return + } + + // assert charset per RFC 7159 sec 8.1 + var charset = getCharset(req) || 'utf-8' + if (charset.slice(0, 4) !== 'utf-') { + debug('invalid charset') + next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', { + charset: charset, + type: 'charset.unsupported' + })) + return + } + + // read + read(req, res, next, parse, debug, { + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} + +/** + * Create strict violation syntax error matching native error. + * + * @param {string} str + * @param {string} char + * @return {Error} + * @private + */ + +function createStrictSyntaxError (str, char) { + var index = str.indexOf(char) + var partial = '' + + if (index !== -1) { + partial = str.substring(0, index) + JSON_SYNTAX_CHAR + + for (var i = index + 1; i < str.length; i++) { + partial += JSON_SYNTAX_CHAR + } + } + + try { + JSON.parse(partial); /* istanbul ignore next */ throw new SyntaxError('strict violation') + } catch (e) { + return normalizeJsonSyntaxError(e, { + message: e.message.replace(JSON_SYNTAX_REGEXP, function (placeholder) { + return str.substring(index, index + placeholder.length) + }), + stack: e.stack + }) + } +} + +/** + * Get the first non-whitespace character in a string. + * + * @param {string} str + * @return {function} + * @private + */ + +function firstchar (str) { + var match = FIRST_CHAR_REGEXP.exec(str) + + return match + ? match[1] + : undefined +} + +/** + * Get the charset of a request. + * + * @param {object} req + * @api private + */ + +function getCharset (req) { + try { + return (contentType.parse(req).parameters.charset || '').toLowerCase() + } catch (e) { + return undefined + } +} + +/** + * Normalize a SyntaxError for JSON.parse. + * + * @param {SyntaxError} error + * @param {object} obj + * @return {SyntaxError} + */ + +function normalizeJsonSyntaxError (error, obj) { + var keys = Object.getOwnPropertyNames(error) + + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + if (key !== 'stack' && key !== 'message') { + delete error[key] + } + } + + // replace stack before message for Node.js 0.10 and below + error.stack = obj.stack.replace(error.message, obj.message) + error.message = obj.message + + return error +} + +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ + +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } +} diff --git a/system/login/node_modules/body-parser/lib/types/raw.js b/system/login/node_modules/body-parser/lib/types/raw.js new file mode 100644 index 0000000..f5d1b67 --- /dev/null +++ b/system/login/node_modules/body-parser/lib/types/raw.js @@ -0,0 +1,101 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + */ + +var bytes = require('bytes') +var debug = require('debug')('body-parser:raw') +var read = require('../read') +var typeis = require('type-is') + +/** + * Module exports. + */ + +module.exports = raw + +/** + * Create a middleware to parse raw bodies. + * + * @param {object} [options] + * @return {function} + * @api public + */ + +function raw (options) { + var opts = options || {} + + var inflate = opts.inflate !== false + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var type = opts.type || 'application/octet-stream' + var verify = opts.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + function parse (buf) { + return buf + } + + return function rawParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return + } + + req.body = req.body || {} + + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return + } + + // read + read(req, res, next, parse, debug, { + encoding: null, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} + +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ + +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } +} diff --git a/system/login/node_modules/body-parser/lib/types/text.js b/system/login/node_modules/body-parser/lib/types/text.js new file mode 100644 index 0000000..083a009 --- /dev/null +++ b/system/login/node_modules/body-parser/lib/types/text.js @@ -0,0 +1,121 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + */ + +var bytes = require('bytes') +var contentType = require('content-type') +var debug = require('debug')('body-parser:text') +var read = require('../read') +var typeis = require('type-is') + +/** + * Module exports. + */ + +module.exports = text + +/** + * Create a middleware to parse text bodies. + * + * @param {object} [options] + * @return {function} + * @api public + */ + +function text (options) { + var opts = options || {} + + var defaultCharset = opts.defaultCharset || 'utf-8' + var inflate = opts.inflate !== false + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var type = opts.type || 'text/plain' + var verify = opts.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + function parse (buf) { + return buf + } + + return function textParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return + } + + req.body = req.body || {} + + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return + } + + // get charset + var charset = getCharset(req) || defaultCharset + + // read + read(req, res, next, parse, debug, { + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} + +/** + * Get the charset of a request. + * + * @param {object} req + * @api private + */ + +function getCharset (req) { + try { + return (contentType.parse(req).parameters.charset || '').toLowerCase() + } catch (e) { + return undefined + } +} + +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ + +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } +} diff --git a/system/login/node_modules/body-parser/lib/types/urlencoded.js b/system/login/node_modules/body-parser/lib/types/urlencoded.js new file mode 100644 index 0000000..b2ca8f1 --- /dev/null +++ b/system/login/node_modules/body-parser/lib/types/urlencoded.js @@ -0,0 +1,284 @@ +/*! + * body-parser + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var bytes = require('bytes') +var contentType = require('content-type') +var createError = require('http-errors') +var debug = require('debug')('body-parser:urlencoded') +var deprecate = require('depd')('body-parser') +var read = require('../read') +var typeis = require('type-is') + +/** + * Module exports. + */ + +module.exports = urlencoded + +/** + * Cache of parser modules. + */ + +var parsers = Object.create(null) + +/** + * Create a middleware to parse urlencoded bodies. + * + * @param {object} [options] + * @return {function} + * @public + */ + +function urlencoded (options) { + var opts = options || {} + + // notice because option default will flip in next major + if (opts.extended === undefined) { + deprecate('undefined extended: provide extended option') + } + + var extended = opts.extended !== false + var inflate = opts.inflate !== false + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var type = opts.type || 'application/x-www-form-urlencoded' + var verify = opts.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + // create the appropriate query parser + var queryparse = extended + ? extendedparser(opts) + : simpleparser(opts) + + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + function parse (body) { + return body.length + ? queryparse(body) + : {} + } + + return function urlencodedParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return + } + + req.body = req.body || {} + + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return + } + + // assert charset + var charset = getCharset(req) || 'utf-8' + if (charset !== 'utf-8') { + debug('invalid charset') + next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', { + charset: charset, + type: 'charset.unsupported' + })) + return + } + + // read + read(req, res, next, parse, debug, { + debug: debug, + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} + +/** + * Get the extended query parser. + * + * @param {object} options + */ + +function extendedparser (options) { + var parameterLimit = options.parameterLimit !== undefined + ? options.parameterLimit + : 1000 + var parse = parser('qs') + + if (isNaN(parameterLimit) || parameterLimit < 1) { + throw new TypeError('option parameterLimit must be a positive number') + } + + if (isFinite(parameterLimit)) { + parameterLimit = parameterLimit | 0 + } + + return function queryparse (body) { + var paramCount = parameterCount(body, parameterLimit) + + if (paramCount === undefined) { + debug('too many parameters') + throw createError(413, 'too many parameters', { + type: 'parameters.too.many' + }) + } + + var arrayLimit = Math.max(100, paramCount) + + debug('parse extended urlencoding') + return parse(body, { + allowPrototypes: true, + arrayLimit: arrayLimit, + depth: Infinity, + parameterLimit: parameterLimit + }) + } +} + +/** + * Get the charset of a request. + * + * @param {object} req + * @api private + */ + +function getCharset (req) { + try { + return (contentType.parse(req).parameters.charset || '').toLowerCase() + } catch (e) { + return undefined + } +} + +/** + * Count the number of parameters, stopping once limit reached + * + * @param {string} body + * @param {number} limit + * @api private + */ + +function parameterCount (body, limit) { + var count = 0 + var index = 0 + + while ((index = body.indexOf('&', index)) !== -1) { + count++ + index++ + + if (count === limit) { + return undefined + } + } + + return count +} + +/** + * Get parser for module name dynamically. + * + * @param {string} name + * @return {function} + * @api private + */ + +function parser (name) { + var mod = parsers[name] + + if (mod !== undefined) { + return mod.parse + } + + // this uses a switch for static require analysis + switch (name) { + case 'qs': + mod = require('qs') + break + case 'querystring': + mod = require('querystring') + break + } + + // store to prevent invoking require() + parsers[name] = mod + + return mod.parse +} + +/** + * Get the simple query parser. + * + * @param {object} options + */ + +function simpleparser (options) { + var parameterLimit = options.parameterLimit !== undefined + ? options.parameterLimit + : 1000 + var parse = parser('querystring') + + if (isNaN(parameterLimit) || parameterLimit < 1) { + throw new TypeError('option parameterLimit must be a positive number') + } + + if (isFinite(parameterLimit)) { + parameterLimit = parameterLimit | 0 + } + + return function queryparse (body) { + var paramCount = parameterCount(body, parameterLimit) + + if (paramCount === undefined) { + debug('too many parameters') + throw createError(413, 'too many parameters', { + type: 'parameters.too.many' + }) + } + + debug('parse urlencoding') + return parse(body, undefined, undefined, { maxKeys: parameterLimit }) + } +} + +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ + +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } +} diff --git a/system/login/node_modules/body-parser/package.json b/system/login/node_modules/body-parser/package.json new file mode 100644 index 0000000..4637304 --- /dev/null +++ b/system/login/node_modules/body-parser/package.json @@ -0,0 +1,56 @@ +{ + "name": "body-parser", + "description": "Node.js body parsing middleware", + "version": "1.20.2", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "repository": "expressjs/body-parser", + "dependencies": { + "bytes": "3.1.2", + "content-type": "~1.0.5", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "on-finished": "2.4.1", + "qs": "6.11.0", + "raw-body": "2.5.2", + "type-is": "~1.6.18", + "unpipe": "1.0.0" + }, + "devDependencies": { + "eslint": "8.34.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.27.5", + "eslint-plugin-markdown": "3.0.0", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "6.1.1", + "eslint-plugin-standard": "4.1.0", + "methods": "1.1.2", + "mocha": "10.2.0", + "nyc": "15.1.0", + "safe-buffer": "5.2.1", + "supertest": "6.3.3" + }, + "files": [ + "lib/", + "LICENSE", + "HISTORY.md", + "SECURITY.md", + "index.js" + ], + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --require test/support/env --reporter spec --check-leaks --bail test/", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/system/login/node_modules/express/History.md b/system/login/node_modules/express/History.md new file mode 100644 index 0000000..e49870f --- /dev/null +++ b/system/login/node_modules/express/History.md @@ -0,0 +1,3588 @@ +4.18.2 / 2022-10-08 +=================== + + * Fix regression routing a large stack in a single route + * deps: body-parser@1.20.1 + - deps: qs@6.11.0 + - perf: remove unnecessary object clone + * deps: qs@6.11.0 + +4.18.1 / 2022-04-29 +=================== + + * Fix hanging on large stack of sync routes + +4.18.0 / 2022-04-25 +=================== + + * Add "root" option to `res.download` + * Allow `options` without `filename` in `res.download` + * Deprecate string and non-integer arguments to `res.status` + * Fix behavior of `null`/`undefined` as `maxAge` in `res.cookie` + * Fix handling very large stacks of sync middleware + * Ignore `Object.prototype` values in settings through `app.set`/`app.get` + * Invoke `default` with same arguments as types in `res.format` + * Support proper 205 responses using `res.send` + * Use `http-errors` for `res.format` error + * deps: body-parser@1.20.0 + - Fix error message for json parse whitespace in `strict` + - Fix internal error when inflated body exceeds limit + - Prevent loss of async hooks context + - Prevent hanging when request already read + - deps: depd@2.0.0 + - deps: http-errors@2.0.0 + - deps: on-finished@2.4.1 + - deps: qs@6.10.3 + - deps: raw-body@2.5.1 + * deps: cookie@0.5.0 + - Add `priority` option + - Fix `expires` option to reject invalid dates + * deps: depd@2.0.0 + - Replace internal `eval` usage with `Function` constructor + - Use instance methods on `process` to check for listeners + * deps: finalhandler@1.2.0 + - Remove set content headers that break response + - deps: on-finished@2.4.1 + - deps: statuses@2.0.1 + * deps: on-finished@2.4.1 + - Prevent loss of async hooks context + * deps: qs@6.10.3 + * deps: send@0.18.0 + - Fix emitted 416 error missing headers property + - Limit the headers removed for 304 response + - deps: depd@2.0.0 + - deps: destroy@1.2.0 + - deps: http-errors@2.0.0 + - deps: on-finished@2.4.1 + - deps: statuses@2.0.1 + * deps: serve-static@1.15.0 + - deps: send@0.18.0 + * deps: statuses@2.0.1 + - Remove code 306 + - Rename `425 Unordered Collection` to standard `425 Too Early` + +4.17.3 / 2022-02-16 +=================== + + * deps: accepts@~1.3.8 + - deps: mime-types@~2.1.34 + - deps: negotiator@0.6.3 + * deps: body-parser@1.19.2 + - deps: bytes@3.1.2 + - deps: qs@6.9.7 + - deps: raw-body@2.4.3 + * deps: cookie@0.4.2 + * deps: qs@6.9.7 + * Fix handling of `__proto__` keys + * pref: remove unnecessary regexp for trust proxy + +4.17.2 / 2021-12-16 +=================== + + * Fix handling of `undefined` in `res.jsonp` + * Fix handling of `undefined` when `"json escape"` is enabled + * Fix incorrect middleware execution with unanchored `RegExp`s + * Fix `res.jsonp(obj, status)` deprecation message + * Fix typo in `res.is` JSDoc + * deps: body-parser@1.19.1 + - deps: bytes@3.1.1 + - deps: http-errors@1.8.1 + - deps: qs@6.9.6 + - deps: raw-body@2.4.2 + - deps: safe-buffer@5.2.1 + - deps: type-is@~1.6.18 + * deps: content-disposition@0.5.4 + - deps: safe-buffer@5.2.1 + * deps: cookie@0.4.1 + - Fix `maxAge` option to reject invalid values + * deps: proxy-addr@~2.0.7 + - Use `req.socket` over deprecated `req.connection` + - deps: forwarded@0.2.0 + - deps: ipaddr.js@1.9.1 + * deps: qs@6.9.6 + * deps: safe-buffer@5.2.1 + * deps: send@0.17.2 + - deps: http-errors@1.8.1 + - deps: ms@2.1.3 + - pref: ignore empty http tokens + * deps: serve-static@1.14.2 + - deps: send@0.17.2 + * deps: setprototypeof@1.2.0 + +4.17.1 / 2019-05-25 +=================== + + * Revert "Improve error message for `null`/`undefined` to `res.status`" + +4.17.0 / 2019-05-16 +=================== + + * Add `express.raw` to parse bodies into `Buffer` + * Add `express.text` to parse bodies into string + * Improve error message for non-strings to `res.sendFile` + * Improve error message for `null`/`undefined` to `res.status` + * Support multiple hosts in `X-Forwarded-Host` + * deps: accepts@~1.3.7 + * deps: body-parser@1.19.0 + - Add encoding MIK + - Add petabyte (`pb`) support + - Fix parsing array brackets after index + - deps: bytes@3.1.0 + - deps: http-errors@1.7.2 + - deps: iconv-lite@0.4.24 + - deps: qs@6.7.0 + - deps: raw-body@2.4.0 + - deps: type-is@~1.6.17 + * deps: content-disposition@0.5.3 + * deps: cookie@0.4.0 + - Add `SameSite=None` support + * deps: finalhandler@~1.1.2 + - Set stricter `Content-Security-Policy` header + - deps: parseurl@~1.3.3 + - deps: statuses@~1.5.0 + * deps: parseurl@~1.3.3 + * deps: proxy-addr@~2.0.5 + - deps: ipaddr.js@1.9.0 + * deps: qs@6.7.0 + - Fix parsing array brackets after index + * deps: range-parser@~1.2.1 + * deps: send@0.17.1 + - Set stricter CSP header in redirect & error responses + - deps: http-errors@~1.7.2 + - deps: mime@1.6.0 + - deps: ms@2.1.1 + - deps: range-parser@~1.2.1 + - deps: statuses@~1.5.0 + - perf: remove redundant `path.normalize` call + * deps: serve-static@1.14.1 + - Set stricter CSP header in redirect response + - deps: parseurl@~1.3.3 + - deps: send@0.17.1 + * deps: setprototypeof@1.1.1 + * deps: statuses@~1.5.0 + - Add `103 Early Hints` + * deps: type-is@~1.6.18 + - deps: mime-types@~2.1.24 + - perf: prevent internal `throw` on invalid type + +4.16.4 / 2018-10-10 +=================== + + * Fix issue where `"Request aborted"` may be logged in `res.sendfile` + * Fix JSDoc for `Router` constructor + * deps: body-parser@1.18.3 + - Fix deprecation warnings on Node.js 10+ + - Fix stack trace for strict json parse error + - deps: depd@~1.1.2 + - deps: http-errors@~1.6.3 + - deps: iconv-lite@0.4.23 + - deps: qs@6.5.2 + - deps: raw-body@2.3.3 + - deps: type-is@~1.6.16 + * deps: proxy-addr@~2.0.4 + - deps: ipaddr.js@1.8.0 + * deps: qs@6.5.2 + * deps: safe-buffer@5.1.2 + +4.16.3 / 2018-03-12 +=================== + + * deps: accepts@~1.3.5 + - deps: mime-types@~2.1.18 + * deps: depd@~1.1.2 + - perf: remove argument reassignment + * deps: encodeurl@~1.0.2 + - Fix encoding `%` as last character + * deps: finalhandler@1.1.1 + - Fix 404 output for bad / missing pathnames + - deps: encodeurl@~1.0.2 + - deps: statuses@~1.4.0 + * deps: proxy-addr@~2.0.3 + - deps: ipaddr.js@1.6.0 + * deps: send@0.16.2 + - Fix incorrect end tag in default error & redirects + - deps: depd@~1.1.2 + - deps: encodeurl@~1.0.2 + - deps: statuses@~1.4.0 + * deps: serve-static@1.13.2 + - Fix incorrect end tag in redirects + - deps: encodeurl@~1.0.2 + - deps: send@0.16.2 + * deps: statuses@~1.4.0 + * deps: type-is@~1.6.16 + - deps: mime-types@~2.1.18 + +4.16.2 / 2017-10-09 +=================== + + * Fix `TypeError` in `res.send` when given `Buffer` and `ETag` header set + * perf: skip parsing of entire `X-Forwarded-Proto` header + +4.16.1 / 2017-09-29 +=================== + + * deps: send@0.16.1 + * deps: serve-static@1.13.1 + - Fix regression when `root` is incorrectly set to a file + - deps: send@0.16.1 + +4.16.0 / 2017-09-28 +=================== + + * Add `"json escape"` setting for `res.json` and `res.jsonp` + * Add `express.json` and `express.urlencoded` to parse bodies + * Add `options` argument to `res.download` + * Improve error message when autoloading invalid view engine + * Improve error messages when non-function provided as middleware + * Skip `Buffer` encoding when not generating ETag for small response + * Use `safe-buffer` for improved Buffer API + * deps: accepts@~1.3.4 + - deps: mime-types@~2.1.16 + * deps: content-type@~1.0.4 + - perf: remove argument reassignment + - perf: skip parameter parsing when no parameters + * deps: etag@~1.8.1 + - perf: replace regular expression with substring + * deps: finalhandler@1.1.0 + - Use `res.headersSent` when available + * deps: parseurl@~1.3.2 + - perf: reduce overhead for full URLs + - perf: unroll the "fast-path" `RegExp` + * deps: proxy-addr@~2.0.2 + - Fix trimming leading / trailing OWS in `X-Forwarded-For` + - deps: forwarded@~0.1.2 + - deps: ipaddr.js@1.5.2 + - perf: reduce overhead when no `X-Forwarded-For` header + * deps: qs@6.5.1 + - Fix parsing & compacting very deep objects + * deps: send@0.16.0 + - Add 70 new types for file extensions + - Add `immutable` option + - Fix missing `` in default error & redirects + - Set charset as "UTF-8" for .js and .json + - Use instance methods on steam to check for listeners + - deps: mime@1.4.1 + - perf: improve path validation speed + * deps: serve-static@1.13.0 + - Add 70 new types for file extensions + - Add `immutable` option + - Set charset as "UTF-8" for .js and .json + - deps: send@0.16.0 + * deps: setprototypeof@1.1.0 + * deps: utils-merge@1.0.1 + * deps: vary@~1.1.2 + - perf: improve header token parsing speed + * perf: re-use options object when generating ETags + * perf: remove dead `.charset` set in `res.jsonp` + +4.15.5 / 2017-09-24 +=================== + + * deps: debug@2.6.9 + * deps: finalhandler@~1.0.6 + - deps: debug@2.6.9 + - deps: parseurl@~1.3.2 + * deps: fresh@0.5.2 + - Fix handling of modified headers with invalid dates + - perf: improve ETag match loop + - perf: improve `If-None-Match` token parsing + * deps: send@0.15.6 + - Fix handling of modified headers with invalid dates + - deps: debug@2.6.9 + - deps: etag@~1.8.1 + - deps: fresh@0.5.2 + - perf: improve `If-Match` token parsing + * deps: serve-static@1.12.6 + - deps: parseurl@~1.3.2 + - deps: send@0.15.6 + - perf: improve slash collapsing + +4.15.4 / 2017-08-06 +=================== + + * deps: debug@2.6.8 + * deps: depd@~1.1.1 + - Remove unnecessary `Buffer` loading + * deps: finalhandler@~1.0.4 + - deps: debug@2.6.8 + * deps: proxy-addr@~1.1.5 + - Fix array argument being altered + - deps: ipaddr.js@1.4.0 + * deps: qs@6.5.0 + * deps: send@0.15.4 + - deps: debug@2.6.8 + - deps: depd@~1.1.1 + - deps: http-errors@~1.6.2 + * deps: serve-static@1.12.4 + - deps: send@0.15.4 + +4.15.3 / 2017-05-16 +=================== + + * Fix error when `res.set` cannot add charset to `Content-Type` + * deps: debug@2.6.7 + - Fix `DEBUG_MAX_ARRAY_LENGTH` + - deps: ms@2.0.0 + * deps: finalhandler@~1.0.3 + - Fix missing `` in HTML document + - deps: debug@2.6.7 + * deps: proxy-addr@~1.1.4 + - deps: ipaddr.js@1.3.0 + * deps: send@0.15.3 + - deps: debug@2.6.7 + - deps: ms@2.0.0 + * deps: serve-static@1.12.3 + - deps: send@0.15.3 + * deps: type-is@~1.6.15 + - deps: mime-types@~2.1.15 + * deps: vary@~1.1.1 + - perf: hoist regular expression + +4.15.2 / 2017-03-06 +=================== + + * deps: qs@6.4.0 + - Fix regression parsing keys starting with `[` + +4.15.1 / 2017-03-05 +=================== + + * deps: send@0.15.1 + - Fix issue when `Date.parse` does not return `NaN` on invalid date + - Fix strict violation in broken environments + * deps: serve-static@1.12.1 + - Fix issue when `Date.parse` does not return `NaN` on invalid date + - deps: send@0.15.1 + +4.15.0 / 2017-03-01 +=================== + + * Add debug message when loading view engine + * Add `next("router")` to exit from router + * Fix case where `router.use` skipped requests routes did not + * Remove usage of `res._headers` private field + - Improves compatibility with Node.js 8 nightly + * Skip routing when `req.url` is not set + * Use `%o` in path debug to tell types apart + * Use `Object.create` to setup request & response prototypes + * Use `setprototypeof` module to replace `__proto__` setting + * Use `statuses` instead of `http` module for status messages + * deps: debug@2.6.1 + - Allow colors in workers + - Deprecated `DEBUG_FD` environment variable set to `3` or higher + - Fix error when running under React Native + - Use same color for same namespace + - deps: ms@0.7.2 + * deps: etag@~1.8.0 + - Use SHA1 instead of MD5 for ETag hashing + - Works with FIPS 140-2 OpenSSL configuration + * deps: finalhandler@~1.0.0 + - Fix exception when `err` cannot be converted to a string + - Fully URL-encode the pathname in the 404 + - Only include the pathname in the 404 message + - Send complete HTML document + - Set `Content-Security-Policy: default-src 'self'` header + - deps: debug@2.6.1 + * deps: fresh@0.5.0 + - Fix false detection of `no-cache` request directive + - Fix incorrect result when `If-None-Match` has both `*` and ETags + - Fix weak `ETag` matching to match spec + - perf: delay reading header values until needed + - perf: enable strict mode + - perf: hoist regular expressions + - perf: remove duplicate conditional + - perf: remove unnecessary boolean coercions + - perf: skip checking modified time if ETag check failed + - perf: skip parsing `If-None-Match` when no `ETag` header + - perf: use `Date.parse` instead of `new Date` + * deps: qs@6.3.1 + - Fix array parsing from skipping empty values + - Fix compacting nested arrays + * deps: send@0.15.0 + - Fix false detection of `no-cache` request directive + - Fix incorrect result when `If-None-Match` has both `*` and ETags + - Fix weak `ETag` matching to match spec + - Remove usage of `res._headers` private field + - Support `If-Match` and `If-Unmodified-Since` headers + - Use `res.getHeaderNames()` when available + - Use `res.headersSent` when available + - deps: debug@2.6.1 + - deps: etag@~1.8.0 + - deps: fresh@0.5.0 + - deps: http-errors@~1.6.1 + * deps: serve-static@1.12.0 + - Fix false detection of `no-cache` request directive + - Fix incorrect result when `If-None-Match` has both `*` and ETags + - Fix weak `ETag` matching to match spec + - Remove usage of `res._headers` private field + - Send complete HTML document in redirect response + - Set default CSP header in redirect response + - Support `If-Match` and `If-Unmodified-Since` headers + - Use `res.getHeaderNames()` when available + - Use `res.headersSent` when available + - deps: send@0.15.0 + * perf: add fast match path for `*` route + * perf: improve `req.ips` performance + +4.14.1 / 2017-01-28 +=================== + + * deps: content-disposition@0.5.2 + * deps: finalhandler@0.5.1 + - Fix exception when `err.headers` is not an object + - deps: statuses@~1.3.1 + - perf: hoist regular expressions + - perf: remove duplicate validation path + * deps: proxy-addr@~1.1.3 + - deps: ipaddr.js@1.2.0 + * deps: send@0.14.2 + - deps: http-errors@~1.5.1 + - deps: ms@0.7.2 + - deps: statuses@~1.3.1 + * deps: serve-static@~1.11.2 + - deps: send@0.14.2 + * deps: type-is@~1.6.14 + - deps: mime-types@~2.1.13 + +4.14.0 / 2016-06-16 +=================== + + * Add `acceptRanges` option to `res.sendFile`/`res.sendfile` + * Add `cacheControl` option to `res.sendFile`/`res.sendfile` + * Add `options` argument to `req.range` + - Includes the `combine` option + * Encode URL in `res.location`/`res.redirect` if not already encoded + * Fix some redirect handling in `res.sendFile`/`res.sendfile` + * Fix Windows absolute path check using forward slashes + * Improve error with invalid arguments to `req.get()` + * Improve performance for `res.json`/`res.jsonp` in most cases + * Improve `Range` header handling in `res.sendFile`/`res.sendfile` + * deps: accepts@~1.3.3 + - Fix including type extensions in parameters in `Accept` parsing + - Fix parsing `Accept` parameters with quoted equals + - Fix parsing `Accept` parameters with quoted semicolons + - Many performance improvements + - deps: mime-types@~2.1.11 + - deps: negotiator@0.6.1 + * deps: content-type@~1.0.2 + - perf: enable strict mode + * deps: cookie@0.3.1 + - Add `sameSite` option + - Fix cookie `Max-Age` to never be a floating point number + - Improve error message when `encode` is not a function + - Improve error message when `expires` is not a `Date` + - Throw better error for invalid argument to parse + - Throw on invalid values provided to `serialize` + - perf: enable strict mode + - perf: hoist regular expression + - perf: use for loop in parse + - perf: use string concatenation for serialization + * deps: finalhandler@0.5.0 + - Change invalid or non-numeric status code to 500 + - Overwrite status message to match set status code + - Prefer `err.statusCode` if `err.status` is invalid + - Set response headers from `err.headers` object + - Use `statuses` instead of `http` module for status messages + * deps: proxy-addr@~1.1.2 + - Fix accepting various invalid netmasks + - Fix IPv6-mapped IPv4 validation edge cases + - IPv4 netmasks must be contiguous + - IPv6 addresses cannot be used as a netmask + - deps: ipaddr.js@1.1.1 + * deps: qs@6.2.0 + - Add `decoder` option in `parse` function + * deps: range-parser@~1.2.0 + - Add `combine` option to combine overlapping ranges + - Fix incorrectly returning -1 when there is at least one valid range + - perf: remove internal function + * deps: send@0.14.1 + - Add `acceptRanges` option + - Add `cacheControl` option + - Attempt to combine multiple ranges into single range + - Correctly inherit from `Stream` class + - Fix `Content-Range` header in 416 responses when using `start`/`end` options + - Fix `Content-Range` header missing from default 416 responses + - Fix redirect error when `path` contains raw non-URL characters + - Fix redirect when `path` starts with multiple forward slashes + - Ignore non-byte `Range` headers + - deps: http-errors@~1.5.0 + - deps: range-parser@~1.2.0 + - deps: statuses@~1.3.0 + - perf: remove argument reassignment + * deps: serve-static@~1.11.1 + - Add `acceptRanges` option + - Add `cacheControl` option + - Attempt to combine multiple ranges into single range + - Fix redirect error when `req.url` contains raw non-URL characters + - Ignore non-byte `Range` headers + - Use status code 301 for redirects + - deps: send@0.14.1 + * deps: type-is@~1.6.13 + - Fix type error when given invalid type to match against + - deps: mime-types@~2.1.11 + * deps: vary@~1.1.0 + - Only accept valid field names in the `field` argument + * perf: use strict equality when possible + +4.13.4 / 2016-01-21 +=================== + + * deps: content-disposition@0.5.1 + - perf: enable strict mode + * deps: cookie@0.1.5 + - Throw on invalid values provided to `serialize` + * deps: depd@~1.1.0 + - Support web browser loading + - perf: enable strict mode + * deps: escape-html@~1.0.3 + - perf: enable strict mode + - perf: optimize string replacement + - perf: use faster string coercion + * deps: finalhandler@0.4.1 + - deps: escape-html@~1.0.3 + * deps: merge-descriptors@1.0.1 + - perf: enable strict mode + * deps: methods@~1.1.2 + - perf: enable strict mode + * deps: parseurl@~1.3.1 + - perf: enable strict mode + * deps: proxy-addr@~1.0.10 + - deps: ipaddr.js@1.0.5 + - perf: enable strict mode + * deps: range-parser@~1.0.3 + - perf: enable strict mode + * deps: send@0.13.1 + - deps: depd@~1.1.0 + - deps: destroy@~1.0.4 + - deps: escape-html@~1.0.3 + - deps: range-parser@~1.0.3 + * deps: serve-static@~1.10.2 + - deps: escape-html@~1.0.3 + - deps: parseurl@~1.3.0 + - deps: send@0.13.1 + +4.13.3 / 2015-08-02 +=================== + + * Fix infinite loop condition using `mergeParams: true` + * Fix inner numeric indices incorrectly altering parent `req.params` + +4.13.2 / 2015-07-31 +=================== + + * deps: accepts@~1.2.12 + - deps: mime-types@~2.1.4 + * deps: array-flatten@1.1.1 + - perf: enable strict mode + * deps: path-to-regexp@0.1.7 + - Fix regression with escaped round brackets and matching groups + * deps: type-is@~1.6.6 + - deps: mime-types@~2.1.4 + +4.13.1 / 2015-07-05 +=================== + + * deps: accepts@~1.2.10 + - deps: mime-types@~2.1.2 + * deps: qs@4.0.0 + - Fix dropping parameters like `hasOwnProperty` + - Fix various parsing edge cases + * deps: type-is@~1.6.4 + - deps: mime-types@~2.1.2 + - perf: enable strict mode + - perf: remove argument reassignment + +4.13.0 / 2015-06-20 +=================== + + * Add settings to debug output + * Fix `res.format` error when only `default` provided + * Fix issue where `next('route')` in `app.param` would incorrectly skip values + * Fix hiding platform issues with `decodeURIComponent` + - Only `URIError`s are a 400 + * Fix using `*` before params in routes + * Fix using capture groups before params in routes + * Simplify `res.cookie` to call `res.append` + * Use `array-flatten` module for flattening arrays + * deps: accepts@~1.2.9 + - deps: mime-types@~2.1.1 + - perf: avoid argument reassignment & argument slice + - perf: avoid negotiator recursive construction + - perf: enable strict mode + - perf: remove unnecessary bitwise operator + * deps: cookie@0.1.3 + - perf: deduce the scope of try-catch deopt + - perf: remove argument reassignments + * deps: escape-html@1.0.2 + * deps: etag@~1.7.0 + - Always include entity length in ETags for hash length extensions + - Generate non-Stats ETags using MD5 only (no longer CRC32) + - Improve stat performance by removing hashing + - Improve support for JXcore + - Remove base64 padding in ETags to shorten + - Support "fake" stats objects in environments without fs + - Use MD5 instead of MD4 in weak ETags over 1KB + * deps: finalhandler@0.4.0 + - Fix a false-positive when unpiping in Node.js 0.8 + - Support `statusCode` property on `Error` objects + - Use `unpipe` module for unpiping requests + - deps: escape-html@1.0.2 + - deps: on-finished@~2.3.0 + - perf: enable strict mode + - perf: remove argument reassignment + * deps: fresh@0.3.0 + - Add weak `ETag` matching support + * 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 + * deps: path-to-regexp@0.1.6 + * deps: send@0.13.0 + - Allow Node.js HTTP server to set `Date` response header + - Fix incorrectly removing `Content-Location` on 304 response + - Improve the default redirect response headers + - Send appropriate headers on default error response + - Use `http-errors` for standard emitted errors + - Use `statuses` instead of `http` module for status messages + - deps: escape-html@1.0.2 + - deps: etag@~1.7.0 + - deps: fresh@0.3.0 + - deps: on-finished@~2.3.0 + - perf: enable strict mode + - perf: remove unnecessary array allocations + * deps: serve-static@~1.10.0 + - Add `fallthrough` option + - Fix reading options from options prototype + - Improve the default redirect response headers + - Malformed URLs now `next()` instead of 400 + - deps: escape-html@1.0.2 + - deps: send@0.13.0 + - perf: enable strict mode + - perf: remove argument reassignment + * deps: type-is@~1.6.3 + - deps: mime-types@~2.1.1 + - perf: reduce try block size + - perf: remove bitwise operations + * perf: enable strict mode + * perf: isolate `app.render` try block + * perf: remove argument reassignments in application + * perf: remove argument reassignments in request prototype + * perf: remove argument reassignments in response prototype + * perf: remove argument reassignments in routing + * perf: remove argument reassignments in `View` + * perf: skip attempting to decode zero length string + * perf: use saved reference to `http.STATUS_CODES` + +4.12.4 / 2015-05-17 +=================== + + * deps: accepts@~1.2.7 + - deps: mime-types@~2.0.11 + - deps: negotiator@0.5.3 + * deps: debug@~2.2.0 + - deps: ms@0.7.1 + * deps: depd@~1.0.1 + * deps: etag@~1.6.0 + - Improve support for JXcore + - Support "fake" stats objects in environments without `fs` + * deps: finalhandler@0.3.6 + - deps: debug@~2.2.0 + - deps: on-finished@~2.2.1 + * deps: on-finished@~2.2.1 + - Fix `isFinished(req)` when data buffered + * deps: proxy-addr@~1.0.8 + - deps: ipaddr.js@1.0.1 + * deps: qs@2.4.2 + - Fix allowing parameters like `constructor` + * deps: send@0.12.3 + - deps: debug@~2.2.0 + - deps: depd@~1.0.1 + - deps: etag@~1.6.0 + - deps: ms@0.7.1 + - deps: on-finished@~2.2.1 + * deps: serve-static@~1.9.3 + - deps: send@0.12.3 + * deps: type-is@~1.6.2 + - deps: mime-types@~2.0.11 + +4.12.3 / 2015-03-17 +=================== + + * deps: accepts@~1.2.5 + - deps: mime-types@~2.0.10 + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + * deps: finalhandler@0.3.4 + - deps: debug@~2.1.3 + * deps: proxy-addr@~1.0.7 + - deps: ipaddr.js@0.1.9 + * deps: qs@2.4.1 + - Fix error when parameter `hasOwnProperty` is present + * deps: send@0.12.2 + - Throw errors early for invalid `extensions` or `index` options + - deps: debug@~2.1.3 + * deps: serve-static@~1.9.2 + - deps: send@0.12.2 + * deps: type-is@~1.6.1 + - deps: mime-types@~2.0.10 + +4.12.2 / 2015-03-02 +=================== + + * Fix regression where `"Request aborted"` is logged using `res.sendFile` + +4.12.1 / 2015-03-01 +=================== + + * Fix constructing application with non-configurable prototype properties + * Fix `ECONNRESET` errors from `res.sendFile` usage + * Fix `req.host` when using "trust proxy" hops count + * Fix `req.protocol`/`req.secure` when using "trust proxy" hops count + * Fix wrong `code` on aborted connections from `res.sendFile` + * deps: merge-descriptors@1.0.0 + +4.12.0 / 2015-02-23 +=================== + + * Fix `"trust proxy"` setting to inherit when app is mounted + * Generate `ETag`s for all request responses + - No longer restricted to only responses for `GET` and `HEAD` requests + * Use `content-type` to parse `Content-Type` headers + * deps: accepts@~1.2.4 + - Fix preference sorting to be stable for long acceptable lists + - deps: mime-types@~2.0.9 + - deps: negotiator@0.5.1 + * deps: cookie-signature@1.0.6 + * deps: send@0.12.1 + - Always read the stat size from the file + - Fix mutating passed-in `options` + - deps: mime@1.3.4 + * deps: serve-static@~1.9.1 + - deps: send@0.12.1 + * deps: type-is@~1.6.0 + - fix argument reassignment + - fix false-positives in `hasBody` `Transfer-Encoding` check + - support wildcard for both type and subtype (`*/*`) + - deps: mime-types@~2.0.9 + +4.11.2 / 2015-02-01 +=================== + + * Fix `res.redirect` double-calling `res.end` for `HEAD` requests + * deps: accepts@~1.2.3 + - deps: mime-types@~2.0.8 + * deps: proxy-addr@~1.0.6 + - deps: ipaddr.js@0.1.8 + * deps: type-is@~1.5.6 + - deps: mime-types@~2.0.8 + +4.11.1 / 2015-01-20 +=================== + + * deps: send@0.11.1 + - Fix root path disclosure + * deps: serve-static@~1.8.1 + - Fix redirect loop in Node.js 0.11.14 + - Fix root path disclosure + - deps: send@0.11.1 + +4.11.0 / 2015-01-13 +=================== + + * Add `res.append(field, val)` to append headers + * Deprecate leading `:` in `name` for `app.param(name, fn)` + * Deprecate `req.param()` -- use `req.params`, `req.body`, or `req.query` instead + * Deprecate `app.param(fn)` + * Fix `OPTIONS` responses to include the `HEAD` method properly + * Fix `res.sendFile` not always detecting aborted connection + * Match routes iteratively to prevent stack overflows + * deps: accepts@~1.2.2 + - deps: mime-types@~2.0.7 + - deps: negotiator@0.5.0 + * deps: send@0.11.0 + - deps: debug@~2.1.1 + - deps: etag@~1.5.1 + - deps: ms@0.7.0 + - deps: on-finished@~2.2.0 + * deps: serve-static@~1.8.0 + - deps: send@0.11.0 + +4.10.8 / 2015-01-13 +=================== + + * Fix crash from error within `OPTIONS` response handler + * deps: proxy-addr@~1.0.5 + - deps: ipaddr.js@0.1.6 + +4.10.7 / 2015-01-04 +=================== + + * Fix `Allow` header for `OPTIONS` to not contain duplicate methods + * Fix incorrect "Request aborted" for `res.sendFile` when `HEAD` or 304 + * deps: debug@~2.1.1 + * deps: finalhandler@0.3.3 + - deps: debug@~2.1.1 + - deps: on-finished@~2.2.0 + * deps: methods@~1.1.1 + * deps: on-finished@~2.2.0 + * deps: serve-static@~1.7.2 + - Fix potential open redirect when mounted at root + * deps: type-is@~1.5.5 + - deps: mime-types@~2.0.7 + +4.10.6 / 2014-12-12 +=================== + + * Fix exception in `req.fresh`/`req.stale` without response headers + +4.10.5 / 2014-12-10 +=================== + + * Fix `res.send` double-calling `res.end` for `HEAD` requests + * deps: accepts@~1.1.4 + - deps: mime-types@~2.0.4 + * deps: type-is@~1.5.4 + - deps: mime-types@~2.0.4 + +4.10.4 / 2014-11-24 +=================== + + * Fix `res.sendfile` logging standard write errors + +4.10.3 / 2014-11-23 +=================== + + * Fix `res.sendFile` logging standard write errors + * deps: etag@~1.5.1 + * deps: proxy-addr@~1.0.4 + - deps: ipaddr.js@0.1.5 + * deps: qs@2.3.3 + - Fix `arrayLimit` behavior + +4.10.2 / 2014-11-09 +=================== + + * Correctly invoke async router callback asynchronously + * deps: accepts@~1.1.3 + - deps: mime-types@~2.0.3 + * deps: type-is@~1.5.3 + - deps: mime-types@~2.0.3 + +4.10.1 / 2014-10-28 +=================== + + * Fix handling of URLs containing `://` in the path + * deps: qs@2.3.2 + - Fix parsing of mixed objects and values + +4.10.0 / 2014-10-23 +=================== + + * Add support for `app.set('views', array)` + - Views are looked up in sequence in array of directories + * Fix `res.send(status)` to mention `res.sendStatus(status)` + * Fix handling of invalid empty URLs + * Use `content-disposition` module for `res.attachment`/`res.download` + - Sends standards-compliant `Content-Disposition` header + - Full Unicode support + * Use `path.resolve` in view lookup + * deps: debug@~2.1.0 + - Implement `DEBUG_FD` env variable support + * deps: depd@~1.0.0 + * deps: etag@~1.5.0 + - Improve string performance + - Slightly improve speed for weak ETags over 1KB + * deps: finalhandler@0.3.2 + - Terminate in progress response only on error + - Use `on-finished` to determine request status + - deps: debug@~2.1.0 + - deps: on-finished@~2.1.1 + * deps: on-finished@~2.1.1 + - Fix handling of pipelined requests + * deps: qs@2.3.0 + - Fix parsing of mixed implicit and explicit arrays + * deps: send@0.10.1 + - deps: debug@~2.1.0 + - deps: depd@~1.0.0 + - deps: etag@~1.5.0 + - deps: on-finished@~2.1.1 + * deps: serve-static@~1.7.1 + - deps: send@0.10.1 + +4.9.8 / 2014-10-17 +================== + + * Fix `res.redirect` body when redirect status specified + * deps: accepts@~1.1.2 + - Fix error when media type has invalid parameter + - deps: negotiator@0.4.9 + +4.9.7 / 2014-10-10 +================== + + * Fix using same param name in array of paths + +4.9.6 / 2014-10-08 +================== + + * deps: accepts@~1.1.1 + - deps: mime-types@~2.0.2 + - deps: negotiator@0.4.8 + * deps: serve-static@~1.6.4 + - Fix redirect loop when index file serving disabled + * deps: type-is@~1.5.2 + - deps: mime-types@~2.0.2 + +4.9.5 / 2014-09-24 +================== + + * deps: etag@~1.4.0 + * deps: proxy-addr@~1.0.3 + - Use `forwarded` npm module + * deps: send@0.9.3 + - deps: etag@~1.4.0 + * deps: serve-static@~1.6.3 + - deps: send@0.9.3 + +4.9.4 / 2014-09-19 +================== + + * deps: qs@2.2.4 + - Fix issue with object keys starting with numbers truncated + +4.9.3 / 2014-09-18 +================== + + * deps: proxy-addr@~1.0.2 + - Fix a global leak when multiple subnets are trusted + - deps: ipaddr.js@0.1.3 + +4.9.2 / 2014-09-17 +================== + + * Fix regression for empty string `path` in `app.use` + * Fix `router.use` to accept array of middleware without path + * Improve error message for bad `app.use` arguments + +4.9.1 / 2014-09-16 +================== + + * Fix `app.use` to accept array of middleware without path + * deps: depd@0.4.5 + * deps: etag@~1.3.1 + * deps: send@0.9.2 + - deps: depd@0.4.5 + - deps: etag@~1.3.1 + - deps: range-parser@~1.0.2 + * deps: serve-static@~1.6.2 + - deps: send@0.9.2 + +4.9.0 / 2014-09-08 +================== + + * Add `res.sendStatus` + * Invoke callback for sendfile when client aborts + - Applies to `res.sendFile`, `res.sendfile`, and `res.download` + - `err` will be populated with request aborted error + * Support IP address host in `req.subdomains` + * Use `etag` to generate `ETag` headers + * deps: accepts@~1.1.0 + - update `mime-types` + * deps: cookie-signature@1.0.5 + * deps: debug@~2.0.0 + * deps: finalhandler@0.2.0 + - Set `X-Content-Type-Options: nosniff` header + - deps: debug@~2.0.0 + * deps: fresh@0.2.4 + * deps: media-typer@0.3.0 + - Throw error when parameter format invalid on parse + * deps: qs@2.2.3 + - Fix issue where first empty value in array is discarded + * deps: range-parser@~1.0.2 + * deps: send@0.9.1 + - Add `lastModified` option + - Use `etag` to generate `ETag` header + - deps: debug@~2.0.0 + - deps: fresh@0.2.4 + * deps: serve-static@~1.6.1 + - Add `lastModified` option + - deps: send@0.9.1 + * deps: type-is@~1.5.1 + - fix `hasbody` to be true for `content-length: 0` + - deps: media-typer@0.3.0 + - deps: mime-types@~2.0.1 + * deps: vary@~1.0.0 + - Accept valid `Vary` header string as `field` + +4.8.8 / 2014-09-04 +================== + + * deps: send@0.8.5 + - Fix a path traversal issue when using `root` + - Fix malicious path detection for empty string path + * deps: serve-static@~1.5.4 + - deps: send@0.8.5 + +4.8.7 / 2014-08-29 +================== + + * deps: qs@2.2.2 + - Remove unnecessary cloning + +4.8.6 / 2014-08-27 +================== + + * deps: qs@2.2.0 + - Array parsing fix + - Performance improvements + +4.8.5 / 2014-08-18 +================== + + * deps: send@0.8.3 + - deps: destroy@1.0.3 + - deps: on-finished@2.1.0 + * deps: serve-static@~1.5.3 + - deps: send@0.8.3 + +4.8.4 / 2014-08-14 +================== + + * deps: qs@1.2.2 + * deps: send@0.8.2 + - Work around `fd` leak in Node.js 0.10 for `fs.ReadStream` + * deps: serve-static@~1.5.2 + - deps: send@0.8.2 + +4.8.3 / 2014-08-10 +================== + + * deps: parseurl@~1.3.0 + * deps: qs@1.2.1 + * deps: serve-static@~1.5.1 + - Fix parsing of weird `req.originalUrl` values + - deps: parseurl@~1.3.0 + - deps: utils-merge@1.0.0 + +4.8.2 / 2014-08-07 +================== + + * deps: qs@1.2.0 + - Fix parsing array of objects + +4.8.1 / 2014-08-06 +================== + + * fix incorrect deprecation warnings on `res.download` + * deps: qs@1.1.0 + - Accept urlencoded square brackets + - Accept empty values in implicit array notation + +4.8.0 / 2014-08-05 +================== + + * add `res.sendFile` + - accepts a file system path instead of a URL + - requires an absolute path or `root` option specified + * deprecate `res.sendfile` -- use `res.sendFile` instead + * support mounted app as any argument to `app.use()` + * deps: qs@1.0.2 + - Complete rewrite + - Limits array length to 20 + - Limits object depth to 5 + - Limits parameters to 1,000 + * deps: send@0.8.1 + - Add `extensions` option + * deps: serve-static@~1.5.0 + - Add `extensions` option + - deps: send@0.8.1 + +4.7.4 / 2014-08-04 +================== + + * fix `res.sendfile` regression for serving directory index files + * deps: send@0.7.4 + - Fix incorrect 403 on Windows and Node.js 0.11 + - Fix serving index files without root dir + * deps: serve-static@~1.4.4 + - deps: send@0.7.4 + +4.7.3 / 2014-08-04 +================== + + * deps: send@0.7.3 + - Fix incorrect 403 on Windows and Node.js 0.11 + * deps: serve-static@~1.4.3 + - Fix incorrect 403 on Windows and Node.js 0.11 + - deps: send@0.7.3 + +4.7.2 / 2014-07-27 +================== + + * deps: depd@0.4.4 + - Work-around v8 generating empty stack traces + * deps: send@0.7.2 + - deps: depd@0.4.4 + * deps: serve-static@~1.4.2 + +4.7.1 / 2014-07-26 +================== + + * deps: depd@0.4.3 + - Fix exception when global `Error.stackTraceLimit` is too low + * deps: send@0.7.1 + - deps: depd@0.4.3 + * deps: serve-static@~1.4.1 + +4.7.0 / 2014-07-25 +================== + + * fix `req.protocol` for proxy-direct connections + * configurable query parser with `app.set('query parser', parser)` + - `app.set('query parser', 'extended')` parse with "qs" module + - `app.set('query parser', 'simple')` parse with "querystring" core module + - `app.set('query parser', false)` disable query string parsing + - `app.set('query parser', true)` enable simple parsing + * deprecate `res.json(status, obj)` -- use `res.status(status).json(obj)` instead + * deprecate `res.jsonp(status, obj)` -- use `res.status(status).jsonp(obj)` instead + * deprecate `res.send(status, body)` -- use `res.status(status).send(body)` instead + * deps: debug@1.0.4 + * deps: depd@0.4.2 + - Add `TRACE_DEPRECATION` environment variable + - Remove non-standard grey color from color output + - Support `--no-deprecation` argument + - Support `--trace-deprecation` argument + * deps: finalhandler@0.1.0 + - Respond after request fully read + - deps: debug@1.0.4 + * deps: parseurl@~1.2.0 + - Cache URLs based on original value + - Remove no-longer-needed URL mis-parse work-around + - Simplify the "fast-path" `RegExp` + * deps: send@0.7.0 + - Add `dotfiles` option + - Cap `maxAge` value to 1 year + - deps: debug@1.0.4 + - deps: depd@0.4.2 + * deps: serve-static@~1.4.0 + - deps: parseurl@~1.2.0 + - deps: send@0.7.0 + * perf: prevent multiple `Buffer` creation in `res.send` + +4.6.1 / 2014-07-12 +================== + + * fix `subapp.mountpath` regression for `app.use(subapp)` + +4.6.0 / 2014-07-11 +================== + + * accept multiple callbacks to `app.use()` + * add explicit "Rosetta Flash JSONP abuse" protection + - previous versions are not vulnerable; this is just explicit protection + * catch errors in multiple `req.param(name, fn)` handlers + * deprecate `res.redirect(url, status)` -- use `res.redirect(status, url)` instead + * fix `res.send(status, num)` to send `num` as json (not error) + * remove unnecessary escaping when `res.jsonp` returns JSON response + * support non-string `path` in `app.use(path, fn)` + - supports array of paths + - supports `RegExp` + * router: fix optimization on router exit + * router: refactor location of `try` blocks + * router: speed up standard `app.use(fn)` + * deps: debug@1.0.3 + - Add support for multiple wildcards in namespaces + * deps: finalhandler@0.0.3 + - deps: debug@1.0.3 + * deps: methods@1.1.0 + - add `CONNECT` + * deps: parseurl@~1.1.3 + - faster parsing of href-only URLs + * deps: path-to-regexp@0.1.3 + * deps: send@0.6.0 + - deps: debug@1.0.3 + * deps: serve-static@~1.3.2 + - deps: parseurl@~1.1.3 + - deps: send@0.6.0 + * perf: fix arguments reassign deopt in some `res` methods + +4.5.1 / 2014-07-06 +================== + + * fix routing regression when altering `req.method` + +4.5.0 / 2014-07-04 +================== + + * add deprecation message to non-plural `req.accepts*` + * add deprecation message to `res.send(body, status)` + * add deprecation message to `res.vary()` + * add `headers` option to `res.sendfile` + - use to set headers on successful file transfer + * add `mergeParams` option to `Router` + - merges `req.params` from parent routes + * add `req.hostname` -- correct name for what `req.host` returns + * deprecate things with `depd` module + * deprecate `req.host` -- use `req.hostname` instead + * fix behavior when handling request without routes + * fix handling when `route.all` is only route + * invoke `router.param()` only when route matches + * restore `req.params` after invoking router + * use `finalhandler` for final response handling + * use `media-typer` to alter content-type charset + * deps: accepts@~1.0.7 + * deps: send@0.5.0 + - Accept string for `maxage` (converted by `ms`) + - Include link in default redirect response + * deps: serve-static@~1.3.0 + - Accept string for `maxAge` (converted by `ms`) + - Add `setHeaders` option + - Include HTML link in redirect response + - deps: send@0.5.0 + * deps: type-is@~1.3.2 + +4.4.5 / 2014-06-26 +================== + + * deps: cookie-signature@1.0.4 + - fix for timing attacks + +4.4.4 / 2014-06-20 +================== + + * fix `res.attachment` Unicode filenames in Safari + * fix "trim prefix" debug message in `express:router` + * deps: accepts@~1.0.5 + * deps: buffer-crc32@0.2.3 + +4.4.3 / 2014-06-11 +================== + + * fix persistence of modified `req.params[name]` from `app.param()` + * deps: accepts@1.0.3 + - deps: negotiator@0.4.6 + * deps: debug@1.0.2 + * deps: send@0.4.3 + - Do not throw uncatchable error on file open race condition + - Use `escape-html` for HTML escaping + - deps: debug@1.0.2 + - deps: finished@1.2.2 + - deps: fresh@0.2.2 + * deps: serve-static@1.2.3 + - Do not throw uncatchable error on file open race condition + - deps: send@0.4.3 + +4.4.2 / 2014-06-09 +================== + + * fix catching errors from top-level handlers + * use `vary` module for `res.vary` + * deps: debug@1.0.1 + * deps: proxy-addr@1.0.1 + * deps: send@0.4.2 + - fix "event emitter leak" warnings + - deps: debug@1.0.1 + - deps: finished@1.2.1 + * deps: serve-static@1.2.2 + - fix "event emitter leak" warnings + - deps: send@0.4.2 + * deps: type-is@1.2.1 + +4.4.1 / 2014-06-02 +================== + + * deps: methods@1.0.1 + * deps: send@0.4.1 + - Send `max-age` in `Cache-Control` in correct format + * deps: serve-static@1.2.1 + - use `escape-html` for escaping + - deps: send@0.4.1 + +4.4.0 / 2014-05-30 +================== + + * custom etag control with `app.set('etag', val)` + - `app.set('etag', function(body, encoding){ return '"etag"' })` custom etag generation + - `app.set('etag', 'weak')` weak tag + - `app.set('etag', 'strong')` strong etag + - `app.set('etag', false)` turn off + - `app.set('etag', true)` standard etag + * mark `res.send` ETag as weak and reduce collisions + * update accepts to 1.0.2 + - Fix interpretation when header not in request + * update send to 0.4.0 + - Calculate ETag with md5 for reduced collisions + - Ignore stream errors after request ends + - deps: debug@0.8.1 + * update serve-static to 1.2.0 + - Calculate ETag with md5 for reduced collisions + - Ignore stream errors after request ends + - deps: send@0.4.0 + +4.3.2 / 2014-05-28 +================== + + * fix handling of errors from `router.param()` callbacks + +4.3.1 / 2014-05-23 +================== + + * revert "fix behavior of multiple `app.VERB` for the same path" + - this caused a regression in the order of route execution + +4.3.0 / 2014-05-21 +================== + + * add `req.baseUrl` to access the path stripped from `req.url` in routes + * fix behavior of multiple `app.VERB` for the same path + * fix issue routing requests among sub routers + * invoke `router.param()` only when necessary instead of every match + * proper proxy trust with `app.set('trust proxy', trust)` + - `app.set('trust proxy', 1)` trust first hop + - `app.set('trust proxy', 'loopback')` trust loopback addresses + - `app.set('trust proxy', '10.0.0.1')` trust single IP + - `app.set('trust proxy', '10.0.0.1/16')` trust subnet + - `app.set('trust proxy', '10.0.0.1, 10.0.0.2')` trust list + - `app.set('trust proxy', false)` turn off + - `app.set('trust proxy', true)` trust everything + * set proper `charset` in `Content-Type` for `res.send` + * update type-is to 1.2.0 + - support suffix matching + +4.2.0 / 2014-05-11 +================== + + * deprecate `app.del()` -- use `app.delete()` instead + * deprecate `res.json(obj, status)` -- use `res.json(status, obj)` instead + - the edge-case `res.json(status, num)` requires `res.status(status).json(num)` + * deprecate `res.jsonp(obj, status)` -- use `res.jsonp(status, obj)` instead + - the edge-case `res.jsonp(status, num)` requires `res.status(status).jsonp(num)` + * fix `req.next` when inside router instance + * include `ETag` header in `HEAD` requests + * keep previous `Content-Type` for `res.jsonp` + * support PURGE method + - add `app.purge` + - add `router.purge` + - include PURGE in `app.all` + * update debug to 0.8.0 + - add `enable()` method + - change from stderr to stdout + * update methods to 1.0.0 + - add PURGE + +4.1.2 / 2014-05-08 +================== + + * fix `req.host` for IPv6 literals + * fix `res.jsonp` error if callback param is object + +4.1.1 / 2014-04-27 +================== + + * fix package.json to reflect supported node version + +4.1.0 / 2014-04-24 +================== + + * pass options from `res.sendfile` to `send` + * preserve casing of headers in `res.header` and `res.set` + * support unicode file names in `res.attachment` and `res.download` + * update accepts to 1.0.1 + - deps: negotiator@0.4.0 + * update cookie to 0.1.2 + - Fix for maxAge == 0 + - made compat with expires field + * update send to 0.3.0 + - Accept API options in options object + - Coerce option types + - Control whether to generate etags + - Default directory access to 403 when index disabled + - Fix sending files with dots without root set + - Include file path in etag + - Make "Can't set headers after they are sent." catchable + - Send full entity-body for multi range requests + - Set etags to "weak" + - Support "If-Range" header + - Support multiple index paths + - deps: mime@1.2.11 + * update serve-static to 1.1.0 + - Accept options directly to `send` module + - Resolve relative paths at middleware setup + - Use parseurl to parse the URL from request + - deps: send@0.3.0 + * update type-is to 1.1.0 + - add non-array values support + - add `multipart` as a shorthand + +4.0.0 / 2014-04-09 +================== + + * remove: + - node 0.8 support + - connect and connect's patches except for charset handling + - express(1) - moved to [express-generator](https://github.com/expressjs/generator) + - `express.createServer()` - it has been deprecated for a long time. Use `express()` + - `app.configure` - use logic in your own app code + - `app.router` - is removed + - `req.auth` - use `basic-auth` instead + - `req.accepted*` - use `req.accepts*()` instead + - `res.location` - relative URL resolution is removed + - `res.charset` - include the charset in the content type when using `res.set()` + - all bundled middleware except `static` + * change: + - `app.route` -> `app.mountpath` when mounting an express app in another express app + - `json spaces` no longer enabled by default in development + - `req.accepts*` -> `req.accepts*s` - i.e. `req.acceptsEncoding` -> `req.acceptsEncodings` + - `req.params` is now an object instead of an array + - `res.locals` is no longer a function. It is a plain js object. Treat it as such. + - `res.headerSent` -> `res.headersSent` to match node.js ServerResponse object + * refactor: + - `req.accepts*` with [accepts](https://github.com/expressjs/accepts) + - `req.is` with [type-is](https://github.com/expressjs/type-is) + - [path-to-regexp](https://github.com/component/path-to-regexp) + * add: + - `app.router()` - returns the app Router instance + - `app.route()` - Proxy to the app's `Router#route()` method to create a new route + - Router & Route - public API + +3.21.2 / 2015-07-31 +=================== + + * deps: connect@2.30.2 + - deps: body-parser@~1.13.3 + - deps: compression@~1.5.2 + - deps: errorhandler@~1.4.2 + - deps: method-override@~2.3.5 + - deps: serve-index@~1.7.2 + - deps: type-is@~1.6.6 + - deps: vhost@~3.0.1 + * deps: vary@~1.0.1 + - Fix setting empty header from empty `field` + - perf: enable strict mode + - perf: remove argument reassignments + +3.21.1 / 2015-07-05 +=================== + + * deps: basic-auth@~1.0.3 + * deps: connect@2.30.1 + - deps: body-parser@~1.13.2 + - deps: compression@~1.5.1 + - deps: errorhandler@~1.4.1 + - deps: morgan@~1.6.1 + - deps: pause@0.1.0 + - deps: qs@4.0.0 + - deps: serve-index@~1.7.1 + - deps: type-is@~1.6.4 + +3.21.0 / 2015-06-18 +=================== + + * deps: basic-auth@1.0.2 + - perf: enable strict mode + - perf: hoist regular expression + - perf: parse with regular expressions + - perf: remove argument reassignment + * deps: connect@2.30.0 + - deps: body-parser@~1.13.1 + - deps: bytes@2.1.0 + - deps: compression@~1.5.0 + - deps: cookie@0.1.3 + - deps: cookie-parser@~1.3.5 + - deps: csurf@~1.8.3 + - deps: errorhandler@~1.4.0 + - deps: express-session@~1.11.3 + - deps: finalhandler@0.4.0 + - deps: fresh@0.3.0 + - deps: morgan@~1.6.0 + - deps: serve-favicon@~2.3.0 + - deps: serve-index@~1.7.0 + - deps: serve-static@~1.10.0 + - deps: type-is@~1.6.3 + * deps: cookie@0.1.3 + - perf: deduce the scope of try-catch deopt + - perf: remove argument reassignments + * deps: escape-html@1.0.2 + * deps: etag@~1.7.0 + - Always include entity length in ETags for hash length extensions + - Generate non-Stats ETags using MD5 only (no longer CRC32) + - Improve stat performance by removing hashing + - Improve support for JXcore + - Remove base64 padding in ETags to shorten + - Support "fake" stats objects in environments without fs + - Use MD5 instead of MD4 in weak ETags over 1KB + * deps: fresh@0.3.0 + - Add weak `ETag` matching support + * deps: mkdirp@0.5.1 + - Work in global strict mode + * deps: send@0.13.0 + - Allow Node.js HTTP server to set `Date` response header + - Fix incorrectly removing `Content-Location` on 304 response + - Improve the default redirect response headers + - Send appropriate headers on default error response + - Use `http-errors` for standard emitted errors + - Use `statuses` instead of `http` module for status messages + - deps: escape-html@1.0.2 + - deps: etag@~1.7.0 + - deps: fresh@0.3.0 + - deps: on-finished@~2.3.0 + - perf: enable strict mode + - perf: remove unnecessary array allocations + +3.20.3 / 2015-05-17 +=================== + + * deps: connect@2.29.2 + - deps: body-parser@~1.12.4 + - deps: compression@~1.4.4 + - deps: connect-timeout@~1.6.2 + - deps: debug@~2.2.0 + - deps: depd@~1.0.1 + - deps: errorhandler@~1.3.6 + - deps: finalhandler@0.3.6 + - deps: method-override@~2.3.3 + - deps: morgan@~1.5.3 + - deps: qs@2.4.2 + - deps: response-time@~2.3.1 + - deps: serve-favicon@~2.2.1 + - deps: serve-index@~1.6.4 + - deps: serve-static@~1.9.3 + - deps: type-is@~1.6.2 + * deps: debug@~2.2.0 + - deps: ms@0.7.1 + * deps: depd@~1.0.1 + * deps: proxy-addr@~1.0.8 + - deps: ipaddr.js@1.0.1 + * deps: send@0.12.3 + - deps: debug@~2.2.0 + - deps: depd@~1.0.1 + - deps: etag@~1.6.0 + - deps: ms@0.7.1 + - deps: on-finished@~2.2.1 + +3.20.2 / 2015-03-16 +=================== + + * deps: connect@2.29.1 + - deps: body-parser@~1.12.2 + - deps: compression@~1.4.3 + - deps: connect-timeout@~1.6.1 + - deps: debug@~2.1.3 + - deps: errorhandler@~1.3.5 + - deps: express-session@~1.10.4 + - deps: finalhandler@0.3.4 + - deps: method-override@~2.3.2 + - deps: morgan@~1.5.2 + - deps: qs@2.4.1 + - deps: serve-index@~1.6.3 + - deps: serve-static@~1.9.2 + - deps: type-is@~1.6.1 + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + * deps: merge-descriptors@1.0.0 + * deps: proxy-addr@~1.0.7 + - deps: ipaddr.js@0.1.9 + * deps: send@0.12.2 + - Throw errors early for invalid `extensions` or `index` options + - deps: debug@~2.1.3 + +3.20.1 / 2015-02-28 +=================== + + * Fix `req.host` when using "trust proxy" hops count + * Fix `req.protocol`/`req.secure` when using "trust proxy" hops count + +3.20.0 / 2015-02-18 +=================== + + * Fix `"trust proxy"` setting to inherit when app is mounted + * Generate `ETag`s for all request responses + - No longer restricted to only responses for `GET` and `HEAD` requests + * Use `content-type` to parse `Content-Type` headers + * deps: connect@2.29.0 + - Use `content-type` to parse `Content-Type` headers + - deps: body-parser@~1.12.0 + - deps: compression@~1.4.1 + - deps: connect-timeout@~1.6.0 + - deps: cookie-parser@~1.3.4 + - deps: cookie-signature@1.0.6 + - deps: csurf@~1.7.0 + - deps: errorhandler@~1.3.4 + - deps: express-session@~1.10.3 + - deps: http-errors@~1.3.1 + - deps: response-time@~2.3.0 + - deps: serve-index@~1.6.2 + - deps: serve-static@~1.9.1 + - deps: type-is@~1.6.0 + * deps: cookie-signature@1.0.6 + * deps: send@0.12.1 + - Always read the stat size from the file + - Fix mutating passed-in `options` + - deps: mime@1.3.4 + +3.19.2 / 2015-02-01 +=================== + + * deps: connect@2.28.3 + - deps: compression@~1.3.1 + - deps: csurf@~1.6.6 + - deps: errorhandler@~1.3.3 + - deps: express-session@~1.10.2 + - deps: serve-index@~1.6.1 + - deps: type-is@~1.5.6 + * deps: proxy-addr@~1.0.6 + - deps: ipaddr.js@0.1.8 + +3.19.1 / 2015-01-20 +=================== + + * deps: connect@2.28.2 + - deps: body-parser@~1.10.2 + - deps: serve-static@~1.8.1 + * deps: send@0.11.1 + - Fix root path disclosure + +3.19.0 / 2015-01-09 +=================== + + * Fix `OPTIONS` responses to include the `HEAD` method property + * Use `readline` for prompt in `express(1)` + * deps: commander@2.6.0 + * deps: connect@2.28.1 + - deps: body-parser@~1.10.1 + - deps: compression@~1.3.0 + - deps: connect-timeout@~1.5.0 + - deps: csurf@~1.6.4 + - deps: debug@~2.1.1 + - deps: errorhandler@~1.3.2 + - deps: express-session@~1.10.1 + - deps: finalhandler@0.3.3 + - deps: method-override@~2.3.1 + - deps: morgan@~1.5.1 + - deps: serve-favicon@~2.2.0 + - deps: serve-index@~1.6.0 + - deps: serve-static@~1.8.0 + - deps: type-is@~1.5.5 + * deps: debug@~2.1.1 + * deps: methods@~1.1.1 + * deps: proxy-addr@~1.0.5 + - deps: ipaddr.js@0.1.6 + * deps: send@0.11.0 + - deps: debug@~2.1.1 + - deps: etag@~1.5.1 + - deps: ms@0.7.0 + - deps: on-finished@~2.2.0 + +3.18.6 / 2014-12-12 +=================== + + * Fix exception in `req.fresh`/`req.stale` without response headers + +3.18.5 / 2014-12-11 +=================== + + * deps: connect@2.27.6 + - deps: compression@~1.2.2 + - deps: express-session@~1.9.3 + - deps: http-errors@~1.2.8 + - deps: serve-index@~1.5.3 + - deps: type-is@~1.5.4 + +3.18.4 / 2014-11-23 +=================== + + * deps: connect@2.27.4 + - deps: body-parser@~1.9.3 + - deps: compression@~1.2.1 + - deps: errorhandler@~1.2.3 + - deps: express-session@~1.9.2 + - deps: qs@2.3.3 + - deps: serve-favicon@~2.1.7 + - deps: serve-static@~1.5.1 + - deps: type-is@~1.5.3 + * deps: etag@~1.5.1 + * deps: proxy-addr@~1.0.4 + - deps: ipaddr.js@0.1.5 + +3.18.3 / 2014-11-09 +=================== + + * deps: connect@2.27.3 + - Correctly invoke async callback asynchronously + - deps: csurf@~1.6.3 + +3.18.2 / 2014-10-28 +=================== + + * deps: connect@2.27.2 + - Fix handling of URLs containing `://` in the path + - deps: body-parser@~1.9.2 + - deps: qs@2.3.2 + +3.18.1 / 2014-10-22 +=================== + + * Fix internal `utils.merge` deprecation warnings + * deps: connect@2.27.1 + - deps: body-parser@~1.9.1 + - deps: express-session@~1.9.1 + - deps: finalhandler@0.3.2 + - deps: morgan@~1.4.1 + - deps: qs@2.3.0 + - deps: serve-static@~1.7.1 + * deps: send@0.10.1 + - deps: on-finished@~2.1.1 + +3.18.0 / 2014-10-17 +=================== + + * Use `content-disposition` module for `res.attachment`/`res.download` + - Sends standards-compliant `Content-Disposition` header + - Full Unicode support + * Use `etag` module to generate `ETag` headers + * deps: connect@2.27.0 + - Use `http-errors` module for creating errors + - Use `utils-merge` module for merging objects + - deps: body-parser@~1.9.0 + - deps: compression@~1.2.0 + - deps: connect-timeout@~1.4.0 + - deps: debug@~2.1.0 + - deps: depd@~1.0.0 + - deps: express-session@~1.9.0 + - deps: finalhandler@0.3.1 + - deps: method-override@~2.3.0 + - deps: morgan@~1.4.0 + - deps: response-time@~2.2.0 + - deps: serve-favicon@~2.1.6 + - deps: serve-index@~1.5.0 + - deps: serve-static@~1.7.0 + * deps: debug@~2.1.0 + - Implement `DEBUG_FD` env variable support + * deps: depd@~1.0.0 + * deps: send@0.10.0 + - deps: debug@~2.1.0 + - deps: depd@~1.0.0 + - deps: etag@~1.5.0 + +3.17.8 / 2014-10-15 +=================== + + * deps: connect@2.26.6 + - deps: compression@~1.1.2 + - deps: csurf@~1.6.2 + - deps: errorhandler@~1.2.2 + +3.17.7 / 2014-10-08 +=================== + + * deps: connect@2.26.5 + - Fix accepting non-object arguments to `logger` + - deps: serve-static@~1.6.4 + +3.17.6 / 2014-10-02 +=================== + + * deps: connect@2.26.4 + - deps: morgan@~1.3.2 + - deps: type-is@~1.5.2 + +3.17.5 / 2014-09-24 +=================== + + * deps: connect@2.26.3 + - deps: body-parser@~1.8.4 + - deps: serve-favicon@~2.1.5 + - deps: serve-static@~1.6.3 + * deps: proxy-addr@~1.0.3 + - Use `forwarded` npm module + * deps: send@0.9.3 + - deps: etag@~1.4.0 + +3.17.4 / 2014-09-19 +=================== + + * deps: connect@2.26.2 + - deps: body-parser@~1.8.3 + - deps: qs@2.2.4 + +3.17.3 / 2014-09-18 +=================== + + * deps: proxy-addr@~1.0.2 + - Fix a global leak when multiple subnets are trusted + - deps: ipaddr.js@0.1.3 + +3.17.2 / 2014-09-15 +=================== + + * Use `crc` instead of `buffer-crc32` for speed + * deps: connect@2.26.1 + - deps: body-parser@~1.8.2 + - deps: depd@0.4.5 + - deps: express-session@~1.8.2 + - deps: morgan@~1.3.1 + - deps: serve-favicon@~2.1.3 + - deps: serve-static@~1.6.2 + * deps: depd@0.4.5 + * deps: send@0.9.2 + - deps: depd@0.4.5 + - deps: etag@~1.3.1 + - deps: range-parser@~1.0.2 + +3.17.1 / 2014-09-08 +=================== + + * Fix error in `req.subdomains` on empty host + +3.17.0 / 2014-09-08 +=================== + + * Support `X-Forwarded-Host` in `req.subdomains` + * Support IP address host in `req.subdomains` + * deps: connect@2.26.0 + - deps: body-parser@~1.8.1 + - deps: compression@~1.1.0 + - deps: connect-timeout@~1.3.0 + - deps: cookie-parser@~1.3.3 + - deps: cookie-signature@1.0.5 + - deps: csurf@~1.6.1 + - deps: debug@~2.0.0 + - deps: errorhandler@~1.2.0 + - deps: express-session@~1.8.1 + - deps: finalhandler@0.2.0 + - deps: fresh@0.2.4 + - deps: media-typer@0.3.0 + - deps: method-override@~2.2.0 + - deps: morgan@~1.3.0 + - deps: qs@2.2.3 + - deps: serve-favicon@~2.1.3 + - deps: serve-index@~1.2.1 + - deps: serve-static@~1.6.1 + - deps: type-is@~1.5.1 + - deps: vhost@~3.0.0 + * deps: cookie-signature@1.0.5 + * deps: debug@~2.0.0 + * deps: fresh@0.2.4 + * deps: media-typer@0.3.0 + - Throw error when parameter format invalid on parse + * deps: range-parser@~1.0.2 + * deps: send@0.9.1 + - Add `lastModified` option + - Use `etag` to generate `ETag` header + - deps: debug@~2.0.0 + - deps: fresh@0.2.4 + * deps: vary@~1.0.0 + - Accept valid `Vary` header string as `field` + +3.16.10 / 2014-09-04 +==================== + + * deps: connect@2.25.10 + - deps: serve-static@~1.5.4 + * deps: send@0.8.5 + - Fix a path traversal issue when using `root` + - Fix malicious path detection for empty string path + +3.16.9 / 2014-08-29 +=================== + + * deps: connect@2.25.9 + - deps: body-parser@~1.6.7 + - deps: qs@2.2.2 + +3.16.8 / 2014-08-27 +=================== + + * deps: connect@2.25.8 + - deps: body-parser@~1.6.6 + - deps: csurf@~1.4.1 + - deps: qs@2.2.0 + +3.16.7 / 2014-08-18 +=================== + + * deps: connect@2.25.7 + - deps: body-parser@~1.6.5 + - deps: express-session@~1.7.6 + - deps: morgan@~1.2.3 + - deps: serve-static@~1.5.3 + * deps: send@0.8.3 + - deps: destroy@1.0.3 + - deps: on-finished@2.1.0 + +3.16.6 / 2014-08-14 +=================== + + * deps: connect@2.25.6 + - deps: body-parser@~1.6.4 + - deps: qs@1.2.2 + - deps: serve-static@~1.5.2 + * deps: send@0.8.2 + - Work around `fd` leak in Node.js 0.10 for `fs.ReadStream` + +3.16.5 / 2014-08-11 +=================== + + * deps: connect@2.25.5 + - Fix backwards compatibility in `logger` + +3.16.4 / 2014-08-10 +=================== + + * Fix original URL parsing in `res.location` + * deps: connect@2.25.4 + - Fix `query` middleware breaking with argument + - deps: body-parser@~1.6.3 + - deps: compression@~1.0.11 + - deps: connect-timeout@~1.2.2 + - deps: express-session@~1.7.5 + - deps: method-override@~2.1.3 + - deps: on-headers@~1.0.0 + - deps: parseurl@~1.3.0 + - deps: qs@1.2.1 + - deps: response-time@~2.0.1 + - deps: serve-index@~1.1.6 + - deps: serve-static@~1.5.1 + * deps: parseurl@~1.3.0 + +3.16.3 / 2014-08-07 +=================== + + * deps: connect@2.25.3 + - deps: multiparty@3.3.2 + +3.16.2 / 2014-08-07 +=================== + + * deps: connect@2.25.2 + - deps: body-parser@~1.6.2 + - deps: qs@1.2.0 + +3.16.1 / 2014-08-06 +=================== + + * deps: connect@2.25.1 + - deps: body-parser@~1.6.1 + - deps: qs@1.1.0 + +3.16.0 / 2014-08-05 +=================== + + * deps: connect@2.25.0 + - deps: body-parser@~1.6.0 + - deps: compression@~1.0.10 + - deps: csurf@~1.4.0 + - deps: express-session@~1.7.4 + - deps: qs@1.0.2 + - deps: serve-static@~1.5.0 + * deps: send@0.8.1 + - Add `extensions` option + +3.15.3 / 2014-08-04 +=================== + + * fix `res.sendfile` regression for serving directory index files + * deps: connect@2.24.3 + - deps: serve-index@~1.1.5 + - deps: serve-static@~1.4.4 + * deps: send@0.7.4 + - Fix incorrect 403 on Windows and Node.js 0.11 + - Fix serving index files without root dir + +3.15.2 / 2014-07-27 +=================== + + * deps: connect@2.24.2 + - deps: body-parser@~1.5.2 + - deps: depd@0.4.4 + - deps: express-session@~1.7.2 + - deps: morgan@~1.2.2 + - deps: serve-static@~1.4.2 + * deps: depd@0.4.4 + - Work-around v8 generating empty stack traces + * deps: send@0.7.2 + - deps: depd@0.4.4 + +3.15.1 / 2014-07-26 +=================== + + * deps: connect@2.24.1 + - deps: body-parser@~1.5.1 + - deps: depd@0.4.3 + - deps: express-session@~1.7.1 + - deps: morgan@~1.2.1 + - deps: serve-index@~1.1.4 + - deps: serve-static@~1.4.1 + * deps: depd@0.4.3 + - Fix exception when global `Error.stackTraceLimit` is too low + * deps: send@0.7.1 + - deps: depd@0.4.3 + +3.15.0 / 2014-07-22 +=================== + + * Fix `req.protocol` for proxy-direct connections + * Pass options from `res.sendfile` to `send` + * deps: connect@2.24.0 + - deps: body-parser@~1.5.0 + - deps: compression@~1.0.9 + - deps: connect-timeout@~1.2.1 + - deps: debug@1.0.4 + - deps: depd@0.4.2 + - deps: express-session@~1.7.0 + - deps: finalhandler@0.1.0 + - deps: method-override@~2.1.2 + - deps: morgan@~1.2.0 + - deps: multiparty@3.3.1 + - deps: parseurl@~1.2.0 + - deps: serve-static@~1.4.0 + * deps: debug@1.0.4 + * deps: depd@0.4.2 + - Add `TRACE_DEPRECATION` environment variable + - Remove non-standard grey color from color output + - Support `--no-deprecation` argument + - Support `--trace-deprecation` argument + * deps: parseurl@~1.2.0 + - Cache URLs based on original value + - Remove no-longer-needed URL mis-parse work-around + - Simplify the "fast-path" `RegExp` + * deps: send@0.7.0 + - Add `dotfiles` option + - Cap `maxAge` value to 1 year + - deps: debug@1.0.4 + - deps: depd@0.4.2 + +3.14.0 / 2014-07-11 +=================== + + * add explicit "Rosetta Flash JSONP abuse" protection + - previous versions are not vulnerable; this is just explicit protection + * deprecate `res.redirect(url, status)` -- use `res.redirect(status, url)` instead + * fix `res.send(status, num)` to send `num` as json (not error) + * remove unnecessary escaping when `res.jsonp` returns JSON response + * deps: basic-auth@1.0.0 + - support empty password + - support empty username + * deps: connect@2.23.0 + - deps: debug@1.0.3 + - deps: express-session@~1.6.4 + - deps: method-override@~2.1.0 + - deps: parseurl@~1.1.3 + - deps: serve-static@~1.3.1 + * deps: debug@1.0.3 + - Add support for multiple wildcards in namespaces + * deps: methods@1.1.0 + - add `CONNECT` + * deps: parseurl@~1.1.3 + - faster parsing of href-only URLs + +3.13.0 / 2014-07-03 +=================== + + * add deprecation message to `app.configure` + * add deprecation message to `req.auth` + * use `basic-auth` to parse `Authorization` header + * deps: connect@2.22.0 + - deps: csurf@~1.3.0 + - deps: express-session@~1.6.1 + - deps: multiparty@3.3.0 + - deps: serve-static@~1.3.0 + * deps: send@0.5.0 + - Accept string for `maxage` (converted by `ms`) + - Include link in default redirect response + +3.12.1 / 2014-06-26 +=================== + + * deps: connect@2.21.1 + - deps: cookie-parser@1.3.2 + - deps: cookie-signature@1.0.4 + - deps: express-session@~1.5.2 + - deps: type-is@~1.3.2 + * deps: cookie-signature@1.0.4 + - fix for timing attacks + +3.12.0 / 2014-06-21 +=================== + + * use `media-typer` to alter content-type charset + * deps: connect@2.21.0 + - deprecate `connect(middleware)` -- use `app.use(middleware)` instead + - deprecate `connect.createServer()` -- use `connect()` instead + - fix `res.setHeader()` patch to work with with get -> append -> set pattern + - deps: compression@~1.0.8 + - deps: errorhandler@~1.1.1 + - deps: express-session@~1.5.0 + - deps: serve-index@~1.1.3 + +3.11.0 / 2014-06-19 +=================== + + * deprecate things with `depd` module + * deps: buffer-crc32@0.2.3 + * deps: connect@2.20.2 + - deprecate `verify` option to `json` -- use `body-parser` npm module instead + - deprecate `verify` option to `urlencoded` -- use `body-parser` npm module instead + - deprecate things with `depd` module + - use `finalhandler` for final response handling + - use `media-typer` to parse `content-type` for charset + - deps: body-parser@1.4.3 + - deps: connect-timeout@1.1.1 + - deps: cookie-parser@1.3.1 + - deps: csurf@1.2.2 + - deps: errorhandler@1.1.0 + - deps: express-session@1.4.0 + - deps: multiparty@3.2.9 + - deps: serve-index@1.1.2 + - deps: type-is@1.3.1 + - deps: vhost@2.0.0 + +3.10.5 / 2014-06-11 +=================== + + * deps: connect@2.19.6 + - deps: body-parser@1.3.1 + - deps: compression@1.0.7 + - deps: debug@1.0.2 + - deps: serve-index@1.1.1 + - deps: serve-static@1.2.3 + * deps: debug@1.0.2 + * deps: send@0.4.3 + - Do not throw uncatchable error on file open race condition + - Use `escape-html` for HTML escaping + - deps: debug@1.0.2 + - deps: finished@1.2.2 + - deps: fresh@0.2.2 + +3.10.4 / 2014-06-09 +=================== + + * deps: connect@2.19.5 + - fix "event emitter leak" warnings + - deps: csurf@1.2.1 + - deps: debug@1.0.1 + - deps: serve-static@1.2.2 + - deps: type-is@1.2.1 + * deps: debug@1.0.1 + * deps: send@0.4.2 + - fix "event emitter leak" warnings + - deps: finished@1.2.1 + - deps: debug@1.0.1 + +3.10.3 / 2014-06-05 +=================== + + * use `vary` module for `res.vary` + * deps: connect@2.19.4 + - deps: errorhandler@1.0.2 + - deps: method-override@2.0.2 + - deps: serve-favicon@2.0.1 + * deps: debug@1.0.0 + +3.10.2 / 2014-06-03 +=================== + + * deps: connect@2.19.3 + - deps: compression@1.0.6 + +3.10.1 / 2014-06-03 +=================== + + * deps: connect@2.19.2 + - deps: compression@1.0.4 + * deps: proxy-addr@1.0.1 + +3.10.0 / 2014-06-02 +=================== + + * deps: connect@2.19.1 + - deprecate `methodOverride()` -- use `method-override` npm module instead + - deps: body-parser@1.3.0 + - deps: method-override@2.0.1 + - deps: multiparty@3.2.8 + - deps: response-time@2.0.0 + - deps: serve-static@1.2.1 + * deps: methods@1.0.1 + * deps: send@0.4.1 + - Send `max-age` in `Cache-Control` in correct format + +3.9.0 / 2014-05-30 +================== + + * custom etag control with `app.set('etag', val)` + - `app.set('etag', function(body, encoding){ return '"etag"' })` custom etag generation + - `app.set('etag', 'weak')` weak tag + - `app.set('etag', 'strong')` strong etag + - `app.set('etag', false)` turn off + - `app.set('etag', true)` standard etag + * Include ETag in HEAD requests + * mark `res.send` ETag as weak and reduce collisions + * update connect to 2.18.0 + - deps: compression@1.0.3 + - deps: serve-index@1.1.0 + - deps: serve-static@1.2.0 + * update send to 0.4.0 + - Calculate ETag with md5 for reduced collisions + - Ignore stream errors after request ends + - deps: debug@0.8.1 + +3.8.1 / 2014-05-27 +================== + + * update connect to 2.17.3 + - deps: body-parser@1.2.2 + - deps: express-session@1.2.1 + - deps: method-override@1.0.2 + +3.8.0 / 2014-05-21 +================== + + * keep previous `Content-Type` for `res.jsonp` + * set proper `charset` in `Content-Type` for `res.send` + * update connect to 2.17.1 + - fix `res.charset` appending charset when `content-type` has one + - deps: express-session@1.2.0 + - deps: morgan@1.1.1 + - deps: serve-index@1.0.3 + +3.7.0 / 2014-05-18 +================== + + * proper proxy trust with `app.set('trust proxy', trust)` + - `app.set('trust proxy', 1)` trust first hop + - `app.set('trust proxy', 'loopback')` trust loopback addresses + - `app.set('trust proxy', '10.0.0.1')` trust single IP + - `app.set('trust proxy', '10.0.0.1/16')` trust subnet + - `app.set('trust proxy', '10.0.0.1, 10.0.0.2')` trust list + - `app.set('trust proxy', false)` turn off + - `app.set('trust proxy', true)` trust everything + * update connect to 2.16.2 + - deprecate `res.headerSent` -- use `res.headersSent` + - deprecate `res.on("header")` -- use on-headers module instead + - fix edge-case in `res.appendHeader` that would append in wrong order + - json: use body-parser + - urlencoded: use body-parser + - dep: bytes@1.0.0 + - dep: cookie-parser@1.1.0 + - dep: csurf@1.2.0 + - dep: express-session@1.1.0 + - dep: method-override@1.0.1 + +3.6.0 / 2014-05-09 +================== + + * deprecate `app.del()` -- use `app.delete()` instead + * deprecate `res.json(obj, status)` -- use `res.json(status, obj)` instead + - the edge-case `res.json(status, num)` requires `res.status(status).json(num)` + * deprecate `res.jsonp(obj, status)` -- use `res.jsonp(status, obj)` instead + - the edge-case `res.jsonp(status, num)` requires `res.status(status).jsonp(num)` + * support PURGE method + - add `app.purge` + - add `router.purge` + - include PURGE in `app.all` + * update connect to 2.15.0 + * Add `res.appendHeader` + * Call error stack even when response has been sent + * Patch `res.headerSent` to return Boolean + * Patch `res.headersSent` for node.js 0.8 + * Prevent default 404 handler after response sent + * dep: compression@1.0.2 + * dep: connect-timeout@1.1.0 + * dep: debug@^0.8.0 + * dep: errorhandler@1.0.1 + * dep: express-session@1.0.4 + * dep: morgan@1.0.1 + * dep: serve-favicon@2.0.0 + * dep: serve-index@1.0.2 + * update debug to 0.8.0 + * add `enable()` method + * change from stderr to stdout + * update methods to 1.0.0 + - add PURGE + * update mkdirp to 0.5.0 + +3.5.3 / 2014-05-08 +================== + + * fix `req.host` for IPv6 literals + * fix `res.jsonp` error if callback param is object + +3.5.2 / 2014-04-24 +================== + + * update connect to 2.14.5 + * update cookie to 0.1.2 + * update mkdirp to 0.4.0 + * update send to 0.3.0 + +3.5.1 / 2014-03-25 +================== + + * pin less-middleware in generated app + +3.5.0 / 2014-03-06 +================== + + * bump deps + +3.4.8 / 2014-01-13 +================== + + * prevent incorrect automatic OPTIONS responses #1868 @dpatti + * update binary and examples for jade 1.0 #1876 @yossi, #1877 @reqshark, #1892 @matheusazzi + * throw 400 in case of malformed paths @rlidwka + +3.4.7 / 2013-12-10 +================== + + * update connect + +3.4.6 / 2013-12-01 +================== + + * update connect (raw-body) + +3.4.5 / 2013-11-27 +================== + + * update connect + * res.location: remove leading ./ #1802 @kapouer + * res.redirect: fix `res.redirect('toString') #1829 @michaelficarra + * res.send: always send ETag when content-length > 0 + * router: add Router.all() method + +3.4.4 / 2013-10-29 +================== + + * update connect + * update supertest + * update methods + * express(1): replace bodyParser() with urlencoded() and json() #1795 @chirag04 + +3.4.3 / 2013-10-23 +================== + + * update connect + +3.4.2 / 2013-10-18 +================== + + * update connect + * downgrade commander + +3.4.1 / 2013-10-15 +================== + + * update connect + * update commander + * jsonp: check if callback is a function + * router: wrap encodeURIComponent in a try/catch #1735 (@lxe) + * res.format: now includes charset @1747 (@sorribas) + * res.links: allow multiple calls @1746 (@sorribas) + +3.4.0 / 2013-09-07 +================== + + * add res.vary(). Closes #1682 + * update connect + +3.3.8 / 2013-09-02 +================== + + * update connect + +3.3.7 / 2013-08-28 +================== + + * update connect + +3.3.6 / 2013-08-27 +================== + + * Revert "remove charset from json responses. Closes #1631" (causes issues in some clients) + * add: req.accepts take an argument list + +3.3.4 / 2013-07-08 +================== + + * update send and connect + +3.3.3 / 2013-07-04 +================== + + * update connect + +3.3.2 / 2013-07-03 +================== + + * update connect + * update send + * remove .version export + +3.3.1 / 2013-06-27 +================== + + * update connect + +3.3.0 / 2013-06-26 +================== + + * update connect + * add support for multiple X-Forwarded-Proto values. Closes #1646 + * change: remove charset from json responses. Closes #1631 + * change: return actual booleans from req.accept* functions + * fix jsonp callback array throw + +3.2.6 / 2013-06-02 +================== + + * update connect + +3.2.5 / 2013-05-21 +================== + + * update connect + * update node-cookie + * add: throw a meaningful error when there is no default engine + * change generation of ETags with res.send() to GET requests only. Closes #1619 + +3.2.4 / 2013-05-09 +================== + + * fix `req.subdomains` when no Host is present + * fix `req.host` when no Host is present, return undefined + +3.2.3 / 2013-05-07 +================== + + * update connect / qs + +3.2.2 / 2013-05-03 +================== + + * update qs + +3.2.1 / 2013-04-29 +================== + + * add app.VERB() paths array deprecation warning + * update connect + * update qs and remove all ~ semver crap + * fix: accept number as value of Signed Cookie + +3.2.0 / 2013-04-15 +================== + + * add "view" constructor setting to override view behaviour + * add req.acceptsEncoding(name) + * add req.acceptedEncodings + * revert cookie signature change causing session race conditions + * fix sorting of Accept values of the same quality + +3.1.2 / 2013-04-12 +================== + + * add support for custom Accept parameters + * update cookie-signature + +3.1.1 / 2013-04-01 +================== + + * add X-Forwarded-Host support to `req.host` + * fix relative redirects + * update mkdirp + * update buffer-crc32 + * remove legacy app.configure() method from app template. + +3.1.0 / 2013-01-25 +================== + + * add support for leading "." in "view engine" setting + * add array support to `res.set()` + * add node 0.8.x to travis.yml + * add "subdomain offset" setting for tweaking `req.subdomains` + * add `res.location(url)` implementing `res.redirect()`-like setting of Location + * use app.get() for x-powered-by setting for inheritance + * fix colons in passwords for `req.auth` + +3.0.6 / 2013-01-04 +================== + + * add http verb methods to Router + * update connect + * fix mangling of the `res.cookie()` options object + * fix jsonp whitespace escape. Closes #1132 + +3.0.5 / 2012-12-19 +================== + + * add throwing when a non-function is passed to a route + * fix: explicitly remove Transfer-Encoding header from 204 and 304 responses + * revert "add 'etag' option" + +3.0.4 / 2012-12-05 +================== + + * add 'etag' option to disable `res.send()` Etags + * add escaping of urls in text/plain in `res.redirect()` + for old browsers interpreting as html + * change crc32 module for a more liberal license + * update connect + +3.0.3 / 2012-11-13 +================== + + * update connect + * update cookie module + * fix cookie max-age + +3.0.2 / 2012-11-08 +================== + + * add OPTIONS to cors example. Closes #1398 + * fix route chaining regression. Closes #1397 + +3.0.1 / 2012-11-01 +================== + + * update connect + +3.0.0 / 2012-10-23 +================== + + * add `make clean` + * add "Basic" check to req.auth + * add `req.auth` test coverage + * add cb && cb(payload) to `res.jsonp()`. Closes #1374 + * add backwards compat for `res.redirect()` status. Closes #1336 + * add support for `res.json()` to retain previously defined Content-Types. Closes #1349 + * update connect + * change `res.redirect()` to utilize a pathname-relative Location again. Closes #1382 + * remove non-primitive string support for `res.send()` + * fix view-locals example. Closes #1370 + * fix route-separation example + +3.0.0rc5 / 2012-09-18 +================== + + * update connect + * add redis search example + * add static-files example + * add "x-powered-by" setting (`app.disable('x-powered-by')`) + * add "application/octet-stream" redirect Accept test case. Closes #1317 + +3.0.0rc4 / 2012-08-30 +================== + + * add `res.jsonp()`. Closes #1307 + * add "verbose errors" option to error-pages example + * add another route example to express(1) so people are not so confused + * add redis online user activity tracking example + * update connect dep + * fix etag quoting. Closes #1310 + * fix error-pages 404 status + * fix jsonp callback char restrictions + * remove old OPTIONS default response + +3.0.0rc3 / 2012-08-13 +================== + + * update connect dep + * fix signed cookies to work with `connect.cookieParser()` ("s:" prefix was missing) [tnydwrds] + * fix `res.render()` clobbering of "locals" + +3.0.0rc2 / 2012-08-03 +================== + + * add CORS example + * update connect dep + * deprecate `.createServer()` & remove old stale examples + * fix: escape `res.redirect()` link + * fix vhost example + +3.0.0rc1 / 2012-07-24 +================== + + * add more examples to view-locals + * add scheme-relative redirects (`res.redirect("//foo.com")`) support + * update cookie dep + * update connect dep + * update send dep + * fix `express(1)` -h flag, use -H for hogan. Closes #1245 + * fix `res.sendfile()` socket error handling regression + +3.0.0beta7 / 2012-07-16 +================== + + * update connect dep for `send()` root normalization regression + +3.0.0beta6 / 2012-07-13 +================== + + * add `err.view` property for view errors. Closes #1226 + * add "jsonp callback name" setting + * add support for "/foo/:bar*" non-greedy matches + * change `res.sendfile()` to use `send()` module + * change `res.send` to use "response-send" module + * remove `app.locals.use` and `res.locals.use`, use regular middleware + +3.0.0beta5 / 2012-07-03 +================== + + * add "make check" support + * add route-map example + * add `res.json(obj, status)` support back for BC + * add "methods" dep, remove internal methods module + * update connect dep + * update auth example to utilize cores pbkdf2 + * updated tests to use "supertest" + +3.0.0beta4 / 2012-06-25 +================== + + * Added `req.auth` + * Added `req.range(size)` + * Added `res.links(obj)` + * Added `res.send(body, status)` support back for backwards compat + * Added `.default()` support to `res.format()` + * Added 2xx / 304 check to `req.fresh` + * Revert "Added + support to the router" + * Fixed `res.send()` freshness check, respect res.statusCode + +3.0.0beta3 / 2012-06-15 +================== + + * Added hogan `--hjs` to express(1) [nullfirm] + * Added another example to content-negotiation + * Added `fresh` dep + * Changed: `res.send()` always checks freshness + * Fixed: expose connects mime module. Closes #1165 + +3.0.0beta2 / 2012-06-06 +================== + + * Added `+` support to the router + * Added `req.host` + * Changed `req.param()` to check route first + * Update connect dep + +3.0.0beta1 / 2012-06-01 +================== + + * Added `res.format()` callback to override default 406 behaviour + * Fixed `res.redirect()` 406. Closes #1154 + +3.0.0alpha5 / 2012-05-30 +================== + + * Added `req.ip` + * Added `{ signed: true }` option to `res.cookie()` + * Removed `res.signedCookie()` + * Changed: dont reverse `req.ips` + * Fixed "trust proxy" setting check for `req.ips` + +3.0.0alpha4 / 2012-05-09 +================== + + * Added: allow `[]` in jsonp callback. Closes #1128 + * Added `PORT` env var support in generated template. Closes #1118 [benatkin] + * Updated: connect 2.2.2 + +3.0.0alpha3 / 2012-05-04 +================== + + * Added public `app.routes`. Closes #887 + * Added _view-locals_ example + * Added _mvc_ example + * Added `res.locals.use()`. Closes #1120 + * Added conditional-GET support to `res.send()` + * Added: coerce `res.set()` values to strings + * Changed: moved `static()` in generated apps below router + * Changed: `res.send()` only set ETag when not previously set + * Changed connect 2.2.1 dep + * Changed: `make test` now runs unit / acceptance tests + * Fixed req/res proto inheritance + +3.0.0alpha2 / 2012-04-26 +================== + + * Added `make benchmark` back + * Added `res.send()` support for `String` objects + * Added client-side data exposing example + * Added `res.header()` and `req.header()` aliases for BC + * Added `express.createServer()` for BC + * Perf: memoize parsed urls + * Perf: connect 2.2.0 dep + * Changed: make `expressInit()` middleware self-aware + * Fixed: use app.get() for all core settings + * Fixed redis session example + * Fixed session example. Closes #1105 + * Fixed generated express dep. Closes #1078 + +3.0.0alpha1 / 2012-04-15 +================== + + * Added `app.locals.use(callback)` + * Added `app.locals` object + * Added `app.locals(obj)` + * Added `res.locals` object + * Added `res.locals(obj)` + * Added `res.format()` for content-negotiation + * Added `app.engine()` + * Added `res.cookie()` JSON cookie support + * Added "trust proxy" setting + * Added `req.subdomains` + * Added `req.protocol` + * Added `req.secure` + * Added `req.path` + * Added `req.ips` + * Added `req.fresh` + * Added `req.stale` + * Added comma-delimited / array support for `req.accepts()` + * Added debug instrumentation + * Added `res.set(obj)` + * Added `res.set(field, value)` + * Added `res.get(field)` + * Added `app.get(setting)`. Closes #842 + * Added `req.acceptsLanguage()` + * Added `req.acceptsCharset()` + * Added `req.accepted` + * Added `req.acceptedLanguages` + * Added `req.acceptedCharsets` + * Added "json replacer" setting + * Added "json spaces" setting + * Added X-Forwarded-Proto support to `res.redirect()`. Closes #92 + * Added `--less` support to express(1) + * Added `express.response` prototype + * Added `express.request` prototype + * Added `express.application` prototype + * Added `app.path()` + * Added `app.render()` + * Added `res.type()` to replace `res.contentType()` + * Changed: `res.redirect()` to add relative support + * Changed: enable "jsonp callback" by default + * Changed: renamed "case sensitive routes" to "case sensitive routing" + * Rewrite of all tests with mocha + * Removed "root" setting + * Removed `res.redirect('home')` support + * Removed `req.notify()` + * Removed `app.register()` + * Removed `app.redirect()` + * Removed `app.is()` + * Removed `app.helpers()` + * Removed `app.dynamicHelpers()` + * Fixed `res.sendfile()` with non-GET. Closes #723 + * Fixed express(1) public dir for windows. Closes #866 + +2.5.9/ 2012-04-02 +================== + + * Added support for PURGE request method [pbuyle] + * Fixed `express(1)` generated app `app.address()` before `listening` [mmalecki] + +2.5.8 / 2012-02-08 +================== + + * Update mkdirp dep. Closes #991 + +2.5.7 / 2012-02-06 +================== + + * Fixed `app.all` duplicate DELETE requests [mscdex] + +2.5.6 / 2012-01-13 +================== + + * Updated hamljs dev dep. Closes #953 + +2.5.5 / 2012-01-08 +================== + + * Fixed: set `filename` on cached templates [matthewleon] + +2.5.4 / 2012-01-02 +================== + + * Fixed `express(1)` eol on 0.4.x. Closes #947 + +2.5.3 / 2011-12-30 +================== + + * Fixed `req.is()` when a charset is present + +2.5.2 / 2011-12-10 +================== + + * Fixed: express(1) LF -> CRLF for windows + +2.5.1 / 2011-11-17 +================== + + * Changed: updated connect to 1.8.x + * Removed sass.js support from express(1) + +2.5.0 / 2011-10-24 +================== + + * Added ./routes dir for generated app by default + * Added npm install reminder to express(1) app gen + * Added 0.5.x support + * Removed `make test-cov` since it wont work with node 0.5.x + * Fixed express(1) public dir for windows. Closes #866 + +2.4.7 / 2011-10-05 +================== + + * Added mkdirp to express(1). Closes #795 + * Added simple _json-config_ example + * Added shorthand for the parsed request's pathname via `req.path` + * Changed connect dep to 1.7.x to fix npm issue... + * Fixed `res.redirect()` __HEAD__ support. [reported by xerox] + * Fixed `req.flash()`, only escape args + * Fixed absolute path checking on windows. Closes #829 [reported by andrewpmckenzie] + +2.4.6 / 2011-08-22 +================== + + * Fixed multiple param callback regression. Closes #824 [reported by TroyGoode] + +2.4.5 / 2011-08-19 +================== + + * Added support for routes to handle errors. Closes #809 + * Added `app.routes.all()`. Closes #803 + * Added "basepath" setting to work in conjunction with reverse proxies etc. + * Refactored `Route` to use a single array of callbacks + * Added support for multiple callbacks for `app.param()`. Closes #801 +Closes #805 + * Changed: removed .call(self) for route callbacks + * Dependency: `qs >= 0.3.1` + * Fixed `res.redirect()` on windows due to `join()` usage. Closes #808 + +2.4.4 / 2011-08-05 +================== + + * Fixed `res.header()` intention of a set, even when `undefined` + * Fixed `*`, value no longer required + * Fixed `res.send(204)` support. Closes #771 + +2.4.3 / 2011-07-14 +================== + + * Added docs for `status` option special-case. Closes #739 + * Fixed `options.filename`, exposing the view path to template engines + +2.4.2. / 2011-07-06 +================== + + * Revert "removed jsonp stripping" for XSS + +2.4.1 / 2011-07-06 +================== + + * Added `res.json()` JSONP support. Closes #737 + * Added _extending-templates_ example. Closes #730 + * Added "strict routing" setting for trailing slashes + * Added support for multiple envs in `app.configure()` calls. Closes #735 + * Changed: `res.send()` using `res.json()` + * Changed: when cookie `path === null` don't default it + * Changed; default cookie path to "home" setting. Closes #731 + * Removed _pids/logs_ creation from express(1) + +2.4.0 / 2011-06-28 +================== + + * Added chainable `res.status(code)` + * Added `res.json()`, an explicit version of `res.send(obj)` + * Added simple web-service example + +2.3.12 / 2011-06-22 +================== + + * \#express is now on freenode! come join! + * Added `req.get(field, param)` + * Added links to Japanese documentation, thanks @hideyukisaito! + * Added; the `express(1)` generated app outputs the env + * Added `content-negotiation` example + * Dependency: connect >= 1.5.1 < 2.0.0 + * Fixed view layout bug. Closes #720 + * Fixed; ignore body on 304. Closes #701 + +2.3.11 / 2011-06-04 +================== + + * Added `npm test` + * Removed generation of dummy test file from `express(1)` + * Fixed; `express(1)` adds express as a dep + * Fixed; prune on `prepublish` + +2.3.10 / 2011-05-27 +================== + + * Added `req.route`, exposing the current route + * Added _package.json_ generation support to `express(1)` + * Fixed call to `app.param()` function for optional params. Closes #682 + +2.3.9 / 2011-05-25 +================== + + * Fixed bug-ish with `../' in `res.partial()` calls + +2.3.8 / 2011-05-24 +================== + + * Fixed `app.options()` + +2.3.7 / 2011-05-23 +================== + + * Added route `Collection`, ex: `app.get('/user/:id').remove();` + * Added support for `app.param(fn)` to define param logic + * Removed `app.param()` support for callback with return value + * Removed module.parent check from express(1) generated app. Closes #670 + * Refactored router. Closes #639 + +2.3.6 / 2011-05-20 +================== + + * Changed; using devDependencies instead of git submodules + * Fixed redis session example + * Fixed markdown example + * Fixed view caching, should not be enabled in development + +2.3.5 / 2011-05-20 +================== + + * Added export `.view` as alias for `.View` + +2.3.4 / 2011-05-08 +================== + + * Added `./examples/say` + * Fixed `res.sendfile()` bug preventing the transfer of files with spaces + +2.3.3 / 2011-05-03 +================== + + * Added "case sensitive routes" option. + * Changed; split methods supported per rfc [slaskis] + * Fixed route-specific middleware when using the same callback function several times + +2.3.2 / 2011-04-27 +================== + + * Fixed view hints + +2.3.1 / 2011-04-26 +================== + + * Added `app.match()` as `app.match.all()` + * Added `app.lookup()` as `app.lookup.all()` + * Added `app.remove()` for `app.remove.all()` + * Added `app.remove.VERB()` + * Fixed template caching collision issue. Closes #644 + * Moved router over from connect and started refactor + +2.3.0 / 2011-04-25 +================== + + * Added options support to `res.clearCookie()` + * Added `res.helpers()` as alias of `res.locals()` + * Added; json defaults to UTF-8 with `res.send()`. Closes #632. [Daniel * Dependency `connect >= 1.4.0` + * Changed; auto set Content-Type in res.attachement [Aaron Heckmann] + * Renamed "cache views" to "view cache". Closes #628 + * Fixed caching of views when using several apps. Closes #637 + * Fixed gotcha invoking `app.param()` callbacks once per route middleware. +Closes #638 + * Fixed partial lookup precedence. Closes #631 +Shaw] + +2.2.2 / 2011-04-12 +================== + + * Added second callback support for `res.download()` connection errors + * Fixed `filename` option passing to template engine + +2.2.1 / 2011-04-04 +================== + + * Added `layout(path)` helper to change the layout within a view. Closes #610 + * Fixed `partial()` collection object support. + Previously only anything with `.length` would work. + When `.length` is present one must still be aware of holes, + however now `{ collection: {foo: 'bar'}}` is valid, exposes + `keyInCollection` and `keysInCollection`. + + * Performance improved with better view caching + * Removed `request` and `response` locals + * Changed; errorHandler page title is now `Express` instead of `Connect` + +2.2.0 / 2011-03-30 +================== + + * Added `app.lookup.VERB()`, ex `app.lookup.put('/user/:id')`. Closes #606 + * Added `app.match.VERB()`, ex `app.match.put('/user/12')`. Closes #606 + * Added `app.VERB(path)` as alias of `app.lookup.VERB()`. + * Dependency `connect >= 1.2.0` + +2.1.1 / 2011-03-29 +================== + + * Added; expose `err.view` object when failing to locate a view + * Fixed `res.partial()` call `next(err)` when no callback is given [reported by aheckmann] + * Fixed; `res.send(undefined)` responds with 204 [aheckmann] + +2.1.0 / 2011-03-24 +================== + + * Added `/_?` partial lookup support. Closes #447 + * Added `request`, `response`, and `app` local variables + * Added `settings` local variable, containing the app's settings + * Added `req.flash()` exception if `req.session` is not available + * Added `res.send(bool)` support (json response) + * Fixed stylus example for latest version + * Fixed; wrap try/catch around `res.render()` + +2.0.0 / 2011-03-17 +================== + + * Fixed up index view path alternative. + * Changed; `res.locals()` without object returns the locals + +2.0.0rc3 / 2011-03-17 +================== + + * Added `res.locals(obj)` to compliment `res.local(key, val)` + * Added `res.partial()` callback support + * Fixed recursive error reporting issue in `res.render()` + +2.0.0rc2 / 2011-03-17 +================== + + * Changed; `partial()` "locals" are now optional + * Fixed `SlowBuffer` support. Closes #584 [reported by tyrda01] + * Fixed .filename view engine option [reported by drudge] + * Fixed blog example + * Fixed `{req,res}.app` reference when mounting [Ben Weaver] + +2.0.0rc / 2011-03-14 +================== + + * Fixed; expose `HTTPSServer` constructor + * Fixed express(1) default test charset. Closes #579 [reported by secoif] + * Fixed; default charset to utf-8 instead of utf8 for lame IE [reported by NickP] + +2.0.0beta3 / 2011-03-09 +================== + + * Added support for `res.contentType()` literal + The original `res.contentType('.json')`, + `res.contentType('application/json')`, and `res.contentType('json')` + will work now. + * Added `res.render()` status option support back + * Added charset option for `res.render()` + * Added `.charset` support (via connect 1.0.4) + * Added view resolution hints when in development and a lookup fails + * Added layout lookup support relative to the page view. + For example while rendering `./views/user/index.jade` if you create + `./views/user/layout.jade` it will be used in favour of the root layout. + * Fixed `res.redirect()`. RFC states absolute url [reported by unlink] + * Fixed; default `res.send()` string charset to utf8 + * Removed `Partial` constructor (not currently used) + +2.0.0beta2 / 2011-03-07 +================== + + * Added res.render() `.locals` support back to aid in migration process + * Fixed flash example + +2.0.0beta / 2011-03-03 +================== + + * Added HTTPS support + * Added `res.cookie()` maxAge support + * Added `req.header()` _Referrer_ / _Referer_ special-case, either works + * Added mount support for `res.redirect()`, now respects the mount-point + * Added `union()` util, taking place of `merge(clone())` combo + * Added stylus support to express(1) generated app + * Added secret to session middleware used in examples and generated app + * Added `res.local(name, val)` for progressive view locals + * Added default param support to `req.param(name, default)` + * Added `app.disabled()` and `app.enabled()` + * Added `app.register()` support for omitting leading ".", either works + * Added `res.partial()`, using the same interface as `partial()` within a view. Closes #539 + * Added `app.param()` to map route params to async/sync logic + * Added; aliased `app.helpers()` as `app.locals()`. Closes #481 + * Added extname with no leading "." support to `res.contentType()` + * Added `cache views` setting, defaulting to enabled in "production" env + * Added index file partial resolution, eg: partial('user') may try _views/user/index.jade_. + * Added `req.accepts()` support for extensions + * Changed; `res.download()` and `res.sendfile()` now utilize Connect's + static file server `connect.static.send()`. + * Changed; replaced `connect.utils.mime()` with npm _mime_ module + * Changed; allow `req.query` to be pre-defined (via middleware or other parent + * Changed view partial resolution, now relative to parent view + * Changed view engine signature. no longer `engine.render(str, options, callback)`, now `engine.compile(str, options) -> Function`, the returned function accepts `fn(locals)`. + * Fixed `req.param()` bug returning Array.prototype methods. Closes #552 + * Fixed; using `Stream#pipe()` instead of `sys.pump()` in `res.sendfile()` + * Fixed; using _qs_ module instead of _querystring_ + * Fixed; strip unsafe chars from jsonp callbacks + * Removed "stream threshold" setting + +1.0.8 / 2011-03-01 +================== + + * Allow `req.query` to be pre-defined (via middleware or other parent app) + * "connect": ">= 0.5.0 < 1.0.0". Closes #547 + * Removed the long deprecated __EXPRESS_ENV__ support + +1.0.7 / 2011-02-07 +================== + + * Fixed `render()` setting inheritance. + Mounted apps would not inherit "view engine" + +1.0.6 / 2011-02-07 +================== + + * Fixed `view engine` setting bug when period is in dirname + +1.0.5 / 2011-02-05 +================== + + * Added secret to generated app `session()` call + +1.0.4 / 2011-02-05 +================== + + * Added `qs` dependency to _package.json_ + * Fixed namespaced `require()`s for latest connect support + +1.0.3 / 2011-01-13 +================== + + * Remove unsafe characters from JSONP callback names [Ryan Grove] + +1.0.2 / 2011-01-10 +================== + + * Removed nested require, using `connect.router` + +1.0.1 / 2010-12-29 +================== + + * Fixed for middleware stacked via `createServer()` + previously the `foo` middleware passed to `createServer(foo)` + would not have access to Express methods such as `res.send()` + or props like `req.query` etc. + +1.0.0 / 2010-11-16 +================== + + * Added; deduce partial object names from the last segment. + For example by default `partial('forum/post', postObject)` will + give you the _post_ object, providing a meaningful default. + * Added http status code string representation to `res.redirect()` body + * Added; `res.redirect()` supporting _text/plain_ and _text/html_ via __Accept__. + * Added `req.is()` to aid in content negotiation + * Added partial local inheritance [suggested by masylum]. Closes #102 + providing access to parent template locals. + * Added _-s, --session[s]_ flag to express(1) to add session related middleware + * Added _--template_ flag to express(1) to specify the + template engine to use. + * Added _--css_ flag to express(1) to specify the + stylesheet engine to use (or just plain css by default). + * Added `app.all()` support [thanks aheckmann] + * Added partial direct object support. + You may now `partial('user', user)` providing the "user" local, + vs previously `partial('user', { object: user })`. + * Added _route-separation_ example since many people question ways + to do this with CommonJS modules. Also view the _blog_ example for + an alternative. + * Performance; caching view path derived partial object names + * Fixed partial local inheritance precedence. [reported by Nick Poulden] Closes #454 + * Fixed jsonp support; _text/javascript_ as per mailinglist discussion + +1.0.0rc4 / 2010-10-14 +================== + + * Added _NODE_ENV_ support, _EXPRESS_ENV_ is deprecated and will be removed in 1.0.0 + * Added route-middleware support (very helpful, see the [docs](http://expressjs.com/guide.html#Route-Middleware)) + * Added _jsonp callback_ setting to enable/disable jsonp autowrapping [Dav Glass] + * Added callback query check on response.send to autowrap JSON objects for simple webservice implementations [Dav Glass] + * Added `partial()` support for array-like collections. Closes #434 + * Added support for swappable querystring parsers + * Added session usage docs. Closes #443 + * Added dynamic helper caching. Closes #439 [suggested by maritz] + * Added authentication example + * Added basic Range support to `res.sendfile()` (and `res.download()` etc) + * Changed; `express(1)` generated app using 2 spaces instead of 4 + * Default env to "development" again [aheckmann] + * Removed _context_ option is no more, use "scope" + * Fixed; exposing _./support_ libs to examples so they can run without installs + * Fixed mvc example + +1.0.0rc3 / 2010-09-20 +================== + + * Added confirmation for `express(1)` app generation. Closes #391 + * Added extending of flash formatters via `app.flashFormatters` + * Added flash formatter support. Closes #411 + * Added streaming support to `res.sendfile()` using `sys.pump()` when >= "stream threshold" + * Added _stream threshold_ setting for `res.sendfile()` + * Added `res.send()` __HEAD__ support + * Added `res.clearCookie()` + * Added `res.cookie()` + * Added `res.render()` headers option + * Added `res.redirect()` response bodies + * Added `res.render()` status option support. Closes #425 [thanks aheckmann] + * Fixed `res.sendfile()` responding with 403 on malicious path + * Fixed `res.download()` bug; when an error occurs remove _Content-Disposition_ + * Fixed; mounted apps settings now inherit from parent app [aheckmann] + * Fixed; stripping Content-Length / Content-Type when 204 + * Fixed `res.send()` 204. Closes #419 + * Fixed multiple _Set-Cookie_ headers via `res.header()`. Closes #402 + * Fixed bug messing with error handlers when `listenFD()` is called instead of `listen()`. [thanks guillermo] + + +1.0.0rc2 / 2010-08-17 +================== + + * Added `app.register()` for template engine mapping. Closes #390 + * Added `res.render()` callback support as second argument (no options) + * Added callback support to `res.download()` + * Added callback support for `res.sendfile()` + * Added support for middleware access via `express.middlewareName()` vs `connect.middlewareName()` + * Added "partials" setting to docs + * Added default expresso tests to `express(1)` generated app. Closes #384 + * Fixed `res.sendfile()` error handling, defer via `next()` + * Fixed `res.render()` callback when a layout is used [thanks guillermo] + * Fixed; `make install` creating ~/.node_libraries when not present + * Fixed issue preventing error handlers from being defined anywhere. Closes #387 + +1.0.0rc / 2010-07-28 +================== + + * Added mounted hook. Closes #369 + * Added connect dependency to _package.json_ + + * Removed "reload views" setting and support code + development env never caches, production always caches. + + * Removed _param_ in route callbacks, signature is now + simply (req, res, next), previously (req, res, params, next). + Use _req.params_ for path captures, _req.query_ for GET params. + + * Fixed "home" setting + * Fixed middleware/router precedence issue. Closes #366 + * Fixed; _configure()_ callbacks called immediately. Closes #368 + +1.0.0beta2 / 2010-07-23 +================== + + * Added more examples + * Added; exporting `Server` constructor + * Added `Server#helpers()` for view locals + * Added `Server#dynamicHelpers()` for dynamic view locals. Closes #349 + * Added support for absolute view paths + * Added; _home_ setting defaults to `Server#route` for mounted apps. Closes #363 + * Added Guillermo Rauch to the contributor list + * Added support for "as" for non-collection partials. Closes #341 + * Fixed _install.sh_, ensuring _~/.node_libraries_ exists. Closes #362 [thanks jf] + * Fixed `res.render()` exceptions, now passed to `next()` when no callback is given [thanks guillermo] + * Fixed instanceof `Array` checks, now `Array.isArray()` + * Fixed express(1) expansion of public dirs. Closes #348 + * Fixed middleware precedence. Closes #345 + * Fixed view watcher, now async [thanks aheckmann] + +1.0.0beta / 2010-07-15 +================== + + * Re-write + - much faster + - much lighter + - Check [ExpressJS.com](http://expressjs.com) for migration guide and updated docs + +0.14.0 / 2010-06-15 +================== + + * Utilize relative requires + * Added Static bufferSize option [aheckmann] + * Fixed caching of view and partial subdirectories [aheckmann] + * Fixed mime.type() comments now that ".ext" is not supported + * Updated haml submodule + * Updated class submodule + * Removed bin/express + +0.13.0 / 2010-06-01 +================== + + * Added node v0.1.97 compatibility + * Added support for deleting cookies via Request#cookie('key', null) + * Updated haml submodule + * Fixed not-found page, now using using charset utf-8 + * Fixed show-exceptions page, now using using charset utf-8 + * Fixed view support due to fs.readFile Buffers + * Changed; mime.type() no longer accepts ".type" due to node extname() changes + +0.12.0 / 2010-05-22 +================== + + * Added node v0.1.96 compatibility + * Added view `helpers` export which act as additional local variables + * Updated haml submodule + * Changed ETag; removed inode, modified time only + * Fixed LF to CRLF for setting multiple cookies + * Fixed cookie compilation; values are now urlencoded + * Fixed cookies parsing; accepts quoted values and url escaped cookies + +0.11.0 / 2010-05-06 +================== + + * Added support for layouts using different engines + - this.render('page.html.haml', { layout: 'super-cool-layout.html.ejs' }) + - this.render('page.html.haml', { layout: 'foo' }) // assumes 'foo.html.haml' + - this.render('page.html.haml', { layout: false }) // no layout + * Updated ext submodule + * Updated haml submodule + * Fixed EJS partial support by passing along the context. Issue #307 + +0.10.1 / 2010-05-03 +================== + + * Fixed binary uploads. + +0.10.0 / 2010-04-30 +================== + + * Added charset support via Request#charset (automatically assigned to 'UTF-8' when respond()'s + encoding is set to 'utf8' or 'utf-8'. + * Added "encoding" option to Request#render(). Closes #299 + * Added "dump exceptions" setting, which is enabled by default. + * Added simple ejs template engine support + * Added error response support for text/plain, application/json. Closes #297 + * Added callback function param to Request#error() + * Added Request#sendHead() + * Added Request#stream() + * Added support for Request#respond(304, null) for empty response bodies + * Added ETag support to Request#sendfile() + * Added options to Request#sendfile(), passed to fs.createReadStream() + * Added filename arg to Request#download() + * Performance enhanced due to pre-reversing plugins so that plugins.reverse() is not called on each request + * Performance enhanced by preventing several calls to toLowerCase() in Router#match() + * Changed; Request#sendfile() now streams + * Changed; Renamed Request#halt() to Request#respond(). Closes #289 + * Changed; Using sys.inspect() instead of JSON.encode() for error output + * Changed; run() returns the http.Server instance. Closes #298 + * Changed; Defaulting Server#host to null (INADDR_ANY) + * Changed; Logger "common" format scale of 0.4f + * Removed Logger "request" format + * Fixed; Catching ENOENT in view caching, preventing error when "views/partials" is not found + * Fixed several issues with http client + * Fixed Logger Content-Length output + * Fixed bug preventing Opera from retaining the generated session id. Closes #292 + +0.9.0 / 2010-04-14 +================== + + * Added DSL level error() route support + * Added DSL level notFound() route support + * Added Request#error() + * Added Request#notFound() + * Added Request#render() callback function. Closes #258 + * Added "max upload size" setting + * Added "magic" variables to collection partials (\_\_index\_\_, \_\_length\_\_, \_\_isFirst\_\_, \_\_isLast\_\_). Closes #254 + * Added [haml.js](http://github.com/visionmedia/haml.js) submodule; removed haml-js + * Added callback function support to Request#halt() as 3rd/4th arg + * Added preprocessing of route param wildcards using param(). Closes #251 + * Added view partial support (with collections etc) + * Fixed bug preventing falsey params (such as ?page=0). Closes #286 + * Fixed setting of multiple cookies. Closes #199 + * Changed; view naming convention is now NAME.TYPE.ENGINE (for example page.html.haml) + * Changed; session cookie is now httpOnly + * Changed; Request is no longer global + * Changed; Event is no longer global + * Changed; "sys" module is no longer global + * Changed; moved Request#download to Static plugin where it belongs + * Changed; Request instance created before body parsing. Closes #262 + * Changed; Pre-caching views in memory when "cache view contents" is enabled. Closes #253 + * Changed; Pre-caching view partials in memory when "cache view partials" is enabled + * Updated support to node --version 0.1.90 + * Updated dependencies + * Removed set("session cookie") in favour of use(Session, { cookie: { ... }}) + * Removed utils.mixin(); use Object#mergeDeep() + +0.8.0 / 2010-03-19 +================== + + * Added coffeescript example app. Closes #242 + * Changed; cache api now async friendly. Closes #240 + * Removed deprecated 'express/static' support. Use 'express/plugins/static' + +0.7.6 / 2010-03-19 +================== + + * Added Request#isXHR. Closes #229 + * Added `make install` (for the executable) + * Added `express` executable for setting up simple app templates + * Added "GET /public/*" to Static plugin, defaulting to /public + * Added Static plugin + * Fixed; Request#render() only calls cache.get() once + * Fixed; Namespacing View caches with "view:" + * Fixed; Namespacing Static caches with "static:" + * Fixed; Both example apps now use the Static plugin + * Fixed set("views"). Closes #239 + * Fixed missing space for combined log format + * Deprecated Request#sendfile() and 'express/static' + * Removed Server#running + +0.7.5 / 2010-03-16 +================== + + * Added Request#flash() support without args, now returns all flashes + * Updated ext submodule + +0.7.4 / 2010-03-16 +================== + + * Fixed session reaper + * Changed; class.js replacing js-oo Class implementation (quite a bit faster, no browser cruft) + +0.7.3 / 2010-03-16 +================== + + * Added package.json + * Fixed requiring of haml / sass due to kiwi removal + +0.7.2 / 2010-03-16 +================== + + * Fixed GIT submodules (HAH!) + +0.7.1 / 2010-03-16 +================== + + * Changed; Express now using submodules again until a PM is adopted + * Changed; chat example using millisecond conversions from ext + +0.7.0 / 2010-03-15 +================== + + * Added Request#pass() support (finds the next matching route, or the given path) + * Added Logger plugin (default "common" format replaces CommonLogger) + * Removed Profiler plugin + * Removed CommonLogger plugin + +0.6.0 / 2010-03-11 +================== + + * Added seed.yml for kiwi package management support + * Added HTTP client query string support when method is GET. Closes #205 + + * Added support for arbitrary view engines. + For example "foo.engine.html" will now require('engine'), + the exports from this module are cached after the first require(). + + * Added async plugin support + + * Removed usage of RESTful route funcs as http client + get() etc, use http.get() and friends + + * Removed custom exceptions + +0.5.0 / 2010-03-10 +================== + + * Added ext dependency (library of js extensions) + * Removed extname() / basename() utils. Use path module + * Removed toArray() util. Use arguments.values + * Removed escapeRegexp() util. Use RegExp.escape() + * Removed process.mixin() dependency. Use utils.mixin() + * Removed Collection + * Removed ElementCollection + * Shameless self promotion of ebook "Advanced JavaScript" (http://dev-mag.com) ;) + +0.4.0 / 2010-02-11 +================== + + * Added flash() example to sample upload app + * Added high level restful http client module (express/http) + * Changed; RESTful route functions double as HTTP clients. Closes #69 + * Changed; throwing error when routes are added at runtime + * Changed; defaulting render() context to the current Request. Closes #197 + * Updated haml submodule + +0.3.0 / 2010-02-11 +================== + + * Updated haml / sass submodules. Closes #200 + * Added flash message support. Closes #64 + * Added accepts() now allows multiple args. fixes #117 + * Added support for plugins to halt. Closes #189 + * Added alternate layout support. Closes #119 + * Removed Route#run(). Closes #188 + * Fixed broken specs due to use(Cookie) missing + +0.2.1 / 2010-02-05 +================== + + * Added "plot" format option for Profiler (for gnuplot processing) + * Added request number to Profiler plugin + * Fixed binary encoding for multipart file uploads, was previously defaulting to UTF8 + * Fixed issue with routes not firing when not files are present. Closes #184 + * Fixed process.Promise -> events.Promise + +0.2.0 / 2010-02-03 +================== + + * Added parseParam() support for name[] etc. (allows for file inputs with "multiple" attr) Closes #180 + * Added Both Cache and Session option "reapInterval" may be "reapEvery". Closes #174 + * Added expiration support to cache api with reaper. Closes #133 + * Added cache Store.Memory#reap() + * Added Cache; cache api now uses first class Cache instances + * Added abstract session Store. Closes #172 + * Changed; cache Memory.Store#get() utilizing Collection + * Renamed MemoryStore -> Store.Memory + * Fixed use() of the same plugin several time will always use latest options. Closes #176 + +0.1.0 / 2010-02-03 +================== + + * Changed; Hooks (before / after) pass request as arg as well as evaluated in their context + * Updated node support to 0.1.27 Closes #169 + * Updated dirname(__filename) -> __dirname + * Updated libxmljs support to v0.2.0 + * Added session support with memory store / reaping + * Added quick uid() helper + * Added multi-part upload support + * Added Sass.js support / submodule + * Added production env caching view contents and static files + * Added static file caching. Closes #136 + * Added cache plugin with memory stores + * Added support to StaticFile so that it works with non-textual files. + * Removed dirname() helper + * Removed several globals (now their modules must be required) + +0.0.2 / 2010-01-10 +================== + + * Added view benchmarks; currently haml vs ejs + * Added Request#attachment() specs. Closes #116 + * Added use of node's parseQuery() util. Closes #123 + * Added `make init` for submodules + * Updated Haml + * Updated sample chat app to show messages on load + * Updated libxmljs parseString -> parseHtmlString + * Fixed `make init` to work with older versions of git + * Fixed specs can now run independent specs for those who can't build deps. Closes #127 + * Fixed issues introduced by the node url module changes. Closes 126. + * Fixed two assertions failing due to Collection#keys() returning strings + * Fixed faulty Collection#toArray() spec due to keys() returning strings + * Fixed `make test` now builds libxmljs.node before testing + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/system/login/node_modules/express/LICENSE b/system/login/node_modules/express/LICENSE new file mode 100644 index 0000000..aa927e4 --- /dev/null +++ b/system/login/node_modules/express/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2009-2014 TJ Holowaychuk +Copyright (c) 2013-2014 Roman Shtylman +Copyright (c) 2014-2015 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/system/login/node_modules/express/Readme.md b/system/login/node_modules/express/Readme.md new file mode 100644 index 0000000..0936816 --- /dev/null +++ b/system/login/node_modules/express/Readme.md @@ -0,0 +1,166 @@ +[![Express Logo](https://i.cloudup.com/zfY6lL7eFa-3000x3000.png)](http://expressjs.com/) + + Fast, unopinionated, minimalist web framework for [Node.js](http://nodejs.org). + + [![NPM Version][npm-version-image]][npm-url] + [![NPM Install Size][npm-install-size-image]][npm-install-size-url] + [![NPM Downloads][npm-downloads-image]][npm-downloads-url] + +```js +const express = require('express') +const app = express() + +app.get('/', function (req, res) { + res.send('Hello World') +}) + +app.listen(3000) +``` + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). + +Before installing, [download and install Node.js](https://nodejs.org/en/download/). +Node.js 0.10 or higher is required. + +If this is a brand new project, make sure to create a `package.json` first with +the [`npm init` command](https://docs.npmjs.com/creating-a-package-json-file). + +Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```console +$ npm install express +``` + +Follow [our installing guide](http://expressjs.com/en/starter/installing.html) +for more information. + +## Features + + * Robust routing + * Focus on high performance + * Super-high test coverage + * HTTP helpers (redirection, caching, etc) + * View system supporting 14+ template engines + * Content negotiation + * Executable for generating applications quickly + +## Docs & Community + + * [Website and Documentation](http://expressjs.com/) - [[website repo](https://github.com/expressjs/expressjs.com)] + * [#express](https://web.libera.chat/#express) on [Libera Chat](https://libera.chat) IRC + * [GitHub Organization](https://github.com/expressjs) for Official Middleware & Modules + * Visit the [Wiki](https://github.com/expressjs/express/wiki) + * [Google Group](https://groups.google.com/group/express-js) for discussion + * [Gitter](https://gitter.im/expressjs/express) for support and discussion + +**PROTIP** Be sure to read [Migrating from 3.x to 4.x](https://github.com/expressjs/express/wiki/Migrating-from-3.x-to-4.x) as well as [New features in 4.x](https://github.com/expressjs/express/wiki/New-features-in-4.x). + +## Quick Start + + The quickest way to get started with express is to utilize the executable [`express(1)`](https://github.com/expressjs/generator) to generate an application as shown below: + + Install the executable. The executable's major version will match Express's: + +```console +$ npm install -g express-generator@4 +``` + + Create the app: + +```console +$ express /tmp/foo && cd /tmp/foo +``` + + Install dependencies: + +```console +$ npm install +``` + + Start the server: + +```console +$ npm start +``` + + View the website at: http://localhost:3000 + +## Philosophy + + The Express philosophy is to provide small, robust tooling for HTTP servers, making + it a great solution for single page applications, websites, hybrids, or public + HTTP APIs. + + Express does not force you to use any specific ORM or template engine. With support for over + 14 template engines via [Consolidate.js](https://github.com/tj/consolidate.js), + you can quickly craft your perfect framework. + +## Examples + + To view the examples, clone the Express repo and install the dependencies: + +```console +$ git clone git://github.com/expressjs/express.git --depth 1 +$ cd express +$ npm install +``` + + Then run whichever example you want: + +```console +$ node examples/content-negotiation +``` + +## Contributing + + [![Linux Build][github-actions-ci-image]][github-actions-ci-url] + [![Windows Build][appveyor-image]][appveyor-url] + [![Test Coverage][coveralls-image]][coveralls-url] + +The Express.js project welcomes all constructive contributions. Contributions take many forms, +from code for bug fixes and enhancements, to additions and fixes to documentation, additional +tests, triaging incoming pull requests and issues, and more! + +See the [Contributing Guide](Contributing.md) for more technical details on contributing. + +### Security Issues + +If you discover a security vulnerability in Express, please see [Security Policies and Procedures](Security.md). + +### Running Tests + +To run the test suite, first install the dependencies, then run `npm test`: + +```console +$ npm install +$ npm test +``` + +## People + +The original author of Express is [TJ Holowaychuk](https://github.com/tj) + +The current lead maintainer is [Douglas Christopher Wilson](https://github.com/dougwilson) + +[List of all contributors](https://github.com/expressjs/express/graphs/contributors) + +## License + + [MIT](LICENSE) + +[appveyor-image]: https://badgen.net/appveyor/ci/dougwilson/express/master?label=windows +[appveyor-url]: https://ci.appveyor.com/project/dougwilson/express +[coveralls-image]: https://badgen.net/coveralls/c/github/expressjs/express/master +[coveralls-url]: https://coveralls.io/r/expressjs/express?branch=master +[github-actions-ci-image]: https://badgen.net/github/checks/expressjs/express/master?label=linux +[github-actions-ci-url]: https://github.com/expressjs/express/actions/workflows/ci.yml +[npm-downloads-image]: https://badgen.net/npm/dm/express +[npm-downloads-url]: https://npmcharts.com/compare/express?minimal=true +[npm-install-size-image]: https://badgen.net/packagephobia/install/express +[npm-install-size-url]: https://packagephobia.com/result?p=express +[npm-url]: https://npmjs.org/package/express +[npm-version-image]: https://badgen.net/npm/v/express diff --git a/system/login/node_modules/express/index.js b/system/login/node_modules/express/index.js new file mode 100644 index 0000000..d219b0c --- /dev/null +++ b/system/login/node_modules/express/index.js @@ -0,0 +1,11 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +module.exports = require('./lib/express'); diff --git a/system/login/node_modules/express/lib/application.js b/system/login/node_modules/express/lib/application.js new file mode 100644 index 0000000..ebb30b5 --- /dev/null +++ b/system/login/node_modules/express/lib/application.js @@ -0,0 +1,661 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var finalhandler = require('finalhandler'); +var Router = require('./router'); +var methods = require('methods'); +var middleware = require('./middleware/init'); +var query = require('./middleware/query'); +var debug = require('debug')('express:application'); +var View = require('./view'); +var http = require('http'); +var compileETag = require('./utils').compileETag; +var compileQueryParser = require('./utils').compileQueryParser; +var compileTrust = require('./utils').compileTrust; +var deprecate = require('depd')('express'); +var flatten = require('array-flatten'); +var merge = require('utils-merge'); +var resolve = require('path').resolve; +var setPrototypeOf = require('setprototypeof') + +/** + * Module variables. + * @private + */ + +var hasOwnProperty = Object.prototype.hasOwnProperty +var slice = Array.prototype.slice; + +/** + * Application prototype. + */ + +var app = exports = module.exports = {}; + +/** + * Variable for trust proxy inheritance back-compat + * @private + */ + +var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default'; + +/** + * Initialize the server. + * + * - setup default configuration + * - setup default middleware + * - setup route reflection methods + * + * @private + */ + +app.init = function init() { + this.cache = {}; + this.engines = {}; + this.settings = {}; + + this.defaultConfiguration(); +}; + +/** + * Initialize application configuration. + * @private + */ + +app.defaultConfiguration = function defaultConfiguration() { + var env = process.env.NODE_ENV || 'development'; + + // default settings + this.enable('x-powered-by'); + this.set('etag', 'weak'); + this.set('env', env); + this.set('query parser', 'extended'); + this.set('subdomain offset', 2); + this.set('trust proxy', false); + + // trust proxy inherit back-compat + Object.defineProperty(this.settings, trustProxyDefaultSymbol, { + configurable: true, + value: true + }); + + debug('booting in %s mode', env); + + this.on('mount', function onmount(parent) { + // inherit trust proxy + if (this.settings[trustProxyDefaultSymbol] === true + && typeof parent.settings['trust proxy fn'] === 'function') { + delete this.settings['trust proxy']; + delete this.settings['trust proxy fn']; + } + + // inherit protos + setPrototypeOf(this.request, parent.request) + setPrototypeOf(this.response, parent.response) + setPrototypeOf(this.engines, parent.engines) + setPrototypeOf(this.settings, parent.settings) + }); + + // setup locals + this.locals = Object.create(null); + + // top-most app is mounted at / + this.mountpath = '/'; + + // default locals + this.locals.settings = this.settings; + + // default configuration + this.set('view', View); + this.set('views', resolve('views')); + this.set('jsonp callback name', 'callback'); + + if (env === 'production') { + this.enable('view cache'); + } + + Object.defineProperty(this, 'router', { + get: function() { + throw new Error('\'app.router\' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.'); + } + }); +}; + +/** + * lazily adds the base router if it has not yet been added. + * + * We cannot add the base router in the defaultConfiguration because + * it reads app settings which might be set after that has run. + * + * @private + */ +app.lazyrouter = function lazyrouter() { + if (!this._router) { + this._router = new Router({ + caseSensitive: this.enabled('case sensitive routing'), + strict: this.enabled('strict routing') + }); + + this._router.use(query(this.get('query parser fn'))); + this._router.use(middleware.init(this)); + } +}; + +/** + * Dispatch a req, res pair into the application. Starts pipeline processing. + * + * If no callback is provided, then default error handlers will respond + * in the event of an error bubbling through the stack. + * + * @private + */ + +app.handle = function handle(req, res, callback) { + var router = this._router; + + // final handler + var done = callback || finalhandler(req, res, { + env: this.get('env'), + onerror: logerror.bind(this) + }); + + // no routes + if (!router) { + debug('no routes defined on app'); + done(); + return; + } + + router.handle(req, res, done); +}; + +/** + * Proxy `Router#use()` to add middleware to the app router. + * See Router#use() documentation for details. + * + * If the _fn_ parameter is an express app, then it will be + * mounted at the _route_ specified. + * + * @public + */ + +app.use = function use(fn) { + var offset = 0; + var path = '/'; + + // default path to '/' + // disambiguate app.use([fn]) + if (typeof fn !== 'function') { + var arg = fn; + + while (Array.isArray(arg) && arg.length !== 0) { + arg = arg[0]; + } + + // first arg is the path + if (typeof arg !== 'function') { + offset = 1; + path = fn; + } + } + + var fns = flatten(slice.call(arguments, offset)); + + if (fns.length === 0) { + throw new TypeError('app.use() requires a middleware function') + } + + // setup router + this.lazyrouter(); + var router = this._router; + + fns.forEach(function (fn) { + // non-express app + if (!fn || !fn.handle || !fn.set) { + return router.use(path, fn); + } + + debug('.use app under %s', path); + fn.mountpath = path; + fn.parent = this; + + // restore .app property on req and res + router.use(path, function mounted_app(req, res, next) { + var orig = req.app; + fn.handle(req, res, function (err) { + setPrototypeOf(req, orig.request) + setPrototypeOf(res, orig.response) + next(err); + }); + }); + + // mounted an app + fn.emit('mount', this); + }, this); + + return this; +}; + +/** + * Proxy to the app `Router#route()` + * Returns a new `Route` instance for the _path_. + * + * Routes are isolated middleware stacks for specific paths. + * See the Route api docs for details. + * + * @public + */ + +app.route = function route(path) { + this.lazyrouter(); + return this._router.route(path); +}; + +/** + * Register the given template engine callback `fn` + * as `ext`. + * + * By default will `require()` the engine based on the + * file extension. For example if you try to render + * a "foo.ejs" file Express will invoke the following internally: + * + * app.engine('ejs', require('ejs').__express); + * + * For engines that do not provide `.__express` out of the box, + * or if you wish to "map" a different extension to the template engine + * you may use this method. For example mapping the EJS template engine to + * ".html" files: + * + * app.engine('html', require('ejs').renderFile); + * + * In this case EJS provides a `.renderFile()` method with + * the same signature that Express expects: `(path, options, callback)`, + * though note that it aliases this method as `ejs.__express` internally + * so if you're using ".ejs" extensions you don't need to do anything. + * + * Some template engines do not follow this convention, the + * [Consolidate.js](https://github.com/tj/consolidate.js) + * library was created to map all of node's popular template + * engines to follow this convention, thus allowing them to + * work seamlessly within Express. + * + * @param {String} ext + * @param {Function} fn + * @return {app} for chaining + * @public + */ + +app.engine = function engine(ext, fn) { + if (typeof fn !== 'function') { + throw new Error('callback function required'); + } + + // get file extension + var extension = ext[0] !== '.' + ? '.' + ext + : ext; + + // store engine + this.engines[extension] = fn; + + return this; +}; + +/** + * Proxy to `Router#param()` with one added api feature. The _name_ parameter + * can be an array of names. + * + * See the Router#param() docs for more details. + * + * @param {String|Array} name + * @param {Function} fn + * @return {app} for chaining + * @public + */ + +app.param = function param(name, fn) { + this.lazyrouter(); + + if (Array.isArray(name)) { + for (var i = 0; i < name.length; i++) { + this.param(name[i], fn); + } + + return this; + } + + this._router.param(name, fn); + + return this; +}; + +/** + * Assign `setting` to `val`, or return `setting`'s value. + * + * app.set('foo', 'bar'); + * app.set('foo'); + * // => "bar" + * + * Mounted servers inherit their parent server's settings. + * + * @param {String} setting + * @param {*} [val] + * @return {Server} for chaining + * @public + */ + +app.set = function set(setting, val) { + if (arguments.length === 1) { + // app.get(setting) + var settings = this.settings + + while (settings && settings !== Object.prototype) { + if (hasOwnProperty.call(settings, setting)) { + return settings[setting] + } + + settings = Object.getPrototypeOf(settings) + } + + return undefined + } + + debug('set "%s" to %o', setting, val); + + // set value + this.settings[setting] = val; + + // trigger matched settings + switch (setting) { + case 'etag': + this.set('etag fn', compileETag(val)); + break; + case 'query parser': + this.set('query parser fn', compileQueryParser(val)); + break; + case 'trust proxy': + this.set('trust proxy fn', compileTrust(val)); + + // trust proxy inherit back-compat + Object.defineProperty(this.settings, trustProxyDefaultSymbol, { + configurable: true, + value: false + }); + + break; + } + + return this; +}; + +/** + * Return the app's absolute pathname + * based on the parent(s) that have + * mounted it. + * + * For example if the application was + * mounted as "/admin", which itself + * was mounted as "/blog" then the + * return value would be "/blog/admin". + * + * @return {String} + * @private + */ + +app.path = function path() { + return this.parent + ? this.parent.path() + this.mountpath + : ''; +}; + +/** + * Check if `setting` is enabled (truthy). + * + * app.enabled('foo') + * // => false + * + * app.enable('foo') + * app.enabled('foo') + * // => true + * + * @param {String} setting + * @return {Boolean} + * @public + */ + +app.enabled = function enabled(setting) { + return Boolean(this.set(setting)); +}; + +/** + * Check if `setting` is disabled. + * + * app.disabled('foo') + * // => true + * + * app.enable('foo') + * app.disabled('foo') + * // => false + * + * @param {String} setting + * @return {Boolean} + * @public + */ + +app.disabled = function disabled(setting) { + return !this.set(setting); +}; + +/** + * Enable `setting`. + * + * @param {String} setting + * @return {app} for chaining + * @public + */ + +app.enable = function enable(setting) { + return this.set(setting, true); +}; + +/** + * Disable `setting`. + * + * @param {String} setting + * @return {app} for chaining + * @public + */ + +app.disable = function disable(setting) { + return this.set(setting, false); +}; + +/** + * Delegate `.VERB(...)` calls to `router.VERB(...)`. + */ + +methods.forEach(function(method){ + app[method] = function(path){ + if (method === 'get' && arguments.length === 1) { + // app.get(setting) + return this.set(path); + } + + this.lazyrouter(); + + var route = this._router.route(path); + route[method].apply(route, slice.call(arguments, 1)); + return this; + }; +}); + +/** + * Special-cased "all" method, applying the given route `path`, + * middleware, and callback to _every_ HTTP method. + * + * @param {String} path + * @param {Function} ... + * @return {app} for chaining + * @public + */ + +app.all = function all(path) { + this.lazyrouter(); + + var route = this._router.route(path); + var args = slice.call(arguments, 1); + + for (var i = 0; i < methods.length; i++) { + route[methods[i]].apply(route, args); + } + + return this; +}; + +// del -> delete alias + +app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead'); + +/** + * Render the given view `name` name with `options` + * and a callback accepting an error and the + * rendered template string. + * + * Example: + * + * app.render('email', { name: 'Tobi' }, function(err, html){ + * // ... + * }) + * + * @param {String} name + * @param {Object|Function} options or fn + * @param {Function} callback + * @public + */ + +app.render = function render(name, options, callback) { + var cache = this.cache; + var done = callback; + var engines = this.engines; + var opts = options; + var renderOptions = {}; + var view; + + // support callback function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } + + // merge app.locals + merge(renderOptions, this.locals); + + // merge options._locals + if (opts._locals) { + merge(renderOptions, opts._locals); + } + + // merge options + merge(renderOptions, opts); + + // set .cache unless explicitly provided + if (renderOptions.cache == null) { + renderOptions.cache = this.enabled('view cache'); + } + + // primed cache + if (renderOptions.cache) { + view = cache[name]; + } + + // view + if (!view) { + var View = this.get('view'); + + view = new View(name, { + defaultEngine: this.get('view engine'), + root: this.get('views'), + engines: engines + }); + + if (!view.path) { + var dirs = Array.isArray(view.root) && view.root.length > 1 + ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"' + : 'directory "' + view.root + '"' + var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs); + err.view = view; + return done(err); + } + + // prime the cache + if (renderOptions.cache) { + cache[name] = view; + } + } + + // render + tryRender(view, renderOptions, done); +}; + +/** + * Listen for connections. + * + * A node `http.Server` is returned, with this + * application (which is a `Function`) as its + * callback. If you wish to create both an HTTP + * and HTTPS server you may do so with the "http" + * and "https" modules as shown here: + * + * var http = require('http') + * , https = require('https') + * , express = require('express') + * , app = express(); + * + * http.createServer(app).listen(80); + * https.createServer({ ... }, app).listen(443); + * + * @return {http.Server} + * @public + */ + +app.listen = function listen() { + var server = http.createServer(this); + return server.listen.apply(server, arguments); +}; + +/** + * Log error using console.error. + * + * @param {Error} err + * @private + */ + +function logerror(err) { + /* istanbul ignore next */ + if (this.get('env') !== 'test') console.error(err.stack || err.toString()); +} + +/** + * Try rendering a view. + * @private + */ + +function tryRender(view, options, callback) { + try { + view.render(options, callback); + } catch (err) { + callback(err); + } +} diff --git a/system/login/node_modules/express/lib/express.js b/system/login/node_modules/express/lib/express.js new file mode 100644 index 0000000..d188a16 --- /dev/null +++ b/system/login/node_modules/express/lib/express.js @@ -0,0 +1,116 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + */ + +var bodyParser = require('body-parser') +var EventEmitter = require('events').EventEmitter; +var mixin = require('merge-descriptors'); +var proto = require('./application'); +var Route = require('./router/route'); +var Router = require('./router'); +var req = require('./request'); +var res = require('./response'); + +/** + * Expose `createApplication()`. + */ + +exports = module.exports = createApplication; + +/** + * Create an express application. + * + * @return {Function} + * @api public + */ + +function createApplication() { + var app = function(req, res, next) { + app.handle(req, res, next); + }; + + mixin(app, EventEmitter.prototype, false); + mixin(app, proto, false); + + // expose the prototype that will get set on requests + app.request = Object.create(req, { + app: { configurable: true, enumerable: true, writable: true, value: app } + }) + + // expose the prototype that will get set on responses + app.response = Object.create(res, { + app: { configurable: true, enumerable: true, writable: true, value: app } + }) + + app.init(); + return app; +} + +/** + * Expose the prototypes. + */ + +exports.application = proto; +exports.request = req; +exports.response = res; + +/** + * Expose constructors. + */ + +exports.Route = Route; +exports.Router = Router; + +/** + * Expose middleware + */ + +exports.json = bodyParser.json +exports.query = require('./middleware/query'); +exports.raw = bodyParser.raw +exports.static = require('serve-static'); +exports.text = bodyParser.text +exports.urlencoded = bodyParser.urlencoded + +/** + * Replace removed middleware with an appropriate error message. + */ + +var removedMiddlewares = [ + 'bodyParser', + 'compress', + 'cookieSession', + 'session', + 'logger', + 'cookieParser', + 'favicon', + 'responseTime', + 'errorHandler', + 'timeout', + 'methodOverride', + 'vhost', + 'csrf', + 'directory', + 'limit', + 'multipart', + 'staticCache' +] + +removedMiddlewares.forEach(function (name) { + Object.defineProperty(exports, name, { + get: function () { + throw new Error('Most middleware (like ' + name + ') is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.'); + }, + configurable: true + }); +}); diff --git a/system/login/node_modules/express/lib/middleware/init.js b/system/login/node_modules/express/lib/middleware/init.js new file mode 100644 index 0000000..dfd0427 --- /dev/null +++ b/system/login/node_modules/express/lib/middleware/init.js @@ -0,0 +1,43 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var setPrototypeOf = require('setprototypeof') + +/** + * Initialization middleware, exposing the + * request and response to each other, as well + * as defaulting the X-Powered-By header field. + * + * @param {Function} app + * @return {Function} + * @api private + */ + +exports.init = function(app){ + return function expressInit(req, res, next){ + if (app.enabled('x-powered-by')) res.setHeader('X-Powered-By', 'Express'); + req.res = res; + res.req = req; + req.next = next; + + setPrototypeOf(req, app.request) + setPrototypeOf(res, app.response) + + res.locals = res.locals || Object.create(null); + + next(); + }; +}; + diff --git a/system/login/node_modules/express/lib/middleware/query.js b/system/login/node_modules/express/lib/middleware/query.js new file mode 100644 index 0000000..7e91669 --- /dev/null +++ b/system/login/node_modules/express/lib/middleware/query.js @@ -0,0 +1,47 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + */ + +var merge = require('utils-merge') +var parseUrl = require('parseurl'); +var qs = require('qs'); + +/** + * @param {Object} options + * @return {Function} + * @api public + */ + +module.exports = function query(options) { + var opts = merge({}, options) + var queryparse = qs.parse; + + if (typeof options === 'function') { + queryparse = options; + opts = undefined; + } + + if (opts !== undefined && opts.allowPrototypes === undefined) { + // back-compat for qs module + opts.allowPrototypes = true; + } + + return function query(req, res, next){ + if (!req.query) { + var val = parseUrl(req).query; + req.query = queryparse(val, opts); + } + + next(); + }; +}; diff --git a/system/login/node_modules/express/lib/request.js b/system/login/node_modules/express/lib/request.js new file mode 100644 index 0000000..3f1eeca --- /dev/null +++ b/system/login/node_modules/express/lib/request.js @@ -0,0 +1,525 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var accepts = require('accepts'); +var deprecate = require('depd')('express'); +var isIP = require('net').isIP; +var typeis = require('type-is'); +var http = require('http'); +var fresh = require('fresh'); +var parseRange = require('range-parser'); +var parse = require('parseurl'); +var proxyaddr = require('proxy-addr'); + +/** + * Request prototype. + * @public + */ + +var req = Object.create(http.IncomingMessage.prototype) + +/** + * Module exports. + * @public + */ + +module.exports = req + +/** + * Return request header. + * + * The `Referrer` header field is special-cased, + * both `Referrer` and `Referer` are interchangeable. + * + * Examples: + * + * req.get('Content-Type'); + * // => "text/plain" + * + * req.get('content-type'); + * // => "text/plain" + * + * req.get('Something'); + * // => undefined + * + * Aliased as `req.header()`. + * + * @param {String} name + * @return {String} + * @public + */ + +req.get = +req.header = function header(name) { + if (!name) { + throw new TypeError('name argument is required to req.get'); + } + + if (typeof name !== 'string') { + throw new TypeError('name must be a string to req.get'); + } + + var lc = name.toLowerCase(); + + switch (lc) { + case 'referer': + case 'referrer': + return this.headers.referrer + || this.headers.referer; + default: + return this.headers[lc]; + } +}; + +/** + * To do: update docs. + * + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single MIME type string + * such as "application/json", an extension name + * such as "json", a comma-delimited list such as "json, html, text/plain", + * an argument list such as `"json", "html", "text/plain"`, + * or an array `["json", "html", "text/plain"]`. When a list + * or array is given, the _best_ match, if any is returned. + * + * Examples: + * + * // Accept: text/html + * req.accepts('html'); + * // => "html" + * + * // Accept: text/*, application/json + * req.accepts('html'); + * // => "html" + * req.accepts('text/html'); + * // => "text/html" + * req.accepts('json, text'); + * // => "json" + * req.accepts('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * req.accepts('image/png'); + * req.accepts('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * req.accepts(['html', 'json']); + * req.accepts('html', 'json'); + * req.accepts('html, json'); + * // => "json" + * + * @param {String|Array} type(s) + * @return {String|Array|Boolean} + * @public + */ + +req.accepts = function(){ + var accept = accepts(this); + return accept.types.apply(accept, arguments); +}; + +/** + * Check if the given `encoding`s are accepted. + * + * @param {String} ...encoding + * @return {String|Array} + * @public + */ + +req.acceptsEncodings = function(){ + var accept = accepts(this); + return accept.encodings.apply(accept, arguments); +}; + +req.acceptsEncoding = deprecate.function(req.acceptsEncodings, + 'req.acceptsEncoding: Use acceptsEncodings instead'); + +/** + * Check if the given `charset`s are acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param {String} ...charset + * @return {String|Array} + * @public + */ + +req.acceptsCharsets = function(){ + var accept = accepts(this); + return accept.charsets.apply(accept, arguments); +}; + +req.acceptsCharset = deprecate.function(req.acceptsCharsets, + 'req.acceptsCharset: Use acceptsCharsets instead'); + +/** + * Check if the given `lang`s are acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param {String} ...lang + * @return {String|Array} + * @public + */ + +req.acceptsLanguages = function(){ + var accept = accepts(this); + return accept.languages.apply(accept, arguments); +}; + +req.acceptsLanguage = deprecate.function(req.acceptsLanguages, + 'req.acceptsLanguage: Use acceptsLanguages instead'); + +/** + * Parse Range header field, capping to the given `size`. + * + * Unspecified ranges such as "0-" require knowledge of your resource length. In + * the case of a byte range this is of course the total number of bytes. If the + * Range header field is not given `undefined` is returned, `-1` when unsatisfiable, + * and `-2` when syntactically invalid. + * + * When ranges are returned, the array has a "type" property which is the type of + * range that is required (most commonly, "bytes"). Each array element is an object + * with a "start" and "end" property for the portion of the range. + * + * The "combine" option can be set to `true` and overlapping & adjacent ranges + * will be combined into a single range. + * + * NOTE: remember that ranges are inclusive, so for example "Range: users=0-3" + * should respond with 4 users when available, not 3. + * + * @param {number} size + * @param {object} [options] + * @param {boolean} [options.combine=false] + * @return {number|array} + * @public + */ + +req.range = function range(size, options) { + var range = this.get('Range'); + if (!range) return; + return parseRange(size, range, options); +}; + +/** + * Return the value of param `name` when present or `defaultValue`. + * + * - Checks route placeholders, ex: _/user/:id_ + * - Checks body params, ex: id=12, {"id":12} + * - Checks query string params, ex: ?id=12 + * + * To utilize request bodies, `req.body` + * should be an object. This can be done by using + * the `bodyParser()` middleware. + * + * @param {String} name + * @param {Mixed} [defaultValue] + * @return {String} + * @public + */ + +req.param = function param(name, defaultValue) { + var params = this.params || {}; + var body = this.body || {}; + var query = this.query || {}; + + var args = arguments.length === 1 + ? 'name' + : 'name, default'; + deprecate('req.param(' + args + '): Use req.params, req.body, or req.query instead'); + + if (null != params[name] && params.hasOwnProperty(name)) return params[name]; + if (null != body[name]) return body[name]; + if (null != query[name]) return query[name]; + + return defaultValue; +}; + +/** + * Check if the incoming request contains the "Content-Type" + * header field, and it contains the given mime `type`. + * + * Examples: + * + * // With Content-Type: text/html; charset=utf-8 + * req.is('html'); + * req.is('text/html'); + * req.is('text/*'); + * // => true + * + * // When Content-Type is application/json + * req.is('json'); + * req.is('application/json'); + * req.is('application/*'); + * // => true + * + * req.is('html'); + * // => false + * + * @param {String|Array} types... + * @return {String|false|null} + * @public + */ + +req.is = function is(types) { + var arr = types; + + // support flattened arguments + if (!Array.isArray(types)) { + arr = new Array(arguments.length); + for (var i = 0; i < arr.length; i++) { + arr[i] = arguments[i]; + } + } + + return typeis(this, arr); +}; + +/** + * Return the protocol string "http" or "https" + * when requested with TLS. When the "trust proxy" + * setting trusts the socket address, the + * "X-Forwarded-Proto" header field will be trusted + * and used if present. + * + * If you're running behind a reverse proxy that + * supplies https for you this may be enabled. + * + * @return {String} + * @public + */ + +defineGetter(req, 'protocol', function protocol(){ + var proto = this.connection.encrypted + ? 'https' + : 'http'; + var trust = this.app.get('trust proxy fn'); + + if (!trust(this.connection.remoteAddress, 0)) { + return proto; + } + + // Note: X-Forwarded-Proto is normally only ever a + // single value, but this is to be safe. + var header = this.get('X-Forwarded-Proto') || proto + var index = header.indexOf(',') + + return index !== -1 + ? header.substring(0, index).trim() + : header.trim() +}); + +/** + * Short-hand for: + * + * req.protocol === 'https' + * + * @return {Boolean} + * @public + */ + +defineGetter(req, 'secure', function secure(){ + return this.protocol === 'https'; +}); + +/** + * Return the remote address from the trusted proxy. + * + * The is the remote address on the socket unless + * "trust proxy" is set. + * + * @return {String} + * @public + */ + +defineGetter(req, 'ip', function ip(){ + var trust = this.app.get('trust proxy fn'); + return proxyaddr(this, trust); +}); + +/** + * When "trust proxy" is set, trusted proxy addresses + client. + * + * For example if the value were "client, proxy1, proxy2" + * you would receive the array `["client", "proxy1", "proxy2"]` + * where "proxy2" is the furthest down-stream and "proxy1" and + * "proxy2" were trusted. + * + * @return {Array} + * @public + */ + +defineGetter(req, 'ips', function ips() { + var trust = this.app.get('trust proxy fn'); + var addrs = proxyaddr.all(this, trust); + + // reverse the order (to farthest -> closest) + // and remove socket address + addrs.reverse().pop() + + return addrs +}); + +/** + * Return subdomains as an array. + * + * Subdomains are the dot-separated parts of the host before the main domain of + * the app. By default, the domain of the app is assumed to be the last two + * parts of the host. This can be changed by setting "subdomain offset". + * + * For example, if the domain is "tobi.ferrets.example.com": + * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. + * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. + * + * @return {Array} + * @public + */ + +defineGetter(req, 'subdomains', function subdomains() { + var hostname = this.hostname; + + if (!hostname) return []; + + var offset = this.app.get('subdomain offset'); + var subdomains = !isIP(hostname) + ? hostname.split('.').reverse() + : [hostname]; + + return subdomains.slice(offset); +}); + +/** + * Short-hand for `url.parse(req.url).pathname`. + * + * @return {String} + * @public + */ + +defineGetter(req, 'path', function path() { + return parse(this).pathname; +}); + +/** + * Parse the "Host" header field to a hostname. + * + * When the "trust proxy" setting trusts the socket + * address, the "X-Forwarded-Host" header field will + * be trusted. + * + * @return {String} + * @public + */ + +defineGetter(req, 'hostname', function hostname(){ + var trust = this.app.get('trust proxy fn'); + var host = this.get('X-Forwarded-Host'); + + if (!host || !trust(this.connection.remoteAddress, 0)) { + host = this.get('Host'); + } else if (host.indexOf(',') !== -1) { + // Note: X-Forwarded-Host is normally only ever a + // single value, but this is to be safe. + host = host.substring(0, host.indexOf(',')).trimRight() + } + + if (!host) return; + + // IPv6 literal support + var offset = host[0] === '[' + ? host.indexOf(']') + 1 + : 0; + var index = host.indexOf(':', offset); + + return index !== -1 + ? host.substring(0, index) + : host; +}); + +// TODO: change req.host to return host in next major + +defineGetter(req, 'host', deprecate.function(function host(){ + return this.hostname; +}, 'req.host: Use req.hostname instead')); + +/** + * Check if the request is fresh, aka + * Last-Modified and/or the ETag + * still match. + * + * @return {Boolean} + * @public + */ + +defineGetter(req, 'fresh', function(){ + var method = this.method; + var res = this.res + var status = res.statusCode + + // GET or HEAD for weak freshness validation only + if ('GET' !== method && 'HEAD' !== method) return false; + + // 2xx or 304 as per rfc2616 14.26 + if ((status >= 200 && status < 300) || 304 === status) { + return fresh(this.headers, { + 'etag': res.get('ETag'), + 'last-modified': res.get('Last-Modified') + }) + } + + return false; +}); + +/** + * Check if the request is stale, aka + * "Last-Modified" and / or the "ETag" for the + * resource has changed. + * + * @return {Boolean} + * @public + */ + +defineGetter(req, 'stale', function stale(){ + return !this.fresh; +}); + +/** + * Check if the request was an _XMLHttpRequest_. + * + * @return {Boolean} + * @public + */ + +defineGetter(req, 'xhr', function xhr(){ + var val = this.get('X-Requested-With') || ''; + return val.toLowerCase() === 'xmlhttprequest'; +}); + +/** + * Helper function for creating a getter on an object. + * + * @param {Object} obj + * @param {String} name + * @param {Function} getter + * @private + */ +function defineGetter(obj, name, getter) { + Object.defineProperty(obj, name, { + configurable: true, + enumerable: true, + get: getter + }); +} diff --git a/system/login/node_modules/express/lib/response.js b/system/login/node_modules/express/lib/response.js new file mode 100644 index 0000000..fede486 --- /dev/null +++ b/system/login/node_modules/express/lib/response.js @@ -0,0 +1,1169 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var Buffer = require('safe-buffer').Buffer +var contentDisposition = require('content-disposition'); +var createError = require('http-errors') +var deprecate = require('depd')('express'); +var encodeUrl = require('encodeurl'); +var escapeHtml = require('escape-html'); +var http = require('http'); +var isAbsolute = require('./utils').isAbsolute; +var onFinished = require('on-finished'); +var path = require('path'); +var statuses = require('statuses') +var merge = require('utils-merge'); +var sign = require('cookie-signature').sign; +var normalizeType = require('./utils').normalizeType; +var normalizeTypes = require('./utils').normalizeTypes; +var setCharset = require('./utils').setCharset; +var cookie = require('cookie'); +var send = require('send'); +var extname = path.extname; +var mime = send.mime; +var resolve = path.resolve; +var vary = require('vary'); + +/** + * Response prototype. + * @public + */ + +var res = Object.create(http.ServerResponse.prototype) + +/** + * Module exports. + * @public + */ + +module.exports = res + +/** + * Module variables. + * @private + */ + +var charsetRegExp = /;\s*charset\s*=/; + +/** + * Set status `code`. + * + * @param {Number} code + * @return {ServerResponse} + * @public + */ + +res.status = function status(code) { + if ((typeof code === 'string' || Math.floor(code) !== code) && code > 99 && code < 1000) { + deprecate('res.status(' + JSON.stringify(code) + '): use res.status(' + Math.floor(code) + ') instead') + } + this.statusCode = code; + return this; +}; + +/** + * Set Link header field with the given `links`. + * + * Examples: + * + * res.links({ + * next: 'http://api.example.com/users?page=2', + * last: 'http://api.example.com/users?page=5' + * }); + * + * @param {Object} links + * @return {ServerResponse} + * @public + */ + +res.links = function(links){ + var link = this.get('Link') || ''; + if (link) link += ', '; + return this.set('Link', link + Object.keys(links).map(function(rel){ + return '<' + links[rel] + '>; rel="' + rel + '"'; + }).join(', ')); +}; + +/** + * Send a response. + * + * Examples: + * + * res.send(Buffer.from('wahoo')); + * res.send({ some: 'json' }); + * res.send('

some html

'); + * + * @param {string|number|boolean|object|Buffer} body + * @public + */ + +res.send = function send(body) { + var chunk = body; + var encoding; + var req = this.req; + var type; + + // settings + var app = this.app; + + // allow status / body + if (arguments.length === 2) { + // res.send(body, status) backwards compat + if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') { + deprecate('res.send(body, status): Use res.status(status).send(body) instead'); + this.statusCode = arguments[1]; + } else { + deprecate('res.send(status, body): Use res.status(status).send(body) instead'); + this.statusCode = arguments[0]; + chunk = arguments[1]; + } + } + + // disambiguate res.send(status) and res.send(status, num) + if (typeof chunk === 'number' && arguments.length === 1) { + // res.send(status) will set status message as text string + if (!this.get('Content-Type')) { + this.type('txt'); + } + + deprecate('res.send(status): Use res.sendStatus(status) instead'); + this.statusCode = chunk; + chunk = statuses.message[chunk] + } + + switch (typeof chunk) { + // string defaulting to html + case 'string': + if (!this.get('Content-Type')) { + this.type('html'); + } + break; + case 'boolean': + case 'number': + case 'object': + if (chunk === null) { + chunk = ''; + } else if (Buffer.isBuffer(chunk)) { + if (!this.get('Content-Type')) { + this.type('bin'); + } + } else { + return this.json(chunk); + } + break; + } + + // write strings in utf-8 + if (typeof chunk === 'string') { + encoding = 'utf8'; + type = this.get('Content-Type'); + + // reflect this in content-type + if (typeof type === 'string') { + this.set('Content-Type', setCharset(type, 'utf-8')); + } + } + + // determine if ETag should be generated + var etagFn = app.get('etag fn') + var generateETag = !this.get('ETag') && typeof etagFn === 'function' + + // populate Content-Length + var len + if (chunk !== undefined) { + if (Buffer.isBuffer(chunk)) { + // get length of Buffer + len = chunk.length + } else if (!generateETag && chunk.length < 1000) { + // just calculate length when no ETag + small chunk + len = Buffer.byteLength(chunk, encoding) + } else { + // convert chunk to Buffer and calculate + chunk = Buffer.from(chunk, encoding) + encoding = undefined; + len = chunk.length + } + + this.set('Content-Length', len); + } + + // populate ETag + var etag; + if (generateETag && len !== undefined) { + if ((etag = etagFn(chunk, encoding))) { + this.set('ETag', etag); + } + } + + // freshness + if (req.fresh) this.statusCode = 304; + + // strip irrelevant headers + if (204 === this.statusCode || 304 === this.statusCode) { + this.removeHeader('Content-Type'); + this.removeHeader('Content-Length'); + this.removeHeader('Transfer-Encoding'); + chunk = ''; + } + + // alter headers for 205 + if (this.statusCode === 205) { + this.set('Content-Length', '0') + this.removeHeader('Transfer-Encoding') + chunk = '' + } + + if (req.method === 'HEAD') { + // skip body for HEAD + this.end(); + } else { + // respond + this.end(chunk, encoding); + } + + return this; +}; + +/** + * Send JSON response. + * + * Examples: + * + * res.json(null); + * res.json({ user: 'tj' }); + * + * @param {string|number|boolean|object} obj + * @public + */ + +res.json = function json(obj) { + var val = obj; + + // allow status / body + if (arguments.length === 2) { + // res.json(body, status) backwards compat + if (typeof arguments[1] === 'number') { + deprecate('res.json(obj, status): Use res.status(status).json(obj) instead'); + this.statusCode = arguments[1]; + } else { + deprecate('res.json(status, obj): Use res.status(status).json(obj) instead'); + this.statusCode = arguments[0]; + val = arguments[1]; + } + } + + // settings + var app = this.app; + var escape = app.get('json escape') + var replacer = app.get('json replacer'); + var spaces = app.get('json spaces'); + var body = stringify(val, replacer, spaces, escape) + + // content-type + if (!this.get('Content-Type')) { + this.set('Content-Type', 'application/json'); + } + + return this.send(body); +}; + +/** + * Send JSON response with JSONP callback support. + * + * Examples: + * + * res.jsonp(null); + * res.jsonp({ user: 'tj' }); + * + * @param {string|number|boolean|object} obj + * @public + */ + +res.jsonp = function jsonp(obj) { + var val = obj; + + // allow status / body + if (arguments.length === 2) { + // res.jsonp(body, status) backwards compat + if (typeof arguments[1] === 'number') { + deprecate('res.jsonp(obj, status): Use res.status(status).jsonp(obj) instead'); + this.statusCode = arguments[1]; + } else { + deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead'); + this.statusCode = arguments[0]; + val = arguments[1]; + } + } + + // settings + var app = this.app; + var escape = app.get('json escape') + var replacer = app.get('json replacer'); + var spaces = app.get('json spaces'); + var body = stringify(val, replacer, spaces, escape) + var callback = this.req.query[app.get('jsonp callback name')]; + + // content-type + if (!this.get('Content-Type')) { + this.set('X-Content-Type-Options', 'nosniff'); + this.set('Content-Type', 'application/json'); + } + + // fixup callback + if (Array.isArray(callback)) { + callback = callback[0]; + } + + // jsonp + if (typeof callback === 'string' && callback.length !== 0) { + this.set('X-Content-Type-Options', 'nosniff'); + this.set('Content-Type', 'text/javascript'); + + // restrict callback charset + callback = callback.replace(/[^\[\]\w$.]/g, ''); + + if (body === undefined) { + // empty argument + body = '' + } else if (typeof body === 'string') { + // replace chars not allowed in JavaScript that are in JSON + body = body + .replace(/\u2028/g, '\\u2028') + .replace(/\u2029/g, '\\u2029') + } + + // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse" + // the typeof check is just to reduce client error noise + body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');'; + } + + return this.send(body); +}; + +/** + * Send given HTTP status code. + * + * Sets the response status to `statusCode` and the body of the + * response to the standard description from node's http.STATUS_CODES + * or the statusCode number if no description. + * + * Examples: + * + * res.sendStatus(200); + * + * @param {number} statusCode + * @public + */ + +res.sendStatus = function sendStatus(statusCode) { + var body = statuses.message[statusCode] || String(statusCode) + + this.statusCode = statusCode; + this.type('txt'); + + return this.send(body); +}; + +/** + * Transfer the file at the given `path`. + * + * Automatically sets the _Content-Type_ response header field. + * The callback `callback(err)` is invoked when the transfer is complete + * or when an error occurs. Be sure to check `res.headersSent` + * if you wish to attempt responding, as the header and some data + * may have already been transferred. + * + * Options: + * + * - `maxAge` defaulting to 0 (can be string converted by `ms`) + * - `root` root directory for relative filenames + * - `headers` object of headers to serve with file + * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them + * + * Other options are passed along to `send`. + * + * Examples: + * + * The following example illustrates how `res.sendFile()` may + * be used as an alternative for the `static()` middleware for + * dynamic situations. The code backing `res.sendFile()` is actually + * the same code, so HTTP cache support etc is identical. + * + * app.get('/user/:uid/photos/:file', function(req, res){ + * var uid = req.params.uid + * , file = req.params.file; + * + * req.user.mayViewFilesFrom(uid, function(yes){ + * if (yes) { + * res.sendFile('/uploads/' + uid + '/' + file); + * } else { + * res.send(403, 'Sorry! you cant see that.'); + * } + * }); + * }); + * + * @public + */ + +res.sendFile = function sendFile(path, options, callback) { + var done = callback; + var req = this.req; + var res = this; + var next = req.next; + var opts = options || {}; + + if (!path) { + throw new TypeError('path argument is required to res.sendFile'); + } + + if (typeof path !== 'string') { + throw new TypeError('path must be a string to res.sendFile') + } + + // support function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } + + if (!opts.root && !isAbsolute(path)) { + throw new TypeError('path must be absolute or specify root to res.sendFile'); + } + + // create file stream + var pathname = encodeURI(path); + var file = send(req, pathname, opts); + + // transfer + sendfile(res, file, opts, function (err) { + if (done) return done(err); + if (err && err.code === 'EISDIR') return next(); + + // next() all but write errors + if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { + next(err); + } + }); +}; + +/** + * Transfer the file at the given `path`. + * + * Automatically sets the _Content-Type_ response header field. + * The callback `callback(err)` is invoked when the transfer is complete + * or when an error occurs. Be sure to check `res.headersSent` + * if you wish to attempt responding, as the header and some data + * may have already been transferred. + * + * Options: + * + * - `maxAge` defaulting to 0 (can be string converted by `ms`) + * - `root` root directory for relative filenames + * - `headers` object of headers to serve with file + * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them + * + * Other options are passed along to `send`. + * + * Examples: + * + * The following example illustrates how `res.sendfile()` may + * be used as an alternative for the `static()` middleware for + * dynamic situations. The code backing `res.sendfile()` is actually + * the same code, so HTTP cache support etc is identical. + * + * app.get('/user/:uid/photos/:file', function(req, res){ + * var uid = req.params.uid + * , file = req.params.file; + * + * req.user.mayViewFilesFrom(uid, function(yes){ + * if (yes) { + * res.sendfile('/uploads/' + uid + '/' + file); + * } else { + * res.send(403, 'Sorry! you cant see that.'); + * } + * }); + * }); + * + * @public + */ + +res.sendfile = function (path, options, callback) { + var done = callback; + var req = this.req; + var res = this; + var next = req.next; + var opts = options || {}; + + // support function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } + + // create file stream + var file = send(req, path, opts); + + // transfer + sendfile(res, file, opts, function (err) { + if (done) return done(err); + if (err && err.code === 'EISDIR') return next(); + + // next() all but write errors + if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { + next(err); + } + }); +}; + +res.sendfile = deprecate.function(res.sendfile, + 'res.sendfile: Use res.sendFile instead'); + +/** + * Transfer the file at the given `path` as an attachment. + * + * Optionally providing an alternate attachment `filename`, + * and optional callback `callback(err)`. The callback is invoked + * when the data transfer is complete, or when an error has + * occurred. Be sure to check `res.headersSent` if you plan to respond. + * + * Optionally providing an `options` object to use with `res.sendFile()`. + * This function will set the `Content-Disposition` header, overriding + * any `Content-Disposition` header passed as header options in order + * to set the attachment and filename. + * + * This method uses `res.sendFile()`. + * + * @public + */ + +res.download = function download (path, filename, options, callback) { + var done = callback; + var name = filename; + var opts = options || null + + // support function as second or third arg + if (typeof filename === 'function') { + done = filename; + name = null; + opts = null + } else if (typeof options === 'function') { + done = options + opts = null + } + + // support optional filename, where options may be in it's place + if (typeof filename === 'object' && + (typeof options === 'function' || options === undefined)) { + name = null + opts = filename + } + + // set Content-Disposition when file is sent + var headers = { + 'Content-Disposition': contentDisposition(name || path) + }; + + // merge user-provided headers + if (opts && opts.headers) { + var keys = Object.keys(opts.headers) + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + if (key.toLowerCase() !== 'content-disposition') { + headers[key] = opts.headers[key] + } + } + } + + // merge user-provided options + opts = Object.create(opts) + opts.headers = headers + + // Resolve the full path for sendFile + var fullPath = !opts.root + ? resolve(path) + : path + + // send file + return this.sendFile(fullPath, opts, done) +}; + +/** + * Set _Content-Type_ response header with `type` through `mime.lookup()` + * when it does not contain "/", or set the Content-Type to `type` otherwise. + * + * Examples: + * + * res.type('.html'); + * res.type('html'); + * res.type('json'); + * res.type('application/json'); + * res.type('png'); + * + * @param {String} type + * @return {ServerResponse} for chaining + * @public + */ + +res.contentType = +res.type = function contentType(type) { + var ct = type.indexOf('/') === -1 + ? mime.lookup(type) + : type; + + return this.set('Content-Type', ct); +}; + +/** + * Respond to the Acceptable formats using an `obj` + * of mime-type callbacks. + * + * This method uses `req.accepted`, an array of + * acceptable types ordered by their quality values. + * When "Accept" is not present the _first_ callback + * is invoked, otherwise the first match is used. When + * no match is performed the server responds with + * 406 "Not Acceptable". + * + * Content-Type is set for you, however if you choose + * you may alter this within the callback using `res.type()` + * or `res.set('Content-Type', ...)`. + * + * res.format({ + * 'text/plain': function(){ + * res.send('hey'); + * }, + * + * 'text/html': function(){ + * res.send('

hey

'); + * }, + * + * 'application/json': function () { + * res.send({ message: 'hey' }); + * } + * }); + * + * In addition to canonicalized MIME types you may + * also use extnames mapped to these types: + * + * res.format({ + * text: function(){ + * res.send('hey'); + * }, + * + * html: function(){ + * res.send('

hey

'); + * }, + * + * json: function(){ + * res.send({ message: 'hey' }); + * } + * }); + * + * By default Express passes an `Error` + * with a `.status` of 406 to `next(err)` + * if a match is not made. If you provide + * a `.default` callback it will be invoked + * instead. + * + * @param {Object} obj + * @return {ServerResponse} for chaining + * @public + */ + +res.format = function(obj){ + var req = this.req; + var next = req.next; + + var keys = Object.keys(obj) + .filter(function (v) { return v !== 'default' }) + + var key = keys.length > 0 + ? req.accepts(keys) + : false; + + this.vary("Accept"); + + if (key) { + this.set('Content-Type', normalizeType(key).value); + obj[key](req, this, next); + } else if (obj.default) { + obj.default(req, this, next) + } else { + next(createError(406, { + types: normalizeTypes(keys).map(function (o) { return o.value }) + })) + } + + return this; +}; + +/** + * Set _Content-Disposition_ header to _attachment_ with optional `filename`. + * + * @param {String} filename + * @return {ServerResponse} + * @public + */ + +res.attachment = function attachment(filename) { + if (filename) { + this.type(extname(filename)); + } + + this.set('Content-Disposition', contentDisposition(filename)); + + return this; +}; + +/** + * Append additional header `field` with value `val`. + * + * Example: + * + * res.append('Link', ['', '']); + * res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly'); + * res.append('Warning', '199 Miscellaneous warning'); + * + * @param {String} field + * @param {String|Array} val + * @return {ServerResponse} for chaining + * @public + */ + +res.append = function append(field, val) { + var prev = this.get(field); + var value = val; + + if (prev) { + // concat the new and prev vals + value = Array.isArray(prev) ? prev.concat(val) + : Array.isArray(val) ? [prev].concat(val) + : [prev, val] + } + + return this.set(field, value); +}; + +/** + * Set header `field` to `val`, or pass + * an object of header fields. + * + * Examples: + * + * res.set('Foo', ['bar', 'baz']); + * res.set('Accept', 'application/json'); + * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); + * + * Aliased as `res.header()`. + * + * @param {String|Object} field + * @param {String|Array} val + * @return {ServerResponse} for chaining + * @public + */ + +res.set = +res.header = function header(field, val) { + if (arguments.length === 2) { + var value = Array.isArray(val) + ? val.map(String) + : String(val); + + // add charset to content-type + if (field.toLowerCase() === 'content-type') { + if (Array.isArray(value)) { + throw new TypeError('Content-Type cannot be set to an Array'); + } + if (!charsetRegExp.test(value)) { + var charset = mime.charsets.lookup(value.split(';')[0]); + if (charset) value += '; charset=' + charset.toLowerCase(); + } + } + + this.setHeader(field, value); + } else { + for (var key in field) { + this.set(key, field[key]); + } + } + return this; +}; + +/** + * Get value for header `field`. + * + * @param {String} field + * @return {String} + * @public + */ + +res.get = function(field){ + return this.getHeader(field); +}; + +/** + * Clear cookie `name`. + * + * @param {String} name + * @param {Object} [options] + * @return {ServerResponse} for chaining + * @public + */ + +res.clearCookie = function clearCookie(name, options) { + var opts = merge({ expires: new Date(1), path: '/' }, options); + + return this.cookie(name, '', opts); +}; + +/** + * Set cookie `name` to `value`, with the given `options`. + * + * Options: + * + * - `maxAge` max-age in milliseconds, converted to `expires` + * - `signed` sign the cookie + * - `path` defaults to "/" + * + * Examples: + * + * // "Remember Me" for 15 minutes + * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); + * + * // same as above + * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) + * + * @param {String} name + * @param {String|Object} value + * @param {Object} [options] + * @return {ServerResponse} for chaining + * @public + */ + +res.cookie = function (name, value, options) { + var opts = merge({}, options); + var secret = this.req.secret; + var signed = opts.signed; + + if (signed && !secret) { + throw new Error('cookieParser("secret") required for signed cookies'); + } + + var val = typeof value === 'object' + ? 'j:' + JSON.stringify(value) + : String(value); + + if (signed) { + val = 's:' + sign(val, secret); + } + + if (opts.maxAge != null) { + var maxAge = opts.maxAge - 0 + + if (!isNaN(maxAge)) { + opts.expires = new Date(Date.now() + maxAge) + opts.maxAge = Math.floor(maxAge / 1000) + } + } + + if (opts.path == null) { + opts.path = '/'; + } + + this.append('Set-Cookie', cookie.serialize(name, String(val), opts)); + + return this; +}; + +/** + * Set the location header to `url`. + * + * The given `url` can also be "back", which redirects + * to the _Referrer_ or _Referer_ headers or "/". + * + * Examples: + * + * res.location('/foo/bar').; + * res.location('http://example.com'); + * res.location('../login'); + * + * @param {String} url + * @return {ServerResponse} for chaining + * @public + */ + +res.location = function location(url) { + var loc = url; + + // "back" is an alias for the referrer + if (url === 'back') { + loc = this.req.get('Referrer') || '/'; + } + + // set location + return this.set('Location', encodeUrl(loc)); +}; + +/** + * Redirect to the given `url` with optional response `status` + * defaulting to 302. + * + * The resulting `url` is determined by `res.location()`, so + * it will play nicely with mounted apps, relative paths, + * `"back"` etc. + * + * Examples: + * + * res.redirect('/foo/bar'); + * res.redirect('http://example.com'); + * res.redirect(301, 'http://example.com'); + * res.redirect('../login'); // /blog/post/1 -> /blog/login + * + * @public + */ + +res.redirect = function redirect(url) { + var address = url; + var body; + var status = 302; + + // allow status / url + if (arguments.length === 2) { + if (typeof arguments[0] === 'number') { + status = arguments[0]; + address = arguments[1]; + } else { + deprecate('res.redirect(url, status): Use res.redirect(status, url) instead'); + status = arguments[1]; + } + } + + // Set location header + address = this.location(address).get('Location'); + + // Support text/{plain,html} by default + this.format({ + text: function(){ + body = statuses.message[status] + '. Redirecting to ' + address + }, + + html: function(){ + var u = escapeHtml(address); + body = '

' + statuses.message[status] + '. Redirecting to ' + u + '

' + }, + + default: function(){ + body = ''; + } + }); + + // Respond + this.statusCode = status; + this.set('Content-Length', Buffer.byteLength(body)); + + if (this.req.method === 'HEAD') { + this.end(); + } else { + this.end(body); + } +}; + +/** + * Add `field` to Vary. If already present in the Vary set, then + * this call is simply ignored. + * + * @param {Array|String} field + * @return {ServerResponse} for chaining + * @public + */ + +res.vary = function(field){ + // checks for back-compat + if (!field || (Array.isArray(field) && !field.length)) { + deprecate('res.vary(): Provide a field name'); + return this; + } + + vary(this, field); + + return this; +}; + +/** + * Render `view` with the given `options` and optional callback `fn`. + * When a callback function is given a response will _not_ be made + * automatically, otherwise a response of _200_ and _text/html_ is given. + * + * Options: + * + * - `cache` boolean hinting to the engine it should cache + * - `filename` filename of the view being rendered + * + * @public + */ + +res.render = function render(view, options, callback) { + var app = this.req.app; + var done = callback; + var opts = options || {}; + var req = this.req; + var self = this; + + // support callback function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } + + // merge res.locals + opts._locals = self.locals; + + // default callback to respond + done = done || function (err, str) { + if (err) return req.next(err); + self.send(str); + }; + + // render + app.render(view, opts, done); +}; + +// pipe the send file stream +function sendfile(res, file, options, callback) { + var done = false; + var streaming; + + // request aborted + function onaborted() { + if (done) return; + done = true; + + var err = new Error('Request aborted'); + err.code = 'ECONNABORTED'; + callback(err); + } + + // directory + function ondirectory() { + if (done) return; + done = true; + + var err = new Error('EISDIR, read'); + err.code = 'EISDIR'; + callback(err); + } + + // errors + function onerror(err) { + if (done) return; + done = true; + callback(err); + } + + // ended + function onend() { + if (done) return; + done = true; + callback(); + } + + // file + function onfile() { + streaming = false; + } + + // finished + function onfinish(err) { + if (err && err.code === 'ECONNRESET') return onaborted(); + if (err) return onerror(err); + if (done) return; + + setImmediate(function () { + if (streaming !== false && !done) { + onaborted(); + return; + } + + if (done) return; + done = true; + callback(); + }); + } + + // streaming + function onstream() { + streaming = true; + } + + file.on('directory', ondirectory); + file.on('end', onend); + file.on('error', onerror); + file.on('file', onfile); + file.on('stream', onstream); + onFinished(res, onfinish); + + if (options.headers) { + // set headers on successful transfer + file.on('headers', function headers(res) { + var obj = options.headers; + var keys = Object.keys(obj); + + for (var i = 0; i < keys.length; i++) { + var k = keys[i]; + res.setHeader(k, obj[k]); + } + }); + } + + // pipe + file.pipe(res); +} + +/** + * Stringify JSON, like JSON.stringify, but v8 optimized, with the + * ability to escape characters that can trigger HTML sniffing. + * + * @param {*} value + * @param {function} replacer + * @param {number} spaces + * @param {boolean} escape + * @returns {string} + * @private + */ + +function stringify (value, replacer, spaces, escape) { + // v8 checks arguments.length for optimizing simple call + // https://bugs.chromium.org/p/v8/issues/detail?id=4730 + var json = replacer || spaces + ? JSON.stringify(value, replacer, spaces) + : JSON.stringify(value); + + if (escape && typeof json === 'string') { + json = json.replace(/[<>&]/g, function (c) { + switch (c.charCodeAt(0)) { + case 0x3c: + return '\\u003c' + case 0x3e: + return '\\u003e' + case 0x26: + return '\\u0026' + /* istanbul ignore next: unreachable default */ + default: + return c + } + }) + } + + return json +} diff --git a/system/login/node_modules/express/lib/router/index.js b/system/login/node_modules/express/lib/router/index.js new file mode 100644 index 0000000..5174c34 --- /dev/null +++ b/system/login/node_modules/express/lib/router/index.js @@ -0,0 +1,673 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var Route = require('./route'); +var Layer = require('./layer'); +var methods = require('methods'); +var mixin = require('utils-merge'); +var debug = require('debug')('express:router'); +var deprecate = require('depd')('express'); +var flatten = require('array-flatten'); +var parseUrl = require('parseurl'); +var setPrototypeOf = require('setprototypeof') + +/** + * Module variables. + * @private + */ + +var objectRegExp = /^\[object (\S+)\]$/; +var slice = Array.prototype.slice; +var toString = Object.prototype.toString; + +/** + * Initialize a new `Router` with the given `options`. + * + * @param {Object} [options] + * @return {Router} which is an callable function + * @public + */ + +var proto = module.exports = function(options) { + var opts = options || {}; + + function router(req, res, next) { + router.handle(req, res, next); + } + + // mixin Router class functions + setPrototypeOf(router, proto) + + router.params = {}; + router._params = []; + router.caseSensitive = opts.caseSensitive; + router.mergeParams = opts.mergeParams; + router.strict = opts.strict; + router.stack = []; + + return router; +}; + +/** + * Map the given param placeholder `name`(s) to the given callback. + * + * Parameter mapping is used to provide pre-conditions to routes + * which use normalized placeholders. For example a _:user_id_ parameter + * could automatically load a user's information from the database without + * any additional code, + * + * The callback uses the same signature as middleware, the only difference + * being that the value of the placeholder is passed, in this case the _id_ + * of the user. Once the `next()` function is invoked, just like middleware + * it will continue on to execute the route, or subsequent parameter functions. + * + * Just like in middleware, you must either respond to the request or call next + * to avoid stalling the request. + * + * app.param('user_id', function(req, res, next, id){ + * User.find(id, function(err, user){ + * if (err) { + * return next(err); + * } else if (!user) { + * return next(new Error('failed to load user')); + * } + * req.user = user; + * next(); + * }); + * }); + * + * @param {String} name + * @param {Function} fn + * @return {app} for chaining + * @public + */ + +proto.param = function param(name, fn) { + // param logic + if (typeof name === 'function') { + deprecate('router.param(fn): Refactor to use path params'); + this._params.push(name); + return; + } + + // apply param functions + var params = this._params; + var len = params.length; + var ret; + + if (name[0] === ':') { + deprecate('router.param(' + JSON.stringify(name) + ', fn): Use router.param(' + JSON.stringify(name.slice(1)) + ', fn) instead') + name = name.slice(1) + } + + for (var i = 0; i < len; ++i) { + if (ret = params[i](name, fn)) { + fn = ret; + } + } + + // ensure we end up with a + // middleware function + if ('function' !== typeof fn) { + throw new Error('invalid param() call for ' + name + ', got ' + fn); + } + + (this.params[name] = this.params[name] || []).push(fn); + return this; +}; + +/** + * Dispatch a req, res into the router. + * @private + */ + +proto.handle = function handle(req, res, out) { + var self = this; + + debug('dispatching %s %s', req.method, req.url); + + var idx = 0; + var protohost = getProtohost(req.url) || '' + var removed = ''; + var slashAdded = false; + var sync = 0 + var paramcalled = {}; + + // store options for OPTIONS request + // only used if OPTIONS request + var options = []; + + // middleware and routes + var stack = self.stack; + + // manage inter-router variables + var parentParams = req.params; + var parentUrl = req.baseUrl || ''; + var done = restore(out, req, 'baseUrl', 'next', 'params'); + + // setup next layer + req.next = next; + + // for options requests, respond with a default if nothing else responds + if (req.method === 'OPTIONS') { + done = wrap(done, function(old, err) { + if (err || options.length === 0) return old(err); + sendOptionsResponse(res, options, old); + }); + } + + // setup basic req values + req.baseUrl = parentUrl; + req.originalUrl = req.originalUrl || req.url; + + next(); + + function next(err) { + var layerError = err === 'route' + ? null + : err; + + // remove added slash + if (slashAdded) { + req.url = req.url.slice(1) + slashAdded = false; + } + + // restore altered req.url + if (removed.length !== 0) { + req.baseUrl = parentUrl; + req.url = protohost + removed + req.url.slice(protohost.length) + removed = ''; + } + + // signal to exit router + if (layerError === 'router') { + setImmediate(done, null) + return + } + + // no more matching layers + if (idx >= stack.length) { + setImmediate(done, layerError); + return; + } + + // max sync stack + if (++sync > 100) { + return setImmediate(next, err) + } + + // get pathname of request + var path = getPathname(req); + + if (path == null) { + return done(layerError); + } + + // find next matching layer + var layer; + var match; + var route; + + while (match !== true && idx < stack.length) { + layer = stack[idx++]; + match = matchLayer(layer, path); + route = layer.route; + + if (typeof match !== 'boolean') { + // hold on to layerError + layerError = layerError || match; + } + + if (match !== true) { + continue; + } + + if (!route) { + // process non-route handlers normally + continue; + } + + if (layerError) { + // routes do not match with a pending error + match = false; + continue; + } + + var method = req.method; + var has_method = route._handles_method(method); + + // build up automatic options response + if (!has_method && method === 'OPTIONS') { + appendMethods(options, route._options()); + } + + // don't even bother matching route + if (!has_method && method !== 'HEAD') { + match = false; + } + } + + // no match + if (match !== true) { + return done(layerError); + } + + // store route for dispatch on change + if (route) { + req.route = route; + } + + // Capture one-time layer values + req.params = self.mergeParams + ? mergeParams(layer.params, parentParams) + : layer.params; + var layerPath = layer.path; + + // this should be done for the layer + self.process_params(layer, paramcalled, req, res, function (err) { + if (err) { + next(layerError || err) + } else if (route) { + layer.handle_request(req, res, next) + } else { + trim_prefix(layer, layerError, layerPath, path) + } + + sync = 0 + }); + } + + function trim_prefix(layer, layerError, layerPath, path) { + if (layerPath.length !== 0) { + // Validate path is a prefix match + if (layerPath !== path.slice(0, layerPath.length)) { + next(layerError) + return + } + + // Validate path breaks on a path separator + var c = path[layerPath.length] + if (c && c !== '/' && c !== '.') return next(layerError) + + // Trim off the part of the url that matches the route + // middleware (.use stuff) needs to have the path stripped + debug('trim prefix (%s) from url %s', layerPath, req.url); + removed = layerPath; + req.url = protohost + req.url.slice(protohost.length + removed.length) + + // Ensure leading slash + if (!protohost && req.url[0] !== '/') { + req.url = '/' + req.url; + slashAdded = true; + } + + // Setup base URL (no trailing slash) + req.baseUrl = parentUrl + (removed[removed.length - 1] === '/' + ? removed.substring(0, removed.length - 1) + : removed); + } + + debug('%s %s : %s', layer.name, layerPath, req.originalUrl); + + if (layerError) { + layer.handle_error(layerError, req, res, next); + } else { + layer.handle_request(req, res, next); + } + } +}; + +/** + * Process any parameters for the layer. + * @private + */ + +proto.process_params = function process_params(layer, called, req, res, done) { + var params = this.params; + + // captured parameters from the layer, keys and values + var keys = layer.keys; + + // fast track + if (!keys || keys.length === 0) { + return done(); + } + + var i = 0; + var name; + var paramIndex = 0; + var key; + var paramVal; + var paramCallbacks; + var paramCalled; + + // process params in order + // param callbacks can be async + function param(err) { + if (err) { + return done(err); + } + + if (i >= keys.length ) { + return done(); + } + + paramIndex = 0; + key = keys[i++]; + name = key.name; + paramVal = req.params[name]; + paramCallbacks = params[name]; + paramCalled = called[name]; + + if (paramVal === undefined || !paramCallbacks) { + return param(); + } + + // param previously called with same value or error occurred + if (paramCalled && (paramCalled.match === paramVal + || (paramCalled.error && paramCalled.error !== 'route'))) { + // restore value + req.params[name] = paramCalled.value; + + // next param + return param(paramCalled.error); + } + + called[name] = paramCalled = { + error: null, + match: paramVal, + value: paramVal + }; + + paramCallback(); + } + + // single param callbacks + function paramCallback(err) { + var fn = paramCallbacks[paramIndex++]; + + // store updated value + paramCalled.value = req.params[key.name]; + + if (err) { + // store error + paramCalled.error = err; + param(err); + return; + } + + if (!fn) return param(); + + try { + fn(req, res, paramCallback, paramVal, key.name); + } catch (e) { + paramCallback(e); + } + } + + param(); +}; + +/** + * Use the given middleware function, with optional path, defaulting to "/". + * + * Use (like `.all`) will run for any http METHOD, but it will not add + * handlers for those methods so OPTIONS requests will not consider `.use` + * functions even if they could respond. + * + * The other difference is that _route_ path is stripped and not visible + * to the handler function. The main effect of this feature is that mounted + * handlers can operate without any code changes regardless of the "prefix" + * pathname. + * + * @public + */ + +proto.use = function use(fn) { + var offset = 0; + var path = '/'; + + // default path to '/' + // disambiguate router.use([fn]) + if (typeof fn !== 'function') { + var arg = fn; + + while (Array.isArray(arg) && arg.length !== 0) { + arg = arg[0]; + } + + // first arg is the path + if (typeof arg !== 'function') { + offset = 1; + path = fn; + } + } + + var callbacks = flatten(slice.call(arguments, offset)); + + if (callbacks.length === 0) { + throw new TypeError('Router.use() requires a middleware function') + } + + for (var i = 0; i < callbacks.length; i++) { + var fn = callbacks[i]; + + if (typeof fn !== 'function') { + throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn)) + } + + // add the middleware + debug('use %o %s', path, fn.name || '') + + var layer = new Layer(path, { + sensitive: this.caseSensitive, + strict: false, + end: false + }, fn); + + layer.route = undefined; + + this.stack.push(layer); + } + + return this; +}; + +/** + * Create a new Route for the given path. + * + * Each route contains a separate middleware stack and VERB handlers. + * + * See the Route api documentation for details on adding handlers + * and middleware to routes. + * + * @param {String} path + * @return {Route} + * @public + */ + +proto.route = function route(path) { + var route = new Route(path); + + var layer = new Layer(path, { + sensitive: this.caseSensitive, + strict: this.strict, + end: true + }, route.dispatch.bind(route)); + + layer.route = route; + + this.stack.push(layer); + return route; +}; + +// create Router#VERB functions +methods.concat('all').forEach(function(method){ + proto[method] = function(path){ + var route = this.route(path) + route[method].apply(route, slice.call(arguments, 1)); + return this; + }; +}); + +// append methods to a list of methods +function appendMethods(list, addition) { + for (var i = 0; i < addition.length; i++) { + var method = addition[i]; + if (list.indexOf(method) === -1) { + list.push(method); + } + } +} + +// get pathname of request +function getPathname(req) { + try { + return parseUrl(req).pathname; + } catch (err) { + return undefined; + } +} + +// Get get protocol + host for a URL +function getProtohost(url) { + if (typeof url !== 'string' || url.length === 0 || url[0] === '/') { + return undefined + } + + var searchIndex = url.indexOf('?') + var pathLength = searchIndex !== -1 + ? searchIndex + : url.length + var fqdnIndex = url.slice(0, pathLength).indexOf('://') + + return fqdnIndex !== -1 + ? url.substring(0, url.indexOf('/', 3 + fqdnIndex)) + : undefined +} + +// get type for error message +function gettype(obj) { + var type = typeof obj; + + if (type !== 'object') { + return type; + } + + // inspect [[Class]] for objects + return toString.call(obj) + .replace(objectRegExp, '$1'); +} + +/** + * Match path to a layer. + * + * @param {Layer} layer + * @param {string} path + * @private + */ + +function matchLayer(layer, path) { + try { + return layer.match(path); + } catch (err) { + return err; + } +} + +// merge params with parent params +function mergeParams(params, parent) { + if (typeof parent !== 'object' || !parent) { + return params; + } + + // make copy of parent for base + var obj = mixin({}, parent); + + // simple non-numeric merging + if (!(0 in params) || !(0 in parent)) { + return mixin(obj, params); + } + + var i = 0; + var o = 0; + + // determine numeric gaps + while (i in params) { + i++; + } + + while (o in parent) { + o++; + } + + // offset numeric indices in params before merge + for (i--; i >= 0; i--) { + params[i + o] = params[i]; + + // create holes for the merge when necessary + if (i < o) { + delete params[i]; + } + } + + return mixin(obj, params); +} + +// restore obj props after function +function restore(fn, obj) { + var props = new Array(arguments.length - 2); + var vals = new Array(arguments.length - 2); + + for (var i = 0; i < props.length; i++) { + props[i] = arguments[i + 2]; + vals[i] = obj[props[i]]; + } + + return function () { + // restore vals + for (var i = 0; i < props.length; i++) { + obj[props[i]] = vals[i]; + } + + return fn.apply(this, arguments); + }; +} + +// send an OPTIONS response +function sendOptionsResponse(res, options, next) { + try { + var body = options.join(','); + res.set('Allow', body); + res.send(body); + } catch (err) { + next(err); + } +} + +// wrap a function +function wrap(old, fn) { + return function proxy() { + var args = new Array(arguments.length + 1); + + args[0] = old; + for (var i = 0, len = arguments.length; i < len; i++) { + args[i + 1] = arguments[i]; + } + + fn.apply(this, args); + }; +} diff --git a/system/login/node_modules/express/lib/router/layer.js b/system/login/node_modules/express/lib/router/layer.js new file mode 100644 index 0000000..4dc8e86 --- /dev/null +++ b/system/login/node_modules/express/lib/router/layer.js @@ -0,0 +1,181 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var pathRegexp = require('path-to-regexp'); +var debug = require('debug')('express:router:layer'); + +/** + * Module variables. + * @private + */ + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +/** + * Module exports. + * @public + */ + +module.exports = Layer; + +function Layer(path, options, fn) { + if (!(this instanceof Layer)) { + return new Layer(path, options, fn); + } + + debug('new %o', path) + var opts = options || {}; + + this.handle = fn; + this.name = fn.name || ''; + this.params = undefined; + this.path = undefined; + this.regexp = pathRegexp(path, this.keys = [], opts); + + // set fast path flags + this.regexp.fast_star = path === '*' + this.regexp.fast_slash = path === '/' && opts.end === false +} + +/** + * Handle the error for the layer. + * + * @param {Error} error + * @param {Request} req + * @param {Response} res + * @param {function} next + * @api private + */ + +Layer.prototype.handle_error = function handle_error(error, req, res, next) { + var fn = this.handle; + + if (fn.length !== 4) { + // not a standard error handler + return next(error); + } + + try { + fn(error, req, res, next); + } catch (err) { + next(err); + } +}; + +/** + * Handle the request for the layer. + * + * @param {Request} req + * @param {Response} res + * @param {function} next + * @api private + */ + +Layer.prototype.handle_request = function handle(req, res, next) { + var fn = this.handle; + + if (fn.length > 3) { + // not a standard request handler + return next(); + } + + try { + fn(req, res, next); + } catch (err) { + next(err); + } +}; + +/** + * Check if this route matches `path`, if so + * populate `.params`. + * + * @param {String} path + * @return {Boolean} + * @api private + */ + +Layer.prototype.match = function match(path) { + var match + + if (path != null) { + // fast path non-ending match for / (any path matches) + if (this.regexp.fast_slash) { + this.params = {} + this.path = '' + return true + } + + // fast path for * (everything matched in a param) + if (this.regexp.fast_star) { + this.params = {'0': decode_param(path)} + this.path = path + return true + } + + // match the path + match = this.regexp.exec(path) + } + + if (!match) { + this.params = undefined; + this.path = undefined; + return false; + } + + // store values + this.params = {}; + this.path = match[0] + + var keys = this.keys; + var params = this.params; + + for (var i = 1; i < match.length; i++) { + var key = keys[i - 1]; + var prop = key.name; + var val = decode_param(match[i]) + + if (val !== undefined || !(hasOwnProperty.call(params, prop))) { + params[prop] = val; + } + } + + return true; +}; + +/** + * Decode param value. + * + * @param {string} val + * @return {string} + * @private + */ + +function decode_param(val) { + if (typeof val !== 'string' || val.length === 0) { + return val; + } + + try { + return decodeURIComponent(val); + } catch (err) { + if (err instanceof URIError) { + err.message = 'Failed to decode param \'' + val + '\''; + err.status = err.statusCode = 400; + } + + throw err; + } +} diff --git a/system/login/node_modules/express/lib/router/route.js b/system/login/node_modules/express/lib/router/route.js new file mode 100644 index 0000000..cc643ac --- /dev/null +++ b/system/login/node_modules/express/lib/router/route.js @@ -0,0 +1,225 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var debug = require('debug')('express:router:route'); +var flatten = require('array-flatten'); +var Layer = require('./layer'); +var methods = require('methods'); + +/** + * Module variables. + * @private + */ + +var slice = Array.prototype.slice; +var toString = Object.prototype.toString; + +/** + * Module exports. + * @public + */ + +module.exports = Route; + +/** + * Initialize `Route` with the given `path`, + * + * @param {String} path + * @public + */ + +function Route(path) { + this.path = path; + this.stack = []; + + debug('new %o', path) + + // route handlers for various http methods + this.methods = {}; +} + +/** + * Determine if the route handles a given method. + * @private + */ + +Route.prototype._handles_method = function _handles_method(method) { + if (this.methods._all) { + return true; + } + + var name = method.toLowerCase(); + + if (name === 'head' && !this.methods['head']) { + name = 'get'; + } + + return Boolean(this.methods[name]); +}; + +/** + * @return {Array} supported HTTP methods + * @private + */ + +Route.prototype._options = function _options() { + var methods = Object.keys(this.methods); + + // append automatic head + if (this.methods.get && !this.methods.head) { + methods.push('head'); + } + + for (var i = 0; i < methods.length; i++) { + // make upper case + methods[i] = methods[i].toUpperCase(); + } + + return methods; +}; + +/** + * dispatch req, res into this route + * @private + */ + +Route.prototype.dispatch = function dispatch(req, res, done) { + var idx = 0; + var stack = this.stack; + var sync = 0 + + if (stack.length === 0) { + return done(); + } + + var method = req.method.toLowerCase(); + if (method === 'head' && !this.methods['head']) { + method = 'get'; + } + + req.route = this; + + next(); + + function next(err) { + // signal to exit route + if (err && err === 'route') { + return done(); + } + + // signal to exit router + if (err && err === 'router') { + return done(err) + } + + // max sync stack + if (++sync > 100) { + return setImmediate(next, err) + } + + var layer = stack[idx++] + + // end of layers + if (!layer) { + return done(err) + } + + if (layer.method && layer.method !== method) { + next(err) + } else if (err) { + layer.handle_error(err, req, res, next); + } else { + layer.handle_request(req, res, next); + } + + sync = 0 + } +}; + +/** + * Add a handler for all HTTP verbs to this route. + * + * Behaves just like middleware and can respond or call `next` + * to continue processing. + * + * You can use multiple `.all` call to add multiple handlers. + * + * function check_something(req, res, next){ + * next(); + * }; + * + * function validate_user(req, res, next){ + * next(); + * }; + * + * route + * .all(validate_user) + * .all(check_something) + * .get(function(req, res, next){ + * res.send('hello world'); + * }); + * + * @param {function} handler + * @return {Route} for chaining + * @api public + */ + +Route.prototype.all = function all() { + var handles = flatten(slice.call(arguments)); + + for (var i = 0; i < handles.length; i++) { + var handle = handles[i]; + + if (typeof handle !== 'function') { + var type = toString.call(handle); + var msg = 'Route.all() requires a callback function but got a ' + type + throw new TypeError(msg); + } + + var layer = Layer('/', {}, handle); + layer.method = undefined; + + this.methods._all = true; + this.stack.push(layer); + } + + return this; +}; + +methods.forEach(function(method){ + Route.prototype[method] = function(){ + var handles = flatten(slice.call(arguments)); + + for (var i = 0; i < handles.length; i++) { + var handle = handles[i]; + + if (typeof handle !== 'function') { + var type = toString.call(handle); + var msg = 'Route.' + method + '() requires a callback function but got a ' + type + throw new Error(msg); + } + + debug('%s %o', method, this.path) + + var layer = Layer('/', {}, handle); + layer.method = method; + + this.methods[method] = true; + this.stack.push(layer); + } + + return this; + }; +}); diff --git a/system/login/node_modules/express/lib/utils.js b/system/login/node_modules/express/lib/utils.js new file mode 100644 index 0000000..799a6a2 --- /dev/null +++ b/system/login/node_modules/express/lib/utils.js @@ -0,0 +1,304 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @api private + */ + +var Buffer = require('safe-buffer').Buffer +var contentDisposition = require('content-disposition'); +var contentType = require('content-type'); +var deprecate = require('depd')('express'); +var flatten = require('array-flatten'); +var mime = require('send').mime; +var etag = require('etag'); +var proxyaddr = require('proxy-addr'); +var qs = require('qs'); +var querystring = require('querystring'); + +/** + * Return strong ETag for `body`. + * + * @param {String|Buffer} body + * @param {String} [encoding] + * @return {String} + * @api private + */ + +exports.etag = createETagGenerator({ weak: false }) + +/** + * Return weak ETag for `body`. + * + * @param {String|Buffer} body + * @param {String} [encoding] + * @return {String} + * @api private + */ + +exports.wetag = createETagGenerator({ weak: true }) + +/** + * Check if `path` looks absolute. + * + * @param {String} path + * @return {Boolean} + * @api private + */ + +exports.isAbsolute = function(path){ + if ('/' === path[0]) return true; + if (':' === path[1] && ('\\' === path[2] || '/' === path[2])) return true; // Windows device path + if ('\\\\' === path.substring(0, 2)) return true; // Microsoft Azure absolute path +}; + +/** + * Flatten the given `arr`. + * + * @param {Array} arr + * @return {Array} + * @api private + */ + +exports.flatten = deprecate.function(flatten, + 'utils.flatten: use array-flatten npm module instead'); + +/** + * Normalize the given `type`, for example "html" becomes "text/html". + * + * @param {String} type + * @return {Object} + * @api private + */ + +exports.normalizeType = function(type){ + return ~type.indexOf('/') + ? acceptParams(type) + : { value: mime.lookup(type), params: {} }; +}; + +/** + * Normalize `types`, for example "html" becomes "text/html". + * + * @param {Array} types + * @return {Array} + * @api private + */ + +exports.normalizeTypes = function(types){ + var ret = []; + + for (var i = 0; i < types.length; ++i) { + ret.push(exports.normalizeType(types[i])); + } + + return ret; +}; + +/** + * Generate Content-Disposition header appropriate for the filename. + * non-ascii filenames are urlencoded and a filename* parameter is added + * + * @param {String} filename + * @return {String} + * @api private + */ + +exports.contentDisposition = deprecate.function(contentDisposition, + 'utils.contentDisposition: use content-disposition npm module instead'); + +/** + * Parse accept params `str` returning an + * object with `.value`, `.quality` and `.params`. + * also includes `.originalIndex` for stable sorting + * + * @param {String} str + * @param {Number} index + * @return {Object} + * @api private + */ + +function acceptParams(str, index) { + var parts = str.split(/ *; */); + var ret = { value: parts[0], quality: 1, params: {}, originalIndex: index }; + + for (var i = 1; i < parts.length; ++i) { + var pms = parts[i].split(/ *= */); + if ('q' === pms[0]) { + ret.quality = parseFloat(pms[1]); + } else { + ret.params[pms[0]] = pms[1]; + } + } + + return ret; +} + +/** + * Compile "etag" value to function. + * + * @param {Boolean|String|Function} val + * @return {Function} + * @api private + */ + +exports.compileETag = function(val) { + var fn; + + if (typeof val === 'function') { + return val; + } + + switch (val) { + case true: + case 'weak': + fn = exports.wetag; + break; + case false: + break; + case 'strong': + fn = exports.etag; + break; + default: + throw new TypeError('unknown value for etag function: ' + val); + } + + return fn; +} + +/** + * Compile "query parser" value to function. + * + * @param {String|Function} val + * @return {Function} + * @api private + */ + +exports.compileQueryParser = function compileQueryParser(val) { + var fn; + + if (typeof val === 'function') { + return val; + } + + switch (val) { + case true: + case 'simple': + fn = querystring.parse; + break; + case false: + fn = newObject; + break; + case 'extended': + fn = parseExtendedQueryString; + break; + default: + throw new TypeError('unknown value for query parser function: ' + val); + } + + return fn; +} + +/** + * Compile "proxy trust" value to function. + * + * @param {Boolean|String|Number|Array|Function} val + * @return {Function} + * @api private + */ + +exports.compileTrust = function(val) { + if (typeof val === 'function') return val; + + if (val === true) { + // Support plain true/false + return function(){ return true }; + } + + if (typeof val === 'number') { + // Support trusting hop count + return function(a, i){ return i < val }; + } + + if (typeof val === 'string') { + // Support comma-separated values + val = val.split(',') + .map(function (v) { return v.trim() }) + } + + return proxyaddr.compile(val || []); +} + +/** + * Set the charset in a given Content-Type string. + * + * @param {String} type + * @param {String} charset + * @return {String} + * @api private + */ + +exports.setCharset = function setCharset(type, charset) { + if (!type || !charset) { + return type; + } + + // parse type + var parsed = contentType.parse(type); + + // set charset + parsed.parameters.charset = charset; + + // format type + return contentType.format(parsed); +}; + +/** + * Create an ETag generator function, generating ETags with + * the given options. + * + * @param {object} options + * @return {function} + * @private + */ + +function createETagGenerator (options) { + return function generateETag (body, encoding) { + var buf = !Buffer.isBuffer(body) + ? Buffer.from(body, encoding) + : body + + return etag(buf, options) + } +} + +/** + * Parse an extended query string with qs. + * + * @return {Object} + * @private + */ + +function parseExtendedQueryString(str) { + return qs.parse(str, { + allowPrototypes: true + }); +} + +/** + * Return new empty object. + * + * @return {Object} + * @api private + */ + +function newObject() { + return {}; +} diff --git a/system/login/node_modules/express/lib/view.js b/system/login/node_modules/express/lib/view.js new file mode 100644 index 0000000..c08ab4d --- /dev/null +++ b/system/login/node_modules/express/lib/view.js @@ -0,0 +1,182 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var debug = require('debug')('express:view'); +var path = require('path'); +var fs = require('fs'); + +/** + * Module variables. + * @private + */ + +var dirname = path.dirname; +var basename = path.basename; +var extname = path.extname; +var join = path.join; +var resolve = path.resolve; + +/** + * Module exports. + * @public + */ + +module.exports = View; + +/** + * Initialize a new `View` with the given `name`. + * + * Options: + * + * - `defaultEngine` the default template engine name + * - `engines` template engine require() cache + * - `root` root path for view lookup + * + * @param {string} name + * @param {object} options + * @public + */ + +function View(name, options) { + var opts = options || {}; + + this.defaultEngine = opts.defaultEngine; + this.ext = extname(name); + this.name = name; + this.root = opts.root; + + if (!this.ext && !this.defaultEngine) { + throw new Error('No default engine was specified and no extension was provided.'); + } + + var fileName = name; + + if (!this.ext) { + // get extension from default engine name + this.ext = this.defaultEngine[0] !== '.' + ? '.' + this.defaultEngine + : this.defaultEngine; + + fileName += this.ext; + } + + if (!opts.engines[this.ext]) { + // load engine + var mod = this.ext.slice(1) + debug('require "%s"', mod) + + // default engine export + var fn = require(mod).__express + + if (typeof fn !== 'function') { + throw new Error('Module "' + mod + '" does not provide a view engine.') + } + + opts.engines[this.ext] = fn + } + + // store loaded engine + this.engine = opts.engines[this.ext]; + + // lookup path + this.path = this.lookup(fileName); +} + +/** + * Lookup view by the given `name` + * + * @param {string} name + * @private + */ + +View.prototype.lookup = function lookup(name) { + var path; + var roots = [].concat(this.root); + + debug('lookup "%s"', name); + + for (var i = 0; i < roots.length && !path; i++) { + var root = roots[i]; + + // resolve the path + var loc = resolve(root, name); + var dir = dirname(loc); + var file = basename(loc); + + // resolve the file + path = this.resolve(dir, file); + } + + return path; +}; + +/** + * Render with the given options. + * + * @param {object} options + * @param {function} callback + * @private + */ + +View.prototype.render = function render(options, callback) { + debug('render "%s"', this.path); + this.engine(this.path, options, callback); +}; + +/** + * Resolve the file within the given directory. + * + * @param {string} dir + * @param {string} file + * @private + */ + +View.prototype.resolve = function resolve(dir, file) { + var ext = this.ext; + + // . + var path = join(dir, file); + var stat = tryStat(path); + + if (stat && stat.isFile()) { + return path; + } + + // /index. + path = join(dir, basename(file, ext), 'index' + ext); + stat = tryStat(path); + + if (stat && stat.isFile()) { + return path; + } +}; + +/** + * Return a stat, maybe. + * + * @param {string} path + * @return {fs.Stats} + * @private + */ + +function tryStat(path) { + debug('stat "%s"', path); + + try { + return fs.statSync(path); + } catch (e) { + return undefined; + } +} diff --git a/system/login/node_modules/express/node_modules/body-parser/HISTORY.md b/system/login/node_modules/express/node_modules/body-parser/HISTORY.md new file mode 100644 index 0000000..fb212b3 --- /dev/null +++ b/system/login/node_modules/express/node_modules/body-parser/HISTORY.md @@ -0,0 +1,657 @@ +1.20.1 / 2022-10-06 +=================== + + * deps: qs@6.11.0 + * perf: remove unnecessary object clone + +1.20.0 / 2022-04-02 +=================== + + * Fix error message for json parse whitespace in `strict` + * Fix internal error when inflated body exceeds limit + * Prevent loss of async hooks context + * Prevent hanging when request already read + * deps: depd@2.0.0 + - Replace internal `eval` usage with `Function` constructor + - Use instance methods on `process` to check for listeners + * deps: http-errors@2.0.0 + - deps: depd@2.0.0 + - deps: statuses@2.0.1 + * deps: on-finished@2.4.1 + * deps: qs@6.10.3 + * deps: raw-body@2.5.1 + - deps: http-errors@2.0.0 + +1.19.2 / 2022-02-15 +=================== + + * deps: bytes@3.1.2 + * deps: qs@6.9.7 + * Fix handling of `__proto__` keys + * deps: raw-body@2.4.3 + - deps: bytes@3.1.2 + +1.19.1 / 2021-12-10 +=================== + + * deps: bytes@3.1.1 + * deps: http-errors@1.8.1 + - deps: inherits@2.0.4 + - deps: toidentifier@1.0.1 + - deps: setprototypeof@1.2.0 + * deps: qs@6.9.6 + * deps: raw-body@2.4.2 + - deps: bytes@3.1.1 + - deps: http-errors@1.8.1 + * deps: safe-buffer@5.2.1 + * deps: type-is@~1.6.18 + +1.19.0 / 2019-04-25 +=================== + + * deps: bytes@3.1.0 + - Add petabyte (`pb`) support + * deps: http-errors@1.7.2 + - Set constructor name when possible + - deps: setprototypeof@1.1.1 + - deps: statuses@'>= 1.5.0 < 2' + * deps: iconv-lite@0.4.24 + - Added encoding MIK + * deps: qs@6.7.0 + - Fix parsing array brackets after index + * deps: raw-body@2.4.0 + - deps: bytes@3.1.0 + - deps: http-errors@1.7.2 + - deps: iconv-lite@0.4.24 + * deps: type-is@~1.6.17 + - deps: mime-types@~2.1.24 + - perf: prevent internal `throw` on invalid type + +1.18.3 / 2018-05-14 +=================== + + * Fix stack trace for strict json parse error + * deps: depd@~1.1.2 + - perf: remove argument reassignment + * deps: http-errors@~1.6.3 + - deps: depd@~1.1.2 + - deps: setprototypeof@1.1.0 + - deps: statuses@'>= 1.3.1 < 2' + * deps: iconv-lite@0.4.23 + - Fix loading encoding with year appended + - Fix deprecation warnings on Node.js 10+ + * deps: qs@6.5.2 + * deps: raw-body@2.3.3 + - deps: http-errors@1.6.3 + - deps: iconv-lite@0.4.23 + * deps: type-is@~1.6.16 + - deps: mime-types@~2.1.18 + +1.18.2 / 2017-09-22 +=================== + + * deps: debug@2.6.9 + * perf: remove argument reassignment + +1.18.1 / 2017-09-12 +=================== + + * deps: content-type@~1.0.4 + - perf: remove argument reassignment + - perf: skip parameter parsing when no parameters + * deps: iconv-lite@0.4.19 + - Fix ISO-8859-1 regression + - Update Windows-1255 + * deps: qs@6.5.1 + - Fix parsing & compacting very deep objects + * deps: raw-body@2.3.2 + - deps: iconv-lite@0.4.19 + +1.18.0 / 2017-09-08 +=================== + + * Fix JSON strict violation error to match native parse error + * Include the `body` property on verify errors + * Include the `type` property on all generated errors + * Use `http-errors` to set status code on errors + * deps: bytes@3.0.0 + * deps: debug@2.6.8 + * deps: depd@~1.1.1 + - Remove unnecessary `Buffer` loading + * deps: http-errors@~1.6.2 + - deps: depd@1.1.1 + * deps: iconv-lite@0.4.18 + - Add support for React Native + - Add a warning if not loaded as utf-8 + - Fix CESU-8 decoding in Node.js 8 + - Improve speed of ISO-8859-1 encoding + * deps: qs@6.5.0 + * deps: raw-body@2.3.1 + - Use `http-errors` for standard emitted errors + - deps: bytes@3.0.0 + - deps: iconv-lite@0.4.18 + - perf: skip buffer decoding on overage chunk + * perf: prevent internal `throw` when missing charset + +1.17.2 / 2017-05-17 +=================== + + * deps: debug@2.6.7 + - Fix `DEBUG_MAX_ARRAY_LENGTH` + - deps: ms@2.0.0 + * deps: type-is@~1.6.15 + - deps: mime-types@~2.1.15 + +1.17.1 / 2017-03-06 +=================== + + * deps: qs@6.4.0 + - Fix regression parsing keys starting with `[` + +1.17.0 / 2017-03-01 +=================== + + * deps: http-errors@~1.6.1 + - Make `message` property enumerable for `HttpError`s + - deps: setprototypeof@1.0.3 + * deps: qs@6.3.1 + - Fix compacting nested arrays + +1.16.1 / 2017-02-10 +=================== + + * deps: debug@2.6.1 + - Fix deprecation messages in WebStorm and other editors + - Undeprecate `DEBUG_FD` set to `1` or `2` + +1.16.0 / 2017-01-17 +=================== + + * 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 + * deps: http-errors@~1.5.1 + - deps: inherits@2.0.3 + - deps: setprototypeof@1.0.2 + - deps: statuses@'>= 1.3.1 < 2' + * deps: iconv-lite@0.4.15 + - Added encoding MS-31J + - Added encoding MS-932 + - Added encoding MS-936 + - Added encoding MS-949 + - Added encoding MS-950 + - Fix GBK/GB18030 handling of Euro character + * deps: qs@6.2.1 + - Fix array parsing from skipping empty values + * deps: raw-body@~2.2.0 + - deps: iconv-lite@0.4.15 + * deps: type-is@~1.6.14 + - deps: mime-types@~2.1.13 + +1.15.2 / 2016-06-19 +=================== + + * deps: bytes@2.4.0 + * deps: content-type@~1.0.2 + - perf: enable strict mode + * deps: http-errors@~1.5.0 + - Use `setprototypeof` module to replace `__proto__` setting + - deps: statuses@'>= 1.3.0 < 2' + - perf: enable strict mode + * deps: qs@6.2.0 + * deps: raw-body@~2.1.7 + - deps: bytes@2.4.0 + - perf: remove double-cleanup on happy path + * deps: type-is@~1.6.13 + - deps: mime-types@~2.1.11 + +1.15.1 / 2016-05-05 +=================== + + * deps: bytes@2.3.0 + - Drop partial bytes on all parsed units + - Fix parsing byte string that looks like hex + * deps: raw-body@~2.1.6 + - deps: bytes@2.3.0 + * deps: type-is@~1.6.12 + - deps: mime-types@~2.1.10 + +1.15.0 / 2016-02-10 +=================== + + * deps: http-errors@~1.4.0 + - Add `HttpError` export, for `err instanceof createError.HttpError` + - deps: inherits@2.0.1 + - deps: statuses@'>= 1.2.1 < 2' + * deps: qs@6.1.0 + * deps: type-is@~1.6.11 + - deps: mime-types@~2.1.9 + +1.14.2 / 2015-12-16 +=================== + + * deps: bytes@2.2.0 + * deps: iconv-lite@0.4.13 + * deps: qs@5.2.0 + * deps: raw-body@~2.1.5 + - deps: bytes@2.2.0 + - deps: iconv-lite@0.4.13 + * deps: type-is@~1.6.10 + - deps: mime-types@~2.1.8 + +1.14.1 / 2015-09-27 +=================== + + * Fix issue where invalid charset results in 400 when `verify` used + * deps: iconv-lite@0.4.12 + - Fix CESU-8 decoding in Node.js 4.x + * deps: raw-body@~2.1.4 + - Fix masking critical errors from `iconv-lite` + - deps: iconv-lite@0.4.12 + * deps: type-is@~1.6.9 + - deps: mime-types@~2.1.7 + +1.14.0 / 2015-09-16 +=================== + + * Fix JSON strict parse error to match syntax errors + * Provide static `require` analysis in `urlencoded` parser + * deps: depd@~1.1.0 + - Support web browser loading + * deps: qs@5.1.0 + * deps: raw-body@~2.1.3 + - Fix sync callback when attaching data listener causes sync read + * deps: type-is@~1.6.8 + - Fix type error when given invalid type to match against + - deps: mime-types@~2.1.6 + +1.13.3 / 2015-07-31 +=================== + + * deps: type-is@~1.6.6 + - deps: mime-types@~2.1.4 + +1.13.2 / 2015-07-05 +=================== + + * deps: iconv-lite@0.4.11 + * deps: qs@4.0.0 + - Fix dropping parameters like `hasOwnProperty` + - Fix user-visible incompatibilities from 3.1.0 + - Fix various parsing edge cases + * deps: raw-body@~2.1.2 + - Fix error stack traces to skip `makeError` + - deps: iconv-lite@0.4.11 + * deps: type-is@~1.6.4 + - deps: mime-types@~2.1.2 + - perf: enable strict mode + - perf: remove argument reassignment + +1.13.1 / 2015-06-16 +=================== + + * deps: qs@2.4.2 + - Downgraded from 3.1.0 because of user-visible incompatibilities + +1.13.0 / 2015-06-14 +=================== + + * Add `statusCode` property on `Error`s, in addition to `status` + * Change `type` default to `application/json` for JSON parser + * Change `type` default to `application/x-www-form-urlencoded` for urlencoded parser + * Provide static `require` analysis + * Use the `http-errors` module to generate errors + * deps: bytes@2.1.0 + - Slight optimizations + * deps: iconv-lite@0.4.10 + - The encoding UTF-16 without BOM now defaults to UTF-16LE when detection fails + - Leading BOM is now removed when decoding + * 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 + * deps: qs@3.1.0 + - Fix dropping parameters like `hasOwnProperty` + - Fix various parsing edge cases + - Parsed object now has `null` prototype + * deps: raw-body@~2.1.1 + - Use `unpipe` module for unpiping requests + - deps: iconv-lite@0.4.10 + * deps: type-is@~1.6.3 + - deps: mime-types@~2.1.1 + - perf: reduce try block size + - perf: remove bitwise operations + * perf: enable strict mode + * perf: remove argument reassignment + * perf: remove delete call + +1.12.4 / 2015-05-10 +=================== + + * deps: debug@~2.2.0 + * deps: qs@2.4.2 + - Fix allowing parameters like `constructor` + * deps: on-finished@~2.2.1 + * deps: raw-body@~2.0.1 + - Fix a false-positive when unpiping in Node.js 0.8 + - deps: bytes@2.0.1 + * deps: type-is@~1.6.2 + - deps: mime-types@~2.0.11 + +1.12.3 / 2015-04-15 +=================== + + * Slight efficiency improvement when not debugging + * deps: depd@~1.0.1 + * deps: iconv-lite@0.4.8 + - Add encoding alias UNICODE-1-1-UTF-7 + * deps: raw-body@1.3.4 + - Fix hanging callback if request aborts during read + - deps: iconv-lite@0.4.8 + +1.12.2 / 2015-03-16 +=================== + + * deps: qs@2.4.1 + - Fix error when parameter `hasOwnProperty` is present + +1.12.1 / 2015-03-15 +=================== + + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + * deps: type-is@~1.6.1 + - deps: mime-types@~2.0.10 + +1.12.0 / 2015-02-13 +=================== + + * add `debug` messages + * accept a function for the `type` option + * use `content-type` to parse `Content-Type` headers + * deps: iconv-lite@0.4.7 + - Gracefully support enumerables on `Object.prototype` + * deps: raw-body@1.3.3 + - deps: iconv-lite@0.4.7 + * deps: type-is@~1.6.0 + - fix argument reassignment + - fix false-positives in `hasBody` `Transfer-Encoding` check + - support wildcard for both type and subtype (`*/*`) + - deps: mime-types@~2.0.9 + +1.11.0 / 2015-01-30 +=================== + + * make internal `extended: true` depth limit infinity + * deps: type-is@~1.5.6 + - deps: mime-types@~2.0.8 + +1.10.2 / 2015-01-20 +=================== + + * deps: iconv-lite@0.4.6 + - Fix rare aliases of single-byte encodings + * deps: raw-body@1.3.2 + - deps: iconv-lite@0.4.6 + +1.10.1 / 2015-01-01 +=================== + + * deps: on-finished@~2.2.0 + * deps: type-is@~1.5.5 + - deps: mime-types@~2.0.7 + +1.10.0 / 2014-12-02 +=================== + + * make internal `extended: true` array limit dynamic + +1.9.3 / 2014-11-21 +================== + + * deps: iconv-lite@0.4.5 + - Fix Windows-31J and X-SJIS encoding support + * deps: qs@2.3.3 + - Fix `arrayLimit` behavior + * deps: raw-body@1.3.1 + - deps: iconv-lite@0.4.5 + * deps: type-is@~1.5.3 + - deps: mime-types@~2.0.3 + +1.9.2 / 2014-10-27 +================== + + * deps: qs@2.3.2 + - Fix parsing of mixed objects and values + +1.9.1 / 2014-10-22 +================== + + * deps: on-finished@~2.1.1 + - Fix handling of pipelined requests + * deps: qs@2.3.0 + - Fix parsing of mixed implicit and explicit arrays + * deps: type-is@~1.5.2 + - deps: mime-types@~2.0.2 + +1.9.0 / 2014-09-24 +================== + + * include the charset in "unsupported charset" error message + * include the encoding in "unsupported content encoding" error message + * deps: depd@~1.0.0 + +1.8.4 / 2014-09-23 +================== + + * fix content encoding to be case-insensitive + +1.8.3 / 2014-09-19 +================== + + * deps: qs@2.2.4 + - Fix issue with object keys starting with numbers truncated + +1.8.2 / 2014-09-15 +================== + + * deps: depd@0.4.5 + +1.8.1 / 2014-09-07 +================== + + * deps: media-typer@0.3.0 + * deps: type-is@~1.5.1 + +1.8.0 / 2014-09-05 +================== + + * make empty-body-handling consistent between chunked requests + - empty `json` produces `{}` + - empty `raw` produces `new Buffer(0)` + - empty `text` produces `''` + - empty `urlencoded` produces `{}` + * deps: qs@2.2.3 + - Fix issue where first empty value in array is discarded + * deps: type-is@~1.5.0 + - fix `hasbody` to be true for `content-length: 0` + +1.7.0 / 2014-09-01 +================== + + * add `parameterLimit` option to `urlencoded` parser + * change `urlencoded` extended array limit to 100 + * respond with 413 when over `parameterLimit` in `urlencoded` + +1.6.7 / 2014-08-29 +================== + + * deps: qs@2.2.2 + - Remove unnecessary cloning + +1.6.6 / 2014-08-27 +================== + + * deps: qs@2.2.0 + - Array parsing fix + - Performance improvements + +1.6.5 / 2014-08-16 +================== + + * deps: on-finished@2.1.0 + +1.6.4 / 2014-08-14 +================== + + * deps: qs@1.2.2 + +1.6.3 / 2014-08-10 +================== + + * deps: qs@1.2.1 + +1.6.2 / 2014-08-07 +================== + + * deps: qs@1.2.0 + - Fix parsing array of objects + +1.6.1 / 2014-08-06 +================== + + * deps: qs@1.1.0 + - Accept urlencoded square brackets + - Accept empty values in implicit array notation + +1.6.0 / 2014-08-05 +================== + + * deps: qs@1.0.2 + - Complete rewrite + - Limits array length to 20 + - Limits object depth to 5 + - Limits parameters to 1,000 + +1.5.2 / 2014-07-27 +================== + + * deps: depd@0.4.4 + - Work-around v8 generating empty stack traces + +1.5.1 / 2014-07-26 +================== + + * deps: depd@0.4.3 + - Fix exception when global `Error.stackTraceLimit` is too low + +1.5.0 / 2014-07-20 +================== + + * deps: depd@0.4.2 + - Add `TRACE_DEPRECATION` environment variable + - Remove non-standard grey color from color output + - Support `--no-deprecation` argument + - Support `--trace-deprecation` argument + * deps: iconv-lite@0.4.4 + - Added encoding UTF-7 + * deps: raw-body@1.3.0 + - deps: iconv-lite@0.4.4 + - Added encoding UTF-7 + - Fix `Cannot switch to old mode now` error on Node.js 0.10+ + * deps: type-is@~1.3.2 + +1.4.3 / 2014-06-19 +================== + + * deps: type-is@1.3.1 + - fix global variable leak + +1.4.2 / 2014-06-19 +================== + + * deps: type-is@1.3.0 + - improve type parsing + +1.4.1 / 2014-06-19 +================== + + * fix urlencoded extended deprecation message + +1.4.0 / 2014-06-19 +================== + + * add `text` parser + * add `raw` parser + * check accepted charset in content-type (accepts utf-8) + * check accepted encoding in content-encoding (accepts identity) + * deprecate `bodyParser()` middleware; use `.json()` and `.urlencoded()` as needed + * deprecate `urlencoded()` without provided `extended` option + * lazy-load urlencoded parsers + * parsers split into files for reduced mem usage + * support gzip and deflate bodies + - set `inflate: false` to turn off + * deps: raw-body@1.2.2 + - Support all encodings from `iconv-lite` + +1.3.1 / 2014-06-11 +================== + + * deps: type-is@1.2.1 + - Switch dependency from mime to mime-types@1.0.0 + +1.3.0 / 2014-05-31 +================== + + * add `extended` option to urlencoded parser + +1.2.2 / 2014-05-27 +================== + + * deps: raw-body@1.1.6 + - assert stream encoding on node.js 0.8 + - assert stream encoding on node.js < 0.10.6 + - deps: bytes@1 + +1.2.1 / 2014-05-26 +================== + + * invoke `next(err)` after request fully read + - prevents hung responses and socket hang ups + +1.2.0 / 2014-05-11 +================== + + * add `verify` option + * deps: type-is@1.2.0 + - support suffix matching + +1.1.2 / 2014-05-11 +================== + + * improve json parser speed + +1.1.1 / 2014-05-11 +================== + + * fix repeated limit parsing with every request + +1.1.0 / 2014-05-10 +================== + + * add `type` option + * deps: pin for safety and consistency + +1.0.2 / 2014-04-14 +================== + + * use `type-is` module + +1.0.1 / 2014-03-20 +================== + + * lower default limits to 100kb diff --git a/system/login/node_modules/express/node_modules/body-parser/LICENSE b/system/login/node_modules/express/node_modules/body-parser/LICENSE new file mode 100644 index 0000000..386b7b6 --- /dev/null +++ b/system/login/node_modules/express/node_modules/body-parser/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2014-2015 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/system/login/node_modules/express/node_modules/body-parser/README.md b/system/login/node_modules/express/node_modules/body-parser/README.md new file mode 100644 index 0000000..c507cbb --- /dev/null +++ b/system/login/node_modules/express/node_modules/body-parser/README.md @@ -0,0 +1,464 @@ +# body-parser + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Build Status][github-actions-ci-image]][github-actions-ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Node.js body parsing middleware. + +Parse incoming request bodies in a middleware before your handlers, available +under the `req.body` property. + +**Note** As `req.body`'s shape is based on user-controlled input, all +properties and values in this object are untrusted and should be validated +before trusting. For example, `req.body.foo.toString()` may fail in multiple +ways, for example the `foo` property may not be there or may not be a string, +and `toString` may not be a function and instead a string or other user input. + +[Learn about the anatomy of an HTTP transaction in Node.js](https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/). + +_This does not handle multipart bodies_, due to their complex and typically +large nature. For multipart bodies, you may be interested in the following +modules: + + * [busboy](https://www.npmjs.org/package/busboy#readme) and + [connect-busboy](https://www.npmjs.org/package/connect-busboy#readme) + * [multiparty](https://www.npmjs.org/package/multiparty#readme) and + [connect-multiparty](https://www.npmjs.org/package/connect-multiparty#readme) + * [formidable](https://www.npmjs.org/package/formidable#readme) + * [multer](https://www.npmjs.org/package/multer#readme) + +This module provides the following parsers: + + * [JSON body parser](#bodyparserjsonoptions) + * [Raw body parser](#bodyparserrawoptions) + * [Text body parser](#bodyparsertextoptions) + * [URL-encoded form body parser](#bodyparserurlencodedoptions) + +Other body parsers you might be interested in: + +- [body](https://www.npmjs.org/package/body#readme) +- [co-body](https://www.npmjs.org/package/co-body#readme) + +## Installation + +```sh +$ npm install body-parser +``` + +## API + +```js +var bodyParser = require('body-parser') +``` + +The `bodyParser` object exposes various factories to create middlewares. All +middlewares will populate the `req.body` property with the parsed body when +the `Content-Type` request header matches the `type` option, or an empty +object (`{}`) if there was no body to parse, the `Content-Type` was not matched, +or an error occurred. + +The various errors returned by this module are described in the +[errors section](#errors). + +### bodyParser.json([options]) + +Returns middleware that only parses `json` and only looks at requests where +the `Content-Type` header matches the `type` option. This parser accepts any +Unicode encoding of the body and supports automatic inflation of `gzip` and +`deflate` encodings. + +A new `body` object containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). + +#### Options + +The `json` function takes an optional `options` object that may contain any of +the following keys: + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### reviver + +The `reviver` option is passed directly to `JSON.parse` as the second +argument. You can find more information on this argument +[in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Example.3A_Using_the_reviver_parameter). + +##### strict + +When set to `true`, will only accept arrays and objects; when `false` will +accept anything `JSON.parse` accepts. Defaults to `true`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a string, array of strings, or a function. If not a +function, `type` option is passed directly to the +[type-is](https://www.npmjs.org/package/type-is#readme) library and this can +be an extension name (like `json`), a mime type (like `application/json`), or +a mime type with a wildcard (like `*/*` or `*/json`). If a function, the `type` +option is called as `fn(req)` and the request is parsed if it returns a truthy +value. Defaults to `application/json`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +### bodyParser.raw([options]) + +Returns middleware that parses all bodies as a `Buffer` and only looks at +requests where the `Content-Type` header matches the `type` option. This +parser supports automatic inflation of `gzip` and `deflate` encodings. + +A new `body` object containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). This will be a `Buffer` object +of the body. + +#### Options + +The `raw` function takes an optional `options` object that may contain any of +the following keys: + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a string, array of strings, or a function. +If not a function, `type` option is passed directly to the +[type-is](https://www.npmjs.org/package/type-is#readme) library and this +can be an extension name (like `bin`), a mime type (like +`application/octet-stream`), or a mime type with a wildcard (like `*/*` or +`application/*`). If a function, the `type` option is called as `fn(req)` +and the request is parsed if it returns a truthy value. Defaults to +`application/octet-stream`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +### bodyParser.text([options]) + +Returns middleware that parses all bodies as a string and only looks at +requests where the `Content-Type` header matches the `type` option. This +parser supports automatic inflation of `gzip` and `deflate` encodings. + +A new `body` string containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). This will be a string of the +body. + +#### Options + +The `text` function takes an optional `options` object that may contain any of +the following keys: + +##### defaultCharset + +Specify the default character set for the text content if the charset is not +specified in the `Content-Type` header of the request. Defaults to `utf-8`. + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a string, array of strings, or a function. If not +a function, `type` option is passed directly to the +[type-is](https://www.npmjs.org/package/type-is#readme) library and this can +be an extension name (like `txt`), a mime type (like `text/plain`), or a mime +type with a wildcard (like `*/*` or `text/*`). If a function, the `type` +option is called as `fn(req)` and the request is parsed if it returns a +truthy value. Defaults to `text/plain`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +### bodyParser.urlencoded([options]) + +Returns middleware that only parses `urlencoded` bodies and only looks at +requests where the `Content-Type` header matches the `type` option. This +parser accepts only UTF-8 encoding of the body and supports automatic +inflation of `gzip` and `deflate` encodings. + +A new `body` object containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). This object will contain +key-value pairs, where the value can be a string or array (when `extended` is +`false`), or any type (when `extended` is `true`). + +#### Options + +The `urlencoded` function takes an optional `options` object that may contain +any of the following keys: + +##### extended + +The `extended` option allows to choose between parsing the URL-encoded data +with the `querystring` library (when `false`) or the `qs` library (when +`true`). The "extended" syntax allows for rich objects and arrays to be +encoded into the URL-encoded format, allowing for a JSON-like experience +with URL-encoded. For more information, please +[see the qs library](https://www.npmjs.org/package/qs#readme). + +Defaults to `true`, but using the default has been deprecated. Please +research into the difference between `qs` and `querystring` and choose the +appropriate setting. + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### parameterLimit + +The `parameterLimit` option controls the maximum number of parameters that +are allowed in the URL-encoded data. If a request contains more parameters +than this value, a 413 will be returned to the client. Defaults to `1000`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a string, array of strings, or a function. If not +a function, `type` option is passed directly to the +[type-is](https://www.npmjs.org/package/type-is#readme) library and this can +be an extension name (like `urlencoded`), a mime type (like +`application/x-www-form-urlencoded`), or a mime type with a wildcard (like +`*/x-www-form-urlencoded`). If a function, the `type` option is called as +`fn(req)` and the request is parsed if it returns a truthy value. Defaults +to `application/x-www-form-urlencoded`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +## Errors + +The middlewares provided by this module create errors using the +[`http-errors` module](https://www.npmjs.com/package/http-errors). The errors +will typically have a `status`/`statusCode` property that contains the suggested +HTTP response code, an `expose` property to determine if the `message` property +should be displayed to the client, a `type` property to determine the type of +error without matching against the `message`, and a `body` property containing +the read body, if available. + +The following are the common errors created, though any error can come through +for various reasons. + +### content encoding unsupported + +This error will occur when the request had a `Content-Encoding` header that +contained an encoding but the "inflation" option was set to `false`. The +`status` property is set to `415`, the `type` property is set to +`'encoding.unsupported'`, and the `charset` property will be set to the +encoding that is unsupported. + +### entity parse failed + +This error will occur when the request contained an entity that could not be +parsed by the middleware. The `status` property is set to `400`, the `type` +property is set to `'entity.parse.failed'`, and the `body` property is set to +the entity value that failed parsing. + +### entity verify failed + +This error will occur when the request contained an entity that could not be +failed verification by the defined `verify` option. The `status` property is +set to `403`, the `type` property is set to `'entity.verify.failed'`, and the +`body` property is set to the entity value that failed verification. + +### request aborted + +This error will occur when the request is aborted by the client before reading +the body has finished. The `received` property will be set to the number of +bytes received before the request was aborted and the `expected` property is +set to the number of expected bytes. The `status` property is set to `400` +and `type` property is set to `'request.aborted'`. + +### request entity too large + +This error will occur when the request body's size is larger than the "limit" +option. The `limit` property will be set to the byte limit and the `length` +property will be set to the request body's length. The `status` property is +set to `413` and the `type` property is set to `'entity.too.large'`. + +### request size did not match content length + +This error will occur when the request's length did not match the length from +the `Content-Length` header. This typically occurs when the request is malformed, +typically when the `Content-Length` header was calculated based on characters +instead of bytes. The `status` property is set to `400` and the `type` property +is set to `'request.size.invalid'`. + +### stream encoding should not be set + +This error will occur when something called the `req.setEncoding` method prior +to this middleware. This module operates directly on bytes only and you cannot +call `req.setEncoding` when using this module. The `status` property is set to +`500` and the `type` property is set to `'stream.encoding.set'`. + +### stream is not readable + +This error will occur when the request is no longer readable when this middleware +attempts to read it. This typically means something other than a middleware from +this module read the request body already and the middleware was also configured to +read the same request. The `status` property is set to `500` and the `type` +property is set to `'stream.not.readable'`. + +### too many parameters + +This error will occur when the content of the request exceeds the configured +`parameterLimit` for the `urlencoded` parser. The `status` property is set to +`413` and the `type` property is set to `'parameters.too.many'`. + +### unsupported charset "BOGUS" + +This error will occur when the request had a charset parameter in the +`Content-Type` header, but the `iconv-lite` module does not support it OR the +parser does not support it. The charset is contained in the message as well +as in the `charset` property. The `status` property is set to `415`, the +`type` property is set to `'charset.unsupported'`, and the `charset` property +is set to the charset that is unsupported. + +### unsupported content encoding "bogus" + +This error will occur when the request had a `Content-Encoding` header that +contained an unsupported encoding. The encoding is contained in the message +as well as in the `encoding` property. The `status` property is set to `415`, +the `type` property is set to `'encoding.unsupported'`, and the `encoding` +property is set to the encoding that is unsupported. + +## Examples + +### Express/Connect top-level generic + +This example demonstrates adding a generic JSON and URL-encoded parser as a +top-level middleware, which will parse the bodies of all incoming requests. +This is the simplest setup. + +```js +var express = require('express') +var bodyParser = require('body-parser') + +var app = express() + +// parse application/x-www-form-urlencoded +app.use(bodyParser.urlencoded({ extended: false })) + +// parse application/json +app.use(bodyParser.json()) + +app.use(function (req, res) { + res.setHeader('Content-Type', 'text/plain') + res.write('you posted:\n') + res.end(JSON.stringify(req.body, null, 2)) +}) +``` + +### Express route-specific + +This example demonstrates adding body parsers specifically to the routes that +need them. In general, this is the most recommended way to use body-parser with +Express. + +```js +var express = require('express') +var bodyParser = require('body-parser') + +var app = express() + +// create application/json parser +var jsonParser = bodyParser.json() + +// create application/x-www-form-urlencoded parser +var urlencodedParser = bodyParser.urlencoded({ extended: false }) + +// POST /login gets urlencoded bodies +app.post('/login', urlencodedParser, function (req, res) { + res.send('welcome, ' + req.body.username) +}) + +// POST /api/users gets JSON bodies +app.post('/api/users', jsonParser, function (req, res) { + // create user in req.body +}) +``` + +### Change accepted type for parsers + +All the parsers accept a `type` option which allows you to change the +`Content-Type` that the middleware will parse. + +```js +var express = require('express') +var bodyParser = require('body-parser') + +var app = express() + +// parse various different custom JSON types as JSON +app.use(bodyParser.json({ type: 'application/*+json' })) + +// parse some custom thing into a Buffer +app.use(bodyParser.raw({ type: 'application/vnd.custom-type' })) + +// parse an HTML body into a string +app.use(bodyParser.text({ type: 'text/html' })) +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/body-parser.svg +[npm-url]: https://npmjs.org/package/body-parser +[coveralls-image]: https://img.shields.io/coveralls/expressjs/body-parser/master.svg +[coveralls-url]: https://coveralls.io/r/expressjs/body-parser?branch=master +[downloads-image]: https://img.shields.io/npm/dm/body-parser.svg +[downloads-url]: https://npmjs.org/package/body-parser +[github-actions-ci-image]: https://img.shields.io/github/workflow/status/expressjs/body-parser/ci/master?label=ci +[github-actions-ci-url]: https://github.com/expressjs/body-parser/actions/workflows/ci.yml diff --git a/system/login/node_modules/express/node_modules/body-parser/SECURITY.md b/system/login/node_modules/express/node_modules/body-parser/SECURITY.md new file mode 100644 index 0000000..9694d42 --- /dev/null +++ b/system/login/node_modules/express/node_modules/body-parser/SECURITY.md @@ -0,0 +1,25 @@ +# Security Policies and Procedures + +## Reporting a Bug + +The Express team and community take all security bugs seriously. Thank you +for improving the security of Express. We appreciate your efforts and +responsible disclosure and will make every effort to acknowledge your +contributions. + +Report security bugs by emailing the current owner(s) of `body-parser`. This +information can be found in the npm registry using the command +`npm owner ls body-parser`. +If unsure or unable to get the information from the above, open an issue +in the [project issue tracker](https://github.com/expressjs/body-parser/issues) +asking for the current contact information. + +To ensure the timely response to your report, please ensure that the entirety +of the report is contained within the email body and not solely behind a web +link or an attachment. + +At least one owner will acknowledge your email within 48 hours, and will send a +more detailed response within 48 hours indicating the next steps in handling +your report. After the initial reply to your report, the owners will +endeavor to keep you informed of the progress towards a fix and full +announcement, and may ask for additional information or guidance. diff --git a/system/login/node_modules/express/node_modules/body-parser/index.js b/system/login/node_modules/express/node_modules/body-parser/index.js new file mode 100644 index 0000000..bb24d73 --- /dev/null +++ b/system/login/node_modules/express/node_modules/body-parser/index.js @@ -0,0 +1,156 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var deprecate = require('depd')('body-parser') + +/** + * Cache of loaded parsers. + * @private + */ + +var parsers = Object.create(null) + +/** + * @typedef Parsers + * @type {function} + * @property {function} json + * @property {function} raw + * @property {function} text + * @property {function} urlencoded + */ + +/** + * Module exports. + * @type {Parsers} + */ + +exports = module.exports = deprecate.function(bodyParser, + 'bodyParser: use individual json/urlencoded middlewares') + +/** + * JSON parser. + * @public + */ + +Object.defineProperty(exports, 'json', { + configurable: true, + enumerable: true, + get: createParserGetter('json') +}) + +/** + * Raw parser. + * @public + */ + +Object.defineProperty(exports, 'raw', { + configurable: true, + enumerable: true, + get: createParserGetter('raw') +}) + +/** + * Text parser. + * @public + */ + +Object.defineProperty(exports, 'text', { + configurable: true, + enumerable: true, + get: createParserGetter('text') +}) + +/** + * URL-encoded parser. + * @public + */ + +Object.defineProperty(exports, 'urlencoded', { + configurable: true, + enumerable: true, + get: createParserGetter('urlencoded') +}) + +/** + * Create a middleware to parse json and urlencoded bodies. + * + * @param {object} [options] + * @return {function} + * @deprecated + * @public + */ + +function bodyParser (options) { + // use default type for parsers + var opts = Object.create(options || null, { + type: { + configurable: true, + enumerable: true, + value: undefined, + writable: true + } + }) + + var _urlencoded = exports.urlencoded(opts) + var _json = exports.json(opts) + + return function bodyParser (req, res, next) { + _json(req, res, function (err) { + if (err) return next(err) + _urlencoded(req, res, next) + }) + } +} + +/** + * Create a getter for loading a parser. + * @private + */ + +function createParserGetter (name) { + return function get () { + return loadParser(name) + } +} + +/** + * Load a parser module. + * @private + */ + +function loadParser (parserName) { + var parser = parsers[parserName] + + if (parser !== undefined) { + return parser + } + + // this uses a switch for static require analysis + switch (parserName) { + case 'json': + parser = require('./lib/types/json') + break + case 'raw': + parser = require('./lib/types/raw') + break + case 'text': + parser = require('./lib/types/text') + break + case 'urlencoded': + parser = require('./lib/types/urlencoded') + break + } + + // store to prevent invoking require() + return (parsers[parserName] = parser) +} diff --git a/system/login/node_modules/express/node_modules/body-parser/lib/read.js b/system/login/node_modules/express/node_modules/body-parser/lib/read.js new file mode 100644 index 0000000..fce6283 --- /dev/null +++ b/system/login/node_modules/express/node_modules/body-parser/lib/read.js @@ -0,0 +1,205 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var createError = require('http-errors') +var destroy = require('destroy') +var getBody = require('raw-body') +var iconv = require('iconv-lite') +var onFinished = require('on-finished') +var unpipe = require('unpipe') +var zlib = require('zlib') + +/** + * Module exports. + */ + +module.exports = read + +/** + * Read a request into a buffer and parse. + * + * @param {object} req + * @param {object} res + * @param {function} next + * @param {function} parse + * @param {function} debug + * @param {object} options + * @private + */ + +function read (req, res, next, parse, debug, options) { + var length + var opts = options + var stream + + // flag as parsed + req._body = true + + // read options + var encoding = opts.encoding !== null + ? opts.encoding + : null + var verify = opts.verify + + try { + // get the content stream + stream = contentstream(req, debug, opts.inflate) + length = stream.length + stream.length = undefined + } catch (err) { + return next(err) + } + + // set raw-body options + opts.length = length + opts.encoding = verify + ? null + : encoding + + // assert charset is supported + if (opts.encoding === null && encoding !== null && !iconv.encodingExists(encoding)) { + return next(createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { + charset: encoding.toLowerCase(), + type: 'charset.unsupported' + })) + } + + // read body + debug('read body') + getBody(stream, opts, function (error, body) { + if (error) { + var _error + + if (error.type === 'encoding.unsupported') { + // echo back charset + _error = createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { + charset: encoding.toLowerCase(), + type: 'charset.unsupported' + }) + } else { + // set status code on error + _error = createError(400, error) + } + + // unpipe from stream and destroy + if (stream !== req) { + unpipe(req) + destroy(stream, true) + } + + // read off entire request + dump(req, function onfinished () { + next(createError(400, _error)) + }) + return + } + + // verify + if (verify) { + try { + debug('verify body') + verify(req, res, body, encoding) + } catch (err) { + next(createError(403, err, { + body: body, + type: err.type || 'entity.verify.failed' + })) + return + } + } + + // parse + var str = body + try { + debug('parse body') + str = typeof body !== 'string' && encoding !== null + ? iconv.decode(body, encoding) + : body + req.body = parse(str) + } catch (err) { + next(createError(400, err, { + body: str, + type: err.type || 'entity.parse.failed' + })) + return + } + + next() + }) +} + +/** + * Get the content stream of the request. + * + * @param {object} req + * @param {function} debug + * @param {boolean} [inflate=true] + * @return {object} + * @api private + */ + +function contentstream (req, debug, inflate) { + var encoding = (req.headers['content-encoding'] || 'identity').toLowerCase() + var length = req.headers['content-length'] + var stream + + debug('content-encoding "%s"', encoding) + + if (inflate === false && encoding !== 'identity') { + throw createError(415, 'content encoding unsupported', { + encoding: encoding, + type: 'encoding.unsupported' + }) + } + + switch (encoding) { + case 'deflate': + stream = zlib.createInflate() + debug('inflate body') + req.pipe(stream) + break + case 'gzip': + stream = zlib.createGunzip() + debug('gunzip body') + req.pipe(stream) + break + case 'identity': + stream = req + stream.length = length + break + default: + throw createError(415, 'unsupported content encoding "' + encoding + '"', { + encoding: encoding, + type: 'encoding.unsupported' + }) + } + + return stream +} + +/** + * Dump the contents of a request. + * + * @param {object} req + * @param {function} callback + * @api private + */ + +function dump (req, callback) { + if (onFinished.isFinished(req)) { + callback(null) + } else { + onFinished(req, callback) + req.resume() + } +} diff --git a/system/login/node_modules/express/node_modules/body-parser/lib/types/json.js b/system/login/node_modules/express/node_modules/body-parser/lib/types/json.js new file mode 100644 index 0000000..c2745be --- /dev/null +++ b/system/login/node_modules/express/node_modules/body-parser/lib/types/json.js @@ -0,0 +1,236 @@ +/*! + * body-parser + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var bytes = require('bytes') +var contentType = require('content-type') +var createError = require('http-errors') +var debug = require('debug')('body-parser:json') +var read = require('../read') +var typeis = require('type-is') + +/** + * Module exports. + */ + +module.exports = json + +/** + * RegExp to match the first non-space in a string. + * + * Allowed whitespace is defined in RFC 7159: + * + * ws = *( + * %x20 / ; Space + * %x09 / ; Horizontal tab + * %x0A / ; Line feed or New line + * %x0D ) ; Carriage return + */ + +var FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*([^\x20\x09\x0a\x0d])/ // eslint-disable-line no-control-regex + +/** + * Create a middleware to parse JSON bodies. + * + * @param {object} [options] + * @return {function} + * @public + */ + +function json (options) { + var opts = options || {} + + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var inflate = opts.inflate !== false + var reviver = opts.reviver + var strict = opts.strict !== false + var type = opts.type || 'application/json' + var verify = opts.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + function parse (body) { + if (body.length === 0) { + // special-case empty json body, as it's a common client-side mistake + // TODO: maybe make this configurable or part of "strict" option + return {} + } + + if (strict) { + var first = firstchar(body) + + if (first !== '{' && first !== '[') { + debug('strict violation') + throw createStrictSyntaxError(body, first) + } + } + + try { + debug('parse json') + return JSON.parse(body, reviver) + } catch (e) { + throw normalizeJsonSyntaxError(e, { + message: e.message, + stack: e.stack + }) + } + } + + return function jsonParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return + } + + req.body = req.body || {} + + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return + } + + // assert charset per RFC 7159 sec 8.1 + var charset = getCharset(req) || 'utf-8' + if (charset.slice(0, 4) !== 'utf-') { + debug('invalid charset') + next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', { + charset: charset, + type: 'charset.unsupported' + })) + return + } + + // read + read(req, res, next, parse, debug, { + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} + +/** + * Create strict violation syntax error matching native error. + * + * @param {string} str + * @param {string} char + * @return {Error} + * @private + */ + +function createStrictSyntaxError (str, char) { + var index = str.indexOf(char) + var partial = index !== -1 + ? str.substring(0, index) + '#' + : '' + + try { + JSON.parse(partial); /* istanbul ignore next */ throw new SyntaxError('strict violation') + } catch (e) { + return normalizeJsonSyntaxError(e, { + message: e.message.replace('#', char), + stack: e.stack + }) + } +} + +/** + * Get the first non-whitespace character in a string. + * + * @param {string} str + * @return {function} + * @private + */ + +function firstchar (str) { + var match = FIRST_CHAR_REGEXP.exec(str) + + return match + ? match[1] + : undefined +} + +/** + * Get the charset of a request. + * + * @param {object} req + * @api private + */ + +function getCharset (req) { + try { + return (contentType.parse(req).parameters.charset || '').toLowerCase() + } catch (e) { + return undefined + } +} + +/** + * Normalize a SyntaxError for JSON.parse. + * + * @param {SyntaxError} error + * @param {object} obj + * @return {SyntaxError} + */ + +function normalizeJsonSyntaxError (error, obj) { + var keys = Object.getOwnPropertyNames(error) + + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + if (key !== 'stack' && key !== 'message') { + delete error[key] + } + } + + // replace stack before message for Node.js 0.10 and below + error.stack = obj.stack.replace(error.message, obj.message) + error.message = obj.message + + return error +} + +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ + +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } +} diff --git a/system/login/node_modules/express/node_modules/body-parser/lib/types/raw.js b/system/login/node_modules/express/node_modules/body-parser/lib/types/raw.js new file mode 100644 index 0000000..f5d1b67 --- /dev/null +++ b/system/login/node_modules/express/node_modules/body-parser/lib/types/raw.js @@ -0,0 +1,101 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + */ + +var bytes = require('bytes') +var debug = require('debug')('body-parser:raw') +var read = require('../read') +var typeis = require('type-is') + +/** + * Module exports. + */ + +module.exports = raw + +/** + * Create a middleware to parse raw bodies. + * + * @param {object} [options] + * @return {function} + * @api public + */ + +function raw (options) { + var opts = options || {} + + var inflate = opts.inflate !== false + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var type = opts.type || 'application/octet-stream' + var verify = opts.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + function parse (buf) { + return buf + } + + return function rawParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return + } + + req.body = req.body || {} + + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return + } + + // read + read(req, res, next, parse, debug, { + encoding: null, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} + +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ + +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } +} diff --git a/system/login/node_modules/express/node_modules/body-parser/lib/types/text.js b/system/login/node_modules/express/node_modules/body-parser/lib/types/text.js new file mode 100644 index 0000000..083a009 --- /dev/null +++ b/system/login/node_modules/express/node_modules/body-parser/lib/types/text.js @@ -0,0 +1,121 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + */ + +var bytes = require('bytes') +var contentType = require('content-type') +var debug = require('debug')('body-parser:text') +var read = require('../read') +var typeis = require('type-is') + +/** + * Module exports. + */ + +module.exports = text + +/** + * Create a middleware to parse text bodies. + * + * @param {object} [options] + * @return {function} + * @api public + */ + +function text (options) { + var opts = options || {} + + var defaultCharset = opts.defaultCharset || 'utf-8' + var inflate = opts.inflate !== false + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var type = opts.type || 'text/plain' + var verify = opts.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + function parse (buf) { + return buf + } + + return function textParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return + } + + req.body = req.body || {} + + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return + } + + // get charset + var charset = getCharset(req) || defaultCharset + + // read + read(req, res, next, parse, debug, { + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} + +/** + * Get the charset of a request. + * + * @param {object} req + * @api private + */ + +function getCharset (req) { + try { + return (contentType.parse(req).parameters.charset || '').toLowerCase() + } catch (e) { + return undefined + } +} + +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ + +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } +} diff --git a/system/login/node_modules/express/node_modules/body-parser/lib/types/urlencoded.js b/system/login/node_modules/express/node_modules/body-parser/lib/types/urlencoded.js new file mode 100644 index 0000000..b2ca8f1 --- /dev/null +++ b/system/login/node_modules/express/node_modules/body-parser/lib/types/urlencoded.js @@ -0,0 +1,284 @@ +/*! + * body-parser + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var bytes = require('bytes') +var contentType = require('content-type') +var createError = require('http-errors') +var debug = require('debug')('body-parser:urlencoded') +var deprecate = require('depd')('body-parser') +var read = require('../read') +var typeis = require('type-is') + +/** + * Module exports. + */ + +module.exports = urlencoded + +/** + * Cache of parser modules. + */ + +var parsers = Object.create(null) + +/** + * Create a middleware to parse urlencoded bodies. + * + * @param {object} [options] + * @return {function} + * @public + */ + +function urlencoded (options) { + var opts = options || {} + + // notice because option default will flip in next major + if (opts.extended === undefined) { + deprecate('undefined extended: provide extended option') + } + + var extended = opts.extended !== false + var inflate = opts.inflate !== false + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var type = opts.type || 'application/x-www-form-urlencoded' + var verify = opts.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + // create the appropriate query parser + var queryparse = extended + ? extendedparser(opts) + : simpleparser(opts) + + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + function parse (body) { + return body.length + ? queryparse(body) + : {} + } + + return function urlencodedParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return + } + + req.body = req.body || {} + + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return + } + + // assert charset + var charset = getCharset(req) || 'utf-8' + if (charset !== 'utf-8') { + debug('invalid charset') + next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', { + charset: charset, + type: 'charset.unsupported' + })) + return + } + + // read + read(req, res, next, parse, debug, { + debug: debug, + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} + +/** + * Get the extended query parser. + * + * @param {object} options + */ + +function extendedparser (options) { + var parameterLimit = options.parameterLimit !== undefined + ? options.parameterLimit + : 1000 + var parse = parser('qs') + + if (isNaN(parameterLimit) || parameterLimit < 1) { + throw new TypeError('option parameterLimit must be a positive number') + } + + if (isFinite(parameterLimit)) { + parameterLimit = parameterLimit | 0 + } + + return function queryparse (body) { + var paramCount = parameterCount(body, parameterLimit) + + if (paramCount === undefined) { + debug('too many parameters') + throw createError(413, 'too many parameters', { + type: 'parameters.too.many' + }) + } + + var arrayLimit = Math.max(100, paramCount) + + debug('parse extended urlencoding') + return parse(body, { + allowPrototypes: true, + arrayLimit: arrayLimit, + depth: Infinity, + parameterLimit: parameterLimit + }) + } +} + +/** + * Get the charset of a request. + * + * @param {object} req + * @api private + */ + +function getCharset (req) { + try { + return (contentType.parse(req).parameters.charset || '').toLowerCase() + } catch (e) { + return undefined + } +} + +/** + * Count the number of parameters, stopping once limit reached + * + * @param {string} body + * @param {number} limit + * @api private + */ + +function parameterCount (body, limit) { + var count = 0 + var index = 0 + + while ((index = body.indexOf('&', index)) !== -1) { + count++ + index++ + + if (count === limit) { + return undefined + } + } + + return count +} + +/** + * Get parser for module name dynamically. + * + * @param {string} name + * @return {function} + * @api private + */ + +function parser (name) { + var mod = parsers[name] + + if (mod !== undefined) { + return mod.parse + } + + // this uses a switch for static require analysis + switch (name) { + case 'qs': + mod = require('qs') + break + case 'querystring': + mod = require('querystring') + break + } + + // store to prevent invoking require() + parsers[name] = mod + + return mod.parse +} + +/** + * Get the simple query parser. + * + * @param {object} options + */ + +function simpleparser (options) { + var parameterLimit = options.parameterLimit !== undefined + ? options.parameterLimit + : 1000 + var parse = parser('querystring') + + if (isNaN(parameterLimit) || parameterLimit < 1) { + throw new TypeError('option parameterLimit must be a positive number') + } + + if (isFinite(parameterLimit)) { + parameterLimit = parameterLimit | 0 + } + + return function queryparse (body) { + var paramCount = parameterCount(body, parameterLimit) + + if (paramCount === undefined) { + debug('too many parameters') + throw createError(413, 'too many parameters', { + type: 'parameters.too.many' + }) + } + + debug('parse urlencoding') + return parse(body, undefined, undefined, { maxKeys: parameterLimit }) + } +} + +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ + +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } +} diff --git a/system/login/node_modules/express/node_modules/body-parser/package.json b/system/login/node_modules/express/node_modules/body-parser/package.json new file mode 100644 index 0000000..9cd2ccb --- /dev/null +++ b/system/login/node_modules/express/node_modules/body-parser/package.json @@ -0,0 +1,56 @@ +{ + "name": "body-parser", + "description": "Node.js body parsing middleware", + "version": "1.20.1", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "repository": "expressjs/body-parser", + "dependencies": { + "bytes": "3.1.2", + "content-type": "~1.0.4", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "on-finished": "2.4.1", + "qs": "6.11.0", + "raw-body": "2.5.1", + "type-is": "~1.6.18", + "unpipe": "1.0.0" + }, + "devDependencies": { + "eslint": "8.24.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.26.0", + "eslint-plugin-markdown": "3.0.0", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "6.0.1", + "eslint-plugin-standard": "4.1.0", + "methods": "1.1.2", + "mocha": "10.0.0", + "nyc": "15.1.0", + "safe-buffer": "5.2.1", + "supertest": "6.3.0" + }, + "files": [ + "lib/", + "LICENSE", + "HISTORY.md", + "SECURITY.md", + "index.js" + ], + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --require test/support/env --reporter spec --check-leaks --bail test/", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/system/login/node_modules/express/node_modules/raw-body/HISTORY.md b/system/login/node_modules/express/node_modules/raw-body/HISTORY.md new file mode 100644 index 0000000..0b6b837 --- /dev/null +++ b/system/login/node_modules/express/node_modules/raw-body/HISTORY.md @@ -0,0 +1,303 @@ +2.5.1 / 2022-02-28 +================== + + * Fix error on early async hooks implementations + +2.5.0 / 2022-02-21 +================== + + * Prevent loss of async hooks context + * Prevent hanging when stream is not readable + * deps: http-errors@2.0.0 + - deps: depd@2.0.0 + - deps: statuses@2.0.1 + +2.4.3 / 2022-02-14 +================== + + * deps: bytes@3.1.2 + +2.4.2 / 2021-11-16 +================== + + * deps: bytes@3.1.1 + * deps: http-errors@1.8.1 + - deps: setprototypeof@1.2.0 + - deps: toidentifier@1.0.1 + +2.4.1 / 2019-06-25 +================== + + * deps: http-errors@1.7.3 + - deps: inherits@2.0.4 + +2.4.0 / 2019-04-17 +================== + + * deps: bytes@3.1.0 + - Add petabyte (`pb`) support + * deps: http-errors@1.7.2 + - Set constructor name when possible + - deps: setprototypeof@1.1.1 + - deps: statuses@'>= 1.5.0 < 2' + * deps: iconv-lite@0.4.24 + - Added encoding MIK + +2.3.3 / 2018-05-08 +================== + + * deps: http-errors@1.6.3 + - deps: depd@~1.1.2 + - deps: setprototypeof@1.1.0 + - deps: statuses@'>= 1.3.1 < 2' + * deps: iconv-lite@0.4.23 + - Fix loading encoding with year appended + - Fix deprecation warnings on Node.js 10+ + +2.3.2 / 2017-09-09 +================== + + * deps: iconv-lite@0.4.19 + - Fix ISO-8859-1 regression + - Update Windows-1255 + +2.3.1 / 2017-09-07 +================== + + * deps: bytes@3.0.0 + * deps: http-errors@1.6.2 + - deps: depd@1.1.1 + * perf: skip buffer decoding on overage chunk + +2.3.0 / 2017-08-04 +================== + + * Add TypeScript definitions + * Use `http-errors` for standard emitted errors + * deps: bytes@2.5.0 + * deps: iconv-lite@0.4.18 + - Add support for React Native + - Add a warning if not loaded as utf-8 + - Fix CESU-8 decoding in Node.js 8 + - Improve speed of ISO-8859-1 encoding + +2.2.0 / 2017-01-02 +================== + + * deps: iconv-lite@0.4.15 + - Added encoding MS-31J + - Added encoding MS-932 + - Added encoding MS-936 + - Added encoding MS-949 + - Added encoding MS-950 + - Fix GBK/GB18030 handling of Euro character + +2.1.7 / 2016-06-19 +================== + + * deps: bytes@2.4.0 + * perf: remove double-cleanup on happy path + +2.1.6 / 2016-03-07 +================== + + * deps: bytes@2.3.0 + - Drop partial bytes on all parsed units + - Fix parsing byte string that looks like hex + +2.1.5 / 2015-11-30 +================== + + * deps: bytes@2.2.0 + * deps: iconv-lite@0.4.13 + +2.1.4 / 2015-09-27 +================== + + * Fix masking critical errors from `iconv-lite` + * deps: iconv-lite@0.4.12 + - Fix CESU-8 decoding in Node.js 4.x + +2.1.3 / 2015-09-12 +================== + + * Fix sync callback when attaching data listener causes sync read + - Node.js 0.10 compatibility issue + +2.1.2 / 2015-07-05 +================== + + * Fix error stack traces to skip `makeError` + * deps: iconv-lite@0.4.11 + - Add encoding CESU-8 + +2.1.1 / 2015-06-14 +================== + + * Use `unpipe` module for unpiping requests + +2.1.0 / 2015-05-28 +================== + + * deps: iconv-lite@0.4.10 + - Improved UTF-16 endianness detection + - Leading BOM is now removed when decoding + - The encoding UTF-16 without BOM now defaults to UTF-16LE when detection fails + +2.0.2 / 2015-05-21 +================== + + * deps: bytes@2.1.0 + - Slight optimizations + +2.0.1 / 2015-05-10 +================== + + * Fix a false-positive when unpiping in Node.js 0.8 + +2.0.0 / 2015-05-08 +================== + + * Return a promise without callback instead of thunk + * deps: bytes@2.0.1 + - units no longer case sensitive when parsing + +1.3.4 / 2015-04-15 +================== + + * Fix hanging callback if request aborts during read + * deps: iconv-lite@0.4.8 + - Add encoding alias UNICODE-1-1-UTF-7 + +1.3.3 / 2015-02-08 +================== + + * deps: iconv-lite@0.4.7 + - Gracefully support enumerables on `Object.prototype` + +1.3.2 / 2015-01-20 +================== + + * deps: iconv-lite@0.4.6 + - Fix rare aliases of single-byte encodings + +1.3.1 / 2014-11-21 +================== + + * deps: iconv-lite@0.4.5 + - Fix Windows-31J and X-SJIS encoding support + +1.3.0 / 2014-07-20 +================== + + * Fully unpipe the stream on error + - Fixes `Cannot switch to old mode now` error on Node.js 0.10+ + +1.2.3 / 2014-07-20 +================== + + * deps: iconv-lite@0.4.4 + - Added encoding UTF-7 + +1.2.2 / 2014-06-19 +================== + + * Send invalid encoding error to callback + +1.2.1 / 2014-06-15 +================== + + * deps: iconv-lite@0.4.3 + - Added encodings UTF-16BE and UTF-16 with BOM + +1.2.0 / 2014-06-13 +================== + + * Passing string as `options` interpreted as encoding + * Support all encodings from `iconv-lite` + +1.1.7 / 2014-06-12 +================== + + * use `string_decoder` module from npm + +1.1.6 / 2014-05-27 +================== + + * check encoding for old streams1 + * support node.js < 0.10.6 + +1.1.5 / 2014-05-14 +================== + + * bump bytes + +1.1.4 / 2014-04-19 +================== + + * allow true as an option + * bump bytes + +1.1.3 / 2014-03-02 +================== + + * fix case when length=null + +1.1.2 / 2013-12-01 +================== + + * be less strict on state.encoding check + +1.1.1 / 2013-11-27 +================== + + * add engines + +1.1.0 / 2013-11-27 +================== + + * add err.statusCode and err.type + * allow for encoding option to be true + * pause the stream instead of dumping on error + * throw if the stream's encoding is set + +1.0.1 / 2013-11-19 +================== + + * dont support streams1, throw if dev set encoding + +1.0.0 / 2013-11-17 +================== + + * rename `expected` option to `length` + +0.2.0 / 2013-11-15 +================== + + * republish + +0.1.1 / 2013-11-15 +================== + + * use bytes + +0.1.0 / 2013-11-11 +================== + + * generator support + +0.0.3 / 2013-10-10 +================== + + * update repo + +0.0.2 / 2013-09-14 +================== + + * dump stream on bad headers + * listen to events after defining received and buffers + +0.0.1 / 2013-09-14 +================== + + * Initial release diff --git a/system/login/node_modules/express/node_modules/raw-body/LICENSE b/system/login/node_modules/express/node_modules/raw-body/LICENSE new file mode 100644 index 0000000..1029a7a --- /dev/null +++ b/system/login/node_modules/express/node_modules/raw-body/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2013-2014 Jonathan Ong +Copyright (c) 2014-2022 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/system/login/node_modules/express/node_modules/raw-body/README.md b/system/login/node_modules/express/node_modules/raw-body/README.md new file mode 100644 index 0000000..695c660 --- /dev/null +++ b/system/login/node_modules/express/node_modules/raw-body/README.md @@ -0,0 +1,223 @@ +# raw-body + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build status][github-actions-ci-image]][github-actions-ci-url] +[![Test coverage][coveralls-image]][coveralls-url] + +Gets the entire buffer of a stream either as a `Buffer` or a string. +Validates the stream's length against an expected length and maximum limit. +Ideal for parsing request bodies. + +## Install + +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 raw-body +``` + +### TypeScript + +This module includes a [TypeScript](https://www.typescriptlang.org/) +declaration file to enable auto complete in compatible editors and type +information for TypeScript projects. This module depends on the Node.js +types, so install `@types/node`: + +```sh +$ npm install @types/node +``` + +## API + +```js +var getRawBody = require('raw-body') +``` + +### getRawBody(stream, [options], [callback]) + +**Returns a promise if no callback specified and global `Promise` exists.** + +Options: + +- `length` - The length of the stream. + If the contents of the stream do not add up to this length, + an `400` error code is returned. +- `limit` - The byte limit of the body. + This is the number of bytes or any string format supported by + [bytes](https://www.npmjs.com/package/bytes), + for example `1000`, `'500kb'` or `'3mb'`. + If the body ends up being larger than this limit, + a `413` error code is returned. +- `encoding` - The encoding to use to decode the body into a string. + By default, a `Buffer` instance will be returned when no encoding is specified. + Most likely, you want `utf-8`, so setting `encoding` to `true` will decode as `utf-8`. + You can use any type of encoding supported by [iconv-lite](https://www.npmjs.org/package/iconv-lite#readme). + +You can also pass a string in place of options to just specify the encoding. + +If an error occurs, the stream will be paused, everything unpiped, +and you are responsible for correctly disposing the stream. +For HTTP requests, you may need to finish consuming the stream if +you want to keep the socket open for future requests. For streams +that use file descriptors, you should `stream.destroy()` or +`stream.close()` to prevent leaks. + +## Errors + +This module creates errors depending on the error condition during reading. +The error may be an error from the underlying Node.js implementation, but is +otherwise an error created by this module, which has the following attributes: + + * `limit` - the limit in bytes + * `length` and `expected` - the expected length of the stream + * `received` - the received bytes + * `encoding` - the invalid encoding + * `status` and `statusCode` - the corresponding status code for the error + * `type` - the error type + +### Types + +The errors from this module have a `type` property which allows for the programmatic +determination of the type of error returned. + +#### encoding.unsupported + +This error will occur when the `encoding` option is specified, but the value does +not map to an encoding supported by the [iconv-lite](https://www.npmjs.org/package/iconv-lite#readme) +module. + +#### entity.too.large + +This error will occur when the `limit` option is specified, but the stream has +an entity that is larger. + +#### request.aborted + +This error will occur when the request stream is aborted by the client before +reading the body has finished. + +#### request.size.invalid + +This error will occur when the `length` option is specified, but the stream has +emitted more bytes. + +#### stream.encoding.set + +This error will occur when the given stream has an encoding set on it, making it +a decoded stream. The stream should not have an encoding set and is expected to +emit `Buffer` objects. + +#### stream.not.readable + +This error will occur when the given stream is not readable. + +## Examples + +### Simple Express example + +```js +var contentType = require('content-type') +var express = require('express') +var getRawBody = require('raw-body') + +var app = express() + +app.use(function (req, res, next) { + getRawBody(req, { + length: req.headers['content-length'], + limit: '1mb', + encoding: contentType.parse(req).parameters.charset + }, function (err, string) { + if (err) return next(err) + req.text = string + next() + }) +}) + +// now access req.text +``` + +### Simple Koa example + +```js +var contentType = require('content-type') +var getRawBody = require('raw-body') +var koa = require('koa') + +var app = koa() + +app.use(function * (next) { + this.text = yield getRawBody(this.req, { + length: this.req.headers['content-length'], + limit: '1mb', + encoding: contentType.parse(this.req).parameters.charset + }) + yield next +}) + +// now access this.text +``` + +### Using as a promise + +To use this library as a promise, simply omit the `callback` and a promise is +returned, provided that a global `Promise` is defined. + +```js +var getRawBody = require('raw-body') +var http = require('http') + +var server = http.createServer(function (req, res) { + getRawBody(req) + .then(function (buf) { + res.statusCode = 200 + res.end(buf.length + ' bytes submitted') + }) + .catch(function (err) { + res.statusCode = 500 + res.end(err.message) + }) +}) + +server.listen(3000) +``` + +### Using with TypeScript + +```ts +import * as getRawBody from 'raw-body'; +import * as http from 'http'; + +const server = http.createServer((req, res) => { + getRawBody(req) + .then((buf) => { + res.statusCode = 200; + res.end(buf.length + ' bytes submitted'); + }) + .catch((err) => { + res.statusCode = err.statusCode; + res.end(err.message); + }); +}); + +server.listen(3000); +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/raw-body.svg +[npm-url]: https://npmjs.org/package/raw-body +[node-version-image]: https://img.shields.io/node/v/raw-body.svg +[node-version-url]: https://nodejs.org/en/download/ +[coveralls-image]: https://img.shields.io/coveralls/stream-utils/raw-body/master.svg +[coveralls-url]: https://coveralls.io/r/stream-utils/raw-body?branch=master +[downloads-image]: https://img.shields.io/npm/dm/raw-body.svg +[downloads-url]: https://npmjs.org/package/raw-body +[github-actions-ci-image]: https://img.shields.io/github/workflow/status/stream-utils/raw-body/ci/master?label=ci +[github-actions-ci-url]: https://github.com/jshttp/stream-utils/raw-body?query=workflow%3Aci diff --git a/system/login/node_modules/express/node_modules/raw-body/SECURITY.md b/system/login/node_modules/express/node_modules/raw-body/SECURITY.md new file mode 100644 index 0000000..2421efc --- /dev/null +++ b/system/login/node_modules/express/node_modules/raw-body/SECURITY.md @@ -0,0 +1,24 @@ +# Security Policies and Procedures + +## Reporting a Bug + +The `raw-body` team and community take all security bugs seriously. Thank you +for improving the security of Express. We appreciate your efforts and +responsible disclosure and will make every effort to acknowledge your +contributions. + +Report security bugs by emailing the current owners of `raw-body`. This information +can be found in the npm registry using the command `npm owner ls raw-body`. +If unsure or unable to get the information from the above, open an issue +in the [project issue tracker](https://github.com/stream-utils/raw-body/issues) +asking for the current contact information. + +To ensure the timely response to your report, please ensure that the entirety +of the report is contained within the email body and not solely behind a web +link or an attachment. + +At least one owner will acknowledge your email within 48 hours, and will send a +more detailed response within 48 hours indicating the next steps in handling +your report. After the initial reply to your report, the owners will +endeavor to keep you informed of the progress towards a fix and full +announcement, and may ask for additional information or guidance. diff --git a/system/login/node_modules/express/node_modules/raw-body/index.d.ts b/system/login/node_modules/express/node_modules/raw-body/index.d.ts new file mode 100644 index 0000000..dcbbebd --- /dev/null +++ b/system/login/node_modules/express/node_modules/raw-body/index.d.ts @@ -0,0 +1,87 @@ +import { Readable } from 'stream'; + +declare namespace getRawBody { + export type Encoding = string | true; + + export interface Options { + /** + * The expected length of the stream. + */ + length?: number | string | null; + /** + * The byte limit of the body. This is the number of bytes or any string + * format supported by `bytes`, for example `1000`, `'500kb'` or `'3mb'`. + */ + limit?: number | string | null; + /** + * The encoding to use to decode the body into a string. By default, a + * `Buffer` instance will be returned when no encoding is specified. Most + * likely, you want `utf-8`, so setting encoding to `true` will decode as + * `utf-8`. You can use any type of encoding supported by `iconv-lite`. + */ + encoding?: Encoding | null; + } + + export interface RawBodyError extends Error { + /** + * The limit in bytes. + */ + limit?: number; + /** + * The expected length of the stream. + */ + length?: number; + expected?: number; + /** + * The received bytes. + */ + received?: number; + /** + * The encoding. + */ + encoding?: string; + /** + * The corresponding status code for the error. + */ + status: number; + statusCode: number; + /** + * The error type. + */ + type: string; + } +} + +/** + * Gets the entire buffer of a stream either as a `Buffer` or a string. + * Validates the stream's length against an expected length and maximum + * limit. Ideal for parsing request bodies. + */ +declare function getRawBody( + stream: Readable, + callback: (err: getRawBody.RawBodyError, body: Buffer) => void +): void; + +declare function getRawBody( + stream: Readable, + options: (getRawBody.Options & { encoding: getRawBody.Encoding }) | getRawBody.Encoding, + callback: (err: getRawBody.RawBodyError, body: string) => void +): void; + +declare function getRawBody( + stream: Readable, + options: getRawBody.Options, + callback: (err: getRawBody.RawBodyError, body: Buffer) => void +): void; + +declare function getRawBody( + stream: Readable, + options: (getRawBody.Options & { encoding: getRawBody.Encoding }) | getRawBody.Encoding +): Promise; + +declare function getRawBody( + stream: Readable, + options?: getRawBody.Options +): Promise; + +export = getRawBody; diff --git a/system/login/node_modules/express/node_modules/raw-body/index.js b/system/login/node_modules/express/node_modules/raw-body/index.js new file mode 100644 index 0000000..a8f537f --- /dev/null +++ b/system/login/node_modules/express/node_modules/raw-body/index.js @@ -0,0 +1,329 @@ +/*! + * raw-body + * Copyright(c) 2013-2014 Jonathan Ong + * Copyright(c) 2014-2022 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var asyncHooks = tryRequireAsyncHooks() +var bytes = require('bytes') +var createError = require('http-errors') +var iconv = require('iconv-lite') +var unpipe = require('unpipe') + +/** + * Module exports. + * @public + */ + +module.exports = getRawBody + +/** + * Module variables. + * @private + */ + +var ICONV_ENCODING_MESSAGE_REGEXP = /^Encoding not recognized: / + +/** + * Get the decoder for a given encoding. + * + * @param {string} encoding + * @private + */ + +function getDecoder (encoding) { + if (!encoding) return null + + try { + return iconv.getDecoder(encoding) + } catch (e) { + // error getting decoder + if (!ICONV_ENCODING_MESSAGE_REGEXP.test(e.message)) throw e + + // the encoding was not found + throw createError(415, 'specified encoding unsupported', { + encoding: encoding, + type: 'encoding.unsupported' + }) + } +} + +/** + * Get the raw body of a stream (typically HTTP). + * + * @param {object} stream + * @param {object|string|function} [options] + * @param {function} [callback] + * @public + */ + +function getRawBody (stream, options, callback) { + var done = callback + var opts = options || {} + + if (options === true || typeof options === 'string') { + // short cut for encoding + opts = { + encoding: options + } + } + + if (typeof options === 'function') { + done = options + opts = {} + } + + // validate callback is a function, if provided + if (done !== undefined && typeof done !== 'function') { + throw new TypeError('argument callback must be a function') + } + + // require the callback without promises + if (!done && !global.Promise) { + throw new TypeError('argument callback is required') + } + + // get encoding + var encoding = opts.encoding !== true + ? opts.encoding + : 'utf-8' + + // convert the limit to an integer + var limit = bytes.parse(opts.limit) + + // convert the expected length to an integer + var length = opts.length != null && !isNaN(opts.length) + ? parseInt(opts.length, 10) + : null + + if (done) { + // classic callback style + return readStream(stream, encoding, length, limit, wrap(done)) + } + + return new Promise(function executor (resolve, reject) { + readStream(stream, encoding, length, limit, function onRead (err, buf) { + if (err) return reject(err) + resolve(buf) + }) + }) +} + +/** + * Halt a stream. + * + * @param {Object} stream + * @private + */ + +function halt (stream) { + // unpipe everything from the stream + unpipe(stream) + + // pause stream + if (typeof stream.pause === 'function') { + stream.pause() + } +} + +/** + * Read the data from the stream. + * + * @param {object} stream + * @param {string} encoding + * @param {number} length + * @param {number} limit + * @param {function} callback + * @public + */ + +function readStream (stream, encoding, length, limit, callback) { + var complete = false + var sync = true + + // check the length and limit options. + // note: we intentionally leave the stream paused, + // so users should handle the stream themselves. + if (limit !== null && length !== null && length > limit) { + return done(createError(413, 'request entity too large', { + expected: length, + length: length, + limit: limit, + type: 'entity.too.large' + })) + } + + // streams1: assert request encoding is buffer. + // streams2+: assert the stream encoding is buffer. + // stream._decoder: streams1 + // state.encoding: streams2 + // state.decoder: streams2, specifically < 0.10.6 + var state = stream._readableState + if (stream._decoder || (state && (state.encoding || state.decoder))) { + // developer error + return done(createError(500, 'stream encoding should not be set', { + type: 'stream.encoding.set' + })) + } + + if (typeof stream.readable !== 'undefined' && !stream.readable) { + return done(createError(500, 'stream is not readable', { + type: 'stream.not.readable' + })) + } + + var received = 0 + var decoder + + try { + decoder = getDecoder(encoding) + } catch (err) { + return done(err) + } + + var buffer = decoder + ? '' + : [] + + // attach listeners + stream.on('aborted', onAborted) + stream.on('close', cleanup) + stream.on('data', onData) + stream.on('end', onEnd) + stream.on('error', onEnd) + + // mark sync section complete + sync = false + + function done () { + var args = new Array(arguments.length) + + // copy arguments + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } + + // mark complete + complete = true + + if (sync) { + process.nextTick(invokeCallback) + } else { + invokeCallback() + } + + function invokeCallback () { + cleanup() + + if (args[0]) { + // halt the stream on error + halt(stream) + } + + callback.apply(null, args) + } + } + + function onAborted () { + if (complete) return + + done(createError(400, 'request aborted', { + code: 'ECONNABORTED', + expected: length, + length: length, + received: received, + type: 'request.aborted' + })) + } + + function onData (chunk) { + if (complete) return + + received += chunk.length + + if (limit !== null && received > limit) { + done(createError(413, 'request entity too large', { + limit: limit, + received: received, + type: 'entity.too.large' + })) + } else if (decoder) { + buffer += decoder.write(chunk) + } else { + buffer.push(chunk) + } + } + + function onEnd (err) { + if (complete) return + if (err) return done(err) + + if (length !== null && received !== length) { + done(createError(400, 'request size did not match content length', { + expected: length, + length: length, + received: received, + type: 'request.size.invalid' + })) + } else { + var string = decoder + ? buffer + (decoder.end() || '') + : Buffer.concat(buffer) + done(null, string) + } + } + + function cleanup () { + buffer = null + + stream.removeListener('aborted', onAborted) + stream.removeListener('data', onData) + stream.removeListener('end', onEnd) + stream.removeListener('error', onEnd) + stream.removeListener('close', cleanup) + } +} + +/** + * Try to require async_hooks + * @private + */ + +function tryRequireAsyncHooks () { + try { + return require('async_hooks') + } catch (e) { + return {} + } +} + +/** + * Wrap function with async resource, if possible. + * AsyncResource.bind static method backported. + * @private + */ + +function wrap (fn) { + var res + + // create anonymous resource + if (asyncHooks.AsyncResource) { + res = new asyncHooks.AsyncResource(fn.name || 'bound-anonymous-fn') + } + + // incompatible node.js + if (!res || !res.runInAsyncScope) { + return fn + } + + // return bound function + return res.runInAsyncScope.bind(res, fn, null) +} diff --git a/system/login/node_modules/express/node_modules/raw-body/package.json b/system/login/node_modules/express/node_modules/raw-body/package.json new file mode 100644 index 0000000..50fc90a --- /dev/null +++ b/system/login/node_modules/express/node_modules/raw-body/package.json @@ -0,0 +1,49 @@ +{ + "name": "raw-body", + "description": "Get and validate the raw body of a readable stream.", + "version": "2.5.1", + "author": "Jonathan Ong (http://jongleberry.com)", + "contributors": [ + "Douglas Christopher Wilson ", + "Raynos " + ], + "license": "MIT", + "repository": "stream-utils/raw-body", + "dependencies": { + "bytes": "3.1.2", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "unpipe": "1.0.0" + }, + "devDependencies": { + "bluebird": "3.7.2", + "eslint": "7.32.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.25.4", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "5.2.0", + "eslint-plugin-standard": "4.1.0", + "mocha": "9.2.1", + "nyc": "15.1.0", + "readable-stream": "2.3.7", + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.8" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "SECURITY.md", + "index.d.ts", + "index.js" + ], + "scripts": { + "lint": "eslint .", + "test": "mocha --trace-deprecation --reporter spec --bail --check-leaks test/", + "test-ci": "nyc --reporter=lcovonly --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/system/login/node_modules/express/package.json b/system/login/node_modules/express/package.json new file mode 100644 index 0000000..0996637 --- /dev/null +++ b/system/login/node_modules/express/package.json @@ -0,0 +1,99 @@ +{ + "name": "express", + "description": "Fast, unopinionated, minimalist web framework", + "version": "4.18.2", + "author": "TJ Holowaychuk ", + "contributors": [ + "Aaron Heckmann ", + "Ciaran Jessup ", + "Douglas Christopher Wilson ", + "Guillermo Rauch ", + "Jonathan Ong ", + "Roman Shtylman ", + "Young Jae Sim " + ], + "license": "MIT", + "repository": "expressjs/express", + "homepage": "http://expressjs.com/", + "keywords": [ + "express", + "framework", + "sinatra", + "web", + "http", + "rest", + "restful", + "router", + "app", + "api" + ], + "dependencies": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "1.20.1", + "content-disposition": "0.5.4", + "content-type": "~1.0.4", + "cookie": "0.5.0", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "2.0.0", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "1.2.0", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "merge-descriptors": "1.0.1", + "methods": "~1.1.2", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "path-to-regexp": "0.1.7", + "proxy-addr": "~2.0.7", + "qs": "6.11.0", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "0.18.0", + "serve-static": "1.15.0", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "devDependencies": { + "after": "0.8.2", + "connect-redis": "3.4.2", + "cookie-parser": "1.4.6", + "cookie-session": "2.0.0", + "ejs": "3.1.8", + "eslint": "8.24.0", + "express-session": "1.17.2", + "hbs": "4.2.0", + "marked": "0.7.0", + "method-override": "3.0.0", + "mocha": "10.0.0", + "morgan": "1.10.0", + "multiparty": "4.2.3", + "nyc": "15.1.0", + "pbkdf2-password": "1.2.1", + "supertest": "6.3.0", + "vhost": "~3.0.2" + }, + "engines": { + "node": ">= 0.10.0" + }, + "files": [ + "LICENSE", + "History.md", + "Readme.md", + "index.js", + "lib/" + ], + "scripts": { + "lint": "eslint .", + "test": "mocha --require test/support/env --reporter spec --bail --check-leaks test/ test/acceptance/", + "test-ci": "nyc --reporter=lcovonly --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "test-tap": "mocha --require test/support/env --reporter tap --check-leaks test/ test/acceptance/" + } +} diff --git a/system/login/node_modules/nodemailer/.gitattributes b/system/login/node_modules/nodemailer/.gitattributes new file mode 100644 index 0000000..0318d52 --- /dev/null +++ b/system/login/node_modules/nodemailer/.gitattributes @@ -0,0 +1,6 @@ +*.js text eol=lf +*.txt text eol=lf +*.html text eol=lf +*.htm text eol=lf +*.ics -text +*.bin -text \ No newline at end of file diff --git a/system/login/node_modules/nodemailer/.ncurc.js b/system/login/node_modules/nodemailer/.ncurc.js new file mode 100644 index 0000000..9ab4b0d --- /dev/null +++ b/system/login/node_modules/nodemailer/.ncurc.js @@ -0,0 +1,7 @@ +module.exports = { + upgrade: true, + reject: [ + // API changes break existing tests + 'proxy' + ] +}; diff --git a/system/login/node_modules/nodemailer/.prettierrc.js b/system/login/node_modules/nodemailer/.prettierrc.js new file mode 100644 index 0000000..3f83654 --- /dev/null +++ b/system/login/node_modules/nodemailer/.prettierrc.js @@ -0,0 +1,8 @@ +module.exports = { + printWidth: 160, + tabWidth: 4, + singleQuote: true, + endOfLine: 'lf', + trailingComma: 'none', + arrowParens: 'avoid' +}; diff --git a/system/login/node_modules/nodemailer/CHANGELOG.md b/system/login/node_modules/nodemailer/CHANGELOG.md new file mode 100644 index 0000000..5852db6 --- /dev/null +++ b/system/login/node_modules/nodemailer/CHANGELOG.md @@ -0,0 +1,760 @@ +# CHANGELOG + +## [6.9.7](https://github.com/nodemailer/nodemailer/compare/v6.9.6...v6.9.7) (2023-10-22) + + +### Bug Fixes + +* **customAuth:** Do not require user and pass to be set for custom authentication schemes (fixes [#1584](https://github.com/nodemailer/nodemailer/issues/1584)) ([41d482c](https://github.com/nodemailer/nodemailer/commit/41d482c3f01e26111b06f3e46351b193db3fb5cb)) + +## [6.9.6](https://github.com/nodemailer/nodemailer/compare/v6.9.5...v6.9.6) (2023-10-09) + + +### Bug Fixes + +* **inline:** Use 'inline' as the default Content Dispostion value for embedded images ([db32c93](https://github.com/nodemailer/nodemailer/commit/db32c93fefee527bcc239f13056e5d9181a4d8af)) +* **tests:** Removed Node v12 from test matrix as it is not compatible with the test framework anymore ([7fe0a60](https://github.com/nodemailer/nodemailer/commit/7fe0a608ed6bcb70dc6b2de543ebfc3a30abf984)) + +## [6.9.5](https://github.com/nodemailer/nodemailer/compare/v6.9.4...v6.9.5) (2023-09-06) + + +### Bug Fixes + +* **license:** Updated license year ([da4744e](https://github.com/nodemailer/nodemailer/commit/da4744e491f3a68f4f68e4073684370592630e01)) + +## 6.9.4 2023-07-19 + +- Renamed SendinBlue to Brevo + +## 6.9.3 2023-05-29 + +- Specified license identifier (was defined as MIT, actual value MIT-0) +- If SMTP server disconnects with a message, process it and include as part of the response error + +## 6.9.2 2023-05-11 + +- Fix uncaught exception on invalid attachment content payload + +## 6.9.1 2023-01-27 + +- Fix base64 encoding for emoji bytes in encoded words + +## 6.9.0 2023-01-12 + +- Do not throw if failed to resolve IPv4 addresses +- Include EHLO extensions in the send response +- fix sendMail function: callback should be optional + +## 6.8.0 2022-09-28 + +- Add DNS timeout (huksley) +- add dns.REFUSED (lucagianfelici) + +## 6.7.8 2022-08-11 + +- Allow to use multiple Reply-To addresses + +## 6.7.7 2022-07-06 + +- Resolver fixes + +## 6.7.5 2022-05-04 + +- No changes, pushing a new README to npmjs.org + +## 6.7.4 2022-04-29 + +- Ensure compatibility with Node 18 +- Replaced Travis with Github Actions + +## 6.7.3 2022-03-21 + +- Typo fixes +- Added stale issue automation fir Github +- Add Infomaniak config to well known service (popod) +- Update Outlook/Hotmail host in well known services (popod) +- fix: DSN recipient gets ignored (KornKalle) + +## 6.7.2 2021-11-26 + +- Fix proxies for account verification + +## 6.7.1 2021-11-15 + +- fix verify on ses-transport (stanofsky) + +## 6.7.0 2021-10-11 + +- Updated DNS resolving logic. If there are multiple responses for a A/AAAA record, then loop these randomly instead of only caching the first one + +## 6.6.5 2021-09-23 + +- Replaced Object.values() and Array.flat() with polyfills to allow using Nodemailer in Node v6+ + +## 6.6.4 2021-09-22 + +- Better compatibility with IPv6-only SMTP hosts (oxzi) +- Fix ses verify for sdk v3 (hannesvdvreken) +- Added SECURITY.txt for contact info + +## 6.6.3 2021-07-14 + +- Do not show passwords in SMTP transaction logs. All passwords used in logging are replaced by `"/* secret */"` + +## 6.6.1 2021-05-23 + +- Fixed address formatting issue where newlines in an email address, if provided via address object, were not properly removed. Reported by tmazeika (#1289) + +## 6.6.0 2021-04-28 + +- Added new option `newline` for MailComposer +- aws ses connection verification (Ognjen Jevremovic) + +## 6.5.0 2021-02-26 + +- Pass through textEncoding to subnodes +- Added support for AWS SES v3 SDK +- Fixed tests + +## 6.4.18 2021-02-11 + +- Updated README + +## 6.4.17 2020-12-11 + +- Allow mixing attachments with caendar alternatives + +## 6.4.16 2020-11-12 + +- Applied updated prettier formating rules + +## 6.4.15 2020-11-06 + +- Minor changes in header key casing + +## 6.4.14 2020-10-14 + +- Disabled postinstall script + +## 6.4.13 2020-10-02 + +- Fix normalizeHeaderKey method for single node messages + +## 6.4.12 2020-09-30 + +- Better handling of attachment filenames that include quote symbols +- Includes all information from the oath2 error response in the error message (Normal Gaussian) [1787f227] + +## 6.4.11 2020-07-29 + +- Fixed escape sequence handling in address parsing + +## 6.4.10 2020-06-17 + +- Fixed RFC822 output for MailComposer when using invalid content-type value. Mostly relevant if message attachments have stragne content-type values set. + +## 6.4.7 2020-05-28 + +- Always set charset=utf-8 for Content-Type headers +- Catch error when using invalid crypto.sign input + +## 6.4.6 2020-03-20 + +- fix: `requeueAttempts=n` should requeue `n` times (Patrick Malouin) [a27ed2f7] + +## 6.4.4 2020-03-01 + +- Add `options.forceAuth` for SMTP (Patrick Malouin) [a27ed2f7] + +## 6.4.3 2020-02-22 + +- Added an option to specify max number of requeues when connection closes unexpectedly (Igor Sechyn) [8a927f5a] + +## 6.4.2 2019-12-11 + +- Fixed bug where array item was used with a potentially empty array + +## 6.4.1 2019-12-07 + +- Fix processing server output with unterminated responses + +## 6.4.0 2019-12-04 + +- Do not use auth if server does not advertise AUTH support [f419b09d] +- add dns.CONNREFUSED (Hiroyuki Okada) [5c4c8ca8] + +## 6.3.1 2019-10-09 + +- Ignore "end" events because it might be "error" after it (dex4er) [72bade9] +- Set username and password on the connection proxy object correctly (UsamaAshraf) [250b1a8] +- Support more DNS errors (madarche) [2391aa4] + +## 6.3.0 2019-07-14 + +- Added new option to pass a set of httpHeaders to be sent when fetching attachments. See [PR #1034](https://github.com/nodemailer/nodemailer/pull/1034) + +## 6.2.1 2019-05-24 + +- No changes. It is the same as 6.2.0 that was accidentally published as 6.2.1 to npm + +## 6.2.0 2019-05-24 + +- Added new option for addressparser: `flatten`. If true then ignores group names and returns a single list of all addresses + +## 6.1.1 2019-04-20 + +- Fixed regression bug with missing smtp `authMethod` property + +## 6.1.0 2019-04-06 + +- Added new message property `amp` for providing AMP4EMAIL content + +## 6.0.0 2019-03-25 + +- SMTPConnection: use removeListener instead of removeAllListeners (xr0master) [ddc4af15] + Using removeListener should fix memory leak with Node.js streams + +## 5.1.1 2019-01-09 + +- Added missing option argument for custom auth + +## 5.1.0 2019-01-09 + +- Official support for custom authentication methods and examples (examples/custom-auth-async.js and examples/custom-auth-cb.js) + +## 5.0.1 2019-01-09 + +- Fixed regression error to support Node versions lower than 6.11 +- Added expiremental custom authentication support + +## 5.0.0 2018-12-28 + +- Start using dns.resolve() instead of dns.lookup() for resolving SMTP hostnames. Might be breaking change on some environments so upgrade with care +- Show more logs for renewing OAuth2 tokens, previously it was not possible to see what actually failed + +## 4.7.0 2018-11-19 + +- Cleaned up List-\* header generation +- Fixed 'full' return option for DSN (klaronix) [23b93a3b] +- Support promises `for mailcomposer.build()` + +## 4.6.8 2018-08-15 + +- Use first IP address from DNS resolution when using a proxy (Limbozz) [d4ca847c] +- Return raw email from SES transport (gabegorelick) [3aa08967] + +## 4.6.7 2018-06-15 + +- Added option `skipEncoding` to JSONTransport + +## 4.6.6 2018-06-10 + +- Fixes mime encoded-word compatibility issue with invalid clients like Zimbra + +## 4.6.5 2018-05-23 + +- Fixed broken DKIM stream in Node.js v10 +- Updated error messages for SMTP responses to not include a newline + +## 4.6.4 2018-03-31 + +- Readded logo author link to README that was accidentally removed a while ago + +## 4.6.3 2018-03-13 + +- Removed unneeded dependency + +## 4.6.2 2018-03-06 + +- When redirecting URL calls then do not include original POST content + +## 4.6.1 2018-03-06 + +- Fixed Smtp connection freezing, when trying to send after close / quit (twawszczak) [73d3911c] + +## 4.6.0 2018-02-22 + +- Support socks module v2 in addition to v1 [e228bcb2] +- Fixed invalid promise return value when using createTestAccount [5524e627] +- Allow using local addresses [8f6fa35f] + +## 4.5.0 2018-02-21 + +- Added new message transport option `normalizeHeaderKey(key)=>normalizedKey` for custom header formatting + +## 4.4.2 2018-01-20 + +- Added sponsors section to README +- enclose encodeURIComponent in try..catch to handle invalid urls + +## 4.4.1 2017-12-08 + +- Better handling of unexpectedly dropping connections + +## 4.4.0 2017-11-10 + +- Changed default behavior for attachment option contentTransferEncoding. If it is unset then base64 encoding is used for the attachment. If it is set to false then previous default applies (base64 for most, 7bit for text) + +## 4.3.1 2017-10-25 + +- Fixed a confict with Electron.js where timers do not have unref method + +## 4.3.0 2017-10-23 + +- Added new mail object method `mail.normalize(cb)` that should make creating HTTP API based transports much easier + +## 4.2.0 2017-10-13 + +- Expose streamed messages size and timers in info response + +## v4.1.3 2017-10-06 + +- Allow generating preview links without calling createTestAccount first + +## v4.1.2 2017-10-03 + +- No actual changes. Needed to push updated README to npmjs + +## v4.1.1 2017-09-25 + +- Fixed JSONTransport attachment handling + +## v4.1.0 2017-08-28 + +- Added new methods `createTestAccount` and `getTestMessageUrl` to use autogenerated email accounts from https://Ethereal.email + +## v4.0.1 2017-04-13 + +- Fixed issue with LMTP and STARTTLS + +## v4.0.0 2017-04-06 + +- License changed from EUPLv1.1 to MIT + +## v3.1.8 2017-03-21 + +- Fixed invalid List-\* header generation + +## v3.1.7 2017-03-14 + +- Emit an error if STARTTLS ends with connection being closed + +## v3.1.6 2017-03-14 + +- Expose last server response for smtpConnection + +## v3.1.5 2017-03-08 + +- Fixed SES transport, added missing `response` value + +## v3.1.4 2017-02-26 + +- Fixed DKIM calculation for empty body +- Ensure linebreak after message content. This fixes DKIM signatures for non-multipart messages where input did not end with a newline + +## v3.1.3 2017-02-17 + +- Fixed missing `transport.verify()` methods for SES transport + +## v3.1.2 2017-02-17 + +- Added missing error handlers for Sendmail, SES and Stream transports. If a messages contained an invalid URL as attachment then these transports threw an uncatched error + +## v3.1.1 2017-02-13 + +- Fixed missing `transport.on('idle')` and `transport.isIdle()` methods for SES transports + +## v3.1.0 2017-02-13 + +- Added built-in transport for AWS SES. [Docs](http://localhost:1313/transports/ses/) +- Updated stream transport to allow building JSON strings. [Docs](http://localhost:1313/transports/stream/#json-transport) +- Added new method _mail.resolveAll_ that fetches all attachments and such to be able to more easily build API-based transports + +## v3.0.2 2017-02-04 + +- Fixed a bug with OAuth2 login where error callback was fired twice if getToken was not available. + +## v3.0.1 2017-02-03 + +- Fixed a bug where Nodemailer threw an exception if `disableFileAccess` option was used +- Added FLOSS [exception declaration](FLOSS_EXCEPTIONS.md) + +## v3.0.0 2017-01-31 + +- Initial version of Nodemailer 3 + +This update brings a lot of breaking changes: + +- License changed from MIT to **EUPL-1.1**. This was possible as the new version of Nodemailer is a major rewrite. The features I don't have ownership for, were removed or reimplemented. If there's still some snippets in the code that have vague ownership then notify about the conflicting code and I'll fix it. +- Requires **Node.js v6+** +- All **templating is gone**. It was too confusing to use and to be really universal a huge list of different renderers would be required. Nodemailer is about email, not about parsing different template syntaxes +- **No NTLM authentication**. It was too difficult to re-implement. If you still need it then it would be possible to introduce a pluggable SASL interface where you could load the NTLM module in your own code and pass it to Nodemailer. Currently this is not possible. +- **OAuth2 authentication** is built in and has a different [configuration](https://nodemailer.com/smtp/oauth2/). You can use both user (3LO) and service (2LO) accounts to generate access tokens from Nodemailer. Additionally there's a new feature to authenticate differently for every message – useful if your application sends on behalf of different users instead of a single sender. +- **Improved Calendaring**. Provide an ical file to Nodemailer to send out [calendar events](https://nodemailer.com/message/calendar-events/). + +And also some non-breaking changes: + +- All **dependencies were dropped**. There is exactly 0 dependencies needed to use Nodemailer. This brings the installation time of Nodemailer from NPM down to less than 2 seconds +- **Delivery status notifications** added to Nodemailer +- Improved and built-in **DKIM** signing of messages. Previously you needed an external module for this and it did quite a lousy job with larger messages +- **Stream transport** to return a RFC822 formatted message as a stream. Useful if you want to use Nodemailer as a preprocessor and not for actual delivery. +- **Sendmail** transport built-in, no need for external transport plugin + +See [Nodemailer.com](https://nodemailer.com/) for full documentation + +## 2.7.0 2016-12-08 + +- Bumped mailcomposer that generates encoded-words differently which might break some tests + +## 2.6.0 2016-09-05 + +- Added new options disableFileAccess and disableUrlAccess +- Fixed envelope handling where cc/bcc fields were ignored in the envelope object + +## 2.4.2 2016-05-25 + +- Removed shrinkwrap file. Seemed to cause more trouble than help + +## 2.4.1 2016-05-12 + +- Fixed outdated shrinkwrap file + +## 2.4.0 2016-05-11 + +- Bumped mailcomposer module to allow using `false` as attachment filename (suppresses filename usage) +- Added NTLM authentication support + +## 2.3.2 2016-04-11 + +- Bumped smtp transport modules to get newest smtp-connection that fixes SMTPUTF8 support for internationalized email addresses + +## 2.3.1 2016-04-08 + +- Bumped mailcomposer to have better support for message/822 attachments + +## 2.3.0 2016-03-03 + +- Fixed a bug with attachment filename that contains mixed unicode and dashes +- Added built-in support for proxies by providing a new SMTP option `proxy` that takes a proxy configuration url as its value +- Added option `transport` to dynamically load transport plugins +- Do not require globally installed grunt-cli + +## 2.2.1 2016-02-20 + +- Fixed a bug in SMTP requireTLS option that was broken + +## 2.2.0 2016-02-18 + +- Removed the need to use `clone` dependency +- Added new method `verify` to check SMTP configuration +- Direct transport uses STARTTLS by default, fallbacks to plaintext if STARTTLS fails +- Added new message option `list` for setting List-\* headers +- Add simple proxy support with `getSocket` method +- Added new message option `textEncoding`. If `textEncoding` is not set then detect best encoding automatically +- Added new message option `icalEvent` to embed iCalendar events. Example [here](examples/ical-event.js) +- Added new attachment option `raw` to use prepared MIME contents instead of generating a new one. This might be useful when you want to handcraft some parts of the message yourself, for example if you want to inject a PGP encrypted message as the contents of a MIME node +- Added new message option `raw` to use an existing MIME message instead of generating a new one + +## 2.1.0 2016-02-01 + +Republishing 2.1.0-rc.1 as stable. To recap, here's the notable changes between v2.0 and v2.1: + +- Implemented templating support. You can either use a simple built-in renderer or some external advanced renderer, eg. [node-email-templates](https://github.com/niftylettuce/node-email-templates). Templating [docs](http://nodemailer.com/2-0-0-beta/templating/). +- Updated smtp-pool to emit 'idle' events in order to handle message queue more effectively +- Updated custom header handling, works everywhere the same now, no differences between adding custom headers to the message or to an attachment + +## 2.1.0-rc.1 2016-01-25 + +Sneaked in some new features even though it is already rc + +- If a SMTP pool is closed while there are still messages in a queue, the message callbacks are invoked with an error +- In case of SMTP pool the transporter emits 'idle' when there is a free connection slot available +- Added method `isIdle()` that checks if a pool has still some free connection slots available + +## 2.1.0-rc.0 2016-01-20 + +- Bumped dependency versions + +## 2.1.0-beta.3 2016-01-20 + +- Added support for node-email-templates templating in addition to the built-in renderer + +## 2.1.0-beta.2 2016-01-20 + +- Implemented simple templating feature + +## 2.1.0-beta.1 2016-01-20 + +- Allow using prepared header values that are not folded or encoded by Nodemailer + +## 2.1.0-beta.0 2016-01-20 + +- Use the same header custom structure for message root, attachments and alternatives +- Ensure that Message-Id exists when accessing message +- Allow using array values for custom headers (inserts every value in its own row) + +## 2.0.0 2016-01-11 + +- Released rc.2 as stable + +## 2.0.0-rc.2 2016-01-04 + +- Locked dependencies + +## 2.0.0-beta.2 2016-01-04 + +- Updated documentation to reflect changes with SMTP handling +- Use beta versions for smtp/pool/direct transports +- Updated logging + +## 2.0.0-beta.1 2016-01-03 + +- Use bunyan compatible logger instead of the emit('log') style +- Outsourced some reusable methods to nodemailer-shared +- Support setting direct/smtp/pool with the default configuration + +## 2.0.0-beta.0 2015-12-31 + +- Stream errors are not silently swallowed +- Do not use format=flowed +- Use nodemailer-fetch to fetch URL streams +- jshint replaced by eslint + +## v1.11.0 2015-12-28 + +Allow connection url based SMTP configurations + +## v1.10.0 2015-11-13 + +Added `defaults` argument for `createTransport` to predefine commonn values (eg. `from` address) + +## v1.9.0 2015-11-09 + +Returns a Promise for `sendMail` if callback is not defined + +## v1.8.0 2015-10-08 + +Added priority option (high, normal, low) for setting Importance header + +## v1.7.0 2015-10-06 + +Replaced hyperquest with needle. Fixes issues with compressed data and redirects + +## v1.6.0 2015-10-05 + +Maintenance release. Bumped dependencies to get support for unicode filenames for QQ webmail and to support emoji in filenames + +## v1.5.0 2015-09-24 + +Use mailcomposer instead of built in solution to generate message sources. Bumped libmime gives better quoted-printable handling. + +## v1.4.0 2015-06-27 + +Added new message option `watchHtml` to specify Apple Watch specific HTML part of the message. See [this post](https://litmus.com/blog/how-to-send-hidden-version-email-apple-watch) for details + +## v1.3.4 2015-04-25 + +Maintenance release, bumped buildmail version to get fixed format=flowed handling + +## v1.3.3 2015-04-25 + +Maintenance release, bumped dependencies + +## v1.3.2 2015-03-09 + +Maintenance release, upgraded dependencies. Replaced simplesmtp based tests with smtp-server based ones. + +## v1.3.0 2014-09-12 + +Maintenance release, upgrades buildmail and libmime. Allows using functions as transform plugins and fixes issue with unicode filenames in Gmail. + +## v1.2.2 2014-09-05 + +Proper handling of data uris as attachments. Attachment `path` property can also be defined as a data uri, not just regular url or file path. + +## v1.2.1 2014-08-21 + +Bumped libmime and mailbuild versions to properly handle filenames with spaces (short ascii only filenames with spaces were left unquoted). + +## v1.2.0 2014-08-18 + +Allow using encoded strings as attachments. Added new property `encoding` which defines the encoding used for a `content` string. If encoding is set, the content value is converted to a Buffer value using the defined encoding before usage. Useful for including binary attachemnts in JSON formatted email objects. + +## v1.1.2 2014-08-18 + +Return deprecatin error for v0.x style configuration + +## v1.1.1 2014-07-30 + +Bumped nodemailer-direct-transport dependency. Updated version includes a bugfix for Stream nodes handling. Important only if use direct-transport with Streams (not file paths or urls) as attachment content. + +## v1.1.0 2014-07-29 + +Added new method `resolveContent()` to get the html/text/attachment content as a String or Buffer. + +## v1.0.4 2014-07-23 + +Bugfix release. HTML node was instered twice if the message consisted of a HTML content (but no text content) + at least one attachment with CID + at least one attachment without CID. In this case the HTML node was inserted both to the root level multipart/mixed section and to the multipart/related sub section + +## v1.0.3 2014-07-16 + +Fixed a bug where Nodemailer crashed if the message content type was multipart/related + +## v1.0.2 2014-07-16 + +Upgraded nodemailer-smtp-transport to 0.1.11\. The docs state that for SSL you should use 'secure' option but the underlying smtp-connection module used 'secureConnection' for this purpose. Fixed smpt-connection to match the docs. + +## v1.0.1 2014-07-15 + +Implemented missing #close method that is passed to the underlying transport object. Required by the smtp pool. + +## v1.0.0 2014-07-15 + +Total rewrite. See migration guide here: + +## v0.7.1 2014-07-09 + +- Upgraded aws-sdk to 2.0.5 + +## v0.7.0 2014-06-17 + +- Bumped version to v0.7.0 +- Fix AWS-SES usage [5b6bc144] +- Replace current SES with new SES using AWS-SDK (Elanorr) [c79d797a] +- Updated README.md about Node Email Templates (niftylettuce) [e52bef81] + +## v0.6.5 2014-05-15 + +- Bumped version to v0.6.5 +- Use tildes instead of carets for dependency listing [5296ce41] +- Allow clients to set a custom identityString (venables) [5373287d] +- bugfix (adding "-i" to sendmail command line for each new mail) by copying this.args (vrodic) [05a8a9a3] +- update copyright (gdi2290) [3a6cba3a] + +## v0.6.4 2014-05-13 + +- Bumped version to v0.6.4 +- added npmignore, bumped dependencies [21bddcd9] +- Add AOL to well-known services (msouce) [da7dd3b7] + +## v0.6.3 2014-04-16 + +- Bumped version to v0.6.3 +- Upgraded simplesmtp dependency [dd367f59] + +## v0.6.2 2014-04-09 + +- Bumped version to v0.6.2 +- Added error option to Stub transport [c423acad] +- Use SVG npm badge (t3chnoboy) [677117b7] +- add SendCloud to well known services (haio) [43c358e0] +- High-res build-passing and NPM module badges (sahat) [9fdc37cd] + +## v0.6.1 2014-01-26 + +- Bumped version to v0.6.1 +- Do not throw on multiple errors from sendmail command [c6e2cd12] +- Do not require callback for pickup, fixes #238 [93eb3214] +- Added AWSSecurityToken information to README, fixes #235 [58e921d1] +- Added Nodemailer logo [06b7d1a8] + +## v0.6.0 2013-12-30 + +- Bumped version to v0.6.0 +- Allow defining custom transport methods [ec5b48ce] +- Return messageId with responseObject for all built in transport methods [74445cec] +- Bumped dependency versions for mailcomposer and readable-stream [9a034c34] +- Changed pickup argument name to 'directory' [01c3ea53] +- Added support for IIS pickup directory with PICKUP transport (philipproplesch) [36940b59..360a2878] +- Applied common styles [9e93a409] +- Updated readme [c78075e7] + +## v0.5.15 2013-12-13 + +- bumped version to v0.5.15 +- Updated README, added global options info for setting uo transports [554bb0e5] +- Resolve public hostname, if resolveHostname property for a transport object is set to `true` [9023a6e1..4c66b819] + +## v0.5.14 2013-12-05 + +- bumped version to v0.5.14 +- Expose status for direct messages [f0312df6] +- Allow to skip the X-Mailer header if xMailer value is set to 'false' [f2c20a68] + +## v0.5.13 2013-12-03 + +- bumped version to v0.5.13 +- Use the name property from the transport object to use for the domain part of message-id values (1598eee9) + +## v0.5.12 2013-12-02 + +- bumped version to v0.5.12 +- Expose transport method and transport module version if available [a495106e] +- Added 'he' module instead of using custom html entity decoding [c197d102] +- Added xMailer property for transport configuration object to override X-Mailer value [e8733a61] +- Updated README, added description for 'mail' method [e1f5f3a6] + +## v0.5.11 2013-11-28 + +- bumped version to v0.5.11 +- Updated mailcomposer version. Replaces ent with he [6a45b790e] + +## v0.5.10 2013-11-26 + +- bumped version to v0.5.10 +- added shorthand function mail() for direct transport type [88129bd7] +- minor tweaks and typo fixes [f797409e..ceac0ca4] + +## v0.5.9 2013-11-25 + +- bumped version to v0.5.9 +- Update for 'direct' handling [77b84e2f] +- do not require callback to be provided for 'direct' type [ec51c79f] + +## v0.5.8 2013-11-22 + +- bumped version to v0.5.8 +- Added support for 'direct' transport [826f226d..0dbbcbbc] + +## v0.5.7 2013-11-18 + +- bumped version to v0.5.7 +- Replace \r\n by \n in Sendmail transport (rolftimmermans) [fed2089e..616ec90c] A lot of sendmail implementations choke on \r\n newlines and require \n This commit addresses this by transforming all \r\n sequences passed to the sendmail command with \n + +## v0.5.6 2013-11-15 + +- bumped version to v0.5.6 +- Upgraded mailcomposer dependency to 0.2.4 [e5ff9c40] +- Removed noCR option [e810d1b8] +- Update wellknown.js, added FastMail (k-j-kleist) [cf930f6d] + +## v0.5.5 2013-10-30 + +- bumped version to v0.5.5 +- Updated mailcomposer dependnecy version to 0.2.3 +- Remove legacy code - node v0.4 is not supported anymore anyway +- Use hostname (autodetected or from the options.name property) for Message-Id instead of "Nodemailer" (helps a bit when messages are identified as spam) +- Added maxMessages info to README + +## v0.5.4 2013-10-29 + +- bumped version to v0.5.4 +- added "use strict" statements +- Added DSN info to README +- add support for QQ enterprise email (coderhaoxin) +- Add a Bitdeli Badge to README +- DSN options Passthrought into simplesmtp. (irvinzz) + +## v0.5.3 2013-10-03 + +- bumped version v0.5.3 +- Using a stub transport to prevent sendmail from being called during a test. (jsdevel) +- closes #78: sendmail transport does not work correctly on Unix machines. (jsdevel) +- Updated PaaS Support list to include Modulus. (fiveisprime) +- Translate self closing break tags to newline (kosmasgiannis) +- fix typos (aeosynth) + +## v0.5.2 2013-07-25 + +- bumped version v0.5.2 +- Merge pull request #177 from MrSwitch/master Fixing Amazon SES, fatal error caused by bad connection diff --git a/system/login/node_modules/nodemailer/CODE_OF_CONDUCT.md b/system/login/node_modules/nodemailer/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..e6895ed --- /dev/null +++ b/system/login/node_modules/nodemailer/CODE_OF_CONDUCT.md @@ -0,0 +1,76 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, sex characteristics, gender identity and expression, +level of experience, education, socio-economic status, nationality, personal +appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at info@nodemailer.com. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see +https://www.contributor-covenant.org/faq diff --git a/system/login/node_modules/nodemailer/LICENSE b/system/login/node_modules/nodemailer/LICENSE new file mode 100644 index 0000000..fdfc967 --- /dev/null +++ b/system/login/node_modules/nodemailer/LICENSE @@ -0,0 +1,16 @@ +Copyright (c) 2011-2023 Andris Reinman + +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 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/system/login/node_modules/nodemailer/README.md b/system/login/node_modules/nodemailer/README.md new file mode 100644 index 0000000..c90da55 --- /dev/null +++ b/system/login/node_modules/nodemailer/README.md @@ -0,0 +1,97 @@ +# Nodemailer + +[![Nodemailer](https://raw.githubusercontent.com/nodemailer/nodemailer/master/assets/nm_logo_200x136.png)](https://nodemailer.com/about/) + +Send emails from Node.js – easy as cake! 🍰✉️ + +[![NPM](https://nodei.co/npm/nodemailer.png?downloads=true&downloadRank=true&stars=true)](https://nodemailer.com/about/) + +See [nodemailer.com](https://nodemailer.com/) for documentation and terms. + +--- + +> Check out **[EmailEngine](https://emailengine.app/?utm_source=github-nodemailer&utm_campaign=nodemailer&utm_medium=readme-link)** – a self-hosted email gateway that allows making **REST requests against IMAP and SMTP servers**. EmailEngine also sends webhooks whenever something changes on the registered accounts.\ +> \ +> Using the email accounts registered with EmailEngine, you can receive and [send emails](https://emailengine.app/sending-emails?utm_source=github-nodemailer&utm_campaign=nodemailer&utm_medium=readme-link). EmailEngine supports OAuth2, delayed sends, opens and clicks tracking, bounce detection, etc. All on top of regular email accounts without an external MTA service. + +--- + +This project is supported by [Forward Email](https://forwardemail.net) – the 100% open-source and privacy-focused email service. + +--- + +This project is supported by [Opensense](https://www.opensense.com) - The beautiful email signature management company for Office 365 and Google Workspace. + +--- + +## Having an issue? + +#### First review the docs + +Documentation for Nodemailer can be found at [nodemailer.com](https://nodemailer.com/about/). + +#### Nodemailer throws a SyntaxError for "..." + +You are using an older Node.js version than v6.0. Upgrade Node.js to get support for the spread operator. Nodemailer supports all Node.js versions starting from Node.js@v6.0.0. + +#### I'm having issues with Gmail + +Gmail either works well, or it does not work at all. It is probably easier to switch to an alternative service instead of fixing issues with Gmail. If Gmail does not work for you, then don't use it. Read more about it [here](https://nodemailer.com/usage/using-gmail/). + +#### I get ETIMEDOUT errors + +Check your firewall settings. Timeout usually occurs when you try to open a connection to a firewalled port either on the server or on your machine. Some ISPs also block email ports to prevent spamming. + +#### Nodemailer works on one machine but not in another + +It's either a firewall issue, or your SMTP server blocks authentication attempts from some servers. + +#### I get TLS errors + +- If you are running the code on your machine, check your antivirus settings. Antiviruses often mess around with email ports usage. Node.js might not recognize the MITM cert your antivirus is using. +- Latest Node versions allow only TLS versions 1.2 and higher. Some servers might still use TLS 1.1 or lower. Check Node.js docs on how to get correct TLS support for your app. You can change this with [tls.minVersion](https://nodejs.org/dist/latest-v16.x/docs/api/tls.html#tls_tls_createsecurecontext_options) option +- You might have the wrong value for the `secure` option. This should be set to `true` only for port 465. For every other port, it should be `false`. Setting it to `false` does not mean that Nodemailer would not use TLS. Nodemailer would still try to upgrade the connection to use TLS if the server supports it. +- Older Node versions do not fully support the certificate chain of the newest Let's Encrypt certificates. Either set [tls.rejectUnauthorized](https://nodejs.org/dist/latest-v16.x/docs/api/tls.html#tlsconnectoptions-callback) to `false` to skip chain verification or upgrade your Node version + +``` +let configOptions = { + host: "smtp.example.com", + port: 587, + tls: { + rejectUnauthorized: true, + minVersion: "TLSv1.2" + } +} +``` + +#### I have issues with DNS / hosts file + +Node.js uses [c-ares](https://nodejs.org/en/docs/meta/topics/dependencies/#c-ares) to resolve domain names, not the DNS library provided by the system, so if you have some custom DNS routing set up, it might be ignored. Nodemailer runs [dns.resolve4()](https://nodejs.org/dist/latest-v16.x/docs/api/dns.html#dnsresolve4hostname-options-callback) and [dns.resolve6()](https://nodejs.org/dist/latest-v16.x/docs/api/dns.html#dnsresolve6hostname-options-callback) to resolve hostname into an IP address. If both calls fail, then Nodemailer will fall back to [dns.lookup()](https://nodejs.org/dist/latest-v16.x/docs/api/dns.html#dnslookuphostname-options-callback). If this does not work for you, you can hard code the IP address into the configuration like shown below. In that case, Nodemailer would not perform any DNS lookups. + +``` +let configOptions = { + host: "1.2.3.4", + port: 465, + secure: true, + tls: { + // must provide server name, otherwise TLS certificate check will fail + servername: "example.com" + } +} +``` + +#### I have an issue with TypeScript types + +Nodemailer has official support for Node.js only. For anything related to TypeScript, you need to directly contact the authors of the [type definitions](https://www.npmjs.com/package/@types/nodemailer). + +#### I have a different problem + +If you are having issues with Nodemailer, then the best way to find help would be [Stack Overflow](https://stackoverflow.com/search?q=nodemailer) or revisit the [docs](https://nodemailer.com/about/). + +### License + +Nodemailer is licensed under the **MIT No Attribution license** + +--- + +The Nodemailer logo was designed by [Sven Kristjansen](https://www.behance.net/kristjansen). diff --git a/system/login/node_modules/nodemailer/SECURITY.txt b/system/login/node_modules/nodemailer/SECURITY.txt new file mode 100644 index 0000000..27a54d3 --- /dev/null +++ b/system/login/node_modules/nodemailer/SECURITY.txt @@ -0,0 +1,22 @@ +-----BEGIN PGP SIGNED MESSAGE----- +Hash: SHA256 + +Contact: mailto:andris@reinman.eu +Encryption: https://keys.openpgp.org/vks/v1/by-fingerprint/5D952A46E1D8C931F6364E01DC6C83F4D584D364 +Preferred-Languages: en, et +-----BEGIN PGP SIGNATURE----- + +iQIzBAEBCAAdFiEEXZUqRuHYyTH2Nk4B3GyD9NWE02QFAmFDnUgACgkQ3GyD9NWE +02RqUA/+MM3afmRYq874C7wp+uN6dTMCvUX5g5zqBZ2yKpFr46L+PYvM7o8TMm5h +hmLT2I1zZmi+xezOL3zHFizaw0tKkZIz9cWl3Jrgs0FLp0zOsSz1xucp9Q2tYM/Q +vbiP6ys0gbim4tkDGRmZOEiO23s0BuRnmHt7vZg210O+D105Yd8/Ohzbj6PSLBO5 +W1tA7Xw5t0FQ14NNH5+MKyDIKoCX12n0FmrC6qLTXeojf291UgKhCUPda3LIGTmx +mTXz0y68149Mw+JikRCYP8HfGRY9eA4XZrYXF7Bl2T9OJpKD3JAH+69P3xBw19Gn +Csaw3twu8P1bxoVGjY4KRrBOp68W8TwZYjWVWbqY6oV8hb/JfrMxa+kaSxRuloFs +oL6+phrDSPTWdOj2LlEDBJbPOMeDFzIlsBBcJ/JHCEHTvlHl7LoWr3YuWce9PUwl +4r3JUovvaeuJxLgC0vu3WCB3Jeocsl3SreqNkrVc1IjvkSomn3YGm5nCNAd/2F0V +exCGRk/8wbkSjAY38GwQ8K/VuFsefWN3L9sVwIMAMu88KFCAN+GzVFiwvyIXehF5 +eogP9mIXzdQ5YReQjUjApOzGz54XnDyv9RJ3sdvMHosLP+IOg+0q5t9agWv6aqSR +2HzCpiQnH/gmM5NS0AU4Koq/L7IBeLu1B8+61/+BiHgZJJmPdgU= +=BUZr +-----END PGP SIGNATURE----- diff --git a/system/login/node_modules/nodemailer/lib/addressparser/index.js b/system/login/node_modules/nodemailer/lib/addressparser/index.js new file mode 100644 index 0000000..8260ddb --- /dev/null +++ b/system/login/node_modules/nodemailer/lib/addressparser/index.js @@ -0,0 +1,313 @@ +'use strict'; + +/** + * Converts tokens for a single address into an address object + * + * @param {Array} tokens Tokens object + * @return {Object} Address object + */ +function _handleAddress(tokens) { + let token; + let isGroup = false; + let state = 'text'; + let address; + let addresses = []; + let data = { + address: [], + comment: [], + group: [], + text: [] + }; + let i; + let len; + + // Filter out , (comments) and regular text + for (i = 0, len = tokens.length; i < len; i++) { + token = tokens[i]; + if (token.type === 'operator') { + switch (token.value) { + case '<': + state = 'address'; + break; + case '(': + state = 'comment'; + break; + case ':': + state = 'group'; + isGroup = true; + break; + default: + state = 'text'; + } + } else if (token.value) { + if (state === 'address') { + // handle use case where unquoted name includes a "<" + // Apple Mail truncates everything between an unexpected < and an address + // and so will we + token.value = token.value.replace(/^[^<]*<\s*/, ''); + } + data[state].push(token.value); + } + } + + // If there is no text but a comment, replace the two + if (!data.text.length && data.comment.length) { + data.text = data.comment; + data.comment = []; + } + + if (isGroup) { + // http://tools.ietf.org/html/rfc2822#appendix-A.1.3 + data.text = data.text.join(' '); + addresses.push({ + name: data.text || (address && address.name), + group: data.group.length ? addressparser(data.group.join(',')) : [] + }); + } else { + // If no address was found, try to detect one from regular text + if (!data.address.length && data.text.length) { + for (i = data.text.length - 1; i >= 0; i--) { + if (data.text[i].match(/^[^@\s]+@[^@\s]+$/)) { + data.address = data.text.splice(i, 1); + break; + } + } + + let _regexHandler = function (address) { + if (!data.address.length) { + data.address = [address.trim()]; + return ' '; + } else { + return address; + } + }; + + // still no address + if (!data.address.length) { + for (i = data.text.length - 1; i >= 0; i--) { + // fixed the regex to parse email address correctly when email address has more than one @ + data.text[i] = data.text[i].replace(/\s*\b[^@\s]+@[^\s]+\b\s*/, _regexHandler).trim(); + if (data.address.length) { + break; + } + } + } + } + + // If there's still is no text but a comment exixts, replace the two + if (!data.text.length && data.comment.length) { + data.text = data.comment; + data.comment = []; + } + + // Keep only the first address occurence, push others to regular text + if (data.address.length > 1) { + data.text = data.text.concat(data.address.splice(1)); + } + + // Join values with spaces + data.text = data.text.join(' '); + data.address = data.address.join(' '); + + if (!data.address && isGroup) { + return []; + } else { + address = { + address: data.address || data.text || '', + name: data.text || data.address || '' + }; + + if (address.address === address.name) { + if ((address.address || '').match(/@/)) { + address.name = ''; + } else { + address.address = ''; + } + } + + addresses.push(address); + } + } + + return addresses; +} + +/** + * Creates a Tokenizer object for tokenizing address field strings + * + * @constructor + * @param {String} str Address field string + */ +class Tokenizer { + constructor(str) { + this.str = (str || '').toString(); + this.operatorCurrent = ''; + this.operatorExpecting = ''; + this.node = null; + this.escaped = false; + + this.list = []; + /** + * Operator tokens and which tokens are expected to end the sequence + */ + this.operators = { + '"': '"', + '(': ')', + '<': '>', + ',': '', + ':': ';', + // Semicolons are not a legal delimiter per the RFC2822 grammar other + // than for terminating a group, but they are also not valid for any + // other use in this context. Given that some mail clients have + // historically allowed the semicolon as a delimiter equivalent to the + // comma in their UI, it makes sense to treat them the same as a comma + // when used outside of a group. + ';': '' + }; + } + + /** + * Tokenizes the original input string + * + * @return {Array} An array of operator|text tokens + */ + tokenize() { + let chr, + list = []; + for (let i = 0, len = this.str.length; i < len; i++) { + chr = this.str.charAt(i); + this.checkChar(chr); + } + + this.list.forEach(node => { + node.value = (node.value || '').toString().trim(); + if (node.value) { + list.push(node); + } + }); + + return list; + } + + /** + * Checks if a character is an operator or text and acts accordingly + * + * @param {String} chr Character from the address field + */ + checkChar(chr) { + if (this.escaped) { + // ignore next condition blocks + } else if (chr === this.operatorExpecting) { + this.node = { + type: 'operator', + value: chr + }; + this.list.push(this.node); + this.node = null; + this.operatorExpecting = ''; + this.escaped = false; + return; + } else if (!this.operatorExpecting && chr in this.operators) { + this.node = { + type: 'operator', + value: chr + }; + this.list.push(this.node); + this.node = null; + this.operatorExpecting = this.operators[chr]; + this.escaped = false; + return; + } else if (['"', "'"].includes(this.operatorExpecting) && chr === '\\') { + this.escaped = true; + return; + } + + if (!this.node) { + this.node = { + type: 'text', + value: '' + }; + this.list.push(this.node); + } + + if (chr === '\n') { + // Convert newlines to spaces. Carriage return is ignored as \r and \n usually + // go together anyway and there already is a WS for \n. Lone \r means something is fishy. + chr = ' '; + } + + if (chr.charCodeAt(0) >= 0x21 || [' ', '\t'].includes(chr)) { + // skip command bytes + this.node.value += chr; + } + + this.escaped = false; + } +} + +/** + * Parses structured e-mail addresses from an address field + * + * Example: + * + * 'Name ' + * + * will be converted to + * + * [{name: 'Name', address: 'address@domain'}] + * + * @param {String} str Address field + * @return {Array} An array of address objects + */ +function addressparser(str, options) { + options = options || {}; + + let tokenizer = new Tokenizer(str); + let tokens = tokenizer.tokenize(); + + let addresses = []; + let address = []; + let parsedAddresses = []; + + tokens.forEach(token => { + if (token.type === 'operator' && (token.value === ',' || token.value === ';')) { + if (address.length) { + addresses.push(address); + } + address = []; + } else { + address.push(token); + } + }); + + if (address.length) { + addresses.push(address); + } + + addresses.forEach(address => { + address = _handleAddress(address); + if (address.length) { + parsedAddresses = parsedAddresses.concat(address); + } + }); + + if (options.flatten) { + let addresses = []; + let walkAddressList = list => { + list.forEach(address => { + if (address.group) { + return walkAddressList(address.group); + } else { + addresses.push(address); + } + }); + }; + walkAddressList(parsedAddresses); + return addresses; + } + + return parsedAddresses; +} + +// expose to the world +module.exports = addressparser; diff --git a/system/login/node_modules/nodemailer/lib/base64/index.js b/system/login/node_modules/nodemailer/lib/base64/index.js new file mode 100644 index 0000000..cafd5d8 --- /dev/null +++ b/system/login/node_modules/nodemailer/lib/base64/index.js @@ -0,0 +1,142 @@ +'use strict'; + +const Transform = require('stream').Transform; + +/** + * Encodes a Buffer into a base64 encoded string + * + * @param {Buffer} buffer Buffer to convert + * @returns {String} base64 encoded string + */ +function encode(buffer) { + if (typeof buffer === 'string') { + buffer = Buffer.from(buffer, 'utf-8'); + } + + return buffer.toString('base64'); +} + +/** + * Adds soft line breaks to a base64 string + * + * @param {String} str base64 encoded string that might need line wrapping + * @param {Number} [lineLength=76] Maximum allowed length for a line + * @returns {String} Soft-wrapped base64 encoded string + */ +function wrap(str, lineLength) { + str = (str || '').toString(); + lineLength = lineLength || 76; + + if (str.length <= lineLength) { + return str; + } + + let result = []; + let pos = 0; + let chunkLength = lineLength * 1024; + while (pos < str.length) { + let wrappedLines = str + .substr(pos, chunkLength) + .replace(new RegExp('.{' + lineLength + '}', 'g'), '$&\r\n') + .trim(); + result.push(wrappedLines); + pos += chunkLength; + } + + return result.join('\r\n').trim(); +} + +/** + * Creates a transform stream for encoding data to base64 encoding + * + * @constructor + * @param {Object} options Stream options + * @param {Number} [options.lineLength=76] Maximum length for lines, set to false to disable wrapping + */ +class Encoder extends Transform { + constructor(options) { + super(); + // init Transform + this.options = options || {}; + + if (this.options.lineLength !== false) { + this.options.lineLength = this.options.lineLength || 76; + } + + this._curLine = ''; + this._remainingBytes = false; + + this.inputBytes = 0; + this.outputBytes = 0; + } + + _transform(chunk, encoding, done) { + if (encoding !== 'buffer') { + chunk = Buffer.from(chunk, encoding); + } + + if (!chunk || !chunk.length) { + return setImmediate(done); + } + + this.inputBytes += chunk.length; + + if (this._remainingBytes && this._remainingBytes.length) { + chunk = Buffer.concat([this._remainingBytes, chunk], this._remainingBytes.length + chunk.length); + this._remainingBytes = false; + } + + if (chunk.length % 3) { + this._remainingBytes = chunk.slice(chunk.length - (chunk.length % 3)); + chunk = chunk.slice(0, chunk.length - (chunk.length % 3)); + } else { + this._remainingBytes = false; + } + + let b64 = this._curLine + encode(chunk); + + if (this.options.lineLength) { + b64 = wrap(b64, this.options.lineLength); + + // remove last line as it is still most probably incomplete + let lastLF = b64.lastIndexOf('\n'); + if (lastLF < 0) { + this._curLine = b64; + b64 = ''; + } else if (lastLF === b64.length - 1) { + this._curLine = ''; + } else { + this._curLine = b64.substr(lastLF + 1); + b64 = b64.substr(0, lastLF + 1); + } + } + + if (b64) { + this.outputBytes += b64.length; + this.push(Buffer.from(b64, 'ascii')); + } + + setImmediate(done); + } + + _flush(done) { + if (this._remainingBytes && this._remainingBytes.length) { + this._curLine += encode(this._remainingBytes); + } + + if (this._curLine) { + this._curLine = wrap(this._curLine, this.options.lineLength); + this.outputBytes += this._curLine.length; + this.push(this._curLine, 'ascii'); + this._curLine = ''; + } + done(); + } +} + +// expose to the world +module.exports = { + encode, + wrap, + Encoder +}; diff --git a/system/login/node_modules/nodemailer/lib/dkim/index.js b/system/login/node_modules/nodemailer/lib/dkim/index.js new file mode 100644 index 0000000..7536b37 --- /dev/null +++ b/system/login/node_modules/nodemailer/lib/dkim/index.js @@ -0,0 +1,251 @@ +'use strict'; + +// FIXME: +// replace this Transform mess with a method that pipes input argument to output argument + +const MessageParser = require('./message-parser'); +const RelaxedBody = require('./relaxed-body'); +const sign = require('./sign'); +const PassThrough = require('stream').PassThrough; +const fs = require('fs'); +const path = require('path'); +const crypto = require('crypto'); + +const DKIM_ALGO = 'sha256'; +const MAX_MESSAGE_SIZE = 128 * 1024; // buffer messages larger than this to disk + +/* +// Usage: + +let dkim = new DKIM({ + domainName: 'example.com', + keySelector: 'key-selector', + privateKey, + cacheDir: '/tmp' +}); +dkim.sign(input).pipe(process.stdout); + +// Where inputStream is a rfc822 message (either a stream, string or Buffer) +// and outputStream is a DKIM signed rfc822 message +*/ + +class DKIMSigner { + constructor(options, keys, input, output) { + this.options = options || {}; + this.keys = keys; + + this.cacheTreshold = Number(this.options.cacheTreshold) || MAX_MESSAGE_SIZE; + this.hashAlgo = this.options.hashAlgo || DKIM_ALGO; + + this.cacheDir = this.options.cacheDir || false; + + this.chunks = []; + this.chunklen = 0; + this.readPos = 0; + this.cachePath = this.cacheDir ? path.join(this.cacheDir, 'message.' + Date.now() + '-' + crypto.randomBytes(14).toString('hex')) : false; + this.cache = false; + + this.headers = false; + this.bodyHash = false; + this.parser = false; + this.relaxedBody = false; + + this.input = input; + this.output = output; + this.output.usingCache = false; + + this.hasErrored = false; + + this.input.on('error', err => { + this.hasErrored = true; + this.cleanup(); + output.emit('error', err); + }); + } + + cleanup() { + if (!this.cache || !this.cachePath) { + return; + } + fs.unlink(this.cachePath, () => false); + } + + createReadCache() { + // pipe remainings to cache file + this.cache = fs.createReadStream(this.cachePath); + this.cache.once('error', err => { + this.cleanup(); + this.output.emit('error', err); + }); + this.cache.once('close', () => { + this.cleanup(); + }); + this.cache.pipe(this.output); + } + + sendNextChunk() { + if (this.hasErrored) { + return; + } + + if (this.readPos >= this.chunks.length) { + if (!this.cache) { + return this.output.end(); + } + return this.createReadCache(); + } + let chunk = this.chunks[this.readPos++]; + if (this.output.write(chunk) === false) { + return this.output.once('drain', () => { + this.sendNextChunk(); + }); + } + setImmediate(() => this.sendNextChunk()); + } + + sendSignedOutput() { + let keyPos = 0; + let signNextKey = () => { + if (keyPos >= this.keys.length) { + this.output.write(this.parser.rawHeaders); + return setImmediate(() => this.sendNextChunk()); + } + let key = this.keys[keyPos++]; + let dkimField = sign(this.headers, this.hashAlgo, this.bodyHash, { + domainName: key.domainName, + keySelector: key.keySelector, + privateKey: key.privateKey, + headerFieldNames: this.options.headerFieldNames, + skipFields: this.options.skipFields + }); + if (dkimField) { + this.output.write(Buffer.from(dkimField + '\r\n')); + } + return setImmediate(signNextKey); + }; + + if (this.bodyHash && this.headers) { + return signNextKey(); + } + + this.output.write(this.parser.rawHeaders); + this.sendNextChunk(); + } + + createWriteCache() { + this.output.usingCache = true; + // pipe remainings to cache file + this.cache = fs.createWriteStream(this.cachePath); + this.cache.once('error', err => { + this.cleanup(); + // drain input + this.relaxedBody.unpipe(this.cache); + this.relaxedBody.on('readable', () => { + while (this.relaxedBody.read() !== null) { + // do nothing + } + }); + this.hasErrored = true; + // emit error + this.output.emit('error', err); + }); + this.cache.once('close', () => { + this.sendSignedOutput(); + }); + this.relaxedBody.removeAllListeners('readable'); + this.relaxedBody.pipe(this.cache); + } + + signStream() { + this.parser = new MessageParser(); + this.relaxedBody = new RelaxedBody({ + hashAlgo: this.hashAlgo + }); + + this.parser.on('headers', value => { + this.headers = value; + }); + + this.relaxedBody.on('hash', value => { + this.bodyHash = value; + }); + + this.relaxedBody.on('readable', () => { + let chunk; + if (this.cache) { + return; + } + while ((chunk = this.relaxedBody.read()) !== null) { + this.chunks.push(chunk); + this.chunklen += chunk.length; + if (this.chunklen >= this.cacheTreshold && this.cachePath) { + return this.createWriteCache(); + } + } + }); + + this.relaxedBody.on('end', () => { + if (this.cache) { + return; + } + this.sendSignedOutput(); + }); + + this.parser.pipe(this.relaxedBody); + setImmediate(() => this.input.pipe(this.parser)); + } +} + +class DKIM { + constructor(options) { + this.options = options || {}; + this.keys = [].concat( + this.options.keys || { + domainName: options.domainName, + keySelector: options.keySelector, + privateKey: options.privateKey + } + ); + } + + sign(input, extraOptions) { + let output = new PassThrough(); + let inputStream = input; + let writeValue = false; + + if (Buffer.isBuffer(input)) { + writeValue = input; + inputStream = new PassThrough(); + } else if (typeof input === 'string') { + writeValue = Buffer.from(input); + inputStream = new PassThrough(); + } + + let options = this.options; + if (extraOptions && Object.keys(extraOptions).length) { + options = {}; + Object.keys(this.options || {}).forEach(key => { + options[key] = this.options[key]; + }); + Object.keys(extraOptions || {}).forEach(key => { + if (!(key in options)) { + options[key] = extraOptions[key]; + } + }); + } + + let signer = new DKIMSigner(options, this.keys, inputStream, output); + setImmediate(() => { + signer.signStream(); + if (writeValue) { + setImmediate(() => { + inputStream.end(writeValue); + }); + } + }); + + return output; + } +} + +module.exports = DKIM; diff --git a/system/login/node_modules/nodemailer/lib/dkim/message-parser.js b/system/login/node_modules/nodemailer/lib/dkim/message-parser.js new file mode 100644 index 0000000..8ee93d2 --- /dev/null +++ b/system/login/node_modules/nodemailer/lib/dkim/message-parser.js @@ -0,0 +1,155 @@ +'use strict'; + +const Transform = require('stream').Transform; + +/** + * MessageParser instance is a transform stream that separates message headers + * from the rest of the body. Headers are emitted with the 'headers' event. Message + * body is passed on as the resulting stream. + */ +class MessageParser extends Transform { + constructor(options) { + super(options); + this.lastBytes = Buffer.alloc(4); + this.headersParsed = false; + this.headerBytes = 0; + this.headerChunks = []; + this.rawHeaders = false; + this.bodySize = 0; + } + + /** + * Keeps count of the last 4 bytes in order to detect line breaks on chunk boundaries + * + * @param {Buffer} data Next data chunk from the stream + */ + updateLastBytes(data) { + let lblen = this.lastBytes.length; + let nblen = Math.min(data.length, lblen); + + // shift existing bytes + for (let i = 0, len = lblen - nblen; i < len; i++) { + this.lastBytes[i] = this.lastBytes[i + nblen]; + } + + // add new bytes + for (let i = 1; i <= nblen; i++) { + this.lastBytes[lblen - i] = data[data.length - i]; + } + } + + /** + * Finds and removes message headers from the remaining body. We want to keep + * headers separated until final delivery to be able to modify these + * + * @param {Buffer} data Next chunk of data + * @return {Boolean} Returns true if headers are already found or false otherwise + */ + checkHeaders(data) { + if (this.headersParsed) { + return true; + } + + let lblen = this.lastBytes.length; + let headerPos = 0; + this.curLinePos = 0; + for (let i = 0, len = this.lastBytes.length + data.length; i < len; i++) { + let chr; + if (i < lblen) { + chr = this.lastBytes[i]; + } else { + chr = data[i - lblen]; + } + if (chr === 0x0a && i) { + let pr1 = i - 1 < lblen ? this.lastBytes[i - 1] : data[i - 1 - lblen]; + let pr2 = i > 1 ? (i - 2 < lblen ? this.lastBytes[i - 2] : data[i - 2 - lblen]) : false; + if (pr1 === 0x0a) { + this.headersParsed = true; + headerPos = i - lblen + 1; + this.headerBytes += headerPos; + break; + } else if (pr1 === 0x0d && pr2 === 0x0a) { + this.headersParsed = true; + headerPos = i - lblen + 1; + this.headerBytes += headerPos; + break; + } + } + } + + if (this.headersParsed) { + this.headerChunks.push(data.slice(0, headerPos)); + this.rawHeaders = Buffer.concat(this.headerChunks, this.headerBytes); + this.headerChunks = null; + this.emit('headers', this.parseHeaders()); + if (data.length - 1 > headerPos) { + let chunk = data.slice(headerPos); + this.bodySize += chunk.length; + // this would be the first chunk of data sent downstream + setImmediate(() => this.push(chunk)); + } + return false; + } else { + this.headerBytes += data.length; + this.headerChunks.push(data); + } + + // store last 4 bytes to catch header break + this.updateLastBytes(data); + + return false; + } + + _transform(chunk, encoding, callback) { + if (!chunk || !chunk.length) { + return callback(); + } + + if (typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + + let headersFound; + + try { + headersFound = this.checkHeaders(chunk); + } catch (E) { + return callback(E); + } + + if (headersFound) { + this.bodySize += chunk.length; + this.push(chunk); + } + + setImmediate(callback); + } + + _flush(callback) { + if (this.headerChunks) { + let chunk = Buffer.concat(this.headerChunks, this.headerBytes); + this.bodySize += chunk.length; + this.push(chunk); + this.headerChunks = null; + } + callback(); + } + + parseHeaders() { + let lines = (this.rawHeaders || '').toString().split(/\r?\n/); + for (let i = lines.length - 1; i > 0; i--) { + if (/^\s/.test(lines[i])) { + lines[i - 1] += '\n' + lines[i]; + lines.splice(i, 1); + } + } + return lines + .filter(line => line.trim()) + .map(line => ({ + key: line.substr(0, line.indexOf(':')).trim().toLowerCase(), + line + })); + } +} + +module.exports = MessageParser; diff --git a/system/login/node_modules/nodemailer/lib/dkim/relaxed-body.js b/system/login/node_modules/nodemailer/lib/dkim/relaxed-body.js new file mode 100644 index 0000000..03558e8 --- /dev/null +++ b/system/login/node_modules/nodemailer/lib/dkim/relaxed-body.js @@ -0,0 +1,154 @@ +'use strict'; + +// streams through a message body and calculates relaxed body hash + +const Transform = require('stream').Transform; +const crypto = require('crypto'); + +class RelaxedBody extends Transform { + constructor(options) { + super(); + options = options || {}; + this.chunkBuffer = []; + this.chunkBufferLen = 0; + this.bodyHash = crypto.createHash(options.hashAlgo || 'sha1'); + this.remainder = ''; + this.byteLength = 0; + + this.debug = options.debug; + this._debugBody = options.debug ? [] : false; + } + + updateHash(chunk) { + let bodyStr; + + // find next remainder + let nextRemainder = ''; + + // This crux finds and removes the spaces from the last line and the newline characters after the last non-empty line + // If we get another chunk that does not match this description then we can restore the previously processed data + let state = 'file'; + for (let i = chunk.length - 1; i >= 0; i--) { + let c = chunk[i]; + + if (state === 'file' && (c === 0x0a || c === 0x0d)) { + // do nothing, found \n or \r at the end of chunk, stil end of file + } else if (state === 'file' && (c === 0x09 || c === 0x20)) { + // switch to line ending mode, this is the last non-empty line + state = 'line'; + } else if (state === 'line' && (c === 0x09 || c === 0x20)) { + // do nothing, found ' ' or \t at the end of line, keep processing the last non-empty line + } else if (state === 'file' || state === 'line') { + // non line/file ending character found, switch to body mode + state = 'body'; + if (i === chunk.length - 1) { + // final char is not part of line end or file end, so do nothing + break; + } + } + + if (i === 0) { + // reached to the beginning of the chunk, check if it is still about the ending + // and if the remainder also matches + if ( + (state === 'file' && (!this.remainder || /[\r\n]$/.test(this.remainder))) || + (state === 'line' && (!this.remainder || /[ \t]$/.test(this.remainder))) + ) { + // keep everything + this.remainder += chunk.toString('binary'); + return; + } else if (state === 'line' || state === 'file') { + // process existing remainder as normal line but store the current chunk + nextRemainder = chunk.toString('binary'); + chunk = false; + break; + } + } + + if (state !== 'body') { + continue; + } + + // reached first non ending byte + nextRemainder = chunk.slice(i + 1).toString('binary'); + chunk = chunk.slice(0, i + 1); + break; + } + + let needsFixing = !!this.remainder; + if (chunk && !needsFixing) { + // check if we even need to change anything + for (let i = 0, len = chunk.length; i < len; i++) { + if (i && chunk[i] === 0x0a && chunk[i - 1] !== 0x0d) { + // missing \r before \n + needsFixing = true; + break; + } else if (i && chunk[i] === 0x0d && chunk[i - 1] === 0x20) { + // trailing WSP found + needsFixing = true; + break; + } else if (i && chunk[i] === 0x20 && chunk[i - 1] === 0x20) { + // multiple spaces found, needs to be replaced with just one + needsFixing = true; + break; + } else if (chunk[i] === 0x09) { + // TAB found, needs to be replaced with a space + needsFixing = true; + break; + } + } + } + + if (needsFixing) { + bodyStr = this.remainder + (chunk ? chunk.toString('binary') : ''); + this.remainder = nextRemainder; + bodyStr = bodyStr + .replace(/\r?\n/g, '\n') // use js line endings + .replace(/[ \t]*$/gm, '') // remove line endings, rtrim + .replace(/[ \t]+/gm, ' ') // single spaces + .replace(/\n/g, '\r\n'); // restore rfc822 line endings + chunk = Buffer.from(bodyStr, 'binary'); + } else if (nextRemainder) { + this.remainder = nextRemainder; + } + + if (this.debug) { + this._debugBody.push(chunk); + } + this.bodyHash.update(chunk); + } + + _transform(chunk, encoding, callback) { + if (!chunk || !chunk.length) { + return callback(); + } + + if (typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + + this.updateHash(chunk); + + this.byteLength += chunk.length; + this.push(chunk); + callback(); + } + + _flush(callback) { + // generate final hash and emit it + if (/[\r\n]$/.test(this.remainder) && this.byteLength > 2) { + // add terminating line end + this.bodyHash.update(Buffer.from('\r\n')); + } + if (!this.byteLength) { + // emit empty line buffer to keep the stream flowing + this.push(Buffer.from('\r\n')); + // this.bodyHash.update(Buffer.from('\r\n')); + } + + this.emit('hash', this.bodyHash.digest('base64'), this.debug ? Buffer.concat(this._debugBody) : false); + callback(); + } +} + +module.exports = RelaxedBody; diff --git a/system/login/node_modules/nodemailer/lib/dkim/sign.js b/system/login/node_modules/nodemailer/lib/dkim/sign.js new file mode 100644 index 0000000..b243dc3 --- /dev/null +++ b/system/login/node_modules/nodemailer/lib/dkim/sign.js @@ -0,0 +1,117 @@ +'use strict'; + +const punycode = require('punycode'); +const mimeFuncs = require('../mime-funcs'); +const crypto = require('crypto'); + +/** + * Returns DKIM signature header line + * + * @param {Object} headers Parsed headers object from MessageParser + * @param {String} bodyHash Base64 encoded hash of the message + * @param {Object} options DKIM options + * @param {String} options.domainName Domain name to be signed for + * @param {String} options.keySelector DKIM key selector to use + * @param {String} options.privateKey DKIM private key to use + * @return {String} Complete header line + */ + +module.exports = (headers, hashAlgo, bodyHash, options) => { + options = options || {}; + + // all listed fields from RFC4871 #5.5 + let defaultFieldNames = + 'From:Sender:Reply-To:Subject:Date:Message-ID:To:' + + 'Cc:MIME-Version:Content-Type:Content-Transfer-Encoding:Content-ID:' + + 'Content-Description:Resent-Date:Resent-From:Resent-Sender:' + + 'Resent-To:Resent-Cc:Resent-Message-ID:In-Reply-To:References:' + + 'List-Id:List-Help:List-Unsubscribe:List-Subscribe:List-Post:' + + 'List-Owner:List-Archive'; + + let fieldNames = options.headerFieldNames || defaultFieldNames; + + let canonicalizedHeaderData = relaxedHeaders(headers, fieldNames, options.skipFields); + let dkimHeader = generateDKIMHeader(options.domainName, options.keySelector, canonicalizedHeaderData.fieldNames, hashAlgo, bodyHash); + + let signer, signature; + + canonicalizedHeaderData.headers += 'dkim-signature:' + relaxedHeaderLine(dkimHeader); + + signer = crypto.createSign(('rsa-' + hashAlgo).toUpperCase()); + signer.update(canonicalizedHeaderData.headers); + try { + signature = signer.sign(options.privateKey, 'base64'); + } catch (E) { + return false; + } + + return dkimHeader + signature.replace(/(^.{73}|.{75}(?!\r?\n|\r))/g, '$&\r\n ').trim(); +}; + +module.exports.relaxedHeaders = relaxedHeaders; + +function generateDKIMHeader(domainName, keySelector, fieldNames, hashAlgo, bodyHash) { + let dkim = [ + 'v=1', + 'a=rsa-' + hashAlgo, + 'c=relaxed/relaxed', + 'd=' + punycode.toASCII(domainName), + 'q=dns/txt', + 's=' + keySelector, + 'bh=' + bodyHash, + 'h=' + fieldNames + ].join('; '); + + return mimeFuncs.foldLines('DKIM-Signature: ' + dkim, 76) + ';\r\n b='; +} + +function relaxedHeaders(headers, fieldNames, skipFields) { + let includedFields = new Set(); + let skip = new Set(); + let headerFields = new Map(); + + (skipFields || '') + .toLowerCase() + .split(':') + .forEach(field => { + skip.add(field.trim()); + }); + + (fieldNames || '') + .toLowerCase() + .split(':') + .filter(field => !skip.has(field.trim())) + .forEach(field => { + includedFields.add(field.trim()); + }); + + for (let i = headers.length - 1; i >= 0; i--) { + let line = headers[i]; + // only include the first value from bottom to top + if (includedFields.has(line.key) && !headerFields.has(line.key)) { + headerFields.set(line.key, relaxedHeaderLine(line.line)); + } + } + + let headersList = []; + let fields = []; + includedFields.forEach(field => { + if (headerFields.has(field)) { + fields.push(field); + headersList.push(field + ':' + headerFields.get(field)); + } + }); + + return { + headers: headersList.join('\r\n') + '\r\n', + fieldNames: fields.join(':') + }; +} + +function relaxedHeaderLine(line) { + return line + .substr(line.indexOf(':') + 1) + .replace(/\r?\n/g, '') + .replace(/\s+/g, ' ') + .trim(); +} diff --git a/system/login/node_modules/nodemailer/lib/fetch/cookies.js b/system/login/node_modules/nodemailer/lib/fetch/cookies.js new file mode 100644 index 0000000..917b840 --- /dev/null +++ b/system/login/node_modules/nodemailer/lib/fetch/cookies.js @@ -0,0 +1,281 @@ +'use strict'; + +// module to handle cookies + +const urllib = require('url'); + +const SESSION_TIMEOUT = 1800; // 30 min + +/** + * Creates a biskviit cookie jar for managing cookie values in memory + * + * @constructor + * @param {Object} [options] Optional options object + */ +class Cookies { + constructor(options) { + this.options = options || {}; + this.cookies = []; + } + + /** + * Stores a cookie string to the cookie storage + * + * @param {String} cookieStr Value from the 'Set-Cookie:' header + * @param {String} url Current URL + */ + set(cookieStr, url) { + let urlparts = urllib.parse(url || ''); + let cookie = this.parse(cookieStr); + let domain; + + if (cookie.domain) { + domain = cookie.domain.replace(/^\./, ''); + + // do not allow cross origin cookies + if ( + // can't be valid if the requested domain is shorter than current hostname + urlparts.hostname.length < domain.length || + // prefix domains with dot to be sure that partial matches are not used + ('.' + urlparts.hostname).substr(-domain.length + 1) !== '.' + domain + ) { + cookie.domain = urlparts.hostname; + } + } else { + cookie.domain = urlparts.hostname; + } + + if (!cookie.path) { + cookie.path = this.getPath(urlparts.pathname); + } + + // if no expire date, then use sessionTimeout value + if (!cookie.expires) { + cookie.expires = new Date(Date.now() + (Number(this.options.sessionTimeout || SESSION_TIMEOUT) || SESSION_TIMEOUT) * 1000); + } + + return this.add(cookie); + } + + /** + * Returns cookie string for the 'Cookie:' header. + * + * @param {String} url URL to check for + * @returns {String} Cookie header or empty string if no matches were found + */ + get(url) { + return this.list(url) + .map(cookie => cookie.name + '=' + cookie.value) + .join('; '); + } + + /** + * Lists all valied cookie objects for the specified URL + * + * @param {String} url URL to check for + * @returns {Array} An array of cookie objects + */ + list(url) { + let result = []; + let i; + let cookie; + + for (i = this.cookies.length - 1; i >= 0; i--) { + cookie = this.cookies[i]; + + if (this.isExpired(cookie)) { + this.cookies.splice(i, i); + continue; + } + + if (this.match(cookie, url)) { + result.unshift(cookie); + } + } + + return result; + } + + /** + * Parses cookie string from the 'Set-Cookie:' header + * + * @param {String} cookieStr String from the 'Set-Cookie:' header + * @returns {Object} Cookie object + */ + parse(cookieStr) { + let cookie = {}; + + (cookieStr || '') + .toString() + .split(';') + .forEach(cookiePart => { + let valueParts = cookiePart.split('='); + let key = valueParts.shift().trim().toLowerCase(); + let value = valueParts.join('=').trim(); + let domain; + + if (!key) { + // skip empty parts + return; + } + + switch (key) { + case 'expires': + value = new Date(value); + // ignore date if can not parse it + if (value.toString() !== 'Invalid Date') { + cookie.expires = value; + } + break; + + case 'path': + cookie.path = value; + break; + + case 'domain': + domain = value.toLowerCase(); + if (domain.length && domain.charAt(0) !== '.') { + domain = '.' + domain; // ensure preceeding dot for user set domains + } + cookie.domain = domain; + break; + + case 'max-age': + cookie.expires = new Date(Date.now() + (Number(value) || 0) * 1000); + break; + + case 'secure': + cookie.secure = true; + break; + + case 'httponly': + cookie.httponly = true; + break; + + default: + if (!cookie.name) { + cookie.name = key; + cookie.value = value; + } + } + }); + + return cookie; + } + + /** + * Checks if a cookie object is valid for a specified URL + * + * @param {Object} cookie Cookie object + * @param {String} url URL to check for + * @returns {Boolean} true if cookie is valid for specifiec URL + */ + match(cookie, url) { + let urlparts = urllib.parse(url || ''); + + // check if hostname matches + // .foo.com also matches subdomains, foo.com does not + if ( + urlparts.hostname !== cookie.domain && + (cookie.domain.charAt(0) !== '.' || ('.' + urlparts.hostname).substr(-cookie.domain.length) !== cookie.domain) + ) { + return false; + } + + // check if path matches + let path = this.getPath(urlparts.pathname); + if (path.substr(0, cookie.path.length) !== cookie.path) { + return false; + } + + // check secure argument + if (cookie.secure && urlparts.protocol !== 'https:') { + return false; + } + + return true; + } + + /** + * Adds (or updates/removes if needed) a cookie object to the cookie storage + * + * @param {Object} cookie Cookie value to be stored + */ + add(cookie) { + let i; + let len; + + // nothing to do here + if (!cookie || !cookie.name) { + return false; + } + + // overwrite if has same params + for (i = 0, len = this.cookies.length; i < len; i++) { + if (this.compare(this.cookies[i], cookie)) { + // check if the cookie needs to be removed instead + if (this.isExpired(cookie)) { + this.cookies.splice(i, 1); // remove expired/unset cookie + return false; + } + + this.cookies[i] = cookie; + return true; + } + } + + // add as new if not already expired + if (!this.isExpired(cookie)) { + this.cookies.push(cookie); + } + + return true; + } + + /** + * Checks if two cookie objects are the same + * + * @param {Object} a Cookie to check against + * @param {Object} b Cookie to check against + * @returns {Boolean} True, if the cookies are the same + */ + compare(a, b) { + return a.name === b.name && a.path === b.path && a.domain === b.domain && a.secure === b.secure && a.httponly === a.httponly; + } + + /** + * Checks if a cookie is expired + * + * @param {Object} cookie Cookie object to check against + * @returns {Boolean} True, if the cookie is expired + */ + isExpired(cookie) { + return (cookie.expires && cookie.expires < new Date()) || !cookie.value; + } + + /** + * Returns normalized cookie path for an URL path argument + * + * @param {String} pathname + * @returns {String} Normalized path + */ + getPath(pathname) { + let path = (pathname || '/').split('/'); + path.pop(); // remove filename part + path = path.join('/').trim(); + + // ensure path prefix / + if (path.charAt(0) !== '/') { + path = '/' + path; + } + + // ensure path suffix / + if (path.substr(-1) !== '/') { + path += '/'; + } + + return path; + } +} + +module.exports = Cookies; diff --git a/system/login/node_modules/nodemailer/lib/fetch/index.js b/system/login/node_modules/nodemailer/lib/fetch/index.js new file mode 100644 index 0000000..2e73dbd --- /dev/null +++ b/system/login/node_modules/nodemailer/lib/fetch/index.js @@ -0,0 +1,274 @@ +'use strict'; + +const http = require('http'); +const https = require('https'); +const urllib = require('url'); +const zlib = require('zlib'); +const PassThrough = require('stream').PassThrough; +const Cookies = require('./cookies'); +const packageData = require('../../package.json'); +const net = require('net'); + +const MAX_REDIRECTS = 5; + +module.exports = function (url, options) { + return nmfetch(url, options); +}; + +module.exports.Cookies = Cookies; + +function nmfetch(url, options) { + options = options || {}; + + options.fetchRes = options.fetchRes || new PassThrough(); + options.cookies = options.cookies || new Cookies(); + options.redirects = options.redirects || 0; + options.maxRedirects = isNaN(options.maxRedirects) ? MAX_REDIRECTS : options.maxRedirects; + + if (options.cookie) { + [].concat(options.cookie || []).forEach(cookie => { + options.cookies.set(cookie, url); + }); + options.cookie = false; + } + + let fetchRes = options.fetchRes; + let parsed = urllib.parse(url); + let method = (options.method || '').toString().trim().toUpperCase() || 'GET'; + let finished = false; + let cookies; + let body; + + let handler = parsed.protocol === 'https:' ? https : http; + + let headers = { + 'accept-encoding': 'gzip,deflate', + 'user-agent': 'nodemailer/' + packageData.version + }; + + Object.keys(options.headers || {}).forEach(key => { + headers[key.toLowerCase().trim()] = options.headers[key]; + }); + + if (options.userAgent) { + headers['user-agent'] = options.userAgent; + } + + if (parsed.auth) { + headers.Authorization = 'Basic ' + Buffer.from(parsed.auth).toString('base64'); + } + + if ((cookies = options.cookies.get(url))) { + headers.cookie = cookies; + } + + if (options.body) { + if (options.contentType !== false) { + headers['Content-Type'] = options.contentType || 'application/x-www-form-urlencoded'; + } + + if (typeof options.body.pipe === 'function') { + // it's a stream + headers['Transfer-Encoding'] = 'chunked'; + body = options.body; + body.on('error', err => { + if (finished) { + return; + } + finished = true; + err.type = 'FETCH'; + err.sourceUrl = url; + fetchRes.emit('error', err); + }); + } else { + if (options.body instanceof Buffer) { + body = options.body; + } else if (typeof options.body === 'object') { + try { + // encodeURIComponent can fail on invalid input (partial emoji etc.) + body = Buffer.from( + Object.keys(options.body) + .map(key => { + let value = options.body[key].toString().trim(); + return encodeURIComponent(key) + '=' + encodeURIComponent(value); + }) + .join('&') + ); + } catch (E) { + if (finished) { + return; + } + finished = true; + E.type = 'FETCH'; + E.sourceUrl = url; + fetchRes.emit('error', E); + return; + } + } else { + body = Buffer.from(options.body.toString().trim()); + } + + headers['Content-Type'] = options.contentType || 'application/x-www-form-urlencoded'; + headers['Content-Length'] = body.length; + } + // if method is not provided, use POST instead of GET + method = (options.method || '').toString().trim().toUpperCase() || 'POST'; + } + + let req; + let reqOptions = { + method, + host: parsed.hostname, + path: parsed.path, + port: parsed.port ? parsed.port : parsed.protocol === 'https:' ? 443 : 80, + headers, + rejectUnauthorized: false, + agent: false + }; + + if (options.tls) { + Object.keys(options.tls).forEach(key => { + reqOptions[key] = options.tls[key]; + }); + } + + if (parsed.protocol === 'https:' && parsed.hostname && parsed.hostname !== reqOptions.host && !net.isIP(parsed.hostname) && !reqOptions.servername) { + reqOptions.servername = parsed.hostname; + } + + try { + req = handler.request(reqOptions); + } catch (E) { + finished = true; + setImmediate(() => { + E.type = 'FETCH'; + E.sourceUrl = url; + fetchRes.emit('error', E); + }); + return fetchRes; + } + + if (options.timeout) { + req.setTimeout(options.timeout, () => { + if (finished) { + return; + } + finished = true; + req.abort(); + let err = new Error('Request Timeout'); + err.type = 'FETCH'; + err.sourceUrl = url; + fetchRes.emit('error', err); + }); + } + + req.on('error', err => { + if (finished) { + return; + } + finished = true; + err.type = 'FETCH'; + err.sourceUrl = url; + fetchRes.emit('error', err); + }); + + req.on('response', res => { + let inflate; + + if (finished) { + return; + } + + switch (res.headers['content-encoding']) { + case 'gzip': + case 'deflate': + inflate = zlib.createUnzip(); + break; + } + + if (res.headers['set-cookie']) { + [].concat(res.headers['set-cookie'] || []).forEach(cookie => { + options.cookies.set(cookie, url); + }); + } + + if ([301, 302, 303, 307, 308].includes(res.statusCode) && res.headers.location) { + // redirect + options.redirects++; + if (options.redirects > options.maxRedirects) { + finished = true; + let err = new Error('Maximum redirect count exceeded'); + err.type = 'FETCH'; + err.sourceUrl = url; + fetchRes.emit('error', err); + req.abort(); + return; + } + // redirect does not include POST body + options.method = 'GET'; + options.body = false; + return nmfetch(urllib.resolve(url, res.headers.location), options); + } + + fetchRes.statusCode = res.statusCode; + fetchRes.headers = res.headers; + + if (res.statusCode >= 300 && !options.allowErrorResponse) { + finished = true; + let err = new Error('Invalid status code ' + res.statusCode); + err.type = 'FETCH'; + err.sourceUrl = url; + fetchRes.emit('error', err); + req.abort(); + return; + } + + res.on('error', err => { + if (finished) { + return; + } + finished = true; + err.type = 'FETCH'; + err.sourceUrl = url; + fetchRes.emit('error', err); + req.abort(); + }); + + if (inflate) { + res.pipe(inflate).pipe(fetchRes); + inflate.on('error', err => { + if (finished) { + return; + } + finished = true; + err.type = 'FETCH'; + err.sourceUrl = url; + fetchRes.emit('error', err); + req.abort(); + }); + } else { + res.pipe(fetchRes); + } + }); + + setImmediate(() => { + if (body) { + try { + if (typeof body.pipe === 'function') { + return body.pipe(req); + } else { + req.write(body); + } + } catch (err) { + finished = true; + err.type = 'FETCH'; + err.sourceUrl = url; + fetchRes.emit('error', err); + return; + } + } + req.end(); + }); + + return fetchRes; +} diff --git a/system/login/node_modules/nodemailer/lib/json-transport/index.js b/system/login/node_modules/nodemailer/lib/json-transport/index.js new file mode 100644 index 0000000..769bde6 --- /dev/null +++ b/system/login/node_modules/nodemailer/lib/json-transport/index.js @@ -0,0 +1,82 @@ +'use strict'; + +const packageData = require('../../package.json'); +const shared = require('../shared'); + +/** + * Generates a Transport object to generate JSON output + * + * @constructor + * @param {Object} optional config parameter + */ +class JSONTransport { + constructor(options) { + options = options || {}; + + this.options = options || {}; + + this.name = 'JSONTransport'; + this.version = packageData.version; + + this.logger = shared.getLogger(this.options, { + component: this.options.component || 'json-transport' + }); + } + + /** + *

Compiles a mailcomposer message and forwards it to handler that sends it.

+ * + * @param {Object} emailMessage MailComposer object + * @param {Function} callback Callback function to run when the sending is completed + */ + send(mail, done) { + // Sendmail strips this header line by itself + mail.message.keepBcc = true; + + let envelope = mail.data.envelope || mail.message.getEnvelope(); + let messageId = mail.message.messageId(); + + let recipients = [].concat(envelope.to || []); + if (recipients.length > 3) { + recipients.push('...and ' + recipients.splice(2).length + ' more'); + } + this.logger.info( + { + tnx: 'send', + messageId + }, + 'Composing JSON structure of %s to <%s>', + messageId, + recipients.join(', ') + ); + + setImmediate(() => { + mail.normalize((err, data) => { + if (err) { + this.logger.error( + { + err, + tnx: 'send', + messageId + }, + 'Failed building JSON structure for %s. %s', + messageId, + err.message + ); + return done(err); + } + + delete data.envelope; + delete data.normalizedHeaders; + + return done(null, { + envelope, + messageId, + message: this.options.skipEncoding ? data : JSON.stringify(data) + }); + }); + }); + } +} + +module.exports = JSONTransport; diff --git a/system/login/node_modules/nodemailer/lib/mail-composer/index.js b/system/login/node_modules/nodemailer/lib/mail-composer/index.js new file mode 100644 index 0000000..206d44c --- /dev/null +++ b/system/login/node_modules/nodemailer/lib/mail-composer/index.js @@ -0,0 +1,565 @@ +/* eslint no-undefined: 0 */ + +'use strict'; + +const MimeNode = require('../mime-node'); +const mimeFuncs = require('../mime-funcs'); + +/** + * Creates the object for composing a MimeNode instance out from the mail options + * + * @constructor + * @param {Object} mail Mail options + */ +class MailComposer { + constructor(mail) { + this.mail = mail || {}; + this.message = false; + } + + /** + * Builds MimeNode instance + */ + compile() { + this._alternatives = this.getAlternatives(); + this._htmlNode = this._alternatives.filter(alternative => /^text\/html\b/i.test(alternative.contentType)).pop(); + this._attachments = this.getAttachments(!!this._htmlNode); + + this._useRelated = !!(this._htmlNode && this._attachments.related.length); + this._useAlternative = this._alternatives.length > 1; + this._useMixed = this._attachments.attached.length > 1 || (this._alternatives.length && this._attachments.attached.length === 1); + + // Compose MIME tree + if (this.mail.raw) { + this.message = new MimeNode('message/rfc822', { newline: this.mail.newline }).setRaw(this.mail.raw); + } else if (this._useMixed) { + this.message = this._createMixed(); + } else if (this._useAlternative) { + this.message = this._createAlternative(); + } else if (this._useRelated) { + this.message = this._createRelated(); + } else { + this.message = this._createContentNode( + false, + [] + .concat(this._alternatives || []) + .concat(this._attachments.attached || []) + .shift() || { + contentType: 'text/plain', + content: '' + } + ); + } + + // Add custom headers + if (this.mail.headers) { + this.message.addHeader(this.mail.headers); + } + + // Add headers to the root node, always overrides custom headers + ['from', 'sender', 'to', 'cc', 'bcc', 'reply-to', 'in-reply-to', 'references', 'subject', 'message-id', 'date'].forEach(header => { + let key = header.replace(/-(\w)/g, (o, c) => c.toUpperCase()); + if (this.mail[key]) { + this.message.setHeader(header, this.mail[key]); + } + }); + + // Sets custom envelope + if (this.mail.envelope) { + this.message.setEnvelope(this.mail.envelope); + } + + // ensure Message-Id value + this.message.messageId(); + + return this.message; + } + + /** + * List all attachments. Resulting attachment objects can be used as input for MimeNode nodes + * + * @param {Boolean} findRelated If true separate related attachments from attached ones + * @returns {Object} An object of arrays (`related` and `attached`) + */ + getAttachments(findRelated) { + let icalEvent, eventObject; + let attachments = [].concat(this.mail.attachments || []).map((attachment, i) => { + let data; + let isMessageNode = /^message\//i.test(attachment.contentType); + + if (/^data:/i.test(attachment.path || attachment.href)) { + attachment = this._processDataUrl(attachment); + } + + let contentType = attachment.contentType || mimeFuncs.detectMimeType(attachment.filename || attachment.path || attachment.href || 'bin'); + let isImage = /^image\//i.test(contentType); + let contentDisposition = attachment.contentDisposition || (isMessageNode || (isImage && attachment.cid) ? 'inline' : 'attachment'); + + data = { + contentType, + contentDisposition, + contentTransferEncoding: 'contentTransferEncoding' in attachment ? attachment.contentTransferEncoding : 'base64' + }; + + if (attachment.filename) { + data.filename = attachment.filename; + } else if (!isMessageNode && attachment.filename !== false) { + data.filename = (attachment.path || attachment.href || '').split('/').pop().split('?').shift() || 'attachment-' + (i + 1); + if (data.filename.indexOf('.') < 0) { + data.filename += '.' + mimeFuncs.detectExtension(data.contentType); + } + } + + if (/^https?:\/\//i.test(attachment.path)) { + attachment.href = attachment.path; + attachment.path = undefined; + } + + if (attachment.cid) { + data.cid = attachment.cid; + } + + if (attachment.raw) { + data.raw = attachment.raw; + } else if (attachment.path) { + data.content = { + path: attachment.path + }; + } else if (attachment.href) { + data.content = { + href: attachment.href, + httpHeaders: attachment.httpHeaders + }; + } else { + data.content = attachment.content || ''; + } + + if (attachment.encoding) { + data.encoding = attachment.encoding; + } + + if (attachment.headers) { + data.headers = attachment.headers; + } + + return data; + }); + + if (this.mail.icalEvent) { + if ( + typeof this.mail.icalEvent === 'object' && + (this.mail.icalEvent.content || this.mail.icalEvent.path || this.mail.icalEvent.href || this.mail.icalEvent.raw) + ) { + icalEvent = this.mail.icalEvent; + } else { + icalEvent = { + content: this.mail.icalEvent + }; + } + + eventObject = {}; + Object.keys(icalEvent).forEach(key => { + eventObject[key] = icalEvent[key]; + }); + + eventObject.contentType = 'application/ics'; + if (!eventObject.headers) { + eventObject.headers = {}; + } + eventObject.filename = eventObject.filename || 'invite.ics'; + eventObject.headers['Content-Disposition'] = 'attachment'; + eventObject.headers['Content-Transfer-Encoding'] = 'base64'; + } + + if (!findRelated) { + return { + attached: attachments.concat(eventObject || []), + related: [] + }; + } else { + return { + attached: attachments.filter(attachment => !attachment.cid).concat(eventObject || []), + related: attachments.filter(attachment => !!attachment.cid) + }; + } + } + + /** + * List alternatives. Resulting objects can be used as input for MimeNode nodes + * + * @returns {Array} An array of alternative elements. Includes the `text` and `html` values as well + */ + getAlternatives() { + let alternatives = [], + text, + html, + watchHtml, + amp, + icalEvent, + eventObject; + + if (this.mail.text) { + if (typeof this.mail.text === 'object' && (this.mail.text.content || this.mail.text.path || this.mail.text.href || this.mail.text.raw)) { + text = this.mail.text; + } else { + text = { + content: this.mail.text + }; + } + text.contentType = 'text/plain; charset=utf-8'; + } + + if (this.mail.watchHtml) { + if ( + typeof this.mail.watchHtml === 'object' && + (this.mail.watchHtml.content || this.mail.watchHtml.path || this.mail.watchHtml.href || this.mail.watchHtml.raw) + ) { + watchHtml = this.mail.watchHtml; + } else { + watchHtml = { + content: this.mail.watchHtml + }; + } + watchHtml.contentType = 'text/watch-html; charset=utf-8'; + } + + if (this.mail.amp) { + if (typeof this.mail.amp === 'object' && (this.mail.amp.content || this.mail.amp.path || this.mail.amp.href || this.mail.amp.raw)) { + amp = this.mail.amp; + } else { + amp = { + content: this.mail.amp + }; + } + amp.contentType = 'text/x-amp-html; charset=utf-8'; + } + + // NB! when including attachments with a calendar alternative you might end up in a blank screen on some clients + if (this.mail.icalEvent) { + if ( + typeof this.mail.icalEvent === 'object' && + (this.mail.icalEvent.content || this.mail.icalEvent.path || this.mail.icalEvent.href || this.mail.icalEvent.raw) + ) { + icalEvent = this.mail.icalEvent; + } else { + icalEvent = { + content: this.mail.icalEvent + }; + } + + eventObject = {}; + Object.keys(icalEvent).forEach(key => { + eventObject[key] = icalEvent[key]; + }); + + if (eventObject.content && typeof eventObject.content === 'object') { + // we are going to have the same attachment twice, so mark this to be + // resolved just once + eventObject.content._resolve = true; + } + + eventObject.filename = false; + eventObject.contentType = 'text/calendar; charset=utf-8; method=' + (eventObject.method || 'PUBLISH').toString().trim().toUpperCase(); + if (!eventObject.headers) { + eventObject.headers = {}; + } + } + + if (this.mail.html) { + if (typeof this.mail.html === 'object' && (this.mail.html.content || this.mail.html.path || this.mail.html.href || this.mail.html.raw)) { + html = this.mail.html; + } else { + html = { + content: this.mail.html + }; + } + html.contentType = 'text/html; charset=utf-8'; + } + + [] + .concat(text || []) + .concat(watchHtml || []) + .concat(amp || []) + .concat(html || []) + .concat(eventObject || []) + .concat(this.mail.alternatives || []) + .forEach(alternative => { + let data; + + if (/^data:/i.test(alternative.path || alternative.href)) { + alternative = this._processDataUrl(alternative); + } + + data = { + contentType: alternative.contentType || mimeFuncs.detectMimeType(alternative.filename || alternative.path || alternative.href || 'txt'), + contentTransferEncoding: alternative.contentTransferEncoding + }; + + if (alternative.filename) { + data.filename = alternative.filename; + } + + if (/^https?:\/\//i.test(alternative.path)) { + alternative.href = alternative.path; + alternative.path = undefined; + } + + if (alternative.raw) { + data.raw = alternative.raw; + } else if (alternative.path) { + data.content = { + path: alternative.path + }; + } else if (alternative.href) { + data.content = { + href: alternative.href + }; + } else { + data.content = alternative.content || ''; + } + + if (alternative.encoding) { + data.encoding = alternative.encoding; + } + + if (alternative.headers) { + data.headers = alternative.headers; + } + + alternatives.push(data); + }); + + return alternatives; + } + + /** + * Builds multipart/mixed node. It should always contain different type of elements on the same level + * eg. text + attachments + * + * @param {Object} parentNode Parent for this note. If it does not exist, a root node is created + * @returns {Object} MimeNode node element + */ + _createMixed(parentNode) { + let node; + + if (!parentNode) { + node = new MimeNode('multipart/mixed', { + baseBoundary: this.mail.baseBoundary, + textEncoding: this.mail.textEncoding, + boundaryPrefix: this.mail.boundaryPrefix, + disableUrlAccess: this.mail.disableUrlAccess, + disableFileAccess: this.mail.disableFileAccess, + normalizeHeaderKey: this.mail.normalizeHeaderKey, + newline: this.mail.newline + }); + } else { + node = parentNode.createChild('multipart/mixed', { + disableUrlAccess: this.mail.disableUrlAccess, + disableFileAccess: this.mail.disableFileAccess, + normalizeHeaderKey: this.mail.normalizeHeaderKey, + newline: this.mail.newline + }); + } + + if (this._useAlternative) { + this._createAlternative(node); + } else if (this._useRelated) { + this._createRelated(node); + } + + [] + .concat((!this._useAlternative && this._alternatives) || []) + .concat(this._attachments.attached || []) + .forEach(element => { + // if the element is a html node from related subpart then ignore it + if (!this._useRelated || element !== this._htmlNode) { + this._createContentNode(node, element); + } + }); + + return node; + } + + /** + * Builds multipart/alternative node. It should always contain same type of elements on the same level + * eg. text + html view of the same data + * + * @param {Object} parentNode Parent for this note. If it does not exist, a root node is created + * @returns {Object} MimeNode node element + */ + _createAlternative(parentNode) { + let node; + + if (!parentNode) { + node = new MimeNode('multipart/alternative', { + baseBoundary: this.mail.baseBoundary, + textEncoding: this.mail.textEncoding, + boundaryPrefix: this.mail.boundaryPrefix, + disableUrlAccess: this.mail.disableUrlAccess, + disableFileAccess: this.mail.disableFileAccess, + normalizeHeaderKey: this.mail.normalizeHeaderKey, + newline: this.mail.newline + }); + } else { + node = parentNode.createChild('multipart/alternative', { + disableUrlAccess: this.mail.disableUrlAccess, + disableFileAccess: this.mail.disableFileAccess, + normalizeHeaderKey: this.mail.normalizeHeaderKey, + newline: this.mail.newline + }); + } + + this._alternatives.forEach(alternative => { + if (this._useRelated && this._htmlNode === alternative) { + this._createRelated(node); + } else { + this._createContentNode(node, alternative); + } + }); + + return node; + } + + /** + * Builds multipart/related node. It should always contain html node with related attachments + * + * @param {Object} parentNode Parent for this note. If it does not exist, a root node is created + * @returns {Object} MimeNode node element + */ + _createRelated(parentNode) { + let node; + + if (!parentNode) { + node = new MimeNode('multipart/related; type="text/html"', { + baseBoundary: this.mail.baseBoundary, + textEncoding: this.mail.textEncoding, + boundaryPrefix: this.mail.boundaryPrefix, + disableUrlAccess: this.mail.disableUrlAccess, + disableFileAccess: this.mail.disableFileAccess, + normalizeHeaderKey: this.mail.normalizeHeaderKey, + newline: this.mail.newline + }); + } else { + node = parentNode.createChild('multipart/related; type="text/html"', { + disableUrlAccess: this.mail.disableUrlAccess, + disableFileAccess: this.mail.disableFileAccess, + normalizeHeaderKey: this.mail.normalizeHeaderKey, + newline: this.mail.newline + }); + } + + this._createContentNode(node, this._htmlNode); + + this._attachments.related.forEach(alternative => this._createContentNode(node, alternative)); + + return node; + } + + /** + * Creates a regular node with contents + * + * @param {Object} parentNode Parent for this note. If it does not exist, a root node is created + * @param {Object} element Node data + * @returns {Object} MimeNode node element + */ + _createContentNode(parentNode, element) { + element = element || {}; + element.content = element.content || ''; + + let node; + let encoding = (element.encoding || 'utf8') + .toString() + .toLowerCase() + .replace(/[-_\s]/g, ''); + + if (!parentNode) { + node = new MimeNode(element.contentType, { + filename: element.filename, + baseBoundary: this.mail.baseBoundary, + textEncoding: this.mail.textEncoding, + boundaryPrefix: this.mail.boundaryPrefix, + disableUrlAccess: this.mail.disableUrlAccess, + disableFileAccess: this.mail.disableFileAccess, + normalizeHeaderKey: this.mail.normalizeHeaderKey, + newline: this.mail.newline + }); + } else { + node = parentNode.createChild(element.contentType, { + filename: element.filename, + textEncoding: this.mail.textEncoding, + disableUrlAccess: this.mail.disableUrlAccess, + disableFileAccess: this.mail.disableFileAccess, + normalizeHeaderKey: this.mail.normalizeHeaderKey, + newline: this.mail.newline + }); + } + + // add custom headers + if (element.headers) { + node.addHeader(element.headers); + } + + if (element.cid) { + node.setHeader('Content-Id', '<' + element.cid.replace(/[<>]/g, '') + '>'); + } + + if (element.contentTransferEncoding) { + node.setHeader('Content-Transfer-Encoding', element.contentTransferEncoding); + } else if (this.mail.encoding && /^text\//i.test(element.contentType)) { + node.setHeader('Content-Transfer-Encoding', this.mail.encoding); + } + + if (!/^text\//i.test(element.contentType) || element.contentDisposition) { + node.setHeader( + 'Content-Disposition', + element.contentDisposition || (element.cid && /^image\//i.test(element.contentType) ? 'inline' : 'attachment') + ); + } + + if (typeof element.content === 'string' && !['utf8', 'usascii', 'ascii'].includes(encoding)) { + element.content = Buffer.from(element.content, encoding); + } + + // prefer pregenerated raw content + if (element.raw) { + node.setRaw(element.raw); + } else { + node.setContent(element.content); + } + + return node; + } + + /** + * Parses data uri and converts it to a Buffer + * + * @param {Object} element Content element + * @return {Object} Parsed element + */ + _processDataUrl(element) { + let parts = (element.path || element.href).match(/^data:((?:[^;]*;)*(?:[^,]*)),(.*)$/i); + if (!parts) { + return element; + } + + element.content = /\bbase64$/i.test(parts[1]) ? Buffer.from(parts[2], 'base64') : Buffer.from(decodeURIComponent(parts[2])); + + if ('path' in element) { + element.path = false; + } + + if ('href' in element) { + element.href = false; + } + + parts[1].split(';').forEach(item => { + if (/^\w+\/[^/]+$/i.test(item)) { + element.contentType = element.contentType || item.toLowerCase(); + } + }); + + return element; + } +} + +module.exports = MailComposer; diff --git a/system/login/node_modules/nodemailer/lib/mailer/index.js b/system/login/node_modules/nodemailer/lib/mailer/index.js new file mode 100644 index 0000000..aa28055 --- /dev/null +++ b/system/login/node_modules/nodemailer/lib/mailer/index.js @@ -0,0 +1,427 @@ +'use strict'; + +const EventEmitter = require('events'); +const shared = require('../shared'); +const mimeTypes = require('../mime-funcs/mime-types'); +const MailComposer = require('../mail-composer'); +const DKIM = require('../dkim'); +const httpProxyClient = require('../smtp-connection/http-proxy-client'); +const util = require('util'); +const urllib = require('url'); +const packageData = require('../../package.json'); +const MailMessage = require('./mail-message'); +const net = require('net'); +const dns = require('dns'); +const crypto = require('crypto'); + +/** + * Creates an object for exposing the Mail API + * + * @constructor + * @param {Object} transporter Transport object instance to pass the mails to + */ +class Mail extends EventEmitter { + constructor(transporter, options, defaults) { + super(); + + this.options = options || {}; + this._defaults = defaults || {}; + + this._defaultPlugins = { + compile: [(...args) => this._convertDataImages(...args)], + stream: [] + }; + + this._userPlugins = { + compile: [], + stream: [] + }; + + this.meta = new Map(); + + this.dkim = this.options.dkim ? new DKIM(this.options.dkim) : false; + + this.transporter = transporter; + this.transporter.mailer = this; + + this.logger = shared.getLogger(this.options, { + component: this.options.component || 'mail' + }); + + this.logger.debug( + { + tnx: 'create' + }, + 'Creating transport: %s', + this.getVersionString() + ); + + // setup emit handlers for the transporter + if (typeof this.transporter.on === 'function') { + // deprecated log interface + this.transporter.on('log', log => { + this.logger.debug( + { + tnx: 'transport' + }, + '%s: %s', + log.type, + log.message + ); + }); + + // transporter errors + this.transporter.on('error', err => { + this.logger.error( + { + err, + tnx: 'transport' + }, + 'Transport Error: %s', + err.message + ); + this.emit('error', err); + }); + + // indicates if the sender has became idle + this.transporter.on('idle', (...args) => { + this.emit('idle', ...args); + }); + } + + /** + * Optional methods passed to the underlying transport object + */ + ['close', 'isIdle', 'verify'].forEach(method => { + this[method] = (...args) => { + if (typeof this.transporter[method] === 'function') { + if (method === 'verify' && typeof this.getSocket === 'function') { + this.transporter.getSocket = this.getSocket; + this.getSocket = false; + } + return this.transporter[method](...args); + } else { + this.logger.warn( + { + tnx: 'transport', + methodName: method + }, + 'Non existing method %s called for transport', + method + ); + return false; + } + }; + }); + + // setup proxy handling + if (this.options.proxy && typeof this.options.proxy === 'string') { + this.setupProxy(this.options.proxy); + } + } + + use(step, plugin) { + step = (step || '').toString(); + if (!this._userPlugins.hasOwnProperty(step)) { + this._userPlugins[step] = [plugin]; + } else { + this._userPlugins[step].push(plugin); + } + + return this; + } + + /** + * Sends an email using the preselected transport object + * + * @param {Object} data E-data description + * @param {Function?} callback Callback to run once the sending succeeded or failed + */ + sendMail(data, callback = null) { + let promise; + + if (!callback) { + promise = new Promise((resolve, reject) => { + callback = shared.callbackPromise(resolve, reject); + }); + } + + if (typeof this.getSocket === 'function') { + this.transporter.getSocket = this.getSocket; + this.getSocket = false; + } + + let mail = new MailMessage(this, data); + + this.logger.debug( + { + tnx: 'transport', + name: this.transporter.name, + version: this.transporter.version, + action: 'send' + }, + 'Sending mail using %s/%s', + this.transporter.name, + this.transporter.version + ); + + this._processPlugins('compile', mail, err => { + if (err) { + this.logger.error( + { + err, + tnx: 'plugin', + action: 'compile' + }, + 'PluginCompile Error: %s', + err.message + ); + return callback(err); + } + + mail.message = new MailComposer(mail.data).compile(); + + mail.setMailerHeader(); + mail.setPriorityHeaders(); + mail.setListHeaders(); + + this._processPlugins('stream', mail, err => { + if (err) { + this.logger.error( + { + err, + tnx: 'plugin', + action: 'stream' + }, + 'PluginStream Error: %s', + err.message + ); + return callback(err); + } + + if (mail.data.dkim || this.dkim) { + mail.message.processFunc(input => { + let dkim = mail.data.dkim ? new DKIM(mail.data.dkim) : this.dkim; + this.logger.debug( + { + tnx: 'DKIM', + messageId: mail.message.messageId(), + dkimDomains: dkim.keys.map(key => key.keySelector + '.' + key.domainName).join(', ') + }, + 'Signing outgoing message with %s keys', + dkim.keys.length + ); + return dkim.sign(input, mail.data._dkim); + }); + } + + this.transporter.send(mail, (...args) => { + if (args[0]) { + this.logger.error( + { + err: args[0], + tnx: 'transport', + action: 'send' + }, + 'Send Error: %s', + args[0].message + ); + } + callback(...args); + }); + }); + }); + + return promise; + } + + getVersionString() { + return util.format('%s (%s; +%s; %s/%s)', packageData.name, packageData.version, packageData.homepage, this.transporter.name, this.transporter.version); + } + + _processPlugins(step, mail, callback) { + step = (step || '').toString(); + + if (!this._userPlugins.hasOwnProperty(step)) { + return callback(); + } + + let userPlugins = this._userPlugins[step] || []; + let defaultPlugins = this._defaultPlugins[step] || []; + + if (userPlugins.length) { + this.logger.debug( + { + tnx: 'transaction', + pluginCount: userPlugins.length, + step + }, + 'Using %s plugins for %s', + userPlugins.length, + step + ); + } + + if (userPlugins.length + defaultPlugins.length === 0) { + return callback(); + } + + let pos = 0; + let block = 'default'; + let processPlugins = () => { + let curplugins = block === 'default' ? defaultPlugins : userPlugins; + if (pos >= curplugins.length) { + if (block === 'default' && userPlugins.length) { + block = 'user'; + pos = 0; + curplugins = userPlugins; + } else { + return callback(); + } + } + let plugin = curplugins[pos++]; + plugin(mail, err => { + if (err) { + return callback(err); + } + processPlugins(); + }); + }; + + processPlugins(); + } + + /** + * Sets up proxy handler for a Nodemailer object + * + * @param {String} proxyUrl Proxy configuration url + */ + setupProxy(proxyUrl) { + let proxy = urllib.parse(proxyUrl); + + // setup socket handler for the mailer object + this.getSocket = (options, callback) => { + let protocol = proxy.protocol.replace(/:$/, '').toLowerCase(); + + if (this.meta.has('proxy_handler_' + protocol)) { + return this.meta.get('proxy_handler_' + protocol)(proxy, options, callback); + } + + switch (protocol) { + // Connect using a HTTP CONNECT method + case 'http': + case 'https': + httpProxyClient(proxy.href, options.port, options.host, (err, socket) => { + if (err) { + return callback(err); + } + return callback(null, { + connection: socket + }); + }); + return; + case 'socks': + case 'socks5': + case 'socks4': + case 'socks4a': { + if (!this.meta.has('proxy_socks_module')) { + return callback(new Error('Socks module not loaded')); + } + let connect = ipaddress => { + let proxyV2 = !!this.meta.get('proxy_socks_module').SocksClient; + let socksClient = proxyV2 ? this.meta.get('proxy_socks_module').SocksClient : this.meta.get('proxy_socks_module'); + let proxyType = Number(proxy.protocol.replace(/\D/g, '')) || 5; + let connectionOpts = { + proxy: { + ipaddress, + port: Number(proxy.port), + type: proxyType + }, + [proxyV2 ? 'destination' : 'target']: { + host: options.host, + port: options.port + }, + command: 'connect' + }; + + if (proxy.auth) { + let username = decodeURIComponent(proxy.auth.split(':').shift()); + let password = decodeURIComponent(proxy.auth.split(':').pop()); + if (proxyV2) { + connectionOpts.proxy.userId = username; + connectionOpts.proxy.password = password; + } else if (proxyType === 4) { + connectionOpts.userid = username; + } else { + connectionOpts.authentication = { + username, + password + }; + } + } + + socksClient.createConnection(connectionOpts, (err, info) => { + if (err) { + return callback(err); + } + return callback(null, { + connection: info.socket || info + }); + }); + }; + + if (net.isIP(proxy.hostname)) { + return connect(proxy.hostname); + } + + return dns.resolve(proxy.hostname, (err, address) => { + if (err) { + return callback(err); + } + connect(Array.isArray(address) ? address[0] : address); + }); + } + } + callback(new Error('Unknown proxy configuration')); + }; + } + + _convertDataImages(mail, callback) { + if ((!this.options.attachDataUrls && !mail.data.attachDataUrls) || !mail.data.html) { + return callback(); + } + mail.resolveContent(mail.data, 'html', (err, html) => { + if (err) { + return callback(err); + } + let cidCounter = 0; + html = (html || '').toString().replace(/(]* src\s*=[\s"']*)(data:([^;]+);[^"'>\s]+)/gi, (match, prefix, dataUri, mimeType) => { + let cid = crypto.randomBytes(10).toString('hex') + '@localhost'; + if (!mail.data.attachments) { + mail.data.attachments = []; + } + if (!Array.isArray(mail.data.attachments)) { + mail.data.attachments = [].concat(mail.data.attachments || []); + } + mail.data.attachments.push({ + path: dataUri, + cid, + filename: 'image-' + ++cidCounter + '.' + mimeTypes.detectExtension(mimeType) + }); + return prefix + 'cid:' + cid; + }); + mail.data.html = html; + callback(); + }); + } + + set(key, value) { + return this.meta.set(key, value); + } + + get(key) { + return this.meta.get(key); + } +} + +module.exports = Mail; diff --git a/system/login/node_modules/nodemailer/lib/mailer/mail-message.js b/system/login/node_modules/nodemailer/lib/mailer/mail-message.js new file mode 100644 index 0000000..24d492b --- /dev/null +++ b/system/login/node_modules/nodemailer/lib/mailer/mail-message.js @@ -0,0 +1,315 @@ +'use strict'; + +const shared = require('../shared'); +const MimeNode = require('../mime-node'); +const mimeFuncs = require('../mime-funcs'); + +class MailMessage { + constructor(mailer, data) { + this.mailer = mailer; + this.data = {}; + this.message = null; + + data = data || {}; + let options = mailer.options || {}; + let defaults = mailer._defaults || {}; + + Object.keys(data).forEach(key => { + this.data[key] = data[key]; + }); + + this.data.headers = this.data.headers || {}; + + // apply defaults + Object.keys(defaults).forEach(key => { + if (!(key in this.data)) { + this.data[key] = defaults[key]; + } else if (key === 'headers') { + // headers is a special case. Allow setting individual default headers + Object.keys(defaults.headers).forEach(key => { + if (!(key in this.data.headers)) { + this.data.headers[key] = defaults.headers[key]; + } + }); + } + }); + + // force specific keys from transporter options + ['disableFileAccess', 'disableUrlAccess', 'normalizeHeaderKey'].forEach(key => { + if (key in options) { + this.data[key] = options[key]; + } + }); + } + + resolveContent(...args) { + return shared.resolveContent(...args); + } + + resolveAll(callback) { + let keys = [ + [this.data, 'html'], + [this.data, 'text'], + [this.data, 'watchHtml'], + [this.data, 'amp'], + [this.data, 'icalEvent'] + ]; + + if (this.data.alternatives && this.data.alternatives.length) { + this.data.alternatives.forEach((alternative, i) => { + keys.push([this.data.alternatives, i]); + }); + } + + if (this.data.attachments && this.data.attachments.length) { + this.data.attachments.forEach((attachment, i) => { + if (!attachment.filename) { + attachment.filename = (attachment.path || attachment.href || '').split('/').pop().split('?').shift() || 'attachment-' + (i + 1); + if (attachment.filename.indexOf('.') < 0) { + attachment.filename += '.' + mimeFuncs.detectExtension(attachment.contentType); + } + } + + if (!attachment.contentType) { + attachment.contentType = mimeFuncs.detectMimeType(attachment.filename || attachment.path || attachment.href || 'bin'); + } + + keys.push([this.data.attachments, i]); + }); + } + + let mimeNode = new MimeNode(); + + let addressKeys = ['from', 'to', 'cc', 'bcc', 'sender', 'replyTo']; + + addressKeys.forEach(address => { + let value; + if (this.message) { + value = [].concat(mimeNode._parseAddresses(this.message.getHeader(address === 'replyTo' ? 'reply-to' : address)) || []); + } else if (this.data[address]) { + value = [].concat(mimeNode._parseAddresses(this.data[address]) || []); + } + if (value && value.length) { + this.data[address] = value; + } else if (address in this.data) { + this.data[address] = null; + } + }); + + let singleKeys = ['from', 'sender']; + singleKeys.forEach(address => { + if (this.data[address]) { + this.data[address] = this.data[address].shift(); + } + }); + + let pos = 0; + let resolveNext = () => { + if (pos >= keys.length) { + return callback(null, this.data); + } + let args = keys[pos++]; + if (!args[0] || !args[0][args[1]]) { + return resolveNext(); + } + shared.resolveContent(...args, (err, value) => { + if (err) { + return callback(err); + } + + let node = { + content: value + }; + if (args[0][args[1]] && typeof args[0][args[1]] === 'object' && !Buffer.isBuffer(args[0][args[1]])) { + Object.keys(args[0][args[1]]).forEach(key => { + if (!(key in node) && !['content', 'path', 'href', 'raw'].includes(key)) { + node[key] = args[0][args[1]][key]; + } + }); + } + + args[0][args[1]] = node; + resolveNext(); + }); + }; + + setImmediate(() => resolveNext()); + } + + normalize(callback) { + let envelope = this.data.envelope || this.message.getEnvelope(); + let messageId = this.message.messageId(); + + this.resolveAll((err, data) => { + if (err) { + return callback(err); + } + + data.envelope = envelope; + data.messageId = messageId; + + ['html', 'text', 'watchHtml', 'amp'].forEach(key => { + if (data[key] && data[key].content) { + if (typeof data[key].content === 'string') { + data[key] = data[key].content; + } else if (Buffer.isBuffer(data[key].content)) { + data[key] = data[key].content.toString(); + } + } + }); + + if (data.icalEvent && Buffer.isBuffer(data.icalEvent.content)) { + data.icalEvent.content = data.icalEvent.content.toString('base64'); + data.icalEvent.encoding = 'base64'; + } + + if (data.alternatives && data.alternatives.length) { + data.alternatives.forEach(alternative => { + if (alternative && alternative.content && Buffer.isBuffer(alternative.content)) { + alternative.content = alternative.content.toString('base64'); + alternative.encoding = 'base64'; + } + }); + } + + if (data.attachments && data.attachments.length) { + data.attachments.forEach(attachment => { + if (attachment && attachment.content && Buffer.isBuffer(attachment.content)) { + attachment.content = attachment.content.toString('base64'); + attachment.encoding = 'base64'; + } + }); + } + + data.normalizedHeaders = {}; + Object.keys(data.headers || {}).forEach(key => { + let value = [].concat(data.headers[key] || []).shift(); + value = (value && value.value) || value; + if (value) { + if (['references', 'in-reply-to', 'message-id', 'content-id'].includes(key)) { + value = this.message._encodeHeaderValue(key, value); + } + data.normalizedHeaders[key] = value; + } + }); + + if (data.list && typeof data.list === 'object') { + let listHeaders = this._getListHeaders(data.list); + listHeaders.forEach(entry => { + data.normalizedHeaders[entry.key] = entry.value.map(val => (val && val.value) || val).join(', '); + }); + } + + if (data.references) { + data.normalizedHeaders.references = this.message._encodeHeaderValue('references', data.references); + } + + if (data.inReplyTo) { + data.normalizedHeaders['in-reply-to'] = this.message._encodeHeaderValue('in-reply-to', data.inReplyTo); + } + + return callback(null, data); + }); + } + + setMailerHeader() { + if (!this.message || !this.data.xMailer) { + return; + } + this.message.setHeader('X-Mailer', this.data.xMailer); + } + + setPriorityHeaders() { + if (!this.message || !this.data.priority) { + return; + } + switch ((this.data.priority || '').toString().toLowerCase()) { + case 'high': + this.message.setHeader('X-Priority', '1 (Highest)'); + this.message.setHeader('X-MSMail-Priority', 'High'); + this.message.setHeader('Importance', 'High'); + break; + case 'low': + this.message.setHeader('X-Priority', '5 (Lowest)'); + this.message.setHeader('X-MSMail-Priority', 'Low'); + this.message.setHeader('Importance', 'Low'); + break; + default: + // do not add anything, since all messages are 'Normal' by default + } + } + + setListHeaders() { + if (!this.message || !this.data.list || typeof this.data.list !== 'object') { + return; + } + // add optional List-* headers + if (this.data.list && typeof this.data.list === 'object') { + this._getListHeaders(this.data.list).forEach(listHeader => { + listHeader.value.forEach(value => { + this.message.addHeader(listHeader.key, value); + }); + }); + } + } + + _getListHeaders(listData) { + // make sure an url looks like + return Object.keys(listData).map(key => ({ + key: 'list-' + key.toLowerCase().trim(), + value: [].concat(listData[key] || []).map(value => ({ + prepared: true, + foldLines: true, + value: [] + .concat(value || []) + .map(value => { + if (typeof value === 'string') { + value = { + url: value + }; + } + + if (value && value.url) { + if (key.toLowerCase().trim() === 'id') { + // List-ID: "comment" + let comment = value.comment || ''; + if (mimeFuncs.isPlainText(comment)) { + comment = '"' + comment + '"'; + } else { + comment = mimeFuncs.encodeWord(comment); + } + + return (value.comment ? comment + ' ' : '') + this._formatListUrl(value.url).replace(/^<[^:]+\/{,2}/, ''); + } + + // List-*: (comment) + let comment = value.comment || ''; + if (!mimeFuncs.isPlainText(comment)) { + comment = mimeFuncs.encodeWord(comment); + } + + return this._formatListUrl(value.url) + (value.comment ? ' (' + comment + ')' : ''); + } + + return ''; + }) + .filter(value => value) + .join(', ') + })) + })); + } + + _formatListUrl(url) { + url = url.replace(/[\s<]+|[\s>]+/g, ''); + if (/^(https?|mailto|ftp):/.test(url)) { + return '<' + url + '>'; + } + if (/^[^@]+@[^@]+$/.test(url)) { + return ''; + } + + return ''; + } +} + +module.exports = MailMessage; diff --git a/system/login/node_modules/nodemailer/lib/mime-funcs/index.js b/system/login/node_modules/nodemailer/lib/mime-funcs/index.js new file mode 100644 index 0000000..86e975d --- /dev/null +++ b/system/login/node_modules/nodemailer/lib/mime-funcs/index.js @@ -0,0 +1,625 @@ +/* eslint no-control-regex:0 */ + +'use strict'; + +const base64 = require('../base64'); +const qp = require('../qp'); +const mimeTypes = require('./mime-types'); + +module.exports = { + /** + * Checks if a value is plaintext string (uses only printable 7bit chars) + * + * @param {String} value String to be tested + * @returns {Boolean} true if it is a plaintext string + */ + isPlainText(value, isParam) { + const re = isParam ? /[\x00-\x08\x0b\x0c\x0e-\x1f"\u0080-\uFFFF]/ : /[\x00-\x08\x0b\x0c\x0e-\x1f\u0080-\uFFFF]/; + if (typeof value !== 'string' || re.test(value)) { + return false; + } else { + return true; + } + }, + + /** + * Checks if a multi line string containes lines longer than the selected value. + * + * Useful when detecting if a mail message needs any processing at all – + * if only plaintext characters are used and lines are short, then there is + * no need to encode the values in any way. If the value is plaintext but has + * longer lines then allowed, then use format=flowed + * + * @param {Number} lineLength Max line length to check for + * @returns {Boolean} Returns true if there is at least one line longer than lineLength chars + */ + hasLongerLines(str, lineLength) { + if (str.length > 128 * 1024) { + // do not test strings longer than 128kB + return true; + } + return new RegExp('^.{' + (lineLength + 1) + ',}', 'm').test(str); + }, + + /** + * Encodes a string or an Buffer to an UTF-8 MIME Word (rfc2047) + * + * @param {String|Buffer} data String to be encoded + * @param {String} mimeWordEncoding='Q' Encoding for the mime word, either Q or B + * @param {Number} [maxLength=0] If set, split mime words into several chunks if needed + * @return {String} Single or several mime words joined together + */ + encodeWord(data, mimeWordEncoding, maxLength) { + mimeWordEncoding = (mimeWordEncoding || 'Q').toString().toUpperCase().trim().charAt(0); + maxLength = maxLength || 0; + + let encodedStr; + let toCharset = 'UTF-8'; + + if (maxLength && maxLength > 7 + toCharset.length) { + maxLength -= 7 + toCharset.length; + } + + if (mimeWordEncoding === 'Q') { + // https://tools.ietf.org/html/rfc2047#section-5 rule (3) + encodedStr = qp.encode(data).replace(/[^a-z0-9!*+\-/=]/gi, chr => { + let ord = chr.charCodeAt(0).toString(16).toUpperCase(); + if (chr === ' ') { + return '_'; + } else { + return '=' + (ord.length === 1 ? '0' + ord : ord); + } + }); + } else if (mimeWordEncoding === 'B') { + encodedStr = typeof data === 'string' ? data : base64.encode(data); + maxLength = maxLength ? Math.max(3, ((maxLength - (maxLength % 4)) / 4) * 3) : 0; + } + + if (maxLength && (mimeWordEncoding !== 'B' ? encodedStr : base64.encode(data)).length > maxLength) { + if (mimeWordEncoding === 'Q') { + encodedStr = this.splitMimeEncodedString(encodedStr, maxLength).join('?= =?' + toCharset + '?' + mimeWordEncoding + '?'); + } else { + // RFC2047 6.3 (2) states that encoded-word must include an integral number of characters, so no chopping unicode sequences + let parts = []; + let lpart = ''; + for (let i = 0, len = encodedStr.length; i < len; i++) { + let chr = encodedStr.charAt(i); + + if (/[\ud83c\ud83d\ud83e]/.test(chr) && i < len - 1) { + // composite emoji byte, so add the next byte as well + chr += encodedStr.charAt(++i); + } + + // check if we can add this character to the existing string + // without breaking byte length limit + if (Buffer.byteLength(lpart + chr) <= maxLength || i === 0) { + lpart += chr; + } else { + // we hit the length limit, so push the existing string and start over + parts.push(base64.encode(lpart)); + lpart = chr; + } + } + if (lpart) { + parts.push(base64.encode(lpart)); + } + + if (parts.length > 1) { + encodedStr = parts.join('?= =?' + toCharset + '?' + mimeWordEncoding + '?'); + } else { + encodedStr = parts.join(''); + } + } + } else if (mimeWordEncoding === 'B') { + encodedStr = base64.encode(data); + } + + return '=?' + toCharset + '?' + mimeWordEncoding + '?' + encodedStr + (encodedStr.substr(-2) === '?=' ? '' : '?='); + }, + + /** + * Finds word sequences with non ascii text and converts these to mime words + * + * @param {String} value String to be encoded + * @param {String} mimeWordEncoding='Q' Encoding for the mime word, either Q or B + * @param {Number} [maxLength=0] If set, split mime words into several chunks if needed + * @param {Boolean} [encodeAll=false] If true and the value needs encoding then encodes entire string, not just the smallest match + * @return {String} String with possible mime words + */ + encodeWords(value, mimeWordEncoding, maxLength, encodeAll) { + maxLength = maxLength || 0; + + let encodedValue; + + // find first word with a non-printable ascii or special symbol in it + let firstMatch = value.match(/(?:^|\s)([^\s]*["\u0080-\uFFFF])/); + if (!firstMatch) { + return value; + } + + if (encodeAll) { + // if it is requested to encode everything or the string contains something that resebles encoded word, then encode everything + + return this.encodeWord(value, mimeWordEncoding, maxLength); + } + + // find the last word with a non-printable ascii in it + let lastMatch = value.match(/(["\u0080-\uFFFF][^\s]*)[^"\u0080-\uFFFF]*$/); + if (!lastMatch) { + // should not happen + return value; + } + + let startIndex = + firstMatch.index + + ( + firstMatch[0].match(/[^\s]/) || { + index: 0 + } + ).index; + let endIndex = lastMatch.index + (lastMatch[1] || '').length; + + encodedValue = + (startIndex ? value.substr(0, startIndex) : '') + + this.encodeWord(value.substring(startIndex, endIndex), mimeWordEncoding || 'Q', maxLength) + + (endIndex < value.length ? value.substr(endIndex) : ''); + + return encodedValue; + }, + + /** + * Joins parsed header value together as 'value; param1=value1; param2=value2' + * PS: We are following RFC 822 for the list of special characters that we need to keep in quotes. + * Refer: https://www.w3.org/Protocols/rfc1341/4_Content-Type.html + * @param {Object} structured Parsed header value + * @return {String} joined header value + */ + buildHeaderValue(structured) { + let paramsArray = []; + + Object.keys(structured.params || {}).forEach(param => { + // filename might include unicode characters so it is a special case + // other values probably do not + let value = structured.params[param]; + if (!this.isPlainText(value, true) || value.length >= 75) { + this.buildHeaderParam(param, value, 50).forEach(encodedParam => { + if (!/[\s"\\;:/=(),<>@[\]?]|^[-']|'$/.test(encodedParam.value) || encodedParam.key.substr(-1) === '*') { + paramsArray.push(encodedParam.key + '=' + encodedParam.value); + } else { + paramsArray.push(encodedParam.key + '=' + JSON.stringify(encodedParam.value)); + } + }); + } else if (/[\s'"\\;:/=(),<>@[\]?]|^-/.test(value)) { + paramsArray.push(param + '=' + JSON.stringify(value)); + } else { + paramsArray.push(param + '=' + value); + } + }); + + return structured.value + (paramsArray.length ? '; ' + paramsArray.join('; ') : ''); + }, + + /** + * Encodes a string or an Buffer to an UTF-8 Parameter Value Continuation encoding (rfc2231) + * Useful for splitting long parameter values. + * + * For example + * title="unicode string" + * becomes + * title*0*=utf-8''unicode + * title*1*=%20string + * + * @param {String|Buffer} data String to be encoded + * @param {Number} [maxLength=50] Max length for generated chunks + * @param {String} [fromCharset='UTF-8'] Source sharacter set + * @return {Array} A list of encoded keys and headers + */ + buildHeaderParam(key, data, maxLength) { + let list = []; + let encodedStr = typeof data === 'string' ? data : (data || '').toString(); + let encodedStrArr; + let chr, ord; + let line; + let startPos = 0; + let i, len; + + maxLength = maxLength || 50; + + // process ascii only text + if (this.isPlainText(data, true)) { + // check if conversion is even needed + if (encodedStr.length <= maxLength) { + return [ + { + key, + value: encodedStr + } + ]; + } + + encodedStr = encodedStr.replace(new RegExp('.{' + maxLength + '}', 'g'), str => { + list.push({ + line: str + }); + return ''; + }); + + if (encodedStr) { + list.push({ + line: encodedStr + }); + } + } else { + if (/[\uD800-\uDBFF]/.test(encodedStr)) { + // string containts surrogate pairs, so normalize it to an array of bytes + encodedStrArr = []; + for (i = 0, len = encodedStr.length; i < len; i++) { + chr = encodedStr.charAt(i); + ord = chr.charCodeAt(0); + if (ord >= 0xd800 && ord <= 0xdbff && i < len - 1) { + chr += encodedStr.charAt(i + 1); + encodedStrArr.push(chr); + i++; + } else { + encodedStrArr.push(chr); + } + } + encodedStr = encodedStrArr; + } + + // first line includes the charset and language info and needs to be encoded + // even if it does not contain any unicode characters + line = 'utf-8\x27\x27'; + let encoded = true; + startPos = 0; + + // process text with unicode or special chars + for (i = 0, len = encodedStr.length; i < len; i++) { + chr = encodedStr[i]; + + if (encoded) { + chr = this.safeEncodeURIComponent(chr); + } else { + // try to urlencode current char + chr = chr === ' ' ? chr : this.safeEncodeURIComponent(chr); + // By default it is not required to encode a line, the need + // only appears when the string contains unicode or special chars + // in this case we start processing the line over and encode all chars + if (chr !== encodedStr[i]) { + // Check if it is even possible to add the encoded char to the line + // If not, there is no reason to use this line, just push it to the list + // and start a new line with the char that needs encoding + if ((this.safeEncodeURIComponent(line) + chr).length >= maxLength) { + list.push({ + line, + encoded + }); + line = ''; + startPos = i - 1; + } else { + encoded = true; + i = startPos; + line = ''; + continue; + } + } + } + + // if the line is already too long, push it to the list and start a new one + if ((line + chr).length >= maxLength) { + list.push({ + line, + encoded + }); + line = chr = encodedStr[i] === ' ' ? ' ' : this.safeEncodeURIComponent(encodedStr[i]); + if (chr === encodedStr[i]) { + encoded = false; + startPos = i - 1; + } else { + encoded = true; + } + } else { + line += chr; + } + } + + if (line) { + list.push({ + line, + encoded + }); + } + } + + return list.map((item, i) => ({ + // encoded lines: {name}*{part}* + // unencoded lines: {name}*{part} + // if any line needs to be encoded then the first line (part==0) is always encoded + key: key + '*' + i + (item.encoded ? '*' : ''), + value: item.line + })); + }, + + /** + * Parses a header value with key=value arguments into a structured + * object. + * + * parseHeaderValue('content-type: text/plain; CHARSET='UTF-8'') -> + * { + * 'value': 'text/plain', + * 'params': { + * 'charset': 'UTF-8' + * } + * } + * + * @param {String} str Header value + * @return {Object} Header value as a parsed structure + */ + parseHeaderValue(str) { + let response = { + value: false, + params: {} + }; + let key = false; + let value = ''; + let type = 'value'; + let quote = false; + let escaped = false; + let chr; + + for (let i = 0, len = str.length; i < len; i++) { + chr = str.charAt(i); + if (type === 'key') { + if (chr === '=') { + key = value.trim().toLowerCase(); + type = 'value'; + value = ''; + continue; + } + value += chr; + } else { + if (escaped) { + value += chr; + } else if (chr === '\\') { + escaped = true; + continue; + } else if (quote && chr === quote) { + quote = false; + } else if (!quote && chr === '"') { + quote = chr; + } else if (!quote && chr === ';') { + if (key === false) { + response.value = value.trim(); + } else { + response.params[key] = value.trim(); + } + type = 'key'; + value = ''; + } else { + value += chr; + } + escaped = false; + } + } + + if (type === 'value') { + if (key === false) { + response.value = value.trim(); + } else { + response.params[key] = value.trim(); + } + } else if (value.trim()) { + response.params[value.trim().toLowerCase()] = ''; + } + + // handle parameter value continuations + // https://tools.ietf.org/html/rfc2231#section-3 + + // preprocess values + Object.keys(response.params).forEach(key => { + let actualKey, nr, match, value; + if ((match = key.match(/(\*(\d+)|\*(\d+)\*|\*)$/))) { + actualKey = key.substr(0, match.index); + nr = Number(match[2] || match[3]) || 0; + + if (!response.params[actualKey] || typeof response.params[actualKey] !== 'object') { + response.params[actualKey] = { + charset: false, + values: [] + }; + } + + value = response.params[key]; + + if (nr === 0 && match[0].substr(-1) === '*' && (match = value.match(/^([^']*)'[^']*'(.*)$/))) { + response.params[actualKey].charset = match[1] || 'iso-8859-1'; + value = match[2]; + } + + response.params[actualKey].values[nr] = value; + + // remove the old reference + delete response.params[key]; + } + }); + + // concatenate split rfc2231 strings and convert encoded strings to mime encoded words + Object.keys(response.params).forEach(key => { + let value; + if (response.params[key] && Array.isArray(response.params[key].values)) { + value = response.params[key].values.map(val => val || '').join(''); + + if (response.params[key].charset) { + // convert "%AB" to "=?charset?Q?=AB?=" + response.params[key] = + '=?' + + response.params[key].charset + + '?Q?' + + value + // fix invalidly encoded chars + .replace(/[=?_\s]/g, s => { + let c = s.charCodeAt(0).toString(16); + if (s === ' ') { + return '_'; + } else { + return '%' + (c.length < 2 ? '0' : '') + c; + } + }) + // change from urlencoding to percent encoding + .replace(/%/g, '=') + + '?='; + } else { + response.params[key] = value; + } + } + }); + + return response; + }, + + /** + * Returns file extension for a content type string. If no suitable extensions + * are found, 'bin' is used as the default extension + * + * @param {String} mimeType Content type to be checked for + * @return {String} File extension + */ + detectExtension: mimeType => mimeTypes.detectExtension(mimeType), + + /** + * Returns content type for a file extension. If no suitable content types + * are found, 'application/octet-stream' is used as the default content type + * + * @param {String} extension Extension to be checked for + * @return {String} File extension + */ + detectMimeType: extension => mimeTypes.detectMimeType(extension), + + /** + * Folds long lines, useful for folding header lines (afterSpace=false) and + * flowed text (afterSpace=true) + * + * @param {String} str String to be folded + * @param {Number} [lineLength=76] Maximum length of a line + * @param {Boolean} afterSpace If true, leave a space in th end of a line + * @return {String} String with folded lines + */ + foldLines(str, lineLength, afterSpace) { + str = (str || '').toString(); + lineLength = lineLength || 76; + + let pos = 0, + len = str.length, + result = '', + line, + match; + + while (pos < len) { + line = str.substr(pos, lineLength); + if (line.length < lineLength) { + result += line; + break; + } + if ((match = line.match(/^[^\n\r]*(\r?\n|\r)/))) { + line = match[0]; + result += line; + pos += line.length; + continue; + } else if ((match = line.match(/(\s+)[^\s]*$/)) && match[0].length - (afterSpace ? (match[1] || '').length : 0) < line.length) { + line = line.substr(0, line.length - (match[0].length - (afterSpace ? (match[1] || '').length : 0))); + } else if ((match = str.substr(pos + line.length).match(/^[^\s]+(\s*)/))) { + line = line + match[0].substr(0, match[0].length - (!afterSpace ? (match[1] || '').length : 0)); + } + + result += line; + pos += line.length; + if (pos < len) { + result += '\r\n'; + } + } + + return result; + }, + + /** + * Splits a mime encoded string. Needed for dividing mime words into smaller chunks + * + * @param {String} str Mime encoded string to be split up + * @param {Number} maxlen Maximum length of characters for one part (minimum 12) + * @return {Array} Split string + */ + splitMimeEncodedString: (str, maxlen) => { + let curLine, + match, + chr, + done, + lines = []; + + // require at least 12 symbols to fit possible 4 octet UTF-8 sequences + maxlen = Math.max(maxlen || 0, 12); + + while (str.length) { + curLine = str.substr(0, maxlen); + + // move incomplete escaped char back to main + if ((match = curLine.match(/[=][0-9A-F]?$/i))) { + curLine = curLine.substr(0, match.index); + } + + done = false; + while (!done) { + done = true; + // check if not middle of a unicode char sequence + if ((match = str.substr(curLine.length).match(/^[=]([0-9A-F]{2})/i))) { + chr = parseInt(match[1], 16); + // invalid sequence, move one char back anc recheck + if (chr < 0xc2 && chr > 0x7f) { + curLine = curLine.substr(0, curLine.length - 3); + done = false; + } + } + } + + if (curLine.length) { + lines.push(curLine); + } + str = str.substr(curLine.length); + } + + return lines; + }, + + encodeURICharComponent: chr => { + let res = ''; + let ord = chr.charCodeAt(0).toString(16).toUpperCase(); + + if (ord.length % 2) { + ord = '0' + ord; + } + + if (ord.length > 2) { + for (let i = 0, len = ord.length / 2; i < len; i++) { + res += '%' + ord.substr(i, 2); + } + } else { + res += '%' + ord; + } + + return res; + }, + + safeEncodeURIComponent(str) { + str = (str || '').toString(); + + try { + // might throw if we try to encode invalid sequences, eg. partial emoji + str = encodeURIComponent(str); + } catch (E) { + // should never run + return str.replace(/[^\x00-\x1F *'()<>@,;:\\"[\]?=\u007F-\uFFFF]+/g, ''); + } + + // ensure chars that are not handled by encodeURICompent are converted as well + return str.replace(/[\x00-\x1F *'()<>@,;:\\"[\]?=\u007F-\uFFFF]/g, chr => this.encodeURICharComponent(chr)); + } +}; diff --git a/system/login/node_modules/nodemailer/lib/mime-funcs/mime-types.js b/system/login/node_modules/nodemailer/lib/mime-funcs/mime-types.js new file mode 100644 index 0000000..1e9a220 --- /dev/null +++ b/system/login/node_modules/nodemailer/lib/mime-funcs/mime-types.js @@ -0,0 +1,2102 @@ +/* eslint quote-props: 0 */ + +'use strict'; + +const path = require('path'); + +const defaultMimeType = 'application/octet-stream'; +const defaultExtension = 'bin'; + +const mimeTypes = new Map([ + ['application/acad', 'dwg'], + ['application/applixware', 'aw'], + ['application/arj', 'arj'], + ['application/atom+xml', 'xml'], + ['application/atomcat+xml', 'atomcat'], + ['application/atomsvc+xml', 'atomsvc'], + ['application/base64', ['mm', 'mme']], + ['application/binhex', 'hqx'], + ['application/binhex4', 'hqx'], + ['application/book', ['book', 'boo']], + ['application/ccxml+xml,', 'ccxml'], + ['application/cdf', 'cdf'], + ['application/cdmi-capability', 'cdmia'], + ['application/cdmi-container', 'cdmic'], + ['application/cdmi-domain', 'cdmid'], + ['application/cdmi-object', 'cdmio'], + ['application/cdmi-queue', 'cdmiq'], + ['application/clariscad', 'ccad'], + ['application/commonground', 'dp'], + ['application/cu-seeme', 'cu'], + ['application/davmount+xml', 'davmount'], + ['application/drafting', 'drw'], + ['application/dsptype', 'tsp'], + ['application/dssc+der', 'dssc'], + ['application/dssc+xml', 'xdssc'], + ['application/dxf', 'dxf'], + ['application/ecmascript', ['js', 'es']], + ['application/emma+xml', 'emma'], + ['application/envoy', 'evy'], + ['application/epub+zip', 'epub'], + ['application/excel', ['xls', 'xl', 'xla', 'xlb', 'xlc', 'xld', 'xlk', 'xll', 'xlm', 'xlt', 'xlv', 'xlw']], + ['application/exi', 'exi'], + ['application/font-tdpfr', 'pfr'], + ['application/fractals', 'fif'], + ['application/freeloader', 'frl'], + ['application/futuresplash', 'spl'], + ['application/gnutar', 'tgz'], + ['application/groupwise', 'vew'], + ['application/hlp', 'hlp'], + ['application/hta', 'hta'], + ['application/hyperstudio', 'stk'], + ['application/i-deas', 'unv'], + ['application/iges', ['iges', 'igs']], + ['application/inf', 'inf'], + ['application/internet-property-stream', 'acx'], + ['application/ipfix', 'ipfix'], + ['application/java', 'class'], + ['application/java-archive', 'jar'], + ['application/java-byte-code', 'class'], + ['application/java-serialized-object', 'ser'], + ['application/java-vm', 'class'], + ['application/javascript', 'js'], + ['application/json', 'json'], + ['application/lha', 'lha'], + ['application/lzx', 'lzx'], + ['application/mac-binary', 'bin'], + ['application/mac-binhex', 'hqx'], + ['application/mac-binhex40', 'hqx'], + ['application/mac-compactpro', 'cpt'], + ['application/macbinary', 'bin'], + ['application/mads+xml', 'mads'], + ['application/marc', 'mrc'], + ['application/marcxml+xml', 'mrcx'], + ['application/mathematica', 'ma'], + ['application/mathml+xml', 'mathml'], + ['application/mbedlet', 'mbd'], + ['application/mbox', 'mbox'], + ['application/mcad', 'mcd'], + ['application/mediaservercontrol+xml', 'mscml'], + ['application/metalink4+xml', 'meta4'], + ['application/mets+xml', 'mets'], + ['application/mime', 'aps'], + ['application/mods+xml', 'mods'], + ['application/mp21', 'm21'], + ['application/mp4', 'mp4'], + ['application/mspowerpoint', ['ppt', 'pot', 'pps', 'ppz']], + ['application/msword', ['doc', 'dot', 'w6w', 'wiz', 'word']], + ['application/mswrite', 'wri'], + ['application/mxf', 'mxf'], + ['application/netmc', 'mcp'], + ['application/octet-stream', ['*']], + ['application/oda', 'oda'], + ['application/oebps-package+xml', 'opf'], + ['application/ogg', 'ogx'], + ['application/olescript', 'axs'], + ['application/onenote', 'onetoc'], + ['application/patch-ops-error+xml', 'xer'], + ['application/pdf', 'pdf'], + ['application/pgp-encrypted', 'asc'], + ['application/pgp-signature', 'pgp'], + ['application/pics-rules', 'prf'], + ['application/pkcs-12', 'p12'], + ['application/pkcs-crl', 'crl'], + ['application/pkcs10', 'p10'], + ['application/pkcs7-mime', ['p7c', 'p7m']], + ['application/pkcs7-signature', 'p7s'], + ['application/pkcs8', 'p8'], + ['application/pkix-attr-cert', 'ac'], + ['application/pkix-cert', ['cer', 'crt']], + ['application/pkix-crl', 'crl'], + ['application/pkix-pkipath', 'pkipath'], + ['application/pkixcmp', 'pki'], + ['application/plain', 'text'], + ['application/pls+xml', 'pls'], + ['application/postscript', ['ps', 'ai', 'eps']], + ['application/powerpoint', 'ppt'], + ['application/pro_eng', ['part', 'prt']], + ['application/prs.cww', 'cww'], + ['application/pskc+xml', 'pskcxml'], + ['application/rdf+xml', 'rdf'], + ['application/reginfo+xml', 'rif'], + ['application/relax-ng-compact-syntax', 'rnc'], + ['application/resource-lists+xml', 'rl'], + ['application/resource-lists-diff+xml', 'rld'], + ['application/ringing-tones', 'rng'], + ['application/rls-services+xml', 'rs'], + ['application/rsd+xml', 'rsd'], + ['application/rss+xml', 'xml'], + ['application/rtf', ['rtf', 'rtx']], + ['application/sbml+xml', 'sbml'], + ['application/scvp-cv-request', 'scq'], + ['application/scvp-cv-response', 'scs'], + ['application/scvp-vp-request', 'spq'], + ['application/scvp-vp-response', 'spp'], + ['application/sdp', 'sdp'], + ['application/sea', 'sea'], + ['application/set', 'set'], + ['application/set-payment-initiation', 'setpay'], + ['application/set-registration-initiation', 'setreg'], + ['application/shf+xml', 'shf'], + ['application/sla', 'stl'], + ['application/smil', ['smi', 'smil']], + ['application/smil+xml', 'smi'], + ['application/solids', 'sol'], + ['application/sounder', 'sdr'], + ['application/sparql-query', 'rq'], + ['application/sparql-results+xml', 'srx'], + ['application/srgs', 'gram'], + ['application/srgs+xml', 'grxml'], + ['application/sru+xml', 'sru'], + ['application/ssml+xml', 'ssml'], + ['application/step', ['step', 'stp']], + ['application/streamingmedia', 'ssm'], + ['application/tei+xml', 'tei'], + ['application/thraud+xml', 'tfi'], + ['application/timestamped-data', 'tsd'], + ['application/toolbook', 'tbk'], + ['application/vda', 'vda'], + ['application/vnd.3gpp.pic-bw-large', 'plb'], + ['application/vnd.3gpp.pic-bw-small', 'psb'], + ['application/vnd.3gpp.pic-bw-var', 'pvb'], + ['application/vnd.3gpp2.tcap', 'tcap'], + ['application/vnd.3m.post-it-notes', 'pwn'], + ['application/vnd.accpac.simply.aso', 'aso'], + ['application/vnd.accpac.simply.imp', 'imp'], + ['application/vnd.acucobol', 'acu'], + ['application/vnd.acucorp', 'atc'], + ['application/vnd.adobe.air-application-installer-package+zip', 'air'], + ['application/vnd.adobe.fxp', 'fxp'], + ['application/vnd.adobe.xdp+xml', 'xdp'], + ['application/vnd.adobe.xfdf', 'xfdf'], + ['application/vnd.ahead.space', 'ahead'], + ['application/vnd.airzip.filesecure.azf', 'azf'], + ['application/vnd.airzip.filesecure.azs', 'azs'], + ['application/vnd.amazon.ebook', 'azw'], + ['application/vnd.americandynamics.acc', 'acc'], + ['application/vnd.amiga.ami', 'ami'], + ['application/vnd.android.package-archive', 'apk'], + ['application/vnd.anser-web-certificate-issue-initiation', 'cii'], + ['application/vnd.anser-web-funds-transfer-initiation', 'fti'], + ['application/vnd.antix.game-component', 'atx'], + ['application/vnd.apple.installer+xml', 'mpkg'], + ['application/vnd.apple.mpegurl', 'm3u8'], + ['application/vnd.aristanetworks.swi', 'swi'], + ['application/vnd.audiograph', 'aep'], + ['application/vnd.blueice.multipass', 'mpm'], + ['application/vnd.bmi', 'bmi'], + ['application/vnd.businessobjects', 'rep'], + ['application/vnd.chemdraw+xml', 'cdxml'], + ['application/vnd.chipnuts.karaoke-mmd', 'mmd'], + ['application/vnd.cinderella', 'cdy'], + ['application/vnd.claymore', 'cla'], + ['application/vnd.cloanto.rp9', 'rp9'], + ['application/vnd.clonk.c4group', 'c4g'], + ['application/vnd.cluetrust.cartomobile-config', 'c11amc'], + ['application/vnd.cluetrust.cartomobile-config-pkg', 'c11amz'], + ['application/vnd.commonspace', 'csp'], + ['application/vnd.contact.cmsg', 'cdbcmsg'], + ['application/vnd.cosmocaller', 'cmc'], + ['application/vnd.crick.clicker', 'clkx'], + ['application/vnd.crick.clicker.keyboard', 'clkk'], + ['application/vnd.crick.clicker.palette', 'clkp'], + ['application/vnd.crick.clicker.template', 'clkt'], + ['application/vnd.crick.clicker.wordbank', 'clkw'], + ['application/vnd.criticaltools.wbs+xml', 'wbs'], + ['application/vnd.ctc-posml', 'pml'], + ['application/vnd.cups-ppd', 'ppd'], + ['application/vnd.curl.car', 'car'], + ['application/vnd.curl.pcurl', 'pcurl'], + ['application/vnd.data-vision.rdz', 'rdz'], + ['application/vnd.denovo.fcselayout-link', 'fe_launch'], + ['application/vnd.dna', 'dna'], + ['application/vnd.dolby.mlp', 'mlp'], + ['application/vnd.dpgraph', 'dpg'], + ['application/vnd.dreamfactory', 'dfac'], + ['application/vnd.dvb.ait', 'ait'], + ['application/vnd.dvb.service', 'svc'], + ['application/vnd.dynageo', 'geo'], + ['application/vnd.ecowin.chart', 'mag'], + ['application/vnd.enliven', 'nml'], + ['application/vnd.epson.esf', 'esf'], + ['application/vnd.epson.msf', 'msf'], + ['application/vnd.epson.quickanime', 'qam'], + ['application/vnd.epson.salt', 'slt'], + ['application/vnd.epson.ssf', 'ssf'], + ['application/vnd.eszigno3+xml', 'es3'], + ['application/vnd.ezpix-album', 'ez2'], + ['application/vnd.ezpix-package', 'ez3'], + ['application/vnd.fdf', 'fdf'], + ['application/vnd.fdsn.seed', 'seed'], + ['application/vnd.flographit', 'gph'], + ['application/vnd.fluxtime.clip', 'ftc'], + ['application/vnd.framemaker', 'fm'], + ['application/vnd.frogans.fnc', 'fnc'], + ['application/vnd.frogans.ltf', 'ltf'], + ['application/vnd.fsc.weblaunch', 'fsc'], + ['application/vnd.fujitsu.oasys', 'oas'], + ['application/vnd.fujitsu.oasys2', 'oa2'], + ['application/vnd.fujitsu.oasys3', 'oa3'], + ['application/vnd.fujitsu.oasysgp', 'fg5'], + ['application/vnd.fujitsu.oasysprs', 'bh2'], + ['application/vnd.fujixerox.ddd', 'ddd'], + ['application/vnd.fujixerox.docuworks', 'xdw'], + ['application/vnd.fujixerox.docuworks.binder', 'xbd'], + ['application/vnd.fuzzysheet', 'fzs'], + ['application/vnd.genomatix.tuxedo', 'txd'], + ['application/vnd.geogebra.file', 'ggb'], + ['application/vnd.geogebra.tool', 'ggt'], + ['application/vnd.geometry-explorer', 'gex'], + ['application/vnd.geonext', 'gxt'], + ['application/vnd.geoplan', 'g2w'], + ['application/vnd.geospace', 'g3w'], + ['application/vnd.gmx', 'gmx'], + ['application/vnd.google-earth.kml+xml', 'kml'], + ['application/vnd.google-earth.kmz', 'kmz'], + ['application/vnd.grafeq', 'gqf'], + ['application/vnd.groove-account', 'gac'], + ['application/vnd.groove-help', 'ghf'], + ['application/vnd.groove-identity-message', 'gim'], + ['application/vnd.groove-injector', 'grv'], + ['application/vnd.groove-tool-message', 'gtm'], + ['application/vnd.groove-tool-template', 'tpl'], + ['application/vnd.groove-vcard', 'vcg'], + ['application/vnd.hal+xml', 'hal'], + ['application/vnd.handheld-entertainment+xml', 'zmm'], + ['application/vnd.hbci', 'hbci'], + ['application/vnd.hhe.lesson-player', 'les'], + ['application/vnd.hp-hpgl', ['hgl', 'hpg', 'hpgl']], + ['application/vnd.hp-hpid', 'hpid'], + ['application/vnd.hp-hps', 'hps'], + ['application/vnd.hp-jlyt', 'jlt'], + ['application/vnd.hp-pcl', 'pcl'], + ['application/vnd.hp-pclxl', 'pclxl'], + ['application/vnd.hydrostatix.sof-data', 'sfd-hdstx'], + ['application/vnd.hzn-3d-crossword', 'x3d'], + ['application/vnd.ibm.minipay', 'mpy'], + ['application/vnd.ibm.modcap', 'afp'], + ['application/vnd.ibm.rights-management', 'irm'], + ['application/vnd.ibm.secure-container', 'sc'], + ['application/vnd.iccprofile', 'icc'], + ['application/vnd.igloader', 'igl'], + ['application/vnd.immervision-ivp', 'ivp'], + ['application/vnd.immervision-ivu', 'ivu'], + ['application/vnd.insors.igm', 'igm'], + ['application/vnd.intercon.formnet', 'xpw'], + ['application/vnd.intergeo', 'i2g'], + ['application/vnd.intu.qbo', 'qbo'], + ['application/vnd.intu.qfx', 'qfx'], + ['application/vnd.ipunplugged.rcprofile', 'rcprofile'], + ['application/vnd.irepository.package+xml', 'irp'], + ['application/vnd.is-xpr', 'xpr'], + ['application/vnd.isac.fcs', 'fcs'], + ['application/vnd.jam', 'jam'], + ['application/vnd.jcp.javame.midlet-rms', 'rms'], + ['application/vnd.jisp', 'jisp'], + ['application/vnd.joost.joda-archive', 'joda'], + ['application/vnd.kahootz', 'ktz'], + ['application/vnd.kde.karbon', 'karbon'], + ['application/vnd.kde.kchart', 'chrt'], + ['application/vnd.kde.kformula', 'kfo'], + ['application/vnd.kde.kivio', 'flw'], + ['application/vnd.kde.kontour', 'kon'], + ['application/vnd.kde.kpresenter', 'kpr'], + ['application/vnd.kde.kspread', 'ksp'], + ['application/vnd.kde.kword', 'kwd'], + ['application/vnd.kenameaapp', 'htke'], + ['application/vnd.kidspiration', 'kia'], + ['application/vnd.kinar', 'kne'], + ['application/vnd.koan', 'skp'], + ['application/vnd.kodak-descriptor', 'sse'], + ['application/vnd.las.las+xml', 'lasxml'], + ['application/vnd.llamagraphics.life-balance.desktop', 'lbd'], + ['application/vnd.llamagraphics.life-balance.exchange+xml', 'lbe'], + ['application/vnd.lotus-1-2-3', '123'], + ['application/vnd.lotus-approach', 'apr'], + ['application/vnd.lotus-freelance', 'pre'], + ['application/vnd.lotus-notes', 'nsf'], + ['application/vnd.lotus-organizer', 'org'], + ['application/vnd.lotus-screencam', 'scm'], + ['application/vnd.lotus-wordpro', 'lwp'], + ['application/vnd.macports.portpkg', 'portpkg'], + ['application/vnd.mcd', 'mcd'], + ['application/vnd.medcalcdata', 'mc1'], + ['application/vnd.mediastation.cdkey', 'cdkey'], + ['application/vnd.mfer', 'mwf'], + ['application/vnd.mfmp', 'mfm'], + ['application/vnd.micrografx.flo', 'flo'], + ['application/vnd.micrografx.igx', 'igx'], + ['application/vnd.mif', 'mif'], + ['application/vnd.mobius.daf', 'daf'], + ['application/vnd.mobius.dis', 'dis'], + ['application/vnd.mobius.mbk', 'mbk'], + ['application/vnd.mobius.mqy', 'mqy'], + ['application/vnd.mobius.msl', 'msl'], + ['application/vnd.mobius.plc', 'plc'], + ['application/vnd.mobius.txf', 'txf'], + ['application/vnd.mophun.application', 'mpn'], + ['application/vnd.mophun.certificate', 'mpc'], + ['application/vnd.mozilla.xul+xml', 'xul'], + ['application/vnd.ms-artgalry', 'cil'], + ['application/vnd.ms-cab-compressed', 'cab'], + ['application/vnd.ms-excel', ['xls', 'xla', 'xlc', 'xlm', 'xlt', 'xlw', 'xlb', 'xll']], + ['application/vnd.ms-excel.addin.macroenabled.12', 'xlam'], + ['application/vnd.ms-excel.sheet.binary.macroenabled.12', 'xlsb'], + ['application/vnd.ms-excel.sheet.macroenabled.12', 'xlsm'], + ['application/vnd.ms-excel.template.macroenabled.12', 'xltm'], + ['application/vnd.ms-fontobject', 'eot'], + ['application/vnd.ms-htmlhelp', 'chm'], + ['application/vnd.ms-ims', 'ims'], + ['application/vnd.ms-lrm', 'lrm'], + ['application/vnd.ms-officetheme', 'thmx'], + ['application/vnd.ms-outlook', 'msg'], + ['application/vnd.ms-pki.certstore', 'sst'], + ['application/vnd.ms-pki.pko', 'pko'], + ['application/vnd.ms-pki.seccat', 'cat'], + ['application/vnd.ms-pki.stl', 'stl'], + ['application/vnd.ms-pkicertstore', 'sst'], + ['application/vnd.ms-pkiseccat', 'cat'], + ['application/vnd.ms-pkistl', 'stl'], + ['application/vnd.ms-powerpoint', ['ppt', 'pot', 'pps', 'ppa', 'pwz']], + ['application/vnd.ms-powerpoint.addin.macroenabled.12', 'ppam'], + ['application/vnd.ms-powerpoint.presentation.macroenabled.12', 'pptm'], + ['application/vnd.ms-powerpoint.slide.macroenabled.12', 'sldm'], + ['application/vnd.ms-powerpoint.slideshow.macroenabled.12', 'ppsm'], + ['application/vnd.ms-powerpoint.template.macroenabled.12', 'potm'], + ['application/vnd.ms-project', 'mpp'], + ['application/vnd.ms-word.document.macroenabled.12', 'docm'], + ['application/vnd.ms-word.template.macroenabled.12', 'dotm'], + ['application/vnd.ms-works', ['wks', 'wcm', 'wdb', 'wps']], + ['application/vnd.ms-wpl', 'wpl'], + ['application/vnd.ms-xpsdocument', 'xps'], + ['application/vnd.mseq', 'mseq'], + ['application/vnd.musician', 'mus'], + ['application/vnd.muvee.style', 'msty'], + ['application/vnd.neurolanguage.nlu', 'nlu'], + ['application/vnd.noblenet-directory', 'nnd'], + ['application/vnd.noblenet-sealer', 'nns'], + ['application/vnd.noblenet-web', 'nnw'], + ['application/vnd.nokia.configuration-message', 'ncm'], + ['application/vnd.nokia.n-gage.data', 'ngdat'], + ['application/vnd.nokia.n-gage.symbian.install', 'n-gage'], + ['application/vnd.nokia.radio-preset', 'rpst'], + ['application/vnd.nokia.radio-presets', 'rpss'], + ['application/vnd.nokia.ringing-tone', 'rng'], + ['application/vnd.novadigm.edm', 'edm'], + ['application/vnd.novadigm.edx', 'edx'], + ['application/vnd.novadigm.ext', 'ext'], + ['application/vnd.oasis.opendocument.chart', 'odc'], + ['application/vnd.oasis.opendocument.chart-template', 'otc'], + ['application/vnd.oasis.opendocument.database', 'odb'], + ['application/vnd.oasis.opendocument.formula', 'odf'], + ['application/vnd.oasis.opendocument.formula-template', 'odft'], + ['application/vnd.oasis.opendocument.graphics', 'odg'], + ['application/vnd.oasis.opendocument.graphics-template', 'otg'], + ['application/vnd.oasis.opendocument.image', 'odi'], + ['application/vnd.oasis.opendocument.image-template', 'oti'], + ['application/vnd.oasis.opendocument.presentation', 'odp'], + ['application/vnd.oasis.opendocument.presentation-template', 'otp'], + ['application/vnd.oasis.opendocument.spreadsheet', 'ods'], + ['application/vnd.oasis.opendocument.spreadsheet-template', 'ots'], + ['application/vnd.oasis.opendocument.text', 'odt'], + ['application/vnd.oasis.opendocument.text-master', 'odm'], + ['application/vnd.oasis.opendocument.text-template', 'ott'], + ['application/vnd.oasis.opendocument.text-web', 'oth'], + ['application/vnd.olpc-sugar', 'xo'], + ['application/vnd.oma.dd2+xml', 'dd2'], + ['application/vnd.openofficeorg.extension', 'oxt'], + ['application/vnd.openxmlformats-officedocument.presentationml.presentation', 'pptx'], + ['application/vnd.openxmlformats-officedocument.presentationml.slide', 'sldx'], + ['application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'ppsx'], + ['application/vnd.openxmlformats-officedocument.presentationml.template', 'potx'], + ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'xlsx'], + ['application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'xltx'], + ['application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'docx'], + ['application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'dotx'], + ['application/vnd.osgeo.mapguide.package', 'mgp'], + ['application/vnd.osgi.dp', 'dp'], + ['application/vnd.palm', 'pdb'], + ['application/vnd.pawaafile', 'paw'], + ['application/vnd.pg.format', 'str'], + ['application/vnd.pg.osasli', 'ei6'], + ['application/vnd.picsel', 'efif'], + ['application/vnd.pmi.widget', 'wg'], + ['application/vnd.pocketlearn', 'plf'], + ['application/vnd.powerbuilder6', 'pbd'], + ['application/vnd.previewsystems.box', 'box'], + ['application/vnd.proteus.magazine', 'mgz'], + ['application/vnd.publishare-delta-tree', 'qps'], + ['application/vnd.pvi.ptid1', 'ptid'], + ['application/vnd.quark.quarkxpress', 'qxd'], + ['application/vnd.realvnc.bed', 'bed'], + ['application/vnd.recordare.musicxml', 'mxl'], + ['application/vnd.recordare.musicxml+xml', 'musicxml'], + ['application/vnd.rig.cryptonote', 'cryptonote'], + ['application/vnd.rim.cod', 'cod'], + ['application/vnd.rn-realmedia', 'rm'], + ['application/vnd.rn-realplayer', 'rnx'], + ['application/vnd.route66.link66+xml', 'link66'], + ['application/vnd.sailingtracker.track', 'st'], + ['application/vnd.seemail', 'see'], + ['application/vnd.sema', 'sema'], + ['application/vnd.semd', 'semd'], + ['application/vnd.semf', 'semf'], + ['application/vnd.shana.informed.formdata', 'ifm'], + ['application/vnd.shana.informed.formtemplate', 'itp'], + ['application/vnd.shana.informed.interchange', 'iif'], + ['application/vnd.shana.informed.package', 'ipk'], + ['application/vnd.simtech-mindmapper', 'twd'], + ['application/vnd.smaf', 'mmf'], + ['application/vnd.smart.teacher', 'teacher'], + ['application/vnd.solent.sdkm+xml', 'sdkm'], + ['application/vnd.spotfire.dxp', 'dxp'], + ['application/vnd.spotfire.sfs', 'sfs'], + ['application/vnd.stardivision.calc', 'sdc'], + ['application/vnd.stardivision.draw', 'sda'], + ['application/vnd.stardivision.impress', 'sdd'], + ['application/vnd.stardivision.math', 'smf'], + ['application/vnd.stardivision.writer', 'sdw'], + ['application/vnd.stardivision.writer-global', 'sgl'], + ['application/vnd.stepmania.stepchart', 'sm'], + ['application/vnd.sun.xml.calc', 'sxc'], + ['application/vnd.sun.xml.calc.template', 'stc'], + ['application/vnd.sun.xml.draw', 'sxd'], + ['application/vnd.sun.xml.draw.template', 'std'], + ['application/vnd.sun.xml.impress', 'sxi'], + ['application/vnd.sun.xml.impress.template', 'sti'], + ['application/vnd.sun.xml.math', 'sxm'], + ['application/vnd.sun.xml.writer', 'sxw'], + ['application/vnd.sun.xml.writer.global', 'sxg'], + ['application/vnd.sun.xml.writer.template', 'stw'], + ['application/vnd.sus-calendar', 'sus'], + ['application/vnd.svd', 'svd'], + ['application/vnd.symbian.install', 'sis'], + ['application/vnd.syncml+xml', 'xsm'], + ['application/vnd.syncml.dm+wbxml', 'bdm'], + ['application/vnd.syncml.dm+xml', 'xdm'], + ['application/vnd.tao.intent-module-archive', 'tao'], + ['application/vnd.tmobile-livetv', 'tmo'], + ['application/vnd.trid.tpt', 'tpt'], + ['application/vnd.triscape.mxs', 'mxs'], + ['application/vnd.trueapp', 'tra'], + ['application/vnd.ufdl', 'ufd'], + ['application/vnd.uiq.theme', 'utz'], + ['application/vnd.umajin', 'umj'], + ['application/vnd.unity', 'unityweb'], + ['application/vnd.uoml+xml', 'uoml'], + ['application/vnd.vcx', 'vcx'], + ['application/vnd.visio', 'vsd'], + ['application/vnd.visionary', 'vis'], + ['application/vnd.vsf', 'vsf'], + ['application/vnd.wap.wbxml', 'wbxml'], + ['application/vnd.wap.wmlc', 'wmlc'], + ['application/vnd.wap.wmlscriptc', 'wmlsc'], + ['application/vnd.webturbo', 'wtb'], + ['application/vnd.wolfram.player', 'nbp'], + ['application/vnd.wordperfect', 'wpd'], + ['application/vnd.wqd', 'wqd'], + ['application/vnd.wt.stf', 'stf'], + ['application/vnd.xara', ['web', 'xar']], + ['application/vnd.xfdl', 'xfdl'], + ['application/vnd.yamaha.hv-dic', 'hvd'], + ['application/vnd.yamaha.hv-script', 'hvs'], + ['application/vnd.yamaha.hv-voice', 'hvp'], + ['application/vnd.yamaha.openscoreformat', 'osf'], + ['application/vnd.yamaha.openscoreformat.osfpvg+xml', 'osfpvg'], + ['application/vnd.yamaha.smaf-audio', 'saf'], + ['application/vnd.yamaha.smaf-phrase', 'spf'], + ['application/vnd.yellowriver-custom-menu', 'cmp'], + ['application/vnd.zul', 'zir'], + ['application/vnd.zzazz.deck+xml', 'zaz'], + ['application/vocaltec-media-desc', 'vmd'], + ['application/vocaltec-media-file', 'vmf'], + ['application/voicexml+xml', 'vxml'], + ['application/widget', 'wgt'], + ['application/winhlp', 'hlp'], + ['application/wordperfect', ['wp', 'wp5', 'wp6', 'wpd']], + ['application/wordperfect6.0', ['w60', 'wp5']], + ['application/wordperfect6.1', 'w61'], + ['application/wsdl+xml', 'wsdl'], + ['application/wspolicy+xml', 'wspolicy'], + ['application/x-123', 'wk1'], + ['application/x-7z-compressed', '7z'], + ['application/x-abiword', 'abw'], + ['application/x-ace-compressed', 'ace'], + ['application/x-aim', 'aim'], + ['application/x-authorware-bin', 'aab'], + ['application/x-authorware-map', 'aam'], + ['application/x-authorware-seg', 'aas'], + ['application/x-bcpio', 'bcpio'], + ['application/x-binary', 'bin'], + ['application/x-binhex40', 'hqx'], + ['application/x-bittorrent', 'torrent'], + ['application/x-bsh', ['bsh', 'sh', 'shar']], + ['application/x-bytecode.elisp', 'elc'], + ['application/x-bytecode.python', 'pyc'], + ['application/x-bzip', 'bz'], + ['application/x-bzip2', ['boz', 'bz2']], + ['application/x-cdf', 'cdf'], + ['application/x-cdlink', 'vcd'], + ['application/x-chat', ['cha', 'chat']], + ['application/x-chess-pgn', 'pgn'], + ['application/x-cmu-raster', 'ras'], + ['application/x-cocoa', 'cco'], + ['application/x-compactpro', 'cpt'], + ['application/x-compress', 'z'], + ['application/x-compressed', ['tgz', 'gz', 'z', 'zip']], + ['application/x-conference', 'nsc'], + ['application/x-cpio', 'cpio'], + ['application/x-cpt', 'cpt'], + ['application/x-csh', 'csh'], + ['application/x-debian-package', 'deb'], + ['application/x-deepv', 'deepv'], + ['application/x-director', ['dir', 'dcr', 'dxr']], + ['application/x-doom', 'wad'], + ['application/x-dtbncx+xml', 'ncx'], + ['application/x-dtbook+xml', 'dtb'], + ['application/x-dtbresource+xml', 'res'], + ['application/x-dvi', 'dvi'], + ['application/x-elc', 'elc'], + ['application/x-envoy', ['env', 'evy']], + ['application/x-esrehber', 'es'], + ['application/x-excel', ['xls', 'xla', 'xlb', 'xlc', 'xld', 'xlk', 'xll', 'xlm', 'xlt', 'xlv', 'xlw']], + ['application/x-font-bdf', 'bdf'], + ['application/x-font-ghostscript', 'gsf'], + ['application/x-font-linux-psf', 'psf'], + ['application/x-font-otf', 'otf'], + ['application/x-font-pcf', 'pcf'], + ['application/x-font-snf', 'snf'], + ['application/x-font-ttf', 'ttf'], + ['application/x-font-type1', 'pfa'], + ['application/x-font-woff', 'woff'], + ['application/x-frame', 'mif'], + ['application/x-freelance', 'pre'], + ['application/x-futuresplash', 'spl'], + ['application/x-gnumeric', 'gnumeric'], + ['application/x-gsp', 'gsp'], + ['application/x-gss', 'gss'], + ['application/x-gtar', 'gtar'], + ['application/x-gzip', ['gz', 'gzip']], + ['application/x-hdf', 'hdf'], + ['application/x-helpfile', ['help', 'hlp']], + ['application/x-httpd-imap', 'imap'], + ['application/x-ima', 'ima'], + ['application/x-internet-signup', ['ins', 'isp']], + ['application/x-internett-signup', 'ins'], + ['application/x-inventor', 'iv'], + ['application/x-ip2', 'ip'], + ['application/x-iphone', 'iii'], + ['application/x-java-class', 'class'], + ['application/x-java-commerce', 'jcm'], + ['application/x-java-jnlp-file', 'jnlp'], + ['application/x-javascript', 'js'], + ['application/x-koan', ['skd', 'skm', 'skp', 'skt']], + ['application/x-ksh', 'ksh'], + ['application/x-latex', ['latex', 'ltx']], + ['application/x-lha', 'lha'], + ['application/x-lisp', 'lsp'], + ['application/x-livescreen', 'ivy'], + ['application/x-lotus', 'wq1'], + ['application/x-lotusscreencam', 'scm'], + ['application/x-lzh', 'lzh'], + ['application/x-lzx', 'lzx'], + ['application/x-mac-binhex40', 'hqx'], + ['application/x-macbinary', 'bin'], + ['application/x-magic-cap-package-1.0', 'mc$'], + ['application/x-mathcad', 'mcd'], + ['application/x-meme', 'mm'], + ['application/x-midi', ['mid', 'midi']], + ['application/x-mif', 'mif'], + ['application/x-mix-transfer', 'nix'], + ['application/x-mobipocket-ebook', 'prc'], + ['application/x-mplayer2', 'asx'], + ['application/x-ms-application', 'application'], + ['application/x-ms-wmd', 'wmd'], + ['application/x-ms-wmz', 'wmz'], + ['application/x-ms-xbap', 'xbap'], + ['application/x-msaccess', 'mdb'], + ['application/x-msbinder', 'obd'], + ['application/x-mscardfile', 'crd'], + ['application/x-msclip', 'clp'], + ['application/x-msdownload', ['exe', 'dll']], + ['application/x-msexcel', ['xls', 'xla', 'xlw']], + ['application/x-msmediaview', ['mvb', 'm13', 'm14']], + ['application/x-msmetafile', 'wmf'], + ['application/x-msmoney', 'mny'], + ['application/x-mspowerpoint', 'ppt'], + ['application/x-mspublisher', 'pub'], + ['application/x-msschedule', 'scd'], + ['application/x-msterminal', 'trm'], + ['application/x-mswrite', 'wri'], + ['application/x-navi-animation', 'ani'], + ['application/x-navidoc', 'nvd'], + ['application/x-navimap', 'map'], + ['application/x-navistyle', 'stl'], + ['application/x-netcdf', ['cdf', 'nc']], + ['application/x-newton-compatible-pkg', 'pkg'], + ['application/x-nokia-9000-communicator-add-on-software', 'aos'], + ['application/x-omc', 'omc'], + ['application/x-omcdatamaker', 'omcd'], + ['application/x-omcregerator', 'omcr'], + ['application/x-pagemaker', ['pm4', 'pm5']], + ['application/x-pcl', 'pcl'], + ['application/x-perfmon', ['pma', 'pmc', 'pml', 'pmr', 'pmw']], + ['application/x-pixclscript', 'plx'], + ['application/x-pkcs10', 'p10'], + ['application/x-pkcs12', ['p12', 'pfx']], + ['application/x-pkcs7-certificates', ['p7b', 'spc']], + ['application/x-pkcs7-certreqresp', 'p7r'], + ['application/x-pkcs7-mime', ['p7m', 'p7c']], + ['application/x-pkcs7-signature', ['p7s', 'p7a']], + ['application/x-pointplus', 'css'], + ['application/x-portable-anymap', 'pnm'], + ['application/x-project', ['mpc', 'mpt', 'mpv', 'mpx']], + ['application/x-qpro', 'wb1'], + ['application/x-rar-compressed', 'rar'], + ['application/x-rtf', 'rtf'], + ['application/x-sdp', 'sdp'], + ['application/x-sea', 'sea'], + ['application/x-seelogo', 'sl'], + ['application/x-sh', 'sh'], + ['application/x-shar', ['shar', 'sh']], + ['application/x-shockwave-flash', 'swf'], + ['application/x-silverlight-app', 'xap'], + ['application/x-sit', 'sit'], + ['application/x-sprite', ['spr', 'sprite']], + ['application/x-stuffit', 'sit'], + ['application/x-stuffitx', 'sitx'], + ['application/x-sv4cpio', 'sv4cpio'], + ['application/x-sv4crc', 'sv4crc'], + ['application/x-tar', 'tar'], + ['application/x-tbook', ['sbk', 'tbk']], + ['application/x-tcl', 'tcl'], + ['application/x-tex', 'tex'], + ['application/x-tex-tfm', 'tfm'], + ['application/x-texinfo', ['texi', 'texinfo']], + ['application/x-troff', ['roff', 't', 'tr']], + ['application/x-troff-man', 'man'], + ['application/x-troff-me', 'me'], + ['application/x-troff-ms', 'ms'], + ['application/x-troff-msvideo', 'avi'], + ['application/x-ustar', 'ustar'], + ['application/x-visio', ['vsd', 'vst', 'vsw']], + ['application/x-vnd.audioexplosion.mzz', 'mzz'], + ['application/x-vnd.ls-xpix', 'xpix'], + ['application/x-vrml', 'vrml'], + ['application/x-wais-source', ['src', 'wsrc']], + ['application/x-winhelp', 'hlp'], + ['application/x-wintalk', 'wtk'], + ['application/x-world', ['wrl', 'svr']], + ['application/x-wpwin', 'wpd'], + ['application/x-wri', 'wri'], + ['application/x-x509-ca-cert', ['cer', 'crt', 'der']], + ['application/x-x509-user-cert', 'crt'], + ['application/x-xfig', 'fig'], + ['application/x-xpinstall', 'xpi'], + ['application/x-zip-compressed', 'zip'], + ['application/xcap-diff+xml', 'xdf'], + ['application/xenc+xml', 'xenc'], + ['application/xhtml+xml', 'xhtml'], + ['application/xml', 'xml'], + ['application/xml-dtd', 'dtd'], + ['application/xop+xml', 'xop'], + ['application/xslt+xml', 'xslt'], + ['application/xspf+xml', 'xspf'], + ['application/xv+xml', 'mxml'], + ['application/yang', 'yang'], + ['application/yin+xml', 'yin'], + ['application/ynd.ms-pkipko', 'pko'], + ['application/zip', 'zip'], + ['audio/adpcm', 'adp'], + ['audio/aiff', ['aiff', 'aif', 'aifc']], + ['audio/basic', ['snd', 'au']], + ['audio/it', 'it'], + ['audio/make', ['funk', 'my', 'pfunk']], + ['audio/make.my.funk', 'pfunk'], + ['audio/mid', ['mid', 'rmi']], + ['audio/midi', ['midi', 'kar', 'mid']], + ['audio/mod', 'mod'], + ['audio/mp4', 'mp4a'], + ['audio/mpeg', ['mpga', 'mp3', 'm2a', 'mp2', 'mpa', 'mpg']], + ['audio/mpeg3', 'mp3'], + ['audio/nspaudio', ['la', 'lma']], + ['audio/ogg', 'oga'], + ['audio/s3m', 's3m'], + ['audio/tsp-audio', 'tsi'], + ['audio/tsplayer', 'tsp'], + ['audio/vnd.dece.audio', 'uva'], + ['audio/vnd.digital-winds', 'eol'], + ['audio/vnd.dra', 'dra'], + ['audio/vnd.dts', 'dts'], + ['audio/vnd.dts.hd', 'dtshd'], + ['audio/vnd.lucent.voice', 'lvp'], + ['audio/vnd.ms-playready.media.pya', 'pya'], + ['audio/vnd.nuera.ecelp4800', 'ecelp4800'], + ['audio/vnd.nuera.ecelp7470', 'ecelp7470'], + ['audio/vnd.nuera.ecelp9600', 'ecelp9600'], + ['audio/vnd.qcelp', 'qcp'], + ['audio/vnd.rip', 'rip'], + ['audio/voc', 'voc'], + ['audio/voxware', 'vox'], + ['audio/wav', 'wav'], + ['audio/webm', 'weba'], + ['audio/x-aac', 'aac'], + ['audio/x-adpcm', 'snd'], + ['audio/x-aiff', ['aiff', 'aif', 'aifc']], + ['audio/x-au', 'au'], + ['audio/x-gsm', ['gsd', 'gsm']], + ['audio/x-jam', 'jam'], + ['audio/x-liveaudio', 'lam'], + ['audio/x-mid', ['mid', 'midi']], + ['audio/x-midi', ['midi', 'mid']], + ['audio/x-mod', 'mod'], + ['audio/x-mpeg', 'mp2'], + ['audio/x-mpeg-3', 'mp3'], + ['audio/x-mpegurl', 'm3u'], + ['audio/x-mpequrl', 'm3u'], + ['audio/x-ms-wax', 'wax'], + ['audio/x-ms-wma', 'wma'], + ['audio/x-nspaudio', ['la', 'lma']], + ['audio/x-pn-realaudio', ['ra', 'ram', 'rm', 'rmm', 'rmp']], + ['audio/x-pn-realaudio-plugin', ['ra', 'rmp', 'rpm']], + ['audio/x-psid', 'sid'], + ['audio/x-realaudio', 'ra'], + ['audio/x-twinvq', 'vqf'], + ['audio/x-twinvq-plugin', ['vqe', 'vql']], + ['audio/x-vnd.audioexplosion.mjuicemediafile', 'mjf'], + ['audio/x-voc', 'voc'], + ['audio/x-wav', 'wav'], + ['audio/xm', 'xm'], + ['chemical/x-cdx', 'cdx'], + ['chemical/x-cif', 'cif'], + ['chemical/x-cmdf', 'cmdf'], + ['chemical/x-cml', 'cml'], + ['chemical/x-csml', 'csml'], + ['chemical/x-pdb', ['pdb', 'xyz']], + ['chemical/x-xyz', 'xyz'], + ['drawing/x-dwf', 'dwf'], + ['i-world/i-vrml', 'ivr'], + ['image/bmp', ['bmp', 'bm']], + ['image/cgm', 'cgm'], + ['image/cis-cod', 'cod'], + ['image/cmu-raster', ['ras', 'rast']], + ['image/fif', 'fif'], + ['image/florian', ['flo', 'turbot']], + ['image/g3fax', 'g3'], + ['image/gif', 'gif'], + ['image/ief', ['ief', 'iefs']], + ['image/jpeg', ['jpeg', 'jpe', 'jpg', 'jfif', 'jfif-tbnl']], + ['image/jutvision', 'jut'], + ['image/ktx', 'ktx'], + ['image/naplps', ['nap', 'naplps']], + ['image/pict', ['pic', 'pict']], + ['image/pipeg', 'jfif'], + ['image/pjpeg', ['jfif', 'jpe', 'jpeg', 'jpg']], + ['image/png', ['png', 'x-png']], + ['image/prs.btif', 'btif'], + ['image/svg+xml', 'svg'], + ['image/tiff', ['tif', 'tiff']], + ['image/vasa', 'mcf'], + ['image/vnd.adobe.photoshop', 'psd'], + ['image/vnd.dece.graphic', 'uvi'], + ['image/vnd.djvu', 'djvu'], + ['image/vnd.dvb.subtitle', 'sub'], + ['image/vnd.dwg', ['dwg', 'dxf', 'svf']], + ['image/vnd.dxf', 'dxf'], + ['image/vnd.fastbidsheet', 'fbs'], + ['image/vnd.fpx', 'fpx'], + ['image/vnd.fst', 'fst'], + ['image/vnd.fujixerox.edmics-mmr', 'mmr'], + ['image/vnd.fujixerox.edmics-rlc', 'rlc'], + ['image/vnd.ms-modi', 'mdi'], + ['image/vnd.net-fpx', ['fpx', 'npx']], + ['image/vnd.rn-realflash', 'rf'], + ['image/vnd.rn-realpix', 'rp'], + ['image/vnd.wap.wbmp', 'wbmp'], + ['image/vnd.xiff', 'xif'], + ['image/webp', 'webp'], + ['image/x-cmu-raster', 'ras'], + ['image/x-cmx', 'cmx'], + ['image/x-dwg', ['dwg', 'dxf', 'svf']], + ['image/x-freehand', 'fh'], + ['image/x-icon', 'ico'], + ['image/x-jg', 'art'], + ['image/x-jps', 'jps'], + ['image/x-niff', ['niff', 'nif']], + ['image/x-pcx', 'pcx'], + ['image/x-pict', ['pct', 'pic']], + ['image/x-portable-anymap', 'pnm'], + ['image/x-portable-bitmap', 'pbm'], + ['image/x-portable-graymap', 'pgm'], + ['image/x-portable-greymap', 'pgm'], + ['image/x-portable-pixmap', 'ppm'], + ['image/x-quicktime', ['qif', 'qti', 'qtif']], + ['image/x-rgb', 'rgb'], + ['image/x-tiff', ['tif', 'tiff']], + ['image/x-windows-bmp', 'bmp'], + ['image/x-xbitmap', 'xbm'], + ['image/x-xbm', 'xbm'], + ['image/x-xpixmap', ['xpm', 'pm']], + ['image/x-xwd', 'xwd'], + ['image/x-xwindowdump', 'xwd'], + ['image/xbm', 'xbm'], + ['image/xpm', 'xpm'], + ['message/rfc822', ['eml', 'mht', 'mhtml', 'nws', 'mime']], + ['model/iges', ['iges', 'igs']], + ['model/mesh', 'msh'], + ['model/vnd.collada+xml', 'dae'], + ['model/vnd.dwf', 'dwf'], + ['model/vnd.gdl', 'gdl'], + ['model/vnd.gtw', 'gtw'], + ['model/vnd.mts', 'mts'], + ['model/vnd.vtu', 'vtu'], + ['model/vrml', ['vrml', 'wrl', 'wrz']], + ['model/x-pov', 'pov'], + ['multipart/x-gzip', 'gzip'], + ['multipart/x-ustar', 'ustar'], + ['multipart/x-zip', 'zip'], + ['music/crescendo', ['mid', 'midi']], + ['music/x-karaoke', 'kar'], + ['paleovu/x-pv', 'pvu'], + ['text/asp', 'asp'], + ['text/calendar', 'ics'], + ['text/css', 'css'], + ['text/csv', 'csv'], + ['text/ecmascript', 'js'], + ['text/h323', '323'], + ['text/html', ['html', 'htm', 'stm', 'acgi', 'htmls', 'htx', 'shtml']], + ['text/iuls', 'uls'], + ['text/javascript', 'js'], + ['text/mcf', 'mcf'], + ['text/n3', 'n3'], + ['text/pascal', 'pas'], + [ + 'text/plain', + [ + 'txt', + 'bas', + 'c', + 'h', + 'c++', + 'cc', + 'com', + 'conf', + 'cxx', + 'def', + 'f', + 'f90', + 'for', + 'g', + 'hh', + 'idc', + 'jav', + 'java', + 'list', + 'log', + 'lst', + 'm', + 'mar', + 'pl', + 'sdml', + 'text' + ] + ], + ['text/plain-bas', 'par'], + ['text/prs.lines.tag', 'dsc'], + ['text/richtext', ['rtx', 'rt', 'rtf']], + ['text/scriplet', 'wsc'], + ['text/scriptlet', 'sct'], + ['text/sgml', ['sgm', 'sgml']], + ['text/tab-separated-values', 'tsv'], + ['text/troff', 't'], + ['text/turtle', 'ttl'], + ['text/uri-list', ['uni', 'unis', 'uri', 'uris']], + ['text/vnd.abc', 'abc'], + ['text/vnd.curl', 'curl'], + ['text/vnd.curl.dcurl', 'dcurl'], + ['text/vnd.curl.mcurl', 'mcurl'], + ['text/vnd.curl.scurl', 'scurl'], + ['text/vnd.fly', 'fly'], + ['text/vnd.fmi.flexstor', 'flx'], + ['text/vnd.graphviz', 'gv'], + ['text/vnd.in3d.3dml', '3dml'], + ['text/vnd.in3d.spot', 'spot'], + ['text/vnd.rn-realtext', 'rt'], + ['text/vnd.sun.j2me.app-descriptor', 'jad'], + ['text/vnd.wap.wml', 'wml'], + ['text/vnd.wap.wmlscript', 'wmls'], + ['text/webviewhtml', 'htt'], + ['text/x-asm', ['asm', 's']], + ['text/x-audiosoft-intra', 'aip'], + ['text/x-c', ['c', 'cc', 'cpp']], + ['text/x-component', 'htc'], + ['text/x-fortran', ['for', 'f', 'f77', 'f90']], + ['text/x-h', ['h', 'hh']], + ['text/x-java-source', ['java', 'jav']], + ['text/x-java-source,java', 'java'], + ['text/x-la-asf', 'lsx'], + ['text/x-m', 'm'], + ['text/x-pascal', 'p'], + ['text/x-script', 'hlb'], + ['text/x-script.csh', 'csh'], + ['text/x-script.elisp', 'el'], + ['text/x-script.guile', 'scm'], + ['text/x-script.ksh', 'ksh'], + ['text/x-script.lisp', 'lsp'], + ['text/x-script.perl', 'pl'], + ['text/x-script.perl-module', 'pm'], + ['text/x-script.phyton', 'py'], + ['text/x-script.rexx', 'rexx'], + ['text/x-script.scheme', 'scm'], + ['text/x-script.sh', 'sh'], + ['text/x-script.tcl', 'tcl'], + ['text/x-script.tcsh', 'tcsh'], + ['text/x-script.zsh', 'zsh'], + ['text/x-server-parsed-html', ['shtml', 'ssi']], + ['text/x-setext', 'etx'], + ['text/x-sgml', ['sgm', 'sgml']], + ['text/x-speech', ['spc', 'talk']], + ['text/x-uil', 'uil'], + ['text/x-uuencode', ['uu', 'uue']], + ['text/x-vcalendar', 'vcs'], + ['text/x-vcard', 'vcf'], + ['text/xml', 'xml'], + ['video/3gpp', '3gp'], + ['video/3gpp2', '3g2'], + ['video/animaflex', 'afl'], + ['video/avi', 'avi'], + ['video/avs-video', 'avs'], + ['video/dl', 'dl'], + ['video/fli', 'fli'], + ['video/gl', 'gl'], + ['video/h261', 'h261'], + ['video/h263', 'h263'], + ['video/h264', 'h264'], + ['video/jpeg', 'jpgv'], + ['video/jpm', 'jpm'], + ['video/mj2', 'mj2'], + ['video/mp4', 'mp4'], + ['video/mpeg', ['mpeg', 'mp2', 'mpa', 'mpe', 'mpg', 'mpv2', 'm1v', 'm2v', 'mp3']], + ['video/msvideo', 'avi'], + ['video/ogg', 'ogv'], + ['video/quicktime', ['mov', 'qt', 'moov']], + ['video/vdo', 'vdo'], + ['video/vivo', ['viv', 'vivo']], + ['video/vnd.dece.hd', 'uvh'], + ['video/vnd.dece.mobile', 'uvm'], + ['video/vnd.dece.pd', 'uvp'], + ['video/vnd.dece.sd', 'uvs'], + ['video/vnd.dece.video', 'uvv'], + ['video/vnd.fvt', 'fvt'], + ['video/vnd.mpegurl', 'mxu'], + ['video/vnd.ms-playready.media.pyv', 'pyv'], + ['video/vnd.rn-realvideo', 'rv'], + ['video/vnd.uvvu.mp4', 'uvu'], + ['video/vnd.vivo', ['viv', 'vivo']], + ['video/vosaic', 'vos'], + ['video/webm', 'webm'], + ['video/x-amt-demorun', 'xdr'], + ['video/x-amt-showrun', 'xsr'], + ['video/x-atomic3d-feature', 'fmf'], + ['video/x-dl', 'dl'], + ['video/x-dv', ['dif', 'dv']], + ['video/x-f4v', 'f4v'], + ['video/x-fli', 'fli'], + ['video/x-flv', 'flv'], + ['video/x-gl', 'gl'], + ['video/x-isvideo', 'isu'], + ['video/x-la-asf', ['lsf', 'lsx']], + ['video/x-m4v', 'm4v'], + ['video/x-motion-jpeg', 'mjpg'], + ['video/x-mpeg', ['mp3', 'mp2']], + ['video/x-mpeq2a', 'mp2'], + ['video/x-ms-asf', ['asf', 'asr', 'asx']], + ['video/x-ms-asf-plugin', 'asx'], + ['video/x-ms-wm', 'wm'], + ['video/x-ms-wmv', 'wmv'], + ['video/x-ms-wmx', 'wmx'], + ['video/x-ms-wvx', 'wvx'], + ['video/x-msvideo', 'avi'], + ['video/x-qtc', 'qtc'], + ['video/x-scm', 'scm'], + ['video/x-sgi-movie', ['movie', 'mv']], + ['windows/metafile', 'wmf'], + ['www/mime', 'mime'], + ['x-conference/x-cooltalk', 'ice'], + ['x-music/x-midi', ['mid', 'midi']], + ['x-world/x-3dmf', ['3dm', '3dmf', 'qd3', 'qd3d']], + ['x-world/x-svr', 'svr'], + ['x-world/x-vrml', ['flr', 'vrml', 'wrl', 'wrz', 'xaf', 'xof']], + ['x-world/x-vrt', 'vrt'], + ['xgl/drawing', 'xgz'], + ['xgl/movie', 'xmz'] +]); +const extensions = new Map([ + ['123', 'application/vnd.lotus-1-2-3'], + ['323', 'text/h323'], + ['*', 'application/octet-stream'], + ['3dm', 'x-world/x-3dmf'], + ['3dmf', 'x-world/x-3dmf'], + ['3dml', 'text/vnd.in3d.3dml'], + ['3g2', 'video/3gpp2'], + ['3gp', 'video/3gpp'], + ['7z', 'application/x-7z-compressed'], + ['a', 'application/octet-stream'], + ['aab', 'application/x-authorware-bin'], + ['aac', 'audio/x-aac'], + ['aam', 'application/x-authorware-map'], + ['aas', 'application/x-authorware-seg'], + ['abc', 'text/vnd.abc'], + ['abw', 'application/x-abiword'], + ['ac', 'application/pkix-attr-cert'], + ['acc', 'application/vnd.americandynamics.acc'], + ['ace', 'application/x-ace-compressed'], + ['acgi', 'text/html'], + ['acu', 'application/vnd.acucobol'], + ['acx', 'application/internet-property-stream'], + ['adp', 'audio/adpcm'], + ['aep', 'application/vnd.audiograph'], + ['afl', 'video/animaflex'], + ['afp', 'application/vnd.ibm.modcap'], + ['ahead', 'application/vnd.ahead.space'], + ['ai', 'application/postscript'], + ['aif', ['audio/aiff', 'audio/x-aiff']], + ['aifc', ['audio/aiff', 'audio/x-aiff']], + ['aiff', ['audio/aiff', 'audio/x-aiff']], + ['aim', 'application/x-aim'], + ['aip', 'text/x-audiosoft-intra'], + ['air', 'application/vnd.adobe.air-application-installer-package+zip'], + ['ait', 'application/vnd.dvb.ait'], + ['ami', 'application/vnd.amiga.ami'], + ['ani', 'application/x-navi-animation'], + ['aos', 'application/x-nokia-9000-communicator-add-on-software'], + ['apk', 'application/vnd.android.package-archive'], + ['application', 'application/x-ms-application'], + ['apr', 'application/vnd.lotus-approach'], + ['aps', 'application/mime'], + ['arc', 'application/octet-stream'], + ['arj', ['application/arj', 'application/octet-stream']], + ['art', 'image/x-jg'], + ['asf', 'video/x-ms-asf'], + ['asm', 'text/x-asm'], + ['aso', 'application/vnd.accpac.simply.aso'], + ['asp', 'text/asp'], + ['asr', 'video/x-ms-asf'], + ['asx', ['video/x-ms-asf', 'application/x-mplayer2', 'video/x-ms-asf-plugin']], + ['atc', 'application/vnd.acucorp'], + ['atomcat', 'application/atomcat+xml'], + ['atomsvc', 'application/atomsvc+xml'], + ['atx', 'application/vnd.antix.game-component'], + ['au', ['audio/basic', 'audio/x-au']], + ['avi', ['video/avi', 'video/msvideo', 'application/x-troff-msvideo', 'video/x-msvideo']], + ['avs', 'video/avs-video'], + ['aw', 'application/applixware'], + ['axs', 'application/olescript'], + ['azf', 'application/vnd.airzip.filesecure.azf'], + ['azs', 'application/vnd.airzip.filesecure.azs'], + ['azw', 'application/vnd.amazon.ebook'], + ['bas', 'text/plain'], + ['bcpio', 'application/x-bcpio'], + ['bdf', 'application/x-font-bdf'], + ['bdm', 'application/vnd.syncml.dm+wbxml'], + ['bed', 'application/vnd.realvnc.bed'], + ['bh2', 'application/vnd.fujitsu.oasysprs'], + ['bin', ['application/octet-stream', 'application/mac-binary', 'application/macbinary', 'application/x-macbinary', 'application/x-binary']], + ['bm', 'image/bmp'], + ['bmi', 'application/vnd.bmi'], + ['bmp', ['image/bmp', 'image/x-windows-bmp']], + ['boo', 'application/book'], + ['book', 'application/book'], + ['box', 'application/vnd.previewsystems.box'], + ['boz', 'application/x-bzip2'], + ['bsh', 'application/x-bsh'], + ['btif', 'image/prs.btif'], + ['bz', 'application/x-bzip'], + ['bz2', 'application/x-bzip2'], + ['c', ['text/plain', 'text/x-c']], + ['c++', 'text/plain'], + ['c11amc', 'application/vnd.cluetrust.cartomobile-config'], + ['c11amz', 'application/vnd.cluetrust.cartomobile-config-pkg'], + ['c4g', 'application/vnd.clonk.c4group'], + ['cab', 'application/vnd.ms-cab-compressed'], + ['car', 'application/vnd.curl.car'], + ['cat', ['application/vnd.ms-pkiseccat', 'application/vnd.ms-pki.seccat']], + ['cc', ['text/plain', 'text/x-c']], + ['ccad', 'application/clariscad'], + ['cco', 'application/x-cocoa'], + ['ccxml', 'application/ccxml+xml,'], + ['cdbcmsg', 'application/vnd.contact.cmsg'], + ['cdf', ['application/cdf', 'application/x-cdf', 'application/x-netcdf']], + ['cdkey', 'application/vnd.mediastation.cdkey'], + ['cdmia', 'application/cdmi-capability'], + ['cdmic', 'application/cdmi-container'], + ['cdmid', 'application/cdmi-domain'], + ['cdmio', 'application/cdmi-object'], + ['cdmiq', 'application/cdmi-queue'], + ['cdx', 'chemical/x-cdx'], + ['cdxml', 'application/vnd.chemdraw+xml'], + ['cdy', 'application/vnd.cinderella'], + ['cer', ['application/pkix-cert', 'application/x-x509-ca-cert']], + ['cgm', 'image/cgm'], + ['cha', 'application/x-chat'], + ['chat', 'application/x-chat'], + ['chm', 'application/vnd.ms-htmlhelp'], + ['chrt', 'application/vnd.kde.kchart'], + ['cif', 'chemical/x-cif'], + ['cii', 'application/vnd.anser-web-certificate-issue-initiation'], + ['cil', 'application/vnd.ms-artgalry'], + ['cla', 'application/vnd.claymore'], + ['class', ['application/octet-stream', 'application/java', 'application/java-byte-code', 'application/java-vm', 'application/x-java-class']], + ['clkk', 'application/vnd.crick.clicker.keyboard'], + ['clkp', 'application/vnd.crick.clicker.palette'], + ['clkt', 'application/vnd.crick.clicker.template'], + ['clkw', 'application/vnd.crick.clicker.wordbank'], + ['clkx', 'application/vnd.crick.clicker'], + ['clp', 'application/x-msclip'], + ['cmc', 'application/vnd.cosmocaller'], + ['cmdf', 'chemical/x-cmdf'], + ['cml', 'chemical/x-cml'], + ['cmp', 'application/vnd.yellowriver-custom-menu'], + ['cmx', 'image/x-cmx'], + ['cod', ['image/cis-cod', 'application/vnd.rim.cod']], + ['com', ['application/octet-stream', 'text/plain']], + ['conf', 'text/plain'], + ['cpio', 'application/x-cpio'], + ['cpp', 'text/x-c'], + ['cpt', ['application/mac-compactpro', 'application/x-compactpro', 'application/x-cpt']], + ['crd', 'application/x-mscardfile'], + ['crl', ['application/pkix-crl', 'application/pkcs-crl']], + ['crt', ['application/pkix-cert', 'application/x-x509-user-cert', 'application/x-x509-ca-cert']], + ['cryptonote', 'application/vnd.rig.cryptonote'], + ['csh', ['text/x-script.csh', 'application/x-csh']], + ['csml', 'chemical/x-csml'], + ['csp', 'application/vnd.commonspace'], + ['css', ['text/css', 'application/x-pointplus']], + ['csv', 'text/csv'], + ['cu', 'application/cu-seeme'], + ['curl', 'text/vnd.curl'], + ['cww', 'application/prs.cww'], + ['cxx', 'text/plain'], + ['dae', 'model/vnd.collada+xml'], + ['daf', 'application/vnd.mobius.daf'], + ['davmount', 'application/davmount+xml'], + ['dcr', 'application/x-director'], + ['dcurl', 'text/vnd.curl.dcurl'], + ['dd2', 'application/vnd.oma.dd2+xml'], + ['ddd', 'application/vnd.fujixerox.ddd'], + ['deb', 'application/x-debian-package'], + ['deepv', 'application/x-deepv'], + ['def', 'text/plain'], + ['der', 'application/x-x509-ca-cert'], + ['dfac', 'application/vnd.dreamfactory'], + ['dif', 'video/x-dv'], + ['dir', 'application/x-director'], + ['dis', 'application/vnd.mobius.dis'], + ['djvu', 'image/vnd.djvu'], + ['dl', ['video/dl', 'video/x-dl']], + ['dll', 'application/x-msdownload'], + ['dms', 'application/octet-stream'], + ['dna', 'application/vnd.dna'], + ['doc', 'application/msword'], + ['docm', 'application/vnd.ms-word.document.macroenabled.12'], + ['docx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'], + ['dot', 'application/msword'], + ['dotm', 'application/vnd.ms-word.template.macroenabled.12'], + ['dotx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.template'], + ['dp', ['application/commonground', 'application/vnd.osgi.dp']], + ['dpg', 'application/vnd.dpgraph'], + ['dra', 'audio/vnd.dra'], + ['drw', 'application/drafting'], + ['dsc', 'text/prs.lines.tag'], + ['dssc', 'application/dssc+der'], + ['dtb', 'application/x-dtbook+xml'], + ['dtd', 'application/xml-dtd'], + ['dts', 'audio/vnd.dts'], + ['dtshd', 'audio/vnd.dts.hd'], + ['dump', 'application/octet-stream'], + ['dv', 'video/x-dv'], + ['dvi', 'application/x-dvi'], + ['dwf', ['model/vnd.dwf', 'drawing/x-dwf']], + ['dwg', ['application/acad', 'image/vnd.dwg', 'image/x-dwg']], + ['dxf', ['application/dxf', 'image/vnd.dwg', 'image/vnd.dxf', 'image/x-dwg']], + ['dxp', 'application/vnd.spotfire.dxp'], + ['dxr', 'application/x-director'], + ['ecelp4800', 'audio/vnd.nuera.ecelp4800'], + ['ecelp7470', 'audio/vnd.nuera.ecelp7470'], + ['ecelp9600', 'audio/vnd.nuera.ecelp9600'], + ['edm', 'application/vnd.novadigm.edm'], + ['edx', 'application/vnd.novadigm.edx'], + ['efif', 'application/vnd.picsel'], + ['ei6', 'application/vnd.pg.osasli'], + ['el', 'text/x-script.elisp'], + ['elc', ['application/x-elc', 'application/x-bytecode.elisp']], + ['eml', 'message/rfc822'], + ['emma', 'application/emma+xml'], + ['env', 'application/x-envoy'], + ['eol', 'audio/vnd.digital-winds'], + ['eot', 'application/vnd.ms-fontobject'], + ['eps', 'application/postscript'], + ['epub', 'application/epub+zip'], + ['es', ['application/ecmascript', 'application/x-esrehber']], + ['es3', 'application/vnd.eszigno3+xml'], + ['esf', 'application/vnd.epson.esf'], + ['etx', 'text/x-setext'], + ['evy', ['application/envoy', 'application/x-envoy']], + ['exe', ['application/octet-stream', 'application/x-msdownload']], + ['exi', 'application/exi'], + ['ext', 'application/vnd.novadigm.ext'], + ['ez2', 'application/vnd.ezpix-album'], + ['ez3', 'application/vnd.ezpix-package'], + ['f', ['text/plain', 'text/x-fortran']], + ['f4v', 'video/x-f4v'], + ['f77', 'text/x-fortran'], + ['f90', ['text/plain', 'text/x-fortran']], + ['fbs', 'image/vnd.fastbidsheet'], + ['fcs', 'application/vnd.isac.fcs'], + ['fdf', 'application/vnd.fdf'], + ['fe_launch', 'application/vnd.denovo.fcselayout-link'], + ['fg5', 'application/vnd.fujitsu.oasysgp'], + ['fh', 'image/x-freehand'], + ['fif', ['application/fractals', 'image/fif']], + ['fig', 'application/x-xfig'], + ['fli', ['video/fli', 'video/x-fli']], + ['flo', ['image/florian', 'application/vnd.micrografx.flo']], + ['flr', 'x-world/x-vrml'], + ['flv', 'video/x-flv'], + ['flw', 'application/vnd.kde.kivio'], + ['flx', 'text/vnd.fmi.flexstor'], + ['fly', 'text/vnd.fly'], + ['fm', 'application/vnd.framemaker'], + ['fmf', 'video/x-atomic3d-feature'], + ['fnc', 'application/vnd.frogans.fnc'], + ['for', ['text/plain', 'text/x-fortran']], + ['fpx', ['image/vnd.fpx', 'image/vnd.net-fpx']], + ['frl', 'application/freeloader'], + ['fsc', 'application/vnd.fsc.weblaunch'], + ['fst', 'image/vnd.fst'], + ['ftc', 'application/vnd.fluxtime.clip'], + ['fti', 'application/vnd.anser-web-funds-transfer-initiation'], + ['funk', 'audio/make'], + ['fvt', 'video/vnd.fvt'], + ['fxp', 'application/vnd.adobe.fxp'], + ['fzs', 'application/vnd.fuzzysheet'], + ['g', 'text/plain'], + ['g2w', 'application/vnd.geoplan'], + ['g3', 'image/g3fax'], + ['g3w', 'application/vnd.geospace'], + ['gac', 'application/vnd.groove-account'], + ['gdl', 'model/vnd.gdl'], + ['geo', 'application/vnd.dynageo'], + ['gex', 'application/vnd.geometry-explorer'], + ['ggb', 'application/vnd.geogebra.file'], + ['ggt', 'application/vnd.geogebra.tool'], + ['ghf', 'application/vnd.groove-help'], + ['gif', 'image/gif'], + ['gim', 'application/vnd.groove-identity-message'], + ['gl', ['video/gl', 'video/x-gl']], + ['gmx', 'application/vnd.gmx'], + ['gnumeric', 'application/x-gnumeric'], + ['gph', 'application/vnd.flographit'], + ['gqf', 'application/vnd.grafeq'], + ['gram', 'application/srgs'], + ['grv', 'application/vnd.groove-injector'], + ['grxml', 'application/srgs+xml'], + ['gsd', 'audio/x-gsm'], + ['gsf', 'application/x-font-ghostscript'], + ['gsm', 'audio/x-gsm'], + ['gsp', 'application/x-gsp'], + ['gss', 'application/x-gss'], + ['gtar', 'application/x-gtar'], + ['gtm', 'application/vnd.groove-tool-message'], + ['gtw', 'model/vnd.gtw'], + ['gv', 'text/vnd.graphviz'], + ['gxt', 'application/vnd.geonext'], + ['gz', ['application/x-gzip', 'application/x-compressed']], + ['gzip', ['multipart/x-gzip', 'application/x-gzip']], + ['h', ['text/plain', 'text/x-h']], + ['h261', 'video/h261'], + ['h263', 'video/h263'], + ['h264', 'video/h264'], + ['hal', 'application/vnd.hal+xml'], + ['hbci', 'application/vnd.hbci'], + ['hdf', 'application/x-hdf'], + ['help', 'application/x-helpfile'], + ['hgl', 'application/vnd.hp-hpgl'], + ['hh', ['text/plain', 'text/x-h']], + ['hlb', 'text/x-script'], + ['hlp', ['application/winhlp', 'application/hlp', 'application/x-helpfile', 'application/x-winhelp']], + ['hpg', 'application/vnd.hp-hpgl'], + ['hpgl', 'application/vnd.hp-hpgl'], + ['hpid', 'application/vnd.hp-hpid'], + ['hps', 'application/vnd.hp-hps'], + [ + 'hqx', + [ + 'application/mac-binhex40', + 'application/binhex', + 'application/binhex4', + 'application/mac-binhex', + 'application/x-binhex40', + 'application/x-mac-binhex40' + ] + ], + ['hta', 'application/hta'], + ['htc', 'text/x-component'], + ['htke', 'application/vnd.kenameaapp'], + ['htm', 'text/html'], + ['html', 'text/html'], + ['htmls', 'text/html'], + ['htt', 'text/webviewhtml'], + ['htx', 'text/html'], + ['hvd', 'application/vnd.yamaha.hv-dic'], + ['hvp', 'application/vnd.yamaha.hv-voice'], + ['hvs', 'application/vnd.yamaha.hv-script'], + ['i2g', 'application/vnd.intergeo'], + ['icc', 'application/vnd.iccprofile'], + ['ice', 'x-conference/x-cooltalk'], + ['ico', 'image/x-icon'], + ['ics', 'text/calendar'], + ['idc', 'text/plain'], + ['ief', 'image/ief'], + ['iefs', 'image/ief'], + ['ifm', 'application/vnd.shana.informed.formdata'], + ['iges', ['application/iges', 'model/iges']], + ['igl', 'application/vnd.igloader'], + ['igm', 'application/vnd.insors.igm'], + ['igs', ['application/iges', 'model/iges']], + ['igx', 'application/vnd.micrografx.igx'], + ['iif', 'application/vnd.shana.informed.interchange'], + ['iii', 'application/x-iphone'], + ['ima', 'application/x-ima'], + ['imap', 'application/x-httpd-imap'], + ['imp', 'application/vnd.accpac.simply.imp'], + ['ims', 'application/vnd.ms-ims'], + ['inf', 'application/inf'], + ['ins', ['application/x-internet-signup', 'application/x-internett-signup']], + ['ip', 'application/x-ip2'], + ['ipfix', 'application/ipfix'], + ['ipk', 'application/vnd.shana.informed.package'], + ['irm', 'application/vnd.ibm.rights-management'], + ['irp', 'application/vnd.irepository.package+xml'], + ['isp', 'application/x-internet-signup'], + ['isu', 'video/x-isvideo'], + ['it', 'audio/it'], + ['itp', 'application/vnd.shana.informed.formtemplate'], + ['iv', 'application/x-inventor'], + ['ivp', 'application/vnd.immervision-ivp'], + ['ivr', 'i-world/i-vrml'], + ['ivu', 'application/vnd.immervision-ivu'], + ['ivy', 'application/x-livescreen'], + ['jad', 'text/vnd.sun.j2me.app-descriptor'], + ['jam', ['application/vnd.jam', 'audio/x-jam']], + ['jar', 'application/java-archive'], + ['jav', ['text/plain', 'text/x-java-source']], + ['java', ['text/plain', 'text/x-java-source,java', 'text/x-java-source']], + ['jcm', 'application/x-java-commerce'], + ['jfif', ['image/pipeg', 'image/jpeg', 'image/pjpeg']], + ['jfif-tbnl', 'image/jpeg'], + ['jisp', 'application/vnd.jisp'], + ['jlt', 'application/vnd.hp-jlyt'], + ['jnlp', 'application/x-java-jnlp-file'], + ['joda', 'application/vnd.joost.joda-archive'], + ['jpe', ['image/jpeg', 'image/pjpeg']], + ['jpeg', ['image/jpeg', 'image/pjpeg']], + ['jpg', ['image/jpeg', 'image/pjpeg']], + ['jpgv', 'video/jpeg'], + ['jpm', 'video/jpm'], + ['jps', 'image/x-jps'], + ['js', ['application/javascript', 'application/ecmascript', 'text/javascript', 'text/ecmascript', 'application/x-javascript']], + ['json', 'application/json'], + ['jut', 'image/jutvision'], + ['kar', ['audio/midi', 'music/x-karaoke']], + ['karbon', 'application/vnd.kde.karbon'], + ['kfo', 'application/vnd.kde.kformula'], + ['kia', 'application/vnd.kidspiration'], + ['kml', 'application/vnd.google-earth.kml+xml'], + ['kmz', 'application/vnd.google-earth.kmz'], + ['kne', 'application/vnd.kinar'], + ['kon', 'application/vnd.kde.kontour'], + ['kpr', 'application/vnd.kde.kpresenter'], + ['ksh', ['application/x-ksh', 'text/x-script.ksh']], + ['ksp', 'application/vnd.kde.kspread'], + ['ktx', 'image/ktx'], + ['ktz', 'application/vnd.kahootz'], + ['kwd', 'application/vnd.kde.kword'], + ['la', ['audio/nspaudio', 'audio/x-nspaudio']], + ['lam', 'audio/x-liveaudio'], + ['lasxml', 'application/vnd.las.las+xml'], + ['latex', 'application/x-latex'], + ['lbd', 'application/vnd.llamagraphics.life-balance.desktop'], + ['lbe', 'application/vnd.llamagraphics.life-balance.exchange+xml'], + ['les', 'application/vnd.hhe.lesson-player'], + ['lha', ['application/octet-stream', 'application/lha', 'application/x-lha']], + ['lhx', 'application/octet-stream'], + ['link66', 'application/vnd.route66.link66+xml'], + ['list', 'text/plain'], + ['lma', ['audio/nspaudio', 'audio/x-nspaudio']], + ['log', 'text/plain'], + ['lrm', 'application/vnd.ms-lrm'], + ['lsf', 'video/x-la-asf'], + ['lsp', ['application/x-lisp', 'text/x-script.lisp']], + ['lst', 'text/plain'], + ['lsx', ['video/x-la-asf', 'text/x-la-asf']], + ['ltf', 'application/vnd.frogans.ltf'], + ['ltx', 'application/x-latex'], + ['lvp', 'audio/vnd.lucent.voice'], + ['lwp', 'application/vnd.lotus-wordpro'], + ['lzh', ['application/octet-stream', 'application/x-lzh']], + ['lzx', ['application/lzx', 'application/octet-stream', 'application/x-lzx']], + ['m', ['text/plain', 'text/x-m']], + ['m13', 'application/x-msmediaview'], + ['m14', 'application/x-msmediaview'], + ['m1v', 'video/mpeg'], + ['m21', 'application/mp21'], + ['m2a', 'audio/mpeg'], + ['m2v', 'video/mpeg'], + ['m3u', ['audio/x-mpegurl', 'audio/x-mpequrl']], + ['m3u8', 'application/vnd.apple.mpegurl'], + ['m4v', 'video/x-m4v'], + ['ma', 'application/mathematica'], + ['mads', 'application/mads+xml'], + ['mag', 'application/vnd.ecowin.chart'], + ['man', 'application/x-troff-man'], + ['map', 'application/x-navimap'], + ['mar', 'text/plain'], + ['mathml', 'application/mathml+xml'], + ['mbd', 'application/mbedlet'], + ['mbk', 'application/vnd.mobius.mbk'], + ['mbox', 'application/mbox'], + ['mc$', 'application/x-magic-cap-package-1.0'], + ['mc1', 'application/vnd.medcalcdata'], + ['mcd', ['application/mcad', 'application/vnd.mcd', 'application/x-mathcad']], + ['mcf', ['image/vasa', 'text/mcf']], + ['mcp', 'application/netmc'], + ['mcurl', 'text/vnd.curl.mcurl'], + ['mdb', 'application/x-msaccess'], + ['mdi', 'image/vnd.ms-modi'], + ['me', 'application/x-troff-me'], + ['meta4', 'application/metalink4+xml'], + ['mets', 'application/mets+xml'], + ['mfm', 'application/vnd.mfmp'], + ['mgp', 'application/vnd.osgeo.mapguide.package'], + ['mgz', 'application/vnd.proteus.magazine'], + ['mht', 'message/rfc822'], + ['mhtml', 'message/rfc822'], + ['mid', ['audio/mid', 'audio/midi', 'music/crescendo', 'x-music/x-midi', 'audio/x-midi', 'application/x-midi', 'audio/x-mid']], + ['midi', ['audio/midi', 'music/crescendo', 'x-music/x-midi', 'audio/x-midi', 'application/x-midi', 'audio/x-mid']], + ['mif', ['application/vnd.mif', 'application/x-mif', 'application/x-frame']], + ['mime', ['message/rfc822', 'www/mime']], + ['mj2', 'video/mj2'], + ['mjf', 'audio/x-vnd.audioexplosion.mjuicemediafile'], + ['mjpg', 'video/x-motion-jpeg'], + ['mlp', 'application/vnd.dolby.mlp'], + ['mm', ['application/base64', 'application/x-meme']], + ['mmd', 'application/vnd.chipnuts.karaoke-mmd'], + ['mme', 'application/base64'], + ['mmf', 'application/vnd.smaf'], + ['mmr', 'image/vnd.fujixerox.edmics-mmr'], + ['mny', 'application/x-msmoney'], + ['mod', ['audio/mod', 'audio/x-mod']], + ['mods', 'application/mods+xml'], + ['moov', 'video/quicktime'], + ['mov', 'video/quicktime'], + ['movie', 'video/x-sgi-movie'], + ['mp2', ['video/mpeg', 'audio/mpeg', 'video/x-mpeg', 'audio/x-mpeg', 'video/x-mpeq2a']], + ['mp3', ['audio/mpeg', 'audio/mpeg3', 'video/mpeg', 'audio/x-mpeg-3', 'video/x-mpeg']], + ['mp4', ['video/mp4', 'application/mp4']], + ['mp4a', 'audio/mp4'], + ['mpa', ['video/mpeg', 'audio/mpeg']], + ['mpc', ['application/vnd.mophun.certificate', 'application/x-project']], + ['mpe', 'video/mpeg'], + ['mpeg', 'video/mpeg'], + ['mpg', ['video/mpeg', 'audio/mpeg']], + ['mpga', 'audio/mpeg'], + ['mpkg', 'application/vnd.apple.installer+xml'], + ['mpm', 'application/vnd.blueice.multipass'], + ['mpn', 'application/vnd.mophun.application'], + ['mpp', 'application/vnd.ms-project'], + ['mpt', 'application/x-project'], + ['mpv', 'application/x-project'], + ['mpv2', 'video/mpeg'], + ['mpx', 'application/x-project'], + ['mpy', 'application/vnd.ibm.minipay'], + ['mqy', 'application/vnd.mobius.mqy'], + ['mrc', 'application/marc'], + ['mrcx', 'application/marcxml+xml'], + ['ms', 'application/x-troff-ms'], + ['mscml', 'application/mediaservercontrol+xml'], + ['mseq', 'application/vnd.mseq'], + ['msf', 'application/vnd.epson.msf'], + ['msg', 'application/vnd.ms-outlook'], + ['msh', 'model/mesh'], + ['msl', 'application/vnd.mobius.msl'], + ['msty', 'application/vnd.muvee.style'], + ['mts', 'model/vnd.mts'], + ['mus', 'application/vnd.musician'], + ['musicxml', 'application/vnd.recordare.musicxml+xml'], + ['mv', 'video/x-sgi-movie'], + ['mvb', 'application/x-msmediaview'], + ['mwf', 'application/vnd.mfer'], + ['mxf', 'application/mxf'], + ['mxl', 'application/vnd.recordare.musicxml'], + ['mxml', 'application/xv+xml'], + ['mxs', 'application/vnd.triscape.mxs'], + ['mxu', 'video/vnd.mpegurl'], + ['my', 'audio/make'], + ['mzz', 'application/x-vnd.audioexplosion.mzz'], + ['n-gage', 'application/vnd.nokia.n-gage.symbian.install'], + ['n3', 'text/n3'], + ['nap', 'image/naplps'], + ['naplps', 'image/naplps'], + ['nbp', 'application/vnd.wolfram.player'], + ['nc', 'application/x-netcdf'], + ['ncm', 'application/vnd.nokia.configuration-message'], + ['ncx', 'application/x-dtbncx+xml'], + ['ngdat', 'application/vnd.nokia.n-gage.data'], + ['nif', 'image/x-niff'], + ['niff', 'image/x-niff'], + ['nix', 'application/x-mix-transfer'], + ['nlu', 'application/vnd.neurolanguage.nlu'], + ['nml', 'application/vnd.enliven'], + ['nnd', 'application/vnd.noblenet-directory'], + ['nns', 'application/vnd.noblenet-sealer'], + ['nnw', 'application/vnd.noblenet-web'], + ['npx', 'image/vnd.net-fpx'], + ['nsc', 'application/x-conference'], + ['nsf', 'application/vnd.lotus-notes'], + ['nvd', 'application/x-navidoc'], + ['nws', 'message/rfc822'], + ['o', 'application/octet-stream'], + ['oa2', 'application/vnd.fujitsu.oasys2'], + ['oa3', 'application/vnd.fujitsu.oasys3'], + ['oas', 'application/vnd.fujitsu.oasys'], + ['obd', 'application/x-msbinder'], + ['oda', 'application/oda'], + ['odb', 'application/vnd.oasis.opendocument.database'], + ['odc', 'application/vnd.oasis.opendocument.chart'], + ['odf', 'application/vnd.oasis.opendocument.formula'], + ['odft', 'application/vnd.oasis.opendocument.formula-template'], + ['odg', 'application/vnd.oasis.opendocument.graphics'], + ['odi', 'application/vnd.oasis.opendocument.image'], + ['odm', 'application/vnd.oasis.opendocument.text-master'], + ['odp', 'application/vnd.oasis.opendocument.presentation'], + ['ods', 'application/vnd.oasis.opendocument.spreadsheet'], + ['odt', 'application/vnd.oasis.opendocument.text'], + ['oga', 'audio/ogg'], + ['ogv', 'video/ogg'], + ['ogx', 'application/ogg'], + ['omc', 'application/x-omc'], + ['omcd', 'application/x-omcdatamaker'], + ['omcr', 'application/x-omcregerator'], + ['onetoc', 'application/onenote'], + ['opf', 'application/oebps-package+xml'], + ['org', 'application/vnd.lotus-organizer'], + ['osf', 'application/vnd.yamaha.openscoreformat'], + ['osfpvg', 'application/vnd.yamaha.openscoreformat.osfpvg+xml'], + ['otc', 'application/vnd.oasis.opendocument.chart-template'], + ['otf', 'application/x-font-otf'], + ['otg', 'application/vnd.oasis.opendocument.graphics-template'], + ['oth', 'application/vnd.oasis.opendocument.text-web'], + ['oti', 'application/vnd.oasis.opendocument.image-template'], + ['otp', 'application/vnd.oasis.opendocument.presentation-template'], + ['ots', 'application/vnd.oasis.opendocument.spreadsheet-template'], + ['ott', 'application/vnd.oasis.opendocument.text-template'], + ['oxt', 'application/vnd.openofficeorg.extension'], + ['p', 'text/x-pascal'], + ['p10', ['application/pkcs10', 'application/x-pkcs10']], + ['p12', ['application/pkcs-12', 'application/x-pkcs12']], + ['p7a', 'application/x-pkcs7-signature'], + ['p7b', 'application/x-pkcs7-certificates'], + ['p7c', ['application/pkcs7-mime', 'application/x-pkcs7-mime']], + ['p7m', ['application/pkcs7-mime', 'application/x-pkcs7-mime']], + ['p7r', 'application/x-pkcs7-certreqresp'], + ['p7s', ['application/pkcs7-signature', 'application/x-pkcs7-signature']], + ['p8', 'application/pkcs8'], + ['par', 'text/plain-bas'], + ['part', 'application/pro_eng'], + ['pas', 'text/pascal'], + ['paw', 'application/vnd.pawaafile'], + ['pbd', 'application/vnd.powerbuilder6'], + ['pbm', 'image/x-portable-bitmap'], + ['pcf', 'application/x-font-pcf'], + ['pcl', ['application/vnd.hp-pcl', 'application/x-pcl']], + ['pclxl', 'application/vnd.hp-pclxl'], + ['pct', 'image/x-pict'], + ['pcurl', 'application/vnd.curl.pcurl'], + ['pcx', 'image/x-pcx'], + ['pdb', ['application/vnd.palm', 'chemical/x-pdb']], + ['pdf', 'application/pdf'], + ['pfa', 'application/x-font-type1'], + ['pfr', 'application/font-tdpfr'], + ['pfunk', ['audio/make', 'audio/make.my.funk']], + ['pfx', 'application/x-pkcs12'], + ['pgm', ['image/x-portable-graymap', 'image/x-portable-greymap']], + ['pgn', 'application/x-chess-pgn'], + ['pgp', 'application/pgp-signature'], + ['pic', ['image/pict', 'image/x-pict']], + ['pict', 'image/pict'], + ['pkg', 'application/x-newton-compatible-pkg'], + ['pki', 'application/pkixcmp'], + ['pkipath', 'application/pkix-pkipath'], + ['pko', ['application/ynd.ms-pkipko', 'application/vnd.ms-pki.pko']], + ['pl', ['text/plain', 'text/x-script.perl']], + ['plb', 'application/vnd.3gpp.pic-bw-large'], + ['plc', 'application/vnd.mobius.plc'], + ['plf', 'application/vnd.pocketlearn'], + ['pls', 'application/pls+xml'], + ['plx', 'application/x-pixclscript'], + ['pm', ['text/x-script.perl-module', 'image/x-xpixmap']], + ['pm4', 'application/x-pagemaker'], + ['pm5', 'application/x-pagemaker'], + ['pma', 'application/x-perfmon'], + ['pmc', 'application/x-perfmon'], + ['pml', ['application/vnd.ctc-posml', 'application/x-perfmon']], + ['pmr', 'application/x-perfmon'], + ['pmw', 'application/x-perfmon'], + ['png', 'image/png'], + ['pnm', ['application/x-portable-anymap', 'image/x-portable-anymap']], + ['portpkg', 'application/vnd.macports.portpkg'], + ['pot', ['application/vnd.ms-powerpoint', 'application/mspowerpoint']], + ['potm', 'application/vnd.ms-powerpoint.template.macroenabled.12'], + ['potx', 'application/vnd.openxmlformats-officedocument.presentationml.template'], + ['pov', 'model/x-pov'], + ['ppa', 'application/vnd.ms-powerpoint'], + ['ppam', 'application/vnd.ms-powerpoint.addin.macroenabled.12'], + ['ppd', 'application/vnd.cups-ppd'], + ['ppm', 'image/x-portable-pixmap'], + ['pps', ['application/vnd.ms-powerpoint', 'application/mspowerpoint']], + ['ppsm', 'application/vnd.ms-powerpoint.slideshow.macroenabled.12'], + ['ppsx', 'application/vnd.openxmlformats-officedocument.presentationml.slideshow'], + ['ppt', ['application/vnd.ms-powerpoint', 'application/mspowerpoint', 'application/powerpoint', 'application/x-mspowerpoint']], + ['pptm', 'application/vnd.ms-powerpoint.presentation.macroenabled.12'], + ['pptx', 'application/vnd.openxmlformats-officedocument.presentationml.presentation'], + ['ppz', 'application/mspowerpoint'], + ['prc', 'application/x-mobipocket-ebook'], + ['pre', ['application/vnd.lotus-freelance', 'application/x-freelance']], + ['prf', 'application/pics-rules'], + ['prt', 'application/pro_eng'], + ['ps', 'application/postscript'], + ['psb', 'application/vnd.3gpp.pic-bw-small'], + ['psd', ['application/octet-stream', 'image/vnd.adobe.photoshop']], + ['psf', 'application/x-font-linux-psf'], + ['pskcxml', 'application/pskc+xml'], + ['ptid', 'application/vnd.pvi.ptid1'], + ['pub', 'application/x-mspublisher'], + ['pvb', 'application/vnd.3gpp.pic-bw-var'], + ['pvu', 'paleovu/x-pv'], + ['pwn', 'application/vnd.3m.post-it-notes'], + ['pwz', 'application/vnd.ms-powerpoint'], + ['py', 'text/x-script.phyton'], + ['pya', 'audio/vnd.ms-playready.media.pya'], + ['pyc', 'application/x-bytecode.python'], + ['pyv', 'video/vnd.ms-playready.media.pyv'], + ['qam', 'application/vnd.epson.quickanime'], + ['qbo', 'application/vnd.intu.qbo'], + ['qcp', 'audio/vnd.qcelp'], + ['qd3', 'x-world/x-3dmf'], + ['qd3d', 'x-world/x-3dmf'], + ['qfx', 'application/vnd.intu.qfx'], + ['qif', 'image/x-quicktime'], + ['qps', 'application/vnd.publishare-delta-tree'], + ['qt', 'video/quicktime'], + ['qtc', 'video/x-qtc'], + ['qti', 'image/x-quicktime'], + ['qtif', 'image/x-quicktime'], + ['qxd', 'application/vnd.quark.quarkxpress'], + ['ra', ['audio/x-realaudio', 'audio/x-pn-realaudio', 'audio/x-pn-realaudio-plugin']], + ['ram', 'audio/x-pn-realaudio'], + ['rar', 'application/x-rar-compressed'], + ['ras', ['image/cmu-raster', 'application/x-cmu-raster', 'image/x-cmu-raster']], + ['rast', 'image/cmu-raster'], + ['rcprofile', 'application/vnd.ipunplugged.rcprofile'], + ['rdf', 'application/rdf+xml'], + ['rdz', 'application/vnd.data-vision.rdz'], + ['rep', 'application/vnd.businessobjects'], + ['res', 'application/x-dtbresource+xml'], + ['rexx', 'text/x-script.rexx'], + ['rf', 'image/vnd.rn-realflash'], + ['rgb', 'image/x-rgb'], + ['rif', 'application/reginfo+xml'], + ['rip', 'audio/vnd.rip'], + ['rl', 'application/resource-lists+xml'], + ['rlc', 'image/vnd.fujixerox.edmics-rlc'], + ['rld', 'application/resource-lists-diff+xml'], + ['rm', ['application/vnd.rn-realmedia', 'audio/x-pn-realaudio']], + ['rmi', 'audio/mid'], + ['rmm', 'audio/x-pn-realaudio'], + ['rmp', ['audio/x-pn-realaudio-plugin', 'audio/x-pn-realaudio']], + ['rms', 'application/vnd.jcp.javame.midlet-rms'], + ['rnc', 'application/relax-ng-compact-syntax'], + ['rng', ['application/ringing-tones', 'application/vnd.nokia.ringing-tone']], + ['rnx', 'application/vnd.rn-realplayer'], + ['roff', 'application/x-troff'], + ['rp', 'image/vnd.rn-realpix'], + ['rp9', 'application/vnd.cloanto.rp9'], + ['rpm', 'audio/x-pn-realaudio-plugin'], + ['rpss', 'application/vnd.nokia.radio-presets'], + ['rpst', 'application/vnd.nokia.radio-preset'], + ['rq', 'application/sparql-query'], + ['rs', 'application/rls-services+xml'], + ['rsd', 'application/rsd+xml'], + ['rt', ['text/richtext', 'text/vnd.rn-realtext']], + ['rtf', ['application/rtf', 'text/richtext', 'application/x-rtf']], + ['rtx', ['text/richtext', 'application/rtf']], + ['rv', 'video/vnd.rn-realvideo'], + ['s', 'text/x-asm'], + ['s3m', 'audio/s3m'], + ['saf', 'application/vnd.yamaha.smaf-audio'], + ['saveme', 'application/octet-stream'], + ['sbk', 'application/x-tbook'], + ['sbml', 'application/sbml+xml'], + ['sc', 'application/vnd.ibm.secure-container'], + ['scd', 'application/x-msschedule'], + ['scm', ['application/vnd.lotus-screencam', 'video/x-scm', 'text/x-script.guile', 'application/x-lotusscreencam', 'text/x-script.scheme']], + ['scq', 'application/scvp-cv-request'], + ['scs', 'application/scvp-cv-response'], + ['sct', 'text/scriptlet'], + ['scurl', 'text/vnd.curl.scurl'], + ['sda', 'application/vnd.stardivision.draw'], + ['sdc', 'application/vnd.stardivision.calc'], + ['sdd', 'application/vnd.stardivision.impress'], + ['sdkm', 'application/vnd.solent.sdkm+xml'], + ['sdml', 'text/plain'], + ['sdp', ['application/sdp', 'application/x-sdp']], + ['sdr', 'application/sounder'], + ['sdw', 'application/vnd.stardivision.writer'], + ['sea', ['application/sea', 'application/x-sea']], + ['see', 'application/vnd.seemail'], + ['seed', 'application/vnd.fdsn.seed'], + ['sema', 'application/vnd.sema'], + ['semd', 'application/vnd.semd'], + ['semf', 'application/vnd.semf'], + ['ser', 'application/java-serialized-object'], + ['set', 'application/set'], + ['setpay', 'application/set-payment-initiation'], + ['setreg', 'application/set-registration-initiation'], + ['sfd-hdstx', 'application/vnd.hydrostatix.sof-data'], + ['sfs', 'application/vnd.spotfire.sfs'], + ['sgl', 'application/vnd.stardivision.writer-global'], + ['sgm', ['text/sgml', 'text/x-sgml']], + ['sgml', ['text/sgml', 'text/x-sgml']], + ['sh', ['application/x-shar', 'application/x-bsh', 'application/x-sh', 'text/x-script.sh']], + ['shar', ['application/x-bsh', 'application/x-shar']], + ['shf', 'application/shf+xml'], + ['shtml', ['text/html', 'text/x-server-parsed-html']], + ['sid', 'audio/x-psid'], + ['sis', 'application/vnd.symbian.install'], + ['sit', ['application/x-stuffit', 'application/x-sit']], + ['sitx', 'application/x-stuffitx'], + ['skd', 'application/x-koan'], + ['skm', 'application/x-koan'], + ['skp', ['application/vnd.koan', 'application/x-koan']], + ['skt', 'application/x-koan'], + ['sl', 'application/x-seelogo'], + ['sldm', 'application/vnd.ms-powerpoint.slide.macroenabled.12'], + ['sldx', 'application/vnd.openxmlformats-officedocument.presentationml.slide'], + ['slt', 'application/vnd.epson.salt'], + ['sm', 'application/vnd.stepmania.stepchart'], + ['smf', 'application/vnd.stardivision.math'], + ['smi', ['application/smil', 'application/smil+xml']], + ['smil', 'application/smil'], + ['snd', ['audio/basic', 'audio/x-adpcm']], + ['snf', 'application/x-font-snf'], + ['sol', 'application/solids'], + ['spc', ['text/x-speech', 'application/x-pkcs7-certificates']], + ['spf', 'application/vnd.yamaha.smaf-phrase'], + ['spl', ['application/futuresplash', 'application/x-futuresplash']], + ['spot', 'text/vnd.in3d.spot'], + ['spp', 'application/scvp-vp-response'], + ['spq', 'application/scvp-vp-request'], + ['spr', 'application/x-sprite'], + ['sprite', 'application/x-sprite'], + ['src', 'application/x-wais-source'], + ['sru', 'application/sru+xml'], + ['srx', 'application/sparql-results+xml'], + ['sse', 'application/vnd.kodak-descriptor'], + ['ssf', 'application/vnd.epson.ssf'], + ['ssi', 'text/x-server-parsed-html'], + ['ssm', 'application/streamingmedia'], + ['ssml', 'application/ssml+xml'], + ['sst', ['application/vnd.ms-pkicertstore', 'application/vnd.ms-pki.certstore']], + ['st', 'application/vnd.sailingtracker.track'], + ['stc', 'application/vnd.sun.xml.calc.template'], + ['std', 'application/vnd.sun.xml.draw.template'], + ['step', 'application/step'], + ['stf', 'application/vnd.wt.stf'], + ['sti', 'application/vnd.sun.xml.impress.template'], + ['stk', 'application/hyperstudio'], + ['stl', ['application/vnd.ms-pkistl', 'application/sla', 'application/vnd.ms-pki.stl', 'application/x-navistyle']], + ['stm', 'text/html'], + ['stp', 'application/step'], + ['str', 'application/vnd.pg.format'], + ['stw', 'application/vnd.sun.xml.writer.template'], + ['sub', 'image/vnd.dvb.subtitle'], + ['sus', 'application/vnd.sus-calendar'], + ['sv4cpio', 'application/x-sv4cpio'], + ['sv4crc', 'application/x-sv4crc'], + ['svc', 'application/vnd.dvb.service'], + ['svd', 'application/vnd.svd'], + ['svf', ['image/vnd.dwg', 'image/x-dwg']], + ['svg', 'image/svg+xml'], + ['svr', ['x-world/x-svr', 'application/x-world']], + ['swf', 'application/x-shockwave-flash'], + ['swi', 'application/vnd.aristanetworks.swi'], + ['sxc', 'application/vnd.sun.xml.calc'], + ['sxd', 'application/vnd.sun.xml.draw'], + ['sxg', 'application/vnd.sun.xml.writer.global'], + ['sxi', 'application/vnd.sun.xml.impress'], + ['sxm', 'application/vnd.sun.xml.math'], + ['sxw', 'application/vnd.sun.xml.writer'], + ['t', ['text/troff', 'application/x-troff']], + ['talk', 'text/x-speech'], + ['tao', 'application/vnd.tao.intent-module-archive'], + ['tar', 'application/x-tar'], + ['tbk', ['application/toolbook', 'application/x-tbook']], + ['tcap', 'application/vnd.3gpp2.tcap'], + ['tcl', ['text/x-script.tcl', 'application/x-tcl']], + ['tcsh', 'text/x-script.tcsh'], + ['teacher', 'application/vnd.smart.teacher'], + ['tei', 'application/tei+xml'], + ['tex', 'application/x-tex'], + ['texi', 'application/x-texinfo'], + ['texinfo', 'application/x-texinfo'], + ['text', ['application/plain', 'text/plain']], + ['tfi', 'application/thraud+xml'], + ['tfm', 'application/x-tex-tfm'], + ['tgz', ['application/gnutar', 'application/x-compressed']], + ['thmx', 'application/vnd.ms-officetheme'], + ['tif', ['image/tiff', 'image/x-tiff']], + ['tiff', ['image/tiff', 'image/x-tiff']], + ['tmo', 'application/vnd.tmobile-livetv'], + ['torrent', 'application/x-bittorrent'], + ['tpl', 'application/vnd.groove-tool-template'], + ['tpt', 'application/vnd.trid.tpt'], + ['tr', 'application/x-troff'], + ['tra', 'application/vnd.trueapp'], + ['trm', 'application/x-msterminal'], + ['tsd', 'application/timestamped-data'], + ['tsi', 'audio/tsp-audio'], + ['tsp', ['application/dsptype', 'audio/tsplayer']], + ['tsv', 'text/tab-separated-values'], + ['ttf', 'application/x-font-ttf'], + ['ttl', 'text/turtle'], + ['turbot', 'image/florian'], + ['twd', 'application/vnd.simtech-mindmapper'], + ['txd', 'application/vnd.genomatix.tuxedo'], + ['txf', 'application/vnd.mobius.txf'], + ['txt', 'text/plain'], + ['ufd', 'application/vnd.ufdl'], + ['uil', 'text/x-uil'], + ['uls', 'text/iuls'], + ['umj', 'application/vnd.umajin'], + ['uni', 'text/uri-list'], + ['unis', 'text/uri-list'], + ['unityweb', 'application/vnd.unity'], + ['unv', 'application/i-deas'], + ['uoml', 'application/vnd.uoml+xml'], + ['uri', 'text/uri-list'], + ['uris', 'text/uri-list'], + ['ustar', ['application/x-ustar', 'multipart/x-ustar']], + ['utz', 'application/vnd.uiq.theme'], + ['uu', ['application/octet-stream', 'text/x-uuencode']], + ['uue', 'text/x-uuencode'], + ['uva', 'audio/vnd.dece.audio'], + ['uvh', 'video/vnd.dece.hd'], + ['uvi', 'image/vnd.dece.graphic'], + ['uvm', 'video/vnd.dece.mobile'], + ['uvp', 'video/vnd.dece.pd'], + ['uvs', 'video/vnd.dece.sd'], + ['uvu', 'video/vnd.uvvu.mp4'], + ['uvv', 'video/vnd.dece.video'], + ['vcd', 'application/x-cdlink'], + ['vcf', 'text/x-vcard'], + ['vcg', 'application/vnd.groove-vcard'], + ['vcs', 'text/x-vcalendar'], + ['vcx', 'application/vnd.vcx'], + ['vda', 'application/vda'], + ['vdo', 'video/vdo'], + ['vew', 'application/groupwise'], + ['vis', 'application/vnd.visionary'], + ['viv', ['video/vivo', 'video/vnd.vivo']], + ['vivo', ['video/vivo', 'video/vnd.vivo']], + ['vmd', 'application/vocaltec-media-desc'], + ['vmf', 'application/vocaltec-media-file'], + ['voc', ['audio/voc', 'audio/x-voc']], + ['vos', 'video/vosaic'], + ['vox', 'audio/voxware'], + ['vqe', 'audio/x-twinvq-plugin'], + ['vqf', 'audio/x-twinvq'], + ['vql', 'audio/x-twinvq-plugin'], + ['vrml', ['model/vrml', 'x-world/x-vrml', 'application/x-vrml']], + ['vrt', 'x-world/x-vrt'], + ['vsd', ['application/vnd.visio', 'application/x-visio']], + ['vsf', 'application/vnd.vsf'], + ['vst', 'application/x-visio'], + ['vsw', 'application/x-visio'], + ['vtu', 'model/vnd.vtu'], + ['vxml', 'application/voicexml+xml'], + ['w60', 'application/wordperfect6.0'], + ['w61', 'application/wordperfect6.1'], + ['w6w', 'application/msword'], + ['wad', 'application/x-doom'], + ['wav', ['audio/wav', 'audio/x-wav']], + ['wax', 'audio/x-ms-wax'], + ['wb1', 'application/x-qpro'], + ['wbmp', 'image/vnd.wap.wbmp'], + ['wbs', 'application/vnd.criticaltools.wbs+xml'], + ['wbxml', 'application/vnd.wap.wbxml'], + ['wcm', 'application/vnd.ms-works'], + ['wdb', 'application/vnd.ms-works'], + ['web', 'application/vnd.xara'], + ['weba', 'audio/webm'], + ['webm', 'video/webm'], + ['webp', 'image/webp'], + ['wg', 'application/vnd.pmi.widget'], + ['wgt', 'application/widget'], + ['wiz', 'application/msword'], + ['wk1', 'application/x-123'], + ['wks', 'application/vnd.ms-works'], + ['wm', 'video/x-ms-wm'], + ['wma', 'audio/x-ms-wma'], + ['wmd', 'application/x-ms-wmd'], + ['wmf', ['windows/metafile', 'application/x-msmetafile']], + ['wml', 'text/vnd.wap.wml'], + ['wmlc', 'application/vnd.wap.wmlc'], + ['wmls', 'text/vnd.wap.wmlscript'], + ['wmlsc', 'application/vnd.wap.wmlscriptc'], + ['wmv', 'video/x-ms-wmv'], + ['wmx', 'video/x-ms-wmx'], + ['wmz', 'application/x-ms-wmz'], + ['woff', 'application/x-font-woff'], + ['word', 'application/msword'], + ['wp', 'application/wordperfect'], + ['wp5', ['application/wordperfect', 'application/wordperfect6.0']], + ['wp6', 'application/wordperfect'], + ['wpd', ['application/wordperfect', 'application/vnd.wordperfect', 'application/x-wpwin']], + ['wpl', 'application/vnd.ms-wpl'], + ['wps', 'application/vnd.ms-works'], + ['wq1', 'application/x-lotus'], + ['wqd', 'application/vnd.wqd'], + ['wri', ['application/mswrite', 'application/x-wri', 'application/x-mswrite']], + ['wrl', ['model/vrml', 'x-world/x-vrml', 'application/x-world']], + ['wrz', ['model/vrml', 'x-world/x-vrml']], + ['wsc', 'text/scriplet'], + ['wsdl', 'application/wsdl+xml'], + ['wspolicy', 'application/wspolicy+xml'], + ['wsrc', 'application/x-wais-source'], + ['wtb', 'application/vnd.webturbo'], + ['wtk', 'application/x-wintalk'], + ['wvx', 'video/x-ms-wvx'], + ['x-png', 'image/png'], + ['x3d', 'application/vnd.hzn-3d-crossword'], + ['xaf', 'x-world/x-vrml'], + ['xap', 'application/x-silverlight-app'], + ['xar', 'application/vnd.xara'], + ['xbap', 'application/x-ms-xbap'], + ['xbd', 'application/vnd.fujixerox.docuworks.binder'], + ['xbm', ['image/xbm', 'image/x-xbm', 'image/x-xbitmap']], + ['xdf', 'application/xcap-diff+xml'], + ['xdm', 'application/vnd.syncml.dm+xml'], + ['xdp', 'application/vnd.adobe.xdp+xml'], + ['xdr', 'video/x-amt-demorun'], + ['xdssc', 'application/dssc+xml'], + ['xdw', 'application/vnd.fujixerox.docuworks'], + ['xenc', 'application/xenc+xml'], + ['xer', 'application/patch-ops-error+xml'], + ['xfdf', 'application/vnd.adobe.xfdf'], + ['xfdl', 'application/vnd.xfdl'], + ['xgz', 'xgl/drawing'], + ['xhtml', 'application/xhtml+xml'], + ['xif', 'image/vnd.xiff'], + ['xl', 'application/excel'], + ['xla', ['application/vnd.ms-excel', 'application/excel', 'application/x-msexcel', 'application/x-excel']], + ['xlam', 'application/vnd.ms-excel.addin.macroenabled.12'], + ['xlb', ['application/excel', 'application/vnd.ms-excel', 'application/x-excel']], + ['xlc', ['application/vnd.ms-excel', 'application/excel', 'application/x-excel']], + ['xld', ['application/excel', 'application/x-excel']], + ['xlk', ['application/excel', 'application/x-excel']], + ['xll', ['application/excel', 'application/vnd.ms-excel', 'application/x-excel']], + ['xlm', ['application/vnd.ms-excel', 'application/excel', 'application/x-excel']], + ['xls', ['application/vnd.ms-excel', 'application/excel', 'application/x-msexcel', 'application/x-excel']], + ['xlsb', 'application/vnd.ms-excel.sheet.binary.macroenabled.12'], + ['xlsm', 'application/vnd.ms-excel.sheet.macroenabled.12'], + ['xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'], + ['xlt', ['application/vnd.ms-excel', 'application/excel', 'application/x-excel']], + ['xltm', 'application/vnd.ms-excel.template.macroenabled.12'], + ['xltx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.template'], + ['xlv', ['application/excel', 'application/x-excel']], + ['xlw', ['application/vnd.ms-excel', 'application/excel', 'application/x-msexcel', 'application/x-excel']], + ['xm', 'audio/xm'], + ['xml', ['application/xml', 'text/xml', 'application/atom+xml', 'application/rss+xml']], + ['xmz', 'xgl/movie'], + ['xo', 'application/vnd.olpc-sugar'], + ['xof', 'x-world/x-vrml'], + ['xop', 'application/xop+xml'], + ['xpi', 'application/x-xpinstall'], + ['xpix', 'application/x-vnd.ls-xpix'], + ['xpm', ['image/xpm', 'image/x-xpixmap']], + ['xpr', 'application/vnd.is-xpr'], + ['xps', 'application/vnd.ms-xpsdocument'], + ['xpw', 'application/vnd.intercon.formnet'], + ['xslt', 'application/xslt+xml'], + ['xsm', 'application/vnd.syncml+xml'], + ['xspf', 'application/xspf+xml'], + ['xsr', 'video/x-amt-showrun'], + ['xul', 'application/vnd.mozilla.xul+xml'], + ['xwd', ['image/x-xwd', 'image/x-xwindowdump']], + ['xyz', ['chemical/x-xyz', 'chemical/x-pdb']], + ['yang', 'application/yang'], + ['yin', 'application/yin+xml'], + ['z', ['application/x-compressed', 'application/x-compress']], + ['zaz', 'application/vnd.zzazz.deck+xml'], + ['zip', ['application/zip', 'multipart/x-zip', 'application/x-zip-compressed', 'application/x-compressed']], + ['zir', 'application/vnd.zul'], + ['zmm', 'application/vnd.handheld-entertainment+xml'], + ['zoo', 'application/octet-stream'], + ['zsh', 'text/x-script.zsh'] +]); + +module.exports = { + detectMimeType(filename) { + if (!filename) { + return defaultMimeType; + } + + let parsed = path.parse(filename); + let extension = (parsed.ext.substr(1) || parsed.name || '').split('?').shift().trim().toLowerCase(); + let value = defaultMimeType; + + if (extensions.has(extension)) { + value = extensions.get(extension); + } + + if (Array.isArray(value)) { + return value[0]; + } + return value; + }, + + detectExtension(mimeType) { + if (!mimeType) { + return defaultExtension; + } + let parts = (mimeType || '').toLowerCase().trim().split('/'); + let rootType = parts.shift().trim(); + let subType = parts.join('/').trim(); + + if (mimeTypes.has(rootType + '/' + subType)) { + let value = mimeTypes.get(rootType + '/' + subType); + if (Array.isArray(value)) { + return value[0]; + } + return value; + } + + switch (rootType) { + case 'text': + return 'txt'; + default: + return 'bin'; + } + } +}; diff --git a/system/login/node_modules/nodemailer/lib/mime-node/index.js b/system/login/node_modules/nodemailer/lib/mime-node/index.js new file mode 100644 index 0000000..21bd422 --- /dev/null +++ b/system/login/node_modules/nodemailer/lib/mime-node/index.js @@ -0,0 +1,1305 @@ +/* eslint no-undefined: 0, prefer-spread: 0, no-control-regex: 0 */ + +'use strict'; + +const crypto = require('crypto'); +const fs = require('fs'); +const punycode = require('punycode'); +const PassThrough = require('stream').PassThrough; +const shared = require('../shared'); + +const mimeFuncs = require('../mime-funcs'); +const qp = require('../qp'); +const base64 = require('../base64'); +const addressparser = require('../addressparser'); +const nmfetch = require('../fetch'); +const LastNewline = require('./last-newline'); + +const LeWindows = require('./le-windows'); +const LeUnix = require('./le-unix'); + +/** + * Creates a new mime tree node. Assumes 'multipart/*' as the content type + * if it is a branch, anything else counts as leaf. If rootNode is missing from + * the options, assumes this is the root. + * + * @param {String} contentType Define the content type for the node. Can be left blank for attachments (derived from filename) + * @param {Object} [options] optional options + * @param {Object} [options.rootNode] root node for this tree + * @param {Object} [options.parentNode] immediate parent for this node + * @param {Object} [options.filename] filename for an attachment node + * @param {String} [options.baseBoundary] shared part of the unique multipart boundary + * @param {Boolean} [options.keepBcc] If true, do not exclude Bcc from the generated headers + * @param {Function} [options.normalizeHeaderKey] method to normalize header keys for custom caseing + * @param {String} [options.textEncoding] either 'Q' (the default) or 'B' + */ +class MimeNode { + constructor(contentType, options) { + this.nodeCounter = 0; + + options = options || {}; + + /** + * shared part of the unique multipart boundary + */ + this.baseBoundary = options.baseBoundary || crypto.randomBytes(8).toString('hex'); + this.boundaryPrefix = options.boundaryPrefix || '--_NmP'; + + this.disableFileAccess = !!options.disableFileAccess; + this.disableUrlAccess = !!options.disableUrlAccess; + + this.normalizeHeaderKey = options.normalizeHeaderKey; + + /** + * If date headers is missing and current node is the root, this value is used instead + */ + this.date = new Date(); + + /** + * Root node for current mime tree + */ + this.rootNode = options.rootNode || this; + + /** + * If true include Bcc in generated headers (if available) + */ + this.keepBcc = !!options.keepBcc; + + /** + * If filename is specified but contentType is not (probably an attachment) + * detect the content type from filename extension + */ + if (options.filename) { + /** + * Filename for this node. Useful with attachments + */ + this.filename = options.filename; + if (!contentType) { + contentType = mimeFuncs.detectMimeType(this.filename.split('.').pop()); + } + } + + /** + * Indicates which encoding should be used for header strings: "Q" or "B" + */ + this.textEncoding = (options.textEncoding || '').toString().trim().charAt(0).toUpperCase(); + + /** + * Immediate parent for this node (or undefined if not set) + */ + this.parentNode = options.parentNode; + + /** + * Hostname for default message-id values + */ + this.hostname = options.hostname; + + /** + * If set to 'win' then uses \r\n, if 'linux' then \n. If not set (or `raw` is used) then newlines are kept as is. + */ + this.newline = options.newline; + + /** + * An array for possible child nodes + */ + this.childNodes = []; + + /** + * Used for generating unique boundaries (prepended to the shared base) + */ + this._nodeId = ++this.rootNode.nodeCounter; + + /** + * A list of header values for this node in the form of [{key:'', value:''}] + */ + this._headers = []; + + /** + * True if the content only uses ASCII printable characters + * @type {Boolean} + */ + this._isPlainText = false; + + /** + * True if the content is plain text but has longer lines than allowed + * @type {Boolean} + */ + this._hasLongLines = false; + + /** + * If set, use instead this value for envelopes instead of generating one + * @type {Boolean} + */ + this._envelope = false; + + /** + * If set then use this value as the stream content instead of building it + * @type {String|Buffer|Stream} + */ + this._raw = false; + + /** + * Additional transform streams that the message will be piped before + * exposing by createReadStream + * @type {Array} + */ + this._transforms = []; + + /** + * Additional process functions that the message will be piped through before + * exposing by createReadStream. These functions are run after transforms + * @type {Array} + */ + this._processFuncs = []; + + /** + * If content type is set (or derived from the filename) add it to headers + */ + if (contentType) { + this.setHeader('Content-Type', contentType); + } + } + + /////// PUBLIC METHODS + + /** + * Creates and appends a child node.Arguments provided are passed to MimeNode constructor + * + * @param {String} [contentType] Optional content type + * @param {Object} [options] Optional options object + * @return {Object} Created node object + */ + createChild(contentType, options) { + if (!options && typeof contentType === 'object') { + options = contentType; + contentType = undefined; + } + let node = new MimeNode(contentType, options); + this.appendChild(node); + return node; + } + + /** + * Appends an existing node to the mime tree. Removes the node from an existing + * tree if needed + * + * @param {Object} childNode node to be appended + * @return {Object} Appended node object + */ + appendChild(childNode) { + if (childNode.rootNode !== this.rootNode) { + childNode.rootNode = this.rootNode; + childNode._nodeId = ++this.rootNode.nodeCounter; + } + + childNode.parentNode = this; + + this.childNodes.push(childNode); + return childNode; + } + + /** + * Replaces current node with another node + * + * @param {Object} node Replacement node + * @return {Object} Replacement node + */ + replace(node) { + if (node === this) { + return this; + } + + this.parentNode.childNodes.forEach((childNode, i) => { + if (childNode === this) { + node.rootNode = this.rootNode; + node.parentNode = this.parentNode; + node._nodeId = this._nodeId; + + this.rootNode = this; + this.parentNode = undefined; + + node.parentNode.childNodes[i] = node; + } + }); + + return node; + } + + /** + * Removes current node from the mime tree + * + * @return {Object} removed node + */ + remove() { + if (!this.parentNode) { + return this; + } + + for (let i = this.parentNode.childNodes.length - 1; i >= 0; i--) { + if (this.parentNode.childNodes[i] === this) { + this.parentNode.childNodes.splice(i, 1); + this.parentNode = undefined; + this.rootNode = this; + return this; + } + } + } + + /** + * Sets a header value. If the value for selected key exists, it is overwritten. + * You can set multiple values as well by using [{key:'', value:''}] or + * {key: 'value'} as the first argument. + * + * @param {String|Array|Object} key Header key or a list of key value pairs + * @param {String} value Header value + * @return {Object} current node + */ + setHeader(key, value) { + let added = false, + headerValue; + + // Allow setting multiple headers at once + if (!value && key && typeof key === 'object') { + // allow {key:'content-type', value: 'text/plain'} + if (key.key && 'value' in key) { + this.setHeader(key.key, key.value); + } else if (Array.isArray(key)) { + // allow [{key:'content-type', value: 'text/plain'}] + key.forEach(i => { + this.setHeader(i.key, i.value); + }); + } else { + // allow {'content-type': 'text/plain'} + Object.keys(key).forEach(i => { + this.setHeader(i, key[i]); + }); + } + return this; + } + + key = this._normalizeHeaderKey(key); + + headerValue = { + key, + value + }; + + // Check if the value exists and overwrite + for (let i = 0, len = this._headers.length; i < len; i++) { + if (this._headers[i].key === key) { + if (!added) { + // replace the first match + this._headers[i] = headerValue; + added = true; + } else { + // remove following matches + this._headers.splice(i, 1); + i--; + len--; + } + } + } + + // match not found, append the value + if (!added) { + this._headers.push(headerValue); + } + + return this; + } + + /** + * Adds a header value. If the value for selected key exists, the value is appended + * as a new field and old one is not touched. + * You can set multiple values as well by using [{key:'', value:''}] or + * {key: 'value'} as the first argument. + * + * @param {String|Array|Object} key Header key or a list of key value pairs + * @param {String} value Header value + * @return {Object} current node + */ + addHeader(key, value) { + // Allow setting multiple headers at once + if (!value && key && typeof key === 'object') { + // allow {key:'content-type', value: 'text/plain'} + if (key.key && key.value) { + this.addHeader(key.key, key.value); + } else if (Array.isArray(key)) { + // allow [{key:'content-type', value: 'text/plain'}] + key.forEach(i => { + this.addHeader(i.key, i.value); + }); + } else { + // allow {'content-type': 'text/plain'} + Object.keys(key).forEach(i => { + this.addHeader(i, key[i]); + }); + } + return this; + } else if (Array.isArray(value)) { + value.forEach(val => { + this.addHeader(key, val); + }); + return this; + } + + this._headers.push({ + key: this._normalizeHeaderKey(key), + value + }); + + return this; + } + + /** + * Retrieves the first mathcing value of a selected key + * + * @param {String} key Key to search for + * @retun {String} Value for the key + */ + getHeader(key) { + key = this._normalizeHeaderKey(key); + for (let i = 0, len = this._headers.length; i < len; i++) { + if (this._headers[i].key === key) { + return this._headers[i].value; + } + } + } + + /** + * Sets body content for current node. If the value is a string, charset is added automatically + * to Content-Type (if it is text/*). If the value is a Buffer, you need to specify + * the charset yourself + * + * @param (String|Buffer) content Body content + * @return {Object} current node + */ + setContent(content) { + this.content = content; + if (typeof this.content.pipe === 'function') { + // pre-stream handler. might be triggered if a stream is set as content + // and 'error' fires before anything is done with this stream + this._contentErrorHandler = err => { + this.content.removeListener('error', this._contentErrorHandler); + this.content = err; + }; + this.content.once('error', this._contentErrorHandler); + } else if (typeof this.content === 'string') { + this._isPlainText = mimeFuncs.isPlainText(this.content); + if (this._isPlainText && mimeFuncs.hasLongerLines(this.content, 76)) { + // If there are lines longer than 76 symbols/bytes do not use 7bit + this._hasLongLines = true; + } + } + return this; + } + + build(callback) { + let promise; + + if (!callback) { + promise = new Promise((resolve, reject) => { + callback = shared.callbackPromise(resolve, reject); + }); + } + + let stream = this.createReadStream(); + let buf = []; + let buflen = 0; + let returned = false; + + stream.on('readable', () => { + let chunk; + + while ((chunk = stream.read()) !== null) { + buf.push(chunk); + buflen += chunk.length; + } + }); + + stream.once('error', err => { + if (returned) { + return; + } + returned = true; + + return callback(err); + }); + + stream.once('end', chunk => { + if (returned) { + return; + } + returned = true; + + if (chunk && chunk.length) { + buf.push(chunk); + buflen += chunk.length; + } + return callback(null, Buffer.concat(buf, buflen)); + }); + + return promise; + } + + getTransferEncoding() { + let transferEncoding = false; + let contentType = (this.getHeader('Content-Type') || '').toString().toLowerCase().trim(); + + if (this.content) { + transferEncoding = (this.getHeader('Content-Transfer-Encoding') || '').toString().toLowerCase().trim(); + if (!transferEncoding || !['base64', 'quoted-printable'].includes(transferEncoding)) { + if (/^text\//i.test(contentType)) { + // If there are no special symbols, no need to modify the text + if (this._isPlainText && !this._hasLongLines) { + transferEncoding = '7bit'; + } else if (typeof this.content === 'string' || this.content instanceof Buffer) { + // detect preferred encoding for string value + transferEncoding = this._getTextEncoding(this.content) === 'Q' ? 'quoted-printable' : 'base64'; + } else { + // we can not check content for a stream, so either use preferred encoding or fallback to QP + transferEncoding = this.textEncoding === 'B' ? 'base64' : 'quoted-printable'; + } + } else if (!/^(multipart|message)\//i.test(contentType)) { + transferEncoding = transferEncoding || 'base64'; + } + } + } + return transferEncoding; + } + + /** + * Builds the header block for the mime node. Append \r\n\r\n before writing the content + * + * @returns {String} Headers + */ + buildHeaders() { + let transferEncoding = this.getTransferEncoding(); + let headers = []; + + if (transferEncoding) { + this.setHeader('Content-Transfer-Encoding', transferEncoding); + } + + if (this.filename && !this.getHeader('Content-Disposition')) { + this.setHeader('Content-Disposition', 'attachment'); + } + + // Ensure mandatory header fields + if (this.rootNode === this) { + if (!this.getHeader('Date')) { + this.setHeader('Date', this.date.toUTCString().replace(/GMT/, '+0000')); + } + + // ensure that Message-Id is present + this.messageId(); + + if (!this.getHeader('MIME-Version')) { + this.setHeader('MIME-Version', '1.0'); + } + } + + this._headers.forEach(header => { + let key = header.key; + let value = header.value; + let structured; + let param; + let options = {}; + let formattedHeaders = ['From', 'Sender', 'To', 'Cc', 'Bcc', 'Reply-To', 'Date', 'References']; + + if (value && typeof value === 'object' && !formattedHeaders.includes(key)) { + Object.keys(value).forEach(key => { + if (key !== 'value') { + options[key] = value[key]; + } + }); + value = (value.value || '').toString(); + if (!value.trim()) { + return; + } + } + + if (options.prepared) { + // header value is + if (options.foldLines) { + headers.push(mimeFuncs.foldLines(key + ': ' + value)); + } else { + headers.push(key + ': ' + value); + } + return; + } + + switch (header.key) { + case 'Content-Disposition': + structured = mimeFuncs.parseHeaderValue(value); + if (this.filename) { + structured.params.filename = this.filename; + } + value = mimeFuncs.buildHeaderValue(structured); + break; + + case 'Content-Type': + structured = mimeFuncs.parseHeaderValue(value); + + this._handleContentType(structured); + + if (structured.value.match(/^text\/plain\b/) && typeof this.content === 'string' && /[\u0080-\uFFFF]/.test(this.content)) { + structured.params.charset = 'utf-8'; + } + + value = mimeFuncs.buildHeaderValue(structured); + + if (this.filename) { + // add support for non-compliant clients like QQ webmail + // we can't build the value with buildHeaderValue as the value is non standard and + // would be converted to parameter continuation encoding that we do not want + param = this._encodeWords(this.filename); + + if (param !== this.filename || /[\s'"\\;:/=(),<>@[\]?]|^-/.test(param)) { + // include value in quotes if needed + param = '"' + param + '"'; + } + value += '; name=' + param; + } + break; + + case 'Bcc': + if (!this.keepBcc) { + // skip BCC values + return; + } + break; + } + + value = this._encodeHeaderValue(key, value); + + // skip empty lines + if (!(value || '').toString().trim()) { + return; + } + + if (typeof this.normalizeHeaderKey === 'function') { + let normalized = this.normalizeHeaderKey(key, value); + if (normalized && typeof normalized === 'string' && normalized.length) { + key = normalized; + } + } + + headers.push(mimeFuncs.foldLines(key + ': ' + value, 76)); + }); + + return headers.join('\r\n'); + } + + /** + * Streams the rfc2822 message from the current node. If this is a root node, + * mandatory header fields are set if missing (Date, Message-Id, MIME-Version) + * + * @return {String} Compiled message + */ + createReadStream(options) { + options = options || {}; + + let stream = new PassThrough(options); + let outputStream = stream; + let transform; + + this.stream(stream, options, err => { + if (err) { + outputStream.emit('error', err); + return; + } + stream.end(); + }); + + for (let i = 0, len = this._transforms.length; i < len; i++) { + transform = typeof this._transforms[i] === 'function' ? this._transforms[i]() : this._transforms[i]; + outputStream.once('error', err => { + transform.emit('error', err); + }); + outputStream = outputStream.pipe(transform); + } + + // ensure terminating newline after possible user transforms + transform = new LastNewline(); + outputStream.once('error', err => { + transform.emit('error', err); + }); + outputStream = outputStream.pipe(transform); + + // dkim and stuff + for (let i = 0, len = this._processFuncs.length; i < len; i++) { + transform = this._processFuncs[i]; + outputStream = transform(outputStream); + } + + if (this.newline) { + const winbreak = ['win', 'windows', 'dos', '\r\n'].includes(this.newline.toString().toLowerCase()); + const newlineTransform = winbreak ? new LeWindows() : new LeUnix(); + + const stream = outputStream.pipe(newlineTransform); + outputStream.on('error', err => stream.emit('error', err)); + return stream; + } + + return outputStream; + } + + /** + * Appends a transform stream object to the transforms list. Final output + * is passed through this stream before exposing + * + * @param {Object} transform Read-Write stream + */ + transform(transform) { + this._transforms.push(transform); + } + + /** + * Appends a post process function. The functon is run after transforms and + * uses the following syntax + * + * processFunc(input) -> outputStream + * + * @param {Object} processFunc Read-Write stream + */ + processFunc(processFunc) { + this._processFuncs.push(processFunc); + } + + stream(outputStream, options, done) { + let transferEncoding = this.getTransferEncoding(); + let contentStream; + let localStream; + + // protect actual callback against multiple triggering + let returned = false; + let callback = err => { + if (returned) { + return; + } + returned = true; + done(err); + }; + + // for multipart nodes, push child nodes + // for content nodes end the stream + let finalize = () => { + let childId = 0; + let processChildNode = () => { + if (childId >= this.childNodes.length) { + outputStream.write('\r\n--' + this.boundary + '--\r\n'); + return callback(); + } + let child = this.childNodes[childId++]; + outputStream.write((childId > 1 ? '\r\n' : '') + '--' + this.boundary + '\r\n'); + child.stream(outputStream, options, err => { + if (err) { + return callback(err); + } + setImmediate(processChildNode); + }); + }; + + if (this.multipart) { + setImmediate(processChildNode); + } else { + return callback(); + } + }; + + // pushes node content + let sendContent = () => { + if (this.content) { + if (Object.prototype.toString.call(this.content) === '[object Error]') { + // content is already errored + return callback(this.content); + } + + if (typeof this.content.pipe === 'function') { + this.content.removeListener('error', this._contentErrorHandler); + this._contentErrorHandler = err => callback(err); + this.content.once('error', this._contentErrorHandler); + } + + let createStream = () => { + if (['quoted-printable', 'base64'].includes(transferEncoding)) { + contentStream = new (transferEncoding === 'base64' ? base64 : qp).Encoder(options); + + contentStream.pipe(outputStream, { + end: false + }); + contentStream.once('end', finalize); + contentStream.once('error', err => callback(err)); + + localStream = this._getStream(this.content); + localStream.pipe(contentStream); + } else { + // anything that is not QP or Base54 passes as-is + localStream = this._getStream(this.content); + localStream.pipe(outputStream, { + end: false + }); + localStream.once('end', finalize); + } + + localStream.once('error', err => callback(err)); + }; + + if (this.content._resolve) { + let chunks = []; + let chunklen = 0; + let returned = false; + let sourceStream = this._getStream(this.content); + sourceStream.on('error', err => { + if (returned) { + return; + } + returned = true; + callback(err); + }); + sourceStream.on('readable', () => { + let chunk; + while ((chunk = sourceStream.read()) !== null) { + chunks.push(chunk); + chunklen += chunk.length; + } + }); + sourceStream.on('end', () => { + if (returned) { + return; + } + returned = true; + this.content._resolve = false; + this.content._resolvedValue = Buffer.concat(chunks, chunklen); + setImmediate(createStream); + }); + } else { + setImmediate(createStream); + } + return; + } else { + return setImmediate(finalize); + } + }; + + if (this._raw) { + setImmediate(() => { + if (Object.prototype.toString.call(this._raw) === '[object Error]') { + // content is already errored + return callback(this._raw); + } + + // remove default error handler (if set) + if (typeof this._raw.pipe === 'function') { + this._raw.removeListener('error', this._contentErrorHandler); + } + + let raw = this._getStream(this._raw); + raw.pipe(outputStream, { + end: false + }); + raw.on('error', err => outputStream.emit('error', err)); + raw.on('end', finalize); + }); + } else { + outputStream.write(this.buildHeaders() + '\r\n\r\n'); + setImmediate(sendContent); + } + } + + /** + * Sets envelope to be used instead of the generated one + * + * @return {Object} SMTP envelope in the form of {from: 'from@example.com', to: ['to@example.com']} + */ + setEnvelope(envelope) { + let list; + + this._envelope = { + from: false, + to: [] + }; + + if (envelope.from) { + list = []; + this._convertAddresses(this._parseAddresses(envelope.from), list); + list = list.filter(address => address && address.address); + if (list.length && list[0]) { + this._envelope.from = list[0].address; + } + } + ['to', 'cc', 'bcc'].forEach(key => { + if (envelope[key]) { + this._convertAddresses(this._parseAddresses(envelope[key]), this._envelope.to); + } + }); + + this._envelope.to = this._envelope.to.map(to => to.address).filter(address => address); + + let standardFields = ['to', 'cc', 'bcc', 'from']; + Object.keys(envelope).forEach(key => { + if (!standardFields.includes(key)) { + this._envelope[key] = envelope[key]; + } + }); + + return this; + } + + /** + * Generates and returns an object with parsed address fields + * + * @return {Object} Address object + */ + getAddresses() { + let addresses = {}; + + this._headers.forEach(header => { + let key = header.key.toLowerCase(); + if (['from', 'sender', 'reply-to', 'to', 'cc', 'bcc'].includes(key)) { + if (!Array.isArray(addresses[key])) { + addresses[key] = []; + } + + this._convertAddresses(this._parseAddresses(header.value), addresses[key]); + } + }); + + return addresses; + } + + /** + * Generates and returns SMTP envelope with the sender address and a list of recipients addresses + * + * @return {Object} SMTP envelope in the form of {from: 'from@example.com', to: ['to@example.com']} + */ + getEnvelope() { + if (this._envelope) { + return this._envelope; + } + + let envelope = { + from: false, + to: [] + }; + this._headers.forEach(header => { + let list = []; + if (header.key === 'From' || (!envelope.from && ['Reply-To', 'Sender'].includes(header.key))) { + this._convertAddresses(this._parseAddresses(header.value), list); + if (list.length && list[0]) { + envelope.from = list[0].address; + } + } else if (['To', 'Cc', 'Bcc'].includes(header.key)) { + this._convertAddresses(this._parseAddresses(header.value), envelope.to); + } + }); + + envelope.to = envelope.to.map(to => to.address); + + return envelope; + } + + /** + * Returns Message-Id value. If it does not exist, then creates one + * + * @return {String} Message-Id value + */ + messageId() { + let messageId = this.getHeader('Message-ID'); + // You really should define your own Message-Id field! + if (!messageId) { + messageId = this._generateMessageId(); + this.setHeader('Message-ID', messageId); + } + return messageId; + } + + /** + * Sets pregenerated content that will be used as the output of this node + * + * @param {String|Buffer|Stream} Raw MIME contents + */ + setRaw(raw) { + this._raw = raw; + + if (this._raw && typeof this._raw.pipe === 'function') { + // pre-stream handler. might be triggered if a stream is set as content + // and 'error' fires before anything is done with this stream + this._contentErrorHandler = err => { + this._raw.removeListener('error', this._contentErrorHandler); + this._raw = err; + }; + this._raw.once('error', this._contentErrorHandler); + } + + return this; + } + + /////// PRIVATE METHODS + + /** + * Detects and returns handle to a stream related with the content. + * + * @param {Mixed} content Node content + * @returns {Object} Stream object + */ + _getStream(content) { + let contentStream; + + if (content._resolvedValue) { + // pass string or buffer content as a stream + contentStream = new PassThrough(); + + setImmediate(() => { + try { + contentStream.end(content._resolvedValue); + } catch (err) { + contentStream.emit('error', err); + } + }); + + return contentStream; + } else if (typeof content.pipe === 'function') { + // assume as stream + return content; + } else if (content && typeof content.path === 'string' && !content.href) { + if (this.disableFileAccess) { + contentStream = new PassThrough(); + setImmediate(() => contentStream.emit('error', new Error('File access rejected for ' + content.path))); + return contentStream; + } + // read file + return fs.createReadStream(content.path); + } else if (content && typeof content.href === 'string') { + if (this.disableUrlAccess) { + contentStream = new PassThrough(); + setImmediate(() => contentStream.emit('error', new Error('Url access rejected for ' + content.href))); + return contentStream; + } + // fetch URL + return nmfetch(content.href, { headers: content.httpHeaders }); + } else { + // pass string or buffer content as a stream + contentStream = new PassThrough(); + + setImmediate(() => { + try { + contentStream.end(content || ''); + } catch (err) { + contentStream.emit('error', err); + } + }); + return contentStream; + } + } + + /** + * Parses addresses. Takes in a single address or an array or an + * array of address arrays (eg. To: [[first group], [second group],...]) + * + * @param {Mixed} addresses Addresses to be parsed + * @return {Array} An array of address objects + */ + _parseAddresses(addresses) { + return [].concat.apply( + [], + [].concat(addresses).map(address => { + // eslint-disable-line prefer-spread + if (address && address.address) { + address.address = this._normalizeAddress(address.address); + address.name = address.name || ''; + return [address]; + } + return addressparser(address); + }) + ); + } + + /** + * Normalizes a header key, uses Camel-Case form, except for uppercase MIME- + * + * @param {String} key Key to be normalized + * @return {String} key in Camel-Case form + */ + _normalizeHeaderKey(key) { + key = (key || '') + .toString() + // no newlines in keys + .replace(/\r?\n|\r/g, ' ') + .trim() + .toLowerCase() + // use uppercase words, except MIME + .replace(/^X-SMTPAPI$|^(MIME|DKIM|ARC|BIMI)\b|^[a-z]|-(SPF|FBL|ID|MD5)$|-[a-z]/gi, c => c.toUpperCase()) + // special case + .replace(/^Content-Features$/i, 'Content-features'); + + return key; + } + + /** + * Checks if the content type is multipart and defines boundary if needed. + * Doesn't return anything, modifies object argument instead. + * + * @param {Object} structured Parsed header value for 'Content-Type' key + */ + _handleContentType(structured) { + this.contentType = structured.value.trim().toLowerCase(); + + this.multipart = /^multipart\//i.test(this.contentType) ? this.contentType.substr(this.contentType.indexOf('/') + 1) : false; + + if (this.multipart) { + this.boundary = structured.params.boundary = structured.params.boundary || this.boundary || this._generateBoundary(); + } else { + this.boundary = false; + } + } + + /** + * Generates a multipart boundary value + * + * @return {String} boundary value + */ + _generateBoundary() { + return this.rootNode.boundaryPrefix + '-' + this.rootNode.baseBoundary + '-Part_' + this._nodeId; + } + + /** + * Encodes a header value for use in the generated rfc2822 email. + * + * @param {String} key Header key + * @param {String} value Header value + */ + _encodeHeaderValue(key, value) { + key = this._normalizeHeaderKey(key); + + switch (key) { + // Structured headers + case 'From': + case 'Sender': + case 'To': + case 'Cc': + case 'Bcc': + case 'Reply-To': + return this._convertAddresses(this._parseAddresses(value)); + + // values enclosed in <> + case 'Message-ID': + case 'In-Reply-To': + case 'Content-Id': + value = (value || '').toString().replace(/\r?\n|\r/g, ' '); + + if (value.charAt(0) !== '<') { + value = '<' + value; + } + + if (value.charAt(value.length - 1) !== '>') { + value = value + '>'; + } + return value; + + // space separated list of values enclosed in <> + case 'References': + value = [].concat + .apply( + [], + [].concat(value || '').map(elm => { + // eslint-disable-line prefer-spread + elm = (elm || '') + .toString() + .replace(/\r?\n|\r/g, ' ') + .trim(); + return elm.replace(/<[^>]*>/g, str => str.replace(/\s/g, '')).split(/\s+/); + }) + ) + .map(elm => { + if (elm.charAt(0) !== '<') { + elm = '<' + elm; + } + if (elm.charAt(elm.length - 1) !== '>') { + elm = elm + '>'; + } + return elm; + }); + + return value.join(' ').trim(); + + case 'Date': + if (Object.prototype.toString.call(value) === '[object Date]') { + return value.toUTCString().replace(/GMT/, '+0000'); + } + + value = (value || '').toString().replace(/\r?\n|\r/g, ' '); + return this._encodeWords(value); + + case 'Content-Type': + case 'Content-Disposition': + // if it includes a filename then it is already encoded + return (value || '').toString().replace(/\r?\n|\r/g, ' '); + + default: + value = (value || '').toString().replace(/\r?\n|\r/g, ' '); + // encodeWords only encodes if needed, otherwise the original string is returned + return this._encodeWords(value); + } + } + + /** + * Rebuilds address object using punycode and other adjustments + * + * @param {Array} addresses An array of address objects + * @param {Array} [uniqueList] An array to be populated with addresses + * @return {String} address string + */ + _convertAddresses(addresses, uniqueList) { + let values = []; + + uniqueList = uniqueList || []; + + [].concat(addresses || []).forEach(address => { + if (address.address) { + address.address = this._normalizeAddress(address.address); + + if (!address.name) { + values.push(address.address.indexOf(' ') >= 0 ? `<${address.address}>` : `${address.address}`); + } else if (address.name) { + values.push(`${this._encodeAddressName(address.name)} <${address.address}>`); + } + + if (address.address) { + if (!uniqueList.filter(a => a.address === address.address).length) { + uniqueList.push(address); + } + } + } else if (address.group) { + let groupListAddresses = (address.group.length ? this._convertAddresses(address.group, uniqueList) : '').trim(); + values.push(`${this._encodeAddressName(address.name)}:${groupListAddresses};`); + } + }); + + return values.join(', '); + } + + /** + * Normalizes an email address + * + * @param {Array} address An array of address objects + * @return {String} address string + */ + _normalizeAddress(address) { + address = (address || '') + .toString() + .replace(/[\x00-\x1F<>]+/g, ' ') // remove unallowed characters + .trim(); + + let lastAt = address.lastIndexOf('@'); + if (lastAt < 0) { + // Bare username + return address; + } + + let user = address.substr(0, lastAt); + let domain = address.substr(lastAt + 1); + + // Usernames are not touched and are kept as is even if these include unicode + // Domains are punycoded by default + // 'jõgeva.ee' will be converted to 'xn--jgeva-dua.ee' + // non-unicode domains are left as is + + let encodedDomain; + + try { + encodedDomain = punycode.toASCII(domain.toLowerCase()); + } catch (err) { + // keep as is? + } + + if (user.indexOf(' ') >= 0) { + if (user.charAt(0) !== '"') { + user = '"' + user; + } + if (user.substr(-1) !== '"') { + user = user + '"'; + } + } + + return `${user}@${encodedDomain}`; + } + + /** + * If needed, mime encodes the name part + * + * @param {String} name Name part of an address + * @returns {String} Mime word encoded string if needed + */ + _encodeAddressName(name) { + if (!/^[\w ']*$/.test(name)) { + if (/^[\x20-\x7e]*$/.test(name)) { + return '"' + name.replace(/([\\"])/g, '\\$1') + '"'; + } else { + return mimeFuncs.encodeWord(name, this._getTextEncoding(name), 52); + } + } + return name; + } + + /** + * If needed, mime encodes the name part + * + * @param {String} name Name part of an address + * @returns {String} Mime word encoded string if needed + */ + _encodeWords(value) { + // set encodeAll parameter to true even though it is against the recommendation of RFC2047, + // by default only words that include non-ascii should be converted into encoded words + // but some clients (eg. Zimbra) do not handle it properly and remove surrounding whitespace + return mimeFuncs.encodeWords(value, this._getTextEncoding(value), 52, true); + } + + /** + * Detects best mime encoding for a text value + * + * @param {String} value Value to check for + * @return {String} either 'Q' or 'B' + */ + _getTextEncoding(value) { + value = (value || '').toString(); + + let encoding = this.textEncoding; + let latinLen; + let nonLatinLen; + + if (!encoding) { + // count latin alphabet symbols and 8-bit range symbols + control symbols + // if there are more latin characters, then use quoted-printable + // encoding, otherwise use base64 + nonLatinLen = (value.match(/[\x00-\x08\x0B\x0C\x0E-\x1F\u0080-\uFFFF]/g) || []).length; // eslint-disable-line no-control-regex + latinLen = (value.match(/[a-z]/gi) || []).length; + // if there are more latin symbols than binary/unicode, then prefer Q, otherwise B + encoding = nonLatinLen < latinLen ? 'Q' : 'B'; + } + return encoding; + } + + /** + * Generates a message id + * + * @return {String} Random Message-ID value + */ + _generateMessageId() { + return ( + '<' + + [2, 2, 2, 6].reduce( + // crux to generate UUID-like random strings + (prev, len) => prev + '-' + crypto.randomBytes(len).toString('hex'), + crypto.randomBytes(4).toString('hex') + ) + + '@' + + // try to use the domain of the FROM address or fallback to server hostname + (this.getEnvelope().from || this.hostname || 'localhost').split('@').pop() + + '>' + ); + } +} + +module.exports = MimeNode; diff --git a/system/login/node_modules/nodemailer/lib/mime-node/last-newline.js b/system/login/node_modules/nodemailer/lib/mime-node/last-newline.js new file mode 100644 index 0000000..5fcd057 --- /dev/null +++ b/system/login/node_modules/nodemailer/lib/mime-node/last-newline.js @@ -0,0 +1,33 @@ +'use strict'; + +const Transform = require('stream').Transform; + +class LastNewline extends Transform { + constructor() { + super(); + this.lastByte = false; + } + + _transform(chunk, encoding, done) { + if (chunk.length) { + this.lastByte = chunk[chunk.length - 1]; + } + + this.push(chunk); + done(); + } + + _flush(done) { + if (this.lastByte === 0x0a) { + return done(); + } + if (this.lastByte === 0x0d) { + this.push(Buffer.from('\n')); + return done(); + } + this.push(Buffer.from('\r\n')); + return done(); + } +} + +module.exports = LastNewline; diff --git a/system/login/node_modules/nodemailer/lib/mime-node/le-unix.js b/system/login/node_modules/nodemailer/lib/mime-node/le-unix.js new file mode 100644 index 0000000..5feacd3 --- /dev/null +++ b/system/login/node_modules/nodemailer/lib/mime-node/le-unix.js @@ -0,0 +1,43 @@ +'use strict'; + +const stream = require('stream'); +const Transform = stream.Transform; + +/** + * Ensures that only is used for linebreaks + * + * @param {Object} options Stream options + */ +class LeWindows extends Transform { + constructor(options) { + super(options); + // init Transform + this.options = options || {}; + } + + /** + * Escapes dots + */ + _transform(chunk, encoding, done) { + let buf; + let lastPos = 0; + + for (let i = 0, len = chunk.length; i < len; i++) { + if (chunk[i] === 0x0d) { + // \n + buf = chunk.slice(lastPos, i); + lastPos = i + 1; + this.push(buf); + } + } + if (lastPos && lastPos < chunk.length) { + buf = chunk.slice(lastPos); + this.push(buf); + } else if (!lastPos) { + this.push(chunk); + } + done(); + } +} + +module.exports = LeWindows; diff --git a/system/login/node_modules/nodemailer/lib/mime-node/le-windows.js b/system/login/node_modules/nodemailer/lib/mime-node/le-windows.js new file mode 100644 index 0000000..b156a7c --- /dev/null +++ b/system/login/node_modules/nodemailer/lib/mime-node/le-windows.js @@ -0,0 +1,52 @@ +'use strict'; + +const stream = require('stream'); +const Transform = stream.Transform; + +/** + * Ensures that only sequences are used for linebreaks + * + * @param {Object} options Stream options + */ +class LeWindows extends Transform { + constructor(options) { + super(options); + // init Transform + this.options = options || {}; + this.lastByte = false; + } + + /** + * Escapes dots + */ + _transform(chunk, encoding, done) { + let buf; + let lastPos = 0; + + for (let i = 0, len = chunk.length; i < len; i++) { + if (chunk[i] === 0x0a) { + // \n + if ((i && chunk[i - 1] !== 0x0d) || (!i && this.lastByte !== 0x0d)) { + if (i > lastPos) { + buf = chunk.slice(lastPos, i); + this.push(buf); + } + this.push(Buffer.from('\r\n')); + lastPos = i + 1; + } + } + } + + if (lastPos && lastPos < chunk.length) { + buf = chunk.slice(lastPos); + this.push(buf); + } else if (!lastPos) { + this.push(chunk); + } + + this.lastByte = chunk[chunk.length - 1]; + done(); + } +} + +module.exports = LeWindows; diff --git a/system/login/node_modules/nodemailer/lib/nodemailer.js b/system/login/node_modules/nodemailer/lib/nodemailer.js new file mode 100644 index 0000000..6dd544d --- /dev/null +++ b/system/login/node_modules/nodemailer/lib/nodemailer.js @@ -0,0 +1,143 @@ +'use strict'; + +const Mailer = require('./mailer'); +const shared = require('./shared'); +const SMTPPool = require('./smtp-pool'); +const SMTPTransport = require('./smtp-transport'); +const SendmailTransport = require('./sendmail-transport'); +const StreamTransport = require('./stream-transport'); +const JSONTransport = require('./json-transport'); +const SESTransport = require('./ses-transport'); +const nmfetch = require('./fetch'); +const packageData = require('../package.json'); + +const ETHEREAL_API = (process.env.ETHEREAL_API || 'https://api.nodemailer.com').replace(/\/+$/, ''); +const ETHEREAL_WEB = (process.env.ETHEREAL_WEB || 'https://ethereal.email').replace(/\/+$/, ''); +const ETHEREAL_CACHE = ['true', 'yes', 'y', '1'].includes((process.env.ETHEREAL_CACHE || 'yes').toString().trim().toLowerCase()); + +let testAccount = false; + +module.exports.createTransport = function (transporter, defaults) { + let urlConfig; + let options; + let mailer; + + if ( + // provided transporter is a configuration object, not transporter plugin + (typeof transporter === 'object' && typeof transporter.send !== 'function') || + // provided transporter looks like a connection url + (typeof transporter === 'string' && /^(smtps?|direct):/i.test(transporter)) + ) { + if ((urlConfig = typeof transporter === 'string' ? transporter : transporter.url)) { + // parse a configuration URL into configuration options + options = shared.parseConnectionUrl(urlConfig); + } else { + options = transporter; + } + + if (options.pool) { + transporter = new SMTPPool(options); + } else if (options.sendmail) { + transporter = new SendmailTransport(options); + } else if (options.streamTransport) { + transporter = new StreamTransport(options); + } else if (options.jsonTransport) { + transporter = new JSONTransport(options); + } else if (options.SES) { + transporter = new SESTransport(options); + } else { + transporter = new SMTPTransport(options); + } + } + + mailer = new Mailer(transporter, options, defaults); + + return mailer; +}; + +module.exports.createTestAccount = function (apiUrl, callback) { + let promise; + + if (!callback && typeof apiUrl === 'function') { + callback = apiUrl; + apiUrl = false; + } + + if (!callback) { + promise = new Promise((resolve, reject) => { + callback = shared.callbackPromise(resolve, reject); + }); + } + + if (ETHEREAL_CACHE && testAccount) { + setImmediate(() => callback(null, testAccount)); + return promise; + } + + apiUrl = apiUrl || ETHEREAL_API; + + let chunks = []; + let chunklen = 0; + + let req = nmfetch(apiUrl + '/user', { + contentType: 'application/json', + method: 'POST', + body: Buffer.from( + JSON.stringify({ + requestor: packageData.name, + version: packageData.version + }) + ) + }); + + req.on('readable', () => { + let chunk; + while ((chunk = req.read()) !== null) { + chunks.push(chunk); + chunklen += chunk.length; + } + }); + + req.once('error', err => callback(err)); + + req.once('end', () => { + let res = Buffer.concat(chunks, chunklen); + let data; + let err; + try { + data = JSON.parse(res.toString()); + } catch (E) { + err = E; + } + if (err) { + return callback(err); + } + if (data.status !== 'success' || data.error) { + return callback(new Error(data.error || 'Request failed')); + } + delete data.status; + testAccount = data; + callback(null, testAccount); + }); + + return promise; +}; + +module.exports.getTestMessageUrl = function (info) { + if (!info || !info.response) { + return false; + } + + let infoProps = new Map(); + info.response.replace(/\[([^\]]+)\]$/, (m, props) => { + props.replace(/\b([A-Z0-9]+)=([^\s]+)/g, (m, key, value) => { + infoProps.set(key, value); + }); + }); + + if (infoProps.has('STATUS') && infoProps.has('MSGID')) { + return (testAccount.web || ETHEREAL_WEB) + '/message/' + infoProps.get('MSGID'); + } + + return false; +}; diff --git a/system/login/node_modules/nodemailer/lib/qp/index.js b/system/login/node_modules/nodemailer/lib/qp/index.js new file mode 100644 index 0000000..6bf6f08 --- /dev/null +++ b/system/login/node_modules/nodemailer/lib/qp/index.js @@ -0,0 +1,219 @@ +'use strict'; + +const Transform = require('stream').Transform; + +/** + * Encodes a Buffer into a Quoted-Printable encoded string + * + * @param {Buffer} buffer Buffer to convert + * @returns {String} Quoted-Printable encoded string + */ +function encode(buffer) { + if (typeof buffer === 'string') { + buffer = Buffer.from(buffer, 'utf-8'); + } + + // usable characters that do not need encoding + let ranges = [ + // https://tools.ietf.org/html/rfc2045#section-6.7 + [0x09], // + [0x0a], // + [0x0d], // + [0x20, 0x3c], // !"#$%&'()*+,-./0123456789:; + [0x3e, 0x7e] // >?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|} + ]; + let result = ''; + let ord; + + for (let i = 0, len = buffer.length; i < len; i++) { + ord = buffer[i]; + // if the char is in allowed range, then keep as is, unless it is a WS in the end of a line + if (checkRanges(ord, ranges) && !((ord === 0x20 || ord === 0x09) && (i === len - 1 || buffer[i + 1] === 0x0a || buffer[i + 1] === 0x0d))) { + result += String.fromCharCode(ord); + continue; + } + result += '=' + (ord < 0x10 ? '0' : '') + ord.toString(16).toUpperCase(); + } + + return result; +} + +/** + * Adds soft line breaks to a Quoted-Printable string + * + * @param {String} str Quoted-Printable encoded string that might need line wrapping + * @param {Number} [lineLength=76] Maximum allowed length for a line + * @returns {String} Soft-wrapped Quoted-Printable encoded string + */ +function wrap(str, lineLength) { + str = (str || '').toString(); + lineLength = lineLength || 76; + + if (str.length <= lineLength) { + return str; + } + + let pos = 0; + let len = str.length; + let match, code, line; + let lineMargin = Math.floor(lineLength / 3); + let result = ''; + + // insert soft linebreaks where needed + while (pos < len) { + line = str.substr(pos, lineLength); + if ((match = line.match(/\r\n/))) { + line = line.substr(0, match.index + match[0].length); + result += line; + pos += line.length; + continue; + } + + if (line.substr(-1) === '\n') { + // nothing to change here + result += line; + pos += line.length; + continue; + } else if ((match = line.substr(-lineMargin).match(/\n.*?$/))) { + // truncate to nearest line break + line = line.substr(0, line.length - (match[0].length - 1)); + result += line; + pos += line.length; + continue; + } else if (line.length > lineLength - lineMargin && (match = line.substr(-lineMargin).match(/[ \t.,!?][^ \t.,!?]*$/))) { + // truncate to nearest space + line = line.substr(0, line.length - (match[0].length - 1)); + } else if (line.match(/[=][\da-f]{0,2}$/i)) { + // push incomplete encoding sequences to the next line + if ((match = line.match(/[=][\da-f]{0,1}$/i))) { + line = line.substr(0, line.length - match[0].length); + } + + // ensure that utf-8 sequences are not split + while (line.length > 3 && line.length < len - pos && !line.match(/^(?:=[\da-f]{2}){1,4}$/i) && (match = line.match(/[=][\da-f]{2}$/gi))) { + code = parseInt(match[0].substr(1, 2), 16); + if (code < 128) { + break; + } + + line = line.substr(0, line.length - 3); + + if (code >= 0xc0) { + break; + } + } + } + + if (pos + line.length < len && line.substr(-1) !== '\n') { + if (line.length === lineLength && line.match(/[=][\da-f]{2}$/i)) { + line = line.substr(0, line.length - 3); + } else if (line.length === lineLength) { + line = line.substr(0, line.length - 1); + } + pos += line.length; + line += '=\r\n'; + } else { + pos += line.length; + } + + result += line; + } + + return result; +} + +/** + * Helper function to check if a number is inside provided ranges + * + * @param {Number} nr Number to check for + * @param {Array} ranges An Array of allowed values + * @returns {Boolean} True if the value was found inside allowed ranges, false otherwise + */ +function checkRanges(nr, ranges) { + for (let i = ranges.length - 1; i >= 0; i--) { + if (!ranges[i].length) { + continue; + } + if (ranges[i].length === 1 && nr === ranges[i][0]) { + return true; + } + if (ranges[i].length === 2 && nr >= ranges[i][0] && nr <= ranges[i][1]) { + return true; + } + } + return false; +} + +/** + * Creates a transform stream for encoding data to Quoted-Printable encoding + * + * @constructor + * @param {Object} options Stream options + * @param {Number} [options.lineLength=76] Maximum length for lines, set to false to disable wrapping + */ +class Encoder extends Transform { + constructor(options) { + super(); + + // init Transform + this.options = options || {}; + + if (this.options.lineLength !== false) { + this.options.lineLength = this.options.lineLength || 76; + } + + this._curLine = ''; + + this.inputBytes = 0; + this.outputBytes = 0; + } + + _transform(chunk, encoding, done) { + let qp; + + if (encoding !== 'buffer') { + chunk = Buffer.from(chunk, encoding); + } + + if (!chunk || !chunk.length) { + return done(); + } + + this.inputBytes += chunk.length; + + if (this.options.lineLength) { + qp = this._curLine + encode(chunk); + qp = wrap(qp, this.options.lineLength); + qp = qp.replace(/(^|\n)([^\n]*)$/, (match, lineBreak, lastLine) => { + this._curLine = lastLine; + return lineBreak; + }); + + if (qp) { + this.outputBytes += qp.length; + this.push(qp); + } + } else { + qp = encode(chunk); + this.outputBytes += qp.length; + this.push(qp, 'ascii'); + } + + done(); + } + + _flush(done) { + if (this._curLine) { + this.outputBytes += this._curLine.length; + this.push(this._curLine, 'ascii'); + } + done(); + } +} + +// expose to the world +module.exports = { + encode, + wrap, + Encoder +}; diff --git a/system/login/node_modules/nodemailer/lib/sendmail-transport/index.js b/system/login/node_modules/nodemailer/lib/sendmail-transport/index.js new file mode 100644 index 0000000..b1cc13b --- /dev/null +++ b/system/login/node_modules/nodemailer/lib/sendmail-transport/index.js @@ -0,0 +1,210 @@ +'use strict'; + +const spawn = require('child_process').spawn; +const packageData = require('../../package.json'); +const shared = require('../shared'); + +/** + * Generates a Transport object for Sendmail + * + * Possible options can be the following: + * + * * **path** optional path to sendmail binary + * * **newline** either 'windows' or 'unix' + * * **args** an array of arguments for the sendmail binary + * + * @constructor + * @param {Object} optional config parameter for Sendmail + */ +class SendmailTransport { + constructor(options) { + options = options || {}; + + // use a reference to spawn for mocking purposes + this._spawn = spawn; + + this.options = options || {}; + + this.name = 'Sendmail'; + this.version = packageData.version; + + this.path = 'sendmail'; + this.args = false; + this.winbreak = false; + + this.logger = shared.getLogger(this.options, { + component: this.options.component || 'sendmail' + }); + + if (options) { + if (typeof options === 'string') { + this.path = options; + } else if (typeof options === 'object') { + if (options.path) { + this.path = options.path; + } + if (Array.isArray(options.args)) { + this.args = options.args; + } + this.winbreak = ['win', 'windows', 'dos', '\r\n'].includes((options.newline || '').toString().toLowerCase()); + } + } + } + + /** + *

Compiles a mailcomposer message and forwards it to handler that sends it.

+ * + * @param {Object} emailMessage MailComposer object + * @param {Function} callback Callback function to run when the sending is completed + */ + send(mail, done) { + // Sendmail strips this header line by itself + mail.message.keepBcc = true; + + let envelope = mail.data.envelope || mail.message.getEnvelope(); + let messageId = mail.message.messageId(); + let args; + let sendmail; + let returned; + + const hasInvalidAddresses = [] + .concat(envelope.from || []) + .concat(envelope.to || []) + .some(addr => /^-/.test(addr)); + if (hasInvalidAddresses) { + return done(new Error('Can not send mail. Invalid envelope addresses.')); + } + + if (this.args) { + // force -i to keep single dots + args = ['-i'].concat(this.args).concat(envelope.to); + } else { + args = ['-i'].concat(envelope.from ? ['-f', envelope.from] : []).concat(envelope.to); + } + + let callback = err => { + if (returned) { + // ignore any additional responses, already done + return; + } + returned = true; + if (typeof done === 'function') { + if (err) { + return done(err); + } else { + return done(null, { + envelope: mail.data.envelope || mail.message.getEnvelope(), + messageId, + response: 'Messages queued for delivery' + }); + } + } + }; + + try { + sendmail = this._spawn(this.path, args); + } catch (E) { + this.logger.error( + { + err: E, + tnx: 'spawn', + messageId + }, + 'Error occurred while spawning sendmail. %s', + E.message + ); + return callback(E); + } + + if (sendmail) { + sendmail.on('error', err => { + this.logger.error( + { + err, + tnx: 'spawn', + messageId + }, + 'Error occurred when sending message %s. %s', + messageId, + err.message + ); + callback(err); + }); + + sendmail.once('exit', code => { + if (!code) { + return callback(); + } + let err; + if (code === 127) { + err = new Error('Sendmail command not found, process exited with code ' + code); + } else { + err = new Error('Sendmail exited with code ' + code); + } + + this.logger.error( + { + err, + tnx: 'stdin', + messageId + }, + 'Error sending message %s to sendmail. %s', + messageId, + err.message + ); + callback(err); + }); + sendmail.once('close', callback); + + sendmail.stdin.on('error', err => { + this.logger.error( + { + err, + tnx: 'stdin', + messageId + }, + 'Error occurred when piping message %s to sendmail. %s', + messageId, + err.message + ); + callback(err); + }); + + let recipients = [].concat(envelope.to || []); + if (recipients.length > 3) { + recipients.push('...and ' + recipients.splice(2).length + ' more'); + } + this.logger.info( + { + tnx: 'send', + messageId + }, + 'Sending message %s to <%s>', + messageId, + recipients.join(', ') + ); + + let sourceStream = mail.message.createReadStream(); + sourceStream.once('error', err => { + this.logger.error( + { + err, + tnx: 'stdin', + messageId + }, + 'Error occurred when generating message %s. %s', + messageId, + err.message + ); + sendmail.kill('SIGINT'); // do not deliver the message + callback(err); + }); + + sourceStream.pipe(sendmail.stdin); + } else { + return callback(new Error('sendmail was not found')); + } + } +} + +module.exports = SendmailTransport; diff --git a/system/login/node_modules/nodemailer/lib/ses-transport/index.js b/system/login/node_modules/nodemailer/lib/ses-transport/index.js new file mode 100644 index 0000000..6646a4a --- /dev/null +++ b/system/login/node_modules/nodemailer/lib/ses-transport/index.js @@ -0,0 +1,349 @@ +'use strict'; + +const EventEmitter = require('events'); +const packageData = require('../../package.json'); +const shared = require('../shared'); +const LeWindows = require('../mime-node/le-windows'); + +/** + * Generates a Transport object for AWS SES + * + * Possible options can be the following: + * + * * **sendingRate** optional Number specifying how many messages per second should be delivered to SES + * * **maxConnections** optional Number specifying max number of parallel connections to SES + * + * @constructor + * @param {Object} optional config parameter + */ +class SESTransport extends EventEmitter { + constructor(options) { + super(); + options = options || {}; + + this.options = options || {}; + this.ses = this.options.SES; + + this.name = 'SESTransport'; + this.version = packageData.version; + + this.logger = shared.getLogger(this.options, { + component: this.options.component || 'ses-transport' + }); + + // parallel sending connections + this.maxConnections = Number(this.options.maxConnections) || Infinity; + this.connections = 0; + + // max messages per second + this.sendingRate = Number(this.options.sendingRate) || Infinity; + this.sendingRateTTL = null; + this.rateInterval = 1000; // milliseconds + this.rateMessages = []; + + this.pending = []; + + this.idling = true; + + setImmediate(() => { + if (this.idling) { + this.emit('idle'); + } + }); + } + + /** + * Schedules a sending of a message + * + * @param {Object} emailMessage MailComposer object + * @param {Function} callback Callback function to run when the sending is completed + */ + send(mail, callback) { + if (this.connections >= this.maxConnections) { + this.idling = false; + return this.pending.push({ + mail, + callback + }); + } + + if (!this._checkSendingRate()) { + this.idling = false; + return this.pending.push({ + mail, + callback + }); + } + + this._send(mail, (...args) => { + setImmediate(() => callback(...args)); + this._sent(); + }); + } + + _checkRatedQueue() { + if (this.connections >= this.maxConnections || !this._checkSendingRate()) { + return; + } + + if (!this.pending.length) { + if (!this.idling) { + this.idling = true; + this.emit('idle'); + } + return; + } + + let next = this.pending.shift(); + this._send(next.mail, (...args) => { + setImmediate(() => next.callback(...args)); + this._sent(); + }); + } + + _checkSendingRate() { + clearTimeout(this.sendingRateTTL); + + let now = Date.now(); + let oldest = false; + // delete older messages + for (let i = this.rateMessages.length - 1; i >= 0; i--) { + if (this.rateMessages[i].ts >= now - this.rateInterval && (!oldest || this.rateMessages[i].ts < oldest)) { + oldest = this.rateMessages[i].ts; + } + + if (this.rateMessages[i].ts < now - this.rateInterval && !this.rateMessages[i].pending) { + this.rateMessages.splice(i, 1); + } + } + + if (this.rateMessages.length < this.sendingRate) { + return true; + } + + let delay = Math.max(oldest + 1001, now + 20); + this.sendingRateTTL = setTimeout(() => this._checkRatedQueue(), now - delay); + + try { + this.sendingRateTTL.unref(); + } catch (E) { + // Ignore. Happens on envs with non-node timer implementation + } + + return false; + } + + _sent() { + this.connections--; + this._checkRatedQueue(); + } + + /** + * Returns true if there are free slots in the queue + */ + isIdle() { + return this.idling; + } + + /** + * Compiles a mailcomposer message and forwards it to SES + * + * @param {Object} emailMessage MailComposer object + * @param {Function} callback Callback function to run when the sending is completed + */ + _send(mail, callback) { + let statObject = { + ts: Date.now(), + pending: true + }; + this.connections++; + this.rateMessages.push(statObject); + + let envelope = mail.data.envelope || mail.message.getEnvelope(); + let messageId = mail.message.messageId(); + + let recipients = [].concat(envelope.to || []); + if (recipients.length > 3) { + recipients.push('...and ' + recipients.splice(2).length + ' more'); + } + this.logger.info( + { + tnx: 'send', + messageId + }, + 'Sending message %s to <%s>', + messageId, + recipients.join(', ') + ); + + let getRawMessage = next => { + // do not use Message-ID and Date in DKIM signature + if (!mail.data._dkim) { + mail.data._dkim = {}; + } + if (mail.data._dkim.skipFields && typeof mail.data._dkim.skipFields === 'string') { + mail.data._dkim.skipFields += ':date:message-id'; + } else { + mail.data._dkim.skipFields = 'date:message-id'; + } + + let sourceStream = mail.message.createReadStream(); + let stream = sourceStream.pipe(new LeWindows()); + let chunks = []; + let chunklen = 0; + + stream.on('readable', () => { + let chunk; + while ((chunk = stream.read()) !== null) { + chunks.push(chunk); + chunklen += chunk.length; + } + }); + + sourceStream.once('error', err => stream.emit('error', err)); + + stream.once('error', err => { + next(err); + }); + + stream.once('end', () => next(null, Buffer.concat(chunks, chunklen))); + }; + + setImmediate(() => + getRawMessage((err, raw) => { + if (err) { + this.logger.error( + { + err, + tnx: 'send', + messageId + }, + 'Failed creating message for %s. %s', + messageId, + err.message + ); + statObject.pending = false; + return callback(err); + } + + let sesMessage = { + RawMessage: { + // required + Data: raw // required + }, + Source: envelope.from, + Destinations: envelope.to + }; + + Object.keys(mail.data.ses || {}).forEach(key => { + sesMessage[key] = mail.data.ses[key]; + }); + + let ses = (this.ses.aws ? this.ses.ses : this.ses) || {}; + let aws = this.ses.aws || {}; + + let getRegion = cb => { + if (ses.config && typeof ses.config.region === 'function') { + // promise + return ses.config + .region() + .then(region => cb(null, region)) + .catch(err => cb(err)); + } + return cb(null, (ses.config && ses.config.region) || 'us-east-1'); + }; + + getRegion((err, region) => { + if (err || !region) { + region = 'us-east-1'; + } + + let sendPromise; + if (typeof ses.send === 'function' && aws.SendRawEmailCommand) { + // v3 API + sendPromise = ses.send(new aws.SendRawEmailCommand(sesMessage)); + } else { + // v2 API + sendPromise = ses.sendRawEmail(sesMessage).promise(); + } + + sendPromise + .then(data => { + if (region === 'us-east-1') { + region = 'email'; + } + + statObject.pending = false; + callback(null, { + envelope: { + from: envelope.from, + to: envelope.to + }, + messageId: '<' + data.MessageId + (!/@/.test(data.MessageId) ? '@' + region + '.amazonses.com' : '') + '>', + response: data.MessageId, + raw + }); + }) + .catch(err => { + this.logger.error( + { + err, + tnx: 'send' + }, + 'Send error for %s: %s', + messageId, + err.message + ); + statObject.pending = false; + callback(err); + }); + }); + }) + ); + } + + /** + * Verifies SES configuration + * + * @param {Function} callback Callback function + */ + verify(callback) { + let promise; + let ses = (this.ses.aws ? this.ses.ses : this.ses) || {}; + let aws = this.ses.aws || {}; + + const sesMessage = { + RawMessage: { + // required + Data: 'From: invalid@invalid\r\nTo: invalid@invalid\r\n Subject: Invalid\r\n\r\nInvalid' + }, + Source: 'invalid@invalid', + Destinations: ['invalid@invalid'] + }; + + if (!callback) { + promise = new Promise((resolve, reject) => { + callback = shared.callbackPromise(resolve, reject); + }); + } + const cb = err => { + if (err && (err.code || err.Code) !== 'InvalidParameterValue') { + return callback(err); + } + return callback(null, true); + }; + + if (typeof ses.send === 'function' && aws.SendRawEmailCommand) { + // v3 API + sesMessage.RawMessage.Data = Buffer.from(sesMessage.RawMessage.Data); + ses.send(new aws.SendRawEmailCommand(sesMessage), cb); + } else { + // v2 API + ses.sendRawEmail(sesMessage, cb); + } + + return promise; + } +} + +module.exports = SESTransport; diff --git a/system/login/node_modules/nodemailer/lib/shared/index.js b/system/login/node_modules/nodemailer/lib/shared/index.js new file mode 100644 index 0000000..23e88f0 --- /dev/null +++ b/system/login/node_modules/nodemailer/lib/shared/index.js @@ -0,0 +1,638 @@ +/* eslint no-console: 0 */ + +'use strict'; + +const urllib = require('url'); +const util = require('util'); +const fs = require('fs'); +const nmfetch = require('../fetch'); +const dns = require('dns'); +const net = require('net'); +const os = require('os'); + +const DNS_TTL = 5 * 60 * 1000; + +let networkInterfaces; +try { + networkInterfaces = os.networkInterfaces(); +} catch (err) { + // fails on some systems +} + +module.exports.networkInterfaces = networkInterfaces; + +const isFamilySupported = (family, allowInternal) => { + let networkInterfaces = module.exports.networkInterfaces; + if (!networkInterfaces) { + // hope for the best + return true; + } + + const familySupported = + // crux that replaces Object.values(networkInterfaces) as Object.values is not supported in nodejs v6 + Object.keys(networkInterfaces) + .map(key => networkInterfaces[key]) + // crux that replaces .flat() as it is not supported in older Node versions (v10 and older) + .reduce((acc, val) => acc.concat(val), []) + .filter(i => !i.internal || allowInternal) + .filter(i => i.family === 'IPv' + family || i.family === family).length > 0; + + return familySupported; +}; + +const resolver = (family, hostname, options, callback) => { + options = options || {}; + const familySupported = isFamilySupported(family, options.allowInternalNetworkInterfaces); + + if (!familySupported) { + return callback(null, []); + } + + const resolver = dns.Resolver ? new dns.Resolver(options) : dns; + resolver['resolve' + family](hostname, (err, addresses) => { + if (err) { + switch (err.code) { + case dns.NODATA: + case dns.NOTFOUND: + case dns.NOTIMP: + case dns.SERVFAIL: + case dns.CONNREFUSED: + case dns.REFUSED: + case 'EAI_AGAIN': + return callback(null, []); + } + return callback(err); + } + return callback(null, Array.isArray(addresses) ? addresses : [].concat(addresses || [])); + }); +}; + +const dnsCache = (module.exports.dnsCache = new Map()); + +const formatDNSValue = (value, extra) => { + if (!value) { + return Object.assign({}, extra || {}); + } + + return Object.assign( + { + servername: value.servername, + host: + !value.addresses || !value.addresses.length + ? null + : value.addresses.length === 1 + ? value.addresses[0] + : value.addresses[Math.floor(Math.random() * value.addresses.length)] + }, + extra || {} + ); +}; + +module.exports.resolveHostname = (options, callback) => { + options = options || {}; + + if (!options.host && options.servername) { + options.host = options.servername; + } + + if (!options.host || net.isIP(options.host)) { + // nothing to do here + let value = { + addresses: [options.host], + servername: options.servername || false + }; + return callback( + null, + formatDNSValue(value, { + cached: false + }) + ); + } + + let cached; + if (dnsCache.has(options.host)) { + cached = dnsCache.get(options.host); + + if (!cached.expires || cached.expires >= Date.now()) { + return callback( + null, + formatDNSValue(cached.value, { + cached: true + }) + ); + } + } + + resolver(4, options.host, options, (err, addresses) => { + if (err) { + if (cached) { + // ignore error, use expired value + return callback( + null, + formatDNSValue(cached.value, { + cached: true, + error: err + }) + ); + } + return callback(err); + } + + if (addresses && addresses.length) { + let value = { + addresses, + servername: options.servername || options.host + }; + + dnsCache.set(options.host, { + value, + expires: Date.now() + (options.dnsTtl || DNS_TTL) + }); + + return callback( + null, + formatDNSValue(value, { + cached: false + }) + ); + } + + resolver(6, options.host, options, (err, addresses) => { + if (err) { + if (cached) { + // ignore error, use expired value + return callback( + null, + formatDNSValue(cached.value, { + cached: true, + error: err + }) + ); + } + return callback(err); + } + + if (addresses && addresses.length) { + let value = { + addresses, + servername: options.servername || options.host + }; + + dnsCache.set(options.host, { + value, + expires: Date.now() + (options.dnsTtl || DNS_TTL) + }); + + return callback( + null, + formatDNSValue(value, { + cached: false + }) + ); + } + + try { + dns.lookup(options.host, { all: true }, (err, addresses) => { + if (err) { + if (cached) { + // ignore error, use expired value + return callback( + null, + formatDNSValue(cached.value, { + cached: true, + error: err + }) + ); + } + return callback(err); + } + + let address = addresses + ? addresses + .filter(addr => isFamilySupported(addr.family)) + .map(addr => addr.address) + .shift() + : false; + + if (addresses && addresses.length && !address) { + // there are addresses but none can be used + console.warn(`Failed to resolve IPv${addresses[0].family} addresses with current network`); + } + + if (!address && cached) { + // nothing was found, fallback to cached value + return callback( + null, + formatDNSValue(cached.value, { + cached: true + }) + ); + } + + let value = { + addresses: address ? [address] : [options.host], + servername: options.servername || options.host + }; + + dnsCache.set(options.host, { + value, + expires: Date.now() + (options.dnsTtl || DNS_TTL) + }); + + return callback( + null, + formatDNSValue(value, { + cached: false + }) + ); + }); + } catch (err) { + if (cached) { + // ignore error, use expired value + return callback( + null, + formatDNSValue(cached.value, { + cached: true, + error: err + }) + ); + } + return callback(err); + } + }); + }); +}; +/** + * Parses connection url to a structured configuration object + * + * @param {String} str Connection url + * @return {Object} Configuration object + */ +module.exports.parseConnectionUrl = str => { + str = str || ''; + let options = {}; + + [urllib.parse(str, true)].forEach(url => { + let auth; + + switch (url.protocol) { + case 'smtp:': + options.secure = false; + break; + case 'smtps:': + options.secure = true; + break; + case 'direct:': + options.direct = true; + break; + } + + if (!isNaN(url.port) && Number(url.port)) { + options.port = Number(url.port); + } + + if (url.hostname) { + options.host = url.hostname; + } + + if (url.auth) { + auth = url.auth.split(':'); + + if (!options.auth) { + options.auth = {}; + } + + options.auth.user = auth.shift(); + options.auth.pass = auth.join(':'); + } + + Object.keys(url.query || {}).forEach(key => { + let obj = options; + let lKey = key; + let value = url.query[key]; + + if (!isNaN(value)) { + value = Number(value); + } + + switch (value) { + case 'true': + value = true; + break; + case 'false': + value = false; + break; + } + + // tls is nested object + if (key.indexOf('tls.') === 0) { + lKey = key.substr(4); + if (!options.tls) { + options.tls = {}; + } + obj = options.tls; + } else if (key.indexOf('.') >= 0) { + // ignore nested properties besides tls + return; + } + + if (!(lKey in obj)) { + obj[lKey] = value; + } + }); + }); + + return options; +}; + +module.exports._logFunc = (logger, level, defaults, data, message, ...args) => { + let entry = {}; + + Object.keys(defaults || {}).forEach(key => { + if (key !== 'level') { + entry[key] = defaults[key]; + } + }); + + Object.keys(data || {}).forEach(key => { + if (key !== 'level') { + entry[key] = data[key]; + } + }); + + logger[level](entry, message, ...args); +}; + +/** + * Returns a bunyan-compatible logger interface. Uses either provided logger or + * creates a default console logger + * + * @param {Object} [options] Options object that might include 'logger' value + * @return {Object} bunyan compatible logger + */ +module.exports.getLogger = (options, defaults) => { + options = options || {}; + + let response = {}; + let levels = ['trace', 'debug', 'info', 'warn', 'error', 'fatal']; + + if (!options.logger) { + // use vanity logger + levels.forEach(level => { + response[level] = () => false; + }); + return response; + } + + let logger = options.logger; + + if (options.logger === true) { + // create console logger + logger = createDefaultLogger(levels); + } + + levels.forEach(level => { + response[level] = (data, message, ...args) => { + module.exports._logFunc(logger, level, defaults, data, message, ...args); + }; + }); + + return response; +}; + +/** + * Wrapper for creating a callback that either resolves or rejects a promise + * based on input + * + * @param {Function} resolve Function to run if callback is called + * @param {Function} reject Function to run if callback ends with an error + */ +module.exports.callbackPromise = (resolve, reject) => + function () { + let args = Array.from(arguments); + let err = args.shift(); + if (err) { + reject(err); + } else { + resolve(...args); + } + }; + +/** + * Resolves a String or a Buffer value for content value. Useful if the value + * is a Stream or a file or an URL. If the value is a Stream, overwrites + * the stream object with the resolved value (you can't stream a value twice). + * + * This is useful when you want to create a plugin that needs a content value, + * for example the `html` or `text` value as a String or a Buffer but not as + * a file path or an URL. + * + * @param {Object} data An object or an Array you want to resolve an element for + * @param {String|Number} key Property name or an Array index + * @param {Function} callback Callback function with (err, value) + */ +module.exports.resolveContent = (data, key, callback) => { + let promise; + + if (!callback) { + promise = new Promise((resolve, reject) => { + callback = module.exports.callbackPromise(resolve, reject); + }); + } + + let content = (data && data[key] && data[key].content) || data[key]; + let contentStream; + let encoding = ((typeof data[key] === 'object' && data[key].encoding) || 'utf8') + .toString() + .toLowerCase() + .replace(/[-_\s]/g, ''); + + if (!content) { + return callback(null, content); + } + + if (typeof content === 'object') { + if (typeof content.pipe === 'function') { + return resolveStream(content, (err, value) => { + if (err) { + return callback(err); + } + // we can't stream twice the same content, so we need + // to replace the stream object with the streaming result + if (data[key].content) { + data[key].content = value; + } else { + data[key] = value; + } + callback(null, value); + }); + } else if (/^https?:\/\//i.test(content.path || content.href)) { + contentStream = nmfetch(content.path || content.href); + return resolveStream(contentStream, callback); + } else if (/^data:/i.test(content.path || content.href)) { + let parts = (content.path || content.href).match(/^data:((?:[^;]*;)*(?:[^,]*)),(.*)$/i); + if (!parts) { + return callback(null, Buffer.from(0)); + } + return callback(null, /\bbase64$/i.test(parts[1]) ? Buffer.from(parts[2], 'base64') : Buffer.from(decodeURIComponent(parts[2]))); + } else if (content.path) { + return resolveStream(fs.createReadStream(content.path), callback); + } + } + + if (typeof data[key].content === 'string' && !['utf8', 'usascii', 'ascii'].includes(encoding)) { + content = Buffer.from(data[key].content, encoding); + } + + // default action, return as is + setImmediate(() => callback(null, content)); + + return promise; +}; + +/** + * Copies properties from source objects to target objects + */ +module.exports.assign = function (/* target, ... sources */) { + let args = Array.from(arguments); + let target = args.shift() || {}; + + args.forEach(source => { + Object.keys(source || {}).forEach(key => { + if (['tls', 'auth'].includes(key) && source[key] && typeof source[key] === 'object') { + // tls and auth are special keys that need to be enumerated separately + // other objects are passed as is + if (!target[key]) { + // ensure that target has this key + target[key] = {}; + } + Object.keys(source[key]).forEach(subKey => { + target[key][subKey] = source[key][subKey]; + }); + } else { + target[key] = source[key]; + } + }); + }); + return target; +}; + +module.exports.encodeXText = str => { + // ! 0x21 + // + 0x2B + // = 0x3D + // ~ 0x7E + if (!/[^\x21-\x2A\x2C-\x3C\x3E-\x7E]/.test(str)) { + return str; + } + let buf = Buffer.from(str); + let result = ''; + for (let i = 0, len = buf.length; i < len; i++) { + let c = buf[i]; + if (c < 0x21 || c > 0x7e || c === 0x2b || c === 0x3d) { + result += '+' + (c < 0x10 ? '0' : '') + c.toString(16).toUpperCase(); + } else { + result += String.fromCharCode(c); + } + } + return result; +}; + +/** + * Streams a stream value into a Buffer + * + * @param {Object} stream Readable stream + * @param {Function} callback Callback function with (err, value) + */ +function resolveStream(stream, callback) { + let responded = false; + let chunks = []; + let chunklen = 0; + + stream.on('error', err => { + if (responded) { + return; + } + + responded = true; + callback(err); + }); + + stream.on('readable', () => { + let chunk; + while ((chunk = stream.read()) !== null) { + chunks.push(chunk); + chunklen += chunk.length; + } + }); + + stream.on('end', () => { + if (responded) { + return; + } + responded = true; + + let value; + + try { + value = Buffer.concat(chunks, chunklen); + } catch (E) { + return callback(E); + } + callback(null, value); + }); +} + +/** + * Generates a bunyan-like logger that prints to console + * + * @returns {Object} Bunyan logger instance + */ +function createDefaultLogger(levels) { + let levelMaxLen = 0; + let levelNames = new Map(); + levels.forEach(level => { + if (level.length > levelMaxLen) { + levelMaxLen = level.length; + } + }); + + levels.forEach(level => { + let levelName = level.toUpperCase(); + if (levelName.length < levelMaxLen) { + levelName += ' '.repeat(levelMaxLen - levelName.length); + } + levelNames.set(level, levelName); + }); + + let print = (level, entry, message, ...args) => { + let prefix = ''; + if (entry) { + if (entry.tnx === 'server') { + prefix = 'S: '; + } else if (entry.tnx === 'client') { + prefix = 'C: '; + } + + if (entry.sid) { + prefix = '[' + entry.sid + '] ' + prefix; + } + + if (entry.cid) { + prefix = '[#' + entry.cid + '] ' + prefix; + } + } + + message = util.format(message, ...args); + message.split(/\r?\n/).forEach(line => { + console.log('[%s] %s %s', new Date().toISOString().substr(0, 19).replace(/T/, ' '), levelNames.get(level), prefix + line); + }); + }; + + let logger = {}; + levels.forEach(level => { + logger[level] = print.bind(null, level); + }); + + return logger; +} diff --git a/system/login/node_modules/nodemailer/lib/smtp-connection/data-stream.js b/system/login/node_modules/nodemailer/lib/smtp-connection/data-stream.js new file mode 100644 index 0000000..5efa087 --- /dev/null +++ b/system/login/node_modules/nodemailer/lib/smtp-connection/data-stream.js @@ -0,0 +1,108 @@ +'use strict'; + +const stream = require('stream'); +const Transform = stream.Transform; + +/** + * Escapes dots in the beginning of lines. Ends the stream with . + * Also makes sure that only sequences are used for linebreaks + * + * @param {Object} options Stream options + */ +class DataStream extends Transform { + constructor(options) { + super(options); + // init Transform + this.options = options || {}; + this._curLine = ''; + + this.inByteCount = 0; + this.outByteCount = 0; + this.lastByte = false; + } + + /** + * Escapes dots + */ + _transform(chunk, encoding, done) { + let chunks = []; + let chunklen = 0; + let i, + len, + lastPos = 0; + let buf; + + if (!chunk || !chunk.length) { + return done(); + } + + if (typeof chunk === 'string') { + chunk = Buffer.from(chunk); + } + + this.inByteCount += chunk.length; + + for (i = 0, len = chunk.length; i < len; i++) { + if (chunk[i] === 0x2e) { + // . + if ((i && chunk[i - 1] === 0x0a) || (!i && (!this.lastByte || this.lastByte === 0x0a))) { + buf = chunk.slice(lastPos, i + 1); + chunks.push(buf); + chunks.push(Buffer.from('.')); + chunklen += buf.length + 1; + lastPos = i + 1; + } + } else if (chunk[i] === 0x0a) { + // . + if ((i && chunk[i - 1] !== 0x0d) || (!i && this.lastByte !== 0x0d)) { + if (i > lastPos) { + buf = chunk.slice(lastPos, i); + chunks.push(buf); + chunklen += buf.length + 2; + } else { + chunklen += 2; + } + chunks.push(Buffer.from('\r\n')); + lastPos = i + 1; + } + } + } + + if (chunklen) { + // add last piece + if (lastPos < chunk.length) { + buf = chunk.slice(lastPos); + chunks.push(buf); + chunklen += buf.length; + } + + this.outByteCount += chunklen; + this.push(Buffer.concat(chunks, chunklen)); + } else { + this.outByteCount += chunk.length; + this.push(chunk); + } + + this.lastByte = chunk[chunk.length - 1]; + done(); + } + + /** + * Finalizes the stream with a dot on a single line + */ + _flush(done) { + let buf; + if (this.lastByte === 0x0a) { + buf = Buffer.from('.\r\n'); + } else if (this.lastByte === 0x0d) { + buf = Buffer.from('\n.\r\n'); + } else { + buf = Buffer.from('\r\n.\r\n'); + } + this.outByteCount += buf.length; + this.push(buf); + done(); + } +} + +module.exports = DataStream; diff --git a/system/login/node_modules/nodemailer/lib/smtp-connection/http-proxy-client.js b/system/login/node_modules/nodemailer/lib/smtp-connection/http-proxy-client.js new file mode 100644 index 0000000..a59bb49 --- /dev/null +++ b/system/login/node_modules/nodemailer/lib/smtp-connection/http-proxy-client.js @@ -0,0 +1,143 @@ +'use strict'; + +/** + * Minimal HTTP/S proxy client + */ + +const net = require('net'); +const tls = require('tls'); +const urllib = require('url'); + +/** + * Establishes proxied connection to destinationPort + * + * httpProxyClient("http://localhost:3128/", 80, "google.com", function(err, socket){ + * socket.write("GET / HTTP/1.0\r\n\r\n"); + * }); + * + * @param {String} proxyUrl proxy configuration, etg "http://proxy.host:3128/" + * @param {Number} destinationPort Port to open in destination host + * @param {String} destinationHost Destination hostname + * @param {Function} callback Callback to run with the rocket object once connection is established + */ +function httpProxyClient(proxyUrl, destinationPort, destinationHost, callback) { + let proxy = urllib.parse(proxyUrl); + + // create a socket connection to the proxy server + let options; + let connect; + let socket; + + options = { + host: proxy.hostname, + port: Number(proxy.port) ? Number(proxy.port) : proxy.protocol === 'https:' ? 443 : 80 + }; + + if (proxy.protocol === 'https:') { + // we can use untrusted proxies as long as we verify actual SMTP certificates + options.rejectUnauthorized = false; + connect = tls.connect.bind(tls); + } else { + connect = net.connect.bind(net); + } + + // Error harness for initial connection. Once connection is established, the responsibility + // to handle errors is passed to whoever uses this socket + let finished = false; + let tempSocketErr = err => { + if (finished) { + return; + } + finished = true; + try { + socket.destroy(); + } catch (E) { + // ignore + } + callback(err); + }; + + let timeoutErr = () => { + let err = new Error('Proxy socket timed out'); + err.code = 'ETIMEDOUT'; + tempSocketErr(err); + }; + + socket = connect(options, () => { + if (finished) { + return; + } + + let reqHeaders = { + Host: destinationHost + ':' + destinationPort, + Connection: 'close' + }; + if (proxy.auth) { + reqHeaders['Proxy-Authorization'] = 'Basic ' + Buffer.from(proxy.auth).toString('base64'); + } + + socket.write( + // HTTP method + 'CONNECT ' + + destinationHost + + ':' + + destinationPort + + ' HTTP/1.1\r\n' + + // HTTP request headers + Object.keys(reqHeaders) + .map(key => key + ': ' + reqHeaders[key]) + .join('\r\n') + + // End request + '\r\n\r\n' + ); + + let headers = ''; + let onSocketData = chunk => { + let match; + let remainder; + + if (finished) { + return; + } + + headers += chunk.toString('binary'); + if ((match = headers.match(/\r\n\r\n/))) { + socket.removeListener('data', onSocketData); + + remainder = headers.substr(match.index + match[0].length); + headers = headers.substr(0, match.index); + if (remainder) { + socket.unshift(Buffer.from(remainder, 'binary')); + } + + // proxy connection is now established + finished = true; + + // check response code + match = headers.match(/^HTTP\/\d+\.\d+ (\d+)/i); + if (!match || (match[1] || '').charAt(0) !== '2') { + try { + socket.destroy(); + } catch (E) { + // ignore + } + return callback(new Error('Invalid response from proxy' + ((match && ': ' + match[1]) || ''))); + } + + socket.removeListener('error', tempSocketErr); + socket.removeListener('timeout', timeoutErr); + socket.setTimeout(0); + + return callback(null, socket); + } + }; + socket.on('data', onSocketData); + }); + + socket.setTimeout(httpProxyClient.timeout || 30 * 1000); + socket.on('timeout', timeoutErr); + + socket.once('error', tempSocketErr); +} + +module.exports = httpProxyClient; diff --git a/system/login/node_modules/nodemailer/lib/smtp-connection/index.js b/system/login/node_modules/nodemailer/lib/smtp-connection/index.js new file mode 100644 index 0000000..22af726 --- /dev/null +++ b/system/login/node_modules/nodemailer/lib/smtp-connection/index.js @@ -0,0 +1,1812 @@ +'use strict'; + +const packageInfo = require('../../package.json'); +const EventEmitter = require('events').EventEmitter; +const net = require('net'); +const tls = require('tls'); +const os = require('os'); +const crypto = require('crypto'); +const DataStream = require('./data-stream'); +const PassThrough = require('stream').PassThrough; +const shared = require('../shared'); + +// default timeout values in ms +const CONNECTION_TIMEOUT = 2 * 60 * 1000; // how much to wait for the connection to be established +const SOCKET_TIMEOUT = 10 * 60 * 1000; // how much to wait for socket inactivity before disconnecting the client +const GREETING_TIMEOUT = 30 * 1000; // how much to wait after connection is established but SMTP greeting is not receieved +const DNS_TIMEOUT = 30 * 1000; // how much to wait for resolveHostname + +/** + * Generates a SMTP connection object + * + * Optional options object takes the following possible properties: + * + * * **port** - is the port to connect to (defaults to 587 or 465) + * * **host** - is the hostname or IP address to connect to (defaults to 'localhost') + * * **secure** - use SSL + * * **ignoreTLS** - ignore server support for STARTTLS + * * **requireTLS** - forces the client to use STARTTLS + * * **name** - the name of the client server + * * **localAddress** - outbound address to bind to (see: http://nodejs.org/api/net.html#net_net_connect_options_connectionlistener) + * * **greetingTimeout** - Time to wait in ms until greeting message is received from the server (defaults to 10000) + * * **connectionTimeout** - how many milliseconds to wait for the connection to establish + * * **socketTimeout** - Time of inactivity until the connection is closed (defaults to 1 hour) + * * **dnsTimeout** - Time to wait in ms for the DNS requests to be resolved (defaults to 30 seconds) + * * **lmtp** - if true, uses LMTP instead of SMTP protocol + * * **logger** - bunyan compatible logger interface + * * **debug** - if true pass SMTP traffic to the logger + * * **tls** - options for createCredentials + * * **socket** - existing socket to use instead of creating a new one (see: http://nodejs.org/api/net.html#net_class_net_socket) + * * **secured** - boolean indicates that the provided socket has already been upgraded to tls + * + * @constructor + * @namespace SMTP Client module + * @param {Object} [options] Option properties + */ +class SMTPConnection extends EventEmitter { + constructor(options) { + super(options); + + this.id = crypto.randomBytes(8).toString('base64').replace(/\W/g, ''); + this.stage = 'init'; + + this.options = options || {}; + + this.secureConnection = !!this.options.secure; + this.alreadySecured = !!this.options.secured; + + this.port = Number(this.options.port) || (this.secureConnection ? 465 : 587); + this.host = this.options.host || 'localhost'; + + this.allowInternalNetworkInterfaces = this.options.allowInternalNetworkInterfaces || false; + + if (typeof this.options.secure === 'undefined' && this.port === 465) { + // if secure option is not set but port is 465, then default to secure + this.secureConnection = true; + } + + this.name = this.options.name || this._getHostname(); + + this.logger = shared.getLogger(this.options, { + component: this.options.component || 'smtp-connection', + sid: this.id + }); + + this.customAuth = new Map(); + Object.keys(this.options.customAuth || {}).forEach(key => { + let mapKey = (key || '').toString().trim().toUpperCase(); + if (!mapKey) { + return; + } + this.customAuth.set(mapKey, this.options.customAuth[key]); + }); + + /** + * Expose version nr, just for the reference + * @type {String} + */ + this.version = packageInfo.version; + + /** + * If true, then the user is authenticated + * @type {Boolean} + */ + this.authenticated = false; + + /** + * If set to true, this instance is no longer active + * @private + */ + this.destroyed = false; + + /** + * Defines if the current connection is secure or not. If not, + * STARTTLS can be used if available + * @private + */ + this.secure = !!this.secureConnection; + + /** + * Store incomplete messages coming from the server + * @private + */ + this._remainder = ''; + + /** + * Unprocessed responses from the server + * @type {Array} + */ + this._responseQueue = []; + + this.lastServerResponse = false; + + /** + * The socket connecting to the server + * @publick + */ + this._socket = false; + + /** + * Lists supported auth mechanisms + * @private + */ + this._supportedAuth = []; + + /** + * Set to true, if EHLO response includes "AUTH". + * If false then authentication is not tried + */ + this.allowsAuth = false; + + /** + * Includes current envelope (from, to) + * @private + */ + this._envelope = false; + + /** + * Lists supported extensions + * @private + */ + this._supportedExtensions = []; + + /** + * Defines the maximum allowed size for a single message + * @private + */ + this._maxAllowedSize = 0; + + /** + * Function queue to run if a data chunk comes from the server + * @private + */ + this._responseActions = []; + this._recipientQueue = []; + + /** + * Timeout variable for waiting the greeting + * @private + */ + this._greetingTimeout = false; + + /** + * Timeout variable for waiting the connection to start + * @private + */ + this._connectionTimeout = false; + + /** + * If the socket is deemed already closed + * @private + */ + this._destroyed = false; + + /** + * If the socket is already being closed + * @private + */ + this._closing = false; + + /** + * Callbacks for socket's listeners + */ + this._onSocketData = chunk => this._onData(chunk); + this._onSocketError = error => this._onError(error, 'ESOCKET', false, 'CONN'); + this._onSocketClose = () => this._onClose(); + this._onSocketEnd = () => this._onEnd(); + this._onSocketTimeout = () => this._onTimeout(); + } + + /** + * Creates a connection to a SMTP server and sets up connection + * listener + */ + connect(connectCallback) { + if (typeof connectCallback === 'function') { + this.once('connect', () => { + this.logger.debug( + { + tnx: 'smtp' + }, + 'SMTP handshake finished' + ); + connectCallback(); + }); + + const isDestroyedMessage = this._isDestroyedMessage('connect'); + if (isDestroyedMessage) { + return connectCallback(this._formatError(isDestroyedMessage, 'ECONNECTION', false, 'CONN')); + } + } + + let opts = { + port: this.port, + host: this.host, + allowInternalNetworkInterfaces: this.allowInternalNetworkInterfaces, + timeout: this.options.dnsTimeout || DNS_TIMEOUT + }; + + if (this.options.localAddress) { + opts.localAddress = this.options.localAddress; + } + + let setupConnectionHandlers = () => { + this._connectionTimeout = setTimeout(() => { + this._onError('Connection timeout', 'ETIMEDOUT', false, 'CONN'); + }, this.options.connectionTimeout || CONNECTION_TIMEOUT); + + this._socket.on('error', this._onSocketError); + }; + + if (this.options.connection) { + // connection is already opened + this._socket = this.options.connection; + if (this.secureConnection && !this.alreadySecured) { + setImmediate(() => + this._upgradeConnection(err => { + if (err) { + this._onError(new Error('Error initiating TLS - ' + (err.message || err)), 'ETLS', false, 'CONN'); + return; + } + this._onConnect(); + }) + ); + } else { + setImmediate(() => this._onConnect()); + } + return; + } else if (this.options.socket) { + // socket object is set up but not yet connected + this._socket = this.options.socket; + return shared.resolveHostname(opts, (err, resolved) => { + if (err) { + return setImmediate(() => this._onError(err, 'EDNS', false, 'CONN')); + } + this.logger.debug( + { + tnx: 'dns', + source: opts.host, + resolved: resolved.host, + cached: !!resolved.cached + }, + 'Resolved %s as %s [cache %s]', + opts.host, + resolved.host, + resolved.cached ? 'hit' : 'miss' + ); + Object.keys(resolved).forEach(key => { + if (key.charAt(0) !== '_' && resolved[key]) { + opts[key] = resolved[key]; + } + }); + try { + this._socket.connect(this.port, this.host, () => { + this._socket.setKeepAlive(true); + this._onConnect(); + }); + setupConnectionHandlers(); + } catch (E) { + return setImmediate(() => this._onError(E, 'ECONNECTION', false, 'CONN')); + } + }); + } else if (this.secureConnection) { + // connect using tls + if (this.options.tls) { + Object.keys(this.options.tls).forEach(key => { + opts[key] = this.options.tls[key]; + }); + } + return shared.resolveHostname(opts, (err, resolved) => { + if (err) { + return setImmediate(() => this._onError(err, 'EDNS', false, 'CONN')); + } + this.logger.debug( + { + tnx: 'dns', + source: opts.host, + resolved: resolved.host, + cached: !!resolved.cached + }, + 'Resolved %s as %s [cache %s]', + opts.host, + resolved.host, + resolved.cached ? 'hit' : 'miss' + ); + Object.keys(resolved).forEach(key => { + if (key.charAt(0) !== '_' && resolved[key]) { + opts[key] = resolved[key]; + } + }); + try { + this._socket = tls.connect(opts, () => { + this._socket.setKeepAlive(true); + this._onConnect(); + }); + setupConnectionHandlers(); + } catch (E) { + return setImmediate(() => this._onError(E, 'ECONNECTION', false, 'CONN')); + } + }); + } else { + // connect using plaintext + return shared.resolveHostname(opts, (err, resolved) => { + if (err) { + return setImmediate(() => this._onError(err, 'EDNS', false, 'CONN')); + } + this.logger.debug( + { + tnx: 'dns', + source: opts.host, + resolved: resolved.host, + cached: !!resolved.cached + }, + 'Resolved %s as %s [cache %s]', + opts.host, + resolved.host, + resolved.cached ? 'hit' : 'miss' + ); + Object.keys(resolved).forEach(key => { + if (key.charAt(0) !== '_' && resolved[key]) { + opts[key] = resolved[key]; + } + }); + try { + this._socket = net.connect(opts, () => { + this._socket.setKeepAlive(true); + this._onConnect(); + }); + setupConnectionHandlers(); + } catch (E) { + return setImmediate(() => this._onError(E, 'ECONNECTION', false, 'CONN')); + } + }); + } + } + + /** + * Sends QUIT + */ + quit() { + this._sendCommand('QUIT'); + this._responseActions.push(this.close); + } + + /** + * Closes the connection to the server + */ + close() { + clearTimeout(this._connectionTimeout); + clearTimeout(this._greetingTimeout); + this._responseActions = []; + + // allow to run this function only once + if (this._closing) { + return; + } + this._closing = true; + + let closeMethod = 'end'; + + if (this.stage === 'init') { + // Close the socket immediately when connection timed out + closeMethod = 'destroy'; + } + + this.logger.debug( + { + tnx: 'smtp' + }, + 'Closing connection to the server using "%s"', + closeMethod + ); + + let socket = (this._socket && this._socket.socket) || this._socket; + + if (socket && !socket.destroyed) { + try { + this._socket[closeMethod](); + } catch (E) { + // just ignore + } + } + + this._destroy(); + } + + /** + * Authenticate user + */ + login(authData, callback) { + const isDestroyedMessage = this._isDestroyedMessage('login'); + if (isDestroyedMessage) { + return callback(this._formatError(isDestroyedMessage, 'ECONNECTION', false, 'API')); + } + + this._auth = authData || {}; + // Select SASL authentication method + this._authMethod = (this._auth.method || '').toString().trim().toUpperCase() || false; + + if (!this._authMethod && this._auth.oauth2 && !this._auth.credentials) { + this._authMethod = 'XOAUTH2'; + } else if (!this._authMethod || (this._authMethod === 'XOAUTH2' && !this._auth.oauth2)) { + // use first supported + this._authMethod = (this._supportedAuth[0] || 'PLAIN').toUpperCase().trim(); + } + + if (this._authMethod !== 'XOAUTH2' && (!this._auth.credentials || !this._auth.credentials.user || !this._auth.credentials.pass)) { + if ((this._auth.user && this._auth.pass) || this.customAuth.has(this._authMethod)) { + this._auth.credentials = { + user: this._auth.user, + pass: this._auth.pass, + options: this._auth.options + }; + } else { + return callback(this._formatError('Missing credentials for "' + this._authMethod + '"', 'EAUTH', false, 'API')); + } + } + + if (this.customAuth.has(this._authMethod)) { + let handler = this.customAuth.get(this._authMethod); + let lastResponse; + let returned = false; + + let resolve = () => { + if (returned) { + return; + } + returned = true; + this.logger.info( + { + tnx: 'smtp', + username: this._auth.user, + action: 'authenticated', + method: this._authMethod + }, + 'User %s authenticated', + JSON.stringify(this._auth.user) + ); + this.authenticated = true; + callback(null, true); + }; + + let reject = err => { + if (returned) { + return; + } + returned = true; + callback(this._formatError(err, 'EAUTH', lastResponse, 'AUTH ' + this._authMethod)); + }; + + let handlerResponse = handler({ + auth: this._auth, + method: this._authMethod, + + extensions: [].concat(this._supportedExtensions), + authMethods: [].concat(this._supportedAuth), + maxAllowedSize: this._maxAllowedSize || false, + + sendCommand: (cmd, done) => { + let promise; + + if (!done) { + promise = new Promise((resolve, reject) => { + done = shared.callbackPromise(resolve, reject); + }); + } + + this._responseActions.push(str => { + lastResponse = str; + + let codes = str.match(/^(\d+)(?:\s(\d+\.\d+\.\d+))?\s/); + let data = { + command: cmd, + response: str + }; + if (codes) { + data.status = Number(codes[1]) || 0; + if (codes[2]) { + data.code = codes[2]; + } + data.text = str.substr(codes[0].length); + } else { + data.text = str; + data.status = 0; // just in case we need to perform numeric comparisons + } + done(null, data); + }); + setImmediate(() => this._sendCommand(cmd)); + + return promise; + }, + + resolve, + reject + }); + + if (handlerResponse && typeof handlerResponse.catch === 'function') { + // a promise was returned + handlerResponse.then(resolve).catch(reject); + } + + return; + } + + switch (this._authMethod) { + case 'XOAUTH2': + this._handleXOauth2Token(false, callback); + return; + case 'LOGIN': + this._responseActions.push(str => { + this._actionAUTH_LOGIN_USER(str, callback); + }); + this._sendCommand('AUTH LOGIN'); + return; + case 'PLAIN': + this._responseActions.push(str => { + this._actionAUTHComplete(str, callback); + }); + this._sendCommand( + 'AUTH PLAIN ' + + Buffer.from( + //this._auth.user+'\u0000'+ + '\u0000' + // skip authorization identity as it causes problems with some servers + this._auth.credentials.user + + '\u0000' + + this._auth.credentials.pass, + 'utf-8' + ).toString('base64'), + // log entry without passwords + 'AUTH PLAIN ' + + Buffer.from( + //this._auth.user+'\u0000'+ + '\u0000' + // skip authorization identity as it causes problems with some servers + this._auth.credentials.user + + '\u0000' + + '/* secret */', + 'utf-8' + ).toString('base64') + ); + return; + case 'CRAM-MD5': + this._responseActions.push(str => { + this._actionAUTH_CRAM_MD5(str, callback); + }); + this._sendCommand('AUTH CRAM-MD5'); + return; + } + + return callback(this._formatError('Unknown authentication method "' + this._authMethod + '"', 'EAUTH', false, 'API')); + } + + /** + * Sends a message + * + * @param {Object} envelope Envelope object, {from: addr, to: [addr]} + * @param {Object} message String, Buffer or a Stream + * @param {Function} callback Callback to return once sending is completed + */ + send(envelope, message, done) { + if (!message) { + return done(this._formatError('Empty message', 'EMESSAGE', false, 'API')); + } + + const isDestroyedMessage = this._isDestroyedMessage('send message'); + if (isDestroyedMessage) { + return done(this._formatError(isDestroyedMessage, 'ECONNECTION', false, 'API')); + } + + // reject larger messages than allowed + if (this._maxAllowedSize && envelope.size > this._maxAllowedSize) { + return setImmediate(() => { + done(this._formatError('Message size larger than allowed ' + this._maxAllowedSize, 'EMESSAGE', false, 'MAIL FROM')); + }); + } + + // ensure that callback is only called once + let returned = false; + let callback = function () { + if (returned) { + return; + } + returned = true; + + done(...arguments); + }; + + if (typeof message.on === 'function') { + message.on('error', err => callback(this._formatError(err, 'ESTREAM', false, 'API'))); + } + + let startTime = Date.now(); + this._setEnvelope(envelope, (err, info) => { + if (err) { + return callback(err); + } + let envelopeTime = Date.now(); + let stream = this._createSendStream((err, str) => { + if (err) { + return callback(err); + } + + info.envelopeTime = envelopeTime - startTime; + info.messageTime = Date.now() - envelopeTime; + info.messageSize = stream.outByteCount; + info.response = str; + + return callback(null, info); + }); + if (typeof message.pipe === 'function') { + message.pipe(stream); + } else { + stream.write(message); + stream.end(); + } + }); + } + + /** + * Resets connection state + * + * @param {Function} callback Callback to return once connection is reset + */ + reset(callback) { + this._sendCommand('RSET'); + this._responseActions.push(str => { + if (str.charAt(0) !== '2') { + return callback(this._formatError('Could not reset session state. response=' + str, 'EPROTOCOL', str, 'RSET')); + } + this._envelope = false; + return callback(null, true); + }); + } + + /** + * Connection listener that is run when the connection to + * the server is opened + * + * @event + */ + _onConnect() { + clearTimeout(this._connectionTimeout); + + this.logger.info( + { + tnx: 'network', + localAddress: this._socket.localAddress, + localPort: this._socket.localPort, + remoteAddress: this._socket.remoteAddress, + remotePort: this._socket.remotePort + }, + '%s established to %s:%s', + this.secure ? 'Secure connection' : 'Connection', + this._socket.remoteAddress, + this._socket.remotePort + ); + + if (this._destroyed) { + // Connection was established after we already had canceled it + this.close(); + return; + } + + this.stage = 'connected'; + + // clear existing listeners for the socket + this._socket.removeListener('data', this._onSocketData); + this._socket.removeListener('timeout', this._onSocketTimeout); + this._socket.removeListener('close', this._onSocketClose); + this._socket.removeListener('end', this._onSocketEnd); + + this._socket.on('data', this._onSocketData); + this._socket.once('close', this._onSocketClose); + this._socket.once('end', this._onSocketEnd); + + this._socket.setTimeout(this.options.socketTimeout || SOCKET_TIMEOUT); + this._socket.on('timeout', this._onSocketTimeout); + + this._greetingTimeout = setTimeout(() => { + // if still waiting for greeting, give up + if (this._socket && !this._destroyed && this._responseActions[0] === this._actionGreeting) { + this._onError('Greeting never received', 'ETIMEDOUT', false, 'CONN'); + } + }, this.options.greetingTimeout || GREETING_TIMEOUT); + + this._responseActions.push(this._actionGreeting); + + // we have a 'data' listener set up so resume socket if it was paused + this._socket.resume(); + } + + /** + * 'data' listener for data coming from the server + * + * @event + * @param {Buffer} chunk Data chunk coming from the server + */ + _onData(chunk) { + if (this._destroyed || !chunk || !chunk.length) { + return; + } + + let data = (chunk || '').toString('binary'); + let lines = (this._remainder + data).split(/\r?\n/); + let lastline; + + this._remainder = lines.pop(); + + for (let i = 0, len = lines.length; i < len; i++) { + if (this._responseQueue.length) { + lastline = this._responseQueue[this._responseQueue.length - 1]; + if (/^\d+-/.test(lastline.split('\n').pop())) { + this._responseQueue[this._responseQueue.length - 1] += '\n' + lines[i]; + continue; + } + } + this._responseQueue.push(lines[i]); + } + + if (this._responseQueue.length) { + lastline = this._responseQueue[this._responseQueue.length - 1]; + if (/^\d+-/.test(lastline.split('\n').pop())) { + return; + } + } + + this._processResponse(); + } + + /** + * 'error' listener for the socket + * + * @event + * @param {Error} err Error object + * @param {String} type Error name + */ + _onError(err, type, data, command) { + clearTimeout(this._connectionTimeout); + clearTimeout(this._greetingTimeout); + + if (this._destroyed) { + // just ignore, already closed + // this might happen when a socket is canceled because of reached timeout + // but the socket timeout error itself receives only after + return; + } + + err = this._formatError(err, type, data, command); + + this.logger.error(data, err.message); + + this.emit('error', err); + this.close(); + } + + _formatError(message, type, response, command) { + let err; + + if (/Error\]$/i.test(Object.prototype.toString.call(message))) { + err = message; + } else { + err = new Error(message); + } + + if (type && type !== 'Error') { + err.code = type; + } + + if (response) { + err.response = response; + err.message += ': ' + response; + } + + let responseCode = (typeof response === 'string' && Number((response.match(/^\d+/) || [])[0])) || false; + if (responseCode) { + err.responseCode = responseCode; + } + + if (command) { + err.command = command; + } + + return err; + } + + /** + * 'close' listener for the socket + * + * @event + */ + _onClose() { + let serverResponse = false; + + if (this._remainder && this._remainder.trim()) { + if (this.options.debug || this.options.transactionLog) { + this.logger.debug( + { + tnx: 'server' + }, + this._remainder.replace(/\r?\n$/, '') + ); + } + this.lastServerResponse = serverResponse = this._remainder.trim(); + } + + this.logger.info( + { + tnx: 'network' + }, + 'Connection closed' + ); + + if (this.upgrading && !this._destroyed) { + return this._onError(new Error('Connection closed unexpectedly'), 'ETLS', serverResponse, 'CONN'); + } else if (![this._actionGreeting, this.close].includes(this._responseActions[0]) && !this._destroyed) { + return this._onError(new Error('Connection closed unexpectedly'), 'ECONNECTION', serverResponse, 'CONN'); + } else if (/^[45]\d{2}\b/.test(serverResponse)) { + return this._onError(new Error('Connection closed unexpectedly'), 'ECONNECTION', serverResponse, 'CONN'); + } + + this._destroy(); + } + + /** + * 'end' listener for the socket + * + * @event + */ + _onEnd() { + if (this._socket && !this._socket.destroyed) { + this._socket.destroy(); + } + } + + /** + * 'timeout' listener for the socket + * + * @event + */ + _onTimeout() { + return this._onError(new Error('Timeout'), 'ETIMEDOUT', false, 'CONN'); + } + + /** + * Destroys the client, emits 'end' + */ + _destroy() { + if (this._destroyed) { + return; + } + this._destroyed = true; + this.emit('end'); + } + + /** + * Upgrades the connection to TLS + * + * @param {Function} callback Callback function to run when the connection + * has been secured + */ + _upgradeConnection(callback) { + // do not remove all listeners or it breaks node v0.10 as there's + // apparently a 'finish' event set that would be cleared as well + + // we can safely keep 'error', 'end', 'close' etc. events + this._socket.removeListener('data', this._onSocketData); // incoming data is going to be gibberish from this point onwards + this._socket.removeListener('timeout', this._onSocketTimeout); // timeout will be re-set for the new socket object + + let socketPlain = this._socket; + let opts = { + socket: this._socket, + host: this.host + }; + + Object.keys(this.options.tls || {}).forEach(key => { + opts[key] = this.options.tls[key]; + }); + + this.upgrading = true; + // tls.connect is not an asynchronous function however it may still throw errors and requires to be wrapped with try/catch + try { + this._socket = tls.connect(opts, () => { + this.secure = true; + this.upgrading = false; + this._socket.on('data', this._onSocketData); + + socketPlain.removeListener('close', this._onSocketClose); + socketPlain.removeListener('end', this._onSocketEnd); + + return callback(null, true); + }); + } catch (err) { + return callback(err); + } + + this._socket.on('error', this._onSocketError); + this._socket.once('close', this._onSocketClose); + this._socket.once('end', this._onSocketEnd); + + this._socket.setTimeout(this.options.socketTimeout || SOCKET_TIMEOUT); // 10 min. + this._socket.on('timeout', this._onSocketTimeout); + + // resume in case the socket was paused + socketPlain.resume(); + } + + /** + * Processes queued responses from the server + * + * @param {Boolean} force If true, ignores _processing flag + */ + _processResponse() { + if (!this._responseQueue.length) { + return false; + } + + let str = (this.lastServerResponse = (this._responseQueue.shift() || '').toString()); + + if (/^\d+-/.test(str.split('\n').pop())) { + // keep waiting for the final part of multiline response + return; + } + + if (this.options.debug || this.options.transactionLog) { + this.logger.debug( + { + tnx: 'server' + }, + str.replace(/\r?\n$/, '') + ); + } + + if (!str.trim()) { + // skip unexpected empty lines + setImmediate(() => this._processResponse()); + } + + let action = this._responseActions.shift(); + + if (typeof action === 'function') { + action.call(this, str); + setImmediate(() => this._processResponse()); + } else { + return this._onError(new Error('Unexpected Response'), 'EPROTOCOL', str, 'CONN'); + } + } + + /** + * Send a command to the server, append \r\n + * + * @param {String} str String to be sent to the server + * @param {String} logStr Optional string to be used for logging instead of the actual string + */ + _sendCommand(str, logStr) { + if (this._destroyed) { + // Connection already closed, can't send any more data + return; + } + + if (this._socket.destroyed) { + return this.close(); + } + + if (this.options.debug || this.options.transactionLog) { + this.logger.debug( + { + tnx: 'client' + }, + (logStr || str || '').toString().replace(/\r?\n$/, '') + ); + } + + this._socket.write(Buffer.from(str + '\r\n', 'utf-8')); + } + + /** + * Initiates a new message by submitting envelope data, starting with + * MAIL FROM: command + * + * @param {Object} envelope Envelope object in the form of + * {from:'...', to:['...']} + * or + * {from:{address:'...',name:'...'}, to:[address:'...',name:'...']} + */ + _setEnvelope(envelope, callback) { + let args = []; + let useSmtpUtf8 = false; + + this._envelope = envelope || {}; + this._envelope.from = ((this._envelope.from && this._envelope.from.address) || this._envelope.from || '').toString().trim(); + + this._envelope.to = [].concat(this._envelope.to || []).map(to => ((to && to.address) || to || '').toString().trim()); + + if (!this._envelope.to.length) { + return callback(this._formatError('No recipients defined', 'EENVELOPE', false, 'API')); + } + + if (this._envelope.from && /[\r\n<>]/.test(this._envelope.from)) { + return callback(this._formatError('Invalid sender ' + JSON.stringify(this._envelope.from), 'EENVELOPE', false, 'API')); + } + + // check if the sender address uses only ASCII characters, + // otherwise require usage of SMTPUTF8 extension + if (/[\x80-\uFFFF]/.test(this._envelope.from)) { + useSmtpUtf8 = true; + } + + for (let i = 0, len = this._envelope.to.length; i < len; i++) { + if (!this._envelope.to[i] || /[\r\n<>]/.test(this._envelope.to[i])) { + return callback(this._formatError('Invalid recipient ' + JSON.stringify(this._envelope.to[i]), 'EENVELOPE', false, 'API')); + } + + // check if the recipients addresses use only ASCII characters, + // otherwise require usage of SMTPUTF8 extension + if (/[\x80-\uFFFF]/.test(this._envelope.to[i])) { + useSmtpUtf8 = true; + } + } + + // clone the recipients array for latter manipulation + this._envelope.rcptQueue = JSON.parse(JSON.stringify(this._envelope.to || [])); + this._envelope.rejected = []; + this._envelope.rejectedErrors = []; + this._envelope.accepted = []; + + if (this._envelope.dsn) { + try { + this._envelope.dsn = this._setDsnEnvelope(this._envelope.dsn); + } catch (err) { + return callback(this._formatError('Invalid DSN ' + err.message, 'EENVELOPE', false, 'API')); + } + } + + this._responseActions.push(str => { + this._actionMAIL(str, callback); + }); + + // If the server supports SMTPUTF8 and the envelope includes an internationalized + // email address then append SMTPUTF8 keyword to the MAIL FROM command + if (useSmtpUtf8 && this._supportedExtensions.includes('SMTPUTF8')) { + args.push('SMTPUTF8'); + this._usingSmtpUtf8 = true; + } + + // If the server supports 8BITMIME and the message might contain non-ascii bytes + // then append the 8BITMIME keyword to the MAIL FROM command + if (this._envelope.use8BitMime && this._supportedExtensions.includes('8BITMIME')) { + args.push('BODY=8BITMIME'); + this._using8BitMime = true; + } + + if (this._envelope.size && this._supportedExtensions.includes('SIZE')) { + args.push('SIZE=' + this._envelope.size); + } + + // If the server supports DSN and the envelope includes an DSN prop + // then append DSN params to the MAIL FROM command + if (this._envelope.dsn && this._supportedExtensions.includes('DSN')) { + if (this._envelope.dsn.ret) { + args.push('RET=' + shared.encodeXText(this._envelope.dsn.ret)); + } + if (this._envelope.dsn.envid) { + args.push('ENVID=' + shared.encodeXText(this._envelope.dsn.envid)); + } + } + + this._sendCommand('MAIL FROM:<' + this._envelope.from + '>' + (args.length ? ' ' + args.join(' ') : '')); + } + + _setDsnEnvelope(params) { + let ret = (params.ret || params.return || '').toString().toUpperCase() || null; + if (ret) { + switch (ret) { + case 'HDRS': + case 'HEADERS': + ret = 'HDRS'; + break; + case 'FULL': + case 'BODY': + ret = 'FULL'; + break; + } + } + + if (ret && !['FULL', 'HDRS'].includes(ret)) { + throw new Error('ret: ' + JSON.stringify(ret)); + } + + let envid = (params.envid || params.id || '').toString() || null; + + let notify = params.notify || null; + if (notify) { + if (typeof notify === 'string') { + notify = notify.split(','); + } + notify = notify.map(n => n.trim().toUpperCase()); + let validNotify = ['NEVER', 'SUCCESS', 'FAILURE', 'DELAY']; + let invaliNotify = notify.filter(n => !validNotify.includes(n)); + if (invaliNotify.length || (notify.length > 1 && notify.includes('NEVER'))) { + throw new Error('notify: ' + JSON.stringify(notify.join(','))); + } + notify = notify.join(','); + } + + let orcpt = (params.recipient || params.orcpt || '').toString() || null; + if (orcpt && orcpt.indexOf(';') < 0) { + orcpt = 'rfc822;' + orcpt; + } + + return { + ret, + envid, + notify, + orcpt + }; + } + + _getDsnRcptToArgs() { + let args = []; + // If the server supports DSN and the envelope includes an DSN prop + // then append DSN params to the RCPT TO command + if (this._envelope.dsn && this._supportedExtensions.includes('DSN')) { + if (this._envelope.dsn.notify) { + args.push('NOTIFY=' + shared.encodeXText(this._envelope.dsn.notify)); + } + if (this._envelope.dsn.orcpt) { + args.push('ORCPT=' + shared.encodeXText(this._envelope.dsn.orcpt)); + } + } + return args.length ? ' ' + args.join(' ') : ''; + } + + _createSendStream(callback) { + let dataStream = new DataStream(); + let logStream; + + if (this.options.lmtp) { + this._envelope.accepted.forEach((recipient, i) => { + let final = i === this._envelope.accepted.length - 1; + this._responseActions.push(str => { + this._actionLMTPStream(recipient, final, str, callback); + }); + }); + } else { + this._responseActions.push(str => { + this._actionSMTPStream(str, callback); + }); + } + + dataStream.pipe(this._socket, { + end: false + }); + + if (this.options.debug) { + logStream = new PassThrough(); + logStream.on('readable', () => { + let chunk; + while ((chunk = logStream.read())) { + this.logger.debug( + { + tnx: 'message' + }, + chunk.toString('binary').replace(/\r?\n$/, '') + ); + } + }); + dataStream.pipe(logStream); + } + + dataStream.once('end', () => { + this.logger.info( + { + tnx: 'message', + inByteCount: dataStream.inByteCount, + outByteCount: dataStream.outByteCount + }, + '<%s bytes encoded mime message (source size %s bytes)>', + dataStream.outByteCount, + dataStream.inByteCount + ); + }); + + return dataStream; + } + + /** ACTIONS **/ + + /** + * Will be run after the connection is created and the server sends + * a greeting. If the incoming message starts with 220 initiate + * SMTP session by sending EHLO command + * + * @param {String} str Message from the server + */ + _actionGreeting(str) { + clearTimeout(this._greetingTimeout); + + if (str.substr(0, 3) !== '220') { + this._onError(new Error('Invalid greeting. response=' + str), 'EPROTOCOL', str, 'CONN'); + return; + } + + if (this.options.lmtp) { + this._responseActions.push(this._actionLHLO); + this._sendCommand('LHLO ' + this.name); + } else { + this._responseActions.push(this._actionEHLO); + this._sendCommand('EHLO ' + this.name); + } + } + + /** + * Handles server response for LHLO command. If it yielded in + * error, emit 'error', otherwise treat this as an EHLO response + * + * @param {String} str Message from the server + */ + _actionLHLO(str) { + if (str.charAt(0) !== '2') { + this._onError(new Error('Invalid LHLO. response=' + str), 'EPROTOCOL', str, 'LHLO'); + return; + } + + this._actionEHLO(str); + } + + /** + * Handles server response for EHLO command. If it yielded in + * error, try HELO instead, otherwise initiate TLS negotiation + * if STARTTLS is supported by the server or move into the + * authentication phase. + * + * @param {String} str Message from the server + */ + _actionEHLO(str) { + let match; + + if (str.substr(0, 3) === '421') { + this._onError(new Error('Server terminates connection. response=' + str), 'ECONNECTION', str, 'EHLO'); + return; + } + + if (str.charAt(0) !== '2') { + if (this.options.requireTLS) { + this._onError(new Error('EHLO failed but HELO does not support required STARTTLS. response=' + str), 'ECONNECTION', str, 'EHLO'); + return; + } + + // Try HELO instead + this._responseActions.push(this._actionHELO); + this._sendCommand('HELO ' + this.name); + return; + } + + this._ehloLines = str + .split(/\r?\n/) + .map(line => line.replace(/^\d+[ -]/, '').trim()) + .filter(line => line) + .slice(1); + + // Detect if the server supports STARTTLS + if (!this.secure && !this.options.ignoreTLS && (/[ -]STARTTLS\b/im.test(str) || this.options.requireTLS)) { + this._sendCommand('STARTTLS'); + this._responseActions.push(this._actionSTARTTLS); + return; + } + + // Detect if the server supports SMTPUTF8 + if (/[ -]SMTPUTF8\b/im.test(str)) { + this._supportedExtensions.push('SMTPUTF8'); + } + + // Detect if the server supports DSN + if (/[ -]DSN\b/im.test(str)) { + this._supportedExtensions.push('DSN'); + } + + // Detect if the server supports 8BITMIME + if (/[ -]8BITMIME\b/im.test(str)) { + this._supportedExtensions.push('8BITMIME'); + } + + // Detect if the server supports PIPELINING + if (/[ -]PIPELINING\b/im.test(str)) { + this._supportedExtensions.push('PIPELINING'); + } + + // Detect if the server supports AUTH + if (/[ -]AUTH\b/i.test(str)) { + this.allowsAuth = true; + } + + // Detect if the server supports PLAIN auth + if (/[ -]AUTH(?:(\s+|=)[^\n]*\s+|\s+|=)PLAIN/i.test(str)) { + this._supportedAuth.push('PLAIN'); + } + + // Detect if the server supports LOGIN auth + if (/[ -]AUTH(?:(\s+|=)[^\n]*\s+|\s+|=)LOGIN/i.test(str)) { + this._supportedAuth.push('LOGIN'); + } + + // Detect if the server supports CRAM-MD5 auth + if (/[ -]AUTH(?:(\s+|=)[^\n]*\s+|\s+|=)CRAM-MD5/i.test(str)) { + this._supportedAuth.push('CRAM-MD5'); + } + + // Detect if the server supports XOAUTH2 auth + if (/[ -]AUTH(?:(\s+|=)[^\n]*\s+|\s+|=)XOAUTH2/i.test(str)) { + this._supportedAuth.push('XOAUTH2'); + } + + // Detect if the server supports SIZE extensions (and the max allowed size) + if ((match = str.match(/[ -]SIZE(?:[ \t]+(\d+))?/im))) { + this._supportedExtensions.push('SIZE'); + this._maxAllowedSize = Number(match[1]) || 0; + } + + this.emit('connect'); + } + + /** + * Handles server response for HELO command. If it yielded in + * error, emit 'error', otherwise move into the authentication phase. + * + * @param {String} str Message from the server + */ + _actionHELO(str) { + if (str.charAt(0) !== '2') { + this._onError(new Error('Invalid HELO. response=' + str), 'EPROTOCOL', str, 'HELO'); + return; + } + + // assume that authentication is enabled (most probably is not though) + this.allowsAuth = true; + + this.emit('connect'); + } + + /** + * Handles server response for STARTTLS command. If there's an error + * try HELO instead, otherwise initiate TLS upgrade. If the upgrade + * succeedes restart the EHLO + * + * @param {String} str Message from the server + */ + _actionSTARTTLS(str) { + if (str.charAt(0) !== '2') { + if (this.options.opportunisticTLS) { + this.logger.info( + { + tnx: 'smtp' + }, + 'Failed STARTTLS upgrade, continuing unencrypted' + ); + return this.emit('connect'); + } + this._onError(new Error('Error upgrading connection with STARTTLS'), 'ETLS', str, 'STARTTLS'); + return; + } + + this._upgradeConnection((err, secured) => { + if (err) { + this._onError(new Error('Error initiating TLS - ' + (err.message || err)), 'ETLS', false, 'STARTTLS'); + return; + } + + this.logger.info( + { + tnx: 'smtp' + }, + 'Connection upgraded with STARTTLS' + ); + + if (secured) { + // restart session + if (this.options.lmtp) { + this._responseActions.push(this._actionLHLO); + this._sendCommand('LHLO ' + this.name); + } else { + this._responseActions.push(this._actionEHLO); + this._sendCommand('EHLO ' + this.name); + } + } else { + this.emit('connect'); + } + }); + } + + /** + * Handle the response for AUTH LOGIN command. We are expecting + * '334 VXNlcm5hbWU6' (base64 for 'Username:'). Data to be sent as + * response needs to be base64 encoded username. We do not need + * exact match but settle with 334 response in general as some + * hosts invalidly use a longer message than VXNlcm5hbWU6 + * + * @param {String} str Message from the server + */ + _actionAUTH_LOGIN_USER(str, callback) { + if (!/^334[ -]/.test(str)) { + // expecting '334 VXNlcm5hbWU6' + callback(this._formatError('Invalid login sequence while waiting for "334 VXNlcm5hbWU6"', 'EAUTH', str, 'AUTH LOGIN')); + return; + } + + this._responseActions.push(str => { + this._actionAUTH_LOGIN_PASS(str, callback); + }); + + this._sendCommand(Buffer.from(this._auth.credentials.user + '', 'utf-8').toString('base64')); + } + + /** + * Handle the response for AUTH CRAM-MD5 command. We are expecting + * '334 '. Data to be sent as response needs to be + * base64 decoded challenge string, MD5 hashed using the password as + * a HMAC key, prefixed by the username and a space, and finally all + * base64 encoded again. + * + * @param {String} str Message from the server + */ + _actionAUTH_CRAM_MD5(str, callback) { + let challengeMatch = str.match(/^334\s+(.+)$/); + let challengeString = ''; + + if (!challengeMatch) { + return callback(this._formatError('Invalid login sequence while waiting for server challenge string', 'EAUTH', str, 'AUTH CRAM-MD5')); + } else { + challengeString = challengeMatch[1]; + } + + // Decode from base64 + let base64decoded = Buffer.from(challengeString, 'base64').toString('ascii'), + hmacMD5 = crypto.createHmac('md5', this._auth.credentials.pass); + + hmacMD5.update(base64decoded); + + let prepended = this._auth.credentials.user + ' ' + hmacMD5.digest('hex'); + + this._responseActions.push(str => { + this._actionAUTH_CRAM_MD5_PASS(str, callback); + }); + + this._sendCommand( + Buffer.from(prepended).toString('base64'), + // hidden hash for logs + Buffer.from(this._auth.credentials.user + ' /* secret */').toString('base64') + ); + } + + /** + * Handles the response to CRAM-MD5 authentication, if there's no error, + * the user can be considered logged in. Start waiting for a message to send + * + * @param {String} str Message from the server + */ + _actionAUTH_CRAM_MD5_PASS(str, callback) { + if (!str.match(/^235\s+/)) { + return callback(this._formatError('Invalid login sequence while waiting for "235"', 'EAUTH', str, 'AUTH CRAM-MD5')); + } + + this.logger.info( + { + tnx: 'smtp', + username: this._auth.user, + action: 'authenticated', + method: this._authMethod + }, + 'User %s authenticated', + JSON.stringify(this._auth.user) + ); + this.authenticated = true; + callback(null, true); + } + + /** + * Handle the response for AUTH LOGIN command. We are expecting + * '334 UGFzc3dvcmQ6' (base64 for 'Password:'). Data to be sent as + * response needs to be base64 encoded password. + * + * @param {String} str Message from the server + */ + _actionAUTH_LOGIN_PASS(str, callback) { + if (!/^334[ -]/.test(str)) { + // expecting '334 UGFzc3dvcmQ6' + return callback(this._formatError('Invalid login sequence while waiting for "334 UGFzc3dvcmQ6"', 'EAUTH', str, 'AUTH LOGIN')); + } + + this._responseActions.push(str => { + this._actionAUTHComplete(str, callback); + }); + + this._sendCommand( + Buffer.from((this._auth.credentials.pass || '').toString(), 'utf-8').toString('base64'), + // Hidden pass for logs + Buffer.from('/* secret */', 'utf-8').toString('base64') + ); + } + + /** + * Handles the response for authentication, if there's no error, + * the user can be considered logged in. Start waiting for a message to send + * + * @param {String} str Message from the server + */ + _actionAUTHComplete(str, isRetry, callback) { + if (!callback && typeof isRetry === 'function') { + callback = isRetry; + isRetry = false; + } + + if (str.substr(0, 3) === '334') { + this._responseActions.push(str => { + if (isRetry || this._authMethod !== 'XOAUTH2') { + this._actionAUTHComplete(str, true, callback); + } else { + // fetch a new OAuth2 access token + setImmediate(() => this._handleXOauth2Token(true, callback)); + } + }); + this._sendCommand(''); + return; + } + + if (str.charAt(0) !== '2') { + this.logger.info( + { + tnx: 'smtp', + username: this._auth.user, + action: 'authfail', + method: this._authMethod + }, + 'User %s failed to authenticate', + JSON.stringify(this._auth.user) + ); + return callback(this._formatError('Invalid login', 'EAUTH', str, 'AUTH ' + this._authMethod)); + } + + this.logger.info( + { + tnx: 'smtp', + username: this._auth.user, + action: 'authenticated', + method: this._authMethod + }, + 'User %s authenticated', + JSON.stringify(this._auth.user) + ); + this.authenticated = true; + callback(null, true); + } + + /** + * Handle response for a MAIL FROM: command + * + * @param {String} str Message from the server + */ + _actionMAIL(str, callback) { + let message, curRecipient; + if (Number(str.charAt(0)) !== 2) { + if (this._usingSmtpUtf8 && /^550 /.test(str) && /[\x80-\uFFFF]/.test(this._envelope.from)) { + message = 'Internationalized mailbox name not allowed'; + } else { + message = 'Mail command failed'; + } + return callback(this._formatError(message, 'EENVELOPE', str, 'MAIL FROM')); + } + + if (!this._envelope.rcptQueue.length) { + return callback(this._formatError('Can\x27t send mail - no recipients defined', 'EENVELOPE', false, 'API')); + } else { + this._recipientQueue = []; + + if (this._supportedExtensions.includes('PIPELINING')) { + while (this._envelope.rcptQueue.length) { + curRecipient = this._envelope.rcptQueue.shift(); + this._recipientQueue.push(curRecipient); + this._responseActions.push(str => { + this._actionRCPT(str, callback); + }); + this._sendCommand('RCPT TO:<' + curRecipient + '>' + this._getDsnRcptToArgs()); + } + } else { + curRecipient = this._envelope.rcptQueue.shift(); + this._recipientQueue.push(curRecipient); + this._responseActions.push(str => { + this._actionRCPT(str, callback); + }); + this._sendCommand('RCPT TO:<' + curRecipient + '>' + this._getDsnRcptToArgs()); + } + } + } + + /** + * Handle response for a RCPT TO: command + * + * @param {String} str Message from the server + */ + _actionRCPT(str, callback) { + let message, + err, + curRecipient = this._recipientQueue.shift(); + if (Number(str.charAt(0)) !== 2) { + // this is a soft error + if (this._usingSmtpUtf8 && /^553 /.test(str) && /[\x80-\uFFFF]/.test(curRecipient)) { + message = 'Internationalized mailbox name not allowed'; + } else { + message = 'Recipient command failed'; + } + this._envelope.rejected.push(curRecipient); + // store error for the failed recipient + err = this._formatError(message, 'EENVELOPE', str, 'RCPT TO'); + err.recipient = curRecipient; + this._envelope.rejectedErrors.push(err); + } else { + this._envelope.accepted.push(curRecipient); + } + + if (!this._envelope.rcptQueue.length && !this._recipientQueue.length) { + if (this._envelope.rejected.length < this._envelope.to.length) { + this._responseActions.push(str => { + this._actionDATA(str, callback); + }); + this._sendCommand('DATA'); + } else { + err = this._formatError('Can\x27t send mail - all recipients were rejected', 'EENVELOPE', str, 'RCPT TO'); + err.rejected = this._envelope.rejected; + err.rejectedErrors = this._envelope.rejectedErrors; + return callback(err); + } + } else if (this._envelope.rcptQueue.length) { + curRecipient = this._envelope.rcptQueue.shift(); + this._recipientQueue.push(curRecipient); + this._responseActions.push(str => { + this._actionRCPT(str, callback); + }); + this._sendCommand('RCPT TO:<' + curRecipient + '>' + this._getDsnRcptToArgs()); + } + } + + /** + * Handle response for a DATA command + * + * @param {String} str Message from the server + */ + _actionDATA(str, callback) { + // response should be 354 but according to this issue https://github.com/eleith/emailjs/issues/24 + // some servers might use 250 instead, so lets check for 2 or 3 as the first digit + if (!/^[23]/.test(str)) { + return callback(this._formatError('Data command failed', 'EENVELOPE', str, 'DATA')); + } + + let response = { + accepted: this._envelope.accepted, + rejected: this._envelope.rejected + }; + + if (this._ehloLines && this._ehloLines.length) { + response.ehlo = this._ehloLines; + } + + if (this._envelope.rejectedErrors.length) { + response.rejectedErrors = this._envelope.rejectedErrors; + } + + callback(null, response); + } + + /** + * Handle response for a DATA stream when using SMTP + * We expect a single response that defines if the sending succeeded or failed + * + * @param {String} str Message from the server + */ + _actionSMTPStream(str, callback) { + if (Number(str.charAt(0)) !== 2) { + // Message failed + return callback(this._formatError('Message failed', 'EMESSAGE', str, 'DATA')); + } else { + // Message sent succesfully + return callback(null, str); + } + } + + /** + * Handle response for a DATA stream + * We expect a separate response for every recipient. All recipients can either + * succeed or fail separately + * + * @param {String} recipient The recipient this response applies to + * @param {Boolean} final Is this the final recipient? + * @param {String} str Message from the server + */ + _actionLMTPStream(recipient, final, str, callback) { + let err; + if (Number(str.charAt(0)) !== 2) { + // Message failed + err = this._formatError('Message failed for recipient ' + recipient, 'EMESSAGE', str, 'DATA'); + err.recipient = recipient; + this._envelope.rejected.push(recipient); + this._envelope.rejectedErrors.push(err); + for (let i = 0, len = this._envelope.accepted.length; i < len; i++) { + if (this._envelope.accepted[i] === recipient) { + this._envelope.accepted.splice(i, 1); + } + } + } + if (final) { + return callback(null, str); + } + } + + _handleXOauth2Token(isRetry, callback) { + this._auth.oauth2.getToken(isRetry, (err, accessToken) => { + if (err) { + this.logger.info( + { + tnx: 'smtp', + username: this._auth.user, + action: 'authfail', + method: this._authMethod + }, + 'User %s failed to authenticate', + JSON.stringify(this._auth.user) + ); + return callback(this._formatError(err, 'EAUTH', false, 'AUTH XOAUTH2')); + } + this._responseActions.push(str => { + this._actionAUTHComplete(str, isRetry, callback); + }); + this._sendCommand( + 'AUTH XOAUTH2 ' + this._auth.oauth2.buildXOAuth2Token(accessToken), + // Hidden for logs + 'AUTH XOAUTH2 ' + this._auth.oauth2.buildXOAuth2Token('/* secret */') + ); + }); + } + + /** + * + * @param {string} command + * @private + */ + _isDestroyedMessage(command) { + if (this._destroyed) { + return 'Cannot ' + command + ' - smtp connection is already destroyed.'; + } + + if (this._socket) { + if (this._socket.destroyed) { + return 'Cannot ' + command + ' - smtp connection socket is already destroyed.'; + } + + if (!this._socket.writable) { + return 'Cannot ' + command + ' - smtp connection socket is already half-closed.'; + } + } + } + + _getHostname() { + // defaul hostname is machine hostname or [IP] + let defaultHostname; + try { + defaultHostname = os.hostname() || ''; + } catch (err) { + // fails on windows 7 + defaultHostname = 'localhost'; + } + + // ignore if not FQDN + if (!defaultHostname || defaultHostname.indexOf('.') < 0) { + defaultHostname = '[127.0.0.1]'; + } + + // IP should be enclosed in [] + if (defaultHostname.match(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/)) { + defaultHostname = '[' + defaultHostname + ']'; + } + + return defaultHostname; + } +} + +module.exports = SMTPConnection; diff --git a/system/login/node_modules/nodemailer/lib/smtp-pool/index.js b/system/login/node_modules/nodemailer/lib/smtp-pool/index.js new file mode 100644 index 0000000..6a5d309 --- /dev/null +++ b/system/login/node_modules/nodemailer/lib/smtp-pool/index.js @@ -0,0 +1,648 @@ +'use strict'; + +const EventEmitter = require('events'); +const PoolResource = require('./pool-resource'); +const SMTPConnection = require('../smtp-connection'); +const wellKnown = require('../well-known'); +const shared = require('../shared'); +const packageData = require('../../package.json'); + +/** + * Creates a SMTP pool transport object for Nodemailer + * + * @constructor + * @param {Object} options SMTP Connection options + */ +class SMTPPool extends EventEmitter { + constructor(options) { + super(); + + options = options || {}; + if (typeof options === 'string') { + options = { + url: options + }; + } + + let urlData; + let service = options.service; + + if (typeof options.getSocket === 'function') { + this.getSocket = options.getSocket; + } + + if (options.url) { + urlData = shared.parseConnectionUrl(options.url); + service = service || urlData.service; + } + + this.options = shared.assign( + false, // create new object + options, // regular options + urlData, // url options + service && wellKnown(service) // wellknown options + ); + + this.options.maxConnections = this.options.maxConnections || 5; + this.options.maxMessages = this.options.maxMessages || 100; + + this.logger = shared.getLogger(this.options, { + component: this.options.component || 'smtp-pool' + }); + + // temporary object + let connection = new SMTPConnection(this.options); + + this.name = 'SMTP (pool)'; + this.version = packageData.version + '[client:' + connection.version + ']'; + + this._rateLimit = { + counter: 0, + timeout: null, + waiting: [], + checkpoint: false, + delta: Number(this.options.rateDelta) || 1000, + limit: Number(this.options.rateLimit) || 0 + }; + this._closed = false; + this._queue = []; + this._connections = []; + this._connectionCounter = 0; + + this.idling = true; + + setImmediate(() => { + if (this.idling) { + this.emit('idle'); + } + }); + } + + /** + * Placeholder function for creating proxy sockets. This method immediatelly returns + * without a socket + * + * @param {Object} options Connection options + * @param {Function} callback Callback function to run with the socket keys + */ + getSocket(options, callback) { + // return immediatelly + return setImmediate(() => callback(null, false)); + } + + /** + * Queues an e-mail to be sent using the selected settings + * + * @param {Object} mail Mail object + * @param {Function} callback Callback function + */ + send(mail, callback) { + if (this._closed) { + return false; + } + + this._queue.push({ + mail, + requeueAttempts: 0, + callback + }); + + if (this.idling && this._queue.length >= this.options.maxConnections) { + this.idling = false; + } + + setImmediate(() => this._processMessages()); + + return true; + } + + /** + * Closes all connections in the pool. If there is a message being sent, the connection + * is closed later + */ + close() { + let connection; + let len = this._connections.length; + this._closed = true; + + // clear rate limit timer if it exists + clearTimeout(this._rateLimit.timeout); + + if (!len && !this._queue.length) { + return; + } + + // remove all available connections + for (let i = len - 1; i >= 0; i--) { + if (this._connections[i] && this._connections[i].available) { + connection = this._connections[i]; + connection.close(); + this.logger.info( + { + tnx: 'connection', + cid: connection.id, + action: 'removed' + }, + 'Connection #%s removed', + connection.id + ); + } + } + + if (len && !this._connections.length) { + this.logger.debug( + { + tnx: 'connection' + }, + 'All connections removed' + ); + } + + if (!this._queue.length) { + return; + } + + // make sure that entire queue would be cleaned + let invokeCallbacks = () => { + if (!this._queue.length) { + this.logger.debug( + { + tnx: 'connection' + }, + 'Pending queue entries cleared' + ); + return; + } + let entry = this._queue.shift(); + if (entry && typeof entry.callback === 'function') { + try { + entry.callback(new Error('Connection pool was closed')); + } catch (E) { + this.logger.error( + { + err: E, + tnx: 'callback', + cid: connection.id + }, + 'Callback error for #%s: %s', + connection.id, + E.message + ); + } + } + setImmediate(invokeCallbacks); + }; + setImmediate(invokeCallbacks); + } + + /** + * Check the queue and available connections. If there is a message to be sent and there is + * an available connection, then use this connection to send the mail + */ + _processMessages() { + let connection; + let i, len; + + // do nothing if already closed + if (this._closed) { + return; + } + + // do nothing if queue is empty + if (!this._queue.length) { + if (!this.idling) { + // no pending jobs + this.idling = true; + this.emit('idle'); + } + return; + } + + // find first available connection + for (i = 0, len = this._connections.length; i < len; i++) { + if (this._connections[i].available) { + connection = this._connections[i]; + break; + } + } + + if (!connection && this._connections.length < this.options.maxConnections) { + connection = this._createConnection(); + } + + if (!connection) { + // no more free connection slots available + this.idling = false; + return; + } + + // check if there is free space in the processing queue + if (!this.idling && this._queue.length < this.options.maxConnections) { + this.idling = true; + this.emit('idle'); + } + + let entry = (connection.queueEntry = this._queue.shift()); + entry.messageId = (connection.queueEntry.mail.message.getHeader('message-id') || '').replace(/[<>\s]/g, ''); + + connection.available = false; + + this.logger.debug( + { + tnx: 'pool', + cid: connection.id, + messageId: entry.messageId, + action: 'assign' + }, + 'Assigned message <%s> to #%s (%s)', + entry.messageId, + connection.id, + connection.messages + 1 + ); + + if (this._rateLimit.limit) { + this._rateLimit.counter++; + if (!this._rateLimit.checkpoint) { + this._rateLimit.checkpoint = Date.now(); + } + } + + connection.send(entry.mail, (err, info) => { + // only process callback if current handler is not changed + if (entry === connection.queueEntry) { + try { + entry.callback(err, info); + } catch (E) { + this.logger.error( + { + err: E, + tnx: 'callback', + cid: connection.id + }, + 'Callback error for #%s: %s', + connection.id, + E.message + ); + } + connection.queueEntry = false; + } + }); + } + + /** + * Creates a new pool resource + */ + _createConnection() { + let connection = new PoolResource(this); + + connection.id = ++this._connectionCounter; + + this.logger.info( + { + tnx: 'pool', + cid: connection.id, + action: 'conection' + }, + 'Created new pool resource #%s', + connection.id + ); + + // resource comes available + connection.on('available', () => { + this.logger.debug( + { + tnx: 'connection', + cid: connection.id, + action: 'available' + }, + 'Connection #%s became available', + connection.id + ); + + if (this._closed) { + // if already closed run close() that will remove this connections from connections list + this.close(); + } else { + // check if there's anything else to send + this._processMessages(); + } + }); + + // resource is terminated with an error + connection.once('error', err => { + if (err.code !== 'EMAXLIMIT') { + this.logger.error( + { + err, + tnx: 'pool', + cid: connection.id + }, + 'Pool Error for #%s: %s', + connection.id, + err.message + ); + } else { + this.logger.debug( + { + tnx: 'pool', + cid: connection.id, + action: 'maxlimit' + }, + 'Max messages limit exchausted for #%s', + connection.id + ); + } + + if (connection.queueEntry) { + try { + connection.queueEntry.callback(err); + } catch (E) { + this.logger.error( + { + err: E, + tnx: 'callback', + cid: connection.id + }, + 'Callback error for #%s: %s', + connection.id, + E.message + ); + } + connection.queueEntry = false; + } + + // remove the erroneus connection from connections list + this._removeConnection(connection); + + this._continueProcessing(); + }); + + connection.once('close', () => { + this.logger.info( + { + tnx: 'connection', + cid: connection.id, + action: 'closed' + }, + 'Connection #%s was closed', + connection.id + ); + + this._removeConnection(connection); + + if (connection.queueEntry) { + // If the connection closed when sending, add the message to the queue again + // if max number of requeues is not reached yet + // Note that we must wait a bit.. because the callback of the 'error' handler might be called + // in the next event loop + setTimeout(() => { + if (connection.queueEntry) { + if (this._shouldRequeuOnConnectionClose(connection.queueEntry)) { + this._requeueEntryOnConnectionClose(connection); + } else { + this._failDeliveryOnConnectionClose(connection); + } + } + this._continueProcessing(); + }, 50); + } else { + this._continueProcessing(); + } + }); + + this._connections.push(connection); + + return connection; + } + + _shouldRequeuOnConnectionClose(queueEntry) { + if (this.options.maxRequeues === undefined || this.options.maxRequeues < 0) { + return true; + } + + return queueEntry.requeueAttempts < this.options.maxRequeues; + } + + _failDeliveryOnConnectionClose(connection) { + if (connection.queueEntry && connection.queueEntry.callback) { + try { + connection.queueEntry.callback(new Error('Reached maximum number of retries after connection was closed')); + } catch (E) { + this.logger.error( + { + err: E, + tnx: 'callback', + messageId: connection.queueEntry.messageId, + cid: connection.id + }, + 'Callback error for #%s: %s', + connection.id, + E.message + ); + } + connection.queueEntry = false; + } + } + + _requeueEntryOnConnectionClose(connection) { + connection.queueEntry.requeueAttempts = connection.queueEntry.requeueAttempts + 1; + this.logger.debug( + { + tnx: 'pool', + cid: connection.id, + messageId: connection.queueEntry.messageId, + action: 'requeue' + }, + 'Re-queued message <%s> for #%s. Attempt: #%s', + connection.queueEntry.messageId, + connection.id, + connection.queueEntry.requeueAttempts + ); + this._queue.unshift(connection.queueEntry); + connection.queueEntry = false; + } + + /** + * Continue to process message if the pool hasn't closed + */ + _continueProcessing() { + if (this._closed) { + this.close(); + } else { + setTimeout(() => this._processMessages(), 100); + } + } + + /** + * Remove resource from pool + * + * @param {Object} connection The PoolResource to remove + */ + _removeConnection(connection) { + let index = this._connections.indexOf(connection); + + if (index !== -1) { + this._connections.splice(index, 1); + } + } + + /** + * Checks if connections have hit current rate limit and if so, queues the availability callback + * + * @param {Function} callback Callback function to run once rate limiter has been cleared + */ + _checkRateLimit(callback) { + if (!this._rateLimit.limit) { + return callback(); + } + + let now = Date.now(); + + if (this._rateLimit.counter < this._rateLimit.limit) { + return callback(); + } + + this._rateLimit.waiting.push(callback); + + if (this._rateLimit.checkpoint <= now - this._rateLimit.delta) { + return this._clearRateLimit(); + } else if (!this._rateLimit.timeout) { + this._rateLimit.timeout = setTimeout(() => this._clearRateLimit(), this._rateLimit.delta - (now - this._rateLimit.checkpoint)); + this._rateLimit.checkpoint = now; + } + } + + /** + * Clears current rate limit limitation and runs paused callback + */ + _clearRateLimit() { + clearTimeout(this._rateLimit.timeout); + this._rateLimit.timeout = null; + this._rateLimit.counter = 0; + this._rateLimit.checkpoint = false; + + // resume all paused connections + while (this._rateLimit.waiting.length) { + let cb = this._rateLimit.waiting.shift(); + setImmediate(cb); + } + } + + /** + * Returns true if there are free slots in the queue + */ + isIdle() { + return this.idling; + } + + /** + * Verifies SMTP configuration + * + * @param {Function} callback Callback function + */ + verify(callback) { + let promise; + + if (!callback) { + promise = new Promise((resolve, reject) => { + callback = shared.callbackPromise(resolve, reject); + }); + } + + let auth = new PoolResource(this).auth; + + this.getSocket(this.options, (err, socketOptions) => { + if (err) { + return callback(err); + } + + let options = this.options; + if (socketOptions && socketOptions.connection) { + this.logger.info( + { + tnx: 'proxy', + remoteAddress: socketOptions.connection.remoteAddress, + remotePort: socketOptions.connection.remotePort, + destHost: options.host || '', + destPort: options.port || '', + action: 'connected' + }, + 'Using proxied socket from %s:%s to %s:%s', + socketOptions.connection.remoteAddress, + socketOptions.connection.remotePort, + options.host || '', + options.port || '' + ); + options = shared.assign(false, options); + Object.keys(socketOptions).forEach(key => { + options[key] = socketOptions[key]; + }); + } + + let connection = new SMTPConnection(options); + let returned = false; + + connection.once('error', err => { + if (returned) { + return; + } + returned = true; + connection.close(); + return callback(err); + }); + + connection.once('end', () => { + if (returned) { + return; + } + returned = true; + return callback(new Error('Connection closed')); + }); + + let finalize = () => { + if (returned) { + return; + } + returned = true; + connection.quit(); + return callback(null, true); + }; + + connection.connect(() => { + if (returned) { + return; + } + + if (auth && (connection.allowsAuth || options.forceAuth)) { + connection.login(auth, err => { + if (returned) { + return; + } + + if (err) { + returned = true; + connection.close(); + return callback(err); + } + + finalize(); + }); + } else if (!auth && connection.allowsAuth && options.forceAuth) { + let err = new Error('Authentication info was not provided'); + err.code = 'NoAuth'; + + returned = true; + connection.close(); + return callback(err); + } else { + finalize(); + } + }); + }); + + return promise; + } +} + +// expose to the world +module.exports = SMTPPool; diff --git a/system/login/node_modules/nodemailer/lib/smtp-pool/pool-resource.js b/system/login/node_modules/nodemailer/lib/smtp-pool/pool-resource.js new file mode 100644 index 0000000..d67cc5c --- /dev/null +++ b/system/login/node_modules/nodemailer/lib/smtp-pool/pool-resource.js @@ -0,0 +1,253 @@ +'use strict'; + +const SMTPConnection = require('../smtp-connection'); +const assign = require('../shared').assign; +const XOAuth2 = require('../xoauth2'); +const EventEmitter = require('events'); + +/** + * Creates an element for the pool + * + * @constructor + * @param {Object} options SMTPPool instance + */ +class PoolResource extends EventEmitter { + constructor(pool) { + super(); + + this.pool = pool; + this.options = pool.options; + this.logger = this.pool.logger; + + if (this.options.auth) { + switch ((this.options.auth.type || '').toString().toUpperCase()) { + case 'OAUTH2': { + let oauth2 = new XOAuth2(this.options.auth, this.logger); + oauth2.provisionCallback = (this.pool.mailer && this.pool.mailer.get('oauth2_provision_cb')) || oauth2.provisionCallback; + this.auth = { + type: 'OAUTH2', + user: this.options.auth.user, + oauth2, + method: 'XOAUTH2' + }; + oauth2.on('token', token => this.pool.mailer.emit('token', token)); + oauth2.on('error', err => this.emit('error', err)); + break; + } + default: + if (!this.options.auth.user && !this.options.auth.pass) { + break; + } + this.auth = { + type: (this.options.auth.type || '').toString().toUpperCase() || 'LOGIN', + user: this.options.auth.user, + credentials: { + user: this.options.auth.user || '', + pass: this.options.auth.pass, + options: this.options.auth.options + }, + method: (this.options.auth.method || '').trim().toUpperCase() || this.options.authMethod || false + }; + } + } + + this._connection = false; + this._connected = false; + + this.messages = 0; + this.available = true; + } + + /** + * Initiates a connection to the SMTP server + * + * @param {Function} callback Callback function to run once the connection is established or failed + */ + connect(callback) { + this.pool.getSocket(this.options, (err, socketOptions) => { + if (err) { + return callback(err); + } + + let returned = false; + let options = this.options; + if (socketOptions && socketOptions.connection) { + this.logger.info( + { + tnx: 'proxy', + remoteAddress: socketOptions.connection.remoteAddress, + remotePort: socketOptions.connection.remotePort, + destHost: options.host || '', + destPort: options.port || '', + action: 'connected' + }, + 'Using proxied socket from %s:%s to %s:%s', + socketOptions.connection.remoteAddress, + socketOptions.connection.remotePort, + options.host || '', + options.port || '' + ); + + options = assign(false, options); + Object.keys(socketOptions).forEach(key => { + options[key] = socketOptions[key]; + }); + } + + this.connection = new SMTPConnection(options); + + this.connection.once('error', err => { + this.emit('error', err); + if (returned) { + return; + } + returned = true; + return callback(err); + }); + + this.connection.once('end', () => { + this.close(); + if (returned) { + return; + } + returned = true; + + let timer = setTimeout(() => { + if (returned) { + return; + } + // still have not returned, this means we have an unexpected connection close + let err = new Error('Unexpected socket close'); + if (this.connection && this.connection._socket && this.connection._socket.upgrading) { + // starttls connection errors + err.code = 'ETLS'; + } + callback(err); + }, 1000); + + try { + timer.unref(); + } catch (E) { + // Ignore. Happens on envs with non-node timer implementation + } + }); + + this.connection.connect(() => { + if (returned) { + return; + } + + if (this.auth && (this.connection.allowsAuth || options.forceAuth)) { + this.connection.login(this.auth, err => { + if (returned) { + return; + } + returned = true; + + if (err) { + this.connection.close(); + this.emit('error', err); + return callback(err); + } + + this._connected = true; + callback(null, true); + }); + } else { + returned = true; + this._connected = true; + return callback(null, true); + } + }); + }); + } + + /** + * Sends an e-mail to be sent using the selected settings + * + * @param {Object} mail Mail object + * @param {Function} callback Callback function + */ + send(mail, callback) { + if (!this._connected) { + return this.connect(err => { + if (err) { + return callback(err); + } + return this.send(mail, callback); + }); + } + + let envelope = mail.message.getEnvelope(); + let messageId = mail.message.messageId(); + + let recipients = [].concat(envelope.to || []); + if (recipients.length > 3) { + recipients.push('...and ' + recipients.splice(2).length + ' more'); + } + this.logger.info( + { + tnx: 'send', + messageId, + cid: this.id + }, + 'Sending message %s using #%s to <%s>', + messageId, + this.id, + recipients.join(', ') + ); + + if (mail.data.dsn) { + envelope.dsn = mail.data.dsn; + } + + this.connection.send(envelope, mail.message.createReadStream(), (err, info) => { + this.messages++; + + if (err) { + this.connection.close(); + this.emit('error', err); + return callback(err); + } + + info.envelope = { + from: envelope.from, + to: envelope.to + }; + info.messageId = messageId; + + setImmediate(() => { + let err; + if (this.messages >= this.options.maxMessages) { + err = new Error('Resource exhausted'); + err.code = 'EMAXLIMIT'; + this.connection.close(); + this.emit('error', err); + } else { + this.pool._checkRateLimit(() => { + this.available = true; + this.emit('available'); + }); + } + }); + + callback(null, info); + }); + } + + /** + * Closes the connection + */ + close() { + this._connected = false; + if (this.auth && this.auth.oauth2) { + this.auth.oauth2.removeAllListeners(); + } + if (this.connection) { + this.connection.close(); + } + this.emit('close'); + } +} + +module.exports = PoolResource; diff --git a/system/login/node_modules/nodemailer/lib/smtp-transport/index.js b/system/login/node_modules/nodemailer/lib/smtp-transport/index.js new file mode 100644 index 0000000..a1c45a5 --- /dev/null +++ b/system/login/node_modules/nodemailer/lib/smtp-transport/index.js @@ -0,0 +1,416 @@ +'use strict'; + +const EventEmitter = require('events'); +const SMTPConnection = require('../smtp-connection'); +const wellKnown = require('../well-known'); +const shared = require('../shared'); +const XOAuth2 = require('../xoauth2'); +const packageData = require('../../package.json'); + +/** + * Creates a SMTP transport object for Nodemailer + * + * @constructor + * @param {Object} options Connection options + */ +class SMTPTransport extends EventEmitter { + constructor(options) { + super(); + + options = options || {}; + + if (typeof options === 'string') { + options = { + url: options + }; + } + + let urlData; + let service = options.service; + + if (typeof options.getSocket === 'function') { + this.getSocket = options.getSocket; + } + + if (options.url) { + urlData = shared.parseConnectionUrl(options.url); + service = service || urlData.service; + } + + this.options = shared.assign( + false, // create new object + options, // regular options + urlData, // url options + service && wellKnown(service) // wellknown options + ); + + this.logger = shared.getLogger(this.options, { + component: this.options.component || 'smtp-transport' + }); + + // temporary object + let connection = new SMTPConnection(this.options); + + this.name = 'SMTP'; + this.version = packageData.version + '[client:' + connection.version + ']'; + + if (this.options.auth) { + this.auth = this.getAuth({}); + } + } + + /** + * Placeholder function for creating proxy sockets. This method immediatelly returns + * without a socket + * + * @param {Object} options Connection options + * @param {Function} callback Callback function to run with the socket keys + */ + getSocket(options, callback) { + // return immediatelly + return setImmediate(() => callback(null, false)); + } + + getAuth(authOpts) { + if (!authOpts) { + return this.auth; + } + + let hasAuth = false; + let authData = {}; + + if (this.options.auth && typeof this.options.auth === 'object') { + Object.keys(this.options.auth).forEach(key => { + hasAuth = true; + authData[key] = this.options.auth[key]; + }); + } + + if (authOpts && typeof authOpts === 'object') { + Object.keys(authOpts).forEach(key => { + hasAuth = true; + authData[key] = authOpts[key]; + }); + } + + if (!hasAuth) { + return false; + } + + switch ((authData.type || '').toString().toUpperCase()) { + case 'OAUTH2': { + if (!authData.service && !authData.user) { + return false; + } + let oauth2 = new XOAuth2(authData, this.logger); + oauth2.provisionCallback = (this.mailer && this.mailer.get('oauth2_provision_cb')) || oauth2.provisionCallback; + oauth2.on('token', token => this.mailer.emit('token', token)); + oauth2.on('error', err => this.emit('error', err)); + return { + type: 'OAUTH2', + user: authData.user, + oauth2, + method: 'XOAUTH2' + }; + } + default: + return { + type: (authData.type || '').toString().toUpperCase() || 'LOGIN', + user: authData.user, + credentials: { + user: authData.user || '', + pass: authData.pass, + options: authData.options + }, + method: (authData.method || '').trim().toUpperCase() || this.options.authMethod || false + }; + } + } + + /** + * Sends an e-mail using the selected settings + * + * @param {Object} mail Mail object + * @param {Function} callback Callback function + */ + send(mail, callback) { + this.getSocket(this.options, (err, socketOptions) => { + if (err) { + return callback(err); + } + + let returned = false; + let options = this.options; + if (socketOptions && socketOptions.connection) { + this.logger.info( + { + tnx: 'proxy', + remoteAddress: socketOptions.connection.remoteAddress, + remotePort: socketOptions.connection.remotePort, + destHost: options.host || '', + destPort: options.port || '', + action: 'connected' + }, + 'Using proxied socket from %s:%s to %s:%s', + socketOptions.connection.remoteAddress, + socketOptions.connection.remotePort, + options.host || '', + options.port || '' + ); + + // only copy options if we need to modify it + options = shared.assign(false, options); + Object.keys(socketOptions).forEach(key => { + options[key] = socketOptions[key]; + }); + } + + let connection = new SMTPConnection(options); + + connection.once('error', err => { + if (returned) { + return; + } + returned = true; + connection.close(); + return callback(err); + }); + + connection.once('end', () => { + if (returned) { + return; + } + + let timer = setTimeout(() => { + if (returned) { + return; + } + returned = true; + // still have not returned, this means we have an unexpected connection close + let err = new Error('Unexpected socket close'); + if (connection && connection._socket && connection._socket.upgrading) { + // starttls connection errors + err.code = 'ETLS'; + } + callback(err); + }, 1000); + + try { + timer.unref(); + } catch (E) { + // Ignore. Happens on envs with non-node timer implementation + } + }); + + let sendMessage = () => { + let envelope = mail.message.getEnvelope(); + let messageId = mail.message.messageId(); + + let recipients = [].concat(envelope.to || []); + if (recipients.length > 3) { + recipients.push('...and ' + recipients.splice(2).length + ' more'); + } + + if (mail.data.dsn) { + envelope.dsn = mail.data.dsn; + } + + this.logger.info( + { + tnx: 'send', + messageId + }, + 'Sending message %s to <%s>', + messageId, + recipients.join(', ') + ); + + connection.send(envelope, mail.message.createReadStream(), (err, info) => { + returned = true; + connection.close(); + if (err) { + this.logger.error( + { + err, + tnx: 'send' + }, + 'Send error for %s: %s', + messageId, + err.message + ); + return callback(err); + } + info.envelope = { + from: envelope.from, + to: envelope.to + }; + info.messageId = messageId; + try { + return callback(null, info); + } catch (E) { + this.logger.error( + { + err: E, + tnx: 'callback' + }, + 'Callback error for %s: %s', + messageId, + E.message + ); + } + }); + }; + + connection.connect(() => { + if (returned) { + return; + } + + let auth = this.getAuth(mail.data.auth); + + if (auth && (connection.allowsAuth || options.forceAuth)) { + connection.login(auth, err => { + if (auth && auth !== this.auth && auth.oauth2) { + auth.oauth2.removeAllListeners(); + } + if (returned) { + return; + } + + if (err) { + returned = true; + connection.close(); + return callback(err); + } + + sendMessage(); + }); + } else { + sendMessage(); + } + }); + }); + } + + /** + * Verifies SMTP configuration + * + * @param {Function} callback Callback function + */ + verify(callback) { + let promise; + + if (!callback) { + promise = new Promise((resolve, reject) => { + callback = shared.callbackPromise(resolve, reject); + }); + } + + this.getSocket(this.options, (err, socketOptions) => { + if (err) { + return callback(err); + } + + let options = this.options; + if (socketOptions && socketOptions.connection) { + this.logger.info( + { + tnx: 'proxy', + remoteAddress: socketOptions.connection.remoteAddress, + remotePort: socketOptions.connection.remotePort, + destHost: options.host || '', + destPort: options.port || '', + action: 'connected' + }, + 'Using proxied socket from %s:%s to %s:%s', + socketOptions.connection.remoteAddress, + socketOptions.connection.remotePort, + options.host || '', + options.port || '' + ); + + options = shared.assign(false, options); + Object.keys(socketOptions).forEach(key => { + options[key] = socketOptions[key]; + }); + } + + let connection = new SMTPConnection(options); + let returned = false; + + connection.once('error', err => { + if (returned) { + return; + } + returned = true; + connection.close(); + return callback(err); + }); + + connection.once('end', () => { + if (returned) { + return; + } + returned = true; + return callback(new Error('Connection closed')); + }); + + let finalize = () => { + if (returned) { + return; + } + returned = true; + connection.quit(); + return callback(null, true); + }; + + connection.connect(() => { + if (returned) { + return; + } + + let authData = this.getAuth({}); + + if (authData && (connection.allowsAuth || options.forceAuth)) { + connection.login(authData, err => { + if (returned) { + return; + } + + if (err) { + returned = true; + connection.close(); + return callback(err); + } + + finalize(); + }); + } else if (!authData && connection.allowsAuth && options.forceAuth) { + let err = new Error('Authentication info was not provided'); + err.code = 'NoAuth'; + + returned = true; + connection.close(); + return callback(err); + } else { + finalize(); + } + }); + }); + + return promise; + } + + /** + * Releases resources + */ + close() { + if (this.auth && this.auth.oauth2) { + this.auth.oauth2.removeAllListeners(); + } + this.emit('close'); + } +} + +// expose to the world +module.exports = SMTPTransport; diff --git a/system/login/node_modules/nodemailer/lib/stream-transport/index.js b/system/login/node_modules/nodemailer/lib/stream-transport/index.js new file mode 100644 index 0000000..1921469 --- /dev/null +++ b/system/login/node_modules/nodemailer/lib/stream-transport/index.js @@ -0,0 +1,135 @@ +'use strict'; + +const packageData = require('../../package.json'); +const shared = require('../shared'); + +/** + * Generates a Transport object for streaming + * + * Possible options can be the following: + * + * * **buffer** if true, then returns the message as a Buffer object instead of a stream + * * **newline** either 'windows' or 'unix' + * + * @constructor + * @param {Object} optional config parameter + */ +class StreamTransport { + constructor(options) { + options = options || {}; + + this.options = options || {}; + + this.name = 'StreamTransport'; + this.version = packageData.version; + + this.logger = shared.getLogger(this.options, { + component: this.options.component || 'stream-transport' + }); + + this.winbreak = ['win', 'windows', 'dos', '\r\n'].includes((options.newline || '').toString().toLowerCase()); + } + + /** + * Compiles a mailcomposer message and forwards it to handler that sends it + * + * @param {Object} emailMessage MailComposer object + * @param {Function} callback Callback function to run when the sending is completed + */ + send(mail, done) { + // We probably need this in the output + mail.message.keepBcc = true; + + let envelope = mail.data.envelope || mail.message.getEnvelope(); + let messageId = mail.message.messageId(); + + let recipients = [].concat(envelope.to || []); + if (recipients.length > 3) { + recipients.push('...and ' + recipients.splice(2).length + ' more'); + } + this.logger.info( + { + tnx: 'send', + messageId + }, + 'Sending message %s to <%s> using %s line breaks', + messageId, + recipients.join(', '), + this.winbreak ? '' : '' + ); + + setImmediate(() => { + let stream; + + try { + stream = mail.message.createReadStream(); + } catch (E) { + this.logger.error( + { + err: E, + tnx: 'send', + messageId + }, + 'Creating send stream failed for %s. %s', + messageId, + E.message + ); + return done(E); + } + + if (!this.options.buffer) { + stream.once('error', err => { + this.logger.error( + { + err, + tnx: 'send', + messageId + }, + 'Failed creating message for %s. %s', + messageId, + err.message + ); + }); + return done(null, { + envelope: mail.data.envelope || mail.message.getEnvelope(), + messageId, + message: stream + }); + } + + let chunks = []; + let chunklen = 0; + stream.on('readable', () => { + let chunk; + while ((chunk = stream.read()) !== null) { + chunks.push(chunk); + chunklen += chunk.length; + } + }); + + stream.once('error', err => { + this.logger.error( + { + err, + tnx: 'send', + messageId + }, + 'Failed creating message for %s. %s', + messageId, + err.message + ); + return done(err); + }); + + stream.on('end', () => + done(null, { + envelope: mail.data.envelope || mail.message.getEnvelope(), + messageId, + message: Buffer.concat(chunks, chunklen) + }) + ); + }); + } +} + +module.exports = StreamTransport; diff --git a/system/login/node_modules/nodemailer/lib/well-known/index.js b/system/login/node_modules/nodemailer/lib/well-known/index.js new file mode 100644 index 0000000..9fdc28f --- /dev/null +++ b/system/login/node_modules/nodemailer/lib/well-known/index.js @@ -0,0 +1,47 @@ +'use strict'; + +const services = require('./services.json'); +const normalized = {}; + +Object.keys(services).forEach(key => { + let service = services[key]; + + normalized[normalizeKey(key)] = normalizeService(service); + + [].concat(service.aliases || []).forEach(alias => { + normalized[normalizeKey(alias)] = normalizeService(service); + }); + + [].concat(service.domains || []).forEach(domain => { + normalized[normalizeKey(domain)] = normalizeService(service); + }); +}); + +function normalizeKey(key) { + return key.replace(/[^a-zA-Z0-9.-]/g, '').toLowerCase(); +} + +function normalizeService(service) { + let filter = ['domains', 'aliases']; + let response = {}; + + Object.keys(service).forEach(key => { + if (filter.indexOf(key) < 0) { + response[key] = service[key]; + } + }); + + return response; +} + +/** + * Resolves SMTP config for given key. Key can be a name (like 'Gmail'), alias (like 'Google Mail') or + * an email address (like 'test@googlemail.com'). + * + * @param {String} key [description] + * @returns {Object} SMTP config or false if not found + */ +module.exports = function (key) { + key = normalizeKey(key.split('@').pop()); + return normalized[key] || false; +}; diff --git a/system/login/node_modules/nodemailer/lib/well-known/services.json b/system/login/node_modules/nodemailer/lib/well-known/services.json new file mode 100644 index 0000000..5048f7b --- /dev/null +++ b/system/login/node_modules/nodemailer/lib/well-known/services.json @@ -0,0 +1,338 @@ +{ + "1und1": { + "host": "smtp.1und1.de", + "port": 465, + "secure": true, + "authMethod": "LOGIN" + }, + + "Aliyun": { + "domains": ["aliyun.com"], + "host": "smtp.aliyun.com", + "port": 465, + "secure": true + }, + + "AOL": { + "domains": ["aol.com"], + "host": "smtp.aol.com", + "port": 587 + }, + + "Bluewin": { + "host": "smtpauths.bluewin.ch", + "domains": ["bluewin.ch"], + "port": 465 + }, + + "DebugMail": { + "host": "debugmail.io", + "port": 25 + }, + + "DynectEmail": { + "aliases": ["Dynect"], + "host": "smtp.dynect.net", + "port": 25 + }, + + "Ethereal": { + "aliases": ["ethereal.email"], + "host": "smtp.ethereal.email", + "port": 587 + }, + + "FastMail": { + "domains": ["fastmail.fm"], + "host": "smtp.fastmail.com", + "port": 465, + "secure": true + }, + + "Forward Email": { + "aliases": ["FE", "ForwardEmail"], + "domains": ["forwardemail.net"], + "host": "smtp.forwardemail.net", + "port": 465, + "secure": true + }, + + "GandiMail": { + "aliases": ["Gandi", "Gandi Mail"], + "host": "mail.gandi.net", + "port": 587 + }, + + "Gmail": { + "aliases": ["Google Mail"], + "domains": ["gmail.com", "googlemail.com"], + "host": "smtp.gmail.com", + "port": 465, + "secure": true + }, + + "Godaddy": { + "host": "smtpout.secureserver.net", + "port": 25 + }, + + "GodaddyAsia": { + "host": "smtp.asia.secureserver.net", + "port": 25 + }, + + "GodaddyEurope": { + "host": "smtp.europe.secureserver.net", + "port": 25 + }, + + "hot.ee": { + "host": "mail.hot.ee" + }, + + "Hotmail": { + "aliases": ["Outlook", "Outlook.com", "Hotmail.com"], + "domains": ["hotmail.com", "outlook.com"], + "host": "smtp-mail.outlook.com", + "port": 587 + }, + + "iCloud": { + "aliases": ["Me", "Mac"], + "domains": ["me.com", "mac.com"], + "host": "smtp.mail.me.com", + "port": 587 + }, + + "Infomaniak": { + "host": "mail.infomaniak.com", + "domains": ["ik.me", "ikmail.com", "etik.com"], + "port": 587 + }, + + "mail.ee": { + "host": "smtp.mail.ee" + }, + + "Mail.ru": { + "host": "smtp.mail.ru", + "port": 465, + "secure": true + }, + + "Maildev": { + "port": 1025, + "ignoreTLS": true + }, + + "Mailgun": { + "host": "smtp.mailgun.org", + "port": 465, + "secure": true + }, + + "Mailjet": { + "host": "in.mailjet.com", + "port": 587 + }, + + "Mailosaur": { + "host": "mailosaur.io", + "port": 25 + }, + + "Mailtrap": { + "host": "smtp.mailtrap.io", + "port": 2525 + }, + + "Mandrill": { + "host": "smtp.mandrillapp.com", + "port": 587 + }, + + "Naver": { + "host": "smtp.naver.com", + "port": 587 + }, + + "One": { + "host": "send.one.com", + "port": 465, + "secure": true + }, + + "OpenMailBox": { + "aliases": ["OMB", "openmailbox.org"], + "host": "smtp.openmailbox.org", + "port": 465, + "secure": true + }, + + "Outlook365": { + "host": "smtp.office365.com", + "port": 587, + "secure": false + }, + + "OhMySMTP": { + "host": "smtp.ohmysmtp.com", + "port": 587, + "secure": false + }, + + "Postmark": { + "aliases": ["PostmarkApp"], + "host": "smtp.postmarkapp.com", + "port": 2525 + }, + + "qiye.aliyun": { + "host": "smtp.mxhichina.com", + "port": "465", + "secure": true + }, + + "QQ": { + "domains": ["qq.com"], + "host": "smtp.qq.com", + "port": 465, + "secure": true + }, + + "QQex": { + "aliases": ["QQ Enterprise"], + "domains": ["exmail.qq.com"], + "host": "smtp.exmail.qq.com", + "port": 465, + "secure": true + }, + + "SendCloud": { + "host": "smtp.sendcloud.net", + "port": 2525 + }, + + "SendGrid": { + "host": "smtp.sendgrid.net", + "port": 587 + }, + + "SendinBlue": { + "aliases": ["Brevo"], + "host": "smtp-relay.brevo.com", + "port": 587 + }, + + "SendPulse": { + "host": "smtp-pulse.com", + "port": 465, + "secure": true + }, + + "SES": { + "host": "email-smtp.us-east-1.amazonaws.com", + "port": 465, + "secure": true + }, + + "SES-US-EAST-1": { + "host": "email-smtp.us-east-1.amazonaws.com", + "port": 465, + "secure": true + }, + + "SES-US-WEST-2": { + "host": "email-smtp.us-west-2.amazonaws.com", + "port": 465, + "secure": true + }, + + "SES-EU-WEST-1": { + "host": "email-smtp.eu-west-1.amazonaws.com", + "port": 465, + "secure": true + }, + + "SES-AP-SOUTH-1": { + "host": "email-smtp.ap-south-1.amazonaws.com", + "port": 465, + "secure": true + }, + + "SES-AP-NORTHEAST-1": { + "host": "email-smtp.ap-northeast-1.amazonaws.com", + "port": 465, + "secure": true + }, + + "SES-AP-NORTHEAST-2": { + "host": "email-smtp.ap-northeast-2.amazonaws.com", + "port": 465, + "secure": true + }, + + "SES-AP-NORTHEAST-3": { + "host": "email-smtp.ap-northeast-3.amazonaws.com", + "port": 465, + "secure": true + }, + + "SES-AP-SOUTHEAST-1": { + "host": "email-smtp.ap-southeast-1.amazonaws.com", + "port": 465, + "secure": true + }, + + "SES-AP-SOUTHEAST-2": { + "host": "email-smtp.ap-southeast-2.amazonaws.com", + "port": 465, + "secure": true + }, + + "Sparkpost": { + "aliases": ["SparkPost", "SparkPost Mail"], + "domains": ["sparkpost.com"], + "host": "smtp.sparkpostmail.com", + "port": 587, + "secure": false + }, + + "Tipimail": { + "host": "smtp.tipimail.com", + "port": 587 + }, + + "Yahoo": { + "domains": ["yahoo.com"], + "host": "smtp.mail.yahoo.com", + "port": 465, + "secure": true + }, + + "Yandex": { + "domains": ["yandex.ru"], + "host": "smtp.yandex.ru", + "port": 465, + "secure": true + }, + + "Zoho": { + "host": "smtp.zoho.com", + "port": 465, + "secure": true, + "authMethod": "LOGIN" + }, + + "126": { + "host": "smtp.126.com", + "port": 465, + "secure": true + }, + + "163": { + "host": "smtp.163.com", + "port": 465, + "secure": true + } +} diff --git a/system/login/node_modules/nodemailer/lib/xoauth2/index.js b/system/login/node_modules/nodemailer/lib/xoauth2/index.js new file mode 100644 index 0000000..ed461df --- /dev/null +++ b/system/login/node_modules/nodemailer/lib/xoauth2/index.js @@ -0,0 +1,376 @@ +'use strict'; + +const Stream = require('stream').Stream; +const nmfetch = require('../fetch'); +const crypto = require('crypto'); +const shared = require('../shared'); + +/** + * XOAUTH2 access_token generator for Gmail. + * Create client ID for web applications in Google API console to use it. + * See Offline Access for receiving the needed refreshToken for an user + * https://developers.google.com/accounts/docs/OAuth2WebServer#offline + * + * Usage for generating access tokens with a custom method using provisionCallback: + * provisionCallback(user, renew, callback) + * * user is the username to get the token for + * * renew is a boolean that if true indicates that existing token failed and needs to be renewed + * * callback is the callback to run with (error, accessToken [, expires]) + * * accessToken is a string + * * expires is an optional expire time in milliseconds + * If provisionCallback is used, then Nodemailer does not try to attempt generating the token by itself + * + * @constructor + * @param {Object} options Client information for token generation + * @param {String} options.user User e-mail address + * @param {String} options.clientId Client ID value + * @param {String} options.clientSecret Client secret value + * @param {String} options.refreshToken Refresh token for an user + * @param {String} options.accessUrl Endpoint for token generation, defaults to 'https://accounts.google.com/o/oauth2/token' + * @param {String} options.accessToken An existing valid accessToken + * @param {String} options.privateKey Private key for JSW + * @param {Number} options.expires Optional Access Token expire time in ms + * @param {Number} options.timeout Optional TTL for Access Token in seconds + * @param {Function} options.provisionCallback Function to run when a new access token is required + */ +class XOAuth2 extends Stream { + constructor(options, logger) { + super(); + + this.options = options || {}; + + if (options && options.serviceClient) { + if (!options.privateKey || !options.user) { + setImmediate(() => this.emit('error', new Error('Options "privateKey" and "user" are required for service account!'))); + return; + } + + let serviceRequestTimeout = Math.min(Math.max(Number(this.options.serviceRequestTimeout) || 0, 0), 3600); + this.options.serviceRequestTimeout = serviceRequestTimeout || 5 * 60; + } + + this.logger = shared.getLogger( + { + logger + }, + { + component: this.options.component || 'OAuth2' + } + ); + + this.provisionCallback = typeof this.options.provisionCallback === 'function' ? this.options.provisionCallback : false; + + this.options.accessUrl = this.options.accessUrl || 'https://accounts.google.com/o/oauth2/token'; + this.options.customHeaders = this.options.customHeaders || {}; + this.options.customParams = this.options.customParams || {}; + + this.accessToken = this.options.accessToken || false; + + if (this.options.expires && Number(this.options.expires)) { + this.expires = this.options.expires; + } else { + let timeout = Math.max(Number(this.options.timeout) || 0, 0); + this.expires = (timeout && Date.now() + timeout * 1000) || 0; + } + } + + /** + * Returns or generates (if previous has expired) a XOAuth2 token + * + * @param {Boolean} renew If false then use cached access token (if available) + * @param {Function} callback Callback function with error object and token string + */ + getToken(renew, callback) { + if (!renew && this.accessToken && (!this.expires || this.expires > Date.now())) { + return callback(null, this.accessToken); + } + + let generateCallback = (...args) => { + if (args[0]) { + this.logger.error( + { + err: args[0], + tnx: 'OAUTH2', + user: this.options.user, + action: 'renew' + }, + 'Failed generating new Access Token for %s', + this.options.user + ); + } else { + this.logger.info( + { + tnx: 'OAUTH2', + user: this.options.user, + action: 'renew' + }, + 'Generated new Access Token for %s', + this.options.user + ); + } + callback(...args); + }; + + if (this.provisionCallback) { + this.provisionCallback(this.options.user, !!renew, (err, accessToken, expires) => { + if (!err && accessToken) { + this.accessToken = accessToken; + this.expires = expires || 0; + } + generateCallback(err, accessToken); + }); + } else { + this.generateToken(generateCallback); + } + } + + /** + * Updates token values + * + * @param {String} accessToken New access token + * @param {Number} timeout Access token lifetime in seconds + * + * Emits 'token': { user: User email-address, accessToken: the new accessToken, timeout: TTL in seconds} + */ + updateToken(accessToken, timeout) { + this.accessToken = accessToken; + timeout = Math.max(Number(timeout) || 0, 0); + this.expires = (timeout && Date.now() + timeout * 1000) || 0; + + this.emit('token', { + user: this.options.user, + accessToken: accessToken || '', + expires: this.expires + }); + } + + /** + * Generates a new XOAuth2 token with the credentials provided at initialization + * + * @param {Function} callback Callback function with error object and token string + */ + generateToken(callback) { + let urlOptions; + let loggedUrlOptions; + if (this.options.serviceClient) { + // service account - https://developers.google.com/identity/protocols/OAuth2ServiceAccount + let iat = Math.floor(Date.now() / 1000); // unix time + let tokenData = { + iss: this.options.serviceClient, + scope: this.options.scope || 'https://mail.google.com/', + sub: this.options.user, + aud: this.options.accessUrl, + iat, + exp: iat + this.options.serviceRequestTimeout + }; + let token; + try { + token = this.jwtSignRS256(tokenData); + } catch (err) { + return callback(new Error('Can\x27t generate token. Check your auth options')); + } + + urlOptions = { + grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', + assertion: token + }; + + loggedUrlOptions = { + grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', + assertion: tokenData + }; + } else { + if (!this.options.refreshToken) { + return callback(new Error('Can\x27t create new access token for user')); + } + + // web app - https://developers.google.com/identity/protocols/OAuth2WebServer + urlOptions = { + client_id: this.options.clientId || '', + client_secret: this.options.clientSecret || '', + refresh_token: this.options.refreshToken, + grant_type: 'refresh_token' + }; + + loggedUrlOptions = { + client_id: this.options.clientId || '', + client_secret: (this.options.clientSecret || '').substr(0, 6) + '...', + refresh_token: (this.options.refreshToken || '').substr(0, 6) + '...', + grant_type: 'refresh_token' + }; + } + + Object.keys(this.options.customParams).forEach(key => { + urlOptions[key] = this.options.customParams[key]; + loggedUrlOptions[key] = this.options.customParams[key]; + }); + + this.logger.debug( + { + tnx: 'OAUTH2', + user: this.options.user, + action: 'generate' + }, + 'Requesting token using: %s', + JSON.stringify(loggedUrlOptions) + ); + + this.postRequest(this.options.accessUrl, urlOptions, this.options, (error, body) => { + let data; + + if (error) { + return callback(error); + } + + try { + data = JSON.parse(body.toString()); + } catch (E) { + return callback(E); + } + + if (!data || typeof data !== 'object') { + this.logger.debug( + { + tnx: 'OAUTH2', + user: this.options.user, + action: 'post' + }, + 'Response: %s', + (body || '').toString() + ); + return callback(new Error('Invalid authentication response')); + } + + let logData = {}; + Object.keys(data).forEach(key => { + if (key !== 'access_token') { + logData[key] = data[key]; + } else { + logData[key] = (data[key] || '').toString().substr(0, 6) + '...'; + } + }); + + this.logger.debug( + { + tnx: 'OAUTH2', + user: this.options.user, + action: 'post' + }, + 'Response: %s', + JSON.stringify(logData) + ); + + if (data.error) { + // Error Response : https://tools.ietf.org/html/rfc6749#section-5.2 + let errorMessage = data.error; + if (data.error_description) { + errorMessage += ': ' + data.error_description; + } + if (data.error_uri) { + errorMessage += ' (' + data.error_uri + ')'; + } + return callback(new Error(errorMessage)); + } + + if (data.access_token) { + this.updateToken(data.access_token, data.expires_in); + return callback(null, this.accessToken); + } + + return callback(new Error('No access token')); + }); + } + + /** + * Converts an access_token and user id into a base64 encoded XOAuth2 token + * + * @param {String} [accessToken] Access token string + * @return {String} Base64 encoded token for IMAP or SMTP login + */ + buildXOAuth2Token(accessToken) { + let authData = ['user=' + (this.options.user || ''), 'auth=Bearer ' + (accessToken || this.accessToken), '', '']; + return Buffer.from(authData.join('\x01'), 'utf-8').toString('base64'); + } + + /** + * Custom POST request handler. + * This is only needed to keep paths short in Windows – usually this module + * is a dependency of a dependency and if it tries to require something + * like the request module the paths get way too long to handle for Windows. + * As we do only a simple POST request we do not actually require complicated + * logic support (no redirects, no nothing) anyway. + * + * @param {String} url Url to POST to + * @param {String|Buffer} payload Payload to POST + * @param {Function} callback Callback function with (err, buff) + */ + postRequest(url, payload, params, callback) { + let returned = false; + + let chunks = []; + let chunklen = 0; + + let req = nmfetch(url, { + method: 'post', + headers: params.customHeaders, + body: payload, + allowErrorResponse: true + }); + + req.on('readable', () => { + let chunk; + while ((chunk = req.read()) !== null) { + chunks.push(chunk); + chunklen += chunk.length; + } + }); + + req.once('error', err => { + if (returned) { + return; + } + returned = true; + return callback(err); + }); + + req.once('end', () => { + if (returned) { + return; + } + returned = true; + return callback(null, Buffer.concat(chunks, chunklen)); + }); + } + + /** + * Encodes a buffer or a string into Base64url format + * + * @param {Buffer|String} data The data to convert + * @return {String} The encoded string + */ + toBase64URL(data) { + if (typeof data === 'string') { + data = Buffer.from(data); + } + + return data + .toString('base64') + .replace(/[=]+/g, '') // remove '='s + .replace(/\+/g, '-') // '+' → '-' + .replace(/\//g, '_'); // '/' → '_' + } + + /** + * Creates a JSON Web Token signed with RS256 (SHA256 + RSA) + * + * @param {Object} payload The payload to include in the generated token + * @return {String} The generated and signed token + */ + jwtSignRS256(payload) { + payload = ['{"alg":"RS256","typ":"JWT"}', JSON.stringify(payload)].map(val => this.toBase64URL(val)).join('.'); + let signature = crypto.createSign('RSA-SHA256').update(payload).sign(this.options.privateKey); + return payload + '.' + this.toBase64URL(signature); + } +} + +module.exports = XOAuth2; diff --git a/system/login/node_modules/nodemailer/package.json b/system/login/node_modules/nodemailer/package.json new file mode 100644 index 0000000..c1fb6cc --- /dev/null +++ b/system/login/node_modules/nodemailer/package.json @@ -0,0 +1,47 @@ +{ + "name": "nodemailer", + "version": "6.9.7", + "description": "Easy as cake e-mail sending from your Node.js applications", + "main": "lib/nodemailer.js", + "scripts": { + "test": "grunt --trace-warnings", + "update": "rm -rf node_modules/ package-lock.json && ncu -u && npm install" + }, + "repository": { + "type": "git", + "url": "https://github.com/nodemailer/nodemailer.git" + }, + "keywords": [ + "Nodemailer" + ], + "author": "Andris Reinman", + "license": "MIT-0", + "bugs": { + "url": "https://github.com/nodemailer/nodemailer/issues" + }, + "homepage": "https://nodemailer.com/", + "devDependencies": { + "@aws-sdk/client-ses": "3.433.0", + "aws-sdk": "2.1478.0", + "bunyan": "1.8.15", + "chai": "4.3.10", + "eslint-config-nodemailer": "1.2.0", + "eslint-config-prettier": "9.0.0", + "grunt": "1.6.1", + "grunt-cli": "1.4.3", + "grunt-eslint": "24.3.0", + "grunt-mocha-test": "0.13.3", + "libbase64": "1.2.1", + "libmime": "5.2.1", + "libqp": "2.0.1", + "mocha": "10.2.0", + "nodemailer-ntlm-auth": "1.0.4", + "proxy": "1.0.2", + "proxy-test-server": "1.0.0", + "sinon": "17.0.0", + "smtp-server": "3.13.0" + }, + "engines": { + "node": ">=6.0.0" + } +}