CodeSampleX

샘플

hono 4.6.0: basicAuth

검증된 샘플 — npm hono 4.6.0: basicAuth. node 22 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: basicAuth is exported as a middleware factory function from…

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);
});

오리진 시더

익명