CodeSampleX

샘플

hono 4.13.2: cors

검증된 샘플 — npm hono 4.13.2: cors. node 22 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: cors is exported as a middleware factory function from hono/cors

sha256:6a7203349391129e83a1cffed360bcc0bdf44e1ad3c0a3cee8b1d6b564c9c19f

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

검증 실행 환경

환경 컨트랙트 단계 실행일
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

케이스

HOW
목표
verify hono.cors in pkg:npm/hono@4.13.2
패키지
심벌
  • hono.cors
환경
node 22.23.2
생성일
2026-08-27T22:05:22Z

컨트랙트

  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

파일

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

소스 아티팩트 내려받기 (tar.gz)

소스

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);
});

오리진 시더

익명