CodeSampleX

示例

hono 4.13.7: basic-auth

已验证示例 — npm hono 4.13.7: basic-auth. contract 在 node 22 · linux debian/x64 · docker 上运行并通过: basicAuth throws an Error when neither username/password nor…

sha256:7122de289d7c189946c854d88a819b58ffd2bd2aae03ea9b9d02a30dca3df609

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 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-06

案例

HOW
目标
verify hono/basic-auth in pkg:npm/hono@4.13.7
包
符号
  • hono/basic-auth
创建时间
2026-09-06T04:30:38Z

契约

  1. basicAuth throws an Error when neither username/password nor verifyUser is configured
  2. basicAuth middleware authorizes requests matching static username and password
  3. basicAuth middleware rejects unauthorized or missing credentials with 401 and WWW-Authenticate header
  4. basicAuth middleware supports multiple static user credential pairs
  5. basicAuth middleware supports custom verifyUser predicate and onAuthSuccess callback
  6. 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

下载源代码构件 (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 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.
csx.json
{"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"}
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",
      "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"
      }
    }
  }
}
package.json
{
  "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"
  }
}
spec.json
{
  "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"
  ]
}
src/index.mjs
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 };
test/contract.mjs
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.');

原始种子者

匿名