CodeSampleX

샘플

hono 4.13.3: decode

검증된 샘플 — npm hono 4.13.3: decode. node 22 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: decode parses a valid JWT token string and returns header and…

sha256:ae2d78485e8b95d4f74975e3145ab773f93833f7c441a71f29c0e675f8f8e9b0

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

컨트랙트

  1. decode parses a valid JWT token string and returns header and payload objects without requiring a secret key
  2. decode extracts algorithm alg and type typ from the decoded JWT token header
  3. decode extracts standard and custom claims including sub, iss, aud, exp, and roles from the decoded JWT token payload
  4. decode successfully decodes tokens with expired timestamps or altered signatures without rejecting them
  5. decode throws JwtTokenInvalid when given a token string with an invalid number of segments
  6. decode throws JwtTokenInvalid when token parts contain invalid base64url or malformed JSON

파일

  • 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.decode 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.decode

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:002b55fc87387ba9d6ab53d6a46690f1b41db53233d97e1de710d82dcb20e5a7","contract":["decode parses a valid JWT token string and returns header and payload objects without requiring a secret key","decode extracts algorithm alg and type typ from the decoded JWT token header","decode extracts standard and custom claims including sub, iss, aud, exp, and roles from the decoded JWT token payload","decode successfully decodes tokens with expired timestamps or altered signatures without rejecting them","decode throws JwtTokenInvalid when given a token string with an invalid number of segments","decode throws JwtTokenInvalid when token parts contain invalid base64url or malformed JSON"],"goal":"verify hono.decode in pkg:npm/hono@4.13.3","kind":"HOW","packages":["pkg:npm/hono@4.13.3"],"schemaVersion":1,"symbols":["hono.decode"]},"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.decode"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-hono-decode",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-hono-decode",
      "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-decode",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification for hono.decode in pkg:npm/hono@4.13.3",
  "type": "module",
  "dependencies": {
    "hono": "4.13.3"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify hono.decode in pkg:npm/hono@4.13.3",
  "kind": "HOW",
  "packages": [
    "pkg:npm/hono@4.13.3"
  ],
  "symbols": [
    "hono.decode"
  ]
}
src/index.mjs
import { decode, sign } from 'hono/jwt';

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

/**
 * Helper to generate a signed JWT token string for demonstration and verification.
 *
 * @param {object} payload - Claims payload.
 * @param {string} secret - Secret key for HMAC signing.
 * @param {string} [alg='HS256'] - HMAC algorithm.
 * @returns {Promise<string>} Signed JWT string.
 */
export async function createToken(payload, secret, alg = 'HS256') {
  return await sign(payload, secret, alg);
}

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

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

// Contract 1: decode parses a valid JWT token string and returns header and payload objects without requiring a secret key
{
  assert.equal(typeof decode, 'function', 'decode must be a function');
  assert.equal(typeof decodeToken, 'function', 'decodeToken must be a function');

  const payload = { sub: 'usr_contract_101', role: 'admin' };
  const token = await createToken(payload, TEST_SECRET, 'HS256');

  const result = decodeToken(token);
  assert.equal(typeof result, 'object', 'decode must return an object');
  assert.ok(result.header, 'result must have a header object');
  assert.ok(result.payload, 'result must have a payload object');
  assert.equal(typeof result.header, 'object');
  assert.equal(typeof result.payload, 'object');
}

// Contract 2: decode extracts algorithm alg and type typ from the decoded JWT token header
{
  const payload = { sub: 'usr_contract_102' };
  const token = await createToken(payload, TEST_SECRET, 'HS256');

  const { header } = decode(token);
  assert.equal(header.alg, 'HS256', 'Header algorithm must match signing algorithm');
  assert.equal(header.typ, 'JWT', 'Header type must be JWT');
}

// Contract 3: decode extracts standard and custom claims including sub, iss, aud, exp, and roles from the decoded JWT token payload
{
  const claims = {
    sub: 'usr_contract_103',
    iss: 'https://auth.example.com',
    aud: 'https://api.example.com',
    exp: 1893456000,
    roles: ['operator', 'auditor'],
    orgId: 'org_8819'
  };
  const token = await createToken(claims, TEST_SECRET, 'HS256');

  const { payload } = decode(token);
  assert.equal(payload.sub, 'usr_contract_103');
  assert.equal(payload.iss, 'https://auth.example.com');
  assert.equal(payload.aud, 'https://api.example.com');
  assert.equal(payload.exp, 1893456000);
  assert.deepEqual(payload.roles, ['operator', 'auditor']);
  assert.equal(payload.orgId, 'org_8819');
}

// Contract 4: decode successfully decodes tokens with expired timestamps or altered signatures without rejecting them
{
  const expiredPayload = { sub: 'usr_contract_104', exp: 1000 };
  const token = await createToken(expiredPayload, TEST_SECRET, 'HS256');

  // Expired token should decode cleanly without verifying expiration
  const expiredResult = decode(token);
  assert.equal(expiredResult.payload.sub, 'usr_contract_104');
  assert.equal(expiredResult.payload.exp, 1000);

  // Altered signature should still decode header and payload correctly
  const parts = token.split('.');
  const alteredToken = `${parts[0]}.${parts[1]}.altered_signature_segment`;
  const alteredResult = decode(alteredToken);
  assert.equal(alteredResult.payload.sub, 'usr_contract_104');
}

// Contract 5: decode throws JwtTokenInvalid when given a token string with an invalid number of segments
{
  assert.throws(
    () => decode('not-a-token'),
    (err) => err.name === 'JwtTokenInvalid',
    'Single segment token must throw JwtTokenInvalid'
  );
  assert.throws(
    () => decode('header.payload'),
    (err) => err.name === 'JwtTokenInvalid',
    'Two segment token must throw JwtTokenInvalid'
  );
  assert.throws(
    () => decode('part1.part2.part3.part4'),
    (err) => err.name === 'JwtTokenInvalid',
    'Four segment token must throw JwtTokenInvalid'
  );
}

// Contract 6: decode throws JwtTokenInvalid when token parts contain invalid base64url or malformed JSON
{
  assert.throws(
    () => decode('invalid%base64.validpayload.validsig'),
    (err) => err.name === 'JwtTokenInvalid',
    'Invalid base64url character in header must throw JwtTokenInvalid'
  );

  const notJsonBase64 = Buffer.from('non-json-content-string').toString('base64url');
  assert.throws(
    () => decode(`${notJsonBase64}.${notJsonBase64}.validsig`),
    (err) => err.name === 'JwtTokenInvalid',
    'Non-JSON payload must throw JwtTokenInvalid'
  );
}

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

오리진 시더

익명