@claude-flow/security

中文文档
3.0.7发布于 2026/11/09TypeScriptES Module近 30 天下载 20.1万

Security module - CVE fixes, input validation, path security

原始使用文档
文档目录19 节
  1. Features
  2. Installation
  3. Standalone use (without the Ruflo CLI)
  4. Recipe — Validate input, hash a password, generate an API k…
  5. Recipe — Refuse command injection + path traversal
  6. Quick Start
  7. API Reference
  8. Password Hashing (CVE-2 Fix)
  9. Credential Generation (CVE-3 Fix)
  10. Safe Command Execution (HIGH-1 Fix)
  11. Path Validation (HIGH-2 Fix)
  12. Input Validation
  13. Token Generation
  14. Security Constants
  15. Security Audit
  16. Validation Schemas
  17. Dependencies
  18. Related Packages
  19. License

@claude-flow/security

npm version npm downloads License: MIT TypeScript Security Audit

Comprehensive security module for Claude Flow V3 - CVE fixes, input validation, path security, and secure credential management.

Features

  • CVE Remediation - Fixes for CVE-2 (Weak Password Hashing), CVE-3 (Hardcoded Credentials), HIGH-1 (Command Injection), HIGH-2 (Path Traversal)
  • Password Hashing - Secure bcrypt-based password hashing with configurable rounds (12+ recommended)
  • Credential Generation - Cryptographically secure credential and API key generation
  • Safe Command Execution - Allowlist-based command execution preventing injection attacks
  • Path Validation - Protection against path traversal and symlink attacks
  • Input Validation - Zod-based schema validation for all input types
  • Token Generation - Secure token creation with HMAC signing

Installation

npm install @claude-flow/security

Standalone use (without the Ruflo CLI)

This is a plain library — every primitive (PasswordHasher, PathValidator, SafeExecutor, InputValidator, CredentialGenerator) is independently importable. No CLI, no MCP server, no daemon. The primitives close CVE-2 (weak hashing), CVE-3 (default credentials), HIGH-1 (command injection), and HIGH-2 (path traversal) — drop them into any Node app that needs to validate at a system boundary.

Recipe — Validate input, hash a password, generate an API key

// recipe.mjs
import {
  InputValidator,
  EmailSchema,
  PasswordHasher,
  createCredentialGenerator,
} from '@claude-flow/security';

// 1. Validate user input at the boundary (Zod schemas, no surprises)
const email = InputValidator.validate(EmailSchema, '[email protected]');
//             ↳ throws if invalid; returns the typed value otherwise

// 2. Hash a password with bcrypt at the recommended cost (CVE-2)
//    Default policy: ≥8 chars, ≥1 upper, ≥1 lower, ≥1 digit.
//    Tune with new PasswordHasher({ rounds, requireUppercase, ... }).
const hasher = new PasswordHasher({ rounds: 12 });
const hash   = await hasher.hash('CorrectHorseBatteryStaple9');
const ok     = await hasher.verify('CorrectHorseBatteryStaple9', hash); // true

// 3. Generate a high-entropy API key (CVE-3) — uses crypto.randomBytes
//    under the hood and refuses to emit keys below 32 bytes of entropy.
const creds = createCredentialGenerator();
const apiKey = creds.generateApiKey('ck_live_');
console.log(apiKey.keyId, apiKey.key.slice(0, 16) + '…');
// → 7e2b1a9c-…  ck_live_xX9aQ…

Recipe — Refuse command injection + path traversal

import {
  createDevelopmentExecutor,
  createProjectPathValidator,
} from '@claude-flow/security';

// SafeExecutor — only the allow-listed commands ever run (HIGH-1)
const exec = createDevelopmentExecutor({ projectRoot: process.cwd() });
const { stdout } = await exec.execute('git', ['status', '--porcelain']);

// PathValidator — refuses traversal and symlinks out of the project (HIGH-2)
const paths = createProjectPathValidator(process.cwd());
const result = await paths.validate('../../etc/passwd');
if (!result.isValid) console.log('blocked:', result.errors.join('; '));
// → blocked: Path traversal pattern detected

Quick Start

import { createSecurityModule } from '@claude-flow/security';

// Create a complete security module
const security = createSecurityModule({
  projectRoot: '/workspaces/project',
  hmacSecret: process.env.HMAC_SECRET!,
  bcryptRounds: 12,
  allowedCommands: ['git', 'npm', 'node']
});

// Hash a password
const hash = await security.passwordHasher.hash('userPassword123');

// Validate a path
const pathResult = await security.pathValidator.validate('/workspaces/project/src/file.ts');

// Execute command safely
const output = await security.safeExecutor.execute('git', ['status']);

// Generate secure credentials
const creds = await security.credentialGenerator.generate();

API Reference

Password Hashing (CVE-2 Fix)

import { PasswordHasher, createPasswordHasher } from '@claude-flow/security';

const hasher = createPasswordHasher({ rounds: 12 });

// Hash password
const hash = await hasher.hash('password');

// Verify password
const isValid = await hasher.verify('password', hash);

// Check if hash needs rehashing
const needsRehash = hasher.needsRehash(hash);

