CodeSampleX

Exemplo

hono 4.13.7: secureHeaders

Amostra verificada para npm hono 4.13.7: secureHeaders. O contrato rodou em node 22 · linux debian/x64 · docker e passou: createDefaultApp configures Hono…

sha256:c46ab0d2782055c7fd25f91be89634d158b587c2ab8bd2d5bcd62529c51aa0e1

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
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

Caso

HOW
Objetivo
verify secureHeaders in pkg:npm/hono@4.13.7
Pacotes
Símbolos
  • secureHeaders
Ambiente
node 22.23.2
Criado
2026-09-06T04:09:17Z

Contrato

  1. createDefaultApp configures Hono application with default secure headers including X-Content-Type-Options, X-Frame-Options, Strict-Transport-Security, and Cross-Origin policies
  2. secureHeaders middleware applies custom Content-Security-Policy with script-src and NONCE handler, injecting dynamic nonce into context
  3. secureHeaders middleware applies custom Permissions-Policy directives for restricted browser features
  4. secureHeaders middleware supports configuring Cross-Origin-Embedder-Policy and Referrer-Policy
  5. secureHeaders middleware allows disabling specific default security headers when set to false
  6. secureHeaders middleware supports Content-Security-Policy-Report-Only mode with reportUri directive

Arquivos

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

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

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 secureHeaders in 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:
  - secureHeaders

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:f803fdff8899f21503dc8f20f614bd6c311672346a8e07bf59e60c542b3d4058","constraints":{"executionContext":"node"},"contract":["createDefaultApp configures Hono application with default secure headers including X-Content-Type-Options, X-Frame-Options, Strict-Transport-Security, and Cross-Origin policies","secureHeaders middleware applies custom Content-Security-Policy with script-src and NONCE handler, injecting dynamic nonce into context","secureHeaders middleware applies custom Permissions-Policy directives for restricted browser features","secureHeaders middleware supports configuring Cross-Origin-Embedder-Policy and Referrer-Policy","secureHeaders middleware allows disabling specific default security headers when set to false","secureHeaders middleware supports Content-Security-Policy-Report-Only mode with reportUri directive"],"goal":"verify secureHeaders in pkg:npm/hono@4.13.7","kind":"HOW","packages":["pkg:npm/hono@4.13.7"],"schemaVersion":1,"symbols":["secureHeaders"]},"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.7"],"schemaVersion":1,"subject":"pkg:npm/hono@4.13.7","symbols":["secureHeaders"],"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",
  "private": true,
  "description": "Clean-room code sample for secureHeaders in hono@4.13.7",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "hono": "4.13.7"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify secureHeaders in pkg:npm/hono@4.13.7",
  "kind": "HOW",
  "packages": [
    "pkg:npm/hono@4.13.7"
  ],
  "symbols": [
    "secureHeaders"
  ]
}
src/index.js
'use strict';

const { Hono } = require('hono');
const { secureHeaders, NONCE } = require('hono/secure-headers');

/**
 * Creates a Hono application configured with default secure headers.
 *
 * @returns {Hono}
 */
function createDefaultApp() {
  const app = new Hono();
  app.use(secureHeaders());
  app.get('/api/default', (c) => c.json({ status: 'ok' }));
  return app;
}

/**
 * Creates a Hono application configured with customized secure headers including CSP with NONCE,
 * permissions policy, cross-origin embedder policy, and selective header disabling.
 *
 * @returns {Hono}
 */
function createCustomApp() {
  const app = new Hono();
  app.use(
    secureHeaders({
      contentSecurityPolicy: {
        defaultSrc: ["'self'"],
        scriptSrc: ["'self'", NONCE],
        frameAncestors: ["'none'"],
      },
      permissionsPolicy: {
        camera: false,
        geolocation: ['self', 'https://example.com'],
      },
      crossOriginEmbedderPolicy: 'require-corp',
      referrerPolicy: 'strict-origin-when-cross-origin',
      xFrameOptions: false,
    })
  );

  app.get('/api/custom', (c) => {
    const nonce = c.get('secureHeadersNonce');
    return c.json({ nonce });
  });

  return app;
}

/**
 * Creates a Hono application configured with CSP report-only and custom X-Frame-Options.
 *
 * @returns {Hono}
 */
function createReportOnlyApp() {
  const app = new Hono();
  app.use(
    secureHeaders({
      contentSecurityPolicyReportOnly: {
        defaultSrc: ["'self'"],
        reportUri: 'https://example.com/csp-report',
      },
      xFrameOptions: 'DENY',
    })
  );

  app.get('/api/report-only', (c) => c.json({ reporting: true }));
  return app;
}

module.exports = {
  createDefaultApp,
  createCustomApp,
  createReportOnlyApp,
  Hono,
  secureHeaders,
  NONCE,
};
test/contract.mjs
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const {
  createDefaultApp,
  createCustomApp,
  createReportOnlyApp,
  Hono,
  secureHeaders,
  NONCE,
} = require('../src/index.js');

