CodeSampleX

Exemple

hono 4.6.0: bearerAuth

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

sha256:3250a98c16d794ee17df02aa23c4c8c3be119071899a209cdcb190e67a1b341f

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é node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

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-05

Cas

HOW
Objectif
verify pkg:npm/hono@4.6.0
Paquets
Symboles
  • bearerAuth
Environnement
node 22.23.2
Créé
2026-09-05T07:35:51Z

Contrat

  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

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

Seeder d'origine

anonyme