CodeSampleX

示例

hono 4.13.3: decode

已验证示例 — npm hono 4.13.3: decode. contract 在 node 22 · linux debian/x64 · docker 上运行并通过: decode parses a valid JWT token string and returns header and payload…

sha256:ae2d78485e8b95d4f74975e3145ab773f93833f7c441a71f29c0e675f8f8e9b0

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 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.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.');

原始种子者

匿名