Пример
hono 4.13.3: Jwt
Проверенный пример — npm hono 4.13.3: Jwt. Контракт выполнен на node 22 · linux debian/x64 · docker и пройден: sign creates a signed JWT string with three…
sha256:a74fb98049dbee5b16546ef5fe6e4612c2943af1348bbf3746841be08122f8a5
Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла.
Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди.
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-05 |
Кейс
HOW- Цель
- verify hono.Jwt in pkg:npm/hono@4.13.3
- Пакеты
- Символы
-
- hono.Jwt
- Создан
- 2026-09-05T23:46:39Z
Контракт
- sign creates a signed JWT string with three segments for payload and secret
- decode extracts header and payload claims without verifying signature
- verify validates signature and returns payload, rejecting incorrect secret or corrupted token
- jwt middleware requires alg option and authenticates requests with valid Bearer token
- jwt middleware rejects requests without valid Bearer token with 401 Unauthorized
Файлы
- PROMPT.md
- csx.json
- package-lock.json
- package.json
- spec.json
- src/index.mjs
- test/contract.mjs
Исходный код
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.Jwt 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.Jwt
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.
{"case":{"caseId":"case:sha256:95bc6ebfe7c6ed0259e5ca336cab898d594a79bfc8512900287228b364bd1e13","contract":["sign creates a signed JWT string with three segments for payload and secret","decode extracts header and payload claims without verifying signature","verify validates signature and returns payload, rejecting incorrect secret or corrupted token","jwt middleware requires alg option and authenticates requests with valid Bearer token","jwt middleware rejects requests without valid Bearer token with 401 Unauthorized"],"goal":"verify hono.Jwt in pkg:npm/hono@4.13.3","kind":"HOW","packages":["pkg:npm/hono@4.13.3"],"schemaVersion":1,"symbols":["hono.Jwt"]},"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.Jwt"],"verifierAdapter":"node-typescript@1"}
{
"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.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"
}
}
}
}
{
"name": "sample-hono-jwt",
"version": "1.0.0",
"private": true,
"description": "Clean-room verification for hono.Jwt in pkg:npm/hono@4.13.3",
"type": "module",
"dependencies": {
"hono": "4.13.3"
}
}
{
"schemaVersion": 1,
"goal": "verify hono.Jwt in pkg:npm/hono@4.13.3",
"kind": "HOW",
"packages": [
"pkg:npm/hono@4.13.3"
],
"symbols": [
"hono.Jwt"
]
}
import { Hono } from 'hono';
import { jwt, sign, verify, decode } from 'hono/jwt';
export async function createToken(payload, secret, alg = 'HS256') {
return await sign(payload, secret, alg);
}
export function decodeToken(token) {
return decode(token);
}
export async function verifyToken(token, secret, alg = 'HS256') {
return await verify(token, secret, alg);
}
export function createProtectedApp(secret, alg = 'HS256') {
const app = new Hono();
app.use('/api/*', jwt({ secret, alg }));
app.get('/api/me', (c) => {
const payload = c.get('jwtPayload');
return c.json({ user: payload });
});
return app;
}
export { jwt, sign, verify, decode };
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 creates a signed JWT string with three segments for payload and secret
{
assert.equal(typeof sign, 'function');
const payload = { sub: 'usr_1001', role: 'admin' };
const token = await createToken(payload, SECRET, 'HS256');
assert.equal(typeof token, 'string');
const parts = token.split('.');
assert.equal(parts.length, 3);
}
// Contract 2: decode extracts header and payload claims without verifying signature
{
assert.equal(typeof decode, 'function');
const payload = { sub: 'usr_1002', name: 'Alice' };
const token = await createToken(payload, SECRET, 'HS256');
const decoded = decodeToken(token);
assert.equal(typeof decoded, 'object');
assert.equal(decoded.header.alg, 'HS256');
assert.equal(decoded.payload.sub, 'usr_1002');
assert.equal(decoded.payload.name, 'Alice');
}
// Contract 3: verify validates signature and returns payload, rejecting incorrect secret or corrupted token
{
assert.equal(typeof verify, 'function');
const payload = { sub: 'usr_1003' };
const token = await createToken(payload, SECRET, 'HS256');
const verified = await verifyToken(token, SECRET, 'HS256');
assert.equal(verified.sub, 'usr_1003');
await assert.rejects(async () => {
await verifyToken(token, 'wrong-secret-key-32bytes!', 'HS256');
});
const parts = token.split('.');
const tampered = `${parts[0]}.eyJzdWIiOiJ1c3JfOTk5OSJ9.${parts[2]}`;
await assert.rejects(async () => {
await verifyToken(tampered, SECRET, 'HS256');
});
}
// Contract 4: jwt middleware requires alg option and authenticates requests with valid Bearer token
{
assert.equal(typeof jwt, 'function');
assert.throws(() => {
jwt({ secret: SECRET });
}, /requires options for "alg"/);
const app = createProtectedApp(SECRET, 'HS256');
const token = await createToken({ sub: 'usr_1004' }, SECRET, 'HS256');
const res = await app.request('http://localhost/api/me', {
headers: { Authorization: `Bearer ${token}` }
});
assert.equal(res.status, 200);
const data = await res.json();
assert.equal(data.user.sub, 'usr_1004');
}
// Contract 5: jwt middleware rejects requests without valid Bearer token with 401 Unauthorized
{
const app = createProtectedApp(SECRET, 'HS256');
const noAuthRes = await app.request('http://localhost/api/me');
assert.equal(noAuthRes.status, 401);
const invalidRes = await app.request('http://localhost/api/me', {
headers: { Authorization: 'Bearer bad.token.value' }
});
assert.equal(invalidRes.status, 401);
}
console.log('All contracts passed.');
Исходный сидер
аноним