async function testAll() {
  // 1. Export verification
  assert.equal(typeof createDefaultApp, 'function', 'createDefaultApp must be a function');
  assert.equal(typeof createCustomApp, 'function', 'createCustomApp must be a function');
  assert.equal(typeof createReportOnlyApp, 'function', 'createReportOnlyApp must be a function');
  assert.equal(typeof Hono, 'function', 'Hono must be exported');
  assert.equal(typeof secureHeaders, 'function', 'secureHeaders must be exported');
  assert.equal(typeof NONCE, 'function', 'NONCE must be exported');

  // 2. Default secure headers verification
  const defaultApp = createDefaultApp();
  const defaultRes = await defaultApp.fetch(new Request('http://localhost/api/default'));
  assert.equal(defaultRes.status, 200, 'default GET should return 200');

  // Verify standard default security headers
  assert.equal(
    defaultRes.headers.get('x-content-type-options'),
    'nosniff',
    'x-content-type-options should default to nosniff'
  );
  assert.equal(
    defaultRes.headers.get('x-frame-options'),
    'SAMEORIGIN',
    'x-frame-options should default to SAMEORIGIN'
  );
  assert.equal(
    defaultRes.headers.get('cross-origin-opener-policy'),
    'same-origin',
    'cross-origin-opener-policy should default to same-origin'
  );
  assert.equal(
    defaultRes.headers.get('cross-origin-resource-policy'),
    'same-origin',
    'cross-origin-resource-policy should default to same-origin'
  );
  assert.equal(
    defaultRes.headers.get('origin-agent-cluster'),
    '?1',
    'origin-agent-cluster should default to ?1'
  );
  assert.equal(
    defaultRes.headers.get('referrer-policy'),
    'no-referrer',
    'referrer-policy should default to no-referrer'
  );
  assert.equal(
    defaultRes.headers.get('strict-transport-security'),
    'max-age=15552000; includeSubDomains',
    'strict-transport-security should default to 15552000 with subdomains'
  );
  assert.equal(
    defaultRes.headers.get('x-dns-prefetch-control'),
    'off',
    'x-dns-prefetch-control should default to off'
  );
  assert.equal(
    defaultRes.headers.get('x-download-options'),
    'noopen',
    'x-download-options should default to noopen'
  );
  assert.equal(
    defaultRes.headers.get('x-permitted-cross-domain-policies'),
    'none',
    'x-permitted-cross-domain-policies should default to none'
  );
  assert.equal(
    defaultRes.headers.get('x-xss-protection'),
    '0',
    'x-xss-protection should default to 0'
  );

  // 3. Custom CSP with dynamic NONCE and permissions policy
  const customApp = createCustomApp();
  const customRes = await customApp.fetch(new Request('http://localhost/api/custom'));
  assert.equal(customRes.status, 200, 'custom GET should return 200');

  const customBody = await customRes.json();
  assert.ok(customBody.nonce, 'secureHeadersNonce should be available in context');
  assert.equal(typeof customBody.nonce, 'string', 'nonce must be a string');

  const cspHeader = customRes.headers.get('content-security-policy') || '';
  assert.ok(cspHeader.includes("default-src 'self'"), 'CSP should include default-src');
  assert.ok(cspHeader.includes("frame-ancestors 'none'"), 'CSP should include frame-ancestors');
  assert.ok(
    cspHeader.includes(`'nonce-${customBody.nonce}'`),
    'CSP should contain matching dynamic nonce for script-src'
  );

  // Permissions-Policy verification
  const permissionsPolicy = customRes.headers.get('permissions-policy') || '';
  assert.ok(permissionsPolicy.includes('camera=()'), 'permissions-policy should disable camera');
  assert.ok(
    permissionsPolicy.includes('geolocation=(self "https://example.com")'),
    'permissions-policy should configure geolocation origin'
  );

  // COEP and Referrer-Policy override
  assert.equal(
    customRes.headers.get('cross-origin-embedder-policy'),
    'require-corp',
    'COEP should be require-corp'
  );
  assert.equal(
    customRes.headers.get('referrer-policy'),
    'strict-origin-when-cross-origin',
    'referrer-policy should be overridden'
  );

  // Disabled header verification (xFrameOptions: false)
  assert.equal(
    customRes.headers.get('x-frame-options'),
    null,
    'x-frame-options should be omitted when disabled'
  );

  // 4. Report-only CSP and custom X-Frame-Options override
  const reportApp = createReportOnlyApp();
  const reportRes = await reportApp.fetch(new Request('http://localhost/api/report-only'));
  assert.equal(reportRes.status, 200, 'report-only GET should return 200');

  const reportOnlyHeader = reportRes.headers.get('content-security-policy-report-only') || '';
  assert.ok(
    reportOnlyHeader.includes("default-src 'self'"),
    'CSP-Report-Only should include default-src'
  );
  assert.ok(
    reportOnlyHeader.includes('report-uri https://example.com/csp-report'),
    'CSP-Report-Only should include report-uri'
  );
  assert.equal(
    reportRes.headers.get('content-security-policy'),
    null,
    'enforcing CSP should not be present when only report-only is configured'
  );
  assert.equal(
    reportRes.headers.get('x-frame-options'),
    'DENY',
    'x-frame-options should be overridden to DENY'
  );

  console.log('All secureHeaders contract assertions passed successfully.');
}

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

Seeder de origem

anônimo