示例
hono 4.6.0: bearerAuth
已验证示例 — npm hono 4.6.0: bearerAuth. contract 在 node 22 · linux debian/x64 · docker 上运行并通过: bearerAuth is exported as a middleware factory function from…
sha256:3250a98c16d794ee17df02aa23c4c8c3be119071899a209cdcb190e67a1b341f
本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。
提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。
MIT-0
执行证据
声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。
- 证据依据
- 签名契约通过
- 验证回执
- 1
- 构建过它的签名密钥
- 1
声明的环境
node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10
验证运行环境
| 环境 | 契约 | 阶段 | 运行日期 |
|---|---|---|---|
| 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 pkg:npm/hono@4.6.0
- 符号
-
- bearerAuth
- 环境
- node 22.23.2
- 创建时间
- 2026-09-05T07:35:51Z
契约
- bearerAuth is exported as a middleware factory function from hono/bearer-auth
- bearerAuth throws an Error when initialized without token or verifyToken options
- bearerAuth middleware allows authorized requests with valid Bearer token and passes to route handler
- bearerAuth middleware rejects requests missing Authorization header with status 401 and WWW-Authenticate header
- bearerAuth middleware rejects requests with malformed Authorization header with status 400 and invalid_request error
- bearerAuth middleware rejects requests with incorrect Bearer token with status 401 and invalid_token error
- bearerAuth middleware supports dynamic credential validation using custom verifyToken callback
文件
- PROMPT.md
- csx.json
- package-lock.json
- package.json
- spec.json
- src/index.js
- 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 pkg:npm/hono@4.6.0
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:npm/hono@4.6.0
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:51b5aeb930a6451ae0b4105a10744d2b88e7c9a14baac5de11ab6f11d552b7fb","constraints":{"executionContext":"node"},"contract":["bearerAuth is exported as a middleware factory function from hono/bearer-auth","bearerAuth throws an Error when initialized without token or verifyToken options","bearerAuth middleware allows authorized requests with valid Bearer token and passes to route handler","bearerAuth middleware rejects requests missing Authorization header with status 401 and WWW-Authenticate header","bearerAuth middleware rejects requests with malformed Authorization header with status 400 and invalid_request error","bearerAuth middleware rejects requests with incorrect Bearer token with status 401 and invalid_token error","bearerAuth middleware supports dynamic credential validation using custom verifyToken callback"],"goal":"verify pkg:npm/hono@4.6.0","kind":"HOW","packages":["pkg:npm/hono@4.6.0"],"schemaVersion":1,"symbols":["bearerAuth"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","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.6.0"],"schemaVersion":1,"subject":"pkg:npm/hono@4.6.0","symbols":["bearerAuth"],"verifierAdapter":"node-typescript@1"}
{
"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.6.0"
}
},
"node_modules/hono": {
"version": "4.6.0",
"resolved": "https://registry.npmjs.org/hono/-/hono-4.6.0.tgz",
"integrity": "sha512-2jN7gHRCbfFXpHitg87ZDsComUB+PEm+rf2aDjy6e9SCwgnxkpQBCTKYumWQ4q4D3a+KuSW8VJAHzl4EnqYfeg==",
"license": "MIT",
"engines": {
"node": ">=16.0.0"
}
}
}
}
{
"name": "sample-hono-bearer-auth",
"version": "1.0.0",
"private": true,
"description": "Clean-room code sample for bearerAuth in hono@4.6.0",
"main": "src/index.js",
"license": "MIT-0",
"dependencies": {
"hono": "4.6.0"
}
}
{
"schemaVersion": 1,
"goal": "verify pkg:npm/hono@4.6.0",
"kind": "HOW",
"packages": [
"pkg:npm/hono@4.6.0"
],
"constraints": {
"executionContext": "node"
},
"runtimeConditions": {
"ecosystem": "npm",
"language": "javascript",
"moduleSystem": "cjs",
"packageManager": "npm@10.9.8",
"runtime": "node@22.23.2"
}
}
'use strict';
const { Hono } = require('hono');
const { bearerAuth } = require('hono/bearer-auth');
/**
* Creates and configures a Hono application with bearerAuth middleware.
*
* @returns {Hono}
*/
function createApp() {
const app = new Hono();
// 1. Static token protected route
app.use(
'/api/*',
bearerAuth({
token: 'static-secret-token',
realm: 'API Area'
})
);
app.get('/api/data', (c) => {
return c.json({ status: 'ok', access: 'granted' });
});
// 2. Dynamic token verification callback route
app.use(
'/custom/*',
bearerAuth({
verifyToken: async (token, c) => {
return token === 'dynamic-valid-token';
}
})
);
app.get('/custom/profile', (c) => {
return c.json({ user: 'authenticated-user' });
});
return app;
}
module.exports = {
createApp,
Hono,
bearerAuth
};
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
const {
createApp,
Hono,
bearerAuth
} = require('../src/index.js');
async function testAll() {
// 1. bearerAuth is exported as a middleware factory function from hono/bearer-auth
assert.equal(typeof createApp, 'function', 'createApp must be a function');
assert.equal(typeof Hono, 'function', 'Hono export must be a function');
assert.equal(typeof bearerAuth, 'function', 'bearerAuth is exported as a middleware factory function from hono/bearer-auth');
// 2. bearerAuth throws an Error when initialized without token or verifyToken options
assert.throws(
() => {
bearerAuth({});
},
{
name: 'Error',
message: 'bearer auth middleware requires options for "token"',
}
);
const app = createApp();
// 3. bearerAuth middleware allows authorized requests with valid Bearer token and passes to route handler
const validRes = await app.fetch(
new Request('http://localhost/api/data', {
headers: {
Authorization: 'Bearer static-secret-token'
}
})
);
assert.equal(validRes.status, 200, 'valid token must return status 200');
const validBody = await validRes.json();
assert.deepEqual(validBody, { status: 'ok', access: 'granted' });
// 4. bearerAuth middleware rejects requests missing Authorization header with status 401 and WWW-Authenticate header
const missingHeaderRes = await app.fetch(new Request('http://localhost/api/data'));
assert.equal(missingHeaderRes.status, 401, 'missing authorization header must return 401');
const missingAuthHeader = missingHeaderRes.headers.get('www-authenticate');
assert.ok(missingAuthHeader && missingAuthHeader.includes('Bearer'), 'must include Bearer scheme in WWW-Authenticate header');
assert.ok(missingAuthHeader.includes('realm="API Area"'), 'must include configured realm in WWW-Authenticate header');
assert.equal(await missingHeaderRes.text(), 'Unauthorized');
// 5. bearerAuth middleware rejects requests with malformed Authorization header with status 400 and invalid_request error
const malformedRes = await app.fetch(
new Request('http://localhost/api/data', {
headers: {
Authorization: 'InvalidFormatToken'
}
})
);
assert.equal(malformedRes.status, 400, 'malformed header must return 400');
const malformedAuthHeader = malformedRes.headers.get('www-authenticate');
assert.ok(malformedAuthHeader && malformedAuthHeader.includes('error="invalid_request"'), 'must include invalid_request in WWW-Authenticate header');
assert.equal(await malformedRes.text(), 'Bad Request');
// 6. bearerAuth middleware rejects requests with incorrect Bearer token with status 401 and invalid_token error
const wrongTokenRes = await app.fetch(
new Request('http://localhost/api/data', {
headers: {
Authorization: 'Bearer wrong-secret-token'
}
})
);
assert.equal(wrongTokenRes.status, 401, 'incorrect token must return 401');
const wrongAuthHeader = wrongTokenRes.headers.get('www-authenticate');
assert.ok(wrongAuthHeader && wrongAuthHeader.includes('error="invalid_token"'), 'must include invalid_token in WWW-Authenticate header');
assert.equal(await wrongTokenRes.text(), 'Unauthorized');
// 7. bearerAuth middleware supports dynamic credential validation using custom verifyToken callback
const dynamicValidRes = await app.fetch(
new Request('http://localhost/custom/profile', {
headers: {
Authorization: 'Bearer dynamic-valid-token'
}
})
);
assert.equal(dynamicValidRes.status, 200, 'dynamic valid token must return 200');
const dynamicBody = await dynamicValidRes.json();
assert.deepEqual(dynamicBody, { user: 'authenticated-user' });
const dynamicInvalidRes = await app.fetch(
new Request('http://localhost/custom/profile', {
headers: {
Authorization: 'Bearer invalid-token'
}
})
);
assert.equal(dynamicInvalidRes.status, 401, 'dynamic invalid token must return 401');
const dynamicAuthHeader = dynamicInvalidRes.headers.get('www-authenticate');
assert.ok(dynamicAuthHeader && dynamicAuthHeader.includes('error="invalid_token"'), 'must include invalid_token in WWW-Authenticate header');
console.log('All bearerAuth contract assertions passed.');
}
testAll().catch((err) => {
console.error('Contract test failed:', err);
process.exit(1);
});
原始种子者
匿名