CodeSampleX

示例

hono 4.6.0: basicAuth

已验证示例 — npm hono 4.6.0: basicAuth. contract 在 node 22 · linux debian/x64 · docker 上运行并通过: basicAuth is exported as a middleware factory function from…

sha256:c79902bb9716dc2f828438d5b170d5400746d849e0192948d2bc9d9cf9e85ba3

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 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-05

案例

HOW
目标
verify basicAuth in pkg:npm/hono@4.6.0
包
符号
  • basicAuth
创建时间
2026-09-05T07:25:58Z

契约

  1. basicAuth is exported as a middleware factory function from hono/basic-auth
  2. basicAuth middleware rejects requests missing Authorization header with status 401 and WWW-Authenticate header
  3. basicAuth middleware authorizes requests with valid static credentials and allows route handler execution
  4. basicAuth middleware rejects requests with invalid password or username with status 401
  5. basicAuth middleware supports dynamic credential validation using custom verifyUser callback

文件

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • test/contract.mjs

下载源代码构件 (tar.gz)

源代码

PROMPT.md
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 basicAuth in pkg:npm/hono@4.6.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/hono@4.6.0
Demonstrate these symbols/APIs:
  - basicAuth

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.
csx.json
{"case":{"caseId":"case:sha256:6277119337e0f66c1e869f9203a637e20e42b61860f7fa53d523eaf293f597c5","contract":["basicAuth is exported as a middleware factory function from hono/basic-auth","basicAuth middleware rejects requests missing Authorization header with status 401 and WWW-Authenticate header","basicAuth middleware authorizes requests with valid static credentials and allows route handler execution","basicAuth middleware rejects requests with invalid password or username with status 401","basicAuth middleware supports dynamic credential validation using custom verifyUser callback"],"goal":"verify basicAuth in pkg:npm/hono@4.6.0","kind":"HOW","packages":["pkg:npm/hono@4.6.0"],"schemaVersion":1,"symbols":["basicAuth"]},"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.6.0"],"schemaVersion":1,"subject":"pkg:npm/hono@4.6.0","symbols":["basicAuth"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-hono-basic-auth",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-hono-basic-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"
      }
    }
  }
}
package.json
{
  "name": "sample-hono-basic-auth",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room code sample for basicAuth in hono@4.6.0",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "hono": "4.6.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify basicAuth in pkg:npm/hono@4.6.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/hono@4.6.0"
  ],
  "symbols": [
    "basicAuth"
  ]
}
src/index.js
'use strict';

const { Hono } = require('hono');
const { basicAuth } = require('hono/basic-auth');

/**
 * Creates and configures a Hono application with basicAuth middleware.
 *
 * @returns {Hono}
 */
function createApp() {
  const app = new Hono();

  // 1. Static credentials with custom realm
  app.use(
    '/admin/*',
    basicAuth({
      username: 'admin',
      password: 'secretpassword',
      realm: 'Admin Area'
    })
  );

  app.get('/admin/dashboard', (c) => {
    return c.json({ message: 'welcome to admin dashboard' });
  });

  // 2. Dynamic credentials with custom verifyUser callback
  app.use(
    '/dynamic/*',
    basicAuth({
      verifyUser: (username, password, c) => {
        return username === 'alice' && password === 'wonderland';
      },
      realm: 'Restricted Area'
    })
  );

  app.get('/dynamic/profile', (c) => {
    return c.json({ user: 'alice', authenticated: true });
  });

  return app;
}

module.exports = {
  createApp,
  Hono,
  basicAuth
};
test/contract.mjs
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const {
  createApp,
  Hono,
  basicAuth
} = require('../src/index.js');

async function testAll() {
  const app = createApp();

  // 1. basicAuth is exported as a middleware factory function from hono/basic-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 basicAuth, 'function', 'basicAuth is exported as a middleware factory function from hono/basic-auth');

  // 2. basicAuth middleware rejects requests missing Authorization header with status 401 and WWW-Authenticate header
  const unauthorizedRes = await app.fetch(new Request('http://localhost/admin/dashboard'));
  assert.equal(unauthorizedRes.status, 401, 'missing credentials must return 401');
  const authHeader = unauthorizedRes.headers.get('www-authenticate');
  assert.ok(authHeader && authHeader.includes('Basic'), 'response must include WWW-Authenticate header with Basic scheme');
  assert.ok(authHeader.includes('Admin Area'), 'response WWW-Authenticate must include configured realm');

  // 3. basicAuth middleware authorizes requests with valid static credentials and allows route handler execution
  const validCreds = Buffer.from('admin:secretpassword').toString('base64');
  const validRes = await app.fetch(
    new Request('http://localhost/admin/dashboard', {
      headers: { Authorization: `Basic ${validCreds}` }
    })
  );
  assert.equal(validRes.status, 200, 'valid credentials must return status 200');
  const validBody = await validRes.json();
  assert.deepEqual(validBody, { message: 'welcome to admin dashboard' });

  // 4. basicAuth middleware rejects requests with invalid password or username with status 401
  const invalidCreds = Buffer.from('admin:wrongpassword').toString('base64');
  const invalidRes = await app.fetch(
    new Request('http://localhost/admin/dashboard', {
      headers: { Authorization: `Basic ${invalidCreds}` }
    })
  );
  assert.equal(invalidRes.status, 401, 'invalid password must return status 401');

  const wrongUserCreds = Buffer.from('wronguser:secretpassword').toString('base64');
  const wrongUserRes = await app.fetch(
    new Request('http://localhost/admin/dashboard', {
      headers: { Authorization: `Basic ${wrongUserCreds}` }
    })
  );
  assert.equal(wrongUserRes.status, 401, 'wrong username must return status 401');

  // 5. basicAuth middleware supports dynamic credential validation using custom verifyUser callback
  const dynamicValidCreds = Buffer.from('alice:wonderland').toString('base64');
  const dynamicValidRes = await app.fetch(
    new Request('http://localhost/dynamic/profile', {
      headers: { Authorization: `Basic ${dynamicValidCreds}` }
    })
  );
  assert.equal(dynamicValidRes.status, 200, 'dynamic valid credentials must return 200');
  const dynamicData = await dynamicValidRes.json();
  assert.deepEqual(dynamicData, { user: 'alice', authenticated: true });

  const dynamicInvalidCreds = Buffer.from('alice:wrongpass').toString('base64');
  const dynamicInvalidRes = await app.fetch(
    new Request('http://localhost/dynamic/profile', {
      headers: { Authorization: `Basic ${dynamicInvalidCreds}` }
    })
  );
  assert.equal(dynamicInvalidRes.status, 401, 'dynamic invalid credentials must return 401');

  console.log('All basicAuth contract assertions passed.');
}

testAll().catch((err) => {
  console.error('Contract test failed:', err);
  process.exit(1);
});

原始种子者

匿名