CodeSampleX

샘플

hono 4.13.1: bearerAuth

검증된 샘플 — npm hono 4.13.1: bearerAuth. node 22 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: createApp configures Hono application with bearerAuth…

sha256:815bce08ae322c9c73cc42120fd82c63238d695e099da69024302e3ecb69223f

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

케이스

HOW
목표
verify bearerAuth in pkg:npm/hono@4.13.1
패키지
심벌
  • bearerAuth
생성일
2026-09-01T20:20:21Z

컨트랙트

  1. createApp configures Hono application with bearerAuth middleware supporting static token, multi-token whitelist, dynamic validation, custom prefixes, and custom headers
  2. bearerAuth middleware allows access with valid static bearer token and rejects missing, invalid, or malformed Authorization headers
  3. bearerAuth middleware validates requests against an array of allowed static tokens
  4. bearerAuth middleware evaluates custom dynamic token verification callback
  5. bearerAuth middleware supports custom authorization header prefixes
  6. bearerAuth middleware supports custom authentication header names

파일

  • 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 bearerAuth in pkg:npm/hono@4.13.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/hono@4.13.1
Demonstrate these symbols/APIs:
  - bearerAuth

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:6a4b8103f784f52f6ef955300d90170802aa249a8470c03bba4293caffd36268","contract":["createApp configures Hono application with bearerAuth middleware supporting static token, multi-token whitelist, dynamic validation, custom prefixes, and custom headers","bearerAuth middleware allows access with valid static bearer token and rejects missing, invalid, or malformed Authorization headers","bearerAuth middleware validates requests against an array of allowed static tokens","bearerAuth middleware evaluates custom dynamic token verification callback","bearerAuth middleware supports custom authorization header prefixes","bearerAuth middleware supports custom authentication header names"],"goal":"verify bearerAuth in pkg:npm/hono@4.13.1","kind":"HOW","packages":["pkg:npm/hono@4.13.1"],"schemaVersion":1,"symbols":["bearerAuth"]},"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.1"],"schemaVersion":1,"subject":"pkg:npm/hono@4.13.1","symbols":["bearerAuth"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-hono-bearer-auth",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-hono-bearer-auth",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "hono": "4.13.1"
      }
    },
    "node_modules/hono": {
      "version": "4.13.1",
      "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.1.tgz",
      "integrity": "sha512-kdJoFVv2xmayw6cY09H7AbMJMt8Jn5jdlEdXsP7AGBdF2DIptVlKlOLKXP41yPip4/a3yQPv9gVcJYI8YY04dw==",
      "license": "MIT",
      "engines": {
        "node": ">=16.9.0"
      }
    }
  }
}
package.json
{
  "name": "sample-hono-bearer-auth",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room code sample for bearerAuth in hono@4.13.1",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "hono": "4.13.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify bearerAuth in pkg:npm/hono@4.13.1",
  "kind": "HOW",
  "packages": [
    "pkg:npm/hono@4.13.1"
  ],
  "symbols": [
    "bearerAuth"
  ]
}
src/index.js
'use strict';

const { Hono } = require('hono');
const { bearerAuth } = require('hono/bearer-auth');

/**
 * Creates and configures a Hono application with bearerAuth middleware.
 *
 * @returns {Hono}
 */
function createApp() {
  const app = new Hono();

  // 1. Single static token authentication
  const staticToken = 'secret-token-123';
  app.use(
    '/api/protected/*',
    bearerAuth({
      token: staticToken
    })
  );

  app.get('/api/protected/resource', (c) => {
    return c.json({ status: 'ok', data: 'protected content' });
  });

  // 2. Multiple valid tokens authentication
  const allowedTokens = ['admin-token-alpha', 'admin-token-beta'];
  app.use(
    '/api/multi-token/*',
    bearerAuth({
      token: allowedTokens
    })
  );

  app.get('/api/multi-token/data', (c) => {
    return c.json({ status: 'ok', message: 'multi-token access granted' });
  });

  // 3. Custom dynamic token verification function
  app.use(
    '/api/dynamic/*',
    bearerAuth({
      verifyToken: async (token, c) => {
        return token.startsWith('dynamic-valid-');
      }
    })
  );

  app.get('/api/dynamic/profile', (c) => {
    return c.json({ status: 'ok', user: 'verified-dynamic-user' });
  });

  // 4. Custom prefix authentication
  app.use(
    '/api/custom-prefix/*',
    bearerAuth({
      token: 'custom-prefix-token-xyz',
      prefix: 'Token'
    })
  );

  app.get('/api/custom-prefix/status', (c) => {
    return c.json({ status: 'ok', prefix: 'Token' });
  });

  // 5. Custom header name
  app.use(
    '/api/custom-header/*',
    bearerAuth({
      token: 'custom-header-token-456',
      headerName: 'X-API-Key',
      prefix: ''
    })
  );

  app.get('/api/custom-header/info', (c) => {
    return c.json({ status: 'ok', auth: 'custom-header' });
  });

  return app;
}

