CodeSampleX

Ejemplo

hono 4.13.2: sign

Muestra verificada para npm hono 4.13.2: sign. El contrato se ejecutó en node 22 · linux debian/x64 · docker y pasó: sign generates a signed JWT string with…

sha256:56656a039c0847579f0e5cc548ad192bdfcf5b19bdea449301d1407f3f7ef518

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
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

Caso

HOW
Objetivo
verify sign in pkg:npm/hono@4.13.2
Paquetes
Símbolos
  • sign
Entorno
node 22.23.2
Creado
2026-09-01T22:40:49Z

Contrato

  1. sign generates a signed JWT string with three dot-separated base64url segments for a payload and secret
  2. sign defaults to HS256 algorithm and sets typ to JWT in the token header
  3. sign encodes payload claims into the middle base64url segment
  4. sign supports alternative HMAC algorithms including HS384 and HS512
  5. sign produces distinct signatures when payload or secret changes
  6. sign rejects unsupported signing algorithms with an error

Archivos

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

Descargar el artefacto de código fuente (tar.gz)

Código fuente

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 sign 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:
  - sign
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.
csx.json
{"case":{"caseId":"case:sha256:7ebd15ca99ff788e4110c031766a6a8fde596a238ddaf240e6165217f45db602","constraints":{"executionContext":"node"},"contract":["sign generates a signed JWT string with three dot-separated base64url segments for a payload and secret","sign defaults to HS256 algorithm and sets typ to JWT in the token header","sign encodes payload claims into the middle base64url segment","sign supports alternative HMAC algorithms including HS384 and HS512","sign produces distinct signatures when payload or secret changes","sign rejects unsupported signing algorithms with an error"],"goal":"verify sign in pkg:npm/hono@4.13.2","kind":"HOW","packages":["pkg:npm/hono@4.13.2"],"schemaVersion":1,"symbols":["sign"]},"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":["sign"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-hono-sign",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-hono-sign",
      "version": "1.0.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"
      }
    }
  }
}
package.json
{
  "name": "sample-hono-sign",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification for sign in pkg:npm/hono@4.13.2",
  "dependencies": {
    "hono": "4.13.2"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify sign in pkg:npm/hono@4.13.2",
  "kind": "HOW",
  "packages": [
    "pkg:npm/hono@4.13.2"
  ],
  "symbols": [
    "sign"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.mjs
import { sign } from 'hono/jwt';

/**
 * Signs a JWT payload using Hono's sign utility.
 *
 * @param {object} payload - Claims object to include in JWT payload.
 * @param {string|CryptoKey} secret - Secret key for signing.
 * @param {string} [alg='HS256'] - Algorithm to use for signing.
 * @returns {Promise<string>} Signed JWT string with header, payload, and signature segments.
 */
export async function createSignedToken(payload, secret, alg = 'HS256') {
  return await sign(payload, secret, alg);
}

export { sign };
test/contract.mjs
import assert from 'node:assert/strict';
import { createSignedToken, sign } from '../src/index.mjs';

const SECRET_KEY = 'sample-secret-signing-key-32b!';

// Contract 1: sign generates a signed JWT string with three dot-separated base64url segments for a payload and secret
{
  assert.equal(typeof sign, 'function', 'sign must be a function');
  assert.equal(typeof createSignedToken, 'function', 'createSignedToken must be a function');

  const payload = { sub: 'user_1001', role: 'admin', iat: 1700000000 };
  const token = await createSignedToken(payload, SECRET_KEY);

  assert.equal(typeof token, 'string', 'Token must be a string');
  const parts = token.split('.');
  assert.equal(parts.length, 3, 'JWT must contain exactly three parts (header.payload.signature)');
  assert.ok(parts[0].length > 0, 'Header part must not be empty');
  assert.ok(parts[1].length > 0, 'Payload part must not be empty');
  assert.ok(parts[2].length > 0, 'Signature part must not be empty');
}

// Contract 2: sign defaults to HS256 algorithm and sets typ to JWT in the token header
{
  const payload = { sub: 'user_1002' };
  const token = await sign(payload, SECRET_KEY);

  const parts = token.split('.');
  const headerJson = Buffer.from(parts[0], 'base64url').toString('utf-8');
  const header = JSON.parse(headerJson);

  assert.equal(header.alg, 'HS256', 'Default algorithm in header must be HS256');
  assert.equal(header.typ, 'JWT', 'Header typ must be JWT');
}

// Contract 3: sign encodes payload claims into the middle base64url segment
{
  const payload = { sub: 'user_1003', name: 'Test User', permissions: ['read', 'write'], active: true };
  const token = await createSignedToken(payload, SECRET_KEY);

  const parts = token.split('.');
  const payloadJson = Buffer.from(parts[1], 'base64url').toString('utf-8');
  const decodedPayload = JSON.parse(payloadJson);

  assert.equal(decodedPayload.sub, 'user_1003');
  assert.equal(decodedPayload.name, 'Test User');
  assert.deepEqual(decodedPayload.permissions, ['read', 'write']);
  assert.equal(decodedPayload.active, true);
}

// Contract 4: sign supports alternative HMAC algorithms including HS384 and HS512
{
  const payload = { sub: 'user_1004' };

  const token384 = await sign(payload, SECRET_KEY, 'HS384');
  const header384 = JSON.parse(Buffer.from(token384.split('.')[0], 'base64url').toString('utf-8'));
  assert.equal(header384.alg, 'HS384', 'Algorithm in header must be HS384');

  const token512 = await sign(payload, SECRET_KEY, 'HS512');
  const header512 = JSON.parse(Buffer.from(token512.split('.')[0], 'base64url').toString('utf-8'));
  assert.equal(header512.alg, 'HS512', 'Algorithm in header must be HS512');
}

// Contract 5: sign produces distinct signatures when payload or secret changes
{
  const payload1 = { sub: 'user_1005', role: 'member' };
  const payload2 = { sub: 'user_1006', role: 'member' };
  const differentSecret = 'another-different-secret-key-32!';

  const tokenBase = await sign(payload1, SECRET_KEY);
  const tokenDifferentPayload = await sign(payload2, SECRET_KEY);
  const tokenDifferentSecret = await sign(payload1, differentSecret);

  const sigBase = tokenBase.split('.')[2];
  const sigDiffPayload = tokenDifferentPayload.split('.')[2];
  const sigDiffSecret = tokenDifferentSecret.split('.')[2];

  assert.notEqual(sigBase, sigDiffPayload, 'Different payloads must produce different signatures');
  assert.notEqual(sigBase, sigDiffSecret, 'Different secrets must produce different signatures');
}

// Contract 6: sign rejects unsupported signing algorithms with an error
{
  const payload = { sub: 'user_1007' };
  await assert.rejects(
    async () => {
      await sign(payload, SECRET_KEY, 'UNSUPPORTED_ALG');
    },
    (err) => {
      assert.ok(err instanceof Error);
      return true;
    },
    'sign must reject unsupported algorithm'
  );
}

console.log('All contracts for sign in pkg:npm/hono@4.13.2 passed.');

Seeder de origen

anónimo