CodeSampleX

Ejemplo

hono 4.13.7: etag

Muestra verificada para npm hono 4.13.7: etag. El contrato se ejecutó en node 22 · linux debian/x64 · docker y pasó: createApp configures Hono application…

sha256:3c83c6799e1c029c5e16de993a72ae4705dfd6734d0c244cde2bd0c524431c68

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado linux 24 · ubuntu · glibc 2.39 x64 npm

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
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-06

Caso

HOW
Objetivo
verify etag in pkg:npm/hono@4.13.7
Paquetes
Símbolos
  • etag
Creado
2026-09-06T04:11:53Z

Contrato

  1. createApp configures Hono application with etag middleware supporting default, weak, custom digest, and custom retained headers policies
  2. etag middleware generates strong SHA-1 ETag by default and sets ETag response header on 200 responses
  3. etag middleware returns 304 Not Modified with empty body when matching If-None-Match header is provided
  4. etag middleware returns 304 Not Modified when wildcard If-None-Match is provided
  5. etag middleware generates weak ETag prefixed with W/ when weak option is enabled
  6. etag middleware computes custom hash using provided generateDigest function
  7. etag middleware retains only specified headers on 304 responses when retainedHeaders option is provided
  8. etag middleware does not set ETag response header on POST requests

Archivos

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

Descargar el artefacto de código fuente (tar.gz)

Código fuente

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 etag in pkg:npm/hono@4.13.7
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/hono@4.13.7
Demonstrate these symbols/APIs:
  - etag

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:7a2fd54added3163fe134d66d147daf65304adcd0b3096bade1414a73d677e9c","contract":["createApp configures Hono application with etag middleware supporting default, weak, custom digest, and custom retained headers policies","etag middleware generates strong SHA-1 ETag by default and sets ETag response header on 200 responses","etag middleware returns 304 Not Modified with empty body when matching If-None-Match header is provided","etag middleware returns 304 Not Modified when wildcard If-None-Match is provided","etag middleware generates weak ETag prefixed with W/ when weak option is enabled","etag middleware computes custom hash using provided generateDigest function","etag middleware retains only specified headers on 304 responses when retainedHeaders option is provided","etag middleware does not set ETag response header on POST requests"],"goal":"verify etag in pkg:npm/hono@4.13.7","kind":"HOW","packages":["pkg:npm/hono@4.13.7"],"schemaVersion":1,"symbols":["etag"]},"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/hono@4.13.7"],"schemaVersion":1,"subject":"pkg:npm/hono@4.13.7","symbols":["etag"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-hono-etag",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-hono-etag",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "hono": "4.13.7"
      }
    },
    "node_modules/hono": {
      "version": "4.13.7",
      "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.7.tgz",
      "integrity": "sha512-c8/gF9ac8Y78/agExVocyLevgR+JlpNB444Py0FSX8pJoPdYUfUzRcXtYEYGwt6l19qIlVZPN5Mfsw9jFShmQQ==",
      "license": "MIT",
      "engines": {
        "node": ">=16.9.0"
      }
    }
  }
}
package.json
{
  "name": "sample-hono-etag",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room code sample for etag in hono@4.13.7",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "hono": "4.13.7"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify etag in pkg:npm/hono@4.13.7",
  "kind": "HOW",
  "packages": [
    "pkg:npm/hono@4.13.7"
  ],
  "symbols": [
    "etag"
  ]
}
src/index.js
'use strict';

const { Hono } = require('hono');
const { etag, RETAINED_304_HEADERS } = require('hono/etag');

/**
 * Creates and configures a Hono application demonstrating etag middleware.
 *
 * @returns {Hono}
 */
function createApp() {
  const app = new Hono();

  // 1. Default ETag middleware route (strong ETag with SHA-1)
  app.use('/default/*', etag());
  app.get('/default/hello', (c) => {
    return c.text('Hello Hono ETag');
  });

  // 2. Weak ETag middleware route (prefixed with W/)
  app.use('/weak/*', etag({ weak: true }));
  app.get('/weak/hello', (c) => {
    return c.text('Weak ETag content');
  });

  // 3. Custom digest generator
  app.use(
    '/custom-digest/*',
    etag({
      generateDigest: (body) => {
        return crypto.subtle.digest({ name: 'SHA-256' }, body);
      }
    })
  );
  app.get('/custom-digest/hello', (c) => {
    return c.text('Custom digest content');
  });

  // 4. Custom retained headers on 304 responses
  app.use(
    '/retained/*',
    etag({
      retainedHeaders: ['etag', 'x-custom-cache']
    })
  );
  app.get('/retained/hello', (c) => {
    c.header('X-Custom-Cache', 'custom-hit');
    c.header('X-Ignored-Header', 'should-be-dropped');
    return c.text('Retained headers content');
  });

  // 5. POST endpoint where ETag is not automatically generated
  app.use('/api/*', etag());
  app.post('/api/data', (c) => {
    return c.text('Created', 201);
  });

  return app;
}

module.exports = {
  createApp,
  Hono,
  etag,
  RETAINED_304_HEADERS
};
test/contract.mjs
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const {
  createApp,
  Hono,
  etag,
  RETAINED_304_HEADERS
} = require('../src/index.js');

async function testAll() {
  const app = createApp();

  // 1. Export verification
  assert.equal(typeof createApp, 'function', 'createApp must be a function');
  assert.equal(typeof Hono, 'function', 'Hono must be a function');
  assert.equal(typeof etag, 'function', 'etag must be a function');
  assert.ok(Array.isArray(RETAINED_304_HEADERS), 'RETAINED_304_HEADERS must be an array');
  assert.ok(RETAINED_304_HEADERS.includes('etag'), 'RETAINED_304_HEADERS must include etag');
  assert.ok(RETAINED_304_HEADERS.includes('cache-control'), 'RETAINED_304_HEADERS must include cache-control');

  // 2. Default ETag middleware generates strong ETag and handles 304 matching
  const defaultRes = await app.fetch(new Request('http://localhost/default/hello'));
  assert.equal(defaultRes.status, 200, 'initial GET should return 200');
  const strongEtag = defaultRes.headers.get('ETag');
  assert.ok(strongEtag, 'ETag header must be present');
  assert.ok(!strongEtag.startsWith('W/'), 'default ETag must be a strong validator (no W/ prefix)');
  assert.ok(strongEtag.startsWith('"') && strongEtag.endsWith('"'), 'ETag must be quoted');
  const bodyText = await defaultRes.text();
  assert.equal(bodyText, 'Hello Hono ETag');

  // Matching If-None-Match returns 304 Not Modified with empty body
  const cachedRes = await app.fetch(
    new Request('http://localhost/default/hello', {
      headers: { 'If-None-Match': strongEtag }
    })
  );
  assert.equal(cachedRes.status, 304, 'matching If-None-Match must return 304 Not Modified');
  assert.equal(cachedRes.headers.get('ETag'), strongEtag, '304 response must retain ETag header');
  const cachedBody = await cachedRes.text();
  assert.equal(cachedBody, '', '304 response body must be empty');

  // Wildcard If-None-Match returns 304 Not Modified
  const wildcardRes = await app.fetch(
    new Request('http://localhost/default/hello', {
      headers: { 'If-None-Match': '*' }
    })
  );
  assert.equal(wildcardRes.status, 304, 'wildcard If-None-Match must return 304');

  // Mismatched If-None-Match returns 200 with full body
  const mismatchedRes = await app.fetch(
    new Request('http://localhost/default/hello', {
      headers: { 'If-None-Match': '"different-etag"' }
    })
  );
  assert.equal(mismatchedRes.status, 200, 'mismatched If-None-Match must return 200');
  const mismatchedBody = await mismatchedRes.text();
  assert.equal(mismatchedBody, 'Hello Hono ETag');

  // 3. Weak ETag validation
  const weakRes = await app.fetch(new Request('http://localhost/weak/hello'));
  assert.equal(weakRes.status, 200, 'weak endpoint returns 200');
  const weakEtag = weakRes.headers.get('ETag');
  assert.ok(weakEtag, 'weak ETag header must be present');
  assert.ok(weakEtag.startsWith('W/'), 'weak ETag must start with W/');

  const weakCachedRes = await app.fetch(
    new Request('http://localhost/weak/hello', {
      headers: { 'If-None-Match': weakEtag }
    })
  );
  assert.equal(weakCachedRes.status, 304, 'matching weak If-None-Match must return 304');

  // 4. Custom digest generator (e.g. SHA-256 producing 64-char hex hash)
  const customDigestRes = await app.fetch(new Request('http://localhost/custom-digest/hello'));
  assert.equal(customDigestRes.status, 200, 'custom digest endpoint returns 200');
  const customEtag = customDigestRes.headers.get('ETag');
  assert.ok(customEtag, 'custom digest ETag header must be present');
  assert.equal(customEtag.length, 66, 'SHA-256 digest hex length should be 64 plus quotes');

  const customCachedRes = await app.fetch(
    new Request('http://localhost/custom-digest/hello', {
      headers: { 'If-None-Match': customEtag }
    })
  );
  assert.equal(customCachedRes.status, 304, 'matching custom digest If-None-Match must return 304');

  // 5. Custom retained headers filtering on 304 responses
  const retainedInitial = await app.fetch(new Request('http://localhost/retained/hello'));
  assert.equal(retainedInitial.status, 200);
  assert.equal(retainedInitial.headers.get('X-Custom-Cache'), 'custom-hit');
  assert.equal(retainedInitial.headers.get('X-Ignored-Header'), 'should-be-dropped');
  const retainedEtag = retainedInitial.headers.get('ETag');

  const retainedCached = await app.fetch(
    new Request('http://localhost/retained/hello', {
      headers: { 'If-None-Match': retainedEtag }
    })
  );
  assert.equal(retainedCached.status, 304);
  assert.equal(retainedCached.headers.get('ETag'), retainedEtag);
  assert.equal(retainedCached.headers.get('X-Custom-Cache'), 'custom-hit', 'retained header must be preserved');
  assert.equal(retainedCached.headers.get('X-Ignored-Header'), null, 'unretained header must be stripped on 304');

  // 6. Non-GET methods do not receive automatic ETag headers
  const postRes = await app.fetch(
    new Request('http://localhost/api/data', {
      method: 'POST'
    })
  );
  assert.equal(postRes.status, 201, 'POST request returns 201');
  assert.equal(postRes.headers.get('ETag'), null, 'POST request must not include ETag header');

  console.log('All hono/etag contract assertions passed successfully.');
}

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

Seeder de origen

anónimo