CodeSampleX

Пример

hono 4.6.0: basicAuth

Проверенный пример — npm hono 4.6.0: basicAuth. Контракт выполнен на node 22 · linux debian/x64 · docker и пройден: basicAuth is exported as a middleware…

sha256:c79902bb9716dc2f828438d5b170d5400746d849e0192948d2bc9d9cf9e85ba3

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. 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);
});

Исходный сидер

аноним