CodeSampleX

샘플

hono 4.6.0: bearerAuth

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

sha256:3250a98c16d794ee17df02aa23c4c8c3be119071899a209cdcb190e67a1b341f

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

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

검증 실행 환경

환경 컨트랙트 단계 실행일
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 pkg:npm/hono@4.6.0
패키지
심벌
  • bearerAuth
환경
node 22.23.2
생성일
2026-09-05T07:35:51Z

컨트랙트

  1. bearerAuth is exported as a middleware factory function from hono/bearer-auth
  2. bearerAuth throws an Error when initialized without token or verifyToken options
  3. bearerAuth middleware allows authorized requests with valid Bearer token and passes to route handler
  4. bearerAuth middleware rejects requests missing Authorization header with status 401 and WWW-Authenticate header
  5. bearerAuth middleware rejects requests with malformed Authorization header with status 400 and invalid_request error
  6. bearerAuth middleware rejects requests with incorrect Bearer token with status 401 and invalid_token error
  7. bearerAuth middleware supports dynamic credential validation using custom verifyToken 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 pkg:npm/hono@4.6.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/hono@4.6.0
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

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:51b5aeb930a6451ae0b4105a10744d2b88e7c9a14baac5de11ab6f11d552b7fb","constraints":{"executionContext":"node"},"contract":["bearerAuth is exported as a middleware factory function from hono/bearer-auth","bearerAuth throws an Error when initialized without token or verifyToken options","bearerAuth middleware allows authorized requests with valid Bearer token and passes to route handler","bearerAuth middleware rejects requests missing Authorization header with status 401 and WWW-Authenticate header","bearerAuth middleware rejects requests with malformed Authorization header with status 400 and invalid_request error","bearerAuth middleware rejects requests with incorrect Bearer token with status 401 and invalid_token error","bearerAuth middleware supports dynamic credential validation using custom verifyToken callback"],"goal":"verify pkg:npm/hono@4.6.0","kind":"HOW","packages":["pkg:npm/hono@4.6.0"],"schemaVersion":1,"symbols":["bearerAuth"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/hono@4.6.0"],"schemaVersion":1,"subject":"pkg:npm/hono@4.6.0","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.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-bearer-auth",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room code sample for bearerAuth in hono@4.6.0",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "hono": "4.6.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/hono@4.6.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/hono@4.6.0"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
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. Static token protected route
  app.use(
    '/api/*',
    bearerAuth({
      token: 'static-secret-token',
      realm: 'API Area'
    })
  );

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

  // 2. Dynamic token verification callback route
  app.use(
    '/custom/*',
    bearerAuth({
      verifyToken: async (token, c) => {
        return token === 'dynamic-valid-token';
      }
    })
  );

  app.get('/custom/profile', (c) => {
    return c.json({ user: 'authenticated-user' });
  });

  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() {
  // 1. bearerAuth is exported as a middleware factory function from hono/bearer-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 bearerAuth, 'function', 'bearerAuth is exported as a middleware factory function from hono/bearer-auth');

  // 2. bearerAuth throws an Error when initialized without token or verifyToken options
  assert.throws(
    () => {
      bearerAuth({});
    },
    {
      name: 'Error',
      message: 'bearer auth middleware requires options for "token"',
    }
  );

  const app = createApp();

  // 3. bearerAuth middleware allows authorized requests with valid Bearer token and passes to route handler
  const validRes = await app.fetch(
    new Request('http://localhost/api/data', {
      headers: {
        Authorization: 'Bearer static-secret-token'
      }
    })
  );
  assert.equal(validRes.status, 200, 'valid token must return status 200');
  const validBody = await validRes.json();
  assert.deepEqual(validBody, { status: 'ok', access: 'granted' });

  // 4. bearerAuth middleware rejects requests missing Authorization header with status 401 and WWW-Authenticate header
  const missingHeaderRes = await app.fetch(new Request('http://localhost/api/data'));
  assert.equal(missingHeaderRes.status, 401, 'missing authorization header must return 401');
  const missingAuthHeader = missingHeaderRes.headers.get('www-authenticate');
  assert.ok(missingAuthHeader && missingAuthHeader.includes('Bearer'), 'must include Bearer scheme in WWW-Authenticate header');
  assert.ok(missingAuthHeader.includes('realm="API Area"'), 'must include configured realm in WWW-Authenticate header');
  assert.equal(await missingHeaderRes.text(), 'Unauthorized');

  // 5. bearerAuth middleware rejects requests with malformed Authorization header with status 400 and invalid_request error
  const malformedRes = await app.fetch(
    new Request('http://localhost/api/data', {
      headers: {
        Authorization: 'InvalidFormatToken'
      }
    })
  );
  assert.equal(malformedRes.status, 400, 'malformed header must return 400');
  const malformedAuthHeader = malformedRes.headers.get('www-authenticate');
  assert.ok(malformedAuthHeader && malformedAuthHeader.includes('error="invalid_request"'), 'must include invalid_request in WWW-Authenticate header');
  assert.equal(await malformedRes.text(), 'Bad Request');

  // 6. bearerAuth middleware rejects requests with incorrect Bearer token with status 401 and invalid_token error
  const wrongTokenRes = await app.fetch(
    new Request('http://localhost/api/data', {
      headers: {
        Authorization: 'Bearer wrong-secret-token'
      }
    })
  );
  assert.equal(wrongTokenRes.status, 401, 'incorrect token must return 401');
  const wrongAuthHeader = wrongTokenRes.headers.get('www-authenticate');
  assert.ok(wrongAuthHeader && wrongAuthHeader.includes('error="invalid_token"'), 'must include invalid_token in WWW-Authenticate header');
  assert.equal(await wrongTokenRes.text(), 'Unauthorized');

  // 7. bearerAuth middleware supports dynamic credential validation using custom verifyToken callback
  const dynamicValidRes = await app.fetch(
    new Request('http://localhost/custom/profile', {
      headers: {
        Authorization: 'Bearer dynamic-valid-token'
      }
    })
  );
  assert.equal(dynamicValidRes.status, 200, 'dynamic valid token must return 200');
  const dynamicBody = await dynamicValidRes.json();
  assert.deepEqual(dynamicBody, { user: 'authenticated-user' });

  const dynamicInvalidRes = await app.fetch(
    new Request('http://localhost/custom/profile', {
      headers: {
        Authorization: 'Bearer invalid-token'
      }
    })
  );
  assert.equal(dynamicInvalidRes.status, 401, 'dynamic invalid token must return 401');
  const dynamicAuthHeader = dynamicInvalidRes.headers.get('www-authenticate');
  assert.ok(dynamicAuthHeader && dynamicAuthHeader.includes('error="invalid_token"'), 'must include invalid_token in WWW-Authenticate header');

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

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

오리진 시더

익명