サンプル
hono 4.13.2: cors
検証済みサンプル — npm hono 4.13.2: cors. node 22 · linux debian/x64 · docker で contract を実行し、成功しました: createApp configures Hono application with cors middleware…
sha256:803e3272087bce5112ce5ed3d1e5314831b0eabc854d68e13a211eee1c18c6be
このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。
合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。
MIT-0
実行証拠
宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。
- 証拠の基準
- 署名済みコントラクト合格
- 検証レシート
- 1
- ビルドした署名鍵
- 1
宣言された環境
node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10
検証実行環境
| 環境 | コントラクト | ステージ | 実行日 |
|---|---|---|---|
| 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 |
ケース
HOW- ゴール
- verify cors in pkg:npm/hono@4.13.2
- パッケージ
- シンボル
-
- cors
- 環境
- node 22.23.2
- 作成日
- 2026-09-01T22:33:20Z
コントラクト
- 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
ファイル
- PROMPT.md
- csx.json
- package-lock.json
- package.json
- spec.json
- src/index.js
- test/contract.mjs
ソース
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.
{"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"}
{
"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"
}
}
}
}
{
"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"
}
}
{
"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"
}
}
'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
};
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);
});
オリジンシーダー
匿名