CodeSampleX

Exemplo

finalhandler 1.3.1

Amostra verificada para npm finalhandler 1.3.1. O contrato rodou em node 22 · linux debian/x64 · docker e passou: finalhandler(req, res) produces a 404 Not…

sha256:21a40011a4426e5f155a89697ff2239408251bf52209909c5c8a0e747ee865b2

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado linux 24 · ubuntu · glibc 2.39 x64 npm

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
node 22 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22@sha256:8a34c4ab3ea2…
2026-09-19

Caso

HOW
Objetivo
verify pkg:npm/finalhandler@1.3.1
Pacotes
Criado
2026-09-19T01:34:09Z

Contrato

  1. finalhandler(req, res) produces a 404 Not Found response when called without an error for unhandled requests
  2. finalhandler(req, res) produces a 500 or error status response matching err.status/err.statusCode when called with an error
  3. finalhandler(req, res, { onerror }) invokes the onerror callback with the error and request/response objects
  4. finalhandler(req, res, { env: 'production' }) omits error details and stack trace in the response body in production mode
  5. finalhandler(req, res) terminates or destroys socket connection if response headers have already been sent when an error occurs

Arquivos

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • test/contract.mjs

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify pkg:npm/finalhandler@1.3.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/finalhandler@1.3.1

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:60fd8f2215f343e50adbaf4b5fa553739c325b3dd3e02ae6b4802497ec04a68e","contract":["finalhandler(req, res) produces a 404 Not Found response when called without an error for unhandled requests","finalhandler(req, res) produces a 500 or error status response matching err.status/err.statusCode when called with an error","finalhandler(req, res, { onerror }) invokes the onerror callback with the error and request/response objects","finalhandler(req, res, { env: 'production' }) omits error details and stack trace in the response body in production mode","finalhandler(req, res) terminates or destroys socket connection if response headers have already been sent when an error occurs"],"goal":"verify pkg:npm/finalhandler@1.3.1","kind":"HOW","packages":["pkg:npm/finalhandler@1.3.1"],"schemaVersion":1},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/finalhandler@1.3.1"],"schemaVersion":1,"subject":"pkg:npm/finalhandler@1.3.1","verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-finalhandler",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-finalhandler",
      "version": "1.0.0",
      "dependencies": {
        "finalhandler": "1.3.1"
      }
    },
    "node_modules/debug": {
      "version": "2.6.9",
      "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
      "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
      "license": "MIT",
      "dependencies": {
        "ms": "2.0.0"
      }
    },
    "node_modules/ee-first": {
      "version": "1.1.1",
      "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
      "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",
      "license": "MIT"
    },
    "node_modules/encodeurl": {
      "version": "2.0.0",
      "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",
      "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==",
      "license": "MIT",
      "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==",
      "license": "MIT"
    },
    "node_modules/finalhandler": {
      "version": "1.3.1",
      "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.1.tgz",
      "integrity": "sha512-6BN9trH7bp3qvnrRyzsBz+g3lZxTNZTbVO2EV1CS0WIcDbawYVdYvGflME/9QP0h0pYlCDBCTjYa9nZzMDpyxQ==",
      "license": "MIT",
      "dependencies": {
        "debug": "2.6.9",
        "encodeurl": "~2.0.0",
        "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/ms": {
      "version": "2.0.0",
      "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
      "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
      "license": "MIT"
    },
    "node_modules/on-finished": {
      "version": "2.4.1",
      "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",
      "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",
      "license": "MIT",
      "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==",
      "license": "MIT",
      "engines": {
        "node": ">= 0.8"
      }
    },
    "node_modules/statuses": {
      "version": "2.0.1",
      "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz",
      "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==",
      "license": "MIT",
      "engines": {
        "node": ">= 0.8"
      }
    },
    "node_modules/unpipe": {
      "version": "1.0.0",
      "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
      "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",
      "license": "MIT",
      "engines": {
        "node": ">= 0.8"
      }
    }
  }
}
package.json
{
  "name": "sample-finalhandler",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "dependencies": {
    "finalhandler": "1.3.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/finalhandler@1.3.1",
  "kind": "HOW",
  "packages": [
    "pkg:npm/finalhandler@1.3.1"
  ]
}
test/contract.mjs
import assert from 'node:assert/strict';
import http from 'node:http';
import finalhandler from 'finalhandler';

async function runTests() {
  // 1. finalhandler(req, res) produces a 404 Not Found response when called without an error for unhandled requests
  await new Promise((resolve, reject) => {
    const server = http.createServer((req, res) => {
      const done = finalhandler(req, res);
      done();
    });
    server.listen(0, '127.0.0.1', () => {
      const port = server.address().port;
      http.get(`http://127.0.0.1:${port}/not-found-endpoint`, (res) => {
        assert.equal(res.statusCode, 404);
        assert.equal(res.headers['x-content-type-options'], 'nosniff');
        let data = '';
        res.on('data', chunk => data += chunk);
        res.on('end', () => {
          assert(data.includes('Cannot GET /not-found-endpoint'));
          server.close(() => resolve());
        });
      }).on('error', reject);
    });
  });

  // 2. finalhandler(req, res) produces a 500 or error status response matching err.status/err.statusCode when called with an error
  await new Promise((resolve, reject) => {
    const server = http.createServer((req, res) => {
      const done = finalhandler(req, res);
      const err = new Error('Invalid Input');
      err.status = 422;
      done(err);
    });
    server.listen(0, '127.0.0.1', () => {
      const port = server.address().port;
      http.get(`http://127.0.0.1:${port}/unprocessable`, (res) => {
        assert.equal(res.statusCode, 422);
        let data = '';
        res.on('data', chunk => data += chunk);
        res.on('end', () => {
          assert(data.includes('Invalid Input') || data.includes('Unprocessable'));
          server.close(() => resolve());
        });
      }).on('error', reject);
    });
  });

  // 3. finalhandler(req, res, { onerror }) invokes the onerror callback with the error and request/response objects
  await new Promise((resolve, reject) => {
    let onerrorCalled = false;
    const testErr = new Error('Custom Server Error');
    const server = http.createServer((req, res) => {
      const done = finalhandler(req, res, {
        onerror: (err, rReq, rRes) => {
          assert.equal(err, testErr);
          assert.equal(rReq, req);
          assert.equal(rRes, res);
          onerrorCalled = true;
        }
      });
      done(testErr);
    });
    server.listen(0, '127.0.0.1', () => {
      const port = server.address().port;
      http.get(`http://127.0.0.1:${port}/error-route`, (res) => {
        assert.equal(res.statusCode, 500);
        res.resume();
        res.on('end', () => {
          assert.equal(onerrorCalled, true);
          server.close(() => resolve());
        });
      }).on('error', reject);
    });
  });

  // 4. finalhandler(req, res, { env: 'production' }) omits error details and stack trace in the response body in production mode
  await new Promise((resolve, reject) => {
    const server = http.createServer((req, res) => {
      const done = finalhandler(req, res, { env: 'production' });
      const err = new Error('sensitive database error message');
      done(err);
    });
    server.listen(0, '127.0.0.1', () => {
      const port = server.address().port;
      http.get(`http://127.0.0.1:${port}/prod-error`, (res) => {
        assert.equal(res.statusCode, 500);
        let data = '';
        res.on('data', chunk => data += chunk);
        res.on('end', () => {
          assert(!data.includes('sensitive database error message'), 'production mode must not reveal internal error messages');
          assert(data.includes('Internal Server Error'));
          server.close(() => resolve());
        });
      }).on('error', reject);
    });
  });

  // 5. finalhandler(req, res) terminates or destroys socket connection if response headers have already been sent when an error occurs
  await new Promise((resolve, reject) => {
    const server = http.createServer((req, res) => {
      const done = finalhandler(req, res);
      res.writeHead(200, { 'Content-Type': 'text/plain' });
      res.write('partial');
      const err = new Error('Failure after headers sent');
      done(err);
    });
    server.listen(0, '127.0.0.1', () => {
      const port = server.address().port;
      const req = http.get(`http://127.0.0.1:${port}/destroyed`, (res) => {
        res.on('data', () => {});
        res.on('error', () => {
          server.close(() => resolve());
        });
        res.on('end', () => {
          server.close(() => resolve());
        });
      });
      req.on('error', () => {
        server.close(() => resolve());
      });
    });
  });

  console.log('Contract tests passed successfully.');
}

runTests().catch(err => {
  console.error('Contract test failed:', err);
  process.exit(1);
});

Seeder de origem

anônimo