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(plugins): apply the #3557 trust policy on plugins upgrade

Dragan Spiridonove0f2e83a333b
diff --git a/v3/@claude-flow/cli/__tests__/plugins-upgrade-trust-gate.test.ts b/v3/@claude-flow/cli/__tests__/plugins-upgrade-trust-gate.test.ts
new file mode 100644
index 0000000000..2ed2265123
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/plugins-upgrade-trust-gate.test.ts
@@ -0,0 +1,146 @@
+/**
+ * #3557 follow-up — `plugins upgrade` must apply the same trust policy as
+ * `plugins install`. It used to copy the new version's `claude-flow` hooks and
+ * commands straight into the manifest (so hooks withheld at install got
+ * registered on upgrade), and it kept running lifecycle scripts for any install
+ * recorded with scriptsRun:true.
+ *
+ * Drives REAL npm against local tarballs (no network): the mock only rewrites
+ * `<pkg>@<version>` to that version's tarball and delegates to the real
+ * execFile, so npm itself decides whether postinstall runs.
+ */
+import { describe, it, expect, vi, beforeAll, afterAll, beforeEach } from 'vitest';
+import * as fs from 'fs';
+import * as os from 'os';
+import * as path from 'path';
+import { execFileSync } from 'child_process';
+
+const PKG = 'ruflo-upgrade-probe-3557';
+const state: { tarballs: Record<string, string> } = { tarballs: {} };
+
+vi.mock('child_process', async (importOriginal) => {
+ const real = await importOriginal<typeof import('child_process')>();
+ return {
+ ...real,
+ execFile: (file: string, args: string[], opts: unknown, cb: (...a: unknown[]) => void) => {
+ const mapped = args.map((a) => state.tarballs[a] ?? a);
+ return real.execFile(file, mapped, opts as object, cb as never);
+ },
+ };
+});
+
+import { PluginManager } from '../src/plugins/manager.js';
+
+describe('#3557 plugins upgrade re-applies the trust policy', () => {
+ let work: string;
+ let sentinel: string;
+
+ function pack(version: string, claudeFlow: Record<string, unknown>, withPostinstall: boolean): string {
+ const src = path.join(work, `src-${version}`);
+ fs.mkdirSync(src);
+ fs.writeFileSync(
+ path.join(src, 'package.json'),
+ JSON.stringify({
+ name: PKG,
+ version,
+ ...(withPostinstall
+ ? { scripts: { postinstall: `node -e "require('fs').writeFileSync('${sentinel}', '${version}')"` } }
+ : {}),
+ 'claude-flow': claudeFlow,
+ }),
+ );
+ const out = execFileSync('npm', ['pack', '--pack-destination', work, '--ignore-scripts', '--json'], {
+ cwd: src,
+ encoding: 'utf-8',
+ });
+ return path.join(work, JSON.parse(out)[0].filename);
+ }
+
+ async function freshManager(label: string): Promise<PluginManager> {
+ const manager = new PluginManager(fs.mkdtempSync(path.join(work, `${label}-`)));
+ await manager.initialize();
+ return manager;
+ }
+
+ beforeAll(() => {
+ work = fs.mkdtempSync(path.join(os.tmpdir(), 'plugins-upgrade-3557-'));
+ sentinel = path.join(work, 'POSTINSTALL_RAN');
+ // 1.0.0: benign — default permission set only.
+ state.tarballs[`${PKG}@1.0.0`] = pack('1.0.0', { permissions: ['memory:read'], hooks: ['pre-task'], commands: ['probe'] }, false);
+ // 2.0.0 / 3.0.0: elevated permissions, an extra hook, and a postinstall script.
+ const elevated = { trustLevel: 'untrusted', permissions: ['shell:exec'], hooks: ['pre-task', 'post-edit'], commands: ['probe'] };
+ state.tarballs[`${PKG}@2.0.0`] = pack('2.0.0', elevated, true);
+ state.tarballs[`${PKG}@3.0.0`] = pack('3.0.0', elevated, true);
+ }, 120000);
+
+ afterAll(() => fs.rmSync(work, { recursive: true, force: true }));
+
+ beforeEach(() => {
+ fs.rmSync(sentinel, { force: true });
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ });
+
+ it('an upgrade that newly declares elevated permissions withholds its hooks and skips its scripts', async () => {
+ const manager = await freshManager('benign');
+ const installed = await manager.installFromNpm(PKG, '1.0.0', { verify: true });
+ expect(installed.plugin!.hooks).toEqual(['pre-task']);
+
+ const result = await manager.upgrade(PKG, '2.0.0');
+
+ expect(result.success).toBe(true);
+ expect(result.plugin!.version).toBe('2.0.0');
+ expect(result.plugin!.hooks).toEqual([]);
+ expect(result.plugin!.commands).toEqual([]);
+ expect(result.plugin!.withheld).toEqual(
+ expect.objectContaining({ hooks: ['pre-task', 'post-edit'], commands: ['probe'] }),
+ );
+ expect(result.plugin!.permissions).toEqual(['shell:exec']);
+ expect(result.plugin!.scriptsRun).toBe(false);
+ expect(fs.existsSync(sentinel)).toBe(false);
+ expect((await manager.getPlugin(PKG))!.hooks).toEqual([]);
+ }, 120000);
+
+ it('hooks withheld at install stay withheld on upgrade', async () => {
+ const manager = await freshManager('withheld');
+ const installed = await manager.installFromNpm(PKG, '2.0.0', { verify: true });
+ expect(installed.plugin!.hooks).toEqual([]);
+ expect(installed.plugin!.withheld).toBeDefined();
+
+ const result = await manager.upgrade(PKG, '3.0.0');
+
+ expect(result.success).toBe(true);
+ expect(result.plugin!.hooks).toEqual([]);
+ expect(result.plugin!.withheld!.hooks).toEqual(['pre-task', 'post-edit']);
+ expect(fs.existsSync(sentinel)).toBe(false);
+ }, 120000);
+
+ it('a recorded scriptsRun:true (e.g. from registry vouching) does not run the new version\'s scripts', async () => {
+ const manager = await freshManager('vouched');
+ // An earlier install vouched as "official" ran scripts and registered hooks.
+ const installed = await manager.installFromNpm(PKG, '2.0.0', { verify: true, registryTrustLevel: 'official' });
+ expect(installed.plugin!.scriptsRun).toBe(true);
+ expect(installed.plugin!.hooks).toEqual(['pre-task', 'post-edit']);
+ fs.rmSync(sentinel, { force: true });
+
+ const result = await manager.upgrade(PKG, '3.0.0');
+
+ expect(result.success).toBe(true);
+ expect(fs.existsSync(sentinel)).toBe(false);
+ expect(result.plugin!.scriptsRun).toBe(false);
+ expect(result.plugin!.hooks).toEqual([]);
+ expect(result.warnings!.join(' ')).toMatch(/Install scripts were skipped.*--trust/);
+ }, 120000);
+
+ it('--trust on the upgrade runs scripts and registers the hooks', async () => {
+ const manager = await freshManager('trusted');
+ await manager.installFromNpm(PKG, '1.0.0', { verify: true });
+
+ const result = await manager.upgrade(PKG, '2.0.0', { trust: true });
+
+ expect(result.success).toBe(true);
+ expect(fs.readFileSync(sentinel, 'utf-8')).toBe('2.0.0');
+ expect(result.plugin!.scriptsRun).toBe(true);
+ expect(result.plugin!.hooks).toEqual(['pre-task', 'post-edit']);
+ expect(result.plugin!.withheld).toBeUndefined();
+ }, 120000);
+});
diff --git a/v3/@claude-flow/cli/src/commands/plugins.ts b/v3/@claude-flow/cli/src/commands/plugins.ts
index 4ed93078a3..60b6238edc 100644
--- a/v3/@claude-flow/cli/src/commands/plugins.ts
+++ b/v3/@claude-flow/cli/src/commands/plugins.ts
@@ -740,6 +740,23 @@ const upgradeCommand: Command = {
options: [
{ name: 'name', short: 'n', type: 'string', description: 'Plugin name', required: true },
{ name: 'version', short: 'v', type: 'string', description: 'Target version (default: latest)' },
+ {
+ name: 'verify',
+ type: 'boolean',
+ description:
+ 'Re-apply the install trust policy to the new version (default: true). Its hooks and commands are withheld ' +
+ `if it declares trustLevel "untrusted"/"unverified" or permissions beyond the default set (${DEFAULT_PLUGIN_PERMISSIONS.join(', ')}) ` +
+ 'unless --trust is given. --no-verify skips this.',
+ default: true,
+ },
+ {
+ name: 'trust',
+ type: 'boolean',
+ description:
+ "Run the new version's install scripts and register its hooks and commands even if it is untrusted or " +
+ 'declares elevated permissions. Not carried over from the original install.',
+ default: false,
+ },
],
examples: [
{ command: 'claude-flow plugins upgrade -n @claude-flow/neural', description: 'Upgrade to latest' },
@@ -748,6 +765,8 @@ const upgradeCommand: Command = {
action: async (ctx: CommandContext): Promise<CommandResult> => {
const name = ctx.flags.name as string;
const version = ctx.flags.version as string;
+ const verify = ctx.flags.verify !== false;
+ const trust = ctx.flags.trust === true;
if (!name) {
output.printError('Plugin name is required');
@@ -772,7 +791,7 @@ const upgradeCommand: Command = {
const oldVersion = existing.version;
spinner.setText(`Upgrading ${name} from v${oldVersion}...`);
- const result = await manager.upgrade(name, version);
+ const result = await manager.upgrade(name, version, { verify, trust });
if (!result.success) {
spinner.fail(`Upgrade failed: ${result.error}`);
@@ -782,6 +801,19 @@ const upgradeCommand: Command = {
const plugin = result.plugin!;
spinner.succeed(`Upgraded ${name}: v${oldVersion} -> v${plugin.version}`);
+ if (result.decision?.verificationSkipped) {
+ output.printWarning('Verification skipped (--no-verify): hooks and commands were registered without a trust check.');
+ }
+ for (const warning of result.warnings ?? []) {
+ output.printWarning(warning);
+ }
+ if (plugin.withheld) {
+ output.printWarning(
+ `Withheld ${plugin.withheld.hooks.length} hook(s) and ${plugin.withheld.commands.length} command(s) ` +
+ `from ${plugin.name} because it ${plugin.withheld.reasons.join('; ')}. Upgrade with --trust to register them.`,
+ );
+ }
+
return { success: true, data: plugin };
} catch (error) {
spinner.fail('Upgrade failed');
diff --git a/v3/@claude-flow/cli/src/plugins/manager.ts b/v3/@claude-flow/cli/src/plugins/manager.ts
index 8d65e513b7..7de7d4f60b 100644
--- a/v3/@claude-flow/cli/src/plugins/manager.ts
+++ b/v3/@claude-flow/cli/src/plugins/manager.ts
@@ -570,8 +570,9 @@ export class PluginManager {
*/
async upgrade(
packageName: string,
- version?: string
- ): Promise<{ success: boolean; error?: string; plugin?: InstalledPlugin }> {
+ version?: string,
+ opts: Pick<PluginInstallOptions, 'verify' | 'trust'> = {},
+ ): Promise<{ success: boolean; error?: string; plugin?: InstalledPlugin; decision?: TrustDecision; warnings?: string[] }> {
if (!this.manifest) {
await this.initialize();
}
@@ -592,28 +593,51 @@ export class PluginManager {
validatePackageName(versionSpec);
// Reinstall with new version (array form prevents shell injection).
- // An install recorded with scriptsRun:false stays script-free on upgrade;
- // legacy entries (no field) keep their pre-#3557 behaviour.
+ // #3557: the new version's lifecycle scripts run only with an explicit
+ // --trust for this upgrade. A recorded scriptsRun:true from an earlier
+ // install is not enough: it may come from registry vouching that was
+ // never verified, and the new version's scripts were never reviewed.
+ const warnings: string[] = [];
+ const scriptsRun = opts.trust === true;
const upgradeArgs = ['install', '--prefix', this.config.pluginsDir, versionSpec];
- if (existing.scriptsRun === false) upgradeArgs.push('--ignore-scripts');
+ if (!scriptsRun) {
+ upgradeArgs.push('--ignore-scripts');
+ warnings.push(
+ `Install scripts were skipped for ${packageName} (--ignore-scripts). Upgrade with --trust to run them.`,
+ );
+ }
await runNpm(upgradeArgs, 120000);
// Update manifest
const installDir = path.join(this.config.pluginsDir, 'node_modules');
const packageJsonPath = path.join(installDir, packageName, 'package.json');
+ if (!fs.existsSync(packageJsonPath)) {
+ return { success: false, error: `Upgraded package.json not found for ${packageName}` };
+ }
+ const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8')) as Record<string, unknown>;
- if (fs.existsSync(packageJsonPath)) {
- const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));
- existing.version = pkg.version;
- existing.commands = pkg['claude-flow']?.commands || existing.commands;
- existing.hooks = pkg['claude-flow']?.hooks || existing.hooks;
+ // #3557: re-run the trust policy on the NEW version's declaration, so
+ // hooks and commands withheld at install (or newly declared, or newly
+ // needing elevated permissions) are not registered without --trust.
+ const trusted = applyTrustPolicy(pkg, { verify: opts.verify, trust: opts.trust });
+ existing.version = String(pkg.version ?? existing.version);
+ existing.commands = trusted.commands;
+ existing.hooks = trusted.hooks;
+ existing.trustLevel = trusted.trustLevel;
+ existing.permissions = trusted.permissions;
+ existing.verification = opts.verify === false ? 'skipped' : 'npm-integrity';
+ existing.scriptsRun = scriptsRun;
+ if (trusted.withheld) {
+ existing.withheld = trusted.withheld;
+ } else {
+ delete existing.withheld;
}
await this.saveManifest();
console.log(`[PluginManager] Upgraded ${packageName} to ${existing.version}`);
- return { success: true, plugin: existing };
+ return { success: true, plugin: existing, decision: trusted.decision, warnings };
} catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error);
return { success: false, error: errorMsg };