CodeSampleX

샘플

hono 4.12.32

검증된 샘플 — npm hono 4.12.32. node 22 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: jwt, sign, verify, and decode are exported as functions from hono/jwt

sha256:5079d5dbfbbb28ba9ed18d1c0a07396cd1f839ae876859d157be706529a6fa0a

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

검증 실행 환경

환경 컨트랙트 단계 실행일
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

케이스

HOW
목표
verify pkg:npm/hono@4.12.32
패키지
환경
node 22.23.2
생성일
2026-08-28T07:26:32Z

컨트랙트

  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

파일

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.mjs
  • 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.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();

오리진 시더

익명