pax_global_header00006660000000000000000000000064150362145520014515gustar00rootroot0000000000000052 comment=4b017af88f5375bbdf3ad2ee732d2c122e4f52b0 on-headers-1.1.0/000077500000000000000000000000001503621455200135415ustar00rootroot00000000000000on-headers-1.1.0/.eslintignore000066400000000000000000000000261503621455200162420ustar00rootroot00000000000000coverage node_modules on-headers-1.1.0/.eslintrc.yml000066400000000000000000000000771503621455200161710ustar00rootroot00000000000000root: true extends: standard rules: no-param-reassign: error on-headers-1.1.0/.github/000077500000000000000000000000001503621455200151015ustar00rootroot00000000000000on-headers-1.1.0/.github/dependabot.yml000066400000000000000000000005661503621455200177400ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: github-actions directory: / schedule: interval: monthly - package-ecosystem: npm directory: / schedule: interval: monthly time: "23:00" timezone: Europe/London open-pull-requests-limit: 10 ignore: - dependency-name: "*" update-types: ["version-update:semver-major"] on-headers-1.1.0/.github/workflows/000077500000000000000000000000001503621455200171365ustar00rootroot00000000000000on-headers-1.1.0/.github/workflows/ci.yml000066400000000000000000000141301503621455200202530ustar00rootroot00000000000000name: ci on: - pull_request - push permissions: contents: read jobs: test: permissions: checks: write # for coverallsapp/github-action to create new checks contents: read # for actions/checkout to fetch code runs-on: ubuntu-latest strategy: fail-fast: false matrix: name: - Node.js 0.8 - Node.js 0.10 - Node.js 0.12 - io.js 1.x - io.js 2.x - io.js 3.x - Node.js 4.x - Node.js 5.x - Node.js 6.x - Node.js 7.x - Node.js 8.x - Node.js 9.x - Node.js 10.x - Node.js 11.x - Node.js 12.x - Node.js 13.x - Node.js 14.x - Node.js 15.x - Node.js 16.x - Node.js 17.x - Node.js 18.x - Node.js 19.x - Node.js 20.x - Node.js 21.x - Node.js 22.x - Node.js 23.x - Node.js 24.x include: - name: Node.js 0.8 node-version: "0.8" npm-i: mocha@2.5.3 supertest@1.1.0 npm-rm: nyc - name: Node.js 0.10 node-version: "0.10" npm-i: mocha@3.5.3 nyc@10.3.2 supertest@2.0.1 - name: Node.js 0.12 node-version: "0.12" npm-i: mocha@3.5.3 nyc@10.3.2 supertest@2.0.1 - name: io.js 1.x node-version: "1.8" npm-i: mocha@3.5.3 nyc@10.3.2 supertest@2.0.1 - name: io.js 2.x node-version: "2.5" npm-i: mocha@3.5.3 nyc@10.3.2 supertest@2.0.1 - name: io.js 3.x node-version: "3.3" npm-i: mocha@3.5.3 nyc@10.3.2 supertest@2.0.1 - name: Node.js 4.x node-version: "4.9" npm-i: mocha@5.2.0 nyc@11.9.0 supertest@3.4.2 - name: Node.js 5.x node-version: "5.12" npm-i: mocha@5.2.0 nyc@11.9.0 supertest@3.4.2 - name: Node.js 6.x node-version: "6.17" npm-i: mocha@6.2.2 nyc@14.1.1 - name: Node.js 7.x node-version: "7.10" npm-i: mocha@6.2.2 nyc@14.1.1 - name: Node.js 8.x node-version: "8.17" npm-i: mocha@7.1.2 nyc@14.1.1 - name: Node.js 9.x node-version: "9.11" npm-i: mocha@7.1.2 nyc@14.1.1 - name: Node.js 10.x node-version: "10" npm-i: mocha@8.4.0 - name: Node.js 11.x node-version: "11" npm-i: mocha@8.4.0 - name: Node.js 12.x node-version: "12" npm-i: mocha@9.2.2 - name: Node.js 13.x node-version: "13" npm-i: mocha@9.2.2 - name: Node.js 14.x node-version: "14" - name: Node.js 15.x node-version: "15" - name: Node.js 16.x node-version: "16" - name: Node.js 17.x node-version: "17" - name: Node.js 18.x node-version: "18" - name: Node.js 19.x node-version: "19" - name: Node.js 20.x node-version: "20" - name: Node.js 21.x node-version: "21" - name: Node.js 22.x node-version: "22" - name: Node.js 23.x node-version: "23" - name: Node.js 24.x node-version: "24" steps: - uses: actions/checkout@v3 - name: Install Node.js ${{ matrix.node-version }} shell: bash -eo pipefail -l {0} run: | nvm install --default ${{ matrix.node-version }} if [[ "${{ matrix.node-version }}" == 0.* && "$(cut -d. -f2 <<< "${{ matrix.node-version }}")" -lt 10 ]]; then nvm install --alias=npm 0.10 nvm use ${{ matrix.node-version }} if [[ "$(npm -v)" == 1.1.* ]]; then nvm exec npm npm install -g npm@1.1 ln -fs "$(which npm)" "$(dirname "$(nvm which npm)")/npm" else sed -i '1s;^.*$;'"$(printf '#!%q' "$(nvm which npm)")"';' "$(readlink -f "$(which npm)")" fi npm config set strict-ssl false fi dirname "$(nvm which ${{ matrix.node-version }})" >> "$GITHUB_PATH" - name: Configure npm run: | if [[ "$(npm config get package-lock)" == "true" ]]; then npm config set package-lock false else npm config set shrinkwrap false fi - name: Remove npm module(s) ${{ matrix.npm-rm }} run: npm rm --silent --save-dev ${{ matrix.npm-rm }} if: matrix.npm-rm != '' - name: Install npm module(s) ${{ matrix.npm-i }} run: npm install --save-dev ${{ matrix.npm-i }} if: matrix.npm-i != '' - name: Setup Node.js version-specific dependencies shell: bash run: | # eslint for linting # - remove on Node.js < 12 if [[ "$(cut -d. -f1 <<< "${{ matrix.node-version }}")" -lt 12 ]]; then node -pe 'Object.keys(require("./package").devDependencies).join("\n")' | \ grep -E '^eslint(-|$)' | \ sort -r | \ xargs -n1 npm rm --silent --save-dev fi - name: Install Node.js dependencies run: npm install - name: List environment id: list_env shell: bash run: | echo "node@$(node -v)" echo "npm@$(npm -v)" npm -s ls ||: (npm -s ls --depth=0 ||:) | awk -F'[ @]' 'NR>1 && $2 { print $2 "=" $3 }' >> "$GITHUB_OUTPUT" - name: Run tests shell: bash run: | if npm -ps ls nyc | grep -q nyc; then npm run test-ci else npm test fi - name: Lint code if: steps.list_env.outputs.eslint != '' run: npm run lint - name: Collect code coverage uses: coverallsapp/github-action@master if: steps.list_env.outputs.nyc != '' with: github-token: ${{ secrets.GITHUB_TOKEN }} flag-name: run-${{ matrix.test_number }} parallel: true coverage: permissions: checks: write # for coverallsapp/github-action to create new checks needs: test runs-on: ubuntu-latest steps: - name: Upload code coverage uses: coverallsapp/github-action@master with: github-token: ${{ secrets.GITHUB_TOKEN }} parallel-finished: true on-headers-1.1.0/.github/workflows/codeql.yml000066400000000000000000000047511503621455200211370ustar00rootroot00000000000000# For most projects, this workflow file will not need changing; you simply need # to commit it to your repository. # # You may wish to alter this file to override the set of languages analyzed, # or to provide custom queries or build logic. # # ******** NOTE ******** # We have attempted to detect the languages in your repository. Please check # the `language` matrix defined below to confirm you have the correct set of # supported CodeQL languages. # name: "CodeQL" on: push: branches: ["master"] pull_request: # The branches below must be a subset of the branches above branches: ["master"] schedule: - cron: "0 0 * * 1" permissions: contents: read jobs: analyze: name: Analyze runs-on: ubuntu-latest permissions: actions: read contents: read security-events: write strategy: fail-fast: false matrix: language: ["javascript"] # CodeQL supports [ $supported-codeql-languages ] # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support steps: - name: Checkout repository uses: actions/checkout@v4 # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL uses: github/codeql-action/init@v3 with: languages: ${{ matrix.language }} # If you wish to specify custom queries, you can do so here or in a config file. # By default, queries listed here will override any specified in a config file. # Prefix the list here with "+" to use these queries and those in the config file. # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # If this step fails, then you should remove it and run the build manually (see below) - name: Autobuild uses: github/codeql-action/autobuild@v3 # â„šī¸ Command-line programs to run using the OS shell. # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun # If the Autobuild fails above, remove it and uncomment the following three lines. # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance. # - run: | # echo "Run, Build Application using script" # ./location_of_script_within_repo/buildscript.sh - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v3 with: category: "/language:${{matrix.language}}" on-headers-1.1.0/.github/workflows/scorecard.yml000066400000000000000000000056441503621455200216370ustar00rootroot00000000000000# This workflow uses actions that are not certified by GitHub. They are provided # by a third-party and are governed by separate terms of service, privacy # policy, and support documentation. name: Scorecard supply-chain security on: # For Branch-Protection check. Only the default branch is supported. See # https://github.com/ossf/scorecard/blob/main/docs/checks.md#branch-protection branch_protection_rule: # To guarantee Maintained check is occasionally updated. See # https://github.com/ossf/scorecard/blob/main/docs/checks.md#maintained schedule: - cron: '16 21 * * 1' push: branches: [ "master" ] # Declare default permissions as read only. permissions: read-all jobs: analysis: name: Scorecard analysis runs-on: ubuntu-latest permissions: # Needed to upload the results to code-scanning dashboard. security-events: write # Needed to publish results and get a badge (see publish_results below). id-token: write # Uncomment the permissions below if installing in a private repository. # contents: read # actions: read steps: - name: "Checkout code" uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0 with: persist-credentials: false - name: "Run analysis" uses: ossf/scorecard-action@99c53751e09b9529366343771cc321ec74e9bd3d # v2.0.6 with: results_file: results.sarif results_format: sarif # (Optional) "write" PAT token. Uncomment the `repo_token` line below if: # - you want to enable the Branch-Protection check on a *public* repository, or # - you are installing Scorecard on a *private* repository # To create the PAT, follow the steps in https://github.com/ossf/scorecard-action#authentication-with-pat. # repo_token: ${{ secrets.SCORECARD_TOKEN }} # Public repositories: # - Publish results to OpenSSF REST API for easy access by consumers # - Allows the repository to include the Scorecard badge. # - See https://github.com/ossf/scorecard-action#publishing-results. # For private repositories: # - `publish_results` will always be set to `false`, regardless # of the value entered here. publish_results: true # Upload the results as artifacts (optional). Commenting out will disable uploads of run results in SARIF # format to the repository Actions tab. - name: "Upload artifact" uses: actions/upload-artifact@a8a3f3ad30e3422c9c7b888a15615d19a852ae32 # v3.1.3 with: name: SARIF file path: results.sarif retention-days: 5 # Upload the results to GitHub's code scanning dashboard. - name: "Upload to code-scanning" uses: github/codeql-action/upload-sarif@2f93e4319b2f04a2efc38fa7f78bd681bc3f7b2f # v2.23.2 with: sarif_file: results.sarifon-headers-1.1.0/.github/workflows/upstream.yml000066400000000000000000000007301503621455200215210ustar00rootroot00000000000000name: upstream on: workflow_dispatch: schedule: - cron: "33 3 * * 3" # weekly permissions: contents: read jobs: test: runs-on: ubuntu-latest strategy: fail-fast: false matrix: node-version: ['latest'] steps: - uses: actions/checkout@v4 - name: Use Node.js uses: actions/setup-node@v4 with: node-version: ${{ matrix.node-version }} - run: npm install - run: npm run upstream on-headers-1.1.0/.gitignore000066400000000000000000000000661503621455200155330ustar00rootroot00000000000000coverage node_modules npm-debug.log package-lock.json on-headers-1.1.0/HISTORY.md000066400000000000000000000011321503621455200152210ustar00rootroot000000000000001.1.0 / 2025-07-17 ================== * - Fix [CVE-2025-7339](https://www.cve.org/CVERecord?id=CVE-2025-7339) ([GHSA-76c9-3jph-rj3q](https://github.com/expressjs/multer/security/advisories/GHSA-76c9-3jph-rj3q)) 1.0.2 / 2019-02-21 ================== * Fix `res.writeHead` patch missing return value 1.0.1 / 2015-09-29 ================== * perf: enable strict mode 1.0.0 / 2014-08-10 ================== * Honor `res.statusCode` change in `listener` * Move to `jshttp` organization * Prevent `arguments`-related de-opt 0.0.0 / 2014-05-13 ================== * Initial implementation on-headers-1.1.0/LICENSE000066400000000000000000000021011503621455200145400ustar00rootroot00000000000000(The MIT License) Copyright (c) 2014 Douglas Christopher Wilson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. on-headers-1.1.0/README.md000066400000000000000000000041431503621455200150220ustar00rootroot00000000000000# on-headers [![NPM Version][npm-version-image]][npm-url] [![NPM Downloads][npm-downloads-image]][npm-url] [![Node.js Version][node-image]][node-url] [![Build Status][ci-image]][ci-url] [![Coverage Status][coveralls-image]][coveralls-url] Execute a listener when a response is about to write headers. ## Installation This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): ```sh $ npm install on-headers ``` ## API ```js var onHeaders = require('on-headers') ``` ### onHeaders(res, listener) This will add the listener `listener` to fire when headers are emitted for `res`. The listener is passed the `response` object as it's context (`this`). Headers are considered to be emitted only once, right before they are sent to the client. When this is called multiple times on the same `res`, the `listener`s are fired in the reverse order they were added. ## Examples ```js var http = require('http') var onHeaders = require('on-headers') http .createServer(onRequest) .listen(3000) function addPoweredBy () { // set if not set by end of request if (!this.getHeader('X-Powered-By')) { this.setHeader('X-Powered-By', 'Node.js') } } function onRequest (req, res) { onHeaders(res, addPoweredBy) res.setHeader('Content-Type', 'text/plain') res.end('hello!') } ``` ## Testing ```sh $ npm test ``` ## License [MIT](LICENSE) [ci-image]: https://badgen.net/github/checks/jshttp/on-headers/master?label=ci [ci-url]: https://github.com/jshttp/on-headers/actions/workflows/ci.yml [coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/on-headers/master [coveralls-url]: https://coveralls.io/r/jshttp/on-headers?branch=master [node-image]: https://badgen.net/npm/node/on-headers [node-url]: https://nodejs.org/en/download [npm-downloads-image]: https://badgen.net/npm/dm/on-headers [npm-url]: https://npmjs.org/package/on-headers [npm-version-image]: https://badgen.net/npm/v/on-headers on-headers-1.1.0/index.js000066400000000000000000000072171503621455200152150ustar00rootroot00000000000000/*! * on-headers * Copyright(c) 2014 Douglas Christopher Wilson * MIT Licensed */ 'use strict' /** * Module exports. * @public */ module.exports = onHeaders var http = require('http') // older node versions don't have appendHeader var isAppendHeaderSupported = typeof http.ServerResponse.prototype.appendHeader === 'function' var set1dArray = isAppendHeaderSupported ? set1dArrayWithAppend : set1dArrayWithSet /** * Create a replacement writeHead method. * * @param {function} prevWriteHead * @param {function} listener * @private */ function createWriteHead (prevWriteHead, listener) { var fired = false // return function with core name and argument list return function writeHead (statusCode) { // set headers from arguments var args = setWriteHeadHeaders.apply(this, arguments) // fire listener if (!fired) { fired = true listener.call(this) // pass-along an updated status code if (typeof args[0] === 'number' && this.statusCode !== args[0]) { args[0] = this.statusCode args.length = 1 } } return prevWriteHead.apply(this, args) } } /** * Execute a listener when a response is about to write headers. * * @param {object} res * @return {function} listener * @public */ function onHeaders (res, listener) { if (!res) { throw new TypeError('argument res is required') } if (typeof listener !== 'function') { throw new TypeError('argument listener must be a function') } res.writeHead = createWriteHead(res.writeHead, listener) } /** * Set headers contained in array on the response object. * * @param {object} res * @param {array} headers * @private */ function setHeadersFromArray (res, headers) { if (headers.length && Array.isArray(headers[0])) { // 2D set2dArray(res, headers) } else { // 1D if (headers.length % 2 !== 0) { throw new TypeError('headers array is malformed') } set1dArray(res, headers) } } /** * Set headers contained in object on the response object. * * @param {object} res * @param {object} headers * @private */ function setHeadersFromObject (res, headers) { var keys = Object.keys(headers) for (var i = 0; i < keys.length; i++) { var k = keys[i] if (k) res.setHeader(k, headers[k]) } } /** * Set headers and other properties on the response object. * * @param {number} statusCode * @private */ function setWriteHeadHeaders (statusCode) { var length = arguments.length var headerIndex = length > 1 && typeof arguments[1] === 'string' ? 2 : 1 var headers = length >= headerIndex + 1 ? arguments[headerIndex] : undefined this.statusCode = statusCode if (Array.isArray(headers)) { // handle array case setHeadersFromArray(this, headers) } else if (headers) { // handle object case setHeadersFromObject(this, headers) } // copy leading arguments var args = new Array(Math.min(length, headerIndex)) for (var i = 0; i < args.length; i++) { args[i] = arguments[i] } return args } function set2dArray (res, headers) { var key for (var i = 0; i < headers.length; i++) { key = headers[i][0] if (key) { res.setHeader(key, headers[i][1]) } } } function set1dArrayWithAppend (res, headers) { for (var i = 0; i < headers.length; i += 2) { res.removeHeader(headers[i]) } var key for (var j = 0; j < headers.length; j += 2) { key = headers[j] if (key) { res.appendHeader(key, headers[j + 1]) } } } function set1dArrayWithSet (res, headers) { var key for (var i = 0; i < headers.length; i += 2) { key = headers[i] if (key) { res.setHeader(key, headers[i + 1]) } } } on-headers-1.1.0/package.json000066400000000000000000000024051503621455200160300ustar00rootroot00000000000000{ "name": "on-headers", "description": "Execute a listener when a response is about to write headers", "version": "1.1.0", "author": "Douglas Christopher Wilson ", "license": "MIT", "keywords": [ "event", "headers", "http", "onheaders" ], "repository": "jshttp/on-headers", "devDependencies": { "eslint": "6.8.0", "eslint-config-standard": "14.1.1", "eslint-plugin-import": "2.21.2", "eslint-plugin-markdown": "1.0.2", "eslint-plugin-node": "11.1.0", "eslint-plugin-promise": "4.2.1", "eslint-plugin-standard": "4.0.1", "mocha": "10.2.0", "nyc": "15.1.0", "supertest": "4.0.2" }, "files": [ "LICENSE", "HISTORY.md", "README.md", "index.js" ], "engines": { "node": ">= 0.8" }, "scripts": { "lint": "eslint --plugin markdown --ext js,md .", "test": "mocha --reporter spec --check-leaks test/test.js", "test-ci": "nyc --reporter=lcov --reporter=text npm test", "test-cov": "nyc --reporter=html --reporter=text npm test", "update-upstream-hashes": "node scripts/update-upstream-hashes.js", "upstream": "mocha --reporter spec --check-leaks test/upstream.js", "version": "node scripts/version-history.js && git add HISTORY.md" } } on-headers-1.1.0/scripts/000077500000000000000000000000001503621455200152305ustar00rootroot00000000000000on-headers-1.1.0/scripts/update-upstream-hashes.js000066400000000000000000000012351503621455200221600ustar00rootroot00000000000000const fs = require('fs') const path = require('path') const { getFunctionHash, httpServerResponsePrototype: res } = require('../scripts/upstream-common') const updatedHashes = { knownAppendHeaderHash: getFunctionHash(res.appendHeader), knownRemoveHeaderHash: getFunctionHash(res.removeHeader), knownSetHeaderHash: getFunctionHash(res.setHeader), knownWriteHeadHash: getFunctionHash(res.writeHead) } const filename = 'known-upstream-hashes.json' const filePath = path.join(__dirname, `../test/${filename}`) fs.writeFileSync(filePath, JSON.stringify(updatedHashes, null, 2) + '\n', 'utf8') console.log(`✅ updated '${filename}' with current method hashes.`) on-headers-1.1.0/scripts/upstream-common.js000066400000000000000000000005161503621455200207160ustar00rootroot00000000000000const crypto = require('crypto') const http = require('http') function getFunctionHash (fn) { const src = fn.toString().replace(/\s+/g, '') // normalize whitespace return crypto.createHash('sha256').update(src).digest('hex') } module.exports = { getFunctionHash, httpServerResponsePrototype: http.ServerResponse.prototype } on-headers-1.1.0/scripts/version-history.js000066400000000000000000000027771503621455200207670ustar00rootroot00000000000000'use strict' var fs = require('fs') var path = require('path') var HISTORY_FILE_PATH = path.join(__dirname, '..', 'HISTORY.md') var MD_HEADER_REGEXP = /^====*$/ var VERSION = process.env.npm_package_version var VERSION_PLACEHOLDER_REGEXP = /^(?:unreleased|(\d+\.)+x)$/ var historyFileLines = fs.readFileSync(HISTORY_FILE_PATH, 'utf-8').split('\n') if (!MD_HEADER_REGEXP.test(historyFileLines[1])) { console.error('Missing header in HISTORY.md') process.exit(1) } if (!VERSION_PLACEHOLDER_REGEXP.test(historyFileLines[0])) { console.error('Missing placegolder version in HISTORY.md') process.exit(1) } if (historyFileLines[0].indexOf('x') !== -1) { var versionCheckRegExp = new RegExp('^' + historyFileLines[0].replace('x', '.+') + '$') if (!versionCheckRegExp.test(VERSION)) { console.error('Version %s does not match placeholder %s', VERSION, historyFileLines[0]) process.exit(1) } } historyFileLines[0] = VERSION + ' / ' + getLocaleDate() historyFileLines[1] = repeat('=', historyFileLines[0].length) fs.writeFileSync(HISTORY_FILE_PATH, historyFileLines.join('\n')) function getLocaleDate () { var now = new Date() return zeroPad(now.getFullYear(), 4) + '-' + zeroPad(now.getMonth() + 1, 2) + '-' + zeroPad(now.getDate(), 2) } function repeat (str, length) { var out = '' for (var i = 0; i < length; i++) { out += str } return out } function zeroPad (number, length) { var num = number.toString() while (num.length < length) { num = '0' + num } return num } on-headers-1.1.0/test/000077500000000000000000000000001503621455200145205ustar00rootroot00000000000000on-headers-1.1.0/test/.eslintrc.yml000066400000000000000000000000231503621455200171370ustar00rootroot00000000000000env: mocha: true on-headers-1.1.0/test/known-upstream-hashes.json000066400000000000000000000005711503621455200216610ustar00rootroot00000000000000{ "knownAppendHeaderHash": "0deb9f70c3bba63993321cca9281fb4607e2567bed1436b8574c5b86698125a8", "knownRemoveHeaderHash": "3ad5ccb0a858beb6268f281492bd8d42c9815f5316cc3c4f7f735e142fcd29d9", "knownSetHeaderHash": "2d4f95e92586d28bfd4d3137a8eaacb82b255967d8c26413015c6b56daf0afe7", "knownWriteHeadHash": "281e0d02084a69893b8c3b8692e3c7c4de2ce22a626217fcf597fa6ddf6955a9" } on-headers-1.1.0/test/test.js000066400000000000000000000267111503621455200160440ustar00rootroot00000000000000 var assert = require('assert') var http = require('http') var onHeaders = require('..') var request = require('supertest') // older node versions don't have appendHeader var isAppendHeaderSupported = typeof http.ServerResponse.prototype.appendHeader === 'function' describe('onHeaders(res, listener)', function () { it('should fire after setHeader', function (done) { var server = createServer(echoListener) request(server) .get('/') .expect('X-Outgoing-Echo', 'test') .expect(200, done) }) it('should fire before write', function (done) { var server = createServer(echoListener, handler) function handler (req, res) { res.setHeader('X-Outgoing', 'test') res.write('1') } request(server) .get('/') .expect('X-Outgoing-Echo', 'test') .expect(200, '1', done) }) it('should fire with no headers', function (done) { var server = createServer(listener, handler) function handler (req, res) {} function listener (req, res) { this.setHeader('X-Headers', getAllHeaderNames(this).join(',')) } request(server) .get('/') .expect('X-Headers', '') .expect(200, done) }) it('should fire only once', function (done) { var count = 0 var server = createServer(listener, handler) function handler (req, res) { res.writeHead(200) try { res.writeHead(200) } catch (e) {} } function listener (req, res) { count++ } request(server) .get('/') .expect(200, function (err) { if (err) return done(err) assert.strictEqual(count, 1) done() }) }) it('should fire in reverse order', function (done) { var server = createServer(echoListener, handler) function handler (req, res) { onHeaders(res, appendHeader(1)) onHeaders(res, appendHeader(2)) onHeaders(res, appendHeader(3)) res.setHeader('X-Outgoing', 'test') } request(server) .get('/') .expect('X-Outgoing-Echo', 'test,3,2,1') .expect(200, done) }) describe('arguments', function () { describe('res', function () { it('should be required', function () { assert.throws(onHeaders.bind(), /res.*required/) }) }) describe('listener', function () { it('should be required', function (done) { var server = createServer() request(server) .get('/') .expect(500, /listener.*function/, done) }) it('should only accept function', function (done) { var server = createServer(42) request(server) .get('/') .expect(500, /listener.*function/, done) }) }) }) describe('setHeader', function () { it('should be available in listener', function (done) { var server = createServer(echoListener) request(server) .get('/') .expect('X-Outgoing-Echo', 'test') .expect(200, done) }) }) describe('writeHead(status)', function () { it('should make status available in listener', function (done) { var server = createServer(listener, handler) function handler (req, res) { res.writeHead(201) } function listener (req, res) { this.setHeader('X-Status', this.statusCode) } request(server) .get('/') .expect('X-Status', '201') .expect(201, done) }) it('should allow manipulation of status in listener', function (done) { var server = createServer(listener, handler) function handler (req, res) { res.writeHead(201) } function listener (req, res) { this.setHeader('X-Status', this.statusCode) this.statusCode = 202 } request(server) .get('/') .expect('X-Status', '201') .expect(202, done) }) it('should pass-through core error', function (done) { var server = createServer(appendHeader(1), handler) function handler (req, res) { res.writeHead() // error } request(server) .get('/') .expect(500, done) }) it('should retain return value', function (done) { var server = http.createServer(function (req, res) { if (req.url === '/attach') { onHeaders(res, appendHeader(1)) } res.end(typeof res.writeHead(200)) }) request(server) .get('/') .expect(200, function (err, res) { if (err) return done(err) request(server) .get('/attach') .expect(200, res.text, done) }) }) }) describe('writeHead(status, reason)', function () { it('should be available in listener', function (done) { var server = createServer(echoListener, handler) function handler (req, res) { res.setHeader('X-Outgoing', 'test') res.writeHead(200, 'OK') } request(server) .get('/') .expect('X-Outgoing-Echo', 'test') .expect(200, done) }) }) describe('writeHead(status, reason, obj)', function () { it('should be available in listener', function (done) { var server = createServer(echoListener, handler) function handler (req, res) { res.writeHead(200, 'OK', { 'X-Outgoing': 'test' }) } request(server) .get('/') .expect('X-Outgoing-Echo', 'test') .expect(200, done) }) }) describe('writeHead(status, obj)', function () { it('should be available in listener', function (done) { var server = createServer(listener, handler) function handler (req, res) { res.writeHead(201, { 'X-Outgoing': 'test' }) } function listener (req, res) { this.setHeader('X-Status', this.statusCode) this.setHeader('X-Outgoing-Echo', this.getHeader('X-Outgoing')) } request(server) .get('/') .expect('X-Status', '201') .expect('X-Outgoing-Echo', 'test') .expect(201, done) }) it('should handle falsy keys', function (done) { var server = createServer(listener, handler) function handler (req, res) { res.writeHead(201, { 'X-Outgoing': 'test', '': 'test' }) } function listener (req, res) { this.setHeader('X-Status', this.statusCode) this.setHeader('X-Outgoing-Echo', this.getHeader('X-Outgoing')) } request(server) .get('/') .expect('X-Status', '201') .expect('X-Outgoing-Echo', 'test') .expect(201, done) }) }) describe('writeHead(status, arr)', function () { it('should be available in listener', function (done) { var server = createServer(listener, handler) function handler (req, res) { res.writeHead(201, [['X-Outgoing', 'test']]) } function listener (req, res) { this.setHeader('X-Status', this.statusCode) this.setHeader('X-Outgoing-Echo', this.getHeader('X-Outgoing')) } request(server) .get('/') .expect('X-Status', '201') .expect('X-Outgoing-Echo', 'test') .expect(201, done) }) it('should ignore empty header key', function (done) { var server = createServer(listener, handler) function handler (req, res) { res.writeHead(201, [['', 'test']]) } function listener (req, res) { } request(server) .get('/') .expect(201, done) }) }) describe('writeHead(status, flat arr)', function () { it('should be available in listener', function (done) { var server = createServer(listener, handler) function handler (req, res) { res.writeHead(201, ['X-Outgoing', 'test']) } function listener (req, res) { this.setHeader('X-Status', this.statusCode) this.setHeader('X-Outgoing-Echo', this.getHeader('X-Outgoing')) } request(server) .get('/') .expect('X-Status', '201') .expect('X-Outgoing-Echo', 'test') .expect(201, done) }) it('should ignore empty header key', function (done) { var server = createServer(listener, handler) function handler (req, res) { res.writeHead(201, ['', 'test']) } function listener (req, res) { } request(server) .get('/') .expect(201, done) }) }) describe('writeHead(status, invalid flat arr)', function () { it('should throw on malformed array', function (done) { var server = createServer(listener, handler) function handler (req, res) { assert.throws(function () { res.writeHead(201, ['foo', 'bar', 'baz']) }, TypeError) } function listener (req, res) { } // gets a 200 here because we caught the error via assert.throws request(server) .get('/') .expect(200, done) }) it('should return 500 on malformed array', function (done) { var server = createServer(listener, handler) function handler (req, res) { res.writeHead(201, ['foo', 'bar', 'baz']) res.end('no soup for you!') } function listener (req, res) { } request(server) .get('/') .expect(500, done) }) }) describe('writeHead(status, duplicate headers)', function () { it('should be respected', function (done) { var server = createServer(listener, handler) function handler (req, res) { res.writeHead(201, ['express', 'is good', 'express', 'is great']) } function listener (req, res) { // no need to duplicate existing listener tests further... right? } var response = request(server).get('/') if (isAppendHeaderSupported) { response .expect('express', 'is good, is great') } else { response .expect('express', 'is great') } response .expect(201) .end(function (err, res) { if (err) throw err var expressIsGood = false var expressIsGreat = false // very old node versions do not have the `rawHeaders` prop var headers = res.res.rawHeaders || res.res.headers if (headers.length) { for (var i = 0; i < headers.length; i++) { const header = headers[i] if (header === 'express') { if (headers[i + 1] === 'is good') { expressIsGood = true } else if (headers[i + 1] === 'is great') { expressIsGreat = true } } } } else { expressIsGreat = headers.express === 'is great' } if (isAppendHeaderSupported) { assert.ok(expressIsGood) } assert.ok(expressIsGreat) done() }) }) }) }) function createServer (listener, handler) { var fn = handler || echoHandler return http.createServer(function (req, res) { try { onHeaders(res, listener) fn(req, res) res.statusCode = 200 } catch (err) { res.statusCode = 500 res.write(err.message) } finally { res.end() } }) } function appendHeader (num) { return function onHeaders () { this.setHeader('X-Outgoing', this.getHeader('X-Outgoing') + ',' + num) } } function echoHandler (req, res) { res.setHeader('X-Outgoing', 'test') } function echoListener () { this.setHeader('X-Outgoing-Echo', this.getHeader('X-Outgoing')) } function getAllHeaderNames (res) { return typeof res.getHeaderNames !== 'function' ? Object.keys(this._headers || {}) : res.getHeaderNames() } on-headers-1.1.0/test/upstream.js000066400000000000000000000027321503621455200167220ustar00rootroot00000000000000// NOTE: this is a temporary solution to tell us if future changes to the monkey-patched methods // could impact this package. Recognizing this is not an ideal solution, we plan to address this when // we can drop the monkey-patching entirely. const assert = require('assert') const knownHashes = require('./known-upstream-hashes.json') const { getFunctionHash, httpServerResponsePrototype: res } = require('../scripts/upstream-common') const { knownAppendHeaderHash, knownRemoveHeaderHash, knownSetHeaderHash, knownWriteHeadHash } = knownHashes describe('function verification', function () { it('should match the known function hash of writeHead', function () { const currentHash = getFunctionHash(res.writeHead) assert.strictEqual(currentHash, knownWriteHeadHash, 'writeHead hash has changed') }) it('should match the known function hash of setHeader', function () { const currentHash = getFunctionHash(res.setHeader) assert.strictEqual(currentHash, knownSetHeaderHash, 'setHeader hash has changed') }) it('should match the known function hash of appendHeader', function () { const currentHash = getFunctionHash(res.appendHeader) assert.strictEqual(currentHash, knownAppendHeaderHash, 'appendHeader hash has changed') }) it('should match the known function hash of removeHeader', function () { const currentHash = getFunctionHash(res.removeHeader) assert.strictEqual(currentHash, knownRemoveHeaderHash, 'removeHeader hash has changed') }) })