Exemple
hono 4.13.1: bearer-auth
Échantillon vérifié pour npm hono 4.13.1: bearer-auth. Le contrat s'est exécuté sur node 22 · linux debian/x64 · docker et a réussi.
sha256:2d4eefa45fd8c7c70c76c1dae4176e893170476d2c405b78836d5be4c9f78a34
Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré.
Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes.
MIT-0
Preuves d'exécution
L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.
- Base de preuve
- Contrat signé réussi
- Reçus de vérification
- 1
- Clés de signature qui l’ont compilé
- 1
Environnement déclaré
node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10
Environnements des exécutions de vérification
| Environnement | Contrat | Étapes | Exécution |
|---|---|---|---|
| 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 |
Cas
HOW- Objectif
- verify hono/bearer-auth in pkg:npm/hono@4.13.1
- Paquets
- Symboles
-
- hono/bearer-auth
- Environnement
- node 22.23.2
- Créé
- 2026-09-01T19:51:44Z
Contrat
- assert bearerAuth is exported as a function from hono/bearer-auth
- assert bearerAuth grants access with 200 OK when valid static bearer token is provided
- assert bearerAuth returns 401 Unauthorized with WWW-Authenticate header when authorization header is missing
- assert bearerAuth returns 400 Bad Request when authorization header prefix is malformed
- assert bearerAuth returns 401 Unauthorized with invalid_token error when token does not match
- assert bearerAuth supports multiple valid tokens configured as an array
- assert bearerAuth supports custom verifyToken predicate function
- assert bearerAuth supports custom headerName and custom prefix
- assert bearerAuth supports custom realm and custom error messages
Fichiers
- PROMPT.md
- csx.json
- index.mjs
- package-lock.json
- package.json
- spec.json
- test/contract.mjs
Code source
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/bearer-auth in pkg:npm/hono@4.13.1
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:npm/hono@4.13.1
Demonstrate these symbols/APIs:
- hono/bearer-auth
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:5b137ee068f37e934a117a992930bf88f774c27c0c856a7ad4384b4be7f540db","contract":["assert bearerAuth is exported as a function from hono/bearer-auth","assert bearerAuth grants access with 200 OK when valid static bearer token is provided","assert bearerAuth returns 401 Unauthorized with WWW-Authenticate header when authorization header is missing","assert bearerAuth returns 400 Bad Request when authorization header prefix is malformed","assert bearerAuth returns 401 Unauthorized with invalid_token error when token does not match","assert bearerAuth supports multiple valid tokens configured as an array","assert bearerAuth supports custom verifyToken predicate function","assert bearerAuth supports custom headerName and custom prefix","assert bearerAuth supports custom realm and custom error messages"],"goal":"verify hono/bearer-auth in pkg:npm/hono@4.13.1","kind":"HOW","packages":["pkg:npm/hono@4.13.1"],"schemaVersion":1,"symbols":["hono/bearer-auth"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","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.13.1"],"schemaVersion":1,"subject":"pkg:npm/hono@4.13.1","symbols":["hono/bearer-auth"],"verifierAdapter":"node-typescript@1"}
import { Hono } from 'hono';
import { bearerAuth } from 'hono/bearer-auth';
export { bearerAuth };
/**
* Creates a Hono application protected by bearerAuth middleware.
* @param {import('hono/bearer-auth').BearerAuthOptions} options
* @returns {Hono}
*/
export function createProtectedApp(options) {
const app = new Hono();
app.use('/api/*', bearerAuth(options));
app.get('/api/resource', (c) => c.json({ status: 'ok', message: 'access granted' }));
return app;
}
{
"name": "sample-hono-bearer-auth",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "sample-hono-bearer-auth",
"version": "1.0.0",
"license": "MIT-0",
"dependencies": {
"hono": "4.13.1"
}
},
"node_modules/hono": {
"version": "4.13.1",
"resolved": "https://registry.npmjs.org/hono/-/hono-4.13.1.tgz",
"integrity": "sha512-kdJoFVv2xmayw6cY09H7AbMJMt8Jn5jdlEdXsP7AGBdF2DIptVlKlOLKXP41yPip4/a3yQPv9gVcJYI8YY04dw==",
"license": "MIT",
"engines": {
"node": ">=16.9.0"
}
}
}
}
{
"name": "sample-hono-bearer-auth",
"version": "1.0.0",
"description": "Clean-room sample verifying hono/bearer-auth in hono",
"type": "module",
"main": "index.mjs",
"license": "MIT-0",
"dependencies": {
"hono": "4.13.1"
}
}
{
"schemaVersion": 1,
"goal": "verify hono/bearer-auth in pkg:npm/hono@4.13.1",
"kind": "HOW",
"packages": [
"pkg:npm/hono@4.13.1"
],
"symbols": [
"hono/bearer-auth"
]
}
import assert from 'node:assert';
import { bearerAuth } from 'hono/bearer-auth';
import { createProtectedApp } from '../index.mjs';
// 1. assert bearerAuth is exported as a function from hono/bearer-auth
assert.strictEqual(typeof bearerAuth, 'function', 'bearerAuth must be a function');
// 2. assert bearerAuth grants access with 200 OK when valid static bearer token is provided
const singleTokenApp = createProtectedApp({ token: 'secret-token-123' });
const resValid = await singleTokenApp.request('/api/resource', {
headers: { Authorization: 'Bearer secret-token-123' },
});
assert.strictEqual(resValid.status, 200, 'Valid bearer token must return 200 OK');
const validData = await resValid.json();
assert.deepStrictEqual(validData, { status: 'ok', message: 'access granted' }, 'Response body must match protected handler output');
// 3. assert bearerAuth returns 401 Unauthorized with WWW-Authenticate header when authorization header is missing
const resNoHeader = await singleTokenApp.request('/api/resource');
assert.strictEqual(resNoHeader.status, 401, 'Missing authorization header must return 401 Unauthorized');
assert.strictEqual(resNoHeader.headers.get('www-authenticate'), 'Bearer realm=""', 'Must set WWW-Authenticate realm header on missing auth');
// 4. assert bearerAuth returns 400 Bad Request when authorization header prefix is malformed
const resBadFormat = await singleTokenApp.request('/api/resource', {
headers: { Authorization: 'Basic secret-token-123' },
});
assert.strictEqual(resBadFormat.status, 400, 'Invalid auth header prefix format must return 400 Bad Request');
// 5. assert bearerAuth returns 401 Unauthorized with invalid_token error when token does not match
const resWrongToken = await singleTokenApp.request('/api/resource', {
headers: { Authorization: 'Bearer incorrect-token' },
});
assert.strictEqual(resWrongToken.status, 401, 'Incorrect bearer token must return 401 Unauthorized');
assert.strictEqual(resWrongToken.headers.get('www-authenticate'), 'Bearer error="invalid_token"', 'Must set WWW-Authenticate error on invalid token');
// 6. assert bearerAuth supports multiple valid tokens configured as an array
const multiTokenApp = createProtectedApp({ token: ['token-alpha', 'token-beta'] });
const resAlpha = await multiTokenApp.request('/api/resource', {
headers: { Authorization: 'Bearer token-alpha' },
});
assert.strictEqual(resAlpha.status, 200, 'First token in multi-token array must return 200 OK');
const resBeta = await multiTokenApp.request('/api/resource', {
headers: { Authorization: 'Bearer token-beta' },
});
assert.strictEqual(resBeta.status, 200, 'Second token in multi-token array must return 200 OK');
const resGamma = await multiTokenApp.request('/api/resource', {
headers: { Authorization: 'Bearer token-gamma' },
});
assert.strictEqual(resGamma.status, 401, 'Unlisted token in multi-token array must return 401 Unauthorized');
// 7. assert bearerAuth supports custom verifyToken predicate function
const customVerifyApp = createProtectedApp({
verifyToken: async (token, c) => {
return token === 'dynamic-valid' && c.req.path === '/api/resource';
},
});
const resDynamicValid = await customVerifyApp.request('/api/resource', {
headers: { Authorization: 'Bearer dynamic-valid' },
});
assert.strictEqual(resDynamicValid.status, 200, 'verifyToken returning true must grant access');
const resDynamicInvalid = await customVerifyApp.request('/api/resource', {
headers: { Authorization: 'Bearer dynamic-invalid' },
});
assert.strictEqual(resDynamicInvalid.status, 401, 'verifyToken returning false must return 401 Unauthorized');
// 8. assert bearerAuth supports custom headerName and custom prefix
const customHeaderApp = createProtectedApp({
headerName: 'x-api-key',
prefix: 'Token',
token: 'custom-header-secret',
});
const resCustomHeaderValid = await customHeaderApp.request('/api/resource', {
headers: { 'x-api-key': 'Token custom-header-secret' },
});
assert.strictEqual(resCustomHeaderValid.status, 200, 'Custom header and prefix must grant access');
const resCustomHeaderWrongPrefix = await customHeaderApp.request('/api/resource', {
headers: { 'x-api-key': 'Bearer custom-header-secret' },
});
assert.strictEqual(resCustomHeaderWrongPrefix.status, 400, 'Mismatched prefix on custom header must return 400 Bad Request');
// 9. assert bearerAuth supports custom realm and custom error messages
const customMessagesApp = createProtectedApp({
token: 'msg-token',
realm: 'secure-api',
noAuthenticationHeaderMessage: 'No token header',
invalidAuthenticationHeaderMessage: 'Invalid prefix scheme',
invalidTokenMessage: 'Token verification failed',
});
const resCustomNoHeader = await customMessagesApp.request('/api/resource');
assert.strictEqual(resCustomNoHeader.status, 401, 'Custom message app missing header must return 401');
assert.strictEqual(await resCustomNoHeader.text(), 'No token header', 'Custom noAuthenticationHeaderMessage must be returned');
assert.strictEqual(resCustomNoHeader.headers.get('www-authenticate'), 'Bearer realm="secure-api"', 'Custom realm must be reflected in header');
const resCustomBadPrefix = await customMessagesApp.request('/api/resource', {
headers: { Authorization: 'Digest 12345' },
});
assert.strictEqual(resCustomBadPrefix.status, 400, 'Custom message app bad prefix must return 400');
assert.strictEqual(await resCustomBadPrefix.text(), 'Invalid prefix scheme', 'Custom invalidAuthenticationHeaderMessage must be returned');
const resCustomWrongToken = await customMessagesApp.request('/api/resource', {
headers: { Authorization: 'Bearer wrong-msg-token' },
});
assert.strictEqual(resCustomWrongToken.status, 401, 'Custom message app wrong token must return 401');
assert.strictEqual(await resCustomWrongToken.text(), 'Token verification failed', 'Custom invalidTokenMessage must be returned');
console.log('All hono/bearer-auth contract assertions passed.');
Seeder d'origine
anonyme