CodeSampleX

샘플

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

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. 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.');

오리진 시더

익명