Files
ruflo/v3/@claude-flow/shared
e7299de48c fix(security): daily scan 2026-11-18 — 2 fixes (#5032)
* fix(security): vulnerable zod pin in claude-flow umbrella

The zod 4 migration (#5021) describes bumping the root claude-flow
package from zod 3.25.76 to 4.6.7, but the root package.json and
package-lock.json still pin 3.25.76, which is affected by
GHSA-mrhx-c7xc-m3w5 (memory exhaustion while validating oversized
constrained collections, high). The umbrella ships the cli and shared
dist, which resolve zod from the umbrella's own dependency, so this pin
is what claude-flow users get, and it also leaves the migrated zod 4
code running against zod 3.

Pin zod 4.6.7 (matching every @claude-flow/* leaf) and update the
lockfile. npm deduped the nested zod 4 copies onto the hoisted one and
synced the stale @claude-flow/shared workspace version (3.0.8 -> 3.0.9)
in the lockfile. Remaining zod 3 copies come only from agentic-flow and
the published plugin-gastown-bridge.

Test: tests/root-zod-advisory-pin.test.mjs fails on main, passes here.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01MfPHVLCpRTZEbZUYnwDgWy

* fix(security): missing auth on /ws in shared MCP HTTP transport

@claude-flow/shared ships its own HttpTransport (exported via MCPServer
and createTransport). #4962 hardened the @claude-flow/mcp copy, but the
shared copy still accepted every /ws upgrade when token auth was
enabled, and nothing after the upgrade checked a token. Token auth is
the setting that lets the transport bind beyond loopback, so that
configuration exposed every registered MCP tool over /ws without
credentials. The HTTP check also accepted any bearer token when the
token list was empty or unset, and compared tokens in non-constant time.

- verifyClient authenticates the upgrade when auth is enabled
  (Authorization: Bearer, or ?token= for browsers, parsed against a
  fixed base URL; never throws).
- Token matching fails closed on an empty list, skips unset entries,
  and compares SHA-256 digests with timingSafeEqual, no early exit.

Test: shared/__tests__/mcp/http-transport-ws-upgrade-auth.test.ts
(2 of 4 cases fail on main, all pass here).

shared is a non-bundled leaf: it needs a standalone publish to reach
direct consumers.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01MfPHVLCpRTZEbZUYnwDgWy

* fix(security): keep legacy v3/mcp tools compiling on zod 4

Follow-up to the root zod 4.6.7 pin: zod 4 removed the single-argument
z.record(value) form, so the 17 call sites in v3/mcp/tools added type
errors to the root tsc build. Use z.record(z.string(), z.unknown()),
the same rewrite #5021 applied to the @claude-flow packages. The root
build error set is now identical to origin/main.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01MfPHVLCpRTZEbZUYnwDgWy

* chore(shared): 3.0.10 for the /ws auth fix; CLI pins it

The shared transport fix is publishable source in a non-bundled leaf, so
the leaf-package-publish gate requires a version bump. Bump shared to
3.0.10 and the CLI's exact pin (pnpm lock specifier only; it stays a
workspace link).

Not done here, because it needs the published tarball: the root
claude-flow pin and package-lock.json entry stay at 3.0.9 until
@claude-flow/shared@3.0.10 is on npm (the lockfile needs its integrity
hash). Until then audit-leaf-versions-published and
audit-wrapper-dep-ranges report the unpublished pin, as designed.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01MfPHVLCpRTZEbZUYnwDgWy

* fix(security): claude-flow umbrella pins @claude-flow/shared 3.0.10

shared 3.0.10 (the /ws auth fix) is now published; the umbrella's exact
range must include it or audit-wrapper-dep-ranges fails and npx installs
resolve two shared copies.

Co-Authored-By: RuFlo <ruv@ruv.net>

---------

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: r <r@x>
2026-11-18 23:51:47 -05:00
..
2026-01-04 20:24:17 +00:00

@claude-flow/shared

Animated diagram: raw config is validated by Zod schemas into typed config that flows through the EventBus to other packages

@claude-flow/shared — Shared types, Zod config schemas and validators, the event bus and resilience helpers that the other @claude-flow packages build on.

Supported environments: Node.js 20+ · ESM · Linux, macOS, Windows (pure JavaScript)

Quickstart

npm install @claude-flow/shared
import { validateAgentConfig } from '@claude-flow/shared';

const ok = validateAgentConfig({ id: 'coder-1', name: 'Coder', type: 'coder' });
console.log(ok.success, ok.data.maxConcurrentTasks, ok.data.priority);

const bad = validateAgentConfig({ id: 'coder-1', name: 'Coder', type: 'coder', priority: 500 });
console.log(bad.success, bad.errors.map((e) => `${e.path}: ${e.code}`).join(', '));

Expected output:

true 5 50
false priority: too_big

Next: @claude-flow/hooks builds its lifecycle hooks on these types.

npm version npm downloads License: MIT TypeScript Core

Shared utilities, types, and core infrastructure for Claude Flow V3 - the foundation module used by all other @claude-flow packages.

Features

  • Core Types - Agent, Task, Memory, MCP, and Swarm type definitions
  • Core Interfaces - Agent, Task, Memory, Event, and Coordinator interfaces
  • Configuration - Schema validation, loading, and default values
  • Event System - Event bus, coordinator, and handler utilities
  • Hooks System - Pre/post execution hooks for extensibility
  • MCP Infrastructure - Server, transport, connection pool, and tool registry
  • Health Monitoring - Health checks and monitoring utilities

Installation

npm install @claude-flow/shared

Quick Start

import {
  AgentState,
  TaskDefinition,
  MemoryEntry,
  EventBus,
  ConfigLoader
} from '@claude-flow/shared';

// Use shared types
const agent: AgentState = {
  id: { id: 'agent-1', swarmId: 'swarm-1', type: 'coder' },
  name: 'Code Agent',
  type: 'coder',
  status: 'idle'
};

// Use configuration
const config = await ConfigLoader.load('./config.json');

// Use event system
const eventBus = new EventBus();
eventBus.on('task.completed', (event) => {
  console.log(`Task ${event.taskId} completed`);
});

Package Exports

// Main entry (recommended - includes all modules)
import { ... } from '@claude-flow/shared';

// Submodule exports (for tree-shaking or specific imports)
import { ... } from '@claude-flow/shared/types';      // Type definitions
import { ... } from '@claude-flow/shared/core';       // Config, interfaces, orchestrator
import { ... } from '@claude-flow/shared/events';     // Event sourcing (ADR-007)
import { ... } from '@claude-flow/shared/hooks';      // Hooks system
import { ... } from '@claude-flow/shared/mcp';        // MCP server infrastructure
import { ... } from '@claude-flow/shared/security';   // Security utilities
import { ... } from '@claude-flow/shared/resilience'; // Retry, circuit breaker, rate limiter

API Reference

Types

import type {
  // Agent types
  AgentId,
  AgentState,
  AgentType,
  AgentStatus,
  AgentCapabilities,
  AgentMetrics,

  // Task types
  TaskId,
  TaskDefinition,
  TaskType,
  TaskStatus,
  TaskPriority,

  // Memory types
  MemoryEntry,
  MemoryType,
  SearchResult,

  // Swarm types
  SwarmId,
  SwarmStatus,
  SwarmEvent,
  CoordinatorConfig,

  // MCP types
  MCPTool,
  MCPRequest,
  MCPResponse
} from '@claude-flow/shared/types';

Core Interfaces

import type {
  IAgent,
  ITask,
  IMemory,
  ICoordinator,
  IEventHandler
} from '@claude-flow/shared/core';

// Agent interface
interface IAgent {
  getId(): AgentId;
  getState(): AgentState;
  execute(task: TaskDefinition): Promise<TaskResult>;
  handleMessage(message: Message): Promise<void>;
}

// Memory interface
interface IMemory {
  store(entry: MemoryEntry): Promise<string>;
  retrieve(id: string): Promise<MemoryEntry | null>;
  search(query: SearchQuery): Promise<SearchResult[]>;
  delete(id: string): Promise<boolean>;
}

// Coordinator interface
interface ICoordinator {
  initialize(): Promise<void>;
  shutdown(): Promise<void>;
  registerAgent(agent: IAgent): Promise<string>;
  submitTask(task: TaskDefinition): Promise<string>;
}

Configuration

import {
  ConfigLoader,
  ConfigValidator,
  defaultConfig,
  ConfigSchema
} from '@claude-flow/shared/core';

// Load configuration
const config = await ConfigLoader.load('./config.json');
const config2 = await ConfigLoader.loadFromEnv();

// Validate configuration
const errors = ConfigValidator.validate(config);
if (errors.length > 0) {
  console.error('Invalid config:', errors);
}

// Default configuration
const defaults = defaultConfig();

Event System

import { EventBus, EventCoordinator } from '@claude-flow/shared/events';

const eventBus = new EventBus();

// Subscribe to events
eventBus.on('agent.joined', (event) => {
  console.log(`Agent ${event.agentId} joined`);
});

eventBus.on('task.*', (event) => {
  console.log(`Task event: ${event.type}`);
});

// Emit events
eventBus.emit({
  type: 'task.completed',
  taskId: 'task-1',
  result: { success: true }
});

// Event coordinator for complex workflows
const coordinator = new EventCoordinator();
coordinator.orchestrate([
  { event: 'step1.done', handler: () => startStep2() },
  { event: 'step2.done', handler: () => startStep3() }
]);

Hooks System

import { HooksManager, Hook } from '@claude-flow/shared/hooks';

const hooks = new HooksManager();

// Register pre-execution hook
hooks.register('pre:task', async (context) => {
  console.log(`Starting task: ${context.taskId}`);
  return { ...context, startTime: Date.now() };
});

// Register post-execution hook
hooks.register('post:task', async (context, result) => {
  const duration = Date.now() - context.startTime;
  console.log(`Task completed in ${duration}ms`);
});

// Execute with hooks
const result = await hooks.execute('task', context, async (ctx) => {
  return await runTask(ctx);
});

MCP Infrastructure

import {
  createMCPServer,
  createToolRegistry,
  createConnectionPool,
  createSessionManager,
  defineTool,
  quickStart,
} from '@claude-flow/shared/mcp';

// Quick start - simplest way to create an MCP server
const server = await quickStart({
  transport: 'stdio',
  name: 'My MCP Server',
});

// Tool registry
const registry = createToolRegistry();
registry.register(defineTool({
  name: 'swarm_init',
  description: 'Initialize a swarm',
  inputSchema: { type: 'object', properties: { topology: { type: 'string' } } },
  handler: async (params) => ({ result: 'initialized' }),
}));

// Connection pool
const pool = createConnectionPool({
  maxConnections: 10,
  acquireTimeoutMs: 30000,
});

// Session manager
const sessions = createSessionManager({ timeoutMs: 3600000 });
const session = await sessions.create({ clientInfo: { name: 'client' } });

Health Monitor

import { HealthMonitor, HealthCheck } from '@claude-flow/shared/core';

const monitor = new HealthMonitor();

// Register health checks
monitor.register('database', async () => {
  const connected = await db.ping();
  return { healthy: connected, latency: pingTime };
});

monitor.register('memory', async () => {
  const usage = process.memoryUsage();
  return { healthy: usage.heapUsed < MAX_HEAP, usage };
});

// Run health checks
const report = await monitor.check();
// { overall: 'healthy', checks: { database: {...}, memory: {...} } }

TypeScript Types

All types are fully exported and documented:

// Re-export all types
export * from './types/agent.types';
export * from './types/task.types';
export * from './types/memory.types';
export * from './types/swarm.types';
export * from './types/mcp.types';

Dependencies

  • sql.js - SQLite WASM for cross-platform persistence

Used By

This package is a dependency of all other @claude-flow modules:

License

MIT


Built by rUv · ruv.io · Source