CodeSampleX

示例

hono 4.12.32

已验证示例 — npm hono 4.12.32. contract 在 node 22 · linux alpine/x64 · docker 上运行并通过: jwt, sign, verify, and decode are exported as functions from hono/jwt

sha256:5079d5dbfbbb28ba9ed18d1c0a07396cd1f839ae876859d157be706529a6fa0a

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 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();

原始种子者

匿名