Credential Generation (CVE-3 Fix)

import { CredentialGenerator, generateCredentials } from '@claude-flow/security';

const generator = new CredentialGenerator();

// Generate API key
const apiKey = await generator.generateApiKey({
  prefix: 'cf',
  length: 32
});

// Generate complete credentials
const creds = generateCredentials({
  includeApiKey: true,
  includeSecret: true
});

Safe Command Execution (HIGH-1 Fix)

import { SafeExecutor, createDevelopmentExecutor } from '@claude-flow/security';

const executor = createDevelopmentExecutor();

// Execute allowed command
const result = await executor.execute('git', ['status']);

// With timeout
const result2 = await executor.execute('npm', ['install'], {
  timeout: 60000,
  cwd: '/workspaces/project'
});

Path Validation (HIGH-2 Fix)

import { PathValidator, createProjectPathValidator } from '@claude-flow/security';

const validator = createProjectPathValidator('/workspaces/project');

// Validate path
const result = await validator.validate('../../../etc/passwd');
// { valid: false, reason: 'Path traversal detected' }

// Safe path
const result2 = await validator.validate('/workspaces/project/src/index.ts');
// { valid: true, normalized: '/workspaces/project/src/index.ts' }

Input Validation

import {
  InputValidator,
  SafeStringSchema,
  EmailSchema,
  PasswordSchema,
  SpawnAgentSchema
} from '@claude-flow/security';

// Validate email
const email = EmailSchema.parse('[email protected]');

// Validate password
const password = PasswordSchema.parse('SecurePass123!');

// Validate agent spawn request
const agentRequest = SpawnAgentSchema.parse({
  type: 'coder',
  name: 'code-agent-1'
});

// Sanitize HTML
import { sanitizeHtml } from '@claude-flow/security';
const safe = sanitizeHtml('<script>alert("xss")</script>Hello');
// 'Hello'

Token Generation

import { TokenGenerator, quickGenerate } from '@claude-flow/security';

const generator = new TokenGenerator({
  hmacSecret: process.env.HMAC_SECRET!
});

// Generate signed token
const token = await generator.generate({
  type: 'session',
  expiresIn: 3600
});

// Verify token
const verified = await generator.verify(token);

// Quick generation
const sessionToken = quickGenerate.sessionToken();
const verificationCode = quickGenerate.verificationCode();

Security Constants

import {
  MIN_BCRYPT_ROUNDS,      // 12
  MAX_BCRYPT_ROUNDS,      // 14
  MIN_PASSWORD_LENGTH,    // 8
  MAX_PASSWORD_LENGTH,    // 72 (bcrypt limit)
  DEFAULT_TOKEN_EXPIRATION,   // 3600 (1 hour)
  DEFAULT_SESSION_EXPIRATION  // 86400 (24 hours)
} from '@claude-flow/security';

Security Audit

import { auditSecurityConfig } from '@claude-flow/security';

const warnings = auditSecurityConfig({
  bcryptRounds: 10,
  hmacSecret: 'short'
});

// ['bcryptRounds (10) below recommended minimum (12)',
//  'hmacSecret should be at least 32 characters']

Validation Schemas

SchemaDescription
SafeStringSchemaBasic safe string with length limits
IdentifierSchemaAlphanumeric identifiers
FilenameSchemaSafe filenames
EmailSchemaEmail addresses
PasswordSchemaSecure passwords
UUIDSchemaUUID v4 format
HttpsUrlSchemaHTTPS URLs only
SemverSchemaSemantic versions
PortSchemaValid port numbers
IPv4SchemaIPv4 addresses
SpawnAgentSchemaAgent spawn requests
TaskInputSchemaTask definitions
SecurityConfigSchemaSecurity configuration

Dependencies

  • bcrypt - Password hashing
  • zod - Schema validation

License

MIT

版本与发布记录

@claude-flow/security 共发布 15 个版本,首次发布于 2026/01/07;过去 12 个月发布了 15 个版本。

版本发布日期距今
3.0.7latest2026/11/09今天
3.0.62026/11/019 天前
3.0.52026/10/1328 天前
3.0.42026/10/1130 天前
3.0.32026/10/091 个月前
3.0.22026/10/081 个月前

其他发布通道:alpha → 3.0.1,v3alpha → 3.0.1。

关于 @claude-flow/security 的常见问题

@claude-flow/security 是什么?

Security module - CVE fixes, input validation, path security

如何安装 @claude-flow/security?

在项目目录运行 npm install @claude-flow/security,或使用 pnpm add / yarn add / bun add。

@claude-flow/security 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@claude-flow/security 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@claude-flow/security 可以商用吗?

@claude-flow/security 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@claude-flow/security 的下载量有多少?

根据 npm 官方下载统计,@claude-flow/security 在 2026/10/10 – 2026/11/08 这 30 天内被下载 200,901 次,日均约 6,697 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@claude-flow/security 还在维护吗?

最新版本 3.0.7 发布于 2026/11/09(今天);至今共发布 15 个版本,其中过去 12 个月发布了 15 个;首次发布于 2026/01/07。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。