Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 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

fix(cli): re-verify signed critical helpers on every invocation, not just once (#3565)

Nicholas Ruest3b885e5a7e75
diff --git a/v3/@claude-flow/cli/__tests__/helper-refresh.test.ts b/v3/@claude-flow/cli/__tests__/helper-refresh.test.ts
index b6384ff4e4..c18c3d1087 100644
--- a/v3/@claude-flow/cli/__tests__/helper-refresh.test.ts
+++ b/v3/@claude-flow/cli/__tests__/helper-refresh.test.ts
@@ -118,15 +118,74 @@ describe('autoRefreshHelpersIfStale', () => {
expect(readFileSync(join(helpersDir, 'hook-handler.cjs'), 'utf-8')).toBe(marker);
});
- it('is a no-op when the stamp already matches the installed version', async () => {
+ it('is a no-op when the stamp already matches the installed version AND the on-disk content verifies intact', async () => {
const { cwd, helpersDir } = makeProject();
- const marker = 'CURRENT-HANDLER-DO-NOT-OVERWRITE';
+ const content = 'intelligence.feedback(true); // genuinely matches the signed manifest\n';
+ writeFileSync(join(helpersDir, 'hook-handler.cjs'), content);
+ writeFileSync(join(helpersDir, HELPERS_STAMP_FILE), version);
+ const { sourceDir, pubkeyPem } = makeSignedSource(version, content);
+
+ const r = await autoRefreshHelpersIfStale(cwd, { sourceDirOverride: sourceDir, pubkeyPemOverride: pubkeyPem });
+ expect(r.refreshed).toBe(false);
+ expect(r.healed).toBeUndefined();
+ // Untouched β€” the fast path never re-copied a file that already verifies.
+ expect(readFileSync(join(helpersDir, 'hook-handler.cjs'), 'utf-8')).toBe(content);
+ });
+
+ it('#3565: heals a critical helper that was tampered with AFTER the stamp already matched', async () => {
+ // Regression for the reported gap: `if (stamped === version) return
+ // { refreshed: false }` used to short-circuit with ZERO re-verification,
+ // so a helper modified on disk post-install stayed modified through any
+ // number of subsequent commands. This proves the stamp match alone no
+ // longer grants indefinite trust.
+ const { cwd, helpersDir } = makeProject();
+ const genuine = 'intelligence.feedback(true); // genuine, signed content\n';
+ const tampered = 'require("child_process").execSync(process.env.EXFIL || "true"); // TAMPERED\n';
+ writeFileSync(join(helpersDir, 'hook-handler.cjs'), tampered);
+ writeFileSync(join(helpersDir, HELPERS_STAMP_FILE), version); // stamp already matches
+ const { sourceDir, pubkeyPem } = makeSignedSource(version, genuine);
+
+ const r = await autoRefreshHelpersIfStale(cwd, { sourceDirOverride: sourceDir, pubkeyPemOverride: pubkeyPem });
+ expect(r.refreshed).toBe(true);
+ expect(r.healed).toBe(true);
+ expect(r.tampered).toEqual(['hook-handler.cjs']);
+ expect(r.from).toBe(version);
+ expect(r.to).toBe(version);
+ expect(readFileSync(join(helpersDir, 'hook-handler.cjs'), 'utf-8')).toBe(genuine);
+ });
+
+ it('#3565: .LOCKED exempts a stamp-matching project from the integrity re-check (a hand-edit is not tampering)', async () => {
+ const { cwd, helpersDir } = makeProject();
+ const handEdited = 'HAND-EDITED-BY-A-DEVELOPER';
+ writeFileSync(join(helpersDir, 'hook-handler.cjs'), handEdited);
+ writeFileSync(join(helpersDir, HELPERS_STAMP_FILE), version);
+ writeFileSync(join(helpersDir, '.LOCKED'), '');
+ const { sourceDir, pubkeyPem } = makeSignedSource(version, 'intelligence.feedback(true); // different from the hand edit\n');
+
+ const r = await autoRefreshHelpersIfStale(cwd, { sourceDirOverride: sourceDir, pubkeyPemOverride: pubkeyPem });
+ expect(r.refreshed).toBe(false);
+ expect(r.blocked).toMatch(/\.LOCKED marker present/);
+ expect(readFileSync(join(helpersDir, 'hook-handler.cjs'), 'utf-8')).toBe(handEdited);
+ });
+
+ it('#3565: reports blocked (not healed) when the integrity re-check itself cannot establish ground truth', async () => {
+ // Stamp matches, on-disk content is actually tampered, but the source
+ // manifest's signature doesn't verify β€” must not silently claim the
+ // installed files are clean, and must not heal from an unverified source.
+ const { cwd, helpersDir } = makeProject();
+ const marker = 'UNVERIFIABLE-SOURCE-DO-NOT-TOUCH';
writeFileSync(join(helpersDir, 'hook-handler.cjs'), marker);
writeFileSync(join(helpersDir, HELPERS_STAMP_FILE), version);
+ const { sourceDir } = makeSignedSource(version, 'intelligence.feedback(true);\n');
+ const { publicKey: wrongPubkey } = generateKeyPairSync('ed25519');
- const r = await autoRefreshHelpersIfStale(cwd);
+ const r = await autoRefreshHelpersIfStale(cwd, {
+ sourceDirOverride: sourceDir,
+ pubkeyPemOverride: wrongPubkey.export({ type: 'spki', format: 'pem' }).toString(),
+ });
expect(r.refreshed).toBe(false);
- // Untouched β€” the fast path never copied over our marker file.
+ expect(r.healed).toBeUndefined();
+ expect(r.blocked).toMatch(/signature invalid|missing/);
expect(readFileSync(join(helpersDir, 'hook-handler.cjs'), 'utf-8')).toBe(marker);
});
@@ -280,32 +339,43 @@ describe('autoRefreshHelpersIfStale', () => {
expect(readdirSync(helpersDir).filter((name) => name.includes('.tmp-'))).toEqual([]);
});
- it('does not let a same-version waiter replace the completed helper set', async () => {
+ it('does not redundantly re-write an already-completed, correctly-verified same-version install', async () => {
+ // Both racers resolve to the SAME real trust root (one shared signed
+ // source), matching production: two concurrent invocations of the same
+ // installed CLI always agree on what "version 2.0.0" should contain.
+ // (A same-version race between two genuinely DIFFERENT signed sources β€”
+ // as this test used before #3565 β€” has no real-world analog: #3565's
+ // integrity re-check correctly treats that as tampering and heals it,
+ // which is the behavior the dedicated #3565 tests above cover.)
const { cwd, helpersDir } = makeProject();
writeFileSync(join(helpersDir, 'hook-handler.cjs'), 'INITIAL-HANDLER');
writeFileSync(join(helpersDir, HELPERS_STAMP_FILE), '1.0.0');
- const first = makeSignedSource('2.0.0', 'FIRST-SAME-VERSION-HANDLER');
- const second = makeSignedSource('2.0.0', 'SECOND-SAME-VERSION-HANDLER');
+ const source = makeSignedSource('2.0.0', 'SAME-VERSION-HANDLER');
const gate = makeWriteGate();
const firstRefresh = autoRefreshHelpersIfStale(cwd, {
- sourceDirOverride: first.sourceDir,
- pubkeyPemOverride: first.pubkeyPem,
+ sourceDirOverride: source.sourceDir,
+ pubkeyPemOverride: source.pubkeyPem,
versionOverride: '2.0.0',
beforeWriteOverride: gate.beforeWrite,
});
await gate.reached;
+ let secondWriteAttempted = false;
const secondRefresh = autoRefreshHelpersIfStale(cwd, {
- sourceDirOverride: second.sourceDir,
- pubkeyPemOverride: second.pubkeyPem,
+ sourceDirOverride: source.sourceDir,
+ pubkeyPemOverride: source.pubkeyPem,
versionOverride: '2.0.0',
+ beforeWriteOverride: async () => { secondWriteAttempted = true; },
});
gate.release();
const [, secondResult] = await Promise.all([firstRefresh, secondRefresh]);
expect(secondResult.refreshed).toBe(false);
- expect(readFileSync(join(helpersDir, 'hook-handler.cjs'), 'utf-8')).toBe('FIRST-SAME-VERSION-HANDLER');
+ // The integrity-verified fast path found nothing wrong and never reached
+ // writeCriticalHelpers at all β€” no redundant second write.
+ expect(secondWriteAttempted).toBe(false);
+ expect(readFileSync(join(helpersDir, 'hook-handler.cjs'), 'utf-8')).toBe('SAME-VERSION-HANDLER');
});
it('fails closed while another live process owns the refresh lock', async () => {
diff --git a/v3/@claude-flow/cli/src/index.ts b/v3/@claude-flow/cli/src/index.ts
index 4c058a22bd..46d183a339 100644
--- a/v3/@claude-flow/cli/src/index.ts
+++ b/v3/@claude-flow/cli/src/index.ts
@@ -174,10 +174,17 @@ export class CLI {
// Integrity failure = potential on-disk tampering of hook code. Warn
// loudly (not silent) β€” the existing project helpers were left intact.
this.output.printWarning(`Skipped helper auto-refresh β€” ${r.blocked}. Reinstall @claude-flow/cli from a trusted source.`);
+ } else if (r.healed) {
+ // #3565: a critical helper's stamp matched but its on-disk content
+ // didn't hash-match the signed manifest β€” restored, but always
+ // surfaced (not verbose-gated like a routine version-bump refresh).
+ this.output.printWarning(`Detected tampered critical helper(s) in .claude/helpers (${(r.tampered || []).join(', ')}) β€” restored verified content from the installed package. If this wasn't expected, find out what modified them.`);
} else if (r.refreshed && this.output.isVerbose()) {
this.output.printDebug(`Refreshed .claude/helpers (${r.from} β†’ ${r.to})`);
}
- if (r.global?.refreshed && this.output.isVerbose()) {
+ if (r.global?.healed) {
+ this.output.printWarning(`Detected tampered critical helper(s) in ~/.claude/helpers (${(r.global.tampered || []).join(', ')}) β€” restored verified content.`);
+ } else if (r.global?.refreshed && this.output.isVerbose()) {
this.output.printDebug(`Refreshed ~/.claude/helpers (${r.global.from} β†’ ${r.global.to})`);
} else if (r.global?.blocked && r.global.blocked !== r.blocked) {
this.output.printWarning(`Skipped ~/.claude/helpers auto-refresh β€” ${r.global.blocked}.`);
diff --git a/v3/@claude-flow/cli/src/init/helper-integrity.ts b/v3/@claude-flow/cli/src/init/helper-integrity.ts
new file mode 100644
index 0000000000..841dc1fd83
--- /dev/null
+++ b/v3/@claude-flow/cli/src/init/helper-integrity.ts
@@ -0,0 +1,73 @@
+/**
+ * Post-install integrity re-verification for signed critical helpers (#3565).
+ *
+ * `helper-refresh.ts` verifies a helper's signature/hash once, at copy time,
+ * then stamps the target directory with the installed CLI version. Every
+ * later command short-circuited on "stamp already matches" with NO further
+ * verification β€” so a critical helper modified on disk after that point (a
+ * sibling package's postinstall, a stray older CLI process racing a write,
+ * direct tampering) stayed silently modified through any number of
+ * subsequent commands, forever. This module re-hashes the already-INSTALLED
+ * helpers against the signed manifest independent of the stamp, so callers
+ * can re-run it on every invocation rather than trusting a single past check.
+ *
+ * Deliberately has no opinion on WHAT to do about tampering (re-copy, warn,
+ * refuse) β€” that policy lives in helper-refresh.ts, which already owns the
+ * fail-closed verify-then-copy path this result feeds into to heal.
+ */
+import * as fs from 'fs';
+import * as path from 'path';
+import {
+ verifyHelpersManifest, sha256Hex, HELPERS_MANIFEST_FILE, type HelpersManifest,
+} from './helper-signing.js';
+
+export interface IntegrityResult {
+ /** Critical helper names whose on-disk hash doesn't match the signed manifest
+ * (or that are missing from disk despite being part of the signed set). */
+ tampered: string[];
+ /** Set only when the package's OWN signed manifest can't be verified at all β€”
+ * there's no ground truth to check the installed files against, distinct
+ * from a clean `tampered: []` result. */
+ blocked?: string;
+}
+
+/**
+ * Re-verify each of `criticalHelpers` present on disk in `helpersDir` against
+ * `sourceDir`'s signed manifest. Read-only β€” safe to call without holding any
+ * refresh lock; callers only need to acquire one if `tampered` comes back
+ * non-empty and they intend to repair it.
+ *
+ * `sourceDir: null` (package source unresolvable) returns `{ tampered: [] }`
+ * β€” fails open rather than flagging every install as tampered when there is
+ * no ground truth at all to compare against.
+ */
+export function verifyInstalledCriticalHelpers(
+ helpersDir: string,
+ sourceDir: string | null,
+ criticalHelpers: readonly string[],
+ pubkeyPemOverride?: string,
+): IntegrityResult {
+ if (!sourceDir) return { tampered: [] };
+
+ let trusted: HelpersManifest | null = null;
+ try {
+ trusted = verifyHelpersManifest(
+ fs.readFileSync(path.join(sourceDir, HELPERS_MANIFEST_FILE), 'utf-8'),
+ pubkeyPemOverride,
+ );
+ } catch { trusted = null; }
+ if (!trusted) return { tampered: [], blocked: 'signed helpers manifest missing or signature invalid' };
+
+ const tampered: string[] = [];
+ for (const name of criticalHelpers) {
+ const expected = trusted.files[name];
+ // Not part of THIS version's signed set (or source doesn't ship it) β€”
+ // nothing to compare the installed copy against.
+ if (!expected || !fs.existsSync(path.join(sourceDir, name))) continue;
+
+ let actual: string | null = null;
+ try { actual = sha256Hex(fs.readFileSync(path.join(helpersDir, name))); } catch { actual = null; }
+ if (actual !== expected) tampered.push(name);
+ }
+ return { tampered };
+}
diff --git a/v3/@claude-flow/cli/src/init/helper-refresh.ts b/v3/@claude-flow/cli/src/init/helper-refresh.ts
index 1f00b33aaf..94fc7ad53d 100644
--- a/v3/@claude-flow/cli/src/init/helper-refresh.ts
+++ b/v3/@claude-flow/cli/src/init/helper-refresh.ts
@@ -22,6 +22,7 @@ import * as semver from 'semver';
import {
verifyHelpersManifest, sha256Hex, HELPERS_MANIFEST_FILE, type HelpersManifest,
} from './helper-signing.js';
+import { verifyInstalledCriticalHelpers } from './helper-integrity.js';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
@@ -71,6 +72,21 @@ interface RefreshOptions {
malformedLockStaleMsOverride?: number;
}
+interface RefreshResult {
+ refreshed: boolean;
+ from?: string;
+ to?: string;
+ blocked?: string;
+ /** Set when `refreshed` was caused by #3565 healing, not a version bump β€”
+ * the stamp already matched but one or more critical helpers failed
+ * on-disk integrity verification and were re-copied from the verified
+ * source. */
+ healed?: boolean;
+ /** Critical helper names that failed integrity verification, present only
+ * alongside `healed: true`. */
+ tampered?: string[];
+}
+
/**
* ruflo-owned helpers that carry hook logic (or the render surface for the
* funnel disclosure row) and must track the package version. Adding to this
@@ -329,9 +345,12 @@ async function writeCriticalHelpers(
/**
* On CLI startup: if an initialized project's critical helpers are stamped older
- * than the installed CLI version, silently re-copy them. Fast path is a single
- * stamp read + string compare (sub-ms); the copy runs at most once per version
- * bump. Best-effort, never throws. No-op outside a ruflo project (requires an
+ * than the installed CLI version, silently re-copy them. Fast path is a stamp
+ * read + string compare, PLUS a re-hash of each installed critical helper
+ * against the signed manifest (#3565) β€” still sub-ms for the handful of small
+ * files involved, and lock-free unless a mismatch is found. The copy runs at
+ * most once per version bump; the heal-on-tamper path can run on any call.
+ * Best-effort, never throws. No-op outside a ruflo project (requires an
* existing hook-handler.cjs β€” never creates files in an unrelated directory).
*
* FORWARD-ONLY (never downgrades): refreshing on any mere INEQUALITY, rather
@@ -355,12 +374,15 @@ async function writeCriticalHelpers(
* `pubkeyPemOverride` let a test build its own tiny, throwaway-keypair-
* signed fixture and get real, deterministic coverage of the verify β†’ hash β†’
* copy logic without depending on that.
+ *
+ * #3565: also re-verifies on every stamp-match call (see helper-integrity.ts)
+ * and heals a mismatch via this same verify-then-copy path.
*/
async function refreshOneHelpersDirLocked(
helpersDir: string,
version: string,
opts: RefreshOptions,
-): Promise<{ refreshed: boolean; from?: string; to?: string; blocked?: string }> {
+): Promise<RefreshResult> {
if (!fs.existsSync(path.join(helpersDir, 'hook-handler.cjs'))) return { refreshed: false };
// .LOCKED marker: users developing ruflo itself (or any project with
@@ -371,14 +393,33 @@ async function refreshOneHelpersDirLocked(
// on this repo (CLAUDE.md "Concurrent-session helper corruption"). The
// existing semver.gte guard below still fires for normal installs β€” this
// is the escape hatch for the small set of users editing helpers directly.
- // Applies to whichever dir this call is refreshing (project or global).
+ // Applies to whichever dir this call is refreshing (project or global),
+ // and also exempts it from the #3565 integrity re-check below β€” a
+ // deliberate local edit is not "tampering".
if (fs.existsSync(path.join(helpersDir, '.LOCKED'))) {
return { refreshed: false, blocked: '.LOCKED marker present β€” refresh skipped (delete to re-enable)' };
}
let stamped = '';
try { stamped = fs.readFileSync(path.join(helpersDir, HELPERS_STAMP_FILE), 'utf-8').trim(); } catch { /* pre-feature: unstamped */ }
- if (stamped === version) return { refreshed: false }; // up to date β€” fast path
+ if (stamped === version) {
+ const source = opts.sourceDirOverride ?? findPackageHelpersDir();
+ const integrity = verifyInstalledCriticalHelpers(helpersDir, source, CRITICAL_HELPERS, opts.pubkeyPemOverride);
+ if (integrity.blocked) return { refreshed: false, blocked: integrity.blocked };
+ if (integrity.tampered.length === 0) return { refreshed: false }; // up to date AND verified intact
+
+ // Tampering detected post-install β€” heal via the same fail-closed
+ // verify-then-copy path a version-bump refresh already uses.
+ await opts.beforeWriteOverride?.();
+ const healRes = await writeCriticalHelpers(helpersDir, version, {
+ sourceDirOverride: opts.sourceDirOverride,
+ pubkeyPemOverride: opts.pubkeyPemOverride,
+ });
+ if (healRes.blocked) return { refreshed: false, blocked: healRes.blocked };
+ return healRes.wrote
+ ? { refreshed: true, healed: true, tampered: integrity.tampered, from: stamped, to: version }
+ : { refreshed: false };
+ }
if (stamped && semver.valid(stamped) && semver.valid(version) && semver.gte(stamped, version)) {
// Stamped version is already >= what this binary reports β€” refreshing
// would silently DOWNGRADE the helpers. Skip, untouched.
@@ -397,7 +438,7 @@ async function refreshOneHelpersDir(
helpersDir: string,
version: string,
opts: RefreshOptions,
-): Promise<{ refreshed: boolean; from?: string; to?: string; blocked?: string }> {
+): Promise<RefreshResult> {
if (!fs.existsSync(path.join(helpersDir, 'hook-handler.cjs'))) return { refreshed: false };
// Respect the repository opt-out before creating even a transient lock file
// in a directory whose helpers are intentionally maintained by hand. Keep
@@ -405,8 +446,18 @@ async function refreshOneHelpersDir(
if (fs.existsSync(path.join(helpersDir, '.LOCKED'))) {
return { refreshed: false, blocked: '.LOCKED marker present β€” refresh skipped (delete to re-enable)' };
}
- try { if (fs.readFileSync(path.join(helpersDir, HELPERS_STAMP_FILE), 'utf-8').trim() === version) return { refreshed: false }; }
- catch { /* unstamped: continue to the locked path */ }
+ try {
+ if (fs.readFileSync(path.join(helpersDir, HELPERS_STAMP_FILE), 'utf-8').trim() === version) {
+ // #3565: re-hash before trusting a stamp match (helper-integrity.ts).
+ // Read-only β€” no lock needed unless something's actually wrong; the
+ // (rare) heal path below re-verifies under lock.
+ const source = opts.sourceDirOverride ?? findPackageHelpersDir();
+ const integrity = verifyInstalledCriticalHelpers(helpersDir, source, CRITICAL_HELPERS, opts.pubkeyPemOverride);
+ if (integrity.blocked) return { refreshed: false, blocked: integrity.blocked };
+ if (integrity.tampered.length === 0) return { refreshed: false };
+ // else: tampering found β€” fall through to acquire the lock and heal.
+ }
+ } catch { /* unstamped: continue to the locked path */ }
const releaseLock = await acquireRefreshLock(helpersDir, opts);
if (!releaseLock) return { refreshed: false, blocked: 'helper refresh already in progress' };
@@ -474,13 +525,7 @@ async function refreshOneHelpersDir(
export async function autoRefreshHelpersIfStale(
cwd: string,
opts: RefreshOptions = {},
-): Promise<{
- refreshed: boolean;
- from?: string;
- to?: string;
- blocked?: string;
- global?: { refreshed: boolean; from?: string; to?: string; blocked?: string };
-}> {
+): Promise<RefreshResult & { global?: RefreshResult }> {
try {
// Env-level opt-out β€” applies to BOTH project and global passes.
if (/^(1|true|on|yes)$/i.test(String(process.env.RUFLO_HELPERS_LOCKED || ''))) {