CodeSampleX

Exemple

hono 4.13.1: bearerAuth

Échantillon vérifié pour npm hono 4.13.1: bearerAuth. Le contrat s'est exécuté sur node 22 · linux debian/x64 · docker et a réussi.

sha256:815bce08ae322c9c73cc42120fd82c63238d695e099da69024302e3ecb69223f

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
1
Clés de signature qui l’ont compilé
1
Environnement déclaré linux 24 · ubuntu · glibc 2.39 x64 npm

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
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

Cas

HOW
Objectif
verify bearerAuth in pkg:npm/hono@4.13.1
Paquets
Symboles
  • bearerAuth
Créé
2026-09-01T20:20:21Z

Contrat

  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

Fichiers

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

Télécharger l’artefact source (tar.gz)

Code source

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);
});

Seeder d'origine

anonyme