🌊 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(security): report "could not scan" instead of a clean tree when npm audit fails (#4124)
martinvladef14b161e16d
diff --git a/v3/@claude-flow/cli/__tests__/security-audit-no-lockfile-4124.test.ts b/v3/@claude-flow/cli/__tests__/security-audit-no-lockfile-4124.test.tsnew file mode 100644index 0000000000..b921533de7--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/security-audit-no-lockfile-4124.test.ts@@ -0,0 +1,70 @@+/**+ * #4124: in a pnpm/yarn/bun project `npm audit --json` prints+ * {"error":{"code":"ENOLOCK",...}} and no `vulnerabilities` key. `security+ * scan` (deps phase) and `security cve` read that as a clean tree and exited+ * 0, so a release check got a false all-clear. They must report "could not+ * scan" instead, and the persisted record must not make the statusline CLEAN.+ */+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { spawnSync } from 'child_process';+import { mkdtempSync, rmSync, writeFileSync, readFileSync } from 'fs';+import { join } from 'path';+import { tmpdir } from 'os';+import { fileURLToPath } from 'url';+import { interpretNpmAudit } from '../src/commands/security.js';+import { getSecurityStatus } from '../src/funnel/local-signals.js';++const CLI_BIN = fileURLToPath(new URL('../bin/cli.js', import.meta.url));+const ENOLOCK = JSON.stringify({ error: { code: 'ENOLOCK', summary: 'This command requires an existing lockfile.' } });++describe('interpretNpmAudit', () => {+ it('treats an npm error object as could-not-scan, with the right package manager hint', () => {+ const dir = mkdtempSync(join(tmpdir(), 'audit-4124-'));+ try {+ writeFileSync(join(dir, 'pnpm-lock.yaml'), 'lockfileVersion: 9.0\n');+ const result = interpretNpmAudit(ENOLOCK, dir);+ expect(result.ok).toBe(false);+ if (!result.ok) {+ expect(result.reason).toContain('ENOLOCK');+ expect(result.reason).toContain('pnpm audit');+ }+ } finally { rmSync(dir, { recursive: true, force: true }); }+ });+ it('rejects output with no vulnerability report and non-JSON output', () => {+ expect(interpretNpmAudit('{}').ok).toBe(false);+ expect(interpretNpmAudit('not json').ok).toBe(false);+ });+ it('accepts a real report, including an empty one', () => {+ expect(interpretNpmAudit(JSON.stringify({ auditReportVersion: 2, vulnerabilities: {}, metadata: {} }))).toEqual({ ok: true, vulnerabilities: {} });+ });+});++describe('security scan / cve on a lockfile-less (pnpm) project', () => {+ let dir: string;+ beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), 'audit-4124-cli-'));+ writeFileSync(join(dir, 'package.json'), JSON.stringify({ name: 'pnpm-fixture', version: '1.0.0' }));+ writeFileSync(join(dir, 'pnpm-lock.yaml'), 'lockfileVersion: 9.0\n');+ });+ afterEach(() => rmSync(dir, { recursive: true, force: true }));++ it('scan --type deps exits non-zero, says the scan did not run, and persists an incomplete record', () => {+ const res = spawnSync(process.execPath, [CLI_BIN, 'security', 'scan', '--target', dir, '--depth', 'quick', '--type', 'deps'], { encoding: 'utf-8', timeout: 60_000 });+ const out = `${res.stdout}${res.stderr}`;+ expect(res.status).not.toBe(0);+ expect(out).toContain('Dependency scan skipped');+ expect(out).toContain('pnpm audit');+ expect(out).not.toContain('No security issues found!');+ const record = JSON.parse(readFileSync(join(dir, '.claude', 'security-scans', 'scan-deps-quick.json'), 'utf-8'));+ expect(record.incomplete).toBe(true);+ expect(getSecurityStatus(dir).status).toBe('PENDING');+ });++ it('cve --list exits non-zero instead of printing "No known vulnerabilities"', () => {+ const res = spawnSync(process.execPath, [CLI_BIN, 'security', 'cve', '--list'], { cwd: dir, encoding: 'utf-8', timeout: 60_000 });+ const out = `${res.stdout}${res.stderr}`;+ expect(res.status).not.toBe(0);+ expect(out).not.toContain('No known vulnerabilities');+ expect(out).toContain('Could not check dependencies');+ });+});diff --git a/v3/@claude-flow/cli/__tests__/security-scan-persistence.test.ts b/v3/@claude-flow/cli/__tests__/security-scan-persistence.test.tsindex 6f944c770e..06d5e7295a 100644--- a/v3/@claude-flow/cli/__tests__/security-scan-persistence.test.ts+++ b/v3/@claude-flow/cli/__tests__/security-scan-persistence.test.ts@@ -28,6 +28,13 @@ beforeEach(() => {join(scanTarget, 'package.json'),JSON.stringify({ name: 'security-scan-persist-fixture', version: '1.0.0' }),);+ // #4124: without a lockfile `npm audit` fails (ENOLOCK), which is now+ // reported as "could not scan" instead of clean. An empty v3 lockfile lets+ // npm audit produce a real (empty) report offline.+ writeFileSync(+ join(scanTarget, 'package-lock.json'),+ JSON.stringify({ name: 'security-scan-persist-fixture', version: '1.0.0', lockfileVersion: 3, requires: true, packages: { '': { name: 'security-scan-persist-fixture', version: '1.0.0' } } }),+ );});afterEach(() => {diff --git a/v3/@claude-flow/cli/src/commands/security.ts b/v3/@claude-flow/cli/src/commands/security.tsindex c765e3f19e..4397e20795 100644--- a/v3/@claude-flow/cli/src/commands/security.ts+++ b/v3/@claude-flow/cli/src/commands/security.ts@@ -182,6 +182,7 @@ const scanCommand: Command = {const findings: ScanFinding[] = [];let criticalCount = 0, highCount = 0, mediumCount = 0, lowCount = 0;+ let depsSkipped: string | undefined;try {const fs = await import('fs');@@ -207,30 +208,31 @@ const scanCommand: Command = {auditResult = (auditErr instanceof Error && 'stdout' in auditErr ? (auditErr as { stdout: string }).stdout : undefined) || '{}';}- try {- const audit = JSON.parse(auditResult);- if (audit.vulnerabilities) {- for (const [pkg, vuln] of Object.entries(audit.vulnerabilities as Record<string, { severity: string; via: Array<{ title?: string; url?: string }> }>)) {- const sev = vuln.severity || 'low';- const title = Array.isArray(vuln.via) && vuln.via[0]?.title ? vuln.via[0].title : 'Vulnerability';- if (sev === 'critical') criticalCount++;- else if (sev === 'high') highCount++;- else if (sev === 'moderate' || sev === 'medium') mediumCount++;- else lowCount++;-- findings.push({- severity: sev === 'critical' ? 'critical' :- sev === 'high' ? 'high' :- sev === 'moderate' || sev === 'medium' ? 'medium' : 'low',- type: 'Dependency CVE',- location: `package.json:${pkg}`,- description: title.substring(0, 35),- });- }+ const audit = interpretNpmAudit(auditResult, path.resolve(target));+ if (!audit.ok) {+ depsSkipped = audit.reason;+ } else {+ for (const [pkg, vuln] of Object.entries(audit.vulnerabilities)) {+ const sev = vuln.severity || 'low';+ const first = Array.isArray(vuln.via) ? vuln.via[0] : undefined;+ const title = typeof first === 'object' && first?.title ? first.title : 'Vulnerability';+ if (sev === 'critical') criticalCount++;+ else if (sev === 'high') highCount++;+ else if (sev === 'moderate' || sev === 'medium') mediumCount++;+ else lowCount++;++ findings.push({+ severity: sev === 'critical' ? 'critical' :+ sev === 'high' ? 'high' :+ sev === 'moderate' || sev === 'medium' ? 'medium' : 'low',+ type: 'Dependency CVE',+ location: `package.json:${pkg}`,+ description: title.substring(0, 35),+ });}- } catch { /* JSON parse failed, no vulns */ }+ }}- } catch { /* npm audit failed */ }+ } catch (err) { depsSkipped = `npm audit could not run: ${err instanceof Error ? err.message : String(err)}`; }}// Phase 2: Scan for hardcoded secrets@@ -359,9 +361,12 @@ const scanCommand: Command = {if (findings.length > 20) {output.writeln(output.dim(`... and ${findings.length - 20} more issues`));}+ } else if (depsSkipped) {+ output.writeln(output.warning('No issues found by the checks that ran, but the dependency scan did not run.'));} else {output.writeln(output.success('No security issues found!'));}+ if (depsSkipped) output.writeln(output.warning(`Dependency scan skipped: ${depsSkipped}`));output.writeln();output.printBox([@@ -386,6 +391,7 @@ const scanCommand: Command = {low: lowCount,total: findings.length,},+ ...(depsSkipped ? { incomplete: true, skipped: { deps: depsSkipped } } : {}),findings,};@@ -422,6 +428,10 @@ const scanCommand: Command = {if (outputFormat === 'json') output.printJson(record);else if (outputFormat === 'sarif') output.printJson(scanSarif(findings));+ if (depsSkipped) {+ if (outputFormat !== 'text') output.printError(`Dependency scan skipped: ${depsSkipped}`);+ return { success: false, exitCode: 2 };+ }return { success: findings.length === 0 || (criticalCount === 0 && highCount === 0) };} catch (error) {if (outputFormat === 'text') spinner.fail('Scan failed');@@ -431,6 +441,43 @@ const scanCommand: Command = {},};+/**+ * #4124: `npm audit` can fail without exiting through the vulnerability path.+ * In a pnpm/yarn/bun project there is no package-lock.json, so it prints+ * `{"error":{"code":"ENOLOCK",...}}`. That has no `vulnerabilities` key, and+ * both `scan` and `cve` used to read it as a clean tree. Only a report with a+ * `vulnerabilities` object counts as a scan; anything else is "could not scan".+ */+type NpmAuditVuln = { severity: string; via: Array<{ title?: string; url?: string; source?: number; name?: string } | string> };+export type NpmAuditResult =+ | { ok: true; vulnerabilities: Record<string, NpmAuditVuln> }+ | { ok: false; reason: string };+export function interpretNpmAudit(raw: string, dir?: string): NpmAuditResult {+ let audit: { vulnerabilities?: unknown; error?: { code?: string; summary?: string } };+ try {+ audit = JSON.parse(raw);+ } catch {+ return { ok: false, reason: 'npm audit did not return a JSON report.' };+ }+ if (audit && typeof audit === 'object' && audit.error) {+ const code = typeof audit.error.code === 'string' ? audit.error.code : 'error';+ const summary = typeof audit.error.summary === 'string' ? audit.error.summary : 'npm audit failed.';+ return { ok: false, reason: `npm audit failed (${code}): ${summary}${code === 'ENOLOCK' ? auditHint(dir) : ''}` };+ }+ if (!audit || typeof audit !== 'object' || !audit.vulnerabilities || typeof audit.vulnerabilities !== 'object') {+ return { ok: false, reason: 'npm audit returned no vulnerability report.' };+ }+ return { ok: true, vulnerabilities: audit.vulnerabilities as Record<string, NpmAuditVuln> };+}+function auditHint(dir?: string): string {+ if (!dir) return '';+ const has = (f: string) => existsSync(resolvePath(dir, f));+ if (has('pnpm-lock.yaml')) return ' This is a pnpm project: run `pnpm audit` instead.';+ if (has('yarn.lock')) return ' This is a yarn project: run `yarn npm audit` (Berry) or `yarn audit` (v1) instead.';+ if (has('bun.lock') || has('bun.lockb')) return ' This is a bun project: run `bun audit` instead.';+ return ' Create one with `npm i --package-lock-only`, or use your package manager\'s audit.';+}+// CVE subcommandconst cveCommand: Command = {name: 'cve',@@ -466,23 +513,22 @@ const cveCommand: Command = {auditJson = (e instanceof Error && 'stdout' in e ? (e as { stdout: string }).stdout : '') || '{}';}- let audit: { vulnerabilities?: Record<string, { severity: string; via: Array<{ title?: string; url?: string; source?: number; name?: string }> }> };- try {- audit = JSON.parse(auditJson);- } catch {- output.writeln(output.warning('âš Could not parse `npm audit --json` output.'));- output.writeln(output.dim('Make sure you are inside a project with a package.json.'));+ const audit = interpretNpmAudit(auditJson, process.cwd());+ if (!audit.ok) {+ output.writeln(output.warning(`âš Could not check dependencies: ${audit.reason}`));+ output.writeln(output.dim('No result is reported rather than a false all-clear.'));return { success: false, exitCode: 2 };}- const vulns = audit.vulnerabilities || {};+ const vulns = audit.vulnerabilities;const cveRows: Array<{ pkg: string; severity: string; cveIds: string[]; title: string; url: string | undefined }> = [];const CVE_RE = /CVE-\d{4}-\d{4,7}/g;for (const [pkg, v] of Object.entries(vulns)) {const sev = v.severity || 'low';- const titles = (v.via || []).filter((x) => typeof x === 'object' && x?.title).map((x) => x.title!);- const urls = (v.via || []).filter((x) => typeof x === 'object' && x?.url).map((x) => x.url!);+ const via = (v.via || []).filter((x): x is Exclude<typeof x, string> => typeof x === 'object' && x !== null);+ const titles = via.filter((x) => x.title).map((x) => x.title!);+ const urls = via.filter((x) => x.url).map((x) => x.url!);const allText = `${titles.join(' ')} ${urls.join(' ')}`;const cveIds = Array.from(new Set(allText.match(CVE_RE) || []));cveRows.push({ pkg, severity: sev, cveIds, title: titles[0] || 'Vulnerability', url: urls[0] });diff --git a/v3/@claude-flow/cli/src/funnel/local-signals.ts b/v3/@claude-flow/cli/src/funnel/local-signals.tsindex 7cca5e04bf..d201e73e22 100644--- a/v3/@claude-flow/cli/src/funnel/local-signals.ts+++ b/v3/@claude-flow/cli/src/funnel/local-signals.ts@@ -42,7 +42,8 @@ export function getSecurityStatus(cwd: string = process.cwd()): SecurityStatus {scan.summary?.total ?? scan.totalFindings ?? scan.findings?.length ?? 0;const findings = Math.max(0, Number.isFinite(rawFindings) ? rawFindings : 0);return {- status: findings > 0 ? 'ISSUES' : 'CLEAN',+ // #4124: a scan whose dependency phase could not run is not a clean scan.+ status: findings > 0 ? 'ISSUES' : scan.incomplete === true ? 'PENDING' : 'CLEAN',findings,scannedAt: typeof scan.timestamp === 'string' ? scan.timestamp : undefined,cvesFixed: 0,