npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@codewheel/mcp-http-security

v1.0.0

Published

Secure HTTP transport for MCP servers with API key authentication, IP/origin allowlisting, and middleware support

Readme

mcp-http-security

Secure HTTP transport for MCP (Model Context Protocol) servers with API key authentication, IP/origin allowlisting, and Express-compatible middleware.

Installation

npm install @codewheel/mcp-http-security

Features

  • API Key Management - Create, validate, and revoke API keys with scopes and TTL
  • Secure Hashing - SHA-256 with pepper for timing-safe secret validation
  • IP Allowlisting - CIDR notation support for IPv4 and IPv6
  • Origin Validation - Hostname validation with wildcard subdomain support
  • Express Middleware - Drop-in security middleware for Express-style apps
  • Pluggable Storage - Memory, file, or custom storage backends
  • Zero Runtime Dependencies - Only Node.js crypto module

Quick Start

Basic Setup with Express

import express from 'express';
import {
  ApiKeyManager,
  MemoryStorage,
  RequestValidator,
  SecurityConfig,
  createSecurityMiddleware,
} from '@codewheel/mcp-http-security';

const app = express();

// Create storage and API key manager
const storage = new MemoryStorage();
const apiKeyManager = new ApiKeyManager(storage, 'your-secret-pepper');

// Create request validator
const requestValidator = new RequestValidator({
  allowedIps: ['127.0.0.1', '192.168.0.0/16'],
  allowedOrigins: ['example.com', '*.example.com'],
});

// Apply security middleware
app.use(createSecurityMiddleware({
  apiKeyManager,
  requestValidator,
  config: new SecurityConfig({
    requireAuth: true,
    allowedScopes: ['read', 'write'],
  }),
}));

// Your routes here
app.get('/api/data', (req, res) => {
  res.json({ message: 'Authenticated!' });
});

Creating API Keys

import { ApiKeyManager, FileStorage } from '@codewheel/mcp-http-security';

const storage = new FileStorage('./api-keys.json');
const manager = new ApiKeyManager(storage, 'your-secret-pepper');

// Create a key with scopes
const { apiKey, metadata } = await manager.createKey({
  label: 'Production API Key',
  scopes: ['read', 'write'],
  ttlSeconds: 86400 * 30, // 30 days
});

console.log('API Key:', apiKey); // mcp.abc123def456.secret...
console.log('Expires:', new Date(metadata.expires! * 1000));

Validating API Keys

try {
  const key = await manager.validate(apiKey);
  console.log('Valid key:', key.label);
  console.log('Scopes:', key.scopes);
  console.log('Has write access:', key.hasScope('write'));
} catch (error) {
  if (error instanceof AuthenticationException) {
    console.log('Invalid or expired key');
  }
}

IP Validation

import { IpValidator } from '@codewheel/mcp-http-security';

const validator = new IpValidator([
  '127.0.0.1',           // Single IP
  '192.168.0.0/16',      // IPv4 CIDR
  '10.0.0.0/8',
  '::1',                  // IPv6 localhost
  '2001:db8::/32',       // IPv6 CIDR
]);

validator.isAllowed('192.168.1.100'); // true
validator.isAllowed('8.8.8.8');       // false

Origin Validation

import { OriginValidator } from '@codewheel/mcp-http-security';

const validator = new OriginValidator([
  'example.com',
  '*.example.com',  // Matches foo.example.com
  'localhost',
]);

validator.isAllowed('example.com');      // true
validator.isAllowed('api.example.com');  // true
validator.isAllowed('other.com');        // false

API Reference

ApiKeyManager

new ApiKeyManager(storage: StorageInterface, pepper: string, options?: {
  clock?: Clock;
  keyPrefix?: string;
})

// Methods
createKey(options: CreateKeyOptions): Promise<CreateKeyResult>
listKeys(): Promise<ApiKeyMetadata[]>
getKey(keyId: string): Promise<ApiKeyMetadata | undefined>
revokeKey(keyId: string): Promise<boolean>
validate(apiKey: string): Promise<ApiKey>

ApiKey

// Properties
keyId: string
label: string
scopes: readonly string[]
created: number
lastUsed?: number
expires?: number

// Methods
hasScope(scope: string): boolean
hasAnyScope(scopes: string[]): boolean
hasAllScopes(scopes: string[]): boolean
isExpired(currentTime?: number): boolean
toMetadata(): ApiKeyMetadata

RequestValidator

new RequestValidator(options?: {
  allowedIps?: string[];
  allowedOrigins?: string[];
  ipValidator?: IpValidator;
  originValidator?: OriginValidator;
})

// Methods
validate(request: ValidatableRequest): void  // throws ValidationException
isValid(request: ValidatableRequest): boolean
getClientIp(request: ValidatableRequest): string | null
getRequestHostname(request: ValidatableRequest): string | null

SecurityConfig

new SecurityConfig(options?: {
  requireAuth?: boolean;       // default: true
  allowedScopes?: string[];    // default: []
  authHeader?: string;         // default: "Authorization"
  apiKeyHeader?: string;       // default: "X-MCP-Api-Key"
  scopesAttribute?: string;    // default: "mcp.scopes"
  keyAttribute?: string;       // default: "mcp.key"
  silentFail?: boolean;        // default: false
})

Storage Backends

// In-memory (for testing)
new MemoryStorage()

// File-based (JSON)
new FileStorage(filePath: string)

// Custom storage: implement StorageInterface
interface StorageInterface {
  getAll(): Promise<Map<string, ApiKeyData>>;
  setAll(keys: Map<string, ApiKeyData>): Promise<void>;
  get(keyId: string): Promise<ApiKeyData | undefined>;
  set(keyId: string, data: ApiKeyData): Promise<void>;
  delete(keyId: string): Promise<boolean>;
}

Exceptions

SecurityException        // base class, HTTP 403
AuthenticationException  // HTTP 401
AuthorizationException   // HTTP 403, includes requiredScopes/actualScopes
ValidationException      // HTTP 404
RateLimitException       // HTTP 429, includes retryAfterSeconds

Cross-Language Support

This package is part of the MCP security ecosystem:

| Language | Package | |----------|---------| | TypeScript | @codewheel/mcp-http-security | | PHP | code-wheel/mcp-http-security |

All packages maintain API parity for consistent security handling across your stack.

License

MIT