🌊 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
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
fix(memory): one validator for namespaces and keys across store, import, export and purge (#3570 follow-up)
ruvb1811363ec99
diff --git a/v3/@claude-flow/cli/__tests__/memory-store-import-namespace-3570.test.ts b/v3/@claude-flow/cli/__tests__/memory-store-import-namespace-3570.test.tsindex 2ba7944b8e..24bdce8e4f 100644--- a/v3/@claude-flow/cli/__tests__/memory-store-import-namespace-3570.test.ts+++ b/v3/@claude-flow/cli/__tests__/memory-store-import-namespace-3570.test.ts@@ -93,3 +93,92 @@ describe('namespace path-traversal validation on write paths (#3570)', () => {expect(mocks.storeEntry).toHaveBeenCalledTimes(2);});});++// ---------------------------------------------------------------------------+// Follow-up: close the remaining #3570 gaps. One validator (`validateIdentifier`)+// now governs namespaces on store (CLI + MCP), import, export and purge, and the+// MCP key rule (`DANGEROUS_KEY_PATTERN`) is shared with the CLI and import paths.+// ---------------------------------------------------------------------------+import * as initializer from '../src/memory/memory-initializer.js';++const mcpStoreTool = memoryTools.find(t => t.name === 'memory_store')!;+type Real = typeof import('../src/memory/memory-initializer.js');+const realPurge = async (namespace: string) => {+ const { purgeNamespace } = await vi.importActual<Real>('../src/memory/memory-initializer.js');+ // A namespace that passes validation may still fail later on the scratch+ // database; only a namespace error counts as a rejection.+ try { return await purgeNamespace({ namespace, dbPath: join(tempDir, 'purge.db') }); }+ catch (e) { return { success: false, error: String(e) }; }+};+const isNamespaceRejection = (msg?: string) => /namespace/i.test(msg ?? '');+const cliStore = async (flags: Record<string, unknown>) =>+ (await storeCommand.action!({ args: [], flags: { value: 'v', ...flags } } as any))?.success === true;+const mcpStore = async (args: Record<string, unknown>) => {+ try { const r: any = await mcpStoreTool.handler({ value: 'v', ...args }); return r?.success !== false; }+ catch { return false; }+};+const exportAccepts = async (namespace: string) => {+ vi.mocked(initializer.listEntries).mockResolvedValue({ success: true, entries: [], total: 0 } as any);+ try { await exportTool.handler({ outputPath: join(tempDir, 'rt.json'), namespace }); return true; }+ catch (e) { if (/namespace/.test(String(e))) return false; throw e; }+};+const purgeAccepts = async (namespace: string) => !isNamespaceRejection((await realPurge(namespace)).error);++describe('#3570 follow-up (a): keys use the shared MCP key rule on every write path', () => {+ it('CLI memory store rejects a key containing ../ and writes nothing', async () => {+ expect(await cliStore({ key: '../../escape', namespace: 'ok' })).toBe(false);+ expect(mocks.storeEntry).not.toHaveBeenCalled();+ });++ it('memory import rejects an entry whose key contains ../ and writes nothing', async () => {+ const inputPath = writeImport('bad-key.json', [+ { key: 'fine', namespace: 'project', value: 'one' },+ { key: '../../escape', namespace: 'project', value: 'two' },+ ]);+ await expect(importTool.handler({ inputPath })).rejects.toThrow(/Key contains disallowed characters/);+ expect(mocks.storeEntry).not.toHaveBeenCalled();+ });++ it('keys containing a plain / stay legal on CLI store, MCP store and import', async () => {+ expect(await cliStore({ key: 'probe/x', namespace: 'ok' })).toBe(true);+ expect(await mcpStore({ key: 'probe/x', namespace: 'ok' })).toBe(true);+ const inputPath = writeImport('slash-key.json', [{ key: 'probe/x', namespace: 'ok', value: 'v' }]);+ expect(((await importTool.handler({ inputPath })) as any).imported.entries).toBe(1);+ });+});++describe('#3570 follow-up (b): purge uses the same namespace validator', () => {+ it('purge accepts team:alice, which store and export already accept', async () => {+ expect(await purgeAccepts('team:alice')).toBe(true);+ });++ it('purge still rejects traversal and slash namespaces', async () => {+ expect(isNamespaceRejection((await realPurge('../../..')).error)).toBe(true);+ expect(isNamespaceRejection((await realPurge('proj/sub')).error)).toBe(true);+ });+});++describe('#3570 follow-up (c): MCP memory_store namespaces use the same validator', () => {+ it('MCP memory_store rejects proj/sub and writes nothing', async () => {+ expect(await mcpStore({ key: 'k', namespace: 'proj/sub' })).toBe(false);+ expect(mocks.storeEntry).not.toHaveBeenCalled();+ });++ it('MCP memory_store still accepts team:alice', async () => {+ expect(await mcpStore({ key: 'k', namespace: 'team:alice' })).toBe(true);+ });+});++describe('#3570 round trip: a namespace store accepts can always be exported and purged', () => {+ const candidates = [+ 'default', 'project-a', 'team:alice', 'a.b', 'ns_1:2.3', 'proj/sub', '../../..',+ 'x y', '-lead', '.hidden', 'with$dollar', 'a'.repeat(129),+ ];+ it.each(candidates)('%s: every write path agrees with export and purge', async ns => {+ const cli = await cliStore({ key: 'k', namespace: ns });+ const mcp = await mcpStore({ key: 'k', namespace: ns });+ const exp = await exportAccepts(ns);+ const purge = await purgeAccepts(ns);+ expect({ ns, cli, mcp, purge }).toEqual({ ns, cli: exp, mcp: exp, purge: exp });+ });+});diff --git a/v3/@claude-flow/cli/src/commands/memory.ts b/v3/@claude-flow/cli/src/commands/memory.tsindex c889548df1..a7885346a3 100644--- a/v3/@claude-flow/cli/src/commands/memory.ts+++ b/v3/@claude-flow/cli/src/commands/memory.ts@@ -14,6 +14,7 @@ import { resolveDbPath } from '../memory/memory-initializer.js';import { existsSync } from 'node:fs';import { siblingAgentDbPath } from '../memory/memory-bridge.js';import { validateIdentifier } from '../mcp-tools/validate-input.js';+import { memoryKeyError } from '../mcp-tools/memory-tools.js';/*** #3228: a miss in one store is not a miss in the memory.@@ -201,6 +202,12 @@ const storeCommand: Command = {output.printError(vNs.error!);return { success: false, exitCode: 1 };}+ // #3570 follow-up: the same key rule MCP memory_store enforces.+ const keyError = memoryKeyError(key);+ if (keyError) {+ output.printError(keyError);+ return { success: false, exitCode: 1 };+ }// #2752 MemPoison gate — scan before persist when opted in.// CLI flag ctx.flags.scanContent takes precedence over RUFLO_MEMORY_SCAN_ON_WRITE env vardiff --git a/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/memory-tools.tsindex f7aa32506c..b642acf799 100644--- a/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts@@ -66,7 +66,16 @@ const MAX_QUERY_LENGTH = 4096;// validateMemoryInput. Imported by sanitizeMemoryKey so write-side sanitization// and read-side rejection can never drift apart (the symmetry bug behind #1884).const DANGEROUS_KEY_CHARS = /[;&|`$(){}[\]<>!#\\\0]|\.\.[/\\]/g;-const DANGEROUS_KEY_PATTERN = /[;&|`$(){}[\]<>!#\\\0]|\.\.[/\\]/;+export const DANGEROUS_KEY_PATTERN = /[;&|`$(){}[\]<>!#\\\0]|\.\.[/\\]/;++/**+ * #3570: the one key rule for every memory write path (MCP store, CLI store,+ * import). Plain `/` stays legal (`probe/x`); traversal and shell metacharacters+ * do not. Returns the error message, or null when the key is acceptable.+ */+export function memoryKeyError(key: string): string | null {+ return DANGEROUS_KEY_PATTERN.test(key) ? 'Key contains disallowed characters' : null;+}function validateMemoryInput(key?: string, value?: string, query?: string, namespace?: string): void {if (key && key.length > MAX_KEY_LENGTH) {@@ -79,9 +88,8 @@ function validateMemoryInput(key?: string, value?: string, query?: string, namesthrow new Error(`Query exceeds maximum length of ${MAX_QUERY_LENGTH} characters`);}// Reject path traversal and shell metacharacters in keys/namespaces (#1425)- if (key && DANGEROUS_KEY_PATTERN.test(key)) {- throw new Error('Key contains disallowed characters');- }+ const keyError = key ? memoryKeyError(key) : null;+ if (keyError) throw new Error(keyError);if (namespace && DANGEROUS_KEY_PATTERN.test(namespace)) {throw new Error('Namespace contains disallowed characters');}@@ -491,6 +499,10 @@ export const memoryTools: MCPTool[] = [}validateMemoryInput(key, value, undefined, namespace);+ // #3570: a namespace written here must be exportable and purgeable, so it+ // passes the same validator export and purge use.+ const vNs = validateIdentifier(namespace, 'namespace');+ if (!vNs.valid) throw new Error(vNs.error);const startTime = performance.now();@@ -1620,6 +1632,13 @@ export const memoryTools: MCPTool[] = [}}}+ // #3570 follow-up: keys get the same up-front, all-or-nothing check.+ for (const e of entries) {+ if (e && typeof e.key === 'string') {+ const keyError = memoryKeyError(e.key);+ if (keyError) throw new Error(`${keyError}: ${JSON.stringify(e.key)}`);+ }+ }let imported = 0; let skipped = 0;for (const e of entries) {if (!e || typeof e.key !== 'string') { skipped++; continue; }diff --git a/v3/@claude-flow/cli/src/memory/memory-initializer.ts b/v3/@claude-flow/cli/src/memory/memory-initializer.tsindex 28e76dae5e..a2600fd649 100644--- a/v3/@claude-flow/cli/src/memory/memory-initializer.ts+++ b/v3/@claude-flow/cli/src/memory/memory-initializer.ts@@ -16,6 +16,7 @@ import { AsyncLocalStorage } from 'node:async_hooks';import { createRequire } from 'node:module';import { readFileMaybeEncrypted, writeFileAtomic, writeFileRestricted } from '../fs-secure.js';import { restoreMemoryDbFromBackup } from '../services/memory-backup.js';+import { validateIdentifier } from '../mcp-tools/validate-input.js';/*** ADR-323 — typed memory provenance. Distinguishes WHO/WHAT wrote a memory@@ -3992,8 +3993,6 @@ export async function withMemoryDbLock<T>(dbPath: string, fn: () => Promise<T> |}}-const NAMESPACE_PATTERN = /^[A-Za-z0-9._-]{1,128}$/;-export async function purgeNamespace(options: {namespace: string;dbPath?: string;@@ -4007,8 +4006,11 @@ export async function purgeNamespace(options: {}> {const { namespace, dbPath: customPath } = options;- if (!NAMESPACE_PATTERN.test(namespace)) {- return { success: false, deletedCount: 0, remainingEntries: 0, error: `Invalid namespace: ${namespace}` };+ // #3570: the same validator store, import and export use, so any namespace+ // that can be written can also be purged (`team:alice` included).+ const vNs = validateIdentifier(namespace, 'namespace');+ if (!vNs.valid) {+ return { success: false, deletedCount: 0, remainingEntries: 0, error: `Invalid namespace: ${vNs.error}` };}const swarmDir = getMemoryRoot();