module.exports = {
  createApp,
  Hono,
  bearerAuth
};
test/contract.mjs
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const {
  createApp,
  Hono,
  bearerAuth
} = require('../src/index.js');

async function testAll() {
  const app = createApp();

  // 1. Export verification
  assert.equal(typeof createApp, 'function', 'createApp must be a function');
  assert.equal(typeof Hono, 'function', 'Hono export must be a function');
  assert.equal(typeof bearerAuth, 'function', 'bearerAuth export must be a function');

  // 2. Single static token authentication
  // Case A: Valid token -> 200 OK
  const validStaticRes = await app.fetch(
    new Request('http://localhost/api/protected/resource', {
      headers: {
        Authorization: 'Bearer secret-token-123'
      }
    })
  );
  assert.equal(validStaticRes.status, 200, 'Valid bearer token must return 200');
  const validStaticData = await validStaticRes.json();
  assert.deepEqual(validStaticData, { status: 'ok', data: 'protected content' });

  // Case B: Missing Authorization header -> 401 Unauthorized
  const missingHeaderRes = await app.fetch(
    new Request('http://localhost/api/protected/resource')
  );
  assert.equal(missingHeaderRes.status, 401, 'Missing Authorization header must return 401');

  // Case C: Invalid token -> 401 Unauthorized
  const invalidTokenRes = await app.fetch(
    new Request('http://localhost/api/protected/resource', {
      headers: {
        Authorization: 'Bearer wrong-token'
      }
    })
  );
  assert.equal(invalidTokenRes.status, 401, 'Invalid token must return 401');

  // Case D: Malformed header (missing prefix) -> 400 Bad Request
  const malformedHeaderRes = await app.fetch(
    new Request('http://localhost/api/protected/resource', {
      headers: {
        Authorization: 'Basic secret-token-123'
      }
    })
  );
  assert.equal(malformedHeaderRes.status, 400, 'Malformed header must return 400');

  // 3. Multiple valid tokens authentication
  // Token 1 in whitelist
  const multiTokenRes1 = await app.fetch(
    new Request('http://localhost/api/multi-token/data', {
      headers: {
        Authorization: 'Bearer admin-token-alpha'
      }
    })
  );
  assert.equal(multiTokenRes1.status, 200, 'First whitelisted token must return 200');

  // Token 2 in whitelist
  const multiTokenRes2 = await app.fetch(
    new Request('http://localhost/api/multi-token/data', {
      headers: {
        Authorization: 'Bearer admin-token-beta'
      }
    })
  );
  assert.equal(multiTokenRes2.status, 200, 'Second whitelisted token must return 200');

  // Unlisted token
  const multiTokenResReject = await app.fetch(
    new Request('http://localhost/api/multi-token/data', {
      headers: {
        Authorization: 'Bearer unlisted-token'
      }
    })
  );
  assert.equal(multiTokenResReject.status, 401, 'Unlisted token must return 401');

  // 4. Custom dynamic token verification function
  const dynamicSuccessRes = await app.fetch(
    new Request('http://localhost/api/dynamic/profile', {
      headers: {
        Authorization: 'Bearer dynamic-valid-12345'
      }
    })
  );
  assert.equal(dynamicSuccessRes.status, 200, 'Dynamic valid token must return 200');
  const dynamicData = await dynamicSuccessRes.json();
  assert.deepEqual(dynamicData, { status: 'ok', user: 'verified-dynamic-user' });

  const dynamicFailRes = await app.fetch(
    new Request('http://localhost/api/dynamic/profile', {
      headers: {
        Authorization: 'Bearer dynamic-invalid-12345'
      }
    })
  );
  assert.equal(dynamicFailRes.status, 401, 'Dynamic invalid token must return 401');

  // 5. Custom prefix authentication
  const customPrefixSuccess = await app.fetch(
    new Request('http://localhost/api/custom-prefix/status', {
      headers: {
        Authorization: 'Token custom-prefix-token-xyz'
      }
    })
  );
  assert.equal(customPrefixSuccess.status, 200, 'Custom prefix token must return 200');

  const customPrefixMismatch = await app.fetch(
    new Request('http://localhost/api/custom-prefix/status', {
      headers: {
        Authorization: 'Bearer custom-prefix-token-xyz'
      }
    })
  );
  assert.equal(customPrefixMismatch.status, 400, 'Mismatched prefix must return 400');

  // 6. Custom header name
  const customHeaderSuccess = await app.fetch(
    new Request('http://localhost/api/custom-header/info', {
      headers: {
        'X-API-Key': 'custom-header-token-456'
      }
    })
  );
  assert.equal(customHeaderSuccess.status, 200, 'Custom header auth must return 200');

  const customHeaderMissing = await app.fetch(
    new Request('http://localhost/api/custom-header/info')
  );
  assert.equal(customHeaderMissing.status, 401, 'Missing custom header must return 401');

  console.log('All bearerAuth contract assertions passed successfully.');
}

testAll().catch((err) => {
  console.error('Contract test failure:', err);
  process.exit(1);
});

오리진 시더

익명