CodeSampleX

Beispiel

hono 4.13.1: cors

Verifiziertes Beispiel für npm hono 4.13.1: cors. Der Vertrag lief auf node 22 · linux alpine/x64 · docker und bestand: createApp configures Hono application…

sha256:68473d0af5144b70b8f240e19fbc22f3fdb17112bf8039fde9e9bd01a29affaa

Dieses Netzwerk bietet eine Sache: ein Sample, das baut. Es hat es in einer Sandbox ausgeführt und die signierte Quittung behalten. Es bewertet nichts und garantiert nichts — ob derselbe Code bei Ihnen baut, hat es nicht gemessen. Wie viele verschiedene Signaturschlüssel eine bestandene Vertragsquittung eingereicht haben. Einer ist der Autor allein; mehr als einer heißt, jemand anderes hat es auch gebaut. Ein Schlüssel wird selbst erzeugt und hat keine registrierte Identität dahinter — gezählt werden Schlüssel, nicht Personen. MIT-0

Ausführungsbelege

Die deklarierte Umgebung und die signierten Läufe stehen getrennt, damit Sie genau sehen, was dieses Sample ausgeführt hat und wo.

Beleggrundlage
Signierter Vertrag bestanden
Verifizierungsbelege
1
Signaturschlüssel, die es gebaut haben
1
Deklarierte Umgebung linux 24 · ubuntu · glibc 2.39 x64 npm

Umgebungen der Verifizierungsläufe

Umgebung Contract Stufen Lauf
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-28

Fall

HOW
Ziel
verify hono.cors middleware configuration and CORS header handling in pkg:npm/hono@4.13.1
Pakete
Symbole
  • hono/cors
Erstellt
2026-08-28T05:50:59Z

Contract

  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

Dateien

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

Quellartefakt herunterladen (tar.gz)

Quelltext

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 middleware configuration and CORS header handling in pkg:npm/hono@4.13.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/hono@4.13.1
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:bf06785960fad4743b7f85528f7b14b8a9797077c5fd7f9008cc513498ed1ab3","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 hono.cors middleware configuration and CORS header handling in pkg:npm/hono@4.13.1","kind":"HOW","packages":["pkg:npm/hono@4.13.1"],"schemaVersion":1,"symbols":["hono/cors"]},"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.1"],"schemaVersion":1,"subject":"pkg:npm/hono@4.13.1","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",
      "license": "MIT-0",
      "dependencies": {
        "hono": "4.13.1"
      }
    },
    "node_modules/hono": {
      "version": "4.13.1",
      "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.1.tgz",
      "integrity": "sha512-kdJoFVv2xmayw6cY09H7AbMJMt8Jn5jdlEdXsP7AGBdF2DIptVlKlOLKXP41yPip4/a3yQPv9gVcJYI8YY04dw==",
      "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 hono/cors in hono@4.13.1",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "hono": "4.13.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify hono.cors middleware configuration and CORS header handling in pkg:npm/hono@4.13.1",
  "kind": "HOW",
  "packages": [
    "pkg:npm/hono@4.13.1"
  ],
  "symbols": [
    "hono/cors"
  ]
}
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 hono/cors contract assertions passed successfully.');
}

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

Ursprungs-Seeder

anonym