CodeSampleX

Пример

hono 4.13.7: secure-headers

Проверенный пример — npm hono 4.13.7: secure-headers. Контракт выполнен на node 22 · linux debian/x64 · docker и пройден: secureHeaders is exported as a…

sha256:682a94ccd9568d63b3d31e1d2108f5310e836bdb16f17357ed059c6523d8db87

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. 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-06

Кейс

HOW
Цель
verify pkg:npm/hono@4.13.7
Пакеты
Символы
  • hono/secure-headers
Окружение
node 22.23.2
Создан
2026-09-06T03:48:29Z

Контракт

  1. secureHeaders is exported as a middleware factory function and NONCE as a marker from hono/secure-headers
  2. secureHeaders middleware injects standard security headers including nosniff, SAMEORIGIN, and no-referrer
  3. secureHeaders middleware applies default Strict-Transport-Security header with max-age and includeSubDomains
  4. secureHeaders middleware allows disabling specific default headers or overriding option values
  5. secureHeaders middleware formats custom Content-Security-Policy directives
  6. secureHeaders middleware generates dynamic CSP nonce with NONCE token and stores it in context secureHeadersNonce

Файлы

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

Скачать артефакт с исходным кодом (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 pkg:npm/hono@4.13.7
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/hono@4.13.7
Demonstrate these symbols/APIs:
  - hono/secure-headers

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:4ec2c6de1a180d7ff9bb9a3687f7b22926dc7bebee53ce82b9aecd2a75493684","contract":["secureHeaders is exported as a middleware factory function and NONCE as a marker from hono/secure-headers","secureHeaders middleware injects standard security headers including nosniff, SAMEORIGIN, and no-referrer","secureHeaders middleware applies default Strict-Transport-Security header with max-age and includeSubDomains","secureHeaders middleware allows disabling specific default headers or overriding option values","secureHeaders middleware formats custom Content-Security-Policy directives","secureHeaders middleware generates dynamic CSP nonce with NONCE token and stores it in context secureHeadersNonce"],"goal":"verify pkg:npm/hono@4.13.7","kind":"HOW","packages":["pkg:npm/hono@4.13.7"],"schemaVersion":1,"symbols":["hono/secure-headers"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"esm","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.7"],"schemaVersion":1,"subject":"pkg:npm/hono@4.13.7","symbols":["hono/secure-headers"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-hono-secure-headers",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-hono-secure-headers",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "hono": "4.13.7"
      }
    },
    "node_modules/hono": {
      "version": "4.13.7",
      "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.7.tgz",
      "integrity": "sha512-c8/gF9ac8Y78/agExVocyLevgR+JlpNB444Py0FSX8pJoPdYUfUzRcXtYEYGwt6l19qIlVZPN5Mfsw9jFShmQQ==",
      "license": "MIT",
      "engines": {
        "node": ">=16.9.0"
      }
    }
  }
}
package.json
{
  "name": "sample-hono-secure-headers",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "license": "MIT-0",
  "dependencies": {
    "hono": "4.13.7"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/hono@4.13.7",
  "kind": "HOW",
  "packages": [
    "pkg:npm/hono@4.13.7"
  ],
  "symbols": [
    "hono/secure-headers"
  ]
}
test/contract.mjs
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { fileURLToPath } from 'node:url';
import { Hono } from 'hono';
import { secureHeaders, NONCE } from 'hono/secure-headers';

// Contract 1: secureHeaders is exported as a middleware factory function and NONCE as a marker from hono/secure-headers
{
  assert.strictEqual(typeof secureHeaders, 'function', 'secureHeaders must be a function');
  assert.strictEqual(typeof NONCE, 'function', 'NONCE must be a function');

  // Verify pinned package version
  const honoEntryUrl = import.meta.resolve('hono');
  const pkgJsonPath = fileURLToPath(new URL('../package.json', honoEntryUrl));
  assert.ok(fs.existsSync(pkgJsonPath), 'hono package.json must exist');
  const pkgJson = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf8'));
  assert.strictEqual(pkgJson.name, 'hono');
  assert.strictEqual(pkgJson.version, '4.13.7');
  assert.ok(pkgJson.exports['./secure-headers'], 'hono must export ./secure-headers subpath');
}

// Contract 2: secureHeaders middleware injects standard security headers including nosniff, SAMEORIGIN, and no-referrer
{
  const app = new Hono();
  app.use('*', secureHeaders());
  app.get('/default-headers', (c) => c.text('ok'));

  const res = await app.request('http://localhost/default-headers');
  assert.strictEqual(res.status, 200, 'GET /default-headers returns HTTP 200');

  assert.strictEqual(res.headers.get('x-content-type-options'), 'nosniff');
  assert.strictEqual(res.headers.get('x-frame-options'), 'SAMEORIGIN');
  assert.strictEqual(res.headers.get('referrer-policy'), 'no-referrer');
  assert.strictEqual(res.headers.get('x-xss-protection'), '0');
  assert.strictEqual(res.headers.get('cross-origin-opener-policy'), 'same-origin');
  assert.strictEqual(res.headers.get('cross-origin-resource-policy'), 'same-origin');
  assert.strictEqual(res.headers.get('x-download-options'), 'noopen');
  assert.strictEqual(res.headers.get('x-permitted-cross-domain-policies'), 'none');
}

// Contract 3: secureHeaders middleware applies default Strict-Transport-Security header with max-age and includeSubDomains
{
  const app = new Hono();
  app.use('*', secureHeaders());
  app.get('/hsts', (c) => c.text('hsts'));

  const res = await app.request('http://localhost/hsts');
  assert.strictEqual(res.status, 200);

  const hsts = res.headers.get('strict-transport-security');
  assert.ok(hsts, 'Strict-Transport-Security header must be present');
  assert.ok(hsts.includes('max-age='), 'HSTS must specify max-age');
  assert.ok(hsts.includes('includeSubDomains'), 'HSTS must include includeSubDomains');
}

// Contract 4: secureHeaders middleware allows disabling specific default headers or overriding option values
{
  const app = new Hono();
  app.use('*', secureHeaders({
    xFrameOptions: 'DENY',
    strictTransportSecurity: false,
    xXssProtection: false,
  }));
  app.get('/custom-options', (c) => c.text('custom'));

  const res = await app.request('http://localhost/custom-options');
  assert.strictEqual(res.status, 200);

  assert.strictEqual(res.headers.get('x-frame-options'), 'DENY', 'x-frame-options should be overridden to DENY');
  assert.strictEqual(res.headers.get('strict-transport-security'), null, 'strict-transport-security should be disabled');
  assert.strictEqual(res.headers.get('x-xss-protection'), null, 'x-xss-protection should be disabled');
  // untouched defaults remain active
  assert.strictEqual(res.headers.get('x-content-type-options'), 'nosniff');
}

// Contract 5: secureHeaders middleware formats custom Content-Security-Policy directives
{
  const app = new Hono();
  app.use('*', secureHeaders({
    contentSecurityPolicy: {
      defaultSrc: ["'self'"],
      scriptSrc: ["'self'", 'https://example.com'],
      styleSrc: ["'self'", "'unsafe-inline'"],
      objectSrc: ["'none'"],
    },
  }));
  app.get('/csp', (c) => c.text('csp'));

  const res = await app.request('http://localhost/csp');
  assert.strictEqual(res.status, 200);

  const csp = res.headers.get('content-security-policy');
  assert.ok(csp, 'Content-Security-Policy header must be present');
  assert.ok(csp.includes("default-src 'self'"));
  assert.ok(csp.includes("script-src 'self' https://example.com"));
  assert.ok(csp.includes("style-src 'self' 'unsafe-inline'"));
  assert.ok(csp.includes("object-src 'none'"));
}

// Contract 6: secureHeaders middleware generates dynamic CSP nonce with NONCE token and stores it in context secureHeadersNonce
{
  const app = new Hono();
  app.use('*', secureHeaders({
    contentSecurityPolicy: {
      scriptSrc: [NONCE],
    },
  }));
  app.get('/nonce', (c) => {
    const nonce = c.get('secureHeadersNonce');
    return c.json({ nonce });
  });

  const res = await app.request('http://localhost/nonce');
  assert.strictEqual(res.status, 200);

  const data = await res.json();
  assert.ok(typeof data.nonce === 'string' && data.nonce.length > 0, 'Context must contain non-empty secureHeadersNonce');

  const csp = res.headers.get('content-security-policy');
  assert.ok(csp, 'Content-Security-Policy header must be present');
  assert.ok(csp.includes(`'nonce-${data.nonce}'`), 'CSP header must contain the generated nonce matching context');
}

console.log('CONTRACT PASS: All hono/secure-headers assertions passed.');

Исходный сидер

аноним