CodeSampleX

샘플

hono 4.13.2: jwt

검증된 샘플 — npm hono 4.13.2: jwt. node 22 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: sign generates a signed JWT string with three base64url-encoded…

sha256:4152daf35516ba7e6e50ccc74055c0e45e6699de815c1ec6eea09495776532d7

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

실행 증거

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

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

검증 실행 환경

환경 컨트랙트 단계 실행일
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 jwt in pkg:npm/hono@4.13.2
패키지
심벌
  • jwt
환경
node 22.23.2
생성일
2026-09-01T22:36:52Z

컨트랙트

  1. sign generates a signed JWT string with three base64url-encoded segments for a given payload and secret
  2. decode parses token header and payload without verifying signature
  3. verify validates token signature and returns the payload, rejecting invalid secrets or tampered tokens
  4. jwt middleware authenticates requests with valid Bearer token and injects jwtPayload into context
  5. jwt middleware rejects requests with missing or invalid Bearer tokens with 401 Unauthorized

파일

  • 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 jwt 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:
  - jwt
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:f5a5625edcc557bac1ff88b671ee7a90add5aa9222fef98af801a86f3709ddaa","constraints":{"executionContext":"node"},"contract":["sign generates a signed JWT string with three base64url-encoded segments for a given payload and secret","decode parses token header and payload without verifying signature","verify validates token signature and returns the payload, rejecting invalid secrets or tampered tokens","jwt middleware authenticates requests with valid Bearer token and injects jwtPayload into context","jwt middleware rejects requests with missing or invalid Bearer tokens with 401 Unauthorized"],"goal":"verify jwt in pkg:npm/hono@4.13.2","kind":"HOW","packages":["pkg:npm/hono@4.13.2"],"schemaVersion":1,"symbols":["jwt"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","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.13.2"],"schemaVersion":1,"subject":"pkg:npm/hono@4.13.2","symbols":["jwt"],"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.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-jwt",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification for jwt in pkg:npm/hono@4.13.2",
  "dependencies": {
    "hono": "4.13.2"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify jwt in pkg:npm/hono@4.13.2",
  "kind": "HOW",
  "packages": [
    "pkg:npm/hono@4.13.2"
  ],
  "symbols": [
    "jwt"
  ],
  "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';

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

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

/**
 * Verifies a JWT token signature and returns the verified payload.
 *
 * @param {string} token - The raw JWT token string.
 * @param {string} secret - Secret key to verify token 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);
}

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

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

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

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

  return app;
}

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

const SECRET = 'sample-verification-secret-key-32bytes!';

// Contract 1: sign generates a signed JWT string with three base64url-encoded segments for a given payload and secret
{
  assert.equal(typeof sign, 'function', 'sign must be a function');
  assert.equal(typeof createToken, 'function');

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

  assert.equal(typeof token, 'string', 'Token must be a string');
  const parts = token.split('.');
  assert.equal(parts.length, 3, 'JWT must have header, payload, and signature parts');
}

// Contract 2: decode parses token header and payload without verifying signature
{
  assert.equal(typeof decode, 'function', 'decode must be a function');
  assert.equal(typeof decodeToken, 'function');

  const payload = { sub: 'usr_1002', name: 'Alice', aud: 'api' };
  const token = await createToken(payload, SECRET, 'HS256');

  const decoded = decodeToken(token);
  assert.equal(typeof decoded, 'object', 'decode must return an object');
  assert.equal(decoded.header.alg, 'HS256', 'Header algorithm must match');
  assert.equal(decoded.header.typ, 'JWT', 'Header type must be JWT');
  assert.equal(decoded.payload.sub, 'usr_1002');
  assert.equal(decoded.payload.name, 'Alice');
  assert.equal(decoded.payload.aud, 'api');
}

// Contract 3: verify validates token signature and returns the payload, rejecting invalid secrets or tampered tokens
{
  assert.equal(typeof verify, 'function', 'verify must be a function');
  assert.equal(typeof verifyToken, 'function');

  const payload = { sub: 'usr_1003', role: 'editor' };
  const token = await createToken(payload, SECRET, 'HS256');

  // Valid verification
  const verified = await verifyToken(token, SECRET, 'HS256');
  assert.equal(verified.sub, 'usr_1003');
  assert.equal(verified.role, 'editor');

  // Invalid secret rejection
  await assert.rejects(
    async () => {
      await verifyToken(token, 'different-wrong-secret-key-32bytes!', 'HS256');
    },
    'verify must reject invalid secret'
  );

  // Tampered payload rejection
  const parts = token.split('.');
  const tamperedToken = `${parts[0]}.eyJzdWIiOiJ1c3JfOTk5OSJ9.${parts[2]}`;
  await assert.rejects(
    async () => {
      await verifyToken(tamperedToken, SECRET, 'HS256');
    },
    'verify must reject tampered token'
  );
}

// Contract 4: jwt middleware authenticates requests with valid Bearer token and injects jwtPayload into context
{
  assert.equal(typeof jwt, 'function', 'jwt must be a function');
  const app = createProtectedApp(SECRET);

  // Public route should be accessible without token
  const pubRes = await app.request('http://localhost/public');
  assert.equal(pubRes.status, 200);
  const pubData = await pubRes.json();
  assert.equal(pubData.status, 'ok');

  // Valid token accessing protected route
  const token = await createToken({ sub: 'usr_1004', role: 'member' }, SECRET, 'HS256');
  const protRes = await app.request('http://localhost/api/profile', {
    headers: {
      Authorization: `Bearer ${token}`
    }
  });
  assert.equal(protRes.status, 200, 'Protected route should return 200 with valid Bearer token');
  const protData = await protRes.json();
  assert.equal(protData.success, true);
  assert.equal(protData.user.sub, 'usr_1004');
  assert.equal(protData.user.role, 'member');
}

// Contract 5: jwt middleware rejects requests with missing or invalid Bearer tokens with 401 Unauthorized
{
  const app = createProtectedApp(SECRET);

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

  // Invalid / corrupted token
  const invalidRes = await app.request('http://localhost/api/profile', {
    headers: {
      Authorization: 'Bearer invalid.token.payload'
    }
  });
  assert.equal(invalidRes.status, 401, 'Invalid Bearer token should return 401');

  // Token signed with wrong secret
  const wrongToken = await createToken({ sub: 'usr_fake' }, 'wrong-secret-key-32bytes!', 'HS256');
  const wrongRes = await app.request('http://localhost/api/profile', {
    headers: {
      Authorization: `Bearer ${wrongToken}`
    }
  });
  assert.equal(wrongRes.status, 401, 'Bearer token with wrong secret should return 401');
}

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

오리진 시더

익명