CodeSampleX

샘플

hono 4.13.2: verify

검증된 샘플 — npm hono 4.13.2: verify. node 22 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: verify validates token signature against secret key and returns…

sha256:92bab2711a6c4531fb43bd669d992fdd714cfdc1036742fdc07bbff5acd3bdd7

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

케이스

HOW
목표
verify verify in pkg:npm/hono@4.13.2
패키지
심벌
  • verify
생성일
2026-09-01T22:40:12Z

컨트랙트

  1. verify validates token signature against secret key and returns the decoded payload object
  2. verify rejects when token signature is invalid, secret is incorrect, or token payload is tampered
  3. verify supports HS256 and HS512 HMAC algorithms
  4. sign generates a valid 3-part base64url-encoded JWT string verified by verify
  5. jwt middleware uses verify to protect routes, allowing valid Bearer tokens and returning 401 for invalid 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 verify 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:
  - 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:3a5b6507eb551e21ec0d51df2443c67d28be926af0fb6f434c017d95bb049dd7","contract":["verify validates token signature against secret key and returns the decoded payload object","verify rejects when token signature is invalid, secret is incorrect, or token payload is tampered","verify supports HS256 and HS512 HMAC algorithms","sign generates a valid 3-part base64url-encoded JWT string verified by verify","jwt middleware uses verify to protect routes, allowing valid Bearer tokens and returning 401 for invalid tokens"],"goal":"verify verify in pkg:npm/hono@4.13.2","kind":"HOW","packages":["pkg:npm/hono@4.13.2"],"schemaVersion":1,"symbols":["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.2"],"schemaVersion":1,"subject":"pkg:npm/hono@4.13.2","symbols":["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.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-verify",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification for JWT verify and signing in Hono",
  "dependencies": {
    "hono": "4.13.2"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify verify in pkg:npm/hono@4.13.2",
  "kind": "HOW",
  "packages": [
    "pkg:npm/hono@4.13.2"
  ],
  "symbols": [
    "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 with JWT authentication middleware.
 *
 * @param {string} secret - Secret key for JWT verification.
 * @param {string} [alg='HS256'] - Algorithm expected.
 * @returns {Hono} Configured Hono app instance.
 */
export function createProtectedApp(secret, alg = 'HS256') {
  const app = new Hono();

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

  app.use('/api/*', jwt({ secret, alg }));

  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-secret-key-at-least-32-chars-long!';
const SECRET_512 = 'sample-secret-key-at-least-64-chars-long-for-hs512-algorithm-testing!';

// Contract 1: verify validates token signature against secret key and returns the decoded payload object
{
  assert.equal(typeof verify, 'function', 'verify must be a function');
  assert.equal(typeof verifyToken, 'function');

  const payload = { sub: 'user_101', 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, 'user_101');
  assert.equal(verified.role, 'admin');
}

// Contract 2: verify rejects when token signature is invalid, secret is incorrect, or token payload is tampered
{
  const payload = { sub: 'user_102', 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 tamperedToken = `${parts[0]}.eyJzdWIiOiJ1c3JfaGFja2VkIn0.${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-jwt-token', SECRET_256, 'HS256');
    },
    'verify must reject malformed token'
  );
}

// Contract 3: verify supports HS256 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 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 4: sign generates a valid 3-part base64url-encoded JWT string verified by verify
{
  assert.equal(typeof sign, 'function', 'sign must be a function');
  assert.equal(typeof decode, 'function', 'decode must be a function');

  const payload = { sub: 'user_103', name: 'Bob', aud: 'sample-audience' };
  const token = await createToken(payload, SECRET_256, 'HS256');

  assert.equal(typeof token, 'string');
  const segments = token.split('.');
  assert.equal(segments.length, 3, 'Token must contain 3 segments');

  const decoded = decodeToken(token);
  assert.equal(decoded.header.alg, 'HS256');
  assert.equal(decoded.header.typ, 'JWT');
  assert.equal(decoded.payload.sub, 'user_103');
  assert.equal(decoded.payload.name, 'Bob');
}

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

  // Public endpoint
  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 to protected endpoint
  const validToken = await createToken({ sub: 'user_104', role: 'viewer' }, 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, 'user_104');

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

  // Invalid token in Authorization header
  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 verify in pkg:npm/hono@4.13.2 passed.');

오리진 시더

익명