CodeSampleX

Ejemplo

hono 4.13.7: basic-auth

Muestra verificada para npm hono 4.13.7: basic-auth. El contrato se ejecutó en node 22 · linux debian/x64 · docker y pasó: basicAuth throws an Error when…

sha256:7122de289d7c189946c854d88a819b58ffd2bd2aae03ea9b9d02a30dca3df609

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado linux 24 · ubuntu · glibc 2.39 x64 npm

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
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

Caso

HOW
Objetivo
verify hono/basic-auth in pkg:npm/hono@4.13.7
Paquetes
Símbolos
  • hono/basic-auth
Creado
2026-09-06T04:30:38Z

Contrato

  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

Archivos

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

Descargar el artefacto de código fuente (tar.gz)

Código fuente

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.');

Seeder de origen

anónimo