Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

checkpoint: File edit:

rUv9309826fffe2
diff --git a/v3/@claude-flow/shared/src/index.ts b/v3/@claude-flow/shared/src/index.ts
index 44d739412a..03832d9721 100644
--- a/v3/@claude-flow/shared/src/index.ts
+++ b/v3/@claude-flow/shared/src/index.ts
@@ -26,3 +26,6 @@ export * from './core/index.js';
// Hooks System - Extensible hook points for tool execution and lifecycle events
export * from './hooks/index.js';
+
+// Security Utilities - Secure random generation, input validation
+export * from './security/index.js';
diff --git a/v3/@claude-flow/shared/src/security/index.ts b/v3/@claude-flow/shared/src/security/index.ts
new file mode 100644
index 0000000000..f3161fa14f
--- /dev/null
+++ b/v3/@claude-flow/shared/src/security/index.ts
@@ -0,0 +1,39 @@
+/**
+ * Security Module
+ *
+ * Shared security utilities for V3 Claude Flow.
+ *
+ * @module v3/shared/security
+ */
+
+// Secure random generation
+export {
+ generateSecureId,
+ generateUUID,
+ generateSecureToken,
+ generateShortId,
+ generateSessionId,
+ generateAgentId,
+ generateTaskId,
+ generateMemoryId,
+ generateEventId,
+ generateSwarmId,
+ generatePatternId,
+ generateTrajectoryId,
+ secureRandomInt,
+ secureRandomChoice,
+ secureShuffleArray,
+} from './secure-random.js';
+
+// Input validation
+export {
+ validateInput,
+ sanitizeString,
+ validatePath,
+ validateCommand,
+ validateTags,
+ isValidIdentifier,
+ escapeForSql,
+ type ValidationResult,
+ type ValidationOptions,
+} from './input-validation.js';
diff --git a/v3/@claude-flow/shared/src/security/input-validation.ts b/v3/@claude-flow/shared/src/security/input-validation.ts
new file mode 100644
index 0000000000..eae2e9a930
--- /dev/null
+++ b/v3/@claude-flow/shared/src/security/input-validation.ts
@@ -0,0 +1,265 @@
+/**
+ * Input Validation Utilities
+ *
+ * Secure input validation and sanitization.
+ *
+ * @module v3/shared/security/input-validation
+ */
+
+/**
+ * Validation result
+ */
+export interface ValidationResult {
+ valid: boolean;
+ error?: string;
+ sanitized?: unknown;
+}
+
+/**
+ * Validation options
+ */
+export interface ValidationOptions {
+ maxLength?: number;
+ minLength?: number;
+ pattern?: RegExp;
+ allowedChars?: RegExp;
+ required?: boolean;
+ trim?: boolean;
+}
+
+/**
+ * Default validation options
+ */
+const DEFAULT_OPTIONS: ValidationOptions = {
+ maxLength: 10000,
+ minLength: 0,
+ required: false,
+ trim: true,
+};
+
+/**
+ * Validate and sanitize string input
+ * @param input Input string
+ * @param options Validation options
+ * @returns Validation result
+ */
+export function validateInput(
+ input: unknown,
+ options: ValidationOptions = {}
+): ValidationResult {
+ const opts = { ...DEFAULT_OPTIONS, ...options };
+
+ // Check if input exists
+ if (input === null || input === undefined) {
+ if (opts.required) {
+ return { valid: false, error: 'Input is required' };
+ }
+ return { valid: true, sanitized: null };
+ }
+
+ // Convert to string
+ if (typeof input !== 'string') {
+ return { valid: false, error: 'Input must be a string' };
+ }
+
+ let sanitized = input;
+
+ // Trim whitespace
+ if (opts.trim) {
+ sanitized = sanitized.trim();
+ }
+
+ // Check length
+ if (opts.minLength && sanitized.length < opts.minLength) {
+ return {
+ valid: false,
+ error: `Input must be at least ${opts.minLength} characters`,
+ };
+ }
+
+ if (opts.maxLength && sanitized.length > opts.maxLength) {
+ return {
+ valid: false,
+ error: `Input must be at most ${opts.maxLength} characters`,
+ };
+ }
+
+ // Check pattern
+ if (opts.pattern && !opts.pattern.test(sanitized)) {
+ return { valid: false, error: 'Input does not match required pattern' };
+ }
+
+ // Check allowed characters
+ if (opts.allowedChars && !opts.allowedChars.test(sanitized)) {
+ return { valid: false, error: 'Input contains invalid characters' };
+ }
+
+ return { valid: true, sanitized };
+}
+
+/**
+ * Sanitize string by removing dangerous characters
+ * @param input Input string
+ * @returns Sanitized string
+ */
+export function sanitizeString(input: string): string {
+ return input
+ .replace(/[<>]/g, '') // Remove HTML tags
+ .replace(/[\x00-\x1f\x7f]/g, '') // Remove control characters
+ .replace(/[\u2028\u2029]/g, '') // Remove line/paragraph separators
+ .trim();
+}
+
+/**
+ * Validate file path (prevent path traversal)
+ * @param path File path
+ * @param allowedBase Allowed base directory
+ * @returns Validation result
+ */
+export function validatePath(
+ path: string,
+ allowedBase?: string
+): ValidationResult {
+ // Normalize and check for path traversal
+ const normalized = path
+ .replace(/\\/g, '/') // Normalize Windows paths
+ .replace(/\/+/g, '/'); // Remove duplicate slashes
+
+ // Check for dangerous patterns
+ if (normalized.includes('..') || normalized.includes('~')) {
+ return {
+ valid: false,
+ error: 'Path contains directory traversal characters',
+ };
+ }
+
+ // Check for absolute paths outside allowed base
+ if (allowedBase && !normalized.startsWith(allowedBase)) {
+ const isAbsolute = normalized.startsWith('/') || /^[a-zA-Z]:/.test(normalized);
+ if (isAbsolute) {
+ return { valid: false, error: 'Path is outside allowed directory' };
+ }
+ }
+
+ // Check for null bytes
+ if (normalized.includes('\0')) {
+ return { valid: false, error: 'Path contains null bytes' };
+ }
+
+ // Check length
+ if (normalized.length > 4096) {
+ return { valid: false, error: 'Path is too long' };
+ }
+
+ return { valid: true, sanitized: normalized };
+}
+
+/**
+ * Validate command (prevent command injection)
+ * @param command Command string
+ * @param allowedCommands Optional whitelist of allowed commands
+ * @returns Validation result
+ */
+export function validateCommand(
+ command: string,
+ allowedCommands?: string[]
+): ValidationResult {
+ // Extract base command
+ const parts = command.trim().split(/\s+/);
+ const baseCommand = parts[0]?.toLowerCase();
+
+ if (!baseCommand) {
+ return { valid: false, error: 'Empty command' };
+ }
+
+ // Check whitelist if provided
+ if (allowedCommands && !allowedCommands.includes(baseCommand)) {
+ return { valid: false, error: `Command '${baseCommand}' is not allowed` };
+ }
+
+ // Check for dangerous shell characters
+ const dangerousPatterns = [
+ /[;&|`$]/, // Shell operators
+ /\$\(/, // Command substitution
+ /`.*`/, // Backtick substitution
+ /\|\|/, // OR operator
+ /&&/, // AND operator
+ />\s*>/, // Append redirection
+ /<\s*</, // Here document
+ /\r|\n/, // Newlines (command chaining)
+ ];
+
+ for (const pattern of dangerousPatterns) {
+ if (pattern.test(command)) {
+ return { valid: false, error: 'Command contains dangerous characters' };
+ }
+ }
+
+ return { valid: true, sanitized: command };
+}
+
+/**
+ * Validate tags for safe SQL usage
+ * @param tags Array of tag strings
+ * @returns Validation result with sanitized tags
+ */
+export function validateTags(tags: unknown): ValidationResult {
+ if (!Array.isArray(tags)) {
+ return { valid: false, error: 'Tags must be an array' };
+ }
+
+ const sanitized: string[] = [];
+ const tagPattern = /^[a-zA-Z0-9_\-.:]+$/;
+
+ for (const tag of tags) {
+ if (typeof tag !== 'string') {
+ return { valid: false, error: 'Each tag must be a string' };
+ }
+
+ const trimmed = tag.trim();
+
+ if (trimmed.length === 0) {
+ continue; // Skip empty tags
+ }
+
+ if (trimmed.length > 100) {
+ return { valid: false, error: 'Tag is too long (max 100 characters)' };
+ }
+
+ if (!tagPattern.test(trimmed)) {
+ return {
+ valid: false,
+ error: `Invalid tag: '${trimmed}'. Tags can only contain alphanumeric characters, underscores, hyphens, dots, and colons`,
+ };
+ }
+
+ sanitized.push(trimmed);
+ }
+
+ return { valid: true, sanitized };
+}
+
+/**
+ * Check if string is a valid identifier
+ * @param id Identifier string
+ * @returns True if valid
+ */
+export function isValidIdentifier(id: string): boolean {
+ return /^[a-zA-Z_][a-zA-Z0-9_\-]*$/.test(id) && id.length <= 256;
+}
+
+/**
+ * Escape string for safe SQL usage (use parameterized queries instead when possible)
+ * This is a LAST RESORT - always prefer parameterized queries
+ * @param value String to escape
+ * @returns Escaped string
+ */
+export function escapeForSql(value: string): string {
+ return value
+ .replace(/'/g, "''") // Escape single quotes
+ .replace(/\\/g, '\\\\') // Escape backslashes
+ .replace(/\x00/g, '') // Remove null bytes
+ .replace(/\n/g, '\\n') // Escape newlines
+ .replace(/\r/g, '\\r') // Escape carriage returns
+ .replace(/\x1a/g, '\\Z'); // Escape ctrl+Z (EOF in Windows)
+}
diff --git a/v3/@claude-flow/shared/src/security/secure-random.ts b/v3/@claude-flow/shared/src/security/secure-random.ts
new file mode 100644
index 0000000000..56c4b3410f
--- /dev/null
+++ b/v3/@claude-flow/shared/src/security/secure-random.ts
@@ -0,0 +1,159 @@
+/**
+ * Secure Random Utilities
+ *
+ * Cryptographically secure random ID and token generation.
+ * Replaces Math.random() for security-sensitive operations.
+ *
+ * @module v3/shared/security/secure-random
+ */
+
+import { randomBytes, randomUUID } from 'crypto';
+
+/**
+ * Generate a cryptographically secure random ID
+ * @param prefix Optional prefix for the ID
+ * @param length Number of random bytes (default 12)
+ * @returns Secure random ID string
+ */
+export function generateSecureId(prefix?: string, length: number = 12): string {
+ const timestamp = Date.now().toString(36);
+ const randomPart = randomBytes(length).toString('hex');
+ return prefix ? `${prefix}_${timestamp}_${randomPart}` : `${timestamp}_${randomPart}`;
+}
+
+/**
+ * Generate a UUID v4 (cryptographically secure)
+ * @returns UUID string
+ */
+export function generateUUID(): string {
+ return randomUUID();
+}
+
+/**
+ * Generate a secure token for authentication
+ * @param length Number of bytes (default 32)
+ * @returns Hex-encoded token string
+ */
+export function generateSecureToken(length: number = 32): string {
+ return randomBytes(length).toString('hex');
+}
+
+/**
+ * Generate a short secure ID (for display purposes)
+ * @param prefix Optional prefix
+ * @returns Short secure ID
+ */
+export function generateShortId(prefix?: string): string {
+ const id = randomBytes(6).toString('base64url');
+ return prefix ? `${prefix}-${id}` : id;
+}
+
+/**
+ * Generate a secure session ID
+ * @returns Session ID string
+ */
+export function generateSessionId(): string {
+ return generateSecureId('session', 16);
+}
+
+/**
+ * Generate a secure agent ID
+ * @returns Agent ID string
+ */
+export function generateAgentId(): string {
+ return generateSecureId('agent', 12);
+}
+
+/**
+ * Generate a secure task ID
+ * @returns Task ID string
+ */
+export function generateTaskId(): string {
+ return generateSecureId('task', 12);
+}
+
+/**
+ * Generate a secure memory ID
+ * @returns Memory ID string
+ */
+export function generateMemoryId(): string {
+ return generateSecureId('mem', 12);
+}
+
+/**
+ * Generate a secure event ID
+ * @returns Event ID string
+ */
+export function generateEventId(): string {
+ return generateSecureId('evt', 12);
+}
+
+/**
+ * Generate a secure swarm ID
+ * @returns Swarm ID string
+ */
+export function generateSwarmId(): string {
+ return generateSecureId('swarm', 12);
+}
+
+/**
+ * Generate a secure pattern ID
+ * @returns Pattern ID string
+ */
+export function generatePatternId(): string {
+ return generateSecureId('pat', 12);
+}
+
+/**
+ * Generate a secure trajectory ID
+ * @returns Trajectory ID string
+ */
+export function generateTrajectoryId(): string {
+ return generateSecureId('traj', 12);
+}
+
+/**
+ * Generate a random integer in range [min, max] using crypto
+ * @param min Minimum value (inclusive)
+ * @param max Maximum value (inclusive)
+ * @returns Cryptographically random integer
+ */
+export function secureRandomInt(min: number, max: number): number {
+ const range = max - min + 1;
+ const bytesNeeded = Math.ceil(Math.log2(range) / 8);
+ const maxValid = Math.pow(256, bytesNeeded) - (Math.pow(256, bytesNeeded) % range);
+
+ let randomValue: number;
+ do {
+ const bytes = randomBytes(bytesNeeded);
+ randomValue = bytes.reduce((acc, byte, i) => acc + byte * Math.pow(256, i), 0);
+ } while (randomValue >= maxValid);
+
+ return min + (randomValue % range);
+}
+
+/**
+ * Secure random selection from array
+ * @param array Array to select from
+ * @returns Random element
+ */
+export function secureRandomChoice<T>(array: T[]): T {
+ if (array.length === 0) {
+ throw new Error('Cannot select from empty array');
+ }
+ return array[secureRandomInt(0, array.length - 1)]!;
+}
+
+/**
+ * Secure shuffle array (Fisher-Yates with crypto)
+ * @param array Array to shuffle
+ * @returns New shuffled array
+ */
+export function secureShuffleArray<T>(array: T[]): T[] {
+ const result = [...array];
+ for (let i = result.length - 1; i > 0; i--) {
+ const j = secureRandomInt(0, i);
+ [result[i], result[j]] = [result[j]!, result[i]!];
+ }
+ return result;
+}