CodeSampleX

示例

hono 4.13.3: verify

已验证示例 — npm hono 4.13.3: verify. contract 在 node 22 · linux debian/x64 · docker 上运行并通过: verify validates JWT signature using secret key and algorithm…

sha256:87192efd5c7d32e779cc9e22bdbf7eefaf56aebb6e1a132481fd30d9df3ecb87

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

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
1
构建过它的签名密钥
1
声明的环境 linux 24 · ubuntu · glibc 2.39 x64 npm

验证运行环境

环境 契约 阶段 运行日期
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-04

案例

HOW
目标
verify hono.verify in pkg:npm/hono@4.13.3
包
符号
  • hono.verify
创建时间
2026-09-04T13:32:43Z

契约

  1. verify validates JWT signature using secret key and algorithm, returning the decoded payload
  2. verify rejects when secret key is incorrect, token signature is invalid, or payload is tampered
  3. verify rejects tokens that have expired according to the exp claim
  4. verify supports HS256, HS384, and HS512 HMAC algorithms
  5. jwt middleware uses verify to protect routes, authenticating valid Bearer tokens and returning 401 for invalid or missing tokens

文件

  • 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 hono.verify in pkg:npm/hono@4.13.3
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/hono@4.13.3
Demonstrate these symbols/APIs:
  - hono.verify

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:13b77b5f43a0d621cf6dff47f7bfb0c9f7543a7fcb4f42cfc795825a216d6316","contract":["verify validates JWT signature using secret key and algorithm, returning the decoded payload","verify rejects when secret key is incorrect, token signature is invalid, or payload is tampered","verify rejects tokens that have expired according to the exp claim","verify supports HS256, HS384, and HS512 HMAC algorithms","jwt middleware uses verify to protect routes, authenticating valid Bearer tokens and returning 401 for invalid or missing tokens"],"goal":"verify hono.verify in pkg:npm/hono@4.13.3","kind":"HOW","packages":["pkg:npm/hono@4.13.3"],"schemaVersion":1,"symbols":["hono.verify"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/hono@4.13.3"],"schemaVersion":1,"subject":"pkg:npm/hono@4.13.3","symbols":["hono.verify"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-hono-verify",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-hono-verify",
      "version": "1.0.0",
      "dependencies": {
        "hono": "4.13.3"
      }
    },
    "node_modules/hono": {
      "version": "4.13.3",
      "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.3.tgz",
      "integrity": "sha512-r8AO2mYHoLxSHkgafNeC/BXyb2vWRxD3jem4Ts+ptav8oTG5FIRifAjuJEmZI4bSvvc2ns0GxmIYiZnHqN3mMw==",
      "license": "MIT",
      "engines": {
        "node": ">=16.9.0"
      }
    }
  }
}
package.json
{
  "name": "sample-hono-verify",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification for hono.verify in pkg:npm/hono@4.13.3",
  "type": "module",
  "dependencies": {
    "hono": "4.13.3"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify hono.verify in pkg:npm/hono@4.13.3",
  "kind": "HOW",
  "packages": [
    "pkg:npm/hono@4.13.3"
  ],
  "symbols": [
    "hono.verify"
  ]
}
src/index.mjs
import { Hono } from 'hono';
import { jwt, sign, verify, decode } from 'hono/jwt';

/**
 * Signs a JWT payload with the specified secret and algorithm.
 *
 * @param {object} payload - Claims payload object.
 * @param {string} secret - Secret signing key.
 * @param {string} [alg='HS256'] - Algorithm to use for HMAC signing.
 * @returns {Promise<string>} Signed JWT string.
 */
export async function createToken(payload, secret, alg = 'HS256') {
  return await sign(payload, secret, alg);
}

/**
 * Verifies a JWT token signature and returns the payload.
 *
 * @param {string} token - Raw JWT token string.
 * @param {string} secret - Secret key to verify against.
 * @param {string} [alg='HS256'] - Algorithm expected.
 * @returns {Promise<object>} Verified payload.
 */
export async function verifyToken(token, secret, alg = 'HS256') {
  return await verify(token, secret, alg);
}

/**
 * Decodes a JWT token without verifying its signature.
 *
 * @param {string} token - Raw JWT token string.
 * @returns {{ header: object, payload: object }} Decoded header and payload.
 */
export function decodeToken(token) {
  return decode(token);
}

/**
 * Creates a Hono application configured with JWT authentication middleware.
 *
 * @param {string} secret - Secret key used by JWT middleware.
 * @param {string} [alg='HS256'] - Algorithm expected.
 * @returns {Hono} Configured Hono application instance.
 */
export function createProtectedApp(secret, alg = 'HS256') {
  const app = new Hono();

  // Public endpoint
  app.get('/public', (c) => c.json({ status: 'ok', access: 'public' }));

  // Protected route guarded by jwt middleware
  app.use('/api/*', jwt({ secret, alg }));

  // Protected endpoint accessing jwtPayload injected into context
  app.get('/api/protected', (c) => {
    const payload = c.get('jwtPayload');
    return c.json({
      success: true,
      payload
    });
  });

  return app;
}

export { jwt, sign, verify, decode };
test/contract.mjs
import assert from 'node:assert/strict';
import {
  createToken,
  verifyToken,
  decodeToken,
  createProtectedApp,
  jwt,
  sign,
  verify,
  decode
} from '../src/index.mjs';

const SECRET_256 = 'sample-verification-secret-key-32bytes!';
const SECRET_384 = 'sample-verification-secret-key-at-least-48-chars-long-for-hs384!';
const SECRET_512 = 'sample-verification-secret-key-at-least-64-chars-long-for-hs512-testing!';

// Contract 1: verify validates JWT signature using secret key and algorithm, returning the decoded payload
{
  assert.equal(typeof verify, 'function', 'verify must be a function');
  assert.equal(typeof verifyToken, 'function', 'verifyToken must be a function');

  const payload = { sub: 'usr_contract_1', role: 'admin', iat: Math.floor(Date.now() / 1000) };
  const token = await createToken(payload, SECRET_256, 'HS256');

  const verified = await verifyToken(token, SECRET_256, 'HS256');
  assert.equal(typeof verified, 'object', 'verify must return payload object');
  assert.equal(verified.sub, 'usr_contract_1');
  assert.equal(verified.role, 'admin');
}

// Contract 2: verify rejects when secret key is incorrect, token signature is invalid, or payload is tampered
{
  const payload = { sub: 'usr_contract_2', role: 'editor' };
  const token = await createToken(payload, SECRET_256, 'HS256');

  // Wrong secret
  await assert.rejects(
    async () => {
      await verifyToken(token, 'wrong-secret-key-at-least-32-chars-long!', 'HS256');
    },
    'verify must reject when secret is incorrect'
  );

  // Tampered payload segment
  const parts = token.split('.');
  assert.equal(parts.length, 3);
  const tamperedPayload = Buffer.from(JSON.stringify({ sub: 'tampered_user' })).toString('base64url');
  const tamperedToken = `${parts[0]}.${tamperedPayload}.${parts[2]}`;
  await assert.rejects(
    async () => {
      await verifyToken(tamperedToken, SECRET_256, 'HS256');
    },
    'verify must reject tampered token'
  );

  // Malformed token format
  await assert.rejects(
    async () => {
      await verifyToken('not.a.valid.jwt.token', SECRET_256, 'HS256');
    },
    'verify must reject malformed token'
  );
}

// Contract 3: verify rejects tokens that have expired according to the exp claim
{
  const pastTime = Math.floor(Date.now() / 1000) - 300;
  const expiredPayload = { sub: 'usr_expired', exp: pastTime };
  const expiredToken = await createToken(expiredPayload, SECRET_256, 'HS256');

  await assert.rejects(
    async () => {
      await verifyToken(expiredToken, SECRET_256, 'HS256');
    },
    'verify must reject expired tokens'
  );
}

// Contract 4: verify supports HS256, HS384, and HS512 HMAC algorithms
{
  const payload256 = { sub: 'user_hs256', alg: 'HS256' };
  const token256 = await createToken(payload256, SECRET_256, 'HS256');
  const verified256 = await verifyToken(token256, SECRET_256, 'HS256');
  assert.equal(verified256.sub, 'user_hs256');

  const payload384 = { sub: 'user_hs384', alg: 'HS384' };
  const token384 = await createToken(payload384, SECRET_384, 'HS384');
  const verified384 = await verifyToken(token384, SECRET_384, 'HS384');
  assert.equal(verified384.sub, 'user_hs384');

  const payload512 = { sub: 'user_hs512', alg: 'HS512' };
  const token512 = await createToken(payload512, SECRET_512, 'HS512');
  const verified512 = await verifyToken(token512, SECRET_512, 'HS512');
  assert.equal(verified512.sub, 'user_hs512');
}

// Contract 5: jwt middleware uses verify to protect routes, authenticating valid Bearer tokens and returning 401 for invalid or missing tokens
{
  assert.equal(typeof jwt, 'function', 'jwt must be a function');
  const app = createProtectedApp(SECRET_256, 'HS256');

  // Public endpoint succeeds without auth
  const pubRes = await app.request('http://localhost/public');
  assert.equal(pubRes.status, 200);
  const pubData = await pubRes.json();
  assert.equal(pubData.access, 'public');

  // Valid Bearer token succeeds on protected route
  const validToken = await createToken({ sub: 'usr_authorized', role: 'member' }, SECRET_256, 'HS256');
  const protRes = await app.request('http://localhost/api/protected', {
    headers: {
      Authorization: `Bearer ${validToken}`
    }
  });
  assert.equal(protRes.status, 200);
  const protData = await protRes.json();
  assert.equal(protData.success, true);
  assert.equal(protData.payload.sub, 'usr_authorized');
  assert.equal(protData.payload.role, 'member');

  // Missing Authorization header returns 401
  const missingRes = await app.request('http://localhost/api/protected');
  assert.equal(missingRes.status, 401);

  // Invalid Bearer token returns 401
  const badAuthRes = await app.request('http://localhost/api/protected', {
    headers: {
      Authorization: 'Bearer invalid.bearer.token'
    }
  });
  assert.equal(badAuthRes.status, 401);
}

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

原始种子者

匿名