サンプル
hono 4.13.7: basic-auth
検証済みサンプル — npm hono 4.13.7: basic-auth. node 22 · linux debian/x64 · docker で contract を実行し、成功しました: basicAuth throws an Error when neither username/password…
sha256:7122de289d7c189946c854d88a819b58ffd2bd2aae03ea9b9d02a30dca3df609
このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。
合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。
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-06 |
ケース
HOW- ゴール
- verify hono/basic-auth in pkg:npm/hono@4.13.7
- パッケージ
- シンボル
-
- hono/basic-auth
- 作成日
- 2026-09-06T04:30:38Z
コントラクト
- basicAuth throws an Error when neither username/password nor verifyUser is configured
- basicAuth middleware authorizes requests matching static username and password
- basicAuth middleware rejects unauthorized or missing credentials with 401 and WWW-Authenticate header
- basicAuth middleware supports multiple static user credential pairs
- basicAuth middleware supports custom verifyUser predicate and onAuthSuccess callback
- basicAuth middleware formats custom object invalidUserMessage as JSON
ファイル
- 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/basic-auth in pkg:npm/hono@4.13.7
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:npm/hono@4.13.7
Demonstrate these symbols/APIs:
- hono/basic-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:54bba64364ba3c450da275b86a350c3e2f9ad6c11312592d9f8cd0122d8895c0","contract":["basicAuth throws an Error when neither username/password nor verifyUser is configured","basicAuth middleware authorizes requests matching static username and password","basicAuth middleware rejects unauthorized or missing credentials with 401 and WWW-Authenticate header","basicAuth middleware supports multiple static user credential pairs","basicAuth middleware supports custom verifyUser predicate and onAuthSuccess callback","basicAuth middleware formats custom object invalidUserMessage as JSON"],"goal":"verify hono/basic-auth in pkg:npm/hono@4.13.7","kind":"HOW","packages":["pkg:npm/hono@4.13.7"],"schemaVersion":1,"symbols":["hono/basic-auth"]},"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.7"],"schemaVersion":1,"subject":"pkg:npm/hono@4.13.7","symbols":["hono/basic-auth"],"verifierAdapter":"node-typescript@1"}
{
"name": "sample-hono-basic-auth",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "sample-hono-basic-auth",
"version": "1.0.0",
"dependencies": {
"hono": "4.13.7"
}
},
"node_modules/hono": {
"version": "4.13.7",
"resolved": "https://registry.npmjs.org/hono/-/hono-4.13.7.tgz",
"integrity": "sha512-c8/gF9ac8Y78/agExVocyLevgR+JlpNB444Py0FSX8pJoPdYUfUzRcXtYEYGwt6l19qIlVZPN5Mfsw9jFShmQQ==",
"license": "MIT",
"engines": {
"node": ">=16.9.0"
}
}
}
}
{
"name": "sample-hono-basic-auth",
"version": "1.0.0",
"private": true,
"description": "Clean-room verification for hono/basic-auth in pkg:npm/hono@4.13.7",
"type": "module",
"dependencies": {
"hono": "4.13.7"
}
}
{
"schemaVersion": 1,
"goal": "verify hono/basic-auth in pkg:npm/hono@4.13.7",
"kind": "HOW",
"packages": [
"pkg:npm/hono@4.13.7"
],
"symbols": [
"hono/basic-auth"
]
}
import { Hono } from 'hono';
import { basicAuth } from 'hono/basic-auth';
/**
* Creates a Hono application protected with static basic auth credentials.
*
* @param {object} options - Basic auth options (username, password, realm, invalidUserMessage).
* @param {Array<object>} [extraUsers] - Optional additional users.
* @returns {Hono} Configured Hono app.
*/
export function createBasicAuthApp(options, ...extraUsers) {
const app = new Hono();
// Public endpoint
app.get('/public', (c) => c.json({ status: 'ok', public: true }));
// Protected route guarded by basicAuth middleware
app.use('/admin/*', basicAuth(options, ...extraUsers));
app.get('/admin/data', (c) => c.json({ secret: 'protected-payload' }));
return app;
}
/**
* Creates a Hono application configured with dynamic verifyUser authentication.
*
* @param {Function} verifyUser - Custom credential validation function.
* @param {Function} [onAuthSuccess] - Callback executed on successful authentication.
* @returns {Hono} Configured Hono app.
*/
export function createDynamicAuthApp(verifyUser, onAuthSuccess) {
const app = new Hono();
app.use(
'/secure/*',
basicAuth({
verifyUser,
...(onAuthSuccess ? { onAuthSuccess } : {})
})
);
app.get('/secure/profile', (c) => {
const user = c.get('user') || 'anonymous';
return c.json({ authenticated: true, user });
});
return app;
}
export { basicAuth };
import assert from 'node:assert/strict';
import { basicAuth, createBasicAuthApp, createDynamicAuthApp } from '../src/index.mjs';
function toBasicAuthHeader(username, password) {
return 'Basic ' + Buffer.from(`${username}:${password}`).toString('base64');
}
// Contract 1: basicAuth throws an Error when neither username/password nor verifyUser is configured
{
assert.equal(typeof basicAuth, 'function', 'basicAuth must be a function');
assert.throws(
() => {
basicAuth({});
},
/basic auth middleware requires options for "username and password" or "verifyUser"/,
'basicAuth must throw when missing both credentials and verifyUser'
);
}
// Contract 2: basicAuth middleware authorizes requests matching static username and password
{
const app = createBasicAuthApp({
username: 'admin',
password: 'supersecretpassword',
realm: 'Administration'
});
const validHeader = toBasicAuthHeader('admin', 'supersecretpassword');
const res = await app.request('http://localhost/admin/data', {
headers: { Authorization: validHeader }
});
assert.equal(res.status, 200, 'Valid credentials must yield 200 OK');
const body = await res.json();
assert.deepEqual(body, { secret: 'protected-payload' });
// Verify public route remains accessible without credentials
const pubRes = await app.request('http://localhost/public');
assert.equal(pubRes.status, 200);
}
// Contract 3: basicAuth middleware rejects unauthorized or missing credentials with 401 and WWW-Authenticate header
{
const app = createBasicAuthApp({
username: 'admin',
password: 'supersecretpassword',
realm: 'Administration'
});
// Missing Authorization header
const missingRes = await app.request('http://localhost/admin/data');
assert.equal(missingRes.status, 401, 'Missing credentials must yield 401');
assert.equal(
missingRes.headers.get('WWW-Authenticate'),
'Basic realm="Administration"',
'Must return WWW-Authenticate header with specified realm'
);
assert.equal(await missingRes.text(), 'Unauthorized');
// Wrong password
const wrongPwHeader = toBasicAuthHeader('admin', 'wrongpass');
const wrongPwRes = await app.request('http://localhost/admin/data', {
headers: { Authorization: wrongPwHeader }
});
assert.equal(wrongPwRes.status, 401, 'Incorrect password must yield 401');
// Wrong username
const wrongUserHeader = toBasicAuthHeader('stranger', 'supersecretpassword');
const wrongUserRes = await app.request('http://localhost/admin/data', {
headers: { Authorization: wrongUserHeader }
});
assert.equal(wrongUserRes.status, 401, 'Incorrect username must yield 401');
}
// Contract 4: basicAuth middleware supports multiple static user credential pairs
{
const app = createBasicAuthApp(
{ username: 'alice', password: 'alice-password' },
{ username: 'bob', password: 'bob-password' }
);
const resAlice = await app.request('http://localhost/admin/data', {
headers: { Authorization: toBasicAuthHeader('alice', 'alice-password') }
});
assert.equal(resAlice.status, 200, 'Alice must be authorized');
const resBob = await app.request('http://localhost/admin/data', {
headers: { Authorization: toBasicAuthHeader('bob', 'bob-password') }
});
assert.equal(resBob.status, 200, 'Bob must be authorized');
const resCharlie = await app.request('http://localhost/admin/data', {
headers: { Authorization: toBasicAuthHeader('charlie', 'charlie-password') }
});
assert.equal(resCharlie.status, 401, 'Charlie must be rejected');
}
// Contract 5: basicAuth middleware supports custom verifyUser predicate and onAuthSuccess callback
{
let successRecorded = null;
const app = createDynamicAuthApp(
async (username, password, c) => {
return username === 'dynamic-user' && password === 'dynamic-pass';
},
async (c, username) => {
successRecorded = username;
c.set('user', username);
}
);
const resValid = await app.request('http://localhost/secure/profile', {
headers: { Authorization: toBasicAuthHeader('dynamic-user', 'dynamic-pass') }
});
assert.equal(resValid.status, 200, 'Valid dynamic credentials must succeed');
assert.equal(successRecorded, 'dynamic-user', 'onAuthSuccess must receive username');
const bodyValid = await resValid.json();
assert.deepEqual(bodyValid, { authenticated: true, user: 'dynamic-user' });
// Invalid dynamic credentials
const resInvalid = await app.request('http://localhost/secure/profile', {
headers: { Authorization: toBasicAuthHeader('dynamic-user', 'wrong-pass') }
});
assert.equal(resInvalid.status, 401, 'Invalid dynamic credentials must fail');
}
// Contract 6: basicAuth middleware formats custom object invalidUserMessage as JSON
{
const app = createBasicAuthApp({
username: 'apiuser',
password: 'apipassword',
invalidUserMessage: { error: 'Authentication required', code: 40101 }
});
const res = await app.request('http://localhost/admin/data');
assert.equal(res.status, 401);
assert.equal(res.headers.get('content-type'), 'application/json');
const errorJson = await res.json();
assert.deepEqual(errorJson, { error: 'Authentication required', code: 40101 });
}
console.log('All contracts for hono/basic-auth in pkg:npm/hono@4.13.7 passed.');
オリジンシーダー
匿名