CodeSampleX

Exemple

hono 4.12.32

Échantillon vérifié pour npm hono 4.12.32. Le contrat s'est exécuté sur node 22 · linux alpine/x64 · docker et a réussi : jwt, sign, verify, and decode are…

sha256:5079d5dbfbbb28ba9ed18d1c0a07396cd1f839ae876859d157be706529a6fa0a

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
1
Clés de signature qui l’ont compilé
1
Environnement déclaré node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
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-28

Cas

HOW
Objectif
verify pkg:npm/hono@4.12.32
Paquets
Environnement
node 22.23.2
Créé
2026-08-28T07:26:32Z

Contrat

  1. jwt, sign, verify, and decode are exported as functions from hono/jwt
  2. sign creates a signed JWT string and decode extracts payload without verification
  3. verify validates signature with algorithm and secret, rejecting invalid signatures
  4. verify throws JwtAlgorithmRequired when algorithm argument is omitted
  5. jwt middleware protects routes, returning status 401 when Authorization header is missing or malformed
  6. jwt middleware grants access for valid Bearer token and attaches decoded payload to context jwtPayload
  7. jwt middleware supports extracting and validating token from configured cookie

Fichiers

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

Télécharger l’artefact source (tar.gz)

Code source

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.12.32
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/hono@4.12.32
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:774c0b704863258028e57a88258c68f0a5f240487d63328cee8c7b62b956db53","constraints":{"executionContext":"node"},"contract":["jwt, sign, verify, and decode are exported as functions from hono/jwt","sign creates a signed JWT string and decode extracts payload without verification","verify validates signature with algorithm and secret, rejecting invalid signatures","verify throws JwtAlgorithmRequired when algorithm argument is omitted","jwt middleware protects routes, returning status 401 when Authorization header is missing or malformed","jwt middleware grants access for valid Bearer token and attaches decoded payload to context jwtPayload","jwt middleware supports extracting and validating token from configured cookie"],"goal":"verify pkg:npm/hono@4.12.32","kind":"HOW","packages":["pkg:npm/hono@4.12.32"],"schemaVersion":1},"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.12.32"],"schemaVersion":1,"subject":"pkg:npm/hono@4.12.32","verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-hono-jwt",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-hono-jwt",
      "version": "1.0.0",
      "dependencies": {
        "hono": "4.12.32"
      }
    },
    "node_modules/hono": {
      "version": "4.12.32",
      "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.32.tgz",
      "integrity": "sha512-XcuyW9qE2kJn07PkecMOBd5Vq/hMy7mmGw+idz1yblbg9N17ijJODrvPkn7/dwL3Kulj8LcRJ69DLOWf91dRUg==",
      "license": "MIT",
      "engines": {
        "node": ">=16.9.0"
      }
    }
  }
}
package.json
{
  "name": "sample-hono-jwt",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "dependencies": {
    "hono": "4.12.32"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/hono@4.12.32",
  "kind": "HOW",
  "packages": [
    "pkg:npm/hono@4.12.32"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.mjs
import { Hono } from "hono";
import { jwt, sign, verify, decode } from "hono/jwt";

export function generateToken(payload, secret, alg = "HS256") {
  return sign(payload, secret, alg);
}

export function parseToken(token) {
  return decode(token);
}

export function validateToken(token, secret, alg = "HS256") {
  return verify(token, secret, alg);
}

export function createApp(secret) {
  const app = new Hono();

  // Public health check route
  app.get("/health", (c) => c.json({ status: "healthy" }));

  // JWT Bearer auth protected routes
  app.use("/api/*", jwt({ secret, alg: "HS256" }));

  app.get("/api/profile", (c) => {
    const payload = c.get("jwtPayload");
    return c.json({
      status: "authenticated",
      user: payload,
    });
  });

  // JWT Cookie auth protected routes
  app.use("/cookie-api/*", jwt({ secret, alg: "HS256", cookie: "auth_token" }));

  app.get("/cookie-api/session", (c) => {
    const payload = c.get("jwtPayload");
    return c.json({
      status: "authenticated",
      session: payload,
    });
  });

  return app;
}
test/contract.mjs
import assert from "node:assert/strict";
import { Hono } from "hono";
import { jwt, sign, verify, decode } from "hono/jwt";
import { createApp, generateToken, parseToken, validateToken } from "../src/index.mjs";

async function runContract() {
  const secretKey = "test-jwt-secret-key-1234567890123456";
  const userPayload = {
    sub: "user-42",
    role: "admin",
    name: "Sample User",
  };

  // 1. Verify module exports
  assert.equal(typeof jwt, "function", "jwt should be a middleware factory function");
  assert.equal(typeof sign, "function", "sign should be a function");
  assert.equal(typeof verify, "function", "verify should be a function");
  assert.equal(typeof decode, "function", "decode should be a function");

  // 2. Test sign and decode
  const token = await generateToken(userPayload, secretKey, "HS256");
  assert.equal(typeof token, "string", "Token must be a non-empty string");
  assert.ok(token.split(".").length === 3, "JWT token must have 3 segments");

  const decoded = parseToken(token);
  assert.equal(decoded.payload.sub, "user-42");
  assert.equal(decoded.payload.role, "admin");
  assert.equal(decoded.payload.name, "Sample User");
  assert.equal(decoded.header.alg, "HS256");

  // 3. Test verify with valid and invalid secret
  const verifiedPayload = await validateToken(token, secretKey, "HS256");
  assert.equal(verifiedPayload.sub, "user-42");
  assert.equal(verifiedPayload.role, "admin");

  await assert.rejects(
    async () => {
      await validateToken(token, "wrong-secret-key-0000000000000000", "HS256");
    },
    "verify should reject with invalid secret"
  );

  // 4. Test verify without alg option throws JwtAlgorithmRequired
  await assert.rejects(
    async () => {
      await verify(token, secretKey);
    },
    (err) => {
      return err && err.name === "JwtAlgorithmRequired";
    },
    "verify without alg option must throw JwtAlgorithmRequired"
  );

  // 5. Setup app and test routes
  const app = createApp(secretKey);

  // Public route test
  const healthRes = await app.request("http://localhost/health");
  assert.equal(healthRes.status, 200);
  assert.deepEqual(await healthRes.json(), { status: "healthy" });

  // 6. Protected route without token returns 401
  const noAuthRes = await app.request("http://localhost/api/profile");
  assert.equal(noAuthRes.status, 401, "Protected route must return 401 without auth header");

  // Malformed token returns 401
  const badTokenRes = await app.request("http://localhost/api/profile", {
    headers: { Authorization: "Bearer bad.token.here" },
  });
  assert.equal(badTokenRes.status, 401, "Protected route must return 401 with malformed token");

  // 7. Protected route with valid Bearer token returns 200 and payload in context
  const authRes = await app.request("http://localhost/api/profile", {
    headers: { Authorization: `Bearer ${token}` },
  });
  assert.equal(authRes.status, 200, "Protected route must return 200 with valid Bearer token");
  const authData = await authRes.json();
  assert.equal(authData.status, "authenticated");
  assert.equal(authData.user.sub, "user-42");
  assert.equal(authData.user.role, "admin");

  // 8. Protected route with Cookie authentication
  const cookieRes = await app.request("http://localhost/cookie-api/session", {
    headers: { Cookie: `auth_token=${token}` },
  });
  assert.equal(cookieRes.status, 200, "Cookie protected route must return 200 with valid auth cookie");
  const cookieData = await cookieRes.json();
  assert.equal(cookieData.status, "authenticated");
  assert.equal(cookieData.session.sub, "user-42");

  // Cookie protected route without cookie returns 401
  const noCookieRes = await app.request("http://localhost/cookie-api/session");
  assert.equal(noCookieRes.status, 401, "Cookie protected route must return 401 without auth cookie");

  console.log("All contract tests passed successfully.");
}

await runContract();

Seeder d'origine

anonyme