CodeSampleX

示例

hono 4.13.1: bearerAuth

已验证示例 — npm hono 4.13.1: bearerAuth. contract 在 node 22 · linux debian/x64 · docker 上运行并通过: createApp configures Hono application with bearerAuth middleware…

sha256:815bce08ae322c9c73cc42120fd82c63238d695e099da69024302e3ecb69223f

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 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);
});

原始种子者

匿名