From 3252b2dcae01f3e90f1ef3ff92e48fd7f8da88b3 Mon Sep 17 00:00:00 2001 From: r Date: Mon, 9 Nov 2026 02:49:40 -0500 Subject: [PATCH] fix(shared): zod ^4.6.7 (GHSA-mrhx-c7xc-m3w5), express floor; shared 3.0.8 zod < 4.6.6 can exhaust memory validating oversized constrained collections (GHSA-mrhx-c7xc-m3w5, high); there is no 3.x fix. @claude-flow/shared is the most-installed zod 3 holdout (~286k downloads/month, a dependency of the cli, hooks, claims, guidance, testing, deployment and the iot/federation plugins). - config validator: ZodError.errors -> .issues; foreign ZodErrors are recognised by shape; z.ZodType (port from #4535 by Dragan Spiridonov) - schema: one-argument z.record(value) -> z.record(z.string(), value) - express ^4.22.2 || ^5.0.0 -> ^4.22.3 || ^5.1.0: 4.22.2 and 5.0.0-5.0.1 are inside GHSA-qw6h-vgh9-j6wx - advisory-ranges test over the manifest (zod, express, ws) - ADR-356 metadata (homepage, repository with directory, bugs, keywords) and a README quickstart verified against a packed tarball, with a flow SVG shared is a registry-resolved leaf of @claude-flow/cli, so this PR also needs the cli pin ("@claude-flow/shared": "3.0.8") and the claude-flow root pin from the release lane, after 3.0.8 is on the registry. Co-authored-by: Dragan Spiridonov Co-Authored-By: claude-flow --- v3/@claude-flow/shared/README.md | 39 ++++++++ .../shared/__tests__/advisory-ranges.test.ts | 70 ++++++++++++++ .../__tests__/zod4-config-validator.test.ts | 91 +++++++++++++++++++ v3/@claude-flow/shared/assets/shared-flow.svg | 22 +++++ v3/@claude-flow/shared/package.json | 29 +++++- .../shared/src/core/config/schema.ts | 8 +- .../shared/src/core/config/validator.ts | 33 +++++-- v3/pnpm-lock.yaml | 44 ++++----- 8 files changed, 296 insertions(+), 40 deletions(-) create mode 100644 v3/@claude-flow/shared/__tests__/advisory-ranges.test.ts create mode 100644 v3/@claude-flow/shared/__tests__/zod4-config-validator.test.ts create mode 100644 v3/@claude-flow/shared/assets/shared-flow.svg diff --git a/v3/@claude-flow/shared/README.md b/v3/@claude-flow/shared/README.md index 0b5cae844c..b613ceaa0e 100644 --- a/v3/@claude-flow/shared/README.md +++ b/v3/@claude-flow/shared/README.md @@ -1,5 +1,38 @@ # @claude-flow/shared + +![Animated diagram: raw config is validated by Zod schemas into typed config that flows through the EventBus to other packages](https://raw.githubusercontent.com/ruvnet/ruflo/main/v3/@claude-flow/shared/assets/shared-flow.svg) + +**@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 + +```bash +npm install @claude-flow/shared +``` + +```js +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: + +```text +true 5 50 +false priority: too_big +``` + +Next: [`@claude-flow/hooks`](https://www.npmjs.com/package/@claude-flow/hooks) builds its lifecycle hooks on these types. + + [![npm version](https://img.shields.io/npm/v/@claude-flow/shared.svg)](https://www.npmjs.com/package/@claude-flow/shared) [![npm downloads](https://img.shields.io/npm/dm/@claude-flow/shared.svg)](https://www.npmjs.com/package/@claude-flow/shared) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) @@ -321,3 +354,9 @@ This package is a dependency of all other @claude-flow modules: ## License MIT + + +--- + +Built by [rUv](https://ruv.io) · [ruv.io](https://ruv.io) · [Source](https://github.com/ruvnet/ruflo/tree/main/v3/@claude-flow/shared) + diff --git a/v3/@claude-flow/shared/__tests__/advisory-ranges.test.ts b/v3/@claude-flow/shared/__tests__/advisory-ranges.test.ts new file mode 100644 index 0000000000..11061c832d --- /dev/null +++ b/v3/@claude-flow/shared/__tests__/advisory-ranges.test.ts @@ -0,0 +1,70 @@ +/** + * Regression guard: the published dependency ranges must not admit versions + * with known advisories. Each row is (field, package, versions that must be + * rejected, versions that must be admitted). + * + * Ranges are restricted to `^X.Y.Z` alternatives joined by `||`, so the check + * below is exact without pulling semver into the package. + */ + +import { readFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { describe, it, expect } from 'vitest'; + +const here = dirname(fileURLToPath(import.meta.url)); +const manifest = JSON.parse(readFileSync(join(here, '..', 'package.json'), 'utf8')) as Record< + string, + Record | undefined +>; + +type Version = { major: number; minor: number; patch: number; pre: boolean }; + +function parse(v: string): Version { + const m = /^(\d+)\.(\d+)\.(\d+)(-.+)?$/.exec(v); + if (!m) throw new Error(`not a version: ${v}`); + return { major: +m[1], minor: +m[2], patch: +m[3], pre: m[4] !== undefined }; +} + +function cmp(a: Version, b: Version): number { + return a.major - b.major || a.minor - b.minor || a.patch - b.patch; +} + +/** Caret semantics for X >= 1: same major, >= floor, no prereleases. */ +function satisfies(version: string, range: string): boolean { + const v = parse(version); + return range.split('||').some((part) => { + const m = /^\s*\^(\d+\.\d+\.\d+)\s*$/.exec(part); + if (!m) throw new Error(`unsupported range form: ${part.trim()}`); + const floor = parse(m[1]); + return !v.pre && v.major === floor.major && floor.major >= 1 && cmp(v, floor) >= 0; + }); +} + +const rows: Array<[field: string, name: string, advisory: string, rejected: string[], admitted: string[]]> = [ + ['dependencies', 'zod', 'GHSA-mrhx-c7xc-m3w5', ['3.22.4', '3.25.76', '4.6.5'], ['4.6.7']], + ['dependencies', 'express', 'GHSA-qw6h-vgh9-j6wx', ['4.22.2', '5.0.1'], ['4.22.3', '5.1.0', '5.3.0']], + ['dependencies', 'ws', 'GHSA-96hv-2xvq-fx4p', ['8.20.1'], ['8.21.0']], +]; + +describe('advisory-free dependency ranges', () => { + for (const [field, name, advisory, rejected, admitted] of rows) { + const range = manifest[field]?.[name]; + + it(`${field}.${name} is declared`, () => { + expect(range).toBeTypeOf('string'); + }); + + for (const v of rejected) { + it(`${field}.${name} rejects ${v} (${advisory})`, () => { + expect(satisfies(v, range!)).toBe(false); + }); + } + + for (const v of admitted) { + it(`${field}.${name} admits ${v}`, () => { + expect(satisfies(v, range!)).toBe(true); + }); + } + } +}); diff --git a/v3/@claude-flow/shared/__tests__/zod4-config-validator.test.ts b/v3/@claude-flow/shared/__tests__/zod4-config-validator.test.ts new file mode 100644 index 0000000000..0413c65f3e --- /dev/null +++ b/v3/@claude-flow/shared/__tests__/zod4-config-validator.test.ts @@ -0,0 +1,91 @@ +/** + * Config validation under zod 4. + * + * zod 4 removed `ZodError.errors` (use `.issues`). The validator mapped + * `error.errors`, so every invalid config threw a TypeError out of the + * validator instead of returning `{ success: false, errors }`. + */ + +import { describe, it, expect } from 'vitest'; +import { + validateAgentConfig, + validateSwarmConfig, + ConfigValidator, +} from '../src/core/config/validator.js'; +import { AgentConfigSchema } from '../src/core/config/schema.js'; + +describe('config validator under zod 4', () => { + it('returns structured errors for an invalid agent config', () => { + const result = validateAgentConfig({ id: '', name: 'x' }); + expect(result.success).toBe(false); + expect(result.errors?.length).toBeGreaterThan(0); + const paths = result.errors?.map((e) => e.path) ?? []; + expect(paths).toContain('id'); + expect(paths).toContain('type'); + for (const e of result.errors ?? []) { + expect(typeof e.message).toBe('string'); + expect(typeof e.code).toBe('string'); + } + }); + + it('returns structured errors for an invalid swarm topology', () => { + const result = validateSwarmConfig({ topology: 'not-a-topology' }); + expect(result.success).toBe(false); + expect(result.errors?.[0]?.path).toBe('topology'); + }); + + it('still applies defaults on a valid agent config', () => { + const result = validateAgentConfig({ id: 'a1', name: 'A', type: 'coder' }); + expect(result.success).toBe(true); + expect(result.data).toMatchObject({ + capabilities: [], + maxConcurrentTasks: 5, + priority: 50, + }); + }); + + it('treats a ZodError from another zod copy as a validation failure', () => { + // A caller-supplied schema built with a different zod (e.g. zod 3) throws + // a ZodError that is not an instance of this package's z.ZodError. + const foreign = { + parse() { + throw Object.assign(new Error('foreign'), { + name: 'ZodError', + issues: [{ path: ['x'], message: 'Expected string', code: 'invalid_type' }], + }); + }, + }; + expect(ConfigValidator.isValid(foreign as never, 42)).toBe(false); + }); + + it('does not mistake an operational error named ZodError for a validation failure', () => { + const impostor = { + parse() { + throw Object.assign(new Error('database failed'), { name: 'ZodError', issues: [] }); + }, + }; + expect(() => ConfigValidator.isValid(impostor as never, {})).toThrow('database failed'); + }); + + it('reports symbol path segments instead of throwing', () => { + const sym = Symbol('meta'); + const foreign = { + parse() { + throw Object.assign(new Error('foreign'), { + name: 'ZodError', + issues: [{ path: ['metadata', sym], message: 'bad key', code: 'invalid_key' }], + }); + }, + }; + expect(() => ConfigValidator.validateOrThrow(foreign as never, {}, 'agent')).toThrow( + /- metadata\.Symbol\(meta\): bad key/, + ); + }); + + it('validateAgentOrThrow reports the invalid fields, not a TypeError', () => { + expect(AgentConfigSchema.safeParse({}).success).toBe(false); + expect(() => ConfigValidator.validateAgentOrThrow({ id: '' })).toThrow( + /Invalid agent configuration:\n {2}- id: /, + ); + }); +}); diff --git a/v3/@claude-flow/shared/assets/shared-flow.svg b/v3/@claude-flow/shared/assets/shared-flow.svg new file mode 100644 index 0000000000..1ebd042bfb --- /dev/null +++ b/v3/@claude-flow/shared/assets/shared-flow.svg @@ -0,0 +1,22 @@ + +@claude-flow/shared: validated config to typed events +Raw configuration is checked by Zod schemas in ConfigValidator, becomes typed config, and flows through the EventBus and EventStore to the other @claude-flow packages. + + +@claude-flow/shared: validated config to typed events + +Raw configJSON / objectZod schemasConfigValidatorTyped configdefaults appliedEventBusEventStoreConsumershooks, plugins, cli + + diff --git a/v3/@claude-flow/shared/package.json b/v3/@claude-flow/shared/package.json index ba795d5f9d..b8c53a570e 100644 --- a/v3/@claude-flow/shared/package.json +++ b/v3/@claude-flow/shared/package.json @@ -1,8 +1,8 @@ { "name": "@claude-flow/shared", - "version": "3.0.7", + "version": "3.0.8", "type": "module", - "description": "Shared module - common types, events, utilities, core interfaces", + "description": "Shared types, event bus, config schemas and validators, MCP transport helpers and resilience utilities used by the Ruflo (claude-flow) V3 packages.", "main": "dist/index.js", "types": "dist/index.d.ts", "exports": { @@ -30,11 +30,11 @@ "dependencies": { "@types/ws": "^8.5.10", "cors": "^2.8.5", - "express": "^4.22.2 || ^5.0.0", + "express": "^4.22.3 || ^5.1.0", "helmet": "^7.2.0", "sql.js": "^1.10.3", "ws": "^8.21.0", - "zod": "^3.22.4" + "zod": "^4.6.7" }, "devDependencies": { "@types/cors": "^2.8.17", @@ -45,5 +45,26 @@ }, "publishConfig": { "access": "public" + }, + "keywords": [ + "ruflo", + "claude-flow", + "shared", + "types", + "event-bus", + "config-validation", + "zod", + "mcp", + "resilience", + "typescript" + ], + "homepage": "https://ruv.io", + "repository": { + "type": "git", + "url": "git+https://github.com/ruvnet/ruflo.git", + "directory": "v3/@claude-flow/shared" + }, + "bugs": { + "url": "https://github.com/ruvnet/ruflo/issues" } } diff --git a/v3/@claude-flow/shared/src/core/config/schema.ts b/v3/@claude-flow/shared/src/core/config/schema.ts index 1c281f945d..06131914f9 100644 --- a/v3/@claude-flow/shared/src/core/config/schema.ts +++ b/v3/@claude-flow/shared/src/core/config/schema.ts @@ -25,7 +25,7 @@ export const AgentConfigSchema = z.object({ maxMemoryMb: z.number().int().positive().optional(), maxCpuPercent: z.number().min(0).max(100).optional(), }).optional(), - metadata: z.record(z.unknown()).optional(), + metadata: z.record(z.string(), z.unknown()).optional(), }); /** @@ -37,7 +37,7 @@ export const TaskConfigSchema = z.object({ priority: z.number().int().min(0).max(100).default(50), timeout: z.number().int().positive().optional(), assignedAgent: z.string().optional(), - input: z.record(z.unknown()).optional(), + input: z.record(z.string(), z.unknown()).optional(), metadata: z.object({ requiredCapabilities: z.array(z.string()).optional(), retryCount: z.number().int().min(0).optional(), @@ -75,7 +75,7 @@ export const SwarmConfigSchema = z.object({ batchSize: z.number().int().positive().default(10), flushIntervalMs: z.number().int().positive().default(100), }).optional(), - metadata: z.record(z.unknown()).optional(), + metadata: z.record(z.string(), z.unknown()).optional(), }); /** @@ -127,7 +127,7 @@ export const MCPServerConfigSchema = z.object({ resources: z.boolean().default(true), prompts: z.boolean().default(true), logging: z.boolean().default(true), - experimental: z.record(z.boolean()).optional(), + experimental: z.record(z.string(), z.boolean()).optional(), }).optional(), }); diff --git a/v3/@claude-flow/shared/src/core/config/validator.ts b/v3/@claude-flow/shared/src/core/config/validator.ts index 134b82f57d..60b154b468 100644 --- a/v3/@claude-flow/shared/src/core/config/validator.ts +++ b/v3/@claude-flow/shared/src/core/config/validator.ts @@ -42,20 +42,37 @@ export interface ValidationError { /** * Convert Zod error to validation errors */ -function zodErrorToValidationErrors(error: ZodError): ValidationError[] { - return error.errors.map((e) => ({ - path: e.path.join('.'), +function zodErrorToValidationErrors(error: Pick): ValidationError[] { + return error.issues.map((e) => ({ + path: e.path.map(String).join('.'), message: e.message, code: e.code, })); } +function isZodErrorLike(error: unknown): error is Pick { + if (!(error instanceof Error) || error.name !== 'ZodError') return false; + const issues = (error as { issues?: unknown }).issues; + return ( + Array.isArray(issues) && + issues.length > 0 && + issues.every( + (i) => + i !== null && + typeof i === 'object' && + Array.isArray((i as { path?: unknown }).path) && + typeof (i as { message?: unknown }).message === 'string' && + typeof (i as { code?: unknown }).code === 'string', + ) + ); +} + /** * Generic validation function * Uses parse + try/catch to get output types with defaults applied */ function validate( - schema: z.ZodType, + schema: z.ZodType, data: unknown ): ValidationResult { try { @@ -65,7 +82,9 @@ function validate( data: parsed, }; } catch (error) { - if (error instanceof z.ZodError) { + // Callers may pass a schema built with another zod copy (e.g. zod 3), + // whose ZodError is not an instance of this one. Match on shape. + if (error instanceof z.ZodError || isZodErrorLike(error)) { return { success: false, errors: zodErrorToValidationErrors(error), @@ -132,7 +151,7 @@ export class ConfigValidator { * Validate and throw on error */ static validateOrThrow( - schema: z.ZodType, + schema: z.ZodType, data: unknown, configName: string ): TOutput { @@ -201,7 +220,7 @@ export class ConfigValidator { * Check if data matches schema */ static isValid( - schema: z.ZodType, + schema: z.ZodType, data: unknown ): boolean { return validate(schema, data).success; diff --git a/v3/pnpm-lock.yaml b/v3/pnpm-lock.yaml index f445cf880b..9686fc6969 100644 --- a/v3/pnpm-lock.yaml +++ b/v3/pnpm-lock.yaml @@ -137,7 +137,7 @@ importers: version: link:../security '@claude-flow/shared': specifier: 3.0.7 - version: link:../shared + version: 3.0.7 '@electron/asar': specifier: ^4.3.1 version: 4.3.1 @@ -658,8 +658,8 @@ importers: specifier: ^8.21.0 version: 8.21.1 zod: - specifier: ^3.22.4 - version: 3.25.76 + specifier: ^4.6.7 + version: 4.6.7 devDependencies: '@types/cors': specifier: ^2.8.17 @@ -955,6 +955,22 @@ packages: resolution: {integrity: sha512-k7vvKPbf7J2fZ5klGRD9AeKfUvojuZIQ3BT5u7Jfv+puwXkUBUT5PVyMDfJZpy30CBDXGMgw7fguK/lpOMBvgw==} requiresBuild: true + /@claude-flow/shared@3.0.7: + resolution: {integrity: sha512-eX/JdzywhVFxL+BQaMOphPBVL95icFJgf3piNzTyGy2nT8zFqdDQ34qpS+RfFv3Yjpo00NDj/4CzoqRTni7ImA==} + dependencies: + '@types/ws': 8.18.1 + cors: 2.8.6 + express: 5.2.1 + helmet: 7.2.0 + sql.js: 1.14.1 + ws: 8.21.1 + zod: 3.25.76 + transitivePeerDependencies: + - bufferutil + - supports-color + - utf-8-validate + dev: false + /@cognitum-one/sdk@0.2.1(multicast-dns@7.2.5): resolution: {integrity: sha512-ZIYKq6Tqc7zcDQRSrxphm0Uji497Mf1bi7azn2aTM4F0k+IEdPpTmAngGVaXX/hR7DYhOQ5gkUCja0DiOJLOJw==} engines: {node: '>=18'} @@ -6175,8 +6191,6 @@ packages: peerDependencies: typescript: '>=5.0.0' peerDependenciesMeta: - agentic-flow: - optional: true typescript: optional: true dependencies: @@ -10442,34 +10456,14 @@ packages: '@ruvector/ruvllm': ^4.1.0 rvlite: ^0.2.0 peerDependenciesMeta: - '@metaharness/darwin': - optional: true - '@metaharness/flywheel': - optional: true - '@metaharness/harness': - optional: true - '@metaharness/redblue': - optional: true - '@metaharness/router': - optional: true - '@metaharness/weight-eft': - optional: true - '@metaharness/workspace-lens': - optional: true - '@metaharness/workspace-probe': - optional: true '@ruvector/diskann': optional: true '@ruvector/pi-brain': optional: true - '@ruvector/rabitq-wasm': - optional: true '@ruvector/router': optional: true '@ruvector/ruvllm': optional: true - metaharness: - optional: true rvlite: optional: true dependencies: