Exemplo
hono 4.12.32
Amostra verificada para npm hono 4.12.32. O contrato rodou em node 22 · linux alpine/x64 · docker e passou: jwt, sign, verify, and decode are exported as…
sha256:5079d5dbfbbb28ba9ed18d1c0a07396cd1f839ae876859d157be706529a6fa0a
Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu.
Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas.
MIT-0
Evidência de execução
O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.
- Base da evidência
- Contrato assinado aprovado
- Recibos de verificação
- 1
- Chaves de assinatura que o compilaram
- 1
Ambiente declarado
node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10
Ambientes das execuções de verificação
| Ambiente | Contrato | Etapas | Execução |
|---|---|---|---|
| node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5… |
2026-08-28 |
Caso
HOW- Objetivo
- verify pkg:npm/hono@4.12.32
- Pacotes
- Ambiente
- node 22.23.2
- Criado
- 2026-08-28T07:26:32Z
Contrato
- jwt, sign, verify, and decode are exported as functions from hono/jwt
- sign creates a signed JWT string and decode extracts payload without verification
- verify validates signature with algorithm and secret, rejecting invalid signatures
- verify throws JwtAlgorithmRequired when algorithm argument is omitted
- jwt middleware protects routes, returning status 401 when Authorization header is missing or malformed
- jwt middleware grants access for valid Bearer token and attaches decoded payload to context jwtPayload
- jwt middleware supports extracting and validating token from configured cookie
Arquivos
- PROMPT.md
- csx.json
- package-lock.json
- package.json
- spec.json
- src/index.mjs
- test/contract.mjs
Código-fonte
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 pkg:npm/hono@4.12.32
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:npm/hono@4.12.32
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.
{"case":{"caseId":"case:sha256:774c0b704863258028e57a88258c68f0a5f240487d63328cee8c7b62b956db53","constraints":{"executionContext":"node"},"contract":["jwt, sign, verify, and decode are exported as functions from hono/jwt","sign creates a signed JWT string and decode extracts payload without verification","verify validates signature with algorithm and secret, rejecting invalid signatures","verify throws JwtAlgorithmRequired when algorithm argument is omitted","jwt middleware protects routes, returning status 401 when Authorization header is missing or malformed","jwt middleware grants access for valid Bearer token and attaches decoded payload to context jwtPayload","jwt middleware supports extracting and validating token from configured cookie"],"goal":"verify pkg:npm/hono@4.12.32","kind":"HOW","packages":["pkg:npm/hono@4.12.32"],"schemaVersion":1},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"esm","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.12.32"],"schemaVersion":1,"subject":"pkg:npm/hono@4.12.32","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.12.32"
}
},
"node_modules/hono": {
"version": "4.12.32",
"resolved": "https://registry.npmjs.org/hono/-/hono-4.12.32.tgz",
"integrity": "sha512-XcuyW9qE2kJn07PkecMOBd5Vq/hMy7mmGw+idz1yblbg9N17ijJODrvPkn7/dwL3Kulj8LcRJ69DLOWf91dRUg==",
"license": "MIT",
"engines": {
"node": ">=16.9.0"
}
}
}
}
{
"name": "sample-hono-jwt",
"version": "1.0.0",
"type": "module",
"private": true,
"dependencies": {
"hono": "4.12.32"
}
}
{
"schemaVersion": 1,
"goal": "verify pkg:npm/hono@4.12.32",
"kind": "HOW",
"packages": [
"pkg:npm/hono@4.12.32"
],
"constraints": {
"executionContext": "node"
},
"runtimeConditions": {
"ecosystem": "npm",
"language": "javascript",
"moduleSystem": "cjs",
"packageManager": "npm@10.9.8",
"runtime": "node@22.23.2"
}
}
import { Hono } from "hono";
import { jwt, sign, verify, decode } from "hono/jwt";
export function generateToken(payload, secret, alg = "HS256") {
return sign(payload, secret, alg);
}
export function parseToken(token) {
return decode(token);
}
export function validateToken(token, secret, alg = "HS256") {
return verify(token, secret, alg);
}
export function createApp(secret) {
const app = new Hono();
// Public health check route
app.get("/health", (c) => c.json({ status: "healthy" }));
// JWT Bearer auth protected routes
app.use("/api/*", jwt({ secret, alg: "HS256" }));
app.get("/api/profile", (c) => {
const payload = c.get("jwtPayload");
return c.json({
status: "authenticated",
user: payload,
});
});
// JWT Cookie auth protected routes
app.use("/cookie-api/*", jwt({ secret, alg: "HS256", cookie: "auth_token" }));
app.get("/cookie-api/session", (c) => {
const payload = c.get("jwtPayload");
return c.json({
status: "authenticated",
session: payload,
});
});
return app;
}
import assert from "node:assert/strict";
import { Hono } from "hono";
import { jwt, sign, verify, decode } from "hono/jwt";
import { createApp, generateToken, parseToken, validateToken } from "../src/index.mjs";
async function runContract() {
const secretKey = "test-jwt-secret-key-1234567890123456";
const userPayload = {
sub: "user-42",
role: "admin",
name: "Sample User",
};
// 1. Verify module exports
assert.equal(typeof jwt, "function", "jwt should be a middleware factory function");
assert.equal(typeof sign, "function", "sign should be a function");
assert.equal(typeof verify, "function", "verify should be a function");
assert.equal(typeof decode, "function", "decode should be a function");
// 2. Test sign and decode
const token = await generateToken(userPayload, secretKey, "HS256");
assert.equal(typeof token, "string", "Token must be a non-empty string");
assert.ok(token.split(".").length === 3, "JWT token must have 3 segments");
const decoded = parseToken(token);
assert.equal(decoded.payload.sub, "user-42");
assert.equal(decoded.payload.role, "admin");
assert.equal(decoded.payload.name, "Sample User");
assert.equal(decoded.header.alg, "HS256");
// 3. Test verify with valid and invalid secret
const verifiedPayload = await validateToken(token, secretKey, "HS256");
assert.equal(verifiedPayload.sub, "user-42");
assert.equal(verifiedPayload.role, "admin");
await assert.rejects(
async () => {
await validateToken(token, "wrong-secret-key-0000000000000000", "HS256");
},
"verify should reject with invalid secret"
);
// 4. Test verify without alg option throws JwtAlgorithmRequired
await assert.rejects(
async () => {
await verify(token, secretKey);
},
(err) => {
return err && err.name === "JwtAlgorithmRequired";
},
"verify without alg option must throw JwtAlgorithmRequired"
);
// 5. Setup app and test routes
const app = createApp(secretKey);
// Public route test
const healthRes = await app.request("http://localhost/health");
assert.equal(healthRes.status, 200);
assert.deepEqual(await healthRes.json(), { status: "healthy" });
// 6. Protected route without token returns 401
const noAuthRes = await app.request("http://localhost/api/profile");
assert.equal(noAuthRes.status, 401, "Protected route must return 401 without auth header");
// Malformed token returns 401
const badTokenRes = await app.request("http://localhost/api/profile", {
headers: { Authorization: "Bearer bad.token.here" },
});
assert.equal(badTokenRes.status, 401, "Protected route must return 401 with malformed token");
// 7. Protected route with valid Bearer token returns 200 and payload in context
const authRes = await app.request("http://localhost/api/profile", {
headers: { Authorization: `Bearer ${token}` },
});
assert.equal(authRes.status, 200, "Protected route must return 200 with valid Bearer token");
const authData = await authRes.json();
assert.equal(authData.status, "authenticated");
assert.equal(authData.user.sub, "user-42");
assert.equal(authData.user.role, "admin");
// 8. Protected route with Cookie authentication
const cookieRes = await app.request("http://localhost/cookie-api/session", {
headers: { Cookie: `auth_token=${token}` },
});
assert.equal(cookieRes.status, 200, "Cookie protected route must return 200 with valid auth cookie");
const cookieData = await cookieRes.json();
assert.equal(cookieData.status, "authenticated");
assert.equal(cookieData.session.sub, "user-42");
// Cookie protected route without cookie returns 401
const noCookieRes = await app.request("http://localhost/cookie-api/session");
assert.equal(noCookieRes.status, 401, "Cookie protected route must return 401 without auth cookie");
console.log("All contract tests passed successfully.");
}
await runContract();
Seeder de origem
anônimo