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<Out, In> (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 <spiridonovdragan@gmail.com>
Co-Authored-By: claude-flow <ruv@ruv.net>
This commit is contained in:
committed 2026-11-09 02:49:40 -05:00
1 parent ef6ae01c26
commit 3252b2dcae
8 files changed
+296 -40

No files matched your search

+39
View File
@@ -1,5 +1,38 @@
# @claude-flow/shared
<!-- adr-356:quickstart:start -->
![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.
<!-- adr-356:quickstart:end -->
[![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
<!-- adr-356:footer:start -->
---
Built by [rUv](https://ruv.io) · [ruv.io](https://ruv.io) · [Source](https://github.com/ruvnet/ruflo/tree/main/v3/@claude-flow/shared)
<!-- adr-356:footer:end -->
@@ -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<string, string> | 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);
});
}
}
});
@@ -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: /,
);
});
});
@@ -0,0 +1,22 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 760 170" width="760" height="170" role="img" aria-labelledby="t d">
<title id="t">@claude-flow/shared: validated config to typed events</title>
<desc id="d">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.</desc>
<style>
.bg{fill:#1e293b}
.cap{fill:#e2e8f0;font:600 15px system-ui,-apple-system,Segoe UI,sans-serif}
.s rect{fill:#334155;stroke:#64748b;stroke-width:1.5}
.s{animation:pulse 6s infinite}
.h{fill:#f8fafc;font:600 13px system-ui,-apple-system,Segoe UI,sans-serif;text-anchor:middle}
.t{fill:#cbd5e1;font:11px system-ui,-apple-system,Segoe UI,sans-serif;text-anchor:middle}
.a{fill:none;stroke:#94a3b8;stroke-width:2}
.dot{fill:#38bdf8;animation:move 6s linear infinite}
@keyframes pulse{0%,20.0%{opacity:1}28.0%,100%{opacity:.62}}
@keyframes move{from{transform:translateX(0)}to{transform:translateX(600px)}}
@media (prefers-reduced-motion:reduce){.s,.dot{animation:none}}
</style>
<rect class="bg" width="760" height="170" rx="14"/>
<text class="cap" x="20" y="34">@claude-flow/shared: validated config to typed events</text>
<path class="a" d="M147 90h14m-5 -4l5 4l-5 4"/><path class="a" d="M297 90h14m-5 -4l5 4l-5 4"/><path class="a" d="M447 90h14m-5 -4l5 4l-5 4"/><path class="a" d="M597 90h14m-5 -4l5 4l-5 4"/>
<g class="s" style="animation-delay:0.0s"><rect x="16" y="58" width="128" height="64" rx="10"/><text class="h" x="80" y="85">Raw config</text><text class="t" x="80" y="104">JSON / object</text></g><g class="s" style="animation-delay:1.2s"><rect x="166" y="58" width="128" height="64" rx="10"/><text class="h" x="230" y="85">Zod schemas</text><text class="t" x="230" y="104">ConfigValidator</text></g><g class="s" style="animation-delay:2.4s"><rect x="316" y="58" width="128" height="64" rx="10"/><text class="h" x="380" y="85">Typed config</text><text class="t" x="380" y="104">defaults applied</text></g><g class="s" style="animation-delay:3.6s"><rect x="466" y="58" width="128" height="64" rx="10"/><text class="h" x="530" y="85">EventBus</text><text class="t" x="530" y="104">EventStore</text></g><g class="s" style="animation-delay:4.8s"><rect x="616" y="58" width="128" height="64" rx="10"/><text class="h" x="680" y="85">Consumers</text><text class="t" x="680" y="104">hooks, plugins, cli</text></g>
<circle class="dot" cx="80" cy="140" r="5"/>
</svg>

After

Width:  |  Height:  |  Size: 2.4 KiB

+25 -4
View File
@@ -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"
}
}
@@ -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(),
});
@@ -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<ZodError, 'issues'>): 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<ZodError, 'issues'> {
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<TInput, TOutput>(
schema: z.ZodType<TOutput, z.ZodTypeDef, TInput>,
schema: z.ZodType<TOutput, TInput>,
data: unknown
): ValidationResult<TOutput> {
try {
@@ -65,7 +82,9 @@ function validate<TInput, TOutput>(
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<TInput, TOutput>(
schema: z.ZodType<TOutput, z.ZodTypeDef, TInput>,
schema: z.ZodType<TOutput, TInput>,
data: unknown,
configName: string
): TOutput {
@@ -201,7 +220,7 @@ export class ConfigValidator {
* Check if data matches schema
*/
static isValid<TInput, TOutput>(
schema: z.ZodType<TOutput, z.ZodTypeDef, TInput>,
schema: z.ZodType<TOutput, TInput>,
data: unknown
): boolean {
return validate(schema, data).success;
+19 -25
View File
@@ -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: