CodeSampleX

Ejemplo

hono 4.13.2: cors

Muestra verificada para npm hono 4.13.2: cors. El contrato se ejecutó en node 22 · linux alpine/x64 · docker y pasó: cors is exported as a middleware factory…

sha256:6a7203349391129e83a1cffed360bcc0bdf44e1ad3c0a3cee8b1d6b564c9c19f

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 node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-08-27

Caso

HOW
Objetivo
verify hono.cors in pkg:npm/hono@4.13.2
Paquetes
Símbolos
  • hono.cors
Entorno
node 22.23.2
Creado
2026-08-27T22:05:22Z

Contrato

  1. cors is exported as a middleware factory function from hono/cors
  2. cors sets default wildcard Access-Control-Allow-Origin header and handles preflight OPTIONS with 204 No Content
  3. cors supports custom origin, allowMethods, allowHeaders, exposeHeaders, maxAge, and credentials options
  4. cors supports dynamic origin resolver functions and sets Vary: Origin header

Archivos

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

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 hono.cors in pkg:npm/hono@4.13.2
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/hono@4.13.2
Demonstrate these symbols/APIs:
  - hono.cors

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:dcac08b6fac7f861ca081a24fa8f2b11995593ad3f5424e11e723f998f49d0a6","contract":["cors is exported as a middleware factory function from hono/cors","cors sets default wildcard Access-Control-Allow-Origin header and handles preflight OPTIONS with 204 No Content","cors supports custom origin, allowMethods, allowHeaders, exposeHeaders, maxAge, and credentials options","cors supports dynamic origin resolver functions and sets Vary: Origin header"],"goal":"verify hono.cors in pkg:npm/hono@4.13.2","kind":"HOW","packages":["pkg:npm/hono@4.13.2"],"schemaVersion":1,"symbols":["hono.cors"]},"contractCommand":["node","test/contract.cjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/hono@4.13.2"],"schemaVersion":1,"subject":"pkg:npm/hono@4.13.2","symbols":["hono.cors"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-hono-cors",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-hono-cors",
      "version": "1.0.0",
      "dependencies": {
        "hono": "4.13.2"
      }
    },
    "node_modules/hono": {
      "version": "4.13.2",
      "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.2.tgz",
      "integrity": "sha512-JydRilDRkYBQMt9qR9U92mXxmbGqsqSn/IKOrh4e7/gEbn+0zSr8igTu0obwJoNGN4sez28DIql7FBHWydoJpA==",
      "license": "MIT",
      "engines": {
        "node": ">=16.9.0"
      }
    }
  }
}
package.json
{
  "name": "sample-hono-cors",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification for hono.cors",
  "dependencies": {
    "hono": "4.13.2"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify hono.cors in pkg:npm/hono@4.13.2",
  "kind": "HOW",
  "packages": [
    "pkg:npm/hono@4.13.2"
  ],
  "symbols": [
    "hono.cors"
  ]
}
src/index.js
const { Hono } = require('hono');
const { cors } = require('hono/cors');

/**
 * Creates and configures a Hono application demonstrating hono.cors.
 * @param {import('hono/cors').CORSOptions} [options] - CORS configuration options.
 * @returns {Hono} Configured Hono application instance.
 */
function createApp(options) {
  const app = new Hono();

  if (options !== undefined) {
    app.use('/api/*', cors(options));
  } else {
    app.use('/api/*', cors());
  }

  app.get('/api/data', (c) => c.json({ message: 'hello' }));

  app.post('/api/items', (c) => {
    c.header('X-Response-Id', 'resp-123');
    return c.json({ created: true });
  });

  app.get('/api/profile', (c) => c.json({ user: 'alice' }));

  return app;
}

module.exports = {
  createApp,
  cors
};
test/contract.cjs
const assert = require('node:assert/strict');
const { createApp, cors } = require('../src/index.js');
const { cors: rawCors } = require('hono/cors');

async function runContractTests() {
  // 1. cors is exported as a middleware factory function from hono/cors
  assert.equal(typeof cors, 'function', 'cors must be exported as a function');
  assert.equal(typeof rawCors, 'function', 'hono/cors must export cors function');
  const mw = cors();
  assert.equal(typeof mw, 'function', 'cors factory must return a middleware function');

  // 2. cors sets default wildcard Access-Control-Allow-Origin header and handles preflight OPTIONS with 204 No Content
  {
    const defaultApp = createApp();

    const preflightRes = await defaultApp.request('http://localhost/api/data', {
      method: 'OPTIONS',
      headers: {
        'Origin': 'https://example.com',
        'Access-Control-Request-Method': 'GET'
      }
    });
    assert.equal(preflightRes.status, 204, 'Default CORS preflight OPTIONS should return 204 No Content');
    assert.equal(preflightRes.headers.get('access-control-allow-origin'), '*', 'Default allow-origin should be *');
    assert.equal(
      preflightRes.headers.get('access-control-allow-methods'),
      'GET,HEAD,PUT,POST,DELETE,PATCH,QUERY',
      'Default allow-methods should match Hono defaults'
    );

    const getRes = await defaultApp.request('http://localhost/api/data', {
      method: 'GET',
      headers: {
        'Origin': 'https://example.com'
      }
    });
    assert.equal(getRes.status, 200, 'Simple GET request should return 200');
    assert.equal(getRes.headers.get('access-control-allow-origin'), '*', 'GET response should include allow-origin *');
    const data = await getRes.json();
    assert.deepEqual(data, { message: 'hello' });
  }

  // 3. cors supports custom origin, allowMethods, allowHeaders, exposeHeaders, maxAge, and credentials options
  {
    const customApp = createApp({
      origin: 'https://example.com',
      allowMethods: ['GET', 'POST', 'PUT', 'DELETE'],
      allowHeaders: ['X-Custom-Header', 'Content-Type', 'Authorization'],
      exposeHeaders: ['X-Response-Id', 'Content-Length'],
      maxAge: 600,
      credentials: true
    });

    const preflightRes = await customApp.request('http://localhost/api/items', {
      method: 'OPTIONS',
      headers: {
        'Origin': 'https://example.com',
        'Access-Control-Request-Method': 'POST',
        'Access-Control-Request-Headers': 'X-Custom-Header, Content-Type'
      }
    });
    assert.equal(preflightRes.status, 204, 'Custom CORS preflight OPTIONS should return 204');
    assert.equal(preflightRes.headers.get('access-control-allow-origin'), 'https://example.com');
    assert.equal(preflightRes.headers.get('access-control-allow-methods'), 'GET,POST,PUT,DELETE');
    assert.equal(preflightRes.headers.get('access-control-allow-headers'), 'X-Custom-Header,Content-Type,Authorization');
    assert.equal(preflightRes.headers.get('access-control-max-age'), '600');
    assert.equal(preflightRes.headers.get('access-control-allow-credentials'), 'true');
    assert.equal(preflightRes.headers.get('vary'), 'Origin, Access-Control-Request-Headers');

    const postRes = await customApp.request('http://localhost/api/items', {
      method: 'POST',
      headers: {
        'Origin': 'https://example.com',
        'Content-Type': 'application/json',
        'X-Custom-Header': 'test-val'
      },
      body: JSON.stringify({ name: 'test' })
    });
    assert.equal(postRes.status, 200, 'Custom CORS POST should return 200');
    assert.equal(postRes.headers.get('access-control-allow-origin'), 'https://example.com');
    assert.equal(postRes.headers.get('access-control-allow-credentials'), 'true');
    assert.equal(postRes.headers.get('access-control-expose-headers'), 'X-Response-Id,Content-Length');
    assert.equal(postRes.headers.get('x-response-id'), 'resp-123');
    const postData = await postRes.json();
    assert.deepEqual(postData, { created: true });
  }

  // 4. cors supports dynamic origin resolver functions and sets Vary: Origin header
  {
    const dynamicApp = createApp({
      origin: (origin) => {
        if (origin.endsWith('.example.com')) {
          return origin;
        }
        return 'https://example.com';
      },
      credentials: true
    });

    const subRes = await dynamicApp.request('http://localhost/api/profile', {
      headers: { 'Origin': 'https://sub.example.com' }
    });
    assert.equal(subRes.status, 200);
    assert.equal(subRes.headers.get('access-control-allow-origin'), 'https://sub.example.com');
    assert.equal(subRes.headers.get('access-control-allow-credentials'), 'true');
    assert.equal(subRes.headers.get('vary'), 'Origin');

    const nonSubRes = await dynamicApp.request('http://localhost/api/profile', {
      headers: { 'Origin': 'https://example.org' }
    });
    assert.equal(nonSubRes.status, 200);
    assert.equal(nonSubRes.headers.get('access-control-allow-origin'), 'https://example.com');
    assert.equal(nonSubRes.headers.get('access-control-allow-credentials'), 'true');
    assert.equal(nonSubRes.headers.get('vary'), 'Origin');
  }

  console.log('Contract assertions for hono.cors passed.');
}

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

Seeder de origen

anónimo