サンプル
cors 2.8.6: cors
検証済みサンプル — npm cors 2.8.6: cors. node 22 · linux alpine/x64 · docker で contract を実行し、成功しました: cors is exported as a function from cors package
sha256:967878c4e4e2dc3fcaea821e96b777ab8d21019aa36026307e3ae828601839fe
このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。
合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。
MIT-0
実行証拠
宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。
- 証拠の基準
- 署名済みコントラクト合格
- 検証レシート
- 1
- ビルドした署名鍵
- 1
宣言された環境
linux 24 · ubuntu · glibc 2.39 x64 npm
検証実行環境
| 環境 | コントラクト | ステージ | 実行日 |
|---|---|---|---|
| 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-26 |
ケース
HOW- ゴール
- verify pkg:npm/cors@2.8.6
- パッケージ
- シンボル
-
- cors
- 作成日
- 2026-08-26T08:54:13Z
コントラクト
- cors is exported as a function from cors package
- cors() sets default Access-Control-Allow-Origin to wildcard (*)
- cors({ origin: true }) reflects the request Origin header and appends Vary: Origin
- cors({ origin: [...] }) allows matching origin from allowed array and suppresses origin header for non-matching origins
- cors({ credentials: true }) sets Access-Control-Allow-Credentials to true
- cors handles OPTIONS preflight request by default with status 204, Content-Length 0, and configured methods/headers
- cors({ optionsSuccessStatus: 200 }) responds with status 200 for OPTIONS preflight requests
- cors supports dynamic options callback to determine configuration per request and forwards callback errors
ファイル
- 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 pkg:npm/cors@2.8.6
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:npm/cors@2.8.6
Demonstrate these symbols/APIs:
- 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.
{"case":{"caseId":"case:sha256:3d6cd8de858490b8a58ab7383bcfe5f6fe0d4495a9e06428b5656642af1b8e99","contract":["cors is exported as a function from cors package","cors() sets default Access-Control-Allow-Origin to wildcard (*)","cors({ origin: true }) reflects the request Origin header and appends Vary: Origin","cors({ origin: [...] }) allows matching origin from allowed array and suppresses origin header for non-matching origins","cors({ credentials: true }) sets Access-Control-Allow-Credentials to true","cors handles OPTIONS preflight request by default with status 204, Content-Length 0, and configured methods/headers","cors({ optionsSuccessStatus: 200 }) responds with status 200 for OPTIONS preflight requests","cors supports dynamic options callback to determine configuration per request and forwards callback errors"],"goal":"verify pkg:npm/cors@2.8.6","kind":"HOW","packages":["pkg:npm/cors@2.8.6"],"schemaVersion":1,"symbols":["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/cors@2.8.6"],"schemaVersion":1,"subject":"pkg:npm/cors@2.8.6","symbols":["cors"],"verifierAdapter":"node-typescript@1"}
{
"name": "sample-cors",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "sample-cors",
"version": "1.0.0",
"license": "MIT-0",
"dependencies": {
"cors": "2.8.6"
}
},
"node_modules/cors": {
"version": "2.8.6",
"resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz",
"integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==",
"license": "MIT",
"dependencies": {
"object-assign": "^4",
"vary": "^1"
},
"engines": {
"node": ">= 0.10"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/object-assign": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
"integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/vary": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
"integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
}
}
}
{
"name": "sample-cors",
"version": "1.0.0",
"private": true,
"description": "Clean-room code sample for pkg:npm/cors@2.8.6",
"main": "src/index.js",
"license": "MIT-0",
"dependencies": {
"cors": "2.8.6"
}
}
{
"schemaVersion": 1,
"goal": "verify pkg:npm/cors@2.8.6",
"kind": "HOW",
"packages": [
"pkg:npm/cors@2.8.6"
],
"symbols": [
"cors"
]
}
const cors = require('cors');
/**
* Creates a default CORS middleware.
* @returns {Function} Express/Connect middleware.
*/
function createDefaultCors() {
return cors();
}
/**
* Creates a CORS middleware with origin configuration.
* @param {boolean|string|RegExp|Array<string>|Function} origin
* @returns {Function} Express/Connect middleware.
*/
function createOriginCors(origin) {
return cors({ origin });
}
/**
* Creates a CORS middleware with custom options.
* @param {Object} options
* @returns {Function} Express/Connect middleware.
*/
function createCustomCors(options) {
return cors(options);
}
/**
* Helper to create a mock HTTP request and response for testing CORS.
* @param {Object} [options]
* @returns {{ req: Object, res: Object, headers: Object, isEnded: () => boolean }}
*/
function createMockHttp(options = {}) {
const headers = {};
const req = {
method: options.method || 'GET',
headers: options.headers || {}
};
let ended = false;
const res = {
statusCode: 200,
getHeader(name) {
return headers[name.toLowerCase()];
},
setHeader(name, value) {
headers[name.toLowerCase()] = value;
},
end() {
ended = true;
}
};
return {
req,
res,
headers,
isEnded: () => ended
};
}
module.exports = {
cors,
createDefaultCors,
createOriginCors,
createCustomCors,
createMockHttp
};
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
const {
cors,
createDefaultCors,
createOriginCors,
createCustomCors,
createMockHttp
} = require('../src/index.js');
async function runTests() {
// 1. cors is exported as a function from cors package
assert.equal(typeof cors, 'function', 'cors must be exported as a function');
assert.equal(typeof createDefaultCors, 'function', 'createDefaultCors helper must be a function');
assert.equal(typeof createOriginCors, 'function', 'createOriginCors helper must be a function');
assert.equal(typeof createCustomCors, 'function', 'createCustomCors helper must be a function');
// 2. cors() sets default Access-Control-Allow-Origin to wildcard (*)
{
const mw = createDefaultCors();
const { req, res, headers } = createMockHttp({ headers: { origin: 'https://example.com' } });
let nextCalled = false;
mw(req, res, () => { nextCalled = true; });
assert.equal(nextCalled, true, 'Default cors middleware must call next');
assert.equal(headers['access-control-allow-origin'], '*', 'Default origin must be wildcard *');
}
// 3. cors({ origin: true }) reflects the request Origin header and appends Vary: Origin
{
const mw = createOriginCors(true);
const { req, res, headers } = createMockHttp({ headers: { origin: 'https://client.example.com' } });
let nextCalled = false;
mw(req, res, () => { nextCalled = true; });
assert.equal(nextCalled, true, 'Origin reflection middleware must call next');
assert.equal(headers['access-control-allow-origin'], 'https://client.example.com', 'Origin must be reflected from request header');
assert.equal(headers['vary'], 'Origin', 'Vary header must be set to Origin');
}
// 4. cors({ origin: [...] }) allows matching origin from allowed array and suppresses origin header for non-matching origins
{
const allowedOrigins = ['https://app1.example.com', 'https://app2.example.com'];
const mw = createOriginCors(allowedOrigins);
// Matching origin
const matching = createMockHttp({ headers: { origin: 'https://app2.example.com' } });
mw(matching.req, matching.res, () => {});
assert.equal(matching.headers['access-control-allow-origin'], 'https://app2.example.com', 'Allowed origin in array must be permitted');
assert.equal(matching.headers['vary'], 'Origin', 'Vary must be Origin for array matching');
// Non-matching origin
const nonMatching = createMockHttp({ headers: { origin: 'https://unauthorized.example.com' } });
mw(nonMatching.req, nonMatching.res, () => {});
assert.equal(nonMatching.headers['access-control-allow-origin'], undefined, 'Disallowed origin must not receive Access-Control-Allow-Origin');
assert.equal(nonMatching.headers['vary'], 'Origin', 'Vary header must still be set to Origin');
}
// 5. cors({ credentials: true }) sets Access-Control-Allow-Credentials to true
{
const mw = createCustomCors({ origin: 'https://secure.example.com', credentials: true });
const { req, res, headers } = createMockHttp({ headers: { origin: 'https://secure.example.com' } });
mw(req, res, () => {});
assert.equal(headers['access-control-allow-origin'], 'https://secure.example.com', 'Allowed origin must be set');
assert.equal(headers['access-control-allow-credentials'], 'true', 'Credentials header must be set to true');
}
// 6. cors handles OPTIONS preflight request by default with status 204, Content-Length 0, and configured methods/headers
{
const mw = createCustomCors({
origin: 'https://api.example.com',
methods: ['GET', 'POST', 'PUT'],
allowedHeaders: ['Authorization', 'Content-Type'],
exposedHeaders: ['X-Request-Id'],
maxAge: 7200
});
const { req, res, headers, isEnded } = createMockHttp({
method: 'OPTIONS',
headers: {
origin: 'https://api.example.com',
'access-control-request-method': 'POST',
'access-control-request-headers': 'authorization, content-type'
}
});
let nextCalled = false;
mw(req, res, () => { nextCalled = true; });
assert.equal(nextCalled, false, 'Preflight handler must terminate and not call next by default');
assert.equal(isEnded(), true, 'Preflight handler must end response');
assert.equal(res.statusCode, 204, 'Default preflight status code must be 204');
assert.equal(headers['content-length'], '0', 'Preflight Content-Length must be 0');
assert.equal(headers['access-control-allow-origin'], 'https://api.example.com', 'Preflight origin header must match');
assert.equal(headers['access-control-allow-methods'], 'GET,POST,PUT', 'Preflight allowed methods must match');
assert.equal(headers['access-control-allow-headers'], 'Authorization,Content-Type', 'Preflight allowed headers must match');
assert.equal(headers['access-control-max-age'], '7200', 'Preflight max age must match');
}
// 7. cors({ optionsSuccessStatus: 200 }) responds with status 200 for OPTIONS preflight requests
{
const mw = createCustomCors({
origin: 'https://legacy.example.com',
optionsSuccessStatus: 200
});
const { req, res, headers, isEnded } = createMockHttp({
method: 'OPTIONS',
headers: { origin: 'https://legacy.example.com' }
});
let nextCalled = false;
mw(req, res, () => { nextCalled = true; });
assert.equal(nextCalled, false, 'Preflight handler must terminate');
assert.equal(isEnded(), true, 'Preflight handler must end response');
assert.equal(res.statusCode, 200, 'Preflight status code must be 200 when optionsSuccessStatus is 200');
assert.equal(headers['content-length'], '0', 'Preflight Content-Length must be 0');
}
// 8. cors supports dynamic options callback to determine configuration per request and forwards callback errors
{
// Success path with dynamic options callback
const dynamicMw = cors((req, callback) => {
const isAllowed = req.headers.origin === 'https://dynamic.example.com';
callback(null, { origin: isAllowed });
});
const allowedHttp = createMockHttp({ headers: { origin: 'https://dynamic.example.com' } });
dynamicMw(allowedHttp.req, allowedHttp.res, () => {});
assert.equal(allowedHttp.headers['access-control-allow-origin'], 'https://dynamic.example.com', 'Dynamic allowed origin must be set');
// Error path with dynamic options callback
const errorMw = cors((req, callback) => {
callback(new Error('CORS rejected by policy'));
});
const errorHttp = createMockHttp({ headers: { origin: 'https://blocked.example.com' } });
let passedError = null;
errorMw(errorHttp.req, errorHttp.res, (err) => {
passedError = err;
});
assert.ok(passedError instanceof Error, 'Callback error must be forwarded to next(err)');
assert.equal(passedError.message, 'CORS rejected by policy', 'Error message must match callback error');
}
console.log('All contract assertions for cors passed successfully.');
}
runTests().catch((err) => {
console.error('Contract test failed:', err);
process.exit(1);
});
オリジンシーダー
匿名