CodeSampleX

Exemplo

hono 4.13.2: cors

Amostra verificada para npm hono 4.13.2: cors. O contrato rodou em node 22 · linux debian/x64 · docker e passou: createApp configures Hono application with…

sha256:803e3272087bce5112ce5ed3d1e5314831b0eabc854d68e13a211eee1c18c6be

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

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-01

Caso

HOW
Objetivo
verify cors in pkg:npm/hono@4.13.2
Pacotes
Símbolos
  • cors
Ambiente
node 22.23.2
Criado
2026-09-01T22:33:20Z

Contrato

  1. createApp configures Hono application with cors middleware supporting wildcard, restricted, and dynamic origin policies
  2. cors middleware handles preflight OPTIONS requests and sets Access-Control-Allow-Origin header for wildcard origin
  3. cors middleware enforces restricted origin whitelist with allowed methods, custom headers, credentials, and maxAge
  4. cors middleware exposes specified custom response headers via Access-Control-Expose-Headers on successful requests
  5. cors middleware rejects requests from origins outside the configured whitelist
  6. cors middleware validates dynamic origins using a custom callback function

Arquivos

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • 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 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:
  - cors
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

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:38a6040415a17fe882cbfc21416c67470c4d4d20803ad321108b7723746c4881","constraints":{"executionContext":"node"},"contract":["createApp configures Hono application with cors middleware supporting wildcard, restricted, and dynamic origin policies","cors middleware handles preflight OPTIONS requests and sets Access-Control-Allow-Origin header for wildcard origin","cors middleware enforces restricted origin whitelist with allowed methods, custom headers, credentials, and maxAge","cors middleware exposes specified custom response headers via Access-Control-Expose-Headers on successful requests","cors middleware rejects requests from origins outside the configured whitelist","cors middleware validates dynamic origins using a custom callback function"],"goal":"verify cors in pkg:npm/hono@4.13.2","kind":"HOW","packages":["pkg:npm/hono@4.13.2"],"schemaVersion":1,"symbols":["cors"]},"contractCommand":["node","test/contract.mjs"],"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":["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",
      "license": "MIT-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 code sample for cors in hono@4.13.2",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "hono": "4.13.2"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify cors in pkg:npm/hono@4.13.2",
  "kind": "HOW",
  "packages": [
    "pkg:npm/hono@4.13.2"
  ],
  "symbols": [
    "cors"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.js
'use strict';

const { Hono } = require('hono');
const { cors } = require('hono/cors');

/**
 * Creates and configures a Hono application with various CORS policies.
 *
 * @returns {Hono}
 */
function createApp() {
  const app = new Hono();

  // 1. Wildcard public CORS endpoint
  app.use(
    '/api/public/*',
    cors({
      origin: '*',
      allowMethods: ['GET', 'HEAD', 'OPTIONS']
    })
  );

  app.get('/api/public/data', (c) => {
    return c.json({ message: 'public accessible content' });
  });

  // 2. Strict restricted CORS endpoint with explicit allowed origins, custom methods, headers, credentials, and maxAge
  app.use(
    '/api/restricted/*',
    cors({
      origin: ['https://app.example.com', 'https://admin.example.com'],
      allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
      allowHeaders: ['Content-Type', 'Authorization', 'X-Custom-Header'],
      exposeHeaders: ['X-Total-Count', 'X-Request-Id'],
      maxAge: 600,
      credentials: true
    })
  );

  app.post('/api/restricted/items', async (c) => {
    const body = await c.req.json();
    c.header('X-Request-Id', 'req-12345');
    c.header('X-Total-Count', '1');
    return c.json({ created: true, item: body }, 201);
  });

  // 3. Dynamic origin validation with callback function
  app.use(
    '/api/dynamic/*',
    cors({
      origin: (origin) => {
        if (origin && origin.endsWith('.example.com')) {
          return origin;
        }
        return undefined;
      },
      credentials: true
    })
  );

  app.get('/api/dynamic/profile', (c) => {
    return c.json({ user: 'tester', role: 'admin' });
  });

  return app;
}

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

const require = createRequire(import.meta.url);
const {
  createApp,
  Hono,
  cors
} = 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 export must be a function');
  assert.equal(typeof cors, 'function', 'cors export must be a function');

  // 2. Wildcard CORS preflight & GET request handling
  const publicPreflight = await app.fetch(
    new Request('http://localhost/api/public/data', {
      method: 'OPTIONS',
      headers: {
        Origin: 'https://public.example.com',
        'Access-Control-Request-Method': 'GET'
      }
    })
  );
  assert.equal(publicPreflight.status, 204, 'preflight should return 204 No Content');
  assert.equal(publicPreflight.headers.get('access-control-allow-origin'), '*', 'wildcard origin should allow *');

  const publicGet = await app.fetch(
    new Request('http://localhost/api/public/data', {
      headers: { Origin: 'https://public.example.com' }
    })
  );
  assert.equal(publicGet.status, 200, 'public GET should return 200');
  assert.equal(publicGet.headers.get('access-control-allow-origin'), '*', 'public GET should set allow-origin *');
  const publicData = await publicGet.json();
  assert.deepEqual(publicData, { message: 'public accessible content' });

  // 3. Restricted CORS preflight with credentials, custom headers, maxAge
  const restrictedPreflight = await app.fetch(
    new Request('http://localhost/api/restricted/items', {
      method: 'OPTIONS',
      headers: {
        Origin: 'https://app.example.com',
        'Access-Control-Request-Method': 'POST',
        'Access-Control-Request-Headers': 'Content-Type, X-Custom-Header'
      }
    })
  );
  assert.equal(restrictedPreflight.status, 204, 'preflight should return 204 No Content');
  assert.equal(
    restrictedPreflight.headers.get('access-control-allow-origin'),
    'https://app.example.com',
    'allowed origin should be reflected'
  );
  assert.equal(
    restrictedPreflight.headers.get('access-control-allow-credentials'),
    'true',
    'credentials should be true'
  );
  assert.equal(
    restrictedPreflight.headers.get('access-control-max-age'),
    '600',
    'maxAge should be 600'
  );
  const allowMethods = restrictedPreflight.headers.get('access-control-allow-methods') || '';
  assert.ok(allowMethods.includes('POST'), 'allow-methods should include POST');
  const allowHeaders = restrictedPreflight.headers.get('access-control-allow-headers') || '';
  assert.ok(allowHeaders.includes('X-Custom-Header'), 'allow-headers should include X-Custom-Header');
  const varyHeader = restrictedPreflight.headers.get('vary') || '';
  assert.ok(varyHeader.includes('Origin'), 'Vary should contain Origin');

  // 4. Restricted CORS POST request with exposed headers
  const restrictedPost = await app.fetch(
    new Request('http://localhost/api/restricted/items', {
      method: 'POST',
      headers: {
        Origin: 'https://app.example.com',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ name: 'Gadget', price: 99 })
    })
  );
  assert.equal(restrictedPost.status, 201, 'restricted POST should return 201 Created');
  assert.equal(
    restrictedPost.headers.get('access-control-allow-origin'),
    'https://app.example.com',
    'allowed origin should be set on response'
  );
  assert.equal(
    restrictedPost.headers.get('access-control-allow-credentials'),
    'true',
    'credentials should be set on response'
  );
  const exposeHeaders = restrictedPost.headers.get('access-control-expose-headers') || '';
  assert.ok(exposeHeaders.includes('X-Request-Id'), 'expose-headers should include X-Request-Id');
  assert.ok(exposeHeaders.includes('X-Total-Count'), 'expose-headers should include X-Total-Count');
  const postData = await restrictedPost.json();
  assert.deepEqual(postData, { created: true, item: { name: 'Gadget', price: 99 } });

  // 5. Restricted CORS rejected origin
  const rejectedPreflight = await app.fetch(
    new Request('http://localhost/api/restricted/items', {
      method: 'OPTIONS',
      headers: {
        Origin: 'https://other.example.com',
        'Access-Control-Request-Method': 'POST'
      }
    })
  );
  assert.notEqual(
    rejectedPreflight.headers.get('access-control-allow-origin'),
    'https://other.example.com',
    'unauthorized origin must not be allowed'
  );

  // 6. Dynamic origin validation with callback function
  const dynamicAllowed = await app.fetch(
    new Request('http://localhost/api/dynamic/profile', {
      headers: { Origin: 'https://service.example.com' }
    })
  );
  assert.equal(dynamicAllowed.status, 200, 'dynamic endpoint should return 200');
  assert.equal(
    dynamicAllowed.headers.get('access-control-allow-origin'),
    'https://service.example.com',
    'dynamic valid subdomain should be allowed'
  );
  assert.equal(
    dynamicAllowed.headers.get('access-control-allow-credentials'),
    'true',
    'dynamic credentials should be true'
  );

  const dynamicDisallowed = await app.fetch(
    new Request('http://localhost/api/dynamic/profile', {
      headers: { Origin: 'http://localhost:8080' }
    })
  );
  assert.equal(dynamicDisallowed.status, 200, 'endpoint returns 200');
  assert.equal(
    dynamicDisallowed.headers.get('access-control-allow-origin'),
    null,
    'disallowed origin must not receive Access-Control-Allow-Origin header'
  );

  console.log('All cors contract assertions passed successfully.');
}

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

Seeder de origem

anônimo