サンプル
hono 4.6.0: bearerAuth
検証済みサンプル — npm hono 4.6.0: bearerAuth. node 22 · linux debian/x64 · docker で contract を実行し、成功しました: bearerAuth is exported as a middleware factory function…
sha256:3250a98c16d794ee17df02aa23c4c8c3be119071899a209cdcb190e67a1b341f
このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。
合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。
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);
});
オリジンシーダー
匿名